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