@weapp-vite/web 1.3.18 → 1.3.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/compiler/wxml/compile.mjs.map +1 -1
- package/dist/compiler/wxml/interpolation.mjs.map +1 -1
- package/dist/compiler/wxml/parser.mjs.map +1 -1
- package/dist/compiler/wxml/renderer.mjs.map +1 -1
- package/dist/compiler/wxml/specialNodes.mjs.map +1 -1
- package/dist/compiler/wxs.mjs.map +1 -1
- package/dist/css/wxss.mjs.map +1 -1
- package/dist/plugin/entry.mjs.map +1 -1
- package/dist/plugin/files.mjs.map +1 -1
- package/dist/plugin/index.mjs.map +1 -1
- package/dist/plugin/path.mjs.map +1 -1
- package/dist/plugin/scan.mjs.map +1 -1
- package/dist/plugin/scanConfig.mjs.map +1 -1
- package/dist/runtime/button/helpers.mjs.map +1 -1
- package/dist/runtime/button/index.mjs.map +1 -1
- package/dist/runtime/component/behavior.mjs.map +1 -1
- package/dist/runtime/component/state.mjs.map +1 -1
- package/dist/runtime/legacyTemplate/expression.mjs.map +1 -1
- package/dist/runtime/legacyTemplate/index.mjs.map +1 -1
- package/dist/runtime/polyfill/auth.mjs.map +1 -1
- package/dist/runtime/polyfill/canvasContext.mjs.map +1 -1
- package/dist/runtime/polyfill/deviceApi.mjs.map +1 -1
- package/dist/runtime/polyfill/filePicker.mjs.map +1 -1
- package/dist/runtime/polyfill/fileSystemManager.mjs.map +1 -1
- package/dist/runtime/polyfill/files.mjs.map +1 -1
- package/dist/runtime/polyfill/interaction.mjs.map +1 -1
- package/dist/runtime/polyfill/interactionApi.mjs.map +1 -1
- package/dist/runtime/polyfill/location.mjs.map +1 -1
- package/dist/runtime/polyfill/locationApi.mjs.map +1 -1
- package/dist/runtime/polyfill/mediaActions.mjs.map +1 -1
- package/dist/runtime/polyfill/mediaApi/picker.mjs.map +1 -1
- package/dist/runtime/polyfill/mediaApi/process.mjs.map +1 -1
- package/dist/runtime/polyfill/mediaInfo.mjs.map +1 -1
- package/dist/runtime/polyfill/mediaPicker.mjs.map +1 -1
- package/dist/runtime/polyfill/mediaProcess.mjs.map +1 -1
- package/dist/runtime/polyfill/network/request.mjs.map +1 -1
- package/dist/runtime/polyfill/network/status.mjs.map +1 -1
- package/dist/runtime/polyfill/platformRuntime.mjs.map +1 -1
- package/dist/runtime/polyfill/routeRuntime/lifecycle.mjs.map +1 -1
- package/dist/runtime/polyfill/routeRuntime/options.mjs.map +1 -1
- package/dist/runtime/polyfill/routeRuntime/url.mjs.map +1 -1
- package/dist/runtime/polyfill/runtimeOps.mjs.map +1 -1
- package/dist/runtime/polyfill/storage.mjs.map +1 -1
- package/dist/runtime/polyfill/subscribe.mjs.map +1 -1
- package/dist/runtime/polyfill/system.mjs.map +1 -1
- package/dist/runtime/polyfill/systemApi.mjs.map +1 -1
- package/dist/runtime/polyfill/ui.mjs.map +1 -1
- package/dist/runtime/polyfill/videoContext.mjs.map +1 -1
- package/dist/runtime/renderContext.mjs.map +1 -1
- package/dist/shared/slugify.mjs.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compile.mjs","names":[],"sources":["../../../src/compiler/wxml/compile.ts"],"sourcesContent":["import type {\n ImportEntry,\n IncludeEntry,\n TemplateDefinition,\n WxmlCompileOptions,\n WxmlCompileResult,\n WxsEntry,\n} from './types'\n\nimport { readFileSync } from 'node:fs'\nimport { addDependency, createDependencyContext, warnCircularTemplate, warnReadTemplate } from './dependency'\nimport { buildNavigationBarAttrs, extractNavigationBarFromPageMeta } from './navigation'\nimport { parseWxml } from './parser'\nimport { renderer } from './renderer'\nimport { collectSpecialNodes, normalizeTemplatePath, shouldMarkWxsImport, toRelativeImport } from './specialNodes'\n\nexport function compileWxml(options: WxmlCompileOptions): WxmlCompileResult {\n const dependencyContext = options.dependencyContext ?? createDependencyContext()\n const expandDependencies = options.expandDependencies ?? !options.dependencyContext\n const warnings = dependencyContext.warnings\n\n const expandDependencyTree = (dependencies: string[], importer: string) => {\n for (const target of dependencies) {\n if (!target) {\n continue\n }\n if (dependencyContext.active.has(target)) {\n warnCircularTemplate(dependencyContext, importer, target)\n continue\n }\n if (dependencyContext.visited.has(target)) {\n continue\n }\n dependencyContext.visited.add(target)\n dependencyContext.active.add(target)\n let source: string\n try {\n source = readFileSync(target, 'utf8')\n }\n catch {\n warnReadTemplate(dependencyContext, target)\n dependencyContext.active.delete(target)\n continue\n }\n try {\n const result = compileWxml({\n id: target,\n source,\n resolveTemplatePath: options.resolveTemplatePath,\n resolveWxsPath: options.resolveWxsPath,\n dependencyContext,\n expandDependencies: false,\n })\n expandDependencyTree(result.dependencies, target)\n }\n catch (error) {\n if (error instanceof Error && error.message) {\n warnings.push(`[web] 无法解析模板依赖: ${target} ${error.message}`)\n }\n }\n dependencyContext.active.delete(target)\n }\n }\n\n let nodes = parseWxml(options.source)\n let navigationBarAttrs: Record<string, string> | undefined\n if (options.navigationBar) {\n const extracted = extractNavigationBarFromPageMeta(nodes)\n nodes = extracted.nodes\n if (extracted.warnings.length > 0) {\n warnings.push(...extracted.warnings)\n }\n navigationBarAttrs = extracted.attrs\n }\n\n const templates: TemplateDefinition[] = []\n const includes: IncludeEntry[] = []\n const imports: ImportEntry[] = []\n const wxs: WxsEntry[] = []\n const wxsModules = new Map<string, string>()\n\n const renderNodesList = collectSpecialNodes(nodes, {\n templates,\n includes,\n imports,\n wxs,\n wxsModules,\n warnings,\n sourceId: options.id,\n resolveTemplate: (raw: string) => options.resolveTemplatePath(raw, options.id),\n resolveWxs: (raw: string) => options.resolveWxsPath(raw, options.id),\n })\n\n if (options.navigationBar && options.navigationBar.config.navigationStyle !== 'custom') {\n const attrs = buildNavigationBarAttrs(options.navigationBar.config, navigationBarAttrs)\n renderNodesList.unshift({\n type: 'element',\n name: 'weapp-navigation-bar',\n attribs: attrs,\n })\n }\n\n const importLines: string[] = [\n `import { html } from 'lit'`,\n `import { repeat } from 'lit/directives/repeat.js'`,\n ]\n const bodyLines: string[] = []\n const directDependencies: string[] = []\n\n for (const entry of imports) {\n const importPath = normalizeTemplatePath(toRelativeImport(options.id, entry.id))\n importLines.push(`import { templates as ${entry.importName} } from '${importPath}'`)\n addDependency(entry.id, dependencyContext, directDependencies)\n }\n\n for (const entry of includes) {\n const importPath = normalizeTemplatePath(toRelativeImport(options.id, entry.id))\n importLines.push(`import { render as ${entry.importName} } from '${importPath}'`)\n addDependency(entry.id, dependencyContext, directDependencies)\n }\n\n for (const entry of wxs) {\n if (entry.kind === 'src') {\n const baseImport = normalizeTemplatePath(toRelativeImport(options.id, entry.value))\n const importPath = shouldMarkWxsImport(entry.value)\n ? `${baseImport}?wxs`\n : baseImport\n importLines.push(`import ${entry.importName} from '${importPath}'`)\n addDependency(entry.value, dependencyContext, directDependencies)\n }\n }\n\n if (templates.length > 0 || imports.length > 0) {\n const templatePairs: string[] = []\n for (const entry of imports) {\n templatePairs.push(`...${entry.importName}`)\n }\n for (const template of templates) {\n const rendered = renderer.renderNodes(template.nodes, 'scope', '__wxs_modules', options.componentTags)\n templatePairs.push(`${JSON.stringify(template.name)}: (scope, ctx) => ${rendered}`)\n }\n bodyLines.push(`const __templates = { ${templatePairs.join(', ')} }`)\n }\n else {\n bodyLines.push(`const __templates = {}`)\n }\n\n if (wxs.length > 0) {\n bodyLines.push(`const __wxs_inline_cache = Object.create(null)`)\n bodyLines.push(`let __wxs_modules = {}`)\n const wxsMapEntries: string[] = []\n for (const entry of wxs) {\n if (entry.kind === 'inline') {\n const inlineCode = entry.value.trim()\n const cacheKey = JSON.stringify(entry.module)\n if (inlineCode) {\n bodyLines.push(`function ${entry.importName}(ctx) {`)\n bodyLines.push(` if (!__wxs_inline_cache[${cacheKey}]) {`)\n bodyLines.push(` __wxs_inline_cache[${cacheKey}] = ctx.createWxsModule(${JSON.stringify(inlineCode)}, ${JSON.stringify(options.id)})`)\n bodyLines.push(` }`)\n bodyLines.push(` return __wxs_inline_cache[${cacheKey}]`)\n bodyLines.push(`}`)\n }\n else {\n bodyLines.push(`function ${entry.importName}() { return {} }`)\n }\n wxsMapEntries.push(`${JSON.stringify(entry.module)}: ${entry.importName}(ctx)`)\n continue\n }\n wxsMapEntries.push(`${JSON.stringify(entry.module)}: ${entry.importName}`)\n }\n bodyLines.push(`function __resolveWxsModules(ctx) {`)\n bodyLines.push(` return { ${wxsMapEntries.join(', ')} }`)\n bodyLines.push(`}`)\n }\n else {\n bodyLines.push(`const __wxs_modules = {}`)\n }\n\n const includesRender = includes.map(entry => `${entry.importName}(scope, ctx)`)\n const renderContent = renderer.renderNodes(renderNodesList, 'scope', '__wxs_modules', options.componentTags)\n const contentExpr = includesRender.length > 0\n ? `[${[...includesRender, renderContent].join(', ')}]`\n : renderContent\n\n bodyLines.push(`export function render(scope, ctx) {`)\n if (wxs.length > 0) {\n bodyLines.push(` __wxs_modules = __resolveWxsModules(ctx)`)\n }\n bodyLines.push(` return ${contentExpr}`)\n bodyLines.push(`}`)\n bodyLines.push(`export const templates = __templates`)\n bodyLines.push(`export default render`)\n\n if (expandDependencies) {\n dependencyContext.visited.add(options.id)\n dependencyContext.active.add(options.id)\n expandDependencyTree(directDependencies, options.id)\n dependencyContext.active.delete(options.id)\n }\n\n const code = [...importLines, '', ...bodyLines].join('\\n')\n const dependencies = expandDependencies ? dependencyContext.dependencies : directDependencies\n return {\n code,\n dependencies,\n warnings: warnings.length > 0 ? warnings : undefined,\n }\n}\n"],"mappings":";;;;;;;;AAgBA,SAAgB,YAAY,SAAgD;CAC1E,MAAM,oBAAoB,QAAQ,qBAAqB,yBAAyB;CAChF,MAAM,qBAAqB,QAAQ,sBAAsB,CAAC,QAAQ;CAClE,MAAM,WAAW,kBAAkB;CAEnC,MAAM,wBAAwB,cAAwB,aAAqB;AACzE,OAAK,MAAM,UAAU,cAAc;AACjC,OAAI,CAAC,OACH;AAEF,OAAI,kBAAkB,OAAO,IAAI,OAAO,EAAE;AACxC,yBAAqB,mBAAmB,UAAU,OAAO;AACzD;;AAEF,OAAI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D,WAAU,KAAK,wBAAwB;AAEvC,KAAI,oBAAoB;AACtB,oBAAkB,QAAQ,IAAI,QAAQ,GAAG;AACzC,oBAAkB,OAAO,IAAI,QAAQ,GAAG;AACxC,uBAAqB,oBAAoB,QAAQ,GAAG;AACpD,oBAAkB,OAAO,OAAO,QAAQ,GAAG;;AAK7C,QAAO;EACL,MAHW;GAAC,GAAG;GAAa;GAAI,GAAG;GAAU,CAAC,KAAK,KAAK;EAIxD,cAHmB,qBAAqB,kBAAkB,eAAe;EAIzE,UAAU,SAAS,SAAS,IAAI,WAAW;EAC5C"}
|
|
1
|
+
{"version":3,"file":"compile.mjs","names":[],"sources":["../../../src/compiler/wxml/compile.ts"],"sourcesContent":["import type {\n ImportEntry,\n IncludeEntry,\n TemplateDefinition,\n WxmlCompileOptions,\n WxmlCompileResult,\n WxsEntry,\n} from './types'\n\nimport { readFileSync } from 'node:fs'\nimport { addDependency, createDependencyContext, warnCircularTemplate, warnReadTemplate } from './dependency'\nimport { buildNavigationBarAttrs, extractNavigationBarFromPageMeta } from './navigation'\nimport { parseWxml } from './parser'\nimport { renderer } from './renderer'\nimport { collectSpecialNodes, normalizeTemplatePath, shouldMarkWxsImport, toRelativeImport } from './specialNodes'\n\nexport function compileWxml(options: WxmlCompileOptions): WxmlCompileResult {\n const dependencyContext = options.dependencyContext ?? createDependencyContext()\n const expandDependencies = options.expandDependencies ?? !options.dependencyContext\n const warnings = dependencyContext.warnings\n\n const expandDependencyTree = (dependencies: string[], importer: string) => {\n for (const target of dependencies) {\n if (!target) {\n continue\n }\n if (dependencyContext.active.has(target)) {\n warnCircularTemplate(dependencyContext, importer, target)\n continue\n }\n if (dependencyContext.visited.has(target)) {\n continue\n }\n dependencyContext.visited.add(target)\n dependencyContext.active.add(target)\n let source: string\n try {\n source = readFileSync(target, 'utf8')\n }\n catch {\n warnReadTemplate(dependencyContext, target)\n dependencyContext.active.delete(target)\n continue\n }\n try {\n const result = compileWxml({\n id: target,\n source,\n resolveTemplatePath: options.resolveTemplatePath,\n resolveWxsPath: options.resolveWxsPath,\n dependencyContext,\n expandDependencies: false,\n })\n expandDependencyTree(result.dependencies, target)\n }\n catch (error) {\n if (error instanceof Error && error.message) {\n warnings.push(`[web] 无法解析模板依赖: ${target} ${error.message}`)\n }\n }\n dependencyContext.active.delete(target)\n }\n }\n\n let nodes = parseWxml(options.source)\n let navigationBarAttrs: Record<string, string> | undefined\n if (options.navigationBar) {\n const extracted = extractNavigationBarFromPageMeta(nodes)\n nodes = extracted.nodes\n if (extracted.warnings.length > 0) {\n warnings.push(...extracted.warnings)\n }\n navigationBarAttrs = extracted.attrs\n }\n\n const templates: TemplateDefinition[] = []\n const includes: IncludeEntry[] = []\n const imports: ImportEntry[] = []\n const wxs: WxsEntry[] = []\n const wxsModules = new Map<string, string>()\n\n const renderNodesList = collectSpecialNodes(nodes, {\n templates,\n includes,\n imports,\n wxs,\n wxsModules,\n warnings,\n sourceId: options.id,\n resolveTemplate: (raw: string) => options.resolveTemplatePath(raw, options.id),\n resolveWxs: (raw: string) => options.resolveWxsPath(raw, options.id),\n })\n\n if (options.navigationBar && options.navigationBar.config.navigationStyle !== 'custom') {\n const attrs = buildNavigationBarAttrs(options.navigationBar.config, navigationBarAttrs)\n renderNodesList.unshift({\n type: 'element',\n name: 'weapp-navigation-bar',\n attribs: attrs,\n })\n }\n\n const importLines: string[] = [\n `import { html } from 'lit'`,\n `import { repeat } from 'lit/directives/repeat.js'`,\n ]\n const bodyLines: string[] = []\n const directDependencies: string[] = []\n\n for (const entry of imports) {\n const importPath = normalizeTemplatePath(toRelativeImport(options.id, entry.id))\n importLines.push(`import { templates as ${entry.importName} } from '${importPath}'`)\n addDependency(entry.id, dependencyContext, directDependencies)\n }\n\n for (const entry of includes) {\n const importPath = normalizeTemplatePath(toRelativeImport(options.id, entry.id))\n importLines.push(`import { render as ${entry.importName} } from '${importPath}'`)\n addDependency(entry.id, dependencyContext, directDependencies)\n }\n\n for (const entry of wxs) {\n if (entry.kind === 'src') {\n const baseImport = normalizeTemplatePath(toRelativeImport(options.id, entry.value))\n const importPath = shouldMarkWxsImport(entry.value)\n ? `${baseImport}?wxs`\n : baseImport\n importLines.push(`import ${entry.importName} from '${importPath}'`)\n addDependency(entry.value, dependencyContext, directDependencies)\n }\n }\n\n if (templates.length > 0 || imports.length > 0) {\n const templatePairs: string[] = []\n for (const entry of imports) {\n templatePairs.push(`...${entry.importName}`)\n }\n for (const template of templates) {\n const rendered = renderer.renderNodes(template.nodes, 'scope', '__wxs_modules', options.componentTags)\n templatePairs.push(`${JSON.stringify(template.name)}: (scope, ctx) => ${rendered}`)\n }\n bodyLines.push(`const __templates = { ${templatePairs.join(', ')} }`)\n }\n else {\n bodyLines.push(`const __templates = {}`)\n }\n\n if (wxs.length > 0) {\n bodyLines.push(`const __wxs_inline_cache = Object.create(null)`)\n bodyLines.push(`let __wxs_modules = {}`)\n const wxsMapEntries: string[] = []\n for (const entry of wxs) {\n if (entry.kind === 'inline') {\n const inlineCode = entry.value.trim()\n const cacheKey = JSON.stringify(entry.module)\n if (inlineCode) {\n bodyLines.push(`function ${entry.importName}(ctx) {`)\n bodyLines.push(` if (!__wxs_inline_cache[${cacheKey}]) {`)\n bodyLines.push(` __wxs_inline_cache[${cacheKey}] = ctx.createWxsModule(${JSON.stringify(inlineCode)}, ${JSON.stringify(options.id)})`)\n bodyLines.push(` }`)\n bodyLines.push(` return __wxs_inline_cache[${cacheKey}]`)\n bodyLines.push(`}`)\n }\n else {\n bodyLines.push(`function ${entry.importName}() { return {} }`)\n }\n wxsMapEntries.push(`${JSON.stringify(entry.module)}: ${entry.importName}(ctx)`)\n continue\n }\n wxsMapEntries.push(`${JSON.stringify(entry.module)}: ${entry.importName}`)\n }\n bodyLines.push(`function __resolveWxsModules(ctx) {`)\n bodyLines.push(` return { ${wxsMapEntries.join(', ')} }`)\n bodyLines.push(`}`)\n }\n else {\n bodyLines.push(`const __wxs_modules = {}`)\n }\n\n const includesRender = includes.map(entry => `${entry.importName}(scope, ctx)`)\n const renderContent = renderer.renderNodes(renderNodesList, 'scope', '__wxs_modules', options.componentTags)\n const contentExpr = includesRender.length > 0\n ? `[${[...includesRender, renderContent].join(', ')}]`\n : renderContent\n\n bodyLines.push(`export function render(scope, ctx) {`)\n if (wxs.length > 0) {\n bodyLines.push(` __wxs_modules = __resolveWxsModules(ctx)`)\n }\n bodyLines.push(` return ${contentExpr}`)\n bodyLines.push(`}`)\n bodyLines.push(`export const templates = __templates`)\n bodyLines.push(`export default render`)\n\n if (expandDependencies) {\n dependencyContext.visited.add(options.id)\n dependencyContext.active.add(options.id)\n expandDependencyTree(directDependencies, options.id)\n dependencyContext.active.delete(options.id)\n }\n\n const code = [...importLines, '', ...bodyLines].join('\\n')\n const dependencies = expandDependencies ? dependencyContext.dependencies : directDependencies\n return {\n code,\n dependencies,\n warnings: warnings.length > 0 ? warnings : undefined,\n }\n}\n"],"mappings":";;;;;;;;AAgBA,SAAgB,YAAY,SAAgD;CAC1E,MAAM,oBAAoB,QAAQ,qBAAqB,yBAAyB;CAChF,MAAM,qBAAqB,QAAQ,sBAAsB,CAAC,QAAQ;CAClE,MAAM,WAAW,kBAAkB;CAEnC,MAAM,wBAAwB,cAAwB,aAAqB;AACzE,OAAK,MAAM,UAAU,cAAc;AACjC,OAAI,CAAC,OACH;AAEF,OAAI,kBAAkB,OAAO,IAAI,OAAO,EAAE;AACxC,yBAAqB,mBAAmB,UAAU,OAAO;AACzD;;AAEF,OAAI,kBAAkB,QAAQ,IAAI,OAAO,CACvC;AAEF,qBAAkB,QAAQ,IAAI,OAAO;AACrC,qBAAkB,OAAO,IAAI,OAAO;GACpC,IAAI;AACJ,OAAI;AACF,aAAS,aAAa,QAAQ,OAAO;WAEjC;AACJ,qBAAiB,mBAAmB,OAAO;AAC3C,sBAAkB,OAAO,OAAO,OAAO;AACvC;;AAEF,OAAI;AASF,yBARe,YAAY;KACzB,IAAI;KACJ;KACA,qBAAqB,QAAQ;KAC7B,gBAAgB,QAAQ;KAC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,SAAS,IAAI,WAAW;EAC5C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interpolation.mjs","names":[],"sources":["../../../src/compiler/wxml/interpolation.ts"],"sourcesContent":["import type { InterpolationPart } from './types'\n\nexport function parseInterpolations(value: string): InterpolationPart[] {\n const parts: InterpolationPart[] = []\n if (!value.includes('{{')) {\n return [{ type: 'text', value }]\n }\n let cursor = 0\n while (cursor < value.length) {\n const start = value.indexOf('{{', cursor)\n if (start === -1) {\n parts.push({ type: 'text', value: value.slice(cursor) })\n break\n }\n if (start > cursor) {\n parts.push({ type: 'text', value: value.slice(cursor, start) })\n }\n const end = value.indexOf('}}', start + 2)\n if (end === -1) {\n parts.push({ type: 'text', value: value.slice(start) })\n break\n }\n const expr = value.slice(start + 2, end).trim()\n if (expr) {\n parts.push({ type: 'expr', value: expr })\n }\n cursor = end + 2\n }\n return parts\n}\n\nexport function buildExpression(parts: InterpolationPart[], scopeVar: string, wxsVar: string) {\n if (parts.length === 0) {\n return '\"\"'\n }\n if (parts.length === 1 && parts[0]?.type === 'text') {\n return JSON.stringify(parts[0].value)\n }\n if (parts.length === 1 && parts[0]?.type === 'expr') {\n return `ctx.eval(${JSON.stringify(parts[0].value)}, ${scopeVar}, ${wxsVar})`\n }\n const segments = parts.map((part) => {\n if (part.type === 'text') {\n return JSON.stringify(part.value)\n }\n return `ctx.eval(${JSON.stringify(part.value)}, ${scopeVar}, ${wxsVar})`\n })\n return `(${segments.join(' + ')})`\n}\n\nfunction hasTopLevelColon(expression: string) {\n let depth = 0\n let inSingleQuote = false\n let inDoubleQuote = false\n let inTemplate = false\n let escaped = false\n let sawTopLevelQuestion = false\n\n for (let index = 0; index < expression.length; index += 1) {\n const char = expression[index]!\n\n if (inSingleQuote) {\n if (escaped) {\n escaped = false\n continue\n }\n if (char === '\\\\') {\n escaped = true\n continue\n }\n if (char === '\\'') {\n inSingleQuote = false\n }\n continue\n }\n if (inDoubleQuote) {\n if (escaped) {\n escaped = false\n continue\n }\n if (char === '\\\\') {\n escaped = true\n continue\n }\n if (char === '\"') {\n inDoubleQuote = false\n }\n continue\n }\n if (inTemplate) {\n if (escaped) {\n escaped = false\n continue\n }\n if (char === '\\\\') {\n escaped = true\n continue\n }\n if (char === '`') {\n inTemplate = false\n }\n continue\n }\n\n if (char === '\\'') {\n inSingleQuote = true\n continue\n }\n if (char === '\"') {\n inDoubleQuote = true\n continue\n }\n if (char === '`') {\n inTemplate = true\n continue\n }\n\n if (char === '(' || char === '[' || char === '{') {\n depth += 1\n continue\n }\n if (char === ')' || char === ']' || char === '}') {\n depth = Math.max(0, depth - 1)\n continue\n }\n\n if (depth !== 0) {\n continue\n }\n\n if (char === '?') {\n sawTopLevelQuestion = true\n continue\n }\n if (char === ':') {\n return !sawTopLevelQuestion\n }\n }\n\n return false\n}\n\nfunction shouldWrapShorthandObject(expression: string) {\n const trimmed = expression.trim()\n if (!trimmed) {\n return false\n }\n if (trimmed.startsWith('{') || trimmed.startsWith('[') || trimmed.startsWith('(')) {\n return false\n }\n return hasTopLevelColon(trimmed)\n}\n\nexport function buildTemplateDataExpression(raw: string, scopeVar: string, wxsVar: string) {\n const trimmed = raw.trim()\n const parts = parseInterpolations(trimmed)\n if (parts.length === 1 && parts[0]?.type === 'expr') {\n const expr = parts[0].value.trim()\n if (expr) {\n const normalizedExpr = shouldWrapShorthandObject(expr) ? `{ ${expr} }` : expr\n return buildExpression([{ type: 'expr', value: normalizedExpr }], scopeVar, wxsVar)\n }\n }\n return buildExpression(parseInterpolations(raw), scopeVar, wxsVar)\n}\n"],"mappings":";AAEA,SAAgB,oBAAoB,OAAoC;CACtE,MAAM,QAA6B,EAAE;AACrC,KAAI,CAAC,MAAM,SAAS,KAAK,CACvB,QAAO,CAAC;EAAE,MAAM;EAAQ;EAAO,CAAC;CAElC,IAAI,SAAS;AACb,QAAO,SAAS,MAAM,QAAQ;EAC5B,MAAM,QAAQ,MAAM,QAAQ,MAAM,OAAO;AACzC,MAAI,UAAU,IAAI;AAChB,SAAM,KAAK;IAAE,MAAM;IAAQ,OAAO,MAAM,MAAM,OAAO;IAAE,CAAC;AACxD;;AAEF,MAAI,QAAQ,OACV,OAAM,KAAK;GAAE,MAAM;GAAQ,OAAO,MAAM,MAAM,QAAQ,MAAM;GAAE,CAAC;EAEjE,MAAM,MAAM,MAAM,QAAQ,MAAM,QAAQ,EAAE;AAC1C,MAAI,QAAQ,IAAI;AACd,SAAM,KAAK;IAAE,MAAM;IAAQ,OAAO,MAAM,MAAM,MAAM;IAAE,CAAC;AACvD;;EAEF,MAAM,OAAO,MAAM,MAAM,QAAQ,GAAG,IAAI,CAAC,MAAM;AAC/C,MAAI,KACF,OAAM,KAAK;GAAE,MAAM;GAAQ,OAAO;GAAM,CAAC;AAE3C,WAAS,MAAM;;AAEjB,QAAO;;AAGT,SAAgB,gBAAgB,OAA4B,UAAkB,QAAgB;AAC5F,KAAI,MAAM,WAAW,EACnB,QAAO;AAET,KAAI,MAAM,WAAW,KAAK,MAAM,IAAI,SAAS,OAC3C,QAAO,KAAK,UAAU,MAAM,GAAG,MAAM;AAEvC,KAAI,MAAM,WAAW,KAAK,MAAM,IAAI,SAAS,OAC3C,QAAO,YAAY,KAAK,UAAU,MAAM,GAAG,MAAM,CAAC,IAAI,SAAS,IAAI,OAAO;AAQ5E,QAAO,IANU,MAAM,KAAK,SAAS;AACnC,MAAI,KAAK,SAAS,OAChB,QAAO,KAAK,UAAU,KAAK,MAAM;AAEnC,SAAO,YAAY,KAAK,UAAU,KAAK,MAAM,CAAC,IAAI,SAAS,IAAI,OAAO;
|
|
1
|
+
{"version":3,"file":"interpolation.mjs","names":[],"sources":["../../../src/compiler/wxml/interpolation.ts"],"sourcesContent":["import type { InterpolationPart } from './types'\n\nexport function parseInterpolations(value: string): InterpolationPart[] {\n const parts: InterpolationPart[] = []\n if (!value.includes('{{')) {\n return [{ type: 'text', value }]\n }\n let cursor = 0\n while (cursor < value.length) {\n const start = value.indexOf('{{', cursor)\n if (start === -1) {\n parts.push({ type: 'text', value: value.slice(cursor) })\n break\n }\n if (start > cursor) {\n parts.push({ type: 'text', value: value.slice(cursor, start) })\n }\n const end = value.indexOf('}}', start + 2)\n if (end === -1) {\n parts.push({ type: 'text', value: value.slice(start) })\n break\n }\n const expr = value.slice(start + 2, end).trim()\n if (expr) {\n parts.push({ type: 'expr', value: expr })\n }\n cursor = end + 2\n }\n return parts\n}\n\nexport function buildExpression(parts: InterpolationPart[], scopeVar: string, wxsVar: string) {\n if (parts.length === 0) {\n return '\"\"'\n }\n if (parts.length === 1 && parts[0]?.type === 'text') {\n return JSON.stringify(parts[0].value)\n }\n if (parts.length === 1 && parts[0]?.type === 'expr') {\n return `ctx.eval(${JSON.stringify(parts[0].value)}, ${scopeVar}, ${wxsVar})`\n }\n const segments = parts.map((part) => {\n if (part.type === 'text') {\n return JSON.stringify(part.value)\n }\n return `ctx.eval(${JSON.stringify(part.value)}, ${scopeVar}, ${wxsVar})`\n })\n return `(${segments.join(' + ')})`\n}\n\nfunction hasTopLevelColon(expression: string) {\n let depth = 0\n let inSingleQuote = false\n let inDoubleQuote = false\n let inTemplate = false\n let escaped = false\n let sawTopLevelQuestion = false\n\n for (let index = 0; index < expression.length; index += 1) {\n const char = expression[index]!\n\n if (inSingleQuote) {\n if (escaped) {\n escaped = false\n continue\n }\n if (char === '\\\\') {\n escaped = true\n continue\n }\n if (char === '\\'') {\n inSingleQuote = false\n }\n continue\n }\n if (inDoubleQuote) {\n if (escaped) {\n escaped = false\n continue\n }\n if (char === '\\\\') {\n escaped = true\n continue\n }\n if (char === '\"') {\n inDoubleQuote = false\n }\n continue\n }\n if (inTemplate) {\n if (escaped) {\n escaped = false\n continue\n }\n if (char === '\\\\') {\n escaped = true\n continue\n }\n if (char === '`') {\n inTemplate = false\n }\n continue\n }\n\n if (char === '\\'') {\n inSingleQuote = true\n continue\n }\n if (char === '\"') {\n inDoubleQuote = true\n continue\n }\n if (char === '`') {\n inTemplate = true\n continue\n }\n\n if (char === '(' || char === '[' || char === '{') {\n depth += 1\n continue\n }\n if (char === ')' || char === ']' || char === '}') {\n depth = Math.max(0, depth - 1)\n continue\n }\n\n if (depth !== 0) {\n continue\n }\n\n if (char === '?') {\n sawTopLevelQuestion = true\n continue\n }\n if (char === ':') {\n return !sawTopLevelQuestion\n }\n }\n\n return false\n}\n\nfunction shouldWrapShorthandObject(expression: string) {\n const trimmed = expression.trim()\n if (!trimmed) {\n return false\n }\n if (trimmed.startsWith('{') || trimmed.startsWith('[') || trimmed.startsWith('(')) {\n return false\n }\n return hasTopLevelColon(trimmed)\n}\n\nexport function buildTemplateDataExpression(raw: string, scopeVar: string, wxsVar: string) {\n const trimmed = raw.trim()\n const parts = parseInterpolations(trimmed)\n if (parts.length === 1 && parts[0]?.type === 'expr') {\n const expr = parts[0].value.trim()\n if (expr) {\n const normalizedExpr = shouldWrapShorthandObject(expr) ? `{ ${expr} }` : expr\n return buildExpression([{ type: 'expr', value: normalizedExpr }], scopeVar, wxsVar)\n }\n }\n return buildExpression(parseInterpolations(raw), scopeVar, wxsVar)\n}\n"],"mappings":";AAEA,SAAgB,oBAAoB,OAAoC;CACtE,MAAM,QAA6B,EAAE;AACrC,KAAI,CAAC,MAAM,SAAS,KAAK,CACvB,QAAO,CAAC;EAAE,MAAM;EAAQ;EAAO,CAAC;CAElC,IAAI,SAAS;AACb,QAAO,SAAS,MAAM,QAAQ;EAC5B,MAAM,QAAQ,MAAM,QAAQ,MAAM,OAAO;AACzC,MAAI,UAAU,IAAI;AAChB,SAAM,KAAK;IAAE,MAAM;IAAQ,OAAO,MAAM,MAAM,OAAO;IAAE,CAAC;AACxD;;AAEF,MAAI,QAAQ,OACV,OAAM,KAAK;GAAE,MAAM;GAAQ,OAAO,MAAM,MAAM,QAAQ,MAAM;GAAE,CAAC;EAEjE,MAAM,MAAM,MAAM,QAAQ,MAAM,QAAQ,EAAE;AAC1C,MAAI,QAAQ,IAAI;AACd,SAAM,KAAK;IAAE,MAAM;IAAQ,OAAO,M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SAAS;AACX,cAAU;AACV;;AAEF,OAAI,SAAS,MAAM;AACjB,cAAU;AACV;;AAEF,OAAI,SAAS,IACX,cAAa;AAEf;;AAGF,MAAI,SAAS,KAAM;AACjB,mBAAgB;AAChB;;AAEF,MAAI,SAAS,MAAK;AAChB,mBAAgB;AAChB;;AAEF,MAAI,SAAS,KAAK;AAChB,gBAAa;AACb;;AAGF,MAAI,SAAS,OAAO,SAAS,OAAO,SAAS,KAAK;AAChD,YAAS;AACT;;AAEF,MAAI,SAAS,OAAO,SAAS,OAAO,SAAS,KAAK;AAChD,WAAQ,KAAK,IAAI,GAAG,QAAQ,EAAE;AAC9B;;AAGF,MAAI,UAAU,EACZ;AAGF,MAAI,SAAS,KAAK;AAChB,yBAAsB;AACtB;;AAEF,MAAI,SAAS,IACX,QAAO,CAAC;;AAIZ,QAAO;;AAGT,SAAS,0BAA0B,YAAoB;CACrD,MAAM,UAAU,WAAW,MAAM;AACjC,KAAI,CAAC,QACH,QAAO;AAET,KAAI,QAAQ,WAAW,IAAI,IAAI,QAAQ,WAAW,IAAI,IAAI,QAAQ,WAAW,IAAI,CAC/E,QAAO;AAET,QAAO,iBAAiB,QAAQ;;AAGlC,SAAgB,4BAA4B,KAAa,UAAkB,QAAgB;CAEzF,MAAM,QAAQ,oBADE,IAAI,MACqB,CAAC;AAC1C,KAAI,MAAM,WAAW,KAAK,MAAM,IAAI,SAAS,QAAQ;EACnD,MAAM,OAAO,MAAM,GAAG,MAAM,MAAM;AAClC,MAAI,KAEF,QAAO,gBAAgB,CAAC;GAAE,MAAM;GAAQ,OADjB,0BAA0B,KAAK,GAAG,KAAK,KAAK,MAAM;GACV,CAAC,EAAE,UAAU,OAAO;;AAGvF,QAAO,gBAAgB,oBAAoB,IAAI,EAAE,UAAU,OAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parser.mjs","names":[],"sources":["../../../src/compiler/wxml/parser.ts"],"sourcesContent":["import type { ChildNode, DataNode, Element, Node } from 'domhandler'\n\nimport type { RenderNode } from './types'\n\nimport { parseDocument } from 'htmlparser2'\n\nfunction isRenderableNode(node: Node) {\n if (node.type === 'directive' || node.type === 'comment') {\n return false\n }\n if (node.type === 'text') {\n const data = (node as DataNode).data ?? ''\n return data.trim().length > 0\n }\n return true\n}\n\ntype NodeWithChildren = Node & { children: ChildNode[] }\n\nfunction hasChildren(node: Node): node is NodeWithChildren {\n return Array.isArray((node as NodeWithChildren).children)\n}\n\nfunction toRenderNode(node: Node, children?: RenderNode[]): RenderNode | undefined {\n if (node.type === 'text') {\n const data = (node as DataNode).data ?? ''\n return { type: 'text', data }\n }\n if (node.type === 'tag' || node.type === 'script' || node.type === 'style') {\n const element = node as Element\n return {\n type: 'element',\n name: element.name,\n attribs: element.attribs ?? {},\n children,\n }\n }\n return undefined\n}\n\nfunction convertNode(node: Node): RenderNode | undefined {\n if (!isRenderableNode(node)) {\n return undefined\n }\n const children = (hasChildren(node) && node.children.length > 0)\n ? node.children.map(child => convertNode(child)).filter((child): child is RenderNode => Boolean(child))\n : undefined\n return toRenderNode(node, children)\n}\n\nexport function parseWxml(source: string): RenderNode[] {\n const document = parseDocument(source, {\n xmlMode: true,\n decodeEntities: true,\n recognizeSelfClosing: true,\n })\n const nodes = (document.children ?? []).filter(isRenderableNode)\n return nodes\n .map(node => convertNode(node))\n .filter((node): node is RenderNode => Boolean(node))\n}\n"],"mappings":";;;AAMA,SAAS,iBAAiB,MAAY;AACpC,KAAI,KAAK,SAAS,eAAe,KAAK,SAAS,UAC7C,QAAO;AAET,KAAI,KAAK,SAAS,OAEhB,SADc,KAAkB,QAAQ,IAC5B,MAAM,CAAC,SAAS;AAE9B,QAAO;;AAKT,SAAS,YAAY,MAAsC;AACzD,QAAO,MAAM,QAAS,KAA0B,SAAS;;AAG3D,SAAS,aAAa,MAAY,UAAiD;AACjF,KAAI,KAAK,SAAS,OAEhB,QAAO;EAAE,MAAM;EAAQ,MADT,KAAkB,QAAQ;EACX;AAE/B,KAAI,KAAK,SAAS,SAAS,KAAK,SAAS,YAAY,KAAK,SAAS,SAAS;EAC1E,MAAM,UAAU;AAChB,SAAO;GACL,MAAM;GACN,MAAM,QAAQ;GACd,SAAS,QAAQ,WAAW,EAAE;GAC9B;GACD;;;AAKL,SAAS,YAAY,MAAoC;AACvD,KAAI,CAAC,iBAAiB,KAAK,CACzB;AAKF,QAAO,aAAa,MAHF,YAAY,KAAK,IAAI,KAAK,SAAS,SAAS,IAC1D,KAAK,SAAS,KAAI,UAAS,YAAY,MAAM,CAAC,CAAC,QAAQ,UAA+B,QAAQ,MAAM,CAAC,GACrG,OAC+B;;AAGrC,SAAgB,UAAU,QAA8B;AAOtD,SANiB,cAAc,QAAQ;EACrC,SAAS;EACT,gBAAgB;EAChB,sBAAsB;EACvB,CAAC,
|
|
1
|
+
{"version":3,"file":"parser.mjs","names":[],"sources":["../../../src/compiler/wxml/parser.ts"],"sourcesContent":["import type { ChildNode, DataNode, Element, Node } from 'domhandler'\n\nimport type { RenderNode } from './types'\n\nimport { parseDocument } from 'htmlparser2'\n\nfunction isRenderableNode(node: Node) {\n if (node.type === 'directive' || node.type === 'comment') {\n return false\n }\n if (node.type === 'text') {\n const data = (node as DataNode).data ?? ''\n return data.trim().length > 0\n }\n return true\n}\n\ntype NodeWithChildren = Node & { children: ChildNode[] }\n\nfunction hasChildren(node: Node): node is NodeWithChildren {\n return Array.isArray((node as NodeWithChildren).children)\n}\n\nfunction toRenderNode(node: Node, children?: RenderNode[]): RenderNode | undefined {\n if (node.type === 'text') {\n const data = (node as DataNode).data ?? ''\n return { type: 'text', data }\n }\n if (node.type === 'tag' || node.type === 'script' || node.type === 'style') {\n const element = node as Element\n return {\n type: 'element',\n name: element.name,\n attribs: element.attribs ?? {},\n children,\n }\n }\n return undefined\n}\n\nfunction convertNode(node: Node): RenderNode | undefined {\n if (!isRenderableNode(node)) {\n return undefined\n }\n const children = (hasChildren(node) && node.children.length > 0)\n ? node.children.map(child => convertNode(child)).filter((child): child is RenderNode => Boolean(child))\n : undefined\n return toRenderNode(node, children)\n}\n\nexport function parseWxml(source: string): RenderNode[] {\n const document = parseDocument(source, {\n xmlMode: true,\n decodeEntities: true,\n recognizeSelfClosing: true,\n })\n const nodes = (document.children ?? []).filter(isRenderableNode)\n return nodes\n .map(node => convertNode(node))\n .filter((node): node is RenderNode => Boolean(node))\n}\n"],"mappings":";;;AAMA,SAAS,iBAAiB,MAAY;AACpC,KAAI,KAAK,SAAS,eAAe,KAAK,SAAS,UAC7C,QAAO;AAET,KAAI,KAAK,SAAS,OAEhB,SADc,KAAkB,QAAQ,IAC5B,MAAM,CAAC,SAAS;AAE9B,QAAO;;AAKT,SAAS,YAAY,MAAsC;AACzD,QAAO,MAAM,QAAS,KAA0B,SAAS;;AAG3D,SAAS,aAAa,MAAY,UAAiD;AACjF,KAAI,KAAK,SAAS,OAEhB,QAAO;EAAE,MAAM;EAAQ,MADT,KAAkB,QAAQ;EACX;AAE/B,KAAI,KAAK,SAAS,SAAS,KAAK,SAAS,YAAY,KAAK,SAAS,SAAS;EAC1E,MAAM,UAAU;AAChB,SAAO;GACL,MAAM;GACN,MAAM,QAAQ;GACd,SAAS,QAAQ,WAAW,EAAE;GAC9B;GACD;;;AAKL,SAAS,YAAY,MAAoC;AACvD,KAAI,CAAC,iBAAiB,KAAK,CACzB;AAKF,QAAO,aAAa,MAHF,YAAY,KAAK,IAAI,KAAK,SAAS,SAAS,IAC1D,KAAK,SAAS,KAAI,UAAS,YAAY,MAAM,CAAC,CAAC,QAAQ,UAA+B,QAAQ,MAAM,CAAC,GACrG,OAC+B;;AAGrC,SAAgB,UAAU,QAA8B;AAOtD,SANiB,cAAc,QAAQ;EACrC,SAAS;EACT,gBAAgB;EAChB,sBAAsB;EACvB,CACsB,CAAC,YAAY,EAAE,EAAE,OAAO,iBACnC,CACT,KAAI,SAAQ,YAAY,KAAK,CAAC,CAC9B,QAAQ,SAA6B,QAAQ,KAAK,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"renderer.mjs","names":[],"sources":["../../../src/compiler/wxml/renderer.ts"],"sourcesContent":["import type { RenderElementNode, RenderNode } from './types'\nimport {\n hasControlAttribute,\n normalizeTagName,\n resolveControlAttributeValue,\n SELF_CLOSING_TAGS,\n} from '../../shared/wxml'\nimport {\n extractFor,\n isConditionalElement,\n renderAttributes,\n resolveComponentTagName,\n stripControlAttributes,\n} from './attributes'\nimport { buildExpression, buildTemplateDataExpression, parseInterpolations } from './interpolation'\n\ninterface RenderElementOptions {\n skipFor?: boolean\n overrideAttribs?: Record<string, string>\n}\n\nexport class Renderer {\n renderNodes(\n nodes: RenderNode[],\n scopeVar: string,\n wxsVar: string,\n componentTags?: Record<string, string>,\n ): string {\n const parts: string[] = []\n for (let index = 0; index < nodes.length; index += 1) {\n const node = nodes[index]\n if (isConditionalElement(node)) {\n const { rendered, endIndex } = this.renderConditionalSequence(\n nodes,\n index,\n scopeVar,\n wxsVar,\n componentTags,\n )\n parts.push(rendered)\n index = endIndex\n continue\n }\n parts.push(this.renderNode(node, scopeVar, wxsVar, componentTags))\n }\n if (parts.length === 0) {\n return '\"\"'\n }\n if (parts.length === 1) {\n return parts[0]!\n }\n return `[${parts.join(', ')}]`\n }\n\n private renderConditionalSequence(\n nodes: RenderNode[],\n startIndex: number,\n scopeVar: string,\n wxsVar: string,\n componentTags?: Record<string, string>,\n ): { rendered: string, endIndex: number } {\n const branches: Array<{ node: RenderElementNode, attribs: Record<string, string> }> = []\n let cursor = startIndex\n while (cursor < nodes.length) {\n const candidate = nodes[cursor]\n if (!isConditionalElement(candidate)) {\n break\n }\n const attribs = candidate.attribs ?? {}\n if (branches.length === 0 && !hasControlAttribute(attribs, 'if')) {\n break\n }\n if (branches.length > 0 && !hasControlAttribute(attribs, 'elif') && !hasControlAttribute(attribs, 'else')) {\n break\n }\n branches.push({ node: candidate, attribs })\n cursor += 1\n if (hasControlAttribute(attribs, 'else')) {\n break\n }\n }\n if (!branches.length) {\n const node = nodes[startIndex]\n if (!node) {\n return { rendered: '\"\"', endIndex: startIndex }\n }\n return { rendered: this.renderNode(node, scopeVar, wxsVar, componentTags), endIndex: startIndex }\n }\n let expr = '\"\"'\n for (let index = branches.length - 1; index >= 0; index -= 1) {\n const { node, attribs } = branches[index]!\n const cleanedAttribs = stripControlAttributes(attribs)\n if (hasControlAttribute(attribs, 'else')) {\n expr = this.renderElement(node, scopeVar, wxsVar, componentTags, { overrideAttribs: cleanedAttribs })\n continue\n }\n const conditionExpr = resolveControlAttributeValue(attribs, 'if')\n ?? resolveControlAttributeValue(attribs, 'elif')\n ?? ''\n const rendered = this.renderElement(node, scopeVar, wxsVar, componentTags, { overrideAttribs: cleanedAttribs })\n const condition = buildExpression(parseInterpolations(conditionExpr), scopeVar, wxsVar)\n expr = `(${condition} ? ${rendered} : ${expr})`\n }\n return { rendered: expr, endIndex: startIndex + branches.length - 1 }\n }\n\n private renderNode(\n node: RenderNode,\n scopeVar: string,\n wxsVar: string,\n componentTags?: Record<string, string>,\n ): string {\n if (node.type === 'text') {\n const parts = parseInterpolations(node.data ?? '')\n return buildExpression(parts, scopeVar, wxsVar)\n }\n if (node.type === 'element') {\n if (node.name === 'template' && node.attribs?.is) {\n return this.renderTemplateInvoke(node, scopeVar, wxsVar)\n }\n return this.renderElement(node, scopeVar, wxsVar, componentTags)\n }\n return '\"\"'\n }\n\n private renderTemplateInvoke(\n node: RenderElementNode,\n scopeVar: string,\n wxsVar: string,\n ): string {\n const attribs = node.attribs ?? {}\n const isExpr = buildExpression(parseInterpolations(attribs.is ?? ''), scopeVar, wxsVar)\n const dataExpr = attribs.data\n ? buildTemplateDataExpression(attribs.data, scopeVar, wxsVar)\n : undefined\n const scopeExpr = dataExpr\n ? `ctx.mergeScope(${scopeVar}, ${dataExpr})`\n : scopeVar\n return `ctx.renderTemplate(__templates, ${isExpr}, ${scopeExpr}, ctx)`\n }\n\n private renderElement(\n node: RenderElementNode,\n scopeVar: string,\n wxsVar: string,\n componentTags?: Record<string, string>,\n options: RenderElementOptions = {},\n ): string {\n const attribs = options.overrideAttribs ?? node.attribs ?? {}\n if (!options.skipFor) {\n const forInfo = extractFor(node.attribs ?? {})\n if (forInfo.expr) {\n const listExpression = buildExpression(parseInterpolations(forInfo.expr), scopeVar, wxsVar)\n const listExpr = `ctx.normalizeList(${listExpression})`\n const itemVar = forInfo.itemName\n const indexVar = forInfo.indexName\n const scopeExpr = `ctx.createScope(${scopeVar}, { ${itemVar}: ${itemVar}, ${indexVar}: ${indexVar} })`\n const itemRender = this.renderElement(\n node,\n '__scope',\n wxsVar,\n componentTags,\n { skipFor: true, overrideAttribs: forInfo.restAttribs },\n )\n const keyExpr = `ctx.key(${JSON.stringify(forInfo.key ?? '')}, ${itemVar}, ${indexVar}, ${scopeExpr}, ${wxsVar})`\n return `repeat(${listExpr}, (${itemVar}, ${indexVar}) => ${keyExpr}, (${itemVar}, ${indexVar}) => { const __scope = ${scopeExpr}; return ${itemRender}; })`\n }\n }\n\n const customTag = resolveComponentTagName(node.name ?? '', componentTags)\n const tagName = customTag ?? normalizeTagName(node.name ?? '')\n if (tagName === '#fragment') {\n return this.renderNodes(node.children ?? [], scopeVar, wxsVar, componentTags)\n }\n\n const attrs = renderAttributes(attribs, scopeVar, wxsVar, {\n skipControl: true,\n preferProperty: Boolean(customTag),\n })\n const childNodes = node.children ?? []\n const children = childNodes\n .map(child => `\\${${this.renderNode(child, scopeVar, wxsVar, componentTags)}}`)\n .join('')\n if (SELF_CLOSING_TAGS.has(tagName) && childNodes.length === 0) {\n return `html\\`<${tagName}${attrs} />\\``\n }\n return `html\\`<${tagName}${attrs}>${children}</${tagName}>\\``\n }\n}\n\nexport const renderer = new Renderer()\n"],"mappings":";;;;;AAqBA,IAAa,WAAb,MAAsB;CACpB,YACE,OACA,UACA,QACA,eACQ;EACR,MAAM,QAAkB,EAAE;AAC1B,OAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS,GAAG;GACpD,MAAM,OAAO,MAAM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QAAQ,KAAK,EAAE,UAAU,OAAO,CACtC;IACrD,MAAM,UAAU,QAAQ;IACxB,MAAM,WAAW,QAAQ;IACzB,MAAM,YAAY,mBAAmB,SAAS,MAAM,QAAQ,IAAI,QAAQ,IAAI,SAAS,IAAI,SAAS;IAClG,MAAM,aAAa,KAAK,cACtB,MACA,WACA,QACA,eACA;KAAE,SAAS;KAAM,iBAAiB,QAAQ;KAAa,CACxD;AAED,WAAO,UAAU,SAAS,KAAK,QAAQ,IAAI,SAAS,OADpC,WAAW,KAAK,UAAU,QAAQ,OAAO,GAAG,CAAC,IAAI,QAAQ,IAAI,SAAS,IAAI,UAAU,IAAI,OAAO,GAC5C,KAAK,QAAQ,IAAI,SAAS,yBAAyB,UAAU,WAAW,WAAW;;;EAI1J,MAAM,YAAY,wBAAwB,KAAK,QAAQ,IAAI,cAAc;EACzE,MAAM,UAAU,aAAa,iBAAiB,KAAK,QAAQ,GAAG;AAC9D,MAAI,YAAY,YACd,QAAO,KAAK,YAAY,KAAK,YAAY,EAAE,EAAE,UAAU,QAAQ,cAAc;EAG/E,MAAM,QAAQ,iBAAiB,SAAS,UAAU,QAAQ;GACxD,aAAa;GACb,gBAAgB,QAAQ,UAAU;GACnC,CAAC;EACF,MAAM,aAAa,KAAK,YAAY,EAAE;EACtC,MAAM,WAAW,WACd,KAAI,UAAS,MAAM,KAAK,WAAW,OAAO,UAAU,QAAQ,cAAc,CAAC,GAAG,CAC9E,KAAK,GAAG;AACX,MAAI,kBAAkB,IAAI,QAAQ,IAAI,WAAW,WAAW,EAC1D,QAAO,UAAU,UAAU,MAAM;AAEnC,SAAO,UAAU,UAAU,MAAM,GAAG,SAAS,IAAI,QAAQ;;;AAI7D,MAAa,WAAW,IAAI,UAAU"}
|
|
1
|
+
{"version":3,"file":"renderer.mjs","names":[],"sources":["../../../src/compiler/wxml/renderer.ts"],"sourcesContent":["import type { RenderElementNode, RenderNode } from './types'\nimport {\n hasControlAttribute,\n normalizeTagName,\n resolveControlAttributeValue,\n SELF_CLOSING_TAGS,\n} from '../../shared/wxml'\nimport {\n extractFor,\n isConditionalElement,\n renderAttributes,\n resolveComponentTagName,\n stripControlAttributes,\n} from './attributes'\nimport { buildExpression, buildTemplateDataExpression, parseInterpolations } from './interpolation'\n\ninterface RenderElementOptions {\n skipFor?: boolean\n overrideAttribs?: Record<string, string>\n}\n\nexport class Renderer {\n renderNodes(\n nodes: RenderNode[],\n scopeVar: string,\n wxsVar: string,\n componentTags?: Record<string, string>,\n ): string {\n const parts: string[] = []\n for (let index = 0; index < nodes.length; index += 1) {\n const node = nodes[index]\n if (isConditionalElement(node)) {\n const { rendered, endIndex } = this.renderConditionalSequence(\n nodes,\n index,\n scopeVar,\n wxsVar,\n componentTags,\n )\n parts.push(rendered)\n index = endIndex\n continue\n }\n parts.push(this.renderNode(node, scopeVar, wxsVar, componentTags))\n }\n if (parts.length === 0) {\n return '\"\"'\n }\n if (parts.length === 1) {\n return parts[0]!\n }\n return `[${parts.join(', ')}]`\n }\n\n private renderConditionalSequence(\n nodes: RenderNode[],\n startIndex: number,\n scopeVar: string,\n wxsVar: string,\n componentTags?: Record<string, string>,\n ): { rendered: string, endIndex: number } {\n const branches: Array<{ node: RenderElementNode, attribs: Record<string, string> }> = []\n let cursor = startIndex\n while (cursor < nodes.length) {\n const candidate = nodes[cursor]\n if (!isConditionalElement(candidate)) {\n break\n }\n const attribs = candidate.attribs ?? {}\n if (branches.length === 0 && !hasControlAttribute(attribs, 'if')) {\n break\n }\n if (branches.length > 0 && !hasControlAttribute(attribs, 'elif') && !hasControlAttribute(attribs, 'else')) {\n break\n }\n branches.push({ node: candidate, attribs })\n cursor += 1\n if (hasControlAttribute(attribs, 'else')) {\n break\n }\n }\n if (!branches.length) {\n const node = nodes[startIndex]\n if (!node) {\n return { rendered: '\"\"', endIndex: startIndex }\n }\n return { rendered: this.renderNode(node, scopeVar, wxsVar, componentTags), endIndex: startIndex }\n }\n let expr = '\"\"'\n for (let index = branches.length - 1; index >= 0; index -= 1) {\n const { node, attribs } = branches[index]!\n const cleanedAttribs = stripControlAttributes(attribs)\n if (hasControlAttribute(attribs, 'else')) {\n expr = this.renderElement(node, scopeVar, wxsVar, componentTags, { overrideAttribs: cleanedAttribs })\n continue\n }\n const conditionExpr = resolveControlAttributeValue(attribs, 'if')\n ?? resolveControlAttributeValue(attribs, 'elif')\n ?? ''\n const rendered = this.renderElement(node, scopeVar, wxsVar, componentTags, { overrideAttribs: cleanedAttribs })\n const condition = buildExpression(parseInterpolations(conditionExpr), scopeVar, wxsVar)\n expr = `(${condition} ? ${rendered} : ${expr})`\n }\n return { rendered: expr, endIndex: startIndex + branches.length - 1 }\n }\n\n private renderNode(\n node: RenderNode,\n scopeVar: string,\n wxsVar: string,\n componentTags?: Record<string, string>,\n ): string {\n if (node.type === 'text') {\n const parts = parseInterpolations(node.data ?? '')\n return buildExpression(parts, scopeVar, wxsVar)\n }\n if (node.type === 'element') {\n if (node.name === 'template' && node.attribs?.is) {\n return this.renderTemplateInvoke(node, scopeVar, wxsVar)\n }\n return this.renderElement(node, scopeVar, wxsVar, componentTags)\n }\n return '\"\"'\n }\n\n private renderTemplateInvoke(\n node: RenderElementNode,\n scopeVar: string,\n wxsVar: string,\n ): string {\n const attribs = node.attribs ?? {}\n const isExpr = buildExpression(parseInterpolations(attribs.is ?? ''), scopeVar, wxsVar)\n const dataExpr = attribs.data\n ? buildTemplateDataExpression(attribs.data, scopeVar, wxsVar)\n : undefined\n const scopeExpr = dataExpr\n ? `ctx.mergeScope(${scopeVar}, ${dataExpr})`\n : scopeVar\n return `ctx.renderTemplate(__templates, ${isExpr}, ${scopeExpr}, ctx)`\n }\n\n private renderElement(\n node: RenderElementNode,\n scopeVar: string,\n wxsVar: string,\n componentTags?: Record<string, string>,\n options: RenderElementOptions = {},\n ): string {\n const attribs = options.overrideAttribs ?? node.attribs ?? {}\n if (!options.skipFor) {\n const forInfo = extractFor(node.attribs ?? {})\n if (forInfo.expr) {\n const listExpression = buildExpression(parseInterpolations(forInfo.expr), scopeVar, wxsVar)\n const listExpr = `ctx.normalizeList(${listExpression})`\n const itemVar = forInfo.itemName\n const indexVar = forInfo.indexName\n const scopeExpr = `ctx.createScope(${scopeVar}, { ${itemVar}: ${itemVar}, ${indexVar}: ${indexVar} })`\n const itemRender = this.renderElement(\n node,\n '__scope',\n wxsVar,\n componentTags,\n { skipFor: true, overrideAttribs: forInfo.restAttribs },\n )\n const keyExpr = `ctx.key(${JSON.stringify(forInfo.key ?? '')}, ${itemVar}, ${indexVar}, ${scopeExpr}, ${wxsVar})`\n return `repeat(${listExpr}, (${itemVar}, ${indexVar}) => ${keyExpr}, (${itemVar}, ${indexVar}) => { const __scope = ${scopeExpr}; return ${itemRender}; })`\n }\n }\n\n const customTag = resolveComponentTagName(node.name ?? '', componentTags)\n const tagName = customTag ?? normalizeTagName(node.name ?? '')\n if (tagName === '#fragment') {\n return this.renderNodes(node.children ?? [], scopeVar, wxsVar, componentTags)\n }\n\n const attrs = renderAttributes(attribs, scopeVar, wxsVar, {\n skipControl: true,\n preferProperty: Boolean(customTag),\n })\n const childNodes = node.children ?? []\n const children = childNodes\n .map(child => `\\${${this.renderNode(child, scopeVar, wxsVar, componentTags)}}`)\n .join('')\n if (SELF_CLOSING_TAGS.has(tagName) && childNodes.length === 0) {\n return `html\\`<${tagName}${attrs} />\\``\n }\n return `html\\`<${tagName}${attrs}>${children}</${tagName}>\\``\n }\n}\n\nexport const renderer = new Renderer()\n"],"mappings":";;;;;AAqBA,IAAa,WAAb,MAAsB;CACpB,YACE,OACA,UACA,QACA,eACQ;EACR,MAAM,QAAkB,EAAE;AAC1B,OAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS,GAAG;GACpD,MAAM,OAAO,MAAM;AACnB,OAAI,qBAAqB,KAAK,EAAE;IAC9B,MAAM,EAAE,UAAU,aAAa,KAAK,0BAClC,OACA,OACA,UACA,QACA,cACD;AACD,UAAM,KAAK,SAAS;AACpB,YAAQ;AACR;;A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,IAAI,SAAS,IAAI,SAAS;IAClG,MAAM,aAAa,KAAK,cACtB,MACA,WACA,QACA,eACA;KAAE,SAAS;KAAM,iBAAiB,QAAQ;KAAa,CACxD;AAED,WAAO,UAAU,SAAS,KAAK,QAAQ,IAAI,SAAS,OAAO,WADhC,KAAK,UAAU,QAAQ,OAAO,GAAG,CAAC,IAAI,QAAQ,IAAI,SAAS,IAAI,UAAU,IAAI,OAAO,GAC5C,KAAK,QAAQ,IAAI,SAAS,yBAAyB,UAAU,WAAW,WAAW;;;EAI1J,MAAM,YAAY,wBAAwB,KAAK,QAAQ,IAAI,cAAc;EACzE,MAAM,UAAU,aAAa,iBAAiB,KAAK,QAAQ,GAAG;AAC9D,MAAI,YAAY,YACd,QAAO,KAAK,YAAY,KAAK,YAAY,EAAE,EAAE,UAAU,QAAQ,cAAc;EAG/E,MAAM,QAAQ,iBAAiB,SAAS,UAAU,QAAQ;GACxD,aAAa;GACb,gBAAgB,QAAQ,UAAU;GACnC,CAAC;EACF,MAAM,aAAa,KAAK,YAAY,EAAE;EACtC,MAAM,WAAW,WACd,KAAI,UAAS,MAAM,KAAK,WAAW,OAAO,UAAU,QAAQ,cAAc,CAAC,GAAG,CAC9E,KAAK,GAAG;AACX,MAAI,kBAAkB,IAAI,QAAQ,IAAI,WAAW,WAAW,EAC1D,QAAO,UAAU,UAAU,MAAM;AAEnC,SAAO,UAAU,UAAU,MAAM,GAAG,SAAS,IAAI,QAAQ;;;AAI7D,MAAa,WAAW,IAAI,UAAU"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"specialNodes.mjs","names":[],"sources":["../../../src/compiler/wxml/specialNodes.ts"],"sourcesContent":["import type {\n ImportEntry,\n IncludeEntry,\n RenderNode,\n TemplateDefinition,\n WxsEntry,\n} from './types'\n\nimport { dirname, relative } from 'pathe'\nimport { TEMPLATE_IMPORT_TAG_NAMES, TEMPLATE_INCLUDE_TAG_NAMES } from '../../shared/wxml'\n\nexport function shouldMarkWxsImport(pathname: string) {\n const lower = pathname.toLowerCase()\n if (lower.endsWith('.wxs') || lower.endsWith('.wxs.ts') || lower.endsWith('.wxs.js')) {\n return false\n }\n return lower.endsWith('.ts') || lower.endsWith('.js')\n}\n\ninterface CollectSpecialNodesContext {\n templates: TemplateDefinition[]\n includes: IncludeEntry[]\n imports: ImportEntry[]\n wxs: WxsEntry[]\n wxsModules: Map<string, string>\n warnings: string[]\n sourceId: string\n resolveTemplate: (raw: string) => string | undefined\n resolveWxs: (raw: string) => string | undefined\n}\n\nexport function collectSpecialNodes(nodes: RenderNode[], context: CollectSpecialNodesContext) {\n const renderable: RenderNode[] = []\n for (const node of nodes) {\n if (node.type === 'element') {\n const name = node.name ?? ''\n if (name === 'template' && node.attribs?.name) {\n context.templates.push({\n name: node.attribs.name,\n nodes: collectSpecialNodes(node.children ?? [], context),\n })\n continue\n }\n if (TEMPLATE_IMPORT_TAG_NAMES.includes(name) && node.attribs?.src) {\n const resolved = context.resolveTemplate(node.attribs.src)\n if (resolved) {\n context.imports.push({\n id: resolved,\n importName: `__wxml_import_${context.imports.length}`,\n })\n }\n else {\n context.warnings.push(`[web] 无法解析模板依赖: ${node.attribs.src} (from ${context.sourceId})`)\n }\n continue\n }\n if (TEMPLATE_INCLUDE_TAG_NAMES.includes(name) && node.attribs?.src) {\n const resolved = context.resolveTemplate(node.attribs.src)\n if (resolved) {\n context.includes.push({\n id: resolved,\n importName: `__wxml_include_${context.includes.length}`,\n })\n }\n else {\n context.warnings.push(`[web] 无法解析模板依赖: ${node.attribs.src} (from ${context.sourceId})`)\n }\n continue\n }\n if (name === 'wxs') {\n const moduleName = node.attribs?.module?.trim()\n if (moduleName) {\n const previousSource = context.wxsModules.get(moduleName)\n if (previousSource) {\n context.warnings.push(`[web] WXS 模块名重复: ${moduleName} (from ${context.sourceId})`)\n }\n context.wxsModules.set(moduleName, context.sourceId)\n if (node.attribs?.src) {\n const resolved = context.resolveWxs(node.attribs.src)\n if (resolved) {\n context.wxs.push({\n module: moduleName,\n kind: 'src',\n importName: `__wxs_${context.wxs.length}`,\n value: resolved,\n })\n }\n }\n else {\n const inlineCode = (node.children ?? [])\n .filter(child => child.type === 'text')\n .map(child => child.data ?? '')\n .join('')\n context.wxs.push({\n module: moduleName,\n kind: 'inline',\n importName: `__wxs_${context.wxs.length}`,\n value: inlineCode,\n })\n }\n }\n continue\n }\n if (node.children?.length) {\n node.children = collectSpecialNodes(node.children, context)\n }\n }\n renderable.push(node)\n }\n return renderable\n}\n\nexport function normalizeTemplatePath(pathname: string) {\n return pathname.split('\\\\').join('/')\n}\n\nexport function toRelativeImport(from: string, target: string) {\n const fromDir = dirname(from)\n const rel = relative(fromDir, target)\n if (!rel || rel.startsWith('.')) {\n const fallback = normalizeTemplatePath(target).split('/').pop() ?? ''\n return rel || `./${fallback}`\n }\n return `./${rel}`\n}\n"],"mappings":";;;;AAWA,SAAgB,oBAAoB,UAAkB;CACpD,MAAM,QAAQ,SAAS,aAAa;AACpC,KAAI,MAAM,SAAS,OAAO,IAAI,MAAM,SAAS,UAAU,IAAI,MAAM,SAAS,UAAU,CAClF,QAAO;AAET,QAAO,MAAM,SAAS,MAAM,IAAI,MAAM,SAAS,MAAM;;AAevD,SAAgB,oBAAoB,OAAqB,SAAqC;CAC5F,MAAM,aAA2B,EAAE;AACnC,MAAK,MAAM,QAAQ,OAAO;AACxB,MAAI,KAAK,SAAS,WAAW;GAC3B,MAAM,OAAO,KAAK,QAAQ;AAC1B,OAAI,SAAS,cAAc,KAAK,SAAS,MAAM;AAC7C,YAAQ,UAAU,KAAK;KACrB,MAAM,KAAK,QAAQ;KACnB,OAAO,oBAAoB,KAAK,YAAY,EAAE,EAAE,QAAQ;KACzD,CAAC;AACF;;AAEF,OAAI,0BAA0B,SAAS,KAAK,IAAI,KAAK,SAAS,KAAK;IACjE,MAAM,WAAW,QAAQ,gBAAgB,KAAK,QAAQ,IAAI;AAC1D,QAAI,SACF,SAAQ,QAAQ,KAAK;KACnB,IAAI;KACJ,YAAY,iBAAiB,QAAQ,QAAQ;KAC9C,CAAC;QAGF,SAAQ,SAAS,KAAK,mBAAmB,KAAK,QAAQ,IAAI,SAAS,QAAQ,SAAS,GAAG;AAEzF;;AAEF,OAAI,2BAA2B,SAAS,KAAK,IAAI,KAAK,SAAS,KAAK;IAClE,MAAM,WAAW,QAAQ,gBAAgB,KAAK,QAAQ,IAAI;AAC1D,QAAI,SACF,SAAQ,SAAS,KAAK;KACpB,IAAI;KACJ,YAAY,kBAAkB,QAAQ,SAAS;KAChD,CAAC;QAGF,SAAQ,SAAS,KAAK,mBAAmB,KAAK,QAAQ,IAAI,SAAS,QAAQ,SAAS,GAAG;AAEzF;;AAEF,OAAI,SAAS,OAAO;IAClB,MAAM,aAAa,KAAK,SAAS,QAAQ,MAAM;AAC/C,QAAI,YAAY;AAEd,SADuB,QAAQ,WAAW,IAAI,
|
|
1
|
+
{"version":3,"file":"specialNodes.mjs","names":[],"sources":["../../../src/compiler/wxml/specialNodes.ts"],"sourcesContent":["import type {\n ImportEntry,\n IncludeEntry,\n RenderNode,\n TemplateDefinition,\n WxsEntry,\n} from './types'\n\nimport { dirname, relative } from 'pathe'\nimport { TEMPLATE_IMPORT_TAG_NAMES, TEMPLATE_INCLUDE_TAG_NAMES } from '../../shared/wxml'\n\nexport function shouldMarkWxsImport(pathname: string) {\n const lower = pathname.toLowerCase()\n if (lower.endsWith('.wxs') || lower.endsWith('.wxs.ts') || lower.endsWith('.wxs.js')) {\n return false\n }\n return lower.endsWith('.ts') || lower.endsWith('.js')\n}\n\ninterface CollectSpecialNodesContext {\n templates: TemplateDefinition[]\n includes: IncludeEntry[]\n imports: ImportEntry[]\n wxs: WxsEntry[]\n wxsModules: Map<string, string>\n warnings: string[]\n sourceId: string\n resolveTemplate: (raw: string) => string | undefined\n resolveWxs: (raw: string) => string | undefined\n}\n\nexport function collectSpecialNodes(nodes: RenderNode[], context: CollectSpecialNodesContext) {\n const renderable: RenderNode[] = []\n for (const node of nodes) {\n if (node.type === 'element') {\n const name = node.name ?? ''\n if (name === 'template' && node.attribs?.name) {\n context.templates.push({\n name: node.attribs.name,\n nodes: collectSpecialNodes(node.children ?? [], context),\n })\n continue\n }\n if (TEMPLATE_IMPORT_TAG_NAMES.includes(name) && node.attribs?.src) {\n const resolved = context.resolveTemplate(node.attribs.src)\n if (resolved) {\n context.imports.push({\n id: resolved,\n importName: `__wxml_import_${context.imports.length}`,\n })\n }\n else {\n context.warnings.push(`[web] 无法解析模板依赖: ${node.attribs.src} (from ${context.sourceId})`)\n }\n continue\n }\n if (TEMPLATE_INCLUDE_TAG_NAMES.includes(name) && node.attribs?.src) {\n const resolved = context.resolveTemplate(node.attribs.src)\n if (resolved) {\n context.includes.push({\n id: resolved,\n importName: `__wxml_include_${context.includes.length}`,\n })\n }\n else {\n context.warnings.push(`[web] 无法解析模板依赖: ${node.attribs.src} (from ${context.sourceId})`)\n }\n continue\n }\n if (name === 'wxs') {\n const moduleName = node.attribs?.module?.trim()\n if (moduleName) {\n const previousSource = context.wxsModules.get(moduleName)\n if (previousSource) {\n context.warnings.push(`[web] WXS 模块名重复: ${moduleName} (from ${context.sourceId})`)\n }\n context.wxsModules.set(moduleName, context.sourceId)\n if (node.attribs?.src) {\n const resolved = context.resolveWxs(node.attribs.src)\n if (resolved) {\n context.wxs.push({\n module: moduleName,\n kind: 'src',\n importName: `__wxs_${context.wxs.length}`,\n value: resolved,\n })\n }\n }\n else {\n const inlineCode = (node.children ?? [])\n .filter(child => child.type === 'text')\n .map(child => child.data ?? '')\n .join('')\n context.wxs.push({\n module: moduleName,\n kind: 'inline',\n importName: `__wxs_${context.wxs.length}`,\n value: inlineCode,\n })\n }\n }\n continue\n }\n if (node.children?.length) {\n node.children = collectSpecialNodes(node.children, context)\n }\n }\n renderable.push(node)\n }\n return renderable\n}\n\nexport function normalizeTemplatePath(pathname: string) {\n return pathname.split('\\\\').join('/')\n}\n\nexport function toRelativeImport(from: string, target: string) {\n const fromDir = dirname(from)\n const rel = relative(from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ies: string[]\n warnings?: string[]\n}\n\nexport interface WxsTransformOptions {\n resolvePath: (request: string, importer: string) => string | undefined\n toImportPath?: (resolved: string, importer: string) => string\n}\n\nconst REQUIRE_RE = /require\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g\n\nfunction normalizePath(p: string) {\n return p.split('\\\\\\\\').join('/')\n}\n\nfunction isPlainWxsScript(pathname: string) {\n const lower = pathname.toLowerCase()\n if (lower.endsWith('.wxs') || lower.endsWith('.wxs.ts') || lower.endsWith('.wxs.js')) {\n return false\n }\n return lower.endsWith('.ts') || lower.endsWith('.js')\n}\n\nfunction appendWxsQuery(pathname: string) {\n if (pathname.includes('?wxs') || pathname.includes('&wxs')) {\n return pathname\n }\n return `${pathname}${pathname.includes('?') ? '&' : '?'}wxs`\n}\n\nfunction isSupportedRequirePath(request: string) {\n const normalized = request.replace(/\\\\/g, '/')\n return normalized.startsWith('.') || normalized.startsWith('/')\n}\n\nexport function transformWxsToEsm(code: string, id: string, options: WxsTransformOptions): WxsTransformResult {\n const dependencies: string[] = []\n const importLines: string[] = []\n const mapEntries: string[] = []\n const warnings: string[] = []\n\n const seen = new Set<string>()\n while (true) {\n const match = REQUIRE_RE.exec(code)\n if (!match) {\n break\n }\n const request = match[1]\n if (!request || seen.has(request)) {\n continue\n }\n seen.add(request)\n if (!isSupportedRequirePath(request)) {\n warnings.push(`[@weapp-vite/web] WXS require 仅支持相对或绝对路径: ${request} (from ${id})`)\n continue\n }\n const normalizedRequest = request.replace(/\\\\/g, '/')\n const resolved = options.resolvePath(normalizedRequest, id)\n if (!resolved) {\n warnings.push(`[@weapp-vite/web] 无法解析 WXS require: ${request} (from ${id})`)\n continue\n }\n let importPath = normalizePath(options.toImportPath?.(resolved, id) ?? resolved)\n if (isPlainWxsScript(resolved)) {\n importPath = appendWxsQuery(importPath)\n }\n const importName = `__wxs_dep_${dependencies.length}`\n importLines.push(`import ${importName} from '${importPath}'`)\n mapEntries.push(`[${JSON.stringify(request)}, ${importName}]`)\n dependencies.push(resolved)\n }\n\n const requireMap = `const __wxs_require_map = new Map([${mapEntries.join(', ')}])`\n const requireFn = [\n `const __wxs_require_warned = new Set()`,\n `function require(id) {`,\n ` if (__wxs_require_map.has(id)) {`,\n ` return __wxs_require_map.get(id)`,\n ` }`,\n ` if (!__wxs_require_warned.has(id)) {`,\n ` __wxs_require_warned.add(id)`,\n ` if (typeof console !== 'undefined' && typeof console.warn === 'function') {`,\n ` console.warn(\\`[@weapp-vite/web] WXS require 未解析: \\${id}\\`)`,\n ` }`,\n ` }`,\n ` return undefined`,\n `}`,\n ].join('\\\\n')\n const moduleInit = `const module = { exports: {} }\\\\nconst exports = module.exports`\n const helpers = `const getRegExp = (pattern, flags) => new RegExp(pattern, flags)\\\\nconst getDate = (value) => (value == null ? new Date() : new Date(value))`\n\n const body = [\n ...importLines,\n requireMap,\n requireFn,\n moduleInit,\n helpers,\n code,\n `export default module.exports`,\n ].join('\\\\n')\n\n return {\n code: body,\n dependencies,\n warnings: warnings.length > 0 ? warnings : undefined,\n }\n}\n"],"mappings":";AAWA,MAAM,aAAa;AAEnB,SAAS,cAAc,GAAW;AAChC,QAAO,EAAE,MAAM,OAAO,CAAC,KAAK,IAAI;;AAGlC,SAAS,iBAAiB,UAAkB;CAC1C,MAAM,QAAQ,SAAS,aAAa;AACpC,KAAI,MAAM,SAAS,OAAO,IAAI,MAAM,SAAS,UAAU,IAAI,MAAM,SAAS,UAAU,CAClF,QAAO;AAET,QAAO,MAAM,SAAS,MAAM,IAAI,MAAM,SAAS,MAAM;;AAGvD,SAAS,eAAe,UAAkB;AACxC,KAAI,SAAS,SAAS,OAAO,IAAI,SAAS,SAAS,OAAO,CACxD,QAAO;AAET,QAAO,GAAG,WAAW,SAAS,SAAS,IAAI,GAAG,MAAM,IAAI;;AAG1D,SAAS,uBAAuB,SAAiB;CAC/C,MAAM,aAAa,QAAQ,QAAQ,OAAO,IAAI;AAC9C,QAAO,WAAW,WAAW,IAAI,IAAI,WAAW,WAAW,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js","names":[],"sources":["../../src/compiler/wxs.ts"],"sourcesContent":["export interface WxsTransformResult {\n code: string\n dependencies: string[]\n warnings?: string[]\n}\n\nexport interface WxsTransformOptions {\n resolvePath: (request: string, importer: string) => string | undefined\n toImportPath?: (resolved: string, importer: string) => string\n}\n\nconst REQUIRE_RE = /require\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g\n\nfunction normalizePath(p: string) {\n return p.split('\\\\\\\\').join('/')\n}\n\nfunction isPlainWxsScript(pathname: string) {\n const lower = pathname.toLowerCase()\n if (lower.endsWith('.wxs') || lower.endsWith('.wxs.ts') || lower.endsWith('.wxs.js')) {\n return false\n }\n return lower.endsWith('.ts') || lower.endsWith('.js')\n}\n\nfunction appendWxsQuery(pathname: string) {\n if (pathname.includes('?wxs') || pathname.includes('&wxs')) {\n return pathname\n }\n return `${pathname}${pathname.includes('?') ? '&' : '?'}wxs`\n}\n\nfunction isSupportedRequirePath(request: string) {\n const normalized = request.replace(/\\\\/g, '/')\n return normalized.startsWith('.') || normalized.startsWith('/')\n}\n\nexport function transformWxsToEsm(code: string, id: string, options: WxsTransformOptions): WxsTransformResult {\n const dependencies: string[] = []\n const importLines: string[] = []\n const mapEntries: string[] = []\n const warnings: string[] = []\n\n const seen = new Set<string>()\n while (true) {\n const match = REQUIRE_RE.exec(code)\n if (!match) {\n break\n }\n const request = match[1]\n if (!request || seen.has(request)) {\n continue\n }\n seen.add(request)\n if (!isSupportedRequirePath(request)) {\n warnings.push(`[@weapp-vite/web] WXS require 仅支持相对或绝对路径: ${request} (from ${id})`)\n continue\n }\n const normalizedRequest = request.replace(/\\\\/g, '/')\n const resolved = options.resolvePath(normalizedRequest, id)\n if (!resolved) {\n warnings.push(`[@weapp-vite/web] 无法解析 WXS require: ${request} (from ${id})`)\n continue\n }\n let importPath = normalizePath(options.toImportPath?.(resolved, id) ?? resolved)\n if (isPlainWxsScript(resolved)) {\n importPath = appendWxsQuery(importPath)\n }\n const importName = `__wxs_dep_${dependencies.length}`\n importLines.push(`import ${importName} from '${importPath}'`)\n mapEntries.push(`[${JSON.stringify(request)}, ${importName}]`)\n dependencies.push(resolved)\n }\n\n const requireMap = `const __wxs_require_map = new Map([${mapEntries.join(', ')}])`\n const requireFn = [\n `const __wxs_require_warned = new Set()`,\n `function require(id) {`,\n ` if (__wxs_require_map.has(id)) {`,\n ` return __wxs_require_map.get(id)`,\n ` }`,\n ` if (!__wxs_require_warned.has(id)) {`,\n ` __wxs_require_warned.add(id)`,\n ` if (typeof console !== 'undefined' && typeof console.warn === 'function') {`,\n ` console.warn(\\`[@weapp-vite/web] WXS require 未解析: \\${id}\\`)`,\n ` }`,\n ` }`,\n ` return undefined`,\n `}`,\n ].join('\\\\n')\n const moduleInit = `const module = { exports: {} }\\\\nconst exports = module.exports`\n const helpers = `const getRegExp = (pattern, flags) => new RegExp(pattern, flags)\\\\nconst getDate = (value) => (value == null ? new Date() : new Date(value))`\n\n const body = [\n ...importLines,\n requireMap,\n requireFn,\n moduleInit,\n helpers,\n code,\n `export default module.exports`,\n ].join('\\\\n')\n\n return {\n code: body,\n dependencies,\n warnings: warnings.length > 0 ? warnings : undefined,\n }\n}\n"],"mappings":";AAWA,MAAM,aAAa;AAEnB,SAAS,cAAc,GAAW;AAChC,QAAO,EAAE,MAAM,OAAO,CAAC,KAAK,IAAI;;AAGlC,SAAS,iBAAiB,UAAkB;CAC1C,MAAM,QAAQ,SAAS,aAAa;AACpC,KAAI,MAAM,SAAS,OAAO,IAAI,MAAM,SAAS,UAAU,IAAI,MAAM,SAAS,UAAU,CAClF,QAAO;AAET,QAAO,MAAM,SAAS,MAAM,IAAI,MAAM,SAAS,MAAM;;AAGvD,SAAS,eAAe,UAAkB;AACxC,KAAI,SAAS,SAAS,OAAO,IAAI,SAAS,SAAS,OAAO,CACxD,QAAO;AAET,QAAO,GAAG,WAAW,SAAS,SAAS,IAAI,GAAG,MAAM,IAAI;;AAG1D,SAAS,uBAAuB,SAAiB;CAC/C,MAAM,aAAa,QAAQ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ACA;GACA;GACA;GACA;GACA;GACD,CAAC,KAAK,MAGK;EACV;EACA,UAAU,SAAS,SAAS,IAAI,WAAW;EAC5C"}
|
package/dist/css/wxss.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wxss.mjs","names":[],"sources":["../../src/css/wxss.ts"],"sourcesContent":["export interface WxssTransformOptions {\n /**\n * 1rpx 对应的 CSS 像素数。\n * 默认值近似于 750rpx 设计稿在 375px 屏幕上的换算。\n */\n pxPerRpx?: number\n /**\n * rpx 换算的设计宽度。传入后会把 rpx 转为\n * `calc(var(--rpx) * N)` 以实现响应式缩放。\n */\n designWidth?: number\n /**\n * 用于存储运行时 rpx 大小的 CSS 变量名。\n * @default \"--rpx\"\n */\n rpxVar?: string\n}\n\nexport interface WxssTransformResult {\n css: string\n}\n\nconst RPX_RE = /(-?(?:\\d+(?:\\.\\d+)?|\\.\\d+))rpx/gi\n\nexport function transformWxssToCss(source: string, options?: WxssTransformOptions): WxssTransformResult {\n const rpxVar = options?.rpxVar ?? '--rpx'\n const useVariable = typeof options?.designWidth === 'number' && Number.isFinite(options.designWidth)\n const ratio = options?.pxPerRpx ?? 0.5\n const css = source.replace(RPX_RE, (_, value: string) => {\n const numeric = Number.parseFloat(value)\n if (Number.isNaN(numeric)) {\n return `${value}px`\n }\n if (useVariable) {\n return `calc(var(${rpxVar}) * ${numeric})`\n }\n const converted = Math.round(numeric * ratio * 1000) / 1000\n return `${converted}px`\n })\n return {\n css,\n }\n}\n"],"mappings":";AAsBA,MAAM,SAAS;AAEf,SAAgB,mBAAmB,QAAgB,SAAqD;CACtG,MAAM,SAAS,SAAS,UAAU;CAClC,MAAM,cAAc,OAAO,SAAS,gBAAgB,YAAY,OAAO,SAAS,QAAQ,YAAY;CACpG,MAAM,QAAQ,SAAS,YAAY;AAYnC,QAAO,EACL,KAZU,OAAO,QAAQ,SAAS,GAAG,UAAkB;EACvD,MAAM,UAAU,OAAO,WAAW,MAAM;AACxC,MAAI,OAAO,MAAM,QAAQ,CACvB,QAAO,GAAG,MAAM;AAElB,MAAI,YACF,QAAO,YAAY,OAAO,MAAM,QAAQ;AAG1C,SAAO,GADW,KAAK,MAAM,UAAU,QAAQ,IAAK,GAAG,IACnC;
|
|
1
|
+
{"version":3,"file":"wxss.mjs","names":[],"sources":["../../src/css/wxss.ts"],"sourcesContent":["export interface WxssTransformOptions {\n /**\n * 1rpx 对应的 CSS 像素数。\n * 默认值近似于 750rpx 设计稿在 375px 屏幕上的换算。\n */\n pxPerRpx?: number\n /**\n * rpx 换算的设计宽度。传入后会把 rpx 转为\n * `calc(var(--rpx) * N)` 以实现响应式缩放。\n */\n designWidth?: number\n /**\n * 用于存储运行时 rpx 大小的 CSS 变量名。\n * @default \"--rpx\"\n */\n rpxVar?: string\n}\n\nexport interface WxssTransformResult {\n css: string\n}\n\nconst RPX_RE = /(-?(?:\\d+(?:\\.\\d+)?|\\.\\d+))rpx/gi\n\nexport function transformWxssToCss(source: string, options?: WxssTransformOptions): WxssTransformResult {\n const rpxVar = options?.rpxVar ?? '--rpx'\n const useVariable = typeof options?.designWidth === 'number' && Number.isFinite(options.designWidth)\n const ratio = options?.pxPerRpx ?? 0.5\n const css = source.replace(RPX_RE, (_, value: string) => {\n const numeric = Number.parseFloat(value)\n if (Number.isNaN(numeric)) {\n return `${value}px`\n }\n if (useVariable) {\n return `calc(var(${rpxVar}) * ${numeric})`\n }\n const converted = Math.round(numeric * ratio * 1000) / 1000\n return `${converted}px`\n })\n return {\n css,\n }\n}\n"],"mappings":";AAsBA,MAAM,SAAS;AAEf,SAAgB,mBAAmB,QAAgB,SAAqD;CACtG,MAAM,SAAS,SAAS,UAAU;CAClC,MAAM,cAAc,OAAO,SAAS,gBAAgB,YAAY,OAAO,SAAS,QAAQ,YAAY;CACpG,MAAM,QAAQ,SAAS,YAAY;AAYnC,QAAO,EACL,KAZU,OAAO,QAAQ,SAAS,GAAG,UAAkB;EACvD,MAAM,UAAU,OAAO,WAAW,MAAM;AACxC,MAAI,OAAO,MAAM,QAAQ,CACvB,QAAO,GAAG,MAAM;AAElB,MAAI,YACF,QAAO,YAAY,OAAO,MAAM,QAAQ;AAG1C,SAAO,GADW,KAAK,MAAM,UAAU,QAAQ,IAAK,GAAG,IACnC;GAGjB,EACJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"entry.mjs","names":[],"sources":["../../src/plugin/entry.ts"],"sourcesContent":["import type { WxssTransformOptions } from '../css/wxss'\n\nimport type { ScanResult, WeappWebPluginOptions } from './types'\nimport { relativeModuleId, resolveRuntimePolyfillPath, toViteFsImport } from './path'\n\nexport function generateEntryModule(\n result: ScanResult,\n root: string,\n wxssOptions?: WxssTransformOptions,\n pluginOptions?: WeappWebPluginOptions,\n) {\n const runtimePolyfillId = toViteFsImport(resolveRuntimePolyfillPath())\n const importLines: string[] = [`import { initializePageRoutes } from '${runtimePolyfillId}'`]\n const bodyLines: string[] = []\n\n for (const page of result.pages) {\n importLines.push(`import '${relativeModuleId(root, page.script)}'`)\n }\n for (const component of result.components) {\n importLines.push(`import '${relativeModuleId(root, component.script)}'`)\n }\n if (result.app) {\n importLines.push(`import '${relativeModuleId(root, result.app)}'`)\n }\n\n const pageOrder = result.pages.map(page => page.id)\n const rpxConfig = wxssOptions?.designWidth\n ? { designWidth: wxssOptions.designWidth, varName: wxssOptions.rpxVar }\n : undefined\n\n const initOptions: Record<string, any> = {}\n if (rpxConfig) {\n initOptions.rpx = rpxConfig\n }\n if (pluginOptions?.form?.preventDefault !== undefined) {\n initOptions.form = { preventDefault: pluginOptions.form.preventDefault }\n }\n\n const runtimeOptions: Record<string, any> = {}\n if (pluginOptions?.runtime?.executionMode) {\n runtimeOptions.executionMode = pluginOptions.runtime.executionMode\n }\n if (pluginOptions?.runtime?.warnings) {\n runtimeOptions.warnings = pluginOptions.runtime.warnings\n }\n if (Object.keys(runtimeOptions).length > 0) {\n initOptions.runtime = runtimeOptions\n }\n\n const initOptionsCode = Object.keys(initOptions).length > 0 ? `, ${JSON.stringify(initOptions)}` : ''\n bodyLines.push(`initializePageRoutes(${JSON.stringify(pageOrder)}${initOptionsCode})`)\n return [...importLines, ...bodyLines].join('\\n')\n}\n"],"mappings":";;;AAKA,SAAgB,oBACd,QACA,MACA,aACA,eACA;CAEA,MAAM,cAAwB,CAAC,yCADL,eAAe,4BAA4B,CAAC,
|
|
1
|
+
{"version":3,"file":"entry.mjs","names":[],"sources":["../../src/plugin/entry.ts"],"sourcesContent":["import type { WxssTransformOptions } from '../css/wxss'\n\nimport type { ScanResult, WeappWebPluginOptions } from './types'\nimport { relativeModuleId, resolveRuntimePolyfillPath, toViteFsImport } from './path'\n\nexport function generateEntryModule(\n result: ScanResult,\n root: string,\n wxssOptions?: WxssTransformOptions,\n pluginOptions?: WeappWebPluginOptions,\n) {\n const runtimePolyfillId = toViteFsImport(resolveRuntimePolyfillPath())\n const importLines: string[] = [`import { initializePageRoutes } from '${runtimePolyfillId}'`]\n const bodyLines: string[] = []\n\n for (const page of result.pages) {\n importLines.push(`import '${relativeModuleId(root, page.script)}'`)\n }\n for (const component of result.components) {\n importLines.push(`import '${relativeModuleId(root, component.script)}'`)\n }\n if (result.app) {\n importLines.push(`import '${relativeModuleId(root, result.app)}'`)\n }\n\n const pageOrder = result.pages.map(page => page.id)\n const rpxConfig = wxssOptions?.designWidth\n ? { designWidth: wxssOptions.designWidth, varName: wxssOptions.rpxVar }\n : undefined\n\n const initOptions: Record<string, any> = {}\n if (rpxConfig) {\n initOptions.rpx = rpxConfig\n }\n if (pluginOptions?.form?.preventDefault !== undefined) {\n initOptions.form = { preventDefault: pluginOptions.form.preventDefault }\n }\n\n const runtimeOptions: Record<string, any> = {}\n if (pluginOptions?.runtime?.executionMode) {\n runtimeOptions.executionMode = pluginOptions.runtime.executionMode\n }\n if (pluginOptions?.runtime?.warnings) {\n runtimeOptions.warnings = pluginOptions.runtime.warnings\n }\n if (Object.keys(runtimeOptions).length > 0) {\n initOptions.runtime = runtimeOptions\n }\n\n const initOptionsCode = Object.keys(initOptions).length > 0 ? `, ${JSON.stringify(initOptions)}` : ''\n bodyLines.push(`initializePageRoutes(${JSON.stringify(pageOrder)}${initOptionsCode})`)\n return [...importLines, ...bodyLines].join('\\n')\n}\n"],"mappings":";;;AAKA,SAAgB,oBACd,QACA,MACA,aACA,eACA;CAEA,MAAM,cAAwB,CAAC,yCADL,eAAe,4BAA4B,CACoB,CAAC,GAAG;CAC7F,MAAM,YAAsB,EAAE;AAE9B,MAAK,MAAM,QAAQ,OAAO,MACxB,aAAY,KAAK,WAAW,iBAAiB,MAAM,KAAK,OAAO,CAAC,GAAG;AAErE,MAAK,MAAM,aAAa,OAAO,WAC7B,aAAY,KAAK,WAAW,iBAAiB,MAAM,UAAU,OAAO,CAAC,GAAG;AAE1E,KAAI,OAAO,IACT,aAAY,KAAK,WAAW,iBAAiB,MAAM,OAAO,IAAI,CAAC,GAAG;CAGpE,MAAM,YAAY,OAAO,MAAM,KAAI,SAAQ,KAAK,GAAG;CACnD,MAAM,YAAY,aAAa,cAC3B;EAAE,aAAa,YAAY;EAAa,SAAS,YAAY;EAAQ,GACrE;CAEJ,MAAM,cAAmC,EAAE;AAC3C,KAAI,UACF,aAAY,MAAM;AAEpB,KAAI,eAAe,MAAM,mBAAmB,OAC1C,aAAY,OAAO,EAAE,gBAAgB,cAAc,KAAK,gBAAgB;CAG1E,MAAM,iBAAsC,EAAE;AAC9C,KAAI,eAAe,SAAS,cAC1B,gBAAe,gBAAgB,cAAc,QAAQ;AAEvD,KAAI,eAAe,SAAS,SAC1B,gBAAe,WAAW,cAAc,QAAQ;AAElD,KAAI,OAAO,KAAK,eAAe,CAAC,SAAS,EACvC,aAAY,UAAU;CAGxB,MAAM,kBAAkB,OAAO,KAAK,YAAY,CAAC,SAAS,IAAI,KAAK,KAAK,UAAU,YAAY,KAAK;AACnG,WAAU,KAAK,wBAAwB,KAAK,UAAU,UAAU,GAAG,gBAAgB,GAAG;AACtF,QAAO,CAAC,GAAG,aAAa,GAAG,UAAU,CAAC,KAAK,KAAK"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"files.mjs","names":[],"sources":["../../src/plugin/files.ts"],"sourcesContent":["import { fs } from '@weapp-core/shared/fs'\nimport { extname } from 'pathe'\nimport { bundleRequire } from 'rolldown-require'\n\nimport { SCRIPT_EXTS, STYLE_EXTS, TEMPLATE_EXTS } from './constants'\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nexport async function readJsonFile(pathname: string) {\n const candidates = [pathname]\n if (pathname.endsWith('.json')) {\n candidates.push(`${pathname}.ts`, `${pathname}.js`)\n }\n\n for (const candidate of candidates) {\n if (!(await fs.pathExists(candidate))) {\n continue\n }\n if (candidate.endsWith('.json')) {\n const json = await fs.readJson(candidate).catch(() => undefined)\n if (!isRecord(json)) {\n return undefined\n }\n return json\n }\n const { mod } = await bundleRequire({\n filepath: candidate,\n preserveTemporaryFile: true,\n })\n const resolved = typeof mod.default === 'function'\n ? await mod.default()\n : mod.default\n if (!isRecord(resolved)) {\n return undefined\n }\n return resolved\n }\n\n return undefined\n}\n\nexport async function resolveJsonPath(basePath: string) {\n const candidates = [basePath]\n if (basePath.endsWith('.json')) {\n candidates.push(`${basePath}.ts`, `${basePath}.js`)\n }\n for (const candidate of candidates) {\n if (await fs.pathExists(candidate)) {\n return candidate\n }\n }\n return undefined\n}\n\nexport async function resolveScriptFile(basePath: string) {\n const ext = extname(basePath)\n if (ext && (await fs.pathExists(basePath))) {\n return basePath\n }\n for (const candidateExt of SCRIPT_EXTS) {\n const candidate = `${basePath}${candidateExt}`\n if (await fs.pathExists(candidate)) {\n return candidate\n }\n }\n return undefined\n}\n\nexport async function resolveStyleFile(scriptPath: string) {\n const base = scriptPath.replace(new RegExp(`${extname(scriptPath)}$`), '')\n for (const ext of STYLE_EXTS) {\n const candidate = `${base}${ext}`\n if (await fs.pathExists(candidate)) {\n return candidate\n }\n }\n return undefined\n}\n\nexport async function resolveTemplateFile(scriptPath: string) {\n const base = scriptPath.replace(new RegExp(`${extname(scriptPath)}$`), '')\n for (const ext of TEMPLATE_EXTS) {\n const candidate = `${base}${ext}`\n if (await fs.pathExists(candidate)) {\n return candidate\n }\n }\n return undefined\n}\n"],"mappings":";;;;;;AAMA,SAAgB,SAAS,OAAkD;AACzE,QAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,MAAM;;AAG7E,eAAsB,aAAa,UAAkB;CACnD,MAAM,aAAa,CAAC,SAAS;AAC7B,KAAI,SAAS,SAAS,QAAQ,CAC5B,YAAW,KAAK,GAAG,SAAS,MAAM,GAAG,SAAS,KAAK;AAGrD,MAAK,MAAM,aAAa,YAAY;AAClC,MAAI,CAAE,MAAM,GAAG,WAAW,UAAU,CAClC;AAEF,MAAI,UAAU,SAAS,QAAQ,EAAE;GAC/B,MAAM,OAAO,MAAM,GAAG,SAAS,UAAU,CAAC,YAAY,OAAU;AAChE,OAAI,CAAC,SAAS,KAAK,CACjB;AAEF,UAAO;;EAET,MAAM,EAAE,QAAQ,MAAM,cAAc;GAClC,UAAU;GACV,uBAAuB;GACxB,CAAC;EACF,MAAM,WAAW,OAAO,IAAI,YAAY,aACpC,MAAM,IAAI,SAAS,GACnB,IAAI;AACR,MAAI,CAAC,SAAS,SAAS,CACrB;AAEF,SAAO;;;AAMX,eAAsB,gBAAgB,UAAkB;CACtD,MAAM,aAAa,CAAC,SAAS;AAC7B,KAAI,SAAS,SAAS,QAAQ,CAC5B,YAAW,KAAK,GAAG,SAAS,MAAM,GAAG,SAAS,KAAK;AAErD,MAAK,MAAM,aAAa,WACtB,KAAI,MAAM,GAAG,WAAW,UAAU,CAChC,QAAO;;AAMb,eAAsB,kBAAkB,UAAkB;AAExD,KADY,QAAQ,
|
|
1
|
+
{"version":3,"file":"files.mjs","names":[],"sources":["../../src/plugin/files.ts"],"sourcesContent":["import { fs } from '@weapp-core/shared/fs'\nimport { extname } from 'pathe'\nimport { bundleRequire } from 'rolldown-require'\n\nimport { SCRIPT_EXTS, STYLE_EXTS, TEMPLATE_EXTS } from './constants'\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nexport async function readJsonFile(pathname: string) {\n const candidates = [pathname]\n if (pathname.endsWith('.json')) {\n candidates.push(`${pathname}.ts`, `${pathname}.js`)\n }\n\n for (const candidate of candidates) {\n if (!(await fs.pathExists(candidate))) {\n continue\n }\n if (candidate.endsWith('.json')) {\n const json = await fs.readJson(candidate).catch(() => undefined)\n if (!isRecord(json)) {\n return undefined\n }\n return json\n }\n const { mod } = await bundleRequire({\n filepath: candidate,\n preserveTemporaryFile: true,\n })\n const resolved = typeof mod.default === 'function'\n ? await mod.default()\n : mod.default\n if (!isRecord(resolved)) {\n return undefined\n }\n return resolved\n }\n\n return undefined\n}\n\nexport async function resolveJsonPath(basePath: string) {\n const candidates = [basePath]\n if (basePath.endsWith('.json')) {\n candidates.push(`${basePath}.ts`, `${basePath}.js`)\n }\n for (const candidate of candidates) {\n if (await fs.pathExists(candidate)) {\n return candidate\n }\n }\n return undefined\n}\n\nexport async function resolveScriptFile(basePath: string) {\n const ext = extname(basePath)\n if (ext && (await fs.pathExists(basePath))) {\n return basePath\n }\n for (const candidateExt of SCRIPT_EXTS) {\n const candidate = `${basePath}${candidateExt}`\n if (await fs.pathExists(candidate)) {\n return candidate\n }\n }\n return undefined\n}\n\nexport async function resolveStyleFile(scriptPath: string) {\n const base = scriptPath.replace(new RegExp(`${extname(scriptPath)}$`), '')\n for (const ext of STYLE_EXTS) {\n const candidate = `${base}${ext}`\n if (await fs.pathExists(candidate)) {\n return candidate\n }\n }\n return undefined\n}\n\nexport async function resolveTemplateFile(scriptPath: string) {\n const base = scriptPath.replace(new RegExp(`${extname(scriptPath)}$`), '')\n for (const ext of TEMPLATE_EXTS) {\n const candidate = `${base}${ext}`\n if (await fs.pathExists(candidate)) {\n return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EAAE,GAAG;AAC1E,MAAK,MAAM,OAAO,YAAY;EAC5B,MAAM,YAAY,GAAG,OAAO;AAC5B,MAAI,MAAM,GAAG,WAAW,UAAU,CAChC,QAAO;;;AAMb,eAAsB,oBAAoB,YAAoB;CAC5D,MAAM,OAAO,WAAW,QAAQ,IAAI,OAAO,GAAG,QAAQ,WAAW,CAAC,GAAG,EAAE,GAAG;AAC1E,MAAK,MAAM,OAAO,eAAe;EAC/B,MAAM,YAAY,GAAG,OAAO;AAC5B,MAAI,MAAM,GAAG,WAAW,UAAU,CAChC,QAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/plugin/index.ts"],"sourcesContent":["import type { SourceMap } from 'magic-string'\nimport type { WeappWebPluginOptions } from './types'\nimport process from 'node:process'\n\nimport { extname, resolve } from 'pathe'\nimport { compileWxml } from '../compiler/wxml'\nimport { transformWxsToEsm } from '../compiler/wxs'\nimport { transformWxssToCss } from '../css/wxss'\nimport { ENTRY_ID, SCRIPT_EXTS, STYLE_EXTS, TEMPLATE_EXTS, TRANSFORM_STYLE_EXTS, WXS_EXTS } from './constants'\nimport { generateEntryModule } from './entry'\nimport { cleanUrl, isHtmlEntry, isInsideDir, normalizePath, resolveTemplatePathSync, resolveWxsPathSync, toRelativeImport } from './path'\nimport { transformScriptModule } from './register'\nimport { scanProject } from './scan'\nimport { createEmptyScanState } from './state'\n\ninterface WebPluginContext {\n warn?: (message: string) => void\n addWatchFile?: (id: string) => void\n}\n\ntype WebTransformResult = { code: string, map: SourceMap | null } | null\n\ninterface WebResolvedConfig {\n root: string\n command: string\n}\n\ninterface WebHmrContext {\n file: string\n}\n\ninterface WeappWebVitePlugin {\n name: string\n enforce?: 'pre' | 'post'\n configResolved?: (this: WebPluginContext, config: WebResolvedConfig) => void | Promise<void>\n buildStart?: (this: WebPluginContext) => void | Promise<void>\n resolveId?: (id: 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 createInlineStyleModule(css: string) {\n const serialized = JSON.stringify(css)\n return [\n `const __weapp_injected_styles__ = new Map()`,\n `function __weapp_createStyleId__(css) {`,\n ` let hash = 2166136261`,\n ` for (let i = 0; i < css.length; i++) {`,\n ` hash ^= css.charCodeAt(i)`,\n ` hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24)`,\n ` }`,\n ` return 'weapp-web-style-' + (hash >>> 0).toString(36)`,\n `}`,\n `function __weapp_removeStyle__(id) {`,\n ` if (typeof document === 'undefined') {`,\n ` return`,\n ` }`,\n ` const style = __weapp_injected_styles__.get(id)`,\n ` if (style) {`,\n ` style.remove()`,\n ` __weapp_injected_styles__.delete(id)`,\n ` }`,\n `}`,\n `function injectStyle(css, id) {`,\n ` if (typeof document === 'undefined') {`,\n ` return () => {}`,\n ` }`,\n ` const styleId = id ?? __weapp_createStyleId__(css)`,\n ` const existing = __weapp_injected_styles__.get(styleId)`,\n ` if (existing) {`,\n ` if (existing.textContent !== css) {`,\n ` existing.textContent = css`,\n ` }`,\n ` return () => __weapp_removeStyle__(styleId)`,\n ` }`,\n ` const style = document.createElement('style')`,\n ` style.id = styleId`,\n ` style.textContent = css`,\n ` document.head.append(style)`,\n ` __weapp_injected_styles__.set(styleId, style)`,\n ` return () => __weapp_removeStyle__(styleId)`,\n `}`,\n `const css = ${serialized}`,\n `export default css`,\n `export function useStyle(id) {`,\n ` return injectStyle(css, id)`,\n `}`,\n ].join('\\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\n const state = createEmptyScanState()\n const wxssOptions = options.wxss\n\n const resolveTemplatePath = (raw: string, importer: string) => resolveTemplatePathSync(raw, importer, srcRoot)\n const resolveWxsPath = (raw: string, importer: string) => resolveWxsPathSync(raw, importer, srcRoot)\n\n return {\n name: '@weapp-vite/web',\n enforce: 'pre',\n async configResolved(this: WebPluginContext, config: WebResolvedConfig) {\n root = config.root\n srcRoot = resolve(root, options.srcDir ?? 'src')\n enableHmr = config.command === 'serve'\n await scanProject({ srcRoot, warn: this.warn?.bind(this), state })\n },\n async buildStart(this: WebPluginContext) {\n await scanProject({ srcRoot, warn: this.warn?.bind(this), state })\n },\n resolveId(id: string) {\n if (id === '/@weapp-vite/web/entry' || id === '@weapp-vite/web/entry') {\n return ENTRY_ID\n }\n return null\n },\n load(id: string) {\n if (id === ENTRY_ID) {\n return generateEntryModule(state.scanResult, root, wxssOptions, options)\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 scanProject({ srcRoot, warn: this.warn?.bind(this), state })\n }\n },\n transform(this: WebPluginContext, code: string, id: string) {\n const clean = cleanUrl(id)\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 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: code,\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 null\n }\n if (clean.includes('node_modules')) {\n return 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 })\n },\n }\n}\n\nexport type { WeappWebPluginOptions } from './types'\n"],"mappings":";;;;;;;;;;;;;AA8CA,SAAS,eAAe,IAAY;CAClC,MAAM,QAAQ,GAAG,aAAa;AAC9B,QAAO,cAAc,MAAK,QAAO,MAAM,SAAS,IAAI,CAAC;;AAGvD,SAAS,UAAU,IAAY;CAC7B,MAAM,QA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AAO;KAChF,aAAa;KACb,eAAe,UAAU,aAAa,cAAc,iBAAiB,UAAU,SAAS,CAAC;KAC1F,CAAC;IACF,MAAM,eAAe,KAAK;AAC1B,QAAI,aAAa,SAAS,KAAK,aAC7B,MAAK,MAAM,OAAO,aAChB,cAAa,KAAK,MAAM,IAAI;IAGhC,MAAM,OAAO,KAAK;AAClB,QAAI,UAAU,UAAU,KACtB,MAAK,MAAM,WAAW,SACpB,MAAK,KAAK,MAAM,QAAQ;AAG5B,WAAO;KAAE,MAAM;KAAU,KAAK;KAAM;;AAGtC,OAAI,qBAAqB,MAAK,QAAO,MAAM,SAAS,IAAI,CAAC,EAAE;IACzD,MAAM,EAAE,QAAQ,mBAAmB,MAAM,YAAY;AACrD,WAAO;KACL,MAAM,wBAAwB,IAAI;KAClC,KAAK;KACN;;AAGH,OAAI,WAAW,MAAK,QAAO,MAAM,SAAS,IAAI,CAAC,IAAI,CAAC,MAAM,SAAS,QAAQ,EAAE;IAC3E,MAAM,EAAE,QAAQ,mBAAmB,MAAM,YAAY;AACrD,WAAO;KAAE,MAAM;KAAK,KAAK;KAAM;;AAGjC,OAAI,CAAC,YAAY,MAAK,QAAO,MAAM,SAAS,IAAI,CAAC,CAC/C,QAAO;AAET,OAAI,MAAM,SAAS,eAAe,CAChC,QAAO;GAGT,MAAM,OAAO,MAAM,WAAW,IAAI,cAAc,MAAM,CAAC;AACvD,OAAI,CAAC,KACH,QAAO;AAGT,UAAO,sBAAsB;IAC3B;IACA,SAAS;IACT;IACA;IACD,CAAC;;EAEL"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/plugin/index.ts"],"sourcesContent":["import type { SourceMap } from 'magic-string'\nimport type { WeappWebPluginOptions } from './types'\nimport process from 'node:process'\n\nimport { extname, resolve } from 'pathe'\nimport { compileWxml } from '../compiler/wxml'\nimport { transformWxsToEsm } from '../compiler/wxs'\nimport { transformWxssToCss } from '../css/wxss'\nimport { ENTRY_ID, SCRIPT_EXTS, STYLE_EXTS, TEMPLATE_EXTS, TRANSFORM_STYLE_EXTS, WXS_EXTS } from './constants'\nimport { generateEntryModule } from './entry'\nimport { cleanUrl, isHtmlEntry, isInsideDir, normalizePath, resolveTemplatePathSync, resolveWxsPathSync, toRelativeImport } from './path'\nimport { transformScriptModule } from './register'\nimport { scanProject } from './scan'\nimport { createEmptyScanState } from './state'\n\ninterface WebPluginContext {\n warn?: (message: string) => void\n addWatchFile?: (id: string) => void\n}\n\ntype WebTransformResult = { code: string, map: SourceMap | null } | null\n\ninterface WebResolvedConfig {\n root: string\n command: string\n}\n\ninterface WebHmrContext {\n file: string\n}\n\ninterface WeappWebVitePlugin {\n name: string\n enforce?: 'pre' | 'post'\n configResolved?: (this: WebPluginContext, config: WebResolvedConfig) => void | Promise<void>\n buildStart?: (this: WebPluginContext) => void | Promise<void>\n resolveId?: (id: 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 createInlineStyleModule(css: string) {\n const serialized = JSON.stringify(css)\n return [\n `const __weapp_injected_styles__ = new Map()`,\n `function __weapp_createStyleId__(css) {`,\n ` let hash = 2166136261`,\n ` for (let i = 0; i < css.length; i++) {`,\n ` hash ^= css.charCodeAt(i)`,\n ` hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24)`,\n ` }`,\n ` return 'weapp-web-style-' + (hash >>> 0).toString(36)`,\n `}`,\n `function __weapp_removeStyle__(id) {`,\n ` if (typeof document === 'undefined') {`,\n ` return`,\n ` }`,\n ` const style = __weapp_injected_styles__.get(id)`,\n ` if (style) {`,\n ` style.remove()`,\n ` __weapp_injected_styles__.delete(id)`,\n ` }`,\n `}`,\n `function injectStyle(css, id) {`,\n ` if (typeof document === 'undefined') {`,\n ` return () => {}`,\n ` }`,\n ` const styleId = id ?? __weapp_createStyleId__(css)`,\n ` const existing = __weapp_injected_styles__.get(styleId)`,\n ` if (existing) {`,\n ` if (existing.textContent !== css) {`,\n ` existing.textContent = css`,\n ` }`,\n ` return () => __weapp_removeStyle__(styleId)`,\n ` }`,\n ` const style = document.createElement('style')`,\n ` style.id = styleId`,\n ` style.textContent = css`,\n ` document.head.append(style)`,\n ` __weapp_injected_styles__.set(styleId, style)`,\n ` return () => __weapp_removeStyle__(styleId)`,\n `}`,\n `const css = ${serialized}`,\n `export default css`,\n `export function useStyle(id) {`,\n ` return injectStyle(css, id)`,\n `}`,\n ].join('\\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\n const state = createEmptyScanState()\n const wxssOptions = options.wxss\n\n const resolveTemplatePath = (raw: string, importer: string) => resolveTemplatePathSync(raw, importer, srcRoot)\n const resolveWxsPath = (raw: string, importer: string) => resolveWxsPathSync(raw, importer, srcRoot)\n\n return {\n name: '@weapp-vite/web',\n enforce: 'pre',\n async configResolved(this: WebPluginContext, config: WebResolvedConfig) {\n root = config.root\n srcRoot = resolve(root, options.srcDir ?? 'src')\n enableHmr = config.command === 'serve'\n await scanProject({ srcRoot, warn: this.warn?.bind(this), state })\n },\n async buildStart(this: WebPluginContext) {\n await scanProject({ srcRoot, warn: this.warn?.bind(this), state })\n },\n resolveId(id: string) {\n if (id === '/@weapp-vite/web/entry' || id === '@weapp-vite/web/entry') {\n return ENTRY_ID\n }\n return null\n },\n load(id: string) {\n if (id === ENTRY_ID) {\n return generateEntryModule(state.scanResult, root, wxssOptions, options)\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 scanProject({ srcRoot, warn: this.warn?.bind(this), state })\n }\n },\n transform(this: WebPluginContext, code: string, id: string) {\n const clean = cleanUrl(id)\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 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: code,\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 null\n }\n if (clean.includes('node_modules')) {\n return 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 })\n },\n }\n}\n\nexport type { WeappWebPluginOptions } from './types'\n"],"mappings":";;;;;;;;;;;;;AA8CA,SAAS,eAAe,IAAY;CAClC,MAAM,QAAQ,GAAG,aAAa;AAC9B,QAAO,cAAc,MAAK,QAAO,MAAM,SAAS,IAAI,CAAC;;AAGvD,SAAS,UAAU,IAAY;CAC7B,MAAM,QAAQ,GAAG,aAAa;AAC9B,QAAO,SAAS,MAAK,QAAO,MAAM,SAAS,IAAI,CAAC;;AAGlD,SAAS,YAAY,IAAY;AAC/B,QAAO,GAAG,SAAS,OAAO,IAAI,GAAG,SAAS,OAAO;;AAGnD,SAAS,wBAAwB,KAAa;AAE5C,QAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,eAxCiB,KAAK,UAAU,IAwCP;EACzB;EACA;EACA;EACA;EACD,CAAC,KAAK,KAAK;;AAGd,SAAgB,eAAe,UAAiC,EAAE,EAAsB;CACtF,IAAI,OAAO,QAAQ,KAAK;CACxB,IAAI,UAAU,QAAQ,MAAM,QAAQ,UAAU,MAAM;CACpD,IAAI,YAAY;CAEhB,MAAM,QAAQ,sBAAsB;CACpC,MAAM,cAAc,QAAQ;CAE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AAO;KAAE,MAAM;KAAK,KAAK;KAAM;;AAGjC,OAAI,CAAC,YAAY,MAAK,QAAO,MAAM,SAAS,IAAI,CAAC,CAC/C,QAAO;AAET,OAAI,MAAM,SAAS,eAAe,CAChC,QAAO;GAGT,MAAM,OAAO,MAAM,WAAW,IAAI,cAAc,MAAM,CAAC;AACvD,OAAI,CAAC,KACH,QAAO;AAGT,UAAO,sBAAsB;IAC3B;IACA,SAAS;IACT;IACA;IACD,CAAC;;EAEL"}
|
package/dist/plugin/path.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"path.mjs","names":[],"sources":["../../src/plugin/path.ts"],"sourcesContent":["import { existsSync } from 'node:fs'\nimport { fileURLToPath } from 'node:url'\nimport { dirname, extname, normalize, posix, relative, resolve } from 'pathe'\n\nimport { TEMPLATE_EXTS, WXS_RESOLVE_EXTS } from './constants'\n\nexport function cleanUrl(url: string) {\n const queryIndex = url.indexOf('?')\n if (queryIndex >= 0) {\n return url.slice(0, queryIndex)\n }\n return url\n}\n\nexport function normalizePath(p: string) {\n return posix.normalize(p.split('\\\\').join('/'))\n}\n\nexport function isInsideDir(filePath: string, dir: string) {\n const rel = relative(dir, filePath)\n return rel === '' || (!rel.startsWith('..') && !posix.isAbsolute(rel))\n}\n\nexport function isHtmlEntry(filePath: string, root: string) {\n if (!filePath.toLowerCase().endsWith('.html')) {\n return false\n }\n return normalizePath(filePath) === normalizePath(resolve(root, 'index.html'))\n}\n\nexport function toPosixId(id: string) {\n return normalize(id).split('\\\\').join('/')\n}\n\nexport function toRelativeImport(from: string, target: string) {\n const fromDir = dirname(from)\n const rel = relative(fromDir, target)\n if (!rel || rel.startsWith('.')) {\n return normalizePath(rel || `./${posix.basename(target)}`)\n }\n return `./${normalizePath(rel)}`\n}\n\nexport function appendInlineQuery(id: string) {\n if (id.includes('?')) {\n if (id.includes('?inline') || id.includes('&inline')) {\n return id\n }\n return `${id}&inline`\n }\n return `${id}?inline`\n}\n\nexport function relativeModuleId(root: string, absPath: string) {\n const rel = relative(root, absPath)\n return `/${normalizePath(rel)}`\n}\n\nexport function toViteFsImport(absPath: string) {\n const normalized = normalizePath(absPath)\n return normalized.startsWith('/')\n ? `/@fs${normalized}`\n : `/@fs/${normalized}`\n}\n\nexport function resolveRuntimePolyfillPath() {\n const currentDir = dirname(fileURLToPath(import.meta.url))\n const candidates = [\n resolve(currentDir, '../runtime/index.mjs'),\n resolve(currentDir, './runtime/index.mjs'),\n resolve(currentDir, '../runtime/polyfill.ts'),\n resolve(currentDir, '../runtime/index.ts'),\n ]\n\n for (const candidate of candidates) {\n if (existsSync(candidate)) {\n return candidate\n }\n }\n\n throw new Error('[@weapp-vite/web] Failed to resolve runtime polyfill path.')\n}\n\nexport function resolveImportBase(raw: string, importer: string, srcRoot: string) {\n if (!raw) {\n return undefined\n }\n if (raw.startsWith('.')) {\n return resolve(dirname(importer), raw)\n }\n if (raw.startsWith('/')) {\n return resolve(srcRoot, raw.slice(1))\n }\n return resolve(srcRoot, raw)\n}\n\nexport function resolveFileWithExtensionsSync(basePath: string, extensions: string[]) {\n if (extname(basePath) && existsSync(basePath)) {\n return basePath\n }\n for (const ext of extensions) {\n const candidate = `${basePath}${ext}`\n if (existsSync(candidate)) {\n return candidate\n }\n }\n return undefined\n}\n\nexport function resolveTemplatePathSync(raw: string, importer: string, srcRoot: string) {\n const base = resolveImportBase(raw, importer, srcRoot)\n if (!base) {\n return undefined\n }\n return resolveFileWithExtensionsSync(base, TEMPLATE_EXTS)\n}\n\nexport function resolveWxsPathSync(raw: string, importer: string, srcRoot: string) {\n if (!raw) {\n return undefined\n }\n let base: string | undefined\n if (raw.startsWith('.')) {\n base = resolve(dirname(importer), raw)\n }\n else if (raw.startsWith('/')) {\n base = resolve(srcRoot, raw.slice(1))\n }\n else {\n return undefined\n }\n return resolveFileWithExtensionsSync(base, WXS_RESOLVE_EXTS)\n}\n"],"mappings":";;;;;;AAMA,SAAgB,SAAS,KAAa;CACpC,MAAM,aAAa,IAAI,QAAQ,IAAI;AACnC,KAAI,cAAc,EAChB,QAAO,IAAI,MAAM,GAAG,WAAW;AAEjC,QAAO;;AAGT,SAAgB,cAAc,GAAW;AACvC,QAAO,MAAM,UAAU,EAAE,MAAM,KAAK,CAAC,KAAK,IAAI,CAAC;;AAGjD,SAAgB,YAAY,UAAkB,KAAa;CACzD,MAAM,MAAM,SAAS,KAAK,SAAS;AACnC,QAAO,QAAQ,MAAO,CAAC,IAAI,WAAW,KAAK,IAAI,CAAC,MAAM,WAAW,IAAI;;AAGvE,SAAgB,YAAY,UAAkB,MAAc;AAC1D,KAAI,CAAC,SAAS,aAAa,CAAC,SAAS,QAAQ,CAC3C,QAAO;AAET,QAAO,cAAc,SAAS,KAAK,cAAc,QAAQ,MAAM,aAAa,CAAC;;AAG/E,SAAgB,UAAU,IAAY;AACpC,QAAO,UAAU,GAAG,CAAC,MAAM,KAAK,CAAC,KAAK,IAAI;;AAG5C,SAAgB,iBAAiB,MAAc,QAAgB;CAE7D,MAAM,MAAM,SADI,QAAQ,
|
|
1
|
+
{"version":3,"file":"path.mjs","names":[],"sources":["../../src/plugin/path.ts"],"sourcesContent":["import { existsSync } from 'node:fs'\nimport { fileURLToPath } from 'node:url'\nimport { dirname, extname, normalize, posix, relative, resolve } from 'pathe'\n\nimport { TEMPLATE_EXTS, WXS_RESOLVE_EXTS } from './constants'\n\nexport function cleanUrl(url: string) {\n const queryIndex = url.indexOf('?')\n if (queryIndex >= 0) {\n return url.slice(0, queryIndex)\n }\n return url\n}\n\nexport function normalizePath(p: string) {\n return posix.normalize(p.split('\\\\').join('/'))\n}\n\nexport function isInsideDir(filePath: string, dir: string) {\n const rel = relative(dir, filePath)\n return rel === '' || (!rel.startsWith('..') && !posix.isAbsolute(rel))\n}\n\nexport function isHtmlEntry(filePath: string, root: string) {\n if (!filePath.toLowerCase().endsWith('.html')) {\n return false\n }\n return normalizePath(filePath) === normalizePath(resolve(root, 'index.html'))\n}\n\nexport function toPosixId(id: string) {\n return normalize(id).split('\\\\').join('/')\n}\n\nexport function toRelativeImport(from: string, target: string) {\n const fromDir = dirname(from)\n const rel = relative(fromDir, target)\n if (!rel || rel.startsWith('.')) {\n return normalizePath(rel || `./${posix.basename(target)}`)\n }\n return `./${normalizePath(rel)}`\n}\n\nexport function appendInlineQuery(id: string) {\n if (id.includes('?')) {\n if (id.includes('?inline') || id.includes('&inline')) {\n return id\n }\n return `${id}&inline`\n }\n return `${id}?inline`\n}\n\nexport function relativeModuleId(root: string, absPath: string) {\n const rel = relative(root, absPath)\n return `/${normalizePath(rel)}`\n}\n\nexport function toViteFsImport(absPath: string) {\n const normalized = normalizePath(absPath)\n return normalized.startsWith('/')\n ? `/@fs${normalized}`\n : `/@fs/${normalized}`\n}\n\nexport function resolveRuntimePolyfillPath() {\n const currentDir = dirname(fileURLToPath(import.meta.url))\n const candidates = [\n resolve(currentDir, '../runtime/index.mjs'),\n resolve(currentDir, './runtime/index.mjs'),\n resolve(currentDir, '../runtime/polyfill.ts'),\n resolve(currentDir, '../runtime/index.ts'),\n ]\n\n for (const candidate of candidates) {\n if (existsSync(candidate)) {\n return candidate\n }\n }\n\n throw new Error('[@weapp-vite/web] Failed to resolve runtime polyfill path.')\n}\n\nexport function resolveImportBase(raw: string, importer: string, srcRoot: string) {\n if (!raw) {\n return undefined\n }\n if (raw.startsWith('.')) {\n return resolve(dirname(importer), raw)\n }\n if (raw.startsWith('/')) {\n return resolve(srcRoot, raw.slice(1))\n }\n return resolve(srcRoot, raw)\n}\n\nexport function resolveFileWithExtensionsSync(basePath: string, extensions: string[]) {\n if (extname(basePath) && existsSync(basePath)) {\n return basePath\n }\n for (const ext of extensions) {\n const candidate = `${basePath}${ext}`\n if (existsSync(candidate)) {\n return candidate\n }\n }\n return undefined\n}\n\nexport function resolveTemplatePathSync(raw: string, importer: string, srcRoot: string) {\n const base = resolveImportBase(raw, importer, srcRoot)\n if (!base) {\n return undefined\n }\n return resolveFileWithExtensionsSync(base, TEMPLATE_EXTS)\n}\n\nexport function resolveWxsPathSync(raw: string, importer: string, srcRoot: string) {\n if (!raw) {\n return undefined\n }\n let base: string | undefined\n if (raw.startsWith('.')) {\n base = resolve(dirname(importer), raw)\n }\n else if (raw.startsWith('/')) {\n base = resolve(srcRoot, raw.slice(1))\n }\n else {\n return undefined\n }\n return resolveFileWithExtensionsSync(base, WXS_RESOLVE_EXTS)\n}\n"],"mappings":";;;;;;AAMA,SAAgB,SAAS,KAAa;CACpC,MAAM,aAAa,IAAI,QAAQ,IAAI;AACnC,KAAI,cAAc,EAChB,QAAO,IAAI,MAAM,GAAG,WAAW;AAEjC,QAAO;;AAGT,SAAgB,cAAc,GAAW;AACvC,QAAO,MAAM,UAAU,EAAE,MAAM,KAAK,CAAC,KAAK,IAAI,CAAC;;AAGjD,SAAgB,YAAY,UAAkB,KAAa;CACzD,MAAM,MAAM,SAAS,KAAK,SAAS;AACnC,QAAO,QAAQ,MAAO,CAAC,IAAI,WAAW,KAAK,IAAI,CAAC,MAAM,WAAW,IAAI;;AAGvE,SAAgB,YAAY,UAAkB,MAAc;AAC1D,KAAI,CAAC,SAAS,aAAa,CAAC,SAAS,QAAQ,CAC3C,QAAO;AAET,QAAO,cAAc,SAAS,KAAK,cAAc,QAAQ,MAAM,aAAa,CAAC;;AAG/E,SAAgB,UAAU,IAAY;AACpC,QAAO,UAAU,GAAG,CAAC,MAAM,KAAK,CAAC,KAAK,IAAI;;AAG5C,SAAgB,iBAAiB,MAAc,QAAgB;CAE7D,MAAM,MAAM,SADI,QAAQ,KACI,EAAE,OAAO;AACrC,KAAI,CAAC,OAAO,IAAI,WAAW,IAAI,CAC7B,QAAO,cAAc,OAAO,KAAK,MAAM,SAAS,OAAO,GAAG;AAE5D,QAAO,KAAK,cAAc,IAAI;;AAGhC,SAAgB,kBAAkB,IAAY;AAC5C,KAAI,GAAG,SAAS,IAAI,EAAE;AACpB,MAAI,GAAG,SAAS,UAAU,IAAI,GAAG,SAAS,UAAU,CAClD,QAAO;AA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,KAAI,IAAI,WAAW,IAAI,CACrB,QAAO,QAAQ,QAAQ,SAAS,EAAE,IAAI;UAE/B,IAAI,WAAW,IAAI,CAC1B,QAAO,QAAQ,SAAS,IAAI,MAAM,EAAE,CAAC;KAGrC;AAEF,QAAO,8BAA8B,MAAM,iBAAiB"}
|
package/dist/plugin/scan.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scan.mjs","names":[],"sources":["../../src/plugin/scan.ts"],"sourcesContent":["import type { ComponentEntry, PageEntry, ScanState, WarnFn } from './types'\nimport process from 'node:process'\n\nimport { dirname, extname, join, posix, relative, resolve } from 'pathe'\nimport { slugify } from '../shared/slugify'\nimport { isRecord, readJsonFile, resolveJsonPath, resolveScriptFile, resolveStyleFile, resolveTemplateFile } from './files'\nimport { mergeNavigationConfig, pickNavigationConfig } from './navigation'\nimport { normalizePath, toPosixId } from './path'\nimport { collectComponentTagsFromConfig, collectComponentTagsFromJson, mergeComponentTags } from './scanConfig'\n\ninterface ScanProjectOptions {\n srcRoot: string\n warn?: WarnFn\n state: ScanState\n}\n\nexport async function scanProject({ srcRoot, warn, state }: ScanProjectOptions) {\n state.moduleMeta.clear()\n state.pageNavigationMap.clear()\n state.templateComponentMap.clear()\n state.templatePathSet.clear()\n state.componentTagMap.clear()\n state.componentIdMap.clear()\n\n let appNavigationDefaults = {}\n let appComponentTags: Record<string, string> = {}\n\n const pages = new Map<string, PageEntry>()\n const components = new Map<string, ComponentEntry>()\n\n const reportWarning = (message: string) => {\n if (warn) {\n warn(message)\n return\n }\n if (typeof process !== 'undefined' && typeof process.emitWarning === 'function') {\n process.emitWarning(message)\n }\n }\n\n const appScript = await resolveScriptFile(join(srcRoot, 'app'))\n if (appScript) {\n state.moduleMeta.set(normalizePath(appScript), {\n kind: 'app',\n id: 'app',\n scriptPath: appScript,\n stylePath: await resolveStyleFile(appScript),\n })\n }\n\n const resolveComponentScript = async (raw: string, importerDir: string) => {\n const base = resolveComponentBase(raw, importerDir, srcRoot)\n if (!base) {\n return undefined\n }\n return resolveScriptFile(base)\n }\n\n const getComponentId = (script: string) => {\n const cached = state.componentIdMap.get(script)\n if (cached) {\n return cached\n }\n const idRelative = relative(srcRoot, script).replace(new RegExp(`${extname(script)}$`), '')\n const componentIdPosix = toPosixId(idRelative)\n state.componentIdMap.set(script, componentIdPosix)\n return componentIdPosix\n }\n\n const getComponentTag = (script: string) => {\n const cached = state.componentTagMap.get(script)\n if (cached) {\n return cached\n }\n const id = getComponentId(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 base = resolveComponentBase(componentId, importerDir, srcRoot)\n const script = base ? await resolveScriptFile(base) : undefined\n if (!script || components.has(script)) {\n return\n }\n\n const idRelative = relative(srcRoot, script).replace(new RegExp(`${extname(script)}$`), '')\n const componentIdPosix = toPosixId(idRelative)\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 state.moduleMeta.set(normalizePath(script), {\n kind: 'component',\n id: componentIdPosix,\n scriptPath: script,\n templatePath: template,\n stylePath: style,\n })\n\n components.set(script, { script, id: componentIdPosix })\n\n const componentJsonBasePath = `${script.replace(new RegExp(`${extname(script)}$`), '')}.json`\n const componentTags = 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\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 const appJsonBasePath = join(srcRoot, 'app.json')\n const appJsonPath = await resolveJsonPath(appJsonBasePath)\n if (appJsonPath) {\n const appJson = await readJsonFile(appJsonPath)\n\n if (appJson) {\n appComponentTags = await collectComponentTagsFromConfig({\n json: appJson,\n importerDir: srcRoot,\n jsonPath: appJsonPath,\n warn: reportWarning,\n resolveComponentScript,\n getComponentTag,\n collectComponent,\n onResolved: (tags) => {\n appComponentTags = tags\n },\n })\n }\n\n if (appJson?.pages && Array.isArray(appJson.pages)) {\n for (const page of appJson.pages) {\n if (typeof page === 'string') {\n await collectPage(page)\n }\n }\n }\n\n if (appJson?.subPackages && Array.isArray(appJson.subPackages)) {\n for (const pkg of appJson.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 const windowConfig = isRecord(appJson?.window) ? appJson.window : undefined\n appNavigationDefaults = pickNavigationConfig(windowConfig)\n }\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 }\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\n state.moduleMeta.set(normalizePath(script), {\n kind: 'page',\n id: toPosixId(pageId),\n scriptPath: script,\n templatePath: template,\n stylePath: style,\n })\n\n pages.set(script, {\n script,\n id: toPosixId(pageId),\n })\n\n const pageComponentTags = 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 : await collectComponentTagsFromJson({\n jsonBasePath: pageJsonBasePath,\n importerDir: dirname(script),\n warn: reportWarning,\n collectFromConfig: (json, importerDir, jsonPath, nextWarn) => collectComponentTagsFromConfig({\n json,\n importerDir,\n jsonPath,\n warn: nextWarn,\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\n if (!template) {\n return\n }\n\n if (pageJson) {\n state.pageNavigationMap.set(\n normalizePath(template),\n mergeNavigationConfig(appNavigationDefaults, pickNavigationConfig(pageJson)),\n )\n return\n }\n\n state.pageNavigationMap.set(normalizePath(template), { ...appNavigationDefaults })\n }\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 resolve(srcRoot, raw)\n}\n"],"mappings":";;;;;;;;;AAgBA,eAAsB,YAAY,EAAE,SAAS,MAAM,SAA6B;AAC9E,OAAM,WAAW,OAAO;AACxB,OAAM,kBAAkB,OAAO;AAC/B,OAAM,qBAAqB,OAAO;AAClC,OAAM,gBAAgB,OAAO;AAC7B,OAAM,gBAAgB,OAAO;AAC7B,OAAM,eAAe,OAAO;CAE5B,IAAI,wBAAwB,EAAE;CAC9B,IAAI,mBAA2C,EAAE;CAEjD,MAAM,wBAAQ,IAAI,KAAwB;CAC1C,MAAM,6BAAa,IAAI,KAA6B;CAEpD,MAAM,iBAAiB,YAAoB;AACzC,MAAI,MAAM;AACR,QAAK,QAAQ;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M,6BAA6B;GACjC,cAAc;GACd,aAAa,QAAQ,OAAO;GAC5B,MAAM;GACN,oBAAoB,MAAM,aAAa,UAAU,aAAa,+BAA+B;IAC3F;IACA;IACA;IACA,MAAM;IACN;IACA;IACA;IACD,CAAC;GACH,CAAC;AAEN,MAAI,UAAU;GACZ,MAAM,aAAa,mBAAmB,kBAAkB,kBAAkB;AAC1E,OAAI,OAAO,KAAK,WAAW,CAAC,SAAS,EACnC,OAAM,qBAAqB,IAAI,cAAc,SAAS,EAAE,WAAW;OAGnE,OAAM,qBAAqB,OAAO,cAAc,SAAS,CAAC;;AAI9D,MAAI,CAAC,SACH;AAGF,MAAI,UAAU;AACZ,SAAM,kBAAkB,IACtB,cAAc,SAAS,EACvB,sBAAsB,uBAAuB,qBAAqB,SAAS,CAAC,CAC7E;AACD;;AAGF,QAAM,kBAAkB,IAAI,cAAc,SAAS,EAAE,EAAE,GAAG,uBAAuB,CAAC;;;AAItF,SAAS,qBAAqB,KAAa,aAAqB,SAAiB;AAC/E,KAAI,CAAC,IACH;AAEF,KAAI,IAAI,WAAW,IAAI,CACrB,QAAO,QAAQ,aAAa,IAAI;AAElC,KAAI,IAAI,WAAW,IAAI,CACrB,QAAO,QAAQ,SAAS,IAAI,MAAM,EAAE,CAAC;AAEvC,QAAO,QAAQ,SAAS,IAAI"}
|
|
1
|
+
{"version":3,"file":"scan.mjs","names":[],"sources":["../../src/plugin/scan.ts"],"sourcesContent":["import type { ComponentEntry, PageEntry, ScanState, WarnFn } from './types'\nimport process from 'node:process'\n\nimport { dirname, extname, join, posix, relative, resolve } from 'pathe'\nimport { slugify } from '../shared/slugify'\nimport { isRecord, readJsonFile, resolveJsonPath, resolveScriptFile, resolveStyleFile, resolveTemplateFile } from './files'\nimport { mergeNavigationConfig, pickNavigationConfig } from './navigation'\nimport { normalizePath, toPosixId } from './path'\nimport { collectComponentTagsFromConfig, collectComponentTagsFromJson, mergeComponentTags } from './scanConfig'\n\ninterface ScanProjectOptions {\n srcRoot: string\n warn?: WarnFn\n state: ScanState\n}\n\nexport async function scanProject({ srcRoot, warn, state }: ScanProjectOptions) {\n state.moduleMeta.clear()\n state.pageNavigationMap.clear()\n state.templateComponentMap.clear()\n state.templatePathSet.clear()\n state.componentTagMap.clear()\n state.componentIdMap.clear()\n\n let appNavigationDefaults = {}\n let appComponentTags: Record<string, string> = {}\n\n const pages = new Map<string, PageEntry>()\n const components = new Map<string, ComponentEntry>()\n\n const reportWarning = (message: string) => {\n if (warn) {\n warn(message)\n return\n }\n if (typeof process !== 'undefined' && typeof process.emitWarning === 'function') {\n process.emitWarning(message)\n }\n }\n\n const appScript = await resolveScriptFile(join(srcRoot, 'app'))\n if (appScript) {\n state.moduleMeta.set(normalizePath(appScript), {\n kind: 'app',\n id: 'app',\n scriptPath: appScript,\n stylePath: await resolveStyleFile(appScript),\n })\n }\n\n const resolveComponentScript = async (raw: string, importerDir: string) => {\n const base = resolveComponentBase(raw, importerDir, srcRoot)\n if (!base) {\n return undefined\n }\n return resolveScriptFile(base)\n }\n\n const getComponentId = (script: string) => {\n const cached = state.componentIdMap.get(script)\n if (cached) {\n return cached\n }\n const idRelative = relative(srcRoot, script).replace(new RegExp(`${extname(script)}$`), '')\n const componentIdPosix = toPosixId(idRelative)\n state.componentIdMap.set(script, componentIdPosix)\n return componentIdPosix\n }\n\n const getComponentTag = (script: string) => {\n const cached = state.componentTagMap.get(script)\n if (cached) {\n return cached\n }\n const id = getComponentId(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 base = resolveComponentBase(componentId, importerDir, srcRoot)\n const script = base ? await resolveScriptFile(base) : undefined\n if (!script || components.has(script)) {\n return\n }\n\n const idRelative = relative(srcRoot, script).replace(new RegExp(`${extname(script)}$`), '')\n const componentIdPosix = toPosixId(idRelative)\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 state.moduleMeta.set(normalizePath(script), {\n kind: 'component',\n id: componentIdPosix,\n scriptPath: script,\n templatePath: template,\n stylePath: style,\n })\n\n components.set(script, { script, id: componentIdPosix })\n\n const componentJsonBasePath = `${script.replace(new RegExp(`${extname(script)}$`), '')}.json`\n const componentTags = 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\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 const appJsonBasePath = join(srcRoot, 'app.json')\n const appJsonPath = await resolveJsonPath(appJsonBasePath)\n if (appJsonPath) {\n const appJson = await readJsonFile(appJsonPath)\n\n if (appJson) {\n appComponentTags = await collectComponentTagsFromConfig({\n json: appJson,\n importerDir: srcRoot,\n jsonPath: appJsonPath,\n warn: reportWarning,\n resolveComponentScript,\n getComponentTag,\n collectComponent,\n onResolved: (tags) => {\n appComponentTags = tags\n },\n })\n }\n\n if (appJson?.pages && Array.isArray(appJson.pages)) {\n for (const page of appJson.pages) {\n if (typeof page === 'string') {\n await collectPage(page)\n }\n }\n }\n\n if (appJson?.subPackages && Array.isArray(appJson.subPackages)) {\n for (const pkg of appJson.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 const windowConfig = isRecord(appJson?.window) ? appJson.window : undefined\n appNavigationDefaults = pickNavigationConfig(windowConfig)\n }\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 }\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\n state.moduleMeta.set(normalizePath(script), {\n kind: 'page',\n id: toPosixId(pageId),\n scriptPath: script,\n templatePath: template,\n stylePath: style,\n })\n\n pages.set(script, {\n script,\n id: toPosixId(pageId),\n })\n\n const pageComponentTags = 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 : await collectComponentTagsFromJson({\n jsonBasePath: pageJsonBasePath,\n importerDir: dirname(script),\n warn: reportWarning,\n collectFromConfig: (json, importerDir, jsonPath, nextWarn) => collectComponentTagsFromConfig({\n json,\n importerDir,\n jsonPath,\n warn: nextWarn,\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\n if (!template) {\n return\n }\n\n if (pageJson) {\n state.pageNavigationMap.set(\n normalizePath(template),\n mergeNavigationConfig(appNavigationDefaults, pickNavigationConfig(pageJson)),\n )\n return\n }\n\n state.pageNavigationMap.set(normalizePath(template), { ...appNavigationDefaults })\n }\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 resolve(srcRoot, raw)\n}\n"],"mappings":";;;;;;;;;AAgBA,eAAsB,YAAY,EAAE,SAAS,MAAM,SAA6B;AAC9E,OAAM,WAAW,OAAO;AACxB,OAAM,kBAAkB,OAAO;AAC/B,OAAM,qBAAqB,OAAO;AAClC,OAAM,gBAAgB,OAAO;AAC7B,OAAM,gBAAgB,OAAO;AAC7B,OAAM,eAAe,OAAO;CAE5B,IAAI,wBAAwB,EAAE;CAC9B,IAAI,mBAA2C,EAAE;CAEjD,MAAM,wBAAQ,IAAI,KAAwB;CAC1C,MAAM,6BAAa,IAAI,KAA6B;CAEpD,MAAM,iBAAiB,YAAoB;AACzC,MAAI,MAAM;AACR,QAAK,QAAQ;AACb;;AAEF,MAAI,OAAO,YAAY,eAAe,OAAO,QAAQ,gBAAgB,WACnE,SAAQ,YAAY,QAAQ;;CAIhC,MAAM,YAAY,MAAM,kBAAkB,KAAK,SAAS,MAAM,CAAC;AAC/D,KAAI,UACF,OAAM,WAAW,IAAI,cAAc,UAAU,EAAE;EAC7C,MAAM;EACN,IAAI;EACJ,YAAY;EACZ,WAAW,MAAM,iBAAiB,UAAU;EAC7C,CAAC;CAGJ,MAAM,yBAAyB,OAAO,KAAa,gBAAwB;EACzE,MAAM,OAAO,qBAAqB,KAAK,aAAa,QAAQ;AAC5D,MAAI,CAAC,KACH;AAEF,SAAO,kBAAkB,KAAK;;CAGhC,MAAM,kBAAkB,WAAmB;EACzC,MAAM,SAAS,MAAM,eAAe,IAAI,OAAO;AAC/C,MAAI,OACF,QAAO;EAGT,MAAM,mBAAmB,UADN,SAAS,SAAS,OAAO,CAAC,QAAQ,IAAI,OAAO,GAAG,QAAQ,OAAO,CAAC,GAAG,EAAE,GAC3C,CAAC;AAC9C,QAAM,eAA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AAEF,KAAI,IAAI,WAAW,IAAI,CACrB,QAAO,QAAQ,aAAa,IAAI;AAElC,KAAI,IAAI,WAAW,IAAI,CACrB,QAAO,QAAQ,SAAS,IAAI,MAAM,EAAE,CAAC;AAEvC,QAAO,QAAQ,SAAS,IAAI"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scanConfig.mjs","names":[],"sources":["../../src/plugin/scanConfig.ts"],"sourcesContent":["import type { WarnFn } from './types'\nimport { readJsonFile, resolveJsonPath } from './files'\n\ninterface CollectComponentTagsFromConfigOptions {\n json: Record<string, unknown>\n importerDir: string\n jsonPath: string\n warn: WarnFn\n resolveComponentScript: (raw: string, importerDir: string) => Promise<string | undefined>\n getComponentTag: (script: string) => string\n collectComponent: (componentId: string, importerDir: string) => Promise<void>\n onResolved?: (tags: Record<string, string>) => void\n}\n\nexport async function collectComponentTagsFromConfig({\n json,\n importerDir,\n jsonPath,\n warn,\n resolveComponentScript,\n getComponentTag,\n collectComponent,\n onResolved,\n}: CollectComponentTagsFromConfigOptions) {\n const usingComponents = json.usingComponents\n if (!usingComponents || typeof usingComponents !== 'object') {\n return {}\n }\n\n const tags: Record<string, string> = {}\n const resolved: Array<{ rawValue: string }> = []\n\n for (const [rawKey, rawValue] of Object.entries(usingComponents)) {\n if (typeof rawValue !== 'string') {\n continue\n }\n const key = normalizeComponentKey(rawKey)\n if (!key) {\n continue\n }\n const script = await resolveComponentScript(rawValue, importerDir)\n if (!script) {\n warn(`[@weapp-vite/web] usingComponents entry \"${rawKey}\" not found: ${rawValue} (${jsonPath})`)\n continue\n }\n const tag = getComponentTag(script)\n tags[key] = tag\n resolved.push({ rawValue })\n }\n\n onResolved?.(tags)\n for (const entry of resolved) {\n await collectComponent(entry.rawValue, importerDir)\n }\n\n return tags\n}\n\ninterface CollectComponentTagsFromJsonOptions {\n jsonBasePath: string\n importerDir: string\n warn: WarnFn\n collectFromConfig: (json: Record<string, unknown>, importerDir: string, jsonPath: string, warn: WarnFn) => Promise<Record<string, string>>\n}\n\nexport async function collectComponentTagsFromJson({\n jsonBasePath,\n importerDir,\n warn,\n collectFromConfig,\n}: CollectComponentTagsFromJsonOptions) {\n const resolvedPath = await resolveJsonPath(jsonBasePath)\n if (!resolvedPath) {\n return {}\n }\n const json = await readJsonFile(resolvedPath)\n if (!json) {\n return {}\n }\n return collectFromConfig(json, importerDir, resolvedPath, warn)\n}\n\nexport function mergeComponentTags(base: Record<string, string>, overrides: Record<string, string>) {\n if (!Object.keys(base).length && !Object.keys(overrides).length) {\n return {}\n }\n return {\n ...base,\n ...overrides,\n }\n}\n\nfunction normalizeComponentKey(raw: string) {\n return raw.trim().toLowerCase()\n}\n"],"mappings":";;;AAcA,eAAsB,+BAA+B,EACnD,MACA,aACA,UACA,MACA,wBACA,iBACA,kBACA,cACwC;CACxC,MAAM,kBAAkB,KAAK;AAC7B,KAAI,CAAC,mBAAmB,OAAO,oBAAoB,SACjD,QAAO,EAAE;CAGX,MAAM,OAA+B,EAAE;CACvC,MAAM,WAAwC,EAAE;AAEhD,MAAK,MAAM,CAAC,QAAQ,aAAa,OAAO,QAAQ,gBAAgB,EAAE;AAChE,MAAI,OAAO,aAAa,SACtB;EAEF,MAAM,MAAM,sBAAsB,OAAO;AACzC,MAAI,CAAC,IACH;EAEF,MAAM,SAAS,MAAM,uBAAuB,UAAU,YAAY;AAClE,MAAI,CAAC,QAAQ;AACX,QAAK,4CAA4C,OAAO,eAAe,SAAS,IAAI,SAAS,GAAG;AAChG;;AAGF,OAAK,OADO,gBAAgB,
|
|
1
|
+
{"version":3,"file":"scanConfig.mjs","names":[],"sources":["../../src/plugin/scanConfig.ts"],"sourcesContent":["import type { WarnFn } from './types'\nimport { readJsonFile, resolveJsonPath } from './files'\n\ninterface CollectComponentTagsFromConfigOptions {\n json: Record<string, unknown>\n importerDir: string\n jsonPath: string\n warn: WarnFn\n resolveComponentScript: (raw: string, importerDir: string) => Promise<string | undefined>\n getComponentTag: (script: string) => string\n collectComponent: (componentId: string, importerDir: string) => Promise<void>\n onResolved?: (tags: Record<string, string>) => void\n}\n\nexport async function collectComponentTagsFromConfig({\n json,\n importerDir,\n jsonPath,\n warn,\n resolveComponentScript,\n getComponentTag,\n collectComponent,\n onResolved,\n}: CollectComponentTagsFromConfigOptions) {\n const usingComponents = json.usingComponents\n if (!usingComponents || typeof usingComponents !== 'object') {\n return {}\n }\n\n const tags: Record<string, string> = {}\n const resolved: Array<{ rawValue: string }> = []\n\n for (const [rawKey, rawValue] of Object.entries(usingComponents)) {\n if (typeof rawValue !== 'string') {\n continue\n }\n const key = normalizeComponentKey(rawKey)\n if (!key) {\n continue\n }\n const script = await resolveComponentScript(rawValue, importerDir)\n if (!script) {\n warn(`[@weapp-vite/web] usingComponents entry \"${rawKey}\" not found: ${rawValue} (${jsonPath})`)\n continue\n }\n const tag = getComponentTag(script)\n tags[key] = tag\n resolved.push({ rawValue })\n }\n\n onResolved?.(tags)\n for (const entry of resolved) {\n await collectComponent(entry.rawValue, importerDir)\n }\n\n return tags\n}\n\ninterface CollectComponentTagsFromJsonOptions {\n jsonBasePath: string\n importerDir: string\n warn: WarnFn\n collectFromConfig: (json: Record<string, unknown>, importerDir: string, jsonPath: string, warn: WarnFn) => Promise<Record<string, string>>\n}\n\nexport async function collectComponentTagsFromJson({\n jsonBasePath,\n importerDir,\n warn,\n collectFromConfig,\n}: CollectComponentTagsFromJsonOptions) {\n const resolvedPath = await resolveJsonPath(jsonBasePath)\n if (!resolvedPath) {\n return {}\n }\n const json = await readJsonFile(resolvedPath)\n if (!json) {\n return {}\n }\n return collectFromConfig(json, importerDir, resolvedPath, warn)\n}\n\nexport function mergeComponentTags(base: Record<string, string>, overrides: Record<string, string>) {\n if (!Object.keys(base).length && !Object.keys(overrides).length) {\n return {}\n }\n return {\n ...base,\n ...overrides,\n }\n}\n\nfunction normalizeComponentKey(raw: string) {\n return raw.trim().toLowerCase()\n}\n"],"mappings":";;;AAcA,eAAsB,+BAA+B,EACnD,MACA,aACA,UACA,MACA,wBACA,iBACA,kBACA,cACwC;CACxC,MAAM,kBAAkB,KAAK;AAC7B,KAAI,CAAC,mBAAmB,OAAO,oBAAoB,SACjD,QAAO,EAAE;CAGX,MAAM,OAA+B,EAAE;CACvC,MAAM,WAAwC,EAAE;AAEhD,MAAK,MAAM,CAAC,QAAQ,aAAa,OAAO,QAAQ,gBAAgB,EAAE;AAChE,MAAI,OAAO,aAAa,SACtB;EAEF,MAAM,MAAM,sBAAsB,OAAO;AACzC,MAAI,CAAC,IACH;EAEF,MAAM,SAAS,MAAM,uBAAuB,UAAU,YAAY;AAClE,MAAI,CAAC,QAAQ;AACX,QAAK,4CAA4C,OAAO,eAAe,SAAS,IAAI,SAAS,GAAG;AAChG;;AAGF,OAAK,OADO,gBAAgB,OACb;AACf,WAAS,KAAK,EAAE,UAAU,CAAC;;AAG7B,cAAa,KAAK;AAClB,MAAK,MAAM,SAAS,SAClB,OAAM,iBAAiB,MAAM,UAAU,YAAY;AAGrD,QAAO;;AAUT,eAAsB,6BAA6B,EACjD,cACA,aACA,MACA,qBACsC;CACtC,MAAM,eAAe,MAAM,gBAAgB,aAAa;AACxD,KAAI,CAAC,aACH,QAAO,EAAE;CAEX,MAAM,OAAO,MAAM,aAAa,aAAa;AAC7C,KAAI,CAAC,KACH,QAAO,EAAE;AAEX,QAAO,kBAAkB,MAAM,aAAa,cAAc,KAAK;;AAGjE,SAAgB,mBAAmB,MAA8B,WAAmC;AAClG,KAAI,CAAC,OAAO,KAAK,KAAK,CAAC,UAAU,CAAC,OAAO,KAAK,UAAU,CAAC,OACvD,QAAO,EAAE;AAEX,QAAO;EACL,GAAG;EACH,GAAG;EACJ;;AAGH,SAAS,sBAAsB,KAAa;AAC1C,QAAO,IAAI,MAAM,CAAC,aAAa"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.mjs","names":[],"sources":["../../../src/runtime/button/helpers.ts"],"sourcesContent":["const DEFAULT_HOVER_CLASS = 'button-hover'\n\nexport const DEFAULT_HOVER_START = 20\nexport const DEFAULT_HOVER_STAY = 70\n\nexport function toBoolean(value: string | null) {\n if (value === null) {\n return false\n }\n const normalized = value.trim().toLowerCase()\n if (normalized === '' || normalized === 'true') {\n return true\n }\n return normalized !== 'false' && normalized !== '0'\n}\n\nexport function parseNumber(value: string | null, fallback: number) {\n if (value === null || value === '') {\n return fallback\n }\n const numeric = Number(value)\n return Number.isFinite(numeric) ? numeric : fallback\n}\n\nexport function isDisabled(element: HTMLElement) {\n return toBoolean(element.getAttribute('disabled')) || toBoolean(element.getAttribute('loading'))\n}\n\nexport function normalizeType(value: string | null) {\n if (!value) {\n return 'default'\n }\n const normalized = value.toLowerCase()\n if (normalized === 'primary' || normalized === 'warn') {\n return normalized\n }\n return 'default'\n}\n\nexport function getHoverClass(element: HTMLElement) {\n const hoverClass = element.getAttribute('hover-class')\n if (!hoverClass) {\n return DEFAULT_HOVER_CLASS\n }\n if (hoverClass === 'none') {\n return ''\n }\n return hoverClass\n}\n\nexport function isInternalNode(node: Node) {\n return node instanceof HTMLElement && node.dataset?.weappInternal === 'true'\n}\n\nexport function collectFormValues(form: HTMLFormElement) {\n const values: Record<string, any> = {}\n\n const appendValue = (name: string, value: any, multiple = false) => {\n if (multiple) {\n if (!Array.isArray(values[name])) {\n values[name] = values[name] === undefined ? [] : [values[name]]\n }\n values[name].push(value)\n return\n }\n values[name] = value\n }\n\n const formElements = Array.from(form.elements ?? [])\n for (const element of formElements) {\n if (!(element instanceof HTMLElement)) {\n continue\n }\n const name = element.getAttribute('name')?.trim()\n if (!name) {\n continue\n }\n const disabled = 'disabled' in element ? (element as any).disabled : toBoolean(element.getAttribute('disabled'))\n if (disabled) {\n continue\n }\n if (element instanceof HTMLInputElement) {\n const type = element.type?.toLowerCase()\n if (type === 'checkbox') {\n if (element.checked) {\n appendValue(name, element.value, true)\n }\n continue\n }\n if (type === 'radio') {\n if (element.checked) {\n appendValue(name, element.value)\n }\n continue\n }\n appendValue(name, element.value)\n continue\n }\n if (element instanceof HTMLTextAreaElement || element instanceof HTMLSelectElement) {\n appendValue(name, (element as HTMLTextAreaElement | HTMLSelectElement).value)\n continue\n }\n }\n\n const customControls = form.querySelectorAll('switch, checkbox, radio, picker, slider, weapp-switch, weapp-checkbox, weapp-radio, weapp-picker, weapp-slider')\n for (const element of Array.from(customControls)) {\n const name = element.getAttribute('name')?.trim()\n if (!name) {\n continue\n }\n const disabled = toBoolean(element.getAttribute('disabled'))\n if (disabled) {\n continue\n }\n const tag = element.tagName.toLowerCase()\n const rawValue = (element as any).value ?? element.getAttribute('value')\n if (tag.includes('checkbox')) {\n const checked = (element as any).checked ?? toBoolean(element.getAttribute('checked'))\n if (checked) {\n appendValue(name, rawValue ?? true, true)\n }\n continue\n }\n if (tag.includes('radio')) {\n const checked = (element as any).checked ?? toBoolean(element.getAttribute('checked'))\n if (checked) {\n appendValue(name, rawValue ?? true)\n }\n continue\n }\n if (tag.includes('switch')) {\n const checked = (element as any).checked ?? toBoolean(element.getAttribute('checked'))\n appendValue(name, checked)\n continue\n }\n appendValue(name, rawValue ?? '')\n }\n\n return values\n}\n"],"mappings":";AAAA,MAAM,sBAAsB;AAK5B,SAAgB,UAAU,OAAsB;AAC9C,KAAI,UAAU,KACZ,QAAO;CAET,MAAM,aAAa,MAAM,MAAM,CAAC,aAAa;AAC7C,KAAI,eAAe,MAAM,eAAe,OACtC,QAAO;AAET,QAAO,eAAe,WAAW,eAAe;;AAGlD,SAAgB,YAAY,OAAsB,UAAkB;AAClE,KAAI,UAAU,QAAQ,UAAU,GAC9B,QAAO;CAET,MAAM,UAAU,OAAO,MAAM;AAC7B,QAAO,OAAO,SAAS,QAAQ,GAAG,UAAU;;AAG9C,SAAgB,WAAW,SAAsB;AAC/C,QAAO,UAAU,QAAQ,aAAa,WAAW,CAAC,IAAI,UAAU,QAAQ,aAAa,UAAU,CAAC;;AAGlG,SAAgB,cAAc,OAAsB;AAClD,KAAI,CAAC,MACH,QAAO;CAET,MAAM,aAAa,M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C9J,MAAK,MAAM,WAAW,MAAM,KAAK,eAAe,EAAE;EAChD,MAAM,OAAO,QAAQ,aAAa,OAAO,EAAE,MAAM;AACjD,MAAI,CAAC,KACH;AAGF,MADiB,UAAU,QAAQ,aAAa,WAAW,
|
|
1
|
+
{"version":3,"file":"helpers.mjs","names":[],"sources":["../../../src/runtime/button/helpers.ts"],"sourcesContent":["const DEFAULT_HOVER_CLASS = 'button-hover'\n\nexport const DEFAULT_HOVER_START = 20\nexport const DEFAULT_HOVER_STAY = 70\n\nexport function toBoolean(value: string | null) {\n if (value === null) {\n return false\n }\n const normalized = value.trim().toLowerCase()\n if (normalized === '' || normalized === 'true') {\n return true\n }\n return normalized !== 'false' && normalized !== '0'\n}\n\nexport function parseNumber(value: string | null, fallback: number) {\n if (value === null || value === '') {\n return fallback\n }\n const numeric = Number(value)\n return Number.isFinite(numeric) ? numeric : fallback\n}\n\nexport function isDisabled(element: HTMLElement) {\n return toBoolean(element.getAttribute('disabled')) || toBoolean(element.getAttribute('loading'))\n}\n\nexport function normalizeType(value: string | null) {\n if (!value) {\n return 'default'\n }\n const normalized = value.toLowerCase()\n if (normalized === 'primary' || normalized === 'warn') {\n return normalized\n }\n return 'default'\n}\n\nexport function getHoverClass(element: HTMLElement) {\n const hoverClass = element.getAttribute('hover-class')\n if (!hoverClass) {\n return DEFAULT_HOVER_CLASS\n }\n if (hoverClass === 'none') {\n return ''\n }\n return hoverClass\n}\n\nexport function isInternalNode(node: Node) {\n return node instanceof HTMLElement && node.dataset?.weappInternal === 'true'\n}\n\nexport function collectFormValues(form: HTMLFormElement) {\n const values: Record<string, any> = {}\n\n const appendValue = (name: string, value: any, multiple = false) => {\n if (multiple) {\n if (!Array.isArray(values[name])) {\n values[name] = values[name] === undefined ? [] : [values[name]]\n }\n values[name].push(value)\n return\n }\n values[name] = value\n }\n\n const formElements = Array.from(form.elements ?? [])\n for (const element of formElements) {\n if (!(element instanceof HTMLElement)) {\n continue\n }\n const name = element.getAttribute('name')?.trim()\n if (!name) {\n continue\n }\n const disabled = 'disabled' in element ? (element as any).disabled : toBoolean(element.getAttribute('disabled'))\n if (disabled) {\n continue\n }\n if (element instanceof HTMLInputElement) {\n const type = element.type?.toLowerCase()\n if (type === 'checkbox') {\n if (element.checked) {\n appendValue(name, element.value, true)\n }\n continue\n }\n if (type === 'radio') {\n if (element.checked) {\n appendValue(name, element.value)\n }\n continue\n }\n appendValue(name, element.value)\n continue\n }\n if (element instanceof HTMLTextAreaElement || element instanceof HTMLSelectElement) {\n appendValue(name, (element as HTMLTextAreaElement | HTMLSelectElement).value)\n continue\n }\n }\n\n const customControls = form.querySelectorAll('switch, checkbox, radio, picker, slider, weapp-switch, weapp-checkbox, weapp-radio, weapp-picker, weapp-slider')\n for (const element of Array.from(customControls)) {\n const name = element.getAttribute('name')?.trim()\n if (!name) {\n continue\n }\n const disabled = toBoolean(element.getAttribute('disabled'))\n if (disabled) {\n continue\n }\n const tag = element.tagName.toLowerCase()\n const rawValue = (element as any).value ?? element.getAttribute('value')\n if (tag.includes('checkbox')) {\n const checked = (element as any).checked ?? toBoolean(element.getAttribute('checked'))\n if (checked) {\n appendValue(name, rawValue ?? true, true)\n }\n continue\n }\n if (tag.includes('radio')) {\n const checked = (element as any).checked ?? toBoolean(element.getAttribute('checked'))\n if (checked) {\n appendValue(name, rawValue ?? true)\n }\n continue\n }\n if (tag.includes('switch')) {\n const checked = (element as any).checked ?? toBoolean(element.getAttribute('checked'))\n appendValue(name, checked)\n continue\n }\n appendValue(name, rawValue ?? '')\n }\n\n return values\n}\n"],"mappings":";AAAA,MAAM,sBAAsB;AAK5B,SAAgB,UAAU,OAAsB;AAC9C,KAAI,UAAU,KACZ,QAAO;CAET,MAAM,aAAa,MAAM,MAAM,CAAC,aAAa;AAC7C,KAAI,eAAe,MAAM,eAAe,OACtC,QAAO;AAET,QAAO,eAAe,WAAW,eAAe;;AAGlD,SAAgB,YAAY,OAAsB,UAAkB;AAClE,KAAI,UAAU,QAAQ,UAAU,G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OAAO,KAAK;AAExC;;AAEF,OAAI,SAAS,SAAS;AACpB,QAAI,QAAQ,QACV,aAAY,MAAM,QAAQ,MAAM;AAElC;;AAEF,eAAY,MAAM,QAAQ,MAAM;AAChC;;AAEF,MAAI,mBAAmB,uBAAuB,mBAAmB,mBAAmB;AAClF,eAAY,MAAO,QAAoD,MAAM;AAC7E;;;CAIJ,MAAM,iBAAiB,KAAK,iBAAiB,iHAAiH;AAC9J,MAAK,MAAM,WAAW,MAAM,KAAK,eAAe,EAAE;EAChD,MAAM,OAAO,QAAQ,aAAa,OAAO,EAAE,MAAM;AACjD,MAAI,CAAC,KACH;AAGF,MADiB,UAAU,QAAQ,aAAa,WAAW,CAC/C,CACV;EAEF,MAAM,MAAM,QAAQ,QAAQ,aAAa;EACzC,MAAM,WAAY,QAAgB,SAAS,QAAQ,aAAa,QAAQ;AACxE,MAAI,IAAI,SAAS,WAAW,EAAE;AAE5B,OADiB,QAAgB,WAAW,UAAU,QAAQ,aAAa,UAAU,CAAC,CAEpF,aAAY,MAAM,YAAY,MAAM,KAAK;AAE3C;;AAEF,MAAI,IAAI,SAAS,QAAQ,EAAE;AAEzB,OADiB,QAAgB,WAAW,UAAU,QAAQ,aAAa,UAAU,CAAC,CAEpF,aAAY,MAAM,YAAY,KAAK;AAErC;;AAEF,MAAI,IAAI,SAAS,SAAS,EAAE;AAE1B,eAAY,MADK,QAAgB,WAAW,UAAU,QAAQ,aAAa,UAAU,CAAC,CAC5D;AAC1B;;AAEF,cAAY,MAAM,YAAY,GAAG;;AAGnC,QAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["#ensureStructure","#applyState","#bindEvents","#clearHoverTimers","#observer","#button","#content","#text","#loading","#handleClickCapture","#handleClick","#handlePressStart","#handlePressEnd","#lastTouchTime","#hoverTimer","#hoverRemoveTimer"],"sources":["../../../src/runtime/button/index.ts"],"sourcesContent":["import {\n collectFormValues,\n DEFAULT_HOVER_START,\n DEFAULT_HOVER_STAY,\n getHoverClass,\n isDisabled,\n isInternalNode,\n normalizeType,\n parseNumber,\n toBoolean,\n} from './helpers'\nimport { ensureButtonStyle } from './style'\n\ninterface ButtonFormConfig {\n preventDefault?: boolean\n}\n\nconst DEFAULT_FORM_CONFIG: Required<ButtonFormConfig> = {\n preventDefault: true,\n}\n\nconst NAV_BUTTON_TAG = 'weapp-button'\nconst BaseElement = (globalThis.HTMLElement ?? class {}) as typeof HTMLElement\n\nlet formConfig: Required<ButtonFormConfig> = { ...DEFAULT_FORM_CONFIG }\n\nclass WeappButton extends BaseElement {\n static observedAttributes = [\n 'type',\n 'plain',\n 'size',\n 'loading',\n 'disabled',\n 'hover-class',\n 'hover-start-time',\n 'hover-stay-time',\n 'form-type',\n 'open-type',\n ]\n\n #button?: HTMLButtonElement\n #content?: HTMLSpanElement\n #text?: HTMLSpanElement\n #loading?: HTMLSpanElement\n #hoverTimer?: ReturnType<typeof globalThis.setTimeout>\n #hoverRemoveTimer?: ReturnType<typeof globalThis.setTimeout>\n #lastTouchTime = 0\n #observer?: MutationObserver\n\n connectedCallback() {\n const root = this.getRootNode()\n if (root instanceof ShadowRoot) {\n ensureButtonStyle(root)\n }\n else {\n ensureButtonStyle()\n }\n this.#ensureStructure()\n this.#applyState()\n this.#bindEvents()\n }\n\n disconnectedCallback() {\n this.#clearHoverTimers()\n this.#observer?.disconnect()\n this.#observer = undefined\n }\n\n attributeChangedCallback() {\n this.#applyState()\n }\n\n #ensureStructure() {\n if (this.#button) {\n return\n }\n const button = document.createElement('button')\n button.type = 'button'\n button.className = 'weapp-btn'\n button.dataset.weappInternal = 'true'\n const content = document.createElement('span')\n content.className = 'weapp-btn__content'\n content.dataset.weappInternal = 'true'\n const loading = document.createElement('span')\n loading.className = 'weapp-btn__loading'\n loading.dataset.weappInternal = 'true'\n loading.setAttribute('hidden', '')\n const text = document.createElement('span')\n text.className = 'weapp-btn__text'\n text.dataset.weappInternal = 'true'\n content.append(loading, text)\n button.append(content)\n\n const existing = [...this.childNodes].filter(node => !isInternalNode(node))\n for (const node of existing) {\n text.appendChild(node)\n }\n this.appendChild(button)\n\n this.#button = button\n this.#content = content\n this.#text = text\n this.#loading = loading\n\n if (typeof MutationObserver !== 'undefined') {\n this.#observer = new MutationObserver((records) => {\n if (!this.#text) {\n return\n }\n for (const record of records) {\n for (const node of [...record.addedNodes]) {\n if (isInternalNode(node)) {\n continue\n }\n if (node === this.#button) {\n continue\n }\n this.#text.appendChild(node)\n }\n }\n })\n this.#observer.observe(this, { childList: true })\n }\n }\n\n #applyState() {\n if (!this.#button || !this.#loading) {\n return\n }\n const type = normalizeType(this.getAttribute('type'))\n const plain = toBoolean(this.getAttribute('plain'))\n const size = (this.getAttribute('size') ?? 'default').toLowerCase()\n const loading = toBoolean(this.getAttribute('loading'))\n const disabled = toBoolean(this.getAttribute('disabled'))\n const openType = this.getAttribute('open-type')\n\n this.classList.toggle('weapp-btn--primary', type === 'primary')\n this.classList.toggle('weapp-btn--warn', type === 'warn')\n this.classList.toggle('weapp-btn--default', type === 'default')\n this.classList.toggle('weapp-btn--plain', plain)\n this.classList.toggle('weapp-btn--mini', size === 'mini')\n this.classList.toggle('weapp-btn--loading', loading)\n this.classList.toggle('weapp-btn--disabled', disabled)\n\n if (openType) {\n const openTypeClass = `weapp-btn--open-type-${openType}`\n for (const className of [...this.classList]) {\n if (className.startsWith('weapp-btn--open-type-') && className !== openTypeClass) {\n this.classList.remove(className)\n }\n }\n this.classList.add(openTypeClass)\n }\n else {\n for (const className of [...this.classList]) {\n if (className.startsWith('weapp-btn--open-type-')) {\n this.classList.remove(className)\n }\n }\n }\n\n const locked = disabled || loading\n this.#button.disabled = locked\n if (locked) {\n this.#button.setAttribute('aria-disabled', 'true')\n }\n else {\n this.#button.removeAttribute('aria-disabled')\n }\n this.#loading.toggleAttribute('hidden', !loading)\n }\n\n #bindEvents() {\n if ((this as any).__weappButtonBound) {\n return\n }\n ;(this as any).__weappButtonBound = true\n this.addEventListener('click', this.#handleClickCapture, true)\n this.addEventListener('click', this.#handleClick)\n this.addEventListener('touchstart', this.#handlePressStart, { passive: true })\n this.addEventListener('mousedown', this.#handlePressStart)\n this.addEventListener('touchend', this.#handlePressEnd)\n this.addEventListener('touchcancel', this.#handlePressEnd)\n this.addEventListener('mouseup', this.#handlePressEnd)\n this.addEventListener('mouseleave', this.#handlePressEnd)\n }\n\n #handleClickCapture = (event: Event) => {\n if (isDisabled(this)) {\n event.preventDefault()\n event.stopImmediatePropagation()\n }\n }\n\n #handleClick = (event: Event) => {\n if (isDisabled(this)) {\n return\n }\n const formType = this.getAttribute('form-type')\n if (!formType) {\n return\n }\n const form = this.closest('form') as HTMLFormElement | null\n if (!form) {\n return\n }\n if (formType === 'submit') {\n const detail = { value: collectFormValues(form) }\n const submitEvent = new CustomEvent('submit', {\n detail,\n bubbles: true,\n cancelable: true,\n })\n const shouldSubmit = form.dispatchEvent(submitEvent)\n if (shouldSubmit && !formConfig.preventDefault) {\n form.submit()\n }\n event.preventDefault()\n return\n }\n if (formType === 'reset') {\n form.reset()\n event.preventDefault()\n }\n }\n\n #handlePressStart = (event: Event) => {\n if (isDisabled(this)) {\n return\n }\n const hoverClass = getHoverClass(this)\n if (!hoverClass) {\n return\n }\n if (event.type === 'touchstart') {\n this.#lastTouchTime = Date.now()\n }\n if (event.type === 'mousedown' && Date.now() - this.#lastTouchTime < 400) {\n return\n }\n const startTime = parseNumber(this.getAttribute('hover-start-time'), DEFAULT_HOVER_START)\n this.#clearHoverTimers()\n this.#hoverTimer = globalThis.setTimeout(() => {\n this.classList.add(hoverClass)\n }, startTime)\n }\n\n #handlePressEnd = (event: Event) => {\n const hoverClass = getHoverClass(this)\n if (!hoverClass) {\n return\n }\n if (event.type === 'mouseup' && Date.now() - this.#lastTouchTime < 400) {\n return\n }\n const stayTime = parseNumber(this.getAttribute('hover-stay-time'), DEFAULT_HOVER_STAY)\n if (this.#hoverTimer) {\n clearTimeout(this.#hoverTimer)\n this.#hoverTimer = undefined\n }\n if (this.classList.contains(hoverClass)) {\n this.#hoverRemoveTimer = globalThis.setTimeout(() => {\n this.classList.remove(hoverClass)\n }, stayTime)\n }\n }\n\n #clearHoverTimers() {\n if (this.#hoverTimer) {\n clearTimeout(this.#hoverTimer)\n this.#hoverTimer = undefined\n }\n if (this.#hoverRemoveTimer) {\n clearTimeout(this.#hoverRemoveTimer)\n this.#hoverRemoveTimer = undefined\n }\n }\n}\n\nexport function ensureButtonDefined(): void {\n if (typeof customElements === 'undefined') {\n return\n }\n if (!customElements.get(NAV_BUTTON_TAG)) {\n customElements.define(NAV_BUTTON_TAG, WeappButton)\n }\n}\n\nexport function setButtonFormConfig(next: ButtonFormConfig): void {\n formConfig = {\n ...formConfig,\n ...next,\n }\n}\n\nexport type { ButtonFormConfig }\n"],"mappings":";;;;AAiBA,MAAM,sBAAkD,EACtD,gBAAgB,MACjB;AAED,MAAM,iBAAiB;AACvB,MAAM,cAAe,WAAW,eAAe,MAAM;AAErD,IAAI,aAAyC,EAAE,GAAG,qBAAqB;AAEvE,IAAM,cAAN,cAA0B,YAAY;CACpC,OAAO,qBAAqB;EAC1B;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD;CAED;CACA;CACA;CACA;CACA;CACA;CACA,iBAAiB;CACjB;CAEA,oBAAoB;EAClB,MAAM,OAAO,KAAK,aAAa;AAC/B,MAAI,gBAAgB,WAClB,mBAAkB,KAAK;MAGvB,oBAAmB;AAErB,QAAKA,iBAAkB;AACvB,QAAKC,YAAa;AAClB,QAAKC,YAAa;;CAGpB,uBAAuB;AACrB,QAAKC,kBAAmB;AACxB,QAAKC,UAAW,YAAY;AAC5B,QAAKA,WAAY;;CAGnB,2BAA2B;AACzB,QAAKH,YAAa;;CAGpB,mBAAmB;AACjB,MAAI,MAAKI,OACP;EAEF,MAAM,SAAS,SAAS,cAAc,SAAS;AAC/C,SAAO,OAAO;AACd,SAAO,YAAY;AACnB,SAAO,QAAQ,gBAAgB;EAC/B,MAAM,UAAU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a,MAAKA,WAAY;AAC9B,SAAKA,aAAc;;AAErB,MAAI,KAAK,UAAU,SAAS,WAAW,CACrC,OAAKC,mBAAoB,WAAW,iBAAiB;AACnD,QAAK,UAAU,OAAO,WAAW;KAChC,SAAS;;CAIhB,oBAAoB;AAClB,MAAI,MAAKD,YAAa;AACpB,gBAAa,MAAKA,WAAY;AAC9B,SAAKA,aAAc;;AAErB,MAAI,MAAKC,kBAAmB;AAC1B,gBAAa,MAAKA,iBAAkB;AACpC,SAAKA,mBAAoB;;;;AAK/B,SAAgB,sBAA4B;AAC1C,KAAI,OAAO,mBAAmB,YAC5B;AAEF,KAAI,CAAC,eAAe,IAAI,eAAe,CACrC,gBAAe,OAAO,gBAAgB,YAAY;;AAItD,SAAgB,oBAAoB,MAA8B;AAChE,cAAa;EACX,GAAG;EACH,GAAG;EACJ"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["#ensureStructure","#applyState","#bindEvents","#clearHoverTimers","#observer","#button","#content","#text","#loading","#handleClickCapture","#handleClick","#handlePressStart","#handlePressEnd","#lastTouchTime","#hoverTimer","#hoverRemoveTimer"],"sources":["../../../src/runtime/button/index.ts"],"sourcesContent":["import {\n collectFormValues,\n DEFAULT_HOVER_START,\n DEFAULT_HOVER_STAY,\n getHoverClass,\n isDisabled,\n isInternalNode,\n normalizeType,\n parseNumber,\n toBoolean,\n} from './helpers'\nimport { ensureButtonStyle } from './style'\n\ninterface ButtonFormConfig {\n preventDefault?: boolean\n}\n\nconst DEFAULT_FORM_CONFIG: Required<ButtonFormConfig> = {\n preventDefault: true,\n}\n\nconst NAV_BUTTON_TAG = 'weapp-button'\nconst BaseElement = (globalThis.HTMLElement ?? class {}) as typeof HTMLElement\n\nlet formConfig: Required<ButtonFormConfig> = { ...DEFAULT_FORM_CONFIG }\n\nclass WeappButton extends BaseElement {\n static observedAttributes = [\n 'type',\n 'plain',\n 'size',\n 'loading',\n 'disabled',\n 'hover-class',\n 'hover-start-time',\n 'hover-stay-time',\n 'form-type',\n 'open-type',\n ]\n\n #button?: HTMLButtonElement\n #content?: HTMLSpanElement\n #text?: HTMLSpanElement\n #loading?: HTMLSpanElement\n #hoverTimer?: ReturnType<typeof globalThis.setTimeout>\n #hoverRemoveTimer?: ReturnType<typeof globalThis.setTimeout>\n #lastTouchTime = 0\n #observer?: MutationObserver\n\n connectedCallback() {\n const root = this.getRootNode()\n if (root instanceof ShadowRoot) {\n ensureButtonStyle(root)\n }\n else {\n ensureButtonStyle()\n }\n this.#ensureStructure()\n this.#applyState()\n this.#bindEvents()\n }\n\n disconnectedCallback() {\n this.#clearHoverTimers()\n this.#observer?.disconnect()\n this.#observer = undefined\n }\n\n attributeChangedCallback() {\n this.#applyState()\n }\n\n #ensureStructure() {\n if (this.#button) {\n return\n }\n const button = document.createElement('button')\n button.type = 'button'\n button.className = 'weapp-btn'\n button.dataset.weappInternal = 'true'\n const content = document.createElement('span')\n content.className = 'weapp-btn__content'\n content.dataset.weappInternal = 'true'\n const loading = document.createElement('span')\n loading.className = 'weapp-btn__loading'\n loading.dataset.weappInternal = 'true'\n loading.setAttribute('hidden', '')\n const text = document.createElement('span')\n text.className = 'weapp-btn__text'\n text.dataset.weappInternal = 'true'\n content.append(loading, text)\n button.append(content)\n\n const existing = [...this.childNodes].filter(node => !isInternalNode(node))\n for (const node of existing) {\n text.appendChild(node)\n }\n this.appendChild(button)\n\n this.#button = button\n this.#content = content\n this.#text = text\n this.#loading = loading\n\n if (typeof MutationObserver !== 'undefined') {\n this.#observer = new MutationObserver((records) => {\n if (!this.#text) {\n return\n }\n for (const record of records) {\n for (const node of [...record.addedNodes]) {\n if (isInternalNode(node)) {\n continue\n }\n if (node === this.#button) {\n continue\n }\n this.#text.appendChild(node)\n }\n }\n })\n this.#observer.observe(this, { childList: true })\n }\n }\n\n #applyState() {\n if (!this.#button || !this.#loading) {\n return\n }\n const type = normalizeType(this.getAttribute('type'))\n const plain = toBoolean(this.getAttribute('plain'))\n const size = (this.getAttribute('size') ?? 'default').toLowerCase()\n const loading = toBoolean(this.getAttribute('loading'))\n const disabled = toBoolean(this.getAttribute('disabled'))\n const openType = this.getAttribute('open-type')\n\n this.classList.toggle('weapp-btn--primary', type === 'primary')\n this.classList.toggle('weapp-btn--warn', type === 'warn')\n this.classList.toggle('weapp-btn--default', type === 'default')\n this.classList.toggle('weapp-btn--plain', plain)\n this.classList.toggle('weapp-btn--mini', size === 'mini')\n this.classList.toggle('weapp-btn--loading', loading)\n this.classList.toggle('weapp-btn--disabled', disabled)\n\n if (openType) {\n const openTypeClass = `weapp-btn--open-type-${openType}`\n for (const className of [...this.classList]) {\n if (className.startsWith('weapp-btn--open-type-') && className !== openTypeClass) {\n this.classList.remove(className)\n }\n }\n this.classList.add(openTypeClass)\n }\n else {\n for (const className of [...this.classList]) {\n if (className.startsWith('weapp-btn--open-type-')) {\n this.classList.remove(className)\n }\n }\n }\n\n const locked = disabled || loading\n this.#button.disabled = locked\n if (locked) {\n this.#button.setAttribute('aria-disabled', 'true')\n }\n else {\n this.#button.removeAttribute('aria-disabled')\n }\n this.#loading.toggleAttribute('hidden', !loading)\n }\n\n #bindEvents() {\n if ((this as any).__weappButtonBound) {\n return\n }\n ;(this as any).__weappButtonBound = true\n this.addEventListener('click', this.#handleClickCapture, true)\n this.addEventListener('click', this.#handleClick)\n this.addEventListener('touchstart', this.#handlePressStart, { passive: true })\n this.addEventListener('mousedown', this.#handlePressStart)\n this.addEventListener('touchend', this.#handlePressEnd)\n this.addEventListener('touchcancel', this.#handlePressEnd)\n this.addEventListener('mouseup', this.#handlePressEnd)\n this.addEventListener('mouseleave', this.#handlePressEnd)\n }\n\n #handleClickCapture = (event: Event) => {\n if (isDisabled(this)) {\n event.preventDefault()\n event.stopImmediatePropagation()\n }\n }\n\n #handleClick = (event: Event) => {\n if (isDisabled(this)) {\n return\n }\n const formType = this.getAttribute('form-type')\n if (!formType) {\n return\n }\n const form = this.closest('form') as HTMLFormElement | null\n if (!form) {\n return\n }\n if (formType === 'submit') {\n const detail = { value: collectFormValues(form) }\n const submitEvent = new CustomEvent('submit', {\n detail,\n bubbles: true,\n cancelable: true,\n })\n const shouldSubmit = form.dispatchEvent(submitEvent)\n if (shouldSubmit && !formConfig.preventDefault) {\n form.submit()\n }\n event.preventDefault()\n return\n }\n if (formType === 'reset') {\n form.reset()\n event.preventDefault()\n }\n }\n\n #handlePressStart = (event: Event) => {\n if (isDisabled(this)) {\n return\n }\n const hoverClass = getHoverClass(this)\n if (!hoverClass) {\n return\n }\n if (event.type === 'touchstart') {\n this.#lastTouchTime = Date.now()\n }\n if (event.type === 'mousedown' && Date.now() - this.#lastTouchTime < 400) {\n return\n }\n const startTime = parseNumber(this.getAttribute('hover-start-time'), DEFAULT_HOVER_START)\n this.#clearHoverTimers()\n this.#hoverTimer = globalThis.setTimeout(() => {\n this.classList.add(hoverClass)\n }, startTime)\n }\n\n #handlePressEnd = (event: Event) => {\n const hoverClass = getHoverClass(this)\n if (!hoverClass) {\n return\n }\n if (event.type === 'mouseup' && Date.now() - this.#lastTouchTime < 400) {\n return\n }\n const stayTime = parseNumber(this.getAttribute('hover-stay-time'), DEFAULT_HOVER_STAY)\n if (this.#hoverTimer) {\n clearTimeout(this.#hoverTimer)\n this.#hoverTimer = undefined\n }\n if (this.classList.contains(hoverClass)) {\n this.#hoverRemoveTimer = globalThis.setTimeout(() => {\n this.classList.remove(hoverClass)\n }, stayTime)\n }\n }\n\n #clearHoverTimers() {\n if (this.#hoverTimer) {\n clearTimeout(this.#hoverTimer)\n this.#hoverTimer = undefined\n }\n if (this.#hoverRemoveTimer) {\n clearTimeout(this.#hoverRemoveTimer)\n this.#hoverRemoveTimer = undefined\n }\n }\n}\n\nexport function ensureButtonDefined(): void {\n if (typeof customElements === 'undefined') {\n return\n }\n if (!customElements.get(NAV_BUTTON_TAG)) {\n customElements.define(NAV_BUTTON_TAG, WeappButton)\n }\n}\n\nexport function setButtonFormConfig(next: ButtonFormConfig): void {\n formConfig = {\n ...formConfig,\n ...next,\n }\n}\n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