1/*
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16var __decorate = (this && this.__decorate) || function (a12, b12, c12, d12) {
17    var e12 = arguments.length,
18        f12 = e12 < 3 ? b12 : d12 === null ? d12 = Object.getOwnPropertyDescriptor(b12, c12) : d12, g12;
19    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
20        f12 = Reflect.decorate(a12, b12, c12, d12);
21    } else {
22        for (var h12 = a12.length - 1; h12 >= 0; h12--) {
23            if (g12 = a12[h12]) {
24                f12 = (e12 < 3 ? g12(f12) : e12 > 3 ? g12(b12, c12, f12) : g12(b12, c12)) || f12;
25            }
26        }
27    }
28    return e12 > 3 && f12 && Object.defineProperty(b12, c12, f12), f12;
29};
30
31if (!("finalizeConstruction" in ViewPU.prototype)) {
32    Reflect.set(ViewPU.prototype, "finalizeConstruction", () => {
33    });
34}
35const web_webview = requireNapi('web.webview');
36const router = requireNapi('router');
37const deviceInfo = requireNapi('deviceInfo');
38const geoLocationManager = requireNapi('geoLocationManager');
39const bundleManager = requireNapi('bundle.bundleManager');
40const abilityAccessCtrl = requireNapi('abilityAccessCtrl');
41const connection = requireNapi('net.connection');
42const request = requireNapi('request');
43const fs = requireNapi('file.fs');
44const util = requireNapi('util');
45const photoAccessHelper = requireNapi('file.photoAccessHelper');
46const filePreview = globalThis.requireNapi('filemanagement.filepreview', false, '', 'hms');
47const fileUri = requireNapi('file.fileuri');
48const picker = requireNapi('multimedia.cameraPicker');
49const filePicker = requireNapi('file.picker');
50const atomicServiceWebNapi = requireInternal('atomicservice.AtomicServiceWeb');
51
52class AsError {
53    constructor(m11, n11) {
54        this.code = m11;
55        this.message = n11;
56    }
57}
58
59class JsApiConfig {
60    constructor(i11, j11, k11, l11) {
61        this.apiName = i11;
62        this.minVersion = j11;
63        this.maxVersion = k11;
64        this.requiredFieldNames = l11;
65    }
66}
67
68const LOG_ENABLE = true;
69const LOG_PREFIX = '[AtomicServiceWebLog]';
70const UPLOAD_IMAGE_CACHE_DIR = '/cache/';
71const JAVA_SCRIPT_PROXY_OBJECT_NAME = 'atomicServiceProxy';
72const JAVA_SCRIPT_PROXY_API_NAME_LIST = ['invokeJsApi'];
73const ATOMIC_SERVICE_JS_API_MAP = new Map();
74const registerJsApi = (u11, v11, w11, x11, y11) => {
75    ATOMIC_SERVICE_JS_API_MAP.set(u11, new JsApiConfig(v11, w11, x11, y11));
76};
77const MAX_VERSION = '99.99.99';
78const ATOMIC_SERVICE_JS_SDK_CURRENT_VERSION = '1.0.0';
79const PERMISSION_APPROXIMATELY_LOCATION = 'ohos.permission.APPROXIMATELY_LOCATION';
80const SYSTEM_INTERNAL_ERROR = new AsError(500, 'System internal error.');
81const JS_API_INVALID_INVOKE_ERROR = new AsError(200001, 'Invalid invoke.');
82const PARAM_REQUIRED_ERROR_CODE = 200002;
83const PARAM_NUMBER_POSITIVE_ERROR_CODE = 200003;
84const ROUTER_PARAM_MODE_INVALID_ERROR = new AsError(200004, 'Param mode is invalid.');
85const BACK_URL_NOT_EXIST_OR_OPENED_ERROR = new AsError(200005, 'Url is not exist or opened, can not be back.');
86const NAV_PATH_STACK_NOT_EXIST_ERROR_CODE = 200006;
87const POP_PATH_NAME_NOT_EXIST_ERROR = new AsError(200007, 'Name is not exist or opened, can not be pop.');
88const POP_PATH_PARAM_INDEX_INVALID_ERROR = new AsError(200008, 'Param index is invalid.');
89const POP_PATH_INDEX_OUT_OF_RANGE_ERROR = new AsError(200009, 'The Index is out of range.');
90const UPLOAD_IMAGE_FILES_REQUIRED_ERROR = new AsError(200010, 'Param files is required.');
91const UPLOAD_IMAGE_FILE_NOT_EXIST_ERROR_CODE = 200011;
92const UPLOAD_IMAGE_FILES_URI_REQUIRED_ERROR = new AsError(200012, 'Param uri of files is required.');
93const UPLOAD_FILE_ERROR = new AsError(200013, 'Upload file error.');
94const IMAGE_CAN_NOT_PREVIEW_ERROR = new AsError(200014, 'The filePath can not preview.');
95const NETWORK_NO_ACTIVE_ERROR = new AsError(200015, 'The network is not active.');
96const PERMISSION_LOCATION_USER_REFUSED_ERROR = 200016;
97
98registerJsApi('router.pushUrl', 'pushUrl', '1.0.0', MAX_VERSION, ['url']);
99registerJsApi('router.replaceUrl', 'replaceUrl', '1.0.0', MAX_VERSION, ['url']);
100registerJsApi('router.back', 'backUrl', '1.0.0', MAX_VERSION, []);
101registerJsApi('router.clear', 'clearUrl', '1.0.0', MAX_VERSION, []);
102registerJsApi('navPathStack.pushPath', 'pushPath', '1.0.0', MAX_VERSION, ['name']);
103registerJsApi('navPathStack.replacePath', 'replacePath', '1.0.0', MAX_VERSION, ['name']);
104registerJsApi('navPathStack.pop', 'popPath', '1.0.0', MAX_VERSION, []);
105registerJsApi('navPathStack.clear', 'clearPath', '1.0.0', MAX_VERSION, []);
106registerJsApi('asWeb.postMessage', 'postMessage', '1.0.0', MAX_VERSION, ['data']);
107registerJsApi('asWeb.getEnv', 'getEnv', '1.0.0', MAX_VERSION, []);
108registerJsApi('asWeb.checkJsApi', 'checkJsApi', '1.0.0', MAX_VERSION, ['jsApiList']);
109registerJsApi('cameraPicker.pick', 'pickCamera', '1.0.0', MAX_VERSION, ['mediaTypes', 'cameraPosition']);
110registerJsApi('photoViewPicker.select', 'selectPhoto', '1.0.0', MAX_VERSION, []);
111registerJsApi('filePreview.openPreview', 'openPreview', '1.0.0', MAX_VERSION, ['uri']);
112registerJsApi('request.uploadFile', 'uploadFile', '1.0.0', MAX_VERSION, ['url', 'files']);
113registerJsApi('request.downloadFile', 'downloadFile', '1.0.0', MAX_VERSION, ['url']);
114registerJsApi('connection.getNetworkType', 'getNetworkType', '1.0.0', MAX_VERSION, []);
115registerJsApi('location.getLocation', 'getLocation', '1.0.0', MAX_VERSION, []);
116
117export class AtomicServiceWeb extends ViewPU {
118    constructor(s10, t10, u10, v10 = -1, w10 = undefined, x10) {
119        super(s10, u10, v10, x10);
120        if (typeof w10 === "function") {
121            this.paramsGenerator_ = w10;
122        }
123        this.src = undefined;
124        this.navPathStack = undefined;
125        this.__mixedMode = new SynchedPropertySimpleOneWayPU(t10.mixedMode, this, "mixedMode");
126        this.__darkMode = new SynchedPropertySimpleOneWayPU(t10.darkMode, this, "darkMode");
127        this.__forceDarkAccess = new SynchedPropertySimpleOneWayPU(t10.forceDarkAccess, this, "forceDarkAccess");
128        this.__controller = new SynchedPropertyNesedObjectPU(t10.controller, this, "controller");
129        this.onMessage = () => {
130        };
131        this.onErrorReceive = () => {
132        };
133        this.onHttpErrorReceive = () => {
134        };
135        this.onPageBegin = () => {
136        };
137        this.onPageEnd = () => {
138        };
139        this.onProgressChange = () => {
140        };
141        this.onControllerAttached = undefined;
142        this.onLoadIntercept = undefined;
143        this.context = this.getUIContext().getHostContext();
144        this.webViewController = new web_webview.WebviewController();
145        this.schemeHandler = new web_webview.WebSchemeHandler();
146        this.atomicService = undefined;
147        this.atomicServiceProxy = undefined;
148        this.setInitiallyProvidedValue(t10);
149        this.finalizeConstruction();
150    }
151
152    setInitiallyProvidedValue(r10) {
153        if (r10.src !== undefined) {
154            this.src = r10.src;
155        }
156        if (r10.navPathStack !== undefined) {
157            this.navPathStack = r10.navPathStack;
158        }
159        this.__controller.set(r10.controller);
160        if (r10.onMessage !== undefined) {
161            this.onMessage = r10.onMessage;
162        }
163        if (r10.onErrorReceive !== undefined) {
164            this.onErrorReceive = r10.onErrorReceive;
165        }
166        if (r10.onHttpErrorReceive !== undefined) {
167            this.onHttpErrorReceive = r10.onHttpErrorReceive;
168        }
169        if (r10.onPageBegin !== undefined) {
170            this.onPageBegin = r10.onPageBegin;
171        }
172        if (r10.onPageEnd !== undefined) {
173            this.onPageEnd = r10.onPageEnd;
174        }
175        if (r10.onProgressChange !== undefined) {
176            this.onProgressChange = r10.onProgressChange;
177        }
178        if (r10.onControllerAttached !== undefined) {
179            this.onControllerAttached = r10.onControllerAttached;
180        }
181        if (r10.onLoadIntercept !== undefined) {
182            this.onLoadIntercept = r10.onLoadIntercept;
183        }
184        if (r10.context !== undefined) {
185            this.context = r10.context;
186        }
187        if (r10.webViewController !== undefined) {
188            this.webViewController = r10.webViewController;
189        }
190        if (r10.schemeHandler !== undefined) {
191            this.schemeHandler = r10.schemeHandler;
192        }
193        if (r10.atomicService !== undefined) {
194            this.atomicService = r10.atomicService;
195        }
196        if (r10.atomicServiceProxy !== undefined) {
197            this.atomicServiceProxy = r10.atomicServiceProxy;
198        }
199    }
200
201    updateStateVars(q10) {
202        this.__mixedMode.reset(q10.mixedMode);
203        this.__darkMode.reset(q10.darkMode);
204        this.__forceDarkAccess.reset(q10.forceDarkAccess);
205        this.__controller.set(q10.controller);
206    }
207
208    purgeVariableDependenciesOnElmtId(p10) {
209        this.__mixedMode.purgeDependencyOnElmtId(p10);
210        this.__darkMode.purgeDependencyOnElmtId(p10);
211        this.__forceDarkAccess.purgeDependencyOnElmtId(p10);
212        this.__controller.purgeDependencyOnElmtId(p10);
213    }
214
215    aboutToBeDeleted() {
216        this.__mixedMode.aboutToBeDeleted();
217        this.__darkMode.aboutToBeDeleted();
218        this.__forceDarkAccess.aboutToBeDeleted();
219        this.__controller.aboutToBeDeleted();
220        SubscriberManager.Get().delete(this.id__());
221        this.aboutToBeDeletedInternal();
222    }
223
224    get mixedMode() {
225        return this.__mixedMode.get();
226    }
227
228    set mixedMode(t11) {
229        this.__mixedMode.set(t11);
230    }
231
232    get darkMode() {
233        return this.__darkMode.get();
234    }
235
236    set darkMode(s11) {
237        this.__darkMode.set(s11);
238    }
239
240    get forceDarkAccess() {
241        return this.__forceDarkAccess.get();
242    }
243
244    set forceDarkAccess(r11) {
245        this.__forceDarkAccess.set(r11);
246    }
247
248    get controller() {
249        return this.__controller.get();
250    }
251
252    aboutToAppear() {
253        if (!this.atomicService) {
254            this.atomicService = new AtomicServiceApi(this.context, this.navPathStack, this.onMessage);
255            this.atomicServiceProxy = new AtomicServiceProxy(this.atomicService);
256        }
257        try {
258            let h2 = bundleManager.getBundleInfoForSelfSync(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
259            if (h2?.appInfo?.appProvisionType === 'debug') {
260                console.log(`AtomicServiceWeb setWebDebuggingAccess`);
261                web_webview.WebviewController.setWebDebuggingAccess(true);
262            }
263        } catch (d2) {
264            console.error(`AtomicServiceWeb set Web Debug Mode failed, code is ${d2.code}, message is ${d2.message}`);
265        }
266    }
267
268    aboutToDisappear() {
269        this.atomicService?.notifyMessage();
270    }
271
272    initialRender() {
273        this.observeComponentCreation2((g10, h10) => {
274            Web.create({ src: this.src, controller: this.webViewController });
275            Web.zoomAccess(false);
276            Web.allowWindowOpenMethod(false);
277            Web.domStorageAccess(true);
278            Web.layoutMode(WebLayoutMode.NONE);
279            Web.mixedMode(this.mixedMode);
280            Web.darkMode(this.darkMode);
281            Web.forceDarkAccess(this.forceDarkAccess);
282            Web.onErrorReceive((q11) => this.onCommonCallBack('onErrorReceive', q11, this.onErrorReceive));
283            Web.onHttpErrorReceive((p11) => this.onCommonCallBack('onHttpErrorReceive', p11, this.onHttpErrorReceive));
284            Web.onPageBegin((l10) => this.onCommonCallBack('onPageBegin', l10, this.onPageBegin));
285            Web.onPageEnd((b11) => this.onCommonCallBack('onPageEnd', b11, this.onPageEnd));
286            Web.onProgressChange((a11) => this.onCommonCallBack('onProgressChange', a11, this.onProgressChange));
287            Web.onControllerAttached(() => {
288                this.registerJavaScriptProxy();
289                this.schemeHandler.onRequestStart((z10) => {
290                    return !this.checkUrl(z10.getRequestUrl());
291                });
292                this.webViewController.setWebSchemeHandler('https', this.schemeHandler);
293                this.initAtomicServiceWebController();
294                if (this.onControllerAttached) {
295                    try {
296                        this.onControllerAttached();
297                    } catch (y10) {
298                        console.error(`AtomicServiceWeb onControllerAttached failed, code is ${y10.code}, message is ${y10.message}`);
299                    }
300                }
301            });
302            Web.onOverrideUrlLoading((i10) => {
303                return !this.checkUrl(i10.getRequestUrl());
304            });
305            Web.onLoadIntercept(m7 => {
306                let n7 = !this.checkUrl(m7.data.getRequestUrl());
307                if (!n7 && this.onLoadIntercept) {
308                    try {
309                        return this.onLoadIntercept(m7);
310                    } catch (u7) {
311                        console.error(`AtomicServiceWeb onLoadIntercept failed, code is ${u7.code}, message is ${u7.message}`);
312                        return true;
313                    }
314                }
315                return n7;
316            });
317        }, Web);
318    }
319
320    onCommonCallBack(q5, e6, j6) {
321        try {
322            j6 && j6(e6);
323        } catch (k7) {
324            console.error(`AtomicServiceWeb ${q5} failed, code is ${k7.code}, message is ${k7.message}`);
325        }
326    }
327
328    registerJavaScriptProxy() {
329        try {
330            this.webViewController.registerJavaScriptProxy(this.atomicServiceProxy, JAVA_SCRIPT_PROXY_OBJECT_NAME,
331                JAVA_SCRIPT_PROXY_API_NAME_LIST);
332        } catch (d10) {
333            let e10 = d10;
334            console.error(`AtomicServiceWeb registerJavaScriptProxy failed, code is ${e10.code}, message is ${e10.message}`);
335        }
336    }
337
338    initAtomicServiceWebController() {
339        if (!this.controller) {
340            return;
341        }
342        this.controller.setWebviewController(this.webViewController);
343    }
344
345    cutUrl(b10) {
346        if (b10) {
347            let c10 = b10.indexOf('?');
348            if (c10 > -1) {
349                return b10.substring(0, c10);
350            }
351        }
352        return b10;
353    }
354
355    checkUrl(q1) {
356        if (!q1) {
357            return false;
358        }
359        if (q1.startsWith('resource://rawfile')) {
360            return true;
361        }
362        try {
363            let w1 = this.context.abilityInfo.bundleName;
364            let t1 = 'webView';
365            q1 = this.cutUrl(q1);
366            let res = atomicServiceWebNapi.checkUrl(w1, t1, q1);
367            return res === 0;
368        } catch (j2) {
369            let n2 = j2;
370            console.error(`AtomicServiceWeb checkUrl failed, code is ${n2.code}, message is ${n2.message}`);
371            return false;
372        }
373    }
374
375    rerender() {
376        this.updateDirtyElements();
377    }
378}
379let AtomicServiceWebController = class AtomicServiceWebController {
380    setWebviewController(l5) {
381        this.webViewController = l5;
382    }
383
384    checkWebviewController() {
385        if (!this.webViewController) {
386            const d5 = {
387                name: '',
388                message: 'Init error. The AtomicServiceWebController must be associated with a AtomicServiceWeb component.',
389                code: 17100001,
390            };
391            throw d5;
392        }
393    }
394
395    getUserAgent() {
396        this.checkWebviewController();
397        return this.webViewController?.getUserAgent();
398    }
399
400    getCustomUserAgent() {
401        this.checkWebviewController();
402        return this.webViewController?.getCustomUserAgent();
403    }
404
405    setCustomUserAgent(z4) {
406        this.checkWebviewController();
407        this.webViewController?.setCustomUserAgent(z4);
408    }
409
410    accessForward() {
411        this.checkWebviewController();
412        return this.webViewController?.accessForward();
413    }
414
415    accessBackward() {
416        this.checkWebviewController();
417        return this.webViewController?.accessBackward();
418    }
419
420    accessStep(d4) {
421        this.checkWebviewController();
422        return this.webViewController?.accessStep(d4);
423    }
424
425    forward() {
426        this.checkWebviewController();
427        this.webViewController?.forward();
428    }
429
430    backward() {
431        this.checkWebviewController();
432        this.webViewController?.backward();
433    }
434
435    refresh() {
436        this.checkWebviewController();
437        this.webViewController?.refresh();
438    }
439
440    loadUrl(t3, y3) {
441        this.checkWebviewController();
442        if (y3) {
443            this.webViewController?.loadUrl(t3, y3);
444        } else {
445            this.webViewController?.loadUrl(t3);
446        }
447    }
448};
449AtomicServiceWebController = __decorate([
450    Observed
451], AtomicServiceWebController);
452
453export { AtomicServiceWebController };
454
455class AtomicServiceProxy {
456    constructor(z9) {
457        this.atomicService = z9;
458    }
459
460    invokeJsApi(u9, v9) {
461        try {
462            v9 = v9 || {};
463            if (!u9 || !ATOMIC_SERVICE_JS_API_MAP.has(u9)) {
464                this.atomicService.errorWithCodeAndMsg(JS_API_INVALID_INVOKE_ERROR, v9);
465                return;
466            }
467            let x9 = ATOMIC_SERVICE_JS_API_MAP.get(u9);
468            if (!this.atomicService.checkRequiredFieldInOptions(x9, v9)) {
469                return;
470            }
471            let y9 = this.atomicService;
472            y9[x9?.apiName](v9);
473        } catch (w9) {
474            this.atomicService.error(w9, v9);
475        }
476    }
477}
478
479class AtomicService {
480    constructor(q9, r9, s9) {
481        this.messageDataList = [];
482        this.onMessage = () => {
483        };
484        this.context = q9;
485        this.navPathStack = r9;
486        this.onMessage = s9 ? s9 : this.onMessage;
487    }
488
489    success(o9, p9) {
490        try {
491            p9?.callback && p9?.callback(undefined, o9);
492        } catch (f3) {
493            this.consoleError(`callback error, code is ${f3.code}, message is ${f3.message}`);
494        }
495    }
496
497    error(m9, n9) {
498        try {
499            n9?.callback && n9?.callback(new AsError(m9.code ? m9.code : SYSTEM_INTERNAL_ERROR.code,
500                m9.message ? m9.message : SYSTEM_INTERNAL_ERROR.message));
501        } catch (a3) {
502            this.consoleError(`callback error, code is ${a3.code}, message is ${a3.message}`);
503        }
504    }
505
506    errorWithCodeAndMsg(k9, l9) {
507        try {
508            l9?.callback && l9?.callback(k9);
509        } catch (u2) {
510            this.consoleError(`callback error, code is ${u2.code}, message is ${u2.message}`);
511        }
512    }
513
514    consoleLog(j9) {
515        if (LOG_ENABLE) {
516            console.log(`${LOG_PREFIX} ${j9}`);
517        }
518    }
519
520    consoleError(i9) {
521        if (LOG_ENABLE) {
522            console.error(`${LOG_PREFIX} ${i9}`);
523        }
524    }
525
526    logOptions(g9, h9) {
527        this.consoleLog(`${g9} options=${JSON.stringify(h9)}`);
528    }
529
530    checkParamRequired(d9, e9, f9) {
531        if (e9 === undefined || e9 === null || e9 === '') {
532            this.errorWithCodeAndMsg(new AsError(PARAM_REQUIRED_ERROR_CODE, `Param ${d9} is required.`), f9);
533            return false;
534        }
535        return true;
536    }
537
538    checkNumberParamPositive(a9, b9, c9) {
539        if (b9 <= 0) {
540            this.errorWithCodeAndMsg(new AsError(PARAM_NUMBER_POSITIVE_ERROR_CODE,
541                `Param ${a9} must be a positive number.`), c9);
542            return false;
543        }
544        return true;
545    }
546
547    checkRequiredFieldInOptions(v8, w8) {
548        if (!v8) {
549            return false;
550        }
551        if (!v8.requiredFieldNames) {
552            return true;
553        }
554        let x8 = w8;
555        for (let y8 = 0; y8 < v8.requiredFieldNames.length; y8++) {
556            let z8 = v8.requiredFieldNames[y8];
557            if (!this.checkParamRequired(z8, x8[z8], w8)) {
558                return false;
559            }
560        }
561        return true;
562    }
563
564    checkRouterMode(t8, u8) {
565        if (!t8 || t8 === 'Single' || t8 === 'Standard') {
566            return true;
567        }
568        this.errorWithCodeAndMsg(ROUTER_PARAM_MODE_INVALID_ERROR, u8);
569        return false;
570    }
571
572    parseRouterMode(s8) {
573        return s8 === 'Single' ? router.RouterMode.Single : router.RouterMode.Standard;
574    }
575
576    getRouterIndexByDelta(o8) {
577        let p8 = Number.parseInt(router.getLength());
578        for (let q8 = p8; q8 > 0; q8--) {
579            let r8 = router.getStateByIndex(q8);
580            if (r8?.name && o8-- == 0) {
581                return q8;
582            }
583        }
584        return 1;
585    }
586
587    checkBackUrlExists(i8, j8) {
588        let k8 = Number.parseInt(router.getLength());
589        for (let l8 = k8; l8 > 0; l8--) {
590            let m8 = router.getStateByIndex(l8);
591            if (m8?.name) {
592                let n8 = m8?.path + m8?.name;
593                if (n8 === i8) {
594                    return true;
595                }
596            }
597        }
598        this.errorWithCodeAndMsg(BACK_URL_NOT_EXIST_OR_OPENED_ERROR, j8);
599        return false;
600    }
601
602    checkNavPathStack(g8, h8) {
603        if (!this.navPathStack) {
604            this.errorWithCodeAndMsg(new AsError(NAV_PATH_STACK_NOT_EXIST_ERROR_CODE,
605                `Current page is not NavDestination, not support ${g8}().`), h8);
606            return false;
607        }
608        return true;
609    }
610
611    getNavPathIndexByDelta(e8) {
612        let f8 = this.navPathStack?.getAllPathName();
613        if (!f8 || f8.length == 0) {
614            return -1;
615        }
616        return f8.length > e8 ? (f8.length - e8 - 1) : -1;
617    }
618
619    onPopHandler(c8, d8) {
620        if (!c8?.info || !d8) {
621            return;
622        }
623        d8(new OnPopEvent(c8.info.name, c8.info.param, c8.result));
624    }
625
626    getCurrentNavPathInfo() {
627        let a8 = this.navPathStack?.getAllPathName();
628        let b8 = (a8 && a8.length > 0) ?
629            new NavPathInfo(a8[a8.length - 1], a8.length - 1) : new NavPathInfo(undefined, -1);
630        if (b8.index >= 0) {
631            b8.param = this.navPathStack?.getParamByIndex(b8.index);
632        }
633        return b8;
634    }
635
636    notifyMessage() {
637        if (this.messageDataList.length <= 0) {
638            return;
639        }
640        try {
641            this.onMessage(new OnMessageEvent(this.messageDataList));
642        } catch (q2) {
643            this.consoleError(`onMessage failed, code is ${q2.code}, message is ${q2.message}`);
644        }
645        this.messageDataList = [];
646    }
647
648    isJsApiEnable(z7) {
649        if (!z7) {
650            return false;
651        }
652        if (this.compareVersion(z7.minVersion, ATOMIC_SERVICE_JS_SDK_CURRENT_VERSION) &&
653        this.compareVersion(ATOMIC_SERVICE_JS_SDK_CURRENT_VERSION, z7.maxVersion)) {
654            return true;
655        }
656        return false;
657    }
658
659    compareVersion(p7, q7) {
660        if (!p7 || !q7) {
661            return false;
662        }
663        let r7 = p7.split('.').map(y7 => Number.parseInt(y7));
664        let s7 = q7.split('.').map(x7 => Number.parseInt(x7));
665        const t7 = Math.max(r7.length, s7.length);
666        for (let w7 = 0; w7 < t7; w7++) {
667            if (r7[w7] < s7[w7]) {
668                return true;
669            } else if (r7[w7] > s7[w7]) {
670                return false;
671            }
672        }
673        if (r7.length < s7.length) {
674            return true;
675        }
676        if (r7.length > s7.length) {
677            return false;
678        }
679        return true;
680    }
681
682    getUri(o7) {
683        if (!o7 || o7.startsWith('file://')) {
684            return o7;
685        }
686        return fileUri.getUriFromPath(o7);
687    }
688
689    async checkUploadFile(e7) {
690        if (!e7.files || e7.files.length <= 0) {
691            this.errorWithCodeAndMsg(UPLOAD_IMAGE_FILES_REQUIRED_ERROR, e7);
692            return new CheckUploadFileResult(false);
693        }
694        let f7 = new Map();
695        for (let g7 = 0; g7 < e7.files?.length; g7++) {
696            let h7 = e7.files[g7];
697            if (!h7.uri) {
698                this.errorWithCodeAndMsg(UPLOAD_IMAGE_FILES_URI_REQUIRED_ERROR, e7);
699                return new CheckUploadFileResult(false);
700            }
701            if (!h7.uri.startsWith('file://') && !fs.accessSync(h7.uri, fs.AccessModeType.EXIST)) {
702                this.errorWithCodeAndMsg(new AsError(UPLOAD_IMAGE_FILE_NOT_EXIST_ERROR_CODE,
703                    `File uri ${h7.uri} is not exist.`), e7);
704                return new CheckUploadFileResult(false);
705            }
706            let i7 = h7.uri;
707            let j7 = h7.uri;
708            if (j7.indexOf(UPLOAD_IMAGE_CACHE_DIR) < 0) {
709                let l7 = j7.startsWith('file://') ? j7 : fileUri.getUriFromPath(h7.uri);
710                j7 = this.context.cacheDir + '/' + j7.substring(j7.lastIndexOf('/') + 1);
711                try {
712                    await fs.copy(l7, fileUri.getUriFromPath(j7));
713                } catch (x1) {
714                    this.errorWithCodeAndMsg(UPLOAD_FILE_ERROR, e7);
715                    return new CheckUploadFileResult(false);
716                }
717            }
718            h7.uri = 'internal://' + j7.substring(j7.indexOf(UPLOAD_IMAGE_CACHE_DIR) + 1);
719            f7.set(j7, i7);
720        }
721        return new CheckUploadFileResult(true, f7);
722    }
723
724    convertToRequestData(a7) {
725        let b7 = [];
726        if (a7) {
727            a7.forEach(d7 => {
728                if (!d7.name || !d7.value) {
729                    return;
730                }
731                b7.push({ name: d7.name, value: d7.value });
732            });
733        }
734        return b7;
735    }
736
737    convertToFile(w6) {
738        let x6 = [];
739        if (w6) {
740            w6.forEach(z6 => {
741                x6.push({
742                    filename: z6.filename,
743                    name: z6.name,
744                    uri: z6.uri,
745                    type: z6.type
746                });
747            });
748        }
749        return x6;
750    }
751
752    handleUploadFileResult(p6, q6, r6) {
753        let s6 = [];
754        if (p6) {
755            p6.forEach(u6 => {
756                let v6 = u6.path ? q6.get(u6.path) : u6.path;
757                s6.push(new UploadFileTaskState(v6 ? v6 : u6.path, u6.responseCode, u6.message));
758            });
759        }
760        this.success(new UploadFileResult(s6), r6);
761    }
762
763    parseFileNameFromUrl(m6) {
764        if (!m6) {
765            return '';
766        }
767        let n6 = m6.split('?')[0];
768        if (n6.indexOf('/') < 0) {
769            return '';
770        }
771        let o6 = n6.lastIndexOf('/');
772        if (o6 == (n6.length - 1)) {
773            return '';
774        }
775        return n6.substring(o6 + 1);
776    }
777
778    saveDownloadFile(z5, a6, b6, c6) {
779        let d6 = new filePicker.DocumentViewPicker();
780        d6.save({
781            newFileNames: [a6]
782        }).then(h6 => {
783            let i6 = h6[0];
784            fs.copy(fileUri.getUriFromPath(z5), i6).then(() => {
785                c6 && c6(i6);
786            }).catch((l6) => {
787                this.error(l6, b6);
788            });
789        }).catch((g6) => {
790            this.error(g6, b6);
791        });
792    }
793
794    checkAccessToken(v5) {
795        let w5 = bundleManager.getBundleInfoForSelfSync(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
796        let x5 = w5.appInfo.accessTokenId;
797        let y5 = abilityAccessCtrl.createAtManager();
798        return y5.checkAccessToken(x5, v5);
799    }
800
801    checkPermissions(j5, k5) {
802        this.checkAccessToken(j5).then(o5 => {
803            if (o5 == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
804                k5(undefined);
805            } else {
806                let p5 = abilityAccessCtrl.createAtManager();
807                p5.requestPermissionsFromUser(this.context, [j5]).then(t5 => {
808                    for (let u5 = 0; u5 < t5.authResults.length; u5++) {
809                        if (t5.authResults[u5] != 0) {
810                            const error = {
811                                name: '',
812                                message: `RequestPermissionsFromUser error. authResult: ${t5.authResults[u5]}.`,
813                                code: PERMISSION_LOCATION_USER_REFUSED_ERROR
814                            };
815                            k5(error);
816                            return;
817                        }
818                    }
819                    k5(undefined);
820                }).catch((s5) => {
821                    k5(s5);
822                });
823            }
824        }).catch((n5) => {
825            k5(n5);
826        });
827    }
828}
829
830class AtomicServiceApi extends AtomicService {
831    constructor(g5, h5, i5) {
832        super(g5, h5, i5);
833    }
834
835    pushUrl(c5) {
836        if (!this.checkRouterMode(c5.mode, c5)) {
837            return;
838        }
839        router.pushUrl({ url: c5.url, params: c5.params }, this.parseRouterMode(c5.mode)).then(() => {
840            this.success(new PushUrlResult(), c5);
841        }).catch((f5) => {
842            this.error(f5, c5);
843        });
844    }
845
846    replaceUrl(y4) {
847        if (!this.checkRouterMode(y4.mode, y4)) {
848            return;
849        }
850        router.replaceUrl({ url: y4.url, params: y4.params }, this.parseRouterMode(y4.mode)).then(() => {
851            this.success(new ReplaceUrlResult(), y4);
852        }).catch((b5) => {
853            this.error(b5, y4);
854        });
855    }
856
857    backUrl(x4) {
858        if (x4.url) {
859            if (!this.checkBackUrlExists(x4.url, x4)) {
860                return;
861            }
862            router.back({ url: x4.url, params: x4.params });
863            this.success(new BackUrlResult(), x4);
864        } else if (x4.index || x4.index === 0) {
865            if (!this.checkNumberParamPositive('index', x4.index, x4)) {
866                return;
867            }
868            router.back(x4.index, x4.params);
869            this.success(new BackUrlResult(), x4);
870        } else if (x4.delta || x4.delta === 0) {
871            if (!this.checkNumberParamPositive('delta', x4.delta, x4)) {
872                return;
873            }
874            router.back(this.getRouterIndexByDelta(x4.delta), x4.params);
875            this.success(new BackUrlResult(), x4);
876        } else {
877            router.back();
878            this.success(new BackUrlResult(), x4);
879        }
880    }
881
882    clearUrl(w4) {
883        router.clear();
884        this.success(new ClearUrlResult(), w4);
885    }
886
887    pushPath(u4) {
888        if (!this.checkNavPathStack('navPathStack.pushPath', u4)) {
889            return;
890        }
891        this.navPathStack?.pushPath({
892            name: u4.name,
893            param: u4.param,
894            onPop: v4 => this.onPopHandler(v4, u4.onPop)
895        }, u4.animated);
896        this.success(new PushPathResult(), u4);
897    }
898
899    replacePath(s4) {
900        if (!this.checkNavPathStack('navPathStack.replacePath', s4)) {
901            return;
902        }
903        this.navPathStack?.replacePath({
904            name: s4.name,
905            param: s4.param,
906            onPop: t4 => this.onPopHandler(t4, s4.onPop)
907        }, s4.animated);
908        this.success(new ReplacePathResult(), s4);
909    }
910
911    popPath(p4) {
912        if (!this.checkNavPathStack('navPathStack.pop', p4)) {
913            return;
914        }
915        if (p4.name) {
916            let r4 = this.navPathStack?.popToName(p4.name, p4.result, p4.animated);
917            if (r4 === undefined || r4 === -1) {
918                this.errorWithCodeAndMsg(POP_PATH_NAME_NOT_EXIST_ERROR, p4);
919                return;
920            }
921        } else if (p4.index || p4.index === 0) {
922            if (p4.index < -1) {
923                this.errorWithCodeAndMsg(POP_PATH_PARAM_INDEX_INVALID_ERROR, p4);
924                return;
925            }
926            if (p4.index > this.getCurrentNavPathInfo().index) {
927                this.errorWithCodeAndMsg(POP_PATH_INDEX_OUT_OF_RANGE_ERROR, p4);
928                return;
929            }
930            this.navPathStack?.popToIndex(p4.index, p4.result, p4.animated);
931        } else if (p4.delta || p4.delta === 0) {
932            if (!this.checkNumberParamPositive('delta', p4.delta, p4)) {
933                return;
934            }
935            this.navPathStack?.popToIndex(this.getNavPathIndexByDelta(p4.delta), p4.result, p4.animated);
936        } else {
937            this.navPathStack?.pop(p4.result, p4.animated);
938        }
939        let q4 = this.getCurrentNavPathInfo();
940        this.success(new PopPathResult(q4.name, q4.index, q4.param), p4);
941    }
942
943    clearPath(o4) {
944        if (!this.checkNavPathStack('navPathStack.clear', o4)) {
945            return;
946        }
947        this.navPathStack?.clear(o4.animated);
948        this.success(new ClearPathResult(), o4);
949    }
950
951    postMessage(n4) {
952        n4.data && this.messageDataList.push(n4.data);
953        this.success(new PostMessageResult(), n4);
954    }
955
956    getEnv(l4) {
957        let m4 = new GetEnvResult();
958        m4.deviceType = deviceInfo.deviceType;
959        m4.brand = deviceInfo.brand;
960        m4.productModel = deviceInfo.productModel;
961        m4.osFullName = deviceInfo.osFullName;
962        this.success(m4, l4);
963    }
964
965    checkJsApi(h4) {
966        let i4 = new Map();
967        h4.jsApiList?.forEach(k4 => {
968            i4[k4] = this.isJsApiEnable(ATOMIC_SERVICE_JS_API_MAP.get(k4));
969        });
970        this.success(new CheckJsApiResult(i4), h4);
971    }
972
973    pickCamera(c4) {
974        picker.pick(this.context, c4.mediaTypes, {
975            cameraPosition: c4.cameraPosition,
976            saveUri: c4.saveUri,
977            videoDuration: c4.videoDuration
978        }).then((g4) => {
979            this.success(new PickCameraResult(g4.resultCode, g4.resultUri, g4.mediaType), c4);
980        }).catch((f4) => {
981            this.error(f4, c4);
982        });
983    }
984
985    selectPhoto(w3) {
986        let x3 = new photoAccessHelper.PhotoViewPicker();
987        x3.select({
988            MIMEType: w3.mimeType,
989            maxSelectNumber: w3.maxSelectNumber,
990            isPhotoTakingSupported: w3.isPhotoTakingSupported,
991            isEditSupported: w3.isEditSupported,
992            isSearchSupported: w3.isSearchSupported,
993            recommendationOptions: {
994                recommendationType: w3.recommendationType
995            },
996            preselectedUris: w3.preselectedUris
997        }).then((b4) => {
998            this.success(new SelectPhotoResult(b4.photoUris, b4.isOriginalPhoto), w3);
999        }).catch((a4) => {
1000            this.error(a4, w3);
1001        });
1002    }
1003
1004    openPreview(n3) {
1005        let o3 = this.getUri(n3.uri);
1006        filePreview.canPreview(this.context, o3).then((s3) => {
1007            if (!s3) {
1008                this.errorWithCodeAndMsg(IMAGE_CAN_NOT_PREVIEW_ERROR, n3);
1009                return;
1010            }
1011            filePreview.openPreview(this.context, {
1012                uri: o3,
1013                mimeType: n3.mimeType,
1014                title: n3.title
1015            }).then(() => {
1016                this.success(new OpenPreviewResult(), n3);
1017            }).catch((v3) => {
1018                this.error(v3, n3);
1019            });
1020        }).catch((r3) => {
1021            this.error(r3, n3);
1022        });
1023    }
1024
1025    uploadFile(z2) {
1026        this.checkUploadFile(z2).then(d3 => {
1027            if (!d3.checkResult) {
1028                return;
1029            }
1030            let e3 = {
1031                url: z2.url,
1032                header: z2.header,
1033                method: z2.method,
1034                files: this.convertToFile(z2.files),
1035                data: this.convertToRequestData(z2.data)
1036            };
1037            request.uploadFile(this.context, e3).then((i3) => {
1038                i3.on('complete', (m3) => {
1039                    this.handleUploadFileResult(m3, d3.uriMap, z2);
1040                });
1041                i3.on('fail', (l3) => {
1042                    this.handleUploadFileResult(l3, d3.uriMap, z2);
1043                });
1044            }).catch((h3) => {
1045                this.error(h3, z2);
1046            });
1047        }).catch((c3) => {
1048            this.error(c3, z2);
1049        });
1050    }
1051
1052    downloadFile(m2) {
1053        let n2 = m2.fileName ? m2.fileName : this.parseFileNameFromUrl(m2.url);
1054        let o2 = `${util.generateRandomUUID().replaceAll('-', '')}`;
1055        let p2 = `${this.context.cacheDir}/${o2}`;
1056        request.downloadFile(this.context, {
1057            url: m2.url,
1058            header: m2.header ? m2.header : new Object(),
1059            filePath: p2,
1060            enableMetered: m2.enableMetered,
1061            enableRoaming: m2.enableRoaming,
1062            networkType: m2.networkType,
1063            background: false
1064        }).then((t2) => {
1065            t2.on('complete', () => {
1066                this.saveDownloadFile(p2, n2, m2, y2 => {
1067                    this.success(new DownloadFileResult(y2), m2);
1068                });
1069            });
1070            t2.on('fail', w2 => {
1071                this.errorWithCodeAndMsg(new AsError(w2, 'File download fail.'), m2);
1072            });
1073        }).catch((s2) => {
1074            this.error(s2, m2);
1075        });
1076    }
1077
1078    getNetworkType(c2) {
1079        connection.getDefaultNet().then(g2 => {
1080            if (!g2 || g2.netId === 0) {
1081                this.errorWithCodeAndMsg(NETWORK_NO_ACTIVE_ERROR, c2);
1082                return;
1083            }
1084            connection.getNetCapabilities(g2).then(k2 => {
1085                let l2 = new GetNetworkTypeResult(k2.bearerTypes, k2.networkCap, k2.linkUpBandwidthKbps,
1086                    k2.linkDownBandwidthKbps);
1087                this.success(l2, c2);
1088            }).catch((j2) => {
1089                this.error(j2, c2);
1090            });
1091        }).catch((f2) => {
1092            this.error(f2, c2);
1093        });
1094    }
1095
1096    getLocation(u1) {
1097        this.checkPermissions(PERMISSION_APPROXIMATELY_LOCATION, w1 => {
1098            if (w1) {
1099                this.error(w1, u1);
1100                return;
1101            }
1102            geoLocationManager.getCurrentLocation({
1103                priority: u1.priority,
1104                scenario: u1.scenario,
1105                maxAccuracy: u1.maxAccuracy,
1106                timeoutMs: u1.timeoutMs
1107            }).then(a2 => {
1108                let b2 =
1109                    new GetLocationResult(a2.latitude, a2.longitude, a2.altitude, a2.accuracy, a2.speed, a2.timeStamp,
1110                        a2.direction, a2.timeSinceBoot, a2.additions, a2.additionSize);
1111                this.success(b2, u1);
1112            }).catch((z1) => {
1113                this.error(z1, u1);
1114            });
1115        });
1116    }
1117}
1118
1119class NavPathInfo {
1120    constructor(s1, t1) {
1121        this.name = s1;
1122        this.index = t1;
1123    }
1124}
1125
1126class CheckUploadFileResult {
1127    constructor(q1, r1) {
1128        this.checkResult = q1;
1129        this.uriMap = r1;
1130    }
1131}
1132
1133class BaseOptions {
1134}
1135
1136class PushUrlOptions extends BaseOptions {
1137}
1138
1139class PushUrlResult {
1140}
1141
1142class ReplaceUrlOptions extends BaseOptions {
1143}
1144
1145class ReplaceUrlResult {
1146}
1147
1148class BackUrlOptions extends BaseOptions {
1149}
1150
1151class BackUrlResult {
1152}
1153
1154class ClearUrlOptions extends BaseOptions {
1155}
1156
1157class ClearUrlResult {
1158}
1159
1160class OnPopEvent {
1161    constructor(n1, o1, p1) {
1162        this.name = n1;
1163        this.param = o1;
1164        this.result = p1;
1165    }
1166}
1167
1168class PushPathOptions extends BaseOptions {
1169}
1170
1171class PushPathResult {
1172}
1173
1174class ReplacePathOptions extends BaseOptions {
1175}
1176
1177class ReplacePathResult {
1178}
1179
1180class PopPathOptions extends BaseOptions {
1181}
1182
1183class PopPathResult {
1184    constructor(k1, l1, m1) {
1185        this.name = k1;
1186        this.index = l1;
1187        this.param = m1;
1188    }
1189}
1190
1191class ClearPathOptions extends BaseOptions {
1192}
1193
1194class ClearPathResult {
1195}
1196
1197class PostMessageOptions extends BaseOptions {
1198}
1199
1200class PostMessageResult {
1201}
1202
1203export class OnMessageEvent {
1204    constructor(j1) {
1205        this.data = j1;
1206    }
1207}
1208
1209export class OnErrorReceiveEvent {
1210    constructor(h1, i1) {
1211        this.request = h1;
1212        this.error = i1;
1213    }
1214}
1215
1216export class OnHttpErrorReceiveEvent {
1217    constructor(f1, g1) {
1218        this.request = f1;
1219        this.response = g1;
1220    }
1221}
1222
1223export class OnPageBeginEvent {
1224    constructor(e1) {
1225        this.url = e1;
1226    }
1227}
1228
1229export class OnPageEndEvent {
1230    constructor(d1) {
1231        this.url = d1;
1232    }
1233}
1234
1235export class WebHeader {
1236    constructor(j3, p3) {
1237        this.headerKey = j3;
1238        this.headerValue = p3;
1239    }
1240}
1241
1242class GetEnvOptions extends BaseOptions {
1243}
1244
1245class GetEnvResult {
1246}
1247
1248class CheckJsApiOptions extends BaseOptions {
1249}
1250
1251class CheckJsApiResult {
1252    constructor(c1) {
1253        this.checkResult = c1;
1254    }
1255}
1256
1257class PickCameraOptions extends BaseOptions {
1258}
1259
1260class PickCameraResult {
1261    constructor(z, a1, b1) {
1262        this.resultCode = z;
1263        this.resultUri = a1;
1264        this.mediaType = b1;
1265    }
1266}
1267
1268class SelectPhotoOptions extends BaseOptions {
1269}
1270
1271class SelectPhotoResult {
1272    constructor(x, y) {
1273        this.photoUris = x;
1274        this.isOriginalPhoto = y;
1275    }
1276}
1277
1278class OpenPreviewOptions extends BaseOptions {
1279}
1280
1281class OpenPreviewResult {
1282}
1283
1284class UploadFileOptions extends BaseOptions {
1285}
1286
1287class UploadFile {
1288    constructor(t, u, v, w) {
1289        this.filename = t;
1290        this.name = u;
1291        this.uri = v;
1292        this.type = w;
1293    }
1294}
1295
1296class UploadRequestData {
1297}
1298
1299class UploadFileResult {
1300    constructor(s) {
1301        this.taskStates = s;
1302    }
1303}
1304
1305class UploadFileTaskState {
1306    constructor(p, q, r) {
1307        this.path = p;
1308        this.responseCode = q;
1309        this.message = r;
1310    }
1311}
1312
1313class DownloadFileOptions extends BaseOptions {
1314}
1315
1316class DownloadFileResult {
1317    constructor(o) {
1318        this.uri = o;
1319    }
1320}
1321
1322class GetNetworkTypeOptions extends BaseOptions {
1323}
1324
1325class GetNetworkTypeResult {
1326    constructor(k, l, m, n) {
1327        this.bearerTypes = k;
1328        this.networkCap = l;
1329        this.linkUpBandwidthKbps = m;
1330        this.linkDownBandwidthKbps = n;
1331    }
1332}
1333
1334class GetLocationOptions extends BaseOptions {
1335}
1336
1337class GetLocationResult {
1338    constructor(a, b, c, d, e, f, g, h, i, j) {
1339        this.latitude = a;
1340        this.longitude = b;
1341        this.altitude = c;
1342        this.accuracy = d;
1343        this.speed = e;
1344        this.timeStamp = f;
1345        this.direction = g;
1346        this.timeSinceBoot = h;
1347        this.additions = i;
1348        this.additionSize = j;
1349    }
1350}
1351
1352export default {
1353    AtomicServiceWeb,
1354    AtomicServiceWebController
1355}
1356