unplugin-env 1.0.3 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -151,6 +151,32 @@ build({
151
151
 
152
152
  <br></details>
153
153
 
154
+ ## Options
155
+
156
+ ```ts
157
+ Starter({
158
+ env: {
159
+ configDir: 'config',
160
+ emitFileName: 'manifest.js',
161
+ emitDir: 'assets',
162
+ globalName: 'manifest',
163
+ devMatch: /dev/i,
164
+ buildMatch: /prod/i,
165
+ },
166
+ compress: {
167
+ includeBaseDir: true,
168
+ },
169
+ })
170
+ ```
171
+
172
+ - `env.configDir`: directory to locate config files.
173
+ - `env.emitFileName`: output file name for the emitted asset and injected script.
174
+ - `env.emitDir`: subdirectory under the build output directory.
175
+ - `env.globalName`: global variable name on `window`.
176
+ - `env.devMatch`: regex to pick the dev config file.
177
+ - `env.buildMatch`: regex to pick the build config file.
178
+ - `compress.includeBaseDir`: keep the top-level folder inside the zip.
179
+
154
180
  ## System Requirements
155
181
 
156
182
  ### Runtime Environment
package/README.zh-CN.md CHANGED
@@ -153,6 +153,32 @@ build({
153
153
 
154
154
  <br></details>
155
155
 
156
+ ## 配置项
157
+
158
+ ```ts
159
+ Starter({
160
+ env: {
161
+ configDir: 'config',
162
+ emitFileName: 'manifest.js',
163
+ emitDir: 'assets',
164
+ globalName: 'manifest',
165
+ devMatch: /dev/i,
166
+ buildMatch: /prod/i,
167
+ },
168
+ compress: {
169
+ includeBaseDir: true,
170
+ },
171
+ })
172
+ ```
173
+
174
+ - `env.configDir`: 配置文件所在目录。
175
+ - `env.emitFileName`: 输出文件名(用于 emit 和注入脚本)。
176
+ - `env.emitDir`: 输出子目录(相对于构建输出目录)。
177
+ - `env.globalName`: 挂到 `window` 的全局变量名。
178
+ - `env.devMatch`: 匹配开发环境配置文件的正则。
179
+ - `env.buildMatch`: 匹配生产环境配置文件的正则。
180
+ - `compress.includeBaseDir`: 压缩时是否保留顶层目录。
181
+
156
182
  ## 系统要求详情
157
183
 
158
184
  ### 运行环境
@@ -1147,7 +1147,7 @@ var require_parse = __commonJS({
1147
1147
  CHAR_NO_BREAK_SPACE,
1148
1148
  CHAR_ZERO_WIDTH_NOBREAK_SPACE
1149
1149
  } = require_constants();
1150
- var parse = (input, options = {}) => {
1150
+ var parse2 = (input, options = {}) => {
1151
1151
  if (typeof input !== "string") {
1152
1152
  throw new TypeError("Expected a string");
1153
1153
  }
@@ -1347,7 +1347,7 @@ var require_parse = __commonJS({
1347
1347
  push({ type: "eos" });
1348
1348
  return ast;
1349
1349
  };
1350
- module.exports = parse;
1350
+ module.exports = parse2;
1351
1351
  }
1352
1352
  });
1353
1353
 
@@ -1358,7 +1358,7 @@ var require_braces = __commonJS({
1358
1358
  var stringify = require_stringify();
1359
1359
  var compile = require_compile();
1360
1360
  var expand = require_expand();
1361
- var parse = require_parse();
1361
+ var parse2 = require_parse();
1362
1362
  var braces = (input, options = {}) => {
1363
1363
  let output = [];
1364
1364
  if (Array.isArray(input)) {
@@ -1378,7 +1378,7 @@ var require_braces = __commonJS({
1378
1378
  }
1379
1379
  return output;
1380
1380
  };
1381
- braces.parse = (input, options = {}) => parse(input, options);
1381
+ braces.parse = (input, options = {}) => parse2(input, options);
1382
1382
  braces.stringify = (input, options = {}) => {
1383
1383
  if (typeof input === "string") {
1384
1384
  return stringify(braces.parse(input, options), options);
@@ -2031,7 +2031,7 @@ var require_parse2 = __commonJS({
2031
2031
  var syntaxError = (type, char) => {
2032
2032
  return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
2033
2033
  };
2034
- var parse = (input, options) => {
2034
+ var parse2 = (input, options) => {
2035
2035
  if (typeof input !== "string") {
2036
2036
  throw new TypeError("Expected a string");
2037
2037
  }
@@ -2180,7 +2180,7 @@ var require_parse2 = __commonJS({
2180
2180
  output = token.close = `)$))${extglobStar}`;
2181
2181
  }
2182
2182
  if (token.inner.includes("*") && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
2183
- const expression = parse(rest, { ...options, fastpaths: false }).output;
2183
+ const expression = parse2(rest, { ...options, fastpaths: false }).output;
2184
2184
  output = token.close = `)${expression})${extglobStar})`;
2185
2185
  }
2186
2186
  if (token.prev.type === "bos") {
@@ -2705,7 +2705,7 @@ var require_parse2 = __commonJS({
2705
2705
  }
2706
2706
  return state;
2707
2707
  };
2708
- parse.fastpaths = (input, options) => {
2708
+ parse2.fastpaths = (input, options) => {
2709
2709
  const opts = { ...options };
2710
2710
  const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
2711
2711
  const len = input.length;
@@ -2771,7 +2771,7 @@ var require_parse2 = __commonJS({
2771
2771
  }
2772
2772
  return source;
2773
2773
  };
2774
- module.exports = parse;
2774
+ module.exports = parse2;
2775
2775
  }
2776
2776
  });
2777
2777
 
@@ -2781,7 +2781,7 @@ var require_picomatch = __commonJS({
2781
2781
  "use strict";
2782
2782
  var path3 = __require("path");
2783
2783
  var scan = require_scan();
2784
- var parse = require_parse2();
2784
+ var parse2 = require_parse2();
2785
2785
  var utils = require_utils2();
2786
2786
  var constants = require_constants2();
2787
2787
  var isObject = (val) => val && typeof val === "object" && !Array.isArray(val);
@@ -2869,7 +2869,7 @@ var require_picomatch = __commonJS({
2869
2869
  picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
2870
2870
  picomatch.parse = (pattern, options) => {
2871
2871
  if (Array.isArray(pattern)) return pattern.map((p) => picomatch.parse(p, options));
2872
- return parse(pattern, { ...options, fastpaths: false });
2872
+ return parse2(pattern, { ...options, fastpaths: false });
2873
2873
  };
2874
2874
  picomatch.scan = (input, options) => scan(input, options);
2875
2875
  picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
@@ -2895,10 +2895,10 @@ var require_picomatch = __commonJS({
2895
2895
  }
2896
2896
  let parsed = { negated: false, fastpaths: true };
2897
2897
  if (options.fastpaths !== false && (input[0] === "." || input[0] === "*")) {
2898
- parsed.output = parse.fastpaths(input, options);
2898
+ parsed.output = parse2.fastpaths(input, options);
2899
2899
  }
2900
2900
  if (!parsed.output) {
2901
- parsed = parse(input, options);
2901
+ parsed = parse2(input, options);
2902
2902
  }
2903
2903
  return picomatch.compileRe(parsed, options, returnOutput, returnState);
2904
2904
  };
@@ -6050,13 +6050,13 @@ var Log = class {
6050
6050
 
6051
6051
  // src/core/compress.ts
6052
6052
  async function createCompress(options, outDir) {
6053
- const { ignoreBase } = options;
6053
+ const { includeBaseDir } = options;
6054
6054
  const zipFilePath = path.resolve(process3.cwd(), `${path.basename(outDir)}.zip`);
6055
6055
  const absoluteOutDir = path.resolve(outDir);
6056
6056
  Log.log("Compressing directory:", absoluteOutDir);
6057
6057
  try {
6058
6058
  const zip = new Zip();
6059
- if (ignoreBase) {
6059
+ if (!includeBaseDir) {
6060
6060
  zip.addFolder(absoluteOutDir);
6061
6061
  } else {
6062
6062
  zip.addFolder(absoluteOutDir, path.basename(outDir));
@@ -6082,11 +6082,12 @@ import { deepMerge } from "@antfu/utils";
6082
6082
 
6083
6083
  // src/core/generate.ts
6084
6084
  var import_fast_glob = __toESM(require_out4(), 1);
6085
+ import { execSync } from "child_process";
6085
6086
  import { promises as fs2 } from "fs";
6086
6087
  import path2 from "path";
6087
6088
  import process4 from "process";
6088
- import { getPackageInfo } from "local-pkg";
6089
- import recast from "recast";
6089
+ import * as recast from "recast";
6090
+ import tsParser from "recast/parsers/typescript.js";
6090
6091
  function mergeObjects(prodObj, devObj) {
6091
6092
  const prodProps = new Map(prodObj.properties.map((p) => [p.key.name || p.key.value, p]));
6092
6093
  for (const prop of devObj.properties) {
@@ -6101,33 +6102,56 @@ function mergeObjects(prodObj, devObj) {
6101
6102
  }
6102
6103
  }
6103
6104
  async function generateScript(options, context) {
6104
- const { dir, fileName, globalName, serve, build } = options.env;
6105
- const folder = await findFolder(process4.cwd(), dir);
6106
- const files = await (0, import_fast_glob.default)("*.+(js|ts)", {
6105
+ const { configDir, emitFileName, emitDir, globalName, devMatch, buildMatch } = options.env;
6106
+ const folder = await resolveConfigFolder(process4.cwd(), configDir);
6107
+ if (!folder)
6108
+ throw new Error(`[unplugin-env] Config directory "${configDir}" not found from ${process4.cwd()}`);
6109
+ const files = await (0, import_fast_glob.default)("*.{js,ts}", {
6107
6110
  absolute: true,
6108
6111
  cwd: folder
6109
6112
  });
6113
+ if (!files.length)
6114
+ throw new Error(`[unplugin-env] No config files found in ${folder}`);
6110
6115
  const { mode, base } = context;
6111
- const testReg = mode === "dev" ? serve : build;
6116
+ const testReg = mode === "dev" ? devMatch : buildMatch;
6112
6117
  let target = "";
6113
6118
  let source = "";
6114
6119
  let code = "";
6115
- const name = fileName;
6120
+ let targetFile = "";
6121
+ let sourceFile = "";
6122
+ const resolvedEmitFileName = resolveEmitFileName(emitDir, emitFileName);
6116
6123
  for (const file of files) {
6117
6124
  try {
6118
6125
  const mod = await fs2.readFile(file, "utf-8");
6119
- if (testReg?.test(file))
6126
+ if (testReg?.test(file)) {
6120
6127
  target = mod;
6121
- else
6128
+ targetFile = file;
6129
+ } else {
6122
6130
  source = mod;
6131
+ sourceFile = file;
6132
+ }
6123
6133
  } catch (error) {
6124
6134
  console.error(`Error loading file ${file}:`, error);
6125
6135
  }
6126
6136
  }
6127
- const targetAst = recast.parse(target);
6128
- const sourceAst = recast.parse(source);
6129
- const targetExport = targetAst.program.body.find((n) => n.type === "ExportDefaultDeclaration").declaration;
6130
- const sourceExport = sourceAst.program.body.find((n) => n.type === "ExportDefaultDeclaration").declaration;
6137
+ if (files.length === 1) {
6138
+ if (!target) {
6139
+ target = source;
6140
+ targetFile = sourceFile;
6141
+ }
6142
+ if (!source) {
6143
+ source = target;
6144
+ sourceFile = targetFile;
6145
+ }
6146
+ }
6147
+ if (!target || !targetFile)
6148
+ throw new Error(`[unplugin-env] No file matched "${testReg}" in ${folder}`);
6149
+ if (!source || !sourceFile)
6150
+ throw new Error(`[unplugin-env] No base config file found in ${folder}`);
6151
+ const targetAst = parseConfig(target, targetFile);
6152
+ const sourceAst = parseConfig(source, sourceFile);
6153
+ const targetExport = getDefaultExportObject(targetAst, targetFile);
6154
+ const sourceExport = getDefaultExportObject(sourceAst, sourceFile);
6131
6155
  mergeObjects(sourceExport, targetExport);
6132
6156
  const mergedCode = recast.print(sourceExport).code;
6133
6157
  const returnedTarget = mergedCode;
@@ -6135,55 +6159,206 @@ async function generateScript(options, context) {
6135
6159
  code = `window.${globalName}=${returnedTarget};
6136
6160
  ${versionInfo}`;
6137
6161
  const formatCode = code;
6162
+ const viteIgnoreAttr = context.framework === "vite" ? " vite-ignore" : "";
6163
+ const scriptSrc = joinBasePath(base, resolvedEmitFileName);
6138
6164
  return {
6139
6165
  code,
6140
- script: ` <script type="text/javascript" src="${base}${fileName}"></script>
6166
+ script: ` <script type="text/javascript"${viteIgnoreAttr} src="${scriptSrc}"></script>
6141
6167
  </head>`,
6142
6168
  emit: {
6143
6169
  type: "asset",
6144
- fileName: name,
6170
+ fileName: resolvedEmitFileName,
6145
6171
  source: formatCode
6146
6172
  },
6147
6173
  watchFiles: files
6148
6174
  };
6149
6175
  }
6176
+ async function getFullPackageJson(cwd = process4.cwd()) {
6177
+ const pkgPath = path2.resolve(cwd, "package.json");
6178
+ const content = await fs2.readFile(pkgPath, "utf-8");
6179
+ return JSON.parse(content);
6180
+ }
6181
+ function wrapText(text, maxLen) {
6182
+ const lines = [];
6183
+ let current = "";
6184
+ for (const char of text) {
6185
+ current += char;
6186
+ if (current.length >= maxLen) {
6187
+ lines.push(current);
6188
+ current = "";
6189
+ }
6190
+ }
6191
+ if (current)
6192
+ lines.push(current);
6193
+ return lines;
6194
+ }
6195
+ function parseConfig(code, filePath) {
6196
+ const parser = filePath.endsWith(".ts") ? tsParser : void 0;
6197
+ return parser ? recast.parse(code, { parser }) : recast.parse(code);
6198
+ }
6199
+ function getDefaultExportObject(ast, filePath) {
6200
+ const exportNode = ast?.program?.body?.find((node) => node.type === "ExportDefaultDeclaration");
6201
+ if (!exportNode?.declaration)
6202
+ throw new Error(`[unplugin-env] ${filePath} must have a default export of an object`);
6203
+ let decl = exportNode.declaration;
6204
+ if (decl.type === "TSAsExpression" || decl.type === "TSTypeAssertion")
6205
+ decl = decl.expression;
6206
+ if (decl.type === "CallExpression" && decl.arguments?.[0]?.type === "ObjectExpression")
6207
+ decl = decl.arguments[0];
6208
+ if (decl.type !== "ObjectExpression")
6209
+ throw new Error(`[unplugin-env] ${filePath} default export must be an object literal`);
6210
+ return decl;
6211
+ }
6212
+ function joinBasePath(base, resourcePath) {
6213
+ const safeBase = base && base.endsWith("/") ? base : `${base || "/"}`.replace(/\/?$/, "/");
6214
+ const safeFile = resourcePath.replace(/^\/+/, "");
6215
+ return `${safeBase}${safeFile}`;
6216
+ }
6217
+ function resolveEmitFileName(emitDir, emitFileName) {
6218
+ const normalizedFile = emitFileName.replace(/\\/g, "/").replace(/^\/+/, "");
6219
+ if (!emitDir)
6220
+ return normalizedFile;
6221
+ const normalizedDir = emitDir.replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
6222
+ if (!normalizedDir)
6223
+ return normalizedFile;
6224
+ const prefix = `${normalizedDir}/`;
6225
+ if (normalizedFile === normalizedDir || normalizedFile.startsWith(prefix))
6226
+ return normalizedFile;
6227
+ return path2.posix.join(normalizedDir, normalizedFile);
6228
+ }
6229
+ async function resolveConfigFolder(root, configDir) {
6230
+ if (!configDir)
6231
+ return "";
6232
+ const candidate = path2.isAbsolute(configDir) ? configDir : path2.resolve(root, configDir);
6233
+ try {
6234
+ const stat = await fs2.stat(candidate);
6235
+ if (stat.isDirectory())
6236
+ return candidate;
6237
+ } catch {
6238
+ }
6239
+ return findFolder(root, configDir);
6240
+ }
6150
6241
  async function generateVersion(options, mode) {
6151
- const pkg = await getPackageInfo(process4.cwd());
6152
- return `console.info("Version: %c${pkg?.version}%c - ${mode === "dev" ? "runtime" : "built"} on %c${options.datetime}%c", "color: green;", '', "color: blue;", '')`;
6242
+ const pkg = await getFullPackageJson(process4.cwd());
6243
+ const name = pkg?.name ?? "Unknown App";
6244
+ const version = `v${pkg?.version ?? "0.0.0"}`;
6245
+ const branchName = getBranchName() || "unknown";
6246
+ const commitHash = getCommitHash() || "unknown";
6247
+ const datetime = options.datetime;
6248
+ const stateLabel = mode === "dev" ? "runtime" : "built";
6249
+ const stateColor = mode === "dev" ? "#059669" : "#2563EB";
6250
+ const MAX_DESC_LINE_LEN = 36;
6251
+ const rawDesc = pkg?.description ?? "unknown";
6252
+ const descLines = wrapText(rawDesc, MAX_DESC_LINE_LEN);
6253
+ const baseLines = [
6254
+ `${name} ${version} ${stateLabel}`,
6255
+ `Branch : ${branchName}`,
6256
+ `Commit : ${commitHash}`,
6257
+ `Time : ${datetime}`,
6258
+ `Desc : ${descLines[0]}`,
6259
+ ...descLines.slice(1).map((l) => ` ${l}`)
6260
+ ];
6261
+ const maxLen = Math.max(...baseLines.map((l) => l.length));
6262
+ const divider = "-".repeat(maxLen + 4);
6263
+ const textParts = [
6264
+ `${divider}
6265
+ `,
6266
+ ` ${name} `,
6267
+ ` ${version} `,
6268
+ ` ${stateLabel}
6269
+ `,
6270
+ `${divider}
6271
+ `,
6272
+ ` Branch :`,
6273
+ ` ${branchName}
6274
+ `,
6275
+ ` Commit :`,
6276
+ ` ${commitHash}
6277
+ `,
6278
+ ` Time :`,
6279
+ ` ${datetime}
6280
+ `,
6281
+ ` Desc :`,
6282
+ ` ${descLines[0]}
6283
+ `,
6284
+ ...descLines.slice(1).map((l) => ` ${l}
6285
+ `),
6286
+ `${divider}`
6287
+ ];
6288
+ const styles3 = [
6289
+ "color:#9CA3AF",
6290
+ // divider
6291
+ "color:#111827;font-weight:600",
6292
+ // name
6293
+ "color:#2563EB;font-weight:600",
6294
+ // version
6295
+ `color:${stateColor};font-weight:600`,
6296
+ // state
6297
+ "color:#9CA3AF",
6298
+ // divider
6299
+ "color:#6B7280",
6300
+ // Branch label
6301
+ "color:#111827",
6302
+ "color:#6B7280",
6303
+ // Commit label
6304
+ "color:#111827",
6305
+ "color:#6B7280",
6306
+ // Time label
6307
+ "color:#2563EB",
6308
+ "color:#6B7280",
6309
+ // Desc label
6310
+ "color:#4B5563",
6311
+ ...descLines.slice(1).map(() => "color:#4B5563"),
6312
+ "color:#9CA3AF"
6313
+ // divider
6314
+ ];
6315
+ return `
6316
+ console.log(
6317
+ ${JSON.stringify(`%c${textParts.join("%c")}`)},
6318
+ ${styles3.map((s) => JSON.stringify(s)).join(",\n ")}
6319
+ )
6320
+ `.trim();
6153
6321
  }
6154
6322
  async function findFolder(directoryPath, dir) {
6155
6323
  const ignore = /* @__PURE__ */ new Set(["dist", "node_modules", "playground", "example", "test", "jest", "tests", "locales", "public", ".git", ".github", ".vscode"]);
6156
- const files = await fs2.readdir(directoryPath);
6157
- const filePaths = files.filter((item) => !ignore.has(item));
6324
+ const entries = await fs2.readdir(directoryPath, { withFileTypes: true });
6325
+ const dirLower = dir.toLowerCase();
6326
+ const filePaths = entries.filter((entry) => !ignore.has(entry.name));
6158
6327
  let nestedFolder = "";
6159
- for (const file of filePaths) {
6160
- const fullFilePath = path2.join(directoryPath, file);
6161
- const stat = await fs2.stat(fullFilePath);
6162
- if (stat.isDirectory()) {
6163
- if (file.toLowerCase() === dir) {
6164
- return fullFilePath;
6165
- } else {
6166
- nestedFolder = await findFolder(fullFilePath, dir);
6167
- if (nestedFolder)
6168
- return nestedFolder;
6169
- }
6170
- }
6328
+ for (const entry of filePaths) {
6329
+ if (!entry.isDirectory())
6330
+ continue;
6331
+ const fullFilePath = path2.join(directoryPath, entry.name);
6332
+ if (entry.name.toLowerCase() === dirLower)
6333
+ return fullFilePath;
6334
+ nestedFolder = await findFolder(fullFilePath, dir);
6335
+ if (nestedFolder)
6336
+ return nestedFolder;
6171
6337
  }
6172
6338
  return "";
6173
6339
  }
6340
+ function getBranchName() {
6341
+ const branchName = execSync("git rev-parse --abbrev-ref HEAD").toString().trim();
6342
+ return branchName;
6343
+ }
6344
+ function getCommitHash() {
6345
+ const commitHash = execSync("git rev-parse HEAD").toString().trim();
6346
+ return commitHash.slice(0, 8);
6347
+ }
6174
6348
 
6175
6349
  // src/core/options.ts
6176
6350
  function resolveOptions(options) {
6177
6351
  const defaults = {
6178
6352
  env: {
6179
- dir: "config",
6180
- fileName: "manifest.js",
6353
+ configDir: "config",
6354
+ emitFileName: "manifest.js",
6355
+ emitDir: "",
6181
6356
  globalName: "manifest",
6182
- serve: /dev/i,
6183
- build: /prod/i
6357
+ devMatch: /dev/i,
6358
+ buildMatch: /prod/i
6184
6359
  },
6185
6360
  compress: {
6186
- ignoreBase: false
6361
+ includeBaseDir: true
6187
6362
  }
6188
6363
  };
6189
6364
  const mergeOptions = deepMerge(defaults, options);
@@ -6280,16 +6455,33 @@ function createUnifiedContext(resolved) {
6280
6455
 
6281
6456
  // src/index.ts
6282
6457
  var virtualEnvId = "virtual:env";
6458
+ var virtualEnvAliasId = "virtual-env";
6283
6459
  var resolvedVirtualEnvId = `\0${virtualEnvId}`;
6460
+ var resolvedVirtualEnvAliasId = `\0${virtualEnvAliasId}`;
6461
+ function isVirtualEnvId(id) {
6462
+ return id.startsWith(virtualEnvId) || id.startsWith(virtualEnvAliasId);
6463
+ }
6464
+ function resolveVirtualEnvId(id) {
6465
+ return id.startsWith(virtualEnvAliasId) ? resolvedVirtualEnvAliasId : resolvedVirtualEnvId;
6466
+ }
6467
+ function isResolvedVirtualEnvId(id) {
6468
+ return id.startsWith(resolvedVirtualEnvId) || id.startsWith(resolvedVirtualEnvAliasId);
6469
+ }
6284
6470
  var unpluginFactory = (options = {}) => {
6285
6471
  const resolved = resolveOptions(options);
6286
6472
  const ctx = createUnifiedContext(resolved);
6473
+ let frameworkReady = null;
6474
+ let legacyEmitHooked = false;
6287
6475
  return [{
6288
6476
  name: "plugin-env",
6289
6477
  enforce: "post",
6290
6478
  rollup: {
6479
+ async buildStart() {
6480
+ const outputOptions = { dir: ctx.outDir };
6481
+ await ctx.setRollup(outputOptions);
6482
+ },
6291
6483
  outputOptions(outputOptions) {
6292
- ctx.setRollup(outputOptions);
6484
+ ctx.outDir = outputOptions.dir || ctx.outDir;
6293
6485
  return outputOptions;
6294
6486
  }
6295
6487
  },
@@ -6299,10 +6491,82 @@ var unpluginFactory = (options = {}) => {
6299
6491
  }
6300
6492
  },
6301
6493
  async webpack(compiler) {
6302
- await ctx.setWebpack(compiler);
6494
+ frameworkReady = ctx.setWebpack(compiler);
6495
+ const webpackLib = compiler.webpack;
6496
+ const RawSource = webpackLib?.sources?.RawSource;
6497
+ compiler.hooks.thisCompilation.tap("plugin-env", (compilation) => {
6498
+ if (webpackLib?.Compilation?.PROCESS_ASSETS_STAGE_PRE_PROCESS) {
6499
+ const { Compilation, sources } = webpackLib;
6500
+ compilation.hooks.processAssets.tapPromise(
6501
+ { name: "plugin-env", stage: Compilation.PROCESS_ASSETS_STAGE_PRE_PROCESS },
6502
+ async () => {
6503
+ await frameworkReady;
6504
+ const manifestName = ctx.scriptInfo.emit.fileName;
6505
+ if (!manifestName)
6506
+ return;
6507
+ const asset = compilation.getAsset(manifestName);
6508
+ if (!asset || asset.info?.minimized)
6509
+ return;
6510
+ compilation.updateAsset(manifestName, asset.source, { ...asset.info, minimized: true });
6511
+ }
6512
+ );
6513
+ compilation.hooks.processAssets.tapPromise(
6514
+ { name: "plugin-env", stage: Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE },
6515
+ async (assets) => {
6516
+ await frameworkReady;
6517
+ const { script } = ctx.scriptInfo;
6518
+ if (!script)
6519
+ return;
6520
+ const scriptTag = script.replace(/<\/head>\s*$/i, "").trim();
6521
+ for (const name of Object.keys(assets)) {
6522
+ if (!name.endsWith(".html"))
6523
+ continue;
6524
+ const asset = compilation.getAsset(name);
6525
+ const html = asset?.source.source().toString() || "";
6526
+ if (!html || html.includes(scriptTag))
6527
+ continue;
6528
+ const nextHtml = html.replace(/<\/head>/i, script);
6529
+ if (nextHtml !== html)
6530
+ compilation.updateAsset(name, new sources.RawSource(nextHtml));
6531
+ }
6532
+ }
6533
+ );
6534
+ } else if (!legacyEmitHooked) {
6535
+ legacyEmitHooked = true;
6536
+ compiler.hooks.emit.tapAsync("plugin-env", (comp, cb) => {
6537
+ const run = () => {
6538
+ const { script } = ctx.scriptInfo;
6539
+ if (!script)
6540
+ return cb();
6541
+ const scriptTag = script.replace(/<\/head>\s*$/i, "").trim();
6542
+ for (const name of Object.keys(comp.assets)) {
6543
+ if (!name.endsWith(".html"))
6544
+ continue;
6545
+ const asset = comp.assets[name];
6546
+ const html = asset?.source().toString() || "";
6547
+ if (!html || html.includes(scriptTag))
6548
+ continue;
6549
+ const nextHtml = html.replace(/<\/head>/i, script);
6550
+ if (nextHtml !== html) {
6551
+ comp.assets[name] = RawSource ? new RawSource(nextHtml) : {
6552
+ source: () => nextHtml,
6553
+ size: () => nextHtml.length
6554
+ };
6555
+ }
6556
+ }
6557
+ cb();
6558
+ };
6559
+ if (frameworkReady) {
6560
+ frameworkReady.then(run).catch((error) => cb(error));
6561
+ } else {
6562
+ run();
6563
+ }
6564
+ });
6565
+ }
6566
+ });
6303
6567
  },
6304
6568
  rspack: async (compiler) => {
6305
- await ctx.setRspack(compiler);
6569
+ frameworkReady = ctx.setRspack(compiler);
6306
6570
  },
6307
6571
  esbuild: {
6308
6572
  async setup(build) {
@@ -6318,35 +6582,62 @@ var unpluginFactory = (options = {}) => {
6318
6582
  }
6319
6583
  },
6320
6584
  async resolveId(id) {
6321
- if (id.startsWith(virtualEnvId))
6322
- return resolvedVirtualEnvId;
6585
+ if (isVirtualEnvId(id))
6586
+ return resolveVirtualEnvId(id);
6587
+ },
6588
+ loadInclude(id) {
6589
+ if (isResolvedVirtualEnvId(id) || isVirtualEnvId(id))
6590
+ return true;
6591
+ if (id.endsWith(".html")) {
6592
+ return ctx.framework === "vite" || ctx.framework === "rollup" || ctx.framework === "rolldown";
6593
+ }
6594
+ return false;
6323
6595
  },
6324
6596
  async load(id) {
6597
+ if (frameworkReady)
6598
+ await frameworkReady;
6325
6599
  const { code, watchFiles, emit, script } = ctx.scriptInfo;
6326
6600
  if (ctx.isDev) {
6327
- if (id.startsWith(resolvedVirtualEnvId)) {
6601
+ if (isResolvedVirtualEnvId(id)) {
6328
6602
  watchFiles.forEach((file) => {
6329
6603
  this.addWatchFile(file);
6330
6604
  });
6331
6605
  return code;
6332
6606
  }
6333
6607
  } else {
6334
- if (id.startsWith(resolvedVirtualEnvId)) {
6608
+ if (isResolvedVirtualEnvId(id)) {
6335
6609
  this.emitFile(emit);
6336
6610
  return "";
6337
6611
  }
6338
- if (id.endsWith(".html")) {
6612
+ const canTransformHtml = ctx.framework === "vite" || ctx.framework === "rollup" || ctx.framework === "rolldown";
6613
+ if (canTransformHtml && id.endsWith(".html")) {
6339
6614
  let code2 = await fs3.readFile(id, "utf-8");
6340
6615
  code2 = code2.replace(/<\/head>/g, script);
6341
6616
  return { code: code2 };
6342
6617
  }
6343
6618
  }
6344
6619
  },
6620
+ transformInclude(id) {
6621
+ return /\.(?:c|m)?(?:j|t)sx?$/.test(id);
6622
+ },
6623
+ async transform(code, id) {
6624
+ if (ctx.framework !== "webpack" && ctx.framework !== "rspack")
6625
+ return;
6626
+ if (!id.match(/\.(?:c|m)?(?:j|t)sx?$/))
6627
+ return;
6628
+ if (!code.includes(virtualEnvId))
6629
+ return;
6630
+ return code.replaceAll(virtualEnvId, virtualEnvAliasId);
6631
+ },
6345
6632
  buildEnd: () => {
6346
- process6.on("beforeExit", async () => {
6633
+ process6.on("beforeExit", () => {
6347
6634
  const { compress } = resolved;
6348
- await createCompress(compress, ctx.outDir);
6349
- process6.exit(0);
6635
+ createCompress(compress, ctx.outDir).then(() => {
6636
+ process6.exit(0);
6637
+ }).catch((error) => {
6638
+ process6.exitCode = 1;
6639
+ throw error;
6640
+ });
6350
6641
  });
6351
6642
  }
6352
6643
  }];