@weapp-vite/web 1.6.0 → 2.0.1

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.
Files changed (63) hide show
  1. package/README.md +22 -0
  2. package/dist/compiler/wxml/compile.mjs +9 -33
  3. package/dist/compiler/wxml/compile.mjs.map +1 -1
  4. package/dist/compiler/wxml/dependency.mjs +9 -1
  5. package/dist/compiler/wxml/dependency.mjs.map +1 -1
  6. package/dist/compiler/wxml/prepare.mjs +43 -0
  7. package/dist/compiler/wxml/prepare.mjs.map +1 -0
  8. package/dist/css/wxss.mjs +2 -1
  9. package/dist/css/wxss.mjs.map +1 -1
  10. package/dist/plugin/assets.d.mts +1 -0
  11. package/dist/plugin/constants.mjs +4 -2
  12. package/dist/plugin/constants.mjs.map +1 -1
  13. package/dist/plugin/hostTypes.d.mts +75 -0
  14. package/dist/plugin/index.d.mts +2 -74
  15. package/dist/plugin/index.mjs +28 -16
  16. package/dist/plugin/index.mjs.map +1 -1
  17. package/dist/plugin/sfcHmr.mjs +38 -0
  18. package/dist/plugin/sfcHmr.mjs.map +1 -0
  19. package/dist/plugin/vueSfc.mjs +12 -9
  20. package/dist/plugin/vueSfc.mjs.map +1 -1
  21. package/dist/runtime/appStyle.mjs +25 -0
  22. package/dist/runtime/appStyle.mjs.map +1 -0
  23. package/dist/runtime/component/element.mjs +39 -19
  24. package/dist/runtime/component/element.mjs.map +1 -1
  25. package/dist/runtime/component/events.mjs +34 -3
  26. package/dist/runtime/component/events.mjs.map +1 -1
  27. package/dist/runtime/component/publicInstance.mjs +7 -3
  28. package/dist/runtime/component/publicInstance.mjs.map +1 -1
  29. package/dist/runtime/component/state.mjs +7 -0
  30. package/dist/runtime/component/state.mjs.map +1 -1
  31. package/dist/runtime/component/types.d.mts +2 -0
  32. package/dist/runtime/component/utils.mjs +23 -3
  33. package/dist/runtime/component/utils.mjs.map +1 -1
  34. package/dist/runtime/componentEvents.mjs +37 -0
  35. package/dist/runtime/componentEvents.mjs.map +1 -0
  36. package/dist/runtime/eventBinding.d.mts +1 -0
  37. package/dist/runtime/eventBinding.mjs +5 -2
  38. package/dist/runtime/eventBinding.mjs.map +1 -1
  39. package/dist/runtime/hostGlobals.d.mts +1 -0
  40. package/dist/runtime/legacyTemplate/dom.mjs +2 -7
  41. package/dist/runtime/legacyTemplate/dom.mjs.map +1 -1
  42. package/dist/runtime/nativeComponents/canvas/index.mjs +12 -3
  43. package/dist/runtime/nativeComponents/canvas/index.mjs.map +1 -1
  44. package/dist/runtime/nativeComponents/index.mjs +0 -1
  45. package/dist/runtime/nativeComponents/index.mjs.map +1 -1
  46. package/dist/runtime/nativeComponents/richText/index.mjs +2 -2
  47. package/dist/runtime/nativeComponents/richText/index.mjs.map +1 -1
  48. package/dist/runtime/pageLayout.d.mts +1 -0
  49. package/dist/runtime/polyfill/index.mjs +1 -1
  50. package/dist/runtime/polyfill/routeRuntime/options.d.mts +1 -0
  51. package/dist/runtime/polyfill/routeRuntime.d.mts +1 -1
  52. package/dist/runtime/polyfill/routeRuntime.mjs +5 -1
  53. package/dist/runtime/polyfill/routeRuntime.mjs.map +1 -1
  54. package/dist/runtime/renderContext.mjs +3 -2
  55. package/dist/runtime/renderContext.mjs.map +1 -1
  56. package/dist/runtime/wevu.d.mts +1 -0
  57. package/dist/runtime/wevu.mjs +2 -0
  58. package/dist/runtime/wevu.mjs.map +1 -1
  59. package/dist/shared/wxml.mjs +5 -1
  60. package/dist/shared/wxml.mjs.map +1 -1
  61. package/package.json +15 -13
  62. package/dist/runtime/nativeComponents/richText/helpers.mjs +0 -230
  63. package/dist/runtime/nativeComponents/richText/helpers.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/plugin/index.ts"],"sourcesContent":["import type { SourceMap } from 'magic-string'\nimport type { ResolveWebAutoImportTag, ResolveWebModuleId, WeappWebPluginOptions, WebResolvedComponent, WebStylePreprocessOptions } from './types'\nimport { readFile } from 'node:fs/promises'\nimport process from 'node:process'\n\nimport { dirname, extname, resolve } from 'pathe'\nimport { isUniAppCompatibilityFile, transformUniAppSource } from 'wevu/compiler'\nimport { compileWxml } from '../compiler/wxml'\nimport { transformWxsToEsm } from '../compiler/wxs'\nimport { createWxssPostcssPlugin, transformWxssToCss } from '../css/wxss'\nimport { createWebAssetMiddleware, emitWebAssets } from './assets'\nimport { AUTO_ROUTES_ID, ENTRY_ID, RESOLVED_AUTO_ROUTES_ID, RUNTIME_ID, SCRIPT_EXTS, SFC_STYLE_QUERY, SFC_TEMPLATE_QUERY, STYLE_EXTS, STYLE_QUERY, TEMPLATE_EXTS, TEMPLATE_QUERY, TRANSFORM_STYLE_EXTS, WEB_COMPONENT_PREFIX, WEB_COMPONENT_QUERY, WXS_EXTS } from './constants'\nimport { collectExternalComponentOptimizeDeps } from './dependencyScan'\nimport { generateAutoRoutesModule, generateEntryModule } from './entry'\nimport { wrapPageTemplate } from './layout'\nimport { createMiniProgramPackageResolver, getAncestorNodeModulesPaths } from './packageResolution'\nimport { cleanUrl, isHtmlEntry, isInsideDir, normalizePath, resolveFileWithExtensionsSync, resolveRuntimePolyfillPath, resolveTemplatePathSync, resolveWxsPathSync, toRelativeImport, toViteFsImport } from './path'\nimport { transformScriptModule } from './register'\nimport { getStableWebComponentId, scanProject } from './scan'\nimport { createEmptyScanState } from './state'\nimport { createInlineStyleModule } from './styleModule'\nimport { ensureWebVueSfcResult, generateWebVueSfcStyle, generateWebVueSfcTemplate, resolveWebVueSfcStyleLanguage, transformWebVueSfcScript } from './vueSfc'\n\ninterface WebPluginContext {\n warn?: (message: string) => void\n addWatchFile?: (id: string) => void\n emitFile?: (asset: { type: 'asset', fileName: string, source: Uint8Array }) => void\n resolve?: (source: string, importer?: string, options?: { skipSelf?: boolean }) => Promise<{ id: string } | null>\n}\n\ntype WebTransformResult = { code: string, map: SourceMap | null } | null\n\ninterface WebPostcssConfig {\n plugins?: Array<{ postcssPlugin?: string }>\n [key: string]: unknown\n}\n\ninterface WebCssConfig {\n postcss?: string | WebPostcssConfig\n preprocessorOptions?: WebStylePreprocessOptions\n}\n\ninterface WebUserConfig {\n css?: {\n postcss?: string | WebPostcssConfig\n preprocessorOptions?: WebStylePreprocessOptions\n }\n}\n\ninterface WebResolvedConfig extends WebUserConfig {\n root: string\n command: string\n createResolver?: () => ResolveWebModuleId\n optimizeDeps?: {\n exclude?: string[]\n include?: string[]\n }\n}\n\ninterface WebHmrContext {\n file: string\n}\n\ninterface WebDevServer {\n middlewares: {\n use: (middleware: ReturnType<typeof createWebAssetMiddleware>) => void\n }\n moduleGraph?: {\n getModuleById: (id: string) => object | undefined\n getModulesByFile: (file: string) => Set<object> | undefined\n invalidateModule: (module: object) => void\n }\n}\n\ninterface WeappWebVitePlugin {\n name: string\n enforce?: 'pre' | 'post'\n config?: (this: WebPluginContext, config: WebUserConfig) => WebUserConfig | void\n configResolved?: (this: WebPluginContext, config: WebResolvedConfig) => void | Promise<void>\n configureServer?: (server: WebDevServer) => void\n buildStart?: (this: WebPluginContext) => void | Promise<void>\n resolveId?: (id: string, importer?: string) => string | null | Promise<string | null>\n load?: (id: string) => string | null | Promise<string | null>\n watchChange?: {\n order: 'post'\n sequential: true\n handler: (this: WebPluginContext, id: string, change: { event: 'create' | 'update' | 'delete' }) => Promise<void>\n }\n handleHotUpdate?: (this: WebPluginContext, ctx: WebHmrContext) => void | Promise<void>\n transform?: (\n this: WebPluginContext,\n code: string,\n id: string,\n ) => WebTransformResult | Promise<WebTransformResult>\n}\n\nconst WEB_RUNTIME_MODULE_IDS = [\n 'lit',\n 'lit/async-directive.js',\n 'lit/directives/repeat.js',\n] as const\n\nconst SCAN_VIRTUAL_MODULE_IDS = [ENTRY_ID, RESOLVED_AUTO_ROUTES_ID] as const\n\nfunction isTemplateFile(id: string) {\n const lower = id.toLowerCase()\n return TEMPLATE_EXTS.some(ext => lower.endsWith(ext))\n}\n\nfunction isWxsFile(id: string) {\n const lower = id.toLowerCase()\n return WXS_EXTS.some(ext => lower.endsWith(ext))\n}\n\nfunction hasWxsQuery(id: string) {\n return id.includes('?wxs') || id.includes('&wxs')\n}\n\nfunction hasQuery(id: string, query: string) {\n return id.includes(`?${query}`) || id.includes(`&${query}`)\n}\n\nfunction isUniAppDependency(id: string, includes: readonly string[]) {\n return includes.some(packageName => id === packageName || id.startsWith(`${packageName}/`))\n}\n\nfunction resolveSfcStyleSourceFilename(id: string) {\n const filename = cleanUrl(id)\n const vueSuffixIndex = filename.lastIndexOf('.vue.')\n return vueSuffixIndex >= 0\n ? filename.slice(0, vueSuffixIndex + '.vue'.length)\n : filename\n}\n\nfunction createWebCssConfig(\n config: WebUserConfig,\n wxssOptions: WeappWebPluginOptions['wxss'],\n warn?: (message: string) => void,\n): WebCssConfig | undefined {\n const postcssConfig = config.css?.postcss\n if (typeof postcssConfig === 'string') {\n warn?.('[@weapp-vite/web] css.postcss 使用配置文件路径时无法注入 WXSS 转换插件。')\n return undefined\n }\n\n const plugins = postcssConfig?.plugins ?? []\n if (plugins.some(plugin => plugin.postcssPlugin === 'weapp-vite-web-wxss')) {\n return undefined\n }\n\n return {\n postcss: {\n ...postcssConfig,\n plugins: [...plugins, createWxssPostcssPlugin(wxssOptions)],\n },\n preprocessorOptions: config.css?.preprocessorOptions,\n }\n}\n\nfunction resolveStylePreprocessOptions(\n options: WebStylePreprocessOptions | undefined,\n root: string,\n): WebStylePreprocessOptions | undefined {\n if (!options) {\n return undefined\n }\n\n const nodeModules = getAncestorNodeModulesPaths(root)\n return Object.fromEntries(Object.entries(options).map(([language, languageOptions]) => {\n if (!['sass', 'scss'].includes(language)) {\n return [language, languageOptions]\n }\n\n const loadPaths = Array.isArray(languageOptions.loadPaths)\n ? languageOptions.loadPaths.filter((value): value is string => typeof value === 'string')\n : []\n return [language, {\n ...languageOptions,\n loadPaths: Array.from(new Set([...loadPaths, ...nodeModules])),\n }]\n }))\n}\n\nexport function weappWebPlugin(options: WeappWebPluginOptions = {}): WeappWebVitePlugin {\n let root = process.cwd()\n let srcRoot = resolve(root, options.srcDir ?? 'src')\n let enableHmr = false\n let devServer: WebDevServer | undefined\n let resolveWebModuleId: ResolveWebModuleId | undefined\n let resolveMiniProgramModuleId: ResolveWebModuleId | undefined\n let resolveWebAutoImportTag: ResolveWebAutoImportTag | undefined\n const webRuntimeModules = new Map<string, string>()\n let stylePreprocessOptions: WebStylePreprocessOptions | undefined\n let componentImportIdMap = new Map<string, string>()\n\n let state = createEmptyScanState()\n let scanQueue: Promise<void> = Promise.resolve()\n const wxssOptions = options.wxss\n const runtimeProvider = options.__runtimeProvider\n const hmrAcceptCode = runtimeProvider\n ? runtimeProvider.hmrAcceptCode\n : 'if (import.meta.hot) { import.meta.hot.accept() }'\n\n const resolveTemplatePath = (raw: string, importer: string) => resolveTemplatePathSync(raw, importer, srcRoot)\n const resolveWxsPath = (raw: string, importer: string) => resolveWxsPathSync(raw, importer, srcRoot)\n const resolveMetaByTemplate = (filename: string) => {\n const normalized = normalizePath(filename)\n for (const meta of state.moduleMeta.values()) {\n if (meta.templatePath && normalizePath(meta.templatePath) === normalized) {\n return meta\n }\n }\n return undefined\n }\n\n const createAutoImportTagResolver = (): ResolveWebAutoImportTag | undefined => {\n const resolvers = options.__autoImportResolvers\n if (!resolvers?.length) {\n return undefined\n }\n return async (tag, importer) => {\n for (const resolver of resolvers) {\n let matched: WebResolvedComponent | void\n if (typeof resolver === 'function') {\n matched = resolver(tag, importer)\n }\n else if (typeof resolver.resolve === 'function') {\n matched = resolver.resolve(tag, importer)\n }\n else {\n const from = resolver.components?.[tag]\n matched = from ? { name: tag, from } : undefined\n }\n if (!matched) {\n continue\n }\n const request = matched.resolvedId ?? matched.from\n const resolvedId = await resolveWebModuleId?.(request, importer)\n return {\n ...matched,\n resolvedId: resolvedId ?? matched.resolvedId,\n sourceType: matched.sourceType ?? (resolvedId?.endsWith('.vue') ? 'wevu-sfc' : 'native'),\n }\n }\n return undefined\n }\n }\n\n const scan = (context: WebPluginContext) => {\n const result = scanQueue.then(async () => {\n const nextState = createEmptyScanState()\n await scanProject({\n srcRoot,\n warn: context.warn?.bind(context),\n state: nextState,\n resolveId: resolveWebModuleId,\n resolveAutoImportTag: resolveWebAutoImportTag,\n resolveAppConfig: options.__resolveAppConfig,\n uniApp: options.__uniApp,\n stylePreprocessOptions,\n })\n const nextComponentImportIdMap = new Map<string, string>()\n for (const component of nextState.scanResult.components) {\n if (component.importId) {\n nextComponentImportIdMap.set(component.importId, component.script)\n }\n }\n const graph = devServer?.moduleGraph\n const files = graph ? new Set<string>() : undefined\n if (files) {\n for (const snapshot of [state, nextState]) {\n for (const file of snapshot.moduleMeta.keys()) {\n files.add(file)\n }\n for (const file of snapshot.templatePathSet) {\n files.add(file)\n }\n for (const [file, result] of snapshot.sfcResults) {\n files.add(`${file}.${resolveWebVueSfcStyleLanguage(result, file)}`)\n }\n }\n }\n // 虚拟模块始终读取最后一次完整快照,不暴露扫描过程中的空映射。\n state = nextState\n componentImportIdMap = nextComponentImportIdMap\n if (graph && files) {\n for (const id of SCAN_VIRTUAL_MODULE_IDS) {\n const module = graph.getModuleById(id)\n if (module) {\n graph.invalidateModule(module)\n }\n }\n // 入口失效不会向下传播;脚本、模板和合成样式同样属于扫描快照。\n for (const file of files) {\n const modules = graph.getModulesByFile(file)\n if (modules) {\n for (const module of modules) {\n graph.invalidateModule(module)\n }\n }\n }\n }\n })\n // 调用方仍接收原始错误;队尾只负责允许下一次文件变更恢复扫描。\n scanQueue = result.catch(() => {})\n return result\n }\n\n const scanChangedFile = async (context: WebPluginContext, file: string) => {\n const clean = cleanUrl(file)\n const normalized = normalizePath(clean)\n if (!isInsideDir(clean, srcRoot) && !state.moduleMeta.has(normalized) && !state.templatePathSet.has(normalized)) {\n return\n }\n if (clean.endsWith('.json') || isTemplateFile(clean) || isWxsFile(clean) || clean.endsWith('.wxss') || SCRIPT_EXTS.includes(extname(clean))) {\n await scan(context)\n }\n }\n\n return {\n name: '@weapp-vite/web',\n enforce: 'pre',\n config(this: WebPluginContext, config: WebUserConfig) {\n const css = createWebCssConfig(config, wxssOptions, this.warn?.bind(this))\n return css ? { css } : undefined\n },\n async configResolved(this: WebPluginContext, config: WebResolvedConfig) {\n root = config.root\n const { createRequire } = await import('node:module')\n const requireFromWebRuntime = createRequire(import.meta.url)\n const requireFromProject = createRequire(resolve(root, 'package.json'))\n for (const id of WEB_RUNTIME_MODULE_IDS) {\n webRuntimeModules.set(id, requireFromWebRuntime.resolve(id))\n }\n webRuntimeModules.set(RUNTIME_ID, resolveRuntimePolyfillPath())\n resolveMiniProgramModuleId = createMiniProgramPackageResolver(requireFromProject.resolve)\n srcRoot = resolve(root, options.srcDir ?? 'src')\n stylePreprocessOptions = resolveStylePreprocessOptions(config.css?.preprocessorOptions, root)\n enableHmr = config.command === 'serve'\n const resolveViteModuleId = config.createResolver?.()\n resolveWebModuleId = resolveViteModuleId\n ? async (source, importer) => {\n const resolved = await resolveViteModuleId(source, importer)\n return await resolveMiniProgramModuleId?.(resolved ?? source, importer)\n ?? await resolveMiniProgramModuleId?.(source, importer)\n ?? resolved\n }\n : undefined\n resolveWebAutoImportTag = createAutoImportTagResolver()\n await scan(this)\n const componentDependencies = await collectExternalComponentOptimizeDeps(state.scanResult.components)\n const uniAppIncludes = options.__uniApp?.include ?? []\n config.optimizeDeps ??= {}\n config.optimizeDeps.exclude = Array.from(new Set([\n ...(config.optimizeDeps.exclude ?? []),\n ...uniAppIncludes,\n ]))\n config.optimizeDeps.include = Array.from(new Set([\n ...(config.optimizeDeps.include ?? []),\n ...componentDependencies,\n ])).filter(dependency => !isUniAppDependency(dependency, uniAppIncludes))\n },\n configureServer(server: WebDevServer) {\n devServer = server\n server.middlewares.use(createWebAssetMiddleware(srcRoot))\n },\n async buildStart(this: WebPluginContext) {\n if (!resolveWebModuleId && this.resolve) {\n resolveWebModuleId = async (source, importer) => {\n const resolved = await this.resolve?.(source, importer, { skipSelf: true })\n return await resolveMiniProgramModuleId?.(resolved?.id ?? source, importer)\n ?? await resolveMiniProgramModuleId?.(source, importer)\n ?? resolved?.id\n }\n }\n resolveWebAutoImportTag = createAutoImportTagResolver()\n await scan(this)\n if (!enableHmr) {\n await emitWebAssets(this, srcRoot)\n }\n },\n resolveId(id: string, importer?: string) {\n const runtimeModule = webRuntimeModules.get(id)\n if (runtimeModule) {\n return runtimeModule\n }\n if (id === '/@weapp-vite/web/entry' || id === '@weapp-vite/web/entry') {\n return ENTRY_ID\n }\n if (id === AUTO_ROUTES_ID) {\n return RESOLVED_AUTO_ROUTES_ID\n }\n if (id.startsWith(WEB_COMPONENT_PREFIX)) {\n const request = decodeURIComponent(id.slice(WEB_COMPONENT_PREFIX.length))\n const resolvedId = componentImportIdMap.get(request)\n return resolvedId ? `${cleanUrl(resolvedId)}?${WEB_COMPONENT_QUERY}` : null\n }\n if (id.startsWith('.') && importer && cleanUrl(importer).endsWith('.vue') && !extname(id)) {\n const resolvedScript = resolveFileWithExtensionsSync(resolve(dirname(cleanUrl(importer)), id), SCRIPT_EXTS)\n if (resolvedScript?.endsWith('.vue')) {\n return resolvedScript\n }\n }\n if (hasQuery(id, SFC_STYLE_QUERY)) {\n const queryIndex = id.indexOf('?')\n const pathname = queryIndex >= 0 ? id.slice(0, queryIndex) : id\n const query = queryIndex >= 0 ? id.slice(queryIndex) : ''\n if (pathname.startsWith('.') && importer) {\n return `${resolve(dirname(cleanUrl(importer)), pathname)}${query}`\n }\n return id\n }\n return resolveMiniProgramModuleId?.(id, importer).then(resolved => resolved ?? null) ?? null\n },\n async load(this: WebPluginContext, id: string) {\n if (id === ENTRY_ID) {\n return generateEntryModule(state.scanResult, root, wxssOptions, options)\n }\n if (id === RESOLVED_AUTO_ROUTES_ID) {\n return generateAutoRoutesModule(state.scanResult)\n }\n if (hasQuery(id, TEMPLATE_QUERY)) {\n const filename = cleanUrl(id)\n let source = await readFile(filename, 'utf8')\n const pageMeta = resolveMetaByTemplate(filename)\n if (pageMeta?.kind === 'page' && state.scanResult.layouts.length) {\n source = wrapPageTemplate(source, state.scanResult.layouts)\n }\n const navigationConfig = state.pageNavigationMap.get(normalizePath(filename))\n const componentTags = state.templateComponentMap.get(normalizePath(filename))\n const compiled = compileWxml({\n id: filename,\n source,\n resolveTemplatePath,\n resolveWxsPath,\n navigationBar: navigationConfig ? { config: navigationConfig } : undefined,\n componentTags,\n })\n for (const dependency of compiled.dependencies) {\n this.addWatchFile?.(dependency)\n }\n for (const warning of compiled.warnings ?? []) {\n this.warn?.(warning)\n }\n return compiled.code\n }\n if (hasWxsQuery(id)) {\n const filename = cleanUrl(id)\n const source = await readFile(filename, 'utf8')\n const compiled = transformWxsToEsm(source, filename, {\n resolvePath: resolveWxsPath,\n toImportPath: (resolved, importer) => normalizePath(toRelativeImport(importer, resolved)),\n })\n for (const dependency of compiled.dependencies) {\n this.addWatchFile?.(dependency)\n }\n for (const warning of compiled.warnings ?? []) {\n this.warn?.(warning)\n }\n return compiled.code\n }\n if (hasQuery(id, STYLE_QUERY)) {\n const source = await readFile(cleanUrl(id), 'utf8')\n const { css } = transformWxssToCss(source, wxssOptions)\n return createInlineStyleModule(css)\n }\n if (id.includes(`?${SFC_TEMPLATE_QUERY}`) || id.includes(`&${SFC_TEMPLATE_QUERY}`)) {\n const filename = cleanUrl(id)\n const meta = state.moduleMeta.get(normalizePath(filename))\n if (!meta) {\n return null\n }\n const result = await ensureWebVueSfcResult({\n filename,\n meta,\n srcRoot,\n state,\n resolveId: resolveWebModuleId,\n resolveAutoImportTag: resolveWebAutoImportTag,\n uniApp: options.__uniApp,\n stylePreprocessOptions,\n })\n const compiled = generateWebVueSfcTemplate(result, meta, filename, srcRoot)\n for (const dependency of compiled.dependencies) {\n this.addWatchFile?.(dependency)\n }\n for (const warning of compiled.warnings ?? []) {\n this.warn?.(warning)\n }\n return compiled.code\n }\n if (id.includes(`?${SFC_STYLE_QUERY}`) || id.includes(`&${SFC_STYLE_QUERY}`)) {\n const filename = resolveSfcStyleSourceFilename(id)\n const meta = state.moduleMeta.get(normalizePath(filename))\n if (!meta) {\n return null\n }\n const result = await ensureWebVueSfcResult({\n filename,\n meta,\n srcRoot,\n state,\n resolveId: resolveWebModuleId,\n resolveAutoImportTag: resolveWebAutoImportTag,\n uniApp: options.__uniApp,\n stylePreprocessOptions,\n })\n return generateWebVueSfcStyle(result)\n }\n return null\n },\n watchChange: {\n order: 'post',\n sequential: true,\n async handler(this: WebPluginContext, id, change) {\n // Vite 的 handleHotUpdate 不处理增删;必须在结构性 HMR 前发布完整入口。\n if (enableHmr && change.event !== 'update') {\n await scanChangedFile(this, id)\n }\n },\n },\n async handleHotUpdate(this: WebPluginContext, ctx: WebHmrContext) {\n await scanChangedFile(this, ctx.file)\n },\n async transform(this: WebPluginContext, code: string, id: string) {\n const clean = cleanUrl(id)\n let uniAppTransformed = false\n\n if (\n options.__uniApp\n && isUniAppCompatibilityFile(clean, srcRoot, options.__uniApp.include)\n && !clean.endsWith('.vue')\n ) {\n const transformed = transformUniAppSource(code, { filename: clean, target: 'h5' })\n if (transformed.changed) {\n code = transformed.code\n uniAppTransformed = true\n }\n }\n\n if (\n hasQuery(id, TEMPLATE_QUERY)\n || hasWxsQuery(id)\n || hasQuery(id, STYLE_QUERY)\n || hasQuery(id, SFC_TEMPLATE_QUERY)\n || hasQuery(id, SFC_STYLE_QUERY)\n ) {\n return null\n }\n\n if (clean.endsWith('.vue')) {\n const normalized = normalizePath(clean)\n const meta = state.moduleMeta.get(normalized) ?? {\n kind: 'component' as const,\n id: getStableWebComponentId(clean, srcRoot),\n scriptPath: clean,\n sourceType: 'vue-sfc' as const,\n }\n state.moduleMeta.set(normalized, meta)\n const result = await ensureWebVueSfcResult({\n filename: clean,\n meta,\n srcRoot,\n state,\n source: code,\n resolveId: resolveWebModuleId,\n resolveAutoImportTag: resolveWebAutoImportTag,\n uniApp: options.__uniApp,\n stylePreprocessOptions,\n })\n return transformWebVueSfcScript({\n code: result.script!,\n filename: clean,\n meta,\n runtimeModuleId: runtimeProvider?.moduleId ?? toViteFsImport(resolveRuntimePolyfillPath()),\n styleLanguage: resolveWebVueSfcStyleLanguage(result, clean),\n enableHmr,\n hmrAcceptCode,\n })\n }\n\n if (isTemplateFile(clean)) {\n if (isHtmlEntry(clean, root)) {\n return null\n }\n const normalizedId = normalizePath(clean)\n if (state.templatePathSet.size > 0) {\n if (!isInsideDir(clean, srcRoot)) {\n return null\n }\n if (!state.templatePathSet.has(normalizedId)) {\n return null\n }\n }\n let templateSource = code\n const pageMeta = resolveMetaByTemplate(clean)\n if (pageMeta?.kind === 'page' && state.scanResult.layouts.length) {\n templateSource = wrapPageTemplate(code, state.scanResult.layouts)\n }\n const navigationConfig = state.pageNavigationMap.get(normalizedId)\n const componentTags = state.templateComponentMap.get(normalizedId)\n const { code: compiled, dependencies, warnings } = compileWxml({\n id: clean,\n source: templateSource,\n resolveTemplatePath,\n resolveWxsPath,\n navigationBar: navigationConfig ? { config: navigationConfig } : undefined,\n componentTags,\n })\n const addWatchFile = this.addWatchFile\n if (dependencies.length > 0 && addWatchFile) {\n for (const dep of dependencies) {\n addWatchFile.call(this, dep)\n }\n }\n const warn = this.warn\n if (warnings?.length && warn) {\n for (const warning of warnings) {\n warn.call(this, warning)\n }\n }\n return { code: compiled, map: null }\n }\n\n if (isWxsFile(clean) || hasWxsQuery(id)) {\n const { code: compiled, dependencies, warnings } = transformWxsToEsm(code, clean, {\n resolvePath: resolveWxsPath,\n toImportPath: (resolved, importer) => normalizePath(toRelativeImport(importer, resolved)),\n })\n const addWatchFile = this.addWatchFile\n if (dependencies.length > 0 && addWatchFile) {\n for (const dep of dependencies) {\n addWatchFile.call(this, dep)\n }\n }\n const warn = this.warn\n if (warnings?.length && warn) {\n for (const warning of warnings) {\n warn.call(this, warning)\n }\n }\n return { code: compiled, map: null }\n }\n\n if (TRANSFORM_STYLE_EXTS.some(ext => clean.endsWith(ext))) {\n const { css } = transformWxssToCss(code, wxssOptions)\n return {\n code: createInlineStyleModule(css),\n map: null,\n }\n }\n\n if (STYLE_EXTS.some(ext => clean.endsWith(ext)) && !clean.endsWith('.wxss')) {\n const { css } = transformWxssToCss(code, wxssOptions)\n return { code: css, map: null }\n }\n\n if (!SCRIPT_EXTS.some(ext => clean.endsWith(ext))) {\n return uniAppTransformed ? { code, map: null } : null\n }\n if (clean.includes('node_modules') && !hasQuery(id, WEB_COMPONENT_QUERY)) {\n return options.__uniApp && isUniAppCompatibilityFile(clean, srcRoot, options.__uniApp.include)\n ? { code, map: null }\n : null\n }\n\n const meta = state.moduleMeta.get(normalizePath(clean))\n if (!meta) {\n return null\n }\n\n return transformScriptModule({\n code,\n cleanId: clean,\n meta,\n enableHmr,\n runtimeModuleId: runtimeProvider?.moduleId,\n hmrAcceptCode,\n })\n },\n }\n}\n\nexport type { WeappWebPluginOptions } from './types'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAgGA,MAAM,yBAAyB;CAC7B;CACA;CACA;AACF;AAEA,MAAM,0BAA0B,CAAC,UAAU,uBAAuB;AAElE,SAAS,eAAe,IAAY;CAClC,MAAM,QAAQ,GAAG,YAAY;CAC7B,OAAO,cAAc,MAAK,QAAO,MAAM,SAAS,GAAG,CAAC;AACtD;AAEA,SAAS,UAAU,IAAY;CAC7B,MAAM,QAAQ,GAAG,YAAY;CAC7B,OAAO,SAAS,MAAK,QAAO,MAAM,SAAS,GAAG,CAAC;AACjD;AAEA,SAAS,YAAY,IAAY;CAC/B,OAAO,GAAG,SAAS,MAAM,KAAK,GAAG,SAAS,MAAM;AAClD;AAEA,SAAS,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,k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O;KAAE,MAAM;KAAU,KAAK;IAAK;GACrC;GAEA,IAAI,qBAAqB,MAAK,QAAO,MAAM,SAAS,GAAG,CAAC,GAAG;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 { WeappWebVitePlugin, WebCssConfig, WebDevServer, WebHmrContext, WebPluginContext, WebResolvedConfig, WebUserConfig } from './hostTypes'\nimport type { ResolveWebAutoImportTag, ResolveWebModuleId, WeappWebPluginOptions, WebResolvedComponent, WebStylePreprocessOptions } from './types'\nimport { readFile } from 'node:fs/promises'\nimport process from 'node:process'\n\nimport { dirname, extname, resolve } from 'pathe'\nimport { isUniAppCompatibilityFile, transformUniAppSource } from 'wevu/compiler'\nimport { compileWxml } from '../compiler/wxml'\nimport { transformWxsToEsm } from '../compiler/wxs'\nimport { createWxssPostcssPlugin, transformWxssToCss } from '../css/wxss'\nimport { createWebAssetMiddleware, emitWebAssets } from './assets'\nimport { AUTO_ROUTES_ID, ENTRY_ID, RESOLVED_AUTO_ROUTES_ID, RUNTIME_ID, SCRIPT_EXTS, SFC_STYLE_QUERY, SFC_TEMPLATE_QUERY, STYLE_EXTS, STYLE_QUERY, TEMPLATE_EXTS, TEMPLATE_QUERY, TRANSFORM_STYLE_EXTS, WEB_COMPONENT_PREFIX, WEB_COMPONENT_QUERY, WXS_EXTS } from './constants'\nimport { collectExternalComponentOptimizeDeps } from './dependencyScan'\nimport { generateAutoRoutesModule, generateEntryModule } from './entry'\nimport { wrapPageTemplate } from './layout'\nimport { createMiniProgramPackageResolver, getAncestorNodeModulesPaths } from './packageResolution'\nimport { cleanUrl, isHtmlEntry, isInsideDir, normalizePath, resolveFileWithExtensionsSync, resolveRuntimePolyfillPath, resolveTemplatePathSync, resolveWxsPathSync, toRelativeImport, toViteFsImport } from './path'\nimport { transformScriptModule } from './register'\nimport { getStableWebComponentId, scanProject } from './scan'\nimport { collectSfcHmrModules } from './sfcHmr'\nimport { createEmptyScanState } from './state'\nimport { createInlineStyleModule } from './styleModule'\nimport { ensureWebVueSfcResult, generateWebVueSfcStyle, generateWebVueSfcTemplate, resolveWebVueSfcStyleLanguage, transformWebVueSfcScript } from './vueSfc'\n\nconst WEB_RUNTIME_MODULE_IDS = [\n 'lit',\n 'lit/async-directive.js',\n 'lit/directives/repeat.js',\n] as const\n\nconst SCAN_VIRTUAL_MODULE_IDS = [ENTRY_ID, RESOLVED_AUTO_ROUTES_ID] as const\n\nfunction isTemplateFile(id: string) {\n const lower = id.toLowerCase()\n return TEMPLATE_EXTS.some(ext => lower.endsWith(ext))\n}\n\nfunction isWxsFile(id: string) {\n const lower = id.toLowerCase()\n return WXS_EXTS.some(ext => lower.endsWith(ext))\n}\n\nfunction hasWxsQuery(id: string) {\n return id.includes('?wxs') || id.includes('&wxs')\n}\n\nfunction hasQuery(id: string, query: string) {\n return id.includes(`?${query}`) || id.includes(`&${query}`)\n}\n\nfunction isUniAppDependency(id: string, includes: readonly string[]) {\n return includes.some(packageName => id === packageName || id.startsWith(`${packageName}/`))\n}\n\nfunction resolveSfcStyleSourceFilename(id: string) {\n const filename = cleanUrl(id)\n const vueSuffixIndex = filename.lastIndexOf('.vue.')\n return vueSuffixIndex >= 0\n ? filename.slice(0, vueSuffixIndex + '.vue'.length)\n : filename\n}\n\nfunction createWebCssConfig(\n config: WebUserConfig,\n wxssOptions: WeappWebPluginOptions['wxss'],\n warn?: (message: string) => void,\n): WebCssConfig | undefined {\n const postcssConfig = config.css?.postcss\n if (typeof postcssConfig === 'string') {\n warn?.('[@weapp-vite/web] css.postcss 使用配置文件路径时无法注入 WXSS 转换插件。')\n return undefined\n }\n\n const plugins = postcssConfig?.plugins ?? []\n if (plugins.some(plugin => 'postcssPlugin' in plugin && plugin.postcssPlugin === 'weapp-vite-web-wxss')) {\n return undefined\n }\n\n return {\n postcss: {\n ...postcssConfig,\n plugins: [...plugins, createWxssPostcssPlugin(wxssOptions)],\n },\n preprocessorOptions: config.css?.preprocessorOptions,\n }\n}\n\nfunction resolveStylePreprocessOptions(\n options: WebStylePreprocessOptions | undefined,\n root: string,\n): WebStylePreprocessOptions | undefined {\n if (!options) {\n return undefined\n }\n\n const nodeModules = getAncestorNodeModulesPaths(root)\n return Object.fromEntries(Object.entries(options).map(([language, languageOptions]) => {\n if (!['sass', 'scss'].includes(language)) {\n return [language, languageOptions]\n }\n\n const loadPaths = Array.isArray(languageOptions.loadPaths)\n ? languageOptions.loadPaths.filter((value): value is string => typeof value === 'string')\n : []\n return [language, {\n ...languageOptions,\n loadPaths: Array.from(new Set([...loadPaths, ...nodeModules])),\n }]\n }))\n}\n\nexport function weappWebPlugin(options: WeappWebPluginOptions = {}): WeappWebVitePlugin {\n let root = process.cwd()\n let srcRoot = resolve(root, options.srcDir ?? 'src')\n let enableHmr = false\n let devServer: WebDevServer | undefined\n let resolveWebModuleId: ResolveWebModuleId | undefined\n let resolveMiniProgramModuleId: ResolveWebModuleId | undefined\n let resolveWebAutoImportTag: ResolveWebAutoImportTag | undefined\n const webRuntimeModules = new Map<string, string>()\n let stylePreprocessOptions: WebStylePreprocessOptions | undefined\n let componentImportIdMap = new Map<string, string>()\n\n let state = createEmptyScanState()\n let scanQueue: Promise<void> = Promise.resolve()\n const wxssOptions = options.wxss\n const runtimeProvider = options.__runtimeProvider\n const hmrAcceptCode = runtimeProvider\n ? runtimeProvider.hmrAcceptCode\n : 'if (import.meta.hot) { import.meta.hot.accept() }'\n\n const resolveTemplatePath = (raw: string, importer: string) => resolveTemplatePathSync(raw, importer, srcRoot)\n const resolveWxsPath = (raw: string, importer: string) => resolveWxsPathSync(raw, importer, srcRoot)\n const resolveMetaByTemplate = (filename: string) => {\n const normalized = normalizePath(filename)\n for (const meta of state.moduleMeta.values()) {\n if (meta.templatePath && normalizePath(meta.templatePath) === normalized) {\n return meta\n }\n }\n return undefined\n }\n\n const createAutoImportTagResolver = (): ResolveWebAutoImportTag | undefined => {\n const resolvers = options.__autoImportResolvers\n if (!resolvers?.length) {\n return undefined\n }\n return async (tag, importer) => {\n for (const resolver of resolvers) {\n let matched: WebResolvedComponent | void\n if (typeof resolver === 'function') {\n matched = resolver(tag, importer)\n }\n else if (typeof resolver.resolve === 'function') {\n matched = resolver.resolve(tag, importer)\n }\n else {\n const from = resolver.components?.[tag]\n matched = from ? { name: tag, from } : undefined\n }\n if (!matched) {\n continue\n }\n const request = matched.resolvedId ?? matched.from\n const resolvedId = await resolveWebModuleId?.(request, importer)\n return {\n ...matched,\n resolvedId: resolvedId ?? matched.resolvedId,\n sourceType: matched.sourceType ?? (resolvedId?.endsWith('.vue') ? 'wevu-sfc' : 'native'),\n }\n }\n return undefined\n }\n }\n\n const scan = (context: WebPluginContext) => {\n const graph = devServer?.moduleGraph\n // 先撤销旧拓扑响应,避免扫描期间的浏览器重验证通过缓存跳过 load。\n for (const id of SCAN_VIRTUAL_MODULE_IDS) {\n const module = graph?.getModuleById(id)\n if (module) {\n graph?.invalidateModule(module)\n }\n }\n const result = scanQueue.then(async () => {\n const previousState = state\n const nextState = createEmptyScanState()\n await scanProject({\n srcRoot,\n warn: context.warn?.bind(context),\n state: nextState,\n resolveId: resolveWebModuleId,\n resolveAutoImportTag: resolveWebAutoImportTag,\n resolveAppConfig: options.__resolveAppConfig,\n uniApp: options.__uniApp,\n stylePreprocessOptions,\n })\n const nextComponentImportIdMap = new Map<string, string>()\n for (const component of nextState.scanResult.components) {\n if (component.importId) {\n nextComponentImportIdMap.set(component.importId, component.script)\n }\n }\n const files = graph ? new Set<string>() : undefined\n if (files) {\n for (const snapshot of [state, nextState]) {\n for (const file of snapshot.moduleMeta.keys()) {\n files.add(file)\n }\n for (const file of snapshot.templatePathSet) {\n files.add(file)\n }\n for (const [file, result] of snapshot.sfcResults) {\n files.add(`${file}.${resolveWebVueSfcStyleLanguage(result, file)}`)\n }\n }\n }\n // 源模块始终读取最后一次完整快照,不暴露扫描过程中的空映射。\n state = nextState\n componentImportIdMap = nextComponentImportIdMap\n if (graph && files) {\n // 入口失效不会向下传播;脚本、模板和合成样式同样属于扫描快照。\n for (const file of files) {\n const modules = graph.getModulesByFile(file)\n if (modules) {\n for (const module of modules) {\n graph.invalidateModule(module)\n }\n }\n }\n }\n return [previousState, nextState] as const\n })\n // 调用方仍接收原始错误;队尾只负责允许下一次文件变更恢复扫描。\n scanQueue = result.then(() => {}, () => {})\n return result\n }\n\n const scanChangedFile = async (context: WebPluginContext, file: string) => {\n const clean = cleanUrl(file)\n const normalized = normalizePath(clean)\n if (!isInsideDir(clean, srcRoot) && !state.moduleMeta.has(normalized) && !state.templatePathSet.has(normalized)) {\n return\n }\n if (state.templatePathSet.has(normalized) || clean.endsWith('.json') || isTemplateFile(clean) || isWxsFile(clean) || clean.endsWith('.wxss') || SCRIPT_EXTS.includes(extname(clean))) {\n return scan(context)\n }\n }\n\n return {\n name: '@weapp-vite/web',\n enforce: 'pre',\n config(this: WebPluginContext, config: WebUserConfig) {\n const css = createWebCssConfig(config, wxssOptions, this.warn?.bind(this))\n return css ? { css } : undefined\n },\n async configResolved(this: WebPluginContext, config: WebResolvedConfig) {\n root = config.root\n const { createRequire } = await import('node:module')\n const requireFromWebRuntime = createRequire(import.meta.url)\n const requireFromProject = createRequire(resolve(root, 'package.json'))\n for (const id of WEB_RUNTIME_MODULE_IDS) {\n webRuntimeModules.set(id, requireFromWebRuntime.resolve(id))\n }\n webRuntimeModules.set(RUNTIME_ID, resolveRuntimePolyfillPath())\n resolveMiniProgramModuleId = createMiniProgramPackageResolver(requireFromProject.resolve)\n srcRoot = resolve(root, options.srcDir ?? 'src')\n stylePreprocessOptions = resolveStylePreprocessOptions(config.css?.preprocessorOptions, root)\n enableHmr = config.command === 'serve'\n const resolveViteModuleId = config.createResolver?.()\n resolveWebModuleId = resolveViteModuleId\n ? async (source, importer) => {\n const resolved = await resolveViteModuleId(source, importer)\n return await resolveMiniProgramModuleId?.(resolved ?? source, importer)\n ?? await resolveMiniProgramModuleId?.(source, importer)\n ?? resolved\n }\n : undefined\n resolveWebAutoImportTag = createAutoImportTagResolver()\n await scan(this)\n const componentDependencies = await collectExternalComponentOptimizeDeps(state.scanResult.components)\n const uniAppIncludes = options.__uniApp?.include ?? []\n config.optimizeDeps ??= {}\n config.optimizeDeps.exclude = Array.from(new Set([\n ...(config.optimizeDeps.exclude ?? []),\n ...uniAppIncludes,\n ]))\n config.optimizeDeps.include = Array.from(new Set([\n ...(config.optimizeDeps.include ?? []),\n ...componentDependencies,\n ])).filter(dependency => !isUniAppDependency(dependency, uniAppIncludes))\n },\n configureServer(server: WebDevServer) {\n devServer = server\n server.middlewares.use(createWebAssetMiddleware(srcRoot))\n },\n async buildStart(this: WebPluginContext) {\n if (!resolveWebModuleId && this.resolve) {\n resolveWebModuleId = async (source, importer) => {\n const resolved = await this.resolve?.(source, importer, { skipSelf: true })\n return await resolveMiniProgramModuleId?.(resolved?.id ?? source, importer)\n ?? await resolveMiniProgramModuleId?.(source, importer)\n ?? resolved?.id\n }\n }\n resolveWebAutoImportTag = createAutoImportTagResolver()\n await scan(this)\n if (!enableHmr) {\n await emitWebAssets(this, srcRoot)\n }\n },\n resolveId(id: string, importer?: string) {\n const runtimeModule = webRuntimeModules.get(id)\n if (runtimeModule) {\n return runtimeModule\n }\n if (id === '/@weapp-vite/web/entry' || id === '@weapp-vite/web/entry') {\n return ENTRY_ID\n }\n if (id === AUTO_ROUTES_ID) {\n return RESOLVED_AUTO_ROUTES_ID\n }\n if (id.startsWith(WEB_COMPONENT_PREFIX)) {\n const request = decodeURIComponent(id.slice(WEB_COMPONENT_PREFIX.length))\n const resolvedId = componentImportIdMap.get(request)\n return resolvedId ? `${cleanUrl(resolvedId)}?${WEB_COMPONENT_QUERY}` : null\n }\n if (id.startsWith('.') && importer && cleanUrl(importer).endsWith('.vue') && !extname(id)) {\n const resolvedScript = resolveFileWithExtensionsSync(resolve(dirname(cleanUrl(importer)), id), SCRIPT_EXTS)\n if (resolvedScript?.endsWith('.vue')) {\n return resolvedScript\n }\n }\n if (hasQuery(id, SFC_STYLE_QUERY)) {\n const queryIndex = id.indexOf('?')\n const pathname = queryIndex >= 0 ? id.slice(0, queryIndex) : id\n const query = queryIndex >= 0 ? id.slice(queryIndex) : ''\n if (pathname.startsWith('.') && importer) {\n return `${resolve(dirname(cleanUrl(importer)), pathname)}${query}`\n }\n return id\n }\n return resolveMiniProgramModuleId?.(id, importer).then(resolved => resolved ?? null) ?? null\n },\n async load(this: WebPluginContext, id: string) {\n if (id === ENTRY_ID) {\n await scanQueue\n return generateEntryModule(state.scanResult, root, wxssOptions, options)\n }\n if (id === RESOLVED_AUTO_ROUTES_ID) {\n await scanQueue\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 this.addWatchFile?.(filename)\n for (const dependency of result.meta?.sfcSrcDeps ?? []) {\n this.addWatchFile?.(dependency)\n }\n return generateWebVueSfcStyle(result)\n }\n return null\n },\n watchChange: {\n order: 'post',\n sequential: true,\n async handler(this: WebPluginContext, id, change) {\n // Vite 的 handleHotUpdate 不处理增删;必须在结构性 HMR 前发布完整入口。\n if (enableHmr && change.event !== 'update') {\n await scanChangedFile(this, id)\n }\n },\n },\n async handleHotUpdate<Module extends object>(this: WebPluginContext, ctx: WebHmrContext<Module>) {\n const graph = devServer?.moduleGraph\n // 扫描排队期间仍可能发布前一轮拓扑;节点归属必须来自本轮实际提交的前后快照。\n // 保留前快照中的已删除 owner、外部块和旧样式后缀,同时用后快照识别恢复的 SFC。\n const snapshots = await scanChangedFile(this, ctx.file)\n const affected = graph\n ? collectSfcHmrModules(snapshots ?? [state], cleanUrl(ctx.file), graph, ctx.modules)\n : ctx.modules\n return ctx.modules || affected?.length ? affected : undefined\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":";;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,yBAAyB;CAC7B;CACA;CACA;AACF;AAEA,MAAM,0BAA0B,CAAC,UAAU,uBAAuB;AAElE,SAAS,eAAe,IAAY;CAClC,MAAM,QAAQ,GAAG,YAAY;CAC7B,OAAO,cAAc,MAAK,QAAO,MAAM,SAAS,GAAG,CAAC;AACtD;AAEA,SAAS,UAAU,IAAY;CAC7B,MAAM,QAAQ,GAAG,YAAY;CAC7B,OAAO,SAAS,MAAK,QAAO,MAAM,SAAS,GAAG,CAAC;AACjD;AAEA,SA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AAK;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"}
@@ -0,0 +1,38 @@
1
+ import { normalizePath } from "./path.mjs";
2
+ import { resolveWebVueSfcStyleLanguage } from "./vueSfc.mjs";
3
+
4
+ //#region src/plugin/sfcHmr.ts
5
+ function reachesSfcOwner(module, owners) {
6
+ const pending = [module];
7
+ const visited = /* @__PURE__ */ new Set();
8
+ while (pending.length) {
9
+ const current = pending.pop();
10
+ if (owners.has(current)) return true;
11
+ if (!visited.has(current)) {
12
+ visited.add(current);
13
+ pending.push(...current.importers);
14
+ }
15
+ }
16
+ return false;
17
+ }
18
+ /** 只将仍连接到 SFC 注册模块的派生节点交给 Vite,避免删除恢复后旧节点触发额外刷新。 */
19
+ function collectSfcHmrModules(states, changedFile, graph, modules) {
20
+ const changed = normalizePath(changedFile);
21
+ const owners = /* @__PURE__ */ new Set();
22
+ const candidates = /* @__PURE__ */ new Set();
23
+ for (const state of states) for (const [filename, result] of state.sfcResults) {
24
+ if (filename !== changed && !result.meta?.sfcSrcDeps?.some((dependency) => normalizePath(dependency) === changed)) continue;
25
+ for (const file of [filename, `${filename}.${resolveWebVueSfcStyleLanguage(result, filename)}`]) for (const module of graph.getModulesByFile(file) ?? []) {
26
+ candidates.add(module);
27
+ if (module.id && normalizePath(module.id) === filename) owners.add(module);
28
+ }
29
+ }
30
+ const affected = new Set(modules);
31
+ for (const module of candidates) if (reachesSfcOwner(module, owners)) affected.add(module);
32
+ else affected.delete(module);
33
+ return [...affected];
34
+ }
35
+
36
+ //#endregion
37
+ export { collectSfcHmrModules };
38
+ //# sourceMappingURL=sfcHmr.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sfcHmr.mjs","names":[],"sources":["../../src/plugin/sfcHmr.ts"],"sourcesContent":["import type { ModuleNode } from 'vite'\nimport type { WebDevServer } from './hostTypes'\nimport type { ScanState } from './types'\nimport { normalizePath } from './path'\nimport { resolveWebVueSfcStyleLanguage } from './vueSfc'\n\nfunction reachesSfcOwner(module: ModuleNode, owners: Set<ModuleNode>) {\n const pending = [module]\n const visited = new Set<ModuleNode>()\n while (pending.length) {\n const current = pending.pop()!\n if (owners.has(current)) {\n return true\n }\n if (!visited.has(current)) {\n visited.add(current)\n pending.push(...current.importers)\n }\n }\n return false\n}\n\n/** 只将仍连接到 SFC 注册模块的派生节点交给 Vite,避免删除恢复后旧节点触发额外刷新。 */\nexport function collectSfcHmrModules<Module extends object>(\n states: readonly ScanState[],\n changedFile: string,\n graph: NonNullable<WebDevServer['moduleGraph']>,\n modules?: Module[],\n) {\n const changed = normalizePath(changedFile)\n const owners = new Set<ModuleNode>()\n const candidates = new Set<ModuleNode>()\n for (const state of states) {\n for (const [filename, result] of state.sfcResults) {\n if (filename !== changed && !result.meta?.sfcSrcDeps?.some(dependency => normalizePath(dependency) === changed)) {\n continue\n }\n for (const file of [filename, `${filename}.${resolveWebVueSfcStyleLanguage(result, filename)}`]) {\n for (const module of graph.getModulesByFile(file) ?? []) {\n candidates.add(module)\n if (module.id && normalizePath(module.id) === filename) {\n owners.add(module)\n }\n }\n }\n }\n }\n const affected = new Set(modules)\n for (const module of candidates) {\n // Vite 的 unlink 会拆除反向依赖,但保留旧文件节点;仅有节点身份不能证明它仍属于当前 SFC。\n if (reachesSfcOwner(module, owners)) {\n affected.add(module as Module)\n }\n else {\n affected.delete(module as Module)\n }\n }\n return [...affected]\n}\n"],"mappings":";;;;AAMA,SAAS,gBAAgB,QAAoB,QAAyB;CACpE,MAAM,UAAU,CAAC,MAAM;CACvB,MAAM,0BAAU,IAAI,IAAgB;CACpC,OAAO,QAAQ,QAAQ;EACrB,MAAM,UAAU,QAAQ,IAAI;EAC5B,IAAI,OAAO,IAAI,OAAO,GACpB,OAAO;EAET,IAAI,CAAC,QAAQ,IAAI,OAAO,GAAG;GACzB,QAAQ,IAAI,OAAO;GACnB,QAAQ,KAAK,GAAG,QAAQ,SAAS;EACnC;CACF;CACA,OAAO;AACT;;AAGA,SAAgB,qBACd,QACA,aACA,OACA,SACA;CACA,MAAM,UAAU,cAAc,WAAW;CACzC,MAAM,yBAAS,IAAI,IAAgB;CACnC,MAAM,6BAAa,IAAI,IAAgB;CACvC,KAAK,MAAM,SAAS,QAClB,KAAK,MAAM,CAAC,UAAU,WAAW,MAAM,YAAY;EACjD,IAAI,aAAa,WAAW,CAAC,OAAO,MAAM,YAAY,MAAK,eAAc,cAAc,UAAU,MAAM,OAAO,GAC5G;EAEF,KAAK,MAAM,QAAQ,CAAC,UAAU,GAAG,SAAS,GAAG,8BAA8B,QAAQ,QAAQ,GAAG,GAC5F,KAAK,MAAM,UAAU,MAAM,iBAAiB,IAAI,KAAK,CAAC,GAAG;GACvD,WAAW,IAAI,MAAM;GACrB,IAAI,OAAO,MAAM,cAAc,OAAO,EAAE,MAAM,UAC5C,OAAO,IAAI,MAAM;EAErB;CAEJ;CAEF,MAAM,WAAW,IAAI,IAAI,OAAO;CAChC,KAAK,MAAM,UAAU,YAEnB,IAAI,gBAAgB,QAAQ,MAAM,GAChC,SAAS,IAAI,MAAgB;MAG7B,SAAS,OAAO,MAAgB;CAGpC,OAAO,CAAC,GAAG,QAAQ;AACrB"}
@@ -1,8 +1,8 @@
1
1
  import { compileWxml } from "../compiler/wxml/compile.mjs";
2
- import { appendInlineQuery, resolveTemplatePathSync, resolveWxsPathSync, toRelativeImport } from "./path.mjs";
2
+ import { appendInlineQuery, normalizePath, resolveTemplatePathSync, resolveWxsPathSync, toRelativeImport } from "./path.mjs";
3
3
  import { resolveScriptFile } from "./files.mjs";
4
4
  import path from "pathe";
5
- import { compileVueFile, isUniAppCompatibilityFile, transformUniAppSource } from "wevu/compiler";
5
+ import { compileVueFile, getMiniProgramTemplatePlatform, isUniAppCompatibilityFile, transformUniAppSource } from "wevu/compiler";
6
6
  import { transform } from "esbuild";
7
7
  import { fs } from "@weapp-core/shared/fs";
8
8
  import { parse } from "@babel/parser";
@@ -12,6 +12,10 @@ import MagicString from "magic-string";
12
12
 
13
13
  //#region src/plugin/vueSfc.ts
14
14
  const traverse = _babelTraverse;
15
+ const webTemplatePlatform = {
16
+ ...getMiniProgramTemplatePlatform("weapp"),
17
+ nativeSlotContext: false
18
+ };
15
19
  async function resolveSfcSrc(request, importer, srcRoot, resolveId) {
16
20
  if (request.startsWith("@/")) return path.resolve(srcRoot, request.slice(2));
17
21
  if (request.startsWith(".")) return path.resolve(path.dirname(importer), request);
@@ -28,6 +32,7 @@ async function compileWebVueSfc(options) {
28
32
  isApp: meta.kind === "app",
29
33
  isPage: meta.kind === "page",
30
34
  sourceMap: false,
35
+ template: { platform: webTemplatePlatform },
31
36
  style: {
32
37
  preprocessOptions: stylePreprocessOptions,
33
38
  preserveDeepSelectors: true,
@@ -56,12 +61,12 @@ async function compileWebVueSfc(options) {
56
61
  return resolveSfcSrc(request, importer, srcRoot, resolveId);
57
62
  } }
58
63
  });
59
- state.sfcResults.set(filename, result);
64
+ state.sfcResults.set(normalizePath(filename), result);
60
65
  for (const dependency of result.meta?.sfcSrcDeps ?? []) state.templatePathSet.add(dependency);
61
66
  return result;
62
67
  }
63
68
  async function ensureWebVueSfcResult(options) {
64
- const cached = options.state.sfcResults.get(options.filename);
69
+ const cached = options.state.sfcResults.get(normalizePath(options.filename));
65
70
  if (cached) return cached;
66
71
  const source = options.source ?? await fs.readFile(options.filename, "utf8");
67
72
  return await compileWebVueSfc({
@@ -91,7 +96,7 @@ async function transformWebVueSfcScript(options) {
91
96
  });
92
97
  const s = new MagicString(code);
93
98
  const templateIdent = meta.kind === "app" ? void 0 : "__weapp_sfc_template__";
94
- const styleIdent = meta.kind === "app" ? void 0 : "__weapp_sfc_style__";
99
+ const styleIdent = "__weapp_sfc_style__";
95
100
  const registerName = getSfcRegisterName(meta.kind);
96
101
  const factoryName = getSfcFactoryName(meta.kind);
97
102
  const registerMetaCode = createRegisterMetaCode(meta, templateIdent, styleIdent);
@@ -106,10 +111,8 @@ async function transformWebVueSfcScript(options) {
106
111
  if (!transformed) throw new Error(`[@weapp-vite/web] Vue SFC 未生成 ${factoryName} 注册调用: ${filename}`);
107
112
  const imports = [`import { ${registerName} } from '${runtimeModuleId}'`];
108
113
  if (templateIdent) imports.push(`import ${templateIdent} from '${toRelativeImport(filename, filename)}?weapp-web-sfc-template'`);
109
- if (styleIdent) {
110
- const styleFilename = `${filename}.${styleLanguage}`;
111
- imports.push(`import ${styleIdent} from '${appendInlineQuery(`${toRelativeImport(filename, styleFilename)}?weapp-web-sfc-style`)}'`);
112
- }
114
+ const styleFilename = `${filename}.${styleLanguage}`;
115
+ imports.push(`import ${styleIdent} from '${appendInlineQuery(`${toRelativeImport(filename, styleFilename)}?weapp-web-sfc-style`)}'`);
113
116
  s.prepend(`${imports.join("\n")}\n`);
114
117
  if (enableHmr && hmrAcceptCode) s.append(`\n${hmrAcceptCode}\n`);
115
118
  const transpiled = await transform(s.toString(), {
@@ -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, 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,2BAA2B;CAC5G,MAAM,SAAS,UAAU,0BAA0B,UAAU,SAAS,OAAO,OAAO,IAChF,sBAAsB,QAAQ,QAAQ;EAAE;EAAU,QAAQ;CAAK,CAAC,CAAC,CAAC,OAClE,Q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AAqC,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, getMiniProgramTemplatePlatform, isUniAppCompatibilityFile, transformUniAppSource } from 'wevu/compiler'\nimport { compileWxml } from '../compiler/wxml'\nimport { resolveScriptFile } from './files'\nimport { appendInlineQuery, normalizePath, resolveTemplatePathSync, resolveWxsPathSync, toRelativeImport } from './path'\n\nconst traverse = _babelTraverse\nconst webTemplatePlatform = { ...getMiniProgramTemplatePlatform('weapp'), nativeSlotContext: false }\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 template: { platform: webTemplatePlatform },\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(normalizePath(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(normalizePath(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 = '__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 const styleFilename = `${filename}.${styleLanguage}`\n imports.push(`import ${styleIdent} from '${appendInlineQuery(`${toRelativeImport(filename, styleFilename)}?weapp-web-sfc-style`)}'`)\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":";;;;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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"}
@@ -0,0 +1,25 @@
1
+ import { injectStyle, removeStyle } from "./style.mjs";
2
+
3
+ //#region src/runtime/appStyle.ts
4
+ const styleId = "weapp-web-app-style";
5
+ const consumers = /* @__PURE__ */ new Set();
6
+ let appStyle = "";
7
+ function getAppStyle() {
8
+ return appStyle;
9
+ }
10
+ /** 应用样式是页面及非隔离组件的共享输入;主题变量通过 document 自然继承。 */
11
+ function setAppStyle(style) {
12
+ if (style === appStyle) return;
13
+ appStyle = style;
14
+ if (style) injectStyle(style, styleId);
15
+ else removeStyle(styleId);
16
+ for (const consumer of consumers) consumer.requestUpdate();
17
+ }
18
+ function trackAppStyle(consumer, enabled) {
19
+ if (enabled) consumers.add(consumer);
20
+ else consumers.delete(consumer);
21
+ }
22
+
23
+ //#endregion
24
+ export { getAppStyle, setAppStyle, trackAppStyle };
25
+ //# sourceMappingURL=appStyle.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"appStyle.mjs","names":[],"sources":["../../src/runtime/appStyle.ts"],"sourcesContent":["import { injectStyle, removeStyle } from './style'\n\ninterface AppStyleConsumer {\n requestUpdate: () => unknown\n}\n\nconst styleId = 'weapp-web-app-style'\nconst consumers = new Set<AppStyleConsumer>()\nlet appStyle = ''\n\nexport function getAppStyle() {\n return appStyle\n}\n\n/** 应用样式是页面及非隔离组件的共享输入;主题变量通过 document 自然继承。 */\nexport function setAppStyle(style: string) {\n if (style === appStyle) {\n return\n }\n appStyle = style\n if (style) {\n injectStyle(style, styleId)\n }\n else {\n removeStyle(styleId)\n }\n for (const consumer of consumers) {\n consumer.requestUpdate()\n }\n}\n\nexport function trackAppStyle(consumer: AppStyleConsumer, enabled: boolean) {\n if (enabled) {\n consumers.add(consumer)\n }\n else {\n consumers.delete(consumer)\n }\n}\n"],"mappings":";;;AAMA,MAAM,UAAU;AAChB,MAAM,4BAAY,IAAI,IAAsB;AAC5C,IAAI,WAAW;AAEf,SAAgB,cAAc;CAC5B,OAAO;AACT;;AAGA,SAAgB,YAAY,OAAe;CACzC,IAAI,UAAU,UACZ;CAEF,WAAW;CACX,IAAI,OACF,YAAY,OAAO,OAAO;MAG1B,YAAY,OAAO;CAErB,KAAK,MAAM,YAAY,WACrB,SAAS,cAAc;AAE3B;AAEA,SAAgB,cAAc,UAA4B,SAAkB;CAC1E,IAAI,SACF,UAAU,IAAI,QAAQ;MAGtB,UAAU,OAAO,QAAQ;AAE7B"}
@@ -1,16 +1,18 @@
1
+ import { getAppStyle, trackAppStyle } from "../appStyle.mjs";
1
2
  import { supportsLit } from "./constants.mjs";
3
+ import { markComponentEvent, registerComponentEventTarget } from "../componentEvents.mjs";
4
+ import { hasOwn } from "../utils/object.mjs";
2
5
  import { createComponentPublicInstance } from "./publicInstance.mjs";
3
6
  import { createIntersectionObserverBridge } from "../polyfill/intersectionObserver.mjs";
4
7
  import { createRenderContext } from "../renderContext.mjs";
5
- import { hasOwn } from "../utils/object.mjs";
6
8
  import { createScopedSelectorQuery, resolveRenderRoot, selectRuntimeComponent, selectRuntimeComponents } from "./dom.mjs";
7
9
  import { bindRuntimeEvents } from "./events.mjs";
8
10
  import { runComponentObservers } from "./observers.mjs";
9
11
  import { resolveRelationNodes } from "./relations.mjs";
10
12
  import { createWebSlotsProxy } from "./slots.mjs";
11
- import { assignDataPath, cloneValue, coerceValue, parseDataPath, resolveDataPath, toCamelCase } from "./utils.mjs";
13
+ import { assignDataPath, cloneCommittedValue, cloneValue, coerceValue, parseDataPath, resolveDataPath, toCamelCase } from "./utils.mjs";
12
14
  import { clearVirtualHostClasses, clearVirtualHostParts, syncVirtualHostClasses, syncVirtualHostParts } from "./virtualHost.mjs";
13
- import { WEVU_HOST_COMMIT_PROMISE_KEY } from "@weapp-core/constants";
15
+ import { WEVU_HOST_COMMIT_PROMISE_KEY, WEVU_HOST_INSTALL_METHOD_KEY } from "@weapp-core/constants";
14
16
  import { html } from "lit";
15
17
  import { unsafeHTML } from "lit/directives/unsafe-html.js";
16
18
 
@@ -35,6 +37,7 @@ function createComponentElementClass({ BaseElement, runtimeState, instances }) {
35
37
  #state;
36
38
  #properties;
37
39
  #methods = {};
40
+ #setupMethods = {};
38
41
  #publicInstance;
39
42
  #exposedMethodNames = /* @__PURE__ */ new Set();
40
43
  #isMounted = false;
@@ -53,6 +56,7 @@ function createComponentElementClass({ BaseElement, runtimeState, instances }) {
53
56
  properties;
54
57
  constructor() {
55
58
  super();
59
+ registerComponentEventTarget(this);
56
60
  const dataOption = runtimeState.componentRef.data ?? {};
57
61
  this.#properties = { ...runtimeState.defaultPropertyValues };
58
62
  this.#state = {
@@ -76,7 +80,7 @@ function createComponentElementClass({ BaseElement, runtimeState, instances }) {
76
80
  get: () => this.#properties
77
81
  }
78
82
  });
79
- this.#publicInstance = createComponentPublicInstance(this, WeappWebComponent.prototype, (key) => typeof key === "string" ? this.#methods[key] : void 0);
83
+ this.#publicInstance = createComponentPublicInstance(this, WeappWebComponent.prototype, (key) => typeof key === "string" ? this.#methods[key] : void 0, this.#properties);
80
84
  for (const [propName] of runtimeState.propertyEntries) Object.defineProperty(this, propName, {
81
85
  configurable: true,
82
86
  enumerable: true,
@@ -116,11 +120,18 @@ function createComponentElementClass({ BaseElement, runtimeState, instances }) {
116
120
  callback?.();
117
121
  }
118
122
  triggerEvent(name, detail, options = {}) {
119
- this.dispatchEvent(new CustomEvent(name, {
123
+ this.dispatchEvent(markComponentEvent(new CustomEvent(name, {
120
124
  detail,
121
125
  bubbles: options.bubbles ?? false,
122
126
  composed: options.composed ?? false
123
- }));
127
+ })));
128
+ }
129
+ [WEVU_HOST_INSTALL_METHOD_KEY](methods) {
130
+ const bound = {};
131
+ for (const [name, method] of Object.entries(methods)) bound[name] = method.bind(this.#publicInstance);
132
+ this.#setupMethods = bound;
133
+ this.#syncMethods(runtimeState.componentRef.methods);
134
+ this.requestUpdate();
124
135
  }
125
136
  createSelectorQuery() {
126
137
  return createScopedSelectorQuery(this);
@@ -146,18 +157,21 @@ function createComponentElementClass({ BaseElement, runtimeState, instances }) {
146
157
  }
147
158
  }
148
159
  connectedCallback() {
160
+ instances.add(this);
149
161
  const superConnected = BaseElement.prototype.connectedCallback;
150
162
  if (supportsLit && typeof superConnected === "function") superConnected.call(this);
151
163
  this.#applyAttributes();
152
164
  if (runtimeState.observerInitEnabled) this.#runInitialObservers();
153
165
  runtimeState.lifetimes.attached?.call(this.#publicInstance);
154
166
  this.#isMounted = true;
155
- if (!supportsLit) this.#renderLegacy();
167
+ trackAppStyle(this, runtimeState.inheritAppStyle);
168
+ this.requestUpdate();
156
169
  }
157
170
  disconnectedCallback() {
158
171
  const superDisconnected = BaseElement.prototype.disconnectedCallback;
159
172
  if (supportsLit && typeof superDisconnected === "function") superDisconnected.call(this);
160
173
  this.#isMounted = false;
174
+ trackAppStyle(this, false);
161
175
  instances.delete(this);
162
176
  runtimeState.lifetimes.detached?.call(this.#publicInstance);
163
177
  }
@@ -179,14 +193,9 @@ function createComponentElementClass({ BaseElement, runtimeState, instances }) {
179
193
  }
180
194
  render() {
181
195
  const result = runtimeState.templateRef(this.#state, this.#renderContext);
182
- const styleMarkup = runtimeState.styleRef ? html`<style>${runtimeState.styleRef}</style>` : null;
183
- if (typeof result === "string") {
184
- this.#usesLegacyTemplate = true;
185
- return html`${styleMarkup}${unsafeHTML(result)}`;
186
- }
187
- this.#usesLegacyTemplate = false;
188
- if (styleMarkup) return html`${styleMarkup}${result}`;
189
- return result;
196
+ const appStyle = runtimeState.inheritAppStyle ? getAppStyle() : "";
197
+ this.#usesLegacyTemplate = typeof result === "string";
198
+ return html`<style>${appStyle}</style><style>${runtimeState.styleRef}</style>${typeof result === "string" ? unsafeHTML(result) : result}`;
190
199
  }
191
200
  requestUpdate(name, oldValue, options) {
192
201
  const superRequestUpdate = BaseElement.prototype.requestUpdate;
@@ -202,12 +211,17 @@ function createComponentElementClass({ BaseElement, runtimeState, instances }) {
202
211
  let changed = false;
203
212
  const changedKeys = [];
204
213
  const previousProperties = {};
214
+ let copiedContainers;
205
215
  for (const [path, value] of Object.entries(patch)) {
206
216
  const segments = parseDataPath(path);
207
217
  const topKey = segments[0];
208
- if (!topKey || topKey === "$slots" || Object.is(resolveDataPath(this.#state, segments), value)) continue;
218
+ if (!topKey || topKey === "$slots") continue;
219
+ let nextValue = value;
220
+ if (value !== null && typeof value === "object") nextValue = cloneCommittedValue(value);
221
+ else if (Object.is(resolveDataPath(this.#state, segments), value)) continue;
209
222
  if (hasOwn(this.#properties, topKey) && !hasOwn(previousProperties, topKey)) previousProperties[topKey] = this.#properties[topKey];
210
- assignDataPath(this.#state, segments, value);
223
+ if (segments.length > 1) copiedContainers ??= /* @__PURE__ */ new WeakSet();
224
+ assignDataPath(this.#state, segments, nextValue, copiedContainers);
211
225
  if (hasOwn(this.#properties, topKey)) this.#properties[topKey] = this.#state[topKey];
212
226
  changedKeys.push(path);
213
227
  changed = true;
@@ -244,6 +258,7 @@ function createComponentElementClass({ BaseElement, runtimeState, instances }) {
244
258
  const resolved = nextMethods ?? {};
245
259
  const bound = {};
246
260
  for (const [name, fn] of Object.entries(resolved)) if (typeof fn === "function") bound[name] = fn.bind(this.#publicInstance);
261
+ Object.assign(bound, this.#setupMethods);
247
262
  for (const name of this.#exposedMethodNames) {
248
263
  if (name in bound) continue;
249
264
  const descriptor = Object.getOwnPropertyDescriptor(this, name);
@@ -252,8 +267,12 @@ function createComponentElementClass({ BaseElement, runtimeState, instances }) {
252
267
  }
253
268
  for (const key of Object.keys(this.#methods)) if (!(key in bound)) delete this.#methods[key];
254
269
  for (const [key, fn] of Object.entries(bound)) {
270
+ const previous = this.#methods[key];
255
271
  this.#methods[key] = fn;
256
- if (!this.#exposedMethodNames.has(key) && key in this) continue;
272
+ if (this.#exposedMethodNames.has(key)) {
273
+ const descriptor = Object.getOwnPropertyDescriptor(this, key);
274
+ if (!descriptor?.configurable || descriptor.value !== previous) continue;
275
+ } else if (key in this) continue;
257
276
  Object.defineProperty(this, key, {
258
277
  configurable: true,
259
278
  enumerable: false,
@@ -266,6 +285,7 @@ function createComponentElementClass({ BaseElement, runtimeState, instances }) {
266
285
  }
267
286
  __weappSync(nextMethods) {
268
287
  this.#syncMethods(nextMethods);
288
+ trackAppStyle(this, this.#isMounted && runtimeState.inheritAppStyle);
269
289
  this.requestUpdate();
270
290
  }
271
291
  __weappInvokePageLifetime(type) {
@@ -275,7 +295,7 @@ function createComponentElementClass({ BaseElement, runtimeState, instances }) {
275
295
  #renderLegacy() {
276
296
  const result = runtimeState.templateRef(this.#state, this.#renderContext);
277
297
  const root = resolveRenderRoot(this);
278
- const styleMarkup = runtimeState.styleRef ? `<style>${runtimeState.styleRef}</style>` : "";
298
+ const styleMarkup = `<style>${runtimeState.inheritAppStyle ? getAppStyle() : ""}</style><style>${runtimeState.styleRef}</style>`;
279
299
  if (typeof result === "string") {
280
300
  root.innerHTML = `${styleMarkup}${result}`;
281
301
  bindRuntimeEvents(root, this.#methods, this);