autotel
Version:
Write Once, Observe Anywhere
1 lines • 5.68 kB
Source Map (JSON)
{"version":3,"sources":["../src/node-require.ts"],"names":["createRequire"],"mappings":";;;;;;AAiCA,IAAI,aAAA;AAEJ,SAAS,cAAA,GAA8B;AACrC,EAAA,IAAI,eAAe,OAAO,aAAA;AAC1B,EAAA,MAAM,IAAA,GAAO,OAAO,UAAA,KAAe,QAAA,GAAW,aAAa,oQAAY;AACvE,EAAA,IAAI,CAAC,IAAA,EAAM;AAGT,IAAA,MAAM,MAAA,CAAO,MAAA;AAAA,MACX,IAAI,MAAM,+CAA+C,CAAA;AAAA,MACzD,EAAE,MAAM,kBAAA;AAAmB,KAC7B;AAAA,EACF;AACA,EAAA,aAAA,GAAgBA,uBAAc,IAAI,CAAA;AAClC,EAAA,OAAO,aAAA;AACT;AAmBO,SAAS,YAAyB,EAAA,EAA2B;AAClE,EAAA,IAAI;AACF,IAAA,OAAO,cAAA,GAAiB,EAAE,CAAA;AAAA,EAC5B,SAAS,KAAA,EAAO;AACd,IAAA,IAAI,KAAA,IAAU,KAAA,CAAgC,IAAA,KAAS,kBAAA,EAAoB;AAEzE,MAAA,OAAO,MAAA;AAAA,IACT;AAEA,IAAA,MAAM,KAAA;AAAA,EACR;AACF;AAmBO,SAAS,cAA2B,EAAA,EAAe;AACxD,EAAA,OAAO,cAAA,GAAiB,EAAE,CAAA;AAC5B;AAiBA,IAAM,WAAA,IAAe,CAAC,EAAA,EAAY,OAAA,KAChC,gBAAe,CAAE,OAAA,CAAQ,IAAI,OAAO,CAAA,CAAA;AACtC,WAAA,CAAY,QAAQ,CAAC,OAAA,KACnB,gBAAe,CAAE,OAAA,CAAQ,MAAM,OAAO,CAAA","file":"chunk-NVAI5CCN.cjs","sourcesContent":["/**\n * Cross-format require() helper for CJS and ESM compatibility\n *\n * Provides a synchronous `require()` function that works in both:\n * - CJS builds: Uses native `require`\n * - ESM builds: Uses `createRequire(import.meta.url)`\n *\n * This allows optional peer dependencies and dynamic module loading\n * to work synchronously in both module formats.\n */\n\nimport { createRequire } from 'node:module';\n\n// `__filename` is provided by CJS and by esbuild's CJS output wrapper, but\n// is undefined under pure ESM. `import.meta.url` is provided by ESM. Pick\n// whichever is available so the helper works in:\n// - native CJS (autotel's published `.cjs`)\n// - native ESM (autotel's published `.js`)\n// - ESM-bundled-into-CJS by a downstream consumer (e.g. CDK's\n// `aws-lambda-nodejs` → esbuild with `format: cjs`). esbuild rewrites\n// `import.meta` to `{}` in this case, so `createRequire(import.meta.url)`\n// alone collapses to `createRequire(undefined)` and crashes at load.\n// `typeof __filename` does NOT throw when the identifier is undeclared, so\n// the ESM build evaluates the conditional safely.\ndeclare const __filename: string | undefined;\n\n// Build the Node `require` lazily on first use. Calling `createRequire`\n// eagerly at module load crashes in runtimes where neither `__filename` nor\n// `import.meta.url` resolves to a path — e.g. Cloudflare Workers / workerd,\n// where the bundle has no module path and `createRequire(undefined)` throws\n// synchronously at import. Deferring the call keeps merely importing this\n// module (and therefore anything that re-exports it, such as `track`)\n// side-effect-free; Node/CJS/ESM still get a real `require` on first call.\nlet cachedRequire: NodeRequire | undefined;\n\nfunction getNodeRequire(): NodeRequire {\n if (cachedRequire) return cachedRequire;\n const base = typeof __filename === 'string' ? __filename : import.meta.url;\n if (!base) {\n // No module path in this runtime. Surface as a missing-module error so\n // optional lookups via `safeRequire()` degrade gracefully to `undefined`.\n throw Object.assign(\n new Error('node require() is unavailable in this runtime'),\n { code: 'MODULE_NOT_FOUND' },\n );\n }\n cachedRequire = createRequire(base);\n return cachedRequire;\n}\n\n/**\n * Synchronously require a module (works in both CJS and ESM)\n *\n * @param id - Module ID to require\n * @returns The required module\n * @throws Error if module cannot be loaded\n *\n * @example\n * ```typescript\n * import { safeRequire } from './node-require';\n *\n * const traceloop = safeRequire('@traceloop/node-server-sdk');\n * if (traceloop) {\n * traceloop.initialize({ ... });\n * }\n * ```\n */\nexport function safeRequire<T = unknown>(id: string): T | undefined {\n try {\n return getNodeRequire()(id) as T;\n } catch (error) {\n if (error && (error as NodeJS.ErrnoException).code === 'MODULE_NOT_FOUND') {\n // Optional dependency missing – return undefined\n return undefined;\n }\n // Any other error is a real bug: rethrow\n throw error;\n }\n}\n\n/**\n * Synchronously require a module (throws if not found)\n *\n * Use this when the module is required (not optional).\n *\n * @param id - Module ID to require\n * @returns The required module\n * @throws Error if module cannot be loaded\n *\n * @example\n * ```typescript\n * import { requireModule } from './node-require';\n *\n * const fs = requireModule<typeof import('node:fs')>('node:fs');\n * const content = fs.readFileSync('file.txt', 'utf8');\n * ```\n */\nexport function requireModule<T = unknown>(id: string): T {\n return getNodeRequire()(id) as T;\n}\n\n/**\n * Direct access to the nodeRequire function (for advanced use cases).\n *\n * Lazily resolves the underlying Node `require` on first call, so importing\n * this binding never triggers `createRequire` in runtimes that lack a module\n * path (e.g. Cloudflare Workers).\n *\n * Only the call signature and `resolve` (including `resolve.paths`) are\n * forwarded. The live, mutable members of a real `require` — `.cache`,\n * `.main`, `.extensions` — are intentionally NOT exposed: a lazy wrapper\n * can't mirror that shared state without resolving eagerly, which would\n * reintroduce the workerd crash. Use `createRequire` directly if you need\n * them.\n */\nconst nodeRequire = ((id: string) => getNodeRequire()(id)) as NodeRequire;\nconst lazyResolve = ((id: string, options?: { paths?: string[] }) =>\n getNodeRequire().resolve(id, options)) as NodeRequire['resolve'];\nlazyResolve.paths = (request: string) =>\n getNodeRequire().resolve.paths(request);\nnodeRequire.resolve = lazyResolve;\n\nexport { nodeRequire };\n"]}