@gaganref/confect-cli 10.3.1-fork.12 → 10.3.1-fork.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/Bundler.mjs CHANGED
@@ -73,6 +73,27 @@ const resolveExternalEsm = Option.liftThrowable((specifier, importer, conditions
73
73
  }));
74
74
  const resolveModule = (specifier, importer) => Option.orElse(resolveEsm(specifier, importer), () => resolveCjs(specifier, importer));
75
75
  /**
76
+ * The names `file` exports, read by esbuild without evaluating the module, so a
77
+ * test kit that only runs under Vite (`import.meta.glob`) can be checked. None
78
+ * when only running the module would list them: a CommonJS module assigns its
79
+ * exports at run time, and bare imports stay external, so `export *` from
80
+ * another package hides its names.
81
+ */
82
+ const exportNames = (file) => Effect.tryPromise({
83
+ try: () => esbuild.build({
84
+ entryPoints: [file],
85
+ bundle: true,
86
+ packages: "external",
87
+ format: "esm",
88
+ platform: "node",
89
+ write: false,
90
+ metafile: true,
91
+ logLevel: "silent",
92
+ outdir: "out"
93
+ }),
94
+ catch: (cause) => new BundlerError({ cause })
95
+ }).pipe(Effect.map(({ metafile, outputFiles }) => Object.values(metafile.inputs).some(({ format }) => format === "cjs") || outputFiles.some(({ text }) => /^export \* from /m.test(text)) ? Option.none() : Option.some(Object.values(metafile.outputs).flatMap(({ exports }) => exports))));
96
+ /**
76
97
  * Bundles first-party workspace dependencies that `bundle-require` would
77
98
  * otherwise externalize and hand to Node's native ESM resolver. Resolves each
78
99
  * bare specifier and, following symlinks, bundles it when its real path lives
@@ -421,6 +442,6 @@ const importersOfPackage = (bundled, packageName, where) => {
421
442
  return Object.entries(bundled.metafile.inputs).filter(([absolutePath, input]) => where(absolutePath) && input.imports.some((imported) => imported.original === packageName || imported.original?.startsWith(subpathPrefix) === true)).map(([absolutePath]) => absolutePath);
422
443
  };
423
444
  //#endregion
424
- export { bundle, bundleWorkspacePlugin, directlyImports, importersOfPackage, resolveModule, withBatch };
445
+ export { bundle, bundleWorkspacePlugin, directlyImports, exportNames, importersOfPackage, resolveModule, withBatch };
425
446
 
426
447
  //# sourceMappingURL=Bundler.mjs.map
@@ -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 * 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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B,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":[],"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,U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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,8 +1,8 @@
1
1
  import { fromBundlerError } from "../BuildError.mjs";
2
2
  import { ProjectRoot } from "../ProjectRoot.mjs";
3
3
  import { logFileAdded, logFileModified, logFileRemoved, logPending, logSuccess, logWarn } from "../log.mjs";
4
- import { bundle, resolveModule } from "../Bundler.mjs";
5
- import { CallbackPrefixError, ComponentNodeGroupError, ConflictingDocNameError, InvalidConvexConfigError, LegacySchemaFileError, tapAndLog } from "../CodegenError.mjs";
4
+ import { bundle, exportNames, resolveModule } from "../Bundler.mjs";
5
+ import { CallbackPrefixError, ComponentNodeGroupError, ConflictingDocNameError, InvalidConvexConfigError, InvalidDeclarationError, LegacySchemaFileError, tapAndLog } from "../CodegenError.mjs";
6
6
  import { ConvexDirectory } from "../ConvexDirectory.mjs";
7
7
  import { ConfectDirectory } from "../ConfectDirectory.mjs";
8
8
  import { assemblyNodesFromLeaves } from "../SpecAssemblyNode.mjs";
@@ -491,12 +491,31 @@ const logGenerated = (effect) => effect.pipe(Effect.tap(Option.match({
491
491
  * Test-only imports never enter the runtime schema or function wrappers.
492
492
  */
493
493
  const quote = (value) => JSON.stringify(value);
494
+ /**
495
+ * A mount's `testing` kit must be a package specifier, so the generated
496
+ * registry holds no machine-specific path, and must export `register`. A kit
497
+ * whose exports cannot be listed without running it passes here, and
498
+ * `TestConfect.layer` names the mount if it has no `register`.
499
+ */
500
+ const checkTestKit = Effect.fnUntraced(function* (mount, specifier, config, configDisplay) {
501
+ const path = yield* Path.Path;
502
+ const invalid = (problem) => new InvalidDeclarationError({
503
+ declarationPath: "confect/app.ts",
504
+ reason: `the mount ${quote(mount)} names the test kit ${quote(specifier)}${problem}`
505
+ });
506
+ if (specifier.startsWith(".") || path.isAbsolute(specifier)) return yield* invalid("; name it by a package specifier, such as \"<package>/testing\".");
507
+ const resolved = resolveModule(specifier, config);
508
+ if (Option.isNone(resolved)) return yield* invalid(`, which does not resolve from ${configDisplay}.`);
509
+ const exports = yield* exportNames(resolved.value).pipe(Effect.mapError((error) => fromBundlerError(specifier, error)));
510
+ if (Option.isSome(exports) && !exports.value.includes("register")) return yield* invalid(", which does not export `register(t, name)`.");
511
+ });
494
512
  const generateTesting = Effect.fnUntraced(function* (app) {
495
513
  const fs = yield* FileSystem.FileSystem;
496
514
  const path = yield* Path.Path;
497
515
  const confectDirectory = yield* ConfectDirectory.get;
498
516
  const convexDirectory = yield* ConvexDirectory.get;
499
517
  const generated = path.join(confectDirectory, "_generated");
518
+ const configDisplay = path.relative(yield* ProjectRoot.get, path.join(convexDirectory, CONVEX_CONFIG_FILENAME)).split(path.sep).join("/");
500
519
  const relative = (file) => {
501
520
  const value = path.relative(generated, file).split(path.sep).join("/");
502
521
  return value.startsWith(".") ? value : `./${value}`;
@@ -513,50 +532,55 @@ const generateTesting = Effect.fnUntraced(function* (app) {
513
532
  const components = [];
514
533
  const httpMounts = [];
515
534
  const kits = /* @__PURE__ */ new Map();
516
- const visit = Effect.fnUntraced(function* (directory, prefix, kind, parentHttpPrefix) {
535
+ const visit = Effect.fnUntraced(function* (directory, prefix, kind, parentHttpPrefix, registeredByKit) {
517
536
  const config = path.join(directory, CONVEX_CONFIG_FILENAME);
518
537
  if (!(yield* fs.exists(config))) return;
519
538
  const installed = yield* discoverInstalledComponents(config, relative(config), kind);
520
539
  for (const component of installed) {
521
540
  const name = prefix + component.name;
541
+ const mount = prefix === "" ? App.mounts(app).find((declared) => declared.name === component.name) : void 0;
522
542
  const fromPackage = !path.isAbsolute(component.componentDefinitionPath);
543
+ const kitEntry = mount?.testing ?? (fromPackage ? `${component.componentDefinitionPath}/test` : void 0);
523
544
  const resolved = fromPackage ? path.dirname(yield* resolveDefinition(`${component.componentDefinitionPath}/convex.config`, config, path).pipe(Effect.fromOption, Effect.mapError(() => new InvalidConvexConfigError({
524
545
  configPath: relative(config),
525
546
  reason: `Cannot resolve component ${component.componentDefinitionPath} for testing.`
526
547
  })))) : component.componentDefinitionPath;
527
- const localPrefix = prefix === "" ? App.mounts(app).find((mount) => mount.name === component.name)?.httpPrefix : component.httpPrefix;
548
+ const localPrefix = prefix === "" ? mount?.httpPrefix : component.httpPrefix;
528
549
  const httpPrefix = parentHttpPrefix === void 0 || localPrefix === void 0 ? void 0 : `${parentHttpPrefix.replace(/\/+$/, "")}${localPrefix}`.replace(/\/+$/, "") || "/";
529
550
  if (httpPrefix !== void 0 && ((yield* fs.exists(path.join(resolved, "http.ts"))) || (yield* fs.exists(path.join(resolved, "http.js"))))) httpMounts.push(`{ componentPath: ${quote(name)}, httpPrefix: ${quote(httpPrefix)} }`);
530
- let identifier = kits.get(resolved);
531
- if (identifier === void 0) {
532
- const cleaned = name.replaceAll(/[^A-Za-z0-9_$]/g, "_");
533
- const base = /^[A-Za-z_$]/.test(cleaned) ? cleaned : `_${cleaned}`;
534
- identifier = `${base}Kit`;
535
- let schemaIdentifier = `${base}Schema`;
536
- for (let n = 2; identifiers.has(identifier) || identifiers.has(schemaIdentifier); n++) {
537
- identifier = `${base}Kit${n}`;
538
- schemaIdentifier = `${base}Schema${n}`;
539
- }
540
- identifiers.add(identifier);
541
- identifiers.add(schemaIdentifier);
542
- kits.set(resolved, identifier);
543
- if (fromPackage) {
544
- const testEntry = `${component.componentDefinitionPath}/test`;
545
- if (Option.isNone(resolveModule(testEntry, config))) return yield* new InvalidConvexConfigError({
546
- configPath: relative(config),
547
- reason: `the component package ${quote(component.componentDefinitionPath)} has no ${quote(testEntry)} export. Tests register a component from another package through that entry's \`register(t, name)\`.`
548
- });
549
- imports.push(`import * as ${identifier} from ${quote(testEntry)};`);
550
- } else {
551
- imports.push(`import ${schemaIdentifier} from ${quote(relative(path.join(resolved, "schema.js")))};`);
552
- declarations.push(`const ${identifier} = { schema: ${schemaIdentifier}, modules: ${yield* moduleMap(resolved)} };`);
551
+ if (!registeredByKit) {
552
+ const kitKey = kitEntry ?? resolved;
553
+ let identifier = kits.get(kitKey);
554
+ if (identifier === void 0) {
555
+ const cleaned = name.replaceAll(/[^A-Za-z0-9_$]/g, "_");
556
+ const base = /^[A-Za-z_$]/.test(cleaned) ? cleaned : `_${cleaned}`;
557
+ identifier = `${base}Kit`;
558
+ let schemaIdentifier = `${base}Schema`;
559
+ for (let n = 2; identifiers.has(identifier) || identifiers.has(schemaIdentifier); n++) {
560
+ identifier = `${base}Kit${n}`;
561
+ schemaIdentifier = `${base}Schema${n}`;
562
+ }
563
+ identifiers.add(identifier);
564
+ identifiers.add(schemaIdentifier);
565
+ kits.set(kitKey, identifier);
566
+ if (kitEntry === void 0) {
567
+ imports.push(`import ${schemaIdentifier} from ${quote(relative(path.join(resolved, "schema.js")))};`);
568
+ declarations.push(`const ${identifier} = { schema: ${schemaIdentifier}, modules: ${yield* moduleMap(resolved)} };`);
569
+ } else {
570
+ if (mount?.testing !== void 0) yield* checkTestKit(mount.name, mount.testing, config, configDisplay);
571
+ else if (Option.isNone(resolveModule(kitEntry, config))) return yield* new InvalidConvexConfigError({
572
+ configPath: relative(config),
573
+ reason: `the component package ${quote(component.componentDefinitionPath)} has no ${quote(kitEntry)} export. Tests register a component from another package through that entry's \`register(t, name)\`.`
574
+ });
575
+ imports.push(`import * as ${identifier} from ${quote(kitEntry)};`);
576
+ }
553
577
  }
578
+ components.push(`${quote(name)}: ${identifier},`);
554
579
  }
555
- components.push(`${quote(name)}: ${identifier},`);
556
- if (!fromPackage) yield* visit(resolved, `${name}/`, "component", httpPrefix);
580
+ if (!fromPackage) yield* visit(resolved, `${name}/`, "component", httpPrefix, registeredByKit || kitEntry !== void 0);
557
581
  }
558
582
  });
559
- yield* visit(convexDirectory, "", (yield* ConvexDirectory.target).kind, "");
583
+ yield* visit(convexDirectory, "", (yield* ConvexDirectory.target).kind, "", false);
560
584
  yield* writeFileStringAndLog(path.join(generated, "testing.ts"), [
561
585
  "// Generated by `confect codegen`. Test-only; do not import in backend functions.",
562
586
  ...imports,
@@ -1 +1 @@
1
- {"version":3,"file":"codegen.mjs","names":["DirectoryOptions.flags","CodegenError.tapAndLog","DirectoryOptions.layer","TableModule.discover","TableModule.validate","GenerationSnapshot.fromLoadedLeaves","FunctionModule.generateFunctions","EntryPoint.planDeclarations","GenerationSnapshot.update","FunctionModule.applyFunctionPlan","GenerationSnapshot.diff","CodegenError.ComponentNodeGroupError","ConvexConfig.componentName","ConvexConfig.CONVEX_CONFIG_FILENAME","Bundler.bundle","CodegenError.CallbackPrefixError","CodegenError.InvalidConvexConfigError","templates.componentContract","templates.assembledSpec","templates.registeredFunctionsForGroup","FunctionPaths.make","TableModule.TABLES_DIRNAME","templates.id","templates.tableWrapper","templates.runtimeSchema","templates.convexSchema","templates.schema","templates.services","DocName.fromTableName","CodegenError.ConflictingDocNameError","templates.docs","templates.refs","ConvexConfig.discoverInstalledComponents","templates.components","ConvexConfig.typeImportPath","ConvexConfig.resolveDefinition","Bundler.resolveModule"],"sources":["../../src/confect/codegen.ts"],"sourcesContent":["import { App, Callback, Env, type GroupSpec, Spec } from \"@confect/core\";\nimport * as Command from \"effect/cli/Command\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as Array from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as Result from \"effect/Result\";\nimport type * as PlatformError from \"effect/PlatformError\";\nimport type { BuildError } from \"../BuildError.js\";\nimport { pipe } from \"effect/Function\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as Record from \"effect/Record\";\nimport type * as Scope from \"effect/Scope\";\nimport * as Bundler from \"../Bundler.js\";\nimport { fromBundlerError } from \"../BuildError.js\";\nimport * as CodegenError from \"../CodegenError.js\";\nimport { LegacySchemaFileError } from \"../CodegenError.js\";\nimport { ConfectDirectory } from \"../ConfectDirectory.js\";\nimport * as ConvexConfig from \"../ConvexConfig.js\";\nimport { ConvexDirectory } from \"../ConvexDirectory.js\";\nimport * as DirectoryOptions from \"../DirectoryOptions.js\";\nimport * as DocName from \"../DocName.js\";\nimport * as FunctionPaths from \"../FunctionPaths.js\";\nimport * as FunctionModule from \"../FunctionModule.js\";\nimport * as GenerationSnapshot from \"../GenerationSnapshot.js\";\nimport * as EntryPoint from \"../EntryPoint.js\";\nimport type { ImplModulePath } from \"../ImplModulePath.js\";\nimport {\n implPathForSpec,\n loadAll,\n registeredFunctionsRelativePath,\n validateAllImpls,\n withImplFiles,\n type LeafModule,\n type LoadedLeafModule,\n} from \"../LeafModule.js\";\nimport {\n logFileAdded,\n logFileModified,\n logFileRemoved,\n logPending,\n logSuccess,\n logWarn,\n} from \"../log.js\";\nimport { ProjectRoot } from \"../ProjectRoot.js\";\nimport { preserveComponentOutput } from \"../Rollback.js\";\nimport { assemblyNodesFromLeaves } from \"../SpecAssemblyNode.js\";\nimport * as TableModule from \"../TableModule.js\";\nimport * as templates from \"../templates.js\";\nimport {\n generateAuthConfig,\n generateCrons,\n generateHttp,\n removePathIfExists,\n toModuleImportPath,\n touchConvexSchema,\n writeFileStringAndLog,\n} from \"../utils.js\";\nimport { syncDeclaration, syncDeclaredHttp } from \"./declaration.js\";\n\nconst GENERATED_DIRNAME = \"_generated\";\n\nconst isComponent = Effect.map(\n ConvexDirectory.target,\n (target) => target.kind === \"component\",\n);\n\nconst GENERATED_SPEC_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"spec.ts\"),\n);\nconst GENERATED_SCHEMA_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"schema.ts\"),\n);\nconst GENERATED_CONVEX_SCHEMA_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"convexSchema.ts\"),\n);\nconst GENERATED_ID_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"id.ts\"),\n);\nconst GENERATED_COMPONENTS_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"components.ts\"),\n);\nconst GENERATED_TABLES_DIRNAME = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"tables\"),\n);\n\nconst LEGACY_PATHS = Effect.gen(function* () {\n const path = yield* Path.Path;\n\n return [\n \"spec.ts\",\n \"nodeSpec.ts\",\n \"impl.ts\",\n \"nodeImpl.ts\",\n path.join(GENERATED_DIRNAME, \"registeredFunctions.ts\"),\n path.join(GENERATED_DIRNAME, \"nodeRegisteredFunctions.ts\"),\n path.join(GENERATED_DIRNAME, \"impl.ts\"),\n path.join(GENERATED_DIRNAME, \"nodeImpl.ts\"),\n // `_generated/nodeSpec.ts` is not part of the generated output (all groups\n // live in `_generated/spec.ts`); delete any copy left by an older version.\n path.join(GENERATED_DIRNAME, \"nodeSpec.ts\"),\n ];\n});\n\nexport const codegen = Command.make(\"codegen\", DirectoryOptions.flags, () =>\n Effect.gen(function* () {\n yield* logPending(\"Performing initial sync…\");\n yield* codegenHandler.pipe(\n Effect.asVoid,\n Effect.tap(() => logSuccess(\"Generated files are up-to-date\")),\n CodegenError.tapAndLog,\n );\n }),\n).pipe(\n Command.provide(DirectoryOptions.layer),\n Command.withDescription(\n \"Generate `confect/_generated` files and the contents of the `convex` directory (except `tsconfig.json`, and `convex.config.ts` unless `confect/app.ts` declares the backend)\",\n ),\n);\n\nconst runCodegen = Effect.gen(function* () {\n yield* validateComponentConfiguration;\n yield* generateConfectGeneratedDirectory;\n // A declared backend's `convex.config.ts` and manifest come first: the\n // components registry below reads the config, and nothing may validate\n // against a manifest the current declaration did not produce.\n const declared = yield* syncDeclaration;\n // Reject a legacy `confect/schema.ts` up front so the user-facing\n // migration message surfaces before any bundler error from impl\n // validation (each impl imports `_generated/schema.ts`).\n yield* rejectLegacySchemaFile;\n // List `confect/tables/*.ts` (filename-only—no bundling yet) so the\n // `_generated/id.ts` constructor can be emitted *before* we bundle any\n // user-authored table module. Tables import from `_generated/id.ts` for\n // cross-table id refs, so it must exist on disk first.\n const tableModules = yield* TableModule.discover;\n yield* warnIfNoTables(tableModules);\n yield* generateIdConstructor(tableModules);\n // Tables and specs can use bound component IDs and schemas, so their\n // imports need the registry even on a project's first codegen run.\n yield* generateComponents;\n yield* validateCallbackPrefixes(declared);\n // Now that `_generated/id.ts` is on disk, bundle each table module and\n // check its default export is an `UnnamedTable`. Surface diagnostics\n // here (rather than later) so they appear before impl-validation noise.\n yield* TableModule.validate(tableModules);\n yield* validateNoDocNameCollisions(tableModules);\n yield* generateTableWrappers(tableModules);\n yield* removeObsoleteTableWrappers(tableModules);\n yield* generateRuntimeSchema(tableModules);\n const leaves = yield* loadAll;\n yield* rejectComponentNodeGroups(leaves);\n yield* removeLegacyFiles;\n const snapshot = yield* Effect.fromResult(\n GenerationSnapshot.fromLoadedLeaves(leaves),\n );\n yield* generateAssembledSpecs(leaves);\n // `_generated/api.ts`/`nodeApi.ts` are no longer imported by generated or\n // impl code (impls take the database schema from `_generated/schema`\n // directly), so remove any copies left over from earlier versions before\n // impl validation runs.\n yield* Effect.all(\n [\n removeGeneratedApi,\n generateRefs,\n generateComponentContract(tableModules),\n removeGeneratedNodeApi,\n generateDocs(tableModules),\n generateServices,\n generateConvexSchema(tableModules),\n ],\n { concurrency: \"unbounded\" },\n );\n yield* validateAllImpls(leaves);\n yield* generateGroupRegisteredFunctions(leaves);\n yield* removeObsoleteRegisteredFunctions(leaves);\n const [functionPaths] = yield* Effect.all(\n [\n FunctionModule.generateFunctions(snapshot),\n generateConvexSchemaReexport,\n logGenerated(\n Option.match(declared, {\n onNone: () => generateHttp,\n onSome: syncDeclaredHttp,\n }),\n ),\n logGenerated(generateCrons),\n Option.isNone(declared)\n ? logGenerated(generateAuthConfig)\n : Effect.succeedNone,\n ],\n { concurrency: \"unbounded\" },\n );\n if (Option.isSome(declared)) yield* generateTesting(declared.value);\n return {\n functionPaths,\n snapshot,\n };\n});\n\nexport const generateWithSnapshot = runCodegen.pipe(\n Effect.withSpan(\"Cli.codegen\"),\n);\n\nexport const makeCodegenHandler = (\n duringRestore?: Effect.Effect<void, never, Scope.Scope>,\n) =>\n preserveComponentOutput(generateWithSnapshot, duringRestore).pipe(\n Effect.tap(() => touchConvexSchema),\n Effect.map(({ functionPaths }) => ({ functionPaths })),\n );\n\nexport const codegenHandler = makeCodegenHandler();\n\nexport const updateDeclarations = Effect.fn(\"Cli.updateDeclarations\")(\n function* (\n snapshot: GenerationSnapshot.GenerationSnapshot,\n declarations: Array.NonEmptyReadonlyArray<EntryPoint.Declaration>,\n affectedImpls: ReadonlyArray<ImplModulePath>,\n ) {\n const path = yield* Path.Path;\n const { paths, tables } = EntryPoint.planDeclarations(\n declarations,\n affectedImpls,\n path,\n );\n yield* TableModule.validate(tables);\n return yield* withImplFiles(paths, (leaves) =>\n Effect.gen(function* () {\n yield* rejectComponentNodeGroups(leaves);\n const next = yield* Effect.fromResult(\n GenerationSnapshot.update(snapshot, leaves),\n );\n yield* validateAllImpls(leaves);\n yield* generateGroupRegisteredFunctions(leaves);\n yield* FunctionModule.applyFunctionPlan(\n GenerationSnapshot.diff(snapshot, next),\n );\n return next;\n }),\n );\n },\n);\n\n// Convex components cannot run Node.js functions, at any nesting depth.\nconst validateComponentGroupRuntime = (\n group: GroupSpec.AnyWithProps,\n groupPath: string,\n specPath: string,\n): Result.Result<void, CodegenError.ComponentNodeGroupError> =>\n Result.gen(function* () {\n if (group.runtime === \"Node\") {\n return yield* Result.fail(\n new CodegenError.ComponentNodeGroupError({ specPath, groupPath }),\n );\n }\n for (const [name, child] of Object.entries(group.groups)) {\n yield* validateComponentGroupRuntime(\n child,\n `${groupPath}.${name}`,\n specPath,\n );\n }\n });\n\nconst rejectComponentNodeGroups = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LoadedLeafModule>,\n) {\n if ((yield* ConvexDirectory.target).kind === \"app\") return;\n yield* Effect.forEach(leaves, (leaf) =>\n Effect.fromResult(\n validateComponentGroupRuntime(\n leaf.spec,\n leaf.groupPathDot,\n leaf.relativePath,\n ),\n ),\n );\n});\n\nconst validateCallbackPrefixes = Effect.fnUntraced(function* (\n declared: Option.Option<App.Any>,\n) {\n if ((yield* ConvexDirectory.target).kind !== \"component\") return;\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const callbacksPath = path.join(yield* ConfectDirectory.get, \"callbacks.ts\");\n if (!(yield* fs.exists(callbacksPath))) return;\n const name = Option.isSome(declared)\n ? Env.name(App.env(declared.value))\n : yield* ConvexConfig.componentName(\n path.join(\n yield* ConvexDirectory.get,\n ConvexConfig.CONVEX_CONFIG_FILENAME,\n ),\n );\n const { module } = yield* Bundler.bundle(callbacksPath).pipe(\n Effect.mapError((error) => fromBundlerError(\"confect/callbacks.ts\", error)),\n );\n for (const contract of Object.values(module)) {\n if (Callback.isContract(contract) && !contract.id.startsWith(`${name}/`)) {\n return yield* new CodegenError.CallbackPrefixError({\n declarationPath: \"confect/callbacks.ts\",\n contractId: contract.id,\n componentName: name,\n });\n }\n }\n});\n\nconst validateComponentConfiguration = Effect.gen(function* () {\n return yield* Match.value((yield* ConvexDirectory.target).kind).pipe(\n Match.when(\"app\", () => Effect.void),\n Match.when(\"component\", () =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const authPath = path.join(confectDirectory, \"auth.ts\");\n if (yield* fs.exists(authPath)) {\n return yield* new CodegenError.InvalidConvexConfigError({\n configPath: authPath,\n reason:\n \"Components cannot configure application authentication. Pass identity explicitly through function arguments.\",\n });\n }\n }),\n ),\n Match.exhaustive,\n );\n});\n\nconst generateComponentContract = Effect.fnUntraced(function* (\n tables: ReadonlyArray<TableModule.TableModule>,\n) {\n return yield* Match.value((yield* ConvexDirectory.target).kind).pipe(\n Match.when(\"app\", () => Effect.void),\n Match.when(\"component\", () =>\n Effect.gen(function* () {\n const path = yield* Path.Path;\n const directory = yield* ConfectDirectory.get;\n const contents = yield* templates.componentContract({\n tableNames: Array.map(tables, (table) => table.tableName),\n });\n yield* writeFileStringAndLog(\n path.join(directory, GENERATED_DIRNAME, \"component.ts\"),\n contents,\n );\n }),\n ),\n Match.exhaustive,\n );\n});\n\nconst generateConfectGeneratedDirectory = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n if (!(yield* fs.exists(path.join(confectDirectory, \"_generated\")))) {\n yield* fs.makeDirectory(path.join(confectDirectory, \"_generated\"), {\n recursive: true,\n });\n yield* logFileAdded(path.join(confectDirectory, \"_generated\") + \"/\");\n }\n});\n\nconst removeLegacyFiles = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const legacyPaths = yield* LEGACY_PATHS;\n\n yield* Effect.forEach(\n legacyPaths,\n Effect.fnUntraced(function* (relativePath: string) {\n const absolutePath = path.join(confectDirectory, relativePath);\n if (yield* fs.exists(absolutePath)) {\n yield* removePathIfExists(absolutePath);\n yield* logFileRemoved(absolutePath);\n }\n }),\n );\n});\n\nconst generateAssembledSpecs = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LeafModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedSpecPath = yield* GENERATED_SPEC_PATH;\n\n // A single assembled spec holds every group regardless of runtime—a Node\n // group's `makeNode()` lives in its imported leaf spec, so the assembled\n // file is runtime-agnostic. Always emit it (even empty) so downstream\n // readers (`loadGeneratedSpec`, `generateRefs`) always find a spec module.\n const nodes = assemblyNodesFromLeaves(leaves);\n const specContents = yield* templates.assembledSpec({ nodes });\n yield* writeFileStringAndLog(\n path.join(confectDirectory, generatedSpecPath),\n specContents,\n );\n});\n\nconst generateGroupRegisteredFunctions = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LoadedLeafModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n yield* Effect.forEach(\n leaves,\n Effect.fnUntraced(function* (leaf: LoadedLeafModule) {\n const registryRelativePath = yield* registeredFunctionsRelativePath(leaf);\n const registryPath = path.join(\n confectDirectory,\n \"_generated\",\n registryRelativePath,\n );\n const registryDir = path.dirname(registryPath);\n const fs = yield* FileSystem.FileSystem;\n if (!(yield* fs.exists(registryDir))) {\n yield* fs.makeDirectory(registryDir, { recursive: true });\n }\n\n const implRelativePath = yield* implPathForSpec(leaf.relativePath);\n const schemaImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(registryPath),\n path.join(confectDirectory, \"_generated\", \"schema.ts\"),\n ),\n );\n // The group's own leaf spec (sibling of its impl), referenced\n // type-only by the registry to shape its returned record.\n const specImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(registryPath),\n path.join(confectDirectory, leaf.relativePath),\n ),\n );\n const implImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(registryPath),\n path.join(confectDirectory, implRelativePath),\n ),\n );\n\n const contents = yield* templates.registeredFunctionsForGroup({\n spec: leaf.spec,\n schemaImportPath,\n specImportPath,\n implImportPath,\n });\n\n yield* writeFileStringAndLog(registryPath, contents);\n }),\n );\n});\n\nconst removeObsoleteRegisteredFunctions = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LeafModule>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const registryRoot = path.join(\n confectDirectory,\n \"_generated\",\n \"registeredFunctions\",\n );\n\n if (!(yield* fs.exists(registryRoot))) {\n return;\n }\n\n const expected = new Set(\n yield* Effect.forEach(leaves, (leaf) =>\n registeredFunctionsRelativePath(leaf),\n ),\n );\n\n const existing = yield* fs.readDirectory(registryRoot, { recursive: true });\n yield* Effect.forEach(existing, (relativePath) => {\n if (path.extname(relativePath) !== \".ts\") {\n return Effect.void;\n }\n const normalized = path.join(\"registeredFunctions\", relativePath);\n if (!expected.has(normalized)) {\n return Effect.gen(function* () {\n const absolutePath = path.join(registryRoot, relativePath);\n if (yield* fs.exists(absolutePath)) {\n yield* removePathIfExists(absolutePath);\n yield* logFileRemoved(absolutePath);\n }\n });\n }\n return Effect.void;\n });\n});\n\nconst getGeneratedSpecPath = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedSpecPath = yield* GENERATED_SPEC_PATH;\n return path.join(confectDirectory, generatedSpecPath);\n});\n\nconst loadGeneratedSpec = Effect.gen(function* () {\n const specPath = yield* getGeneratedSpecPath;\n const { module: specModule } = yield* Bundler.bundle(specPath);\n const spec = specModule.default;\n\n if (!Spec.isSpec(spec)) {\n return yield* Effect.die(\n new Error(\"_generated/spec.ts does not export a valid Spec\"),\n );\n }\n\n return spec;\n});\n\nconst emptyFunctionPaths = FunctionPaths.FunctionPaths.make(HashSet.empty());\n\nexport const loadPreviousFunctionPaths = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const specPath = yield* getGeneratedSpecPath;\n\n if (!(yield* fs.exists(specPath))) {\n return emptyFunctionPaths;\n }\n\n const specResult = yield* loadGeneratedSpec.pipe(Effect.result);\n\n return Result.match(specResult, {\n onFailure: () => emptyFunctionPaths,\n onSuccess: (spec) => FunctionPaths.make(spec),\n });\n});\n\n/**\n * Remove a now-obsolete `_generated/<name>.ts` if present (and log it), for\n * projects upgrading from a version that still emitted it.\n */\nconst removeObsoleteGeneratedFile = Effect.fnUntraced(function* (\n fileName: string,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const filePath = path.join(confectDirectory, \"_generated\", fileName);\n\n if (yield* fs.exists(filePath)) {\n yield* removePathIfExists(filePath);\n yield* logFileRemoved(filePath);\n }\n});\n\n// `_generated/api.ts` is no longer imported by generated or impl code: impls\n// take the database schema (`_generated/schema`) directly, and per-group\n// registries reference the spec type-only. Remove any stale copy.\nconst removeGeneratedApi = removeObsoleteGeneratedFile(\"api.ts\");\n\n// `_generated/nodeApi.ts` is obsolete for the same reason.\nconst removeGeneratedNodeApi = removeObsoleteGeneratedFile(\"nodeApi.ts\");\n\n/**\n * The user-authored `confect/schema.ts` is no longer supported: codegen now\n * owns both `_generated/schema.ts` (runtime) and `_generated/convexSchema.ts`\n * (deploy), derived from a single scan of `confect/tables/*.ts`. Detect a stray\n * file and fail with a clear migration message—leaving it in place would\n * silently shadow the codegen-owned\n * `_generated/schema.ts`/`_generated/convexSchema.ts`.\n */\nconst rejectLegacySchemaFile = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const legacyPath = path.join(confectDirectory, \"schema.ts\");\n\n if (yield* fs.exists(legacyPath)) {\n return yield* new LegacySchemaFileError({ schemaPath: \"schema.ts\" });\n }\n});\n\n/**\n * Surface a yellow `⚠` warning when codegen sees no tables—either the\n * `confect/tables/` directory is missing or it contains no `.ts` files.\n * Generation still succeeds (emitting an empty `DatabaseSchema` and\n * `defineSchema({})`), since action-only/table-free Confect backends are\n * legal—but the warning catches the much more common case of a typoed directory\n * or files placed under the wrong root.\n */\nconst warnIfNoTables = (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) =>\n tableModules.length === 0\n ? logWarn(\n `No tables discovered in \\`confect/${TableModule.TABLES_DIRNAME}/\\`. ` +\n `Generating an empty schema; add a \\`Table.make(...)\\` module under that ` +\n `directory unless this backend is intentionally tables-free.`,\n )\n : Effect.void;\n\nconst tableModuleBindings = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n generatedFilePath: string,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedDir = path.dirname(generatedFilePath);\n\n const generatedTablesDirname = yield* GENERATED_TABLES_DIRNAME;\n\n return yield* Effect.forEach(\n tableModules,\n Effect.fnUntraced(function* (tableModule: TableModule.TableModule) {\n const wrapperAbsolutePath = path.join(\n confectDirectory,\n generatedTablesDirname,\n `${tableModule.tableName}.ts`,\n );\n const importPath = yield* toModuleImportPath(\n path.relative(generatedDir, wrapperAbsolutePath),\n );\n return {\n importPath,\n tableName: tableModule.tableName,\n };\n }),\n );\n});\n\nconst generateIdConstructor = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedIdPath = yield* GENERATED_ID_PATH;\n const idPath = path.join(confectDirectory, generatedIdPath);\n\n const tableNames = Array.map(\n tableModules,\n (tableModule) => tableModule.tableName,\n );\n const contents = yield* Match.value(yield* ConvexDirectory.target).pipe(\n Match.when({ kind: \"app\" }, () => templates.id({ tableNames })),\n Match.when({ kind: \"component\" }, ({ scope }) =>\n templates.id({ tableNames, scope }),\n ),\n Match.exhaustive,\n );\n\n yield* writeFileStringAndLog(idPath, contents);\n});\n\nconst generateTableWrappers = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedTablesDirname = yield* GENERATED_TABLES_DIRNAME;\n const wrappersDir = path.join(confectDirectory, generatedTablesDirname);\n\n if (!(yield* fs.exists(wrappersDir))) {\n yield* fs.makeDirectory(wrappersDir, { recursive: true });\n }\n\n yield* Effect.forEach(\n tableModules,\n Effect.fnUntraced(function* (tableModule: TableModule.TableModule) {\n const wrapperPath = path.join(\n confectDirectory,\n generatedTablesDirname,\n `${tableModule.tableName}.ts`,\n );\n const unnamedAbsolutePath = path.join(\n confectDirectory,\n tableModule.relativePath,\n );\n const unnamedImportPath = yield* toModuleImportPath(\n path.relative(path.dirname(wrapperPath), unnamedAbsolutePath),\n );\n const contents = yield* templates.tableWrapper({\n tableName: tableModule.tableName,\n unnamedImportPath,\n component: yield* isComponent,\n });\n yield* writeFileStringAndLog(wrapperPath, contents);\n }),\n { concurrency: \"unbounded\" },\n );\n});\n\n/**\n * Remove any stale `_generated/tables/*.ts` wrapper whose source table has been\n * deleted or renamed. Mirrors `removeObsoleteRegisteredFunctions` for the\n * wrapper directory.\n */\nconst removeObsoleteTableWrappers = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedTablesDirname = yield* GENERATED_TABLES_DIRNAME;\n const wrappersDir = path.join(confectDirectory, generatedTablesDirname);\n\n if (!(yield* fs.exists(wrappersDir))) {\n return;\n }\n\n const expected = new Set(\n Array.map(tableModules, (tableModule) => `${tableModule.tableName}.ts`),\n );\n const existing = yield* fs.readDirectory(wrappersDir, { recursive: true });\n yield* Effect.forEach(existing, (entry) => {\n if (path.extname(entry) !== \".ts\") {\n return Effect.void;\n }\n if (!expected.has(entry)) {\n return Effect.gen(function* () {\n const absolutePath = path.join(wrappersDir, entry);\n if (yield* fs.exists(absolutePath)) {\n yield* removePathIfExists(absolutePath);\n yield* logFileRemoved(absolutePath);\n }\n });\n }\n return Effect.void;\n });\n});\n\nconst generateRuntimeSchema = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedSchemaPath = yield* GENERATED_SCHEMA_PATH;\n const schemaPath = path.join(confectDirectory, generatedSchemaPath);\n\n const bindings = yield* tableModuleBindings(tableModules, schemaPath);\n const contents = yield* templates.runtimeSchema({\n tableModules: bindings,\n component: yield* isComponent,\n });\n\n yield* writeFileStringAndLog(schemaPath, contents);\n});\n\nconst generateConvexSchema = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedConvexSchemaPath = yield* GENERATED_CONVEX_SCHEMA_PATH;\n const convexSchemaPath = path.join(\n confectDirectory,\n generatedConvexSchemaPath,\n );\n\n const bindings = yield* tableModuleBindings(tableModules, convexSchemaPath);\n const contents = yield* templates.convexSchema({ tableModules: bindings });\n\n yield* writeFileStringAndLog(convexSchemaPath, contents);\n});\n\nconst generateConvexSchemaReexport = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const convexDirectory = yield* ConvexDirectory.get;\n const generatedConvexSchemaRelativePath = yield* GENERATED_CONVEX_SCHEMA_PATH;\n\n const convexSchemaPath = path.join(convexDirectory, \"schema.ts\");\n const generatedConvexSchemaPath = path.join(\n confectDirectory,\n generatedConvexSchemaRelativePath,\n );\n\n const convexSchemaImportPath = yield* toModuleImportPath(\n path.relative(path.dirname(convexSchemaPath), generatedConvexSchemaPath),\n );\n\n const schemaContents = yield* templates.schema({\n convexSchemaImportPath,\n });\n\n yield* writeFileStringAndLog(convexSchemaPath, schemaContents);\n});\n\nconst generateServices = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const confectGeneratedDirectory = path.join(confectDirectory, \"_generated\");\n\n const servicesPath = path.join(confectGeneratedDirectory, \"services.ts\");\n const generatedSchemaPath = yield* GENERATED_SCHEMA_PATH;\n const schemaImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(servicesPath),\n path.join(confectDirectory, generatedSchemaPath),\n ),\n );\n\n const servicesContentsString = yield* templates.services({\n schemaImportPath,\n component: yield* isComponent,\n });\n\n yield* writeFileStringAndLog(servicesPath, servicesContentsString);\n});\n\n/**\n * Two tables whose names fold to the same PascalCase document type name (e.g.\n * `user_profiles` and `userProfiles` → `UserProfilesDoc`) would emit duplicate\n * interfaces in `_generated/docs.ts`. Catch that up front with a clear error\n * rather than letting `tsc` report a duplicate-identifier later.\n */\nconst validateNoDocNameCollisions = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const collisions = pipe(\n tableModules,\n Array.groupBy((tableModule) =>\n DocName.fromTableName(tableModule.tableName),\n ),\n Record.toEntries,\n Array.filter(([, group]) => group.length > 1),\n Array.map(([docName, group]) => ({\n docName,\n tableNames: Array.map(group, (tableModule) => tableModule.tableName),\n })),\n );\n\n if (Array.isReadonlyArrayNonEmpty(collisions)) {\n return yield* new CodegenError.ConflictingDocNameError({ collisions });\n }\n});\n\nconst generateDocs = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const confectGeneratedDirectory = path.join(confectDirectory, \"_generated\");\n\n const docsPath = path.join(confectGeneratedDirectory, \"docs.ts\");\n const generatedSchemaPath = yield* GENERATED_SCHEMA_PATH;\n const schemaImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(docsPath),\n path.join(confectDirectory, generatedSchemaPath),\n ),\n );\n\n const docsContentsString = yield* templates.docs({\n schemaImportPath,\n tables: Array.map(tableModules, (tableModule) => ({\n tableName: tableModule.tableName,\n docName: DocName.fromTableName(tableModule.tableName),\n })),\n });\n\n yield* writeFileStringAndLog(docsPath, docsContentsString);\n});\n\nconst generateRefs = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const confectGeneratedDirectory = path.join(confectDirectory, \"_generated\");\n const refsPath = path.join(confectGeneratedDirectory, \"refs.ts\");\n const refsDir = path.dirname(refsPath);\n const generatedSpecPath = yield* GENERATED_SPEC_PATH;\n\n const specImportPath = yield* toModuleImportPath(\n path.relative(refsDir, path.join(confectDirectory, generatedSpecPath)),\n );\n\n const refsContents = yield* templates.refs({ specImportPath });\n\n yield* writeFileStringAndLog(refsPath, refsContents);\n});\n\n/**\n * Generate `confect/_generated/components.ts`—the typed registry of Convex\n * components installed in `convex/convex.config.ts` (see\n * {@link templates.components}). The file is emitted even when there is no\n * `convex.config.ts` (as an empty registry) so the import surface stays stable.\n * It must exist before loading tables and specs because they may import bound\n * component IDs and schemas.\n */\nexport const generateComponents = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const convexDirectory = yield* ConvexDirectory.get;\n const projectRoot = yield* ProjectRoot.get;\n\n const confectGeneratedDirectory = path.join(\n confectDirectory,\n GENERATED_DIRNAME,\n );\n const generatedComponentsPath = yield* GENERATED_COMPONENTS_PATH;\n const componentsPath = path.join(confectDirectory, generatedComponentsPath);\n\n const convexConfigPath = path.join(\n convexDirectory,\n ConvexConfig.CONVEX_CONFIG_FILENAME,\n );\n\n const installedComponents = (yield* fs.exists(convexConfigPath))\n ? yield* ConvexConfig.discoverInstalledComponents(\n convexConfigPath,\n path.relative(projectRoot, convexConfigPath),\n (yield* ConvexDirectory.target).kind,\n )\n : [];\n\n const contents = yield* templates.components({\n components: Array.map(\n installedComponents,\n ({ name, componentDefinitionPath }) => ({\n name,\n typeImportPath: ConvexConfig.typeImportPath(\n path,\n componentDefinitionPath,\n confectGeneratedDirectory,\n ),\n }),\n ),\n });\n\n yield* writeFileStringAndLog(componentsPath, contents);\n});\n\nconst logGenerated = <E, R>(\n effect: Effect.Effect<\n Option.Option<{\n readonly change: \"Added\" | \"Modified\" | \"Unchanged\";\n readonly convexFilePath: string;\n }>,\n E,\n R\n >,\n) =>\n effect.pipe(\n Effect.tap(\n Option.match({\n onNone: () => Effect.void,\n onSome: ({ change, convexFilePath }) =>\n Match.value(change).pipe(\n Match.when(\"Added\", () => logFileAdded(convexFilePath)),\n Match.when(\"Modified\", () => logFileModified(convexFilePath)),\n Match.when(\"Unchanged\", () => Effect.void),\n Match.exhaustive,\n ),\n }),\n ),\n );\n\n/**\n * Test-only imports never enter the runtime schema or function wrappers.\n */\nconst quote = (value: string) => JSON.stringify(value);\n\nconst generateTesting = Effect.fnUntraced(function* (app: App.Any) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const convexDirectory = yield* ConvexDirectory.get;\n const generated = path.join(confectDirectory, \"_generated\");\n const relative = (file: string) => {\n const value = path.relative(generated, file).split(path.sep).join(\"/\");\n return value.startsWith(\".\") ? value : `./${value}`;\n };\n const imports = [\n 'import schema from \"./schema.js\";',\n 'import convexSchema from \"./convexSchema.js\";',\n ];\n const moduleMap = Effect.fnUntraced(function* (directory: string) {\n const files = (yield* fs.readDirectory(directory, { recursive: true }))\n .filter(\n (file) =>\n /\\.[cm]?[jt]s$/.test(file) &&\n !file.endsWith(\".d.ts\") &&\n !file.split(path.sep).includes(\"_generated\") &&\n !file.includes(\".config.\"),\n )\n .sort();\n return `{ \"_generated/testing.ts\": () => Promise.resolve({}),\\n${files\n .map((file) => {\n const specifier = relative(path.join(directory, file));\n return `${quote(file.split(path.sep).join(\"/\"))}: () => import(${quote(specifier.replace(/\\.([cm]?)[jt]s$/, \".$1js\"))}),`;\n })\n .join(\"\\n\")}\\n}`;\n });\n const declarations: Array<string> = [];\n const identifiers = new Set([\"schema\", \"convexSchema\"]);\n const components: Array<string> = [];\n const httpMounts: Array<string> = [];\n const kits = new Map<string, string>();\n const visit = Effect.fnUntraced(function* (\n directory: string,\n prefix: string,\n kind: \"app\" | \"component\",\n parentHttpPrefix: string | undefined,\n ): Effect.fn.Return<\n void,\n | PlatformError.PlatformError\n | BuildError\n | CodegenError.InvalidConvexConfigError,\n FileSystem.FileSystem | Path.Path\n > {\n const config = path.join(directory, ConvexConfig.CONVEX_CONFIG_FILENAME);\n if (!(yield* fs.exists(config))) return;\n const installed = yield* ConvexConfig.discoverInstalledComponents(\n config,\n relative(config),\n kind,\n );\n for (const component of installed) {\n const name = prefix + component.name;\n // A bare definition belongs to another package. Its directory is read\n // here but never written out; tests reach it through `<package>/test`.\n const fromPackage = !path.isAbsolute(component.componentDefinitionPath);\n const resolved = fromPackage\n ? path.dirname(\n yield* ConvexConfig.resolveDefinition(\n `${component.componentDefinitionPath}/convex.config`,\n config,\n path,\n ).pipe(\n Effect.fromOption,\n Effect.mapError(\n () =>\n new CodegenError.InvalidConvexConfigError({\n configPath: relative(config),\n reason: `Cannot resolve component ${component.componentDefinitionPath} for testing.`,\n }),\n ),\n ),\n )\n : component.componentDefinitionPath;\n const localPrefix =\n prefix === \"\"\n ? App.mounts(app).find((mount) => mount.name === component.name)\n ?.httpPrefix\n : component.httpPrefix;\n const httpPrefix =\n parentHttpPrefix === undefined || localPrefix === undefined\n ? undefined\n : `${parentHttpPrefix.replace(/\\/+$/, \"\")}${localPrefix}`.replace(\n /\\/+$/,\n \"\",\n ) || \"/\";\n if (\n httpPrefix !== undefined &&\n ((yield* fs.exists(path.join(resolved, \"http.ts\"))) ||\n (yield* fs.exists(path.join(resolved, \"http.js\"))))\n ) {\n httpMounts.push(\n `{ componentPath: ${quote(name)}, httpPrefix: ${quote(httpPrefix)} }`,\n );\n }\n let identifier = kits.get(resolved);\n if (identifier === undefined) {\n const cleaned = name.replaceAll(/[^A-Za-z0-9_$]/g, \"_\");\n const base = /^[A-Za-z_$]/.test(cleaned) ? cleaned : `_${cleaned}`;\n identifier = `${base}Kit`;\n let schemaIdentifier = `${base}Schema`;\n for (\n let n = 2;\n identifiers.has(identifier) || identifiers.has(schemaIdentifier);\n n++\n ) {\n identifier = `${base}Kit${n}`;\n schemaIdentifier = `${base}Schema${n}`;\n }\n identifiers.add(identifier);\n identifiers.add(schemaIdentifier);\n kits.set(resolved, identifier);\n if (fromPackage) {\n const testEntry = `${component.componentDefinitionPath}/test`;\n if (Option.isNone(Bundler.resolveModule(testEntry, config))) {\n return yield* new CodegenError.InvalidConvexConfigError({\n configPath: relative(config),\n reason: `the component package ${quote(component.componentDefinitionPath)} has no ${quote(testEntry)} export. Tests register a component from another package through that entry's \\`register(t, name)\\`.`,\n });\n }\n imports.push(`import * as ${identifier} from ${quote(testEntry)};`);\n } else {\n imports.push(\n `import ${schemaIdentifier} from ${quote(relative(path.join(resolved, \"schema.js\")))};`,\n );\n declarations.push(\n `const ${identifier} = { schema: ${schemaIdentifier}, modules: ${yield* moduleMap(resolved)} };`,\n );\n }\n }\n components.push(`${quote(name)}: ${identifier},`);\n // A package's `register` installs its own children.\n if (!fromPackage) {\n yield* visit(resolved, `${name}/`, \"component\", httpPrefix);\n }\n }\n });\n yield* visit(convexDirectory, \"\", (yield* ConvexDirectory.target).kind, \"\");\n yield* writeFileStringAndLog(\n path.join(generated, \"testing.ts\"),\n [\n \"// Generated by `confect codegen`. Test-only; do not import in backend functions.\",\n ...imports,\n ...declarations,\n `export default { httpMounts: [${httpMounts.join(\",\")}], schema, convexSchema, modules: ${yield* moduleMap(convexDirectory)}, components: {${components.join(\"\\n\")}} };`,\n ].join(\"\\n\"),\n );\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DA,MAAM,oBAAoB;AAE1B,MAAM,cAAc,OAAO,IACzB,gBAAgB,SACf,WAAW,OAAO,SAAS,WAC9B;AAEA,MAAM,sBAAsB,OAAO,IAAI,KAAK,OAAO,SACjD,KAAK,KAAK,mBAAmB,SAAS,CACxC;AACA,MAAM,wBAAwB,OAAO,IAAI,KAAK,OAAO,SACnD,KAAK,KAAK,mBAAmB,WAAW,CAC1C;AACA,MAAM,+BAA+B,OAAO,IAAI,KAAK,OAAO,SAC1D,KAAK,KAAK,mBAAmB,iBAAiB,CAChD;AACA,MAAM,oBAAoB,OAAO,IAAI,KAAK,OAAO,SAC/C,KAAK,KAAK,mBAAmB,OAAO,CACtC;AACA,MAAM,4BAA4B,OAAO,IAAI,KAAK,OAAO,SACvD,KAAK,KAAK,mBAAmB,eAAe,CAC9C;AACA,MAAM,2BAA2B,OAAO,IAAI,KAAK,OAAO,SACtD,KAAK,KAAK,mBAAmB,QAAQ,CACvC;AAEA,MAAM,eAAe,OAAO,IAAI,aAAa;CAC3C,MAAM,OAAO,OAAO,KAAK;CAEzB,OAAO;EACL;EACA;EACA;EACA;EACA,KAAK,KAA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AK,IAAI,aAAa,UAAU;EAE9D;CACF,CAAC;CACD,OAAO,MAAM,iBAAiB,KAAK,OAAO,gBAAgB,OAAA,CAAQ,MAAM,EAAE;CAC1E,OAAO,sBACL,KAAK,KAAK,WAAW,YAAY,GACjC;EACE;EACA,GAAG;EACH,GAAG;EACH,iCAAiC,WAAW,KAAK,GAAG,EAAE,oCAAoC,OAAO,UAAU,eAAe,EAAE,iBAAiB,WAAW,KAAK,IAAI,EAAE;CACrK,CAAC,CAAC,KAAK,IAAI,CACb;AACF,CAAC"}
1
+ {"version":3,"file":"codegen.mjs","names":["DirectoryOptions.flags","CodegenError.tapAndLog","DirectoryOptions.layer","TableModule.discover","TableModule.validate","GenerationSnapshot.fromLoadedLeaves","FunctionModule.generateFunctions","EntryPoint.planDeclarations","GenerationSnapshot.update","FunctionModule.applyFunctionPlan","GenerationSnapshot.diff","CodegenError.ComponentNodeGroupError","ConvexConfig.componentName","ConvexConfig.CONVEX_CONFIG_FILENAME","Bundler.bundle","CodegenError.CallbackPrefixError","CodegenError.InvalidConvexConfigError","templates.componentContract","templates.assembledSpec","templates.registeredFunctionsForGroup","FunctionPaths.make","TableModule.TABLES_DIRNAME","templates.id","templates.tableWrapper","templates.runtimeSchema","templates.convexSchema","templates.schema","templates.services","DocName.fromTableName","CodegenError.ConflictingDocNameError","templates.docs","templates.refs","ConvexConfig.discoverInstalledComponents","templates.components","ConvexConfig.typeImportPath","CodegenError.InvalidDeclarationError","Bundler.resolveModule","Bundler.exportNames","ConvexConfig.resolveDefinition"],"sources":["../../src/confect/codegen.ts"],"sourcesContent":["import { App, Callback, Env, type GroupSpec, Spec } from \"@confect/core\";\nimport * as Command from \"effect/cli/Command\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as Array from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as Result from \"effect/Result\";\nimport type * as PlatformError from \"effect/PlatformError\";\nimport type { BuildError } from \"../BuildError.js\";\nimport { pipe } from \"effect/Function\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as Record from \"effect/Record\";\nimport type * as Scope from \"effect/Scope\";\nimport * as Bundler from \"../Bundler.js\";\nimport { fromBundlerError } from \"../BuildError.js\";\nimport * as CodegenError from \"../CodegenError.js\";\nimport { LegacySchemaFileError } from \"../CodegenError.js\";\nimport { ConfectDirectory } from \"../ConfectDirectory.js\";\nimport * as ConvexConfig from \"../ConvexConfig.js\";\nimport { ConvexDirectory } from \"../ConvexDirectory.js\";\nimport * as DirectoryOptions from \"../DirectoryOptions.js\";\nimport * as DocName from \"../DocName.js\";\nimport * as FunctionPaths from \"../FunctionPaths.js\";\nimport * as FunctionModule from \"../FunctionModule.js\";\nimport * as GenerationSnapshot from \"../GenerationSnapshot.js\";\nimport * as EntryPoint from \"../EntryPoint.js\";\nimport type { ImplModulePath } from \"../ImplModulePath.js\";\nimport {\n implPathForSpec,\n loadAll,\n registeredFunctionsRelativePath,\n validateAllImpls,\n withImplFiles,\n type LeafModule,\n type LoadedLeafModule,\n} from \"../LeafModule.js\";\nimport {\n logFileAdded,\n logFileModified,\n logFileRemoved,\n logPending,\n logSuccess,\n logWarn,\n} from \"../log.js\";\nimport { ProjectRoot } from \"../ProjectRoot.js\";\nimport { preserveComponentOutput } from \"../Rollback.js\";\nimport { assemblyNodesFromLeaves } from \"../SpecAssemblyNode.js\";\nimport * as TableModule from \"../TableModule.js\";\nimport * as templates from \"../templates.js\";\nimport {\n generateAuthConfig,\n generateCrons,\n generateHttp,\n removePathIfExists,\n toModuleImportPath,\n touchConvexSchema,\n writeFileStringAndLog,\n} from \"../utils.js\";\nimport { syncDeclaration, syncDeclaredHttp } from \"./declaration.js\";\n\nconst GENERATED_DIRNAME = \"_generated\";\n\nconst isComponent = Effect.map(\n ConvexDirectory.target,\n (target) => target.kind === \"component\",\n);\n\nconst GENERATED_SPEC_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"spec.ts\"),\n);\nconst GENERATED_SCHEMA_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"schema.ts\"),\n);\nconst GENERATED_CONVEX_SCHEMA_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"convexSchema.ts\"),\n);\nconst GENERATED_ID_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"id.ts\"),\n);\nconst GENERATED_COMPONENTS_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"components.ts\"),\n);\nconst GENERATED_TABLES_DIRNAME = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"tables\"),\n);\n\nconst LEGACY_PATHS = Effect.gen(function* () {\n const path = yield* Path.Path;\n\n return [\n \"spec.ts\",\n \"nodeSpec.ts\",\n \"impl.ts\",\n \"nodeImpl.ts\",\n path.join(GENERATED_DIRNAME, \"registeredFunctions.ts\"),\n path.join(GENERATED_DIRNAME, \"nodeRegisteredFunctions.ts\"),\n path.join(GENERATED_DIRNAME, \"impl.ts\"),\n path.join(GENERATED_DIRNAME, \"nodeImpl.ts\"),\n // `_generated/nodeSpec.ts` is not part of the generated output (all groups\n // live in `_generated/spec.ts`); delete any copy left by an older version.\n path.join(GENERATED_DIRNAME, \"nodeSpec.ts\"),\n ];\n});\n\nexport const codegen = Command.make(\"codegen\", DirectoryOptions.flags, () =>\n Effect.gen(function* () {\n yield* logPending(\"Performing initial sync…\");\n yield* codegenHandler.pipe(\n Effect.asVoid,\n Effect.tap(() => logSuccess(\"Generated files are up-to-date\")),\n CodegenError.tapAndLog,\n );\n }),\n).pipe(\n Command.provide(DirectoryOptions.layer),\n Command.withDescription(\n \"Generate `confect/_generated` files and the contents of the `convex` directory (except `tsconfig.json`, and `convex.config.ts` unless `confect/app.ts` declares the backend)\",\n ),\n);\n\nconst runCodegen = Effect.gen(function* () {\n yield* validateComponentConfiguration;\n yield* generateConfectGeneratedDirectory;\n // A declared backend's `convex.config.ts` and manifest come first: the\n // components registry below reads the config, and nothing may validate\n // against a manifest the current declaration did not produce.\n const declared = yield* syncDeclaration;\n // Reject a legacy `confect/schema.ts` up front so the user-facing\n // migration message surfaces before any bundler error from impl\n // validation (each impl imports `_generated/schema.ts`).\n yield* rejectLegacySchemaFile;\n // List `confect/tables/*.ts` (filename-only—no bundling yet) so the\n // `_generated/id.ts` constructor can be emitted *before* we bundle any\n // user-authored table module. Tables import from `_generated/id.ts` for\n // cross-table id refs, so it must exist on disk first.\n const tableModules = yield* TableModule.discover;\n yield* warnIfNoTables(tableModules);\n yield* generateIdConstructor(tableModules);\n // Tables and specs can use bound component IDs and schemas, so their\n // imports need the registry even on a project's first codegen run.\n yield* generateComponents;\n yield* validateCallbackPrefixes(declared);\n // Now that `_generated/id.ts` is on disk, bundle each table module and\n // check its default export is an `UnnamedTable`. Surface diagnostics\n // here (rather than later) so they appear before impl-validation noise.\n yield* TableModule.validate(tableModules);\n yield* validateNoDocNameCollisions(tableModules);\n yield* generateTableWrappers(tableModules);\n yield* removeObsoleteTableWrappers(tableModules);\n yield* generateRuntimeSchema(tableModules);\n const leaves = yield* loadAll;\n yield* rejectComponentNodeGroups(leaves);\n yield* removeLegacyFiles;\n const snapshot = yield* Effect.fromResult(\n GenerationSnapshot.fromLoadedLeaves(leaves),\n );\n yield* generateAssembledSpecs(leaves);\n // `_generated/api.ts`/`nodeApi.ts` are no longer imported by generated or\n // impl code (impls take the database schema from `_generated/schema`\n // directly), so remove any copies left over from earlier versions before\n // impl validation runs.\n yield* Effect.all(\n [\n removeGeneratedApi,\n generateRefs,\n generateComponentContract(tableModules),\n removeGeneratedNodeApi,\n generateDocs(tableModules),\n generateServices,\n generateConvexSchema(tableModules),\n ],\n { concurrency: \"unbounded\" },\n );\n yield* validateAllImpls(leaves);\n yield* generateGroupRegisteredFunctions(leaves);\n yield* removeObsoleteRegisteredFunctions(leaves);\n const [functionPaths] = yield* Effect.all(\n [\n FunctionModule.generateFunctions(snapshot),\n generateConvexSchemaReexport,\n logGenerated(\n Option.match(declared, {\n onNone: () => generateHttp,\n onSome: syncDeclaredHttp,\n }),\n ),\n logGenerated(generateCrons),\n Option.isNone(declared)\n ? logGenerated(generateAuthConfig)\n : Effect.succeedNone,\n ],\n { concurrency: \"unbounded\" },\n );\n if (Option.isSome(declared)) yield* generateTesting(declared.value);\n return {\n functionPaths,\n snapshot,\n };\n});\n\nexport const generateWithSnapshot = runCodegen.pipe(\n Effect.withSpan(\"Cli.codegen\"),\n);\n\nexport const makeCodegenHandler = (\n duringRestore?: Effect.Effect<void, never, Scope.Scope>,\n) =>\n preserveComponentOutput(generateWithSnapshot, duringRestore).pipe(\n Effect.tap(() => touchConvexSchema),\n Effect.map(({ functionPaths }) => ({ functionPaths })),\n );\n\nexport const codegenHandler = makeCodegenHandler();\n\nexport const updateDeclarations = Effect.fn(\"Cli.updateDeclarations\")(\n function* (\n snapshot: GenerationSnapshot.GenerationSnapshot,\n declarations: Array.NonEmptyReadonlyArray<EntryPoint.Declaration>,\n affectedImpls: ReadonlyArray<ImplModulePath>,\n ) {\n const path = yield* Path.Path;\n const { paths, tables } = EntryPoint.planDeclarations(\n declarations,\n affectedImpls,\n path,\n );\n yield* TableModule.validate(tables);\n return yield* withImplFiles(paths, (leaves) =>\n Effect.gen(function* () {\n yield* rejectComponentNodeGroups(leaves);\n const next = yield* Effect.fromResult(\n GenerationSnapshot.update(snapshot, leaves),\n );\n yield* validateAllImpls(leaves);\n yield* generateGroupRegisteredFunctions(leaves);\n yield* FunctionModule.applyFunctionPlan(\n GenerationSnapshot.diff(snapshot, next),\n );\n return next;\n }),\n );\n },\n);\n\n// Convex components cannot run Node.js functions, at any nesting depth.\nconst validateComponentGroupRuntime = (\n group: GroupSpec.AnyWithProps,\n groupPath: string,\n specPath: string,\n): Result.Result<void, CodegenError.ComponentNodeGroupError> =>\n Result.gen(function* () {\n if (group.runtime === \"Node\") {\n return yield* Result.fail(\n new CodegenError.ComponentNodeGroupError({ specPath, groupPath }),\n );\n }\n for (const [name, child] of Object.entries(group.groups)) {\n yield* validateComponentGroupRuntime(\n child,\n `${groupPath}.${name}`,\n specPath,\n );\n }\n });\n\nconst rejectComponentNodeGroups = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LoadedLeafModule>,\n) {\n if ((yield* ConvexDirectory.target).kind === \"app\") return;\n yield* Effect.forEach(leaves, (leaf) =>\n Effect.fromResult(\n validateComponentGroupRuntime(\n leaf.spec,\n leaf.groupPathDot,\n leaf.relativePath,\n ),\n ),\n );\n});\n\nconst validateCallbackPrefixes = Effect.fnUntraced(function* (\n declared: Option.Option<App.Any>,\n) {\n if ((yield* ConvexDirectory.target).kind !== \"component\") return;\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const callbacksPath = path.join(yield* ConfectDirectory.get, \"callbacks.ts\");\n if (!(yield* fs.exists(callbacksPath))) return;\n const name = Option.isSome(declared)\n ? Env.name(App.env(declared.value))\n : yield* ConvexConfig.componentName(\n path.join(\n yield* ConvexDirectory.get,\n ConvexConfig.CONVEX_CONFIG_FILENAME,\n ),\n );\n const { module } = yield* Bundler.bundle(callbacksPath).pipe(\n Effect.mapError((error) => fromBundlerError(\"confect/callbacks.ts\", error)),\n );\n for (const contract of Object.values(module)) {\n if (Callback.isContract(contract) && !contract.id.startsWith(`${name}/`)) {\n return yield* new CodegenError.CallbackPrefixError({\n declarationPath: \"confect/callbacks.ts\",\n contractId: contract.id,\n componentName: name,\n });\n }\n }\n});\n\nconst validateComponentConfiguration = Effect.gen(function* () {\n return yield* Match.value((yield* ConvexDirectory.target).kind).pipe(\n Match.when(\"app\", () => Effect.void),\n Match.when(\"component\", () =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const authPath = path.join(confectDirectory, \"auth.ts\");\n if (yield* fs.exists(authPath)) {\n return yield* new CodegenError.InvalidConvexConfigError({\n configPath: authPath,\n reason:\n \"Components cannot configure application authentication. Pass identity explicitly through function arguments.\",\n });\n }\n }),\n ),\n Match.exhaustive,\n );\n});\n\nconst generateComponentContract = Effect.fnUntraced(function* (\n tables: ReadonlyArray<TableModule.TableModule>,\n) {\n return yield* Match.value((yield* ConvexDirectory.target).kind).pipe(\n Match.when(\"app\", () => Effect.void),\n Match.when(\"component\", () =>\n Effect.gen(function* () {\n const path = yield* Path.Path;\n const directory = yield* ConfectDirectory.get;\n const contents = yield* templates.componentContract({\n tableNames: Array.map(tables, (table) => table.tableName),\n });\n yield* writeFileStringAndLog(\n path.join(directory, GENERATED_DIRNAME, \"component.ts\"),\n contents,\n );\n }),\n ),\n Match.exhaustive,\n );\n});\n\nconst generateConfectGeneratedDirectory = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n if (!(yield* fs.exists(path.join(confectDirectory, \"_generated\")))) {\n yield* fs.makeDirectory(path.join(confectDirectory, \"_generated\"), {\n recursive: true,\n });\n yield* logFileAdded(path.join(confectDirectory, \"_generated\") + \"/\");\n }\n});\n\nconst removeLegacyFiles = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const legacyPaths = yield* LEGACY_PATHS;\n\n yield* Effect.forEach(\n legacyPaths,\n Effect.fnUntraced(function* (relativePath: string) {\n const absolutePath = path.join(confectDirectory, relativePath);\n if (yield* fs.exists(absolutePath)) {\n yield* removePathIfExists(absolutePath);\n yield* logFileRemoved(absolutePath);\n }\n }),\n );\n});\n\nconst generateAssembledSpecs = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LeafModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedSpecPath = yield* GENERATED_SPEC_PATH;\n\n // A single assembled spec holds every group regardless of runtime—a Node\n // group's `makeNode()` lives in its imported leaf spec, so the assembled\n // file is runtime-agnostic. Always emit it (even empty) so downstream\n // readers (`loadGeneratedSpec`, `generateRefs`) always find a spec module.\n const nodes = assemblyNodesFromLeaves(leaves);\n const specContents = yield* templates.assembledSpec({ nodes });\n yield* writeFileStringAndLog(\n path.join(confectDirectory, generatedSpecPath),\n specContents,\n );\n});\n\nconst generateGroupRegisteredFunctions = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LoadedLeafModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n yield* Effect.forEach(\n leaves,\n Effect.fnUntraced(function* (leaf: LoadedLeafModule) {\n const registryRelativePath = yield* registeredFunctionsRelativePath(leaf);\n const registryPath = path.join(\n confectDirectory,\n \"_generated\",\n registryRelativePath,\n );\n const registryDir = path.dirname(registryPath);\n const fs = yield* FileSystem.FileSystem;\n if (!(yield* fs.exists(registryDir))) {\n yield* fs.makeDirectory(registryDir, { recursive: true });\n }\n\n const implRelativePath = yield* implPathForSpec(leaf.relativePath);\n const schemaImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(registryPath),\n path.join(confectDirectory, \"_generated\", \"schema.ts\"),\n ),\n );\n // The group's own leaf spec (sibling of its impl), referenced\n // type-only by the registry to shape its returned record.\n const specImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(registryPath),\n path.join(confectDirectory, leaf.relativePath),\n ),\n );\n const implImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(registryPath),\n path.join(confectDirectory, implRelativePath),\n ),\n );\n\n const contents = yield* templates.registeredFunctionsForGroup({\n spec: leaf.spec,\n schemaImportPath,\n specImportPath,\n implImportPath,\n });\n\n yield* writeFileStringAndLog(registryPath, contents);\n }),\n );\n});\n\nconst removeObsoleteRegisteredFunctions = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LeafModule>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const registryRoot = path.join(\n confectDirectory,\n \"_generated\",\n \"registeredFunctions\",\n );\n\n if (!(yield* fs.exists(registryRoot))) {\n return;\n }\n\n const expected = new Set(\n yield* Effect.forEach(leaves, (leaf) =>\n registeredFunctionsRelativePath(leaf),\n ),\n );\n\n const existing = yield* fs.readDirectory(registryRoot, { recursive: true });\n yield* Effect.forEach(existing, (relativePath) => {\n if (path.extname(relativePath) !== \".ts\") {\n return Effect.void;\n }\n const normalized = path.join(\"registeredFunctions\", relativePath);\n if (!expected.has(normalized)) {\n return Effect.gen(function* () {\n const absolutePath = path.join(registryRoot, relativePath);\n if (yield* fs.exists(absolutePath)) {\n yield* removePathIfExists(absolutePath);\n yield* logFileRemoved(absolutePath);\n }\n });\n }\n return Effect.void;\n });\n});\n\nconst getGeneratedSpecPath = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedSpecPath = yield* GENERATED_SPEC_PATH;\n return path.join(confectDirectory, generatedSpecPath);\n});\n\nconst loadGeneratedSpec = Effect.gen(function* () {\n const specPath = yield* getGeneratedSpecPath;\n const { module: specModule } = yield* Bundler.bundle(specPath);\n const spec = specModule.default;\n\n if (!Spec.isSpec(spec)) {\n return yield* Effect.die(\n new Error(\"_generated/spec.ts does not export a valid Spec\"),\n );\n }\n\n return spec;\n});\n\nconst emptyFunctionPaths = FunctionPaths.FunctionPaths.make(HashSet.empty());\n\nexport const loadPreviousFunctionPaths = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const specPath = yield* getGeneratedSpecPath;\n\n if (!(yield* fs.exists(specPath))) {\n return emptyFunctionPaths;\n }\n\n const specResult = yield* loadGeneratedSpec.pipe(Effect.result);\n\n return Result.match(specResult, {\n onFailure: () => emptyFunctionPaths,\n onSuccess: (spec) => FunctionPaths.make(spec),\n });\n});\n\n/**\n * Remove a now-obsolete `_generated/<name>.ts` if present (and log it), for\n * projects upgrading from a version that still emitted it.\n */\nconst removeObsoleteGeneratedFile = Effect.fnUntraced(function* (\n fileName: string,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const filePath = path.join(confectDirectory, \"_generated\", fileName);\n\n if (yield* fs.exists(filePath)) {\n yield* removePathIfExists(filePath);\n yield* logFileRemoved(filePath);\n }\n});\n\n// `_generated/api.ts` is no longer imported by generated or impl code: impls\n// take the database schema (`_generated/schema`) directly, and per-group\n// registries reference the spec type-only. Remove any stale copy.\nconst removeGeneratedApi = removeObsoleteGeneratedFile(\"api.ts\");\n\n// `_generated/nodeApi.ts` is obsolete for the same reason.\nconst removeGeneratedNodeApi = removeObsoleteGeneratedFile(\"nodeApi.ts\");\n\n/**\n * The user-authored `confect/schema.ts` is no longer supported: codegen now\n * owns both `_generated/schema.ts` (runtime) and `_generated/convexSchema.ts`\n * (deploy), derived from a single scan of `confect/tables/*.ts`. Detect a stray\n * file and fail with a clear migration message—leaving it in place would\n * silently shadow the codegen-owned\n * `_generated/schema.ts`/`_generated/convexSchema.ts`.\n */\nconst rejectLegacySchemaFile = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const legacyPath = path.join(confectDirectory, \"schema.ts\");\n\n if (yield* fs.exists(legacyPath)) {\n return yield* new LegacySchemaFileError({ schemaPath: \"schema.ts\" });\n }\n});\n\n/**\n * Surface a yellow `⚠` warning when codegen sees no tables—either the\n * `confect/tables/` directory is missing or it contains no `.ts` files.\n * Generation still succeeds (emitting an empty `DatabaseSchema` and\n * `defineSchema({})`), since action-only/table-free Confect backends are\n * legal—but the warning catches the much more common case of a typoed directory\n * or files placed under the wrong root.\n */\nconst warnIfNoTables = (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) =>\n tableModules.length === 0\n ? logWarn(\n `No tables discovered in \\`confect/${TableModule.TABLES_DIRNAME}/\\`. ` +\n `Generating an empty schema; add a \\`Table.make(...)\\` module under that ` +\n `directory unless this backend is intentionally tables-free.`,\n )\n : Effect.void;\n\nconst tableModuleBindings = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n generatedFilePath: string,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedDir = path.dirname(generatedFilePath);\n\n const generatedTablesDirname = yield* GENERATED_TABLES_DIRNAME;\n\n return yield* Effect.forEach(\n tableModules,\n Effect.fnUntraced(function* (tableModule: TableModule.TableModule) {\n const wrapperAbsolutePath = path.join(\n confectDirectory,\n generatedTablesDirname,\n `${tableModule.tableName}.ts`,\n );\n const importPath = yield* toModuleImportPath(\n path.relative(generatedDir, wrapperAbsolutePath),\n );\n return {\n importPath,\n tableName: tableModule.tableName,\n };\n }),\n );\n});\n\nconst generateIdConstructor = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedIdPath = yield* GENERATED_ID_PATH;\n const idPath = path.join(confectDirectory, generatedIdPath);\n\n const tableNames = Array.map(\n tableModules,\n (tableModule) => tableModule.tableName,\n );\n const contents = yield* Match.value(yield* ConvexDirectory.target).pipe(\n Match.when({ kind: \"app\" }, () => templates.id({ tableNames })),\n Match.when({ kind: \"component\" }, ({ scope }) =>\n templates.id({ tableNames, scope }),\n ),\n Match.exhaustive,\n );\n\n yield* writeFileStringAndLog(idPath, contents);\n});\n\nconst generateTableWrappers = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedTablesDirname = yield* GENERATED_TABLES_DIRNAME;\n const wrappersDir = path.join(confectDirectory, generatedTablesDirname);\n\n if (!(yield* fs.exists(wrappersDir))) {\n yield* fs.makeDirectory(wrappersDir, { recursive: true });\n }\n\n yield* Effect.forEach(\n tableModules,\n Effect.fnUntraced(function* (tableModule: TableModule.TableModule) {\n const wrapperPath = path.join(\n confectDirectory,\n generatedTablesDirname,\n `${tableModule.tableName}.ts`,\n );\n const unnamedAbsolutePath = path.join(\n confectDirectory,\n tableModule.relativePath,\n );\n const unnamedImportPath = yield* toModuleImportPath(\n path.relative(path.dirname(wrapperPath), unnamedAbsolutePath),\n );\n const contents = yield* templates.tableWrapper({\n tableName: tableModule.tableName,\n unnamedImportPath,\n component: yield* isComponent,\n });\n yield* writeFileStringAndLog(wrapperPath, contents);\n }),\n { concurrency: \"unbounded\" },\n );\n});\n\n/**\n * Remove any stale `_generated/tables/*.ts` wrapper whose source table has been\n * deleted or renamed. Mirrors `removeObsoleteRegisteredFunctions` for the\n * wrapper directory.\n */\nconst removeObsoleteTableWrappers = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedTablesDirname = yield* GENERATED_TABLES_DIRNAME;\n const wrappersDir = path.join(confectDirectory, generatedTablesDirname);\n\n if (!(yield* fs.exists(wrappersDir))) {\n return;\n }\n\n const expected = new Set(\n Array.map(tableModules, (tableModule) => `${tableModule.tableName}.ts`),\n );\n const existing = yield* fs.readDirectory(wrappersDir, { recursive: true });\n yield* Effect.forEach(existing, (entry) => {\n if (path.extname(entry) !== \".ts\") {\n return Effect.void;\n }\n if (!expected.has(entry)) {\n return Effect.gen(function* () {\n const absolutePath = path.join(wrappersDir, entry);\n if (yield* fs.exists(absolutePath)) {\n yield* removePathIfExists(absolutePath);\n yield* logFileRemoved(absolutePath);\n }\n });\n }\n return Effect.void;\n });\n});\n\nconst generateRuntimeSchema = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedSchemaPath = yield* GENERATED_SCHEMA_PATH;\n const schemaPath = path.join(confectDirectory, generatedSchemaPath);\n\n const bindings = yield* tableModuleBindings(tableModules, schemaPath);\n const contents = yield* templates.runtimeSchema({\n tableModules: bindings,\n component: yield* isComponent,\n });\n\n yield* writeFileStringAndLog(schemaPath, contents);\n});\n\nconst generateConvexSchema = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedConvexSchemaPath = yield* GENERATED_CONVEX_SCHEMA_PATH;\n const convexSchemaPath = path.join(\n confectDirectory,\n generatedConvexSchemaPath,\n );\n\n const bindings = yield* tableModuleBindings(tableModules, convexSchemaPath);\n const contents = yield* templates.convexSchema({ tableModules: bindings });\n\n yield* writeFileStringAndLog(convexSchemaPath, contents);\n});\n\nconst generateConvexSchemaReexport = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const convexDirectory = yield* ConvexDirectory.get;\n const generatedConvexSchemaRelativePath = yield* GENERATED_CONVEX_SCHEMA_PATH;\n\n const convexSchemaPath = path.join(convexDirectory, \"schema.ts\");\n const generatedConvexSchemaPath = path.join(\n confectDirectory,\n generatedConvexSchemaRelativePath,\n );\n\n const convexSchemaImportPath = yield* toModuleImportPath(\n path.relative(path.dirname(convexSchemaPath), generatedConvexSchemaPath),\n );\n\n const schemaContents = yield* templates.schema({\n convexSchemaImportPath,\n });\n\n yield* writeFileStringAndLog(convexSchemaPath, schemaContents);\n});\n\nconst generateServices = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const confectGeneratedDirectory = path.join(confectDirectory, \"_generated\");\n\n const servicesPath = path.join(confectGeneratedDirectory, \"services.ts\");\n const generatedSchemaPath = yield* GENERATED_SCHEMA_PATH;\n const schemaImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(servicesPath),\n path.join(confectDirectory, generatedSchemaPath),\n ),\n );\n\n const servicesContentsString = yield* templates.services({\n schemaImportPath,\n component: yield* isComponent,\n });\n\n yield* writeFileStringAndLog(servicesPath, servicesContentsString);\n});\n\n/**\n * Two tables whose names fold to the same PascalCase document type name (e.g.\n * `user_profiles` and `userProfiles` → `UserProfilesDoc`) would emit duplicate\n * interfaces in `_generated/docs.ts`. Catch that up front with a clear error\n * rather than letting `tsc` report a duplicate-identifier later.\n */\nconst validateNoDocNameCollisions = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const collisions = pipe(\n tableModules,\n Array.groupBy((tableModule) =>\n DocName.fromTableName(tableModule.tableName),\n ),\n Record.toEntries,\n Array.filter(([, group]) => group.length > 1),\n Array.map(([docName, group]) => ({\n docName,\n tableNames: Array.map(group, (tableModule) => tableModule.tableName),\n })),\n );\n\n if (Array.isReadonlyArrayNonEmpty(collisions)) {\n return yield* new CodegenError.ConflictingDocNameError({ collisions });\n }\n});\n\nconst generateDocs = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const confectGeneratedDirectory = path.join(confectDirectory, \"_generated\");\n\n const docsPath = path.join(confectGeneratedDirectory, \"docs.ts\");\n const generatedSchemaPath = yield* GENERATED_SCHEMA_PATH;\n const schemaImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(docsPath),\n path.join(confectDirectory, generatedSchemaPath),\n ),\n );\n\n const docsContentsString = yield* templates.docs({\n schemaImportPath,\n tables: Array.map(tableModules, (tableModule) => ({\n tableName: tableModule.tableName,\n docName: DocName.fromTableName(tableModule.tableName),\n })),\n });\n\n yield* writeFileStringAndLog(docsPath, docsContentsString);\n});\n\nconst generateRefs = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const confectGeneratedDirectory = path.join(confectDirectory, \"_generated\");\n const refsPath = path.join(confectGeneratedDirectory, \"refs.ts\");\n const refsDir = path.dirname(refsPath);\n const generatedSpecPath = yield* GENERATED_SPEC_PATH;\n\n const specImportPath = yield* toModuleImportPath(\n path.relative(refsDir, path.join(confectDirectory, generatedSpecPath)),\n );\n\n const refsContents = yield* templates.refs({ specImportPath });\n\n yield* writeFileStringAndLog(refsPath, refsContents);\n});\n\n/**\n * Generate `confect/_generated/components.ts`—the typed registry of Convex\n * components installed in `convex/convex.config.ts` (see\n * {@link templates.components}). The file is emitted even when there is no\n * `convex.config.ts` (as an empty registry) so the import surface stays stable.\n * It must exist before loading tables and specs because they may import bound\n * component IDs and schemas.\n */\nexport const generateComponents = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const convexDirectory = yield* ConvexDirectory.get;\n const projectRoot = yield* ProjectRoot.get;\n\n const confectGeneratedDirectory = path.join(\n confectDirectory,\n GENERATED_DIRNAME,\n );\n const generatedComponentsPath = yield* GENERATED_COMPONENTS_PATH;\n const componentsPath = path.join(confectDirectory, generatedComponentsPath);\n\n const convexConfigPath = path.join(\n convexDirectory,\n ConvexConfig.CONVEX_CONFIG_FILENAME,\n );\n\n const installedComponents = (yield* fs.exists(convexConfigPath))\n ? yield* ConvexConfig.discoverInstalledComponents(\n convexConfigPath,\n path.relative(projectRoot, convexConfigPath),\n (yield* ConvexDirectory.target).kind,\n )\n : [];\n\n const contents = yield* templates.components({\n components: Array.map(\n installedComponents,\n ({ name, componentDefinitionPath }) => ({\n name,\n typeImportPath: ConvexConfig.typeImportPath(\n path,\n componentDefinitionPath,\n confectGeneratedDirectory,\n ),\n }),\n ),\n });\n\n yield* writeFileStringAndLog(componentsPath, contents);\n});\n\nconst logGenerated = <E, R>(\n effect: Effect.Effect<\n Option.Option<{\n readonly change: \"Added\" | \"Modified\" | \"Unchanged\";\n readonly convexFilePath: string;\n }>,\n E,\n R\n >,\n) =>\n effect.pipe(\n Effect.tap(\n Option.match({\n onNone: () => Effect.void,\n onSome: ({ change, convexFilePath }) =>\n Match.value(change).pipe(\n Match.when(\"Added\", () => logFileAdded(convexFilePath)),\n Match.when(\"Modified\", () => logFileModified(convexFilePath)),\n Match.when(\"Unchanged\", () => Effect.void),\n Match.exhaustive,\n ),\n }),\n ),\n );\n\n/**\n * Test-only imports never enter the runtime schema or function wrappers.\n */\nconst quote = (value: string) => JSON.stringify(value);\n\n/**\n * A mount's `testing` kit must be a package specifier, so the generated\n * registry holds no machine-specific path, and must export `register`. A kit\n * whose exports cannot be listed without running it passes here, and\n * `TestConfect.layer` names the mount if it has no `register`.\n */\nconst checkTestKit = Effect.fnUntraced(function* (\n mount: string,\n specifier: string,\n config: string,\n configDisplay: string,\n) {\n const path = yield* Path.Path;\n const invalid = (problem: string) =>\n new CodegenError.InvalidDeclarationError({\n declarationPath: \"confect/app.ts\",\n reason: `the mount ${quote(mount)} names the test kit ${quote(specifier)}${problem}`,\n });\n if (specifier.startsWith(\".\") || path.isAbsolute(specifier)) {\n return yield* invalid(\n '; name it by a package specifier, such as \"<package>/testing\".',\n );\n }\n const resolved = Bundler.resolveModule(specifier, config);\n if (Option.isNone(resolved)) {\n return yield* invalid(`, which does not resolve from ${configDisplay}.`);\n }\n const exports = yield* Bundler.exportNames(resolved.value).pipe(\n Effect.mapError((error) => fromBundlerError(specifier, error)),\n );\n if (Option.isSome(exports) && !exports.value.includes(\"register\")) {\n return yield* invalid(\", which does not export `register(t, name)`.\");\n }\n});\n\nconst generateTesting = Effect.fnUntraced(function* (app: App.Any) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const convexDirectory = yield* ConvexDirectory.get;\n const generated = path.join(confectDirectory, \"_generated\");\n const configDisplay = path\n .relative(\n yield* ProjectRoot.get,\n path.join(convexDirectory, ConvexConfig.CONVEX_CONFIG_FILENAME),\n )\n .split(path.sep)\n .join(\"/\");\n const relative = (file: string) => {\n const value = path.relative(generated, file).split(path.sep).join(\"/\");\n return value.startsWith(\".\") ? value : `./${value}`;\n };\n const imports = [\n 'import schema from \"./schema.js\";',\n 'import convexSchema from \"./convexSchema.js\";',\n ];\n const moduleMap = Effect.fnUntraced(function* (directory: string) {\n const files = (yield* fs.readDirectory(directory, { recursive: true }))\n .filter(\n (file) =>\n /\\.[cm]?[jt]s$/.test(file) &&\n !file.endsWith(\".d.ts\") &&\n !file.split(path.sep).includes(\"_generated\") &&\n !file.includes(\".config.\"),\n )\n .sort();\n return `{ \"_generated/testing.ts\": () => Promise.resolve({}),\\n${files\n .map((file) => {\n const specifier = relative(path.join(directory, file));\n return `${quote(file.split(path.sep).join(\"/\"))}: () => import(${quote(specifier.replace(/\\.([cm]?)[jt]s$/, \".$1js\"))}),`;\n })\n .join(\"\\n\")}\\n}`;\n });\n const declarations: Array<string> = [];\n const identifiers = new Set([\"schema\", \"convexSchema\"]);\n const components: Array<string> = [];\n const httpMounts: Array<string> = [];\n const kits = new Map<string, string>();\n const visit = Effect.fnUntraced(function* (\n directory: string,\n prefix: string,\n kind: \"app\" | \"component\",\n parentHttpPrefix: string | undefined,\n registeredByKit: boolean,\n ): Effect.fn.Return<\n void,\n | PlatformError.PlatformError\n | BuildError\n | CodegenError.InvalidConvexConfigError\n | CodegenError.InvalidDeclarationError,\n FileSystem.FileSystem | Path.Path\n > {\n const config = path.join(directory, ConvexConfig.CONVEX_CONFIG_FILENAME);\n if (!(yield* fs.exists(config))) return;\n const installed = yield* ConvexConfig.discoverInstalledComponents(\n config,\n relative(config),\n kind,\n );\n for (const component of installed) {\n const name = prefix + component.name;\n const mount =\n prefix === \"\"\n ? App.mounts(app).find((declared) => declared.name === component.name)\n : undefined;\n // A bare definition belongs to another package. Its directory is read\n // here but never written out; tests reach it through `<package>/test`\n // or the kit its mount names.\n const fromPackage = !path.isAbsolute(component.componentDefinitionPath);\n const kitEntry =\n mount?.testing ??\n (fromPackage ? `${component.componentDefinitionPath}/test` : undefined);\n const resolved = fromPackage\n ? path.dirname(\n yield* ConvexConfig.resolveDefinition(\n `${component.componentDefinitionPath}/convex.config`,\n config,\n path,\n ).pipe(\n Effect.fromOption,\n Effect.mapError(\n () =>\n new CodegenError.InvalidConvexConfigError({\n configPath: relative(config),\n reason: `Cannot resolve component ${component.componentDefinitionPath} for testing.`,\n }),\n ),\n ),\n )\n : component.componentDefinitionPath;\n const localPrefix =\n prefix === \"\" ? mount?.httpPrefix : component.httpPrefix;\n const httpPrefix =\n parentHttpPrefix === undefined || localPrefix === undefined\n ? undefined\n : `${parentHttpPrefix.replace(/\\/+$/, \"\")}${localPrefix}`.replace(\n /\\/+$/,\n \"\",\n ) || \"/\";\n if (\n httpPrefix !== undefined &&\n ((yield* fs.exists(path.join(resolved, \"http.ts\"))) ||\n (yield* fs.exists(path.join(resolved, \"http.js\"))))\n ) {\n httpMounts.push(\n `{ componentPath: ${quote(name)}, httpPrefix: ${quote(httpPrefix)} }`,\n );\n }\n // A kit's `register` installs the mount's own children, so below it the\n // walk only collects HTTP mounts.\n if (!registeredByKit) {\n const kitKey = kitEntry ?? resolved;\n let identifier = kits.get(kitKey);\n if (identifier === undefined) {\n const cleaned = name.replaceAll(/[^A-Za-z0-9_$]/g, \"_\");\n const base = /^[A-Za-z_$]/.test(cleaned) ? cleaned : `_${cleaned}`;\n identifier = `${base}Kit`;\n let schemaIdentifier = `${base}Schema`;\n for (\n let n = 2;\n identifiers.has(identifier) || identifiers.has(schemaIdentifier);\n n++\n ) {\n identifier = `${base}Kit${n}`;\n schemaIdentifier = `${base}Schema${n}`;\n }\n identifiers.add(identifier);\n identifiers.add(schemaIdentifier);\n kits.set(kitKey, identifier);\n if (kitEntry === undefined) {\n imports.push(\n `import ${schemaIdentifier} from ${quote(relative(path.join(resolved, \"schema.js\")))};`,\n );\n declarations.push(\n `const ${identifier} = { schema: ${schemaIdentifier}, modules: ${yield* moduleMap(resolved)} };`,\n );\n } else {\n if (mount?.testing !== undefined) {\n yield* checkTestKit(\n mount.name,\n mount.testing,\n config,\n configDisplay,\n );\n } else if (Option.isNone(Bundler.resolveModule(kitEntry, config))) {\n return yield* new CodegenError.InvalidConvexConfigError({\n configPath: relative(config),\n reason: `the component package ${quote(component.componentDefinitionPath)} has no ${quote(kitEntry)} export. Tests register a component from another package through that entry's \\`register(t, name)\\`.`,\n });\n }\n imports.push(`import * as ${identifier} from ${quote(kitEntry)};`);\n }\n }\n components.push(`${quote(name)}: ${identifier},`);\n }\n // A package's own `register` installs its children.\n if (!fromPackage) {\n yield* visit(\n resolved,\n `${name}/`,\n \"component\",\n httpPrefix,\n registeredByKit || kitEntry !== undefined,\n );\n }\n }\n });\n yield* visit(\n convexDirectory,\n \"\",\n (yield* ConvexDirectory.target).kind,\n \"\",\n false,\n );\n yield* writeFileStringAndLog(\n path.join(generated, \"testing.ts\"),\n [\n \"// Generated by `confect codegen`. Test-only; do not import in backend functions.\",\n ...imports,\n ...declarations,\n `export default { httpMounts: [${httpMounts.join(\",\")}], schema, convexSchema, modules: ${yield* moduleMap(convexDirectory)}, components: {${components.join(\"\\n\")}} };`,\n ].join(\"\\n\"),\n );\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DA,MAAM,oBAAoB;AAE1B,MAAM,cAAc,OAAO,IACzB,gBAAgB,SACf,WAAW,OAAO,SAAS,WAC9B;AAEA,MAAM,sBAAsB,OAAO,IAAI,KAAK,OAAO,SACjD,KAAK,KAAK,mBAAmB,SAAS,CACxC;AACA,MAAM,wBAAwB,OAAO,IAAI,KAAK,OAAO,SACnD,KAAK,KAAK,mBAAmB,WAAW,CAC1C;AACA,MAAM,+BAA+B,OAAO,IAAI,KAAK,OAAO,SAC1D,KAAK,KAAK,mBAAmB,iBAAiB,CAChD;AACA,MAAM,oBAAoB,OAAO,IAAI,KAAK,OAAO,SAC/C,KAAK,KAAK,mBAAmB,OAAO,CACtC;AACA,MAAM,4BAA4B,OAAO,IAAI,KAAK,OAAO,SACvD,KAAK,KAAK,mBAAmB,eAAe,CAC9C;AACA,MAAM,2BAA2B,OAAO,IAAI,KAAK,OAAO,SACtD,KAAK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ACC,OAAO,gBAAgB,OAAA,CAAQ,MAChC,IACA,KACF;CACA,OAAO,sBACL,KAAK,KAAK,WAAW,YAAY,GACjC;EACE;EACA,GAAG;EACH,GAAG;EACH,iCAAiC,WAAW,KAAK,GAAG,EAAE,oCAAoC,OAAO,UAAU,eAAe,EAAE,iBAAiB,WAAW,KAAK,IAAI,EAAE;CACrK,CAAC,CAAC,KAAK,IAAI,CACb;AACF,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gaganref/confect-cli",
3
- "version": "10.3.1-fork.12",
3
+ "version": "10.3.1-fork.14",
4
4
  "dependencies": {
5
5
  "@effect/platform-node": "^4.0.4",
6
6
  "bundle-require": "^5.1.0",
@@ -9,8 +9,8 @@
9
9
  "exsolve": "^1.1.3"
10
10
  },
11
11
  "peerDependencies": {
12
- "@confect/core": "npm:@gaganref/confect-core@10.3.1-fork.12",
13
- "@confect/server": "npm:@gaganref/confect-server@10.3.1-fork.12",
12
+ "@confect/core": "npm:@gaganref/confect-core@10.3.1-fork.14",
13
+ "@confect/server": "npm:@gaganref/confect-server@10.3.1-fork.14",
14
14
  "effect": "^4.0.4"
15
15
  },
16
16
  "description": "Developer tooling for codegen and sync",