"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __esm = (fn, res) => function __init() { return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; }; var __commonJS = (cb, mod) => function __require() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // ../../node_modules/.pnpm/tsup@8.3.5_@swc+core@1.9.2_jiti@2.4.0_postcss@8.4.49_tsx@4.19.2_typescript@5.6.3_yaml@2.6.1/node_modules/tsup/assets/cjs_shims.js var init_cjs_shims = __esm({ "../../node_modules/.pnpm/tsup@8.3.5_@swc+core@1.9.2_jiti@2.4.0_postcss@8.4.49_tsx@4.19.2_typescript@5.6.3_yaml@2.6.1/node_modules/tsup/assets/cjs_shims.js"() { "use strict"; } }); // ../../node_modules/.pnpm/debounce@2.2.0/node_modules/debounce/index.js var require_debounce = __commonJS({ "../../node_modules/.pnpm/debounce@2.2.0/node_modules/debounce/index.js"(exports2, module2) { "use strict"; init_cjs_shims(); function debounce2(function_, wait = 100, options = {}) { if (typeof function_ !== "function") { throw new TypeError(`Expected the first parameter to be a function, got \`${typeof function_}\`.`); } if (wait < 0) { throw new RangeError("`wait` must not be negative."); } const { immediate } = typeof options === "boolean" ? { immediate: options } : options; let storedContext; let storedArguments; let timeoutId; let timestamp; let result; function run() { const callContext = storedContext; const callArguments = storedArguments; storedContext = void 0; storedArguments = void 0; result = function_.apply(callContext, callArguments); return result; } function later() { const last = Date.now() - timestamp; if (last < wait && last >= 0) { timeoutId = setTimeout(later, wait - last); } else { timeoutId = void 0; if (!immediate) { result = run(); } } } const debounced = function(...arguments_) { if (storedContext && this !== storedContext && Object.getPrototypeOf(this) === Object.getPrototypeOf(storedContext)) { throw new Error("Debounced method called with different contexts of the same prototype."); } storedContext = this; storedArguments = arguments_; timestamp = Date.now(); const callNow = immediate && !timeoutId; if (!timeoutId) { timeoutId = setTimeout(later, wait); } if (callNow) { result = run(); } return result; }; Object.defineProperty(debounced, "isPending", { get() { return timeoutId !== void 0; } }); debounced.clear = () => { if (!timeoutId) { return; } clearTimeout(timeoutId); timeoutId = void 0; }; debounced.flush = () => { if (!timeoutId) { return; } debounced.trigger(); }; debounced.trigger = () => { result = run(); debounced.clear(); }; return debounced; } module2.exports.debounce = debounce2; module2.exports = debounce2; } }); // src/index.ts var src_exports = {}; __export(src_exports, { CompilerContext: () => CompilerContext, createCompilerContext: () => createCompilerContext }); module.exports = __toCommonJS(src_exports); init_cjs_shims(); // src/context.ts init_cjs_shims(); var import_node_process = __toESM(require("process"), 1); var import_shared5 = require("@weapp-core/shared"); var import_del = require("del"); var import_fs_extra5 = __toESM(require("fs-extra"), 1); var import_local_pkg = require("local-pkg"); var import_pathe5 = __toESM(require("pathe"), 1); var import_vite2 = require("vite"); var import_vite_tsconfig_paths = __toESM(require("vite-tsconfig-paths"), 1); // src/debugger.ts init_cjs_shims(); var import_debug = __toESM(require("debug"), 1); function createDebugger(namespace) { const debug3 = (0, import_debug.default)(namespace); if (debug3.enabled) { return debug3; } } // src/defaults.ts init_cjs_shims(); var defaultExcluded = ["**/node_modules/**", "**/miniprogram_npm/**"]; function getOutputExtensions(_platform) { return { js: "js", json: "json", wxml: "wxml", wxss: "wxss", wxs: "wxs" }; } function getWeappViteConfig() { return { enhance: { wxml: true, wxs: true } }; } // src/logger.ts init_cjs_shims(); var import_logger = __toESM(require("@weapp-core/logger"), 1); var logger_default = import_logger.default; // src/plugins/index.ts init_cjs_shims(); var import_shared4 = require("@weapp-core/shared"); var import_debounce = __toESM(require_debounce(), 1); var import_fdir = require("fdir"); var import_fs_extra4 = __toESM(require("fs-extra"), 1); var import_magic_string2 = __toESM(require("magic-string"), 1); var import_pathe4 = __toESM(require("pathe"), 1); var import_vite = require("vite"); // src/constants.ts init_cjs_shims(); var jsExtensions = ["ts", "js"]; var configExtensions = [...jsExtensions.map((x) => `json.${x}`), "json"]; var supportedCssLangs = ["wxss", "scss", "less", "sass", "styl"]; // src/utils/index.ts init_cjs_shims(); // src/utils/file.ts init_cjs_shims(); var import_fs_extra = __toESM(require("fs-extra"), 1); var import_pathe = __toESM(require("pathe"), 1); function isJsOrTs(name) { if (typeof name === "string") { return jsExtensions.some((x) => name.endsWith(`.${x}`)); } return false; } function changeFileExtension(filePath, extension) { if (typeof filePath !== "string") { throw new TypeError(`Expected \`filePath\` to be a string, got \`${typeof filePath}\`.`); } if (typeof extension !== "string") { throw new TypeError(`Expected \`extension\` to be a string, got \`${typeof extension}\`.`); } if (filePath === "") { return ""; } extension = extension ? extension.startsWith(".") ? extension : `.${extension}` : ""; const basename = import_pathe.default.basename(filePath, import_pathe.default.extname(filePath)); return import_pathe.default.join(import_pathe.default.dirname(filePath), basename + extension); } async function findJsEntry(filepath) { for (const ext of jsExtensions) { const p = changeFileExtension(filepath, ext); if (await import_fs_extra.default.exists(p)) { return p; } } } async function findJsonEntry(filepath) { for (const ext of configExtensions) { const p = changeFileExtension(filepath, ext); if (await import_fs_extra.default.exists(p)) { return p; } } } function resolveGlobs(globs, subPackageMeta) { if (Array.isArray(globs)) { return globs; } else if (typeof globs === "function") { return globs(subPackageMeta); } return []; } // src/utils/json.ts init_cjs_shims(); var import_shared = require("@weapp-core/shared"); var import_bundle_require = require("bundle-require"); var import_comment_json = require("comment-json"); var import_fs_extra2 = __toESM(require("fs-extra"), 1); var import_pathe2 = __toESM(require("pathe"), 1); function parseCommentJson(json) { return (0, import_comment_json.parse)(json, void 0, true); } function jsonFileRemoveJsExtension(fileName) { return fileName.replace(/\.[jt]s$/, ""); } function createReadCommentJson(ctx) { return async function readCommentJson(filepath) { try { if (/\.json\.[jt]s$/.test(filepath)) { const { mod } = await (0, import_bundle_require.bundleRequire)({ filepath, cwd: ctx?.cwd, esbuildOptions: { define: ctx?.define } }); return typeof mod.default === "function" ? await mod.default(ctx) : mod.default; } else { return parseCommentJson(await import_fs_extra2.default.readFile(filepath, "utf8")); } } catch (error) { logger_default.error(`\u6B8B\u7834\u7684JSON\u6587\u4EF6: ${filepath}`); logger_default.error(error); } }; } function stringifyJson(value, replacer) { return (0, import_comment_json.stringify)(value, replacer, 2); } function matches(pattern, importee) { if (pattern instanceof RegExp) { return pattern.test(importee); } if (importee.length < pattern.length) { return false; } if (importee === pattern) { return true; } return importee.startsWith(pattern + "/"); } function getAliasEntries({ entries } = {}) { if (!entries) { return []; } if (Array.isArray(entries)) { return entries.map((entry) => { return { find: entry.find, replacement: entry.replacement }; }); } return Object.entries(entries).map(([key, value]) => { return { find: key, replacement: value }; }); } function resolveImportee(importee, entry, aliasEntries) { if (Array.isArray(aliasEntries)) { if (!entry.jsonPath) { return importee; } const matchedEntry = aliasEntries.find((x) => matches(x.find, importee)); if (!matchedEntry) { return importee; } const updatedId = importee.replace(matchedEntry.find, matchedEntry.replacement); return import_pathe2.default.relative(import_pathe2.default.dirname(entry.jsonPath), updatedId); } return importee; } function resolveJson(entry, aliasEntries) { if (entry.json) { const json = structuredClone(entry.json); if (entry.jsonPath && Array.isArray(aliasEntries)) { const usingComponents = (0, import_shared.get)(json, "usingComponents"); if ((0, import_shared.isObject)(usingComponents)) { for (const [key, importee] of Object.entries(usingComponents)) { const resolvedId = resolveImportee(importee, entry, aliasEntries); (0, import_shared.set)(json, `usingComponents.${key}`, resolvedId); } (0, import_shared.set)(json, "usingComponents", usingComponents); } if (entry.type === "app") { const fields = ["subPackages", "subpackages"]; for (const field of fields) { const subPackages = (0, import_shared.get)(json, field); if (Array.isArray(subPackages)) { for (const subPackage of subPackages) { if (subPackage.entry) { subPackage.entry = changeFileExtension(subPackage.entry, "js"); } } } } } } if (Reflect.has(json, "$schema")) { delete json.$schema; } return stringifyJson(json); } } // src/utils/projectConfig.ts init_cjs_shims(); var import_fs_extra3 = __toESM(require("fs-extra"), 1); var import_pathe3 = __toESM(require("pathe"), 1); async function getProjectConfig(root, options) { const baseJsonPath = import_pathe3.default.resolve(root, "project.config.json"); const privateJsonPath = import_pathe3.default.resolve(root, "project.private.config.json"); let baseJson = {}; let privateJson = {}; if (await import_fs_extra3.default.exists(baseJsonPath)) { try { baseJson = await import_fs_extra3.default.readJson(baseJsonPath) || {}; } catch { throw new Error(`\u89E3\u6790 json \u683C\u5F0F\u5931\u8D25, project.config.json \u4E3A\u975E\u6CD5\u7684 json \u683C\u5F0F`); } } else { throw new Error(`\u5728 ${root} \u76EE\u5F55\u4E0B\u627E\u4E0D\u5230 project.config.json`); } if (!options?.ignorePrivate) { if (await import_fs_extra3.default.exists(privateJsonPath)) { try { privateJson = await import_fs_extra3.default.readJson(privateJsonPath) || {}; } catch { throw new Error(`\u89E3\u6790 json \u683C\u5F0F\u5931\u8D25, project.private.config.json \u4E3A\u975E\u6CD5\u7684 json \u683C\u5F0F`); } } } return Object.assign({}, privateJson, baseJson); } // src/utils/regexp.ts init_cjs_shims(); function isRegexp(value) { return Object.prototype.toString.call(value) === "[object RegExp]"; } function regExpTest(arr = [], str) { if (Array.isArray(arr)) { for (const item of arr) { if (typeof item === "string") { if (str.includes(item)) { return true; } } else if (isRegexp(item)) { item.lastIndex = 0; if (item.test(str)) { return true; } } } return false; } throw new TypeError("paramater 'arr' should be a Array of Regexp | String !"); } // src/wxml/index.ts init_cjs_shims(); var import_htmlparser2 = require("htmlparser2"); var import_magic_string = __toESM(require("magic-string"), 1); // src/wxs/index.ts init_cjs_shims(); var import_core = __toESM(require("@babel/core"), 1); var import_types = __toESM(require("@babel/types"), 1); var import_shared3 = require("@weapp-core/shared"); // src/wxs/utils.ts init_cjs_shims(); var import_shared2 = require("@weapp-core/shared"); function normalizeWxsFilename(value) { return (0, import_shared2.addExtension)((0, import_shared2.removeExtensionDeep)(value), ".wxs"); } // src/wxs/index.ts function transformWxsCode(code, options) { const { filename } = (0, import_shared3.defu)(options, { filename: "wxs.ts" }); return import_core.default.transformSync(code, { presets: [ ["@babel/preset-env", { targets: { node: 0 } }], ["@babel/preset-typescript", {}] ], filename, plugins: [ { visitor: { Directive: { enter(p) { p.remove(); } }, CallExpression: { enter(p) { if (p.get("callee").isIdentifier({ name: "require" }) && p.get("arguments").length === 1) { const importee = p.get("arguments")[0]; if (importee.isStringLiteral()) { importee.node.value = normalizeWxsFilename(importee.node.value); } } } }, ExpressionStatement(p) { const expression = p.node.expression; if (expression.type === "CallExpression" && expression.callee.type === "MemberExpression" && import_types.default.isIdentifier(expression.callee.object) && expression.callee.object.name === "Object" && import_types.default.isIdentifier(expression.callee.property) && expression.callee.property.name === "defineProperty" && expression.arguments.length >= 2 && import_types.default.isIdentifier(expression.arguments[0]) && expression.arguments[0].name === "exports" && import_types.default.isStringLiteral(expression.arguments[1]) && expression.arguments[1].value === "__esModule") { p.remove(); } }, NewExpression: { enter(p) { if (p.get("callee").isIdentifier({ name: "RegExp" })) { p.replaceWith( import_types.default.callExpression(import_types.default.identifier("getRegExp"), p.get("arguments").map((x) => x.node)) ); } else if (p.get("callee").isIdentifier({ name: "Date" })) { p.replaceWith( import_types.default.callExpression(import_types.default.identifier("getDate"), p.get("arguments").map((x) => x.node)) ); } } }, RegExpLiteral: { enter(p) { const args = [import_types.default.stringLiteral(p.node.pattern)]; if (p.node.flags) { args.push(import_types.default.stringLiteral(p.node.flags)); } p.replaceWith( import_types.default.callExpression(import_types.default.identifier("getRegExp"), args) ); } }, MemberExpression: { enter(p) { if (p.get("object").isIdentifier({ name: "exports" })) { p.replaceWith( import_types.default.memberExpression( import_types.default.memberExpression(import_types.default.identifier("module"), import_types.default.identifier("exports")), p.get("property").node ) ); } } } } } ] }); } // src/wxml/index.ts var srcImportTagsMap = { // audio: ['src', 'poster'], // video: ['src', 'poster'], // image: ['src'], // https://developers.weixin.qq.com/miniprogram/dev/reference/wxs/01wxs-module.html wxs: ["src"] // https://developers.weixin.qq.com/miniprogram/dev/reference/wxml/import.html // import: ['src'], // include: ['src'], }; function processWxml(wxml) { const ms = new import_magic_string.default(wxml.toString()); const deps = []; let currentTagName = ""; let importAttrs; let attrs = {}; const parser = new import_htmlparser2.Parser({ onopentagname(name) { currentTagName = name; importAttrs = srcImportTagsMap[currentTagName]; }, onattribute(name, value, quote) { attrs[name] = value; if (importAttrs) { for (const attrName of importAttrs) { if (attrName === name) { deps.push({ name, value, quote, tagName: currentTagName, start: parser.startIndex, end: parser.endIndex, attrs }); if (currentTagName === "wxs" && name === "src") { if (/\.wxs.[jt]s$/.test(value)) { ms.update(parser.startIndex + 5, parser.endIndex - 1, normalizeWxsFilename(value)); } } } } } if (name.startsWith("@")) { const start = parser.startIndex; const end = parser.startIndex + name.length; const { dir, mods } = name.split(".").filter((x) => x).reduce((acc, cur, idx) => { if (idx === 0) { acc.dir = cur; } else { acc.mods[cur] = true; } return acc; }, { dir: "", mods: {} }); let rep; if (mods.catch && mods.capture) { rep = `capture-catch:${dir.slice(1)}`; } else if (mods.catch) { rep = `catch:${dir.slice(1)}`; } else if (mods.mut) { rep = `mut-bind:${dir.slice(1)}`; } else if (mods.capture) { rep = `capture-bind:${dir.slice(1)}`; } else { rep = `bind:${dir.slice(1)}`; } if (rep) { ms.update(start, end, rep); } } if (currentTagName === "wxs" && name === "lang" && jsExtensions.includes(value)) { ms.update(parser.startIndex, parser.endIndex, ""); } }, onclosetag() { currentTagName = ""; attrs = {}; importAttrs = void 0; }, ontext(data) { if (currentTagName === "wxs" && jsExtensions.includes(attrs.lang)) { const res = transformWxsCode(data); if (res && res.code) { ms.update(parser.startIndex, parser.endIndex, ` ${res.code}`); } } } }); parser.write( ms.original ); parser.end(); return { deps, code: ms.toString() }; } // src/plugins/parse.ts init_cjs_shims(); function parseRequest(id) { const [filename, rawQuery] = id.split(`?`, 2); const query = Object.fromEntries(new URLSearchParams(rawQuery)); if (Reflect.has(query, "wxss")) { query.wxss = true; } return { filename, query }; } function getCssRealPath(res) { if (res.query.wxss) { return changeFileExtension(res.filename, "wxss"); } return res.filename; } // src/plugins/index.ts var debug = createDebugger("weapp-vite:plugin"); var debouncedLoggerSuccess = (0, import_debounce.default)((message) => { return logger_default.success(message); }, 25); function vitePluginWeapp(ctx, subPackageMeta) { let configResolved; function relative(p) { return import_pathe4.default.relative(configResolved.root, p); } function transformAbsoluteToRelative(p) { if (import_pathe4.default.isAbsolute(p)) { return relative(p); } return p; } function getInputOption(entries2) { return entries2.reduce((acc, cur) => { acc[relative(cur)] = cur; return acc; }, {}); } let entriesSet; let entries; return [ { name: "weapp-vite:pre", enforce: "pre", // config->configResolved->|watching|options->buildStart // config(config, env) { // debug?.(config, env) // }, configResolved(config) { configResolved = config; if ((0, import_shared4.isObject)(configResolved.env)) { for (const [key, value] of Object.entries(configResolved.env)) { ctx.setDefineEnv(key, value); } } }, async options(options) { if (subPackageMeta) { entriesSet = subPackageMeta.entriesSet; entries = subPackageMeta.entries; } else { await ctx.scanAppEntry(); entriesSet = ctx.entriesSet; entries = ctx.entries; } const input = getInputOption([...entriesSet]); options.input = input; }, async buildEnd() { for (const entry of entriesSet) { const moduleInfo = this.getModuleInfo(entry); if (moduleInfo) { const stack = [moduleInfo.id]; const visitedModules = /* @__PURE__ */ new Set(); while (stack.length > 0) { const id = stack.pop(); if (id && !visitedModules.has(id)) { visitedModules.add(id); const info = this.getModuleInfo(id); if (info) { this.addWatchFile(info.id); stack.push(...info.importedIds); } } } } } debug?.("buildEnd start"); const watchFiles = this.getWatchFiles(); debug?.("watchFiles count: ", watchFiles.length); const { build: build2, weapp } = configResolved; const ignore = [ ...defaultExcluded, `${build2.outDir}/**` ]; if (!subPackageMeta) { for (const root of Object.keys(ctx.subPackageMeta)) { ignore.push(import_pathe4.default.join(root, "**")); } } ignore.push(...resolveGlobs(weapp?.copy?.exclude)); const targetDir = subPackageMeta ? import_pathe4.default.join(ctx.srcRoot, subPackageMeta.subPackage.root) : ctx.srcRoot; const assetGlobs = [ // 支持 html "**/*.{wxml,html,wxs}", "**/*.{png,jpg,jpeg,gif,svg,webp}" ]; assetGlobs.push(...resolveGlobs(weapp?.copy?.include)); const patterns = assetGlobs.map( (x) => { return import_pathe4.default.join( targetDir, x ); } ); const relFiles = await new import_fdir.fdir().withRelativePaths().globWithOptions( patterns, { cwd: ctx.cwd, ignore } ).crawl(ctx.cwd).withPromise(); for (const file of relFiles) { const filepath = import_pathe4.default.resolve(ctx.cwd, file); this.addWatchFile(filepath); const isMedia = !/\.(?:wxml|wxs)$/.test(file); const isWxml = /\.wxml$/.test(file); const isHtml = /\.html$/.test(file); const source = isMedia ? await import_fs_extra4.default.readFile(filepath) : await import_fs_extra4.default.readFile(filepath, "utf8"); const fileName = ctx.relativeSrcRoot(file); if (isHtml || isWxml) { let _source; if (weapp?.enhance?.wxml) { const { code, deps } = processWxml(source); _source = code; for (const wxsDep of deps.filter((x) => x.tagName === "wxs")) { if (jsExtensions.includes(wxsDep.attrs.lang) || /\.wxs\.[jt]s$/.test(wxsDep.value)) { const wxsPath = import_pathe4.default.resolve(import_pathe4.default.dirname(filepath), wxsDep.value); if (await import_fs_extra4.default.exists(wxsPath)) { this.addWatchFile(wxsPath); const code2 = await import_fs_extra4.default.readFile(wxsPath, "utf8"); const res = transformWxsCode(code2, { filename: wxsPath }); if (res && res.code) { this.emitFile({ type: "asset", fileName: ctx.relativeSrcRoot(relative((0, import_shared4.removeExtension)(wxsPath))), source: res.code }); } } } } } else { _source = source; } this.emitFile({ type: "asset", fileName: isHtml ? changeFileExtension(fileName, ctx.outputExtensions.wxml) : fileName, source: _source }); } else { this.emitFile({ type: "asset", fileName, source }); } } for (const entry of entries) { if (entry.jsonPath) { this.addWatchFile(entry.jsonPath); if (entry.json) { const fileName = jsonFileRemoveJsExtension(ctx.relativeSrcRoot(import_pathe4.default.relative(ctx.cwd, entry.jsonPath))); this.emitFile({ type: "asset", fileName, source: resolveJson(entry, ctx.aliasEntries) }); } } if (entry.type === "app") { const appEntry = ctx.appEntry; if (appEntry) { if (appEntry.sitemapJsonPath) { this.addWatchFile(appEntry.sitemapJsonPath); if (appEntry.sitemapJson) { const fileName = jsonFileRemoveJsExtension(ctx.relativeSrcRoot(import_pathe4.default.relative(ctx.cwd, appEntry.sitemapJsonPath))); this.emitFile({ type: "asset", fileName, source: resolveJson({ json: appEntry.sitemapJson, jsonPath: appEntry.sitemapJsonPath }, ctx.aliasEntries) }); } } if (appEntry.themeJsonPath) { this.addWatchFile(appEntry.themeJsonPath); if (appEntry.themeJson) { const fileName = jsonFileRemoveJsExtension(ctx.relativeSrcRoot(import_pathe4.default.relative(ctx.cwd, appEntry.themeJsonPath))); this.emitFile({ type: "asset", fileName, source: resolveJson({ json: appEntry.themeJson, jsonPath: appEntry.themeJsonPath }, ctx.aliasEntries) }); } } } } } debug?.("buildEnd end"); }, resolveId(source) { if (/\.wxss$/.test(source)) { return source.replace(/\.wxss$/, ".css?wxss"); } }, async load(id) { if (entriesSet.has(id)) { const code = await import_fs_extra4.default.readFile(id, "utf8"); const ms = new import_magic_string2.default(code); for (const ext of supportedCssLangs) { const mayBeCssPath = changeFileExtension(id, ext); if (await import_fs_extra4.default.exists(mayBeCssPath)) { this.addWatchFile(mayBeCssPath); ms.prepend(`import '${mayBeCssPath}' `); } } return { code: ms.toString() }; } else if ((0, import_vite.isCSSRequest)(id)) { const parsed = parseRequest(id); const realPath = getCssRealPath(parsed); if (await import_fs_extra4.default.exists(realPath)) { const css = await import_fs_extra4.default.readFile(realPath, "utf8"); return { code: css }; } } }, // for debug watchChange(id, change) { debouncedLoggerSuccess(`[${change.event}] ${transformAbsoluteToRelative(id)}`); }, // renderStart() { // const watchFiles = this.getWatchFiles() // debug?.('renderStart watchFiles count: ', watchFiles.length) // }, // transform(code, id, options) { // console.log(id) // }, // 调试监听 // buildEnd() { // }, // renderChunk() { // const watchFiles = this.getWatchFiles() // debug?.('renderChunk watchFiles count: ', watchFiles.length) // }, // augmentChunkHash() { // const watchFiles = this.getWatchFiles() // debug?.('augmentChunkHash watchFiles count: ', watchFiles.length) // }, generateBundle(_options, bundle) { debug?.("generateBundle start"); const bundleKeys = Object.keys(bundle); for (const bundleKey of bundleKeys) { const asset = bundle[bundleKey]; if (bundleKey.endsWith(".css") && asset.type === "asset") { for (const originalFileName of asset.originalFileNames) { if (isJsOrTs(originalFileName)) { const newFileName = ctx.relativeSrcRoot( changeFileExtension(originalFileName, ctx.outputExtensions.wxss) ); this.emitFile({ type: "asset", fileName: newFileName, source: asset.source }); } } delete bundle[bundleKey]; } } debug?.("generateBundle end"); } // writeBundle() { // const watchFiles = this.getWatchFiles() // debug?.('writeBundle watchFiles count: ', watchFiles.length) // }, }, { // todo name: "weapp-vite" }, { // todo name: "weapp-vite:post", enforce: "post" } ]; } // src/config.ts init_cjs_shims(); // src/context.ts var debug2 = createDebugger("weapp-vite:context"); var once = false; function logBuildIndependentSubPackageFinish(root) { if (!once) { logger_default.success(`\u72EC\u7ACB\u5206\u5305 ${root} \u6784\u5EFA\u5B8C\u6210\uFF01`); once = true; } } var CompilerContext = class { /** * loadDefaultConfig 的时候会被重新赋予 */ inlineConfig; cwd; isDev; projectConfig; mode; packageJson; rollupWatcherMap; entriesSet; entries; appEntry; subPackageMeta; aliasEntries; platform; outputExtensions; /** * 不修改 ctx */ readCommentJson; /** * esbuild 定义的环境变量 */ defineEnv; constructor(options) { const { cwd, isDev, inlineConfig, projectConfig, mode, packageJson, platform } = (0, import_shared5.defu)(options, { cwd: import_node_process.default.cwd(), isDev: false, projectConfig: {}, inlineConfig: {}, packageJson: {}, platform: "weapp" }); this.cwd = cwd; this.inlineConfig = inlineConfig; this.isDev = isDev; this.projectConfig = projectConfig; this.mode = mode; this.packageJson = packageJson; this.rollupWatcherMap = /* @__PURE__ */ new Map(); this.subPackageMeta = {}; this.entriesSet = /* @__PURE__ */ new Set(); this.entries = []; this.aliasEntries = []; this.platform = platform; this.outputExtensions = getOutputExtensions(platform); this.readCommentJson = createReadCommentJson(this); this.defineEnv = {}; } // https://github.com/vitejs/vite/blob/192d555f88bba7576e8a40cc027e8a11e006079c/packages/vite/src/node/plugins/define.ts#L41 /** * 插件真正计算出来的 define options */ get define() { const env = { MP_PLATFORM: this.platform, ...this.defineEnv }; const define = {}; for (const [key, value] of Object.entries(env)) { define[`import.meta.env.${key}`] = JSON.stringify(value); } define[`import.meta.env`] = JSON.stringify(env); return define; } setDefineEnv(key, value) { this.defineEnv[key] = value; } get srcRoot() { return this.inlineConfig?.weapp?.srcRoot ?? ""; } relativeSrcRoot(p) { if (this.srcRoot) { return import_pathe5.default.relative(this.srcRoot, p); } return p; } /** * @description 写在 projectConfig 里面的 miniprogramRoot / srcMiniprogramRoot * 默认为 'dist' * */ get mpDistRoot() { return this.projectConfig.miniprogramRoot || this.projectConfig.srcMiniprogramRoot; } get outDir() { return import_pathe5.default.resolve(this.cwd, this.mpDistRoot ?? ""); } async runDev() { if (import_node_process.default.env.NODE_ENV === void 0) { import_node_process.default.env.NODE_ENV = "development"; } debug2?.("dev build watcher start"); const watcher = await (0, import_vite2.build)( this.getConfig() ); debug2?.("dev build watcher end"); debug2?.("dev watcher listen start"); await new Promise((resolve, reject) => { watcher.on("event", async (e) => { if (e.code === "END") { debug2?.("dev watcher listen end"); await this.buildSubPackage(); resolve(e); } else if (e.code === "ERROR") { reject(e); } }); }); this.setRollupWatcher(watcher); return watcher; } getConfig(subPackageMeta, ...configs) { if (this.isDev) { return (0, import_shared5.defu)( this.inlineConfig, ...configs, { root: this.cwd, mode: "development", plugins: [vitePluginWeapp(this, subPackageMeta)], // https://github.com/vitejs/vite/blob/a0336bd5197bb4427251be4c975e30fb596c658f/packages/vite/src/node/config.ts#L1117 define: this.define, build: { watch: { exclude: [ ...defaultExcluded, this.mpDistRoot ? import_pathe5.default.join(this.mpDistRoot, "**") : "dist/**" ], include: [import_pathe5.default.join(this.srcRoot, "**")], chokidar: { ignored: [...defaultExcluded] } }, minify: false, emptyOutDir: false } } ); } else { const inlineConfig = (0, import_shared5.defu)( this.inlineConfig, ...configs, { root: this.cwd, plugins: [vitePluginWeapp(this, subPackageMeta)], mode: "production", define: this.define, build: { emptyOutDir: false } } ); inlineConfig.logLevel = "info"; return inlineConfig; } } async runProd() { debug2?.("prod build start"); const output = await (0, import_vite2.build)( this.getConfig() ); debug2?.("prod build end"); await this.buildSubPackage(); return output; } async build() { if (this.mpDistRoot) { const deletedFilePaths = await (0, import_del.deleteAsync)( [ import_pathe5.default.resolve(this.outDir, "**") ], { ignore: ["**/miniprogram_npm/**"] } ); debug2?.("deletedFilePaths", deletedFilePaths); logger_default.success(`\u5DF2\u6E05\u7A7A ${this.mpDistRoot} \u76EE\u5F55`); } debug2?.("build start"); if (this.isDev) { await this.runDev(); } else { await this.runProd(); } debug2?.("build end"); } async loadDefaultConfig() { const projectConfig = await getProjectConfig(this.cwd); this.projectConfig = projectConfig; if (!this.mpDistRoot) { logger_default.error("\u8BF7\u5728 `project.config.json` \u91CC\u8BBE\u7F6E `miniprogramRoot`, \u6BD4\u5982\u53EF\u4EE5\u8BBE\u7F6E\u4E3A `dist/` "); return; } const packageJsonPath = import_pathe5.default.resolve(this.cwd, "package.json"); const external = []; if (await import_fs_extra5.default.exists(packageJsonPath)) { const localPackageJson = await import_fs_extra5.default.readJson(packageJsonPath, { throws: false }) || {}; this.packageJson = localPackageJson; if (localPackageJson.dependencies) { external.push(...Object.keys(localPackageJson.dependencies)); } } const loaded = await (0, import_vite2.loadConfigFromFile)({ command: this.isDev ? "serve" : "build", mode: this.mode }, void 0, this.cwd); this.inlineConfig = (0, import_shared5.defu)({ configFile: false }, loaded?.config, { build: { rollupOptions: { output: { format: "cjs", strict: false, entryFileNames: (chunkInfo) => { const name = this.relativeSrcRoot(chunkInfo.name); if (name.endsWith(".ts")) { const baseFileName = (0, import_shared5.removeExtension)(name); if (baseFileName.endsWith(".wxs")) { return baseFileName; } return (0, import_shared5.addExtension)(baseFileName, ".js"); } return name; } }, external }, assetsDir: ".", commonjsOptions: { transformMixedEsModules: true, include: void 0 } }, logLevel: "warn", weapp: getWeappViteConfig() }); this.inlineConfig.plugins ??= []; this.inlineConfig.plugins?.push((0, import_vite_tsconfig_paths.default)(this.inlineConfig.weapp?.tsconfigPaths)); this.aliasEntries = getAliasEntries(this.inlineConfig.weapp?.jsonAlias); } get dependenciesCacheFilePath() { return import_pathe5.default.resolve(this.cwd, "node_modules/weapp-vite/.cache/npm.json"); } get dependenciesCacheHash() { return (0, import_shared5.objectHash)(this.packageJson.dependencies ?? {}); } writeDependenciesCache() { return import_fs_extra5.default.outputJSON(this.dependenciesCacheFilePath, { "/": this.dependenciesCacheHash }); } async readDependenciesCache() { if (await import_fs_extra5.default.exists(this.dependenciesCacheFilePath)) { return await import_fs_extra5.default.readJson(this.dependenciesCacheFilePath, { throws: false }); } } async checkDependenciesCacheOutdate() { const json = await this.readDependenciesCache(); if ((0, import_shared5.isObject)(json)) { return this.dependenciesCacheHash !== json["/"]; } return true; } // https://cn.vitejs.dev/guide/build.html#library-mode // miniprogram_dist // miniprogram // https://developers.weixin.qq.com/miniprogram/dev/devtools/npm.html#%E8%87%AA%E5%AE%9A%E4%B9%89%E7%BB%84%E4%BB%B6%E7%9B%B8%E5%85%B3%E7%A4%BA%E4%BE%8B async buildNpm(subPackage, options) { debug2?.("buildNpm start"); const { build: tsupBuild } = await import("tsup"); const isDependenciesCacheOutdate = await this.checkDependenciesCacheOutdate(); let packNpmRelationList = []; if (this.projectConfig.setting?.packNpmManually && Array.isArray(this.projectConfig.setting.packNpmRelationList)) { packNpmRelationList = this.projectConfig.setting.packNpmRelationList; } else { packNpmRelationList = [ { miniprogramNpmDistDir: ".", packageJsonPath: "./package.json" } ]; } const heading = subPackage?.root ? `\u5206\u5305[${subPackage.root}]:` : ""; for (const relation of packNpmRelationList) { const packageJsonPath = import_pathe5.default.resolve(this.cwd, relation.packageJsonPath); if (await import_fs_extra5.default.exists(packageJsonPath)) { const pkgJson = await import_fs_extra5.default.readJson(packageJsonPath); const outDir = import_pathe5.default.resolve(this.cwd, relation.miniprogramNpmDistDir, subPackage?.root ?? "", "miniprogram_npm"); if (pkgJson.dependencies) { const dependencies = Object.keys(pkgJson.dependencies); if (dependencies.length > 0) { for (const dep of dependencies) { if (Array.isArray(subPackage?.dependencies)) { if (!regExpTest(subPackage.dependencies, dep)) { continue; } } const packageInfo = await (0, import_local_pkg.getPackageInfo)(dep); if (!packageInfo) { continue; } const { packageJson: targetJson, rootPath } = packageInfo; if (Reflect.has(targetJson, "miniprogram") && targetJson.miniprogram) { const destOutDir = import_pathe5.default.join(outDir, dep); if (!isDependenciesCacheOutdate && await import_fs_extra5.default.exists(destOutDir)) { logger_default.info(`${heading} ${dep} \u4F9D\u8D56\u672A\u53D1\u751F\u53D8\u5316\uFF0C\u8DF3\u8FC7\u5904\u7406!`); continue; } await import_fs_extra5.default.copy( import_pathe5.default.resolve( rootPath, targetJson.miniprogram ), destOutDir ); } else { const destOutDir = import_pathe5.default.join(outDir, dep); if (!isDependenciesCacheOutdate && await import_fs_extra5.default.exists(destOutDir)) { logger_default.info(`${heading} ${dep} \u4F9D\u8D56\u672A\u53D1\u751F\u53D8\u5316\uFF0C\u8DF3\u8FC7\u5904\u7406!`); continue; } const index = (0, import_local_pkg.resolveModule)(dep); if (!index) { continue; } const mergedOptions = (0, import_shared5.defu)(options, { entry: { index }, format: ["cjs"], outDir: destOutDir, silent: true, shims: true, outExtension: () => { return { js: ".js" }; }, sourcemap: false, config: false // external: [], // clean: false, }); const resolvedOptions = this.inlineConfig.weapp?.npm?.tsup?.(mergedOptions); let finalOptions; if (resolvedOptions === void 0) { finalOptions = mergedOptions; } else if ((0, import_shared5.isObject)(resolvedOptions)) { finalOptions = resolvedOptions; } finalOptions && await tsupBuild(finalOptions); } logger_default.success(`${heading} ${dep} \u4F9D\u8D56\u5904\u7406\u5B8C\u6210!`); } } } } } await this.writeDependenciesCache(); debug2?.("buildNpm end"); } /** * @deps [this.scanComponentEntry] * @param entry * @param relDir */ async usingComponentsHandler(entry, relDir, subPackageMeta) { const { usingComponents } = entry.json; if (usingComponents) { for (const [, componentUrl] of Object.entries(usingComponents)) { if (/plugin:\/\//.test(componentUrl)) { continue; } const tokens = componentUrl.split("/"); if (tokens[0] && (0, import_shared5.isObject)(this.packageJson.dependencies) && Reflect.has(this.packageJson.dependencies, tokens[0])) { continue; } else if (tokens[0] === "") { await this.scanComponentEntry(componentUrl.substring(1), import_pathe5.default.resolve(this.cwd, this.srcRoot), subPackageMeta); } else { const importee = resolveImportee(componentUrl, entry, this.aliasEntries); await this.scanComponentEntry(importee, relDir, subPackageMeta); } } } } resetEntries() { this.entriesSet.clear(); this.entries.length = 0; this.subPackageMeta = {}; } async scanAppEntry() { debug2?.("scanAppEntry start"); this.resetEntries(); const appDirname = import_pathe5.default.resolve(this.cwd, this.srcRoot); const appBasename = import_pathe5.default.resolve(appDirname, "app"); const appConfigFile = await findJsonEntry(appBasename); const appEntryPath = await findJsEntry(appBasename); if (appEntryPath && appConfigFile) { const config = await this.readCommentJson(appConfigFile); if ((0, import_shared5.isObject)(config)) { if (this.entriesSet.has(appEntryPath)) { return; } this.entriesSet.add(appEntryPath); const appEntry = { path: appEntryPath, json: config, jsonPath: appConfigFile, type: "app" }; this.entries.push(appEntry); this.appEntry = appEntry; const { pages, subpackages = [], subPackages = [], sitemapLocation = "sitemap.json", themeLocation = "theme.json" } = config; if (sitemapLocation) { const sitemapJsonPath = await findJsonEntry(import_pathe5.default.resolve(appDirname, sitemapLocation)); if (sitemapJsonPath) { appEntry.sitemapJsonPath = sitemapJsonPath; appEntry.sitemapJson = await this.readCommentJson(sitemapJsonPath); } } if (themeLocation) { const themeJsonPath = await findJsonEntry(import_pathe5.default.resolve(appDirname, themeLocation)); if (themeJsonPath) { appEntry.themeJsonPath = themeJsonPath; appEntry.themeJson = await this.readCommentJson(themeJsonPath); } } const subs = [...subpackages, ...subPackages]; await this.usingComponentsHandler(appEntry, appDirname); if (Array.isArray(pages)) { for (const page of pages) { await this.scanComponentEntry(page, appDirname); } } for (const sub of subs) { if (sub.independent || this.inlineConfig.weapp?.subPackages?.[sub.root]?.independent) { const meta = { entries: [], entriesSet: /* @__PURE__ */ new Set(), // 合并选项 subPackage: { ...sub, dependencies: this.inlineConfig.weapp?.subPackages?.[sub.root].dependencies } }; if (Array.isArray(sub.pages)) { for (const page of sub.pages) { await this.scanComponentEntry(import_pathe5.default.join(sub.root, page), appDirname, meta); } } if (sub.entry) { await this.scanComponentEntry(import_pathe5.default.join(sub.root, sub.entry), appDirname, meta); } this.subPackageMeta[sub.root] = meta; } else { if (Array.isArray(sub.pages)) { for (const page of sub.pages) { await this.scanComponentEntry(import_pathe5.default.join(sub.root, page), appDirname); } } if (sub.entry) { await this.scanComponentEntry(import_pathe5.default.join(sub.root, sub.entry), appDirname); } } } if ((0, import_shared5.get)(appEntry, "json.tabBar.custom")) { await this.scanComponentEntry("custom-tab-bar/index", appDirname); } if ((0, import_shared5.get)(appEntry, "json.appBar")) { await this.scanComponentEntry("app-bar/index", appDirname); } debug2?.("scanAppEntry end"); return appEntry; } } else { throw new Error(`\u5728 ${appDirname} \u76EE\u5F55\u4E0B\u6CA1\u6709\u627E\u5230 \`app.json\`, \u8BF7\u786E\u4FDD\u4F60\u521D\u59CB\u5316\u4E86\u5C0F\u7A0B\u5E8F\u9879\u76EE\uFF0C\u6216\u8005\u5728 \`vite.config.ts\` \u4E2D\u8BBE\u7F6E\u7684\u6B63\u786E\u7684 \`weapp.srcRoot\` \u914D\u7F6E\u8DEF\u5F84 `); } } // usingComponents // subpackages / subPackages // pages // https://developers.weixin.qq.com/miniprogram/dev/framework/structure.html // 页面可以没有 JSON async scanComponentEntry(componentEntry, dirname, subPackageMeta) { const meta = subPackageMeta ?? { entriesSet: this.entriesSet, entries: this.entries }; debug2?.("scanComponentEntry start", componentEntry); let baseName = (0, import_shared5.removeExtension)(import_pathe5.default.resolve(dirname, componentEntry)); if (await import_fs_extra5.default.exists(baseName)) { const stat = await import_fs_extra5.default.stat(baseName); if (stat.isDirectory()) { baseName = import_pathe5.default.join(baseName, "index"); } } const jsEntry = await findJsEntry(baseName); const partialEntry = { path: jsEntry }; if (jsEntry && !meta.entriesSet.has(jsEntry)) { meta.entriesSet.add(jsEntry); meta.entries.push(partialEntry); } const configFile = await findJsonEntry(baseName); if (configFile) { const config = await this.readCommentJson(configFile); const jsonFragment = { json: config, jsonPath: configFile }; if (jsEntry) { partialEntry.json = jsonFragment.json; partialEntry.jsonPath = jsonFragment.jsonPath; } if ((0, import_shared5.isObject)(config)) { await this.usingComponentsHandler(jsonFragment, import_pathe5.default.dirname(configFile), subPackageMeta); } } debug2?.("scanComponentEntry end", componentEntry); } setRollupWatcher(watcher, root = "/") { const oldWatcher = this.rollupWatcherMap.get(root); oldWatcher?.close(); this.rollupWatcherMap.set(root, watcher); } // 独立分包需要单独打包 async buildSubPackage() { debug2?.("buildSubPackage start"); for (const [root, meta] of Object.entries(this.subPackageMeta)) { const inlineConfig = this.getConfig(meta, { build: { rollupOptions: { output: { chunkFileNames() { return `${root}/[name]-[hash].js`; } } } } }); await this.buildNpm(meta.subPackage); const output = await (0, import_vite2.build)( inlineConfig ); if (this.isDev) { const watcher = output; this.setRollupWatcher(watcher, root); await new Promise((resolve, reject) => { watcher.on("event", (e) => { if (e.code === "END") { logBuildIndependentSubPackageFinish(root); resolve(e); } else if (e.code === "ERROR") { reject(e); } }); }); } else { logBuildIndependentSubPackageFinish(root); } } debug2?.("buildSubPackage end"); } }; async function createCompilerContext(options) { const ctx = new CompilerContext(options); await ctx.loadDefaultConfig(); return ctx; } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { CompilerContext, createCompilerContext });