@weapp-vite/web 1.4.10 → 1.4.12

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.
@@ -1,4 +1,4 @@
1
- import { ResolveWebModuleId, WeappWebPluginOptions } from "./types.mjs";
1
+ import { ResolveWebModuleId, WeappWebPluginOptions, WebStylePreprocessOptions } from "./types.mjs";
2
2
  import { createWebAssetMiddleware } from "./assets.mjs";
3
3
  import { SourceMap } from "magic-string";
4
4
  //#region src/plugin/index.d.ts
@@ -29,6 +29,7 @@ interface WebPostcssConfig {
29
29
  interface WebUserConfig {
30
30
  css?: {
31
31
  postcss?: string | WebPostcssConfig;
32
+ preprocessorOptions?: WebStylePreprocessOptions;
32
33
  };
33
34
  }
34
35
  interface WebResolvedConfig extends WebUserConfig {
@@ -48,10 +48,25 @@ function createWebCssConfig(config, wxssOptions, warn) {
48
48
  }
49
49
  const plugins = postcssConfig?.plugins ?? [];
50
50
  if (plugins.some((plugin) => plugin.postcssPlugin === "weapp-vite-web-wxss")) return;
51
- return { postcss: {
52
- ...postcssConfig,
53
- plugins: [...plugins, createWxssPostcssPlugin(wxssOptions)]
54
- } };
51
+ return {
52
+ postcss: {
53
+ ...postcssConfig,
54
+ plugins: [...plugins, createWxssPostcssPlugin(wxssOptions)]
55
+ },
56
+ preprocessorOptions: config.css?.preprocessorOptions
57
+ };
58
+ }
59
+ function resolveStylePreprocessOptions(options, root) {
60
+ if (!options) return;
61
+ const nodeModules = resolve(root, "node_modules");
62
+ return Object.fromEntries(Object.entries(options).map(([language, languageOptions]) => {
63
+ if (!["sass", "scss"].includes(language)) return [language, languageOptions];
64
+ const loadPaths = Array.isArray(languageOptions.loadPaths) ? languageOptions.loadPaths.filter((value) => typeof value === "string") : [];
65
+ return [language, {
66
+ ...languageOptions,
67
+ loadPaths: Array.from(/* @__PURE__ */ new Set([...loadPaths, nodeModules]))
68
+ }];
69
+ }));
55
70
  }
56
71
  function weappWebPlugin(options = {}) {
57
72
  let root = process.cwd();
@@ -59,6 +74,7 @@ function weappWebPlugin(options = {}) {
59
74
  let enableHmr = false;
60
75
  let resolveWebModuleId;
61
76
  let resolveWebAutoImportTag;
77
+ let stylePreprocessOptions;
62
78
  const componentImportIdMap = /* @__PURE__ */ new Map();
63
79
  const state = createEmptyScanState();
64
80
  const wxssOptions = options.wxss;
@@ -104,7 +120,8 @@ function weappWebPlugin(options = {}) {
104
120
  resolveId: resolveWebModuleId,
105
121
  resolveAutoImportTag: resolveWebAutoImportTag,
106
122
  resolveAppConfig: options.__resolveAppConfig,
107
- uniApp: options.__uniApp
123
+ uniApp: options.__uniApp,
124
+ stylePreprocessOptions
108
125
  });
109
126
  componentImportIdMap.clear();
110
127
  for (const component of state.scanResult.components) if (component.importId) componentImportIdMap.set(component.importId, component.script);
@@ -119,6 +136,7 @@ function weappWebPlugin(options = {}) {
119
136
  async configResolved(config) {
120
137
  root = config.root;
121
138
  srcRoot = resolve(root, options.srcDir ?? "src");
139
+ stylePreprocessOptions = resolveStylePreprocessOptions(config.css?.preprocessorOptions, root);
122
140
  enableHmr = config.command === "serve";
123
141
  resolveWebModuleId = config.createResolver?.();
124
142
  resolveWebAutoImportTag = createAutoImportTagResolver();
@@ -209,7 +227,8 @@ function weappWebPlugin(options = {}) {
209
227
  state,
210
228
  resolveId: resolveWebModuleId,
211
229
  resolveAutoImportTag: resolveWebAutoImportTag,
212
- uniApp: options.__uniApp
230
+ uniApp: options.__uniApp,
231
+ stylePreprocessOptions
213
232
  });
214
233
  const compiled = generateWebVueSfcTemplate(result, meta, filename, srcRoot);
215
234
  for (const dependency of compiled.dependencies) this.addWatchFile?.(dependency);
@@ -227,7 +246,8 @@ function weappWebPlugin(options = {}) {
227
246
  state,
228
247
  resolveId: resolveWebModuleId,
229
248
  resolveAutoImportTag: resolveWebAutoImportTag,
230
- uniApp: options.__uniApp
249
+ uniApp: options.__uniApp,
250
+ stylePreprocessOptions
231
251
  });
232
252
  return generateWebVueSfcStyle(result);
233
253
  }
@@ -268,7 +288,8 @@ function weappWebPlugin(options = {}) {
268
288
  source: code,
269
289
  resolveId: resolveWebModuleId,
270
290
  resolveAutoImportTag: resolveWebAutoImportTag,
271
- uniApp: options.__uniApp
291
+ uniApp: options.__uniApp,
292
+ stylePreprocessOptions
272
293
  });
273
294
  return transformWebVueSfcScript({
274
295
  code: result.script,
@@ -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 } 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, 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 { 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}\n\ninterface WebUserConfig {\n css?: {\n postcss?: string | WebPostcssConfig\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\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 }\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 resolveWebAutoImportTag: ResolveWebAutoImportTag | 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 })\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 srcRoot = resolve(root, options.srcDir ?? 'src')\n enableHmr = config.command === 'serve'\n resolveWebModuleId = config.createResolver?.()\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 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 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 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 })\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 })\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 })\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":";;;;;;;;;;;;;;;;;;;;AAmFA,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,SAAS,IAAY,OAAe;CAC3C,OAAO,GAAG,SAAS,IAAI,OAAO,KAAK,GAAG,SAAS,IAAI,OAAO;AAC5D;AAEA,SAAS,mBAAmB,IAAY,UAA6B;CACnE,OAAO,SAAS,MAAK,gBAAe,OAAO,eAAe,GAAG,WAAW,GAAG,YAAY,EAAE,CAAC;AAC5F;AAEA,SAAS,8BAA8B,IAAY;CACjD,MAAM,WAAW,SAAS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G;IACzD,MAAM,EAAE,QAAQ,mBAAmB,MAAM,WAAW;IACpD,OAAO;KACL,MAAM,wBAAwB,GAAG;KACjC,KAAK;IACP;GACF;GAEA,IAAI,WAAW,MAAK,QAAO,MAAM,SAAS,GAAG,CAAC,KAAK,CAAC,MAAM,SAAS,OAAO,GAAG;IAC3E,MAAM,EAAE,QAAQ,mBAAmB,MAAM,WAAW;IACpD,OAAO;KAAE,MAAM;KAAK,KAAK;IAAK;GAChC;GAEA,IAAI,CAAC,YAAY,MAAK,QAAO,MAAM,SAAS,GAAG,CAAC,GAC9C,OAAO,oBAAoB;IAAE;IAAM,KAAK;GAAK,IAAI;GAEnD,IAAI,MAAM,SAAS,cAAc,KAAK,CAAC,SAAS,yBAAuB,GACrE,OAAO,QAAQ,YAAY,0BAA0B,OAAO,SAAS,QAAQ,SAAS,OAAO,IACzF;IAAE;IAAM,KAAK;GAAK,IAClB;GAGN,MAAM,OAAO,MAAM,WAAW,IAAI,cAAc,KAAK,CAAC;GACtD,IAAI,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, 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 { 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\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 = resolve(root, 'node_modules')\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 resolveWebAutoImportTag: ResolveWebAutoImportTag | undefined\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 srcRoot = resolve(root, options.srcDir ?? 'src')\n stylePreprocessOptions = resolveStylePreprocessOptions(config.css?.preprocessorOptions, root)\n enableHmr = config.command === 'serve'\n resolveWebModuleId = config.createResolver?.()\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 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 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 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":";;;;;;;;;;;;;;;;;;;;AAqFA,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,SAAS,IAAY,OAAe;CAC3C,OAAO,GAAG,SAAS,IAAI,OAAO,KAAK,GAAG,SAAS,IAAI,OAAO;AAC5D;AAEA,SAAS,mBAAmB,IAAY,UAA6B;CACnE,OAAO,SAAS,MAAK,gBAAe,OAAO,eAAe,GAAG,WAAW,GAAG,YAAY,EAAE,CAAC;AAC5F;AAEA,SAAS,8BAA8B,IAAY;CACjD,MAAM,WAAW,SAAS,EAAE;CAC5B,MAAM,iBAAiB,SAAS,YAAY,OAAO;CACnD,OAAO,kBAAkB,IACrB,SAAS,MAAM,GAAG,iBA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iBAAiB,iBAAiB;IAClC;GACF,CAAC;EACH;CACF;AACF"}
@@ -23,7 +23,7 @@ function resolveComponentBase(raw, importerDir, srcRoot) {
23
23
  if (raw.startsWith(".")) return resolve(importerDir, raw);
24
24
  if (raw.startsWith("/")) return resolve(srcRoot, raw.slice(1));
25
25
  }
26
- async function scanProject({ srcRoot, warn, state, resolveId, resolveAutoImportTag, resolveAppConfig, uniApp }) {
26
+ async function scanProject({ srcRoot, warn, state, resolveId, resolveAutoImportTag, resolveAppConfig, uniApp, stylePreprocessOptions }) {
27
27
  state.moduleMeta.clear();
28
28
  state.pageNavigationMap.clear();
29
29
  state.templateComponentMap.clear();
@@ -119,7 +119,8 @@ async function scanProject({ srcRoot, warn, state, resolveId, resolveAutoImportT
119
119
  state,
120
120
  resolveId,
121
121
  resolveAutoImportTag,
122
- uniApp
122
+ uniApp,
123
+ stylePreprocessOptions
123
124
  })).config : void 0;
124
125
  const componentTags = sfcConfig ? await collectComponentTagsFromConfig({
125
126
  json: sfcConfig,
@@ -177,7 +178,8 @@ async function scanProject({ srcRoot, warn, state, resolveId, resolveAutoImportT
177
178
  state,
178
179
  resolveId,
179
180
  resolveAutoImportTag,
180
- uniApp
181
+ uniApp,
182
+ stylePreprocessOptions
181
183
  })).config : void 0;
182
184
  const resolvedNavigationConfig = mergeNavigationConfig(appNavigationDefaults, sfcConfig ? pickNavigationConfig(sfcConfig) : pageJson ? pickNavigationConfig(pageJson) : {});
183
185
  pageMeta.navigationBar = Object.keys(resolvedNavigationConfig).length > 0 ? resolvedNavigationConfig : void 0;
@@ -264,7 +266,8 @@ async function scanProject({ srcRoot, warn, state, resolveId, resolveAutoImportT
264
266
  state,
265
267
  resolveId,
266
268
  resolveAutoImportTag,
267
- uniApp
269
+ uniApp,
270
+ stylePreprocessOptions
268
271
  })).config ?? {},
269
272
  ...appJson ?? {}
270
273
  };
@@ -1 +1 @@
1
- {"version":3,"file":"scan.mjs","names":[],"sources":["../../src/plugin/scan.ts"],"sourcesContent":["import type { WebTabBarConfig } from '../shared/tabBar'\nimport type { ComponentEntry, LayoutEntry, ModuleMeta, PageEntry, ResolveWebAutoImportTag, ResolveWebModuleId, ScanState, WarnFn } from './types'\n\nimport { readdir } from 'node:fs/promises'\nimport process from 'node:process'\nimport { dirname, extname, join, posix, relative, resolve } from 'pathe'\nimport { slugify } from '../shared/slugify'\nimport { normalizeWebTabBarConfig } from '../shared/tabBar'\nimport { SCRIPT_EXTS } from './constants'\nimport { isRecord, readJsonFile, resolveJsonPath, resolveScriptFile, resolveStyleFile, resolveTemplateFile } from './files'\nimport { mergeNavigationConfig, pickNavigationConfig } from './navigation'\nimport { isInsideDir, normalizePath, toPosixId } from './path'\nimport { collectComponentTagsFromConfig, collectComponentTagsFromJson, mergeComponentTags } from './scanConfig'\nimport { compileScannedSfc, discoverWebPageIds } from './scanSfc'\n\ninterface ScanProjectOptions {\n srcRoot: string\n warn?: WarnFn\n state: ScanState\n resolveId?: ResolveWebModuleId\n resolveAutoImportTag?: ResolveWebAutoImportTag\n resolveAppConfig?: (appConfigPath: string) => Promise<Record<string, unknown> | undefined>\n uniApp?: { include: string[] }\n}\n\nexport function getStableWebComponentId(script: string, srcRoot: string) {\n const normalized = script.replace(/\\\\/g, '/')\n const nodeModulesIndex = normalized.lastIndexOf('/node_modules/')\n const extension = extname(script)\n if (nodeModulesIndex >= 0) {\n const packageRelative = normalized.slice(nodeModulesIndex + '/node_modules/'.length)\n return `__external__/${packageRelative.slice(0, -extension.length)}`\n }\n return toPosixId(relative(srcRoot, script).slice(0, -extension.length))\n}\n\nfunction resolveComponentBase(raw: string, importerDir: string, srcRoot: string) {\n if (!raw) {\n return undefined\n }\n if (raw.startsWith('.')) {\n return resolve(importerDir, raw)\n }\n if (raw.startsWith('/')) {\n return resolve(srcRoot, raw.slice(1))\n }\n return undefined\n}\n\nexport async function scanProject({ srcRoot, warn, state, resolveId, resolveAutoImportTag, resolveAppConfig, uniApp }: ScanProjectOptions) {\n state.moduleMeta.clear()\n state.pageNavigationMap.clear()\n state.templateComponentMap.clear()\n state.templatePathSet.clear()\n state.componentTagMap.clear()\n state.sfcResults.clear()\n\n let appNavigationDefaults = {}\n let appComponentTags: Record<string, string> = {}\n let appTabBar: WebTabBarConfig | undefined\n\n const pages = new Map<string, PageEntry>()\n const components = new Map<string, ComponentEntry>()\n const layouts = new Map<string, LayoutEntry>()\n\n async function walk(current: string, files: string[]) {\n const entries = await readdir(current, { withFileTypes: true })\n for (const entry of entries) {\n const pathname = join(current, entry.name)\n if (entry.isDirectory()) {\n await walk(pathname, files)\n }\n else {\n files.push(pathname)\n }\n }\n }\n\n const reportWarning = (message: string) => {\n if (warn) {\n warn(message)\n return\n }\n process.emitWarning(message)\n }\n\n const appScript = await resolveScriptFile(join(srcRoot, 'app'))\n if (appScript) {\n const appMeta: ModuleMeta = {\n kind: 'app',\n id: 'app',\n scriptPath: appScript,\n stylePath: await resolveStyleFile(appScript),\n sourceType: appScript.endsWith('.vue') ? 'vue-sfc' : 'native',\n }\n state.moduleMeta.set(normalizePath(appScript), appMeta)\n }\n\n const resolveComponentScript = async (raw: string, importerDir: string) => {\n const base = resolveComponentBase(raw, importerDir, srcRoot)\n if (base) {\n const resolved = await resolveScriptFile(base)\n return resolved ? normalizePath(resolved) : undefined\n }\n const importer = join(importerDir, '__weapp_web_using_components__.ts')\n const resolved = await resolveId?.(raw, importer)\n const script = resolved ? await resolveScriptFile(resolved) : undefined\n return script ? normalizePath(script) : undefined\n }\n\n const getStableComponentId = (script: string) => {\n return getStableWebComponentId(script, srcRoot)\n }\n\n const getComponentTag = (script: string) => {\n const cached = state.componentTagMap.get(script)\n if (cached) {\n return cached\n }\n const id = getStableComponentId(script)\n const tag = slugify(id, 'wv-component')\n state.componentTagMap.set(script, tag)\n return tag\n }\n\n const collectComponent = async (componentId: string, importerDir: string) => {\n const script = await resolveComponentScript(componentId, importerDir)\n if (!script) {\n return\n }\n\n const existing = components.get(script)\n if (existing) {\n existing.importId ??= resolveComponentBase(componentId, importerDir, srcRoot)\n ? undefined\n : componentId\n return\n }\n\n const componentIdPosix = getStableComponentId(script)\n const importId = resolveComponentBase(componentId, importerDir, srcRoot)\n ? (isInsideDir(script, srcRoot) ? undefined : componentIdPosix)\n : componentId\n const template = await resolveTemplateFile(script)\n const style = await resolveStyleFile(script)\n\n if (template) {\n state.templatePathSet.add(normalizePath(template))\n }\n\n const componentMeta: ModuleMeta = {\n kind: 'component',\n id: componentIdPosix,\n scriptPath: script,\n templatePath: template,\n stylePath: style,\n sourceType: script.endsWith('.vue') ? 'vue-sfc' : 'native',\n }\n state.moduleMeta.set(normalizePath(script), componentMeta)\n\n components.set(script, { script, id: componentIdPosix, importId })\n\n const componentJsonBasePath = `${script.replace(new RegExp(`${extname(script)}$`), '')}.json`\n const sfcConfig = script.endsWith('.vue')\n ? (await compileScannedSfc({ filename: script, meta: componentMeta, srcRoot, state, resolveId, resolveAutoImportTag, uniApp })).config\n : undefined\n const componentTags = sfcConfig\n ? await collectComponentTagsFromConfig({\n json: sfcConfig,\n importerDir: dirname(script),\n jsonPath: script,\n warn: reportWarning,\n resolveComponentScript,\n getComponentTag,\n collectComponent,\n })\n : await collectComponentTagsFromJson({\n jsonBasePath: componentJsonBasePath,\n importerDir: dirname(script),\n warn: reportWarning,\n collectFromConfig: (json, nextImporterDir, jsonPath, nextWarn) => collectComponentTagsFromConfig({\n json,\n importerDir: nextImporterDir,\n jsonPath,\n warn: nextWarn,\n resolveComponentScript,\n getComponentTag,\n collectComponent,\n }),\n })\n componentMeta.componentTags = mergeComponentTags(appComponentTags, componentTags)\n\n if (!template) {\n return\n }\n\n const mergedTags = mergeComponentTags(appComponentTags, componentTags)\n if (Object.keys(mergedTags).length > 0) {\n state.templateComponentMap.set(normalizePath(template), mergedTags)\n return\n }\n state.templateComponentMap.delete(normalizePath(template))\n }\n\n async function collectPage(pageId: string) {\n const base = join(srcRoot, pageId)\n const script = await resolveScriptFile(base)\n if (!script) {\n return\n }\n\n const template = await resolveTemplateFile(base)\n if (template) {\n state.templatePathSet.add(normalizePath(template))\n }\n\n const style = await resolveStyleFile(base)\n const pageJsonBasePath = join(srcRoot, `${pageId}.json`)\n const pageJsonPath = await resolveJsonPath(pageJsonBasePath)\n const pageJson = pageJsonPath ? await readJsonFile(pageJsonPath) : undefined\n const pageMeta: ModuleMeta = {\n kind: 'page',\n id: toPosixId(pageId),\n scriptPath: script,\n templatePath: template,\n stylePath: style,\n sourceType: script.endsWith('.vue') ? 'vue-sfc' : 'native',\n }\n\n const sfcConfig = script.endsWith('.vue')\n ? (await compileScannedSfc({ filename: script, meta: pageMeta, srcRoot, state, resolveId, resolveAutoImportTag, uniApp })).config\n : undefined\n const resolvedNavigationConfig = mergeNavigationConfig(\n appNavigationDefaults,\n sfcConfig ? pickNavigationConfig(sfcConfig) : pageJson ? pickNavigationConfig(pageJson) : {},\n )\n pageMeta.navigationBar = Object.keys(resolvedNavigationConfig).length > 0\n ? resolvedNavigationConfig\n : undefined\n state.moduleMeta.set(normalizePath(script), pageMeta)\n\n pages.set(script, {\n script,\n id: toPosixId(pageId),\n })\n\n const pageComponentTags = sfcConfig\n ? await collectComponentTagsFromConfig({\n json: sfcConfig,\n importerDir: dirname(script),\n jsonPath: script,\n warn: reportWarning,\n resolveComponentScript,\n getComponentTag,\n collectComponent,\n })\n : pageJson && pageJsonPath\n ? await collectComponentTagsFromConfig({\n json: pageJson,\n importerDir: dirname(script),\n jsonPath: pageJsonPath,\n warn: reportWarning,\n resolveComponentScript,\n getComponentTag,\n collectComponent,\n })\n : {}\n\n if (template) {\n const mergedTags = mergeComponentTags(appComponentTags, pageComponentTags)\n if (Object.keys(mergedTags).length > 0) {\n state.templateComponentMap.set(normalizePath(template), mergedTags)\n }\n else {\n state.templateComponentMap.delete(normalizePath(template))\n }\n }\n pageMeta.componentTags = mergeComponentTags(appComponentTags, pageComponentTags)\n\n if (!template) {\n return\n }\n\n state.pageNavigationMap.set(normalizePath(template), resolvedNavigationConfig)\n }\n\n async function collectLayouts() {\n const layoutsRoot = join(srcRoot, 'layouts')\n const files: string[] = []\n try {\n await walk(layoutsRoot, files)\n }\n catch {\n return\n }\n for (const filename of files.sort()) {\n const script = SCRIPT_EXTS.includes(extname(filename)) ? filename : undefined\n if (!script) {\n continue\n }\n const relativePath = relative(layoutsRoot, script).replace(/\\\\/g, '/')\n const segments = relativePath.split('/')\n segments.pop()\n if (segments[segments.length - 1] === 'index') {\n segments.pop()\n }\n const name = segments.join('/')\n if (!name) {\n continue\n }\n const id = `layouts/${name}`\n const template = await resolveTemplateFile(script)\n const style = await resolveStyleFile(script)\n const tag = slugify(id, 'wv-component')\n state.moduleMeta.set(normalizePath(script), {\n kind: 'component',\n id,\n scriptPath: script,\n templatePath: template,\n stylePath: style,\n sourceType: 'native',\n })\n layouts.set(script, { script, id, name, tag, template, style })\n if (template) {\n state.templatePathSet.add(normalizePath(template))\n }\n }\n }\n\n const appJsonBasePath = join(srcRoot, 'app.json')\n const appJsonPath = await resolveJsonPath(appJsonBasePath)\n let appJson = appJsonPath\n ? await (resolveAppConfig ? resolveAppConfig(appJsonPath) : readJsonFile(appJsonPath))\n : undefined\n if (appScript?.endsWith('.vue')) {\n const appMeta = state.moduleMeta.get(normalizePath(appScript))!\n const sfcConfig = (await compileScannedSfc({ filename: appScript, meta: appMeta, srcRoot, state, resolveId, resolveAutoImportTag, uniApp })).config\n appJson = {\n ...(sfcConfig ?? {}),\n ...(appJson ?? {}),\n }\n }\n if (appJson) {\n appComponentTags = await collectComponentTagsFromConfig({\n json: appJson,\n importerDir: srcRoot,\n jsonPath: appJsonPath ?? appScript!,\n warn: reportWarning,\n resolveComponentScript,\n getComponentTag,\n collectComponent,\n onResolved: (tags) => {\n appComponentTags = tags\n },\n })\n\n const windowConfig = isRecord(appJson?.window) ? appJson.window : undefined\n appNavigationDefaults = pickNavigationConfig(windowConfig)\n\n const configuredPages = Array.isArray(appJson.pages)\n ? appJson.pages.filter((page): page is string => typeof page === 'string')\n : []\n for (const page of configuredPages.length > 0 ? configuredPages : await discoverWebPageIds(srcRoot)) {\n await collectPage(page)\n }\n\n const subPackages = Array.isArray(appJson.subPackages)\n ? appJson.subPackages\n : Array.isArray(appJson.subpackages)\n ? appJson.subpackages\n : []\n if (subPackages.length > 0) {\n for (const pkg of subPackages) {\n if (!pkg || typeof pkg !== 'object' || !Array.isArray(pkg.pages)) {\n continue\n }\n const root = typeof pkg.root === 'string' ? pkg.root : ''\n for (const page of pkg.pages) {\n if (typeof page !== 'string') {\n continue\n }\n await collectPage(posix.join(root, page))\n }\n }\n }\n\n appTabBar = normalizeWebTabBarConfig(appJson?.tabBar)\n }\n else {\n for (const page of await discoverWebPageIds(srcRoot)) {\n await collectPage(page)\n }\n }\n\n await collectLayouts()\n\n state.appNavigationDefaults = appNavigationDefaults\n state.appComponentTags = appComponentTags\n state.scanResult = {\n app: appScript,\n pages: Array.from(pages.values()),\n components: Array.from(components.values()),\n layouts: Array.from(layouts.values()),\n tabBar: appTabBar,\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAyBA,SAAgB,wBAAwB,QAAgB,SAAiB;CACvE,MAAM,aAAa,OAAO,QAAQ,OAAO,GAAG;CAC5C,MAAM,mBAAmB,WAAW,YAAY,gBAAgB;CAChE,MAAM,YAAY,QAAQ,MAAM;CAChC,IAAI,oBAAoB,GAEtB,OAAO,gBADiB,WAAW,MAAM,mBAAmB,EACvB,CAAC,CAAC,MAAM,GAAG,CAAC,UAAU,MAAM;CAEnE,OAAO,UAAU,SAAS,SAAS,MAAM,CAAC,CAAC,MAAM,GAAG,CAAC,UAAU,MAAM,CAAC;AACxE;AAEA,SAAS,qBAAqB,KAAa,aAAqB,SAAiB;CAC/E,IAAI,CAAC,KACH;CAEF,IAAI,IAAI,WAAW,GAAG,GACpB,OAAO,QAAQ,aAAa,GAAG;CAEjC,IAAI,IAAI,WAAW,GAAG,GACpB,OAAO,QAAQ,SAAS,IAAI,MAAM,CAAC,CAAC;AAGxC;AAEA,eAAsB,YAAY,EAAE,SAAS,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cesContent":["import type { WebTabBarConfig } from '../shared/tabBar'\nimport type { ComponentEntry, LayoutEntry, ModuleMeta, PageEntry, ResolveWebAutoImportTag, ResolveWebModuleId, ScanState, WarnFn, WebStylePreprocessOptions } from './types'\n\nimport { readdir } from 'node:fs/promises'\nimport process from 'node:process'\nimport { dirname, extname, join, posix, relative, resolve } from 'pathe'\nimport { slugify } from '../shared/slugify'\nimport { normalizeWebTabBarConfig } from '../shared/tabBar'\nimport { SCRIPT_EXTS } from './constants'\nimport { isRecord, readJsonFile, resolveJsonPath, resolveScriptFile, resolveStyleFile, resolveTemplateFile } from './files'\nimport { mergeNavigationConfig, pickNavigationConfig } from './navigation'\nimport { isInsideDir, normalizePath, toPosixId } from './path'\nimport { collectComponentTagsFromConfig, collectComponentTagsFromJson, mergeComponentTags } from './scanConfig'\nimport { compileScannedSfc, discoverWebPageIds } from './scanSfc'\n\ninterface ScanProjectOptions {\n srcRoot: string\n warn?: WarnFn\n state: ScanState\n resolveId?: ResolveWebModuleId\n resolveAutoImportTag?: ResolveWebAutoImportTag\n resolveAppConfig?: (appConfigPath: string) => Promise<Record<string, unknown> | undefined>\n uniApp?: { include: string[] }\n stylePreprocessOptions?: WebStylePreprocessOptions\n}\n\nexport function getStableWebComponentId(script: string, srcRoot: string) {\n const normalized = script.replace(/\\\\/g, '/')\n const nodeModulesIndex = normalized.lastIndexOf('/node_modules/')\n const extension = extname(script)\n if (nodeModulesIndex >= 0) {\n const packageRelative = normalized.slice(nodeModulesIndex + '/node_modules/'.length)\n return `__external__/${packageRelative.slice(0, -extension.length)}`\n }\n return toPosixId(relative(srcRoot, script).slice(0, -extension.length))\n}\n\nfunction resolveComponentBase(raw: string, importerDir: string, srcRoot: string) {\n if (!raw) {\n return undefined\n }\n if (raw.startsWith('.')) {\n return resolve(importerDir, raw)\n }\n if (raw.startsWith('/')) {\n return resolve(srcRoot, raw.slice(1))\n }\n return undefined\n}\n\nexport async function scanProject({ srcRoot, warn, state, resolveId, resolveAutoImportTag, resolveAppConfig, uniApp, stylePreprocessOptions }: ScanProjectOptions) {\n state.moduleMeta.clear()\n state.pageNavigationMap.clear()\n state.templateComponentMap.clear()\n state.templatePathSet.clear()\n state.componentTagMap.clear()\n state.sfcResults.clear()\n\n let appNavigationDefaults = {}\n let appComponentTags: Record<string, string> = {}\n let appTabBar: WebTabBarConfig | undefined\n\n const pages = new Map<string, PageEntry>()\n const components = new Map<string, ComponentEntry>()\n const layouts = new Map<string, LayoutEntry>()\n\n async function walk(current: string, files: string[]) {\n const entries = await readdir(current, { withFileTypes: true })\n for (const entry of entries) {\n const pathname = join(current, entry.name)\n if (entry.isDirectory()) {\n await walk(pathname, files)\n }\n else {\n files.push(pathname)\n }\n }\n }\n\n const reportWarning = (message: string) => {\n if (warn) {\n warn(message)\n return\n }\n process.emitWarning(message)\n }\n\n const appScript = await resolveScriptFile(join(srcRoot, 'app'))\n if (appScript) {\n const appMeta: ModuleMeta = {\n kind: 'app',\n id: 'app',\n scriptPath: appScript,\n stylePath: await resolveStyleFile(appScript),\n sourceType: appScript.endsWith('.vue') ? 'vue-sfc' : 'native',\n }\n state.moduleMeta.set(normalizePath(appScript), appMeta)\n }\n\n const resolveComponentScript = async (raw: string, importerDir: string) => {\n const base = resolveComponentBase(raw, importerDir, srcRoot)\n if (base) {\n const resolved = await resolveScriptFile(base)\n return resolved ? normalizePath(resolved) : undefined\n }\n const importer = join(importerDir, '__weapp_web_using_components__.ts')\n const resolved = await resolveId?.(raw, importer)\n const script = resolved ? await resolveScriptFile(resolved) : undefined\n return script ? normalizePath(script) : undefined\n }\n\n const getStableComponentId = (script: string) => {\n return getStableWebComponentId(script, srcRoot)\n }\n\n const getComponentTag = (script: string) => {\n const cached = state.componentTagMap.get(script)\n if (cached) {\n return cached\n }\n const id = getStableComponentId(script)\n const tag = slugify(id, 'wv-component')\n state.componentTagMap.set(script, tag)\n return tag\n }\n\n const collectComponent = async (componentId: string, importerDir: string) => {\n const script = await resolveComponentScript(componentId, importerDir)\n if (!script) {\n return\n }\n\n const existing = components.get(script)\n if (existing) {\n existing.importId ??= resolveComponentBase(componentId, importerDir, srcRoot)\n ? undefined\n : componentId\n return\n }\n\n const componentIdPosix = getStableComponentId(script)\n const importId = resolveComponentBase(componentId, importerDir, srcRoot)\n ? (isInsideDir(script, srcRoot) ? undefined : componentIdPosix)\n : componentId\n const template = await resolveTemplateFile(script)\n const style = await resolveStyleFile(script)\n\n if (template) {\n state.templatePathSet.add(normalizePath(template))\n }\n\n const componentMeta: ModuleMeta = {\n kind: 'component',\n id: componentIdPosix,\n scriptPath: script,\n templatePath: template,\n stylePath: style,\n sourceType: script.endsWith('.vue') ? 'vue-sfc' : 'native',\n }\n state.moduleMeta.set(normalizePath(script), componentMeta)\n\n components.set(script, { script, id: componentIdPosix, importId })\n\n const componentJsonBasePath = `${script.replace(new RegExp(`${extname(script)}$`), '')}.json`\n const sfcConfig = script.endsWith('.vue')\n ? (await compileScannedSfc({ filename: script, meta: componentMeta, srcRoot, state, resolveId, resolveAutoImportTag, uniApp, stylePreprocessOptions })).config\n : undefined\n const componentTags = sfcConfig\n ? await collectComponentTagsFromConfig({\n json: sfcConfig,\n importerDir: dirname(script),\n jsonPath: script,\n warn: reportWarning,\n resolveComponentScript,\n getComponentTag,\n collectComponent,\n })\n : await collectComponentTagsFromJson({\n jsonBasePath: componentJsonBasePath,\n importerDir: dirname(script),\n warn: reportWarning,\n collectFromConfig: (json, nextImporterDir, jsonPath, nextWarn) => collectComponentTagsFromConfig({\n json,\n importerDir: nextImporterDir,\n jsonPath,\n warn: nextWarn,\n resolveComponentScript,\n getComponentTag,\n collectComponent,\n }),\n })\n componentMeta.componentTags = mergeComponentTags(appComponentTags, componentTags)\n\n if (!template) {\n return\n }\n\n const mergedTags = mergeComponentTags(appComponentTags, componentTags)\n if (Object.keys(mergedTags).length > 0) {\n state.templateComponentMap.set(normalizePath(template), mergedTags)\n return\n }\n state.templateComponentMap.delete(normalizePath(template))\n }\n\n async function collectPage(pageId: string) {\n const base = join(srcRoot, pageId)\n const script = await resolveScriptFile(base)\n if (!script) {\n return\n }\n\n const template = await resolveTemplateFile(base)\n if (template) {\n state.templatePathSet.add(normalizePath(template))\n }\n\n const style = await resolveStyleFile(base)\n const pageJsonBasePath = join(srcRoot, `${pageId}.json`)\n const pageJsonPath = await resolveJsonPath(pageJsonBasePath)\n const pageJson = pageJsonPath ? await readJsonFile(pageJsonPath) : undefined\n const pageMeta: ModuleMeta = {\n kind: 'page',\n id: toPosixId(pageId),\n scriptPath: script,\n templatePath: template,\n stylePath: style,\n sourceType: script.endsWith('.vue') ? 'vue-sfc' : 'native',\n }\n\n const sfcConfig = script.endsWith('.vue')\n ? (await compileScannedSfc({ filename: script, meta: pageMeta, srcRoot, state, resolveId, resolveAutoImportTag, uniApp, stylePreprocessOptions })).config\n : undefined\n const resolvedNavigationConfig = mergeNavigationConfig(\n appNavigationDefaults,\n sfcConfig ? pickNavigationConfig(sfcConfig) : pageJson ? pickNavigationConfig(pageJson) : {},\n )\n pageMeta.navigationBar = Object.keys(resolvedNavigationConfig).length > 0\n ? resolvedNavigationConfig\n : undefined\n state.moduleMeta.set(normalizePath(script), pageMeta)\n\n pages.set(script, {\n script,\n id: toPosixId(pageId),\n })\n\n const pageComponentTags = sfcConfig\n ? await collectComponentTagsFromConfig({\n json: sfcConfig,\n importerDir: dirname(script),\n jsonPath: script,\n warn: reportWarning,\n resolveComponentScript,\n getComponentTag,\n collectComponent,\n })\n : pageJson && pageJsonPath\n ? await collectComponentTagsFromConfig({\n json: pageJson,\n importerDir: dirname(script),\n jsonPath: pageJsonPath,\n warn: reportWarning,\n resolveComponentScript,\n getComponentTag,\n collectComponent,\n })\n : {}\n\n if (template) {\n const mergedTags = mergeComponentTags(appComponentTags, pageComponentTags)\n if (Object.keys(mergedTags).length > 0) {\n state.templateComponentMap.set(normalizePath(template), mergedTags)\n }\n else {\n state.templateComponentMap.delete(normalizePath(template))\n }\n }\n pageMeta.componentTags = mergeComponentTags(appComponentTags, pageComponentTags)\n\n if (!template) {\n return\n }\n\n state.pageNavigationMap.set(normalizePath(template), resolvedNavigationConfig)\n }\n\n async function collectLayouts() {\n const layoutsRoot = join(srcRoot, 'layouts')\n const files: string[] = []\n try {\n await walk(layoutsRoot, files)\n }\n catch {\n return\n }\n for (const filename of files.sort()) {\n const script = SCRIPT_EXTS.includes(extname(filename)) ? filename : undefined\n if (!script) {\n continue\n }\n const relativePath = relative(layoutsRoot, script).replace(/\\\\/g, '/')\n const segments = relativePath.split('/')\n segments.pop()\n if (segments[segments.length - 1] === 'index') {\n segments.pop()\n }\n const name = segments.join('/')\n if (!name) {\n continue\n }\n const id = `layouts/${name}`\n const template = await resolveTemplateFile(script)\n const style = await resolveStyleFile(script)\n const tag = slugify(id, 'wv-component')\n state.moduleMeta.set(normalizePath(script), {\n kind: 'component',\n id,\n scriptPath: script,\n templatePath: template,\n stylePath: style,\n sourceType: 'native',\n })\n layouts.set(script, { script, id, name, tag, template, style })\n if (template) {\n state.templatePathSet.add(normalizePath(template))\n }\n }\n }\n\n const appJsonBasePath = join(srcRoot, 'app.json')\n const appJsonPath = await resolveJsonPath(appJsonBasePath)\n let appJson = appJsonPath\n ? await (resolveAppConfig ? resolveAppConfig(appJsonPath) : readJsonFile(appJsonPath))\n : undefined\n if (appScript?.endsWith('.vue')) {\n const appMeta = state.moduleMeta.get(normalizePath(appScript))!\n const sfcConfig = (await compileScannedSfc({ filename: appScript, meta: appMeta, srcRoot, state, resolveId, resolveAutoImportTag, uniApp, stylePreprocessOptions })).config\n appJson = {\n ...(sfcConfig ?? {}),\n ...(appJson ?? {}),\n }\n }\n if (appJson) {\n appComponentTags = await collectComponentTagsFromConfig({\n json: appJson,\n importerDir: srcRoot,\n jsonPath: appJsonPath ?? appScript!,\n warn: reportWarning,\n resolveComponentScript,\n getComponentTag,\n collectComponent,\n onResolved: (tags) => {\n appComponentTags = tags\n },\n })\n\n const windowConfig = isRecord(appJson?.window) ? appJson.window : undefined\n appNavigationDefaults = pickNavigationConfig(windowConfig)\n\n const configuredPages = Array.isArray(appJson.pages)\n ? appJson.pages.filter((page): page is string => typeof page === 'string')\n : []\n for (const page of configuredPages.length > 0 ? configuredPages : await discoverWebPageIds(srcRoot)) {\n await collectPage(page)\n }\n\n const subPackages = Array.isArray(appJson.subPackages)\n ? appJson.subPackages\n : Array.isArray(appJson.subpackages)\n ? appJson.subpackages\n : []\n if (subPackages.length > 0) {\n for (const pkg of subPackages) {\n if (!pkg || typeof pkg !== 'object' || !Array.isArray(pkg.pages)) {\n continue\n }\n const root = typeof pkg.root === 'string' ? pkg.root : ''\n for (const page of pkg.pages) {\n if (typeof page !== 'string') {\n continue\n }\n await collectPage(posix.join(root, page))\n }\n }\n }\n\n appTabBar = normalizeWebTabBarConfig(appJson?.tabBar)\n }\n else {\n for (const page of await discoverWebPageIds(srcRoot)) {\n await collectPage(page)\n }\n }\n\n await collectLayouts()\n\n state.appNavigationDefaults = appNavigationDefaults\n state.appComponentTags = appComponentTags\n state.scanResult = {\n app: appScript,\n pages: Array.from(pages.values()),\n components: Array.from(components.values()),\n layouts: Array.from(layouts.values()),\n tabBar: appTabBar,\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA0BA,SAAgB,wBAAwB,QAAgB,SAAiB;CACvE,MAAM,aAAa,OAAO,QAAQ,OAAO,GAAG;CAC5C,MAAM,mBAAmB,WAAW,YAAY,gBAAgB;CAChE,MAAM,YAAY,QAAQ,MAAM;CAChC,IAAI,oBAAoB,GAEtB,OAAO,gBADiB,WAAW,MAAM,mBAAmB,EACvB,CAAC,CAAC,MAAM,GAAG,CAAC,UAAU,MAAM;CAEnE,OAAO,UAAU,SAAS,SAAS,MAAM,CAAC,CAAC,MAAM,GAAG,CAAC,UAAU,MAAM,CAAC;AACxE;AAEA,SAAS,qBAAqB,KAAa,aAAqB,SAAiB;CAC/E,IAAI,CAAC,KACH;CAEF,IAAI,IAAI,WAAW,GAAG,GACpB,OAAO,QAAQ,aAAa,GAAG;CAEjC,IAAI,I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OAAO,CAAC;EAC1C,SAAS,MAAM,KAAK,QAAQ,OAAO,CAAC;EACpC,QAAQ;CACV;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"scanSfc.mjs","names":[],"sources":["../../src/plugin/scanSfc.ts"],"sourcesContent":["import type { ModuleMeta, ResolveWebAutoImportTag, ResolveWebModuleId, ScanState } from './types'\nimport { readdir, readFile } from 'node:fs/promises'\nimport path from 'pathe'\nimport { SCRIPT_EXTS } from './constants'\nimport { isRecord, resolveTemplateFile } from './files'\nimport { compileWebVueSfc } from './vueSfc'\n\nconst PAGE_SEGMENT = 'pages'\nconst EXCLUDED_PAGE_SEGMENTS = new Set(['components', 'custom-tab-bar', 'layouts'])\n\nexport function parseSfcJsonConfig(source?: string) {\n if (!source) {\n return undefined\n }\n try {\n const parsed = JSON.parse(source) as unknown\n return isRecord(parsed) ? parsed : undefined\n }\n catch {\n return undefined\n }\n}\n\nexport async function compileScannedSfc(options: {\n filename: string\n meta: ModuleMeta\n srcRoot: string\n state: ScanState\n resolveId?: ResolveWebModuleId\n resolveAutoImportTag?: ResolveWebAutoImportTag\n uniApp?: { include: string[] }\n}) {\n const source = await readFile(options.filename, 'utf8')\n const result = await compileWebVueSfc({ ...options, source })\n return {\n result,\n config: parseSfcJsonConfig(result.config),\n }\n}\n\nfunction isPageCandidate(relativePath: string) {\n const segments = relativePath.split('/')\n const pagesIndex = segments.indexOf(PAGE_SEGMENT)\n if (pagesIndex < 0) {\n return false\n }\n const routeSegments = segments.slice(pagesIndex + 1, -1)\n return !routeSegments.some(segment => EXCLUDED_PAGE_SEGMENTS.has(segment))\n}\n\nasync function walk(current: string, files: string[]) {\n const entries = await readdir(current, { withFileTypes: true })\n for (const entry of entries) {\n const pathname = path.join(current, entry.name)\n if (entry.isDirectory()) {\n await walk(pathname, files)\n }\n else {\n files.push(pathname)\n }\n }\n}\n\nexport async function discoverWebPageIds(srcRoot: string) {\n const files: string[] = []\n await walk(srcRoot, files)\n const pageIds = new Set<string>()\n for (const filename of files.sort()) {\n const extension = path.extname(filename)\n if (!SCRIPT_EXTS.includes(extension)) {\n continue\n }\n const relativePath = path.relative(srcRoot, filename).replaceAll('\\\\', '/')\n if (!isPageCandidate(relativePath)) {\n continue\n }\n if (extension !== '.vue' && !(await resolveTemplateFile(filename))) {\n continue\n }\n pageIds.add(relativePath.slice(0, -extension.length))\n }\n return [...pageIds]\n}\n"],"mappings":";;;;;;;AAOA,MAAM,eAAe;AACrB,MAAM,yCAAyB,IAAI,IAAI;CAAC;CAAc;CAAkB;AAAS,CAAC;AAElF,SAAgB,mBAAmB,QAAiB;CAClD,IAAI,CAAC,QACH;CAEF,IAAI;EACF,MAAM,SAAS,KAAK,MAAM,MAAM;EAChC,OAAO,SAAS,MAAM,IAAI,SAAS;CACrC,QACM;EACJ;CACF;AACF;AAEA,eAAsB,kBAAkB,SAQrC;CACD,MAAM,SAAS,MAAM,SAAS,QAAQ,UAAU,MAAM;CACtD,MAAM,SAAS,MAAM,iBAAiB;EAAE,GAAG;EAAS;CAAO,CAAC;CAC5D,OAAO;EACL;EACA,QAAQ,mBAAmB,OAAO,MAAM;CAC1C;AACF;AAEA,SAAS,gBAAgB,cAAsB;CAC7C,MAAM,WAAW,aAAa,MAAM,GAAG;CACvC,MAAM,aAAa,SAAS,QAAQ,YAAY;CAChD,IAAI,aAAa,GACf,OAAO;CAGT,OAAO,CADe,SAAS,MAAM,aAAa,GAAG,EACjC,CAAC,CAAC,MAAK,YAAW,uBAAuB,IAAI,OAAO,CAAC;AAC3E;AAEA,eAAe,KAAK,SAAiB,OAAiB;CACpD,MAAM,UAAU,MAAM,QAAQ,SAAS,EAAE,eAAe,KAAK,CAAC;CAC9D,KAAK,MAAM,SAAS,SAAS;EAC3B,MAAM,WAAW,KAAK,KAAK,SAAS,MAAM,IAAI;EAC9C,IAAI,MAAM,YAAY,GACpB,MAAM,KAAK,UAAU,KAAK;OAG1B,MAAM,KAAK,QAAQ;CAEvB;AACF;AAEA,eAAsB,mBAAmB,SAAiB;CACxD,MAAM,QAAkB,CAAC;CACzB,MAAM,KAAK,SAAS,KAAK;CACzB,MAAM,0BAAU,IAAI,IAAY;CAChC,KAAK,MAAM,YAAY,MAAM,KAAK,GAAG;EACnC,MAAM,YAAY,KAAK,QAAQ,QAAQ;EACvC,IAAI,CAAC,YAAY,SAAS,SAAS,GACjC;EAEF,MAAM,eAAe,KAAK,SAAS,SAAS,QAAQ,CAAC,CAAC,WAAW,MAAM,GAAG;EAC1E,IAAI,CAAC,gBAAgB,YAAY,GAC/B;EAEF,IAAI,cAAc,UAAU,CAAE,MAAM,oBAAoB,QAAQ,GAC9D;EAEF,QAAQ,IAAI,aAAa,MAAM,GAAG,CAAC,UAAU,MAAM,CAAC;CACtD;CACA,OAAO,CAAC,GAAG,OAAO;AACpB"}
1
+ {"version":3,"file":"scanSfc.mjs","names":[],"sources":["../../src/plugin/scanSfc.ts"],"sourcesContent":["import type { ModuleMeta, ResolveWebAutoImportTag, ResolveWebModuleId, ScanState, WebStylePreprocessOptions } from './types'\nimport { readdir, readFile } from 'node:fs/promises'\nimport path from 'pathe'\nimport { SCRIPT_EXTS } from './constants'\nimport { isRecord, resolveTemplateFile } from './files'\nimport { compileWebVueSfc } from './vueSfc'\n\nconst PAGE_SEGMENT = 'pages'\nconst EXCLUDED_PAGE_SEGMENTS = new Set(['components', 'custom-tab-bar', 'layouts'])\n\nexport function parseSfcJsonConfig(source?: string) {\n if (!source) {\n return undefined\n }\n try {\n const parsed = JSON.parse(source) as unknown\n return isRecord(parsed) ? parsed : undefined\n }\n catch {\n return undefined\n }\n}\n\nexport async function compileScannedSfc(options: {\n filename: string\n meta: ModuleMeta\n srcRoot: string\n state: ScanState\n resolveId?: ResolveWebModuleId\n resolveAutoImportTag?: ResolveWebAutoImportTag\n uniApp?: { include: string[] }\n stylePreprocessOptions?: WebStylePreprocessOptions\n}) {\n const source = await readFile(options.filename, 'utf8')\n const result = await compileWebVueSfc({ ...options, source })\n return {\n result,\n config: parseSfcJsonConfig(result.config),\n }\n}\n\nfunction isPageCandidate(relativePath: string) {\n const segments = relativePath.split('/')\n const pagesIndex = segments.indexOf(PAGE_SEGMENT)\n if (pagesIndex < 0) {\n return false\n }\n const routeSegments = segments.slice(pagesIndex + 1, -1)\n return !routeSegments.some(segment => EXCLUDED_PAGE_SEGMENTS.has(segment))\n}\n\nasync function walk(current: string, files: string[]) {\n const entries = await readdir(current, { withFileTypes: true })\n for (const entry of entries) {\n const pathname = path.join(current, entry.name)\n if (entry.isDirectory()) {\n await walk(pathname, files)\n }\n else {\n files.push(pathname)\n }\n }\n}\n\nexport async function discoverWebPageIds(srcRoot: string) {\n const files: string[] = []\n await walk(srcRoot, files)\n const pageIds = new Set<string>()\n for (const filename of files.sort()) {\n const extension = path.extname(filename)\n if (!SCRIPT_EXTS.includes(extension)) {\n continue\n }\n const relativePath = path.relative(srcRoot, filename).replaceAll('\\\\', '/')\n if (!isPageCandidate(relativePath)) {\n continue\n }\n if (extension !== '.vue' && !(await resolveTemplateFile(filename))) {\n continue\n }\n pageIds.add(relativePath.slice(0, -extension.length))\n }\n return [...pageIds]\n}\n"],"mappings":";;;;;;;AAOA,MAAM,eAAe;AACrB,MAAM,yCAAyB,IAAI,IAAI;CAAC;CAAc;CAAkB;AAAS,CAAC;AAElF,SAAgB,mBAAmB,QAAiB;CAClD,IAAI,CAAC,QACH;CAEF,IAAI;EACF,MAAM,SAAS,KAAK,MAAM,MAAM;EAChC,OAAO,SAAS,MAAM,IAAI,SAAS;CACrC,QACM;EACJ;CACF;AACF;AAEA,eAAsB,kBAAkB,SASrC;CACD,MAAM,SAAS,MAAM,SAAS,QAAQ,UAAU,MAAM;CACtD,MAAM,SAAS,MAAM,iBAAiB;EAAE,GAAG;EAAS;CAAO,CAAC;CAC5D,OAAO;EACL;EACA,QAAQ,mBAAmB,OAAO,MAAM;CAC1C;AACF;AAEA,SAAS,gBAAgB,cAAsB;CAC7C,MAAM,WAAW,aAAa,MAAM,GAAG;CACvC,MAAM,aAAa,SAAS,QAAQ,YAAY;CAChD,IAAI,aAAa,GACf,OAAO;CAGT,OAAO,CADe,SAAS,MAAM,aAAa,GAAG,EACjC,CAAC,CAAC,MAAK,YAAW,uBAAuB,IAAI,OAAO,CAAC;AAC3E;AAEA,eAAe,KAAK,SAAiB,OAAiB;CACpD,MAAM,UAAU,MAAM,QAAQ,SAAS,EAAE,eAAe,KAAK,CAAC;CAC9D,KAAK,MAAM,SAAS,SAAS;EAC3B,MAAM,WAAW,KAAK,KAAK,SAAS,MAAM,IAAI;EAC9C,IAAI,MAAM,YAAY,GACpB,MAAM,KAAK,UAAU,KAAK;OAG1B,MAAM,KAAK,QAAQ;CAEvB;AACF;AAEA,eAAsB,mBAAmB,SAAiB;CACxD,MAAM,QAAkB,CAAC;CACzB,MAAM,KAAK,SAAS,KAAK;CACzB,MAAM,0BAAU,IAAI,IAAY;CAChC,KAAK,MAAM,YAAY,MAAM,KAAK,GAAG;EACnC,MAAM,YAAY,KAAK,QAAQ,QAAQ;EACvC,IAAI,CAAC,YAAY,SAAS,SAAS,GACjC;EAEF,MAAM,eAAe,KAAK,SAAS,SAAS,QAAQ,CAAC,CAAC,WAAW,MAAM,GAAG;EAC1E,IAAI,CAAC,gBAAgB,YAAY,GAC/B;EAEF,IAAI,cAAc,UAAU,CAAE,MAAM,oBAAoB,QAAQ,GAC9D;EAEF,QAAQ,IAAI,aAAa,MAAM,GAAG,CAAC,UAAU,MAAM,CAAC;CACtD;CACA,OAAO,CAAC,GAAG,OAAO;AACpB"}
@@ -74,6 +74,7 @@ interface WeappWebPluginOptions {
74
74
  /** @internal */
75
75
  __resolveAppConfig?: (appConfigPath: string) => Promise<Record<string, unknown> | undefined>;
76
76
  }
77
+ type WebStylePreprocessOptions = Record<string, Record<string, unknown>>;
77
78
  interface WebResolvedComponent {
78
79
  name: string;
79
80
  from: string;
@@ -86,5 +87,5 @@ type WebComponentResolver = {
86
87
  } | ((componentName: string, baseName: string) => WebResolvedComponent | void);
87
88
  type ResolveWebModuleId = (source: string, importer?: string) => Promise<string | undefined>;
88
89
  //#endregion
89
- export { ResolveWebModuleId, WeappWebPluginOptions, WebComponentResolver, WebResolvedComponent };
90
+ export { ResolveWebModuleId, WeappWebPluginOptions, WebComponentResolver, WebResolvedComponent, WebStylePreprocessOptions };
90
91
  //# sourceMappingURL=types.d.mts.map
@@ -19,7 +19,7 @@ async function resolveSfcSrc(request, importer, srcRoot, resolveId) {
19
19
  return await resolveId?.(request, importer);
20
20
  }
21
21
  async function compileWebVueSfc(options) {
22
- const { filename, meta, srcRoot, state, resolveId, resolveAutoImportTag, uniApp } = options;
22
+ const { filename, meta, srcRoot, state, resolveId, resolveAutoImportTag, uniApp, stylePreprocessOptions } = options;
23
23
  const source = uniApp && isUniAppCompatibilityFile(filename, srcRoot, uniApp.include) ? transformUniAppSource(options.source, {
24
24
  filename,
25
25
  target: "h5"
@@ -29,6 +29,7 @@ async function compileWebVueSfc(options) {
29
29
  isPage: meta.kind === "page",
30
30
  sourceMap: false,
31
31
  style: {
32
+ preprocessOptions: stylePreprocessOptions,
32
33
  preserveDeepSelectors: true,
33
34
  transformScoped: false
34
35
  },
@@ -1 +1 @@
1
- {"version":3,"file":"vueSfc.mjs","names":[],"sources":["../../src/plugin/vueSfc.ts"],"sourcesContent":["import type { NodePath } from '@babel/traverse'\nimport type { CallExpression } from '@babel/types'\nimport type { VueTransformResult } from 'wevu/compiler'\nimport type { ModuleMeta, ResolveWebAutoImportTag, ResolveWebModuleId, ScanState } from './types'\nimport { parse } from '@babel/parser'\nimport _babelTraverse from '@babel/traverse'\nimport * as t from '@babel/types'\nimport { fs } from '@weapp-core/shared/fs'\nimport { transform } from 'esbuild'\nimport MagicString from 'magic-string'\nimport path from 'pathe'\nimport { compileVueFile, isUniAppCompatibilityFile, transformUniAppSource } from 'wevu/compiler'\nimport { compileWxml } from '../compiler/wxml'\nimport { resolveScriptFile } from './files'\nimport { appendInlineQuery, resolveTemplatePathSync, resolveWxsPathSync, toRelativeImport } from './path'\n\nconst traverse = _babelTraverse\n\nasync function resolveSfcSrc(\n request: string,\n importer: string,\n srcRoot: string,\n resolveId?: ResolveWebModuleId,\n) {\n if (request.startsWith('@/')) {\n return path.resolve(srcRoot, request.slice(2))\n }\n if (request.startsWith('.')) {\n return path.resolve(path.dirname(importer), request)\n }\n if (request.startsWith('/')) {\n return path.resolve(srcRoot, request.slice(1))\n }\n return await resolveId?.(request, importer)\n}\n\nexport async function compileWebVueSfc(options: {\n source: string\n filename: string\n meta: ModuleMeta\n srcRoot: string\n state: ScanState\n resolveId?: ResolveWebModuleId\n resolveAutoImportTag?: ResolveWebAutoImportTag\n uniApp?: { include: string[] }\n}) {\n const { filename, meta, srcRoot, state, resolveId, resolveAutoImportTag, uniApp } = options\n const source = uniApp && isUniAppCompatibilityFile(filename, srcRoot, uniApp.include)\n ? transformUniAppSource(options.source, { filename, target: 'h5' }).code\n : options.source\n const result = await compileVueFile(source, filename, {\n isApp: meta.kind === 'app',\n isPage: meta.kind === 'page',\n sourceMap: false,\n style: {\n preserveDeepSelectors: true,\n transformScoped: false,\n },\n json: { kind: meta.kind },\n autoUsingComponents: {\n enabled: true,\n resolveUsingComponentPath: async (request, importer) => {\n const base = request.startsWith('@/')\n ? path.resolve(srcRoot, request.slice(2))\n : request.startsWith('.')\n ? path.resolve(path.dirname(importer), request)\n : request.startsWith('/')\n ? path.resolve(srcRoot, request.slice(1))\n : undefined\n if (!base) {\n return undefined\n }\n const resolvedId = await resolveScriptFile(base)\n if (!resolvedId) {\n return undefined\n }\n return {\n from: request,\n resolvedId,\n sourceType: resolvedId.endsWith('.vue') ? 'wevu-sfc' : 'native',\n }\n },\n },\n autoImportTags: {\n enabled: Boolean(resolveAutoImportTag),\n resolveUsingComponent: async (tag, importer) => resolveAutoImportTag?.(tag, importer),\n },\n sfcSrc: {\n resolveId: async (request, importer) => {\n return resolveSfcSrc(request, importer!, srcRoot, resolveId)\n },\n },\n })\n state.sfcResults.set(filename, result)\n for (const dependency of result.meta?.sfcSrcDeps ?? []) {\n state.templatePathSet.add(dependency)\n }\n return result\n}\n\nexport async function ensureWebVueSfcResult(options: {\n filename: string\n meta: ModuleMeta\n srcRoot: string\n state: ScanState\n source?: string\n resolveId?: ResolveWebModuleId\n resolveAutoImportTag?: ResolveWebAutoImportTag\n uniApp?: { include: string[] }\n}) {\n const cached = options.state.sfcResults.get(options.filename)\n if (cached) {\n return cached\n }\n const source = options.source ?? await fs.readFile(options.filename, 'utf8')\n return await compileWebVueSfc({ ...options, source })\n}\n\nfunction getSfcRegisterName(kind: ModuleMeta['kind']) {\n return kind === 'app' ? 'registerWebWevuApp' : 'registerWebWevuComponent'\n}\n\nfunction getSfcFactoryName(kind: ModuleMeta['kind']) {\n return kind === 'app' ? 'createApp' : 'createWevuComponent'\n}\n\nfunction createRegisterMetaCode(meta: ModuleMeta, templateIdent?: string, styleIdent?: string) {\n const parts = [`id: ${JSON.stringify(meta.id)}`, `kind: ${JSON.stringify(meta.kind)}`]\n if (templateIdent) {\n parts.push(`template: ${templateIdent}`)\n }\n if (styleIdent) {\n parts.push(`style: ${styleIdent}`)\n }\n if (meta.navigationBar) {\n parts.push(`navigationBar: ${JSON.stringify(meta.navigationBar)}`)\n }\n return `{ ${parts.join(', ')} }`\n}\n\nexport async function transformWebVueSfcScript(options: {\n code: string\n filename: string\n meta: ModuleMeta\n runtimeModuleId: string\n styleLanguage: string\n enableHmr: boolean\n hmrAcceptCode?: string\n}) {\n const { code, filename, meta, runtimeModuleId, styleLanguage, enableHmr, hmrAcceptCode } = options\n const ast = parse(code, {\n sourceType: 'module',\n plugins: ['typescript', 'jsx'],\n ranges: true,\n })\n const s = new MagicString(code)\n const templateIdent = meta.kind === 'app' ? undefined : '__weapp_sfc_template__'\n const styleIdent = meta.kind === 'app' ? undefined : '__weapp_sfc_style__'\n const registerName = getSfcRegisterName(meta.kind)\n const factoryName = getSfcFactoryName(meta.kind)\n const registerMetaCode = createRegisterMetaCode(meta, templateIdent, styleIdent)\n let transformed = false\n\n traverse(ast, {\n CallExpression(nodePath: NodePath<CallExpression>) {\n const callee = nodePath.node.callee\n if (!t.isIdentifier(callee, { name: factoryName })) {\n return\n }\n s.overwrite(callee.start!, callee.end!, registerName)\n s.appendLeft(nodePath.node.end! - 1, `, ${registerMetaCode}`)\n transformed = true\n },\n })\n\n if (!transformed) {\n throw new Error(`[@weapp-vite/web] Vue SFC 未生成 ${factoryName} 注册调用: ${filename}`)\n }\n\n const imports = [`import { ${registerName} } from '${runtimeModuleId}'`]\n if (templateIdent) {\n imports.push(`import ${templateIdent} from '${toRelativeImport(filename, filename)}?weapp-web-sfc-template'`)\n }\n if (styleIdent) {\n const styleFilename = `${filename}.${styleLanguage}`\n imports.push(`import ${styleIdent} from '${appendInlineQuery(`${toRelativeImport(filename, styleFilename)}?weapp-web-sfc-style`)}'`)\n }\n s.prepend(`${imports.join('\\n')}\\n`)\n if (enableHmr && hmrAcceptCode) {\n s.append(`\\n${hmrAcceptCode}\\n`)\n }\n const transpiled = await transform(s.toString(), {\n format: 'esm',\n legalComments: 'inline',\n loader: 'ts',\n sourcefile: filename,\n sourcemap: 'external',\n target: 'es2022',\n })\n return {\n code: transpiled.code,\n map: JSON.parse(transpiled.map),\n }\n}\n\nexport function generateWebVueSfcTemplate(\n result: VueTransformResult,\n meta: ModuleMeta,\n filename: string,\n srcRoot: string,\n) {\n const compiled = compileWxml({\n id: filename,\n source: result.template ?? '',\n navigationBar: meta.navigationBar ? { config: meta.navigationBar } : undefined,\n componentTags: meta.componentTags,\n resolveTemplatePath: (request, importer) => resolveTemplatePathSync(request, importer, srcRoot),\n resolveWxsPath: (request, importer) => resolveWxsPathSync(request, importer, srcRoot),\n })\n return compiled\n}\n\nexport function resolveWebVueSfcStyleLanguage(result: VueTransformResult, filename: string) {\n const languages = new Set(\n (result.meta?.styleBlocks ?? []).map(style => style.lang?.trim() || 'css'),\n )\n for (const language of languages) {\n if (!/^[a-z][a-z0-9-]*$/i.test(language)) {\n throw new Error(`[@weapp-vite/web] Vue SFC 样式语言无效: ${filename} -> ${language}`)\n }\n }\n const preprocessLanguages = [...languages].filter(language => language !== 'css')\n if (preprocessLanguages.length > 1) {\n throw new Error(`[@weapp-vite/web] Vue SFC 暂不支持混合样式语言: ${filename}`)\n }\n return preprocessLanguages[0] ?? 'css'\n}\n\nexport function generateWebVueSfcStyle(result: VueTransformResult) {\n return result.style ?? ''\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,MAAM,WAAW;AAEjB,eAAe,cACb,SACA,UACA,SACA,WACA;CACA,IAAI,QAAQ,WAAW,IAAI,GACzB,OAAO,KAAK,QAAQ,SAAS,QAAQ,MAAM,CAAC,CAAC;CAE/C,IAAI,QAAQ,WAAW,GAAG,GACxB,OAAO,KAAK,QAAQ,KAAK,QAAQ,QAAQ,GAAG,OAAO;CAErD,IAAI,QAAQ,WAAW,GAAG,GACxB,OAAO,KAAK,QAAQ,SAAS,QAAQ,MAAM,CAAC,CAAC;CAE/C,OAAO,MAAM,YAAY,SAAS,QAAQ;AAC5C;AAEA,eAAsB,iBAAiB,SASpC;CACD,MAAM,EAAE,UAAU,MAAM,SAAS,OAAO,WAAW,sBAAsB,WAAW;CACpF,MAAM,SAAS,UAAU,0BAA0B,UAAU,SAAS,OAAO,OAAO,IAChF,sBAAsB,QAAQ,QAAQ;EAAE;EAAU,QAAQ;CAAK,CAAC,CAAC,CAAC,OAClE,QAAQ;CACZ,MAAM,SAAS,MAAM,eAAe,QAAQ,UAAU;EACpD,OAAO,KAAK,SAAS;EACrB,QAAQ,KAAK,SAAS;EACtB,WAAW;EACX,OAAO;GACL,uBAAuB;GACvB,iBAAiB;EACnB;EACA,MAAM,EAAE,MAAM,KAAK,KAAK;EACxB,qBAAqB;GACnB,SAAS;GACT,2BAA2B,OAAO,SAAS,aAAa;IACtD,MAAM,OAAO,QAAQ,WAAW,IAAI,IAChC,KAAK,QAAQ,SAAS,QAAQ,MAAM,CAAC,CAAC,IACtC,QAAQ,WAAW,GAAG,IACpB,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A,EAAE,QAAQ,GAAG,QAAQ,KAAK,IAAI,EAAE,GAAG;CACnC,IAAI,aAAa,eACf,EAAE,OAAO,KAAK,cAAc,GAAG;CAEjC,MAAM,aAAa,MAAM,UAAU,EAAE,SAAS,GAAG;EAC/C,QAAQ;EACR,eAAe;EACf,QAAQ;EACR,YAAY;EACZ,WAAW;EACX,QAAQ;CACV,CAAC;CACD,OAAO;EACL,MAAM,WAAW;EACjB,KAAK,KAAK,MAAM,WAAW,GAAG;CAChC;AACF;AAEA,SAAgB,0BACd,QACA,MACA,UACA,SACA;CASA,OARiB,YAAY;EAC3B,IAAI;EACJ,QAAQ,OAAO,YAAY;EAC3B,eAAe,KAAK,gBAAgB,EAAE,QAAQ,KAAK,cAAc,IAAI;EACrE,eAAe,KAAK;EACpB,sBAAsB,SAAS,aAAa,wBAAwB,SAAS,UAAU,OAAO;EAC9F,iBAAiB,SAAS,aAAa,mBAAmB,SAAS,UAAU,OAAO;CACtF,CACc;AAChB;AAEA,SAAgB,8BAA8B,QAA4B,UAAkB;CAC1F,MAAM,YAAY,IAAI,KACnB,OAAO,MAAM,eAAe,CAAC,EAAC,CAAE,KAAI,UAAS,MAAM,MAAM,KAAK,KAAK,KAAK,CAC3E;CACA,KAAK,MAAM,YAAY,WACrB,IAAI,CAAC,qBAAqB,KAAK,QAAQ,GACrC,MAAM,IAAI,MAAM,qCAAqC,SAAS,MAAM,UAAU;CAGlF,MAAM,sBAAsB,CAAC,GAAG,SAAS,CAAC,CAAC,QAAO,aAAY,aAAa,KAAK;CAChF,IAAI,oBAAoB,SAAS,GAC/B,MAAM,IAAI,MAAM,yCAAyC,UAAU;CAErE,OAAO,oBAAoB,MAAM;AACnC;AAEA,SAAgB,uBAAuB,QAA4B;CACjE,OAAO,OAAO,SAAS;AACzB"}
1
+ {"version":3,"file":"vueSfc.mjs","names":[],"sources":["../../src/plugin/vueSfc.ts"],"sourcesContent":["import type { NodePath } from '@babel/traverse'\nimport type { CallExpression } from '@babel/types'\nimport type { VueTransformResult } from 'wevu/compiler'\nimport type { ModuleMeta, ResolveWebAutoImportTag, ResolveWebModuleId, ScanState, WebStylePreprocessOptions } from './types'\nimport { parse } from '@babel/parser'\nimport _babelTraverse from '@babel/traverse'\nimport * as t from '@babel/types'\nimport { fs } from '@weapp-core/shared/fs'\nimport { transform } from 'esbuild'\nimport MagicString from 'magic-string'\nimport path from 'pathe'\nimport { compileVueFile, isUniAppCompatibilityFile, transformUniAppSource } from 'wevu/compiler'\nimport { compileWxml } from '../compiler/wxml'\nimport { resolveScriptFile } from './files'\nimport { appendInlineQuery, resolveTemplatePathSync, resolveWxsPathSync, toRelativeImport } from './path'\n\nconst traverse = _babelTraverse\n\nasync function resolveSfcSrc(\n request: string,\n importer: string,\n srcRoot: string,\n resolveId?: ResolveWebModuleId,\n) {\n if (request.startsWith('@/')) {\n return path.resolve(srcRoot, request.slice(2))\n }\n if (request.startsWith('.')) {\n return path.resolve(path.dirname(importer), request)\n }\n if (request.startsWith('/')) {\n return path.resolve(srcRoot, request.slice(1))\n }\n return await resolveId?.(request, importer)\n}\n\nexport async function compileWebVueSfc(options: {\n source: string\n filename: string\n meta: ModuleMeta\n srcRoot: string\n state: ScanState\n resolveId?: ResolveWebModuleId\n resolveAutoImportTag?: ResolveWebAutoImportTag\n uniApp?: { include: string[] }\n stylePreprocessOptions?: WebStylePreprocessOptions\n}) {\n const { filename, meta, srcRoot, state, resolveId, resolveAutoImportTag, uniApp, stylePreprocessOptions } = options\n const source = uniApp && isUniAppCompatibilityFile(filename, srcRoot, uniApp.include)\n ? transformUniAppSource(options.source, { filename, target: 'h5' }).code\n : options.source\n const result = await compileVueFile(source, filename, {\n isApp: meta.kind === 'app',\n isPage: meta.kind === 'page',\n sourceMap: false,\n style: {\n preprocessOptions: stylePreprocessOptions,\n preserveDeepSelectors: true,\n transformScoped: false,\n },\n json: { kind: meta.kind },\n autoUsingComponents: {\n enabled: true,\n resolveUsingComponentPath: async (request, importer) => {\n const base = request.startsWith('@/')\n ? path.resolve(srcRoot, request.slice(2))\n : request.startsWith('.')\n ? path.resolve(path.dirname(importer), request)\n : request.startsWith('/')\n ? path.resolve(srcRoot, request.slice(1))\n : undefined\n if (!base) {\n return undefined\n }\n const resolvedId = await resolveScriptFile(base)\n if (!resolvedId) {\n return undefined\n }\n return {\n from: request,\n resolvedId,\n sourceType: resolvedId.endsWith('.vue') ? 'wevu-sfc' : 'native',\n }\n },\n },\n autoImportTags: {\n enabled: Boolean(resolveAutoImportTag),\n resolveUsingComponent: async (tag, importer) => resolveAutoImportTag?.(tag, importer),\n },\n sfcSrc: {\n resolveId: async (request, importer) => {\n return resolveSfcSrc(request, importer!, srcRoot, resolveId)\n },\n },\n })\n state.sfcResults.set(filename, result)\n for (const dependency of result.meta?.sfcSrcDeps ?? []) {\n state.templatePathSet.add(dependency)\n }\n return result\n}\n\nexport async function ensureWebVueSfcResult(options: {\n filename: string\n meta: ModuleMeta\n srcRoot: string\n state: ScanState\n source?: string\n resolveId?: ResolveWebModuleId\n resolveAutoImportTag?: ResolveWebAutoImportTag\n uniApp?: { include: string[] }\n stylePreprocessOptions?: WebStylePreprocessOptions\n}) {\n const cached = options.state.sfcResults.get(options.filename)\n if (cached) {\n return cached\n }\n const source = options.source ?? await fs.readFile(options.filename, 'utf8')\n return await compileWebVueSfc({ ...options, source })\n}\n\nfunction getSfcRegisterName(kind: ModuleMeta['kind']) {\n return kind === 'app' ? 'registerWebWevuApp' : 'registerWebWevuComponent'\n}\n\nfunction getSfcFactoryName(kind: ModuleMeta['kind']) {\n return kind === 'app' ? 'createApp' : 'createWevuComponent'\n}\n\nfunction createRegisterMetaCode(meta: ModuleMeta, templateIdent?: string, styleIdent?: string) {\n const parts = [`id: ${JSON.stringify(meta.id)}`, `kind: ${JSON.stringify(meta.kind)}`]\n if (templateIdent) {\n parts.push(`template: ${templateIdent}`)\n }\n if (styleIdent) {\n parts.push(`style: ${styleIdent}`)\n }\n if (meta.navigationBar) {\n parts.push(`navigationBar: ${JSON.stringify(meta.navigationBar)}`)\n }\n return `{ ${parts.join(', ')} }`\n}\n\nexport async function transformWebVueSfcScript(options: {\n code: string\n filename: string\n meta: ModuleMeta\n runtimeModuleId: string\n styleLanguage: string\n enableHmr: boolean\n hmrAcceptCode?: string\n}) {\n const { code, filename, meta, runtimeModuleId, styleLanguage, enableHmr, hmrAcceptCode } = options\n const ast = parse(code, {\n sourceType: 'module',\n plugins: ['typescript', 'jsx'],\n ranges: true,\n })\n const s = new MagicString(code)\n const templateIdent = meta.kind === 'app' ? undefined : '__weapp_sfc_template__'\n const styleIdent = meta.kind === 'app' ? undefined : '__weapp_sfc_style__'\n const registerName = getSfcRegisterName(meta.kind)\n const factoryName = getSfcFactoryName(meta.kind)\n const registerMetaCode = createRegisterMetaCode(meta, templateIdent, styleIdent)\n let transformed = false\n\n traverse(ast, {\n CallExpression(nodePath: NodePath<CallExpression>) {\n const callee = nodePath.node.callee\n if (!t.isIdentifier(callee, { name: factoryName })) {\n return\n }\n s.overwrite(callee.start!, callee.end!, registerName)\n s.appendLeft(nodePath.node.end! - 1, `, ${registerMetaCode}`)\n transformed = true\n },\n })\n\n if (!transformed) {\n throw new Error(`[@weapp-vite/web] Vue SFC 未生成 ${factoryName} 注册调用: ${filename}`)\n }\n\n const imports = [`import { ${registerName} } from '${runtimeModuleId}'`]\n if (templateIdent) {\n imports.push(`import ${templateIdent} from '${toRelativeImport(filename, filename)}?weapp-web-sfc-template'`)\n }\n if (styleIdent) {\n const styleFilename = `${filename}.${styleLanguage}`\n imports.push(`import ${styleIdent} from '${appendInlineQuery(`${toRelativeImport(filename, styleFilename)}?weapp-web-sfc-style`)}'`)\n }\n s.prepend(`${imports.join('\\n')}\\n`)\n if (enableHmr && hmrAcceptCode) {\n s.append(`\\n${hmrAcceptCode}\\n`)\n }\n const transpiled = await transform(s.toString(), {\n format: 'esm',\n legalComments: 'inline',\n loader: 'ts',\n sourcefile: filename,\n sourcemap: 'external',\n target: 'es2022',\n })\n return {\n code: transpiled.code,\n map: JSON.parse(transpiled.map),\n }\n}\n\nexport function generateWebVueSfcTemplate(\n result: VueTransformResult,\n meta: ModuleMeta,\n filename: string,\n srcRoot: string,\n) {\n const compiled = compileWxml({\n id: filename,\n source: result.template ?? '',\n navigationBar: meta.navigationBar ? { config: meta.navigationBar } : undefined,\n componentTags: meta.componentTags,\n resolveTemplatePath: (request, importer) => resolveTemplatePathSync(request, importer, srcRoot),\n resolveWxsPath: (request, importer) => resolveWxsPathSync(request, importer, srcRoot),\n })\n return compiled\n}\n\nexport function resolveWebVueSfcStyleLanguage(result: VueTransformResult, filename: string) {\n const languages = new Set(\n (result.meta?.styleBlocks ?? []).map(style => style.lang?.trim() || 'css'),\n )\n for (const language of languages) {\n if (!/^[a-z][a-z0-9-]*$/i.test(language)) {\n throw new Error(`[@weapp-vite/web] Vue SFC 样式语言无效: ${filename} -> ${language}`)\n }\n }\n const preprocessLanguages = [...languages].filter(language => language !== 'css')\n if (preprocessLanguages.length > 1) {\n throw new Error(`[@weapp-vite/web] Vue SFC 暂不支持混合样式语言: ${filename}`)\n }\n return preprocessLanguages[0] ?? 'css'\n}\n\nexport function generateWebVueSfcStyle(result: VueTransformResult) {\n return result.style ?? ''\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,MAAM,WAAW;AAEjB,eAAe,cACb,SACA,UACA,SACA,WACA;CACA,IAAI,QAAQ,WAAW,IAAI,GACzB,OAAO,KAAK,QAAQ,SAAS,QAAQ,MAAM,CAAC,CAAC;CAE/C,IAAI,QAAQ,WAAW,GAAG,GACxB,OAAO,KAAK,QAAQ,KAAK,QAAQ,QAAQ,GAAG,OAAO;CAErD,IAAI,QAAQ,WAAW,GAAG,GACxB,OAAO,KAAK,QAAQ,SAAS,QAAQ,MAAM,CAAC,CAAC;CAE/C,OAAO,MAAM,YAAY,SAAS,QAAQ;AAC5C;AAEA,eAAsB,iBAAiB,SAUpC;CACD,MAAM,EAAE,UAAU,MAAM,SAAS,OAAO,WAAW,sBAAsB,QAAQ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C,CAAE,KAAI,UAAS,MAAM,MAAM,KAAK,KAAK,KAAK,CAC3E;CACA,KAAK,MAAM,YAAY,WACrB,IAAI,CAAC,qBAAqB,KAAK,QAAQ,GACrC,MAAM,IAAI,MAAM,qCAAqC,SAAS,MAAM,UAAU;CAGlF,MAAM,sBAAsB,CAAC,GAAG,SAAS,CAAC,CAAC,QAAO,aAAY,aAAa,KAAK;CAChF,IAAI,oBAAoB,SAAS,GAC/B,MAAM,IAAI,MAAM,yCAAyC,UAAU;CAErE,OAAO,oBAAoB,MAAM;AACnC;AAEA,SAAgB,uBAAuB,QAA4B;CACjE,OAAO,OAAO,SAAS;AACzB"}
@@ -1,10 +1,11 @@
1
1
  import { supportsLit } from "./constants.mjs";
2
+ import { createComponentPublicInstance } from "./publicInstance.mjs";
3
+ import { createIntersectionObserverBridge } from "../polyfill/intersectionObserver.mjs";
2
4
  import { createRenderContext } from "../renderContext.mjs";
3
5
  import { hasOwn } from "../utils/object.mjs";
4
6
  import { createScopedSelectorQuery, resolveRenderRoot, selectRuntimeComponent, selectRuntimeComponents } from "./dom.mjs";
5
7
  import { bindRuntimeEvents } from "./events.mjs";
6
8
  import { runComponentObservers } from "./observers.mjs";
7
- import { createComponentPublicInstance } from "./publicInstance.mjs";
8
9
  import { resolveRelationNodes } from "./relations.mjs";
9
10
  import { createWebSlotsProxy } from "./slots.mjs";
10
11
  import { assignDataPath, cloneValue, coerceValue, parseDataPath, resolveDataPath, toCamelCase } from "./utils.mjs";
@@ -104,6 +105,9 @@ function createComponentElementClass({ BaseElement, runtimeState, instances }) {
104
105
  createSelectorQuery() {
105
106
  return createScopedSelectorQuery(this);
106
107
  }
108
+ createIntersectionObserver(options) {
109
+ return createIntersectionObserverBridge(this, options);
110
+ }
107
111
  selectComponent(selector) {
108
112
  return selectRuntimeComponent(this, selector);
109
113
  }
@@ -1 +1 @@
1
- {"version":3,"file":"element.mjs","names":["#properties","#state","#publicInstance","#methods","#setProperty","#syncMethods","#applyDataPatch","#applyAttributes","#runInitialObservers","#isMounted","#renderLegacy","#readyFired","#syncVirtualHostClasses","#usesLegacyTemplate","#renderContext","#observedKeys","#observerInitDone","#exposedMethodNames","#virtualHostClassTokens","#virtualHostRootElement","#virtualHostPartTokens"],"sources":["../../../src/runtime/component/element.ts"],"sourcesContent":["import type {\n CreateComponentElementClassOptions,\n WeappComponentInstance,\n} from './elementTypes'\nimport type {\n ComponentOptions,\n ComponentPublicInstance,\n DataRecord,\n PageLifeTimeHooks,\n TriggerEventOptions,\n} from './types'\nimport type { ClassAttributeElement } from './virtualHost'\nimport { html } from 'lit'\nimport { unsafeHTML } from 'lit/directives/unsafe-html.js'\nimport { createRenderContext } from '../renderContext'\nimport { hasOwn } from '../utils/object'\nimport { supportsLit } from './constants'\nimport {\n createScopedSelectorQuery,\n resolveRenderRoot,\n selectRuntimeComponent,\n selectRuntimeComponents,\n} from './dom'\nimport { bindRuntimeEvents } from './events'\nimport { runComponentObservers } from './observers'\nimport { createComponentPublicInstance } from './publicInstance'\nimport { resolveRelationNodes } from './relations'\nimport { createWebSlotsProxy } from './slots'\nimport { assignDataPath, cloneValue, coerceValue, parseDataPath, resolveDataPath, toCamelCase } from './utils'\nimport {\n clearVirtualHostClasses,\n clearVirtualHostParts,\n syncVirtualHostClasses,\n syncVirtualHostParts,\n} from './virtualHost'\n\nexport type { WeappComponentInstance } from './elementTypes'\nexport type WeappComponentElementClass = typeof HTMLElement & {\n new (): WeappComponentInstance\n}\n\nfunction resolveComposedParent(node: Node): Node | undefined {\n const assignedSlot = (node as Element).assignedSlot\n if (assignedSlot) {\n return assignedSlot\n }\n if (node.parentNode) {\n return node.parentNode\n }\n const root = node.getRootNode?.()\n return root instanceof ShadowRoot ? root.host : undefined\n}\n\nfunction isWeappComponentInstance(value: unknown): value is WeappComponentInstance {\n return Boolean(\n value\n && typeof value === 'object'\n && typeof (value as WeappComponentInstance).__weappSync === 'function',\n )\n}\n\nexport function createComponentElementClass({\n BaseElement,\n runtimeState,\n instances,\n}: CreateComponentElementClassOptions): WeappComponentElementClass {\n const RuntimeBaseElement = BaseElement as typeof HTMLElement & {\n readonly observedAttributes?: string[]\n }\n class WeappWebComponent extends RuntimeBaseElement implements WeappComponentInstance {\n static get observedAttributes() {\n const inherited = super.observedAttributes ?? []\n return Array.from(new Set([...inherited, ...runtimeState.observedAttributes]))\n }\n\n #state: DataRecord\n #properties: DataRecord\n #methods: Record<string, (event: any) => any> = {}\n #publicInstance: ComponentPublicInstance\n #exposedMethodNames = new Set<string>()\n #isMounted = false\n #renderContext = createRenderContext(this, {})\n #usesLegacyTemplate = false\n #readyFired = false\n #observerInitDone = false\n #observedKeys = new Set<string>()\n #virtualHostClassTokens = new Set<string>()\n #virtualHostPartTokens = new Set<string>()\n #virtualHostRootElement: ClassAttributeElement | undefined\n readonly data!: DataRecord\n readonly properties!: DataRecord\n\n constructor() {\n super()\n const dataOption = runtimeState.componentRef.data ?? {}\n this.#properties = { ...runtimeState.defaultPropertyValues }\n this.#state = { ...cloneValue(this.#properties), ...cloneValue(dataOption) }\n Object.defineProperty(this.#state, '$slots', {\n configurable: true,\n enumerable: true,\n value: createWebSlotsProxy(() => this.#state.vueSlots),\n })\n Object.defineProperties(this, {\n data: {\n configurable: true,\n enumerable: true,\n get: () => this.#state,\n },\n properties: {\n configurable: true,\n enumerable: true,\n get: () => this.#properties,\n },\n })\n this.#publicInstance = createComponentPublicInstance(\n this,\n WeappWebComponent.prototype,\n key => typeof key === 'string' ? this.#methods[key] : undefined,\n )\n for (const [propName] of runtimeState.propertyEntries) {\n Object.defineProperty(this, propName, {\n configurable: true,\n enumerable: true,\n get: () => this.#state[propName],\n set: value => this.#setProperty(propName, value),\n })\n }\n this.#syncMethods(runtimeState.componentRef.methods ?? {})\n if (!supportsLit) {\n const host = this as unknown as HTMLElement\n if (!host.shadowRoot && typeof host.attachShadow === 'function') {\n host.attachShadow({ mode: 'open' })\n }\n ;(this as any).renderRoot = host.shadowRoot ?? host\n }\n instances.add(this)\n runtimeState.lifetimes.created?.call(this.#publicInstance)\n }\n\n setData(patch: DataRecord, callback?: () => void) {\n const changed = this.#applyDataPatch(patch)\n if (supportsLit && changed) {\n const updateComplete = (this as unknown as { updateComplete: Promise<boolean> }).updateComplete\n return updateComplete.then(() => {\n callback?.()\n })\n }\n callback?.()\n }\n\n triggerEvent(name: string, detail?: any, options: TriggerEventOptions = {}) {\n this.dispatchEvent(new CustomEvent(name, {\n detail,\n bubbles: options.bubbles ?? false,\n composed: options.composed ?? false,\n }))\n }\n\n createSelectorQuery() {\n return createScopedSelectorQuery(this)\n }\n\n selectComponent(selector: string) {\n return selectRuntimeComponent(this, selector)\n }\n\n selectAllComponents(selector: string) {\n return selectRuntimeComponents(this, selector)\n }\n\n getRelationNodes(relationPath: string) {\n const relation = runtimeState.componentRef.relations?.[relationPath]\n return relation\n ? resolveRelationNodes(this, runtimeState.id, relationPath, relation.type)\n : []\n }\n\n selectOwnerComponent() {\n let current = resolveComposedParent(this)\n while (current) {\n if (isWeappComponentInstance(current)) {\n return current\n }\n current = resolveComposedParent(current)\n }\n return undefined\n }\n\n connectedCallback() {\n const superConnected = (BaseElement.prototype as { connectedCallback?: () => void }).connectedCallback\n if (supportsLit && typeof superConnected === 'function') {\n superConnected.call(this)\n }\n this.#applyAttributes()\n if (runtimeState.observerInitEnabled) {\n this.#runInitialObservers()\n }\n runtimeState.lifetimes.attached?.call(this.#publicInstance)\n this.#isMounted = true\n if (!supportsLit) {\n this.#renderLegacy()\n }\n }\n\n disconnectedCallback() {\n const superDisconnected = (BaseElement.prototype as { disconnectedCallback?: () => void }).disconnectedCallback\n if (supportsLit && typeof superDisconnected === 'function') {\n superDisconnected.call(this)\n }\n this.#isMounted = false\n instances.delete(this)\n runtimeState.lifetimes.detached?.call(this.#publicInstance)\n }\n\n attributeChangedCallback(attrName: string, oldValue: string | null, newValue: string | null) {\n const superAttributeChanged = (BaseElement.prototype as {\n attributeChangedCallback?: (name: string, oldValue: string | null, newValue: string | null) => void\n }).attributeChangedCallback\n if (supportsLit && typeof superAttributeChanged === 'function') {\n superAttributeChanged.call(this, attrName, oldValue, newValue)\n }\n const propName = toCamelCase(attrName)\n if (!hasOwn(this.#properties, propName)) {\n return\n }\n const propOption = runtimeState.componentRef.properties?.[propName]\n this.#setProperty(propName, coerceValue(newValue, propOption?.type))\n }\n\n firstUpdated() {\n runtimeState.lifetimes.ready?.call(this.#publicInstance)\n this.#readyFired = true\n }\n\n updated() {\n this.#syncVirtualHostClasses()\n if (this.#usesLegacyTemplate) {\n bindRuntimeEvents(resolveRenderRoot(this), this.#methods, this)\n }\n }\n\n render() {\n const result = runtimeState.templateRef(this.#state, this.#renderContext)\n const styleMarkup = runtimeState.styleRef\n ? html`<style>${runtimeState.styleRef}</style>`\n : null\n if (typeof result === 'string') {\n this.#usesLegacyTemplate = true\n return html`${styleMarkup}${unsafeHTML(result)}`\n }\n this.#usesLegacyTemplate = false\n if (styleMarkup) {\n return html`${styleMarkup}${result as any}`\n }\n return result\n }\n\n requestUpdate(name?: PropertyKey, oldValue?: unknown, options?: unknown) {\n const superRequestUpdate = (BaseElement.prototype as any).requestUpdate\n if (supportsLit && typeof superRequestUpdate === 'function') {\n return superRequestUpdate.call(this, name, oldValue, options)\n }\n if (this.#isMounted) {\n this.#renderLegacy()\n }\n return undefined\n }\n\n #applyAttributes() {\n if (!this.attributes || typeof this.attributes[Symbol.iterator] !== 'function') {\n return\n }\n for (const attr of this.attributes) {\n this.attributeChangedCallback(attr.name, null, attr.value)\n }\n }\n\n #applyDataPatch(patch: DataRecord) {\n if (!patch || typeof patch !== 'object') {\n return false\n }\n let changed = false\n const changedKeys: string[] = []\n const previousProperties: DataRecord = {}\n for (const [path, value] of Object.entries(patch)) {\n const segments = parseDataPath(path)\n const topKey = segments[0]\n if (!topKey || Object.is(resolveDataPath(this.#state, segments), value)) {\n continue\n }\n if (hasOwn(this.#properties, topKey) && !hasOwn(previousProperties, topKey)) {\n previousProperties[topKey] = this.#properties[topKey]\n }\n assignDataPath(this.#state, segments, value)\n if (hasOwn(this.#properties, topKey)) {\n this.#properties[topKey] = this.#state[topKey]\n }\n changedKeys.push(path)\n changed = true\n }\n if (changed) {\n this.requestUpdate()\n runComponentObservers(runtimeState.componentRef, this.#publicInstance, changedKeys, previousProperties)\n for (const key of changedKeys) {\n if (runtimeState.componentRef.properties?.[key]?.observer) {\n this.#observedKeys.add(key)\n }\n }\n }\n return changed\n }\n\n #setProperty(name: string, value: any) {\n const propOption = runtimeState.componentRef.properties?.[name]\n const coerced = coerceValue(value, propOption?.type)\n const oldValue = this.#properties[name]\n if (oldValue === coerced) {\n return\n }\n this.#properties[name] = coerced\n this.#state[name] = coerced\n if (this.#isMounted) {\n this.requestUpdate()\n }\n runComponentObservers(runtimeState.componentRef, this.#publicInstance, [name], { [name]: oldValue })\n if (propOption?.observer) {\n this.#observedKeys.add(name)\n }\n }\n\n #runInitialObservers() {\n if (this.#observerInitDone) {\n return\n }\n this.#observerInitDone = true\n for (const [propName, propOption] of runtimeState.propertyEntries) {\n if (!propOption.observer || this.#observedKeys.has(propName)) {\n continue\n }\n const value = this.#state[propName]\n propOption.observer.call(this.#publicInstance, value, undefined)\n this.#observedKeys.add(propName)\n }\n }\n\n #syncMethods(nextMethods: ComponentOptions['methods']) {\n const resolved = nextMethods ?? {}\n const bound: Record<string, (event: any) => any> = {}\n for (const [name, fn] of Object.entries(resolved)) {\n if (typeof fn === 'function') {\n bound[name] = fn.bind(this.#publicInstance)\n }\n }\n for (const name of this.#exposedMethodNames) {\n if (name in bound) {\n continue\n }\n const descriptor = Object.getOwnPropertyDescriptor(this, name)\n if (descriptor?.configurable && descriptor.value === this.#methods[name]) {\n delete (this as unknown as Record<string, unknown>)[name]\n }\n this.#exposedMethodNames.delete(name)\n }\n for (const key of Object.keys(this.#methods)) {\n if (!(key in bound)) {\n delete this.#methods[key]\n }\n }\n for (const [key, fn] of Object.entries(bound)) {\n this.#methods[key] = fn\n if (!this.#exposedMethodNames.has(key) && key in this) {\n continue\n }\n Object.defineProperty(this, key, {\n configurable: true,\n enumerable: false,\n writable: true,\n value: fn,\n })\n this.#exposedMethodNames.add(key)\n }\n this.#renderContext = createRenderContext(this, this.#methods)\n }\n\n __weappSync(nextMethods: ComponentOptions['methods']) {\n this.#syncMethods(nextMethods)\n this.requestUpdate()\n }\n\n __weappInvokePageLifetime(type: keyof PageLifeTimeHooks) {\n const hook = runtimeState.pageLifetimes[type]\n if (typeof hook === 'function') {\n hook.call(this.#publicInstance)\n }\n }\n\n #renderLegacy() {\n const result = runtimeState.templateRef(this.#state, this.#renderContext)\n const root = resolveRenderRoot(this)\n const styleMarkup = runtimeState.styleRef ? `<style>${runtimeState.styleRef}</style>` : ''\n if (typeof result === 'string') {\n root.innerHTML = `${styleMarkup}${result}`\n bindRuntimeEvents(root as ShadowRoot, this.#methods, this)\n }\n else if (result == null) {\n root.innerHTML = styleMarkup\n }\n else {\n root.innerHTML = `${styleMarkup}${String(result)}`\n }\n this.#syncVirtualHostClasses()\n if (!this.#readyFired) {\n runtimeState.lifetimes.ready?.call(this.#publicInstance)\n this.#readyFired = true\n }\n }\n\n #syncVirtualHostClasses() {\n const host = this as unknown as ClassAttributeElement\n if (!runtimeState.componentRef.options?.virtualHost) {\n clearVirtualHostClasses(host, this.#virtualHostClassTokens)\n clearVirtualHostParts(this.#virtualHostRootElement, this.#virtualHostPartTokens)\n this.#virtualHostRootElement = undefined\n return\n }\n const root = resolveRenderRoot(this)\n syncVirtualHostClasses(host, root, this.#virtualHostClassTokens)\n this.#virtualHostRootElement = syncVirtualHostParts(\n root,\n this.#virtualHostRootElement,\n this.#virtualHostPartTokens,\n )\n }\n }\n\n return WeappWebComponent as WeappComponentElementClass\n}\n"],"mappings":";;;;;;;;;;;;;;;AAyCA,SAAS,sBAAsB,MAA8B;CAC3D,MAAM,eAAgB,KAAiB;CACvC,IAAI,cACF,OAAO;CAET,IAAI,KAAK,YACP,OAAO,KAAK;CAEd,MAAM,OAAO,KAAK,cAAc;CAChC,OAAO,gB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,MAAM,MAAM,KAAKD,uBAAuB;GAC/D,KAAKC,0BAA0B,qBAC7B,MACA,KAAKA,yBACL,KAAKC,sBACP;EACF;CACF;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"element.mjs","names":["#properties","#state","#publicInstance","#methods","#setProperty","#syncMethods","#applyDataPatch","#applyAttributes","#runInitialObservers","#isMounted","#renderLegacy","#readyFired","#syncVirtualHostClasses","#usesLegacyTemplate","#renderContext","#observedKeys","#observerInitDone","#exposedMethodNames","#virtualHostClassTokens","#virtualHostRootElement","#virtualHostPartTokens"],"sources":["../../../src/runtime/component/element.ts"],"sourcesContent":["import type {\n CreateComponentElementClassOptions,\n WeappComponentInstance,\n} from './elementTypes'\nimport type {\n ComponentOptions,\n ComponentPublicInstance,\n DataRecord,\n PageLifeTimeHooks,\n TriggerEventOptions,\n} from './types'\nimport type { ClassAttributeElement } from './virtualHost'\nimport { html } from 'lit'\nimport { unsafeHTML } from 'lit/directives/unsafe-html.js'\nimport { createIntersectionObserverBridge } from '../polyfill/intersectionObserver'\nimport { createRenderContext } from '../renderContext'\nimport { hasOwn } from '../utils/object'\nimport { supportsLit } from './constants'\nimport {\n createScopedSelectorQuery,\n resolveRenderRoot,\n selectRuntimeComponent,\n selectRuntimeComponents,\n} from './dom'\nimport { bindRuntimeEvents } from './events'\nimport { runComponentObservers } from './observers'\nimport { createComponentPublicInstance } from './publicInstance'\nimport { resolveRelationNodes } from './relations'\nimport { createWebSlotsProxy } from './slots'\nimport { assignDataPath, cloneValue, coerceValue, parseDataPath, resolveDataPath, toCamelCase } from './utils'\nimport {\n clearVirtualHostClasses,\n clearVirtualHostParts,\n syncVirtualHostClasses,\n syncVirtualHostParts,\n} from './virtualHost'\n\nexport type { WeappComponentInstance } from './elementTypes'\nexport type WeappComponentElementClass = typeof HTMLElement & {\n new (): WeappComponentInstance\n}\n\nfunction resolveComposedParent(node: Node): Node | undefined {\n const assignedSlot = (node as Element).assignedSlot\n if (assignedSlot) {\n return assignedSlot\n }\n if (node.parentNode) {\n return node.parentNode\n }\n const root = node.getRootNode?.()\n return root instanceof ShadowRoot ? root.host : undefined\n}\n\nfunction isWeappComponentInstance(value: unknown): value is WeappComponentInstance {\n return Boolean(\n value\n && typeof value === 'object'\n && typeof (value as WeappComponentInstance).__weappSync === 'function',\n )\n}\n\nexport function createComponentElementClass({\n BaseElement,\n runtimeState,\n instances,\n}: CreateComponentElementClassOptions): WeappComponentElementClass {\n const RuntimeBaseElement = BaseElement as typeof HTMLElement & {\n readonly observedAttributes?: string[]\n }\n class WeappWebComponent extends RuntimeBaseElement implements WeappComponentInstance {\n static get observedAttributes() {\n const inherited = super.observedAttributes ?? []\n return Array.from(new Set([...inherited, ...runtimeState.observedAttributes]))\n }\n\n #state: DataRecord\n #properties: DataRecord\n #methods: Record<string, (event: any) => any> = {}\n #publicInstance: ComponentPublicInstance\n #exposedMethodNames = new Set<string>()\n #isMounted = false\n #renderContext = createRenderContext(this, {})\n #usesLegacyTemplate = false\n #readyFired = false\n #observerInitDone = false\n #observedKeys = new Set<string>()\n #virtualHostClassTokens = new Set<string>()\n #virtualHostPartTokens = new Set<string>()\n #virtualHostRootElement: ClassAttributeElement | undefined\n readonly data!: DataRecord\n readonly properties!: DataRecord\n\n constructor() {\n super()\n const dataOption = runtimeState.componentRef.data ?? {}\n this.#properties = { ...runtimeState.defaultPropertyValues }\n this.#state = { ...cloneValue(this.#properties), ...cloneValue(dataOption) }\n Object.defineProperty(this.#state, '$slots', {\n configurable: true,\n enumerable: true,\n value: createWebSlotsProxy(() => this.#state.vueSlots),\n })\n Object.defineProperties(this, {\n data: {\n configurable: true,\n enumerable: true,\n get: () => this.#state,\n },\n properties: {\n configurable: true,\n enumerable: true,\n get: () => this.#properties,\n },\n })\n this.#publicInstance = createComponentPublicInstance(\n this,\n WeappWebComponent.prototype,\n key => typeof key === 'string' ? this.#methods[key] : undefined,\n )\n for (const [propName] of runtimeState.propertyEntries) {\n Object.defineProperty(this, propName, {\n configurable: true,\n enumerable: true,\n get: () => this.#state[propName],\n set: value => this.#setProperty(propName, value),\n })\n }\n this.#syncMethods(runtimeState.componentRef.methods ?? {})\n if (!supportsLit) {\n const host = this as unknown as HTMLElement\n if (!host.shadowRoot && typeof host.attachShadow === 'function') {\n host.attachShadow({ mode: 'open' })\n }\n ;(this as any).renderRoot = host.shadowRoot ?? host\n }\n instances.add(this)\n runtimeState.lifetimes.created?.call(this.#publicInstance)\n }\n\n setData(patch: DataRecord, callback?: () => void) {\n const changed = this.#applyDataPatch(patch)\n if (supportsLit && changed) {\n const updateComplete = (this as unknown as { updateComplete: Promise<boolean> }).updateComplete\n return updateComplete.then(() => {\n callback?.()\n })\n }\n callback?.()\n }\n\n triggerEvent(name: string, detail?: any, options: TriggerEventOptions = {}) {\n this.dispatchEvent(new CustomEvent(name, {\n detail,\n bubbles: options.bubbles ?? false,\n composed: options.composed ?? false,\n }))\n }\n\n createSelectorQuery() {\n return createScopedSelectorQuery(this)\n }\n\n createIntersectionObserver(options?: {\n initialRatio?: number\n observeAll?: boolean\n thresholds?: number[]\n }) {\n return createIntersectionObserverBridge(this, options)\n }\n\n selectComponent(selector: string) {\n return selectRuntimeComponent(this, selector)\n }\n\n selectAllComponents(selector: string) {\n return selectRuntimeComponents(this, selector)\n }\n\n getRelationNodes(relationPath: string) {\n const relation = runtimeState.componentRef.relations?.[relationPath]\n return relation\n ? resolveRelationNodes(this, runtimeState.id, relationPath, relation.type)\n : []\n }\n\n selectOwnerComponent() {\n let current = resolveComposedParent(this)\n while (current) {\n if (isWeappComponentInstance(current)) {\n return current\n }\n current = resolveComposedParent(current)\n }\n return undefined\n }\n\n connectedCallback() {\n const superConnected = (BaseElement.prototype as { connectedCallback?: () => void }).connectedCallback\n if (supportsLit && typeof superConnected === 'function') {\n superConnected.call(this)\n }\n this.#applyAttributes()\n if (runtimeState.observerInitEnabled) {\n this.#runInitialObservers()\n }\n runtimeState.lifetimes.attached?.call(this.#publicInstance)\n this.#isMounted = true\n if (!supportsLit) {\n this.#renderLegacy()\n }\n }\n\n disconnectedCallback() {\n const superDisconnected = (BaseElement.prototype as { disconnectedCallback?: () => void }).disconnectedCallback\n if (supportsLit && typeof superDisconnected === 'function') {\n superDisconnected.call(this)\n }\n this.#isMounted = false\n instances.delete(this)\n runtimeState.lifetimes.detached?.call(this.#publicInstance)\n }\n\n attributeChangedCallback(attrName: string, oldValue: string | null, newValue: string | null) {\n const superAttributeChanged = (BaseElement.prototype as {\n attributeChangedCallback?: (name: string, oldValue: string | null, newValue: string | null) => void\n }).attributeChangedCallback\n if (supportsLit && typeof superAttributeChanged === 'function') {\n superAttributeChanged.call(this, attrName, oldValue, newValue)\n }\n const propName = toCamelCase(attrName)\n if (!hasOwn(this.#properties, propName)) {\n return\n }\n const propOption = runtimeState.componentRef.properties?.[propName]\n this.#setProperty(propName, coerceValue(newValue, propOption?.type))\n }\n\n firstUpdated() {\n runtimeState.lifetimes.ready?.call(this.#publicInstance)\n this.#readyFired = true\n }\n\n updated() {\n this.#syncVirtualHostClasses()\n if (this.#usesLegacyTemplate) {\n bindRuntimeEvents(resolveRenderRoot(this), this.#methods, this)\n }\n }\n\n render() {\n const result = runtimeState.templateRef(this.#state, this.#renderContext)\n const styleMarkup = runtimeState.styleRef\n ? html`<style>${runtimeState.styleRef}</style>`\n : null\n if (typeof result === 'string') {\n this.#usesLegacyTemplate = true\n return html`${styleMarkup}${unsafeHTML(result)}`\n }\n this.#usesLegacyTemplate = false\n if (styleMarkup) {\n return html`${styleMarkup}${result as any}`\n }\n return result\n }\n\n requestUpdate(name?: PropertyKey, oldValue?: unknown, options?: unknown) {\n const superRequestUpdate = (BaseElement.prototype as any).requestUpdate\n if (supportsLit && typeof superRequestUpdate === 'function') {\n return superRequestUpdate.call(this, name, oldValue, options)\n }\n if (this.#isMounted) {\n this.#renderLegacy()\n }\n return undefined\n }\n\n #applyAttributes() {\n if (!this.attributes || typeof this.attributes[Symbol.iterator] !== 'function') {\n return\n }\n for (const attr of this.attributes) {\n this.attributeChangedCallback(attr.name, null, attr.value)\n }\n }\n\n #applyDataPatch(patch: DataRecord) {\n if (!patch || typeof patch !== 'object') {\n return false\n }\n let changed = false\n const changedKeys: string[] = []\n const previousProperties: DataRecord = {}\n for (const [path, value] of Object.entries(patch)) {\n const segments = parseDataPath(path)\n const topKey = segments[0]\n if (!topKey || Object.is(resolveDataPath(this.#state, segments), value)) {\n continue\n }\n if (hasOwn(this.#properties, topKey) && !hasOwn(previousProperties, topKey)) {\n previousProperties[topKey] = this.#properties[topKey]\n }\n assignDataPath(this.#state, segments, value)\n if (hasOwn(this.#properties, topKey)) {\n this.#properties[topKey] = this.#state[topKey]\n }\n changedKeys.push(path)\n changed = true\n }\n if (changed) {\n this.requestUpdate()\n runComponentObservers(runtimeState.componentRef, this.#publicInstance, changedKeys, previousProperties)\n for (const key of changedKeys) {\n if (runtimeState.componentRef.properties?.[key]?.observer) {\n this.#observedKeys.add(key)\n }\n }\n }\n return changed\n }\n\n #setProperty(name: string, value: any) {\n const propOption = runtimeState.componentRef.properties?.[name]\n const coerced = coerceValue(value, propOption?.type)\n const oldValue = this.#properties[name]\n if (oldValue === coerced) {\n return\n }\n this.#properties[name] = coerced\n this.#state[name] = coerced\n if (this.#isMounted) {\n this.requestUpdate()\n }\n runComponentObservers(runtimeState.componentRef, this.#publicInstance, [name], { [name]: oldValue })\n if (propOption?.observer) {\n this.#observedKeys.add(name)\n }\n }\n\n #runInitialObservers() {\n if (this.#observerInitDone) {\n return\n }\n this.#observerInitDone = true\n for (const [propName, propOption] of runtimeState.propertyEntries) {\n if (!propOption.observer || this.#observedKeys.has(propName)) {\n continue\n }\n const value = this.#state[propName]\n propOption.observer.call(this.#publicInstance, value, undefined)\n this.#observedKeys.add(propName)\n }\n }\n\n #syncMethods(nextMethods: ComponentOptions['methods']) {\n const resolved = nextMethods ?? {}\n const bound: Record<string, (event: any) => any> = {}\n for (const [name, fn] of Object.entries(resolved)) {\n if (typeof fn === 'function') {\n bound[name] = fn.bind(this.#publicInstance)\n }\n }\n for (const name of this.#exposedMethodNames) {\n if (name in bound) {\n continue\n }\n const descriptor = Object.getOwnPropertyDescriptor(this, name)\n if (descriptor?.configurable && descriptor.value === this.#methods[name]) {\n delete (this as unknown as Record<string, unknown>)[name]\n }\n this.#exposedMethodNames.delete(name)\n }\n for (const key of Object.keys(this.#methods)) {\n if (!(key in bound)) {\n delete this.#methods[key]\n }\n }\n for (const [key, fn] of Object.entries(bound)) {\n this.#methods[key] = fn\n if (!this.#exposedMethodNames.has(key) && key in this) {\n continue\n }\n Object.defineProperty(this, key, {\n configurable: true,\n enumerable: false,\n writable: true,\n value: fn,\n })\n this.#exposedMethodNames.add(key)\n }\n this.#renderContext = createRenderContext(this, this.#methods)\n }\n\n __weappSync(nextMethods: ComponentOptions['methods']) {\n this.#syncMethods(nextMethods)\n this.requestUpdate()\n }\n\n __weappInvokePageLifetime(type: keyof PageLifeTimeHooks) {\n const hook = runtimeState.pageLifetimes[type]\n if (typeof hook === 'function') {\n hook.call(this.#publicInstance)\n }\n }\n\n #renderLegacy() {\n const result = runtimeState.templateRef(this.#state, this.#renderContext)\n const root = resolveRenderRoot(this)\n const styleMarkup = runtimeState.styleRef ? `<style>${runtimeState.styleRef}</style>` : ''\n if (typeof result === 'string') {\n root.innerHTML = `${styleMarkup}${result}`\n bindRuntimeEvents(root as ShadowRoot, this.#methods, this)\n }\n else if (result == null) {\n root.innerHTML = styleMarkup\n }\n else {\n root.innerHTML = `${styleMarkup}${String(result)}`\n }\n this.#syncVirtualHostClasses()\n if (!this.#readyFired) {\n runtimeState.lifetimes.ready?.call(this.#publicInstance)\n this.#readyFired = true\n }\n }\n\n #syncVirtualHostClasses() {\n const host = this as unknown as ClassAttributeElement\n if (!runtimeState.componentRef.options?.virtualHost) {\n clearVirtualHostClasses(host, this.#virtualHostClassTokens)\n clearVirtualHostParts(this.#virtualHostRootElement, this.#virtualHostPartTokens)\n this.#virtualHostRootElement = undefined\n return\n }\n const root = resolveRenderRoot(this)\n syncVirtualHostClasses(host, root, this.#virtualHostClassTokens)\n this.#virtualHostRootElement = syncVirtualHostParts(\n root,\n this.#virtualHostRootElement,\n this.#virtualHostPartTokens,\n )\n }\n }\n\n return WeappWebComponent as WeappComponentElementClass\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA0CA,SAAS,sBAAsB,MAA8B;CAC3D,MAAM,eAAgB,KAAiB;CACvC,IAAI,cACF,OAAO;CAET,IAAI,KAAK,YACP,OAAO,KAAK;CAEd,MAAM,OAAO,KAAK,cAAc;CAChC,OAAO,gBAAgB,aAAa,KAAK,OAAO;AAClD;AAEA,SAAS,yBAAyB,OAAiD;CACjF,OAAO,QACL,SACG,OAAO,UAAU,YACjB,OAAQ,MAAiC,gBAAgB,UAC9D;AACF;AAEA,SAAgB,4BAA4B,EAC1C,aACA,cACA,aACiE;CACjE,MAAM,qBAAqB;CAG3B,MAAM,0BAA0B,mBAAqD;EACnF,WAAW,qBAAqB;GAC9B,MAAM,YAAY,MAAM,sBAAsB,CAAC;GAC/C,OAAO,MAAM,qBAAK,IAAI,IAAI,CAAC,GAAG,WAAW,GAAG,aAAa,kBAAkB,CAAC,CAAC;EAC/E;EAEA;EACA;EACA,WAAgD,CAAC;EACjD;EACA,sCAAsB,IAAI,IAAY;EACtC,aAAa;EACb,iBAAiB,oBAAoB,MAAM,CAAC,CAAC;EAC7C,sBAAsB;EACtB,cAAc;EACd,oBAAoB;EACpB,gCAAgB,IAAI,IAAY;EAChC,0CAA0B,IAAI,IAAY;EAC1C,yCAAyB,IAAI,IAAY;EACzC;EACA,AAAS;EACT,AAAS;EAET,cAAc;GACZ,MAAM;GACN,MAAM,aAAa,aAAa,aAAa,QAAQ,CAAC;GACtD,KAAKA,cAAc,EAAE,GAAG,aAAa,sBAAsB;GAC3D,KAAKC,SAAS;IAAE,GAAG,WAAW,KAAKD,WAAW;IAAG,GAAG,WAAW,UAAU;GAAE;GAC3E,OAAO,eAAe,KAAKC,QAAQ,UAAU;IAC3C,cAAc;IACd,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,YAAY,GAAG,cAAc,OAAO,MAAM;GAEjD,KAAKS,wBAAwB;GAC7B,IAAI,CAAC,KAAKD,aAAa;IACrB,aAAa,UAAU,OAAO,KAAK,KAAKT,eAAe;IACvD,KAAKS,cAAc;GACrB;EACF;EAEA,0BAA0B;GACxB,MAAM,OAAO;GACb,IAAI,CAAC,aAAa,aAAa,SAAS,aAAa;IACnD,wBAAwB,MAAM,KAAKO,uBAAuB;IAC1D,sBAAsB,KAAKC,yBAAyB,KAAKC,sBAAsB;IAC/E,KAAKD,0BAA0B;IAC/B;GACF;GACA,MAAM,OAAO,kBAAkB,IAAI;GACnC,uBAAuB,MAAM,MAAM,KAAKD,uBAAuB;GAC/D,KAAKC,0BAA0B,qBAC7B,MACA,KAAKA,yBACL,KAAKC,sBACP;EACF;CACF;CAEA,OAAO;AACT"}
@@ -61,6 +61,11 @@ interface ComponentPublicInstance extends HTMLElement {
61
61
  setData: (patch: DataRecord, callback?: () => void) => void | Promise<void>;
62
62
  triggerEvent: (name: string, detail?: any, options?: TriggerEventOptions) => void;
63
63
  createSelectorQuery: () => any;
64
+ createIntersectionObserver: (options?: {
65
+ initialRatio?: number;
66
+ observeAll?: boolean;
67
+ thresholds?: number[];
68
+ }) => any;
64
69
  selectComponent: (selector: string) => ComponentPublicInstance | null;
65
70
  selectAllComponents: (selector: string) => ComponentPublicInstance[];
66
71
  getRelationNodes: (relationPath: string) => ComponentPublicInstance[];
@@ -1,8 +1,8 @@
1
1
  import { __exportAll } from "../../_virtual/_rolldown/runtime.mjs";
2
- import { callMiniProgramAsyncFailure, callMiniProgramAsyncSuccess } from "./async.mjs";
3
- import { createCanvasContextBridge } from "./canvasContext.mjs";
4
2
  import { createSelectorQueryBridge } from "./selectorQuery.mjs";
5
3
  import { createIntersectionObserverBridge } from "./intersectionObserver.mjs";
4
+ import { callMiniProgramAsyncFailure, callMiniProgramAsyncSuccess } from "./async.mjs";
5
+ import { createCanvasContextBridge } from "./canvasContext.mjs";
6
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";
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@weapp-vite/web",
3
3
  "type": "module",
4
- "version": "1.4.10",
4
+ "version": "1.4.12",
5
5
  "description": "Experimental web runtime for weapp-vite templates",
6
6
  "author": "ice breaker <1324318532@qq.com>",
7
7
  "license": "MIT",
@@ -60,10 +60,10 @@
60
60
  "postcss": "^8.5.26",
61
61
  "postcss-selector-parser": "^7.1.5",
62
62
  "rolldown": "1.2.5",
63
- "@weapp-core/constants": "0.1.17",
64
- "rolldown-require": "2.0.26",
63
+ "@weapp-core/constants": "0.2.0",
65
64
  "@weapp-core/shared": "3.1.1",
66
- "wevu": "6.20.5"
65
+ "rolldown-require": "2.0.26",
66
+ "wevu": "6.22.0"
67
67
  },
68
68
  "devDependencies": {
69
69
  "happy-dom": "^20.11.6"