@varlock/nextjs-integration 0.0.6 → 0.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/next-env-compat.d.ts +2 -1
- package/dist/next-env-compat.js +3 -3
- package/dist/next-env-compat.js.map +1 -1
- package/dist/plugin.d.ts +1 -1
- package/dist/plugin.js +4 -4
- package/dist/plugin.js.map +1 -1
- package/package.json +5 -5
|
@@ -20,10 +20,11 @@ type Log = {
|
|
|
20
20
|
};
|
|
21
21
|
declare function processEnv(_loadedEnvFiles: LoadedEnvFiles, _dir?: string, _log?: Log, _forceReload?: boolean, _onReload?: (envFilePath: string) => void): NodeJS.ProcessEnv[];
|
|
22
22
|
declare function resetEnv(): void;
|
|
23
|
-
|
|
23
|
+
type LoadedEnvConfig = {
|
|
24
24
|
combinedEnv: Env;
|
|
25
25
|
parsedEnv: Env | undefined;
|
|
26
26
|
loadedEnvFiles: LoadedEnvFiles;
|
|
27
27
|
};
|
|
28
|
+
declare function loadEnvConfig(dir: string, dev?: boolean, _log?: Log, forceReload?: boolean, _onReload?: (envFilePath: string) => void): LoadedEnvConfig;
|
|
28
29
|
|
|
29
30
|
export { type Env, type LoadedEnvFiles, initialEnv, loadEnvConfig, processEnv, resetEnv, updateInitialEnv };
|
package/dist/next-env-compat.js
CHANGED
|
@@ -76,7 +76,7 @@ function enableExtraFileWatchers() {
|
|
|
76
76
|
destroyFile = true;
|
|
77
77
|
}
|
|
78
78
|
debug("set up extra file watchers", envFilePathToUpdate, destroyFile);
|
|
79
|
-
fs__namespace.watchFile(envSchemaPath, { interval: 500 }, (
|
|
79
|
+
fs__namespace.watchFile(envSchemaPath, { interval: 500 }, (_curr, _prev) => {
|
|
80
80
|
debug(".env.schema changed", envFilePathToUpdate, destroyFile);
|
|
81
81
|
if (destroyFile) {
|
|
82
82
|
fs__namespace.writeFileSync(envFilePathToUpdate, "# trigger reload", "utf-8");
|
|
@@ -152,7 +152,7 @@ function resetEnv() {
|
|
|
152
152
|
replaceProcessEnv(exports.initialEnv);
|
|
153
153
|
}
|
|
154
154
|
}
|
|
155
|
-
function loadEnvConfig(dir, dev,
|
|
155
|
+
function loadEnvConfig(dir, dev, _log = console, forceReload = false, _onReload) {
|
|
156
156
|
exports.initialEnv ||= { ...process.env };
|
|
157
157
|
debug("loadEnvConfig!", "forceReload = ", forceReload);
|
|
158
158
|
rootDir ||= dir;
|
|
@@ -193,7 +193,7 @@ function loadEnvConfig(dir, dev, log = console, forceReload = false, onReload) {
|
|
|
193
193
|
});
|
|
194
194
|
varlockLoadedEnv = JSON.parse(varlockLoadedEnvBuf.toString());
|
|
195
195
|
} catch (err) {
|
|
196
|
-
const {
|
|
196
|
+
const { stdout, stderr } = err;
|
|
197
197
|
const stdoutStr = stdout?.toString() || "";
|
|
198
198
|
const stderrStr = stderr?.toString() || "";
|
|
199
199
|
if (stderrStr.includes("command not found")) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/next-env-compat.ts"],"names":["initialEnv","path","fs","execSync","resetRedactionMap","patchGlobalConsole","initVarlockEnv"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBWA;AAEX,IAAI,YAAA;AAEJ,IAAI,gBAAA;AACJ,IAAI,WAAA;AACJ,IAAI,SAAA;AAEJ,IAAI,iBAAiC,EAAC;AACtC,IAAI,OAAA;AAIJ,SAAS,iCAAA,GAAoD;AAC3D,EAAA,MAAM,QAAA,GAAW,gBAAA,CAAiB,OAAA,CAC/B,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,OAAA,IAAW,CAAA,CAAE,KAAA,KAAU,aAAa,CAAA,CACpD,GAAA,CAAI,CAAC,CAAA,MAAO;AAAA,IACX,MAAM,CAAA,CAAE,KAAA;AAAA,IACR,QAAA,EAAU,EAAA;AAAA,IACV,KAAK;AAAC,GACR,CAAE,CAAA;AACJ,EAAA,IAAI,SAAS,MAAA,EAAQ;AAEnB,IAAA,QAA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C,CAAA;AAIxB,IAAA,OAAA,CAAQ,GAAA,CAAI,aAAA,GAAgB,IAAA,CAAK,SAAA,CAAU;AAAA,MACzC,SAAS,EAAC;AAAA,MACV,QAAQ,EAAC;AAAA,MACT,UAAU;AAAC,KACZ,CAAA;AAED,IAAA,OAAO,EAAE,aAAa,EAAC,EAAG,WAAW,EAAC,EAAG,cAAA,EAAgB,EAAC,EAAE;AAAA,EAC9D;AAEA,EAAA,SAAA,GAAY,EAAC;AACb,EAAA,KAAA,MAAW,CAAC,SAAS,QAAQ,CAAA,IAAK,OAAO,OAAA,CAAQ,gBAAA,CAAiB,MAAM,CAAA,EAAG;AACzE,IAAA,SAAA,CAAU,OAAO,IAAI,QAAA,CAAS,KAAA;AAAA,EAChC;AACA,EAAA,KAAA,CAAM,eAAe,SAAS,CAAA;AAC9B,EAAA,OAAA,CAAQ,GAAA,CAAI,aAAA,GAAgB,IAAA,CAAK,SAAA,CAAU,gBAAgB,CAAA;AAC3D,EAAAM,kBAAA,EAAe;AAEf,EAAAF,qBAAA,CAAkB,gBAAgB,CAAA;AAClC,EAAA,KAAA,CAAM,wCAAwC,CAAA;AAC9C,EAAAC,+BAAA,EAAmB;AAEnB,EAAA,WAAA,GAAc,EAAE,GAAGL,kBAAA,EAAY,GAAG,SAAA,EAAU;AAC5C,EAAA,cAAA,GAAiB,iCAAA,EAAkC;AAGnD,EAAA,IAAI,CAAC,KAAK,oBAAA,EAAqB;AAE/B,EAAA,OAAO,EAAE,WAAA,EAAa,SAAA,EAAW,cAAA,EAAe;AAClD","file":"next-env-compat.js","sourcesContent":["/**\n * Drop-in replacement for @next/env that uses varlock instead of dotenv\n *\n * This must be the default export of the module, and it must stay compatible with @next/env\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { execSync, type spawnSync } from 'child_process';\nimport { type SerializedEnvGraph } from 'varlock';\nimport { initVarlockEnv, resetRedactionMap } from 'varlock/env';\nimport { patchGlobalConsole } from 'varlock/patch-console';\n\nexport type Env = { [key: string]: string | undefined };\nexport type LoadedEnvFiles = Array<{\n path: string\n contents: string\n env: Env\n}>;\n\n/** will store the original values of process.env */\nexport let initialEnv: Env | undefined;\n\nlet lastReloadAt: Date | undefined;\n\nlet varlockLoadedEnv: SerializedEnvGraph;\nlet combinedEnv: Env | undefined;\nlet parsedEnv: Env | undefined;\n// this is used by next just to display the list of .env files in a startup log\nlet loadedEnvFiles: LoadedEnvFiles = [];\nlet rootDir: string | undefined;\n\n// @next/env exports this info and currently it is only used to display\n// a list of filenames loaded, for example: `Environments: .env, .env.development`\nfunction getVarlockSourcesAsLoadedEnvFiles(): LoadedEnvFiles {\n const envFiles = varlockLoadedEnv.sources\n .filter((s) => s.enabled && s.label !== 'process.env')\n .map((s) => ({\n path: s.label,\n contents: '',\n env: {},\n }));\n if (envFiles.length) {\n // this adds an additional line, below the list of files\n envFiles.push({ path: '\\n ✨ loaded by varlock ✨', contents: '', env: {} });\n }\n return envFiles;\n}\n\nconst IS_WORKER = !!process.env.NEXT_PRIVATE_WORKER;\nfunction debug(...args: Array<any>) {\n if (!process.env.DEBUG_VARLOCK_NEXT_INTEGRATION) return;\n console.log(\n IS_WORKER ? 'worker -- ' : 'server -- ',\n ...args,\n );\n}\ndebug('✨ LOADED @next/env module!');\n\n\n// Next.js only watches .env, .env.local, .env.development, .env.development.local\n// but we want to trigger reloads when .env.schema changes\n// so we set up an extra watcher, and trigger no-op changes to one of those files\nlet extraWatcherEnabled = false;\nconst NEXT_WATCHED_ENV_FILES = ['.env', '.env.local', '.env.development', '.env.development.local'];\nfunction enableExtraFileWatchers() {\n if (extraWatcherEnabled || IS_WORKER) return;\n extraWatcherEnabled = true;\n\n if (!rootDir) throw new Error('expected rootDir to be set');\n const envSchemaPath = path.join(rootDir, '.env.schema');\n // its faster to update an existing file, so we check if the user has any\n // otherwise we can create and destroy\n let envFilePathToUpdate: string | null = null;\n for (const envFileName of NEXT_WATCHED_ENV_FILES) {\n const filePath = path.join(rootDir, envFileName);\n if (fs.existsSync(filePath)) {\n envFilePathToUpdate = filePath;\n break;\n }\n }\n let destroyFile = false;\n if (!envFilePathToUpdate) {\n envFilePathToUpdate ||= path.join(rootDir, '.env');\n destroyFile = true;\n }\n\n debug('set up extra file watchers', envFilePathToUpdate, destroyFile);\n\n fs.watchFile(envSchemaPath, { interval: 500 }, (curr, prev) => {\n debug('.env.schema changed', envFilePathToUpdate, destroyFile);\n if (destroyFile) {\n fs.writeFileSync(envFilePathToUpdate, '# trigger reload', 'utf-8');\n setTimeout(() => {\n fs.unlinkSync(envFilePathToUpdate);\n }, 500);\n } else {\n const currentContents = fs.readFileSync(envFilePathToUpdate, 'utf-8');\n fs.writeFileSync(envFilePathToUpdate, currentContents, 'utf-8');\n }\n });\n}\n\nfunction detectOpenNextCloudflareBuild() {\n try {\n // the above works if the build is happening within CI, but we may need to do this for local builds or other CI platforms\n // so we can try to detect if we are within an open-next build by looking at the process info\n\n // we will look at the process tree to try to determine if we are in a opennext build\n // process tree looks like:\n // - opennext-cloudflare build > npm run build > next build\n\n // get grandparent process id\n const pppid = parseInt(execSync(`ps -o ppid= -p ${process.ppid}`).toString().trim());\n // const processInfo = execSync('ps -p '+grandparentPid+' -o command');\n // output looks like\n // ---\n // COMMAND\n // node /.../node_modules/.bin/opennextjs-cloudflare build\n //\n // ---\n const commandName = execSync(`ps -p ${pppid} -o command`).toString().split('\\n')[1];\n if (commandName.endsWith('.bin/opennextjs-cloudflare build')) {\n return true;\n }\n } catch (err) {\n // do nothing\n }\n return false;\n}\n\nfunction writeResolvedEnvFile() {\n // things get complicated on platforms like vercel/cloudflare, they do some of their own magic to load env vars\n // our loader (this file) will run during the _build_ process, but not when the platform is handling server rendered requests\n // also opennext is needed to run outside of vercel, so that adds other changes\n // so we export an additional .env file which the platform itself will automatically load\n\n const dotEnvStrLines = [];\n for (const [itemKey, itemInfo] of Object.entries(varlockLoadedEnv.config)) {\n if (itemInfo.value !== undefined) dotEnvStrLines.push(`${itemKey}=${JSON.stringify(itemInfo.value)}`);\n }\n\n if (\n detectOpenNextCloudflareBuild()\n || process.env.VERCEL || process.env.WORKERS_CI || process.env._VARLOCK_EXPORT_RESOLVED_ENV_FILE\n ) {\n dotEnvStrLines.unshift(`\n# 🛑 DO NOT CHECK THIS FILE INTO VERSION CONTROL 🛑\n# This file was automatically generated by @varlock/nextjs-integration\n# It contains a _fully resolved env_ to pass to platforms (ex: vercel, cloudflare, etc)\n# that are doing their own magic when booting up nextjs in certain scenarios\n#\n# It likely contains sensitive config data and should be deleted after use\n#\n# @disable # tells varlock to ignore this file\n# ---\n `);\n // this is the fully resolved env, which includes additional metadata about each item\n // our runtime code uses this to provide coerced values, redact sensitive values, etc\n dotEnvStrLines.push(`__VARLOCK_ENV=${JSON.stringify(varlockLoadedEnv)}`);\n\n let resolvedEnvFileName = '.env.production.local';\n if (process.env._VARLOCK_EXPORT_RESOLVED_ENV_FILE && !(['true', '1'].includes(process.env._VARLOCK_EXPORT_RESOLVED_ENV_FILE))) {\n resolvedEnvFileName = process.env._VARLOCK_EXPORT_RESOLVED_ENV_FILE;\n }\n if (!rootDir) throw new Error('expected rootDir to be set');\n fs.writeFileSync(path.resolve(rootDir, resolvedEnvFileName), dotEnvStrLines.join('\\n'), 'utf-8');\n }\n}\n\n// - these methods are the same as the original module -----------------\n\nexport function updateInitialEnv(newEnv: Env) {\n if (Object.keys(newEnv).length) {\n debug('updateInitialEnv', newEnv);\n Object.assign(initialEnv || {}, newEnv);\n }\n}\n\ntype Log = {\n info: (...args: Array<any>) => void\n error: (...args: Array<any>) => void\n};\n\nfunction replaceProcessEnv(sourceEnv: Env) {\n Object.keys(process.env).forEach((key) => {\n // Allow mutating internal Next.js env variables after the server has initiated.\n // This is necessary for dynamic things like the IPC server port.\n if (!key.startsWith('__NEXT_PRIVATE')) {\n if (sourceEnv[key] === undefined || sourceEnv[key] === '') {\n delete process.env[key];\n }\n }\n });\n\n Object.entries(sourceEnv).forEach(([key, value]) => {\n process.env[key] = value;\n });\n}\n\n// in original module, but does not appear to be used\nexport function processEnv(\n _loadedEnvFiles: LoadedEnvFiles,\n _dir?: string,\n _log: Log = console,\n _forceReload = false,\n _onReload?: (envFilePath: string) => void,\n) {\n return [process.env];\n}\n\nexport function resetEnv() {\n if (initialEnv) {\n replaceProcessEnv(initialEnv);\n }\n}\n\nexport function loadEnvConfig(\n dir: string,\n dev?: boolean,\n log: Log = console,\n forceReload = false,\n onReload?: (envFilePath: string) => void,\n): {\n combinedEnv: Env\n parsedEnv: Env | undefined\n loadedEnvFiles: LoadedEnvFiles\n} {\n // store actual process.env so we can restore it later\n initialEnv ||= { ...process.env };\n\n debug('loadEnvConfig!', 'forceReload = ', forceReload);\n\n // onReload is used to show a log of which .env file changed\n // TODO: add similar log to show which env file changed\n\n rootDir ||= dir;\n if (rootDir !== dir) throw new Error('root directory changed');\n\n if (dev) enableExtraFileWatchers();\n\n let useCachedEnv = !!process.env.__VARLOCK_ENV;\n if (forceReload) {\n if (!lastReloadAt) {\n lastReloadAt = new Date();\n } else if (lastReloadAt.getTime() < Date.now() - 1000) {\n lastReloadAt = new Date();\n useCachedEnv = false;\n }\n }\n\n if (useCachedEnv) {\n if (!varlockLoadedEnv) {\n varlockLoadedEnv = JSON.parse(process.env.__VARLOCK_ENV || '{}');\n parsedEnv = Object.fromEntries(\n Object.entries(varlockLoadedEnv.config).map(([key, value]) => [key, value.value]),\n );\n\n resetRedactionMap(varlockLoadedEnv);\n debug('patching console with varlock redactor');\n patchGlobalConsole();\n }\n\n combinedEnv = { ...initialEnv, ...parsedEnv };\n\n debug('>> USING CACHED ENV');\n\n return { combinedEnv, parsedEnv, loadedEnvFiles };\n }\n\n lastReloadAt = new Date();\n\n debug('>> RELOADING ENV');\n replaceProcessEnv(initialEnv);\n\n // we must match @next/env default behaviour for which .env.XXX files to load\n // which is based on the current command (`next dev` vs `next build`) and `NODE_ENV=test`\n // however we will pass it through and let the user ignore it by setting their own `@envFlag`\n let envFromNextCommand = dev ? 'development' : 'production';\n if (process.env.NODE_ENV === 'test') envFromNextCommand = 'test';\n debug('Inferred env mode (to match @next/env):', envFromNextCommand);\n\n try {\n const varlockLoadedEnvBuf = execSync(`varlock load --format json-full --env ${envFromNextCommand}`, {\n env: initialEnv as any,\n });\n varlockLoadedEnv = JSON.parse(varlockLoadedEnvBuf.toString());\n } catch (err) {\n const { status, stdout, stderr } = err as ReturnType<typeof spawnSync>;\n const stdoutStr = stdout?.toString() || '';\n const stderrStr = stderr?.toString() || '';\n if (stderrStr.includes('command not found')) {\n console.error([\n '',\n '❌ ERROR: varlock not found',\n 'varlock is a required peer dependency of @varlock/nextjs-integration',\n '',\n 'Please add varlock as a dependency to your project (e.g., `npm install varlock`)',\n ].join('\\n'));\n throw new Error('missing peer dependency - varlock');\n }\n if (stdoutStr) console.log(stdoutStr);\n if (stderrStr) console.error(stderrStr);\n\n // in a build, we want to fail and exit, while in dev we can keep retrying when changes are detected\n if (!dev) process.exit(1);\n\n // if we dont do this, we'll see an error that looks like `process.env.__VARLOCK_ENV is not set` which is misleading.\n // Ideally we would pass through an error of some kind and trigger the webpack runtime error popup\n process.env.__VARLOCK_ENV = JSON.stringify({\n sources: [],\n config: {},\n settings: {},\n });\n\n return { combinedEnv: {}, parsedEnv: {}, loadedEnvFiles: [] };\n }\n\n parsedEnv = {};\n for (const [itemKey, itemInfo] of Object.entries(varlockLoadedEnv.config)) {\n parsedEnv[itemKey] = itemInfo.value;\n }\n debug('LOADED ENV:', parsedEnv);\n process.env.__VARLOCK_ENV = JSON.stringify(varlockLoadedEnv);\n initVarlockEnv(); // calling this will set process.env vars\n\n resetRedactionMap(varlockLoadedEnv);\n debug('patching console with varlock redactor');\n patchGlobalConsole();\n\n combinedEnv = { ...initialEnv, ...parsedEnv };\n loadedEnvFiles = getVarlockSourcesAsLoadedEnvFiles();\n\n // if not a dev build, we may need to write a temp resolved .env file\n if (!dev) writeResolvedEnvFile();\n\n return { combinedEnv, parsedEnv, loadedEnvFiles };\n}\n"]}
|
|
1
|
+
{"version":3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AA,EAAe;AAEf,EAAAF,qBAAA,CAAkB,gBAAgB,CAAA;AAClC,EAAA,KAAA,CAAM,wCAAwC,CAAA;AAC9C,EAAAC,+BAAA,EAAmB;AAEnB,EAAA,WAAA,GAAc,EAAE,GAAGL,kBAAA,EAAY,GAAG,SAAA,EAAU;AAC5C,EAAA,cAAA,GAAiB,iCAAA,EAAkC;AAGnD,EAAA,IAAI,CAAC,KAAK,oBAAA,EAAqB;AAE/B,EAAA,OAAO,EAAE,WAAA,EAAa,SAAA,EAAW,cAAA,EAAe;AAClD","file":"next-env-compat.js","sourcesContent":["/**\n * Drop-in replacement for @next/env that uses varlock instead of dotenv\n *\n * This must be the default export of the module, and it must stay compatible with @next/env\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { execSync, type spawnSync } from 'child_process';\nimport { type SerializedEnvGraph } from 'varlock';\nimport { initVarlockEnv, resetRedactionMap } from 'varlock/env';\nimport { patchGlobalConsole } from 'varlock/patch-console';\n\nexport type Env = { [key: string]: string | undefined };\nexport type LoadedEnvFiles = Array<{\n path: string\n contents: string\n env: Env\n}>;\n\n/** will store the original values of process.env */\nexport let initialEnv: Env | undefined;\n\nlet lastReloadAt: Date | undefined;\n\nlet varlockLoadedEnv: SerializedEnvGraph;\nlet combinedEnv: Env | undefined;\nlet parsedEnv: Env | undefined;\n// this is used by next just to display the list of .env files in a startup log\nlet loadedEnvFiles: LoadedEnvFiles = [];\nlet rootDir: string | undefined;\n\n// @next/env exports this info and currently it is only used to display\n// a list of filenames loaded, for example: `Environments: .env, .env.development`\nfunction getVarlockSourcesAsLoadedEnvFiles(): LoadedEnvFiles {\n const envFiles = varlockLoadedEnv.sources\n .filter((s) => s.enabled && s.label !== 'process.env')\n .map((s) => ({\n path: s.label,\n contents: '',\n env: {},\n }));\n if (envFiles.length) {\n // this adds an additional line, below the list of files\n envFiles.push({ path: '\\n ✨ loaded by varlock ✨', contents: '', env: {} });\n }\n return envFiles;\n}\n\nconst IS_WORKER = !!process.env.NEXT_PRIVATE_WORKER;\nfunction debug(...args: Array<any>) {\n if (!process.env.DEBUG_VARLOCK_NEXT_INTEGRATION) return;\n // eslint-disable-next-line no-console\n console.log(\n IS_WORKER ? 'worker -- ' : 'server -- ',\n ...args,\n );\n}\ndebug('✨ LOADED @next/env module!');\n\n\n// Next.js only watches .env, .env.local, .env.development, .env.development.local\n// but we want to trigger reloads when .env.schema changes\n// so we set up an extra watcher, and trigger no-op changes to one of those files\nlet extraWatcherEnabled = false;\nconst NEXT_WATCHED_ENV_FILES = ['.env', '.env.local', '.env.development', '.env.development.local'];\nfunction enableExtraFileWatchers() {\n if (extraWatcherEnabled || IS_WORKER) return;\n extraWatcherEnabled = true;\n\n if (!rootDir) throw new Error('expected rootDir to be set');\n const envSchemaPath = path.join(rootDir, '.env.schema');\n // its faster to update an existing file, so we check if the user has any\n // otherwise we can create and destroy\n let envFilePathToUpdate: string | null = null;\n for (const envFileName of NEXT_WATCHED_ENV_FILES) {\n const filePath = path.join(rootDir, envFileName);\n if (fs.existsSync(filePath)) {\n envFilePathToUpdate = filePath;\n break;\n }\n }\n let destroyFile = false;\n if (!envFilePathToUpdate) {\n envFilePathToUpdate ||= path.join(rootDir, '.env');\n destroyFile = true;\n }\n\n debug('set up extra file watchers', envFilePathToUpdate, destroyFile);\n\n fs.watchFile(envSchemaPath, { interval: 500 }, (_curr, _prev) => {\n debug('.env.schema changed', envFilePathToUpdate, destroyFile);\n if (destroyFile) {\n fs.writeFileSync(envFilePathToUpdate, '# trigger reload', 'utf-8');\n setTimeout(() => {\n fs.unlinkSync(envFilePathToUpdate);\n }, 500);\n } else {\n const currentContents = fs.readFileSync(envFilePathToUpdate, 'utf-8');\n fs.writeFileSync(envFilePathToUpdate, currentContents, 'utf-8');\n }\n });\n}\n\nfunction detectOpenNextCloudflareBuild() {\n try {\n // the above works if the build is happening within CI, but we may need to do this for local builds or other CI platforms\n // so we can try to detect if we are within an open-next build by looking at the process info\n\n // we will look at the process tree to try to determine if we are in a opennext build\n // process tree looks like:\n // - opennext-cloudflare build > npm run build > next build\n\n // get grandparent process id\n const pppid = parseInt(execSync(`ps -o ppid= -p ${process.ppid}`).toString().trim());\n // const processInfo = execSync('ps -p '+grandparentPid+' -o command');\n // output looks like\n // ---\n // COMMAND\n // node /.../node_modules/.bin/opennextjs-cloudflare build\n //\n // ---\n const commandName = execSync(`ps -p ${pppid} -o command`).toString().split('\\n')[1];\n if (commandName.endsWith('.bin/opennextjs-cloudflare build')) {\n return true;\n }\n } catch (err) {\n // do nothing\n }\n return false;\n}\n\nfunction writeResolvedEnvFile() {\n // things get complicated on platforms like vercel/cloudflare, they do some of their own magic to load env vars\n // our loader (this file) will run during the _build_ process, but not when the platform is handling server rendered requests\n // also opennext is needed to run outside of vercel, so that adds other changes\n // so we export an additional .env file which the platform itself will automatically load\n\n const dotEnvStrLines = [];\n for (const [itemKey, itemInfo] of Object.entries(varlockLoadedEnv.config)) {\n if (itemInfo.value !== undefined) dotEnvStrLines.push(`${itemKey}=${JSON.stringify(itemInfo.value)}`);\n }\n\n if (\n detectOpenNextCloudflareBuild()\n || process.env.VERCEL || process.env.WORKERS_CI || process.env._VARLOCK_EXPORT_RESOLVED_ENV_FILE\n ) {\n dotEnvStrLines.unshift(`\n# 🛑 DO NOT CHECK THIS FILE INTO VERSION CONTROL 🛑\n# This file was automatically generated by @varlock/nextjs-integration\n# It contains a _fully resolved env_ to pass to platforms (ex: vercel, cloudflare, etc)\n# that are doing their own magic when booting up nextjs in certain scenarios\n#\n# It likely contains sensitive config data and should be deleted after use\n#\n# @disable # tells varlock to ignore this file\n# ---\n `);\n // this is the fully resolved env, which includes additional metadata about each item\n // our runtime code uses this to provide coerced values, redact sensitive values, etc\n dotEnvStrLines.push(`__VARLOCK_ENV=${JSON.stringify(varlockLoadedEnv)}`);\n\n let resolvedEnvFileName = '.env.production.local';\n if (process.env._VARLOCK_EXPORT_RESOLVED_ENV_FILE && !(['true', '1'].includes(process.env._VARLOCK_EXPORT_RESOLVED_ENV_FILE))) {\n resolvedEnvFileName = process.env._VARLOCK_EXPORT_RESOLVED_ENV_FILE;\n }\n if (!rootDir) throw new Error('expected rootDir to be set');\n fs.writeFileSync(path.resolve(rootDir, resolvedEnvFileName), dotEnvStrLines.join('\\n'), 'utf-8');\n }\n}\n\n// - these methods are the same as the original module -----------------\n\nexport function updateInitialEnv(newEnv: Env) {\n if (Object.keys(newEnv).length) {\n debug('updateInitialEnv', newEnv);\n Object.assign(initialEnv || {}, newEnv);\n }\n}\n\ntype Log = {\n info: (...args: Array<any>) => void\n error: (...args: Array<any>) => void\n};\n\nfunction replaceProcessEnv(sourceEnv: Env) {\n Object.keys(process.env).forEach((key) => {\n // Allow mutating internal Next.js env variables after the server has initiated.\n // This is necessary for dynamic things like the IPC server port.\n if (!key.startsWith('__NEXT_PRIVATE')) {\n if (sourceEnv[key] === undefined || sourceEnv[key] === '') {\n delete process.env[key];\n }\n }\n });\n\n Object.entries(sourceEnv).forEach(([key, value]) => {\n process.env[key] = value;\n });\n}\n\n// in original module, but does not appear to be used\nexport function processEnv(\n _loadedEnvFiles: LoadedEnvFiles,\n _dir?: string,\n _log: Log = console,\n _forceReload = false,\n _onReload?: (envFilePath: string) => void,\n) {\n return [process.env];\n}\n\nexport function resetEnv() {\n if (initialEnv) {\n replaceProcessEnv(initialEnv);\n }\n}\n\ntype LoadedEnvConfig = {\n combinedEnv: Env\n parsedEnv: Env | undefined\n loadedEnvFiles: LoadedEnvFiles\n};\n\nexport function loadEnvConfig(\n dir: string,\n dev?: boolean,\n _log: Log = console,\n forceReload = false,\n _onReload?: (envFilePath: string) => void,\n): LoadedEnvConfig {\n // store actual process.env so we can restore it later\n initialEnv ||= { ...process.env };\n\n debug('loadEnvConfig!', 'forceReload = ', forceReload);\n\n // onReload is used to show a log of which .env file changed\n // TODO: add similar log to show which env file changed\n\n rootDir ||= dir;\n if (rootDir !== dir) throw new Error('root directory changed');\n\n if (dev) enableExtraFileWatchers();\n\n let useCachedEnv = !!process.env.__VARLOCK_ENV;\n if (forceReload) {\n if (!lastReloadAt) {\n lastReloadAt = new Date();\n } else if (lastReloadAt.getTime() < Date.now() - 1000) {\n lastReloadAt = new Date();\n useCachedEnv = false;\n }\n }\n\n if (useCachedEnv) {\n if (!varlockLoadedEnv) {\n varlockLoadedEnv = JSON.parse(process.env.__VARLOCK_ENV || '{}');\n parsedEnv = Object.fromEntries(\n Object.entries(varlockLoadedEnv.config).map(([key, value]) => [key, value.value]),\n );\n\n resetRedactionMap(varlockLoadedEnv);\n debug('patching console with varlock redactor');\n patchGlobalConsole();\n }\n\n combinedEnv = { ...initialEnv, ...parsedEnv };\n\n debug('>> USING CACHED ENV');\n\n return { combinedEnv, parsedEnv, loadedEnvFiles };\n }\n\n lastReloadAt = new Date();\n\n debug('>> RELOADING ENV');\n replaceProcessEnv(initialEnv);\n\n // we must match @next/env default behaviour for which .env.XXX files to load\n // which is based on the current command (`next dev` vs `next build`) and `NODE_ENV=test`\n // however we will pass it through and let the user ignore it by setting their own `@envFlag`\n let envFromNextCommand = dev ? 'development' : 'production';\n if (process.env.NODE_ENV === 'test') envFromNextCommand = 'test';\n debug('Inferred env mode (to match @next/env):', envFromNextCommand);\n\n try {\n const varlockLoadedEnvBuf = execSync(`varlock load --format json-full --env ${envFromNextCommand}`, {\n env: initialEnv as any,\n });\n varlockLoadedEnv = JSON.parse(varlockLoadedEnvBuf.toString());\n } catch (err) {\n const { stdout, stderr } = err as ReturnType<typeof spawnSync>;\n const stdoutStr = stdout?.toString() || '';\n const stderrStr = stderr?.toString() || '';\n if (stderrStr.includes('command not found')) {\n // eslint-disable-next-line no-console\n console.error([\n '',\n '❌ ERROR: varlock not found',\n 'varlock is a required peer dependency of @varlock/nextjs-integration',\n '',\n 'Please add varlock as a dependency to your project (e.g., `npm install varlock`)',\n ].join('\\n'));\n throw new Error('missing peer dependency - varlock');\n }\n\n if (stdoutStr) console.log(stdoutStr); // eslint-disable-line no-console\n if (stderrStr) console.error(stderrStr); // eslint-disable-line no-console\n\n // in a build, we want to fail and exit, while in dev we can keep retrying when changes are detected\n if (!dev) process.exit(1);\n\n // if we dont do this, we'll see an error that looks like `process.env.__VARLOCK_ENV is not set` which is misleading.\n // Ideally we would pass through an error of some kind and trigger the webpack runtime error popup\n process.env.__VARLOCK_ENV = JSON.stringify({\n sources: [],\n config: {},\n settings: {},\n });\n\n return { combinedEnv: {}, parsedEnv: {}, loadedEnvFiles: [] };\n }\n\n parsedEnv = {};\n for (const [itemKey, itemInfo] of Object.entries(varlockLoadedEnv.config)) {\n parsedEnv[itemKey] = itemInfo.value;\n }\n debug('LOADED ENV:', parsedEnv);\n process.env.__VARLOCK_ENV = JSON.stringify(varlockLoadedEnv);\n initVarlockEnv(); // calling this will set process.env vars\n\n resetRedactionMap(varlockLoadedEnv);\n debug('patching console with varlock redactor');\n patchGlobalConsole();\n\n combinedEnv = { ...initialEnv, ...parsedEnv };\n loadedEnvFiles = getVarlockSourcesAsLoadedEnvFiles();\n\n // if not a dev build, we may need to write a temp resolved .env file\n if (!dev) writeResolvedEnvFile();\n\n return { combinedEnv, parsedEnv, loadedEnvFiles };\n}\n"]}
|
package/dist/plugin.d.ts
CHANGED
|
@@ -4,6 +4,6 @@ type VarlockPluginOptions = {};
|
|
|
4
4
|
type NextConfigFunction = (phase: string, defaults: {
|
|
5
5
|
defaultConfig: NextConfig;
|
|
6
6
|
}) => NextConfig | PromiseLike<NextConfig>;
|
|
7
|
-
declare function varlockNextConfigPlugin(
|
|
7
|
+
declare function varlockNextConfigPlugin(_pluginOptions?: VarlockPluginOptions): (nextConfig: any | NextConfig | NextConfigFunction) => NextConfigFunction;
|
|
8
8
|
|
|
9
9
|
export { type NextConfigFunction, varlockNextConfigPlugin };
|
package/dist/plugin.js
CHANGED
|
@@ -84,7 +84,7 @@ var StaticReplacementsProxy = new Proxy({}, {
|
|
|
84
84
|
if (item && !item.isSensitive) return JSON.stringify(item.value);
|
|
85
85
|
}
|
|
86
86
|
});
|
|
87
|
-
function varlockNextConfigPlugin(
|
|
87
|
+
function varlockNextConfigPlugin(_pluginOptions) {
|
|
88
88
|
return (nextConfig) => {
|
|
89
89
|
debug("varlockNextConfigPlugin init fn");
|
|
90
90
|
return async (phase, defaults) => {
|
|
@@ -110,7 +110,7 @@ function varlockNextConfigPlugin(pluginOptions) {
|
|
|
110
110
|
...resolvedNextConfig,
|
|
111
111
|
webpack(webpackConfig, options) {
|
|
112
112
|
debug("varlockNextConfigPlugin webpack config patching");
|
|
113
|
-
const {
|
|
113
|
+
const { dev } = options;
|
|
114
114
|
if (env.varlockSettings.preventLeaks) {
|
|
115
115
|
patchGlobalFsMethods();
|
|
116
116
|
patchServerResponse.patchGlobalServerResponse({
|
|
@@ -150,8 +150,8 @@ function varlockNextConfigPlugin(pluginOptions) {
|
|
|
150
150
|
}
|
|
151
151
|
});
|
|
152
152
|
}
|
|
153
|
-
function injectVarlockInitIntoWebpackRuntime(
|
|
154
|
-
return function(origSource) {
|
|
153
|
+
function injectVarlockInitIntoWebpackRuntime(_edgeRuntime = false) {
|
|
154
|
+
return function assetUpdateFn(origSource) {
|
|
155
155
|
const origSourceStr = origSource.source();
|
|
156
156
|
const injectorPath = path__default.default.resolve(__dirname, "./patch-next-runtime.js");
|
|
157
157
|
const injectorSrc = fs__default.default.readFileSync(injectorPath, "utf8");
|
package/dist/plugin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/plugin.ts"],"names":["patchGlobalConsole","fs","scanForLeaks","varlockSettings","patchGlobalServerResponse","redactSensitiveConfig","path"],"mappings":";;;;;;;;;;;;;;AAgBA,IAAI,CAAC,OAAA,CAAQ,GAAA,CAAI,aAAA,EAAe;AAC9B,EAAA,OAAA,CAAQ,KAAA,CAAM;AAAA,IACZ,0DAAA;AAAA,IACA,EAAA;AAAA,IACA,gFAAA;AAAA,IACA,kEAAA;AAAA,IACA;AAAA,GACF,CAAE,IAAA,CAAK,IAAI,CAAC,CAAA;AACZ,EAAA,MAAM,I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,oBAAA,IAAI,WAAA,CAAY,QAAA,CAAS,uBAAuB,CAAA,EAAG;AACjD,sBAAA,WAAA,CAAY,WAAA,CAAY,uBAAA,EAAyB,mCAAA,EAAqC,CAAA;AAAA,oBACxF;AACA,oBAAA,IAAI,WAAA,CAAY,QAAA,CAAS,wBAAwB,CAAA,EAAG;AAClD,sBAAA,WAAA,CAAY,WAAA,CAAY,wBAAA,EAA0B,mCAAA,EAAqC,CAAA;AAAA,oBACzF;AACA,oBAAA,IAAI,WAAA,CAAY,QAAA,CAAS,2BAA2B,CAAA,EAAG;AACrD,sBAAA,WAAA,CAAY,WAAA,CAAY,2BAAA,EAA6B,mCAAA,EAAqC,CAAA;AAAA,oBAC5F;AAEA,oBAAA,IAAI,WAAA,CAAY,QAAA,CAAS,yBAAyB,CAAA,EAAG;AACnD,sBAAA,WAAA,CAAY,WAAA,CAAY,yBAAA,EAA2B,mCAAA,CAAoC,IAAI,CAAC,CAAA;AAAA,oBAC9F;AAAA,kBACF;AAAA,iBACF;AAAA,cACF,CAAC,CAAA;AAAA,YACH;AAAA,WAED,CAAA;AAED,UAAA,OAAO,aAAA;AAAA,QACT;AAAA,OACF;AAAA,IACF,CAAA;AAAA,EACF,CAAA;AACF","file":"plugin.js","sourcesContent":["/* eslint-disable no-console */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { NextConfig } from 'next';\n\nimport {\n redactSensitiveConfig, scanForLeaks, varlockSettings,\n} from 'varlock/env';\nimport { patchGlobalServerResponse } from 'varlock/patch-server-response';\nimport { patchGlobalConsole } from 'varlock/patch-console';\n\nimport { type SerializedEnvGraph } from 'varlock';\n\n// make sure varlock has acutally loaded the env files\n// NOTE - we dont need to call `initVarlockEnv` becuase the next-env-compat has already been loaded and called it\nif (!process.env.__VARLOCK_ENV) {\n console.error([\n '🚨 process.env.__VARLOCK_ENV is not set 🚨',\n '',\n 'To use this plugin, you must override @next/env with @varlock/next-integration',\n 'See https://varlock.dev/integrations/nextjs for more information',\n '',\n ].join('\\n'));\n throw new Error('VarlockNextWebpackPlugin: __VARLOCK_ENV is not set');\n}\n\npatchGlobalConsole();\n\nconst IS_WORKER = !!process.env.NEXT_PRIVATE_WORKER;\nfunction debug(...args: Array<any>) {\n if (!process.env.DEBUG_VARLOCK_NEXT_INTEGRATION) return;\n console.log(\n 'plugin',\n IS_WORKER ? '[worker] ' : '[server]',\n '--',\n ...args,\n );\n}\ndebug('✨ LOADED @varlock/next-integration/plugin module!');\n\nconst WEBPACK_PLUGIN_NAME = 'VarlockNextWebpackPlugin';\n\ntype VarlockPluginOptions = {\n // injectResolvedConfigAtBuildTime: boolean,\n};\n\nlet scannedStaticFiles = false;\nasync function scanStaticFiles(nextDirPath: string) {\n scannedStaticFiles = true;\n for await (const file of fs.promises.glob(`${nextDirPath}/**/*.html`)) {\n const fileContents = await fs.promises.readFile(file, 'utf8');\n scanForLeaks(fileContents, { method: 'nextjs scan static html files', file });\n }\n}\n\n// not all file writes go through this, at least in Next 15\n// (likely because webpack and prerendering are happening in workers)\n// but we can use this to monitor writing of certain files and give ourselves a \"hook\"\n// which we can then scan existing files\nfunction patchGlobalFsMethods() {\n // patch fs.promises.writeFile\n const origWriteFileFn = fs.promises.writeFile;\n fs.promises.writeFile = async function dmnoPatchedWriteFile(...args) {\n const filePath = args[0].toString();\n // const fileContents = args[1].toString();\n // console.log('⚡️ patched fs.promises.writeFile', filePath);\n\n if (filePath.endsWith('/.next/next-server.js.nft.json') && !scannedStaticFiles) {\n const nextDirPath = filePath.substring(0, filePath.lastIndexOf('/'));\n await scanStaticFiles(nextDirPath);\n }\n\n // // naively enable/disable detection based on file extension... probably not the best logic but it might be enough?\n // if (\n // filePath.endsWith('.html')\n // || filePath.endsWith('.rsc')\n // || filePath.endsWith('.body')\n // // we also need to scan .js files, but they are already built by webpack so we can't catch it here\n // ) {\n // // TODO: better error details to help user _find_ the problem\n // scanForLeaks(fileContents, { method: 'nextjs fs.writeFile', file: filePath });\n // }\n\n return origWriteFileFn.call(this, ...args);\n };\n}\n\n\n// We use a proxy object for the static replacements that we pass to webpack.DefinePlugin\n// because this plugin/webpack code is not invoked again when env files change\n// instead next is direcly messing with the existing plugins for their own changes\n// so instead we use a proxy object, and grab the values off of process.env.__VARLOCK_ENV\n// which will have been updated by our next-env-compat code\nlet latestLoadedVarlockEnv: SerializedEnvGraph | undefined;\nconst StaticReplacementsProxy = new Proxy({} as Record<string, string>, {\n ownKeys(_target) {\n latestLoadedVarlockEnv = JSON.parse(process.env.__VARLOCK_ENV || '{}') as SerializedEnvGraph;\n const replaceKeys = [] as Array<string>;\n for (const itemKey in latestLoadedVarlockEnv.config) {\n const item = latestLoadedVarlockEnv.config[itemKey];\n if (!item.isSensitive) replaceKeys.push(`ENV.${itemKey}`);\n }\n debug('reloaded static replacements keys', replaceKeys);\n return replaceKeys;\n },\n getOwnPropertyDescriptor(_target, prop) {\n const itemKey = prop.toString().split('.')[1];\n const item = latestLoadedVarlockEnv?.config[itemKey];\n if (!item || item.isSensitive) return;\n return {\n value: '', // this value is not used, the get handler will return the value\n writable: false,\n enumerable: true,\n configurable: true,\n };\n },\n get(_target, prop) {\n const itemKey = prop.toString().split('.')[1];\n const item = latestLoadedVarlockEnv?.config[itemKey];\n if (item && !item.isSensitive) return JSON.stringify(item.value);\n },\n});\n\n\n\n\nexport type NextConfigFunction = (\n phase: string,\n defaults: { defaultConfig: NextConfig },\n) => NextConfig | PromiseLike<NextConfig>;\n\n\n// we make this a plugin a function because we'll likely end up adding some options\nexport function varlockNextConfigPlugin(pluginOptions?: VarlockPluginOptions) {\n // nextjs doesnt have a proper plugin system :(\n // so we use a function which takes in a config object and returns an augmented one\n return (nextConfig: any | NextConfig | NextConfigFunction): NextConfigFunction => {\n debug('varlockNextConfigPlugin init fn');\n\n return async (phase: string, defaults: { defaultConfig: NextConfig }) => {\n let resolvedNextConfig: NextConfig;\n if (typeof nextConfig === 'function') {\n const nextConfigFnResult = nextConfig(phase, defaults);\n resolvedNextConfig = await nextConfigFnResult;\n } else {\n resolvedNextConfig = nextConfig;\n }\n\n if (process.env.TURBOPACK || process.env.npm_config_turbopack) {\n console.error([\n '🚨 @varlock/nextjs-integration: Turbopack is not yet supported for varlockNextConfigPlugin 🚨',\n '',\n 'You can either stop using the `--turbopack` flag',\n 'or remove this plugin from your config, and only use the @next/env override.',\n \"However if you don't use the plugin, you will not get all the benefits of this integration.\",\n '',\n ].join('\\n'));\n throw new Error('varlockNextConfigPlugin: Turbopack is not yet supported');\n }\n\n return {\n ...resolvedNextConfig,\n webpack(webpackConfig, options) {\n debug('varlockNextConfigPlugin webpack config patching');\n\n const { isServer, dev, nextRuntime } = options;\n\n if (varlockSettings.preventLeaks) {\n // we patch fs methods - ideally we would just path them to scan while files are written\n // but instead we use it to detect what phase the build is in, and then run our own scan on already built files\n patchGlobalFsMethods();\n\n // have to wait to run this until here when we know if this is dev mode or not\n patchGlobalServerResponse({\n // ignore sourcemaps - although we may in future want to scrub them?\n ignoreUrlPatterns: [/^\\/__nextjs_source-map\\?.*/],\n // in dev mode, we redact the secrets rather than throwing, because otherwise the dev server crashes\n redactInsteadOfThrow: dev,\n });\n }\n\n // webpack itself is passed in so we dont have to import it (or make it a dependency)\n const webpack = options.webpack;\n\n // apply existing user customizations if there are any\n if (resolvedNextConfig.webpack) {\n webpackConfig = resolvedNextConfig.webpack(webpackConfig, options);\n }\n\n if (!process.env.__VARLOCK_ENV) throw new Error('VarlockNextWebpackPlugin: __VARLOCK_ENV is not set');\n\n // Set up build-time replacements / rewrites - using webpack.DefinePlugin and a proxy\n // TODO: use shared helpers from core library?\n debug('adding ENV.xxx static replacements proxy object');\n webpackConfig.plugins.push(new webpack.DefinePlugin(StaticReplacementsProxy));\n\n if (varlockSettings.preventLeaks) {\n webpackConfig.plugins.push({\n apply(compiler: any) {\n compiler.hooks.assetEmitted.tap(WEBPACK_PLUGIN_NAME, (file: any, assetDetails: any) => {\n const { content, targetPath } = assetDetails;\n // debug('emit file: ', targetPath);\n\n if (\n targetPath.includes('/.next/static/chunks/')\n // Dont think these actually ever happen?\n || targetPath.endsWith('.html')\n || targetPath.endsWith('.body')\n || targetPath.endsWith('.rsc')\n ) {\n // NOTE - in dev mode the request hangs on the error, but the console error should help\n // and during a build, it will actually fail the build\n try {\n scanForLeaks(content, {\n method: '@varlock/nextjs-integration/plugin - assetEmitted hook',\n file: targetPath,\n });\n } catch (err) {\n if (dev) {\n // overwrite file with redacted version\n fs.writeFileSync(targetPath, redactSensitiveConfig(content.toString()));\n } else {\n throw err;\n }\n }\n }\n });\n },\n });\n }\n\n\n\n\n // we need to inject the dmno globals injector and call it\n // and in vercel/netlify etc where we can't run via `dmno run` we need to inject the resolved config into the build\n // not sure if this is the best way, but injecting into the `webpack-runtime.js` file seems to run everywhere\n\n // updates the webpack source to inject dmno global logic and call it\n // we run this on the runtimes for serverless and edge\n function injectVarlockInitIntoWebpackRuntime(edgeRuntime = false) {\n return function (origSource: any) {\n const origSourceStr = origSource.source();\n\n // we will inline the injector code, but need a different version if we are running in the edge runtime\n // const injectorSrc = getCjsModuleSource(`dmno/injector-standalone${edgeRuntime ? '/edge' : ''}`);\n const injectorPath = path.resolve(__dirname, './patch-next-runtime.js');\n const injectorSrc = fs.readFileSync(injectorPath, 'utf8');\n\n\n const updatedSourceStr = [\n // TODO: reimplement dynamic/static functionality, which triggers a call to next/headers (or similar)\n // when accessing a dynamic env item. This will force the page into dynamic rendering mode\n // see DMNO integration for more details\n\n // inline the dmno injector code\n injectorSrc,\n origSourceStr,\n ].join('\\n');\n\n return new webpack.sources.RawSource(updatedSourceStr);\n };\n }\n\n webpackConfig.plugins.push({\n apply(compiler: any) {\n compiler.hooks.thisCompilation.tap(WEBPACK_PLUGIN_NAME, (compilation: any) => {\n compilation.hooks.processAssets.tap(\n {\n name: WEBPACK_PLUGIN_NAME,\n stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,\n },\n () => {\n // not sure why, but these paths are different in build vs dev\n if (compilation.getAsset('webpack-runtime.js')) {\n compilation.updateAsset('webpack-runtime.js', injectVarlockInitIntoWebpackRuntime());\n }\n if (compilation.getAsset('../webpack-runtime.js')) {\n compilation.updateAsset('../webpack-runtime.js', injectVarlockInitIntoWebpackRuntime());\n }\n if (compilation.getAsset('webpack-api-runtime.js')) {\n compilation.updateAsset('webpack-api-runtime.js', injectVarlockInitIntoWebpackRuntime());\n }\n if (compilation.getAsset('../webpack-api-runtime.js')) {\n compilation.updateAsset('../webpack-api-runtime.js', injectVarlockInitIntoWebpackRuntime());\n }\n\n if (compilation.getAsset('edge-runtime-webpack.js')) {\n compilation.updateAsset('edge-runtime-webpack.js', injectVarlockInitIntoWebpackRuntime(true));\n }\n },\n );\n });\n },\n\n });\n\n return webpackConfig; // must return the modified config\n },\n };\n };\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/plugin.ts"],"names":["patchGlobalConsole","fs","scanForLeaks","varlockSettings","patchGlobalServerResponse","redactSensitiveConfig","path"],"mappings":";;;;;;;;;;;;;;AAgBA,IAAI,CAAC,OAAA,CAAQ,GAAA,CAAI,aAAA,EAAe;AAC9B,EAAA,OAAA,CAAQ,KAAA,CAAM;AAAA,IACZ,0DAAA;AAAA,IACA,EAAA;AAAA,IACA,gFAAA;AAAA,IACA,kEAAA;AAAA,IACA;AAAA,GACF,CAAE,IAAA,CAAK,IAAI,CAAC,CAAA;AACZ,EAAA,MAAM,IAAI,MAAM,oDAAoD,CAAA;AACtE;AAEAA,+BAAA,EAAmB;AAEnB,IAAM,SAAA,GAAY,CAAC,CAAC,OAAA,CAAQ,GAAA,CAAI,mBAAA;AAChC,SAAS,SAAS,IAAA,EAAkB;AAClC,EAAA,IAAI,CAAC,OAAA,CAAQ,GAAA,CAAI,8BAAA,EAAgC;AACjD,EAAA,OAAA,CAAQ,GAAA;AAAA,IACN,QAAA;AAAA,IACA,YAAY,WAAA,GAAc,UAAA;AAAA,IAC1B,IAAA;AAAA,IACA,GAAG;AAAA,GACL;AACF;AACA,KAAA,CAAM,wDAAm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,EAA6B,mCAAA,EAAqC,CAAA;AAAA,oBAC5F;AAEA,oBAAA,IAAI,WAAA,CAAY,QAAA,CAAS,yBAAyB,CAAA,EAAG;AACnD,sBAAA,WAAA,CAAY,WAAA,CAAY,yBAAA,EAA2B,mCAAA,CAAoC,IAAI,CAAC,CAAA;AAAA,oBAC9F;AAAA,kBACF;AAAA,iBACF;AAAA,cACF,CAAC,CAAA;AAAA,YACH;AAAA,WAED,CAAA;AAED,UAAA,OAAO,aAAA;AAAA,QACT;AAAA,OACF;AAAA,IACF,CAAA;AAAA,EACF,CAAA;AACF","file":"plugin.js","sourcesContent":["/* eslint-disable no-console */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { NextConfig } from 'next';\n\nimport {\n redactSensitiveConfig, scanForLeaks, varlockSettings,\n} from 'varlock/env';\nimport { patchGlobalServerResponse } from 'varlock/patch-server-response';\nimport { patchGlobalConsole } from 'varlock/patch-console';\n\nimport { type SerializedEnvGraph } from 'varlock';\n\n// make sure varlock has acutally loaded the env files\n// NOTE - we dont need to call `initVarlockEnv` becuase the next-env-compat has already been loaded and called it\nif (!process.env.__VARLOCK_ENV) {\n console.error([\n '🚨 process.env.__VARLOCK_ENV is not set 🚨',\n '',\n 'To use this plugin, you must override @next/env with @varlock/next-integration',\n 'See https://varlock.dev/integrations/nextjs for more information',\n '',\n ].join('\\n'));\n throw new Error('VarlockNextWebpackPlugin: __VARLOCK_ENV is not set');\n}\n\npatchGlobalConsole();\n\nconst IS_WORKER = !!process.env.NEXT_PRIVATE_WORKER;\nfunction debug(...args: Array<any>) {\n if (!process.env.DEBUG_VARLOCK_NEXT_INTEGRATION) return;\n console.log(\n 'plugin',\n IS_WORKER ? '[worker] ' : '[server]',\n '--',\n ...args,\n );\n}\ndebug('✨ LOADED @varlock/next-integration/plugin module!');\n\nconst WEBPACK_PLUGIN_NAME = 'VarlockNextWebpackPlugin';\n\ntype VarlockPluginOptions = {\n // injectResolvedConfigAtBuildTime: boolean,\n};\n\nlet scannedStaticFiles = false;\nasync function scanStaticFiles(nextDirPath: string) {\n scannedStaticFiles = true;\n for await (const file of fs.promises.glob(`${nextDirPath}/**/*.html`)) {\n const fileContents = await fs.promises.readFile(file, 'utf8');\n scanForLeaks(fileContents, { method: 'nextjs scan static html files', file });\n }\n}\n\n// not all file writes go through this, at least in Next 15\n// (likely because webpack and prerendering are happening in workers)\n// but we can use this to monitor writing of certain files and give ourselves a \"hook\"\n// which we can then scan existing files\nfunction patchGlobalFsMethods() {\n // patch fs.promises.writeFile\n const origWriteFileFn = fs.promises.writeFile;\n fs.promises.writeFile = async function dmnoPatchedWriteFile(...args) {\n const filePath = args[0].toString();\n // const fileContents = args[1].toString();\n // console.log('⚡️ patched fs.promises.writeFile', filePath);\n\n if (filePath.endsWith('/.next/next-server.js.nft.json') && !scannedStaticFiles) {\n const nextDirPath = filePath.substring(0, filePath.lastIndexOf('/'));\n await scanStaticFiles(nextDirPath);\n }\n\n // // naively enable/disable detection based on file extension... probably not the best logic but it might be enough?\n // if (\n // filePath.endsWith('.html')\n // || filePath.endsWith('.rsc')\n // || filePath.endsWith('.body')\n // // we also need to scan .js files, but they are already built by webpack so we can't catch it here\n // ) {\n // // TODO: better error details to help user _find_ the problem\n // scanForLeaks(fileContents, { method: 'nextjs fs.writeFile', file: filePath });\n // }\n\n return origWriteFileFn.call(this, ...args);\n };\n}\n\n\n// We use a proxy object for the static replacements that we pass to webpack.DefinePlugin\n// because this plugin/webpack code is not invoked again when env files change\n// instead next is direcly messing with the existing plugins for their own changes\n// so instead we use a proxy object, and grab the values off of process.env.__VARLOCK_ENV\n// which will have been updated by our next-env-compat code\nlet latestLoadedVarlockEnv: SerializedEnvGraph | undefined;\nconst StaticReplacementsProxy = new Proxy({} as Record<string, string>, {\n ownKeys(_target) {\n latestLoadedVarlockEnv = JSON.parse(process.env.__VARLOCK_ENV || '{}') as SerializedEnvGraph;\n const replaceKeys = [] as Array<string>;\n for (const itemKey in latestLoadedVarlockEnv.config) {\n const item = latestLoadedVarlockEnv.config[itemKey];\n if (!item.isSensitive) replaceKeys.push(`ENV.${itemKey}`);\n }\n debug('reloaded static replacements keys', replaceKeys);\n return replaceKeys;\n },\n getOwnPropertyDescriptor(_target, prop) {\n const itemKey = prop.toString().split('.')[1];\n const item = latestLoadedVarlockEnv?.config[itemKey];\n if (!item || item.isSensitive) return;\n return {\n value: '', // this value is not used, the get handler will return the value\n writable: false,\n enumerable: true,\n configurable: true,\n };\n },\n get(_target, prop) {\n const itemKey = prop.toString().split('.')[1];\n const item = latestLoadedVarlockEnv?.config[itemKey];\n if (item && !item.isSensitive) return JSON.stringify(item.value);\n },\n});\n\n\n\n\nexport type NextConfigFunction = (\n phase: string,\n defaults: { defaultConfig: NextConfig },\n) => NextConfig | PromiseLike<NextConfig>;\n\n\n// we make this a plugin a function because we'll likely end up adding some options\nexport function varlockNextConfigPlugin(_pluginOptions?: VarlockPluginOptions) {\n // nextjs doesnt have a proper plugin system :(\n // so we use a function which takes in a config object and returns an augmented one\n return (nextConfig: any | NextConfig | NextConfigFunction): NextConfigFunction => {\n debug('varlockNextConfigPlugin init fn');\n\n return async (phase: string, defaults: { defaultConfig: NextConfig }) => {\n let resolvedNextConfig: NextConfig;\n if (typeof nextConfig === 'function') {\n const nextConfigFnResult = nextConfig(phase, defaults);\n resolvedNextConfig = await nextConfigFnResult;\n } else {\n resolvedNextConfig = nextConfig;\n }\n\n if (process.env.TURBOPACK || process.env.npm_config_turbopack) {\n console.error([\n '🚨 @varlock/nextjs-integration: Turbopack is not yet supported for varlockNextConfigPlugin 🚨',\n '',\n 'You can either stop using the `--turbopack` flag',\n 'or remove this plugin from your config, and only use the @next/env override.',\n \"However if you don't use the plugin, you will not get all the benefits of this integration.\",\n '',\n ].join('\\n'));\n throw new Error('varlockNextConfigPlugin: Turbopack is not yet supported');\n }\n\n return {\n ...resolvedNextConfig,\n webpack(webpackConfig, options) {\n debug('varlockNextConfigPlugin webpack config patching');\n\n const { dev } = options; // also available - isServer, nextRuntime\n\n if (varlockSettings.preventLeaks) {\n // we patch fs methods - ideally we would just path them to scan while files are written\n // but instead we use it to detect what phase the build is in, and then run our own scan on already built files\n patchGlobalFsMethods();\n\n // have to wait to run this until here when we know if this is dev mode or not\n patchGlobalServerResponse({\n // ignore sourcemaps - although we may in future want to scrub them?\n ignoreUrlPatterns: [/^\\/__nextjs_source-map\\?.*/],\n // in dev mode, we redact the secrets rather than throwing, because otherwise the dev server crashes\n redactInsteadOfThrow: dev,\n });\n }\n\n // webpack itself is passed in so we dont have to import it (or make it a dependency)\n const webpack = options.webpack;\n\n // apply existing user customizations if there are any\n if (resolvedNextConfig.webpack) {\n webpackConfig = resolvedNextConfig.webpack(webpackConfig, options);\n }\n\n if (!process.env.__VARLOCK_ENV) throw new Error('VarlockNextWebpackPlugin: __VARLOCK_ENV is not set');\n\n // Set up build-time replacements / rewrites - using webpack.DefinePlugin and a proxy\n // TODO: use shared helpers from core library?\n debug('adding ENV.xxx static replacements proxy object');\n webpackConfig.plugins.push(new webpack.DefinePlugin(StaticReplacementsProxy));\n\n if (varlockSettings.preventLeaks) {\n webpackConfig.plugins.push({\n apply(compiler: any) {\n compiler.hooks.assetEmitted.tap(WEBPACK_PLUGIN_NAME, (file: any, assetDetails: any) => {\n const { content, targetPath } = assetDetails;\n // debug('emit file: ', targetPath);\n\n if (\n targetPath.includes('/.next/static/chunks/')\n // Dont think these actually ever happen?\n || targetPath.endsWith('.html')\n || targetPath.endsWith('.body')\n || targetPath.endsWith('.rsc')\n ) {\n // NOTE - in dev mode the request hangs on the error, but the console error should help\n // and during a build, it will actually fail the build\n try {\n scanForLeaks(content, {\n method: '@varlock/nextjs-integration/plugin - assetEmitted hook',\n file: targetPath,\n });\n } catch (err) {\n if (dev) {\n // overwrite file with redacted version\n fs.writeFileSync(targetPath, redactSensitiveConfig(content.toString()));\n } else {\n throw err;\n }\n }\n }\n });\n },\n });\n }\n\n\n\n\n // we need to inject the dmno globals injector and call it\n // and in vercel/netlify etc where we can't run via `dmno run` we need to inject the resolved config into the build\n // not sure if this is the best way, but injecting into the `webpack-runtime.js` file seems to run everywhere\n\n // updates the webpack source to inject dmno global logic and call it\n // we run this on the runtimes for serverless and edge\n function injectVarlockInitIntoWebpackRuntime(_edgeRuntime = false) {\n return function assetUpdateFn(origSource: any) {\n const origSourceStr = origSource.source();\n\n // we will inline the injector code, but need a different version if we are running in the edge runtime\n // const injectorSrc = getCjsModuleSource(`dmno/injector-standalone${edgeRuntime ? '/edge' : ''}`);\n const injectorPath = path.resolve(__dirname, './patch-next-runtime.js');\n const injectorSrc = fs.readFileSync(injectorPath, 'utf8');\n\n\n const updatedSourceStr = [\n // TODO: reimplement dynamic/static functionality, which triggers a call to next/headers (or similar)\n // when accessing a dynamic env item. This will force the page into dynamic rendering mode\n // see DMNO integration for more details\n\n // inline the dmno injector code\n injectorSrc,\n origSourceStr,\n ].join('\\n');\n\n return new webpack.sources.RawSource(updatedSourceStr);\n };\n }\n\n webpackConfig.plugins.push({\n apply(compiler: any) {\n compiler.hooks.thisCompilation.tap(WEBPACK_PLUGIN_NAME, (compilation: any) => {\n compilation.hooks.processAssets.tap(\n {\n name: WEBPACK_PLUGIN_NAME,\n stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,\n },\n () => {\n // not sure why, but these paths are different in build vs dev\n if (compilation.getAsset('webpack-runtime.js')) {\n compilation.updateAsset('webpack-runtime.js', injectVarlockInitIntoWebpackRuntime());\n }\n if (compilation.getAsset('../webpack-runtime.js')) {\n compilation.updateAsset('../webpack-runtime.js', injectVarlockInitIntoWebpackRuntime());\n }\n if (compilation.getAsset('webpack-api-runtime.js')) {\n compilation.updateAsset('webpack-api-runtime.js', injectVarlockInitIntoWebpackRuntime());\n }\n if (compilation.getAsset('../webpack-api-runtime.js')) {\n compilation.updateAsset('../webpack-api-runtime.js', injectVarlockInitIntoWebpackRuntime());\n }\n\n if (compilation.getAsset('edge-runtime-webpack.js')) {\n compilation.updateAsset('edge-runtime-webpack.js', injectVarlockInitIntoWebpackRuntime(true));\n }\n },\n );\n });\n },\n\n });\n\n return webpackConfig; // must return the modified config\n },\n };\n };\n };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@varlock/nextjs-integration",
|
|
3
3
|
"description": "drop-in replacement for @next/env that uses varlock to load .env files with validation and extra security features",
|
|
4
|
-
"version": "0.0.
|
|
4
|
+
"version": "0.0.8",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
7
7
|
"url": "https://github.com/dmno-dev/varlock.git",
|
|
@@ -37,13 +37,13 @@
|
|
|
37
37
|
},
|
|
38
38
|
"peerDependencies": {
|
|
39
39
|
"next": ">=14",
|
|
40
|
-
"varlock": "^0.0.
|
|
40
|
+
"varlock": "^0.0.9"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
|
-
"@types/node": "^
|
|
44
|
-
"tsup": "^8.
|
|
43
|
+
"@types/node": "^24.2.0",
|
|
44
|
+
"tsup": "^8.5.0",
|
|
45
45
|
"vitest": "^3.2.4",
|
|
46
|
-
"varlock": "^0.0.
|
|
46
|
+
"varlock": "^0.0.9"
|
|
47
47
|
},
|
|
48
48
|
"scripts": {
|
|
49
49
|
"dev": "tsup --watch",
|