@fantasticfour/dotenvx-next 0.1.3 → 0.2.1

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.
Files changed (52) hide show
  1. package/README.md +157 -0
  2. package/dist/chunk-CKQMccvm.cjs +28 -0
  3. package/dist/index.cjs +6 -0
  4. package/dist/index.d.cts +2 -1
  5. package/dist/index.d.mts +2 -1
  6. package/dist/index.mjs +2 -1
  7. package/dist/next-env-compat.cjs +29 -11858
  8. package/dist/next-env-compat.cjs.map +1 -1
  9. package/dist/next-env-compat.d.cts +9 -1
  10. package/dist/next-env-compat.d.cts.map +1 -0
  11. package/dist/next-env-compat.d.mts +9 -0
  12. package/dist/next-env-compat.d.mts.map +1 -0
  13. package/dist/next-env-compat.mjs +31 -0
  14. package/dist/next-env-compat.mjs.map +1 -0
  15. package/dist/plugin.cjs +29 -53
  16. package/dist/plugin.cjs.map +1 -1
  17. package/dist/plugin.d.cts +2 -7
  18. package/dist/plugin.d.cts.map +1 -1
  19. package/dist/plugin.d.mts +2 -7
  20. package/dist/plugin.d.mts.map +1 -1
  21. package/dist/plugin.mjs +25 -52
  22. package/dist/plugin.mjs.map +1 -1
  23. package/dist/turbopack-inject.cjs +95 -4
  24. package/dist/turbopack-inject.cjs.map +1 -0
  25. package/dist/turbopack-inject.d.cts +4 -4
  26. package/dist/turbopack-inject.d.cts.map +1 -1
  27. package/dist/turbopack-inject.d.mts +4 -4
  28. package/dist/turbopack-inject.d.mts.map +1 -1
  29. package/dist/turbopack-inject.mjs +12 -14
  30. package/dist/turbopack-inject.mjs.map +1 -1
  31. package/dist/webpack-plugin-BmC1uBZp.mjs +47 -0
  32. package/dist/webpack-plugin-BmC1uBZp.mjs.map +1 -0
  33. package/dist/webpack-plugin.cjs +3 -11
  34. package/dist/webpack-plugin.cjs.map +1 -1
  35. package/dist/webpack-plugin.d.cts +7 -10
  36. package/dist/webpack-plugin.d.cts.map +1 -1
  37. package/dist/webpack-plugin.d.mts +7 -10
  38. package/dist/webpack-plugin.d.mts.map +1 -1
  39. package/dist/webpack-plugin.mjs +1 -51
  40. package/package.json +18 -19
  41. package/dist/chunk-y_GBKt04.mjs +0 -5
  42. package/dist/init.cjs +0 -16
  43. package/dist/init.cjs.map +0 -1
  44. package/dist/init.d.cts +0 -5
  45. package/dist/init.d.cts.map +0 -1
  46. package/dist/init.d.mts +0 -5
  47. package/dist/init.d.mts.map +0 -1
  48. package/dist/init.mjs +0 -18
  49. package/dist/init.mjs.map +0 -1
  50. package/dist/turbopack-inject-BgCxanwa.cjs +0 -139
  51. package/dist/turbopack-inject-BgCxanwa.cjs.map +0 -1
  52. package/dist/webpack-plugin.mjs.map +0 -1
@@ -1 +1,9 @@
1
- export { };
1
+ import * as _$_next_env0 from "@next/env";
2
+ import { Env, LoadedEnvFiles, loadEnvConfig as loadEnvConfig$1 } from "@next/env";
3
+
4
+ //#region src/next-env-compat.d.ts
5
+ declare const initialEnv: Env | undefined, updateInitialEnv: typeof _$_next_env0.updateInitialEnv, processEnv: typeof _$_next_env0.processEnv, resetEnv: typeof _$_next_env0.resetEnv;
6
+ declare function loadEnvConfig(...args: Parameters<typeof loadEnvConfig$1>): ReturnType<typeof loadEnvConfig$1>;
7
+ //#endregion
8
+ export { type Env, type LoadedEnvFiles, initialEnv, loadEnvConfig, processEnv, resetEnv, updateInitialEnv };
9
+ //# sourceMappingURL=next-env-compat.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"next-env-compat.d.cts","names":[],"sources":["../src/next-env-compat.ts"],"mappings":";;;;cAkCE,UAAA,EAAU,GAAA,cACV,gBAAA,SADU,YAAA,CACM,gBAAA,EAChB,UAAA,SADgB,YAAA,CACN,UAAA,EACV,QAAA,SADU,YAAA,CACF,QAAA;AAAA,iBAGM,aAAA,CAAA,GACX,IAAA,EAAM,UAAA,QAAkB,eAAA,IAC1B,UAAA,QAAkB,eAAA"}
@@ -0,0 +1,9 @@
1
+ import * as _$_next_env0 from "@next/env";
2
+ import { Env, LoadedEnvFiles, loadEnvConfig as loadEnvConfig$1 } from "@next/env";
3
+
4
+ //#region src/next-env-compat.d.ts
5
+ declare const initialEnv: Env | undefined, updateInitialEnv: typeof _$_next_env0.updateInitialEnv, processEnv: typeof _$_next_env0.processEnv, resetEnv: typeof _$_next_env0.resetEnv;
6
+ declare function loadEnvConfig(...args: Parameters<typeof loadEnvConfig$1>): ReturnType<typeof loadEnvConfig$1>;
7
+ //#endregion
8
+ export { type Env, type LoadedEnvFiles, initialEnv, loadEnvConfig, processEnv, resetEnv, updateInitialEnv };
9
+ //# sourceMappingURL=next-env-compat.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"next-env-compat.d.mts","names":[],"sources":["../src/next-env-compat.ts"],"mappings":";;;;cAkCE,UAAA,EAAU,GAAA,cACV,gBAAA,SADU,YAAA,CACM,gBAAA,EAChB,UAAA,SADgB,YAAA,CACN,UAAA,EACV,QAAA,SADU,YAAA,CACF,QAAA;AAAA,iBAGM,aAAA,CAAA,GACX,IAAA,EAAM,UAAA,QAAkB,eAAA,IAC1B,UAAA,QAAkB,eAAA"}
@@ -0,0 +1,31 @@
1
+ import { createRequire } from "node:module";
2
+ import dotenvx from "@dotenvx/dotenvx";
3
+ //#region src/next-env-compat.ts
4
+ /**
5
+ * Drop-in replacement for @next/env that wraps loadEnvConfig to also call
6
+ * dotenvx.config() so dotenvx-decrypted values are present in process.env
7
+ * whenever loadEnvConfig is invoked.
8
+ *
9
+ * Two coverage levels:
10
+ *
11
+ * 1. Webpack alias (partial): plugin.ts sets webpack resolve.alias['@next/env']
12
+ * to this module. Intercepts imports of @next/env INSIDE webpack-bundled code
13
+ * (hot-reload handlers, preview mode helpers in the server bundle).
14
+ * Does NOT cover Next.js's own Node.js startup calls to loadEnvConfig, which
15
+ * happen before webpack runs.
16
+ *
17
+ * 2. npm overrides (full): users add "@next/env" → "@fantasticfour/dotenvx-next"
18
+ * in package.json overrides/resolutions. Node.js resolves require('@next/env')
19
+ * to this package's CJS entry, which re-exports loadEnvConfig, covering startup.
20
+ *
21
+ * @next/env is CJS-only, so createRequire is used to load it from ESM.
22
+ */
23
+ const { loadEnvConfig: originalLoadEnvConfig, initialEnv, updateInitialEnv, processEnv, resetEnv } = createRequire(import.meta.url)("@next/env");
24
+ function loadEnvConfig(...args) {
25
+ dotenvx.config({ quiet: true });
26
+ return originalLoadEnvConfig(...args);
27
+ }
28
+ //#endregion
29
+ export { initialEnv, loadEnvConfig, processEnv, resetEnv, updateInitialEnv };
30
+
31
+ //# sourceMappingURL=next-env-compat.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"next-env-compat.mjs","names":[],"sources":["../src/next-env-compat.ts"],"sourcesContent":["/**\n * Drop-in replacement for @next/env that wraps loadEnvConfig to also call\n * dotenvx.config() so dotenvx-decrypted values are present in process.env\n * whenever loadEnvConfig is invoked.\n *\n * Two coverage levels:\n *\n * 1. Webpack alias (partial): plugin.ts sets webpack resolve.alias['@next/env']\n * to this module. Intercepts imports of @next/env INSIDE webpack-bundled code\n * (hot-reload handlers, preview mode helpers in the server bundle).\n * Does NOT cover Next.js's own Node.js startup calls to loadEnvConfig, which\n * happen before webpack runs.\n *\n * 2. npm overrides (full): users add \"@next/env\" → \"@fantasticfour/dotenvx-next\"\n * in package.json overrides/resolutions. Node.js resolves require('@next/env')\n * to this package's CJS entry, which re-exports loadEnvConfig, covering startup.\n *\n * @next/env is CJS-only, so createRequire is used to load it from ESM.\n */\n\nimport { createRequire } from 'node:module';\nimport dotenvx from '@dotenvx/dotenvx';\nimport type {\n Env,\n LoadedEnvFiles,\n loadEnvConfig as LoadEnvConfigFn,\n} from '@next/env';\n\nconst require = createRequire(import.meta.url);\n\nconst nextEnv = require('@next/env') as typeof import('@next/env');\n\nconst {\n loadEnvConfig: originalLoadEnvConfig,\n initialEnv,\n updateInitialEnv,\n processEnv,\n resetEnv,\n} = nextEnv;\n\nexport function loadEnvConfig(\n ...args: Parameters<typeof LoadEnvConfigFn>\n): ReturnType<typeof LoadEnvConfigFn> {\n dotenvx.config({ quiet: true });\n return originalLoadEnvConfig(...args);\n}\n\nexport type { Env, LoadedEnvFiles };\nexport { initialEnv, updateInitialEnv, processEnv, resetEnv };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAM,EACJ,eAAe,uBACf,YACA,kBACA,YACA,aATc,cAAc,OAAO,KAAK,IAEnB,CAAC,YAQb;AAEX,SAAgB,cACd,GAAG,MACiC;AACpC,SAAQ,OAAO,EAAE,OAAO,MAAM,CAAC;AAC/B,QAAO,sBAAsB,GAAG,KAAK"}
package/dist/plugin.cjs CHANGED
@@ -1,28 +1,32 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_turbopack_inject = require("./turbopack-inject-BgCxanwa.cjs");
2
+ const require_chunk = require("./chunk-CKQMccvm.cjs");
3
3
  const require_webpack_plugin = require("./webpack-plugin.cjs");
4
+ const require_turbopack_inject = require("./turbopack-inject.cjs");
4
5
  let node_fs = require("node:fs");
5
- node_fs = require_turbopack_inject.__toESM(node_fs, 1);
6
+ node_fs = require_chunk.__toESM(node_fs, 1);
6
7
  let node_path = require("node:path");
7
- node_path = require_turbopack_inject.__toESM(node_path, 1);
8
+ node_path = require_chunk.__toESM(node_path, 1);
9
+ let node_url = require("node:url");
10
+ let _dotenvx_dotenvx = require("@dotenvx/dotenvx");
11
+ _dotenvx_dotenvx = require_chunk.__toESM(_dotenvx_dotenvx, 1);
8
12
  //#region src/plugin.ts
9
13
  /**
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.
14
+ * withDotenvx() — Next.js config wrapper that loads dotenvx secrets at build time
15
+ * and inlines them into the webpack/turbopack runtime so they are available before
16
+ * any user code evaluates (Prisma Pool, etc.) at module-load time.
12
17
  *
13
18
  * 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.
19
+ * - At build time, call dotenvx.config() to decrypt env files and capture the
20
+ * resolved key-value pairs.
21
+ * - Webpack builds: prepend Object.assign(process.env, {...}) into webpack-runtime.js
22
+ * via DotenvxWebpackPlugin (processAssets hook at PROCESS_ASSETS_STAGE_ADDITIONS).
23
+ * - Turbopack builds: patch fs.writeFile to detect compilation completion and inject
24
+ * the same snippet into [turbopack]_runtime.js files.
25
+ * - Webpack alias: aliases @next/env inside webpack-bundled code only (hot-reload,
26
+ * preview mode). Does NOT cover Next.js's pre-webpack startup calls — use npm
27
+ * overrides for full coverage. See README.
20
28
  */
21
- const DEFAULT_ENV_FILES = [
22
- ".env.base",
23
- ".env.production",
24
- ".env.preview"
25
- ];
29
+ const DEFAULT_ENV_FILES = [".env"];
26
30
  const PLUGIN_DEBUG = !!process.env.DEBUG_DOTENVX_NEXT;
27
31
  function debugLog(...args) {
28
32
  if (!PLUGIN_DEBUG) return;
@@ -31,59 +35,31 @@ function debugLog(...args) {
31
35
  function resolveExistingFiles(files, envDir) {
32
36
  return files.map((f) => node_path.default.resolve(envDir, f)).filter((absPath) => node_fs.default.existsSync(absPath));
33
37
  }
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
38
  async function dotenvxNextConfigFn(nextConfig, options, phase, defaults) {
47
39
  let resolvedNextConfig;
48
40
  if (typeof nextConfig === "function") resolvedNextConfig = { ...await nextConfig(phase, defaults) };
49
41
  else resolvedNextConfig = { ...nextConfig };
50
42
  const envDir = options.envDir ?? process.cwd();
51
43
  const resolvedFiles = resolveExistingFiles(options.files ?? DEFAULT_ENV_FILES, envDir);
52
- const shouldTrace = options.traceEnvFiles !== false;
53
44
  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
- }
45
+ const { parsed: env = {} } = resolvedFiles.length ? _dotenvx_dotenvx.default.config({
46
+ path: resolvedFiles,
47
+ overload: true,
48
+ quiet: true
49
+ }) : { parsed: {} };
50
+ debugLog(`phase=${phase}, isTurbopack=${isTurbopack}, resolvedFiles=${JSON.stringify(resolvedFiles)}, envKeys=${Object.keys(env).join(",")}`);
51
+ if (isTurbopack) require_turbopack_inject.activateTurbopackInjection(env);
68
52
  const prevWebpack = resolvedNextConfig.webpack;
69
53
  resolvedNextConfig.webpack = (webpackConfig, webpackOptions) => {
70
54
  const config = prevWebpack ? prevWebpack(webpackConfig, webpackOptions) : webpackConfig;
55
+ if (!isTurbopack) config.plugins.push(new require_webpack_plugin.DotenvxWebpackPlugin({ env }));
71
56
  config.resolve ??= {};
72
57
  config.resolve.alias ??= {};
73
58
  const alias = config.resolve.alias;
74
59
  try {
75
60
  alias["@next/env"] = require.resolve("@fantasticfour/dotenvx-next/next-env");
76
61
  } 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);
62
+ alias["@next/env"] = (0, node_url.fileURLToPath)(new URL("./next-env-compat.js", require("url").pathToFileURL(__filename).href));
87
63
  }
88
64
  return config;
89
65
  };
@@ -1 +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"}
1
+ {"version":3,"file":"plugin.cjs","names":["path","fs","dotenvx","DotenvxWebpackPlugin"],"sources":["../src/plugin.ts"],"sourcesContent":["/**\n * withDotenvx() — Next.js config wrapper that loads dotenvx secrets at build time\n * and inlines them into the webpack/turbopack runtime so they are available before\n * any user code evaluates (Prisma Pool, etc.) at module-load time.\n *\n * Strategy:\n * - At build time, call dotenvx.config() to decrypt env files and capture the\n * resolved key-value pairs.\n * - Webpack builds: prepend Object.assign(process.env, {...}) into webpack-runtime.js\n * via DotenvxWebpackPlugin (processAssets hook at PROCESS_ASSETS_STAGE_ADDITIONS).\n * - Turbopack builds: patch fs.writeFile to detect compilation completion and inject\n * the same snippet into [turbopack]_runtime.js files.\n * - Webpack alias: aliases @next/env inside webpack-bundled code only (hot-reload,\n * preview mode). Does NOT cover Next.js's pre-webpack startup calls — use npm\n * overrides for full coverage. See README.\n */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { NextConfig } from 'next';\nimport dotenvx from '@dotenvx/dotenvx';\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'], filtered to files that actually\n * 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\nconst DEFAULT_ENV_FILES = ['.env'];\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\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\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 // Decrypt and resolve env values at build time.\n // parsed contains only the keys from the specified files (not all of process.env).\n const { parsed: env = {} } = resolvedFiles.length\n ? dotenvx.config({ path: resolvedFiles, overload: true, quiet: true })\n : { parsed: {} };\n\n debugLog(\n `phase=${phase}, isTurbopack=${isTurbopack}, resolvedFiles=${JSON.stringify(resolvedFiles)}, envKeys=${Object.keys(env).join(',')}`\n );\n\n if (isTurbopack) {\n activateTurbopackInjection(env);\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 // Register the webpack plugin to inject the env snippet into runtime files\n if (!isTurbopack) {\n (config.plugins as unknown[]).push(new DotenvxWebpackPlugin({ env }));\n }\n\n // Alias @next/env → compat shim for webpack-bundled code paths (hot-reload, etc.).\n // Does NOT cover Next.js startup calls before webpack. See README for npm overrides.\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 try {\n alias['@next/env'] = require.resolve(\n '@fantasticfour/dotenvx-next/next-env'\n );\n } catch {\n // Local dev: package not installed under that name — resolve relative to this file\n alias['@next/env'] = fileURLToPath(\n new URL('./next-env-compat.js', import.meta.url)\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,OAAO;AAElC,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;;AAQhD,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;CAG7D,MAAM,cAAc,CAAC,EACnB,QAAQ,IAAI,aACZ,QAAQ,IAAI,iBACZ,QAAQ,IAAI,mBACZ,QAAQ,IAAI;CAKd,MAAM,EAAE,QAAQ,MAAM,EAAE,KAAK,cAAc,SACvCC,iBAAAA,QAAQ,OAAO;EAAE,MAAM;EAAe,UAAU;EAAM,OAAO;EAAM,CAAC,GACpE,EAAE,QAAQ,EAAE,EAAE;AAElB,UACE,SAAS,MAAM,gBAAgB,YAAY,kBAAkB,KAAK,UAAU,cAAc,CAAC,YAAY,OAAO,KAAK,IAAI,CAAC,KAAK,IAAI,GAClI;AAED,KAAI,YACF,0BAAA,2BAA2B,IAAI;CAIjC,MAAM,cAAc,mBAAmB;AAEvC,oBAAmB,WAAW,eAAe,mBAAmB;EAG9D,MAAM,SAAS,cACX,YAAY,eAAe,eAAe,GAC1C;AAGJ,MAAI,CAAC,YACF,QAAO,QAAsB,KAAK,IAAIC,uBAAAA,qBAAqB,EAAE,KAAK,CAAC,CAAC;AAKvE,SAAO,YAAY,EAAE;AACpB,SAAO,QAAoC,UAAU,EAAE;EACxD,MAAM,QAAS,OAAO,QAAoC;AAI1D,MAAI;AACF,SAAM,eAAe,QAAQ,QAC3B,uCACD;UACK;AAEN,SAAM,gBAAA,GAAA,SAAA,eACJ,IAAI,IAAI,wBAAA,QAAA,MAAA,CAAA,cAAA,WAAA,CAAA,KAAwC,CACjD;;AAGH,SAAO;;AAGT,QAAO;;AAGT,SAAgB,YACd,YACA,UAA8B,EAAE,EAClB;AACd,SAAQ,OAAe,aACrB,oBAAoB,YAAY,SAAS,OAAO,SAAS"}
package/dist/plugin.d.cts CHANGED
@@ -3,19 +3,14 @@ import { NextConfig } from "next";
3
3
  //#region src/plugin.d.ts
4
4
  interface DotenvxNextOptions {
5
5
  /**
6
- * Env files to load. Defaults to ['.env.base', '.env.production', '.env.preview'],
7
- * filtered to files that actually exist in envDir.
6
+ * Env files to load. Defaults to ['.env'], filtered to files that actually
7
+ * exist in envDir.
8
8
  */
9
9
  files?: string[];
10
10
  /**
11
11
  * Directory where env files live. Defaults to process.cwd().
12
12
  */
13
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
14
  }
20
15
  type NextConfigFn = (phase: string, defaults: {
21
16
  defaultConfig: NextConfig;
@@ -1 +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"}
1
+ {"version":3,"file":"plugin.d.cts","names":[],"sources":["../src/plugin.ts"],"mappings":";;;UAyBiB,kBAAA;EA8BH;;;;EAzBZ,KAAA;EA0BwB;;;EArBxB,MAAA;AAAA;AAAA,KAkBG,YAAA,IACH,KAAA,UACA,QAAA;EAAY,aAAA,EAAe,UAAA;AAAA,MACxB,UAAA,GAAa,OAAA,CAAQ,UAAA;AAAA,iBAqFV,WAAA,CACd,UAAA,EAAY,UAAA,GAAa,YAAA,EACzB,OAAA,GAAS,kBAAA,GACR,YAAA"}
package/dist/plugin.d.mts CHANGED
@@ -3,19 +3,14 @@ import { NextConfig } from "next";
3
3
  //#region src/plugin.d.ts
4
4
  interface DotenvxNextOptions {
5
5
  /**
6
- * Env files to load. Defaults to ['.env.base', '.env.production', '.env.preview'],
7
- * filtered to files that actually exist in envDir.
6
+ * Env files to load. Defaults to ['.env'], filtered to files that actually
7
+ * exist in envDir.
8
8
  */
9
9
  files?: string[];
10
10
  /**
11
11
  * Directory where env files live. Defaults to process.cwd().
12
12
  */
13
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
14
  }
20
15
  type NextConfigFn = (phase: string, defaults: {
21
16
  defaultConfig: NextConfig;
@@ -1 +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"}
1
+ {"version":3,"file":"plugin.d.mts","names":[],"sources":["../src/plugin.ts"],"mappings":";;;UAyBiB,kBAAA;EA8BH;;;;EAzBZ,KAAA;EA0BwB;;;EArBxB,MAAA;AAAA;AAAA,KAkBG,YAAA,IACH,KAAA,UACA,QAAA;EAAY,aAAA,EAAe,UAAA;AAAA,MACxB,UAAA,GAAa,OAAA,CAAQ,UAAA;AAAA,iBAqFV,WAAA,CACd,UAAA,EAAY,UAAA,GAAa,YAAA,EACzB,OAAA,GAAS,kBAAA,GACR,YAAA"}
package/dist/plugin.mjs CHANGED
@@ -1,26 +1,27 @@
1
- import { t as __require } from "./chunk-y_GBKt04.mjs";
2
- import { DotenvxWebpackPlugin } from "./webpack-plugin.mjs";
1
+ import { n as __require, t as DotenvxWebpackPlugin } from "./webpack-plugin-BmC1uBZp.mjs";
3
2
  import { activateTurbopackInjection } from "./turbopack-inject.mjs";
4
3
  import fs from "node:fs";
5
4
  import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import dotenvx from "@dotenvx/dotenvx";
6
7
  //#region src/plugin.ts
7
8
  /**
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.
9
+ * withDotenvx() — Next.js config wrapper that loads dotenvx secrets at build time
10
+ * and inlines them into the webpack/turbopack runtime so they are available before
11
+ * any user code evaluates (Prisma Pool, etc.) at module-load time.
10
12
  *
11
13
  * 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.
14
+ * - At build time, call dotenvx.config() to decrypt env files and capture the
15
+ * resolved key-value pairs.
16
+ * - Webpack builds: prepend Object.assign(process.env, {...}) into webpack-runtime.js
17
+ * via DotenvxWebpackPlugin (processAssets hook at PROCESS_ASSETS_STAGE_ADDITIONS).
18
+ * - Turbopack builds: patch fs.writeFile to detect compilation completion and inject
19
+ * the same snippet into [turbopack]_runtime.js files.
20
+ * - Webpack alias: aliases @next/env inside webpack-bundled code only (hot-reload,
21
+ * preview mode). Does NOT cover Next.js's pre-webpack startup calls — use npm
22
+ * overrides for full coverage. See README.
18
23
  */
19
- const DEFAULT_ENV_FILES = [
20
- ".env.base",
21
- ".env.production",
22
- ".env.preview"
23
- ];
24
+ const DEFAULT_ENV_FILES = [".env"];
24
25
  const PLUGIN_DEBUG = !!process.env.DEBUG_DOTENVX_NEXT;
25
26
  function debugLog(...args) {
26
27
  if (!PLUGIN_DEBUG) return;
@@ -29,59 +30,31 @@ function debugLog(...args) {
29
30
  function resolveExistingFiles(files, envDir) {
30
31
  return files.map((f) => path.resolve(envDir, f)).filter((absPath) => fs.existsSync(absPath));
31
32
  }
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
33
  async function dotenvxNextConfigFn(nextConfig, options, phase, defaults) {
45
34
  let resolvedNextConfig;
46
35
  if (typeof nextConfig === "function") resolvedNextConfig = { ...await nextConfig(phase, defaults) };
47
36
  else resolvedNextConfig = { ...nextConfig };
48
37
  const envDir = options.envDir ?? process.cwd();
49
38
  const resolvedFiles = resolveExistingFiles(options.files ?? DEFAULT_ENV_FILES, envDir);
50
- const shouldTrace = options.traceEnvFiles !== false;
51
39
  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
- }
40
+ const { parsed: env = {} } = resolvedFiles.length ? dotenvx.config({
41
+ path: resolvedFiles,
42
+ overload: true,
43
+ quiet: true
44
+ }) : { parsed: {} };
45
+ debugLog(`phase=${phase}, isTurbopack=${isTurbopack}, resolvedFiles=${JSON.stringify(resolvedFiles)}, envKeys=${Object.keys(env).join(",")}`);
46
+ if (isTurbopack) activateTurbopackInjection(env);
66
47
  const prevWebpack = resolvedNextConfig.webpack;
67
48
  resolvedNextConfig.webpack = (webpackConfig, webpackOptions) => {
68
49
  const config = prevWebpack ? prevWebpack(webpackConfig, webpackOptions) : webpackConfig;
50
+ if (!isTurbopack) config.plugins.push(new DotenvxWebpackPlugin({ env }));
69
51
  config.resolve ??= {};
70
52
  config.resolve.alias ??= {};
71
53
  const alias = config.resolve.alias;
72
54
  try {
73
55
  alias["@next/env"] = __require.resolve("@fantasticfour/dotenvx-next/next-env");
74
56
  } 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);
57
+ alias["@next/env"] = fileURLToPath(new URL("./next-env-compat.js", import.meta.url));
85
58
  }
86
59
  return config;
87
60
  };
@@ -1 +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"}
1
+ {"version":3,"file":"plugin.mjs","names":[],"sources":["../src/plugin.ts"],"sourcesContent":["/**\n * withDotenvx() — Next.js config wrapper that loads dotenvx secrets at build time\n * and inlines them into the webpack/turbopack runtime so they are available before\n * any user code evaluates (Prisma Pool, etc.) at module-load time.\n *\n * Strategy:\n * - At build time, call dotenvx.config() to decrypt env files and capture the\n * resolved key-value pairs.\n * - Webpack builds: prepend Object.assign(process.env, {...}) into webpack-runtime.js\n * via DotenvxWebpackPlugin (processAssets hook at PROCESS_ASSETS_STAGE_ADDITIONS).\n * - Turbopack builds: patch fs.writeFile to detect compilation completion and inject\n * the same snippet into [turbopack]_runtime.js files.\n * - Webpack alias: aliases @next/env inside webpack-bundled code only (hot-reload,\n * preview mode). Does NOT cover Next.js's pre-webpack startup calls — use npm\n * overrides for full coverage. See README.\n */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { NextConfig } from 'next';\nimport dotenvx from '@dotenvx/dotenvx';\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'], filtered to files that actually\n * 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\nconst DEFAULT_ENV_FILES = ['.env'];\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\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\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 // Decrypt and resolve env values at build time.\n // parsed contains only the keys from the specified files (not all of process.env).\n const { parsed: env = {} } = resolvedFiles.length\n ? dotenvx.config({ path: resolvedFiles, overload: true, quiet: true })\n : { parsed: {} };\n\n debugLog(\n `phase=${phase}, isTurbopack=${isTurbopack}, resolvedFiles=${JSON.stringify(resolvedFiles)}, envKeys=${Object.keys(env).join(',')}`\n );\n\n if (isTurbopack) {\n activateTurbopackInjection(env);\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 // Register the webpack plugin to inject the env snippet into runtime files\n if (!isTurbopack) {\n (config.plugins as unknown[]).push(new DotenvxWebpackPlugin({ env }));\n }\n\n // Alias @next/env → compat shim for webpack-bundled code paths (hot-reload, etc.).\n // Does NOT cover Next.js startup calls before webpack. See README for npm overrides.\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 try {\n alias['@next/env'] = require.resolve(\n '@fantasticfour/dotenvx-next/next-env'\n );\n } catch {\n // Local dev: package not installed under that name — resolve relative to this file\n alias['@next/env'] = fileURLToPath(\n new URL('./next-env-compat.js', import.meta.url)\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,OAAO;AAElC,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;;AAQhD,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;CAG7D,MAAM,cAAc,CAAC,EACnB,QAAQ,IAAI,aACZ,QAAQ,IAAI,iBACZ,QAAQ,IAAI,mBACZ,QAAQ,IAAI;CAKd,MAAM,EAAE,QAAQ,MAAM,EAAE,KAAK,cAAc,SACvC,QAAQ,OAAO;EAAE,MAAM;EAAe,UAAU;EAAM,OAAO;EAAM,CAAC,GACpE,EAAE,QAAQ,EAAE,EAAE;AAElB,UACE,SAAS,MAAM,gBAAgB,YAAY,kBAAkB,KAAK,UAAU,cAAc,CAAC,YAAY,OAAO,KAAK,IAAI,CAAC,KAAK,IAAI,GAClI;AAED,KAAI,YACF,4BAA2B,IAAI;CAIjC,MAAM,cAAc,mBAAmB;AAEvC,oBAAmB,WAAW,eAAe,mBAAmB;EAG9D,MAAM,SAAS,cACX,YAAY,eAAe,eAAe,GAC1C;AAGJ,MAAI,CAAC,YACF,QAAO,QAAsB,KAAK,IAAI,qBAAqB,EAAE,KAAK,CAAC,CAAC;AAKvE,SAAO,YAAY,EAAE;AACpB,SAAO,QAAoC,UAAU,EAAE;EACxD,MAAM,QAAS,OAAO,QAAoC;AAI1D,MAAI;AACF,SAAM,eAAA,UAAuB,QAC3B,uCACD;UACK;AAEN,SAAM,eAAe,cACnB,IAAI,IAAI,wBAAwB,OAAO,KAAK,IAAI,CACjD;;AAGH,SAAO;;AAGT,QAAO;;AAGT,SAAgB,YACd,YACA,UAA8B,EAAE,EAClB;AACd,SAAQ,OAAe,aACrB,oBAAoB,YAAY,SAAS,OAAO,SAAS"}
@@ -1,5 +1,96 @@
1
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;
2
+ const require_chunk = require("./chunk-CKQMccvm.cjs");
3
+ let node_fs = require("node:fs");
4
+ node_fs = require_chunk.__toESM(node_fs, 1);
5
+ let node_path = require("node:path");
6
+ node_path = require_chunk.__toESM(node_path, 1);
7
+ //#region src/turbopack-inject.ts
8
+ /**
9
+ * Turbopack runtime injection — patches fs.writeFile/fs.writeFileSync to intercept
10
+ * turbopack's build output and prepend the env inline snippet into runtime files.
11
+ *
12
+ * Turbopack writes `[turbopack]_runtime.js` directly (bypassing webpack), so we
13
+ * can't use the processAssets hook. Instead we intercept fs writes and inject when
14
+ * export-detail.json is written (signals compilation is complete).
15
+ */
16
+ function debugLog(...args) {
17
+ if (!process.env.DEBUG_DOTENVX_NEXT) return;
18
+ console.log("[dotenvx-next]", ...args);
19
+ }
20
+ let injectedTurbopackRuntime = false;
21
+ function isInjectedTurbopackRuntime() {
22
+ return injectedTurbopackRuntime;
23
+ }
24
+ /**
25
+ * Inject the env inline snippet into turbopack runtime files.
26
+ * Called after export-detail.json is written (turbopack compilation complete).
27
+ */
28
+ function injectDotenvxInitIntoTurbopackRuntime(nextDirPath, env) {
29
+ if (injectedTurbopackRuntime) return;
30
+ const serverRuntimeFiles = [];
31
+ const edgeWrapperFiles = [];
32
+ const walkDir = (dir) => {
33
+ if (!node_fs.default.existsSync(dir)) return;
34
+ for (const entry of node_fs.default.readdirSync(dir, { withFileTypes: true })) if (entry.isDirectory()) walkDir(node_path.default.join(dir, entry.name));
35
+ else if (entry.name === "[turbopack]_runtime.js") serverRuntimeFiles.push(node_path.default.join(dir, entry.name));
36
+ else if (entry.name.includes("edge-wrapper") && entry.name.endsWith(".js")) edgeWrapperFiles.push(node_path.default.join(dir, entry.name));
37
+ };
38
+ walkDir(nextDirPath);
39
+ debugLog(`turbopack runtime injection: found ${serverRuntimeFiles.length} server runtime files,`, `${edgeWrapperFiles.length} edge wrapper files`);
40
+ if (!serverRuntimeFiles.length) return;
41
+ injectedTurbopackRuntime = true;
42
+ const inlineSnippet = `(function(){if(typeof process!=='undefined'){Object.assign(process.env,${JSON.stringify(env)});}})();`;
43
+ /**
44
+ * Insert inlineSnippet into source respecting ESM constraints.
45
+ * ESM files require all top-level `import` declarations to appear before any
46
+ * other statements, so we must insert after the last import line rather than
47
+ * prepending to the file.
48
+ */
49
+ const insertIntoSource = (origSource) => {
50
+ const lines = origSource.split("\n");
51
+ let lastImportIdx = -1;
52
+ for (let i = 0; i < lines.length; i++) if (/^import\s/.test(lines[i])) lastImportIdx = i;
53
+ if (lastImportIdx >= 0) {
54
+ lines.splice(lastImportIdx + 1, 0, inlineSnippet);
55
+ return lines.join("\n");
56
+ }
57
+ return [inlineSnippet, origSource].join("\n");
58
+ };
59
+ for (const runtimeFile of serverRuntimeFiles) {
60
+ const origSource = node_fs.default.readFileSync(runtimeFile, "utf8");
61
+ node_fs.default.writeFileSync(runtimeFile, insertIntoSource(origSource));
62
+ debugLog(`injected env into turbopack server runtime: ${runtimeFile}`);
63
+ }
64
+ for (const wrapperFile of edgeWrapperFiles) {
65
+ const origSource = node_fs.default.readFileSync(wrapperFile, "utf8");
66
+ node_fs.default.writeFileSync(wrapperFile, insertIntoSource(origSource));
67
+ debugLog(`injected env into turbopack edge wrapper: ${wrapperFile}`);
68
+ }
69
+ }
70
+ /**
71
+ * Patch global fs methods to detect when turbopack compilation completes,
72
+ * then trigger runtime injection.
73
+ */
74
+ function activateTurbopackInjection(env) {
75
+ debugLog("activating turbopack fs intercept");
76
+ const origWriteFileFn = node_fs.default.promises.writeFile;
77
+ node_fs.default.promises.writeFile = async function dotenvxPatchedWriteFile(...args) {
78
+ const filePath = args[0].toString();
79
+ debugLog("fs.promises.writeFile:", filePath);
80
+ if (!injectedTurbopackRuntime && filePath.endsWith("/.next/export-detail.json")) injectDotenvxInitIntoTurbopackRuntime(filePath.substring(0, filePath.lastIndexOf("/")), env);
81
+ return origWriteFileFn.apply(node_fs.default.promises, args);
82
+ };
83
+ const origWriteFileSyncFn = node_fs.default.writeFileSync;
84
+ node_fs.default.writeFileSync = function dotenvxPatchedWriteFileSync(...args) {
85
+ const filePath = args[0].toString();
86
+ debugLog("fs.writeFileSync:", filePath);
87
+ if (!injectedTurbopackRuntime && filePath.endsWith("/.next/export-detail.json")) injectDotenvxInitIntoTurbopackRuntime(filePath.substring(0, filePath.lastIndexOf("/")), env);
88
+ origWriteFileSyncFn.apply(node_fs.default, args);
89
+ };
90
+ }
91
+ //#endregion
92
+ exports.activateTurbopackInjection = activateTurbopackInjection;
93
+ exports.injectDotenvxInitIntoTurbopackRuntime = injectDotenvxInitIntoTurbopackRuntime;
94
+ exports.isInjectedTurbopackRuntime = isInjectedTurbopackRuntime;
95
+
96
+ //# sourceMappingURL=turbopack-inject.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"turbopack-inject.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 env inline snippet 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 env inline snippet into turbopack runtime files.\n * Called after export-detail.json is written (turbopack compilation complete).\n */\nexport function injectDotenvxInitIntoTurbopackRuntime(\n nextDirPath: string,\n env: Record<string, 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 // Inline snippet: assign build-time-resolved values into process.env at runtime.\n const inlineSnippet = `(function(){if(typeof process!=='undefined'){Object.assign(process.env,${JSON.stringify(env)});}})();`;\n\n /**\n * Insert inlineSnippet 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, inlineSnippet);\n return lines.join('\\n');\n }\n // CJS or no imports — prepend\n return [inlineSnippet, 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(`injected env into turbopack server runtime: ${runtimeFile}`);\n }\n\n for (const wrapperFile of edgeWrapperFiles) {\n const origSource = fs.readFileSync(wrapperFile, 'utf8');\n fs.writeFileSync(wrapperFile, insertIntoSource(origSource));\n debugLog(`injected env into turbopack edge wrapper: ${wrapperFile}`);\n }\n}\n\n/**\n * Patch global fs methods to detect when turbopack compilation completes,\n * then trigger runtime injection.\n */\nexport function activateTurbopackInjection(env: Record<string, 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, env);\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, env);\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,KACM;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;CAG3B,MAAM,gBAAgB,0EAA0E,KAAK,UAAU,IAAI,CAAC;;;;;;;CAQpH,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,cAAc;AACjD,UAAO,MAAM,KAAK,KAAK;;AAGzB,SAAO,CAAC,eAAe,WAAW,CAAC,KAAK,KAAK;;AAG/C,MAAK,MAAM,eAAe,oBAAoB;EAC5C,MAAM,aAAaD,QAAAA,QAAG,aAAa,aAAa,OAAO;AACvD,UAAA,QAAG,cAAc,aAAa,iBAAiB,WAAW,CAAC;AAC3D,WAAS,+CAA+C,cAAc;;AAGxE,MAAK,MAAM,eAAe,kBAAkB;EAC1C,MAAM,aAAaA,QAAAA,QAAG,aAAa,aAAa,OAAO;AACvD,UAAA,QAAG,cAAc,aAAa,iBAAiB,WAAW,CAAC;AAC3D,WAAS,6CAA6C,cAAc;;;;;;;AAQxE,SAAgB,2BAA2B,KAAmC;AAC5E,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,IAAI;AAGzD,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,IAAI;AAGzD,sBAAoB,MAAMA,QAAAA,SAAI,KAAK"}
@@ -1,7 +1,7 @@
1
1
  //#region src/turbopack-inject.d.ts
2
2
  /**
3
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.
4
+ * turbopack's build output and prepend the env inline snippet into runtime files.
5
5
  *
6
6
  * Turbopack writes `[turbopack]_runtime.js` directly (bypassing webpack), so we
7
7
  * can't use the processAssets hook. Instead we intercept fs writes and inject when
@@ -9,15 +9,15 @@
9
9
  */
10
10
  declare function isInjectedTurbopackRuntime(): boolean;
11
11
  /**
12
- * Inject the dotenvx init bundle into turbopack runtime files.
12
+ * Inject the env inline snippet into turbopack runtime files.
13
13
  * Called after export-detail.json is written (turbopack compilation complete).
14
14
  */
15
- declare function injectDotenvxInitIntoTurbopackRuntime(nextDirPath: string, initSource: string): void;
15
+ declare function injectDotenvxInitIntoTurbopackRuntime(nextDirPath: string, env: Record<string, string>): void;
16
16
  /**
17
17
  * Patch global fs methods to detect when turbopack compilation completes,
18
18
  * then trigger runtime injection.
19
19
  */
20
- declare function activateTurbopackInjection(initSource: string): void;
20
+ declare function activateTurbopackInjection(env: Record<string, string>): void;
21
21
  //#endregion
22
22
  export { activateTurbopackInjection, injectDotenvxInitIntoTurbopackRuntime, isInjectedTurbopackRuntime };
23
23
  //# sourceMappingURL=turbopack-inject.d.cts.map
@@ -1 +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"}
1
+ {"version":3,"file":"turbopack-inject.d.cts","names":[],"sources":["../src/turbopack-inject.ts"],"mappings":";;AAmBA;;;;;AAQA;;iBARgB,0BAAA,CAAA;;;;;iBAQA,qCAAA,CACd,WAAA,UACA,GAAA,EAAK,MAAA;;AAmFP;;;iBAAgB,0BAAA,CAA2B,GAAA,EAAK,MAAA"}