unplugin-env 1.0.2 → 1.0.4

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.
@@ -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);
@@ -1914,7 +1914,7 @@ var require_scan = __commonJS({
1914
1914
  isExtglob = false;
1915
1915
  isGlob = false;
1916
1916
  }
1917
- let base2 = str;
1917
+ let base = str;
1918
1918
  let prefix = "";
1919
1919
  let glob = "";
1920
1920
  if (start > 0) {
@@ -1922,31 +1922,31 @@ var require_scan = __commonJS({
1922
1922
  str = str.slice(start);
1923
1923
  lastIndex -= start;
1924
1924
  }
1925
- if (base2 && isGlob === true && lastIndex > 0) {
1926
- base2 = str.slice(0, lastIndex);
1925
+ if (base && isGlob === true && lastIndex > 0) {
1926
+ base = str.slice(0, lastIndex);
1927
1927
  glob = str.slice(lastIndex);
1928
1928
  } else if (isGlob === true) {
1929
- base2 = "";
1929
+ base = "";
1930
1930
  glob = str;
1931
1931
  } else {
1932
- base2 = str;
1932
+ base = str;
1933
1933
  }
1934
- if (base2 && base2 !== "" && base2 !== "/" && base2 !== str) {
1935
- if (isPathSeparator(base2.charCodeAt(base2.length - 1))) {
1936
- base2 = base2.slice(0, -1);
1934
+ if (base && base !== "" && base !== "/" && base !== str) {
1935
+ if (isPathSeparator(base.charCodeAt(base.length - 1))) {
1936
+ base = base.slice(0, -1);
1937
1937
  }
1938
1938
  }
1939
1939
  if (opts.unescape === true) {
1940
1940
  if (glob) glob = utils.removeBackslashes(glob);
1941
- if (base2 && backslashes === true) {
1942
- base2 = utils.removeBackslashes(base2);
1941
+ if (base && backslashes === true) {
1942
+ base = utils.removeBackslashes(base);
1943
1943
  }
1944
1944
  }
1945
1945
  const state = {
1946
1946
  prefix,
1947
1947
  input,
1948
1948
  start,
1949
- base: base2,
1949
+ base,
1950
1950
  glob,
1951
1951
  isBrace,
1952
1952
  isBracket,
@@ -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
  };
@@ -3499,28 +3499,28 @@ var require_tasks = __commonJS({
3499
3499
  function groupPatternsByBaseDirectory(patterns) {
3500
3500
  const group = {};
3501
3501
  return patterns.reduce((collection, pattern) => {
3502
- const base2 = utils.pattern.getBaseDirectory(pattern);
3503
- if (base2 in collection) {
3504
- collection[base2].push(pattern);
3502
+ const base = utils.pattern.getBaseDirectory(pattern);
3503
+ if (base in collection) {
3504
+ collection[base].push(pattern);
3505
3505
  } else {
3506
- collection[base2] = [pattern];
3506
+ collection[base] = [pattern];
3507
3507
  }
3508
3508
  return collection;
3509
3509
  }, group);
3510
3510
  }
3511
3511
  exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory;
3512
3512
  function convertPatternGroupsToTasks(positive, negative, dynamic) {
3513
- return Object.keys(positive).map((base2) => {
3514
- return convertPatternGroupToTask(base2, positive[base2], negative, dynamic);
3513
+ return Object.keys(positive).map((base) => {
3514
+ return convertPatternGroupToTask(base, positive[base], negative, dynamic);
3515
3515
  });
3516
3516
  }
3517
3517
  exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks;
3518
- function convertPatternGroupToTask(base2, positive, negative, dynamic) {
3518
+ function convertPatternGroupToTask(base, positive, negative, dynamic) {
3519
3519
  return {
3520
3520
  dynamic,
3521
3521
  positive,
3522
3522
  negative,
3523
- base: base2,
3523
+ base,
3524
3524
  patterns: [].concat(positive, negative.map(utils.pattern.convertToNegativePattern))
3525
3525
  };
3526
3526
  }
@@ -4460,8 +4460,8 @@ var require_async3 = __commonJS({
4460
4460
  onEnd(callback) {
4461
4461
  this._emitter.once("end", callback);
4462
4462
  }
4463
- _pushToQueue(directory, base2) {
4464
- const queueItem = { directory, base: base2 };
4463
+ _pushToQueue(directory, base) {
4464
+ const queueItem = { directory, base };
4465
4465
  this._queue.push(queueItem, (error) => {
4466
4466
  if (error !== null) {
4467
4467
  this._handleError(error);
@@ -4488,19 +4488,19 @@ var require_async3 = __commonJS({
4488
4488
  this._isDestroyed = true;
4489
4489
  this._emitter.emit("error", error);
4490
4490
  }
4491
- _handleEntry(entry, base2) {
4491
+ _handleEntry(entry, base) {
4492
4492
  if (this._isDestroyed || this._isFatalError) {
4493
4493
  return;
4494
4494
  }
4495
4495
  const fullpath = entry.path;
4496
- if (base2 !== void 0) {
4497
- entry.path = common.joinPathSegments(base2, entry.name, this._settings.pathSegmentSeparator);
4496
+ if (base !== void 0) {
4497
+ entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
4498
4498
  }
4499
4499
  if (common.isAppliedFilter(this._settings.entryFilter, entry)) {
4500
4500
  this._emitEntry(entry);
4501
4501
  }
4502
4502
  if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) {
4503
- this._pushToQueue(fullpath, base2 === void 0 ? void 0 : entry.path);
4503
+ this._pushToQueue(fullpath, base === void 0 ? void 0 : entry.path);
4504
4504
  }
4505
4505
  }
4506
4506
  _emitEntry(entry) {
@@ -4608,19 +4608,19 @@ var require_sync3 = __commonJS({
4608
4608
  this._handleQueue();
4609
4609
  return this._storage;
4610
4610
  }
4611
- _pushToQueue(directory, base2) {
4612
- this._queue.add({ directory, base: base2 });
4611
+ _pushToQueue(directory, base) {
4612
+ this._queue.add({ directory, base });
4613
4613
  }
4614
4614
  _handleQueue() {
4615
4615
  for (const item of this._queue.values()) {
4616
4616
  this._handleDirectory(item.directory, item.base);
4617
4617
  }
4618
4618
  }
4619
- _handleDirectory(directory, base2) {
4619
+ _handleDirectory(directory, base) {
4620
4620
  try {
4621
4621
  const entries = this._scandir(directory, this._settings.fsScandirSettings);
4622
4622
  for (const entry of entries) {
4623
- this._handleEntry(entry, base2);
4623
+ this._handleEntry(entry, base);
4624
4624
  }
4625
4625
  } catch (error) {
4626
4626
  this._handleError(error);
@@ -4632,16 +4632,16 @@ var require_sync3 = __commonJS({
4632
4632
  }
4633
4633
  throw error;
4634
4634
  }
4635
- _handleEntry(entry, base2) {
4635
+ _handleEntry(entry, base) {
4636
4636
  const fullpath = entry.path;
4637
- if (base2 !== void 0) {
4638
- entry.path = common.joinPathSegments(base2, entry.name, this._settings.pathSegmentSeparator);
4637
+ if (base !== void 0) {
4638
+ entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
4639
4639
  }
4640
4640
  if (common.isAppliedFilter(this._settings.entryFilter, entry)) {
4641
4641
  this._pushToStorage(entry);
4642
4642
  }
4643
4643
  if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) {
4644
- this._pushToQueue(fullpath, base2 === void 0 ? void 0 : entry.path);
4644
+ this._pushToQueue(fullpath, base === void 0 ? void 0 : entry.path);
4645
4645
  }
4646
4646
  }
4647
4647
  _pushToStorage(entry) {
@@ -5530,14 +5530,14 @@ var require_out4 = __commonJS({
5530
5530
 
5531
5531
  // src/index.ts
5532
5532
  import { promises as fs3 } from "fs";
5533
- import process5 from "process";
5533
+ import process6 from "process";
5534
5534
  import { createUnplugin } from "unplugin";
5535
5535
 
5536
5536
  // src/core/compress.ts
5537
5537
  import fs from "fs";
5538
5538
  import path from "path";
5539
5539
  import process3 from "process";
5540
- import archiver from "archiver";
5540
+ import { Zip } from "zip-lib";
5541
5541
 
5542
5542
  // node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/ansi-styles/index.js
5543
5543
  var ANSI_BACKGROUND_OFFSET = 10;
@@ -6049,48 +6049,45 @@ var Log = class {
6049
6049
  };
6050
6050
 
6051
6051
  // src/core/compress.ts
6052
- async function createCompress(options, outDir2) {
6053
- const { ignoreBase } = options;
6054
- const zipFilePath = path.resolve(process3.cwd(), `${path.basename(outDir2)}.zip`);
6055
- Log.log("Compressing the directory", outDir2);
6056
- return new Promise((resolve, reject) => {
6057
- try {
6058
- const output = fs.createWriteStream(zipFilePath);
6059
- const archive = archiver("zip");
6060
- output.on("close", () => {
6061
- const size = archive.pointer();
6062
- const sizeInMB = size > 1024 * 1024 ? `${(size / 1024 / 1024).toFixed(1)} MB` : `${(size / 1024).toFixed(1)} KB`;
6063
- Log.success("Successfully compressed to", `${zipFilePath} (${sizeInMB})`);
6064
- resolve(null);
6065
- });
6066
- archive.on("warning", (err) => {
6067
- if (err.code === "ENOENT")
6068
- Log.log("File not found during compression:", err.message);
6069
- else
6070
- Log.log("Compression warning:", err.message);
6071
- });
6072
- archive.on("error", (err) => {
6073
- Log.error("Compression error:", err);
6074
- reject(err);
6075
- });
6076
- archive.pipe(output);
6077
- const absoluteOutDir = path.resolve(outDir2);
6078
- archive.directory(absoluteOutDir, ignoreBase ? false : path.basename(outDir2));
6079
- archive.finalize();
6080
- } catch (error) {
6081
- Log.error("Error compressing the directory", error);
6082
- throw error;
6083
- }
6084
- });
6052
+ async function createCompress(options, outDir) {
6053
+ const { includeBaseDir } = options;
6054
+ const zipFilePath = path.resolve(process3.cwd(), `${path.basename(outDir)}.zip`);
6055
+ const absoluteOutDir = path.resolve(outDir);
6056
+ Log.log("Compressing directory:", absoluteOutDir);
6057
+ try {
6058
+ const zip = new Zip();
6059
+ if (!includeBaseDir) {
6060
+ zip.addFolder(absoluteOutDir);
6061
+ } else {
6062
+ zip.addFolder(absoluteOutDir, path.basename(outDir));
6063
+ }
6064
+ await zip.archive(zipFilePath);
6065
+ const stat = fs.statSync(zipFilePath);
6066
+ const size = stat.size;
6067
+ const readableSize = size > 1024 * 1024 ? `${(size / 1024 / 1024).toFixed(1)} MB` : `${(size / 1024).toFixed(1)} KB`;
6068
+ Log.success(
6069
+ "Successfully compressed to:",
6070
+ `${zipFilePath} (${readableSize})`
6071
+ );
6072
+ return null;
6073
+ } catch (error) {
6074
+ Log.error("Compression error:", error);
6075
+ throw error;
6076
+ }
6085
6077
  }
6086
6078
 
6079
+ // src/core/options.ts
6080
+ import process5 from "process";
6081
+ import { deepMerge } from "@antfu/utils";
6082
+
6087
6083
  // src/core/generate.ts
6088
6084
  var import_fast_glob = __toESM(require_out4(), 1);
6085
+ import { execSync } from "child_process";
6089
6086
  import { promises as fs2 } from "fs";
6090
6087
  import path2 from "path";
6091
6088
  import process4 from "process";
6092
- import { getPackageInfo } from "local-pkg";
6093
- import recast from "recast";
6089
+ import * as recast from "recast";
6090
+ import tsParser from "recast/parsers/typescript";
6094
6091
  function mergeObjects(prodObj, devObj) {
6095
6092
  const prodProps = new Map(prodObj.properties.map((p) => [p.key.name || p.key.value, p]));
6096
6093
  for (const prop of devObj.properties) {
@@ -6104,33 +6101,57 @@ function mergeObjects(prodObj, devObj) {
6104
6101
  }
6105
6102
  }
6106
6103
  }
6107
- async function generateScript(options, mode, base2) {
6108
- const { dir, fileName, globalName, serve, build } = options.env;
6109
- const folder = await findFolder(process4.cwd(), dir);
6110
- const files = await (0, import_fast_glob.default)("*.+(js|ts)", {
6104
+ async function generateScript(options, context) {
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}", {
6111
6110
  absolute: true,
6112
6111
  cwd: folder
6113
6112
  });
6114
- const testReg = mode === "serve" ? serve : build;
6113
+ if (!files.length)
6114
+ throw new Error(`[unplugin-env] No config files found in ${folder}`);
6115
+ const { mode, base } = context;
6116
+ const testReg = mode === "dev" ? devMatch : buildMatch;
6115
6117
  let target = "";
6116
6118
  let source = "";
6117
6119
  let code = "";
6118
- const name = fileName;
6120
+ let targetFile = "";
6121
+ let sourceFile = "";
6122
+ const resolvedEmitFileName = resolveEmitFileName(emitDir, emitFileName);
6119
6123
  for (const file of files) {
6120
6124
  try {
6121
6125
  const mod = await fs2.readFile(file, "utf-8");
6122
- if (testReg?.test(file))
6126
+ if (testReg?.test(file)) {
6123
6127
  target = mod;
6124
- else
6128
+ targetFile = file;
6129
+ } else {
6125
6130
  source = mod;
6131
+ sourceFile = file;
6132
+ }
6126
6133
  } catch (error) {
6127
6134
  console.error(`Error loading file ${file}:`, error);
6128
6135
  }
6129
6136
  }
6130
- const targetAst = recast.parse(target);
6131
- const sourceAst = recast.parse(source);
6132
- const targetExport = targetAst.program.body.find((n) => n.type === "ExportDefaultDeclaration").declaration;
6133
- 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);
6134
6155
  mergeObjects(sourceExport, targetExport);
6135
6156
  const mergedCode = recast.print(sourceExport).code;
6136
6157
  const returnedTarget = mergedCode;
@@ -6138,56 +6159,206 @@ async function generateScript(options, mode, base2) {
6138
6159
  code = `window.${globalName}=${returnedTarget};
6139
6160
  ${versionInfo}`;
6140
6161
  const formatCode = code;
6162
+ const viteIgnoreAttr = context.framework === "vite" ? " vite-ignore" : "";
6163
+ const scriptSrc = joinBasePath(base, resolvedEmitFileName);
6141
6164
  return {
6142
6165
  code,
6143
- script: ` <script type="text/javascript" src="${base2}${fileName}"></script>
6166
+ script: ` <script type="text/javascript"${viteIgnoreAttr} src="${scriptSrc}"></script>
6144
6167
  </head>`,
6145
6168
  emit: {
6146
6169
  type: "asset",
6147
- fileName: name,
6170
+ fileName: resolvedEmitFileName,
6148
6171
  source: formatCode
6149
6172
  },
6150
6173
  watchFiles: files
6151
6174
  };
6152
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
+ }
6153
6241
  async function generateVersion(options, mode) {
6154
- const pkg = await getPackageInfo(process4.cwd());
6155
- return `console.info("Version: %c${pkg?.version}%c - ${mode === "serve" ? "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();
6156
6321
  }
6157
6322
  async function findFolder(directoryPath, dir) {
6158
6323
  const ignore = /* @__PURE__ */ new Set(["dist", "node_modules", "playground", "example", "test", "jest", "tests", "locales", "public", ".git", ".github", ".vscode"]);
6159
- const files = await fs2.readdir(directoryPath);
6160
- 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));
6161
6327
  let nestedFolder = "";
6162
- for (const file of filePaths) {
6163
- const fullFilePath = path2.join(directoryPath, file);
6164
- const stat = await fs2.stat(fullFilePath);
6165
- if (stat.isDirectory()) {
6166
- if (file.toLowerCase() === dir) {
6167
- return fullFilePath;
6168
- } else {
6169
- nestedFolder = await findFolder(fullFilePath, dir);
6170
- if (nestedFolder)
6171
- return nestedFolder;
6172
- }
6173
- }
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;
6174
6337
  }
6175
6338
  return "";
6176
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
+ }
6177
6348
 
6178
6349
  // src/core/options.ts
6179
- import { deepMerge } from "@antfu/utils";
6180
6350
  function resolveOptions(options) {
6181
6351
  const defaults = {
6182
6352
  env: {
6183
- dir: "config",
6184
- fileName: "manifest.js",
6353
+ configDir: "config",
6354
+ emitFileName: "manifest.js",
6355
+ emitDir: "",
6185
6356
  globalName: "manifest",
6186
- serve: /dev/i,
6187
- build: /prod/i
6357
+ devMatch: /dev/i,
6358
+ buildMatch: /prod/i
6188
6359
  },
6189
6360
  compress: {
6190
- ignoreBase: false
6361
+ includeBaseDir: true
6191
6362
  }
6192
6363
  };
6193
6364
  const mergeOptions = deepMerge(defaults, options);
@@ -6200,67 +6371,273 @@ function resolveOptions(options) {
6200
6371
  datetime: formatter.format(/* @__PURE__ */ new Date())
6201
6372
  };
6202
6373
  }
6374
+ function createUnifiedContext(resolved) {
6375
+ const ctx = {
6376
+ framework: "",
6377
+ base: "/",
6378
+ outDir: "dist",
6379
+ mode: "build",
6380
+ scriptInfo: {
6381
+ code: "",
6382
+ script: "",
6383
+ emit: {
6384
+ type: "asset",
6385
+ source: "",
6386
+ fileName: ""
6387
+ },
6388
+ watchFiles: []
6389
+ },
6390
+ get isDev() {
6391
+ return this.mode === "dev";
6392
+ },
6393
+ get isBuild() {
6394
+ return this.mode === "build";
6395
+ },
6396
+ // --- VITE ---
6397
+ async setVite(config) {
6398
+ this.framework = "vite";
6399
+ this.base = config.base || "/";
6400
+ this.outDir = config.build?.outDir || "dist";
6401
+ this.mode = config.command === "serve" ? "dev" : "build";
6402
+ ctx.scriptInfo = await generateScript(resolved, ctx);
6403
+ },
6404
+ // --- ROLLUP ---
6405
+ async setRollup(options) {
6406
+ this.framework = "rollup";
6407
+ this.outDir = options.dir || "dist";
6408
+ this.mode = process5.env.ROLLUP_WATCH ? "dev" : "build";
6409
+ ctx.scriptInfo = await generateScript(resolved, ctx);
6410
+ },
6411
+ // --- WEBPACK ---
6412
+ async setWebpack(compiler) {
6413
+ this.framework = "webpack";
6414
+ this.base = compiler.options.output?.publicPath || "/";
6415
+ this.outDir = compiler.options.output?.path || "dist";
6416
+ const raw = compiler.options.mode || "production";
6417
+ this.mode = raw === "development" ? "dev" : "build";
6418
+ ctx.scriptInfo = await generateScript(resolved, ctx);
6419
+ },
6420
+ // --- RSPACK ---
6421
+ async setRspack(compiler) {
6422
+ this.framework = "rspack";
6423
+ this.base = compiler.options.output?.publicPath || "/";
6424
+ this.outDir = compiler.options.output?.path || "dist";
6425
+ const raw = compiler.options.mode || "production";
6426
+ this.mode = raw === "development" ? "dev" : "build";
6427
+ ctx.scriptInfo = await generateScript(resolved, ctx);
6428
+ },
6429
+ // --- ESBUILD ---
6430
+ async setEsbuild(build) {
6431
+ this.framework = "esbuild";
6432
+ this.outDir = build.initialOptions.outdir || "dist";
6433
+ this.mode = build.initialOptions.watch ? "dev" : "build";
6434
+ ctx.scriptInfo = await generateScript(resolved, ctx);
6435
+ },
6436
+ // --- FARM ---
6437
+ async setFarm(compiler) {
6438
+ this.framework = "farm";
6439
+ this.base = compiler.config.output?.publicPath || "/";
6440
+ this.outDir = compiler.config.output?.path || "dist";
6441
+ const raw = compiler.config.mode || "production";
6442
+ this.mode = raw === "development" ? "dev" : "build";
6443
+ ctx.scriptInfo = await generateScript(resolved, ctx);
6444
+ },
6445
+ // --- ROLLDOWN ---
6446
+ async setRolldown(options) {
6447
+ this.framework = "rolldown";
6448
+ this.outDir = options.dir || "dist";
6449
+ this.mode = process5.env.ROLLDOWN_WATCH ? "dev" : "build";
6450
+ ctx.scriptInfo = await generateScript(resolved, ctx);
6451
+ }
6452
+ };
6453
+ return ctx;
6454
+ }
6203
6455
 
6204
6456
  // src/index.ts
6205
6457
  var virtualEnvId = "virtual:env";
6458
+ var virtualEnvAliasId = "virtual-env";
6206
6459
  var resolvedVirtualEnvId = `\0${virtualEnvId}`;
6207
- var base = "";
6208
- var outDir = "";
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
+ }
6209
6470
  var unpluginFactory = (options = {}) => {
6210
6471
  const resolved = resolveOptions(options);
6472
+ const ctx = createUnifiedContext(resolved);
6473
+ let frameworkReady = null;
6474
+ let legacyEmitHooked = false;
6211
6475
  return [{
6212
- name: "plugin-env-serve",
6213
- apply: "serve",
6476
+ name: "plugin-env",
6214
6477
  enforce: "post",
6215
- configResolved(config) {
6216
- outDir = config.build.outDir;
6217
- base = config.base;
6478
+ rollup: {
6479
+ async buildStart() {
6480
+ const outputOptions = { dir: ctx.outDir };
6481
+ await ctx.setRollup(outputOptions);
6482
+ },
6483
+ outputOptions(outputOptions) {
6484
+ ctx.outDir = outputOptions.dir || ctx.outDir;
6485
+ return outputOptions;
6486
+ }
6218
6487
  },
6219
- async resolveId(id) {
6220
- if (id.startsWith(virtualEnvId))
6221
- return resolvedVirtualEnvId;
6488
+ vite: {
6489
+ async configResolved(config) {
6490
+ await ctx.setVite(config);
6491
+ }
6222
6492
  },
6223
- async load(id) {
6224
- if (id.startsWith(resolvedVirtualEnvId)) {
6225
- const { code, watchFiles } = await generateScript(resolved, "serve", base);
6226
- watchFiles.forEach((file) => {
6227
- this.addWatchFile(file);
6228
- });
6229
- return code;
6493
+ async webpack(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
+ });
6567
+ },
6568
+ rspack: async (compiler) => {
6569
+ frameworkReady = ctx.setRspack(compiler);
6570
+ },
6571
+ esbuild: {
6572
+ async setup(build) {
6573
+ await ctx.setEsbuild(build);
6230
6574
  }
6231
- }
6232
- }, {
6233
- name: "unplugin-env-build",
6234
- apply: "build",
6235
- enforce: "post",
6236
- configResolved(config) {
6237
- base = config.base;
6238
- outDir = config.build.outDir;
6239
6575
  },
6240
- resolveId(id) {
6241
- if (id.startsWith(virtualEnvId))
6242
- return resolvedVirtualEnvId;
6576
+ async farm(compiler) {
6577
+ await ctx.setFarm(compiler);
6243
6578
  },
6244
- async load(id) {
6245
- const { emit, script } = await generateScript(resolved, "build", base);
6246
- if (id.startsWith(resolvedVirtualEnvId)) {
6247
- this.emitFile(emit);
6248
- return "";
6579
+ rolldown: {
6580
+ async outputOptions(outputOptions) {
6581
+ await ctx.setRolldown(outputOptions);
6249
6582
  }
6583
+ },
6584
+ async resolveId(id) {
6585
+ if (isVirtualEnvId(id))
6586
+ return resolveVirtualEnvId(id);
6587
+ },
6588
+ loadInclude(id) {
6589
+ if (isResolvedVirtualEnvId(id) || isVirtualEnvId(id))
6590
+ return true;
6250
6591
  if (id.endsWith(".html")) {
6251
- let code = await fs3.readFile(id, "utf8");
6252
- code = code.replace(/<\/head>/g, script);
6253
- return {
6254
- code
6255
- };
6592
+ return ctx.framework === "vite" || ctx.framework === "rollup" || ctx.framework === "rolldown";
6256
6593
  }
6257
- return null;
6594
+ return false;
6595
+ },
6596
+ async load(id) {
6597
+ if (frameworkReady)
6598
+ await frameworkReady;
6599
+ const { code, watchFiles, emit, script } = ctx.scriptInfo;
6600
+ if (ctx.isDev) {
6601
+ if (isResolvedVirtualEnvId(id)) {
6602
+ watchFiles.forEach((file) => {
6603
+ this.addWatchFile(file);
6604
+ });
6605
+ return code;
6606
+ }
6607
+ } else {
6608
+ if (isResolvedVirtualEnvId(id)) {
6609
+ this.emitFile(emit);
6610
+ return "";
6611
+ }
6612
+ const canTransformHtml = ctx.framework === "vite" || ctx.framework === "rollup" || ctx.framework === "rolldown";
6613
+ if (canTransformHtml && id.endsWith(".html")) {
6614
+ let code2 = await fs3.readFile(id, "utf-8");
6615
+ code2 = code2.replace(/<\/head>/g, script);
6616
+ return { code: code2 };
6617
+ }
6618
+ }
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);
6258
6631
  },
6259
6632
  buildEnd: () => {
6260
- process5.on("beforeExit", async () => {
6633
+ process6.on("beforeExit", () => {
6261
6634
  const { compress } = resolved;
6262
- await createCompress(compress, outDir);
6263
- process5.exit(0);
6635
+ createCompress(compress, ctx.outDir).then(() => {
6636
+ process6.exit(0);
6637
+ }).catch((error) => {
6638
+ process6.exitCode = 1;
6639
+ throw error;
6640
+ });
6264
6641
  });
6265
6642
  }
6266
6643
  }];