@weapp-vite/web 1.5.3 → 1.5.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +10 -10
- package/dist/plugin/index.d.mts +12 -0
- package/dist/plugin/index.mjs +56 -16
- package/dist/plugin/index.mjs.map +1 -1
- package/dist/plugin/register.mjs +2 -0
- package/dist/plugin/register.mjs.map +1 -1
- package/dist/runtime/component/element.mjs +1 -1
- package/dist/runtime/index.mjs +12 -11
- package/dist/runtime/index.mjs.map +1 -1
- package/dist/runtime/nativeComponents/navigator.mjs +1 -1
- package/dist/runtime/polyfill/index.mjs +50 -47
- package/dist/runtime/polyfill/index.mjs.map +1 -1
- package/dist/runtime/polyfill/interactionApi.mjs +1 -1
- package/dist/runtime/polyfill/locationApi.mjs +1 -1
- package/dist/runtime/polyfill/mediaApi/file.mjs +1 -1
- package/dist/runtime/polyfill/menuApi.mjs +2 -2
- package/dist/runtime/polyfill/platformApi.mjs +1 -1
- package/dist/runtime/polyfill/routeRuntime/dom.mjs +1 -1
- package/dist/runtime/polyfill/routeRuntime/lifecycle.mjs +1 -0
- package/dist/runtime/polyfill/routeRuntime/lifecycle.mjs.map +1 -1
- package/dist/runtime/polyfill/routeRuntime/stack.mjs +1 -1
- package/dist/runtime/polyfill/routeRuntime.mjs +3 -3
- package/dist/runtime/polyfill/runtimeDataApi.mjs +2 -2
- package/dist/runtime/polyfill/runtimeOps.mjs +1 -1
- package/package.json +8 -8
package/dist/index.mjs
CHANGED
|
@@ -3,31 +3,31 @@ import { transformWxssToCss } from "./css/wxss.mjs";
|
|
|
3
3
|
import { weappWebPlugin } from "./plugin/index.mjs";
|
|
4
4
|
import { setRuntimeWarningOptions } from "./runtime/warning.mjs";
|
|
5
5
|
import { installWebHostGlobals } from "./runtime/hostGlobals.mjs";
|
|
6
|
+
import { getRuntimeClipboard, getRuntimeDialogs, getRuntimeFetch, getRuntimeStorage, getWebRuntimeHost, openRuntimeUrl, resetWebRuntimeHost, setWebRuntimeHost } from "./runtime/host/index.mjs";
|
|
7
|
+
import { authorize, checkSession, getAccountInfoSync, getAppAuthorizeSetting, getAppBaseInfo, getBatteryInfo, getBatteryInfoSync, getDeviceInfo, getFuzzyLocation, getLocation, getMenuButtonBoundingClientRect, getNetworkType, getSetting, getSystemInfo, getSystemInfoSync, getSystemSetting, getUserInfo, getUserProfile, getWindowInfo, login, offNetworkStatusChange, offWindowResize, onNetworkStatusChange, onWindowResize, openAppAuthorizeSetting, openSetting, vibrateShort } from "./runtime/polyfill/deviceAuthSystemApi.mjs";
|
|
8
|
+
import { configureWebSeo, resetWebDocumentHead, setupWebResourceHints, syncWebDocumentHead, updateWebDocumentTitle } from "./runtime/seo/index.mjs";
|
|
6
9
|
import { injectStyle, removeStyle } from "./runtime/style.mjs";
|
|
7
10
|
import { ensureButtonDefined, setButtonFormConfig } from "./runtime/button/index.mjs";
|
|
8
11
|
import { getRuntimeExecutionMode, setRuntimeExecutionMode } from "./runtime/execution.mjs";
|
|
9
12
|
import { createRenderContext } from "./runtime/renderContext.mjs";
|
|
10
13
|
import { defineComponent } from "./runtime/component/index.mjs";
|
|
11
|
-
import { bindRuntimeEvent } from "./runtime/eventBinding.mjs";
|
|
12
|
-
import { getRuntimeClipboard, getRuntimeDialogs, getRuntimeFetch, getRuntimeStorage, getWebRuntimeHost, openRuntimeUrl, resetWebRuntimeHost, setWebRuntimeHost } from "./runtime/host/index.mjs";
|
|
13
14
|
import { resolveImageModeStyle } from "./runtime/nativeComponents/image.mjs";
|
|
14
15
|
import { createInputEventDetail } from "./runtime/nativeComponents/input.mjs";
|
|
15
|
-
import { setNavigationBarMetrics } from "./runtime/navigationBar/index.mjs";
|
|
16
|
-
import { getWebViewportWidth, resolveWebViewportConfig, setupWebViewport } from "./runtime/viewport/index.mjs";
|
|
17
|
-
import { setupRpx } from "./runtime/rpx.mjs";
|
|
18
|
-
import { configureWebSeo, resetWebDocumentHead, setupWebResourceHints, syncWebDocumentHead, updateWebDocumentTitle } from "./runtime/seo/index.mjs";
|
|
19
|
-
import { disposeWebRouting, getWebRoutingConfig, resolveWebRoutingConfig } from "./runtime/polyfill/routeRuntime/history.mjs";
|
|
20
|
-
import { getEnterOptionsSync, getLaunchOptionsSync, initializePageRoutes, navigateBack, navigateTo, offAppHide, offAppShow, onAppHide, onAppShow, reLaunch, redirectTo, registerApp, registerComponent, registerPage, switchTab } from "./runtime/polyfill/routeRuntime.mjs";
|
|
21
16
|
import { clearStorage, clearStorageSync, createCanvasContext, createSelectorQuery, createVKSession, createVideoContext, createWorker, downloadFile, exitMiniProgram, getFileSystemManager, getStorage, getStorageInfo, getStorageInfoSync, getStorageSync, hideKeyboard, loadSubPackage, navigateToMiniProgram, nextTick, pageScrollTo, preloadSubpackage, removeStorage, removeStorageSync, request, setStorage, setStorageSync, startPullDownRefresh, stopPullDownRefresh, uploadFile } from "./runtime/polyfill/runtimeDataApi.mjs";
|
|
22
17
|
import { createScrollEventDetail } from "./runtime/nativeComponents/scrollView.mjs";
|
|
23
18
|
import { createSwitchEventDetail } from "./runtime/nativeComponents/switch.mjs";
|
|
24
19
|
import { createTextareaLineChangeDetail } from "./runtime/nativeComponents/textarea.mjs";
|
|
25
20
|
import { createVideoProgressDetail, createVideoTimeUpdateDetail, resolveVideoObjectFit } from "./runtime/nativeComponents/video/helpers.mjs";
|
|
26
21
|
import { ensureNativeComponentsDefined } from "./runtime/nativeComponents/index.mjs";
|
|
27
|
-
import {
|
|
28
|
-
import {
|
|
22
|
+
import { setNavigationBarMetrics } from "./runtime/navigationBar/index.mjs";
|
|
23
|
+
import { getWebViewportWidth, resolveWebViewportConfig, setupWebViewport } from "./runtime/viewport/index.mjs";
|
|
24
|
+
import { setupRpx } from "./runtime/rpx.mjs";
|
|
25
|
+
import { disposeWebRouting, getWebRoutingConfig, resolveWebRoutingConfig } from "./runtime/polyfill/routeRuntime/history.mjs";
|
|
26
|
+
import { getEnterOptionsSync, getLaunchOptionsSync, initializePageRoutes, navigateBack, navigateTo, offAppHide, offAppShow, onAppHide, onAppShow, reLaunch, redirectTo, registerApp, registerComponent, registerPage, switchTab } from "./runtime/polyfill/routeRuntime.mjs";
|
|
29
27
|
import { chooseAddress, chooseFile, chooseImage, chooseLocation, chooseMedia, chooseMessageFile, chooseVideo, compressImage, compressVideo, getClipboardData, getImageInfo, getVideoInfo, hideLoading, hideTabBar, hideTabBarRedDot, makePhoneCall, openCustomerServiceChat, openDocument, openLocation, openVideoEditor, previewImage, previewMedia, removeTabBarBadge, requestPayment, requestSubscribeMessage, saveFile, saveFileToDisk, saveImageToPhotosAlbum, saveVideoToPhotosAlbum, scanCode, setClipboardData, setTabBarBadge, setTabBarItem, setTabBarStyle, showActionSheet, showLoading, showModal, showShareMenu, showTabBar, showTabBarRedDot, showToast, updateShareMenu } from "./runtime/polyfill/uiMediaApi.mjs";
|
|
30
28
|
import { canIUse, createInterstitialAd, createRewardedVideoAd, getExtConfig, getExtConfigSync, getLogManager, getUpdateManager, hideNavigationBarLoading, reportAnalytics, setBackgroundColor, setBackgroundTextStyle, setNavigationBarColor, setNavigationBarTitle, showNavigationBarLoading } from "./runtime/polyfill/index.mjs";
|
|
29
|
+
import { bindRuntimeEvent } from "./runtime/eventBinding.mjs";
|
|
30
|
+
import { setPageLayout } from "./runtime/pageLayout.mjs";
|
|
31
31
|
import { createTemplate, renderTemplate } from "./runtime/legacyTemplate/index.mjs";
|
|
32
32
|
import { installWebModuleRegistration, registerWebWevuApp, registerWebWevuComponent, registerWebWevuComponentFactory } from "./runtime/wevu.mjs";
|
|
33
33
|
|
package/dist/plugin/index.d.mts
CHANGED
|
@@ -48,6 +48,11 @@ interface WebDevServer {
|
|
|
48
48
|
middlewares: {
|
|
49
49
|
use: (middleware: ReturnType<typeof createWebAssetMiddleware>) => void;
|
|
50
50
|
};
|
|
51
|
+
moduleGraph?: {
|
|
52
|
+
getModuleById: (id: string) => object | undefined;
|
|
53
|
+
getModulesByFile: (file: string) => Set<object> | undefined;
|
|
54
|
+
invalidateModule: (module: object) => void;
|
|
55
|
+
};
|
|
51
56
|
}
|
|
52
57
|
interface WeappWebVitePlugin {
|
|
53
58
|
name: string;
|
|
@@ -58,6 +63,13 @@ interface WeappWebVitePlugin {
|
|
|
58
63
|
buildStart?: (this: WebPluginContext) => void | Promise<void>;
|
|
59
64
|
resolveId?: (id: string, importer?: string) => string | null | Promise<string | null>;
|
|
60
65
|
load?: (id: string) => string | null | Promise<string | null>;
|
|
66
|
+
watchChange?: {
|
|
67
|
+
order: 'post';
|
|
68
|
+
sequential: true;
|
|
69
|
+
handler: (this: WebPluginContext, id: string, change: {
|
|
70
|
+
event: 'create' | 'update' | 'delete';
|
|
71
|
+
}) => Promise<void>;
|
|
72
|
+
};
|
|
61
73
|
handleHotUpdate?: (this: WebPluginContext, ctx: WebHmrContext) => void | Promise<void>;
|
|
62
74
|
transform?: (this: WebPluginContext, code: string, id: string) => WebTransformResult | Promise<WebTransformResult>;
|
|
63
75
|
}
|
package/dist/plugin/index.mjs
CHANGED
|
@@ -24,6 +24,7 @@ const WEB_RUNTIME_MODULE_IDS = [
|
|
|
24
24
|
"lit/async-directive.js",
|
|
25
25
|
"lit/directives/repeat.js"
|
|
26
26
|
];
|
|
27
|
+
const SCAN_VIRTUAL_MODULE_IDS = [ENTRY_ID, RESOLVED_AUTO_ROUTES_ID];
|
|
27
28
|
function isTemplateFile(id) {
|
|
28
29
|
const lower = id.toLowerCase();
|
|
29
30
|
return TEMPLATE_EXTS.some((ext) => lower.endsWith(ext));
|
|
@@ -78,13 +79,15 @@ function weappWebPlugin(options = {}) {
|
|
|
78
79
|
let root = process.cwd();
|
|
79
80
|
let srcRoot = resolve(root, options.srcDir ?? "src");
|
|
80
81
|
let enableHmr = false;
|
|
82
|
+
let devServer;
|
|
81
83
|
let resolveWebModuleId;
|
|
82
84
|
let resolveMiniProgramModuleId;
|
|
83
85
|
let resolveWebAutoImportTag;
|
|
84
86
|
const webRuntimeModules = /* @__PURE__ */ new Map();
|
|
85
87
|
let stylePreprocessOptions;
|
|
86
|
-
|
|
87
|
-
|
|
88
|
+
let componentImportIdMap = /* @__PURE__ */ new Map();
|
|
89
|
+
let state = createEmptyScanState();
|
|
90
|
+
let scanQueue = Promise.resolve();
|
|
88
91
|
const wxssOptions = options.wxss;
|
|
89
92
|
const runtimeProvider = options.__runtimeProvider;
|
|
90
93
|
const hmrAcceptCode = runtimeProvider ? runtimeProvider.hmrAcceptCode : "if (import.meta.hot) { import.meta.hot.accept() }";
|
|
@@ -120,19 +123,49 @@ function weappWebPlugin(options = {}) {
|
|
|
120
123
|
}
|
|
121
124
|
};
|
|
122
125
|
};
|
|
123
|
-
const scan =
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
126
|
+
const scan = (context) => {
|
|
127
|
+
const result = scanQueue.then(async () => {
|
|
128
|
+
const nextState = createEmptyScanState();
|
|
129
|
+
await scanProject({
|
|
130
|
+
srcRoot,
|
|
131
|
+
warn: context.warn?.bind(context),
|
|
132
|
+
state: nextState,
|
|
133
|
+
resolveId: resolveWebModuleId,
|
|
134
|
+
resolveAutoImportTag: resolveWebAutoImportTag,
|
|
135
|
+
resolveAppConfig: options.__resolveAppConfig,
|
|
136
|
+
uniApp: options.__uniApp,
|
|
137
|
+
stylePreprocessOptions
|
|
138
|
+
});
|
|
139
|
+
const nextComponentImportIdMap = /* @__PURE__ */ new Map();
|
|
140
|
+
for (const component of nextState.scanResult.components) if (component.importId) nextComponentImportIdMap.set(component.importId, component.script);
|
|
141
|
+
const graph = devServer?.moduleGraph;
|
|
142
|
+
const files = graph ? /* @__PURE__ */ new Set() : void 0;
|
|
143
|
+
if (files) for (const snapshot of [state, nextState]) {
|
|
144
|
+
for (const file of snapshot.moduleMeta.keys()) files.add(file);
|
|
145
|
+
for (const file of snapshot.templatePathSet) files.add(file);
|
|
146
|
+
for (const [file, result] of snapshot.sfcResults) files.add(`${file}.${resolveWebVueSfcStyleLanguage(result, file)}`);
|
|
147
|
+
}
|
|
148
|
+
state = nextState;
|
|
149
|
+
componentImportIdMap = nextComponentImportIdMap;
|
|
150
|
+
if (graph && files) {
|
|
151
|
+
for (const id of SCAN_VIRTUAL_MODULE_IDS) {
|
|
152
|
+
const module = graph.getModuleById(id);
|
|
153
|
+
if (module) graph.invalidateModule(module);
|
|
154
|
+
}
|
|
155
|
+
for (const file of files) {
|
|
156
|
+
const modules = graph.getModulesByFile(file);
|
|
157
|
+
if (modules) for (const module of modules) graph.invalidateModule(module);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
133
160
|
});
|
|
134
|
-
|
|
135
|
-
|
|
161
|
+
scanQueue = result.catch(() => {});
|
|
162
|
+
return result;
|
|
163
|
+
};
|
|
164
|
+
const scanChangedFile = async (context, file) => {
|
|
165
|
+
const clean = cleanUrl(file);
|
|
166
|
+
const normalized = normalizePath(clean);
|
|
167
|
+
if (!isInsideDir(clean, srcRoot) && !state.moduleMeta.has(normalized) && !state.templatePathSet.has(normalized)) return;
|
|
168
|
+
if (clean.endsWith(".json") || isTemplateFile(clean) || isWxsFile(clean) || clean.endsWith(".wxss") || SCRIPT_EXTS.includes(extname(clean))) await scan(context);
|
|
136
169
|
};
|
|
137
170
|
return {
|
|
138
171
|
name: "@weapp-vite/web",
|
|
@@ -166,6 +199,7 @@ function weappWebPlugin(options = {}) {
|
|
|
166
199
|
config.optimizeDeps.include = Array.from(/* @__PURE__ */ new Set([...config.optimizeDeps.include ?? [], ...componentDependencies])).filter((dependency) => !isUniAppDependency(dependency, uniAppIncludes));
|
|
167
200
|
},
|
|
168
201
|
configureServer(server) {
|
|
202
|
+
devServer = server;
|
|
169
203
|
server.middlewares.use(createWebAssetMiddleware(srcRoot));
|
|
170
204
|
},
|
|
171
205
|
async buildStart() {
|
|
@@ -274,9 +308,15 @@ function weappWebPlugin(options = {}) {
|
|
|
274
308
|
}
|
|
275
309
|
return null;
|
|
276
310
|
},
|
|
311
|
+
watchChange: {
|
|
312
|
+
order: "post",
|
|
313
|
+
sequential: true,
|
|
314
|
+
async handler(id, change) {
|
|
315
|
+
if (enableHmr && change.event !== "update") await scanChangedFile(this, id);
|
|
316
|
+
}
|
|
317
|
+
},
|
|
277
318
|
async handleHotUpdate(ctx) {
|
|
278
|
-
|
|
279
|
-
if (clean.endsWith(".json") || isTemplateFile(clean) || isWxsFile(clean) || clean.endsWith(".wxss") || SCRIPT_EXTS.includes(extname(clean))) await scan(this);
|
|
319
|
+
await scanChangedFile(this, ctx.file);
|
|
280
320
|
},
|
|
281
321
|
async transform(code, id) {
|
|
282
322
|
const clean = cleanUrl(id);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/plugin/index.ts"],"sourcesContent":["import type { SourceMap } from 'magic-string'\nimport type { ResolveWebAutoImportTag, ResolveWebModuleId, WeappWebPluginOptions, WebResolvedComponent, WebStylePreprocessOptions } from './types'\nimport { readFile } from 'node:fs/promises'\nimport process from 'node:process'\n\nimport { dirname, extname, resolve } from 'pathe'\nimport { isUniAppCompatibilityFile, transformUniAppSource } from 'wevu/compiler'\nimport { compileWxml } from '../compiler/wxml'\nimport { transformWxsToEsm } from '../compiler/wxs'\nimport { createWxssPostcssPlugin, transformWxssToCss } from '../css/wxss'\nimport { createWebAssetMiddleware, emitWebAssets } from './assets'\nimport { AUTO_ROUTES_ID, ENTRY_ID, RESOLVED_AUTO_ROUTES_ID, RUNTIME_ID, SCRIPT_EXTS, SFC_STYLE_QUERY, SFC_TEMPLATE_QUERY, STYLE_EXTS, STYLE_QUERY, TEMPLATE_EXTS, TEMPLATE_QUERY, TRANSFORM_STYLE_EXTS, WEB_COMPONENT_PREFIX, WEB_COMPONENT_QUERY, WXS_EXTS } from './constants'\nimport { collectExternalComponentOptimizeDeps } from './dependencyScan'\nimport { generateAutoRoutesModule, generateEntryModule } from './entry'\nimport { wrapPageTemplate } from './layout'\nimport { createMiniProgramPackageResolver, getAncestorNodeModulesPaths } from './packageResolution'\nimport { cleanUrl, isHtmlEntry, isInsideDir, normalizePath, resolveFileWithExtensionsSync, resolveRuntimePolyfillPath, resolveTemplatePathSync, resolveWxsPathSync, toRelativeImport, toViteFsImport } from './path'\nimport { transformScriptModule } from './register'\nimport { getStableWebComponentId, scanProject } from './scan'\nimport { createEmptyScanState } from './state'\nimport { createInlineStyleModule } from './styleModule'\nimport { ensureWebVueSfcResult, generateWebVueSfcStyle, generateWebVueSfcTemplate, resolveWebVueSfcStyleLanguage, transformWebVueSfcScript } from './vueSfc'\n\ninterface WebPluginContext {\n warn?: (message: string) => void\n addWatchFile?: (id: string) => void\n emitFile?: (asset: { type: 'asset', fileName: string, source: Uint8Array }) => void\n resolve?: (source: string, importer?: string, options?: { skipSelf?: boolean }) => Promise<{ id: string } | null>\n}\n\ntype WebTransformResult = { code: string, map: SourceMap | null } | null\n\ninterface WebPostcssConfig {\n plugins?: Array<{ postcssPlugin?: string }>\n [key: string]: unknown\n}\n\ninterface WebCssConfig {\n postcss?: string | WebPostcssConfig\n preprocessorOptions?: WebStylePreprocessOptions\n}\n\ninterface WebUserConfig {\n css?: {\n postcss?: string | WebPostcssConfig\n preprocessorOptions?: WebStylePreprocessOptions\n }\n}\n\ninterface WebResolvedConfig extends WebUserConfig {\n root: string\n command: string\n createResolver?: () => ResolveWebModuleId\n optimizeDeps?: {\n exclude?: string[]\n include?: string[]\n }\n}\n\ninterface WebHmrContext {\n file: string\n}\n\ninterface WebDevServer {\n middlewares: {\n use: (middleware: ReturnType<typeof createWebAssetMiddleware>) => void\n }\n}\n\ninterface WeappWebVitePlugin {\n name: string\n enforce?: 'pre' | 'post'\n config?: (this: WebPluginContext, config: WebUserConfig) => WebUserConfig | void\n configResolved?: (this: WebPluginContext, config: WebResolvedConfig) => void | Promise<void>\n configureServer?: (server: WebDevServer) => void\n buildStart?: (this: WebPluginContext) => void | Promise<void>\n resolveId?: (id: string, importer?: string) => string | null | Promise<string | null>\n load?: (id: string) => string | null | Promise<string | null>\n handleHotUpdate?: (this: WebPluginContext, ctx: WebHmrContext) => void | Promise<void>\n transform?: (\n this: WebPluginContext,\n code: string,\n id: string,\n ) => WebTransformResult | Promise<WebTransformResult>\n}\n\nconst WEB_RUNTIME_MODULE_IDS = [\n 'lit',\n 'lit/async-directive.js',\n 'lit/directives/repeat.js',\n] as const\n\nfunction isTemplateFile(id: string) {\n const lower = id.toLowerCase()\n return TEMPLATE_EXTS.some(ext => lower.endsWith(ext))\n}\n\nfunction isWxsFile(id: string) {\n const lower = id.toLowerCase()\n return WXS_EXTS.some(ext => lower.endsWith(ext))\n}\n\nfunction hasWxsQuery(id: string) {\n return id.includes('?wxs') || id.includes('&wxs')\n}\n\nfunction hasQuery(id: string, query: string) {\n return id.includes(`?${query}`) || id.includes(`&${query}`)\n}\n\nfunction isUniAppDependency(id: string, includes: readonly string[]) {\n return includes.some(packageName => id === packageName || id.startsWith(`${packageName}/`))\n}\n\nfunction resolveSfcStyleSourceFilename(id: string) {\n const filename = cleanUrl(id)\n const vueSuffixIndex = filename.lastIndexOf('.vue.')\n return vueSuffixIndex >= 0\n ? filename.slice(0, vueSuffixIndex + '.vue'.length)\n : filename\n}\n\nfunction createWebCssConfig(\n config: WebUserConfig,\n wxssOptions: WeappWebPluginOptions['wxss'],\n warn?: (message: string) => void,\n): WebCssConfig | undefined {\n const postcssConfig = config.css?.postcss\n if (typeof postcssConfig === 'string') {\n warn?.('[@weapp-vite/web] css.postcss 使用配置文件路径时无法注入 WXSS 转换插件。')\n return undefined\n }\n\n const plugins = postcssConfig?.plugins ?? []\n if (plugins.some(plugin => plugin.postcssPlugin === 'weapp-vite-web-wxss')) {\n return undefined\n }\n\n return {\n postcss: {\n ...postcssConfig,\n plugins: [...plugins, createWxssPostcssPlugin(wxssOptions)],\n },\n preprocessorOptions: config.css?.preprocessorOptions,\n }\n}\n\nfunction resolveStylePreprocessOptions(\n options: WebStylePreprocessOptions | undefined,\n root: string,\n): WebStylePreprocessOptions | undefined {\n if (!options) {\n return undefined\n }\n\n const nodeModules = getAncestorNodeModulesPaths(root)\n return Object.fromEntries(Object.entries(options).map(([language, languageOptions]) => {\n if (!['sass', 'scss'].includes(language)) {\n return [language, languageOptions]\n }\n\n const loadPaths = Array.isArray(languageOptions.loadPaths)\n ? languageOptions.loadPaths.filter((value): value is string => typeof value === 'string')\n : []\n return [language, {\n ...languageOptions,\n loadPaths: Array.from(new Set([...loadPaths, ...nodeModules])),\n }]\n }))\n}\n\nexport function weappWebPlugin(options: WeappWebPluginOptions = {}): WeappWebVitePlugin {\n let root = process.cwd()\n let srcRoot = resolve(root, options.srcDir ?? 'src')\n let enableHmr = false\n let resolveWebModuleId: ResolveWebModuleId | undefined\n let resolveMiniProgramModuleId: ResolveWebModuleId | undefined\n let resolveWebAutoImportTag: ResolveWebAutoImportTag | undefined\n const webRuntimeModules = new Map<string, string>()\n let stylePreprocessOptions: WebStylePreprocessOptions | undefined\n const componentImportIdMap = new Map<string, string>()\n\n const state = createEmptyScanState()\n const wxssOptions = options.wxss\n const runtimeProvider = options.__runtimeProvider\n const hmrAcceptCode = runtimeProvider\n ? runtimeProvider.hmrAcceptCode\n : 'if (import.meta.hot) { import.meta.hot.accept() }'\n\n const resolveTemplatePath = (raw: string, importer: string) => resolveTemplatePathSync(raw, importer, srcRoot)\n const resolveWxsPath = (raw: string, importer: string) => resolveWxsPathSync(raw, importer, srcRoot)\n const resolveMetaByTemplate = (filename: string) => {\n const normalized = normalizePath(filename)\n for (const meta of state.moduleMeta.values()) {\n if (meta.templatePath && normalizePath(meta.templatePath) === normalized) {\n return meta\n }\n }\n return undefined\n }\n\n const createAutoImportTagResolver = (): ResolveWebAutoImportTag | undefined => {\n const resolvers = options.__autoImportResolvers\n if (!resolvers?.length) {\n return undefined\n }\n return async (tag, importer) => {\n for (const resolver of resolvers) {\n let matched: WebResolvedComponent | void\n if (typeof resolver === 'function') {\n matched = resolver(tag, importer)\n }\n else if (typeof resolver.resolve === 'function') {\n matched = resolver.resolve(tag, importer)\n }\n else {\n const from = resolver.components?.[tag]\n matched = from ? { name: tag, from } : undefined\n }\n if (!matched) {\n continue\n }\n const request = matched.resolvedId ?? matched.from\n const resolvedId = await resolveWebModuleId?.(request, importer)\n return {\n ...matched,\n resolvedId: resolvedId ?? matched.resolvedId,\n sourceType: matched.sourceType ?? (resolvedId?.endsWith('.vue') ? 'wevu-sfc' : 'native'),\n }\n }\n return undefined\n }\n }\n\n const scan = async (context: WebPluginContext) => {\n await scanProject({\n srcRoot,\n warn: context.warn?.bind(context),\n state,\n resolveId: resolveWebModuleId,\n resolveAutoImportTag: resolveWebAutoImportTag,\n resolveAppConfig: options.__resolveAppConfig,\n uniApp: options.__uniApp,\n stylePreprocessOptions,\n })\n componentImportIdMap.clear()\n for (const component of state.scanResult.components) {\n if (component.importId) {\n componentImportIdMap.set(component.importId, component.script)\n }\n }\n }\n\n return {\n name: '@weapp-vite/web',\n enforce: 'pre',\n config(this: WebPluginContext, config: WebUserConfig) {\n const css = createWebCssConfig(config, wxssOptions, this.warn?.bind(this))\n return css ? { css } : undefined\n },\n async configResolved(this: WebPluginContext, config: WebResolvedConfig) {\n root = config.root\n const { createRequire } = await import('node:module')\n const requireFromWebRuntime = createRequire(import.meta.url)\n const requireFromProject = createRequire(resolve(root, 'package.json'))\n for (const id of WEB_RUNTIME_MODULE_IDS) {\n webRuntimeModules.set(id, requireFromWebRuntime.resolve(id))\n }\n webRuntimeModules.set(RUNTIME_ID, resolveRuntimePolyfillPath())\n resolveMiniProgramModuleId = createMiniProgramPackageResolver(requireFromProject.resolve)\n srcRoot = resolve(root, options.srcDir ?? 'src')\n stylePreprocessOptions = resolveStylePreprocessOptions(config.css?.preprocessorOptions, root)\n enableHmr = config.command === 'serve'\n const resolveViteModuleId = config.createResolver?.()\n resolveWebModuleId = resolveViteModuleId\n ? async (source, importer) => {\n const resolved = await resolveViteModuleId(source, importer)\n return await resolveMiniProgramModuleId?.(resolved ?? source, importer)\n ?? await resolveMiniProgramModuleId?.(source, importer)\n ?? resolved\n }\n : undefined\n resolveWebAutoImportTag = createAutoImportTagResolver()\n await scan(this)\n const componentDependencies = await collectExternalComponentOptimizeDeps(state.scanResult.components)\n const uniAppIncludes = options.__uniApp?.include ?? []\n config.optimizeDeps ??= {}\n config.optimizeDeps.exclude = Array.from(new Set([\n ...(config.optimizeDeps.exclude ?? []),\n ...uniAppIncludes,\n ]))\n config.optimizeDeps.include = Array.from(new Set([\n ...(config.optimizeDeps.include ?? []),\n ...componentDependencies,\n ])).filter(dependency => !isUniAppDependency(dependency, uniAppIncludes))\n },\n configureServer(server: WebDevServer) {\n server.middlewares.use(createWebAssetMiddleware(srcRoot))\n },\n async buildStart(this: WebPluginContext) {\n if (!resolveWebModuleId && this.resolve) {\n resolveWebModuleId = async (source, importer) => {\n const resolved = await this.resolve?.(source, importer, { skipSelf: true })\n return await resolveMiniProgramModuleId?.(resolved?.id ?? source, importer)\n ?? await resolveMiniProgramModuleId?.(source, importer)\n ?? resolved?.id\n }\n }\n resolveWebAutoImportTag = createAutoImportTagResolver()\n await scan(this)\n if (!enableHmr) {\n await emitWebAssets(this, srcRoot)\n }\n },\n resolveId(id: string, importer?: string) {\n const runtimeModule = webRuntimeModules.get(id)\n if (runtimeModule) {\n return runtimeModule\n }\n if (id === '/@weapp-vite/web/entry' || id === '@weapp-vite/web/entry') {\n return ENTRY_ID\n }\n if (id === AUTO_ROUTES_ID) {\n return RESOLVED_AUTO_ROUTES_ID\n }\n if (id.startsWith(WEB_COMPONENT_PREFIX)) {\n const request = decodeURIComponent(id.slice(WEB_COMPONENT_PREFIX.length))\n const resolvedId = componentImportIdMap.get(request)\n return resolvedId ? `${cleanUrl(resolvedId)}?${WEB_COMPONENT_QUERY}` : null\n }\n if (id.startsWith('.') && importer && cleanUrl(importer).endsWith('.vue') && !extname(id)) {\n const resolvedScript = resolveFileWithExtensionsSync(resolve(dirname(cleanUrl(importer)), id), SCRIPT_EXTS)\n if (resolvedScript?.endsWith('.vue')) {\n return resolvedScript\n }\n }\n if (hasQuery(id, SFC_STYLE_QUERY)) {\n const queryIndex = id.indexOf('?')\n const pathname = queryIndex >= 0 ? id.slice(0, queryIndex) : id\n const query = queryIndex >= 0 ? id.slice(queryIndex) : ''\n if (pathname.startsWith('.') && importer) {\n return `${resolve(dirname(cleanUrl(importer)), pathname)}${query}`\n }\n return id\n }\n return resolveMiniProgramModuleId?.(id, importer).then(resolved => resolved ?? null) ?? null\n },\n async load(this: WebPluginContext, id: string) {\n if (id === ENTRY_ID) {\n return generateEntryModule(state.scanResult, root, wxssOptions, options)\n }\n if (id === RESOLVED_AUTO_ROUTES_ID) {\n return generateAutoRoutesModule(state.scanResult)\n }\n if (hasQuery(id, TEMPLATE_QUERY)) {\n const filename = cleanUrl(id)\n let source = await readFile(filename, 'utf8')\n const pageMeta = resolveMetaByTemplate(filename)\n if (pageMeta?.kind === 'page' && state.scanResult.layouts.length) {\n source = wrapPageTemplate(source, state.scanResult.layouts)\n }\n const navigationConfig = state.pageNavigationMap.get(normalizePath(filename))\n const componentTags = state.templateComponentMap.get(normalizePath(filename))\n const compiled = compileWxml({\n id: filename,\n source,\n resolveTemplatePath,\n resolveWxsPath,\n navigationBar: navigationConfig ? { config: navigationConfig } : undefined,\n componentTags,\n })\n for (const dependency of compiled.dependencies) {\n this.addWatchFile?.(dependency)\n }\n for (const warning of compiled.warnings ?? []) {\n this.warn?.(warning)\n }\n return compiled.code\n }\n if (hasWxsQuery(id)) {\n const filename = cleanUrl(id)\n const source = await readFile(filename, 'utf8')\n const compiled = transformWxsToEsm(source, filename, {\n resolvePath: resolveWxsPath,\n toImportPath: (resolved, importer) => normalizePath(toRelativeImport(importer, resolved)),\n })\n for (const dependency of compiled.dependencies) {\n this.addWatchFile?.(dependency)\n }\n for (const warning of compiled.warnings ?? []) {\n this.warn?.(warning)\n }\n return compiled.code\n }\n if (hasQuery(id, STYLE_QUERY)) {\n const source = await readFile(cleanUrl(id), 'utf8')\n const { css } = transformWxssToCss(source, wxssOptions)\n return createInlineStyleModule(css)\n }\n if (id.includes(`?${SFC_TEMPLATE_QUERY}`) || id.includes(`&${SFC_TEMPLATE_QUERY}`)) {\n const filename = cleanUrl(id)\n const meta = state.moduleMeta.get(normalizePath(filename))\n if (!meta) {\n return null\n }\n const result = await ensureWebVueSfcResult({\n filename,\n meta,\n srcRoot,\n state,\n resolveId: resolveWebModuleId,\n resolveAutoImportTag: resolveWebAutoImportTag,\n uniApp: options.__uniApp,\n stylePreprocessOptions,\n })\n const compiled = generateWebVueSfcTemplate(result, meta, filename, srcRoot)\n for (const dependency of compiled.dependencies) {\n this.addWatchFile?.(dependency)\n }\n for (const warning of compiled.warnings ?? []) {\n this.warn?.(warning)\n }\n return compiled.code\n }\n if (id.includes(`?${SFC_STYLE_QUERY}`) || id.includes(`&${SFC_STYLE_QUERY}`)) {\n const filename = resolveSfcStyleSourceFilename(id)\n const meta = state.moduleMeta.get(normalizePath(filename))\n if (!meta) {\n return null\n }\n const result = await ensureWebVueSfcResult({\n filename,\n meta,\n srcRoot,\n state,\n resolveId: resolveWebModuleId,\n resolveAutoImportTag: resolveWebAutoImportTag,\n uniApp: options.__uniApp,\n stylePreprocessOptions,\n })\n return generateWebVueSfcStyle(result)\n }\n return null\n },\n async handleHotUpdate(this: WebPluginContext, ctx: WebHmrContext) {\n const clean = cleanUrl(ctx.file)\n if (clean.endsWith('.json') || isTemplateFile(clean) || isWxsFile(clean) || clean.endsWith('.wxss') || SCRIPT_EXTS.includes(extname(clean))) {\n await scan(this)\n }\n },\n async transform(this: WebPluginContext, code: string, id: string) {\n const clean = cleanUrl(id)\n let uniAppTransformed = false\n\n if (\n options.__uniApp\n && isUniAppCompatibilityFile(clean, srcRoot, options.__uniApp.include)\n && !clean.endsWith('.vue')\n ) {\n const transformed = transformUniAppSource(code, { filename: clean, target: 'h5' })\n if (transformed.changed) {\n code = transformed.code\n uniAppTransformed = true\n }\n }\n\n if (\n hasQuery(id, TEMPLATE_QUERY)\n || hasWxsQuery(id)\n || hasQuery(id, STYLE_QUERY)\n || hasQuery(id, SFC_TEMPLATE_QUERY)\n || hasQuery(id, SFC_STYLE_QUERY)\n ) {\n return null\n }\n\n if (clean.endsWith('.vue')) {\n const normalized = normalizePath(clean)\n const meta = state.moduleMeta.get(normalized) ?? {\n kind: 'component' as const,\n id: getStableWebComponentId(clean, srcRoot),\n scriptPath: clean,\n sourceType: 'vue-sfc' as const,\n }\n state.moduleMeta.set(normalized, meta)\n const result = await ensureWebVueSfcResult({\n filename: clean,\n meta,\n srcRoot,\n state,\n source: code,\n resolveId: resolveWebModuleId,\n resolveAutoImportTag: resolveWebAutoImportTag,\n uniApp: options.__uniApp,\n stylePreprocessOptions,\n })\n return transformWebVueSfcScript({\n code: result.script!,\n filename: clean,\n meta,\n runtimeModuleId: runtimeProvider?.moduleId ?? toViteFsImport(resolveRuntimePolyfillPath()),\n styleLanguage: resolveWebVueSfcStyleLanguage(result, clean),\n enableHmr,\n hmrAcceptCode,\n })\n }\n\n if (isTemplateFile(clean)) {\n if (isHtmlEntry(clean, root)) {\n return null\n }\n const normalizedId = normalizePath(clean)\n if (state.templatePathSet.size > 0) {\n if (!isInsideDir(clean, srcRoot)) {\n return null\n }\n if (!state.templatePathSet.has(normalizedId)) {\n return null\n }\n }\n let templateSource = code\n const pageMeta = resolveMetaByTemplate(clean)\n if (pageMeta?.kind === 'page' && state.scanResult.layouts.length) {\n templateSource = wrapPageTemplate(code, state.scanResult.layouts)\n }\n const navigationConfig = state.pageNavigationMap.get(normalizedId)\n const componentTags = state.templateComponentMap.get(normalizedId)\n const { code: compiled, dependencies, warnings } = compileWxml({\n id: clean,\n source: templateSource,\n resolveTemplatePath,\n resolveWxsPath,\n navigationBar: navigationConfig ? { config: navigationConfig } : undefined,\n componentTags,\n })\n const addWatchFile = this.addWatchFile\n if (dependencies.length > 0 && addWatchFile) {\n for (const dep of dependencies) {\n addWatchFile.call(this, dep)\n }\n }\n const warn = this.warn\n if (warnings?.length && warn) {\n for (const warning of warnings) {\n warn.call(this, warning)\n }\n }\n return { code: compiled, map: null }\n }\n\n if (isWxsFile(clean) || hasWxsQuery(id)) {\n const { code: compiled, dependencies, warnings } = transformWxsToEsm(code, clean, {\n resolvePath: resolveWxsPath,\n toImportPath: (resolved, importer) => normalizePath(toRelativeImport(importer, resolved)),\n })\n const addWatchFile = this.addWatchFile\n if (dependencies.length > 0 && addWatchFile) {\n for (const dep of dependencies) {\n addWatchFile.call(this, dep)\n }\n }\n const warn = this.warn\n if (warnings?.length && warn) {\n for (const warning of warnings) {\n warn.call(this, warning)\n }\n }\n return { code: compiled, map: null }\n }\n\n if (TRANSFORM_STYLE_EXTS.some(ext => clean.endsWith(ext))) {\n const { css } = transformWxssToCss(code, wxssOptions)\n return {\n code: createInlineStyleModule(css),\n map: null,\n }\n }\n\n if (STYLE_EXTS.some(ext => clean.endsWith(ext)) && !clean.endsWith('.wxss')) {\n const { css } = transformWxssToCss(code, wxssOptions)\n return { code: css, map: null }\n }\n\n if (!SCRIPT_EXTS.some(ext => clean.endsWith(ext))) {\n return uniAppTransformed ? { code, map: null } : null\n }\n if (clean.includes('node_modules') && !hasQuery(id, WEB_COMPONENT_QUERY)) {\n return options.__uniApp && isUniAppCompatibilityFile(clean, srcRoot, options.__uniApp.include)\n ? { code, map: null }\n : null\n }\n\n const meta = state.moduleMeta.get(normalizePath(clean))\n if (!meta) {\n return null\n }\n\n return transformScriptModule({\n code,\n cleanId: clean,\n meta,\n enableHmr,\n runtimeModuleId: runtimeProvider?.moduleId,\n hmrAcceptCode,\n })\n },\n }\n}\n\nexport type { WeappWebPluginOptions } from './types'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAsFA,MAAM,yBAAyB;CAC7B;CACA;CACA;AACF;AAEA,SAAS,eAAe,IAAY;CAClC,MAAM,QAAQ,GAAG,YAAY;CAC7B,OAAO,cAAc,MAAK,QAAO,MAAM,SAAS,GAAG,CAAC;AACtD;AAEA,SAAS,UAAU,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AAI,CAAC,MACH,OAAO;GAGT,OAAO,sBAAsB;IAC3B;IACA,SAAS;IACT;IACA;IACA,iBAAiB,iBAAiB;IAClC;GACF,CAAC;EACH;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/plugin/index.ts"],"sourcesContent":["import type { SourceMap } from 'magic-string'\nimport type { ResolveWebAutoImportTag, ResolveWebModuleId, WeappWebPluginOptions, WebResolvedComponent, WebStylePreprocessOptions } from './types'\nimport { readFile } from 'node:fs/promises'\nimport process from 'node:process'\n\nimport { dirname, extname, resolve } from 'pathe'\nimport { isUniAppCompatibilityFile, transformUniAppSource } from 'wevu/compiler'\nimport { compileWxml } from '../compiler/wxml'\nimport { transformWxsToEsm } from '../compiler/wxs'\nimport { createWxssPostcssPlugin, transformWxssToCss } from '../css/wxss'\nimport { createWebAssetMiddleware, emitWebAssets } from './assets'\nimport { AUTO_ROUTES_ID, ENTRY_ID, RESOLVED_AUTO_ROUTES_ID, RUNTIME_ID, SCRIPT_EXTS, SFC_STYLE_QUERY, SFC_TEMPLATE_QUERY, STYLE_EXTS, STYLE_QUERY, TEMPLATE_EXTS, TEMPLATE_QUERY, TRANSFORM_STYLE_EXTS, WEB_COMPONENT_PREFIX, WEB_COMPONENT_QUERY, WXS_EXTS } from './constants'\nimport { collectExternalComponentOptimizeDeps } from './dependencyScan'\nimport { generateAutoRoutesModule, generateEntryModule } from './entry'\nimport { wrapPageTemplate } from './layout'\nimport { createMiniProgramPackageResolver, getAncestorNodeModulesPaths } from './packageResolution'\nimport { cleanUrl, isHtmlEntry, isInsideDir, normalizePath, resolveFileWithExtensionsSync, resolveRuntimePolyfillPath, resolveTemplatePathSync, resolveWxsPathSync, toRelativeImport, toViteFsImport } from './path'\nimport { transformScriptModule } from './register'\nimport { getStableWebComponentId, scanProject } from './scan'\nimport { createEmptyScanState } from './state'\nimport { createInlineStyleModule } from './styleModule'\nimport { ensureWebVueSfcResult, generateWebVueSfcStyle, generateWebVueSfcTemplate, resolveWebVueSfcStyleLanguage, transformWebVueSfcScript } from './vueSfc'\n\ninterface WebPluginContext {\n warn?: (message: string) => void\n addWatchFile?: (id: string) => void\n emitFile?: (asset: { type: 'asset', fileName: string, source: Uint8Array }) => void\n resolve?: (source: string, importer?: string, options?: { skipSelf?: boolean }) => Promise<{ id: string } | null>\n}\n\ntype WebTransformResult = { code: string, map: SourceMap | null } | null\n\ninterface WebPostcssConfig {\n plugins?: Array<{ postcssPlugin?: string }>\n [key: string]: unknown\n}\n\ninterface WebCssConfig {\n postcss?: string | WebPostcssConfig\n preprocessorOptions?: WebStylePreprocessOptions\n}\n\ninterface WebUserConfig {\n css?: {\n postcss?: string | WebPostcssConfig\n preprocessorOptions?: WebStylePreprocessOptions\n }\n}\n\ninterface WebResolvedConfig extends WebUserConfig {\n root: string\n command: string\n createResolver?: () => ResolveWebModuleId\n optimizeDeps?: {\n exclude?: string[]\n include?: string[]\n }\n}\n\ninterface WebHmrContext {\n file: string\n}\n\ninterface WebDevServer {\n middlewares: {\n use: (middleware: ReturnType<typeof createWebAssetMiddleware>) => void\n }\n moduleGraph?: {\n getModuleById: (id: string) => object | undefined\n getModulesByFile: (file: string) => Set<object> | undefined\n invalidateModule: (module: object) => void\n }\n}\n\ninterface WeappWebVitePlugin {\n name: string\n enforce?: 'pre' | 'post'\n config?: (this: WebPluginContext, config: WebUserConfig) => WebUserConfig | void\n configResolved?: (this: WebPluginContext, config: WebResolvedConfig) => void | Promise<void>\n configureServer?: (server: WebDevServer) => void\n buildStart?: (this: WebPluginContext) => void | Promise<void>\n resolveId?: (id: string, importer?: string) => string | null | Promise<string | null>\n load?: (id: string) => string | null | Promise<string | null>\n watchChange?: {\n order: 'post'\n sequential: true\n handler: (this: WebPluginContext, id: string, change: { event: 'create' | 'update' | 'delete' }) => Promise<void>\n }\n handleHotUpdate?: (this: WebPluginContext, ctx: WebHmrContext) => void | Promise<void>\n transform?: (\n this: WebPluginContext,\n code: string,\n id: string,\n ) => WebTransformResult | Promise<WebTransformResult>\n}\n\nconst WEB_RUNTIME_MODULE_IDS = [\n 'lit',\n 'lit/async-directive.js',\n 'lit/directives/repeat.js',\n] as const\n\nconst SCAN_VIRTUAL_MODULE_IDS = [ENTRY_ID, RESOLVED_AUTO_ROUTES_ID] as const\n\nfunction isTemplateFile(id: string) {\n const lower = id.toLowerCase()\n return TEMPLATE_EXTS.some(ext => lower.endsWith(ext))\n}\n\nfunction isWxsFile(id: string) {\n const lower = id.toLowerCase()\n return WXS_EXTS.some(ext => lower.endsWith(ext))\n}\n\nfunction hasWxsQuery(id: string) {\n return id.includes('?wxs') || id.includes('&wxs')\n}\n\nfunction hasQuery(id: string, query: string) {\n return id.includes(`?${query}`) || id.includes(`&${query}`)\n}\n\nfunction isUniAppDependency(id: string, includes: readonly string[]) {\n return includes.some(packageName => id === packageName || id.startsWith(`${packageName}/`))\n}\n\nfunction resolveSfcStyleSourceFilename(id: string) {\n const filename = cleanUrl(id)\n const vueSuffixIndex = filename.lastIndexOf('.vue.')\n return vueSuffixIndex >= 0\n ? filename.slice(0, vueSuffixIndex + '.vue'.length)\n : filename\n}\n\nfunction createWebCssConfig(\n config: WebUserConfig,\n wxssOptions: WeappWebPluginOptions['wxss'],\n warn?: (message: string) => void,\n): WebCssConfig | undefined {\n const postcssConfig = config.css?.postcss\n if (typeof postcssConfig === 'string') {\n warn?.('[@weapp-vite/web] css.postcss 使用配置文件路径时无法注入 WXSS 转换插件。')\n return undefined\n }\n\n const plugins = postcssConfig?.plugins ?? []\n if (plugins.some(plugin => plugin.postcssPlugin === 'weapp-vite-web-wxss')) {\n return undefined\n }\n\n return {\n postcss: {\n ...postcssConfig,\n plugins: [...plugins, createWxssPostcssPlugin(wxssOptions)],\n },\n preprocessorOptions: config.css?.preprocessorOptions,\n }\n}\n\nfunction resolveStylePreprocessOptions(\n options: WebStylePreprocessOptions | undefined,\n root: string,\n): WebStylePreprocessOptions | undefined {\n if (!options) {\n return undefined\n }\n\n const nodeModules = getAncestorNodeModulesPaths(root)\n return Object.fromEntries(Object.entries(options).map(([language, languageOptions]) => {\n if (!['sass', 'scss'].includes(language)) {\n return [language, languageOptions]\n }\n\n const loadPaths = Array.isArray(languageOptions.loadPaths)\n ? languageOptions.loadPaths.filter((value): value is string => typeof value === 'string')\n : []\n return [language, {\n ...languageOptions,\n loadPaths: Array.from(new Set([...loadPaths, ...nodeModules])),\n }]\n }))\n}\n\nexport function weappWebPlugin(options: WeappWebPluginOptions = {}): WeappWebVitePlugin {\n let root = process.cwd()\n let srcRoot = resolve(root, options.srcDir ?? 'src')\n let enableHmr = false\n let devServer: WebDevServer | undefined\n let resolveWebModuleId: ResolveWebModuleId | undefined\n let resolveMiniProgramModuleId: ResolveWebModuleId | undefined\n let resolveWebAutoImportTag: ResolveWebAutoImportTag | undefined\n const webRuntimeModules = new Map<string, string>()\n let stylePreprocessOptions: WebStylePreprocessOptions | undefined\n let componentImportIdMap = new Map<string, string>()\n\n let state = createEmptyScanState()\n let scanQueue: Promise<void> = Promise.resolve()\n const wxssOptions = options.wxss\n const runtimeProvider = options.__runtimeProvider\n const hmrAcceptCode = runtimeProvider\n ? runtimeProvider.hmrAcceptCode\n : 'if (import.meta.hot) { import.meta.hot.accept() }'\n\n const resolveTemplatePath = (raw: string, importer: string) => resolveTemplatePathSync(raw, importer, srcRoot)\n const resolveWxsPath = (raw: string, importer: string) => resolveWxsPathSync(raw, importer, srcRoot)\n const resolveMetaByTemplate = (filename: string) => {\n const normalized = normalizePath(filename)\n for (const meta of state.moduleMeta.values()) {\n if (meta.templatePath && normalizePath(meta.templatePath) === normalized) {\n return meta\n }\n }\n return undefined\n }\n\n const createAutoImportTagResolver = (): ResolveWebAutoImportTag | undefined => {\n const resolvers = options.__autoImportResolvers\n if (!resolvers?.length) {\n return undefined\n }\n return async (tag, importer) => {\n for (const resolver of resolvers) {\n let matched: WebResolvedComponent | void\n if (typeof resolver === 'function') {\n matched = resolver(tag, importer)\n }\n else if (typeof resolver.resolve === 'function') {\n matched = resolver.resolve(tag, importer)\n }\n else {\n const from = resolver.components?.[tag]\n matched = from ? { name: tag, from } : undefined\n }\n if (!matched) {\n continue\n }\n const request = matched.resolvedId ?? matched.from\n const resolvedId = await resolveWebModuleId?.(request, importer)\n return {\n ...matched,\n resolvedId: resolvedId ?? matched.resolvedId,\n sourceType: matched.sourceType ?? (resolvedId?.endsWith('.vue') ? 'wevu-sfc' : 'native'),\n }\n }\n return undefined\n }\n }\n\n const scan = (context: WebPluginContext) => {\n const result = scanQueue.then(async () => {\n const nextState = createEmptyScanState()\n await scanProject({\n srcRoot,\n warn: context.warn?.bind(context),\n state: nextState,\n resolveId: resolveWebModuleId,\n resolveAutoImportTag: resolveWebAutoImportTag,\n resolveAppConfig: options.__resolveAppConfig,\n uniApp: options.__uniApp,\n stylePreprocessOptions,\n })\n const nextComponentImportIdMap = new Map<string, string>()\n for (const component of nextState.scanResult.components) {\n if (component.importId) {\n nextComponentImportIdMap.set(component.importId, component.script)\n }\n }\n const graph = devServer?.moduleGraph\n const files = graph ? new Set<string>() : undefined\n if (files) {\n for (const snapshot of [state, nextState]) {\n for (const file of snapshot.moduleMeta.keys()) {\n files.add(file)\n }\n for (const file of snapshot.templatePathSet) {\n files.add(file)\n }\n for (const [file, result] of snapshot.sfcResults) {\n files.add(`${file}.${resolveWebVueSfcStyleLanguage(result, file)}`)\n }\n }\n }\n // 虚拟模块始终读取最后一次完整快照,不暴露扫描过程中的空映射。\n state = nextState\n componentImportIdMap = nextComponentImportIdMap\n if (graph && files) {\n for (const id of SCAN_VIRTUAL_MODULE_IDS) {\n const module = graph.getModuleById(id)\n if (module) {\n graph.invalidateModule(module)\n }\n }\n // 入口失效不会向下传播;脚本、模板和合成样式同样属于扫描快照。\n for (const file of files) {\n const modules = graph.getModulesByFile(file)\n if (modules) {\n for (const module of modules) {\n graph.invalidateModule(module)\n }\n }\n }\n }\n })\n // 调用方仍接收原始错误;队尾只负责允许下一次文件变更恢复扫描。\n scanQueue = result.catch(() => {})\n return result\n }\n\n const scanChangedFile = async (context: WebPluginContext, file: string) => {\n const clean = cleanUrl(file)\n const normalized = normalizePath(clean)\n if (!isInsideDir(clean, srcRoot) && !state.moduleMeta.has(normalized) && !state.templatePathSet.has(normalized)) {\n return\n }\n if (clean.endsWith('.json') || isTemplateFile(clean) || isWxsFile(clean) || clean.endsWith('.wxss') || SCRIPT_EXTS.includes(extname(clean))) {\n await scan(context)\n }\n }\n\n return {\n name: '@weapp-vite/web',\n enforce: 'pre',\n config(this: WebPluginContext, config: WebUserConfig) {\n const css = createWebCssConfig(config, wxssOptions, this.warn?.bind(this))\n return css ? { css } : undefined\n },\n async configResolved(this: WebPluginContext, config: WebResolvedConfig) {\n root = config.root\n const { createRequire } = await import('node:module')\n const requireFromWebRuntime = createRequire(import.meta.url)\n const requireFromProject = createRequire(resolve(root, 'package.json'))\n for (const id of WEB_RUNTIME_MODULE_IDS) {\n webRuntimeModules.set(id, requireFromWebRuntime.resolve(id))\n }\n webRuntimeModules.set(RUNTIME_ID, resolveRuntimePolyfillPath())\n resolveMiniProgramModuleId = createMiniProgramPackageResolver(requireFromProject.resolve)\n srcRoot = resolve(root, options.srcDir ?? 'src')\n stylePreprocessOptions = resolveStylePreprocessOptions(config.css?.preprocessorOptions, root)\n enableHmr = config.command === 'serve'\n const resolveViteModuleId = config.createResolver?.()\n resolveWebModuleId = resolveViteModuleId\n ? async (source, importer) => {\n const resolved = await resolveViteModuleId(source, importer)\n return await resolveMiniProgramModuleId?.(resolved ?? source, importer)\n ?? await resolveMiniProgramModuleId?.(source, importer)\n ?? resolved\n }\n : undefined\n resolveWebAutoImportTag = createAutoImportTagResolver()\n await scan(this)\n const componentDependencies = await collectExternalComponentOptimizeDeps(state.scanResult.components)\n const uniAppIncludes = options.__uniApp?.include ?? []\n config.optimizeDeps ??= {}\n config.optimizeDeps.exclude = Array.from(new Set([\n ...(config.optimizeDeps.exclude ?? []),\n ...uniAppIncludes,\n ]))\n config.optimizeDeps.include = Array.from(new Set([\n ...(config.optimizeDeps.include ?? []),\n ...componentDependencies,\n ])).filter(dependency => !isUniAppDependency(dependency, uniAppIncludes))\n },\n configureServer(server: WebDevServer) {\n devServer = server\n server.middlewares.use(createWebAssetMiddleware(srcRoot))\n },\n async buildStart(this: WebPluginContext) {\n if (!resolveWebModuleId && this.resolve) {\n resolveWebModuleId = async (source, importer) => {\n const resolved = await this.resolve?.(source, importer, { skipSelf: true })\n return await resolveMiniProgramModuleId?.(resolved?.id ?? source, importer)\n ?? await resolveMiniProgramModuleId?.(source, importer)\n ?? resolved?.id\n }\n }\n resolveWebAutoImportTag = createAutoImportTagResolver()\n await scan(this)\n if (!enableHmr) {\n await emitWebAssets(this, srcRoot)\n }\n },\n resolveId(id: string, importer?: string) {\n const runtimeModule = webRuntimeModules.get(id)\n if (runtimeModule) {\n return runtimeModule\n }\n if (id === '/@weapp-vite/web/entry' || id === '@weapp-vite/web/entry') {\n return ENTRY_ID\n }\n if (id === AUTO_ROUTES_ID) {\n return RESOLVED_AUTO_ROUTES_ID\n }\n if (id.startsWith(WEB_COMPONENT_PREFIX)) {\n const request = decodeURIComponent(id.slice(WEB_COMPONENT_PREFIX.length))\n const resolvedId = componentImportIdMap.get(request)\n return resolvedId ? `${cleanUrl(resolvedId)}?${WEB_COMPONENT_QUERY}` : null\n }\n if (id.startsWith('.') && importer && cleanUrl(importer).endsWith('.vue') && !extname(id)) {\n const resolvedScript = resolveFileWithExtensionsSync(resolve(dirname(cleanUrl(importer)), id), SCRIPT_EXTS)\n if (resolvedScript?.endsWith('.vue')) {\n return resolvedScript\n }\n }\n if (hasQuery(id, SFC_STYLE_QUERY)) {\n const queryIndex = id.indexOf('?')\n const pathname = queryIndex >= 0 ? id.slice(0, queryIndex) : id\n const query = queryIndex >= 0 ? id.slice(queryIndex) : ''\n if (pathname.startsWith('.') && importer) {\n return `${resolve(dirname(cleanUrl(importer)), pathname)}${query}`\n }\n return id\n }\n return resolveMiniProgramModuleId?.(id, importer).then(resolved => resolved ?? null) ?? null\n },\n async load(this: WebPluginContext, id: string) {\n if (id === ENTRY_ID) {\n return generateEntryModule(state.scanResult, root, wxssOptions, options)\n }\n if (id === RESOLVED_AUTO_ROUTES_ID) {\n return generateAutoRoutesModule(state.scanResult)\n }\n if (hasQuery(id, TEMPLATE_QUERY)) {\n const filename = cleanUrl(id)\n let source = await readFile(filename, 'utf8')\n const pageMeta = resolveMetaByTemplate(filename)\n if (pageMeta?.kind === 'page' && state.scanResult.layouts.length) {\n source = wrapPageTemplate(source, state.scanResult.layouts)\n }\n const navigationConfig = state.pageNavigationMap.get(normalizePath(filename))\n const componentTags = state.templateComponentMap.get(normalizePath(filename))\n const compiled = compileWxml({\n id: filename,\n source,\n resolveTemplatePath,\n resolveWxsPath,\n navigationBar: navigationConfig ? { config: navigationConfig } : undefined,\n componentTags,\n })\n for (const dependency of compiled.dependencies) {\n this.addWatchFile?.(dependency)\n }\n for (const warning of compiled.warnings ?? []) {\n this.warn?.(warning)\n }\n return compiled.code\n }\n if (hasWxsQuery(id)) {\n const filename = cleanUrl(id)\n const source = await readFile(filename, 'utf8')\n const compiled = transformWxsToEsm(source, filename, {\n resolvePath: resolveWxsPath,\n toImportPath: (resolved, importer) => normalizePath(toRelativeImport(importer, resolved)),\n })\n for (const dependency of compiled.dependencies) {\n this.addWatchFile?.(dependency)\n }\n for (const warning of compiled.warnings ?? []) {\n this.warn?.(warning)\n }\n return compiled.code\n }\n if (hasQuery(id, STYLE_QUERY)) {\n const source = await readFile(cleanUrl(id), 'utf8')\n const { css } = transformWxssToCss(source, wxssOptions)\n return createInlineStyleModule(css)\n }\n if (id.includes(`?${SFC_TEMPLATE_QUERY}`) || id.includes(`&${SFC_TEMPLATE_QUERY}`)) {\n const filename = cleanUrl(id)\n const meta = state.moduleMeta.get(normalizePath(filename))\n if (!meta) {\n return null\n }\n const result = await ensureWebVueSfcResult({\n filename,\n meta,\n srcRoot,\n state,\n resolveId: resolveWebModuleId,\n resolveAutoImportTag: resolveWebAutoImportTag,\n uniApp: options.__uniApp,\n stylePreprocessOptions,\n })\n const compiled = generateWebVueSfcTemplate(result, meta, filename, srcRoot)\n for (const dependency of compiled.dependencies) {\n this.addWatchFile?.(dependency)\n }\n for (const warning of compiled.warnings ?? []) {\n this.warn?.(warning)\n }\n return compiled.code\n }\n if (id.includes(`?${SFC_STYLE_QUERY}`) || id.includes(`&${SFC_STYLE_QUERY}`)) {\n const filename = resolveSfcStyleSourceFilename(id)\n const meta = state.moduleMeta.get(normalizePath(filename))\n if (!meta) {\n return null\n }\n const result = await ensureWebVueSfcResult({\n filename,\n meta,\n srcRoot,\n state,\n resolveId: resolveWebModuleId,\n resolveAutoImportTag: resolveWebAutoImportTag,\n uniApp: options.__uniApp,\n stylePreprocessOptions,\n })\n return generateWebVueSfcStyle(result)\n }\n return null\n },\n watchChange: {\n order: 'post',\n sequential: true,\n async handler(this: WebPluginContext, id, change) {\n // Vite 的 handleHotUpdate 不处理增删;必须在结构性 HMR 前发布完整入口。\n if (enableHmr && change.event !== 'update') {\n await scanChangedFile(this, id)\n }\n },\n },\n async handleHotUpdate(this: WebPluginContext, ctx: WebHmrContext) {\n await scanChangedFile(this, ctx.file)\n },\n async transform(this: WebPluginContext, code: string, id: string) {\n const clean = cleanUrl(id)\n let uniAppTransformed = false\n\n if (\n options.__uniApp\n && isUniAppCompatibilityFile(clean, srcRoot, options.__uniApp.include)\n && !clean.endsWith('.vue')\n ) {\n const transformed = transformUniAppSource(code, { filename: clean, target: 'h5' })\n if (transformed.changed) {\n code = transformed.code\n uniAppTransformed = true\n }\n }\n\n if (\n hasQuery(id, TEMPLATE_QUERY)\n || hasWxsQuery(id)\n || hasQuery(id, STYLE_QUERY)\n || hasQuery(id, SFC_TEMPLATE_QUERY)\n || hasQuery(id, SFC_STYLE_QUERY)\n ) {\n return null\n }\n\n if (clean.endsWith('.vue')) {\n const normalized = normalizePath(clean)\n const meta = state.moduleMeta.get(normalized) ?? {\n kind: 'component' as const,\n id: getStableWebComponentId(clean, srcRoot),\n scriptPath: clean,\n sourceType: 'vue-sfc' as const,\n }\n state.moduleMeta.set(normalized, meta)\n const result = await ensureWebVueSfcResult({\n filename: clean,\n meta,\n srcRoot,\n state,\n source: code,\n resolveId: resolveWebModuleId,\n resolveAutoImportTag: resolveWebAutoImportTag,\n uniApp: options.__uniApp,\n stylePreprocessOptions,\n })\n return transformWebVueSfcScript({\n code: result.script!,\n filename: clean,\n meta,\n runtimeModuleId: runtimeProvider?.moduleId ?? toViteFsImport(resolveRuntimePolyfillPath()),\n styleLanguage: resolveWebVueSfcStyleLanguage(result, clean),\n enableHmr,\n hmrAcceptCode,\n })\n }\n\n if (isTemplateFile(clean)) {\n if (isHtmlEntry(clean, root)) {\n return null\n }\n const normalizedId = normalizePath(clean)\n if (state.templatePathSet.size > 0) {\n if (!isInsideDir(clean, srcRoot)) {\n return null\n }\n if (!state.templatePathSet.has(normalizedId)) {\n return null\n }\n }\n let templateSource = code\n const pageMeta = resolveMetaByTemplate(clean)\n if (pageMeta?.kind === 'page' && state.scanResult.layouts.length) {\n templateSource = wrapPageTemplate(code, state.scanResult.layouts)\n }\n const navigationConfig = state.pageNavigationMap.get(normalizedId)\n const componentTags = state.templateComponentMap.get(normalizedId)\n const { code: compiled, dependencies, warnings } = compileWxml({\n id: clean,\n source: templateSource,\n resolveTemplatePath,\n resolveWxsPath,\n navigationBar: navigationConfig ? { config: navigationConfig } : undefined,\n componentTags,\n })\n const addWatchFile = this.addWatchFile\n if (dependencies.length > 0 && addWatchFile) {\n for (const dep of dependencies) {\n addWatchFile.call(this, dep)\n }\n }\n const warn = this.warn\n if (warnings?.length && warn) {\n for (const warning of warnings) {\n warn.call(this, warning)\n }\n }\n return { code: compiled, map: null }\n }\n\n if (isWxsFile(clean) || hasWxsQuery(id)) {\n const { code: compiled, dependencies, warnings } = transformWxsToEsm(code, clean, {\n resolvePath: resolveWxsPath,\n toImportPath: (resolved, importer) => normalizePath(toRelativeImport(importer, resolved)),\n })\n const addWatchFile = this.addWatchFile\n if (dependencies.length > 0 && addWatchFile) {\n for (const dep of dependencies) {\n addWatchFile.call(this, dep)\n }\n }\n const warn = this.warn\n if (warnings?.length && warn) {\n for (const warning of warnings) {\n warn.call(this, warning)\n }\n }\n return { code: compiled, map: null }\n }\n\n if (TRANSFORM_STYLE_EXTS.some(ext => clean.endsWith(ext))) {\n const { css } = transformWxssToCss(code, wxssOptions)\n return {\n code: createInlineStyleModule(css),\n map: null,\n }\n }\n\n if (STYLE_EXTS.some(ext => clean.endsWith(ext)) && !clean.endsWith('.wxss')) {\n const { css } = transformWxssToCss(code, wxssOptions)\n return { code: css, map: null }\n }\n\n if (!SCRIPT_EXTS.some(ext => clean.endsWith(ext))) {\n return uniAppTransformed ? { code, map: null } : null\n }\n if (clean.includes('node_modules') && !hasQuery(id, WEB_COMPONENT_QUERY)) {\n return options.__uniApp && isUniAppCompatibilityFile(clean, srcRoot, options.__uniApp.include)\n ? { code, map: null }\n : null\n }\n\n const meta = state.moduleMeta.get(normalizePath(clean))\n if (!meta) {\n return null\n }\n\n return transformScriptModule({\n code,\n cleanId: clean,\n meta,\n enableHmr,\n runtimeModuleId: runtimeProvider?.moduleId,\n hmrAcceptCode,\n })\n },\n }\n}\n\nexport type { WeappWebPluginOptions } from './types'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAgGA,MAAM,yBAAyB;CAC7B;CACA;CACA;AACF;AAEA,MAAM,0BAA0B,CAAC,UAAU,uBAAuB;AAElE,SAAS,eAAe,IAAY;CAClC,MAAM,QAAQ,GAAG,YAAY;CAC7B,OAAO,cAAc,MAAK,QAAO,MAAM,SAAS,GAAG,CAAC;AACtD;AAEA,SAAS,UAAU,IAAY;CAC7B,MAAM,QAAQ,GAAG,YAAY;CAC7B,OAAO,SAAS,MAAK,QAAO,MAAM,SAAS,GAAG,CAAC;AACjD;AAEA,SAAS,YAAY,IAAY;CAC/B,OAAO,GAAG,SAAS,MAAM,KAAK,GAAG,SAAS,MAAM;AAClD;AAEA,SAAS,S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
import { STYLE_QUERY, TEMPLATE_QUERY } from "./constants.mjs";
|
|
2
2
|
import { appendQuery, resolveRuntimePolyfillPath, toRelativeImport, toViteFsImport } from "./path.mjs";
|
|
3
|
+
import { mayContainPageDeclaration, stripPageDeclaration } from "wevu/compiler";
|
|
3
4
|
import { parse } from "@babel/parser";
|
|
4
5
|
import _babelTraverse from "@babel/traverse";
|
|
5
6
|
import * as t from "@babel/types";
|
|
@@ -48,6 +49,7 @@ function overwriteWevuFactoryCall(path, meta, templateIdent, styleIdent, s) {
|
|
|
48
49
|
s.appendLeft(node.end - 1, `${factoryName}, ${metaCode}`);
|
|
49
50
|
}
|
|
50
51
|
function transformScriptModule({ code, cleanId, meta, enableHmr, runtimeModuleId, hmrAcceptCode }) {
|
|
52
|
+
if (meta.kind === "page" && mayContainPageDeclaration(code)) code = stripPageDeclaration(code, cleanId)?.code ?? code;
|
|
51
53
|
let ast;
|
|
52
54
|
try {
|
|
53
55
|
ast = parse(code, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"register.mjs","names":[],"sources":["../../src/plugin/register.ts"],"sourcesContent":["import type { NodePath } from '@babel/traverse'\nimport type { CallExpression } from '@babel/types'\nimport type { SourceMap } from 'magic-string'\n\nimport type { ModuleMeta } from './types'\nimport { parse } from '@babel/parser'\nimport _babelTraverse from '@babel/traverse'\nimport * as t from '@babel/types'\n\nimport MagicString from 'magic-string'\nimport { STYLE_QUERY, TEMPLATE_QUERY } from './constants'\nimport { appendQuery, resolveRuntimePolyfillPath, toRelativeImport, toViteFsImport } from './path'\n\ntype TraverseFunction = typeof _babelTraverse extends (...args: any[]) => any\n ? typeof _babelTraverse\n : typeof _babelTraverse extends { default: infer D }\n ? D\n : typeof _babelTraverse\n\nexport function resolveBabelTraverse(mod: any): TraverseFunction {\n if (typeof mod === 'function') {\n return mod\n }\n if (mod?.default && typeof mod.default === 'function') {\n return mod.default\n }\n if (mod?.traverse && typeof mod.traverse === 'function') {\n return mod.traverse\n }\n throw new TypeError('[@weapp-vite/web] Failed to resolve @babel/traverse export.')\n}\n\nconst traverse = resolveBabelTraverse(_babelTraverse)\n\nfunction getRegisterName(kind: ModuleMeta['kind'], callee: string) {\n if (kind === 'page' && (callee === 'Page' || callee === 'Component')) {\n return 'registerPage'\n }\n if (kind === 'component' && callee === 'Component') {\n return 'registerComponent'\n }\n if (kind === 'app' && callee === 'App') {\n return 'registerApp'\n }\n return undefined\n}\n\nfunction createRegisterMetaCode(\n meta: ModuleMeta,\n templateIdent: string | undefined,\n styleIdent: string | undefined,\n includeKind = false,\n) {\n const metaParts: string[] = [`id: ${JSON.stringify(meta.id)}`]\n if (includeKind) {\n metaParts.push(`kind: ${JSON.stringify(meta.kind)}`)\n }\n if (templateIdent) {\n metaParts.push(`template: ${templateIdent}`)\n }\n if (styleIdent) {\n metaParts.push(`style: ${styleIdent}`)\n }\n if (meta.navigationBar) {\n metaParts.push(`navigationBar: ${JSON.stringify(meta.navigationBar)}`)\n }\n return `{ ${metaParts.join(', ')} }`\n}\n\nfunction overwriteCall(\n path: NodePath<CallExpression>,\n meta: ModuleMeta,\n registerName: string,\n templateIdent: string | undefined,\n styleIdent: string | undefined,\n s: MagicString,\n includeKind = false,\n) {\n const node = path.node\n const callee = node.callee\n const identifier = callee as t.Identifier\n const end = node.end!\n const insertPosition = end - 1\n const metaCode = createRegisterMetaCode(meta, templateIdent, styleIdent, includeKind)\n s.overwrite(identifier.start!, identifier.end!, registerName)\n s.appendLeft(insertPosition, `, ${metaCode}`)\n}\n\nfunction overwriteWevuFactoryCall(\n path: NodePath<CallExpression>,\n meta: ModuleMeta,\n templateIdent: string | undefined,\n styleIdent: string | undefined,\n s: MagicString,\n) {\n const node = path.node\n const identifier = node.callee as t.Identifier\n const factoryName = identifier.name\n const metaCode = createRegisterMetaCode(meta, templateIdent, styleIdent, true)\n const firstArgument = node.arguments[0]\n s.overwrite(identifier.start!, identifier.end!, 'registerWebWevuComponentFactory')\n if (firstArgument) {\n s.prependLeft(firstArgument.start!, `${factoryName}, ${metaCode}, `)\n return\n }\n s.appendLeft(node.end! - 1, `${factoryName}, ${metaCode}`)\n}\n\ninterface TransformScriptModuleOptions {\n code: string\n cleanId: string\n meta: ModuleMeta\n enableHmr: boolean\n runtimeModuleId?: string\n hmrAcceptCode?: string\n}\n\nexport function transformScriptModule({\n code,\n cleanId,\n meta,\n enableHmr,\n runtimeModuleId,\n hmrAcceptCode,\n}: TransformScriptModuleOptions): null | { code: string, map: SourceMap } {\n let ast: ReturnType<typeof parse> | undefined\n try {\n ast = parse(code, {\n sourceType: 'module',\n plugins: ['typescript', 'jsx'],\n errorRecovery: true,\n ranges: true,\n })\n }\n catch {\n return null\n }\n\n const s = new MagicString(code)\n const wevuDefineComponentSpecifiers = new Map<string, t.ImportSpecifier>()\n for (const statement of ast.program.body) {\n if (!t.isImportDeclaration(statement) || statement.source.value !== 'wevu') {\n continue\n }\n for (const specifier of statement.specifiers) {\n if (\n t.isImportSpecifier(specifier)\n && t.isIdentifier(specifier.imported, { name: 'defineComponent' })\n ) {\n wevuDefineComponentSpecifiers.set(specifier.local.name, specifier)\n }\n }\n }\n\n const imports: string[] = []\n const runtimePolyfillId = runtimeModuleId ?? toViteFsImport(resolveRuntimePolyfillPath())\n const templateIdent = meta.templatePath ? '__weapp_template__' : undefined\n const styleIdent = meta.stylePath ? '__weapp_style__' : undefined\n\n if (meta.templatePath && templateIdent) {\n imports.push(`import ${templateIdent} from '${appendQuery(toRelativeImport(cleanId, meta.templatePath), TEMPLATE_QUERY)}'`)\n }\n\n if (meta.stylePath && styleIdent) {\n const styleQuery = meta.stylePath.endsWith('.wxss') ? STYLE_QUERY : 'inline'\n imports.push(`import ${styleIdent} from '${appendQuery(toRelativeImport(cleanId, meta.stylePath), styleQuery)}'`)\n }\n\n const registerImports = new Set<string>()\n\n traverse(ast, {\n CallExpression(path: NodePath<CallExpression>) {\n if (!t.isIdentifier(path.node.callee)) {\n return\n }\n const name = path.node.callee.name\n const wevuFactorySpecifier = wevuDefineComponentSpecifiers.get(name)\n const binding = path.scope.getBinding(name)\n if (\n wevuFactorySpecifier\n && binding?.path.node === wevuFactorySpecifier\n && meta.kind !== 'app'\n ) {\n registerImports.add('registerWebWevuComponentFactory')\n overwriteWevuFactoryCall(path, meta, templateIdent, styleIdent, s)\n return\n }\n const registerName = getRegisterName(meta.kind, name)\n if (registerName) {\n registerImports.add(registerName)\n overwriteCall(path, meta, registerName, templateIdent, styleIdent, s)\n }\n },\n })\n\n registerImports.add('installWebModuleRegistration')\n imports.unshift(`import { ${Array.from(registerImports).join(', ')} } from '${runtimePolyfillId}'`)\n\n const moduleMetaCode = createRegisterMetaCode(meta, templateIdent, styleIdent, true)\n const restoreIdent = '__weapp_web_restore_registration__'\n const prefix = `${imports.join('\\n')}\\nconst ${restoreIdent} = installWebModuleRegistration(${moduleMetaCode})\\n`\n s.prepend(prefix)\n\n s.append(`\\n${restoreIdent}()\\n`)\n\n if (enableHmr && hmrAcceptCode) {\n s.append(`\\n${hmrAcceptCode}\\n`)\n }\n\n return {\n code: s.toString(),\n map: s.generateMap({\n hires: true,\n }),\n }\n}\n"],"mappings":";;;;;;;;AAmBA,SAAgB,qBAAqB,KAA4B;CAC/D,IAAI,OAAO,QAAQ,YACjB,OAAO;CAET,IAAI,KAAK,WAAW,OAAO,IAAI,YAAY,YACzC,OAAO,IAAI;CAEb,IAAI,KAAK,YAAY,OAAO,IAAI,aAAa,YAC3C,OAAO,IAAI;CAEb,MAAM,IAAI,UAAU,6DAA6D;AACnF;AAEA,MAAM,WAAW,qBAAqB,cAAc;AAEpD,SAAS,gBAAgB,MAA0B,QAAgB;CACjE,IAAI,SAAS,WAAW,WAAW,UAAU,WAAW,cACtD,OAAO;CAET,IAAI,SAAS,eAAe,WAAW,aACrC,OAAO;CAET,IAAI,SAAS,SAAS,WAAW,OAC/B,OAAO;AAGX;AAEA,SAAS,uBACP,MACA,eACA,YACA,cAAc,OACd;CACA,MAAM,YAAsB,CAAC,OAAO,KAAK,U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ChB,gBAAgB,IAAI,YAAY;GAChC,cAAc,MAAM,MAAM,cAAc,eAAe,YAAY,CAAC;EACtE;CACF,EACF,CAAC;CAED,gBAAgB,IAAI,8BAA8B;CAClD,QAAQ,QAAQ,YAAY,MAAM,KAAK,eAAe,CAAC,CAAC,KAAK,IAAI,EAAE,WAAW,kBAAkB,EAAE;CAElG,MAAM,iBAAiB,uBAAuB,MAAM,eAAe,YAAY,IAAI;CACnF,MAAM,eAAe;CACrB,MAAM,SAAS,GAAG,QAAQ,KAAK,IAAI,EAAE,UAAU,aAAa,kCAAkC,eAAe;CAC7G,EAAE,QAAQ,MAAM;CAEhB,EAAE,OAAO,KAAK,aAAa,KAAK;CAEhC,IAAI,aAAa,eACf,EAAE,OAAO,KAAK,cAAc,GAAG;CAGjC,OAAO;EACL,MAAM,EAAE,SAAS;EACjB,KAAK,EAAE,YAAY,EACjB,OAAO,KACT,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"register.mjs","names":[],"sources":["../../src/plugin/register.ts"],"sourcesContent":["import type { NodePath } from '@babel/traverse'\nimport type { CallExpression } from '@babel/types'\nimport type { SourceMap } from 'magic-string'\n\nimport type { ModuleMeta } from './types'\nimport { parse } from '@babel/parser'\nimport _babelTraverse from '@babel/traverse'\nimport * as t from '@babel/types'\n\nimport MagicString from 'magic-string'\nimport { mayContainPageDeclaration, stripPageDeclaration } from 'wevu/compiler'\nimport { STYLE_QUERY, TEMPLATE_QUERY } from './constants'\nimport { appendQuery, resolveRuntimePolyfillPath, toRelativeImport, toViteFsImport } from './path'\n\ntype TraverseFunction = typeof _babelTraverse extends (...args: any[]) => any\n ? typeof _babelTraverse\n : typeof _babelTraverse extends { default: infer D }\n ? D\n : typeof _babelTraverse\n\nexport function resolveBabelTraverse(mod: any): TraverseFunction {\n if (typeof mod === 'function') {\n return mod\n }\n if (mod?.default && typeof mod.default === 'function') {\n return mod.default\n }\n if (mod?.traverse && typeof mod.traverse === 'function') {\n return mod.traverse\n }\n throw new TypeError('[@weapp-vite/web] Failed to resolve @babel/traverse export.')\n}\n\nconst traverse = resolveBabelTraverse(_babelTraverse)\n\nfunction getRegisterName(kind: ModuleMeta['kind'], callee: string) {\n if (kind === 'page' && (callee === 'Page' || callee === 'Component')) {\n return 'registerPage'\n }\n if (kind === 'component' && callee === 'Component') {\n return 'registerComponent'\n }\n if (kind === 'app' && callee === 'App') {\n return 'registerApp'\n }\n return undefined\n}\n\nfunction createRegisterMetaCode(\n meta: ModuleMeta,\n templateIdent: string | undefined,\n styleIdent: string | undefined,\n includeKind = false,\n) {\n const metaParts: string[] = [`id: ${JSON.stringify(meta.id)}`]\n if (includeKind) {\n metaParts.push(`kind: ${JSON.stringify(meta.kind)}`)\n }\n if (templateIdent) {\n metaParts.push(`template: ${templateIdent}`)\n }\n if (styleIdent) {\n metaParts.push(`style: ${styleIdent}`)\n }\n if (meta.navigationBar) {\n metaParts.push(`navigationBar: ${JSON.stringify(meta.navigationBar)}`)\n }\n return `{ ${metaParts.join(', ')} }`\n}\n\nfunction overwriteCall(\n path: NodePath<CallExpression>,\n meta: ModuleMeta,\n registerName: string,\n templateIdent: string | undefined,\n styleIdent: string | undefined,\n s: MagicString,\n includeKind = false,\n) {\n const node = path.node\n const callee = node.callee\n const identifier = callee as t.Identifier\n const end = node.end!\n const insertPosition = end - 1\n const metaCode = createRegisterMetaCode(meta, templateIdent, styleIdent, includeKind)\n s.overwrite(identifier.start!, identifier.end!, registerName)\n s.appendLeft(insertPosition, `, ${metaCode}`)\n}\n\nfunction overwriteWevuFactoryCall(\n path: NodePath<CallExpression>,\n meta: ModuleMeta,\n templateIdent: string | undefined,\n styleIdent: string | undefined,\n s: MagicString,\n) {\n const node = path.node\n const identifier = node.callee as t.Identifier\n const factoryName = identifier.name\n const metaCode = createRegisterMetaCode(meta, templateIdent, styleIdent, true)\n const firstArgument = node.arguments[0]\n s.overwrite(identifier.start!, identifier.end!, 'registerWebWevuComponentFactory')\n if (firstArgument) {\n s.prependLeft(firstArgument.start!, `${factoryName}, ${metaCode}, `)\n return\n }\n s.appendLeft(node.end! - 1, `${factoryName}, ${metaCode}`)\n}\n\ninterface TransformScriptModuleOptions {\n code: string\n cleanId: string\n meta: ModuleMeta\n enableHmr: boolean\n runtimeModuleId?: string\n hmrAcceptCode?: string\n}\n\nexport function transformScriptModule({\n code,\n cleanId,\n meta,\n enableHmr,\n runtimeModuleId,\n hmrAcceptCode,\n}: TransformScriptModuleOptions): null | { code: string, map: SourceMap } {\n if (meta.kind === 'page' && mayContainPageDeclaration(code)) {\n code = stripPageDeclaration(code, cleanId)?.code ?? code\n }\n let ast: ReturnType<typeof parse> | undefined\n try {\n ast = parse(code, {\n sourceType: 'module',\n plugins: ['typescript', 'jsx'],\n errorRecovery: true,\n ranges: true,\n })\n }\n catch {\n return null\n }\n\n const s = new MagicString(code)\n const wevuDefineComponentSpecifiers = new Map<string, t.ImportSpecifier>()\n for (const statement of ast.program.body) {\n if (!t.isImportDeclaration(statement) || statement.source.value !== 'wevu') {\n continue\n }\n for (const specifier of statement.specifiers) {\n if (\n t.isImportSpecifier(specifier)\n && t.isIdentifier(specifier.imported, { name: 'defineComponent' })\n ) {\n wevuDefineComponentSpecifiers.set(specifier.local.name, specifier)\n }\n }\n }\n\n const imports: string[] = []\n const runtimePolyfillId = runtimeModuleId ?? toViteFsImport(resolveRuntimePolyfillPath())\n const templateIdent = meta.templatePath ? '__weapp_template__' : undefined\n const styleIdent = meta.stylePath ? '__weapp_style__' : undefined\n\n if (meta.templatePath && templateIdent) {\n imports.push(`import ${templateIdent} from '${appendQuery(toRelativeImport(cleanId, meta.templatePath), TEMPLATE_QUERY)}'`)\n }\n\n if (meta.stylePath && styleIdent) {\n const styleQuery = meta.stylePath.endsWith('.wxss') ? STYLE_QUERY : 'inline'\n imports.push(`import ${styleIdent} from '${appendQuery(toRelativeImport(cleanId, meta.stylePath), styleQuery)}'`)\n }\n\n const registerImports = new Set<string>()\n\n traverse(ast, {\n CallExpression(path: NodePath<CallExpression>) {\n if (!t.isIdentifier(path.node.callee)) {\n return\n }\n const name = path.node.callee.name\n const wevuFactorySpecifier = wevuDefineComponentSpecifiers.get(name)\n const binding = path.scope.getBinding(name)\n if (\n wevuFactorySpecifier\n && binding?.path.node === wevuFactorySpecifier\n && meta.kind !== 'app'\n ) {\n registerImports.add('registerWebWevuComponentFactory')\n overwriteWevuFactoryCall(path, meta, templateIdent, styleIdent, s)\n return\n }\n const registerName = getRegisterName(meta.kind, name)\n if (registerName) {\n registerImports.add(registerName)\n overwriteCall(path, meta, registerName, templateIdent, styleIdent, s)\n }\n },\n })\n\n registerImports.add('installWebModuleRegistration')\n imports.unshift(`import { ${Array.from(registerImports).join(', ')} } from '${runtimePolyfillId}'`)\n\n const moduleMetaCode = createRegisterMetaCode(meta, templateIdent, styleIdent, true)\n const restoreIdent = '__weapp_web_restore_registration__'\n const prefix = `${imports.join('\\n')}\\nconst ${restoreIdent} = installWebModuleRegistration(${moduleMetaCode})\\n`\n s.prepend(prefix)\n\n s.append(`\\n${restoreIdent}()\\n`)\n\n if (enableHmr && hmrAcceptCode) {\n s.append(`\\n${hmrAcceptCode}\\n`)\n }\n\n return {\n code: s.toString(),\n map: s.generateMap({\n hires: true,\n }),\n }\n}\n"],"mappings":";;;;;;;;;AAoBA,SAAgB,qBAAqB,KAA4B;CAC/D,IAAI,OAAO,QAAQ,YACjB,OAAO;CAET,IAAI,KAAK,WAAW,OAAO,IAAI,YAAY,YACzC,OAAO,IAAI;CAEb,IAAI,KAAK,YAAY,OAAO,IAAI,aAAa,YAC3C,OAAO,IAAI;CAEb,MAAM,IAAI,UAAU,6DAA6D;AACnF;AAEA,MAAM,WAAW,qBAAqB,cAAc;AAEpD,SAAS,gBAAgB,MAA0B,QAAgB;CACjE,IAAI,SAAS,WAAW,WAAW,UAAU,WAAW,cACtD,OAAO;CAET,IAAI,SAAS,eAAe,WAAW,aACrC,OAAO;CAET,IAAI,SAAS,SAAS,WAAW,OAC/B,OAAO;AAGX;AAEA,SA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ACvB,KAAK,SAAS,OACjB;GACA,gBAAgB,IAAI,iCAAiC;GACrD,yBAAyB,MAAM,MAAM,eAAe,YAAY,CAAC;GACjE;EACF;EACA,MAAM,eAAe,gBAAgB,KAAK,MAAM,IAAI;EACpD,IAAI,cAAc;GAChB,gBAAgB,IAAI,YAAY;GAChC,cAAc,MAAM,MAAM,cAAc,eAAe,YAAY,CAAC;EACtE;CACF,EACF,CAAC;CAED,gBAAgB,IAAI,8BAA8B;CAClD,QAAQ,QAAQ,YAAY,MAAM,KAAK,eAAe,CAAC,CAAC,KAAK,IAAI,EAAE,WAAW,kBAAkB,EAAE;CAElG,MAAM,iBAAiB,uBAAuB,MAAM,eAAe,YAAY,IAAI;CACnF,MAAM,eAAe;CACrB,MAAM,SAAS,GAAG,QAAQ,KAAK,IAAI,EAAE,UAAU,aAAa,kCAAkC,eAAe;CAC7G,EAAE,QAAQ,MAAM;CAEhB,EAAE,OAAO,KAAK,aAAa,KAAK;CAEhC,IAAI,aAAa,eACf,EAAE,OAAO,KAAK,cAAc,GAAG;CAGjC,OAAO;EACL,MAAM,EAAE,SAAS;EACjB,KAAK,EAAE,YAAY,EACjB,OAAO,KACT,CAAC;CACH;AACF"}
|
|
@@ -10,8 +10,8 @@ import { resolveRelationNodes } from "./relations.mjs";
|
|
|
10
10
|
import { createWebSlotsProxy } from "./slots.mjs";
|
|
11
11
|
import { assignDataPath, cloneValue, coerceValue, parseDataPath, resolveDataPath, toCamelCase } from "./utils.mjs";
|
|
12
12
|
import { clearVirtualHostClasses, clearVirtualHostParts, syncVirtualHostClasses, syncVirtualHostParts } from "./virtualHost.mjs";
|
|
13
|
-
import { html } from "lit";
|
|
14
13
|
import { WEVU_HOST_COMMIT_PROMISE_KEY } from "@weapp-core/constants";
|
|
14
|
+
import { html } from "lit";
|
|
15
15
|
import { unsafeHTML } from "lit/directives/unsafe-html.js";
|
|
16
16
|
|
|
17
17
|
//#region src/runtime/component/element.ts
|
package/dist/runtime/index.mjs
CHANGED
|
@@ -1,31 +1,31 @@
|
|
|
1
1
|
import { __exportAll, __reExport } from "../_virtual/_rolldown/runtime.mjs";
|
|
2
2
|
import { setRuntimeWarningOptions } from "./warning.mjs";
|
|
3
3
|
import { installWebHostGlobals } from "./hostGlobals.mjs";
|
|
4
|
+
import { getRuntimeClipboard, getRuntimeDialogs, getRuntimeFetch, getRuntimeStorage, getWebRuntimeHost, openRuntimeUrl, resetWebRuntimeHost, setWebRuntimeHost } from "./host/index.mjs";
|
|
5
|
+
import { authorize, checkSession, getAccountInfoSync, getAppAuthorizeSetting, getAppBaseInfo, getBatteryInfo, getBatteryInfoSync, getDeviceInfo, getFuzzyLocation, getLocation, getMenuButtonBoundingClientRect, getNetworkType, getSetting, getSystemInfo, getSystemInfoSync, getSystemSetting, getUserInfo, getUserProfile, getWindowInfo, login, offNetworkStatusChange, offWindowResize, onNetworkStatusChange, onWindowResize, openAppAuthorizeSetting, openSetting, vibrateShort } from "./polyfill/deviceAuthSystemApi.mjs";
|
|
6
|
+
import { configureWebSeo, resetWebDocumentHead, setupWebResourceHints, syncWebDocumentHead, updateWebDocumentTitle } from "./seo/index.mjs";
|
|
4
7
|
import { injectStyle, removeStyle } from "./style.mjs";
|
|
5
8
|
import { ensureButtonDefined, setButtonFormConfig } from "./button/index.mjs";
|
|
6
9
|
import { getRuntimeExecutionMode, setRuntimeExecutionMode } from "./execution.mjs";
|
|
7
10
|
import { createRenderContext } from "./renderContext.mjs";
|
|
8
11
|
import { defineComponent } from "./component/index.mjs";
|
|
9
|
-
import { bindRuntimeEvent } from "./eventBinding.mjs";
|
|
10
|
-
import { getRuntimeClipboard, getRuntimeDialogs, getRuntimeFetch, getRuntimeStorage, getWebRuntimeHost, openRuntimeUrl, resetWebRuntimeHost, setWebRuntimeHost } from "./host/index.mjs";
|
|
11
12
|
import { resolveImageModeStyle } from "./nativeComponents/image.mjs";
|
|
12
13
|
import { createInputEventDetail } from "./nativeComponents/input.mjs";
|
|
13
|
-
import { setNavigationBarMetrics } from "./navigationBar/index.mjs";
|
|
14
|
-
import { getWebViewportWidth, resolveWebViewportConfig, setupWebViewport } from "./viewport/index.mjs";
|
|
15
|
-
import { setupRpx } from "./rpx.mjs";
|
|
16
|
-
import { configureWebSeo, resetWebDocumentHead, setupWebResourceHints, syncWebDocumentHead, updateWebDocumentTitle } from "./seo/index.mjs";
|
|
17
|
-
import { disposeWebRouting, getWebRoutingConfig, resolveWebRoutingConfig } from "./polyfill/routeRuntime/history.mjs";
|
|
18
|
-
import { getEnterOptionsSync, getLaunchOptionsSync, initializePageRoutes, navigateBack, navigateTo, offAppHide, offAppShow, onAppHide, onAppShow, reLaunch, redirectTo, registerApp, registerComponent, registerPage, switchTab } from "./polyfill/routeRuntime.mjs";
|
|
19
14
|
import { clearStorage, clearStorageSync, createCanvasContext, createSelectorQuery, createVKSession, createVideoContext, createWorker, downloadFile, exitMiniProgram, getFileSystemManager, getStorage, getStorageInfo, getStorageInfoSync, getStorageSync, hideKeyboard, loadSubPackage, navigateToMiniProgram, nextTick, pageScrollTo, preloadSubpackage, removeStorage, removeStorageSync, request, setStorage, setStorageSync, startPullDownRefresh, stopPullDownRefresh, uploadFile } from "./polyfill/runtimeDataApi.mjs";
|
|
20
15
|
import { createScrollEventDetail } from "./nativeComponents/scrollView.mjs";
|
|
21
16
|
import { createSwitchEventDetail } from "./nativeComponents/switch.mjs";
|
|
22
17
|
import { createTextareaLineChangeDetail } from "./nativeComponents/textarea.mjs";
|
|
23
18
|
import { createVideoProgressDetail, createVideoTimeUpdateDetail, resolveVideoObjectFit } from "./nativeComponents/video/helpers.mjs";
|
|
24
19
|
import { ensureNativeComponentsDefined } from "./nativeComponents/index.mjs";
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
20
|
+
import { setNavigationBarMetrics } from "./navigationBar/index.mjs";
|
|
21
|
+
import { getWebViewportWidth, resolveWebViewportConfig, setupWebViewport } from "./viewport/index.mjs";
|
|
22
|
+
import { setupRpx } from "./rpx.mjs";
|
|
23
|
+
import { disposeWebRouting, getWebRoutingConfig, resolveWebRoutingConfig } from "./polyfill/routeRuntime/history.mjs";
|
|
24
|
+
import { getEnterOptionsSync, getLaunchOptionsSync, initializePageRoutes, navigateBack, navigateTo, offAppHide, offAppShow, onAppHide, onAppShow, reLaunch, redirectTo, registerApp, registerComponent, registerPage, switchTab } from "./polyfill/routeRuntime.mjs";
|
|
27
25
|
import { chooseAddress, chooseFile, chooseImage, chooseLocation, chooseMedia, chooseMessageFile, chooseVideo, compressImage, compressVideo, getClipboardData, getImageInfo, getVideoInfo, hideLoading, hideTabBar, hideTabBarRedDot, makePhoneCall, openCustomerServiceChat, openDocument, openLocation, openVideoEditor, previewImage, previewMedia, removeTabBarBadge, requestPayment, requestSubscribeMessage, saveFile, saveFileToDisk, saveImageToPhotosAlbum, saveVideoToPhotosAlbum, scanCode, setClipboardData, setTabBarBadge, setTabBarItem, setTabBarStyle, showActionSheet, showLoading, showModal, showShareMenu, showTabBar, showTabBarRedDot, showToast, updateShareMenu } from "./polyfill/uiMediaApi.mjs";
|
|
28
|
-
import { canIUse, createInterstitialAd, createRewardedVideoAd, getExtConfig, getExtConfigSync, getLogManager, getUpdateManager, hideNavigationBarLoading, reportAnalytics, setBackgroundColor, setBackgroundTextStyle, setNavigationBarColor, setNavigationBarTitle, showNavigationBarLoading } from "./polyfill/index.mjs";
|
|
26
|
+
import { canIUse, createInterstitialAd, createRewardedVideoAd, getExtConfig, getExtConfigSync, getLogManager, getUpdateManager, hideNavigationBarLoading, installMiniProgramGlobals, reportAnalytics, setBackgroundColor, setBackgroundTextStyle, setNavigationBarColor, setNavigationBarTitle, showNavigationBarLoading } from "./polyfill/index.mjs";
|
|
27
|
+
import { bindRuntimeEvent } from "./eventBinding.mjs";
|
|
28
|
+
import { setPageLayout } from "./pageLayout.mjs";
|
|
29
29
|
import { createTemplate, renderTemplate } from "./legacyTemplate/index.mjs";
|
|
30
30
|
import { installWebModuleRegistration, registerWebWevuApp, registerWebWevuComponent, registerWebWevuComponentFactory } from "./wevu.mjs";
|
|
31
31
|
|
|
@@ -33,6 +33,7 @@ export * from "wevu/internal-runtime"
|
|
|
33
33
|
|
|
34
34
|
//#region src/runtime/index.ts
|
|
35
35
|
installWebHostGlobals();
|
|
36
|
+
installMiniProgramGlobals();
|
|
36
37
|
|
|
37
38
|
//#endregion
|
|
38
39
|
export { authorize, bindRuntimeEvent, canIUse, checkSession, chooseAddress, chooseFile, chooseImage, chooseLocation, chooseMedia, chooseMessageFile, chooseVideo, clearStorage, clearStorageSync, compressImage, compressVideo, configureWebSeo, createCanvasContext, createInputEventDetail, createInterstitialAd, createRenderContext, createRewardedVideoAd, createScrollEventDetail, createSelectorQuery, createSwitchEventDetail, createTemplate, createTextareaLineChangeDetail, createVKSession, createVideoContext, createVideoProgressDetail, createVideoTimeUpdateDetail, createWorker, defineComponent, disposeWebRouting, downloadFile, ensureButtonDefined, ensureNativeComponentsDefined, exitMiniProgram, getAccountInfoSync, getAppAuthorizeSetting, getAppBaseInfo, getBatteryInfo, getBatteryInfoSync, getClipboardData, getDeviceInfo, getEnterOptionsSync, getExtConfig, getExtConfigSync, getFileSystemManager, getFuzzyLocation, getImageInfo, getLaunchOptionsSync, getLocation, getLogManager, getMenuButtonBoundingClientRect, getNetworkType, getRuntimeClipboard, getRuntimeDialogs, getRuntimeExecutionMode, getRuntimeFetch, getRuntimeStorage, getSetting, getStorage, getStorageInfo, getStorageInfoSync, getStorageSync, getSystemInfo, getSystemInfoSync, getSystemSetting, getUpdateManager, getUserInfo, getUserProfile, getVideoInfo, getWebRoutingConfig, getWebRuntimeHost, getWebViewportWidth, getWindowInfo, hideKeyboard, hideLoading, hideNavigationBarLoading, hideTabBar, hideTabBarRedDot, initializePageRoutes, injectStyle, installWebHostGlobals, installWebModuleRegistration, loadSubPackage, login, makePhoneCall, navigateBack, navigateTo, navigateToMiniProgram, nextTick, offAppHide, offAppShow, offNetworkStatusChange, offWindowResize, onAppHide, onAppShow, onNetworkStatusChange, onWindowResize, openAppAuthorizeSetting, openCustomerServiceChat, openDocument, openLocation, openRuntimeUrl, openSetting, openVideoEditor, pageScrollTo, preloadSubpackage, previewImage, previewMedia, reLaunch, redirectTo, registerApp, registerComponent, registerPage, registerWebWevuApp, registerWebWevuComponent, registerWebWevuComponentFactory, removeStorage, removeStorageSync, removeStyle, removeTabBarBadge, renderTemplate, reportAnalytics, request, requestPayment, requestSubscribeMessage, resetWebDocumentHead, resetWebRuntimeHost, resolveImageModeStyle, resolveVideoObjectFit, resolveWebRoutingConfig, resolveWebViewportConfig, saveFile, saveFileToDisk, saveImageToPhotosAlbum, saveVideoToPhotosAlbum, scanCode, setBackgroundColor, setBackgroundTextStyle, setButtonFormConfig, setClipboardData, setNavigationBarColor, setNavigationBarMetrics, setNavigationBarTitle, setPageLayout, setRuntimeExecutionMode, setRuntimeWarningOptions, setStorage, setStorageSync, setTabBarBadge, setTabBarItem, setTabBarStyle, setWebRuntimeHost, setupRpx, setupWebResourceHints, setupWebViewport, showActionSheet, showLoading, showModal, showNavigationBarLoading, showShareMenu, showTabBar, showTabBarRedDot, showToast, startPullDownRefresh, stopPullDownRefresh, switchTab, syncWebDocumentHead, updateShareMenu, updateWebDocumentTitle, uploadFile, vibrateShort };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/runtime/index.ts"],"sourcesContent":["import { installWebHostGlobals } from './hostGlobals'\n\ninstallWebHostGlobals()\n\nexport type { WebTabBarConfig, WebTabBarItem } from './appShell/tabBar'\nexport { ensureButtonDefined, setButtonFormConfig } from './button'\nexport type { ButtonFormConfig } from './button'\nexport { defineComponent } from './component'\nexport { bindRuntimeEvent } from './eventBinding'\nexport { getRuntimeExecutionMode, setRuntimeExecutionMode } from './execution'\nexport {\n getRuntimeClipboard,\n getRuntimeDialogs,\n getRuntimeFetch,\n getRuntimeStorage,\n getWebRuntimeHost,\n openRuntimeUrl,\n resetWebRuntimeHost,\n setWebRuntimeHost,\n} from './host'\nexport type { WebRuntimeClipboard, WebRuntimeDialogs, WebRuntimeHost, WebRuntimeStorage } from './host'\nexport { installWebHostGlobals } from './hostGlobals'\nexport {\n createInputEventDetail,\n createScrollEventDetail,\n createSwitchEventDetail,\n createTextareaLineChangeDetail,\n createVideoProgressDetail,\n createVideoTimeUpdateDetail,\n ensureNativeComponentsDefined,\n resolveImageModeStyle,\n resolveVideoObjectFit,\n} from './nativeComponents'\nexport { setNavigationBarMetrics } from './navigationBar'\nexport type { NavigationBarMetrics } from './navigationBar'\nexport { setPageLayout } from './pageLayout'\nexport {\n authorize,\n canIUse,\n checkSession,\n chooseAddress,\n chooseFile,\n chooseImage,\n chooseLocation,\n chooseMedia,\n chooseMessageFile,\n chooseVideo,\n clearStorage,\n clearStorageSync,\n compressImage,\n compressVideo,\n createCanvasContext,\n createInterstitialAd,\n createRewardedVideoAd,\n createSelectorQuery,\n createVideoContext,\n createVKSession,\n createWorker,\n downloadFile,\n exitMiniProgram,\n getAccountInfoSync,\n getAppAuthorizeSetting,\n getAppBaseInfo,\n getBatteryInfo,\n getBatteryInfoSync,\n getClipboardData,\n getDeviceInfo,\n getEnterOptionsSync,\n getExtConfig,\n getExtConfigSync,\n getFileSystemManager,\n getFuzzyLocation,\n getImageInfo,\n getLaunchOptionsSync,\n getLocation,\n getLogManager,\n getMenuButtonBoundingClientRect,\n getNetworkType,\n getSetting,\n getStorage,\n getStorageInfo,\n getStorageInfoSync,\n getStorageSync,\n getSystemInfo,\n getSystemInfoSync,\n getSystemSetting,\n getUpdateManager,\n getUserInfo,\n getUserProfile,\n getVideoInfo,\n getWindowInfo,\n hideKeyboard,\n hideLoading,\n hideNavigationBarLoading,\n hideTabBar,\n hideTabBarRedDot,\n initializePageRoutes,\n loadSubPackage,\n login,\n makePhoneCall,\n navigateBack,\n navigateTo,\n navigateToMiniProgram,\n nextTick,\n offAppHide,\n offAppShow,\n offNetworkStatusChange,\n offWindowResize,\n onAppHide,\n onAppShow,\n onNetworkStatusChange,\n onWindowResize,\n openAppAuthorizeSetting,\n openCustomerServiceChat,\n openDocument,\n openLocation,\n openSetting,\n openVideoEditor,\n pageScrollTo,\n preloadSubpackage,\n previewImage,\n previewMedia,\n redirectTo,\n registerApp,\n registerComponent,\n registerPage,\n reLaunch,\n removeStorage,\n removeStorageSync,\n removeTabBarBadge,\n reportAnalytics,\n request,\n requestPayment,\n requestSubscribeMessage,\n saveFile,\n saveFileToDisk,\n saveImageToPhotosAlbum,\n saveVideoToPhotosAlbum,\n scanCode,\n setBackgroundColor,\n setBackgroundTextStyle,\n setClipboardData,\n setNavigationBarColor,\n setNavigationBarTitle,\n setStorage,\n setStorageSync,\n setTabBarBadge,\n setTabBarItem,\n setTabBarStyle,\n showActionSheet,\n showLoading,\n showModal,\n showNavigationBarLoading,\n showShareMenu,\n showTabBar,\n showTabBarRedDot,\n showToast,\n startPullDownRefresh,\n stopPullDownRefresh,\n switchTab,\n updateShareMenu,\n uploadFile,\n vibrateShort,\n} from './polyfill'\nexport type { AppHideCallback, AppHideOptions, AppLaunchOptions, AppShowCallback } from './polyfill'\nexport {\n disposeWebRouting,\n getWebRoutingConfig,\n resolveWebRoutingConfig,\n} from './polyfill/routeRuntime/history'\nexport type {\n ResolvedWebRoutingConfig,\n WebRouteHistoryState,\n WebRouteTarget,\n WebRoutingConfig,\n WebRoutingMode,\n} from './polyfill/routeRuntime/history'\nexport { createRenderContext } from './renderContext'\nexport type { RenderContext } from './renderContext'\nexport { setupRpx } from './rpx'\nexport type { RpxConfig } from './rpx'\nexport {\n configureWebSeo,\n resetWebDocumentHead,\n setupWebResourceHints,\n syncWebDocumentHead,\n updateWebDocumentTitle,\n} from './seo'\nexport type { WebPageHead, WebResourceHint, WebResourceHintRelation, WebResourceHintsConfig, WebSeoConfig } from './seo'\nexport { injectStyle, removeStyle } from './style'\nexport { createTemplate, renderTemplate } from './template'\nexport type { TemplateRenderer, TemplateScope } from './template'\nexport { getWebViewportWidth, resolveWebViewportConfig, setupWebViewport } from './viewport'\nexport type { ResolvedWebViewportConfig, WebViewportConfig } from './viewport'\nexport { setRuntimeWarningOptions } from './warning'\nexport type { RuntimeWarningLevel, RuntimeWarningOptions } from './warning'\nexport {\n installWebModuleRegistration,\n registerWebWevuApp,\n registerWebWevuComponent,\n registerWebWevuComponentFactory,\n} from './wevu'\nexport * from 'wevu/internal-runtime'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/runtime/index.ts"],"sourcesContent":["import { installWebHostGlobals } from './hostGlobals'\nimport { installMiniProgramGlobals } from './polyfill'\n\ninstallWebHostGlobals()\ninstallMiniProgramGlobals()\n\nexport type { WebTabBarConfig, WebTabBarItem } from './appShell/tabBar'\nexport { ensureButtonDefined, setButtonFormConfig } from './button'\nexport type { ButtonFormConfig } from './button'\nexport { defineComponent } from './component'\nexport { bindRuntimeEvent } from './eventBinding'\nexport { getRuntimeExecutionMode, setRuntimeExecutionMode } from './execution'\nexport {\n getRuntimeClipboard,\n getRuntimeDialogs,\n getRuntimeFetch,\n getRuntimeStorage,\n getWebRuntimeHost,\n openRuntimeUrl,\n resetWebRuntimeHost,\n setWebRuntimeHost,\n} from './host'\nexport type { WebRuntimeClipboard, WebRuntimeDialogs, WebRuntimeHost, WebRuntimeStorage } from './host'\nexport { installWebHostGlobals } from './hostGlobals'\nexport {\n createInputEventDetail,\n createScrollEventDetail,\n createSwitchEventDetail,\n createTextareaLineChangeDetail,\n createVideoProgressDetail,\n createVideoTimeUpdateDetail,\n ensureNativeComponentsDefined,\n resolveImageModeStyle,\n resolveVideoObjectFit,\n} from './nativeComponents'\nexport { setNavigationBarMetrics } from './navigationBar'\nexport type { NavigationBarMetrics } from './navigationBar'\nexport { setPageLayout } from './pageLayout'\nexport {\n authorize,\n canIUse,\n checkSession,\n chooseAddress,\n chooseFile,\n chooseImage,\n chooseLocation,\n chooseMedia,\n chooseMessageFile,\n chooseVideo,\n clearStorage,\n clearStorageSync,\n compressImage,\n compressVideo,\n createCanvasContext,\n createInterstitialAd,\n createRewardedVideoAd,\n createSelectorQuery,\n createVideoContext,\n createVKSession,\n createWorker,\n downloadFile,\n exitMiniProgram,\n getAccountInfoSync,\n getAppAuthorizeSetting,\n getAppBaseInfo,\n getBatteryInfo,\n getBatteryInfoSync,\n getClipboardData,\n getDeviceInfo,\n getEnterOptionsSync,\n getExtConfig,\n getExtConfigSync,\n getFileSystemManager,\n getFuzzyLocation,\n getImageInfo,\n getLaunchOptionsSync,\n getLocation,\n getLogManager,\n getMenuButtonBoundingClientRect,\n getNetworkType,\n getSetting,\n getStorage,\n getStorageInfo,\n getStorageInfoSync,\n getStorageSync,\n getSystemInfo,\n getSystemInfoSync,\n getSystemSetting,\n getUpdateManager,\n getUserInfo,\n getUserProfile,\n getVideoInfo,\n getWindowInfo,\n hideKeyboard,\n hideLoading,\n hideNavigationBarLoading,\n hideTabBar,\n hideTabBarRedDot,\n initializePageRoutes,\n loadSubPackage,\n login,\n makePhoneCall,\n navigateBack,\n navigateTo,\n navigateToMiniProgram,\n nextTick,\n offAppHide,\n offAppShow,\n offNetworkStatusChange,\n offWindowResize,\n onAppHide,\n onAppShow,\n onNetworkStatusChange,\n onWindowResize,\n openAppAuthorizeSetting,\n openCustomerServiceChat,\n openDocument,\n openLocation,\n openSetting,\n openVideoEditor,\n pageScrollTo,\n preloadSubpackage,\n previewImage,\n previewMedia,\n redirectTo,\n registerApp,\n registerComponent,\n registerPage,\n reLaunch,\n removeStorage,\n removeStorageSync,\n removeTabBarBadge,\n reportAnalytics,\n request,\n requestPayment,\n requestSubscribeMessage,\n saveFile,\n saveFileToDisk,\n saveImageToPhotosAlbum,\n saveVideoToPhotosAlbum,\n scanCode,\n setBackgroundColor,\n setBackgroundTextStyle,\n setClipboardData,\n setNavigationBarColor,\n setNavigationBarTitle,\n setStorage,\n setStorageSync,\n setTabBarBadge,\n setTabBarItem,\n setTabBarStyle,\n showActionSheet,\n showLoading,\n showModal,\n showNavigationBarLoading,\n showShareMenu,\n showTabBar,\n showTabBarRedDot,\n showToast,\n startPullDownRefresh,\n stopPullDownRefresh,\n switchTab,\n updateShareMenu,\n uploadFile,\n vibrateShort,\n} from './polyfill'\nexport type { AppHideCallback, AppHideOptions, AppLaunchOptions, AppShowCallback } from './polyfill'\nexport {\n disposeWebRouting,\n getWebRoutingConfig,\n resolveWebRoutingConfig,\n} from './polyfill/routeRuntime/history'\nexport type {\n ResolvedWebRoutingConfig,\n WebRouteHistoryState,\n WebRouteTarget,\n WebRoutingConfig,\n WebRoutingMode,\n} from './polyfill/routeRuntime/history'\nexport { createRenderContext } from './renderContext'\nexport type { RenderContext } from './renderContext'\nexport { setupRpx } from './rpx'\nexport type { RpxConfig } from './rpx'\nexport {\n configureWebSeo,\n resetWebDocumentHead,\n setupWebResourceHints,\n syncWebDocumentHead,\n updateWebDocumentTitle,\n} from './seo'\nexport type { WebPageHead, WebResourceHint, WebResourceHintRelation, WebResourceHintsConfig, WebSeoConfig } from './seo'\nexport { injectStyle, removeStyle } from './style'\nexport { createTemplate, renderTemplate } from './template'\nexport type { TemplateRenderer, TemplateScope } from './template'\nexport { getWebViewportWidth, resolveWebViewportConfig, setupWebViewport } from './viewport'\nexport type { ResolvedWebViewportConfig, WebViewportConfig } from './viewport'\nexport { setRuntimeWarningOptions } from './warning'\nexport type { RuntimeWarningLevel, RuntimeWarningOptions } from './warning'\nexport {\n installWebModuleRegistration,\n registerWebWevuApp,\n registerWebWevuComponent,\n registerWebWevuComponentFactory,\n} from './wevu'\nexport * from 'wevu/internal-runtime'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,sBAAsB;AACtB,0BAA0B"}
|
|
@@ -2,8 +2,8 @@ import { getNativeComponentDescriptor } from "../../shared/nativeComponents.mjs"
|
|
|
2
2
|
import { emitRuntimeWarning } from "../warning.mjs";
|
|
3
3
|
import { dispatchMiniProgramEvent, readBooleanAttribute, resolveContainingShadowRoot } from "./helpers.mjs";
|
|
4
4
|
import { ensureNativeComponentStyle } from "./style.mjs";
|
|
5
|
-
import { navigateBack, navigateTo, reLaunch, redirectTo, switchTab } from "../polyfill/routeRuntime.mjs";
|
|
6
5
|
import { exitMiniProgram, navigateToMiniProgram } from "../polyfill/runtimeDataApi.mjs";
|
|
6
|
+
import { navigateBack, navigateTo, reLaunch, redirectTo, switchTab } from "../polyfill/routeRuntime.mjs";
|
|
7
7
|
|
|
8
8
|
//#region src/runtime/nativeComponents/navigator.ts
|
|
9
9
|
const BaseElement = globalThis.HTMLElement ?? class {};
|
|
@@ -1,11 +1,9 @@
|
|
|
1
1
|
import { emitRuntimeWarning } from "../warning.mjs";
|
|
2
|
-
import { callMiniProgramAsyncFailure, callMiniProgramAsyncSuccess } from "./async.mjs";
|
|
3
|
-
import { getAppInstance, getCurrentPagesInternal, getEnterOptionsSync, getLaunchOptionsSync, initializePageRoutes, navigateBack, navigateTo, offAppHide, offAppShow, onAppHide, onAppShow, reLaunch, redirectTo, registerApp, registerComponent, registerPage, switchTab } from "./routeRuntime.mjs";
|
|
4
|
-
import { WEB_USER_DATA_PATH } from "./files.mjs";
|
|
5
|
-
import { clearStorage, clearStorageSync, createCanvasContext, createIntersectionObserver, createSelectorQuery, createVKSession, createVideoContext, createWorker, downloadFile, exitMiniProgram, getFileSystemManager, getStorage, getStorageInfo, getStorageInfoSync, getStorageSync, hideKeyboard, loadSubPackage, navigateToMiniProgram, nextTick, pageScrollTo, preloadSubpackage, removeStorage, removeStorageSync, request, runtimeDataApi_exports, setStorage, setStorageSync, startPullDownRefresh, stopPullDownRefresh, uploadFile } from "./runtimeDataApi.mjs";
|
|
6
2
|
import { createAnimation } from "./animation.mjs";
|
|
3
|
+
import { callMiniProgramAsyncFailure, callMiniProgramAsyncSuccess } from "./async.mjs";
|
|
7
4
|
import { setBackgroundColorBridge, setBackgroundTextStyleBridge } from "./background.mjs";
|
|
8
5
|
import { createCloudBridge } from "./cloud.mjs";
|
|
6
|
+
import { WEB_USER_DATA_PATH } from "./files.mjs";
|
|
9
7
|
import { canIUseBridge } from "./runtimeCapabilityApi.mjs";
|
|
10
8
|
import { authorize, checkSession, deviceAuthSystemApi_exports, getAccountInfoSync, getAppAuthorizeSetting, getAppBaseInfo, getBatteryInfo, getBatteryInfoSync, getDeviceInfo, getFuzzyLocation, getLocation, getMenuButtonBoundingClientRect, getNetworkType, getSetting, getSystemInfo, getSystemInfoSync, getSystemSetting, getUserInfo, getUserProfile, getWindowInfo, login, offNetworkStatusChange, offWindowResize, onNetworkStatusChange, onWindowResize, openAppAuthorizeSetting, openSetting, rpx2px, upx2px, vibrateShort } from "./deviceAuthSystemApi.mjs";
|
|
11
9
|
import { $emit, $off, $on, $once, eventBus_exports } from "./eventBus.mjs";
|
|
@@ -13,6 +11,8 @@ import { loadFontFace } from "./font.mjs";
|
|
|
13
11
|
import { getLocale } from "./locale.mjs";
|
|
14
12
|
import { createNavigationBarRuntimeBridge } from "./navigationBarRuntime.mjs";
|
|
15
13
|
import { createInterstitialAdBridge, createRewardedVideoAdBridge, getExtConfigBridge, getExtConfigSyncBridge, getLogManagerBridge, getUpdateManagerBridge, reportAnalyticsBridge } from "./platformApi.mjs";
|
|
14
|
+
import { clearStorage, clearStorageSync, createCanvasContext, createIntersectionObserver, createSelectorQuery, createVKSession, createVideoContext, createWorker, downloadFile, exitMiniProgram, getFileSystemManager, getStorage, getStorageInfo, getStorageInfoSync, getStorageSync, hideKeyboard, loadSubPackage, navigateToMiniProgram, nextTick, pageScrollTo, preloadSubpackage, removeStorage, removeStorageSync, request, runtimeDataApi_exports, setStorage, setStorageSync, startPullDownRefresh, stopPullDownRefresh, uploadFile } from "./runtimeDataApi.mjs";
|
|
15
|
+
import { getAppInstance, getCurrentPagesInternal, getEnterOptionsSync, getLaunchOptionsSync, initializePageRoutes, navigateBack, navigateTo, offAppHide, offAppShow, onAppHide, onAppShow, reLaunch, redirectTo, registerApp, registerComponent, registerPage, switchTab } from "./routeRuntime.mjs";
|
|
16
16
|
import { chooseAddress, chooseFile, chooseImage, chooseLocation, chooseMedia, chooseMessageFile, chooseVideo, compressImage, compressVideo, getClipboardData, getImageInfo, getVideoInfo, hideLoading, hideTabBar, hideTabBarRedDot, makePhoneCall, openCustomerServiceChat, openDocument, openLocation, openVideoEditor, previewImage, previewMedia, removeTabBarBadge, requestPayment, requestSubscribeMessage, saveFile, saveFileToDisk, saveImageToPhotosAlbum, saveVideoToPhotosAlbum, scanCode, setClipboardData, setTabBarBadge, setTabBarItem, setTabBarStyle, showActionSheet, showLoading, showModal, showShareMenu, showTabBar, showTabBarRedDot, showToast, uiMediaApi_exports, updateShareMenu } from "./uiMediaApi.mjs";
|
|
17
17
|
import { getDefaultMiniProgramRuntimeGlobalKey, getMiniProgramRuntimeGlobalKeys } from "@weapp-core/shared";
|
|
18
18
|
|
|
@@ -70,49 +70,52 @@ function getLogManager(options) {
|
|
|
70
70
|
function reportAnalytics(eventName, data) {
|
|
71
71
|
reportAnalyticsBridge(eventName, data);
|
|
72
72
|
}
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
miniProgramBridge.env
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
73
|
+
/** 由公开运行时入口显式安装,确保拆分发布后的子模块不被摇树优化移除。 */
|
|
74
|
+
function installMiniProgramGlobals() {
|
|
75
|
+
const miniProgramBridge = globalTarget[DEFAULT_MINI_PROGRAM_GLOBAL_KEY] ?? {};
|
|
76
|
+
Object.assign(miniProgramBridge, {
|
|
77
|
+
navigateTo,
|
|
78
|
+
navigateBack,
|
|
79
|
+
redirectTo,
|
|
80
|
+
switchTab,
|
|
81
|
+
reLaunch,
|
|
82
|
+
getLaunchOptionsSync,
|
|
83
|
+
getEnterOptionsSync,
|
|
84
|
+
offAppHide,
|
|
85
|
+
offAppShow,
|
|
86
|
+
onAppHide,
|
|
87
|
+
onAppShow,
|
|
88
|
+
...runtimeDataApi_exports,
|
|
89
|
+
setNavigationBarTitle,
|
|
90
|
+
setNavigationBarColor,
|
|
91
|
+
setBackgroundColor,
|
|
92
|
+
setBackgroundTextStyle,
|
|
93
|
+
showNavigationBarLoading,
|
|
94
|
+
hideNavigationBarLoading,
|
|
95
|
+
...uiMediaApi_exports,
|
|
96
|
+
...deviceAuthSystemApi_exports,
|
|
97
|
+
...eventBus_exports,
|
|
98
|
+
loadFontFace,
|
|
99
|
+
getLocale,
|
|
100
|
+
createAnimation,
|
|
101
|
+
createRewardedVideoAd,
|
|
102
|
+
createInterstitialAd,
|
|
103
|
+
getExtConfigSync,
|
|
104
|
+
getExtConfig,
|
|
105
|
+
getUpdateManager,
|
|
106
|
+
getLogManager,
|
|
107
|
+
reportAnalytics,
|
|
108
|
+
canIUse,
|
|
109
|
+
cloud: cloudBridge
|
|
110
|
+
});
|
|
111
|
+
const miniProgramEnv = miniProgramBridge.env ?? {};
|
|
112
|
+
if (typeof miniProgramEnv.USER_DATA_PATH !== "string" || !miniProgramEnv.USER_DATA_PATH.trim()) miniProgramEnv.USER_DATA_PATH = WEB_USER_DATA_PATH;
|
|
113
|
+
miniProgramBridge.env = miniProgramEnv;
|
|
114
|
+
for (const runtimeGlobalKey of MINI_PROGRAM_GLOBAL_KEYS) globalTarget[runtimeGlobalKey] = miniProgramBridge;
|
|
115
|
+
if (typeof globalTarget.getApp !== "function") globalTarget.getApp = getAppInstance;
|
|
116
|
+
if (typeof globalTarget.getCurrentPages !== "function") globalTarget.getCurrentPages = getCurrentPagesInternal;
|
|
117
|
+
}
|
|
115
118
|
|
|
116
119
|
//#endregion
|
|
117
|
-
export { $emit, $off, $on, $once, authorize, canIUse, checkSession, chooseAddress, chooseFile, chooseImage, chooseLocation, chooseMedia, chooseMessageFile, chooseVideo, clearStorage, clearStorageSync, compressImage, compressVideo, createCanvasContext, createIntersectionObserver, createInterstitialAd, createRewardedVideoAd, createSelectorQuery, createVKSession, createVideoContext, createWorker, downloadFile, exitMiniProgram, getAccountInfoSync, getAppAuthorizeSetting, getAppBaseInfo, getBatteryInfo, getBatteryInfoSync, getClipboardData, getDeviceInfo, getEnterOptionsSync, getExtConfig, getExtConfigSync, getFileSystemManager, getFuzzyLocation, getImageInfo, getLaunchOptionsSync, getLocation, getLogManager, getMenuButtonBoundingClientRect, getNetworkType, getSetting, getStorage, getStorageInfo, getStorageInfoSync, getStorageSync, getSystemInfo, getSystemInfoSync, getSystemSetting, getUpdateManager, getUserInfo, getUserProfile, getVideoInfo, getWindowInfo, hideKeyboard, hideLoading, hideNavigationBarLoading, hideTabBar, hideTabBarRedDot, initializePageRoutes, loadSubPackage, login, makePhoneCall, navigateBack, navigateTo, navigateToMiniProgram, nextTick, offAppHide, offAppShow, offNetworkStatusChange, offWindowResize, onAppHide, onAppShow, onNetworkStatusChange, onWindowResize, openAppAuthorizeSetting, openCustomerServiceChat, openDocument, openLocation, openSetting, openVideoEditor, pageScrollTo, preloadSubpackage, previewImage, previewMedia, reLaunch, redirectTo, registerApp, registerComponent, registerPage, removeStorage, removeStorageSync, removeTabBarBadge, reportAnalytics, request, requestPayment, requestSubscribeMessage, rpx2px, saveFile, saveFileToDisk, saveImageToPhotosAlbum, saveVideoToPhotosAlbum, scanCode, setBackgroundColor, setBackgroundTextStyle, setClipboardData, setNavigationBarColor, setNavigationBarTitle, setStorage, setStorageSync, setTabBarBadge, setTabBarItem, setTabBarStyle, showActionSheet, showLoading, showModal, showNavigationBarLoading, showShareMenu, showTabBar, showTabBarRedDot, showToast, startPullDownRefresh, stopPullDownRefresh, switchTab, updateShareMenu, uploadFile, upx2px, vibrateShort };
|
|
120
|
+
export { $emit, $off, $on, $once, authorize, canIUse, checkSession, chooseAddress, chooseFile, chooseImage, chooseLocation, chooseMedia, chooseMessageFile, chooseVideo, clearStorage, clearStorageSync, compressImage, compressVideo, createCanvasContext, createIntersectionObserver, createInterstitialAd, createRewardedVideoAd, createSelectorQuery, createVKSession, createVideoContext, createWorker, downloadFile, exitMiniProgram, getAccountInfoSync, getAppAuthorizeSetting, getAppBaseInfo, getBatteryInfo, getBatteryInfoSync, getClipboardData, getDeviceInfo, getEnterOptionsSync, getExtConfig, getExtConfigSync, getFileSystemManager, getFuzzyLocation, getImageInfo, getLaunchOptionsSync, getLocation, getLogManager, getMenuButtonBoundingClientRect, getNetworkType, getSetting, getStorage, getStorageInfo, getStorageInfoSync, getStorageSync, getSystemInfo, getSystemInfoSync, getSystemSetting, getUpdateManager, getUserInfo, getUserProfile, getVideoInfo, getWindowInfo, hideKeyboard, hideLoading, hideNavigationBarLoading, hideTabBar, hideTabBarRedDot, initializePageRoutes, installMiniProgramGlobals, loadSubPackage, login, makePhoneCall, navigateBack, navigateTo, navigateToMiniProgram, nextTick, offAppHide, offAppShow, offNetworkStatusChange, offWindowResize, onAppHide, onAppShow, onNetworkStatusChange, onWindowResize, openAppAuthorizeSetting, openCustomerServiceChat, openDocument, openLocation, openSetting, openVideoEditor, pageScrollTo, preloadSubpackage, previewImage, previewMedia, reLaunch, redirectTo, registerApp, registerComponent, registerPage, removeStorage, removeStorageSync, removeTabBarBadge, reportAnalytics, request, requestPayment, requestSubscribeMessage, rpx2px, saveFile, saveFileToDisk, saveImageToPhotosAlbum, saveVideoToPhotosAlbum, scanCode, setBackgroundColor, setBackgroundTextStyle, setClipboardData, setNavigationBarColor, setNavigationBarTitle, setStorage, setStorageSync, setTabBarBadge, setTabBarItem, setTabBarStyle, showActionSheet, showLoading, showModal, showNavigationBarLoading, showShareMenu, showTabBar, showTabBarRedDot, showToast, startPullDownRefresh, stopPullDownRefresh, switchTab, updateShareMenu, uploadFile, upx2px, vibrateShort };
|
|
118
121
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["runtimeDataApi","uiMediaApi","deviceAuthSystemApi","eventBusApi"],"sources":["../../../src/runtime/polyfill/index.ts"],"sourcesContent":["import type {\n AdBaseOptions,\n CloudBridge,\n GetExtConfigOptions,\n InterstitialAd,\n LogManager,\n LogManagerOptions,\n MiniProgramAsyncOptions,\n MiniProgramBaseResult,\n RewardedVideoAd,\n SetBackgroundColorOptions,\n SetBackgroundTextStyleOptions,\n UpdateManager,\n} from './types'\nimport { getDefaultMiniProgramRuntimeGlobalKey, getMiniProgramRuntimeGlobalKeys } from '@weapp-core/shared'\nimport { emitRuntimeWarning } from '../warning'\nimport { createAnimation } from './animation'\nimport {\n callMiniProgramAsyncFailure,\n callMiniProgramAsyncSuccess,\n} from './async'\nimport {\n setBackgroundColorBridge,\n setBackgroundTextStyleBridge,\n} from './background'\nimport { createCloudBridge } from './cloud'\nimport * as deviceAuthSystemApi from './deviceAuthSystemApi'\nimport * as eventBusApi from './eventBus'\nimport { WEB_USER_DATA_PATH } from './files'\nimport { loadFontFace } from './font'\nimport { getLocale } from './locale'\nimport { createNavigationBarRuntimeBridge } from './navigationBarRuntime'\nimport {\n createInterstitialAdBridge,\n createRewardedVideoAdBridge,\n getExtConfigBridge,\n getExtConfigSyncBridge,\n getLogManagerBridge,\n getUpdateManagerBridge,\n reportAnalyticsBridge,\n} from './platformApi'\nimport {\n getAppInstance,\n getCurrentPagesInternal,\n getEnterOptionsSync,\n getLaunchOptionsSync,\n navigateBack,\n navigateTo,\n offAppHide,\n offAppShow,\n onAppHide,\n onAppShow,\n redirectTo,\n reLaunch,\n switchTab,\n} from './routeRuntime'\nimport {\n canIUseBridge,\n} from './runtimeCapabilityApi'\nimport * as runtimeDataApi from './runtimeDataApi'\nimport * as uiMediaApi from './uiMediaApi'\n\nexport { createAnimation } from './animation'\nexport * from './deviceAuthSystemApi'\nexport * from './eventBus'\nexport { loadFontFace } from './font'\nexport { getLocale } from './locale'\n\nexport {\n getEnterOptionsSync,\n getLaunchOptionsSync,\n initializePageRoutes,\n navigateBack,\n navigateTo,\n offAppHide,\n offAppShow,\n onAppHide,\n onAppShow,\n redirectTo,\n registerApp,\n registerComponent,\n registerPage,\n reLaunch,\n switchTab,\n} from './routeRuntime'\n\nexport type { AppHideCallback, AppHideOptions, AppLaunchOptions, AppShowCallback } from './routeRuntime/options'\n\nexport * from './runtimeDataApi'\nexport * from './uiMediaApi'\n\nconst MINI_PROGRAM_GLOBAL_KEYS = getMiniProgramRuntimeGlobalKeys()\nconst DEFAULT_MINI_PROGRAM_GLOBAL_KEY = getDefaultMiniProgramRuntimeGlobalKey()\nconst globalTarget = globalThis as Record<string, unknown>\n\nfunction resolveMiniProgramBridge() {\n for (const runtimeGlobalKey of MINI_PROGRAM_GLOBAL_KEYS) {\n const candidate = globalTarget[runtimeGlobalKey]\n if (candidate && typeof candidate === 'object') {\n return candidate as Record<string, unknown>\n }\n }\n return undefined\n}\n\nconst navigationBarRuntimeBridge = createNavigationBarRuntimeBridge(\n () => getCurrentPagesInternal() as Array<HTMLElement & { renderRoot?: ShadowRoot | HTMLElement }>,\n emitRuntimeWarning,\n)\n\nexport function setNavigationBarTitle(options: { title: string }) {\n return navigationBarRuntimeBridge.setNavigationBarTitle(options)\n}\n\nexport function setNavigationBarColor(options: {\n frontColor?: string\n backgroundColor?: string\n animation?: { duration?: number, timingFunction?: string }\n}) {\n return navigationBarRuntimeBridge.setNavigationBarColor(options)\n}\n\nexport function showNavigationBarLoading() {\n return navigationBarRuntimeBridge.showNavigationBarLoading()\n}\n\nexport function hideNavigationBarLoading() {\n return navigationBarRuntimeBridge.hideNavigationBarLoading()\n}\n\nexport function setBackgroundColor(options?: SetBackgroundColorOptions) {\n return setBackgroundColorBridge(options)\n}\n\nexport function setBackgroundTextStyle(options?: SetBackgroundTextStyleOptions) {\n return setBackgroundTextStyleBridge(options)\n}\n\nexport function canIUse(schema: string) {\n return canIUseBridge(resolveMiniProgramBridge(), schema)\n}\n\nconst cloudBridge: CloudBridge = createCloudBridge(\n (options, result) => callMiniProgramAsyncSuccess(\n options as unknown as MiniProgramAsyncOptions<MiniProgramBaseResult> | undefined,\n result as MiniProgramBaseResult,\n ),\n (options, errMsg) => callMiniProgramAsyncFailure(\n options as unknown as MiniProgramAsyncOptions<MiniProgramBaseResult> | undefined,\n errMsg,\n ),\n) as CloudBridge\n\nexport function createRewardedVideoAd(options?: AdBaseOptions): RewardedVideoAd {\n return createRewardedVideoAdBridge(options)\n}\n\nexport function createInterstitialAd(options?: AdBaseOptions): InterstitialAd {\n return createInterstitialAdBridge(options)\n}\n\nexport function getExtConfigSync() {\n return getExtConfigSyncBridge()\n}\n\nexport function getExtConfig(options?: GetExtConfigOptions) {\n return getExtConfigBridge(options)\n}\n\nexport function getUpdateManager(): UpdateManager {\n return getUpdateManagerBridge()\n}\n\nexport function getLogManager(options?: LogManagerOptions): LogManager {\n return getLogManagerBridge(options)\n}\n\nexport function reportAnalytics(eventName: string, data?: Record<string, unknown>) {\n reportAnalyticsBridge(eventName, data)\n}\n\
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["runtimeDataApi","uiMediaApi","deviceAuthSystemApi","eventBusApi"],"sources":["../../../src/runtime/polyfill/index.ts"],"sourcesContent":["import type {\n AdBaseOptions,\n CloudBridge,\n GetExtConfigOptions,\n InterstitialAd,\n LogManager,\n LogManagerOptions,\n MiniProgramAsyncOptions,\n MiniProgramBaseResult,\n RewardedVideoAd,\n SetBackgroundColorOptions,\n SetBackgroundTextStyleOptions,\n UpdateManager,\n} from './types'\nimport { getDefaultMiniProgramRuntimeGlobalKey, getMiniProgramRuntimeGlobalKeys } from '@weapp-core/shared'\nimport { emitRuntimeWarning } from '../warning'\nimport { createAnimation } from './animation'\nimport {\n callMiniProgramAsyncFailure,\n callMiniProgramAsyncSuccess,\n} from './async'\nimport {\n setBackgroundColorBridge,\n setBackgroundTextStyleBridge,\n} from './background'\nimport { createCloudBridge } from './cloud'\nimport * as deviceAuthSystemApi from './deviceAuthSystemApi'\nimport * as eventBusApi from './eventBus'\nimport { WEB_USER_DATA_PATH } from './files'\nimport { loadFontFace } from './font'\nimport { getLocale } from './locale'\nimport { createNavigationBarRuntimeBridge } from './navigationBarRuntime'\nimport {\n createInterstitialAdBridge,\n createRewardedVideoAdBridge,\n getExtConfigBridge,\n getExtConfigSyncBridge,\n getLogManagerBridge,\n getUpdateManagerBridge,\n reportAnalyticsBridge,\n} from './platformApi'\nimport {\n getAppInstance,\n getCurrentPagesInternal,\n getEnterOptionsSync,\n getLaunchOptionsSync,\n navigateBack,\n navigateTo,\n offAppHide,\n offAppShow,\n onAppHide,\n onAppShow,\n redirectTo,\n reLaunch,\n switchTab,\n} from './routeRuntime'\nimport {\n canIUseBridge,\n} from './runtimeCapabilityApi'\nimport * as runtimeDataApi from './runtimeDataApi'\nimport * as uiMediaApi from './uiMediaApi'\n\nexport { createAnimation } from './animation'\nexport * from './deviceAuthSystemApi'\nexport * from './eventBus'\nexport { loadFontFace } from './font'\nexport { getLocale } from './locale'\n\nexport {\n getEnterOptionsSync,\n getLaunchOptionsSync,\n initializePageRoutes,\n navigateBack,\n navigateTo,\n offAppHide,\n offAppShow,\n onAppHide,\n onAppShow,\n redirectTo,\n registerApp,\n registerComponent,\n registerPage,\n reLaunch,\n switchTab,\n} from './routeRuntime'\n\nexport type { AppHideCallback, AppHideOptions, AppLaunchOptions, AppShowCallback } from './routeRuntime/options'\n\nexport * from './runtimeDataApi'\nexport * from './uiMediaApi'\n\nconst MINI_PROGRAM_GLOBAL_KEYS = getMiniProgramRuntimeGlobalKeys()\nconst DEFAULT_MINI_PROGRAM_GLOBAL_KEY = getDefaultMiniProgramRuntimeGlobalKey()\nconst globalTarget = globalThis as Record<string, unknown>\n\nfunction resolveMiniProgramBridge() {\n for (const runtimeGlobalKey of MINI_PROGRAM_GLOBAL_KEYS) {\n const candidate = globalTarget[runtimeGlobalKey]\n if (candidate && typeof candidate === 'object') {\n return candidate as Record<string, unknown>\n }\n }\n return undefined\n}\n\nconst navigationBarRuntimeBridge = createNavigationBarRuntimeBridge(\n () => getCurrentPagesInternal() as Array<HTMLElement & { renderRoot?: ShadowRoot | HTMLElement }>,\n emitRuntimeWarning,\n)\n\nexport function setNavigationBarTitle(options: { title: string }) {\n return navigationBarRuntimeBridge.setNavigationBarTitle(options)\n}\n\nexport function setNavigationBarColor(options: {\n frontColor?: string\n backgroundColor?: string\n animation?: { duration?: number, timingFunction?: string }\n}) {\n return navigationBarRuntimeBridge.setNavigationBarColor(options)\n}\n\nexport function showNavigationBarLoading() {\n return navigationBarRuntimeBridge.showNavigationBarLoading()\n}\n\nexport function hideNavigationBarLoading() {\n return navigationBarRuntimeBridge.hideNavigationBarLoading()\n}\n\nexport function setBackgroundColor(options?: SetBackgroundColorOptions) {\n return setBackgroundColorBridge(options)\n}\n\nexport function setBackgroundTextStyle(options?: SetBackgroundTextStyleOptions) {\n return setBackgroundTextStyleBridge(options)\n}\n\nexport function canIUse(schema: string) {\n return canIUseBridge(resolveMiniProgramBridge(), schema)\n}\n\nconst cloudBridge: CloudBridge = createCloudBridge(\n (options, result) => callMiniProgramAsyncSuccess(\n options as unknown as MiniProgramAsyncOptions<MiniProgramBaseResult> | undefined,\n result as MiniProgramBaseResult,\n ),\n (options, errMsg) => callMiniProgramAsyncFailure(\n options as unknown as MiniProgramAsyncOptions<MiniProgramBaseResult> | undefined,\n errMsg,\n ),\n) as CloudBridge\n\nexport function createRewardedVideoAd(options?: AdBaseOptions): RewardedVideoAd {\n return createRewardedVideoAdBridge(options)\n}\n\nexport function createInterstitialAd(options?: AdBaseOptions): InterstitialAd {\n return createInterstitialAdBridge(options)\n}\n\nexport function getExtConfigSync() {\n return getExtConfigSyncBridge()\n}\n\nexport function getExtConfig(options?: GetExtConfigOptions) {\n return getExtConfigBridge(options)\n}\n\nexport function getUpdateManager(): UpdateManager {\n return getUpdateManagerBridge()\n}\n\nexport function getLogManager(options?: LogManagerOptions): LogManager {\n return getLogManagerBridge(options)\n}\n\nexport function reportAnalytics(eventName: string, data?: Record<string, unknown>) {\n reportAnalyticsBridge(eventName, data)\n}\n\n/** 由公开运行时入口显式安装,确保拆分发布后的子模块不被摇树优化移除。 */\nexport function installMiniProgramGlobals(): void {\n const miniProgramBridge = (globalTarget[DEFAULT_MINI_PROGRAM_GLOBAL_KEY] as Record<string, unknown> | undefined) ?? {}\n Object.assign(miniProgramBridge, {\n navigateTo,\n navigateBack,\n redirectTo,\n switchTab,\n reLaunch,\n getLaunchOptionsSync,\n getEnterOptionsSync,\n offAppHide,\n offAppShow,\n onAppHide,\n onAppShow,\n ...runtimeDataApi,\n setNavigationBarTitle,\n setNavigationBarColor,\n setBackgroundColor,\n setBackgroundTextStyle,\n showNavigationBarLoading,\n hideNavigationBarLoading,\n ...uiMediaApi,\n ...deviceAuthSystemApi,\n ...eventBusApi,\n loadFontFace,\n getLocale,\n createAnimation,\n createRewardedVideoAd,\n createInterstitialAd,\n getExtConfigSync,\n getExtConfig,\n getUpdateManager,\n getLogManager,\n reportAnalytics,\n canIUse,\n cloud: cloudBridge,\n })\n const miniProgramEnv = (miniProgramBridge.env as Record<string, unknown> | undefined) ?? {}\n if (typeof miniProgramEnv.USER_DATA_PATH !== 'string' || !miniProgramEnv.USER_DATA_PATH.trim()) {\n miniProgramEnv.USER_DATA_PATH = WEB_USER_DATA_PATH\n }\n miniProgramBridge.env = miniProgramEnv\n for (const runtimeGlobalKey of MINI_PROGRAM_GLOBAL_KEYS) {\n globalTarget[runtimeGlobalKey] = miniProgramBridge\n }\n if (typeof globalTarget.getApp !== 'function') {\n globalTarget.getApp = getAppInstance\n }\n if (typeof globalTarget.getCurrentPages !== 'function') {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AAgB,gBAAgB,WAAmB,MAAgC;CACjF,sBAAsB,WAAW,IAAI;AACvC;;AAGA,SAAgB,4BAAkC;CAChD,MAAM,oBAAqB,aAAa,oCAA4E,CAAC;CACrH,OAAO,OAAO,mBAAmB;EAC/B;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,GAAGA;EACH;EACA;EACA;EACA;EACA;EACA;EACA,GAAGC;EACH,GAAGC;EACH,GAAGC;EACH;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,OAAO;CACT,CAAC;CACD,MAAM,iBAAkB,kBAAkB,OAA+C,CAAC;CAC1F,IAAI,OAAO,eAAe,mBAAmB,YAAY,CAAC,eAAe,eAAe,KAAK,GAC3F,eAAe,iBAAiB;CAElC,kBAAkB,MAAM;CACxB,KAAK,MAAM,oBAAoB,0BAC7B,aAAa,oBAAoB;CAEnC,IAAI,OAAO,aAAa,WAAW,YACjC,aAAa,SAAS;CAExB,IAAI,OAAO,aAAa,oBAAoB,YAC1C,aAAa,kBAAkB;AAEnC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { openRuntimeUrl } from "../host/index.mjs";
|
|
2
1
|
import { callMiniProgramAsyncFailure, callMiniProgramAsyncSuccess } from "./async.mjs";
|
|
2
|
+
import { openRuntimeUrl } from "../host/index.mjs";
|
|
3
3
|
import { getGlobalDialogHandlers } from "./ui.mjs";
|
|
4
4
|
import { readClipboardData, resolveScanCodeResult, writeClipboardData } from "./interaction.mjs";
|
|
5
5
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { openRuntimeUrl } from "../host/index.mjs";
|
|
2
1
|
import { callMiniProgramAsyncFailure, callMiniProgramAsyncSuccess } from "./async.mjs";
|
|
2
|
+
import { openRuntimeUrl } from "../host/index.mjs";
|
|
3
3
|
import { normalizeFuzzyCoordinate, normalizeGeoNumber, parseChooseAddressPromptInput, parseChooseLocationPromptInput, readCurrentLocation, readPresetChooseAddress, readPresetChooseLocation, readPresetFuzzyLocation } from "./location.mjs";
|
|
4
4
|
import { openTargetInNewWindow } from "./mediaActions.mjs";
|
|
5
5
|
import { getGlobalDialogHandlers } from "./ui.mjs";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { callMiniProgramAsyncFailure, callMiniProgramAsyncSuccess } from "../async.mjs";
|
|
2
|
-
import { normalizeFilePath, resolveOpenDocumentUrl, resolveSaveFilePath, saveMemoryFile } from "../files.mjs";
|
|
3
2
|
import { openTargetInNewWindow, triggerDownload } from "../mediaActions.mjs";
|
|
3
|
+
import { normalizeFilePath, resolveOpenDocumentUrl, resolveSaveFilePath, saveMemoryFile } from "../files.mjs";
|
|
4
4
|
|
|
5
5
|
//#region src/runtime/polyfill/mediaApi/file.ts
|
|
6
6
|
function saveImageToPhotosAlbumBridge(options) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { setTabBarBadgeState, setTabBarRedDotState, setTabBarVisible, updateTabBarItem, updateTabBarStyle } from "../appShell/tabBar/index.mjs";
|
|
2
1
|
import { callMiniProgramAsyncFailure, callMiniProgramAsyncSuccess } from "./async.mjs";
|
|
3
|
-
import { readNetworkStatusSnapshot } from "./network/status.mjs";
|
|
4
2
|
import { normalizeActionSheetItems, resolveActionSheetSelection, resolveModalSelection } from "./ui.mjs";
|
|
3
|
+
import { setTabBarBadgeState, setTabBarRedDotState, setTabBarVisible, updateTabBarItem, updateTabBarStyle } from "../appShell/tabBar/index.mjs";
|
|
4
|
+
import { readNetworkStatusSnapshot } from "./network/status.mjs";
|
|
5
5
|
import { normalizeSubscribeTemplateIds, resolveSubscribeDecisionMap } from "./subscribe.mjs";
|
|
6
6
|
|
|
7
7
|
//#region src/runtime/polyfill/menuApi.ts
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { callMiniProgramAsyncSuccess, scheduleMicrotask } from "./async.mjs";
|
|
2
|
-
import { createLogManagerBridge, createUpdateManagerBridge, readExtConfigValue, readRuntimeConsole, reportAnalyticsEvent, resolveUpdateManagerPreset } from "./platformRuntime.mjs";
|
|
3
2
|
import { createInterstitialAdImpl, createRewardedVideoAdImpl } from "./ad.mjs";
|
|
3
|
+
import { createLogManagerBridge, createUpdateManagerBridge, readExtConfigValue, readRuntimeConsole, reportAnalyticsEvent, resolveUpdateManagerPreset } from "./platformRuntime.mjs";
|
|
4
4
|
|
|
5
5
|
//#region src/runtime/polyfill/platformApi.ts
|
|
6
6
|
function createRewardedVideoAdBridge(options) {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ensureAppContainer, onDocumentReady } from "../../appShell/container.mjs";
|
|
2
|
-
import { attachRouteMeta } from "./lifecycle.mjs";
|
|
3
2
|
import { bindPageScrollOwner, getPageContainer, restoreEntryScrollPosition, setEntryScrollOwner } from "./scroll.mjs";
|
|
3
|
+
import { attachRouteMeta } from "./lifecycle.mjs";
|
|
4
4
|
|
|
5
5
|
//#region src/runtime/polyfill/routeRuntime/dom.ts
|
|
6
6
|
function applyEntryVisibility(entry) {
|
|
@@ -38,6 +38,7 @@ function attachRouteMeta(element, meta) {
|
|
|
38
38
|
const carrier = element;
|
|
39
39
|
carrier[ROUTE_META_SYMBOL] = meta;
|
|
40
40
|
carrier.route = meta.id;
|
|
41
|
+
carrier.options = meta.query;
|
|
41
42
|
}
|
|
42
43
|
function hidePageInstance(instance, record) {
|
|
43
44
|
const state = getPageState(instance);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lifecycle.mjs","names":[],"sources":["../../../../src/runtime/polyfill/routeRuntime/lifecycle.ts"],"sourcesContent":["import type { ComponentOptions, ComponentPublicInstance } from '../../component'\nimport type { PageRecord, RouteMeta } from './options'\nimport { WEVU_PAGE_LAYOUT_NAME_KEY, WEVU_PAGE_LAYOUT_PROPS_KEY, WEVU_PAGE_LAYOUT_SETTER_KEY } from '@weapp-core/constants'\n\nconst ROUTE_META_SYMBOL = Symbol('@weapp-vite/web:route-meta')\nconst PAGE_STATE_SYMBOL = Symbol('@weapp-vite/web:page-state')\n\ninterface RouteMetaCarrier {\n [ROUTE_META_SYMBOL]?: RouteMeta\n route?: string\n}\n\ninterface PageInstanceState {\n loaded: boolean\n visible: boolean\n}\n\ninterface PageStateCarrier {\n [PAGE_STATE_SYMBOL]?: PageInstanceState\n}\n\ntype ComponentPageLifetimeType = 'show' | 'hide' | 'resize'\n\ninterface PageLifetimeAwareComponent extends HTMLElement {\n __weappInvokePageLifetime?: (type: ComponentPageLifetimeType) => void\n renderRoot?: ShadowRoot | HTMLElement\n}\n\nfunction getRouteMeta(instance: ComponentPublicInstance): RouteMeta | undefined {\n return (instance as RouteMetaCarrier)[ROUTE_META_SYMBOL]\n}\n\nfunction getPageState(instance: ComponentPublicInstance): PageInstanceState {\n const target = instance as PageStateCarrier\n target[PAGE_STATE_SYMBOL] ??= { loaded: false, visible: false }\n return target[PAGE_STATE_SYMBOL]!\n}\n\nfunction walkElementsDeep(root: ParentNode, collector: Set<HTMLElement>) {\n const nodes = Array.from((root as ParentNode & { childNodes?: ArrayLike<unknown> }).childNodes ?? [])\n for (const node of nodes) {\n if (!(node instanceof HTMLElement)) {\n continue\n }\n collector.add(node)\n walkElementsDeep(node, collector)\n if (node.shadowRoot) {\n walkElementsDeep(node.shadowRoot, collector)\n }\n }\n}\n\nexport function dispatchPageLifetimeToComponents(\n page: ComponentPublicInstance,\n type: ComponentPageLifetimeType,\n) {\n const host = page as ComponentPublicInstance & {\n renderRoot?: ShadowRoot | HTMLElement\n shadowRoot?: ShadowRoot | null\n }\n const root = host.renderRoot ?? host.shadowRoot ?? host\n if (!root || typeof root.querySelectorAll !== 'function') {\n return\n }\n const elements = new Set<HTMLElement>()\n walkElementsDeep(root, elements)\n for (const element of elements) {\n const component = element as PageLifetimeAwareComponent\n if (typeof component.__weappInvokePageLifetime === 'function') {\n component.__weappInvokePageLifetime(type)\n }\n }\n}\n\nexport function attachRouteMeta(\n element: HTMLElement & ComponentPublicInstance,\n meta: RouteMeta,\n) {\n const carrier = element as RouteMetaCarrier\n carrier[ROUTE_META_SYMBOL] = meta\n carrier.route = meta.id\n}\n\nexport function hidePageInstance(instance: ComponentPublicInstance, record: PageRecord) {\n const state = getPageState(instance)\n if (!state.visible) {\n return\n }\n dispatchPageLifetimeToComponents(instance, 'hide')\n record.hooks.onHide?.call(instance)\n state.visible = false\n}\n\nexport function showPageInstance(instance: ComponentPublicInstance, record: PageRecord) {\n const state = getPageState(instance)\n if (state.visible || !state.loaded) {\n return\n }\n record.hooks.onShow?.call(instance)\n dispatchPageLifetimeToComponents(instance, 'show')\n state.visible = true\n}\n\nexport function augmentPageComponentOptions(component: ComponentOptions, record: PageRecord) {\n const lifetimes = component.lifetimes ?? {}\n const originalCreated = lifetimes?.created\n const originalAttached = lifetimes?.attached\n const originalReady = lifetimes?.ready\n const originalDetached = lifetimes?.detached\n\n const enhanced: ComponentOptions = {\n ...component,\n lifetimes: {\n ...lifetimes,\n created(this: ComponentPublicInstance) {\n originalCreated?.call(this)\n const target = this as ComponentPublicInstance & Record<string, any>\n target[WEVU_PAGE_LAYOUT_SETTER_KEY] = (layout: string | false, props?: Record<string, any>) => {\n target.setData?.({\n [WEVU_PAGE_LAYOUT_NAME_KEY]: layout === false ? '__wv_no_layout' : layout,\n [WEVU_PAGE_LAYOUT_PROPS_KEY]: layout === false ? {} : (props ?? {}),\n })\n }\n getPageState(this)\n record.instances.add(this)\n },\n attached(this: ComponentPublicInstance) {\n originalAttached?.call(this)\n const meta = getRouteMeta(this)\n if (meta?.entry) {\n meta.entry.instance = this\n }\n const state = getPageState(this)\n if (!state.loaded) {\n record.hooks.onLoad?.call(this, meta?.query ?? {})\n state.loaded = true\n }\n if (meta?.entry.active !== false) {\n record.hooks.onShow?.call(this)\n state.visible = true\n }\n },\n ready(this: ComponentPublicInstance) {\n originalReady?.call(this)\n record.hooks.onReady?.call(this)\n if (getPageState(this).visible) {\n dispatchPageLifetimeToComponents(this, 'show')\n }\n },\n detached(this: ComponentPublicInstance) {\n originalDetached?.call(this)\n const meta = getRouteMeta(this)\n if (meta?.entry) {\n meta.entry.instance = undefined\n }\n const state = getPageState(this)\n hidePageInstance(this, record)\n if (state.loaded) {\n record.hooks.onUnload?.call(this)\n }\n state.loaded = false\n state.visible = false\n record.instances.delete(this)\n },\n },\n }\n\n return enhanced\n}\n"],"mappings":";;;AAIA,MAAM,oBAAoB,OAAO,4BAA4B;AAC7D,MAAM,oBAAoB,OAAO,4BAA4B;
|
|
1
|
+
{"version":3,"file":"lifecycle.mjs","names":[],"sources":["../../../../src/runtime/polyfill/routeRuntime/lifecycle.ts"],"sourcesContent":["import type { ComponentOptions, ComponentPublicInstance } from '../../component'\nimport type { PageRecord, RouteMeta } from './options'\nimport { WEVU_PAGE_LAYOUT_NAME_KEY, WEVU_PAGE_LAYOUT_PROPS_KEY, WEVU_PAGE_LAYOUT_SETTER_KEY } from '@weapp-core/constants'\n\nconst ROUTE_META_SYMBOL = Symbol('@weapp-vite/web:route-meta')\nconst PAGE_STATE_SYMBOL = Symbol('@weapp-vite/web:page-state')\n\ninterface RouteMetaCarrier {\n [ROUTE_META_SYMBOL]?: RouteMeta\n route?: string\n options?: Record<string, string>\n}\n\ninterface PageInstanceState {\n loaded: boolean\n visible: boolean\n}\n\ninterface PageStateCarrier {\n [PAGE_STATE_SYMBOL]?: PageInstanceState\n}\n\ntype ComponentPageLifetimeType = 'show' | 'hide' | 'resize'\n\ninterface PageLifetimeAwareComponent extends HTMLElement {\n __weappInvokePageLifetime?: (type: ComponentPageLifetimeType) => void\n renderRoot?: ShadowRoot | HTMLElement\n}\n\nfunction getRouteMeta(instance: ComponentPublicInstance): RouteMeta | undefined {\n return (instance as RouteMetaCarrier)[ROUTE_META_SYMBOL]\n}\n\nfunction getPageState(instance: ComponentPublicInstance): PageInstanceState {\n const target = instance as PageStateCarrier\n target[PAGE_STATE_SYMBOL] ??= { loaded: false, visible: false }\n return target[PAGE_STATE_SYMBOL]!\n}\n\nfunction walkElementsDeep(root: ParentNode, collector: Set<HTMLElement>) {\n const nodes = Array.from((root as ParentNode & { childNodes?: ArrayLike<unknown> }).childNodes ?? [])\n for (const node of nodes) {\n if (!(node instanceof HTMLElement)) {\n continue\n }\n collector.add(node)\n walkElementsDeep(node, collector)\n if (node.shadowRoot) {\n walkElementsDeep(node.shadowRoot, collector)\n }\n }\n}\n\nexport function dispatchPageLifetimeToComponents(\n page: ComponentPublicInstance,\n type: ComponentPageLifetimeType,\n) {\n const host = page as ComponentPublicInstance & {\n renderRoot?: ShadowRoot | HTMLElement\n shadowRoot?: ShadowRoot | null\n }\n const root = host.renderRoot ?? host.shadowRoot ?? host\n if (!root || typeof root.querySelectorAll !== 'function') {\n return\n }\n const elements = new Set<HTMLElement>()\n walkElementsDeep(root, elements)\n for (const element of elements) {\n const component = element as PageLifetimeAwareComponent\n if (typeof component.__weappInvokePageLifetime === 'function') {\n component.__weappInvokePageLifetime(type)\n }\n }\n}\n\nexport function attachRouteMeta(\n element: HTMLElement & ComponentPublicInstance,\n meta: RouteMeta,\n) {\n const carrier = element as RouteMetaCarrier\n carrier[ROUTE_META_SYMBOL] = meta\n carrier.route = meta.id\n carrier.options = meta.query\n}\n\nexport function hidePageInstance(instance: ComponentPublicInstance, record: PageRecord) {\n const state = getPageState(instance)\n if (!state.visible) {\n return\n }\n dispatchPageLifetimeToComponents(instance, 'hide')\n record.hooks.onHide?.call(instance)\n state.visible = false\n}\n\nexport function showPageInstance(instance: ComponentPublicInstance, record: PageRecord) {\n const state = getPageState(instance)\n if (state.visible || !state.loaded) {\n return\n }\n record.hooks.onShow?.call(instance)\n dispatchPageLifetimeToComponents(instance, 'show')\n state.visible = true\n}\n\nexport function augmentPageComponentOptions(component: ComponentOptions, record: PageRecord) {\n const lifetimes = component.lifetimes ?? {}\n const originalCreated = lifetimes?.created\n const originalAttached = lifetimes?.attached\n const originalReady = lifetimes?.ready\n const originalDetached = lifetimes?.detached\n\n const enhanced: ComponentOptions = {\n ...component,\n lifetimes: {\n ...lifetimes,\n created(this: ComponentPublicInstance) {\n originalCreated?.call(this)\n const target = this as ComponentPublicInstance & Record<string, any>\n target[WEVU_PAGE_LAYOUT_SETTER_KEY] = (layout: string | false, props?: Record<string, any>) => {\n target.setData?.({\n [WEVU_PAGE_LAYOUT_NAME_KEY]: layout === false ? '__wv_no_layout' : layout,\n [WEVU_PAGE_LAYOUT_PROPS_KEY]: layout === false ? {} : (props ?? {}),\n })\n }\n getPageState(this)\n record.instances.add(this)\n },\n attached(this: ComponentPublicInstance) {\n originalAttached?.call(this)\n const meta = getRouteMeta(this)\n if (meta?.entry) {\n meta.entry.instance = this\n }\n const state = getPageState(this)\n if (!state.loaded) {\n record.hooks.onLoad?.call(this, meta?.query ?? {})\n state.loaded = true\n }\n if (meta?.entry.active !== false) {\n record.hooks.onShow?.call(this)\n state.visible = true\n }\n },\n ready(this: ComponentPublicInstance) {\n originalReady?.call(this)\n record.hooks.onReady?.call(this)\n if (getPageState(this).visible) {\n dispatchPageLifetimeToComponents(this, 'show')\n }\n },\n detached(this: ComponentPublicInstance) {\n originalDetached?.call(this)\n const meta = getRouteMeta(this)\n if (meta?.entry) {\n meta.entry.instance = undefined\n }\n const state = getPageState(this)\n hidePageInstance(this, record)\n if (state.loaded) {\n record.hooks.onUnload?.call(this)\n }\n state.loaded = false\n state.visible = false\n record.instances.delete(this)\n },\n },\n }\n\n return enhanced\n}\n"],"mappings":";;;AAIA,MAAM,oBAAoB,OAAO,4BAA4B;AAC7D,MAAM,oBAAoB,OAAO,4BAA4B;AAwB7D,SAAS,aAAa,UAA0D;CAC9E,OAAQ,SAA8B;AACxC;AAEA,SAAS,aAAa,UAAsD;CAC1E,MAAM,SAAS;CACf,OAAO,uBAAuB;EAAE,QAAQ;EAAO,SAAS;CAAM;CAC9D,OAAO,OAAO;AAChB;AAEA,SAAS,iBAAiB,MAAkB,WAA6B;CACvE,MAAM,QAAQ,MAAM,KAAM,KAA0D,cAAc,CAAC,CAAC;CACpG,KAAK,MAAM,QAAQ,OAAO;EAC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B,KAAK,IAAI;IAC1B,MAAM,SAAS;IACf,OAAO,gCAAgC,QAAwB,UAAgC;KAC7F,OAAO,UAAU;OACd,4BAA4B,WAAW,QAAQ,mBAAmB;OAClE,6BAA6B,WAAW,QAAQ,CAAC,IAAK,SAAS,CAAC;KACnE,CAAC;IACH;IACA,aAAa,IAAI;IACjB,OAAO,UAAU,IAAI,IAAI;GAC3B;GACA,WAAwC;IACtC,kBAAkB,KAAK,IAAI;IAC3B,MAAM,OAAO,aAAa,IAAI;IAC9B,IAAI,MAAM,OACR,KAAK,MAAM,WAAW;IAExB,MAAM,QAAQ,aAAa,IAAI;IAC/B,IAAI,CAAC,MAAM,QAAQ;KACjB,OAAO,MAAM,QAAQ,KAAK,MAAM,MAAM,SAAS,CAAC,CAAC;KACjD,MAAM,SAAS;IACjB;IACA,IAAI,MAAM,MAAM,WAAW,OAAO;KAChC,OAAO,MAAM,QAAQ,KAAK,IAAI;KAC9B,MAAM,UAAU;IAClB;GACF;GACA,QAAqC;IACnC,eAAe,KAAK,IAAI;IACxB,OAAO,MAAM,SAAS,KAAK,IAAI;IAC/B,IAAI,aAAa,IAAI,CAAC,CAAC,SACrB,iCAAiC,MAAM,MAAM;GAEjD;GACA,WAAwC;IACtC,kBAAkB,KAAK,IAAI;IAC3B,MAAM,OAAO,aAAa,IAAI;IAC9B,IAAI,MAAM,OACR,KAAK,MAAM,WAAW;IAExB,MAAM,QAAQ,aAAa,IAAI;IAC/B,iBAAiB,MAAM,MAAM;IAC7B,IAAI,MAAM,QACR,OAAO,MAAM,UAAU,KAAK,IAAI;IAElC,MAAM,SAAS;IACf,MAAM,UAAU;IAChB,OAAO,UAAU,OAAO,IAAI;GAC9B;EACF;CAGY;AAChB"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { hidePageInstance, showPageInstance } from "./lifecycle.mjs";
|
|
2
1
|
import { captureEntryScrollPosition, restoreEntryScrollPosition } from "./scroll.mjs";
|
|
2
|
+
import { hidePageInstance, showPageInstance } from "./lifecycle.mjs";
|
|
3
3
|
import { mountEntryToDom, setEntryActiveInDom, unmountEntryFromDom } from "./dom.mjs";
|
|
4
4
|
|
|
5
5
|
//#region src/runtime/polyfill/routeRuntime/stack.ts
|
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import { slugify } from "../../shared/slugify.mjs";
|
|
2
2
|
import { setRuntimeWarningOptions } from "../warning.mjs";
|
|
3
|
+
import { configureTabBar, getTabBarPagePaths, syncTabBarRoute } from "../appShell/tabBar/index.mjs";
|
|
4
|
+
import { configureWebSeo, setupWebResourceHints, syncWebDocumentHead } from "../seo/index.mjs";
|
|
3
5
|
import { setButtonFormConfig } from "../button/index.mjs";
|
|
4
6
|
import { setRuntimeExecutionMode } from "../execution.mjs";
|
|
5
7
|
import { defineComponent } from "../component/index.mjs";
|
|
6
|
-
import {
|
|
8
|
+
import { ensureNativeComponentsDefined } from "../nativeComponents/index.mjs";
|
|
7
9
|
import { ensureNavigationBarDefined, setNavigationBarMetrics } from "../navigationBar/index.mjs";
|
|
8
10
|
import { setupWebViewport } from "../viewport/index.mjs";
|
|
9
11
|
import { setupRpx } from "../rpx.mjs";
|
|
10
|
-
import { configureWebSeo, setupWebResourceHints, syncWebDocumentHead } from "../seo/index.mjs";
|
|
11
12
|
import { resolveCurrentPages } from "./appState.mjs";
|
|
12
13
|
import { normalizeComponentOptions, normalizePageOptions } from "./routeRuntime/options.mjs";
|
|
13
14
|
import { AppLifecycleRuntime } from "./routeRuntime/appLifecycle.mjs";
|
|
@@ -16,7 +17,6 @@ import { augmentPageComponentOptions, dispatchPageLifetimeToComponents } from ".
|
|
|
16
17
|
import { resolveRouteAction } from "./routeRuntime/result.mjs";
|
|
17
18
|
import { PageStackRuntime } from "./routeRuntime/stack.mjs";
|
|
18
19
|
import { parsePageUrl } from "./routeRuntime/url.mjs";
|
|
19
|
-
import { ensureNativeComponentsDefined } from "../nativeComponents/index.mjs";
|
|
20
20
|
|
|
21
21
|
//#region src/runtime/polyfill/routeRuntime.ts
|
|
22
22
|
const pageRegistry = /* @__PURE__ */ new Map();
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { __exportAll } from "../../_virtual/_rolldown/runtime.mjs";
|
|
2
|
+
import { callMiniProgramAsyncFailure, callMiniProgramAsyncSuccess } from "./async.mjs";
|
|
3
|
+
import { downloadFileByFetchBridge, requestByFetchBridge, uploadFileByFetchBridge } from "./network/requestBridge.mjs";
|
|
2
4
|
import { createSelectorQueryBridge } from "./selectorQuery.mjs";
|
|
3
5
|
import { createIntersectionObserverBridge } from "./intersectionObserver.mjs";
|
|
4
|
-
import { callMiniProgramAsyncFailure, callMiniProgramAsyncSuccess } from "./async.mjs";
|
|
5
6
|
import { createCanvasContextBridge } from "./canvasContext.mjs";
|
|
6
|
-
import { downloadFileByFetchBridge, requestByFetchBridge, uploadFileByFetchBridge } from "./network/requestBridge.mjs";
|
|
7
7
|
import { clearStorageSyncBridge, createFileSystemManagerBridgeApi, createVKSessionBridgeApi, createWorkerBridgeApi, getStorageInfoSyncBridge, getStorageSyncBridge, removeStorageSyncBridge, setStorageSyncBridge } from "./runtimeInfra.mjs";
|
|
8
8
|
import { hideKeyboardBridge, loadSubPackageBridge, nextTickBridge, pageScrollToBridge, preloadSubpackageBridge, startPullDownRefreshBridge, stopPullDownRefreshBridge } from "./runtimeOps.mjs";
|
|
9
9
|
import { clearStorageBridge, getStorageBridge, getStorageInfoBridge, removeStorageBridge, setStorageBridge } from "./storageAsync.mjs";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { callMiniProgramAsyncFailure, callMiniProgramAsyncSuccess, normalizeDuration, scheduleMicrotask } from "./async.mjs";
|
|
2
|
-
import { getPageContainer, recordActiveEntryScrollPosition } from "./routeRuntime/scroll.mjs";
|
|
3
2
|
import { resolveSubPackageName } from "./platformRuntime.mjs";
|
|
3
|
+
import { getPageContainer, recordActiveEntryScrollPosition } from "./routeRuntime/scroll.mjs";
|
|
4
4
|
|
|
5
5
|
//#region src/runtime/polyfill/runtimeOps.ts
|
|
6
6
|
function resolveScrollTop(value) {
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@weapp-vite/web",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "1.5.
|
|
4
|
+
"version": "1.5.5",
|
|
5
5
|
"description": "Experimental web runtime for weapp-vite templates",
|
|
6
6
|
"author": "ice breaker <1324318532@qq.com>",
|
|
7
7
|
"license": "MIT",
|
|
@@ -62,11 +62,11 @@
|
|
|
62
62
|
}
|
|
63
63
|
},
|
|
64
64
|
"dependencies": {
|
|
65
|
-
"@babel/parser": "^8.0.
|
|
66
|
-
"@babel/traverse": "^8.0.
|
|
67
|
-
"@babel/types": "^8.0.
|
|
68
|
-
"@weapp-core/constants": "0.2.
|
|
69
|
-
"@weapp-core/shared": "3.2.
|
|
65
|
+
"@babel/parser": "^8.0.6",
|
|
66
|
+
"@babel/traverse": "^8.0.6",
|
|
67
|
+
"@babel/types": "^8.0.6",
|
|
68
|
+
"@weapp-core/constants": "0.2.6",
|
|
69
|
+
"@weapp-core/shared": "3.2.5",
|
|
70
70
|
"domhandler": "^6.0.1",
|
|
71
71
|
"esbuild": "^0.28.2",
|
|
72
72
|
"htmlparser2": "^12.0.0",
|
|
@@ -76,8 +76,8 @@
|
|
|
76
76
|
"postcss": "^8.5.28",
|
|
77
77
|
"postcss-selector-parser": "^7.1.6",
|
|
78
78
|
"rolldown": "1.2.9",
|
|
79
|
-
"rolldown-require": "2.0.
|
|
80
|
-
"wevu": "7.
|
|
79
|
+
"rolldown-require": "2.0.32",
|
|
80
|
+
"wevu": "7.2.0"
|
|
81
81
|
},
|
|
82
82
|
"devDependencies": {
|
|
83
83
|
"happy-dom": "^20.14.5"
|