sailfork / t3code-github / .repos/ alchemy-effect/ packages/ cloudflare-runtime/ src/ rolldown/ plugins/ nodejs-compat.ts

import assert from "node:assert";
import { createRequire } from "node:module";
import path from "node:path";
import { getCloudflarePreset, nonPrefixedNodeModules } from "@cloudflare/unenv-preset";
import { defineEnv } from "unenv";
import { createPlugin } from "../factory.ts";
import { isSkippedEnvironment } from "../options.ts";
import type { BasePluginOptions } from "../options.ts";
import { hasNodejsAls, hasNodejsCompat, toPosixPath } from "../utils.ts";

const ASYNC_HOOKS_REGEXP = /^(node:)?async_hooks$/;
const NODE_BUILTIN_MODULES_REGEXP = new RegExp(`^(${nonPrefixedNodeModules.join("|")}|node:.+)

	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	.repos/alchemy-effect/packages/cloudflare-runtime/src/rolldown/plugins/nodejs-compat.ts at main · sailfork/t3code-github · Sailfork
	
		
); export const nodejsAlsPlugin = createPlugin("nodejs-als", (options) => { if (!hasNodejsAls(options.compatibilityFlags)) return; return { rolldown: { resolveId: { filter: { id: ASYNC_HOOKS_REGEXP }, handler(id) { return { id, external: true }; }, }, }, vite: { enforce: "pre", configEnvironment(name) { if (name === "client") return; return { resolve: { builtins: ["async_hooks", "node:async_hooks"], }, optimizeDeps: { exclude: ["async_hooks", "node:async_hooks"], }, }; }, }, }; }); export interface UnenvApi { polyfill: ReadonlyArray<string>; inject: { [injectedName: string]: string }; } export const getUnenv = (options: BasePluginOptions) => defineEnv({ presets: [ getCloudflarePreset({ compatibilityDate: options.compatibilityDate, compatibilityFlags: options.compatibilityFlags, }), ], }).env; export const nodejsUnenvPlugin = createPlugin<"nodejs-unenv", UnenvApi>( "nodejs-unenv", (options) => { if (!hasNodejsCompat(options.compatibilityFlags, options.compatibilityDate)) return; const { alias, inject, polyfill, external } = getUnenv(options); const entries = new Set(Object.values(alias)); for (const globalInject of Object.values(inject)) { if (typeof globalInject === "string") { entries.add(globalInject); } else { entries.add(globalInject[0]); } } polyfill.forEach((module) => entries.add(module)); external.forEach((module) => entries.delete(module)); const require = createRequire(import.meta.url); // `unresolved` is the polyfill's bare specifier: the key it is // pre-bundled under, shared by every import that aliases to it. const resolveNodejsImport = (id: string) => { if (alias[id] && !external.includes(alias[id])) { return { unresolved: alias[id], resolved: require.resolve(alias[id]) }; } if (entries.has(id)) { return { unresolved: id, resolved: require.resolve(id) }; } }; const RESOLVE_ID_FILTER = { id: [NODE_BUILTIN_MODULES_REGEXP, /^unenv\//, /^@cloudflare\/unenv-preset\//], }; return { shared: { api: { // Virtual entries have no package directory for bare-import resolution. polyfill: polyfill.map((id) => toPosixPath(require.resolve(id))), inject: Object.fromEntries( Object.entries(inject).map(([injectedName, moduleSpecifier]) => { assert( typeof moduleSpecifier === "string", `expected moduleSpecifier to be a string`, ); return [injectedName, toPosixPath(require.resolve(moduleSpecifier))]; }), ), }, }, rolldown: { resolveId: { filter: RESOLVE_ID_FILTER, handler(source, importer, options) { const result = resolveNodejsImport(source); if (!result) return; return this.resolve(result.resolved, importer, options); }, }, }, vite: { enforce: "pre", async configEnvironment(name) { if (name === "client") return; const { esmExternalRequirePlugin } = await import("vite"); return { resolve: { builtins: [...external], }, ...(this.meta.rolldownVersion ? { build: { rolldownOptions: { plugins: [ esmExternalRequirePlugin({ external: [...external], skipDuplicateCheck: true, }), ], }, }, } : {}), // (Node.js built-ins are excluded from pre-bundling for every // Worker environment by the options plugin.) optimizeDeps: this.meta.rolldownVersion ? { rolldownOptions: { plugins: [ // In Vite 8, `require` calls are not automatically replaced when // the format is ESM and `platform` is `neutral`. esmExternalRequirePlugin({ external: [NODE_BUILTIN_MODULES_REGEXP], skipDuplicateCheck: true, }), ], }, } : {}, }; }, async configureServer(server) { await Promise.all( Object.values(server.environments).flatMap(async (environment) => { // Framework-owned Node-side environments (e.g. Astro's `astro` // and `prerender`) must be left untouched — this is a // server-level hook, so `applyToEnvironment` cannot gate it. if (isSkippedEnvironment(options, environment.name)) return; const depsOptimizer = environment.depsOptimizer; if (!depsOptimizer) return; // Environments using Vite's no-discovery ("explicit") optimizer // throw on `registerMissingImport` by design; pre-bundling the // unenv polyfills is best-effort, so skip them. if (!supportsMissingImportRegistration(environment)) return; await depsOptimizer.init(); return Array.from(entries).map((entry) => { const result = resolveNodejsImport(entry); if (!result) return; const registration = depsOptimizer.registerMissingImport( result.unresolved, result.resolved, ); return registration?.processing; }); }), ); }, resolveId: { filter: RESOLVE_ID_FILTER, handler(source, importer, options) { const result = resolveNodejsImport(source); if (!result) return; if ( this.environment.mode === "dev" && this.environment.depsOptimizer && supportsMissingImportRegistration(this.environment) ) { // We are in dev mode (rather than build). // So let's pre-bundle this polyfill entry-point using the dependency optimizer. const { id } = this.environment.depsOptimizer.registerMissingImport( result.unresolved, result.resolved, ); // We use the unresolved path to the polyfill and let the dependency optimizer's // resolver find the resolved path to the bundled version. return this.resolve(id, importer, options); } return this.resolve(result.resolved, importer, options); }, }, }, }; }, ); /** * Vite's no-discovery ("explicit") dependency optimizer throws on * `registerMissingImport` by design, and third-party environments may not * implement it at all. Feature-detect before registering polyfill entries. */ const supportsMissingImportRegistration = (environment: { config: { optimizeDeps?: { noDiscovery?: boolean } }; depsOptimizer?: { registerMissingImport?: unknown } | undefined; }): boolean => environment.config.optimizeDeps?.noDiscovery !== true && typeof environment.depsOptimizer?.registerMissingImport === "function"; export const nodejsImportWarningPlugin = createPlugin("nodejs-import-warning", (options) => { if (hasNodejsCompat(options.compatibilityFlags, options.compatibilityDate)) return; const imports = new Map<string, Set<string>>(); let root = process.cwd(); // In dev there is no `buildEnd` until the server closes, so, as // `@cloudflare/vite-plugin` does, warn once imports go quiet. const devImports = new Map<string, Set<string>>(); let devTimer: ReturnType<typeof setTimeout> | undefined; const warnInDev = (environment: { name: string; logger: { warn: (message: string, options?: { timestamp?: boolean }) => void }; }) => { if (devTimer) clearTimeout(devTimer); devTimer = setTimeout(() => { devTimer = undefined; if (devImports.size === 0) return; let message = `Unexpected Node.js imports for environment "${environment.name}". Do you need to enable the "nodejs_compat" compatibility flag? Refer to https://developers.cloudflare.com/workers/runtime-apis/nodejs/ for more details.\n`; for (const [id, importers] of devImports) { for (const importer of importers) { message += ` - "${id}" imported from "${toPosixPath(path.relative(root, importer))}"\n`; } } devImports.clear(); environment.logger.warn(message, { timestamp: true }); }, 500); }; return { rolldown: { options(options) { if (options.cwd) { root = options.cwd; } }, }, vite: { enforce: "pre", configResolved(config) { root = config.root; }, }, shared: { buildStart() { imports.clear(); }, resolveId: { filter: { id: NODE_BUILTIN_MODULES_REGEXP }, async handler(id, importer) { if (hasNodejsAls(options.compatibilityFlags) && ASYNC_HOOKS_REGEXP.test(id)) return; if (importer) { if (!imports.has(id)) { imports.set(id, new Set()); } imports.get(id)?.add(importer); const environment = ( this as { environment?: { name: string; mode: string; logger: Parameters<typeof warnInDev>[0]["logger"]; }; } ).environment; if (environment?.mode === "dev") { if (!devImports.has(id)) devImports.set(id, new Set()); devImports.get(id)?.add(importer); warnInDev(environment); } } return { id, external: true }; }, }, buildEnd() { const filteredImports: Array<{ id: string; importer: string }> = []; for (const [id, importers] of imports.entries()) { for (const importer of importers) { if (this.getModuleInfo(importer)) { filteredImports.push({ id, importer }); } } } if (filteredImports.length > 0) { const message = [ "Unexpected Node.js imports. ", 'Do you need to enable the "nodejs_compat" compatibility flag? ', "Refer to https://developers.cloudflare.com/workers/runtime-apis/nodejs/ for more details.\n", ...filteredImports.map( ({ id, importer }) => ` - "${id}" imported from "${toPosixPath(path.relative(root, importer))}"\n`, ), ].join(""); this.warn(message); } }, }, }; });
.repos/alchemy-effect/packages/cloudflare-runtime/src/rolldown/plugins/nodejs-compat.ts at main · sailfork/t3code-github · Sailfork
);\n\nexport const nodejsAlsPlugin = createPlugin(\"nodejs-als\", (options) => {\n if (!hasNodejsAls(options.compatibilityFlags)) return;\n return {\n rolldown: {\n resolveId: {\n filter: { id: ASYNC_HOOKS_REGEXP },\n handler(id) {\n return { id, external: true };\n },\n },\n },\n vite: {\n enforce: \"pre\",\n configEnvironment(name) {\n if (name === \"client\") return;\n return {\n resolve: {\n builtins: [\"async_hooks\", \"node:async_hooks\"],\n },\n optimizeDeps: {\n exclude: [\"async_hooks\", \"node:async_hooks\"],\n },\n };\n },\n },\n };\n});\n\nexport interface UnenvApi {\n polyfill: ReadonlyArray\u003cstring>;\n inject: { [injectedName: string]: string };\n}\n\nexport const getUnenv = (options: BasePluginOptions) =>\n defineEnv({\n presets: [\n getCloudflarePreset({\n compatibilityDate: options.compatibilityDate,\n compatibilityFlags: options.compatibilityFlags,\n }),\n ],\n }).env;\n\nexport const nodejsUnenvPlugin = createPlugin\u003c\"nodejs-unenv\", UnenvApi>(\n \"nodejs-unenv\",\n (options) => {\n if (!hasNodejsCompat(options.compatibilityFlags, options.compatibilityDate)) return;\n const { alias, inject, polyfill, external } = getUnenv(options);\n const entries = new Set(Object.values(alias));\n for (const globalInject of Object.values(inject)) {\n if (typeof globalInject === \"string\") {\n entries.add(globalInject);\n } else {\n entries.add(globalInject[0]);\n }\n }\n polyfill.forEach((module) => entries.add(module));\n external.forEach((module) => entries.delete(module));\n const require = createRequire(import.meta.url);\n // `unresolved` is the polyfill's bare specifier: the key it is\n // pre-bundled under, shared by every import that aliases to it.\n const resolveNodejsImport = (id: string) => {\n if (alias[id] && !external.includes(alias[id])) {\n return { unresolved: alias[id], resolved: require.resolve(alias[id]) };\n }\n if (entries.has(id)) {\n return { unresolved: id, resolved: require.resolve(id) };\n }\n };\n const RESOLVE_ID_FILTER = {\n id: [NODE_BUILTIN_MODULES_REGEXP, /^unenv\\//, /^@cloudflare\\/unenv-preset\\//],\n };\n return {\n shared: {\n api: {\n // Virtual entries have no package directory for bare-import resolution.\n polyfill: polyfill.map((id) => toPosixPath(require.resolve(id))),\n inject: Object.fromEntries(\n Object.entries(inject).map(([injectedName, moduleSpecifier]) => {\n assert(\n typeof moduleSpecifier === \"string\",\n `expected moduleSpecifier to be a string`,\n );\n return [injectedName, toPosixPath(require.resolve(moduleSpecifier))];\n }),\n ),\n },\n },\n rolldown: {\n resolveId: {\n filter: RESOLVE_ID_FILTER,\n handler(source, importer, options) {\n const result = resolveNodejsImport(source);\n if (!result) return;\n return this.resolve(result.resolved, importer, options);\n },\n },\n },\n vite: {\n enforce: \"pre\",\n async configEnvironment(name) {\n if (name === \"client\") return;\n const { esmExternalRequirePlugin } = await import(\"vite\");\n return {\n resolve: {\n builtins: [...external],\n },\n ...(this.meta.rolldownVersion\n ? {\n build: {\n rolldownOptions: {\n plugins: [\n esmExternalRequirePlugin({\n external: [...external],\n skipDuplicateCheck: true,\n }),\n ],\n },\n },\n }\n : {}),\n // (Node.js built-ins are excluded from pre-bundling for every\n // Worker environment by the options plugin.)\n optimizeDeps: this.meta.rolldownVersion\n ? {\n rolldownOptions: {\n plugins: [\n // In Vite 8, `require` calls are not automatically replaced when\n // the format is ESM and `platform` is `neutral`.\n esmExternalRequirePlugin({\n external: [NODE_BUILTIN_MODULES_REGEXP],\n skipDuplicateCheck: true,\n }),\n ],\n },\n }\n : {},\n };\n },\n async configureServer(server) {\n await Promise.all(\n Object.values(server.environments).flatMap(async (environment) => {\n // Framework-owned Node-side environments (e.g. Astro's `astro`\n // and `prerender`) must be left untouched — this is a\n // server-level hook, so `applyToEnvironment` cannot gate it.\n if (isSkippedEnvironment(options, environment.name)) return;\n const depsOptimizer = environment.depsOptimizer;\n if (!depsOptimizer) return;\n // Environments using Vite's no-discovery (\"explicit\") optimizer\n // throw on `registerMissingImport` by design; pre-bundling the\n // unenv polyfills is best-effort, so skip them.\n if (!supportsMissingImportRegistration(environment)) return;\n await depsOptimizer.init();\n return Array.from(entries).map((entry) => {\n const result = resolveNodejsImport(entry);\n if (!result) return;\n const registration = depsOptimizer.registerMissingImport(\n result.unresolved,\n result.resolved,\n );\n return registration?.processing;\n });\n }),\n );\n },\n resolveId: {\n filter: RESOLVE_ID_FILTER,\n handler(source, importer, options) {\n const result = resolveNodejsImport(source);\n if (!result) return;\n if (\n this.environment.mode === \"dev\" &&\n this.environment.depsOptimizer &&\n supportsMissingImportRegistration(this.environment)\n ) {\n // We are in dev mode (rather than build).\n // So let's pre-bundle this polyfill entry-point using the dependency optimizer.\n const { id } = this.environment.depsOptimizer.registerMissingImport(\n result.unresolved,\n result.resolved,\n );\n // We use the unresolved path to the polyfill and let the dependency optimizer's\n // resolver find the resolved path to the bundled version.\n return this.resolve(id, importer, options);\n }\n return this.resolve(result.resolved, importer, options);\n },\n },\n },\n };\n },\n);\n\n/**\n * Vite's no-discovery (\"explicit\") dependency optimizer throws on\n * `registerMissingImport` by design, and third-party environments may not\n * implement it at all. Feature-detect before registering polyfill entries.\n */\nconst supportsMissingImportRegistration = (environment: {\n config: { optimizeDeps?: { noDiscovery?: boolean } };\n depsOptimizer?: { registerMissingImport?: unknown } | undefined;\n}): boolean =>\n environment.config.optimizeDeps?.noDiscovery !== true &&\n typeof environment.depsOptimizer?.registerMissingImport === \"function\";\n\nexport const nodejsImportWarningPlugin = createPlugin(\"nodejs-import-warning\", (options) => {\n if (hasNodejsCompat(options.compatibilityFlags, options.compatibilityDate)) return;\n const imports = new Map\u003cstring, Set\u003cstring>>();\n let root = process.cwd();\n // In dev there is no `buildEnd` until the server closes, so, as\n // `@cloudflare/vite-plugin` does, warn once imports go quiet.\n const devImports = new Map\u003cstring, Set\u003cstring>>();\n let devTimer: ReturnType\u003ctypeof setTimeout> | undefined;\n const warnInDev = (environment: {\n name: string;\n logger: { warn: (message: string, options?: { timestamp?: boolean }) => void };\n }) => {\n if (devTimer) clearTimeout(devTimer);\n devTimer = setTimeout(() => {\n devTimer = undefined;\n if (devImports.size === 0) return;\n let message = `Unexpected Node.js imports for environment \"${environment.name}\". Do you need to enable the \"nodejs_compat\" compatibility flag? Refer to https://developers.cloudflare.com/workers/runtime-apis/nodejs/ for more details.\\n`;\n for (const [id, importers] of devImports) {\n for (const importer of importers) {\n message += ` - \"${id}\" imported from \"${toPosixPath(path.relative(root, importer))}\"\\n`;\n }\n }\n devImports.clear();\n environment.logger.warn(message, { timestamp: true });\n }, 500);\n };\n return {\n rolldown: {\n options(options) {\n if (options.cwd) {\n root = options.cwd;\n }\n },\n },\n vite: {\n enforce: \"pre\",\n configResolved(config) {\n root = config.root;\n },\n },\n shared: {\n buildStart() {\n imports.clear();\n },\n resolveId: {\n filter: { id: NODE_BUILTIN_MODULES_REGEXP },\n async handler(id, importer) {\n if (hasNodejsAls(options.compatibilityFlags) && ASYNC_HOOKS_REGEXP.test(id)) return;\n if (importer) {\n if (!imports.has(id)) {\n imports.set(id, new Set());\n }\n imports.get(id)?.add(importer);\n const environment = (\n this as {\n environment?: {\n name: string;\n mode: string;\n logger: Parameters\u003ctypeof warnInDev>[0][\"logger\"];\n };\n }\n ).environment;\n if (environment?.mode === \"dev\") {\n if (!devImports.has(id)) devImports.set(id, new Set());\n devImports.get(id)?.add(importer);\n warnInDev(environment);\n }\n }\n return { id, external: true };\n },\n },\n buildEnd() {\n const filteredImports: Array\u003c{ id: string; importer: string }> = [];\n for (const [id, importers] of imports.entries()) {\n for (const importer of importers) {\n if (this.getModuleInfo(importer)) {\n filteredImports.push({ id, importer });\n }\n }\n }\n if (filteredImports.length > 0) {\n const message = [\n \"Unexpected Node.js imports. \",\n 'Do you need to enable the \"nodejs_compat\" compatibility flag? ',\n \"Refer to https://developers.cloudflare.com/workers/runtime-apis/nodejs/ for more details.\\n\",\n ...filteredImports.map(\n ({ id, importer }) =>\n ` - \"${id}\" imported from \"${toPosixPath(path.relative(root, importer))}\"\\n`,\n ),\n ].join(\"\");\n this.warn(message);\n }\n },\n },\n };\n});\n","preview":null,"history":null,"version":"b570857715da43d96fa33122783ae97a79a32e75"},"/_session?shell=1":null}