@fantasticfour/dotenvx-next 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-y_GBKt04.mjs +5 -0
- package/dist/index.cjs +3 -0
- package/dist/index.d.cts +2 -0
- package/dist/index.d.mts +2 -0
- package/dist/index.mjs +2 -0
- package/dist/init.cjs +16 -0
- package/dist/init.cjs.map +1 -0
- package/dist/init.d.cts +5 -0
- package/dist/init.d.cts.map +1 -0
- package/dist/init.d.mts +5 -0
- package/dist/init.d.mts.map +1 -0
- package/dist/init.mjs +18 -0
- package/dist/init.mjs.map +1 -0
- package/dist/next-env-compat.cjs +11866 -0
- package/dist/next-env-compat.cjs.map +1 -0
- package/dist/next-env-compat.d.cts +1 -0
- package/dist/plugin.cjs +98 -0
- package/dist/plugin.cjs.map +1 -0
- package/dist/plugin.d.cts +26 -0
- package/dist/plugin.d.cts.map +1 -0
- package/dist/plugin.d.mts +26 -0
- package/dist/plugin.d.mts.map +1 -0
- package/dist/plugin.mjs +96 -0
- package/dist/plugin.mjs.map +1 -0
- package/dist/turbopack-inject-BgCxanwa.cjs +139 -0
- package/dist/turbopack-inject-BgCxanwa.cjs.map +1 -0
- package/dist/turbopack-inject.cjs +5 -0
- package/dist/turbopack-inject.d.cts +23 -0
- package/dist/turbopack-inject.d.cts.map +1 -0
- package/dist/turbopack-inject.d.mts +23 -0
- package/dist/turbopack-inject.d.mts.map +1 -0
- package/dist/turbopack-inject.mjs +92 -0
- package/dist/turbopack-inject.mjs.map +1 -0
- package/dist/webpack-plugin.cjs +52 -0
- package/dist/webpack-plugin.cjs.map +1 -0
- package/dist/webpack-plugin.d.cts +27 -0
- package/dist/webpack-plugin.d.cts.map +1 -0
- package/dist/webpack-plugin.d.mts +27 -0
- package/dist/webpack-plugin.d.mts.map +1 -0
- package/dist/webpack-plugin.mjs +52 -0
- package/dist/webpack-plugin.mjs.map +1 -0
- package/package.json +68 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { };
|
package/dist/plugin.cjs
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_turbopack_inject = require("./turbopack-inject-BgCxanwa.cjs");
|
|
3
|
+
const require_webpack_plugin = require("./webpack-plugin.cjs");
|
|
4
|
+
let node_fs = require("node:fs");
|
|
5
|
+
node_fs = require_turbopack_inject.__toESM(node_fs, 1);
|
|
6
|
+
let node_path = require("node:path");
|
|
7
|
+
node_path = require_turbopack_inject.__toESM(node_path, 1);
|
|
8
|
+
//#region src/plugin.ts
|
|
9
|
+
/**
|
|
10
|
+
* withDotenvx() — Next.js config wrapper that ensures dotenvx secrets are loaded
|
|
11
|
+
* before any user code evaluates (Prisma Pool, etc.) at module-load time.
|
|
12
|
+
*
|
|
13
|
+
* Strategy:
|
|
14
|
+
* - Webpack builds: injects a dotenvx init bundle into webpack-runtime.js via
|
|
15
|
+
* DotenvxWebpackPlugin (processAssets hook at PROCESS_ASSETS_STAGE_ADDITIONS).
|
|
16
|
+
* - Turbopack builds: patches fs.writeFile to detect compilation completion and
|
|
17
|
+
* prepend the init bundle into [turbopack]_runtime.js files.
|
|
18
|
+
* - Also aliases @next/env → @fantasticfour/dotenvx-next/next-env so dotenvx
|
|
19
|
+
* secrets are available during Next.js config evaluation itself.
|
|
20
|
+
*/
|
|
21
|
+
const DEFAULT_ENV_FILES = [
|
|
22
|
+
".env.base",
|
|
23
|
+
".env.production",
|
|
24
|
+
".env.preview"
|
|
25
|
+
];
|
|
26
|
+
const PLUGIN_DEBUG = !!process.env.DEBUG_DOTENVX_NEXT;
|
|
27
|
+
function debugLog(...args) {
|
|
28
|
+
if (!PLUGIN_DEBUG) return;
|
|
29
|
+
console.log("[dotenvx-next]", ...args);
|
|
30
|
+
}
|
|
31
|
+
function resolveExistingFiles(files, envDir) {
|
|
32
|
+
return files.map((f) => node_path.default.resolve(envDir, f)).filter((absPath) => node_fs.default.existsSync(absPath));
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Load the compiled init bundle source. This is the CJS bundle from dist/init.cjs
|
|
36
|
+
* that will be prepended into webpack/turbopack runtime files.
|
|
37
|
+
*/
|
|
38
|
+
function loadInitSource() {
|
|
39
|
+
try {
|
|
40
|
+
return require("node:fs").readFileSync(require.resolve("./init.cjs"), "utf8");
|
|
41
|
+
} catch {
|
|
42
|
+
const pkgRoot = node_path.default.resolve(new URL(require("url").pathToFileURL(__filename).href).pathname, "../../");
|
|
43
|
+
return node_fs.default.readFileSync(node_path.default.join(pkgRoot, "dist", "init.cjs"), "utf8");
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
async function dotenvxNextConfigFn(nextConfig, options, phase, defaults) {
|
|
47
|
+
let resolvedNextConfig;
|
|
48
|
+
if (typeof nextConfig === "function") resolvedNextConfig = { ...await nextConfig(phase, defaults) };
|
|
49
|
+
else resolvedNextConfig = { ...nextConfig };
|
|
50
|
+
const envDir = options.envDir ?? process.cwd();
|
|
51
|
+
const resolvedFiles = resolveExistingFiles(options.files ?? DEFAULT_ENV_FILES, envDir);
|
|
52
|
+
const shouldTrace = options.traceEnvFiles !== false;
|
|
53
|
+
const isTurbopack = !!(process.env.TURBOPACK || process.env.TURBOPACK_DEV || process.env.TURBOPACK_BUILD || process.env.npm_config_turbopack);
|
|
54
|
+
debugLog(`phase=${phase}, isTurbopack=${isTurbopack}, resolvedFiles=${JSON.stringify(resolvedFiles)}`);
|
|
55
|
+
if (shouldTrace && resolvedFiles.length > 0) {
|
|
56
|
+
resolvedNextConfig.outputFileTracingIncludes ??= {};
|
|
57
|
+
const tracing = resolvedNextConfig.outputFileTracingIncludes;
|
|
58
|
+
const catchAll = "/**";
|
|
59
|
+
const existing = tracing[catchAll];
|
|
60
|
+
if (Array.isArray(existing)) tracing[catchAll] = [...existing, ...resolvedFiles];
|
|
61
|
+
else tracing[catchAll] = resolvedFiles;
|
|
62
|
+
}
|
|
63
|
+
if (isTurbopack) try {
|
|
64
|
+
require_turbopack_inject.activateTurbopackInjection(loadInitSource());
|
|
65
|
+
} catch (err) {
|
|
66
|
+
console.warn("[dotenvx-next] Could not load init bundle for turbopack injection:", err);
|
|
67
|
+
}
|
|
68
|
+
const prevWebpack = resolvedNextConfig.webpack;
|
|
69
|
+
resolvedNextConfig.webpack = (webpackConfig, webpackOptions) => {
|
|
70
|
+
const config = prevWebpack ? prevWebpack(webpackConfig, webpackOptions) : webpackConfig;
|
|
71
|
+
config.resolve ??= {};
|
|
72
|
+
config.resolve.alias ??= {};
|
|
73
|
+
const alias = config.resolve.alias;
|
|
74
|
+
try {
|
|
75
|
+
alias["@next/env"] = require.resolve("@fantasticfour/dotenvx-next/next-env");
|
|
76
|
+
} catch {
|
|
77
|
+
debugLog("Could not resolve @fantasticfour/dotenvx-next/next-env for alias — skipping");
|
|
78
|
+
}
|
|
79
|
+
if (!isTurbopack) try {
|
|
80
|
+
const plugin = new require_webpack_plugin.DotenvxWebpackPlugin({
|
|
81
|
+
files: resolvedFiles,
|
|
82
|
+
initSource: loadInitSource()
|
|
83
|
+
});
|
|
84
|
+
config.plugins.push(plugin);
|
|
85
|
+
} catch (err) {
|
|
86
|
+
console.warn("[dotenvx-next] Could not load init bundle for webpack injection:", err);
|
|
87
|
+
}
|
|
88
|
+
return config;
|
|
89
|
+
};
|
|
90
|
+
return resolvedNextConfig;
|
|
91
|
+
}
|
|
92
|
+
function withDotenvx(nextConfig, options = {}) {
|
|
93
|
+
return (phase, defaults) => dotenvxNextConfigFn(nextConfig, options, phase, defaults);
|
|
94
|
+
}
|
|
95
|
+
//#endregion
|
|
96
|
+
exports.withDotenvx = withDotenvx;
|
|
97
|
+
|
|
98
|
+
//# sourceMappingURL=plugin.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plugin.cjs","names":["path","fs","DotenvxWebpackPlugin"],"sources":["../src/plugin.ts"],"sourcesContent":["/**\n * withDotenvx() — Next.js config wrapper that ensures dotenvx secrets are loaded\n * before any user code evaluates (Prisma Pool, etc.) at module-load time.\n *\n * Strategy:\n * - Webpack builds: injects a dotenvx init bundle into webpack-runtime.js via\n * DotenvxWebpackPlugin (processAssets hook at PROCESS_ASSETS_STAGE_ADDITIONS).\n * - Turbopack builds: patches fs.writeFile to detect compilation completion and\n * prepend the init bundle into [turbopack]_runtime.js files.\n * - Also aliases @next/env → @fantasticfour/dotenvx-next/next-env so dotenvx\n * secrets are available during Next.js config evaluation itself.\n */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { NextConfig } from 'next';\nimport { DotenvxWebpackPlugin } from './webpack-plugin.js';\nimport { activateTurbopackInjection } from './turbopack-inject.js';\n\nexport interface DotenvxNextOptions {\n /**\n * Env files to load. Defaults to ['.env.base', '.env.production', '.env.preview'],\n * filtered to files that actually exist in envDir.\n */\n files?: string[];\n\n /**\n * Directory where env files live. Defaults to process.cwd().\n */\n envDir?: string;\n\n /**\n * Add resolved env files to outputFileTracingIncludes so Vercel traces them\n * into the serverless function bundle. Default: true.\n */\n traceEnvFiles?: boolean;\n}\n\nconst DEFAULT_ENV_FILES = ['.env.base', '.env.production', '.env.preview'];\n\nconst PLUGIN_DEBUG = !!process.env.DEBUG_DOTENVX_NEXT;\n\nfunction debugLog(...args: unknown[]): void {\n if (!PLUGIN_DEBUG) return;\n console.log('[dotenvx-next]', ...args);\n}\n\nfunction resolveExistingFiles(files: string[], envDir: string): string[] {\n return files\n .map((f) => path.resolve(envDir, f))\n .filter((absPath) => fs.existsSync(absPath));\n}\n\n/**\n * Load the compiled init bundle source. This is the CJS bundle from dist/init.cjs\n * that will be prepended into webpack/turbopack runtime files.\n */\nfunction loadInitSource(): string {\n // During builds, __dirname is the dist directory (CJS output) or src (dev).\n // We resolve relative to this file's location at runtime.\n try {\n // Explicitly resolve init.cjs — not './init', which in a \"type\":\"module\" package\n // resolves to init.js (ESM) even from a CJS context, causing import-in-IIFE errors.\n return require('node:fs').readFileSync(\n require.resolve('./init.cjs'),\n 'utf8'\n ) as string;\n } catch {\n // Fallback: resolve from package root\n const pkgRoot = path.resolve(new URL(import.meta.url).pathname, '../../');\n return fs.readFileSync(path.join(pkgRoot, 'dist', 'init.cjs'), 'utf8');\n }\n}\n\ntype NextConfigFn = (\n phase: string,\n defaults: { defaultConfig: NextConfig }\n) => NextConfig | Promise<NextConfig>;\n\nasync function dotenvxNextConfigFn(\n nextConfig: NextConfig | NextConfigFn,\n options: DotenvxNextOptions,\n phase: string,\n defaults: { defaultConfig: NextConfig }\n): Promise<NextConfig> {\n let resolvedNextConfig: NextConfig;\n\n if (typeof nextConfig === 'function') {\n resolvedNextConfig = {\n ...(await (nextConfig as NextConfigFn)(phase, defaults)),\n };\n } else {\n // Shallow-copy so we never mutate the frozen original config object\n resolvedNextConfig = { ...nextConfig };\n }\n\n const envDir = options.envDir ?? process.cwd();\n const fileNames = options.files ?? DEFAULT_ENV_FILES;\n const resolvedFiles = resolveExistingFiles(fileNames, envDir);\n const shouldTrace = options.traceEnvFiles !== false;\n\n // Detect turbopack (Next 16+ uses it by default in dev)\n const isTurbopack = !!(\n process.env.TURBOPACK ||\n process.env.TURBOPACK_DEV ||\n process.env.TURBOPACK_BUILD ||\n process.env.npm_config_turbopack\n );\n\n debugLog(\n `phase=${phase}, isTurbopack=${isTurbopack}, resolvedFiles=${JSON.stringify(resolvedFiles)}`\n );\n\n // Add env files to outputFileTracingIncludes so Vercel traces them into Lambda\n // Note: outputFileTracingIncludes moved from experimental to top-level in Next 16\n if (shouldTrace && resolvedFiles.length > 0) {\n resolvedNextConfig.outputFileTracingIncludes ??= {};\n\n const tracing = resolvedNextConfig.outputFileTracingIncludes;\n // Apply to all server routes\n const catchAll = '/**';\n const existing = tracing[catchAll];\n if (Array.isArray(existing)) {\n tracing[catchAll] = [...existing, ...resolvedFiles];\n } else {\n tracing[catchAll] = resolvedFiles;\n }\n }\n\n if (isTurbopack) {\n // Turbopack: activate fs intercept to inject init bundle when compilation finishes\n try {\n const initSource = loadInitSource();\n activateTurbopackInjection(initSource);\n } catch (err) {\n console.warn(\n '[dotenvx-next] Could not load init bundle for turbopack injection:',\n err\n );\n }\n }\n\n // Extend webpack config (used for non-turbopack builds and edge runtime)\n const prevWebpack = resolvedNextConfig.webpack;\n\n resolvedNextConfig.webpack = (webpackConfig, webpackOptions) => {\n // Apply user's existing webpack customizations first\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n const config = prevWebpack\n ? prevWebpack(webpackConfig, webpackOptions)\n : webpackConfig;\n\n // Alias @next/env to our drop-in replacement so dotenvx.config() is called\n // during Next's own env loading phase\n config.resolve ??= {};\n (config.resolve as Record<string, unknown>).alias ??= {};\n const alias = (config.resolve as Record<string, unknown>).alias as Record<\n string,\n string\n >;\n\n // Use require.resolve so this works from the dist directory\n try {\n alias['@next/env'] = require.resolve(\n '@fantasticfour/dotenvx-next/next-env'\n );\n } catch {\n // If the package isn't installed under that name (e.g. local dev), skip alias\n debugLog(\n 'Could not resolve @fantasticfour/dotenvx-next/next-env for alias — skipping'\n );\n }\n\n // Register the webpack plugin to inject init bundle into runtime files\n if (!isTurbopack) {\n try {\n const initSource = loadInitSource();\n const plugin = new DotenvxWebpackPlugin({\n files: resolvedFiles,\n initSource,\n });\n (config.plugins as unknown[]).push(plugin);\n } catch (err) {\n console.warn(\n '[dotenvx-next] Could not load init bundle for webpack injection:',\n err\n );\n }\n }\n\n return config;\n };\n\n return resolvedNextConfig;\n}\n\nexport function withDotenvx(\n nextConfig: NextConfig | NextConfigFn,\n options: DotenvxNextOptions = {}\n): NextConfigFn {\n return (phase: string, defaults: { defaultConfig: NextConfig }) =>\n dotenvxNextConfigFn(nextConfig, options, phase, defaults);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,oBAAoB;CAAC;CAAa;CAAmB;CAAe;AAE1E,MAAM,eAAe,CAAC,CAAC,QAAQ,IAAI;AAEnC,SAAS,SAAS,GAAG,MAAuB;AAC1C,KAAI,CAAC,aAAc;AACnB,SAAQ,IAAI,kBAAkB,GAAG,KAAK;;AAGxC,SAAS,qBAAqB,OAAiB,QAA0B;AACvE,QAAO,MACJ,KAAK,MAAMA,UAAAA,QAAK,QAAQ,QAAQ,EAAE,CAAC,CACnC,QAAQ,YAAYC,QAAAA,QAAG,WAAW,QAAQ,CAAC;;;;;;AAOhD,SAAS,iBAAyB;AAGhC,KAAI;AAGF,SAAO,QAAQ,UAAU,CAAC,aACxB,QAAQ,QAAQ,aAAa,EAC7B,OACD;SACK;EAEN,MAAM,UAAUD,UAAAA,QAAK,QAAQ,IAAI,IAAA,QAAA,MAAA,CAAA,cAAA,WAAA,CAAA,KAAoB,CAAC,UAAU,SAAS;AACzE,SAAOC,QAAAA,QAAG,aAAaD,UAAAA,QAAK,KAAK,SAAS,QAAQ,WAAW,EAAE,OAAO;;;AAS1E,eAAe,oBACb,YACA,SACA,OACA,UACqB;CACrB,IAAI;AAEJ,KAAI,OAAO,eAAe,WACxB,sBAAqB,EACnB,GAAI,MAAO,WAA4B,OAAO,SAAS,EACxD;KAGD,sBAAqB,EAAE,GAAG,YAAY;CAGxC,MAAM,SAAS,QAAQ,UAAU,QAAQ,KAAK;CAE9C,MAAM,gBAAgB,qBADJ,QAAQ,SAAS,mBACmB,OAAO;CAC7D,MAAM,cAAc,QAAQ,kBAAkB;CAG9C,MAAM,cAAc,CAAC,EACnB,QAAQ,IAAI,aACZ,QAAQ,IAAI,iBACZ,QAAQ,IAAI,mBACZ,QAAQ,IAAI;AAGd,UACE,SAAS,MAAM,gBAAgB,YAAY,kBAAkB,KAAK,UAAU,cAAc,GAC3F;AAID,KAAI,eAAe,cAAc,SAAS,GAAG;AAC3C,qBAAmB,8BAA8B,EAAE;EAEnD,MAAM,UAAU,mBAAmB;EAEnC,MAAM,WAAW;EACjB,MAAM,WAAW,QAAQ;AACzB,MAAI,MAAM,QAAQ,SAAS,CACzB,SAAQ,YAAY,CAAC,GAAG,UAAU,GAAG,cAAc;MAEnD,SAAQ,YAAY;;AAIxB,KAAI,YAEF,KAAI;AAEF,2BAAA,2BADmB,gBACkB,CAAC;UAC/B,KAAK;AACZ,UAAQ,KACN,sEACA,IACD;;CAKL,MAAM,cAAc,mBAAmB;AAEvC,oBAAmB,WAAW,eAAe,mBAAmB;EAG9D,MAAM,SAAS,cACX,YAAY,eAAe,eAAe,GAC1C;AAIJ,SAAO,YAAY,EAAE;AACpB,SAAO,QAAoC,UAAU,EAAE;EACxD,MAAM,QAAS,OAAO,QAAoC;AAM1D,MAAI;AACF,SAAM,eAAe,QAAQ,QAC3B,uCACD;UACK;AAEN,YACE,8EACD;;AAIH,MAAI,CAAC,YACH,KAAI;GAEF,MAAM,SAAS,IAAIE,uBAAAA,qBAAqB;IACtC,OAAO;IACP,YAHiB,gBAGP;IACX,CAAC;AACD,UAAO,QAAsB,KAAK,OAAO;WACnC,KAAK;AACZ,WAAQ,KACN,oEACA,IACD;;AAIL,SAAO;;AAGT,QAAO;;AAGT,SAAgB,YACd,YACA,UAA8B,EAAE,EAClB;AACd,SAAQ,OAAe,aACrB,oBAAoB,YAAY,SAAS,OAAO,SAAS"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { NextConfig } from "next";
|
|
2
|
+
|
|
3
|
+
//#region src/plugin.d.ts
|
|
4
|
+
interface DotenvxNextOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Env files to load. Defaults to ['.env.base', '.env.production', '.env.preview'],
|
|
7
|
+
* filtered to files that actually exist in envDir.
|
|
8
|
+
*/
|
|
9
|
+
files?: string[];
|
|
10
|
+
/**
|
|
11
|
+
* Directory where env files live. Defaults to process.cwd().
|
|
12
|
+
*/
|
|
13
|
+
envDir?: string;
|
|
14
|
+
/**
|
|
15
|
+
* Add resolved env files to outputFileTracingIncludes so Vercel traces them
|
|
16
|
+
* into the serverless function bundle. Default: true.
|
|
17
|
+
*/
|
|
18
|
+
traceEnvFiles?: boolean;
|
|
19
|
+
}
|
|
20
|
+
type NextConfigFn = (phase: string, defaults: {
|
|
21
|
+
defaultConfig: NextConfig;
|
|
22
|
+
}) => NextConfig | Promise<NextConfig>;
|
|
23
|
+
declare function withDotenvx(nextConfig: NextConfig | NextConfigFn, options?: DotenvxNextOptions): NextConfigFn;
|
|
24
|
+
//#endregion
|
|
25
|
+
export { DotenvxNextOptions, withDotenvx };
|
|
26
|
+
//# sourceMappingURL=plugin.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plugin.d.cts","names":[],"sources":["../src/plugin.ts"],"mappings":";;;UAmBiB,kBAAA;;;;;EAKf,KAAA;EAqDuB;;;EAhDvB,MAAA;EA+C2B;;;;EAzC3B,aAAA;AAAA;AAAA,KAuCG,YAAA,IACH,KAAA,UACA,QAAA;EAAY,aAAA,EAAe,UAAA;AAAA,MACxB,UAAA,GAAa,OAAA,CAAQ,UAAA;AAAA,iBAuHV,WAAA,CACd,UAAA,EAAY,UAAA,GAAa,YAAA,EACzB,OAAA,GAAS,kBAAA,GACR,YAAA"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { NextConfig } from "next";
|
|
2
|
+
|
|
3
|
+
//#region src/plugin.d.ts
|
|
4
|
+
interface DotenvxNextOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Env files to load. Defaults to ['.env.base', '.env.production', '.env.preview'],
|
|
7
|
+
* filtered to files that actually exist in envDir.
|
|
8
|
+
*/
|
|
9
|
+
files?: string[];
|
|
10
|
+
/**
|
|
11
|
+
* Directory where env files live. Defaults to process.cwd().
|
|
12
|
+
*/
|
|
13
|
+
envDir?: string;
|
|
14
|
+
/**
|
|
15
|
+
* Add resolved env files to outputFileTracingIncludes so Vercel traces them
|
|
16
|
+
* into the serverless function bundle. Default: true.
|
|
17
|
+
*/
|
|
18
|
+
traceEnvFiles?: boolean;
|
|
19
|
+
}
|
|
20
|
+
type NextConfigFn = (phase: string, defaults: {
|
|
21
|
+
defaultConfig: NextConfig;
|
|
22
|
+
}) => NextConfig | Promise<NextConfig>;
|
|
23
|
+
declare function withDotenvx(nextConfig: NextConfig | NextConfigFn, options?: DotenvxNextOptions): NextConfigFn;
|
|
24
|
+
//#endregion
|
|
25
|
+
export { DotenvxNextOptions, withDotenvx };
|
|
26
|
+
//# sourceMappingURL=plugin.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plugin.d.mts","names":[],"sources":["../src/plugin.ts"],"mappings":";;;UAmBiB,kBAAA;;;;;EAKf,KAAA;EAqDuB;;;EAhDvB,MAAA;EA+C2B;;;;EAzC3B,aAAA;AAAA;AAAA,KAuCG,YAAA,IACH,KAAA,UACA,QAAA;EAAY,aAAA,EAAe,UAAA;AAAA,MACxB,UAAA,GAAa,OAAA,CAAQ,UAAA;AAAA,iBAuHV,WAAA,CACd,UAAA,EAAY,UAAA,GAAa,YAAA,EACzB,OAAA,GAAS,kBAAA,GACR,YAAA"}
|
package/dist/plugin.mjs
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { t as __require } from "./chunk-y_GBKt04.mjs";
|
|
2
|
+
import { DotenvxWebpackPlugin } from "./webpack-plugin.mjs";
|
|
3
|
+
import { activateTurbopackInjection } from "./turbopack-inject.mjs";
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
//#region src/plugin.ts
|
|
7
|
+
/**
|
|
8
|
+
* withDotenvx() — Next.js config wrapper that ensures dotenvx secrets are loaded
|
|
9
|
+
* before any user code evaluates (Prisma Pool, etc.) at module-load time.
|
|
10
|
+
*
|
|
11
|
+
* Strategy:
|
|
12
|
+
* - Webpack builds: injects a dotenvx init bundle into webpack-runtime.js via
|
|
13
|
+
* DotenvxWebpackPlugin (processAssets hook at PROCESS_ASSETS_STAGE_ADDITIONS).
|
|
14
|
+
* - Turbopack builds: patches fs.writeFile to detect compilation completion and
|
|
15
|
+
* prepend the init bundle into [turbopack]_runtime.js files.
|
|
16
|
+
* - Also aliases @next/env → @fantasticfour/dotenvx-next/next-env so dotenvx
|
|
17
|
+
* secrets are available during Next.js config evaluation itself.
|
|
18
|
+
*/
|
|
19
|
+
const DEFAULT_ENV_FILES = [
|
|
20
|
+
".env.base",
|
|
21
|
+
".env.production",
|
|
22
|
+
".env.preview"
|
|
23
|
+
];
|
|
24
|
+
const PLUGIN_DEBUG = !!process.env.DEBUG_DOTENVX_NEXT;
|
|
25
|
+
function debugLog(...args) {
|
|
26
|
+
if (!PLUGIN_DEBUG) return;
|
|
27
|
+
console.log("[dotenvx-next]", ...args);
|
|
28
|
+
}
|
|
29
|
+
function resolveExistingFiles(files, envDir) {
|
|
30
|
+
return files.map((f) => path.resolve(envDir, f)).filter((absPath) => fs.existsSync(absPath));
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Load the compiled init bundle source. This is the CJS bundle from dist/init.cjs
|
|
34
|
+
* that will be prepended into webpack/turbopack runtime files.
|
|
35
|
+
*/
|
|
36
|
+
function loadInitSource() {
|
|
37
|
+
try {
|
|
38
|
+
return __require("node:fs").readFileSync(__require.resolve("./init.cjs"), "utf8");
|
|
39
|
+
} catch {
|
|
40
|
+
const pkgRoot = path.resolve(new URL(import.meta.url).pathname, "../../");
|
|
41
|
+
return fs.readFileSync(path.join(pkgRoot, "dist", "init.cjs"), "utf8");
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
async function dotenvxNextConfigFn(nextConfig, options, phase, defaults) {
|
|
45
|
+
let resolvedNextConfig;
|
|
46
|
+
if (typeof nextConfig === "function") resolvedNextConfig = { ...await nextConfig(phase, defaults) };
|
|
47
|
+
else resolvedNextConfig = { ...nextConfig };
|
|
48
|
+
const envDir = options.envDir ?? process.cwd();
|
|
49
|
+
const resolvedFiles = resolveExistingFiles(options.files ?? DEFAULT_ENV_FILES, envDir);
|
|
50
|
+
const shouldTrace = options.traceEnvFiles !== false;
|
|
51
|
+
const isTurbopack = !!(process.env.TURBOPACK || process.env.TURBOPACK_DEV || process.env.TURBOPACK_BUILD || process.env.npm_config_turbopack);
|
|
52
|
+
debugLog(`phase=${phase}, isTurbopack=${isTurbopack}, resolvedFiles=${JSON.stringify(resolvedFiles)}`);
|
|
53
|
+
if (shouldTrace && resolvedFiles.length > 0) {
|
|
54
|
+
resolvedNextConfig.outputFileTracingIncludes ??= {};
|
|
55
|
+
const tracing = resolvedNextConfig.outputFileTracingIncludes;
|
|
56
|
+
const catchAll = "/**";
|
|
57
|
+
const existing = tracing[catchAll];
|
|
58
|
+
if (Array.isArray(existing)) tracing[catchAll] = [...existing, ...resolvedFiles];
|
|
59
|
+
else tracing[catchAll] = resolvedFiles;
|
|
60
|
+
}
|
|
61
|
+
if (isTurbopack) try {
|
|
62
|
+
activateTurbopackInjection(loadInitSource());
|
|
63
|
+
} catch (err) {
|
|
64
|
+
console.warn("[dotenvx-next] Could not load init bundle for turbopack injection:", err);
|
|
65
|
+
}
|
|
66
|
+
const prevWebpack = resolvedNextConfig.webpack;
|
|
67
|
+
resolvedNextConfig.webpack = (webpackConfig, webpackOptions) => {
|
|
68
|
+
const config = prevWebpack ? prevWebpack(webpackConfig, webpackOptions) : webpackConfig;
|
|
69
|
+
config.resolve ??= {};
|
|
70
|
+
config.resolve.alias ??= {};
|
|
71
|
+
const alias = config.resolve.alias;
|
|
72
|
+
try {
|
|
73
|
+
alias["@next/env"] = __require.resolve("@fantasticfour/dotenvx-next/next-env");
|
|
74
|
+
} catch {
|
|
75
|
+
debugLog("Could not resolve @fantasticfour/dotenvx-next/next-env for alias — skipping");
|
|
76
|
+
}
|
|
77
|
+
if (!isTurbopack) try {
|
|
78
|
+
const plugin = new DotenvxWebpackPlugin({
|
|
79
|
+
files: resolvedFiles,
|
|
80
|
+
initSource: loadInitSource()
|
|
81
|
+
});
|
|
82
|
+
config.plugins.push(plugin);
|
|
83
|
+
} catch (err) {
|
|
84
|
+
console.warn("[dotenvx-next] Could not load init bundle for webpack injection:", err);
|
|
85
|
+
}
|
|
86
|
+
return config;
|
|
87
|
+
};
|
|
88
|
+
return resolvedNextConfig;
|
|
89
|
+
}
|
|
90
|
+
function withDotenvx(nextConfig, options = {}) {
|
|
91
|
+
return (phase, defaults) => dotenvxNextConfigFn(nextConfig, options, phase, defaults);
|
|
92
|
+
}
|
|
93
|
+
//#endregion
|
|
94
|
+
export { withDotenvx };
|
|
95
|
+
|
|
96
|
+
//# sourceMappingURL=plugin.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plugin.mjs","names":[],"sources":["../src/plugin.ts"],"sourcesContent":["/**\n * withDotenvx() — Next.js config wrapper that ensures dotenvx secrets are loaded\n * before any user code evaluates (Prisma Pool, etc.) at module-load time.\n *\n * Strategy:\n * - Webpack builds: injects a dotenvx init bundle into webpack-runtime.js via\n * DotenvxWebpackPlugin (processAssets hook at PROCESS_ASSETS_STAGE_ADDITIONS).\n * - Turbopack builds: patches fs.writeFile to detect compilation completion and\n * prepend the init bundle into [turbopack]_runtime.js files.\n * - Also aliases @next/env → @fantasticfour/dotenvx-next/next-env so dotenvx\n * secrets are available during Next.js config evaluation itself.\n */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { NextConfig } from 'next';\nimport { DotenvxWebpackPlugin } from './webpack-plugin.js';\nimport { activateTurbopackInjection } from './turbopack-inject.js';\n\nexport interface DotenvxNextOptions {\n /**\n * Env files to load. Defaults to ['.env.base', '.env.production', '.env.preview'],\n * filtered to files that actually exist in envDir.\n */\n files?: string[];\n\n /**\n * Directory where env files live. Defaults to process.cwd().\n */\n envDir?: string;\n\n /**\n * Add resolved env files to outputFileTracingIncludes so Vercel traces them\n * into the serverless function bundle. Default: true.\n */\n traceEnvFiles?: boolean;\n}\n\nconst DEFAULT_ENV_FILES = ['.env.base', '.env.production', '.env.preview'];\n\nconst PLUGIN_DEBUG = !!process.env.DEBUG_DOTENVX_NEXT;\n\nfunction debugLog(...args: unknown[]): void {\n if (!PLUGIN_DEBUG) return;\n console.log('[dotenvx-next]', ...args);\n}\n\nfunction resolveExistingFiles(files: string[], envDir: string): string[] {\n return files\n .map((f) => path.resolve(envDir, f))\n .filter((absPath) => fs.existsSync(absPath));\n}\n\n/**\n * Load the compiled init bundle source. This is the CJS bundle from dist/init.cjs\n * that will be prepended into webpack/turbopack runtime files.\n */\nfunction loadInitSource(): string {\n // During builds, __dirname is the dist directory (CJS output) or src (dev).\n // We resolve relative to this file's location at runtime.\n try {\n // Explicitly resolve init.cjs — not './init', which in a \"type\":\"module\" package\n // resolves to init.js (ESM) even from a CJS context, causing import-in-IIFE errors.\n return require('node:fs').readFileSync(\n require.resolve('./init.cjs'),\n 'utf8'\n ) as string;\n } catch {\n // Fallback: resolve from package root\n const pkgRoot = path.resolve(new URL(import.meta.url).pathname, '../../');\n return fs.readFileSync(path.join(pkgRoot, 'dist', 'init.cjs'), 'utf8');\n }\n}\n\ntype NextConfigFn = (\n phase: string,\n defaults: { defaultConfig: NextConfig }\n) => NextConfig | Promise<NextConfig>;\n\nasync function dotenvxNextConfigFn(\n nextConfig: NextConfig | NextConfigFn,\n options: DotenvxNextOptions,\n phase: string,\n defaults: { defaultConfig: NextConfig }\n): Promise<NextConfig> {\n let resolvedNextConfig: NextConfig;\n\n if (typeof nextConfig === 'function') {\n resolvedNextConfig = {\n ...(await (nextConfig as NextConfigFn)(phase, defaults)),\n };\n } else {\n // Shallow-copy so we never mutate the frozen original config object\n resolvedNextConfig = { ...nextConfig };\n }\n\n const envDir = options.envDir ?? process.cwd();\n const fileNames = options.files ?? DEFAULT_ENV_FILES;\n const resolvedFiles = resolveExistingFiles(fileNames, envDir);\n const shouldTrace = options.traceEnvFiles !== false;\n\n // Detect turbopack (Next 16+ uses it by default in dev)\n const isTurbopack = !!(\n process.env.TURBOPACK ||\n process.env.TURBOPACK_DEV ||\n process.env.TURBOPACK_BUILD ||\n process.env.npm_config_turbopack\n );\n\n debugLog(\n `phase=${phase}, isTurbopack=${isTurbopack}, resolvedFiles=${JSON.stringify(resolvedFiles)}`\n );\n\n // Add env files to outputFileTracingIncludes so Vercel traces them into Lambda\n // Note: outputFileTracingIncludes moved from experimental to top-level in Next 16\n if (shouldTrace && resolvedFiles.length > 0) {\n resolvedNextConfig.outputFileTracingIncludes ??= {};\n\n const tracing = resolvedNextConfig.outputFileTracingIncludes;\n // Apply to all server routes\n const catchAll = '/**';\n const existing = tracing[catchAll];\n if (Array.isArray(existing)) {\n tracing[catchAll] = [...existing, ...resolvedFiles];\n } else {\n tracing[catchAll] = resolvedFiles;\n }\n }\n\n if (isTurbopack) {\n // Turbopack: activate fs intercept to inject init bundle when compilation finishes\n try {\n const initSource = loadInitSource();\n activateTurbopackInjection(initSource);\n } catch (err) {\n console.warn(\n '[dotenvx-next] Could not load init bundle for turbopack injection:',\n err\n );\n }\n }\n\n // Extend webpack config (used for non-turbopack builds and edge runtime)\n const prevWebpack = resolvedNextConfig.webpack;\n\n resolvedNextConfig.webpack = (webpackConfig, webpackOptions) => {\n // Apply user's existing webpack customizations first\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n const config = prevWebpack\n ? prevWebpack(webpackConfig, webpackOptions)\n : webpackConfig;\n\n // Alias @next/env to our drop-in replacement so dotenvx.config() is called\n // during Next's own env loading phase\n config.resolve ??= {};\n (config.resolve as Record<string, unknown>).alias ??= {};\n const alias = (config.resolve as Record<string, unknown>).alias as Record<\n string,\n string\n >;\n\n // Use require.resolve so this works from the dist directory\n try {\n alias['@next/env'] = require.resolve(\n '@fantasticfour/dotenvx-next/next-env'\n );\n } catch {\n // If the package isn't installed under that name (e.g. local dev), skip alias\n debugLog(\n 'Could not resolve @fantasticfour/dotenvx-next/next-env for alias — skipping'\n );\n }\n\n // Register the webpack plugin to inject init bundle into runtime files\n if (!isTurbopack) {\n try {\n const initSource = loadInitSource();\n const plugin = new DotenvxWebpackPlugin({\n files: resolvedFiles,\n initSource,\n });\n (config.plugins as unknown[]).push(plugin);\n } catch (err) {\n console.warn(\n '[dotenvx-next] Could not load init bundle for webpack injection:',\n err\n );\n }\n }\n\n return config;\n };\n\n return resolvedNextConfig;\n}\n\nexport function withDotenvx(\n nextConfig: NextConfig | NextConfigFn,\n options: DotenvxNextOptions = {}\n): NextConfigFn {\n return (phase: string, defaults: { defaultConfig: NextConfig }) =>\n dotenvxNextConfigFn(nextConfig, options, phase, defaults);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsCA,MAAM,oBAAoB;CAAC;CAAa;CAAmB;CAAe;AAE1E,MAAM,eAAe,CAAC,CAAC,QAAQ,IAAI;AAEnC,SAAS,SAAS,GAAG,MAAuB;AAC1C,KAAI,CAAC,aAAc;AACnB,SAAQ,IAAI,kBAAkB,GAAG,KAAK;;AAGxC,SAAS,qBAAqB,OAAiB,QAA0B;AACvE,QAAO,MACJ,KAAK,MAAM,KAAK,QAAQ,QAAQ,EAAE,CAAC,CACnC,QAAQ,YAAY,GAAG,WAAW,QAAQ,CAAC;;;;;;AAOhD,SAAS,iBAAyB;AAGhC,KAAI;AAGF,SAAA,UAAe,UAAU,CAAC,aAAA,UAChB,QAAQ,aAAa,EAC7B,OACD;SACK;EAEN,MAAM,UAAU,KAAK,QAAQ,IAAI,IAAI,OAAO,KAAK,IAAI,CAAC,UAAU,SAAS;AACzE,SAAO,GAAG,aAAa,KAAK,KAAK,SAAS,QAAQ,WAAW,EAAE,OAAO;;;AAS1E,eAAe,oBACb,YACA,SACA,OACA,UACqB;CACrB,IAAI;AAEJ,KAAI,OAAO,eAAe,WACxB,sBAAqB,EACnB,GAAI,MAAO,WAA4B,OAAO,SAAS,EACxD;KAGD,sBAAqB,EAAE,GAAG,YAAY;CAGxC,MAAM,SAAS,QAAQ,UAAU,QAAQ,KAAK;CAE9C,MAAM,gBAAgB,qBADJ,QAAQ,SAAS,mBACmB,OAAO;CAC7D,MAAM,cAAc,QAAQ,kBAAkB;CAG9C,MAAM,cAAc,CAAC,EACnB,QAAQ,IAAI,aACZ,QAAQ,IAAI,iBACZ,QAAQ,IAAI,mBACZ,QAAQ,IAAI;AAGd,UACE,SAAS,MAAM,gBAAgB,YAAY,kBAAkB,KAAK,UAAU,cAAc,GAC3F;AAID,KAAI,eAAe,cAAc,SAAS,GAAG;AAC3C,qBAAmB,8BAA8B,EAAE;EAEnD,MAAM,UAAU,mBAAmB;EAEnC,MAAM,WAAW;EACjB,MAAM,WAAW,QAAQ;AACzB,MAAI,MAAM,QAAQ,SAAS,CACzB,SAAQ,YAAY,CAAC,GAAG,UAAU,GAAG,cAAc;MAEnD,SAAQ,YAAY;;AAIxB,KAAI,YAEF,KAAI;AAEF,6BADmB,gBACkB,CAAC;UAC/B,KAAK;AACZ,UAAQ,KACN,sEACA,IACD;;CAKL,MAAM,cAAc,mBAAmB;AAEvC,oBAAmB,WAAW,eAAe,mBAAmB;EAG9D,MAAM,SAAS,cACX,YAAY,eAAe,eAAe,GAC1C;AAIJ,SAAO,YAAY,EAAE;AACpB,SAAO,QAAoC,UAAU,EAAE;EACxD,MAAM,QAAS,OAAO,QAAoC;AAM1D,MAAI;AACF,SAAM,eAAA,UAAuB,QAC3B,uCACD;UACK;AAEN,YACE,8EACD;;AAIH,MAAI,CAAC,YACH,KAAI;GAEF,MAAM,SAAS,IAAI,qBAAqB;IACtC,OAAO;IACP,YAHiB,gBAGP;IACX,CAAC;AACD,UAAO,QAAsB,KAAK,OAAO;WACnC,KAAK;AACZ,WAAQ,KACN,oEACA,IACD;;AAIL,SAAO;;AAGT,QAAO;;AAGT,SAAgB,YACd,YACA,UAA8B,EAAE,EAClB;AACd,SAAQ,OAAe,aACrB,oBAAoB,YAAY,SAAS,OAAO,SAAS"}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
//#region \0rolldown/runtime.js
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __copyProps = (to, from, except, desc) => {
|
|
9
|
+
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
10
|
+
key = keys[i];
|
|
11
|
+
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
12
|
+
get: ((k) => from[k]).bind(null, key),
|
|
13
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
19
|
+
value: mod,
|
|
20
|
+
enumerable: true
|
|
21
|
+
}) : target, mod));
|
|
22
|
+
//#endregion
|
|
23
|
+
let node_fs = require("node:fs");
|
|
24
|
+
node_fs = __toESM(node_fs, 1);
|
|
25
|
+
let node_path = require("node:path");
|
|
26
|
+
node_path = __toESM(node_path, 1);
|
|
27
|
+
//#region src/turbopack-inject.ts
|
|
28
|
+
/**
|
|
29
|
+
* Turbopack runtime injection — patches fs.writeFile/fs.writeFileSync to intercept
|
|
30
|
+
* turbopack's build output and prepend the dotenvx init bundle into runtime files.
|
|
31
|
+
*
|
|
32
|
+
* Turbopack writes `[turbopack]_runtime.js` directly (bypassing webpack), so we
|
|
33
|
+
* can't use the processAssets hook. Instead we intercept fs writes and inject when
|
|
34
|
+
* export-detail.json is written (signals compilation is complete).
|
|
35
|
+
*/
|
|
36
|
+
function debugLog(...args) {
|
|
37
|
+
if (!process.env.DEBUG_DOTENVX_NEXT) return;
|
|
38
|
+
console.log("[dotenvx-next]", ...args);
|
|
39
|
+
}
|
|
40
|
+
let injectedTurbopackRuntime = false;
|
|
41
|
+
function isInjectedTurbopackRuntime() {
|
|
42
|
+
return injectedTurbopackRuntime;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Inject the dotenvx init bundle into turbopack runtime files.
|
|
46
|
+
* Called after export-detail.json is written (turbopack compilation complete).
|
|
47
|
+
*/
|
|
48
|
+
function injectDotenvxInitIntoTurbopackRuntime(nextDirPath, initSource) {
|
|
49
|
+
if (injectedTurbopackRuntime) return;
|
|
50
|
+
const serverRuntimeFiles = [];
|
|
51
|
+
const edgeWrapperFiles = [];
|
|
52
|
+
const walkDir = (dir) => {
|
|
53
|
+
if (!node_fs.default.existsSync(dir)) return;
|
|
54
|
+
for (const entry of node_fs.default.readdirSync(dir, { withFileTypes: true })) if (entry.isDirectory()) walkDir(node_path.default.join(dir, entry.name));
|
|
55
|
+
else if (entry.name === "[turbopack]_runtime.js") serverRuntimeFiles.push(node_path.default.join(dir, entry.name));
|
|
56
|
+
else if (entry.name.includes("edge-wrapper") && entry.name.endsWith(".js")) edgeWrapperFiles.push(node_path.default.join(dir, entry.name));
|
|
57
|
+
};
|
|
58
|
+
walkDir(nextDirPath);
|
|
59
|
+
debugLog(`turbopack runtime injection: found ${serverRuntimeFiles.length} server runtime files,`, `${edgeWrapperFiles.length} edge wrapper files`);
|
|
60
|
+
if (!serverRuntimeFiles.length) return;
|
|
61
|
+
injectedTurbopackRuntime = true;
|
|
62
|
+
const strippedSource = initSource.replace(/\s*\/\/# sourceMappingURL=\S+\s*$/m, "");
|
|
63
|
+
const iifeWrap = (src) => `(function(exports,module){${src}\n})({},{exports:{}});`;
|
|
64
|
+
const wrappedInit = iifeWrap(strippedSource);
|
|
65
|
+
/**
|
|
66
|
+
* Insert wrappedInit into source respecting ESM constraints.
|
|
67
|
+
* ESM files require all top-level `import` declarations to appear before any
|
|
68
|
+
* other statements, so we must insert after the last import line rather than
|
|
69
|
+
* prepending to the file.
|
|
70
|
+
*/
|
|
71
|
+
const insertIntoSource = (origSource) => {
|
|
72
|
+
const lines = origSource.split("\n");
|
|
73
|
+
let lastImportIdx = -1;
|
|
74
|
+
for (let i = 0; i < lines.length; i++) if (/^import\s/.test(lines[i])) lastImportIdx = i;
|
|
75
|
+
if (lastImportIdx >= 0) {
|
|
76
|
+
lines.splice(lastImportIdx + 1, 0, wrappedInit);
|
|
77
|
+
return lines.join("\n");
|
|
78
|
+
}
|
|
79
|
+
return [wrappedInit, origSource].join("\n");
|
|
80
|
+
};
|
|
81
|
+
for (const runtimeFile of serverRuntimeFiles) {
|
|
82
|
+
const origSource = node_fs.default.readFileSync(runtimeFile, "utf8");
|
|
83
|
+
node_fs.default.writeFileSync(runtimeFile, insertIntoSource(origSource));
|
|
84
|
+
debugLog(`injected dotenvx init into turbopack server runtime: ${runtimeFile}`);
|
|
85
|
+
}
|
|
86
|
+
for (const wrapperFile of edgeWrapperFiles) {
|
|
87
|
+
const origSource = node_fs.default.readFileSync(wrapperFile, "utf8");
|
|
88
|
+
node_fs.default.writeFileSync(wrapperFile, insertIntoSource(origSource));
|
|
89
|
+
debugLog(`injected dotenvx init into turbopack edge wrapper: ${wrapperFile}`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Patch global fs methods to detect when turbopack compilation completes,
|
|
94
|
+
* then trigger runtime injection.
|
|
95
|
+
*/
|
|
96
|
+
function activateTurbopackInjection(initSource) {
|
|
97
|
+
debugLog("activating turbopack fs intercept");
|
|
98
|
+
const origWriteFileFn = node_fs.default.promises.writeFile;
|
|
99
|
+
node_fs.default.promises.writeFile = async function dotenvxPatchedWriteFile(...args) {
|
|
100
|
+
const filePath = args[0].toString();
|
|
101
|
+
debugLog("fs.promises.writeFile:", filePath);
|
|
102
|
+
if (!injectedTurbopackRuntime && filePath.endsWith("/.next/export-detail.json")) injectDotenvxInitIntoTurbopackRuntime(filePath.substring(0, filePath.lastIndexOf("/")), initSource);
|
|
103
|
+
return origWriteFileFn.apply(node_fs.default.promises, args);
|
|
104
|
+
};
|
|
105
|
+
const origWriteFileSyncFn = node_fs.default.writeFileSync;
|
|
106
|
+
node_fs.default.writeFileSync = function dotenvxPatchedWriteFileSync(...args) {
|
|
107
|
+
const filePath = args[0].toString();
|
|
108
|
+
debugLog("fs.writeFileSync:", filePath);
|
|
109
|
+
if (!injectedTurbopackRuntime && filePath.endsWith("/.next/export-detail.json")) injectDotenvxInitIntoTurbopackRuntime(filePath.substring(0, filePath.lastIndexOf("/")), initSource);
|
|
110
|
+
origWriteFileSyncFn.apply(node_fs.default, args);
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
//#endregion
|
|
114
|
+
Object.defineProperty(exports, "__toESM", {
|
|
115
|
+
enumerable: true,
|
|
116
|
+
get: function() {
|
|
117
|
+
return __toESM;
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
Object.defineProperty(exports, "activateTurbopackInjection", {
|
|
121
|
+
enumerable: true,
|
|
122
|
+
get: function() {
|
|
123
|
+
return activateTurbopackInjection;
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
Object.defineProperty(exports, "injectDotenvxInitIntoTurbopackRuntime", {
|
|
127
|
+
enumerable: true,
|
|
128
|
+
get: function() {
|
|
129
|
+
return injectDotenvxInitIntoTurbopackRuntime;
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
Object.defineProperty(exports, "isInjectedTurbopackRuntime", {
|
|
133
|
+
enumerable: true,
|
|
134
|
+
get: function() {
|
|
135
|
+
return isInjectedTurbopackRuntime;
|
|
136
|
+
}
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
//# sourceMappingURL=turbopack-inject-BgCxanwa.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"turbopack-inject-BgCxanwa.cjs","names":["fs","path"],"sources":["../src/turbopack-inject.ts"],"sourcesContent":["/**\n * Turbopack runtime injection — patches fs.writeFile/fs.writeFileSync to intercept\n * turbopack's build output and prepend the dotenvx init bundle into runtime files.\n *\n * Turbopack writes `[turbopack]_runtime.js` directly (bypassing webpack), so we\n * can't use the processAssets hook. Instead we intercept fs writes and inject when\n * export-detail.json is written (signals compilation is complete).\n */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nfunction debugLog(...args: unknown[]): void {\n if (!process.env.DEBUG_DOTENVX_NEXT) return;\n console.log('[dotenvx-next]', ...args);\n}\n\nlet injectedTurbopackRuntime = false;\n\nexport function isInjectedTurbopackRuntime(): boolean {\n return injectedTurbopackRuntime;\n}\n\n/**\n * Inject the dotenvx init bundle into turbopack runtime files.\n * Called after export-detail.json is written (turbopack compilation complete).\n */\nexport function injectDotenvxInitIntoTurbopackRuntime(\n nextDirPath: string,\n initSource: string\n): void {\n if (injectedTurbopackRuntime) return;\n\n const serverRuntimeFiles: string[] = [];\n const edgeWrapperFiles: string[] = [];\n\n const walkDir = (dir: string): void => {\n if (!fs.existsSync(dir)) return;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (entry.isDirectory()) {\n walkDir(path.join(dir, entry.name));\n } else if (entry.name === '[turbopack]_runtime.js') {\n serverRuntimeFiles.push(path.join(dir, entry.name));\n } else if (\n entry.name.includes('edge-wrapper') &&\n entry.name.endsWith('.js')\n ) {\n edgeWrapperFiles.push(path.join(dir, entry.name));\n }\n }\n };\n\n walkDir(nextDirPath);\n\n debugLog(\n `turbopack runtime injection: found ${serverRuntimeFiles.length} server runtime files,`,\n `${edgeWrapperFiles.length} edge wrapper files`\n );\n\n if (!serverRuntimeFiles.length) {\n // Runtime files may not exist yet — turbopack (Rust) writes them directly.\n // We'll retry on subsequent fs writes until they appear.\n return;\n }\n\n // Mark as done so we don't retry\n injectedTurbopackRuntime = true;\n\n // Strip sourcemap comment — if it appears on the last line before the closing\n // `})({},{exports:{}});`, it would comment out the IIFE closer and cause\n // \"Unexpected end of input\" at parse time.\n const strippedSource = initSource.replace(\n /\\s*\\/\\/# sourceMappingURL=\\S+\\s*$/m,\n ''\n );\n\n // Wrap in IIFE to avoid symbol collisions (CJS bundle uses exports.X = ...)\n const iifeWrap = (src: string): string =>\n `(function(exports,module){${src}\\n})({},{exports:{}});`;\n\n const wrappedInit = iifeWrap(strippedSource);\n\n /**\n * Insert wrappedInit into source respecting ESM constraints.\n * ESM files require all top-level `import` declarations to appear before any\n * other statements, so we must insert after the last import line rather than\n * prepending to the file.\n */\n const insertIntoSource = (origSource: string): string => {\n const lines = origSource.split('\\n');\n // Find the last line that starts with 'import ' (top-level import declaration)\n let lastImportIdx = -1;\n for (let i = 0; i < lines.length; i++) {\n if (/^import\\s/.test(lines[i])) {\n lastImportIdx = i;\n }\n }\n if (lastImportIdx >= 0) {\n // Insert after the last import line\n lines.splice(lastImportIdx + 1, 0, wrappedInit);\n return lines.join('\\n');\n }\n // CJS or no imports — prepend as before\n return [wrappedInit, origSource].join('\\n');\n };\n\n for (const runtimeFile of serverRuntimeFiles) {\n const origSource = fs.readFileSync(runtimeFile, 'utf8');\n fs.writeFileSync(runtimeFile, insertIntoSource(origSource));\n debugLog(\n `injected dotenvx init into turbopack server runtime: ${runtimeFile}`\n );\n }\n\n for (const wrapperFile of edgeWrapperFiles) {\n const origSource = fs.readFileSync(wrapperFile, 'utf8');\n fs.writeFileSync(wrapperFile, insertIntoSource(origSource));\n debugLog(\n `injected dotenvx init into turbopack edge wrapper: ${wrapperFile}`\n );\n }\n}\n\n/**\n * Patch global fs methods to detect when turbopack compilation completes,\n * then trigger runtime injection.\n */\nexport function activateTurbopackInjection(initSource: string): void {\n debugLog('activating turbopack fs intercept');\n\n const origWriteFileFn = fs.promises.writeFile;\n fs.promises.writeFile = async function dotenvxPatchedWriteFile(\n ...args: Parameters<typeof fs.promises.writeFile>\n ): ReturnType<typeof fs.promises.writeFile> {\n const filePath = args[0].toString();\n debugLog('fs.promises.writeFile:', filePath);\n\n if (\n !injectedTurbopackRuntime &&\n filePath.endsWith('/.next/export-detail.json')\n ) {\n const nextDirPath = filePath.substring(0, filePath.lastIndexOf('/'));\n injectDotenvxInitIntoTurbopackRuntime(nextDirPath, initSource);\n }\n\n return origWriteFileFn.apply(fs.promises, args);\n };\n\n const origWriteFileSyncFn = fs.writeFileSync;\n fs.writeFileSync = function dotenvxPatchedWriteFileSync(\n ...args: Parameters<typeof fs.writeFileSync>\n ): void {\n const filePath = args[0].toString();\n debugLog('fs.writeFileSync:', filePath);\n\n if (\n !injectedTurbopackRuntime &&\n filePath.endsWith('/.next/export-detail.json')\n ) {\n const nextDirPath = filePath.substring(0, filePath.lastIndexOf('/'));\n injectDotenvxInitIntoTurbopackRuntime(nextDirPath, initSource);\n }\n\n origWriteFileSyncFn.apply(fs, args);\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYA,SAAS,SAAS,GAAG,MAAuB;AAC1C,KAAI,CAAC,QAAQ,IAAI,mBAAoB;AACrC,SAAQ,IAAI,kBAAkB,GAAG,KAAK;;AAGxC,IAAI,2BAA2B;AAE/B,SAAgB,6BAAsC;AACpD,QAAO;;;;;;AAOT,SAAgB,sCACd,aACA,YACM;AACN,KAAI,yBAA0B;CAE9B,MAAM,qBAA+B,EAAE;CACvC,MAAM,mBAA6B,EAAE;CAErC,MAAM,WAAW,QAAsB;AACrC,MAAI,CAACA,QAAAA,QAAG,WAAW,IAAI,CAAE;AACzB,OAAK,MAAM,SAASA,QAAAA,QAAG,YAAY,KAAK,EAAE,eAAe,MAAM,CAAC,CAC9D,KAAI,MAAM,aAAa,CACrB,SAAQC,UAAAA,QAAK,KAAK,KAAK,MAAM,KAAK,CAAC;WAC1B,MAAM,SAAS,yBACxB,oBAAmB,KAAKA,UAAAA,QAAK,KAAK,KAAK,MAAM,KAAK,CAAC;WAEnD,MAAM,KAAK,SAAS,eAAe,IACnC,MAAM,KAAK,SAAS,MAAM,CAE1B,kBAAiB,KAAKA,UAAAA,QAAK,KAAK,KAAK,MAAM,KAAK,CAAC;;AAKvD,SAAQ,YAAY;AAEpB,UACE,sCAAsC,mBAAmB,OAAO,yBAChE,GAAG,iBAAiB,OAAO,qBAC5B;AAED,KAAI,CAAC,mBAAmB,OAGtB;AAIF,4BAA2B;CAK3B,MAAM,iBAAiB,WAAW,QAChC,sCACA,GACD;CAGD,MAAM,YAAY,QAChB,6BAA6B,IAAI;CAEnC,MAAM,cAAc,SAAS,eAAe;;;;;;;CAQ5C,MAAM,oBAAoB,eAA+B;EACvD,MAAM,QAAQ,WAAW,MAAM,KAAK;EAEpC,IAAI,gBAAgB;AACpB,OAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,IAChC,KAAI,YAAY,KAAK,MAAM,GAAG,CAC5B,iBAAgB;AAGpB,MAAI,iBAAiB,GAAG;AAEtB,SAAM,OAAO,gBAAgB,GAAG,GAAG,YAAY;AAC/C,UAAO,MAAM,KAAK,KAAK;;AAGzB,SAAO,CAAC,aAAa,WAAW,CAAC,KAAK,KAAK;;AAG7C,MAAK,MAAM,eAAe,oBAAoB;EAC5C,MAAM,aAAaD,QAAAA,QAAG,aAAa,aAAa,OAAO;AACvD,UAAA,QAAG,cAAc,aAAa,iBAAiB,WAAW,CAAC;AAC3D,WACE,wDAAwD,cACzD;;AAGH,MAAK,MAAM,eAAe,kBAAkB;EAC1C,MAAM,aAAaA,QAAAA,QAAG,aAAa,aAAa,OAAO;AACvD,UAAA,QAAG,cAAc,aAAa,iBAAiB,WAAW,CAAC;AAC3D,WACE,sDAAsD,cACvD;;;;;;;AAQL,SAAgB,2BAA2B,YAA0B;AACnE,UAAS,oCAAoC;CAE7C,MAAM,kBAAkBA,QAAAA,QAAG,SAAS;AACpC,SAAA,QAAG,SAAS,YAAY,eAAe,wBACrC,GAAG,MACuC;EAC1C,MAAM,WAAW,KAAK,GAAG,UAAU;AACnC,WAAS,0BAA0B,SAAS;AAE5C,MACE,CAAC,4BACD,SAAS,SAAS,4BAA4B,CAG9C,uCADoB,SAAS,UAAU,GAAG,SAAS,YAAY,IAAI,CAClB,EAAE,WAAW;AAGhE,SAAO,gBAAgB,MAAMA,QAAAA,QAAG,UAAU,KAAK;;CAGjD,MAAM,sBAAsBA,QAAAA,QAAG;AAC/B,SAAA,QAAA,gBAAmB,SAAS,4BAC1B,GAAG,MACG;EACN,MAAM,WAAW,KAAK,GAAG,UAAU;AACnC,WAAS,qBAAqB,SAAS;AAEvC,MACE,CAAC,4BACD,SAAS,SAAS,4BAA4B,CAG9C,uCADoB,SAAS,UAAU,GAAG,SAAS,YAAY,IAAI,CAClB,EAAE,WAAW;AAGhE,sBAAoB,MAAMA,QAAAA,SAAI,KAAK"}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_turbopack_inject = require("./turbopack-inject-BgCxanwa.cjs");
|
|
3
|
+
exports.activateTurbopackInjection = require_turbopack_inject.activateTurbopackInjection;
|
|
4
|
+
exports.injectDotenvxInitIntoTurbopackRuntime = require_turbopack_inject.injectDotenvxInitIntoTurbopackRuntime;
|
|
5
|
+
exports.isInjectedTurbopackRuntime = require_turbopack_inject.isInjectedTurbopackRuntime;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
//#region src/turbopack-inject.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Turbopack runtime injection — patches fs.writeFile/fs.writeFileSync to intercept
|
|
4
|
+
* turbopack's build output and prepend the dotenvx init bundle into runtime files.
|
|
5
|
+
*
|
|
6
|
+
* Turbopack writes `[turbopack]_runtime.js` directly (bypassing webpack), so we
|
|
7
|
+
* can't use the processAssets hook. Instead we intercept fs writes and inject when
|
|
8
|
+
* export-detail.json is written (signals compilation is complete).
|
|
9
|
+
*/
|
|
10
|
+
declare function isInjectedTurbopackRuntime(): boolean;
|
|
11
|
+
/**
|
|
12
|
+
* Inject the dotenvx init bundle into turbopack runtime files.
|
|
13
|
+
* Called after export-detail.json is written (turbopack compilation complete).
|
|
14
|
+
*/
|
|
15
|
+
declare function injectDotenvxInitIntoTurbopackRuntime(nextDirPath: string, initSource: string): void;
|
|
16
|
+
/**
|
|
17
|
+
* Patch global fs methods to detect when turbopack compilation completes,
|
|
18
|
+
* then trigger runtime injection.
|
|
19
|
+
*/
|
|
20
|
+
declare function activateTurbopackInjection(initSource: string): void;
|
|
21
|
+
//#endregion
|
|
22
|
+
export { activateTurbopackInjection, injectDotenvxInitIntoTurbopackRuntime, isInjectedTurbopackRuntime };
|
|
23
|
+
//# sourceMappingURL=turbopack-inject.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"turbopack-inject.d.cts","names":[],"sources":["../src/turbopack-inject.ts"],"mappings":";;AAmBA;;;;;AAQA;;iBARgB,0BAAA,CAAA;;;AA4GhB;;iBApGgB,qCAAA,CACd,WAAA,UACA,UAAA;;;;;iBAkGc,0BAAA,CAA2B,UAAA"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
//#region src/turbopack-inject.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Turbopack runtime injection — patches fs.writeFile/fs.writeFileSync to intercept
|
|
4
|
+
* turbopack's build output and prepend the dotenvx init bundle into runtime files.
|
|
5
|
+
*
|
|
6
|
+
* Turbopack writes `[turbopack]_runtime.js` directly (bypassing webpack), so we
|
|
7
|
+
* can't use the processAssets hook. Instead we intercept fs writes and inject when
|
|
8
|
+
* export-detail.json is written (signals compilation is complete).
|
|
9
|
+
*/
|
|
10
|
+
declare function isInjectedTurbopackRuntime(): boolean;
|
|
11
|
+
/**
|
|
12
|
+
* Inject the dotenvx init bundle into turbopack runtime files.
|
|
13
|
+
* Called after export-detail.json is written (turbopack compilation complete).
|
|
14
|
+
*/
|
|
15
|
+
declare function injectDotenvxInitIntoTurbopackRuntime(nextDirPath: string, initSource: string): void;
|
|
16
|
+
/**
|
|
17
|
+
* Patch global fs methods to detect when turbopack compilation completes,
|
|
18
|
+
* then trigger runtime injection.
|
|
19
|
+
*/
|
|
20
|
+
declare function activateTurbopackInjection(initSource: string): void;
|
|
21
|
+
//#endregion
|
|
22
|
+
export { activateTurbopackInjection, injectDotenvxInitIntoTurbopackRuntime, isInjectedTurbopackRuntime };
|
|
23
|
+
//# sourceMappingURL=turbopack-inject.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"turbopack-inject.d.mts","names":[],"sources":["../src/turbopack-inject.ts"],"mappings":";;AAmBA;;;;;AAQA;;iBARgB,0BAAA,CAAA;;;AA4GhB;;iBApGgB,qCAAA,CACd,WAAA,UACA,UAAA;;;;;iBAkGc,0BAAA,CAA2B,UAAA"}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
//#region src/turbopack-inject.ts
|
|
4
|
+
/**
|
|
5
|
+
* Turbopack runtime injection — patches fs.writeFile/fs.writeFileSync to intercept
|
|
6
|
+
* turbopack's build output and prepend the dotenvx init bundle into runtime files.
|
|
7
|
+
*
|
|
8
|
+
* Turbopack writes `[turbopack]_runtime.js` directly (bypassing webpack), so we
|
|
9
|
+
* can't use the processAssets hook. Instead we intercept fs writes and inject when
|
|
10
|
+
* export-detail.json is written (signals compilation is complete).
|
|
11
|
+
*/
|
|
12
|
+
function debugLog(...args) {
|
|
13
|
+
if (!process.env.DEBUG_DOTENVX_NEXT) return;
|
|
14
|
+
console.log("[dotenvx-next]", ...args);
|
|
15
|
+
}
|
|
16
|
+
let injectedTurbopackRuntime = false;
|
|
17
|
+
function isInjectedTurbopackRuntime() {
|
|
18
|
+
return injectedTurbopackRuntime;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Inject the dotenvx init bundle into turbopack runtime files.
|
|
22
|
+
* Called after export-detail.json is written (turbopack compilation complete).
|
|
23
|
+
*/
|
|
24
|
+
function injectDotenvxInitIntoTurbopackRuntime(nextDirPath, initSource) {
|
|
25
|
+
if (injectedTurbopackRuntime) return;
|
|
26
|
+
const serverRuntimeFiles = [];
|
|
27
|
+
const edgeWrapperFiles = [];
|
|
28
|
+
const walkDir = (dir) => {
|
|
29
|
+
if (!fs.existsSync(dir)) return;
|
|
30
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) if (entry.isDirectory()) walkDir(path.join(dir, entry.name));
|
|
31
|
+
else if (entry.name === "[turbopack]_runtime.js") serverRuntimeFiles.push(path.join(dir, entry.name));
|
|
32
|
+
else if (entry.name.includes("edge-wrapper") && entry.name.endsWith(".js")) edgeWrapperFiles.push(path.join(dir, entry.name));
|
|
33
|
+
};
|
|
34
|
+
walkDir(nextDirPath);
|
|
35
|
+
debugLog(`turbopack runtime injection: found ${serverRuntimeFiles.length} server runtime files,`, `${edgeWrapperFiles.length} edge wrapper files`);
|
|
36
|
+
if (!serverRuntimeFiles.length) return;
|
|
37
|
+
injectedTurbopackRuntime = true;
|
|
38
|
+
const strippedSource = initSource.replace(/\s*\/\/# sourceMappingURL=\S+\s*$/m, "");
|
|
39
|
+
const iifeWrap = (src) => `(function(exports,module){${src}\n})({},{exports:{}});`;
|
|
40
|
+
const wrappedInit = iifeWrap(strippedSource);
|
|
41
|
+
/**
|
|
42
|
+
* Insert wrappedInit into source respecting ESM constraints.
|
|
43
|
+
* ESM files require all top-level `import` declarations to appear before any
|
|
44
|
+
* other statements, so we must insert after the last import line rather than
|
|
45
|
+
* prepending to the file.
|
|
46
|
+
*/
|
|
47
|
+
const insertIntoSource = (origSource) => {
|
|
48
|
+
const lines = origSource.split("\n");
|
|
49
|
+
let lastImportIdx = -1;
|
|
50
|
+
for (let i = 0; i < lines.length; i++) if (/^import\s/.test(lines[i])) lastImportIdx = i;
|
|
51
|
+
if (lastImportIdx >= 0) {
|
|
52
|
+
lines.splice(lastImportIdx + 1, 0, wrappedInit);
|
|
53
|
+
return lines.join("\n");
|
|
54
|
+
}
|
|
55
|
+
return [wrappedInit, origSource].join("\n");
|
|
56
|
+
};
|
|
57
|
+
for (const runtimeFile of serverRuntimeFiles) {
|
|
58
|
+
const origSource = fs.readFileSync(runtimeFile, "utf8");
|
|
59
|
+
fs.writeFileSync(runtimeFile, insertIntoSource(origSource));
|
|
60
|
+
debugLog(`injected dotenvx init into turbopack server runtime: ${runtimeFile}`);
|
|
61
|
+
}
|
|
62
|
+
for (const wrapperFile of edgeWrapperFiles) {
|
|
63
|
+
const origSource = fs.readFileSync(wrapperFile, "utf8");
|
|
64
|
+
fs.writeFileSync(wrapperFile, insertIntoSource(origSource));
|
|
65
|
+
debugLog(`injected dotenvx init into turbopack edge wrapper: ${wrapperFile}`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Patch global fs methods to detect when turbopack compilation completes,
|
|
70
|
+
* then trigger runtime injection.
|
|
71
|
+
*/
|
|
72
|
+
function activateTurbopackInjection(initSource) {
|
|
73
|
+
debugLog("activating turbopack fs intercept");
|
|
74
|
+
const origWriteFileFn = fs.promises.writeFile;
|
|
75
|
+
fs.promises.writeFile = async function dotenvxPatchedWriteFile(...args) {
|
|
76
|
+
const filePath = args[0].toString();
|
|
77
|
+
debugLog("fs.promises.writeFile:", filePath);
|
|
78
|
+
if (!injectedTurbopackRuntime && filePath.endsWith("/.next/export-detail.json")) injectDotenvxInitIntoTurbopackRuntime(filePath.substring(0, filePath.lastIndexOf("/")), initSource);
|
|
79
|
+
return origWriteFileFn.apply(fs.promises, args);
|
|
80
|
+
};
|
|
81
|
+
const origWriteFileSyncFn = fs.writeFileSync;
|
|
82
|
+
fs.writeFileSync = function dotenvxPatchedWriteFileSync(...args) {
|
|
83
|
+
const filePath = args[0].toString();
|
|
84
|
+
debugLog("fs.writeFileSync:", filePath);
|
|
85
|
+
if (!injectedTurbopackRuntime && filePath.endsWith("/.next/export-detail.json")) injectDotenvxInitIntoTurbopackRuntime(filePath.substring(0, filePath.lastIndexOf("/")), initSource);
|
|
86
|
+
origWriteFileSyncFn.apply(fs, args);
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
//#endregion
|
|
90
|
+
export { activateTurbopackInjection, injectDotenvxInitIntoTurbopackRuntime, isInjectedTurbopackRuntime };
|
|
91
|
+
|
|
92
|
+
//# sourceMappingURL=turbopack-inject.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"turbopack-inject.mjs","names":[],"sources":["../src/turbopack-inject.ts"],"sourcesContent":["/**\n * Turbopack runtime injection — patches fs.writeFile/fs.writeFileSync to intercept\n * turbopack's build output and prepend the dotenvx init bundle into runtime files.\n *\n * Turbopack writes `[turbopack]_runtime.js` directly (bypassing webpack), so we\n * can't use the processAssets hook. Instead we intercept fs writes and inject when\n * export-detail.json is written (signals compilation is complete).\n */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nfunction debugLog(...args: unknown[]): void {\n if (!process.env.DEBUG_DOTENVX_NEXT) return;\n console.log('[dotenvx-next]', ...args);\n}\n\nlet injectedTurbopackRuntime = false;\n\nexport function isInjectedTurbopackRuntime(): boolean {\n return injectedTurbopackRuntime;\n}\n\n/**\n * Inject the dotenvx init bundle into turbopack runtime files.\n * Called after export-detail.json is written (turbopack compilation complete).\n */\nexport function injectDotenvxInitIntoTurbopackRuntime(\n nextDirPath: string,\n initSource: string\n): void {\n if (injectedTurbopackRuntime) return;\n\n const serverRuntimeFiles: string[] = [];\n const edgeWrapperFiles: string[] = [];\n\n const walkDir = (dir: string): void => {\n if (!fs.existsSync(dir)) return;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (entry.isDirectory()) {\n walkDir(path.join(dir, entry.name));\n } else if (entry.name === '[turbopack]_runtime.js') {\n serverRuntimeFiles.push(path.join(dir, entry.name));\n } else if (\n entry.name.includes('edge-wrapper') &&\n entry.name.endsWith('.js')\n ) {\n edgeWrapperFiles.push(path.join(dir, entry.name));\n }\n }\n };\n\n walkDir(nextDirPath);\n\n debugLog(\n `turbopack runtime injection: found ${serverRuntimeFiles.length} server runtime files,`,\n `${edgeWrapperFiles.length} edge wrapper files`\n );\n\n if (!serverRuntimeFiles.length) {\n // Runtime files may not exist yet — turbopack (Rust) writes them directly.\n // We'll retry on subsequent fs writes until they appear.\n return;\n }\n\n // Mark as done so we don't retry\n injectedTurbopackRuntime = true;\n\n // Strip sourcemap comment — if it appears on the last line before the closing\n // `})({},{exports:{}});`, it would comment out the IIFE closer and cause\n // \"Unexpected end of input\" at parse time.\n const strippedSource = initSource.replace(\n /\\s*\\/\\/# sourceMappingURL=\\S+\\s*$/m,\n ''\n );\n\n // Wrap in IIFE to avoid symbol collisions (CJS bundle uses exports.X = ...)\n const iifeWrap = (src: string): string =>\n `(function(exports,module){${src}\\n})({},{exports:{}});`;\n\n const wrappedInit = iifeWrap(strippedSource);\n\n /**\n * Insert wrappedInit into source respecting ESM constraints.\n * ESM files require all top-level `import` declarations to appear before any\n * other statements, so we must insert after the last import line rather than\n * prepending to the file.\n */\n const insertIntoSource = (origSource: string): string => {\n const lines = origSource.split('\\n');\n // Find the last line that starts with 'import ' (top-level import declaration)\n let lastImportIdx = -1;\n for (let i = 0; i < lines.length; i++) {\n if (/^import\\s/.test(lines[i])) {\n lastImportIdx = i;\n }\n }\n if (lastImportIdx >= 0) {\n // Insert after the last import line\n lines.splice(lastImportIdx + 1, 0, wrappedInit);\n return lines.join('\\n');\n }\n // CJS or no imports — prepend as before\n return [wrappedInit, origSource].join('\\n');\n };\n\n for (const runtimeFile of serverRuntimeFiles) {\n const origSource = fs.readFileSync(runtimeFile, 'utf8');\n fs.writeFileSync(runtimeFile, insertIntoSource(origSource));\n debugLog(\n `injected dotenvx init into turbopack server runtime: ${runtimeFile}`\n );\n }\n\n for (const wrapperFile of edgeWrapperFiles) {\n const origSource = fs.readFileSync(wrapperFile, 'utf8');\n fs.writeFileSync(wrapperFile, insertIntoSource(origSource));\n debugLog(\n `injected dotenvx init into turbopack edge wrapper: ${wrapperFile}`\n );\n }\n}\n\n/**\n * Patch global fs methods to detect when turbopack compilation completes,\n * then trigger runtime injection.\n */\nexport function activateTurbopackInjection(initSource: string): void {\n debugLog('activating turbopack fs intercept');\n\n const origWriteFileFn = fs.promises.writeFile;\n fs.promises.writeFile = async function dotenvxPatchedWriteFile(\n ...args: Parameters<typeof fs.promises.writeFile>\n ): ReturnType<typeof fs.promises.writeFile> {\n const filePath = args[0].toString();\n debugLog('fs.promises.writeFile:', filePath);\n\n if (\n !injectedTurbopackRuntime &&\n filePath.endsWith('/.next/export-detail.json')\n ) {\n const nextDirPath = filePath.substring(0, filePath.lastIndexOf('/'));\n injectDotenvxInitIntoTurbopackRuntime(nextDirPath, initSource);\n }\n\n return origWriteFileFn.apply(fs.promises, args);\n };\n\n const origWriteFileSyncFn = fs.writeFileSync;\n fs.writeFileSync = function dotenvxPatchedWriteFileSync(\n ...args: Parameters<typeof fs.writeFileSync>\n ): void {\n const filePath = args[0].toString();\n debugLog('fs.writeFileSync:', filePath);\n\n if (\n !injectedTurbopackRuntime &&\n filePath.endsWith('/.next/export-detail.json')\n ) {\n const nextDirPath = filePath.substring(0, filePath.lastIndexOf('/'));\n injectDotenvxInitIntoTurbopackRuntime(nextDirPath, initSource);\n }\n\n origWriteFileSyncFn.apply(fs, args);\n };\n}\n"],"mappings":";;;;;;;;;;;AAYA,SAAS,SAAS,GAAG,MAAuB;AAC1C,KAAI,CAAC,QAAQ,IAAI,mBAAoB;AACrC,SAAQ,IAAI,kBAAkB,GAAG,KAAK;;AAGxC,IAAI,2BAA2B;AAE/B,SAAgB,6BAAsC;AACpD,QAAO;;;;;;AAOT,SAAgB,sCACd,aACA,YACM;AACN,KAAI,yBAA0B;CAE9B,MAAM,qBAA+B,EAAE;CACvC,MAAM,mBAA6B,EAAE;CAErC,MAAM,WAAW,QAAsB;AACrC,MAAI,CAAC,GAAG,WAAW,IAAI,CAAE;AACzB,OAAK,MAAM,SAAS,GAAG,YAAY,KAAK,EAAE,eAAe,MAAM,CAAC,CAC9D,KAAI,MAAM,aAAa,CACrB,SAAQ,KAAK,KAAK,KAAK,MAAM,KAAK,CAAC;WAC1B,MAAM,SAAS,yBACxB,oBAAmB,KAAK,KAAK,KAAK,KAAK,MAAM,KAAK,CAAC;WAEnD,MAAM,KAAK,SAAS,eAAe,IACnC,MAAM,KAAK,SAAS,MAAM,CAE1B,kBAAiB,KAAK,KAAK,KAAK,KAAK,MAAM,KAAK,CAAC;;AAKvD,SAAQ,YAAY;AAEpB,UACE,sCAAsC,mBAAmB,OAAO,yBAChE,GAAG,iBAAiB,OAAO,qBAC5B;AAED,KAAI,CAAC,mBAAmB,OAGtB;AAIF,4BAA2B;CAK3B,MAAM,iBAAiB,WAAW,QAChC,sCACA,GACD;CAGD,MAAM,YAAY,QAChB,6BAA6B,IAAI;CAEnC,MAAM,cAAc,SAAS,eAAe;;;;;;;CAQ5C,MAAM,oBAAoB,eAA+B;EACvD,MAAM,QAAQ,WAAW,MAAM,KAAK;EAEpC,IAAI,gBAAgB;AACpB,OAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,IAChC,KAAI,YAAY,KAAK,MAAM,GAAG,CAC5B,iBAAgB;AAGpB,MAAI,iBAAiB,GAAG;AAEtB,SAAM,OAAO,gBAAgB,GAAG,GAAG,YAAY;AAC/C,UAAO,MAAM,KAAK,KAAK;;AAGzB,SAAO,CAAC,aAAa,WAAW,CAAC,KAAK,KAAK;;AAG7C,MAAK,MAAM,eAAe,oBAAoB;EAC5C,MAAM,aAAa,GAAG,aAAa,aAAa,OAAO;AACvD,KAAG,cAAc,aAAa,iBAAiB,WAAW,CAAC;AAC3D,WACE,wDAAwD,cACzD;;AAGH,MAAK,MAAM,eAAe,kBAAkB;EAC1C,MAAM,aAAa,GAAG,aAAa,aAAa,OAAO;AACvD,KAAG,cAAc,aAAa,iBAAiB,WAAW,CAAC;AAC3D,WACE,sDAAsD,cACvD;;;;;;;AAQL,SAAgB,2BAA2B,YAA0B;AACnE,UAAS,oCAAoC;CAE7C,MAAM,kBAAkB,GAAG,SAAS;AACpC,IAAG,SAAS,YAAY,eAAe,wBACrC,GAAG,MACuC;EAC1C,MAAM,WAAW,KAAK,GAAG,UAAU;AACnC,WAAS,0BAA0B,SAAS;AAE5C,MACE,CAAC,4BACD,SAAS,SAAS,4BAA4B,CAG9C,uCADoB,SAAS,UAAU,GAAG,SAAS,YAAY,IAAI,CAClB,EAAE,WAAW;AAGhE,SAAO,gBAAgB,MAAM,GAAG,UAAU,KAAK;;CAGjD,MAAM,sBAAsB,GAAG;AAC/B,IAAG,gBAAgB,SAAS,4BAC1B,GAAG,MACG;EACN,MAAM,WAAW,KAAK,GAAG,UAAU;AACnC,WAAS,qBAAqB,SAAS;AAEvC,MACE,CAAC,4BACD,SAAS,SAAS,4BAA4B,CAG9C,uCADoB,SAAS,UAAU,GAAG,SAAS,YAAY,IAAI,CAClB,EAAE,WAAW;AAGhE,sBAAoB,MAAM,IAAI,KAAK"}
|