@fantasticfour/dotenvx-next 0.2.0 → 0.2.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.
@@ -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,12 +1,14 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_turbopack_inject = require("./turbopack-inject-BElH61NN.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");
8
10
  let _dotenvx_dotenvx = require("@dotenvx/dotenvx");
9
- _dotenvx_dotenvx = require_turbopack_inject.__toESM(_dotenvx_dotenvx, 1);
11
+ _dotenvx_dotenvx = require_chunk.__toESM(_dotenvx_dotenvx, 1);
10
12
  //#region src/plugin.ts
11
13
  /**
12
14
  * withDotenvx() — Next.js config wrapper that loads dotenvx secrets at build time
@@ -20,8 +22,9 @@ _dotenvx_dotenvx = require_turbopack_inject.__toESM(_dotenvx_dotenvx, 1);
20
22
  * via DotenvxWebpackPlugin (processAssets hook at PROCESS_ASSETS_STAGE_ADDITIONS).
21
23
  * - Turbopack builds: patch fs.writeFile to detect compilation completion and inject
22
24
  * the same snippet into [turbopack]_runtime.js files.
23
- * - Also aliases @next/env → @fantasticfour/dotenvx-next/next-env so dotenvx
24
- * secrets are available during Next.js config evaluation itself.
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.
25
28
  */
26
29
  const DEFAULT_ENV_FILES = [".env"];
27
30
  const PLUGIN_DEBUG = !!process.env.DEBUG_DOTENVX_NEXT;
@@ -49,15 +52,15 @@ async function dotenvxNextConfigFn(nextConfig, options, phase, defaults) {
49
52
  const prevWebpack = resolvedNextConfig.webpack;
50
53
  resolvedNextConfig.webpack = (webpackConfig, webpackOptions) => {
51
54
  const config = prevWebpack ? prevWebpack(webpackConfig, webpackOptions) : webpackConfig;
55
+ if (!isTurbopack) config.plugins.push(new require_webpack_plugin.DotenvxWebpackPlugin({ env }));
52
56
  config.resolve ??= {};
53
57
  config.resolve.alias ??= {};
54
58
  const alias = config.resolve.alias;
55
59
  try {
56
60
  alias["@next/env"] = require.resolve("@fantasticfour/dotenvx-next/next-env");
57
61
  } catch {
58
- debugLog("Could not resolve @fantasticfour/dotenvx-next/next-env for alias — skipping");
62
+ alias["@next/env"] = (0, node_url.fileURLToPath)(new URL("./next-env-compat.js", require("url").pathToFileURL(__filename).href));
59
63
  }
60
- if (!isTurbopack) config.plugins.push(new require_webpack_plugin.DotenvxWebpackPlugin({ env }));
61
64
  return config;
62
65
  };
63
66
  return resolvedNextConfig;
@@ -1 +1 @@
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 * - 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 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 // 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 the env snippet into runtime files\n if (!isTurbopack) {\n (config.plugins as unknown[]).push(new DotenvxWebpackPlugin({ env }));\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":";;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,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,UA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rB,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"}
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.d.cts","names":[],"sources":["../src/plugin.ts"],"mappings":";;;UAuBiB,kBAAA;EA6Bf;;;;EAxBA,KAAA;EA0BgB;;;EArBhB,MAAA;AAAA;AAAA,KAkBG,YAAA,IACH,KAAA,UACA,QAAA;EAAY,aAAA,EAAe,UAAA;AAAA,MACxB,UAAA,GAAa,OAAA,CAAQ,UAAA;AAAA,iBAuFV,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"}
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.d.mts","names":[],"sources":["../src/plugin.ts"],"mappings":";;;UAuBiB,kBAAA;EA6Bf;;;;EAxBA,KAAA;EA0BgB;;;EArBhB,MAAA;AAAA;AAAA,KAkBG,YAAA,IACH,KAAA,UACA,QAAA;EAAY,aAAA,EAAe,UAAA;AAAA,MACxB,UAAA,GAAa,OAAA,CAAQ,UAAA;AAAA,iBAuFV,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
@@ -2,6 +2,7 @@ import { n as __require, t as DotenvxWebpackPlugin } from "./webpack-plugin-BmC1
2
2
  import { activateTurbopackInjection } from "./turbopack-inject.mjs";
3
3
  import fs from "node:fs";
4
4
  import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
5
6
  import dotenvx from "@dotenvx/dotenvx";
6
7
  //#region src/plugin.ts
7
8
  /**
@@ -16,8 +17,9 @@ import dotenvx from "@dotenvx/dotenvx";
16
17
  * via DotenvxWebpackPlugin (processAssets hook at PROCESS_ASSETS_STAGE_ADDITIONS).
17
18
  * - Turbopack builds: patch fs.writeFile to detect compilation completion and inject
18
19
  * the same snippet into [turbopack]_runtime.js files.
19
- * - Also aliases @next/env → @fantasticfour/dotenvx-next/next-env so dotenvx
20
- * secrets are available during Next.js config evaluation itself.
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.
21
23
  */
22
24
  const DEFAULT_ENV_FILES = [".env"];
23
25
  const PLUGIN_DEBUG = !!process.env.DEBUG_DOTENVX_NEXT;
@@ -45,15 +47,15 @@ async function dotenvxNextConfigFn(nextConfig, options, phase, defaults) {
45
47
  const prevWebpack = resolvedNextConfig.webpack;
46
48
  resolvedNextConfig.webpack = (webpackConfig, webpackOptions) => {
47
49
  const config = prevWebpack ? prevWebpack(webpackConfig, webpackOptions) : webpackConfig;
50
+ if (!isTurbopack) config.plugins.push(new DotenvxWebpackPlugin({ env }));
48
51
  config.resolve ??= {};
49
52
  config.resolve.alias ??= {};
50
53
  const alias = config.resolve.alias;
51
54
  try {
52
55
  alias["@next/env"] = __require.resolve("@fantasticfour/dotenvx-next/next-env");
53
56
  } catch {
54
- debugLog("Could not resolve @fantasticfour/dotenvx-next/next-env for alias — skipping");
57
+ alias["@next/env"] = fileURLToPath(new URL("./next-env-compat.js", import.meta.url));
55
58
  }
56
- if (!isTurbopack) config.plugins.push(new DotenvxWebpackPlugin({ env }));
57
59
  return config;
58
60
  };
59
61
  return resolvedNextConfig;
@@ -1 +1 @@
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 * - 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 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 // 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 the env snippet into runtime files\n if (!isTurbopack) {\n (config.plugins as unknown[]).push(new DotenvxWebpackPlugin({ env }));\n }\n\n return config;\n };\n\n return resolvedNextConfig;\n}\n\nexport function withDotenvx(\n nextConfig: NextConfig | NextConfigFn,\n options: DotenvxNextOptions = {}\n): NextConfigFn {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,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,YACF,QAAO,QAAsB,KAAK,IAAI,qBAAqB,EAAE,KAAK,CAAC,CAAC;AAGvE,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-BElH61NN.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,Q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AAC;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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fantasticfour/dotenvx-next",
3
- "version": "0.2.0",
3
+ "version": "0.2.3",
4
4
  "type": "module",
5
5
  "description": "Next.js plugin that loads dotenvx secrets early — before any user code evaluates — by injecting an init bundle into webpack/turbopack runtime files at build time.",
6
6
  "repository": {
@@ -16,6 +16,7 @@
16
16
  "require": "./dist/index.cjs"
17
17
  },
18
18
  "./next-env": {
19
+ "import": "./dist/next-env-compat.mjs",
19
20
  "require": "./dist/next-env-compat.cjs"
20
21
  }
21
22
  },
@@ -23,33 +24,31 @@
23
24
  "dist"
24
25
  ],
25
26
  "peerDependencies": {
26
- "next": ">=14"
27
- },
28
- "dependencies": {
27
+ "next": ">=14",
29
28
  "@dotenvx/dotenvx": "^1.0.0"
30
29
  },
30
+ "peerDependenciesMeta": {
31
+ "@dotenvx/dotenvx": {
32
+ "optional": false
33
+ }
34
+ },
31
35
  "devDependencies": {
32
36
  "@biomejs/biome": "^2.4.13",
33
37
  "@changesets/cli": "^2.31.0",
34
38
  "@types/node": "^25.6.0",
35
39
  "@typescript/native-preview": "7.0.0-dev.20260421.2",
36
- "husky": "^9.1.7",
37
- "lint-staged": "^16.4.0",
38
40
  "tsdown": "^0.21.10",
39
- "typescript": "^5.9.3",
41
+ "typescript": "^6.0.3",
40
42
  "vitest": "^4.1.5",
41
43
  "webpack": "^5.106.2"
42
44
  },
43
- "lint-staged": {
44
- "**/*": "biome format --write --no-errors-on-unmatched"
45
- },
46
45
  "engines": {
47
46
  "node": ">=18",
48
47
  "pnpm": ">=10.0.0"
49
48
  },
50
49
  "volta": {
51
50
  "node": "24.15.0",
52
- "pnpm": "10.13.1"
51
+ "pnpm": "10.33.2"
53
52
  },
54
53
  "license": "MIT",
55
54
  "scripts": {
@@ -1,137 +0,0 @@
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 env inline snippet 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 env inline snippet into turbopack runtime files.
46
- * Called after export-detail.json is written (turbopack compilation complete).
47
- */
48
- function injectDotenvxInitIntoTurbopackRuntime(nextDirPath, env) {
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 inlineSnippet = `(function(){if(typeof process!=='undefined'){Object.assign(process.env,${JSON.stringify(env)});}})();`;
63
- /**
64
- * Insert inlineSnippet into source respecting ESM constraints.
65
- * ESM files require all top-level `import` declarations to appear before any
66
- * other statements, so we must insert after the last import line rather than
67
- * prepending to the file.
68
- */
69
- const insertIntoSource = (origSource) => {
70
- const lines = origSource.split("\n");
71
- let lastImportIdx = -1;
72
- for (let i = 0; i < lines.length; i++) if (/^import\s/.test(lines[i])) lastImportIdx = i;
73
- if (lastImportIdx >= 0) {
74
- lines.splice(lastImportIdx + 1, 0, inlineSnippet);
75
- return lines.join("\n");
76
- }
77
- return [inlineSnippet, origSource].join("\n");
78
- };
79
- for (const runtimeFile of serverRuntimeFiles) {
80
- const origSource = node_fs.default.readFileSync(runtimeFile, "utf8");
81
- node_fs.default.writeFileSync(runtimeFile, insertIntoSource(origSource));
82
- debugLog(`injected env into turbopack server runtime: ${runtimeFile}`);
83
- }
84
- for (const wrapperFile of edgeWrapperFiles) {
85
- const origSource = node_fs.default.readFileSync(wrapperFile, "utf8");
86
- node_fs.default.writeFileSync(wrapperFile, insertIntoSource(origSource));
87
- debugLog(`injected env into turbopack edge wrapper: ${wrapperFile}`);
88
- }
89
- }
90
- /**
91
- * Patch global fs methods to detect when turbopack compilation completes,
92
- * then trigger runtime injection.
93
- */
94
- function activateTurbopackInjection(env) {
95
- debugLog("activating turbopack fs intercept");
96
- const origWriteFileFn = node_fs.default.promises.writeFile;
97
- node_fs.default.promises.writeFile = async function dotenvxPatchedWriteFile(...args) {
98
- const filePath = args[0].toString();
99
- debugLog("fs.promises.writeFile:", filePath);
100
- if (!injectedTurbopackRuntime && filePath.endsWith("/.next/export-detail.json")) injectDotenvxInitIntoTurbopackRuntime(filePath.substring(0, filePath.lastIndexOf("/")), env);
101
- return origWriteFileFn.apply(node_fs.default.promises, args);
102
- };
103
- const origWriteFileSyncFn = node_fs.default.writeFileSync;
104
- node_fs.default.writeFileSync = function dotenvxPatchedWriteFileSync(...args) {
105
- const filePath = args[0].toString();
106
- debugLog("fs.writeFileSync:", filePath);
107
- if (!injectedTurbopackRuntime && filePath.endsWith("/.next/export-detail.json")) injectDotenvxInitIntoTurbopackRuntime(filePath.substring(0, filePath.lastIndexOf("/")), env);
108
- origWriteFileSyncFn.apply(node_fs.default, args);
109
- };
110
- }
111
- //#endregion
112
- Object.defineProperty(exports, "__toESM", {
113
- enumerable: true,
114
- get: function() {
115
- return __toESM;
116
- }
117
- });
118
- Object.defineProperty(exports, "activateTurbopackInjection", {
119
- enumerable: true,
120
- get: function() {
121
- return activateTurbopackInjection;
122
- }
123
- });
124
- Object.defineProperty(exports, "injectDotenvxInitIntoTurbopackRuntime", {
125
- enumerable: true,
126
- get: function() {
127
- return injectDotenvxInitIntoTurbopackRuntime;
128
- }
129
- });
130
- Object.defineProperty(exports, "isInjectedTurbopackRuntime", {
131
- enumerable: true,
132
- get: function() {
133
- return isInjectedTurbopackRuntime;
134
- }
135
- });
136
-
137
- //# sourceMappingURL=turbopack-inject-BElH61NN.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"turbopack-inject-BElH61NN.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,M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