@gaganref/confect-cli 10.3.1-fork.96 → 10.6.0-fork.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/dist/Ansi.mjs +1 -2
  3. package/dist/BuildError.mjs +5 -5
  4. package/dist/BuildError.mjs.map +1 -1
  5. package/dist/Bundler.mjs +103 -76
  6. package/dist/Bundler.mjs.map +1 -1
  7. package/dist/CodeBlockWriter.mjs +1 -2
  8. package/dist/CodegenError.mjs +27 -17
  9. package/dist/CodegenError.mjs.map +1 -1
  10. package/dist/ConfectDirectory.mjs +8 -3
  11. package/dist/ConfectDirectory.mjs.map +1 -1
  12. package/dist/ConvexConfig.mjs +23 -15
  13. package/dist/ConvexConfig.mjs.map +1 -1
  14. package/dist/ConvexDirectory.mjs +6 -4
  15. package/dist/ConvexDirectory.mjs.map +1 -1
  16. package/dist/Declaration.mjs +92 -56
  17. package/dist/Declaration.mjs.map +1 -1
  18. package/dist/DirectoryOptions.mjs +13 -8
  19. package/dist/DirectoryOptions.mjs.map +1 -1
  20. package/dist/DocName.mjs +1 -2
  21. package/dist/EntryPoint.mjs +17 -15
  22. package/dist/EntryPoint.mjs.map +1 -1
  23. package/dist/Evaluation.mjs +24 -13
  24. package/dist/Evaluation.mjs.map +1 -1
  25. package/dist/EvaluationWorker.mjs +5 -6
  26. package/dist/EvaluationWorker.mjs.map +1 -1
  27. package/dist/FunctionModule.mjs +85 -47
  28. package/dist/FunctionModule.mjs.map +1 -1
  29. package/dist/FunctionPath.mjs +1 -2
  30. package/dist/FunctionPath.mjs.map +1 -1
  31. package/dist/FunctionPaths.mjs +2 -3
  32. package/dist/GenerationSnapshot.mjs +30 -22
  33. package/dist/GenerationSnapshot.mjs.map +1 -1
  34. package/dist/GroupPath.mjs +6 -3
  35. package/dist/GroupPath.mjs.map +1 -1
  36. package/dist/GroupPaths.mjs +1 -2
  37. package/dist/ImplModulePath.mjs +1 -2
  38. package/dist/Json.mjs +13 -0
  39. package/dist/Json.mjs.map +1 -0
  40. package/dist/LeafModule.mjs +121 -41
  41. package/dist/LeafModule.mjs.map +1 -1
  42. package/dist/ManifestSections.mjs +23 -19
  43. package/dist/ManifestSections.mjs.map +1 -1
  44. package/dist/PackageSelfReference.mjs +32 -0
  45. package/dist/PackageSelfReference.mjs.map +1 -0
  46. package/dist/ProjectRoot.mjs +11 -3
  47. package/dist/ProjectRoot.mjs.map +1 -1
  48. package/dist/RelativeModulePath.mjs +1 -2
  49. package/dist/Remove.mjs +2 -3
  50. package/dist/Remove.mjs.map +1 -1
  51. package/dist/RestoreWatcher.mjs +1 -2
  52. package/dist/Rollback.mjs +7 -6
  53. package/dist/Rollback.mjs.map +1 -1
  54. package/dist/SectionFiles.mjs +77 -48
  55. package/dist/SectionFiles.mjs.map +1 -1
  56. package/dist/SnapshotError.mjs +3 -3
  57. package/dist/SnapshotError.mjs.map +1 -1
  58. package/dist/SpecAssemblyNode.mjs +1 -2
  59. package/dist/SpecModulePath.mjs +4 -4
  60. package/dist/SpecModulePath.mjs.map +1 -1
  61. package/dist/SyncState.mjs +3 -4
  62. package/dist/SyncState.mjs.map +1 -1
  63. package/dist/TableModule.mjs +18 -10
  64. package/dist/TableModule.mjs.map +1 -1
  65. package/dist/TableModulePath.mjs +3 -3
  66. package/dist/TableModulePath.mjs.map +1 -1
  67. package/dist/TypeScriptConfig.mjs +135 -0
  68. package/dist/TypeScriptConfig.mjs.map +1 -0
  69. package/dist/WatchBuild.mjs +107 -32
  70. package/dist/WatchBuild.mjs.map +1 -1
  71. package/dist/WatchGraph.mjs +4 -4
  72. package/dist/WatchGraph.mjs.map +1 -1
  73. package/dist/WatchTopology.mjs +5 -4
  74. package/dist/WatchTopology.mjs.map +1 -1
  75. package/dist/Watcher.mjs +179 -108
  76. package/dist/Watcher.mjs.map +1 -1
  77. package/dist/cliApp.mjs +5 -3
  78. package/dist/cliApp.mjs.map +1 -1
  79. package/dist/confect/codegen.mjs +95 -53
  80. package/dist/confect/codegen.mjs.map +1 -1
  81. package/dist/confect/declaration.mjs +76 -42
  82. package/dist/confect/declaration.mjs.map +1 -1
  83. package/dist/confect/dev.mjs +18 -12
  84. package/dist/confect/dev.mjs.map +1 -1
  85. package/dist/confect.mjs +4 -2
  86. package/dist/confect.mjs.map +1 -1
  87. package/dist/index.mjs +1 -2
  88. package/dist/log.mjs +13 -5
  89. package/dist/log.mjs.map +1 -1
  90. package/dist/package.json.mjs +5 -0
  91. package/dist/package.json.mjs.map +1 -0
  92. package/dist/templates.mjs +34 -22
  93. package/dist/templates.mjs.map +1 -1
  94. package/dist/utils.mjs +36 -5
  95. package/dist/utils.mjs.map +1 -1
  96. package/package.json +10 -10
  97. package/dist/package.mjs +0 -6
  98. package/dist/package.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"Bundler.mjs","names":[],"sources":["../src/Bundler.ts"],"sourcesContent":["import { createRequire, isBuiltin } from \"node:module\";\nimport { pathToFileURL } from \"node:url\";\nimport { parseArgs } from \"node:util\";\nimport {\n bundleRequire,\n dynamicImport,\n injectFileScopePlugin,\n JS_EXT_RE,\n loadTsConfig,\n tsconfigPathsToRegExp,\n} from \"bundle-require\";\nimport { resolveModulePath } from \"exsolve\";\nimport { identity, pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Chunk from \"effect/Chunk\";\nimport * as Cause from \"effect/Cause\";\nimport * as Config from \"effect/Config\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as HashMap from \"effect/HashMap\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as Iterable from \"effect/Iterable\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Ref from \"effect/Ref\";\nimport * as Record from \"effect/Record\";\nimport * as Scope from \"effect/Scope\";\nimport * as Schema from \"effect/Schema\";\nimport * as String from \"effect/String\";\nimport * as esbuild from \"esbuild\";\nimport { BundlerError } from \"./BuildError.js\";\nimport { logCoalescedBuildWarnings } from \"./log.js\";\n\nexport interface Bundled {\n readonly module: any;\n readonly metafile: esbuild.Metafile;\n}\n\n/**\n * `bundle-require` sets `absWorkingDir: cwd` on the underlying esbuild build,\n * so the metafile's input keys (and each input's `imports[].path`) are stored\n * relative to that cwd. Callers reach for the metafile with absolute paths\n * (e.g. {@link directlyImports}), so we normalize every key/import path to\n * absolute up front. That way the lookup logic stays oblivious to whatever cwd\n * was used during bundling.\n *\n * `original` (the specifier as written, before resolution) is filled in from\n * `path` when esbuild omits it—esbuild only sets it when it differs from the\n * resolved path, which is exactly the externalized-bare-specifier case that\n * absolutizing `path` would otherwise mangle into `<cwd>/@confect/server`.\n * {@link importersOfPackage} relies on `original` always being the raw\n * specifier.\n */\nconst absolutizeMetafile = (\n path: Path.Path,\n metafile: esbuild.Metafile,\n cwd: string,\n): esbuild.Metafile => {\n const absolutize = (p: string) => path.resolve(cwd, p);\n const inputs = Record.mapEntries(metafile.inputs, (value, key) => [\n absolutize(key),\n {\n ...value,\n imports: Array.map(value.imports, (i) => ({\n ...i,\n path: absolutize(i.path),\n original: i.original ?? i.path,\n })),\n },\n ]);\n const outputs = Record.mapEntries(metafile.outputs, (value, key) => [\n absolutize(key),\n {\n ...value,\n ...(value.entryPoint ? { entryPoint: absolutize(value.entryPoint) } : {}),\n inputs: Record.mapKeys(value.inputs, absolutize),\n imports: Array.map(value.imports, (imported) =>\n imported.external\n ? imported\n : { ...imported, path: absolutize(imported.path) },\n ),\n },\n ]);\n return { inputs, outputs };\n};\n\nconst resolveEsm = Option.liftThrowable((specifier: string, importer: string) =>\n resolveModulePath(specifier, {\n from: importer,\n conditions: [\"node\", \"import\"],\n }),\n);\n\nconst resolveCjs = Option.liftThrowable((specifier: string, importer: string) =>\n createRequire(importer).resolve(specifier),\n);\n\nconst resolveExternalEsm = Option.liftThrowable(\n (specifier: string, importer: string, conditions: string[]) =>\n resolveModulePath(specifier, { from: importer, conditions }),\n);\n\nexport const resolveModule = (\n specifier: string,\n importer: string,\n): Option.Option<string> =>\n Option.orElse(resolveEsm(specifier, importer), () =>\n resolveCjs(specifier, importer),\n );\n\n/**\n * The names `file` exports, read by esbuild without evaluating the module, so a\n * test kit that only runs under Vite (`import.meta.glob`) can be checked. None\n * when only running the module would list them: a CommonJS module assigns its\n * exports at run time, and bare imports stay external, so `export *` from\n * another package hides its names.\n */\nexport const exportNames = (\n file: string,\n): Effect.Effect<Option.Option<ReadonlyArray<string>>, BundlerError> =>\n Effect.tryPromise({\n try: () =>\n esbuild.build({\n entryPoints: [file],\n bundle: true,\n packages: \"external\",\n format: \"esm\",\n platform: \"node\",\n write: false,\n metafile: true,\n logLevel: \"silent\",\n outdir: \"out\",\n }),\n catch: (cause) => new BundlerError({ cause }),\n }).pipe(\n Effect.map(({ metafile, outputFiles }) =>\n Object.values(metafile.inputs).some(({ format }) => format === \"cjs\") ||\n outputFiles.some(({ text }) => /^export \\* from /m.test(text))\n ? Option.none()\n : Option.some(\n Object.values(metafile.outputs).flatMap(({ exports }) => exports),\n ),\n ),\n );\n\n/**\n * Bundles first-party workspace dependencies that `bundle-require` would\n * otherwise externalize and hand to Node's native ESM resolver. Resolves each\n * bare specifier and, following symlinks, bundles it when its real path lives\n * outside `node_modules`—mirroring Vite's \"linked dependencies are not\n * externalized\" heuristic. Registered ahead of `externalPlugin`, so deferring\n * (returning `undefined`) leaves third-party externalization untouched.\n * `skipPatterns` are the tsconfig `paths` regexes, which keep deferring to\n * esbuild's own `paths` resolution.\n */\nexport const bundleWorkspacePlugin = (\n path: Path.Path,\n fs: FileSystem.FileSystem,\n skipPatterns: ReadonlyArray<RegExp>,\n): esbuild.Plugin => ({\n name: \"confect:bundle-workspace\",\n setup(build) {\n build.onResolve({ filter: /^[^./]/ }, (args) => {\n if (args.namespace !== \"file\" && args.namespace !== \"\") return undefined;\n if (isBuiltin(args.path) || path.isAbsolute(args.path)) return undefined;\n if (Array.some(skipPatterns, (pattern) => pattern.test(args.path))) {\n return undefined;\n }\n\n const importer =\n args.importer !== \"\" ? args.importer : path.join(args.resolveDir, \"_\");\n\n return Option.match(resolveModule(args.path, importer), {\n onNone: () => ({\n path: args.path,\n external: true,\n warnings: [\n {\n text: `Confect could not resolve workspace dependency \"${args.path}\" (imported from ${importer}) to bundle it; leaving it external.`,\n },\n ],\n }),\n onSome: (resolved) =>\n Effect.runPromise(\n fs.realPath(resolved).pipe(Effect.orElseSucceed(() => resolved)),\n ).then((real) =>\n pipe(real, String.split(path.sep), Array.contains(\"node_modules\"))\n ? undefined\n : { path: real },\n ),\n });\n });\n },\n});\n\ninterface CapturedBuildResult {\n readonly metafile: esbuild.Metafile | undefined;\n readonly warnings: ReadonlyArray<esbuild.Message>;\n}\n\nconst captureBuildResultPlugin = (\n ref: Ref.Ref<CapturedBuildResult>,\n): esbuild.Plugin => ({\n name: \"confect:capture-build-result\",\n setup(build) {\n build.onEnd((result) => {\n Effect.runSync(\n Ref.set(ref, {\n metafile: result.metafile,\n warnings: result.warnings,\n }),\n );\n });\n },\n});\n\ninterface BatchCompilation {\n readonly entries: HashMap.HashMap<\n string,\n { readonly source: string; readonly output: string }\n >;\n readonly metafile: esbuild.Metafile;\n readonly warnings: ReadonlyArray<esbuild.Message>;\n readonly cwd: string;\n}\n\nclass BatchIncompatible extends Schema.TaggedError<BatchIncompatible>()(\n \"BatchIncompatible\",\n {\n reason: Schema.Literals([\n \"RuntimeConditions\",\n \"UnsupportedEntries\",\n \"MixedTsconfigs\",\n \"UnattributedWarnings\",\n ]),\n message: Schema.String,\n },\n) {}\n\nclass Batch extends Context.Service<\n Batch,\n {\n readonly entryPoints: ReadonlyArray<string>;\n readonly compilation: Effect.Effect<\n Option.Option<BatchCompilation>,\n never,\n Path.Path | FileSystem.FileSystem\n >;\n }\n>()(\"@confect/cli/Bundler/Batch\") {}\n\ninterface ExternalImport {\n readonly path: string;\n readonly original: string;\n}\n\nconst batchResolutionPlugin = (\n path: Path.Path,\n fs: FileSystem.FileSystem,\n skipPatterns: ReadonlyArray<RegExp>,\n conditions: string[],\n externalImports: Ref.Ref<\n HashMap.HashMap<string, ReadonlyArray<ExternalImport>>\n >,\n): esbuild.Plugin => ({\n name: \"confect:batch-resolution\",\n setup(build) {\n const external = (args: esbuild.OnResolveArgs, resolved: string) => {\n const importer = path.resolve(args.importer);\n Effect.runSync(\n Ref.update(\n externalImports,\n HashMap.modifyAt(importer, (imports) =>\n Option.some(\n Array.append(\n Option.getOrElse(imports, () => []),\n { path: resolved, original: args.path },\n ),\n ),\n ),\n ),\n );\n return { path: resolved, external: true };\n };\n build.onResolve({ filter: /.*/ }, (args) => {\n if (args.kind === \"entry-point\") return undefined;\n if (isBuiltin(args.path)) return { path: args.path, external: true };\n if (Array.some(skipPatterns, (pattern) => pattern.test(args.path)))\n return undefined;\n if (/[\\\\/]node_modules[\\\\/]/.test(args.path)) {\n return external(\n args,\n pathToFileURL(path.resolve(args.resolveDir, args.path)).href,\n );\n }\n if (args.path.startsWith(\".\") || path.isAbsolute(args.path))\n return undefined;\n\n const resolved = resolveModule(args.path, args.importer);\n if (Option.isNone(resolved)) {\n return {\n errors: [\n { text: `Could not resolve \"${args.path}\" from ${args.importer}` },\n ],\n };\n }\n return Effect.runPromise(\n fs\n .realPath(resolved.value)\n .pipe(Effect.orElseSucceed(() => resolved.value)),\n ).then((real) => {\n if (!/[\\\\/]node_modules[\\\\/]/.test(real)) return { path: real };\n if (args.kind === \"require-call\" || args.kind === \"require-resolve\") {\n return external(\n args,\n createRequire(args.importer).resolve(args.path),\n );\n }\n return external(\n args,\n Option.match(\n resolveExternalEsm(args.path, args.importer, conditions),\n {\n onNone: () => args.path,\n onSome: (resolvedPath) => pathToFileURL(resolvedPath).href,\n },\n ),\n );\n });\n });\n },\n});\n\nconst compileBatch = Effect.fn(\"Bundler.compileBatch\")(function* (\n entryPoints: ReadonlyArray<string>,\n) {\n const path = yield* Path.Path;\n const fs = yield* FileSystem.FileSystem;\n const nodeOptions = yield* Config.String(\"NODE_OPTIONS\").pipe(\n Config.withDefault(\"\"),\n );\n if (/--conditions|-C|--(?:no-)?addons/.test(nodeOptions))\n return yield* new BatchIncompatible({\n reason: \"RuntimeConditions\",\n message:\n \"NODE_OPTIONS changes Node export conditions; individual builds preserve native resolution.\",\n });\n const runtimeOptions = yield* Effect.try({\n try: () =>\n parseArgs({\n args: process.execArgv,\n options: {\n conditions: { type: \"string\", short: \"C\", multiple: true },\n \"no-addons\": { type: \"boolean\" },\n },\n strict: false,\n allowPositionals: true,\n }).values,\n catch: (cause) => new BundlerError({ cause }),\n });\n const conditions = [\n \"node\",\n \"import\",\n ...(process.features.require_module ? [\"module-sync\"] : []),\n ...(runtimeOptions[\"no-addons\"] ? [] : [\"node-addons\"]),\n ...(runtimeOptions.conditions ?? []).filter(\n (condition) => typeof condition === \"string\",\n ),\n ];\n const entries = Array.dedupe(entryPoints.map((entry) => path.resolve(entry)));\n const first = entries[0];\n if (\n first === undefined ||\n entries.some(\n (entry) => !JS_EXT_RE.test(entry) || /[\\\\/]node_modules[\\\\/]/.test(entry),\n )\n ) {\n return yield* new BatchIncompatible({\n reason: \"UnsupportedEntries\",\n message:\n \"Shared builds require JavaScript or TypeScript entries outside node_modules.\",\n });\n }\n const configs = yield* Effect.try({\n try: () => entries.map((entry) => loadTsConfig(path.dirname(entry))),\n catch: (cause) => new BundlerError({ cause }),\n });\n const config = configs[0];\n if (configs.some((other) => other?.path !== config?.path))\n return yield* new BatchIncompatible({\n reason: \"MixedTsconfigs\",\n message: `Entries use different tsconfigs: ${Array.dedupe(configs.map((item) => item?.path ?? \"(no tsconfig)\")).join(\", \")}`,\n });\n\n const cwd = yield* fs.realPath(path.dirname(first));\n const directory = yield* fs\n .makeTempDirectoryScoped({ prefix: \"confect-batch-\" })\n .pipe(Effect.flatMap((temporary) => fs.realPath(temporary)));\n const artifacts = yield* Effect.forEach(entries, (entry, index) =>\n Effect.map(\n fs.realPath(entry),\n (source) =>\n [\n entry,\n { source, output: path.join(directory, `${index}.mjs`) },\n ] as const,\n ),\n );\n const externalImports = yield* Ref.make(\n HashMap.empty<string, ReadonlyArray<ExternalImport>>(),\n );\n const result = yield* Effect.tryPromise({\n try: () =>\n esbuild.build({\n entryPoints: entries.map((entry, index) => ({\n in: entry,\n out: `${index}`,\n })),\n absWorkingDir: cwd,\n outdir: directory,\n outExtension: { \".js\": \".mjs\" },\n chunkNames: \"chunk-[hash]\",\n format: \"esm\",\n platform: \"node\",\n sourcemap: \"inline\",\n bundle: true,\n splitting: true,\n metafile: true,\n write: false,\n logLevel: \"silent\",\n ...(config?.path\n ? { tsconfig: config.path }\n : { tsconfigRaw: config?.data ?? {} }),\n plugins: [\n batchResolutionPlugin(\n path,\n fs,\n tsconfigPathsToRegExp(config?.data.compilerOptions?.paths ?? {}),\n conditions,\n externalImports,\n ),\n injectFileScopePlugin(),\n ],\n }),\n catch: (cause) => new BundlerError({ cause }),\n });\n const inputPaths = HashSet.fromIterable(\n Object.keys(result.metafile.inputs).map((input) =>\n path.resolve(cwd, input),\n ),\n );\n const unattributedWarnings = result.warnings.filter(\n (warning) =>\n !warning.location ||\n !HashSet.has(inputPaths, path.resolve(cwd, warning.location.file)),\n );\n if (unattributedWarnings.length > 0)\n return yield* new BatchIncompatible({\n reason: \"UnattributedWarnings\",\n message: `Cannot attribute build warnings to entries: ${unattributedWarnings.map((warning) => warning.text).join(\"; \")}`,\n });\n yield* Effect.forEach(result.outputFiles, (output) =>\n fs.writeFile(output.path, output.contents),\n );\n const capturedExternalImports = yield* Ref.get(externalImports);\n const inputs = Object.fromEntries(\n Object.entries(result.metafile.inputs).map(([input, metadata]) => {\n const originals = Option.getOrElse(\n HashMap.get(capturedExternalImports, path.resolve(cwd, input)),\n () => [],\n );\n return [\n input,\n {\n ...metadata,\n imports: metadata.imports.flatMap((imported) => {\n const matching = imported.external\n ? originals.filter((original) => original.path === imported.path)\n : [];\n return matching.length === 0\n ? [imported]\n : matching.map((original) =>\n Object.assign({}, imported, {\n original: original.original,\n }),\n );\n }),\n },\n ];\n }),\n );\n return {\n entries: HashMap.fromIterable(artifacts),\n metafile: absolutizeMetafile(path, { ...result.metafile, inputs }, cwd),\n warnings: result.warnings,\n cwd,\n } satisfies BatchCompilation;\n});\n\n/**\n * Lazily shares one compilation across ordinary bundle calls in this effect.\n * Different tsconfigs and failed compilations fall back to individual builds.\n * Runtime conditions supplied through NODE_OPTIONS also use individual builds.\n * Imports still run at each caller, and temporary chunks live until the effect\n * finishes. The disposable evaluator, not this scope, owns Node's import\n * cache.\n */\nexport const withBatch = <A, E, R>(\n entryPoints: ReadonlyArray<string>,\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<A, E, R> =>\n Effect.scopedWith((scope) =>\n Effect.gen(function* () {\n const current = yield* Effect.serviceOption(Batch);\n if (\n Option.isSome(current) &&\n entryPoints.every((entry) => current.value.entryPoints.includes(entry))\n )\n return yield* effect;\n const compilation = yield* Effect.cached(\n compileBatch(entryPoints).pipe(\n Effect.provideService(Scope.Scope, scope),\n Effect.asSome,\n Effect.catchTag(\"BatchIncompatible\", (error) =>\n Effect.logDebug(\n \"Shared build skipped; falling back to individual builds.\",\n {\n entryPoints,\n reason: error.reason,\n detail: error.message,\n },\n ).pipe(Effect.as(Option.none<BatchCompilation>())),\n ),\n Effect.catch((error) =>\n Effect.logDebug(\n \"Shared build failed; falling back to individual builds.\",\n {\n entryPoints,\n reason: \"CompileFailure\",\n },\n Cause.fail(error),\n ).pipe(Effect.as(Option.none<BatchCompilation>())),\n ),\n ),\n );\n return yield* Effect.provideService(effect, Batch, {\n entryPoints,\n compilation,\n });\n }),\n );\n\ninterface MetafileTraversal {\n readonly pending: Chunk.Chunk<string>;\n readonly visited: HashSet.HashSet<string>;\n}\n\nconst reachableMetafileEntries = <\n Metadata extends {\n readonly imports: ReadonlyArray<{\n readonly path: string;\n readonly external?: boolean;\n }>;\n },\n>(\n entries: Readonly<Record<string, Metadata>>,\n root: string,\n resolveImport: (path: string) => string,\n): Record<string, Metadata> =>\n Object.fromEntries(\n pipe(\n Iterable.unfold<\n MetafileTraversal,\n Option.Option<readonly [string, Metadata]>\n >(\n { pending: Chunk.of(root), visited: HashSet.empty() },\n ({ pending, visited }) => {\n if (!Chunk.isNonEmpty(pending)) return Option.none();\n const key = Chunk.headNonEmpty(pending);\n const remaining = Chunk.tailNonEmpty(pending);\n const metadata = entries[key];\n if (HashSet.has(visited, key) || metadata === undefined)\n return Option.some([\n Option.none(),\n { pending: remaining, visited },\n ]);\n return Option.some([\n Option.some([key, metadata] as const),\n {\n pending: Array.reduce(\n metadata.imports,\n remaining,\n (queue, imported) =>\n imported.external\n ? queue\n : Chunk.append(queue, resolveImport(imported.path)),\n ),\n visited: HashSet.add(visited, key),\n },\n ]);\n },\n ),\n Iterable.getSomes,\n ),\n );\n\nconst entryMetafile = (\n path: Path.Path,\n compilation: BatchCompilation,\n source: string,\n output: string,\n): esbuild.Metafile => ({\n inputs: reachableMetafileEntries(\n compilation.metafile.inputs,\n source,\n identity,\n ),\n outputs: reachableMetafileEntries(\n compilation.metafile.outputs,\n output,\n (key) => path.resolve(compilation.cwd, key),\n ),\n});\n\n/**\n * Bundle a TypeScript entry point with esbuild via {@link bundleRequire} and\n * import the result. `bundle-require` writes a temp `.mjs` next to the source,\n * `import()`s it, and deletes it—so third-party `node_modules` externals\n * resolve through the user's normal `node_modules` walk, while first-party\n * workspace deps are bundled by {@link bundleWorkspacePlugin} and tsconfig\n * `paths` aliases stay inside the bundle.\n *\n * `cwd` is set to the entry's directory so `bundle-require`'s `tsconfig.json`\n * discovery (which walks upward from `cwd`) lands on the project's tsconfig\n * regardless of where `confect codegen` was invoked from, and so esbuild\n * resolves relative imports against the entry's location.\n *\n * The returned pair carries both the imported module and the esbuild metafile\n * so callers can inspect the import graph (see {@link directlyImports}); the\n * metafile is captured via a small `onEnd` plugin because `bundle-require`\n * itself only exposes a flat `dependencies: string[]`.\n *\n * `options.plugins` are registered ahead of every other plugin—including\n * `bundle-require`'s own `externalPlugin`—so a caller-supplied plugin can claim\n * resolutions (e.g. `convex.config` imports) before the workspace and\n * externalization heuristics see them.\n */\nexport const bundle = Effect.fn(\"Bundler.bundle\")(function* (\n entryPoint: string,\n options?: { readonly plugins?: ReadonlyArray<esbuild.Plugin> },\n): Effect.fn.Return<Bundled, BundlerError, Path.Path | FileSystem.FileSystem> {\n const path = yield* Path.Path;\n const fs = yield* FileSystem.FileSystem;\n\n const batch = yield* Effect.serviceOption(Batch);\n if (\n Option.isSome(batch) &&\n !options?.plugins?.length &&\n batch.value.entryPoints.some(\n (entry) => path.resolve(entry) === path.resolve(entryPoint),\n )\n ) {\n const compilation = yield* batch.value.compilation;\n if (Option.isSome(compilation)) {\n const entry = HashMap.get(\n compilation.value.entries,\n path.resolve(entryPoint),\n );\n if (Option.isSome(entry)) {\n const metafile = entryMetafile(\n path,\n compilation.value,\n entry.value.source,\n entry.value.output,\n );\n const module = yield* Effect.tryPromise({\n try: () =>\n dynamicImport(pathToFileURL(entry.value.output).href, {\n format: \"esm\",\n }),\n catch: (cause) => new BundlerError({ cause }),\n }).pipe(\n Effect.ensuring(\n logCoalescedBuildWarnings(\n compilation.value.warnings.filter(\n (warning) =>\n warning.location &&\n metafile.inputs[\n path.resolve(compilation.value.cwd, warning.location.file)\n ],\n ),\n ),\n ),\n );\n return { module, metafile };\n }\n }\n }\n\n const buildResultRef = yield* Ref.make<CapturedBuildResult>({\n metafile: undefined,\n warnings: [],\n });\n\n const cwd = path.dirname(entryPoint);\n const skipPatterns = yield* Effect.try({\n try: () =>\n tsconfigPathsToRegExp(\n loadTsConfig(cwd)?.data.compilerOptions?.paths ?? {},\n ),\n catch: (cause) => new BundlerError({ cause }),\n });\n const result = yield* Effect.tryPromise({\n try: () =>\n bundleRequire({\n filepath: entryPoint,\n cwd,\n format: \"esm\",\n esbuildOptions: {\n plugins: [\n ...(options?.plugins ?? []),\n bundleWorkspacePlugin(path, fs, skipPatterns),\n captureBuildResultPlugin(buildResultRef),\n ],\n logLevel: \"silent\",\n },\n }),\n catch: (cause) => new BundlerError({ cause }),\n }).pipe(\n Effect.ensuring(\n Effect.andThen(Ref.get(buildResultRef), (captured) =>\n logCoalescedBuildWarnings(captured.warnings),\n ),\n ),\n );\n\n const { metafile } = yield* Ref.get(buildResultRef);\n if (!metafile) {\n return yield* Effect.die(new Error(\"esbuild metafile missing\"));\n }\n\n return {\n module: result.mod,\n metafile: absolutizeMetafile(path, metafile, cwd),\n };\n});\n\nconst findMetafileInputKey = Effect.fnUntraced(function* (\n metafile: esbuild.Metafile,\n absolutePath: string,\n) {\n const path = yield* Path.Path;\n const resolved = path.resolve(absolutePath);\n if (metafile.inputs[resolved] !== undefined) return Option.some(resolved);\n const fs = yield* FileSystem.FileSystem;\n const real = yield* fs\n .realPath(resolved)\n .pipe(Effect.orElseSucceed(() => resolved));\n return Array.findFirst(\n Object.keys(metafile.inputs),\n (key) => path.resolve(key) === real,\n );\n});\n\n/**\n * Returns `true` when the module bundled from `sourceAbsolutePath` declares a\n * direct import of `targetAbsolutePath` (according to the bundle's esbuild\n * metafile). Returns `false` if either path is missing from the metafile.\n */\nexport const directlyImports = Effect.fnUntraced(function* (\n bundled: Bundled,\n sourceAbsolutePath: string,\n targetAbsolutePath: string,\n) {\n const path = yield* Path.Path;\n const sourceKey = yield* findMetafileInputKey(\n bundled.metafile,\n sourceAbsolutePath,\n );\n const targetKey = yield* findMetafileInputKey(\n bundled.metafile,\n targetAbsolutePath,\n );\n\n return pipe(\n Option.all([sourceKey, targetKey]),\n Option.flatMap(([sourceKey_, targetKey_]) =>\n Option.fromNullishOr(bundled.metafile.inputs[sourceKey_]).pipe(\n Option.map((sourceInput) => {\n const targetResolved = path.resolve(targetKey_);\n return sourceInput.imports.some(\n (importedFile) =>\n path.resolve(importedFile.path) === targetResolved,\n );\n }),\n ),\n ),\n Option.getOrElse(() => false),\n );\n});\n\n/**\n * Returns the absolute paths of every module in the bundle that declares a\n * direct import of `packageName` (the package itself or one of its subpaths)\n * and satisfies `where`. Use `where` to restrict the search to the modules you\n * care about—the bundle's inputs include every transitive dependency.\n *\n * Matching is on the specifier as written rather than the resolved path,\n * because {@link bundleWorkspacePlugin} bundles first-party workspace\n * dependencies (so `@confect/server` resolves to a path inside the monorepo)\n * while a published install externalizes them (so it stays a bare specifier).\n * esbuild erases `import type` before it produces the metafile, so type-only\n * imports are not reported.\n */\nexport const importersOfPackage = (\n bundled: Bundled,\n packageName: string,\n where: (absolutePath: string) => boolean,\n): ReadonlyArray<string> => {\n const subpathPrefix = `${packageName}/`;\n\n return Object.entries(bundled.metafile.inputs)\n .filter(\n ([absolutePath, input]) =>\n where(absolutePath) &&\n input.imports.some(\n (imported) =>\n imported.original === packageName ||\n imported.original?.startsWith(subpathPrefix) === true,\n ),\n )\n .map(([absolutePath]) => absolutePath);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,MAAM,sBACJ,MACA,UACA,QACqB;CACrB,MAAM,cAAc,MAAc,KAAK,QAAQ,KAAK,CAAC;CAyBrD,OAAO;EAAE,QAxBM,OAAO,WAAW,SAAS,SAAS,OAAO,QAAQ,CAChE,WAAW,GAAG,GACd;GACE,GAAG;GACH,SAAS,MAAM,IAAI,MAAM,UAAU,OAAO;IACxC,GAAG;IACH,MAAM,WAAW,EAAE,IAAI;IACvB,UAAU,EAAE,YAAY,EAAE;GAC5B,EAAE;EACJ,CACF,CAcc;EAAG,SAbD,OAAO,WAAW,SAAS,UAAU,OAAO,QAAQ,CAClE,WAAW,GAAG,GACd;GACE,GAAG;GACH,GAAI,MAAM,aAAa,EAAE,YAAY,WAAW,MAAM,UAAU,EAAE,IAAI,CAAC;GACvE,QAAQ,OAAO,QAAQ,MAAM,QAAQ,UAAU;GAC/C,SAAS,MAAM,IAAI,MAAM,UAAU,aACjC,SAAS,WACL,WACA;IAAE,GAAG;IAAU,MAAM,WAAW,SAAS,IAAI;GAAE,CACrD;EACF,CACF,CACuB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Y;CAC1C,IAAI,SAAS,OAAO,cAAc,KAAA,GAAW,OAAO,OAAO,KAAK,QAAQ;CAExE,MAAM,OAAO,QAAO,OADF,WAAW,WAAA,CAE1B,SAAS,QAAQ,CAAC,CAClB,KAAK,OAAO,oBAAoB,QAAQ,CAAC;CAC5C,OAAO,MAAM,UACX,OAAO,KAAK,SAAS,MAAM,IAC1B,QAAQ,KAAK,QAAQ,GAAG,MAAM,IACjC;AACF,CAAC;;;;;;AAOD,MAAa,kBAAkB,OAAO,WAAW,WAC/C,SACA,oBACA,oBACA;CACA,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,YAAY,OAAO,qBACvB,QAAQ,UACR,kBACF;CACA,MAAM,YAAY,OAAO,qBACvB,QAAQ,UACR,kBACF;CAEA,OAAO,KACL,OAAO,IAAI,CAAC,WAAW,SAAS,CAAC,GACjC,OAAO,SAAS,CAAC,YAAY,gBAC3B,OAAO,cAAc,QAAQ,SAAS,OAAO,WAAW,CAAC,CAAC,KACxD,OAAO,KAAK,gBAAgB;EAC1B,MAAM,iBAAiB,KAAK,QAAQ,UAAU;EAC9C,OAAO,YAAY,QAAQ,MACxB,iBACC,KAAK,QAAQ,aAAa,IAAI,MAAM,cACxC;CACF,CAAC,CACH,CACF,GACA,OAAO,gBAAgB,KAAK,CAC9B;AACF,CAAC;;;;;;;;;;;;;;AAeD,MAAa,sBACX,SACA,aACA,UAC0B;CAC1B,MAAM,gBAAgB,GAAG,YAAY;CAErC,OAAO,OAAO,QAAQ,QAAQ,SAAS,MAAM,CAAC,CAC3C,QACE,CAAC,cAAc,WACd,MAAM,YAAY,KAClB,MAAM,QAAQ,MACX,aACC,SAAS,aAAa,eACtB,SAAS,UAAU,WAAW,aAAa,MAAM,IACrD,CACJ,CAAC,CACA,KAAK,CAAC,kBAAkB,YAAY;AACzC"}
1
+ {"version":3,"file":"Bundler.mjs","names":["TypeScriptConfig.discover","PackageSelfReference.discover","TypeScriptConfig.buildOptions","TypeScriptConfig.aliasPatterns"],"sources":["../src/Bundler.ts"],"sourcesContent":["import { createRequire, isBuiltin } from \"node:module\";\nimport { pathToFileURL } from \"node:url\";\nimport { parseArgs } from \"node:util\";\nimport * as BundleRequire from \"bundle-require\";\nimport { resolveModulePath } from \"exsolve\";\nimport { constUndefined, identity, pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Chunk from \"effect/Chunk\";\nimport * as Cause from \"effect/Cause\";\nimport * as Config from \"effect/Config\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as HashMap from \"effect/HashMap\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as Iterable from \"effect/Iterable\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Ref from \"effect/Ref\";\nimport * as Record from \"effect/Record\";\nimport * as Scope from \"effect/Scope\";\nimport * as Schema from \"effect/Schema\";\nimport * as String from \"effect/String\";\nimport * as esbuild from \"esbuild\";\nimport { BundlerError } from \"./BuildError.js\";\nimport { logCoalescedBuildWarnings } from \"./log.js\";\nimport * as PackageSelfReference from \"./PackageSelfReference.js\";\nimport * as TypeScriptConfig from \"./TypeScriptConfig.js\";\n\nexport interface Bundled {\n readonly module: any;\n readonly metafile: esbuild.Metafile;\n}\n\n/**\n * `bundle-require` sets `absWorkingDir: cwd` on the underlying esbuild build,\n * so the metafile's input keys (and each input's `imports[].path`) are stored\n * relative to that cwd. Callers reach for the metafile with absolute paths\n * (e.g. {@link directlyImports}), so we normalize every key/import path to\n * absolute up front. That way the lookup logic stays oblivious to whatever cwd\n * was used during bundling.\n *\n * `original` (the specifier as written, before resolution) is filled in from\n * `path` when esbuild omits it—esbuild only sets it when it differs from the\n * resolved path, which is exactly the externalized-bare-specifier case that\n * absolutizing `path` would otherwise mangle into `<cwd>/@confect/server`.\n * {@link importersOfPackage} relies on `original` always being the raw\n * specifier.\n */\nconst absolutizeMetafile = (\n path: Path.Path,\n metafile: esbuild.Metafile,\n cwd: string,\n inputPaths: ReadonlyMap<string, string>,\n): esbuild.Metafile => {\n const absolutize = (p: string) => path.resolve(cwd, p);\n const inputPath = (p: string) =>\n inputPaths.get(absolutize(p)) ?? absolutize(p);\n const inputs = Record.mapEntries(metafile.inputs, (value, key) => [\n inputPath(key),\n {\n ...value,\n imports: Array.map(value.imports, (i) => ({\n ...i,\n path: inputPath(i.path),\n original: i.original ?? i.path,\n })),\n },\n ]);\n const outputs = Record.mapEntries(metafile.outputs, (value, key) => [\n absolutize(key),\n {\n ...value,\n ...(value.entryPoint !== undefined && value.entryPoint !== \"\"\n ? { entryPoint: inputPath(value.entryPoint) }\n : {}),\n inputs: Record.mapKeys(value.inputs, inputPath),\n imports: Array.map(value.imports, (imported) =>\n imported.external === true\n ? imported\n : { ...imported, path: absolutize(imported.path) },\n ),\n },\n ]);\n return { inputs, outputs };\n};\n\nconst canonicalInputPaths = Effect.fnUntraced(function* (\n path: Path.Path,\n fs: FileSystem.FileSystem,\n metafile: esbuild.Metafile,\n cwd: string,\n) {\n const inputPaths = yield* Effect.forEach(\n Record.keys(metafile.inputs),\n (input) => {\n const absolute = path.resolve(cwd, input);\n return fs.realPath(absolute).pipe(\n Effect.orElseSucceed(() => absolute),\n Effect.map((real) => [absolute, real] as const),\n );\n },\n );\n return new Map(inputPaths);\n});\n\nconst resolveEsm = Option.liftThrowable((specifier: string, importer: string) =>\n resolveModulePath(specifier, {\n from: importer,\n conditions: [\"node\", \"import\"],\n }),\n);\n\nconst resolveCjs = Option.liftThrowable((specifier: string, importer: string) =>\n createRequire(importer).resolve(specifier),\n);\n\nconst resolveExternalEsm = Option.liftThrowable(\n (specifier: string, importer: string, conditions: string[]) =>\n resolveModulePath(specifier, { from: importer, conditions }),\n);\n\nexport const resolveModule = (\n specifier: string,\n importer: string,\n): Option.Option<string> =>\n Option.orElse(resolveEsm(specifier, importer), () =>\n resolveCjs(specifier, importer),\n );\n\n/**\n * The names `file` exports, read by esbuild without evaluating the module, so a\n * test kit that only runs under Vite (`import.meta.glob`) can be checked. None\n * when only running the module would list them: a CommonJS module assigns its\n * exports at run time, and bare imports stay external, so `export *` from\n * another package hides its names.\n */\nexport const exportNames = (\n file: string,\n): Effect.Effect<Option.Option<ReadonlyArray<string>>, BundlerError> =>\n Effect.tryPromise({\n try: () =>\n esbuild.build({\n entryPoints: [file],\n bundle: true,\n packages: \"external\",\n format: \"esm\",\n platform: \"node\",\n write: false,\n metafile: true,\n logLevel: \"silent\",\n outdir: \"out\",\n }),\n catch: (cause) => BundlerError.make({ cause }),\n }).pipe(\n Effect.map(({ metafile, outputFiles }) =>\n Array.some(\n Record.values(metafile.inputs),\n ({ format }) => format === \"cjs\",\n ) || Array.some(outputFiles, ({ text }) => /^export \\* from /m.test(text))\n ? Option.none()\n : Option.some(\n Array.flatMap(\n Record.values(metafile.outputs),\n ({ exports }) => exports,\n ),\n ),\n ),\n );\n\n/**\n * Bundles first-party workspace dependencies that `bundle-require` would\n * otherwise externalize and hand to Node's native ESM resolver. Resolves each\n * bare specifier and, following symlinks, bundles it when its real path lives\n * outside `node_modules`—mirroring Vite's \"linked dependencies are not\n * externalized\" heuristic. Registered ahead of `externalPlugin`, so deferring\n * (returning `undefined`) leaves third-party externalization untouched.\n * `skipPatterns` leave tsconfig `paths` aliases and package self-references to\n * esbuild's native resolution.\n *\n * @internal\n */\nexport const bundleWorkspacePlugin = (\n path: Path.Path,\n fs: FileSystem.FileSystem,\n skipPatterns: ReadonlyArray<string | RegExp>,\n): esbuild.Plugin => ({\n name: \"confect:bundle-workspace\",\n setup(build) {\n const patterns = [...skipPatterns];\n build.onResolve({ filter: /^[^./]/ }, (args) => {\n if (args.namespace !== \"file\" && args.namespace !== \"\") return undefined;\n if (isBuiltin(args.path) || path.isAbsolute(args.path)) return undefined;\n if (BundleRequire.match(args.path, patterns)) {\n return undefined;\n }\n\n const importer =\n args.importer !== \"\" ? args.importer : path.join(args.resolveDir, \"_\");\n\n return Option.match(resolveModule(args.path, importer), {\n onNone: () => ({\n path: args.path,\n external: true,\n warnings: [\n {\n text: `Confect could not resolve workspace dependency \"${args.path}\" (imported from ${importer}) to bundle it; leaving it external.`,\n },\n ],\n }),\n onSome: (resolved) =>\n Effect.runPromise(\n fs.realPath(resolved).pipe(Effect.orElseSucceed(() => resolved)),\n ).then((real) =>\n pipe(real, String.split(path.sep), Array.contains(\"node_modules\"))\n ? undefined\n : { path: real },\n ),\n });\n });\n },\n});\n\ninterface CapturedBuildResult {\n readonly metafile: esbuild.Metafile | undefined;\n readonly warnings: ReadonlyArray<esbuild.Message>;\n}\n\nconst captureBuildResultPlugin = (\n ref: Ref.Ref<CapturedBuildResult>,\n): esbuild.Plugin => ({\n name: \"confect:capture-build-result\",\n setup(build) {\n build.onEnd((result) => {\n Effect.runSync(\n Ref.set(ref, {\n metafile: result.metafile,\n warnings: result.warnings,\n }),\n );\n });\n },\n});\n\ninterface BatchCompilation {\n readonly entries: HashMap.HashMap<\n string,\n { readonly source: string; readonly output: string }\n >;\n readonly metafile: esbuild.Metafile;\n readonly inputPaths: ReadonlyMap<string, string>;\n readonly warnings: ReadonlyArray<esbuild.Message>;\n readonly cwd: string;\n}\n\nclass BatchIncompatible extends Schema.TaggedError<\n BatchIncompatible,\n { readonly brand: unique symbol }\n>()(\"BatchIncompatible\", {\n reason: Schema.Literals([\n \"RuntimeConditions\",\n \"UnsupportedEntries\",\n \"MixedTsconfigs\",\n \"UnattributedWarnings\",\n ]),\n message: Schema.String,\n}) {}\n\nclass Batch extends Context.Service<\n Batch,\n {\n readonly entryPoints: ReadonlyArray<string>;\n readonly compilation: Effect.Effect<\n Option.Option<BatchCompilation>,\n never,\n Path.Path | FileSystem.FileSystem\n >;\n }\n>()(\"@confect/cli/Bundler/Batch\") {}\n\ninterface ExternalImport {\n readonly path: string;\n readonly original: string;\n}\n\nconst batchResolutionPlugin = (\n path: Path.Path,\n fs: FileSystem.FileSystem,\n skipPatterns: ReadonlyArray<string | RegExp>,\n conditions: string[],\n externalImports: Ref.Ref<\n HashMap.HashMap<string, ReadonlyArray<ExternalImport>>\n >,\n): esbuild.Plugin => ({\n name: \"confect:batch-resolution\",\n setup(build) {\n const patterns = [...skipPatterns];\n const external = (args: esbuild.OnResolveArgs, resolved: string) => {\n const importer = path.resolve(args.importer);\n Effect.runSync(\n Ref.update(\n externalImports,\n HashMap.modifyAt(importer, (imports) =>\n Option.some(\n Array.append(\n Option.getOrElse(imports, () => []),\n { path: resolved, original: args.path },\n ),\n ),\n ),\n ),\n );\n return { path: resolved, external: true };\n };\n build.onResolve({ filter: /.*/ }, (args) => {\n if (args.kind === \"entry-point\") return undefined;\n if (isBuiltin(args.path)) return { path: args.path, external: true };\n if (BundleRequire.match(args.path, patterns)) return undefined;\n if (/[\\\\/]node_modules[\\\\/]/.test(args.path)) {\n return external(\n args,\n pathToFileURL(path.resolve(args.resolveDir, args.path)).href,\n );\n }\n if (String.startsWith(\".\")(args.path) || path.isAbsolute(args.path))\n return undefined;\n\n const resolved = resolveModule(args.path, args.importer);\n if (Option.isNone(resolved)) {\n return {\n errors: [\n { text: `Could not resolve \"${args.path}\" from ${args.importer}` },\n ],\n };\n }\n return Effect.runPromise(\n fs\n .realPath(resolved.value)\n .pipe(Effect.orElseSucceed(() => resolved.value)),\n ).then((real) => {\n if (!/[\\\\/]node_modules[\\\\/]/.test(real)) return { path: real };\n if (args.kind === \"require-call\" || args.kind === \"require-resolve\") {\n return external(\n args,\n createRequire(args.importer).resolve(args.path),\n );\n }\n return external(\n args,\n Option.match(\n resolveExternalEsm(args.path, args.importer, conditions),\n {\n onNone: () => args.path,\n onSome: (resolvedPath) => pathToFileURL(resolvedPath).href,\n },\n ),\n );\n });\n });\n },\n});\n\nconst compileBatch = Effect.fn(\"Bundler.compileBatch\")(function* (\n entryPoints: ReadonlyArray<string>,\n) {\n const path = yield* Path.Path;\n const fs = yield* FileSystem.FileSystem;\n const nodeOptions = yield* Config.String(\"NODE_OPTIONS\").pipe(\n Config.withDefault(\"\"),\n );\n if (/--conditions|-C|--(?:no-)?addons/.test(nodeOptions))\n return yield* BatchIncompatible.make({\n reason: \"RuntimeConditions\",\n message:\n \"NODE_OPTIONS changes Node export conditions; individual builds preserve native resolution.\",\n });\n const runtimeOptions = yield* Effect.try({\n try: () =>\n parseArgs({\n args: process.execArgv,\n options: {\n conditions: { type: \"string\", short: \"C\", multiple: true },\n \"no-addons\": { type: \"boolean\" },\n },\n strict: false,\n allowPositionals: true,\n }).values,\n catch: (cause) => BundlerError.make({ cause }),\n });\n const conditions = [\n \"node\",\n \"import\",\n ...(process.features.require_module ? [\"module-sync\"] : []),\n ...(runtimeOptions[\"no-addons\"] === true ||\n (typeof runtimeOptions[\"no-addons\"] === \"string\" &&\n runtimeOptions[\"no-addons\"] !== \"\")\n ? []\n : [\"node-addons\"]),\n ...Array.filter(\n runtimeOptions.conditions ?? [],\n (condition) => typeof condition === \"string\",\n ),\n ];\n const entries = Array.dedupe(\n Array.map(entryPoints, (entry) => path.resolve(entry)),\n );\n if (\n !Array.isReadonlyArrayNonEmpty(entries) ||\n !Array.every(\n entries,\n (entry) =>\n BundleRequire.JS_EXT_RE.test(entry) &&\n !/[\\\\/]node_modules[\\\\/]/.test(entry),\n )\n ) {\n return yield* BatchIncompatible.make({\n reason: \"UnsupportedEntries\",\n message:\n \"Shared builds require JavaScript or TypeScript entries outside node_modules.\",\n });\n }\n const first = Array.headNonEmpty(entries);\n const configs = yield* Effect.forEach(\n Array.dedupe(Array.map(entries, path.dirname)),\n TypeScriptConfig.discover,\n );\n const config = Array.headNonEmpty(configs);\n const configPath = (\n selected: Option.Option<TypeScriptConfig.TypeScriptConfig>,\n ) => Option.getOrUndefined(Option.map(selected, (value) => value.path));\n if (\n !Array.every(configs, (other) => configPath(other) === configPath(config))\n )\n return yield* BatchIncompatible.make({\n reason: \"MixedTsconfigs\",\n message: `Entries use different tsconfigs: ${Array.join(Array.dedupe(Array.map(configs, (item) => configPath(item) ?? \"(no tsconfig)\")), \", \")}`,\n });\n\n const cwd = yield* fs.realPath(path.dirname(first));\n const directory = yield* fs\n .makeTempDirectoryScoped({ prefix: \"confect-batch-\" })\n .pipe(Effect.flatMap((temporary) => fs.realPath(temporary)));\n const artifacts = yield* Effect.forEach(entries, (entry, index) =>\n Effect.map(\n fs.realPath(entry),\n (source) =>\n [\n entry,\n { source, output: path.join(directory, `${index}.mjs`) },\n ] as const,\n ),\n );\n const externalImports = yield* Ref.make(\n HashMap.empty<string, ReadonlyArray<ExternalImport>>(),\n );\n const discoveredSelfReferences = yield* Effect.forEach(\n Array.dedupe(Array.map(entries, path.dirname)),\n PackageSelfReference.discover,\n );\n const selfReferences = Array.getSomes(discoveredSelfReferences);\n const result = yield* Effect.tryPromise({\n try: () =>\n esbuild.build({\n entryPoints: Array.map(entries, (entry, index) => ({\n in: entry,\n out: `${index}`,\n })),\n absWorkingDir: cwd,\n outdir: directory,\n outExtension: { \".js\": \".mjs\" },\n chunkNames: \"chunk-[hash]\",\n format: \"esm\",\n platform: \"node\",\n sourcemap: \"inline\",\n bundle: true,\n splitting: true,\n metafile: true,\n write: false,\n logLevel: \"silent\",\n ...TypeScriptConfig.buildOptions(config),\n plugins: [\n batchResolutionPlugin(\n path,\n fs,\n [...TypeScriptConfig.aliasPatterns(config), ...selfReferences],\n conditions,\n externalImports,\n ),\n BundleRequire.injectFileScopePlugin(),\n ],\n }),\n catch: (cause) => BundlerError.make({ cause }),\n });\n const inputPaths = HashSet.fromIterable(\n Array.map(Record.keys(result.metafile.inputs), (input) =>\n path.resolve(cwd, input),\n ),\n );\n const unattributedWarnings = Array.filter(\n result.warnings,\n (warning) =>\n warning.location === null ||\n !HashSet.has(inputPaths, path.resolve(cwd, warning.location.file)),\n );\n if (unattributedWarnings.length > 0)\n return yield* BatchIncompatible.make({\n reason: \"UnattributedWarnings\",\n message: `Cannot attribute build warnings to entries: ${Array.join(\n Array.map(unattributedWarnings, (warning) => warning.text),\n \"; \",\n )}`,\n });\n yield* Effect.forEach(result.outputFiles, (output) =>\n fs.writeFile(output.path, output.contents),\n );\n const capturedExternalImports = yield* Ref.get(externalImports);\n const canonicalPaths = yield* canonicalInputPaths(\n path,\n fs,\n result.metafile,\n cwd,\n );\n const inputs = Record.fromEntries(\n Array.map(Record.toEntries(result.metafile.inputs), ([input, metadata]) => {\n const originals = Option.getOrElse(\n HashMap.get(capturedExternalImports, path.resolve(cwd, input)),\n () => [],\n );\n return [\n input,\n {\n ...metadata,\n imports: Array.flatMap(metadata.imports, (imported) => {\n const matching =\n imported.external === true\n ? Array.filter(\n originals,\n (original) => original.path === imported.path,\n )\n : [];\n return matching.length === 0\n ? [imported]\n : Array.map(matching, (original) =>\n Object.assign({}, imported, {\n original: original.original,\n }),\n );\n }),\n },\n ];\n }),\n );\n return {\n entries: HashMap.fromIterable(artifacts),\n metafile: absolutizeMetafile(\n path,\n { ...result.metafile, inputs },\n cwd,\n canonicalPaths,\n ),\n inputPaths: canonicalPaths,\n warnings: result.warnings,\n cwd,\n } satisfies BatchCompilation;\n});\n\n/**\n * Lazily shares one compilation across ordinary bundle calls in this effect.\n * Different tsconfigs and failed compilations fall back to individual builds.\n * Runtime conditions supplied through NODE_OPTIONS also use individual builds.\n * Imports still run at each caller, and temporary chunks live until the effect\n * finishes. The disposable evaluator, not this scope, owns Node's import\n * cache.\n */\nexport const withBatch = <A, E, R>(\n entryPoints: ReadonlyArray<string>,\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<A, E, R> =>\n Effect.scopedWith((scope) =>\n Effect.gen(function* () {\n const current = yield* Effect.serviceOption(Batch);\n if (\n Option.isSome(current) &&\n Array.every(entryPoints, (entry) =>\n current.value.entryPoints.includes(entry),\n )\n )\n return yield* effect;\n const compilation = yield* Effect.cached(\n compileBatch(entryPoints).pipe(\n Effect.provideService(Scope.Scope, scope),\n Effect.asSome,\n Effect.catchTag(\"BatchIncompatible\", (error) =>\n Effect.logDebug(\n \"Shared build skipped; falling back to individual builds.\",\n {\n entryPoints,\n reason: error.reason,\n detail: error.message,\n },\n ).pipe(Effect.as(Option.none<BatchCompilation>())),\n ),\n Effect.catch((error) =>\n Effect.logDebug(\n \"Shared build failed; falling back to individual builds.\",\n {\n entryPoints,\n reason: \"CompileFailure\",\n },\n Cause.fail(error),\n ).pipe(Effect.as(Option.none<BatchCompilation>())),\n ),\n ),\n );\n return yield* Effect.provideService(effect, Batch, {\n entryPoints,\n compilation,\n });\n }),\n );\n\ninterface MetafileTraversal {\n readonly pending: Chunk.Chunk<string>;\n readonly visited: HashSet.HashSet<string>;\n}\n\nconst reachableMetafileEntries = <\n Metadata extends {\n readonly imports: ReadonlyArray<{\n readonly path: string;\n readonly external?: boolean;\n }>;\n },\n>(\n entries: Readonly<Record<string, Metadata>>,\n root: string,\n resolveImport: (path: string) => string,\n): Record<string, Metadata> =>\n Record.fromEntries(\n pipe(\n Iterable.unfold<\n MetafileTraversal,\n Option.Option<readonly [string, Metadata]>\n >(\n { pending: Chunk.of(root), visited: HashSet.empty() },\n ({ pending, visited }) => {\n if (!Chunk.isNonEmpty(pending)) return Option.none();\n const key = Chunk.headNonEmpty(pending);\n const remaining = Chunk.tailNonEmpty(pending);\n const metadata = entries[key];\n if (HashSet.has(visited, key) || metadata === undefined)\n return Option.some([\n Option.none(),\n { pending: remaining, visited },\n ]);\n return Option.some([\n Option.some([key, metadata] as const),\n {\n pending: Array.reduce(\n metadata.imports,\n remaining,\n (queue, imported) =>\n imported.external === true\n ? queue\n : Chunk.append(queue, resolveImport(imported.path)),\n ),\n visited: HashSet.add(visited, key),\n },\n ]);\n },\n ),\n Iterable.getSomes,\n ),\n );\n\nconst entryMetafile = (\n path: Path.Path,\n compilation: BatchCompilation,\n source: string,\n output: string,\n): esbuild.Metafile => ({\n inputs: reachableMetafileEntries(\n compilation.metafile.inputs,\n source,\n identity,\n ),\n outputs: reachableMetafileEntries(\n compilation.metafile.outputs,\n output,\n (key) => path.resolve(compilation.cwd, key),\n ),\n});\n\n/**\n * Bundle a TypeScript entry point with esbuild via\n * {@link BundleRequire.bundleRequire} and import the result. `bundle-require`\n * writes a temp `.mjs` next to the source, `import()`s it, and deletes it—so\n * third-party `node_modules` externals resolve through the user's normal\n * `node_modules` walk, while first-party workspace deps are bundled by\n * {@link bundleWorkspacePlugin} and tsconfig `paths` aliases stay inside the\n * bundle.\n *\n * The returned pair carries both the imported module and the esbuild metafile\n * so callers can inspect the import graph (see {@link directlyImports}); the\n * metafile is captured via a small `onEnd` plugin because `bundle-require`\n * itself only exposes a flat `dependencies: string[]`.\n *\n * `options.plugins` are registered ahead of every other plugin—including\n * `bundle-require`'s own `externalPlugin`—so a caller-supplied plugin can claim\n * resolutions (e.g. `convex.config` imports) before the workspace and\n * externalization heuristics see them.\n */\nexport const bundle = Effect.fn(\"Bundler.bundle\")(\n (\n entryPoint: string,\n options?: { readonly plugins?: ReadonlyArray<esbuild.Plugin> },\n ) => bundleWith(entryPoint, BundleRequire.dynamicImport, options),\n);\n\nexport const check = Effect.fn(\"Bundler.check\")((entryPoint: string) =>\n bundleWith(entryPoint).pipe(Effect.asVoid),\n);\n\nconst bundleWith = Effect.fnUntraced(function* (\n entryPoint: string,\n load?: typeof BundleRequire.dynamicImport,\n options?: { readonly plugins?: ReadonlyArray<esbuild.Plugin> },\n): Effect.fn.Return<Bundled, BundlerError, Path.Path | FileSystem.FileSystem> {\n const path = yield* Path.Path;\n const fs = yield* FileSystem.FileSystem;\n\n const batch = yield* Effect.serviceOption(Batch);\n if (\n Option.isSome(batch) &&\n (options?.plugins?.length ?? 0) === 0 &&\n Array.some(\n batch.value.entryPoints,\n (entry) => path.resolve(entry) === path.resolve(entryPoint),\n )\n ) {\n const compilation = yield* batch.value.compilation;\n if (Option.isSome(compilation)) {\n const entry = HashMap.get(\n compilation.value.entries,\n path.resolve(entryPoint),\n );\n if (Option.isSome(entry)) {\n const metafile = entryMetafile(\n path,\n compilation.value,\n entry.value.source,\n entry.value.output,\n );\n const module = yield* Option.match(Option.fromUndefinedOr(load), {\n onNone: () => Effect.void,\n onSome: (loadModule) =>\n Effect.tryPromise({\n try: () =>\n loadModule(pathToFileURL(entry.value.output).href, {\n format: \"esm\",\n }),\n catch: (cause) => BundlerError.make({ cause }),\n }),\n }).pipe(\n Effect.ensuring(\n logCoalescedBuildWarnings(\n Array.filter(\n compilation.value.warnings,\n (warning) =>\n warning.location !== null &&\n metafile.inputs[\n compilation.value.inputPaths.get(\n path.resolve(\n compilation.value.cwd,\n warning.location.file,\n ),\n ) ??\n path.resolve(compilation.value.cwd, warning.location.file)\n ] !== undefined,\n ),\n ),\n ),\n );\n return { module, metafile };\n }\n }\n }\n\n const buildResultRef = yield* Ref.make<CapturedBuildResult>({\n metafile: undefined,\n warnings: [],\n });\n\n const cwd = path.dirname(entryPoint);\n const selfReference = yield* PackageSelfReference.discover(cwd);\n const selfReferences = Option.toArray(selfReference);\n const config = yield* TypeScriptConfig.discover(cwd);\n const skipPatterns = [\n ...TypeScriptConfig.aliasPatterns(config),\n ...selfReferences,\n ];\n const result = yield* Effect.tryPromise({\n try: () =>\n BundleRequire.bundleRequire({\n filepath: entryPoint,\n require: load ?? constUndefined,\n cwd,\n format: \"esm\",\n tsconfig: false,\n notExternal: skipPatterns,\n esbuildOptions: {\n plugins: [\n {\n name: \"confect:typescript-config\",\n setup(build) {\n delete build.initialOptions.tsconfigRaw;\n Object.assign(\n build.initialOptions,\n TypeScriptConfig.buildOptions(config),\n );\n },\n },\n ...(options?.plugins ?? []),\n bundleWorkspacePlugin(path, fs, skipPatterns),\n captureBuildResultPlugin(buildResultRef),\n ],\n logLevel: \"silent\",\n },\n }),\n catch: (cause) => BundlerError.make({ cause }),\n }).pipe(\n Effect.ensuring(\n Effect.andThen(Ref.get(buildResultRef), (captured) =>\n logCoalescedBuildWarnings(captured.warnings),\n ),\n ),\n );\n\n const { metafile } = yield* Ref.get(buildResultRef);\n if (metafile === undefined) {\n return yield* Effect.die(new Error(\"esbuild metafile missing\"));\n }\n\n const inputPaths = yield* canonicalInputPaths(path, fs, metafile, cwd);\n return {\n module: result.mod,\n metafile: absolutizeMetafile(path, metafile, cwd, inputPaths),\n };\n});\n\nconst findMetafileInputKey = Effect.fnUntraced(function* (\n metafile: esbuild.Metafile,\n absolutePath: string,\n) {\n const path = yield* Path.Path;\n const resolved = path.resolve(absolutePath);\n if (metafile.inputs[resolved] !== undefined) return Option.some(resolved);\n const fs = yield* FileSystem.FileSystem;\n const real = yield* fs\n .realPath(resolved)\n .pipe(Effect.orElseSucceed(() => resolved));\n return Array.findFirst(\n Record.keys(metafile.inputs),\n (key) => path.resolve(key) === real,\n );\n});\n\n/**\n * Returns `true` when the module bundled from `sourceAbsolutePath` declares a\n * direct import of `targetAbsolutePath` (according to the bundle's esbuild\n * metafile). Returns `false` if either path is missing from the metafile.\n */\nexport const directlyImports = Effect.fnUntraced(function* (\n bundled: Bundled,\n sourceAbsolutePath: string,\n targetAbsolutePath: string,\n) {\n const path = yield* Path.Path;\n const sourceKey = yield* findMetafileInputKey(\n bundled.metafile,\n sourceAbsolutePath,\n );\n const targetKey = yield* findMetafileInputKey(\n bundled.metafile,\n targetAbsolutePath,\n );\n\n return pipe(\n Option.all([sourceKey, targetKey]),\n Option.flatMap(([sourceKey_, targetKey_]) =>\n Option.fromNullishOr(bundled.metafile.inputs[sourceKey_]).pipe(\n Option.map((sourceInput) => {\n const targetResolved = path.resolve(targetKey_);\n return Array.some(\n sourceInput.imports,\n (importedFile) =>\n path.resolve(importedFile.path) === targetResolved,\n );\n }),\n ),\n ),\n Option.getOrElse(() => false),\n );\n});\n\n/**\n * Returns the absolute paths of every module in the bundle that declares a\n * direct import of `packageName` (the package itself or one of its subpaths)\n * and satisfies `where`. Use `where` to restrict the search to the modules you\n * care about—the bundle's inputs include every transitive dependency.\n *\n * Matching is on the specifier as written rather than the resolved path,\n * because {@link bundleWorkspacePlugin} bundles first-party workspace\n * dependencies (so `@confect/server` resolves to a path inside the monorepo)\n * while a published install externalizes them (so it stays a bare specifier).\n * esbuild erases `import type` before it produces the metafile, so type-only\n * imports are not reported.\n */\nexport const importersOfPackage = (\n bundled: Bundled,\n packageName: string,\n where: (absolutePath: string) => boolean,\n): ReadonlyArray<string> => {\n const subpathPrefix = `${packageName}/`;\n\n return Array.map(\n Array.filter(\n Record.toEntries(bundled.metafile.inputs),\n ([absolutePath, input]) =>\n where(absolutePath) &&\n Array.some(\n input.imports,\n (imported) =>\n imported.original === packageName ||\n (imported.original !== undefined &&\n String.startsWith(subpathPrefix)(imported.original)),\n ),\n ),\n ([absolutePath]) => absolutePath,\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAM,sBACJ,MACA,UACA,KACA,eACqB;CACrB,MAAM,cAAc,MAAc,KAAK,QAAQ,KAAK,CAAC;CACrD,MAAM,aAAa,MACjB,WAAW,IAAI,WAAW,CAAC,CAAC,KAAK,WAAW,CAAC;CA2B/C,OAAO;EAAE,QA1BM,OAAO,WAAW,SAAS,SAAS,OAAO,QAAQ,CAChE,UAAU,GAAG,GACb;GACE,GAAG;GACH,SAAS,MAAM,IAAI,MAAM,UAAU,OAAO;IACxC,GAAG;IACH,MAAM,UAAU,EAAE,IAAI;IACtB,UAAU,EAAE,YAAY,EAAE;GAC5B,EAAE;EACJ,CACF,CAgBc;EAAG,SAfD,OAAO,WAAW,SAAS,UAAU,OAAO,QAAQ,CAClE,WAAW,GAAG,GACd;GACE,GAAG;GACH,GAAI,MAAM,eAAe,KAAA,KAAa,MAAM,eAAe,KACvD,EAAE,YAAY,UAAU,MAAM,UAAU,EAAE,IAC1C,CAAC;GACL,QAAQ,OAAO,QAAQ,MAAM,QAAQ,SAAS;GAC9C,SAAS,MAAM,IAAI,MAAM,UAAU,aACjC,SAAS,aAAa,OAClB,WACA;IAAE,GAAG;IAAU,MAAM,WAAW,SAAS,IAAI;GAAE,CACrD;EACF,CACF,CACuB;CAAE;AAC3B;AAEA,MAAM,sBAAsB,OAAO,WAAW,WAC5C,MACA,IACA,UACA,KACA;CACA,MAAM,a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"}
@@ -1,6 +1,6 @@
1
1
  import * as Effect from "effect/Effect";
2
2
  import CodeBlockWriter_ from "code-block-writer";
3
- //#region src/CodeBlockWriter.ts
3
+ // src/CodeBlockWriter.ts
4
4
  const indentWriter = Effect.fnUntraced(function* (writer, effect) {
5
5
  const indentationLevel = writer.getIndentationLevel();
6
6
  writer.setIndentationLevel(indentationLevel + 1);
@@ -49,7 +49,6 @@ var CodeBlockWriter = class {
49
49
  return Effect.sync(() => this.writer.toString());
50
50
  }
51
51
  };
52
- //#endregion
53
52
  export { CodeBlockWriter };
54
53
 
55
54
  //# sourceMappingURL=CodeBlockWriter.mjs.map
@@ -1,15 +1,16 @@
1
1
  import { BuildError, isBuildError } from "./BuildError.mjs";
2
+ import { SnapshotError } from "./SnapshotError.mjs";
2
3
  import { red } from "./Ansi.mjs";
3
4
  import { formatPath, renderBuildError } from "./log.mjs";
4
- import { SnapshotError } from "./SnapshotError.mjs";
5
5
  import * as Effect from "effect/Effect";
6
6
  import * as Array from "effect/Array";
7
7
  import { pipe } from "effect/Function";
8
8
  import * as Match from "effect/Match";
9
- import "effect/Option";
9
+ import * as Option from "effect/Option";
10
10
  import * as Schema from "effect/Schema";
11
+ import * as String from "effect/String";
11
12
  import * as Console from "effect/Console";
12
- //#region src/CodegenError.ts
13
+ // src/CodegenError.ts
13
14
  var MissingImplFileError = class extends Schema.TaggedError()("MissingImplFileError", {
14
15
  specPath: Schema.String,
15
16
  expectedImplPath: Schema.String
@@ -36,6 +37,15 @@ var InvalidMiddlewareAttachmentError = class extends Schema.TaggedError()("Inval
36
37
  specPath: Schema.String,
37
38
  message: Schema.String
38
39
  }) {};
40
+ var InvalidContextReuseError = class extends Schema.TaggedError()("InvalidContextReuseError", {
41
+ specPath: Schema.String,
42
+ groupPath: Schema.String,
43
+ reason: Schema.Literals([
44
+ "InvalidOption",
45
+ "NodeRuntime",
46
+ "ReservedFunctionName"
47
+ ])
48
+ }) {};
39
49
  var ImplMissingSpecImportError = class extends Schema.TaggedError()("ImplMissingSpecImportError", {
40
50
  implPath: Schema.String,
41
51
  expectedSpecPath: Schema.String
@@ -113,6 +123,7 @@ const CodegenError = Schema.Union([
113
123
  RemoveBusyError,
114
124
  SpecImportsServerError,
115
125
  InvalidMiddlewareAttachmentError,
126
+ InvalidContextReuseError,
116
127
  ImplMissingSpecImportError,
117
128
  ImplMissingDefaultLayerError,
118
129
  ImplNotFinalizedError,
@@ -139,16 +150,16 @@ const isCodegenError = (error) => {
139
150
  };
140
151
  const cross = red("✘");
141
152
  const stemFromSpecPath = (specPath) => {
142
- const lastSep = Math.max(specPath.lastIndexOf("/"), specPath.lastIndexOf("\\"));
143
- const basename = lastSep < 0 ? specPath : specPath.slice(lastSep + 1);
144
- return basename.endsWith(".spec.ts") ? basename.slice(0, -8) : basename;
153
+ const lastSep = Math.max(Option.getOrElse(String.lastIndexOf("/")(specPath), () => -1), Option.getOrElse(String.lastIndexOf("\\")(specPath), () => -1));
154
+ const basename = lastSep < 0 ? specPath : String.slice(lastSep + 1)(specPath);
155
+ return String.endsWith(".spec.ts")(basename) ? String.slice(0, -8)(basename) : basename;
145
156
  };
146
- const singleLine = (...parts) => `${cross} ${parts.join("")}`;
157
+ const singleLine = (...parts) => `${cross} ${Array.join(parts, "")}`;
147
158
  const renderMissingImplFileError = (error) => singleLine("Spec ", formatPath(error.specPath), " has no sibling impl; create ", formatPath(error.expectedImplPath), " and default-export a GroupImpl layer from it.");
148
159
  const renderMissingSpecFileError = (error) => singleLine("Impl ", formatPath(error.implPath), " has no sibling spec; create ", formatPath(error.expectedSpecPath), " and default-export a GroupSpec from it, or remove the impl.");
149
160
  const renderSpecMissingDefaultGroupSpecError = (error) => singleLine("Spec ", formatPath(error.specPath), " must default-export a GroupSpec; build it with GroupSpec.make() or GroupSpec.makeNode().");
150
161
  const renderSpecImportsServerError = (error) => {
151
- const importers = error.importerPaths.join(", ");
162
+ const importers = Array.join(error.importerPaths, ", ");
152
163
  return singleLine("Spec ", formatPath(error.specPath), ` reaches a module that imports \`@confect/server\`: ${importers}. Spec modules are bundled into your client, so anything they import ships to the browser—move the server logic into a \`*.impl.ts\` module, or use \`import type\` if you only need the types.`);
153
164
  };
154
165
  const renderImplMissingSpecImportError = (error) => {
@@ -158,17 +169,17 @@ const renderImplMissingSpecImportError = (error) => {
158
169
  const renderImplMissingDefaultLayerError = (error) => singleLine("Impl ", formatPath(error.implPath), " must default-export a GroupImpl layer; wrap your handlers with `GroupImpl.make(databaseSchema, groupSpec).pipe(Layer.provide(...))` and `export default` it.");
159
170
  const renderImplNotFinalizedError = (error) => singleLine("Impl ", formatPath(error.implPath), " is not finalized; append `GroupImpl.finalize` to the end of the pipeline (e.g. `GroupImpl.make(databaseSchema, group).pipe(Layer.provide(...), GroupImpl.finalize)`).");
160
171
  const renderImplMissingFunctionsError = (error) => {
161
- const names = error.missingFunctionNames.join(", ");
172
+ const names = Array.join(error.missingFunctionNames, ", ");
162
173
  return singleLine("Impl ", formatPath(error.implPath), ` does not implement every function declared by group \`${error.groupPath}\`; missing: ${names}. Add a \`FunctionImpl.make\` for each missing function and provide it to the group layer.`);
163
174
  };
164
175
  const renderImplMissingMiddlewareError = (error) => {
165
- const keys = error.missingMiddlewareKeys.join(", ");
176
+ const keys = Array.join(error.missingMiddlewareKeys, ", ");
166
177
  return singleLine("Impl ", formatPath(error.implPath), ` does not implement every middleware attached to group \`${error.groupPath}\`; missing: ${keys}. Provide a \`MiddlewareImpl.make\` (or \`makeByFunctionType\`/\`provides\`) layer for each missing middleware to the group layer.`);
167
178
  };
168
179
  const renderInvalidTableDefaultExportError = (error) => singleLine("Table ", formatPath(error.tablePath), " must default-export a Table (e.g. `export default Table.make({ ... })`); convert any named export to a default export.");
169
180
  const renderInvalidTableFilenameError = (error) => singleLine("Table ", formatPath(error.tablePath), ` has an invalid filename: ${error.reason} Convex table names must start with a letter and contain only letters, numbers, and underscores; leading underscores are reserved for system tables.`);
170
181
  const renderDuplicateTableNameError = (error) => {
171
- const conflicts = error.collisions.map(({ tableName, tablePaths }) => `\`${tableName}\` (${tablePaths.join(", ")})`).join("; ");
182
+ const conflicts = Array.join(Array.map(error.collisions, ({ tableName, tablePaths }) => `\`${tableName}\` (${Array.join(tablePaths, ", ")})`), "; ");
172
183
  return singleLine(`Multiple files under \`confect/tables/\` resolve to the same table name. Table names are derived from filenames, so each must be unique across the directory (including subdirectories); rename or remove all but one. Conflicts: ${conflicts}.`);
173
184
  };
174
185
  const renderConflictingDocNameError = (error) => {
@@ -187,23 +198,22 @@ const renderParentChildNameCollisionError = (error) => singleLine("Spec ", forma
187
198
  const renderCodegenError = (error) => {
188
199
  if (isBuildError(error)) return renderBuildError(error);
189
200
  if (error._tag === "ComponentNodeGroupError") return singleLine(`Group "${error.groupPath}" in ${error.specPath} uses the Node runtime. Convex components do not support Node.js functions.`);
190
- if (error._tag === "RequiredMiddlewareError") return singleLine("Required middleware is missing:\n", error.missing.map(({ functionName, middlewareKey }) => `${functionName} requires middleware "${middlewareKey}"`).join("\n"));
201
+ if (error._tag === "RequiredMiddlewareError") return singleLine("Required middleware is missing:\n", pipe(error.missing, Array.map(({ functionName, middlewareKey }) => `${functionName} requires middleware "${middlewareKey}"`), Array.join("\n")));
191
202
  if (error._tag === "RemoveBusyError") return singleLine("Could not remove ", formatPath(error.path), ` after ${error.attempts} attempts because it is busy. Close other tools using it and try again.`);
192
203
  if (error._tag === "InvalidDeclarationError") return singleLine("Declaration ", formatPath(error.declarationPath), ` is invalid: ${error.reason}`);
193
204
  if (error._tag === "InvalidManifestSectionError") return singleLine(`Manifest section "${error.sectionKey}" is invalid: ${error.reason}`);
194
205
  if (error._tag === "DeclarationKindMismatchError") return singleLine("Declaration ", formatPath(error.declarationPath), ` declares kind "${error.declaredKind}", but the target directory is kind "${error.targetKind}".`);
195
206
  if (error._tag === "CallbackPrefixError") return singleLine("Callback contract ", `"${error.contractId}" in `, formatPath(error.declarationPath), ` must start with "${error.componentName}/" for component "${error.componentName}".`);
196
207
  if (error._tag === "HandWrittenConvexFileError") return singleLine("Found a hand-written ", formatPath(error.convexPath), ". `confect codegen` writes it from ", formatPath(error.declarationPath), " now; move its contents there and delete the file.");
197
- if (error._tag === "UnownedConvexEntrypointError") return singleLine(error.filePaths.map((file) => formatPath(file)).join(", "), error.filePaths.length === 1 ? " was" : " were", " not written by confect codegen. Generated files only re-export the registry; put authored code outside convex/. If a file is stale generated output, delete it and run codegen again.");
198
- return Match.value(error).pipe(Match.tag("SnapshotError", ({ reason, relativePath, pathSegments }) => singleLine(`Invalid generation metadata (${reason})`, relativePath === "" ? "" : ` for ${relativePath}`, pathSegments.length === 0 ? "." : ` at ${pathSegments.join("/")}.`)), Match.tag("MissingImplFileError", renderMissingImplFileError), Match.tag("MissingSpecFileError", renderMissingSpecFileError), Match.tag("SpecMissingDefaultGroupSpecError", renderSpecMissingDefaultGroupSpecError), Match.tag("SpecImportsServerError", renderSpecImportsServerError), Match.tag("InvalidMiddlewareAttachmentError", (attachmentError) => singleLine("Spec ", formatPath(attachmentError.specPath), `: ${attachmentError.message}`)), Match.tag("ImplMissingSpecImportError", renderImplMissingSpecImportError), Match.tag("ImplMissingDefaultLayerError", renderImplMissingDefaultLayerError), Match.tag("ImplNotFinalizedError", renderImplNotFinalizedError), Match.tag("ImplMissingFunctionsError", renderImplMissingFunctionsError), Match.tag("ImplMissingMiddlewareError", renderImplMissingMiddlewareError), Match.tag("ParentChildNameCollisionError", renderParentChildNameCollisionError), Match.tag("InvalidTableDefaultExportError", renderInvalidTableDefaultExportError), Match.tag("InvalidTableFilenameError", renderInvalidTableFilenameError), Match.tag("DuplicateTableNameError", renderDuplicateTableNameError), Match.tag("LegacySchemaFileError", renderLegacySchemaFileError), Match.tag("ConflictingDocNameError", renderConflictingDocNameError), Match.tag("InvalidConvexConfigError", renderInvalidConvexConfigError), Match.exhaustive);
208
+ if (error._tag === "UnownedConvexEntrypointError") return singleLine(pipe(error.filePaths, Array.map((file) => formatPath(file)), Array.join(", ")), error.filePaths.length === 1 ? " was" : " were", " not written by confect codegen. Generated files only re-export the registry; put authored code outside convex/. If a file is stale generated output, delete it and run codegen again.");
209
+ return Match.value(error).pipe(Match.tag("SnapshotError", ({ reason, relativePath, pathSegments }) => singleLine(`Invalid generation metadata (${reason})`, relativePath === "" ? "" : ` for ${relativePath}`, pathSegments.length === 0 ? "." : ` at ${Array.join(pathSegments, "/")}.`)), Match.tag("MissingImplFileError", renderMissingImplFileError), Match.tag("MissingSpecFileError", renderMissingSpecFileError), Match.tag("SpecMissingDefaultGroupSpecError", renderSpecMissingDefaultGroupSpecError), Match.tag("SpecImportsServerError", renderSpecImportsServerError), Match.tag("InvalidMiddlewareAttachmentError", (attachmentError) => singleLine("Spec ", formatPath(attachmentError.specPath), `: ${attachmentError.message}`)), Match.tag("ImplMissingSpecImportError", renderImplMissingSpecImportError), Match.tag("InvalidContextReuseError", ({ specPath, groupPath, reason }) => singleLine("Spec ", formatPath(specPath), `, group ${groupPath}: `, Match.value(reason).pipe(Match.when("InvalidOption", () => "experimental_reuseContext must be a boolean."), Match.when("NodeRuntime", () => "experimental_reuseContext is only supported for Convex-runtime groups."), Match.when("ReservedFunctionName", () => "Rename the function experimental_reuseContext before enabling context reuse; its name conflicts with Convex's module flag."), Match.exhaustive))), Match.tag("ImplMissingDefaultLayerError", renderImplMissingDefaultLayerError), Match.tag("ImplNotFinalizedError", renderImplNotFinalizedError), Match.tag("ImplMissingFunctionsError", renderImplMissingFunctionsError), Match.tag("ImplMissingMiddlewareError", renderImplMissingMiddlewareError), Match.tag("ParentChildNameCollisionError", renderParentChildNameCollisionError), Match.tag("InvalidTableDefaultExportError", renderInvalidTableDefaultExportError), Match.tag("InvalidTableFilenameError", renderInvalidTableFilenameError), Match.tag("DuplicateTableNameError", renderDuplicateTableNameError), Match.tag("LegacySchemaFileError", renderLegacySchemaFileError), Match.tag("ConflictingDocNameError", renderConflictingDocNameError), Match.tag("InvalidConvexConfigError", renderInvalidConvexConfigError), Match.exhaustive);
199
210
  };
200
- const logCodegenError = (error) => Console.error(renderCodegenError(error));
211
+ const logCodegenError = (error) => pipe(error, renderCodegenError, Console.error);
201
212
  /**
202
213
  * Log any {@link CodegenError} thrown by `effect` and propagate the failure
203
214
  * unchanged so the caller's error channel is preserved.
204
215
  */
205
216
  const tapAndLog = (effect) => effect.pipe(Effect.tapError((error) => isCodegenError(error) ? logCodegenError(error) : Effect.void));
206
- //#endregion
207
- export { CallbackPrefixError, CodegenError, ComponentNodeGroupError, ConflictingDocNameError, DeclarationKindMismatchError, DuplicateTableNameError, HandWrittenConvexFileError, ImplMissingDefaultLayerError, ImplMissingFunctionsError, ImplMissingMiddlewareError, ImplMissingSpecImportError, ImplNotFinalizedError, InvalidConvexConfigError, InvalidDeclarationError, InvalidManifestSectionError, InvalidMiddlewareAttachmentError, InvalidTableDefaultExportError, InvalidTableFilenameError, LegacySchemaFileError, MissingImplFileError, MissingSpecFileError, ParentChildNameCollisionError, RemoveBusyError, RequiredMiddlewareError, SpecImportsServerError, SpecMissingDefaultGroupSpecError, UnownedConvexEntrypointError, isCodegenError, logCodegenError, renderCodegenError, tapAndLog };
217
+ export { CallbackPrefixError, CodegenError, ComponentNodeGroupError, ConflictingDocNameError, DeclarationKindMismatchError, DuplicateTableNameError, HandWrittenConvexFileError, ImplMissingDefaultLayerError, ImplMissingFunctionsError, ImplMissingMiddlewareError, ImplMissingSpecImportError, ImplNotFinalizedError, InvalidContextReuseError, InvalidConvexConfigError, InvalidDeclarationError, InvalidManifestSectionError, InvalidMiddlewareAttachmentError, InvalidTableDefaultExportError, InvalidTableFilenameError, LegacySchemaFileError, MissingImplFileError, MissingSpecFileError, ParentChildNameCollisionError, RemoveBusyError, RequiredMiddlewareError, SpecImportsServerError, SpecMissingDefaultGroupSpecError, UnownedConvexEntrypointError, isCodegenError, logCodegenError, renderCodegenError, tapAndLog };
208
218
 
209
219
  //# sourceMappingURL=CodegenError.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"CodegenError.mjs","names":["Ansi.red"],"sources":["../src/CodegenError.ts"],"sourcesContent":["import * as Array from \"effect/Array\";\nimport * as Console from \"effect/Console\";\nimport { pipe } from \"effect/Function\";\nimport * as Effect from \"effect/Effect\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport { BuildError, isBuildError } from \"./BuildError.js\";\nimport { SnapshotError } from \"./SnapshotError.js\";\nimport * as Ansi from \"./Ansi.js\";\nimport { formatPath, renderBuildError } from \"./log.js\";\n\n// --- Variants ---\n\nexport class MissingImplFileError extends Schema.TaggedError<MissingImplFileError>()(\n \"MissingImplFileError\",\n {\n specPath: Schema.String,\n expectedImplPath: Schema.String,\n },\n) {}\n\nexport class MissingSpecFileError extends Schema.TaggedError<MissingSpecFileError>()(\n \"MissingSpecFileError\",\n {\n implPath: Schema.String,\n expectedSpecPath: Schema.String,\n },\n) {}\n\nexport class SpecMissingDefaultGroupSpecError extends Schema.TaggedError<SpecMissingDefaultGroupSpecError>()(\n \"SpecMissingDefaultGroupSpecError\",\n {\n specPath: Schema.String,\n },\n) {}\n\nexport class RemoveBusyError extends Schema.TaggedError<RemoveBusyError>()(\n \"RemoveBusyError\",\n { path: Schema.String, attempts: Schema.Finite, cause: Schema.Unknown },\n) {}\n\nexport class ComponentNodeGroupError extends Schema.TaggedError<ComponentNodeGroupError>()(\n \"ComponentNodeGroupError\",\n {\n specPath: Schema.String,\n groupPath: Schema.String,\n },\n) {}\n\nexport class SpecImportsServerError extends Schema.TaggedError<SpecImportsServerError>()(\n \"SpecImportsServerError\",\n {\n specPath: Schema.String,\n importerPaths: Schema.Array(Schema.String),\n },\n) {}\n\nexport class InvalidMiddlewareAttachmentError extends Schema.TaggedError<InvalidMiddlewareAttachmentError>()(\n \"InvalidMiddlewareAttachmentError\",\n { specPath: Schema.String, message: Schema.String },\n) {}\n\nexport class ImplMissingSpecImportError extends Schema.TaggedError<ImplMissingSpecImportError>()(\n \"ImplMissingSpecImportError\",\n {\n implPath: Schema.String,\n expectedSpecPath: Schema.String,\n },\n) {}\n\nexport class ImplMissingDefaultLayerError extends Schema.TaggedError<ImplMissingDefaultLayerError>()(\n \"ImplMissingDefaultLayerError\",\n {\n implPath: Schema.String,\n },\n) {}\n\nexport class ImplNotFinalizedError extends Schema.TaggedError<ImplNotFinalizedError>()(\n \"ImplNotFinalizedError\",\n {\n implPath: Schema.String,\n },\n) {}\n\nexport class ImplMissingFunctionsError extends Schema.TaggedError<ImplMissingFunctionsError>()(\n \"ImplMissingFunctionsError\",\n {\n implPath: Schema.String,\n groupPath: Schema.String,\n missingFunctionNames: Schema.Array(Schema.String),\n },\n) {}\n\nexport class ImplMissingMiddlewareError extends Schema.TaggedError<ImplMissingMiddlewareError>()(\n \"ImplMissingMiddlewareError\",\n {\n implPath: Schema.String,\n groupPath: Schema.String,\n missingMiddlewareKeys: Schema.Array(Schema.String),\n },\n) {}\n\nexport class RequiredMiddlewareError extends Schema.TaggedError<RequiredMiddlewareError>()(\n \"RequiredMiddlewareError\",\n {\n missing: Schema.Array(\n Schema.Struct({\n functionName: Schema.String,\n middlewareKey: Schema.String,\n }),\n ),\n },\n) {}\n\nexport class ParentChildNameCollisionError extends Schema.TaggedError<ParentChildNameCollisionError>()(\n \"ParentChildNameCollisionError\",\n {\n parentSpecPath: Schema.String,\n childSpecPath: Schema.String,\n collisionName: Schema.String,\n collisionKind: Schema.Literals([\"function\", \"group\"]),\n },\n) {}\n\nexport class InvalidTableDefaultExportError extends Schema.TaggedError<InvalidTableDefaultExportError>()(\n \"InvalidTableDefaultExportError\",\n {\n tablePath: Schema.String,\n },\n) {}\n\nexport class InvalidTableFilenameError extends Schema.TaggedError<InvalidTableFilenameError>()(\n \"InvalidTableFilenameError\",\n {\n tablePath: Schema.String,\n reason: Schema.String,\n },\n) {}\n\nexport class DuplicateTableNameError extends Schema.TaggedError<DuplicateTableNameError>()(\n \"DuplicateTableNameError\",\n {\n // Every table name that more than one file resolves to, each paired with\n // the colliding file paths. All collisions are captured in a single pass\n // so the user can fix them together rather than re-running codegen once\n // per conflict.\n collisions: Schema.Array(\n Schema.Struct({\n tableName: Schema.String,\n tablePaths: Schema.Array(Schema.String),\n }),\n ),\n },\n) {}\n\nexport class LegacySchemaFileError extends Schema.TaggedError<LegacySchemaFileError>()(\n \"LegacySchemaFileError\",\n {\n schemaPath: Schema.String,\n },\n) {}\n\nexport class ConflictingDocNameError extends Schema.TaggedError<ConflictingDocNameError>()(\n \"ConflictingDocNameError\",\n {\n collisions: Schema.Array(\n Schema.Struct({\n docName: Schema.String,\n tableNames: Schema.Array(Schema.String),\n }),\n ),\n },\n) {}\n\nexport class InvalidConvexConfigError extends Schema.TaggedError<InvalidConvexConfigError>()(\n \"InvalidConvexConfigError\",\n {\n configPath: Schema.String,\n reason: Schema.String,\n },\n) {}\n\nexport class InvalidDeclarationError extends Schema.TaggedError<InvalidDeclarationError>()(\n \"InvalidDeclarationError\",\n {\n declarationPath: Schema.String,\n reason: Schema.String,\n },\n) {}\n\nexport class InvalidManifestSectionError extends Schema.TaggedError<InvalidManifestSectionError>()(\n \"InvalidManifestSectionError\",\n {\n sectionKey: Schema.String,\n reason: Schema.String,\n },\n) {}\n\nexport class HandWrittenConvexFileError extends Schema.TaggedError<HandWrittenConvexFileError>()(\n \"HandWrittenConvexFileError\",\n {\n convexPath: Schema.String,\n declarationPath: Schema.String,\n },\n) {}\n\nexport class UnownedConvexEntrypointError extends Schema.TaggedError<UnownedConvexEntrypointError>()(\n \"UnownedConvexEntrypointError\",\n { filePaths: Schema.Array(Schema.String) },\n) {}\n\nexport class DeclarationKindMismatchError extends Schema.TaggedError<DeclarationKindMismatchError>()(\n \"DeclarationKindMismatchError\",\n {\n declarationPath: Schema.String,\n declaredKind: Schema.Literals([\"app\", \"component\"]),\n targetKind: Schema.Literals([\"app\", \"component\"]),\n },\n) {}\n\nexport class CallbackPrefixError extends Schema.TaggedError<CallbackPrefixError>()(\n \"CallbackPrefixError\",\n {\n declarationPath: Schema.String,\n contractId: Schema.String,\n componentName: Schema.String,\n },\n) {}\n\nexport const CodegenError = Schema.Union([\n SnapshotError,\n BuildError,\n MissingImplFileError,\n MissingSpecFileError,\n SpecMissingDefaultGroupSpecError,\n ComponentNodeGroupError,\n RemoveBusyError,\n SpecImportsServerError,\n InvalidMiddlewareAttachmentError,\n ImplMissingSpecImportError,\n ImplMissingDefaultLayerError,\n ImplNotFinalizedError,\n ImplMissingFunctionsError,\n ImplMissingMiddlewareError,\n RequiredMiddlewareError,\n ParentChildNameCollisionError,\n InvalidTableDefaultExportError,\n InvalidTableFilenameError,\n DuplicateTableNameError,\n LegacySchemaFileError,\n ConflictingDocNameError,\n InvalidConvexConfigError,\n InvalidDeclarationError,\n InvalidManifestSectionError,\n HandWrittenConvexFileError,\n UnownedConvexEntrypointError,\n DeclarationKindMismatchError,\n CallbackPrefixError,\n]);\nexport type CodegenError = typeof CodegenError.Type;\n\nexport const isCodegenError = (error: unknown): error is CodegenError => {\n if (isBuildError(error)) return true;\n return Schema.is(CodegenError)(error);\n};\n\n// --- Per-variant rendering ---\n\nconst cross = Ansi.red(\"✘\");\n\nconst stemFromSpecPath = (specPath: string): string => {\n const lastSep = Math.max(\n specPath.lastIndexOf(\"/\"),\n specPath.lastIndexOf(\"\\\\\"),\n );\n const basename = lastSep < 0 ? specPath : specPath.slice(lastSep + 1);\n return basename.endsWith(\".spec.ts\")\n ? basename.slice(0, -\".spec.ts\".length)\n : basename;\n};\n\nconst singleLine = (...parts: ReadonlyArray<string>): string =>\n `${cross} ${parts.join(\"\")}`;\n\nconst renderMissingImplFileError = (error: MissingImplFileError): string =>\n singleLine(\n \"Spec \",\n formatPath(error.specPath),\n \" has no sibling impl; create \",\n formatPath(error.expectedImplPath),\n \" and default-export a GroupImpl layer from it.\",\n );\n\nconst renderMissingSpecFileError = (error: MissingSpecFileError): string =>\n singleLine(\n \"Impl \",\n formatPath(error.implPath),\n \" has no sibling spec; create \",\n formatPath(error.expectedSpecPath),\n \" and default-export a GroupSpec from it, or remove the impl.\",\n );\n\nconst renderSpecMissingDefaultGroupSpecError = (\n error: SpecMissingDefaultGroupSpecError,\n): string =>\n singleLine(\n \"Spec \",\n formatPath(error.specPath),\n \" must default-export a GroupSpec; build it with GroupSpec.make() or GroupSpec.makeNode().\",\n );\n\nconst renderSpecImportsServerError = (\n error: SpecImportsServerError,\n): string => {\n const importers = error.importerPaths.join(\", \");\n return singleLine(\n \"Spec \",\n formatPath(error.specPath),\n ` reaches a module that imports \\`@confect/server\\`: ${importers}. Spec modules are bundled into your client, so anything they import ships to the browser—move the server logic into a \\`*.impl.ts\\` module, or use \\`import type\\` if you only need the types.`,\n );\n};\n\nconst renderImplMissingSpecImportError = (\n error: ImplMissingSpecImportError,\n): string => {\n const stem = stemFromSpecPath(error.expectedSpecPath);\n return singleLine(\n \"Impl \",\n formatPath(error.implPath),\n ` does not import its sibling spec; add \\`import ${stem} from \"./${stem}.spec.js\"\\` and pass it to FunctionImpl.make/GroupImpl.make.`,\n );\n};\n\nconst renderImplMissingDefaultLayerError = (\n error: ImplMissingDefaultLayerError,\n): string =>\n singleLine(\n \"Impl \",\n formatPath(error.implPath),\n \" must default-export a GroupImpl layer; wrap your handlers with `GroupImpl.make(databaseSchema, groupSpec).pipe(Layer.provide(...))` and `export default` it.\",\n );\n\nconst renderImplNotFinalizedError = (error: ImplNotFinalizedError): string =>\n singleLine(\n \"Impl \",\n formatPath(error.implPath),\n \" is not finalized; append `GroupImpl.finalize` to the end of the pipeline (e.g. `GroupImpl.make(databaseSchema, group).pipe(Layer.provide(...), GroupImpl.finalize)`).\",\n );\n\nconst renderImplMissingFunctionsError = (\n error: ImplMissingFunctionsError,\n): string => {\n const names = error.missingFunctionNames.join(\", \");\n return singleLine(\n \"Impl \",\n formatPath(error.implPath),\n ` does not implement every function declared by group \\`${error.groupPath}\\`; missing: ${names}. Add a \\`FunctionImpl.make\\` for each missing function and provide it to the group layer.`,\n );\n};\n\nconst renderImplMissingMiddlewareError = (\n error: ImplMissingMiddlewareError,\n): string => {\n const keys = error.missingMiddlewareKeys.join(\", \");\n return singleLine(\n \"Impl \",\n formatPath(error.implPath),\n ` does not implement every middleware attached to group \\`${error.groupPath}\\`; missing: ${keys}. Provide a \\`MiddlewareImpl.make\\` (or \\`makeByFunctionType\\`/\\`provides\\`) layer for each missing middleware to the group layer.`,\n );\n};\n\nconst renderInvalidTableDefaultExportError = (\n error: InvalidTableDefaultExportError,\n): string =>\n singleLine(\n \"Table \",\n formatPath(error.tablePath),\n \" must default-export a Table (e.g. `export default Table.make({ ... })`); convert any named export to a default export.\",\n );\n\nconst renderInvalidTableFilenameError = (\n error: InvalidTableFilenameError,\n): string =>\n singleLine(\n \"Table \",\n formatPath(error.tablePath),\n ` has an invalid filename: ${error.reason} Convex table names must start with a letter and contain only letters, numbers, and underscores; leading underscores are reserved for system tables.`,\n );\n\nconst renderDuplicateTableNameError = (\n error: DuplicateTableNameError,\n): string => {\n const conflicts = error.collisions\n .map(\n ({ tableName, tablePaths }) =>\n `\\`${tableName}\\` (${tablePaths.join(\", \")})`,\n )\n .join(\"; \");\n return singleLine(\n `Multiple files under \\`confect/tables/\\` resolve to the same table name. Table names are derived from filenames, so each must be unique across the directory (including subdirectories); rename or remove all but one. Conflicts: ${conflicts}.`,\n );\n};\n\nconst renderConflictingDocNameError = (\n error: ConflictingDocNameError,\n): string => {\n const conflicts = pipe(\n error.collisions,\n Array.map(\n ({ docName, tableNames }) =>\n `\\`${docName}\\` (${Array.join(tableNames, \", \")})`,\n ),\n Array.join(\"; \"),\n );\n return singleLine(\n `Multiple tables fold to the same generated document type name. Table names are converted to PascalCase (so \\`user_profiles\\` and \\`userProfiles\\` both become \\`UserProfilesDoc\\`); rename all but one of each colliding group. Conflicts: ${conflicts}.`,\n );\n};\n\nconst renderInvalidConvexConfigError = (\n error: InvalidConvexConfigError,\n): string =>\n singleLine(\n \"Convex config \",\n formatPath(error.configPath),\n ` could not be evaluated: ${error.reason}`,\n );\n\nconst renderLegacySchemaFileError = (error: LegacySchemaFileError): string =>\n singleLine(\n \"Found a legacy \",\n formatPath(error.schemaPath),\n \". Delete it: tables in `confect/tables/*.ts` are now the single source of truth, and the runtime schema is generated as `confect/_generated/schema.ts`.\",\n );\n\nconst renderParentChildNameCollisionError = (\n error: ParentChildNameCollisionError,\n): string =>\n singleLine(\n \"Spec \",\n formatPath(error.parentSpecPath),\n ` declares a ${error.collisionKind} \\`${error.collisionName}\\` whose name collides with the sibling subdirectory spec `,\n formatPath(error.childSpecPath),\n `. Rename one of them so the assembled spec has a unique key at this path.`,\n );\n\n/**\n * Render any {@link CodegenError} into a styled, ready-to-print string.\n * Single-error variants render to a one-line `✘`-prefixed message;\n * `BundleFailedError` (the only multi-error variant) renders to a header plus\n * an esbuild diagnostic block.\n */\nexport const renderCodegenError = (error: CodegenError): string => {\n if (isBuildError(error)) return renderBuildError(error);\n // The renderer pipeline below is at Effect's pipe arity limit, so the\n // fork's errors render here.\n if (error._tag === \"ComponentNodeGroupError\") {\n return singleLine(\n `Group \"${error.groupPath}\" in ${error.specPath} uses the Node runtime. Convex components do not support Node.js functions.`,\n );\n }\n if (error._tag === \"RequiredMiddlewareError\") {\n return singleLine(\n \"Required middleware is missing:\\n\",\n error.missing\n .map(\n ({ functionName, middlewareKey }) =>\n `${functionName} requires middleware \"${middlewareKey}\"`,\n )\n .join(\"\\n\"),\n );\n }\n if (error._tag === \"RemoveBusyError\") {\n return singleLine(\n \"Could not remove \",\n formatPath(error.path),\n ` after ${error.attempts} attempts because it is busy. Close other tools using it and try again.`,\n );\n }\n if (error._tag === \"InvalidDeclarationError\") {\n return singleLine(\n \"Declaration \",\n formatPath(error.declarationPath),\n ` is invalid: ${error.reason}`,\n );\n }\n if (error._tag === \"InvalidManifestSectionError\") {\n return singleLine(\n `Manifest section \"${error.sectionKey}\" is invalid: ${error.reason}`,\n );\n }\n if (error._tag === \"DeclarationKindMismatchError\") {\n return singleLine(\n \"Declaration \",\n formatPath(error.declarationPath),\n ` declares kind \"${error.declaredKind}\", but the target directory is kind \"${error.targetKind}\".`,\n );\n }\n if (error._tag === \"CallbackPrefixError\") {\n return singleLine(\n \"Callback contract \",\n `\"${error.contractId}\" in `,\n formatPath(error.declarationPath),\n ` must start with \"${error.componentName}/\" for component \"${error.componentName}\".`,\n );\n }\n if (error._tag === \"HandWrittenConvexFileError\") {\n return singleLine(\n \"Found a hand-written \",\n formatPath(error.convexPath),\n \". `confect codegen` writes it from \",\n formatPath(error.declarationPath),\n \" now; move its contents there and delete the file.\",\n );\n }\n if (error._tag === \"UnownedConvexEntrypointError\") {\n return singleLine(\n error.filePaths.map((file) => formatPath(file)).join(\", \"),\n error.filePaths.length === 1 ? \" was\" : \" were\",\n \" not written by confect codegen. Generated files only re-export the registry; put authored code outside convex/. If a file is stale generated output, delete it and run codegen again.\",\n );\n }\n return Match.value(error).pipe(\n Match.tag(\"SnapshotError\", ({ reason, relativePath, pathSegments }) =>\n singleLine(\n `Invalid generation metadata (${reason})`,\n relativePath === \"\" ? \"\" : ` for ${relativePath}`,\n pathSegments.length === 0 ? \".\" : ` at ${pathSegments.join(\"/\")}.`,\n ),\n ),\n Match.tag(\"MissingImplFileError\", renderMissingImplFileError),\n Match.tag(\"MissingSpecFileError\", renderMissingSpecFileError),\n Match.tag(\n \"SpecMissingDefaultGroupSpecError\",\n renderSpecMissingDefaultGroupSpecError,\n ),\n Match.tag(\"SpecImportsServerError\", renderSpecImportsServerError),\n Match.tag(\"InvalidMiddlewareAttachmentError\", (attachmentError) =>\n singleLine(\n \"Spec \",\n formatPath(attachmentError.specPath),\n `: ${attachmentError.message}`,\n ),\n ),\n Match.tag(\"ImplMissingSpecImportError\", renderImplMissingSpecImportError),\n Match.tag(\n \"ImplMissingDefaultLayerError\",\n renderImplMissingDefaultLayerError,\n ),\n Match.tag(\"ImplNotFinalizedError\", renderImplNotFinalizedError),\n Match.tag(\"ImplMissingFunctionsError\", renderImplMissingFunctionsError),\n Match.tag(\"ImplMissingMiddlewareError\", renderImplMissingMiddlewareError),\n Match.tag(\n \"ParentChildNameCollisionError\",\n renderParentChildNameCollisionError,\n ),\n Match.tag(\n \"InvalidTableDefaultExportError\",\n renderInvalidTableDefaultExportError,\n ),\n Match.tag(\"InvalidTableFilenameError\", renderInvalidTableFilenameError),\n Match.tag(\"DuplicateTableNameError\", renderDuplicateTableNameError),\n Match.tag(\"LegacySchemaFileError\", renderLegacySchemaFileError),\n Match.tag(\"ConflictingDocNameError\", renderConflictingDocNameError),\n Match.tag(\"InvalidConvexConfigError\", renderInvalidConvexConfigError),\n Match.exhaustive,\n );\n};\n\nexport const logCodegenError = (error: CodegenError) =>\n Console.error(renderCodegenError(error));\n\n// --- Effect combinators ---\n\n/**\n * Log any {@link CodegenError} thrown by `effect` and propagate the failure\n * unchanged so the caller's error channel is preserved.\n */\nexport const tapAndLog = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<A, E, R> =>\n effect.pipe(\n Effect.tapError((error) =>\n isCodegenError(error) ? logCodegenError(error) : Effect.void,\n ),\n );\n\n/**\n * Catch any {@link CodegenError} thrown by `effect`, log it, and resolve to\n * `Option.none()`. Success resolves to `Option.some(value)`.\n */\n// oxlint-disable effecttsgo/unsafe-effect-type-assertion -- catchIf removes the error variant selected by this refinement.\nexport const catchAndLog = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<Option.Option<A>, Exclude<E, CodegenError>, R> =>\n Effect.catchIf(Effect.map(effect, Option.some<A>), isCodegenError, (error) =>\n logCodegenError(error).pipe(Effect.as(Option.none<A>())),\n ) as Effect.Effect<Option.Option<A>, Exclude<E, CodegenError>, R>;\n// oxlint-enable effecttsgo/unsafe-effect-type-assertion\n"],"mappings":";;;;;;;;;;;;AAcA,IAAa,uBAAb,cAA0C,OAAO,YAAkC,CAAC,CAClF,wBACA;CACE,UAAU,OAAO;CACjB,kBAAkB,OAAO;AAC3B,CACF,CAAC,CAAC,CAAC;AAEH,IAAa,uBAAb,cAA0C,OAAO,YAAkC,CAAC,CAClF,wBACA;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C,oBAC7C,WACE,SACA,WAAW,gBAAgB,QAAQ,GACnC,KAAK,gBAAgB,SACvB,CACF,GACA,MAAM,IAAI,8BAA8B,gCAAgC,GACxE,MAAM,IACJ,gCACA,kCACF,GACA,MAAM,IAAI,yBAAyB,2BAA2B,GAC9D,MAAM,IAAI,6BAA6B,+BAA+B,GACtE,MAAM,IAAI,8BAA8B,gCAAgC,GACxE,MAAM,IACJ,iCACA,mCACF,GACA,MAAM,IACJ,kCACA,oCACF,GACA,MAAM,IAAI,6BAA6B,+BAA+B,GACtE,MAAM,IAAI,2BAA2B,6BAA6B,GAClE,MAAM,IAAI,yBAAyB,2BAA2B,GAC9D,MAAM,IAAI,2BAA2B,6BAA6B,GAClE,MAAM,IAAI,4BAA4B,8BAA8B,GACpE,MAAM,UACR;AACF;AAEA,MAAa,mBAAmB,UAC9B,QAAQ,MAAM,mBAAmB,KAAK,CAAC;;;;;AAQzC,MAAa,aACX,WAEA,OAAO,KACL,OAAO,UAAU,UACf,eAAe,KAAK,IAAI,gBAAgB,KAAK,IAAI,OAAO,IAC1D,CACF"}
1
+ {"version":3,"file":"CodegenError.mjs","names":["Ansi.red"],"sources":["../src/CodegenError.ts"],"sourcesContent":["import * as String from \"effect/String\";\nimport * as Array from \"effect/Array\";\nimport * as Console from \"effect/Console\";\nimport { pipe } from \"effect/Function\";\nimport * as Effect from \"effect/Effect\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport { BuildError, isBuildError } from \"./BuildError.js\";\nimport { SnapshotError } from \"./SnapshotError.js\";\nimport * as Ansi from \"./Ansi.js\";\nimport { formatPath, renderBuildError } from \"./log.js\";\n\n// --- Variants ---\n\nexport class MissingImplFileError extends Schema.TaggedError<\n MissingImplFileError,\n { readonly brand: unique symbol }\n>()(\"MissingImplFileError\", {\n specPath: Schema.String,\n expectedImplPath: Schema.String,\n}) {}\n\nexport class MissingSpecFileError extends Schema.TaggedError<\n MissingSpecFileError,\n { readonly brand: unique symbol }\n>()(\"MissingSpecFileError\", {\n implPath: Schema.String,\n expectedSpecPath: Schema.String,\n}) {}\n\nexport class SpecMissingDefaultGroupSpecError extends Schema.TaggedError<\n SpecMissingDefaultGroupSpecError,\n { readonly brand: unique symbol }\n>()(\"SpecMissingDefaultGroupSpecError\", {\n specPath: Schema.String,\n}) {}\n\nexport class RemoveBusyError extends Schema.TaggedError<\n RemoveBusyError,\n { readonly brand: unique symbol }\n>()(\"RemoveBusyError\", {\n path: Schema.String,\n attempts: Schema.Finite,\n cause: Schema.Unknown,\n}) {}\n\nexport class ComponentNodeGroupError extends Schema.TaggedError<\n ComponentNodeGroupError,\n { readonly brand: unique symbol }\n>()(\"ComponentNodeGroupError\", {\n specPath: Schema.String,\n groupPath: Schema.String,\n}) {}\n\nexport class SpecImportsServerError extends Schema.TaggedError<\n SpecImportsServerError,\n { readonly brand: unique symbol }\n>()(\"SpecImportsServerError\", {\n specPath: Schema.String,\n importerPaths: Schema.Array(Schema.String),\n}) {}\n\nexport class InvalidMiddlewareAttachmentError extends Schema.TaggedError<\n InvalidMiddlewareAttachmentError,\n { readonly brand: unique symbol }\n>()(\"InvalidMiddlewareAttachmentError\", {\n specPath: Schema.String,\n message: Schema.String,\n}) {}\n\nexport class InvalidContextReuseError extends Schema.TaggedError<\n InvalidContextReuseError,\n { readonly brand: unique symbol }\n>()(\"InvalidContextReuseError\", {\n specPath: Schema.String,\n groupPath: Schema.String,\n reason: Schema.Literals([\n \"InvalidOption\",\n \"NodeRuntime\",\n \"ReservedFunctionName\",\n ]),\n}) {}\n\nexport class ImplMissingSpecImportError extends Schema.TaggedError<\n ImplMissingSpecImportError,\n { readonly brand: unique symbol }\n>()(\"ImplMissingSpecImportError\", {\n implPath: Schema.String,\n expectedSpecPath: Schema.String,\n}) {}\n\nexport class ImplMissingDefaultLayerError extends Schema.TaggedError<\n ImplMissingDefaultLayerError,\n { readonly brand: unique symbol }\n>()(\"ImplMissingDefaultLayerError\", {\n implPath: Schema.String,\n}) {}\n\nexport class ImplNotFinalizedError extends Schema.TaggedError<\n ImplNotFinalizedError,\n { readonly brand: unique symbol }\n>()(\"ImplNotFinalizedError\", {\n implPath: Schema.String,\n}) {}\n\nexport class ImplMissingFunctionsError extends Schema.TaggedError<\n ImplMissingFunctionsError,\n { readonly brand: unique symbol }\n>()(\"ImplMissingFunctionsError\", {\n implPath: Schema.String,\n groupPath: Schema.String,\n missingFunctionNames: Schema.Array(Schema.String),\n}) {}\n\nexport class ImplMissingMiddlewareError extends Schema.TaggedError<\n ImplMissingMiddlewareError,\n { readonly brand: unique symbol }\n>()(\"ImplMissingMiddlewareError\", {\n implPath: Schema.String,\n groupPath: Schema.String,\n missingMiddlewareKeys: Schema.Array(Schema.String),\n}) {}\n\nexport class RequiredMiddlewareError extends Schema.TaggedError<\n RequiredMiddlewareError,\n { readonly brand: unique symbol }\n>()(\"RequiredMiddlewareError\", {\n missing: Schema.Array(\n Schema.Struct({\n functionName: Schema.String,\n middlewareKey: Schema.String,\n }),\n ),\n}) {}\n\nexport class ParentChildNameCollisionError extends Schema.TaggedError<\n ParentChildNameCollisionError,\n { readonly brand: unique symbol }\n>()(\"ParentChildNameCollisionError\", {\n parentSpecPath: Schema.String,\n childSpecPath: Schema.String,\n collisionName: Schema.String,\n collisionKind: Schema.Literals([\"function\", \"group\"]),\n}) {}\n\nexport class InvalidTableDefaultExportError extends Schema.TaggedError<\n InvalidTableDefaultExportError,\n { readonly brand: unique symbol }\n>()(\"InvalidTableDefaultExportError\", {\n tablePath: Schema.String,\n}) {}\n\nexport class InvalidTableFilenameError extends Schema.TaggedError<\n InvalidTableFilenameError,\n { readonly brand: unique symbol }\n>()(\"InvalidTableFilenameError\", {\n tablePath: Schema.String,\n reason: Schema.String,\n}) {}\n\nexport class DuplicateTableNameError extends Schema.TaggedError<\n DuplicateTableNameError,\n { readonly brand: unique symbol }\n>()(\"DuplicateTableNameError\", {\n // Every table name that more than one file resolves to, each paired with\n // the colliding file paths. All collisions are captured in a single pass\n // so the user can fix them together rather than re-running codegen once\n // per conflict.\n collisions: Schema.Array(\n Schema.Struct({\n tableName: Schema.String,\n tablePaths: Schema.Array(Schema.String),\n }),\n ),\n}) {}\n\nexport class LegacySchemaFileError extends Schema.TaggedError<\n LegacySchemaFileError,\n { readonly brand: unique symbol }\n>()(\"LegacySchemaFileError\", {\n schemaPath: Schema.String,\n}) {}\n\nexport class ConflictingDocNameError extends Schema.TaggedError<\n ConflictingDocNameError,\n { readonly brand: unique symbol }\n>()(\"ConflictingDocNameError\", {\n collisions: Schema.Array(\n Schema.Struct({\n docName: Schema.String,\n tableNames: Schema.Array(Schema.String),\n }),\n ),\n}) {}\n\nexport class InvalidConvexConfigError extends Schema.TaggedError<\n InvalidConvexConfigError,\n { readonly brand: unique symbol }\n>()(\"InvalidConvexConfigError\", {\n configPath: Schema.String,\n reason: Schema.String,\n}) {}\n\nexport class InvalidDeclarationError extends Schema.TaggedError<\n InvalidDeclarationError,\n { readonly brand: unique symbol }\n>()(\"InvalidDeclarationError\", {\n declarationPath: Schema.String,\n reason: Schema.String,\n}) {}\n\nexport class InvalidManifestSectionError extends Schema.TaggedError<\n InvalidManifestSectionError,\n { readonly brand: unique symbol }\n>()(\"InvalidManifestSectionError\", {\n sectionKey: Schema.String,\n reason: Schema.String,\n}) {}\n\nexport class HandWrittenConvexFileError extends Schema.TaggedError<\n HandWrittenConvexFileError,\n { readonly brand: unique symbol }\n>()(\"HandWrittenConvexFileError\", {\n convexPath: Schema.String,\n declarationPath: Schema.String,\n}) {}\n\nexport class UnownedConvexEntrypointError extends Schema.TaggedError<\n UnownedConvexEntrypointError,\n { readonly brand: unique symbol }\n>()(\"UnownedConvexEntrypointError\", {\n filePaths: Schema.Array(Schema.String),\n}) {}\n\nexport class DeclarationKindMismatchError extends Schema.TaggedError<\n DeclarationKindMismatchError,\n { readonly brand: unique symbol }\n>()(\"DeclarationKindMismatchError\", {\n declarationPath: Schema.String,\n declaredKind: Schema.Literals([\"app\", \"component\"]),\n targetKind: Schema.Literals([\"app\", \"component\"]),\n}) {}\n\nexport class CallbackPrefixError extends Schema.TaggedError<\n CallbackPrefixError,\n { readonly brand: unique symbol }\n>()(\"CallbackPrefixError\", {\n declarationPath: Schema.String,\n contractId: Schema.String,\n componentName: Schema.String,\n}) {}\n\nexport const CodegenError = Schema.Union([\n SnapshotError,\n BuildError,\n MissingImplFileError,\n MissingSpecFileError,\n SpecMissingDefaultGroupSpecError,\n ComponentNodeGroupError,\n RemoveBusyError,\n SpecImportsServerError,\n InvalidMiddlewareAttachmentError,\n InvalidContextReuseError,\n ImplMissingSpecImportError,\n ImplMissingDefaultLayerError,\n ImplNotFinalizedError,\n ImplMissingFunctionsError,\n ImplMissingMiddlewareError,\n RequiredMiddlewareError,\n ParentChildNameCollisionError,\n InvalidTableDefaultExportError,\n InvalidTableFilenameError,\n DuplicateTableNameError,\n LegacySchemaFileError,\n ConflictingDocNameError,\n InvalidConvexConfigError,\n InvalidDeclarationError,\n InvalidManifestSectionError,\n HandWrittenConvexFileError,\n UnownedConvexEntrypointError,\n DeclarationKindMismatchError,\n CallbackPrefixError,\n]);\nexport type CodegenError = typeof CodegenError.Type;\n\nexport const isCodegenError = (error: unknown): error is CodegenError => {\n if (isBuildError(error)) return true;\n return Schema.is(CodegenError)(error);\n};\n\n// --- Per-variant rendering ---\n\nconst cross = Ansi.red(\"✘\");\n\nconst stemFromSpecPath = (specPath: string): string => {\n const lastSep = Math.max(\n Option.getOrElse(String.lastIndexOf(\"/\")(specPath), () => -1),\n Option.getOrElse(String.lastIndexOf(\"\\\\\")(specPath), () => -1),\n );\n const basename = lastSep < 0 ? specPath : String.slice(lastSep + 1)(specPath);\n return String.endsWith(\".spec.ts\")(basename)\n ? String.slice(0, -\".spec.ts\".length)(basename)\n : basename;\n};\n\nconst singleLine = (...parts: ReadonlyArray<string>): string =>\n `${cross} ${Array.join(parts, \"\")}`;\n\nconst renderMissingImplFileError = (error: MissingImplFileError): string =>\n singleLine(\n \"Spec \",\n formatPath(error.specPath),\n \" has no sibling impl; create \",\n formatPath(error.expectedImplPath),\n \" and default-export a GroupImpl layer from it.\",\n );\n\nconst renderMissingSpecFileError = (error: MissingSpecFileError): string =>\n singleLine(\n \"Impl \",\n formatPath(error.implPath),\n \" has no sibling spec; create \",\n formatPath(error.expectedSpecPath),\n \" and default-export a GroupSpec from it, or remove the impl.\",\n );\n\nconst renderSpecMissingDefaultGroupSpecError = (\n error: SpecMissingDefaultGroupSpecError,\n): string =>\n singleLine(\n \"Spec \",\n formatPath(error.specPath),\n \" must default-export a GroupSpec; build it with GroupSpec.make() or GroupSpec.makeNode().\",\n );\n\nconst renderSpecImportsServerError = (\n error: SpecImportsServerError,\n): string => {\n const importers = Array.join(error.importerPaths, \", \");\n return singleLine(\n \"Spec \",\n formatPath(error.specPath),\n ` reaches a module that imports \\`@confect/server\\`: ${importers}. Spec modules are bundled into your client, so anything they import ships to the browser—move the server logic into a \\`*.impl.ts\\` module, or use \\`import type\\` if you only need the types.`,\n );\n};\n\nconst renderImplMissingSpecImportError = (\n error: ImplMissingSpecImportError,\n): string => {\n const stem = stemFromSpecPath(error.expectedSpecPath);\n return singleLine(\n \"Impl \",\n formatPath(error.implPath),\n ` does not import its sibling spec; add \\`import ${stem} from \"./${stem}.spec.js\"\\` and pass it to FunctionImpl.make/GroupImpl.make.`,\n );\n};\n\nconst renderImplMissingDefaultLayerError = (\n error: ImplMissingDefaultLayerError,\n): string =>\n singleLine(\n \"Impl \",\n formatPath(error.implPath),\n \" must default-export a GroupImpl layer; wrap your handlers with `GroupImpl.make(databaseSchema, groupSpec).pipe(Layer.provide(...))` and `export default` it.\",\n );\n\nconst renderImplNotFinalizedError = (error: ImplNotFinalizedError): string =>\n singleLine(\n \"Impl \",\n formatPath(error.implPath),\n \" is not finalized; append `GroupImpl.finalize` to the end of the pipeline (e.g. `GroupImpl.make(databaseSchema, group).pipe(Layer.provide(...), GroupImpl.finalize)`).\",\n );\n\nconst renderImplMissingFunctionsError = (\n error: ImplMissingFunctionsError,\n): string => {\n const names = Array.join(error.missingFunctionNames, \", \");\n return singleLine(\n \"Impl \",\n formatPath(error.implPath),\n ` does not implement every function declared by group \\`${error.groupPath}\\`; missing: ${names}. Add a \\`FunctionImpl.make\\` for each missing function and provide it to the group layer.`,\n );\n};\n\nconst renderImplMissingMiddlewareError = (\n error: ImplMissingMiddlewareError,\n): string => {\n const keys = Array.join(error.missingMiddlewareKeys, \", \");\n return singleLine(\n \"Impl \",\n formatPath(error.implPath),\n ` does not implement every middleware attached to group \\`${error.groupPath}\\`; missing: ${keys}. Provide a \\`MiddlewareImpl.make\\` (or \\`makeByFunctionType\\`/\\`provides\\`) layer for each missing middleware to the group layer.`,\n );\n};\n\nconst renderInvalidTableDefaultExportError = (\n error: InvalidTableDefaultExportError,\n): string =>\n singleLine(\n \"Table \",\n formatPath(error.tablePath),\n \" must default-export a Table (e.g. `export default Table.make({ ... })`); convert any named export to a default export.\",\n );\n\nconst renderInvalidTableFilenameError = (\n error: InvalidTableFilenameError,\n): string =>\n singleLine(\n \"Table \",\n formatPath(error.tablePath),\n ` has an invalid filename: ${error.reason} Convex table names must start with a letter and contain only letters, numbers, and underscores; leading underscores are reserved for system tables.`,\n );\n\nconst renderDuplicateTableNameError = (\n error: DuplicateTableNameError,\n): string => {\n const conflicts = Array.join(\n Array.map(\n error.collisions,\n ({ tableName, tablePaths }) =>\n `\\`${tableName}\\` (${Array.join(tablePaths, \", \")})`,\n ),\n \"; \",\n );\n return singleLine(\n `Multiple files under \\`confect/tables/\\` resolve to the same table name. Table names are derived from filenames, so each must be unique across the directory (including subdirectories); rename or remove all but one. Conflicts: ${conflicts}.`,\n );\n};\n\nconst renderConflictingDocNameError = (\n error: ConflictingDocNameError,\n): string => {\n const conflicts = pipe(\n error.collisions,\n Array.map(\n ({ docName, tableNames }) =>\n `\\`${docName}\\` (${Array.join(tableNames, \", \")})`,\n ),\n Array.join(\"; \"),\n );\n return singleLine(\n `Multiple tables fold to the same generated document type name. Table names are converted to PascalCase (so \\`user_profiles\\` and \\`userProfiles\\` both become \\`UserProfilesDoc\\`); rename all but one of each colliding group. Conflicts: ${conflicts}.`,\n );\n};\n\nconst renderInvalidConvexConfigError = (\n error: InvalidConvexConfigError,\n): string =>\n singleLine(\n \"Convex config \",\n formatPath(error.configPath),\n ` could not be evaluated: ${error.reason}`,\n );\n\nconst renderLegacySchemaFileError = (error: LegacySchemaFileError): string =>\n singleLine(\n \"Found a legacy \",\n formatPath(error.schemaPath),\n \". Delete it: tables in `confect/tables/*.ts` are now the single source of truth, and the runtime schema is generated as `confect/_generated/schema.ts`.\",\n );\n\nconst renderParentChildNameCollisionError = (\n error: ParentChildNameCollisionError,\n): string =>\n singleLine(\n \"Spec \",\n formatPath(error.parentSpecPath),\n ` declares a ${error.collisionKind} \\`${error.collisionName}\\` whose name collides with the sibling subdirectory spec `,\n formatPath(error.childSpecPath),\n `. Rename one of them so the assembled spec has a unique key at this path.`,\n );\n\n/**\n * Render any {@link CodegenError} into a styled, ready-to-print string.\n * Single-error variants render to a one-line `✘`-prefixed message;\n * `BundleFailedError` (the only multi-error variant) renders to a header plus\n * an esbuild diagnostic block.\n */\nexport const renderCodegenError = (error: CodegenError): string => {\n if (isBuildError(error)) return renderBuildError(error);\n // The renderer pipeline below is at Effect's pipe arity limit, so the\n // fork's errors render here.\n if (error._tag === \"ComponentNodeGroupError\") {\n return singleLine(\n `Group \"${error.groupPath}\" in ${error.specPath} uses the Node runtime. Convex components do not support Node.js functions.`,\n );\n }\n if (error._tag === \"RequiredMiddlewareError\") {\n return singleLine(\n \"Required middleware is missing:\\n\",\n pipe(\n error.missing,\n Array.map(\n ({ functionName, middlewareKey }) =>\n `${functionName} requires middleware \"${middlewareKey}\"`,\n ),\n Array.join(\"\\n\"),\n ),\n );\n }\n if (error._tag === \"RemoveBusyError\") {\n return singleLine(\n \"Could not remove \",\n formatPath(error.path),\n ` after ${error.attempts} attempts because it is busy. Close other tools using it and try again.`,\n );\n }\n if (error._tag === \"InvalidDeclarationError\") {\n return singleLine(\n \"Declaration \",\n formatPath(error.declarationPath),\n ` is invalid: ${error.reason}`,\n );\n }\n if (error._tag === \"InvalidManifestSectionError\") {\n return singleLine(\n `Manifest section \"${error.sectionKey}\" is invalid: ${error.reason}`,\n );\n }\n if (error._tag === \"DeclarationKindMismatchError\") {\n return singleLine(\n \"Declaration \",\n formatPath(error.declarationPath),\n ` declares kind \"${error.declaredKind}\", but the target directory is kind \"${error.targetKind}\".`,\n );\n }\n if (error._tag === \"CallbackPrefixError\") {\n return singleLine(\n \"Callback contract \",\n `\"${error.contractId}\" in `,\n formatPath(error.declarationPath),\n ` must start with \"${error.componentName}/\" for component \"${error.componentName}\".`,\n );\n }\n if (error._tag === \"HandWrittenConvexFileError\") {\n return singleLine(\n \"Found a hand-written \",\n formatPath(error.convexPath),\n \". `confect codegen` writes it from \",\n formatPath(error.declarationPath),\n \" now; move its contents there and delete the file.\",\n );\n }\n if (error._tag === \"UnownedConvexEntrypointError\") {\n return singleLine(\n pipe(\n error.filePaths,\n Array.map((file) => formatPath(file)),\n Array.join(\", \"),\n ),\n error.filePaths.length === 1 ? \" was\" : \" were\",\n \" not written by confect codegen. Generated files only re-export the registry; put authored code outside convex/. If a file is stale generated output, delete it and run codegen again.\",\n );\n }\n return Match.value(error).pipe(\n Match.tag(\"SnapshotError\", ({ reason, relativePath, pathSegments }) =>\n singleLine(\n `Invalid generation metadata (${reason})`,\n relativePath === \"\" ? \"\" : ` for ${relativePath}`,\n pathSegments.length === 0\n ? \".\"\n : ` at ${Array.join(pathSegments, \"/\")}.`,\n ),\n ),\n Match.tag(\"MissingImplFileError\", renderMissingImplFileError),\n Match.tag(\"MissingSpecFileError\", renderMissingSpecFileError),\n Match.tag(\n \"SpecMissingDefaultGroupSpecError\",\n renderSpecMissingDefaultGroupSpecError,\n ),\n Match.tag(\"SpecImportsServerError\", renderSpecImportsServerError),\n Match.tag(\"InvalidMiddlewareAttachmentError\", (attachmentError) =>\n singleLine(\n \"Spec \",\n formatPath(attachmentError.specPath),\n `: ${attachmentError.message}`,\n ),\n ),\n Match.tag(\"ImplMissingSpecImportError\", renderImplMissingSpecImportError),\n Match.tag(\"InvalidContextReuseError\", ({ specPath, groupPath, reason }) =>\n singleLine(\n \"Spec \",\n formatPath(specPath),\n `, group ${groupPath}: `,\n Match.value(reason).pipe(\n Match.when(\n \"InvalidOption\",\n () => \"experimental_reuseContext must be a boolean.\",\n ),\n Match.when(\n \"NodeRuntime\",\n () =>\n \"experimental_reuseContext is only supported for Convex-runtime groups.\",\n ),\n Match.when(\n \"ReservedFunctionName\",\n () =>\n \"Rename the function experimental_reuseContext before enabling context reuse; its name conflicts with Convex's module flag.\",\n ),\n Match.exhaustive,\n ),\n ),\n ),\n Match.tag(\n \"ImplMissingDefaultLayerError\",\n renderImplMissingDefaultLayerError,\n ),\n Match.tag(\"ImplNotFinalizedError\", renderImplNotFinalizedError),\n Match.tag(\"ImplMissingFunctionsError\", renderImplMissingFunctionsError),\n Match.tag(\"ImplMissingMiddlewareError\", renderImplMissingMiddlewareError),\n Match.tag(\n \"ParentChildNameCollisionError\",\n renderParentChildNameCollisionError,\n ),\n Match.tag(\n \"InvalidTableDefaultExportError\",\n renderInvalidTableDefaultExportError,\n ),\n Match.tag(\"InvalidTableFilenameError\", renderInvalidTableFilenameError),\n Match.tag(\"DuplicateTableNameError\", renderDuplicateTableNameError),\n Match.tag(\"LegacySchemaFileError\", renderLegacySchemaFileError),\n Match.tag(\"ConflictingDocNameError\", renderConflictingDocNameError),\n Match.tag(\"InvalidConvexConfigError\", renderInvalidConvexConfigError),\n Match.exhaustive,\n );\n};\n\nexport const logCodegenError = (error: CodegenError) =>\n pipe(error, renderCodegenError, Console.error);\n\n// --- Effect combinators ---\n\n/**\n * Log any {@link CodegenError} thrown by `effect` and propagate the failure\n * unchanged so the caller's error channel is preserved.\n */\nexport const tapAndLog = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<A, E, R> =>\n effect.pipe(\n Effect.tapError((error) =>\n isCodegenError(error) ? logCodegenError(error) : Effect.void,\n ),\n );\n\n/**\n * Catch any {@link CodegenError} thrown by `effect`, log it, and resolve to\n * `Option.none()`. Success resolves to `Option.some(value)`.\n */\n// oxlint-disable effecttsgo/unsafe-effect-type-assertion -- catchIf removes the error variant selected by this refinement.\nexport const catchAndLog = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<Option.Option<A>, Exclude<E, CodegenError>, R> =>\n Effect.catchIf(\n Effect.map(effect, Option.some<A>),\n (error: E): error is E & CodegenError => isCodegenError(error),\n (error: E & CodegenError) =>\n logCodegenError(error).pipe(Effect.as(Option.none<A>())),\n ) as Effect.Effect<Option.Option<A>, Exclude<E, CodegenError>, R>;\n"],"mappings":";;;;;;;;;;;;;AAeA,IAAa,uBAAb,cAA0C,OAAO,YAG/C,CAAC,CAAC,wBAAwB;CAC1B,UAAU,OAAO;CACjB,kBAAkB,OAAO;AAC3B,CAAC,CAAC,CAAC,CAAC;AAEJ,IAAa,uBAAb,cAA0C,OAAO,YAG/C,CAAC,CAAC,wBAAwB;CAC1B,UAAU,OAAO;CACjB,kBAAkB,OAAO;AAC3B,CAAC,CAAC,CAAC,CAAC;AAEJ,IAAa,mCAAb,cAAsD,OAAO,YAG3D,CAAC,CAAC,oCAAoC,EACtC,UAAU,OAAO,OACnB,CAAC,CAAC,CAAC,CAAC;AAEJ,IAAa,kBAAb,cAAqC,OAAO,YAG1C,CAAC,CAAC,mBAAmB;CACrB,MAAM,OAAO;CACb,UAAU,OAAO;CACjB,OAAO,OAAO;AAChB,CAAC,CAAC,CAAC,CAAC;AAEJ,IAAa,0BAAb,cAA6C,OAAO,YAGlD,CAAC,CAAC,2BAA2B;CAC7B,UAAU,OAAO;CACjB,WAAW,OAAO;AACpB,CAAC,CAAC,CAAC,CAAC;AAEJ,IAAa,yBAAb,cAA4C,OAAO,YAGjD,CAAC,CAAC,0BAA0B;CAC5B,UAAU,OAAO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AqC,oBAC7C,WACE,SACA,WAAW,gBAAgB,QAAQ,GACnC,KAAK,gBAAgB,SACvB,CACF,GACA,MAAM,IAAI,8BAA8B,gCAAgC,GACxE,MAAM,IAAI,6BAA6B,EAAE,UAAU,WAAW,aAC5D,WACE,SACA,WAAW,QAAQ,GACnB,WAAW,UAAU,KACrB,MAAM,MAAM,MAAM,CAAC,CAAC,KAClB,MAAM,KACJ,uBACM,8CACR,GACA,MAAM,KACJ,qBAEE,wEACJ,GACA,MAAM,KACJ,8BAEE,4HACJ,GACA,MAAM,UACR,CACF,CACF,GACA,MAAM,IACJ,gCACA,kCACF,GACA,MAAM,IAAI,yBAAyB,2BAA2B,GAC9D,MAAM,IAAI,6BAA6B,+BAA+B,GACtE,MAAM,IAAI,8BAA8B,gCAAgC,GACxE,MAAM,IACJ,iCACA,mCACF,GACA,MAAM,IACJ,kCACA,oCACF,GACA,MAAM,IAAI,6BAA6B,+BAA+B,GACtE,MAAM,IAAI,2BAA2B,6BAA6B,GAClE,MAAM,IAAI,yBAAyB,2BAA2B,GAC9D,MAAM,IAAI,2BAA2B,6BAA6B,GAClE,MAAM,IAAI,4BAA4B,8BAA8B,GACpE,MAAM,UACR;AACF;AAEA,MAAa,mBAAmB,UAC9B,KAAK,OAAO,oBAAoB,QAAQ,KAAK;;;;;AAQ/C,MAAa,aACX,WAEA,OAAO,KACL,OAAO,UAAU,UACf,eAAe,KAAK,IAAI,gBAAgB,KAAK,IAAI,OAAO,IAC1D,CACF"}
@@ -6,7 +6,7 @@ import * as Context from "effect/Context";
6
6
  import * as Ref from "effect/Ref";
7
7
  import * as Schema from "effect/Schema";
8
8
  import * as Layer from "effect/Layer";
9
- //#region src/ConfectDirectory.ts
9
+ // src/ConfectDirectory.ts
10
10
  var ConfectDirectory = class ConfectDirectory extends Context.Service()("@confect/cli/ConfectDirectory") {
11
11
  static get = ConfectDirectory.use((service) => service.get);
12
12
  };
@@ -15,21 +15,26 @@ var ConfectDirectoryNotFoundError = class extends Schema.TaggedError()("ConfectD
15
15
  return "Could not find Confect directory";
16
16
  }
17
17
  };
18
+ /**
19
+ * @internal
20
+ */
18
21
  const findConfectDirectory = Effect.gen(function* () {
19
22
  const fs = yield* FileSystem.FileSystem;
20
23
  const path = yield* Path.Path;
21
24
  const convexDirectory = yield* ConvexDirectory.get;
22
25
  const confectDirectory = path.join(path.dirname(convexDirectory), "confect");
23
26
  if (yield* fs.exists(confectDirectory)) return confectDirectory;
24
- else return yield* new ConfectDirectoryNotFoundError();
27
+ else return yield* ConfectDirectoryNotFoundError.make();
25
28
  });
29
+ /**
30
+ * @internal
31
+ */
26
32
  const layerFromConvexDirectory = Layer.effect(ConfectDirectory, Effect.gen(function* () {
27
33
  const confectDirectory = yield* findConfectDirectory;
28
34
  const ref = yield* Ref.make(confectDirectory);
29
35
  return { get: Ref.get(ref) };
30
36
  }));
31
37
  layerFromConvexDirectory.pipe(Layer.provide(layer$1));
32
- //#endregion
33
38
  export { ConfectDirectory, ConfectDirectoryNotFoundError, findConfectDirectory, layerFromConvexDirectory };
34
39
 
35
40
  //# sourceMappingURL=ConfectDirectory.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"ConfectDirectory.mjs","names":["ConvexDirectory.layer"],"sources":["../src/ConfectDirectory.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Path from \"effect/Path\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as ConvexDirectory from \"./ConvexDirectory.js\";\n\nexport class ConfectDirectory extends Context.Service<\n ConfectDirectory,\n { readonly get: Effect.Effect<string> }\n>()(\"@confect/cli/ConfectDirectory\") {\n static readonly get = ConfectDirectory.use((service) => service.get);\n}\n\nexport class ConfectDirectoryNotFoundError extends Schema.TaggedError<ConfectDirectoryNotFoundError>()(\n \"ConfectDirectoryNotFoundError\",\n {},\n) {\n override get message(): string {\n return \"Could not find Confect directory\";\n }\n}\n\nexport const findConfectDirectory = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n\n const convexDirectory = yield* ConvexDirectory.ConvexDirectory.get;\n\n const confectDirectory = path.join(path.dirname(convexDirectory), \"confect\");\n\n if (yield* fs.exists(confectDirectory)) {\n return confectDirectory;\n } else {\n return yield* new ConfectDirectoryNotFoundError();\n }\n});\n\nexport const layerFromConvexDirectory = Layer.effect(\n ConfectDirectory,\n Effect.gen(function* () {\n const confectDirectory = yield* findConfectDirectory;\n\n const ref = yield* Ref.make<string>(confectDirectory);\n\n return { get: Ref.get(ref) } as const;\n }),\n);\n\nexport const layer = layerFromConvexDirectory.pipe(\n Layer.provide(ConvexDirectory.layer),\n);\n"],"mappings":";;;;;;;;;AASA,IAAa,mBAAb,MAAa,yBAAyB,QAAQ,QAG5C,CAAC,CAAC,+BAA+B,CAAC,CAAC;CACnC,OAAgB,MAAM,iBAAiB,KAAK,YAAY,QAAQ,GAAG;AACrE;AAEA,IAAa,gCAAb,cAAmD,OAAO,YAA2C,CAAC,CACpG,iCACA,CAAC,CACH,CAAC,CAAC;CACA,IAAa,UAAkB;EAC7B,OAAO;CACT;AACF;AAEA,MAAa,uBAAuB,OAAO,IAAI,aAAa;CAC1D,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,OAAO,OAAO,KAAK;CAEzB,MAAM,kBAAkB,OAAA,gBAAuC;CAE/D,MAAM,mBAAmB,KAAK,KAAK,KAAK,QAAQ,eAAe,GAAG,SAAS;CAE3E,IAAI,OAAO,GAAG,OAAO,gBAAgB,GACnC,OAAO;MAEP,OAAO,OAAO,IAAI,8BAA8B;AAEpD,CAAC;AAED,MAAa,2BAA2B,MAAM,OAC5C,kBACA,OAAO,IAAI,aAAa;CACtB,MAAM,mBAAmB,OAAO;CAEhC,MAAM,MAAM,OAAO,IAAI,KAAa,gBAAgB;CAEpD,OAAO,EAAE,KAAK,IAAI,IAAI,GAAG,EAAE;AAC7B,CAAC,CACH;AAEqB,yBAAyB,KAC5C,MAAM,QAAQA,OAAqB,CACrC"}
1
+ {"version":3,"file":"ConfectDirectory.mjs","names":["ConvexDirectory.layer"],"sources":["../src/ConfectDirectory.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Path from \"effect/Path\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as ConvexDirectory from \"./ConvexDirectory.js\";\n\nexport class ConfectDirectory extends Context.Service<\n ConfectDirectory,\n { readonly get: Effect.Effect<string> }\n>()(\"@confect/cli/ConfectDirectory\") {\n static readonly get = ConfectDirectory.use((service) => service.get);\n}\n\nexport class ConfectDirectoryNotFoundError extends Schema.TaggedError<\n ConfectDirectoryNotFoundError,\n { readonly brand: unique symbol }\n>()(\"ConfectDirectoryNotFoundError\", {}) {\n override get message(): string {\n return \"Could not find Confect directory\";\n }\n}\n\n/**\n * @internal\n */\nexport const findConfectDirectory = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n\n const convexDirectory = yield* ConvexDirectory.ConvexDirectory.get;\n\n const confectDirectory = path.join(path.dirname(convexDirectory), \"confect\");\n\n if (yield* fs.exists(confectDirectory)) {\n return confectDirectory;\n } else {\n return yield* ConfectDirectoryNotFoundError.make();\n }\n});\n\n/**\n * @internal\n */\nexport const layerFromConvexDirectory = Layer.effect(\n ConfectDirectory,\n Effect.gen(function* () {\n const confectDirectory = yield* findConfectDirectory;\n\n const ref = yield* Ref.make<string>(confectDirectory);\n\n return { get: Ref.get(ref) } as const;\n }),\n);\n\n/**\n * @internal\n */\nexport const layer = layerFromConvexDirectory.pipe(\n Layer.provide(ConvexDirectory.layer),\n);\n"],"mappings":";;;;;;;;;AASA,IAAa,mBAAb,MAAa,yBAAyB,QAAQ,QAG5C,CAAC,CAAC,+BAA+B,CAAC,CAAC;CACnC,OAAgB,MAAM,iBAAiB,KAAK,YAAY,QAAQ,GAAG;AACrE;AAEA,IAAa,gCAAb,cAAmD,OAAO,YAGxD,CAAC,CAAC,iCAAiC,CAAC,CAAC,CAAC,CAAC;CACvC,IAAa,UAAkB;EAC7B,OAAO;CACT;AACF;;;;AAKA,MAAa,uBAAuB,OAAO,IAAI,aAAa;CAC1D,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,OAAO,OAAO,KAAK;CAEzB,MAAM,kBAAkB,OAAA,gBAAuC;CAE/D,MAAM,mBAAmB,KAAK,KAAK,KAAK,QAAQ,eAAe,GAAG,SAAS;CAE3E,IAAI,OAAO,GAAG,OAAO,gBAAgB,GACnC,OAAO;MAEP,OAAO,OAAO,8BAA8B,KAAK;AAErD,CAAC;;;;AAKD,MAAa,2BAA2B,MAAM,OAC5C,kBACA,OAAO,IAAI,aAAa;CACtB,MAAM,mBAAmB,OAAO;CAEhC,MAAM,MAAM,OAAO,IAAI,KAAa,gBAAgB;CAEpD,OAAO,EAAE,KAAK,IAAI,IAAI,GAAG,EAAE;AAC7B,CAAC,CACH;AAKqB,yBAAyB,KAC5C,MAAM,QAAQA,OAAqB,CACrC"}