@gaganref/confect-cli 10.3.1-fork.4 → 10.3.1-fork.6
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.map +1 -1
- package/dist/CodegenError.mjs +1 -1
- package/dist/CodegenError.mjs.map +1 -1
- package/dist/ConfectDirectory.mjs.map +1 -1
- package/dist/ConvexConfig.mjs.map +1 -1
- package/dist/ConvexDirectory.mjs.map +1 -1
- package/dist/DirectoryOptions.mjs.map +1 -1
- package/dist/EntryPoint.mjs.map +1 -1
- package/dist/Evaluation.mjs.map +1 -1
- package/dist/EvaluationWorker.mjs.map +1 -1
- package/dist/FunctionModule.mjs.map +1 -1
- package/dist/FunctionPath.mjs.map +1 -1
- package/dist/FunctionPaths.mjs.map +1 -1
- package/dist/GenerationSnapshot.mjs.map +1 -1
- package/dist/GroupPaths.mjs.map +1 -1
- package/dist/ImplModulePath.mjs.map +1 -1
- package/dist/LeafModule.mjs +1 -1
- package/dist/LeafModule.mjs.map +1 -1
- package/dist/Remove.mjs.map +1 -1
- package/dist/Rollback.mjs.map +1 -1
- package/dist/SpecAssemblyNode.mjs.map +1 -1
- package/dist/SpecModulePath.mjs.map +1 -1
- package/dist/SyncState.mjs.map +1 -1
- package/dist/TableModule.mjs.map +1 -1
- package/dist/TableModulePath.mjs.map +1 -1
- package/dist/WatchBuild.mjs.map +1 -1
- package/dist/WatchTopology.mjs.map +1 -1
- package/dist/Watcher.mjs.map +1 -1
- package/dist/cliApp.mjs.map +1 -1
- package/dist/confect/codegen.mjs +18 -7
- package/dist/confect/codegen.mjs.map +1 -1
- package/dist/confect/declaration.mjs +4 -3
- package/dist/confect/declaration.mjs.map +1 -1
- package/dist/confect/dev.mjs.map +1 -1
- package/dist/confect.mjs.map +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/log.mjs.map +1 -1
- package/dist/templates.mjs +6 -6
- package/dist/templates.mjs.map +1 -1
- package/dist/utils.mjs +1 -1
- package/dist/utils.mjs.map +1 -1
- package/package.json +3 -3
package/dist/Bundler.mjs.map
CHANGED
|
@@ -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\";\nimport { logCoalescedBuildWarnings } from \"./log\";\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,aAA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AO,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 * Bundles first-party workspace dependencies that `bundle-require` would\n * otherwise externalize and hand to Node's native ESM resolver. Resolves each\n * bare specifier and, following symlinks, bundles it when its real path lives\n * outside `node_modules`—mirroring Vite's \"linked dependencies are not\n * externalized\" heuristic. Registered ahead of `externalPlugin`, so deferring\n * (returning `undefined`) leaves third-party externalization untouched.\n * `skipPatterns` are the tsconfig `paths` regexes, which keep deferring to\n * esbuild's own `paths` resolution.\n */\nexport const bundleWorkspacePlugin = (\n path: Path.Path,\n fs: FileSystem.FileSystem,\n skipPatterns: ReadonlyArray<RegExp>,\n): esbuild.Plugin => ({\n name: \"confect:bundle-workspace\",\n setup(build) {\n build.onResolve({ filter: /^[^./]/ }, (args) => {\n if (args.namespace !== \"file\" && args.namespace !== \"\") return undefined;\n if (isBuiltin(args.path) || path.isAbsolute(args.path)) return undefined;\n if (Array.some(skipPatterns, (pattern) => pattern.test(args.path))) {\n return undefined;\n }\n\n const importer =\n args.importer !== \"\" ? args.importer : path.join(args.resolveDir, \"_\");\n\n return Option.match(resolveModule(args.path, importer), {\n onNone: () => ({\n path: args.path,\n external: true,\n warnings: [\n {\n text: `Confect could not resolve workspace dependency \"${args.path}\" (imported from ${importer}) to bundle it; leaving it external.`,\n },\n ],\n }),\n onSome: (resolved) =>\n Effect.runPromise(\n fs.realPath(resolved).pipe(Effect.orElseSucceed(() => resolved)),\n ).then((real) =>\n pipe(real, String.split(path.sep), Array.contains(\"node_modules\"))\n ? undefined\n : { path: real },\n ),\n });\n });\n },\n});\n\ninterface CapturedBuildResult {\n readonly metafile: esbuild.Metafile | undefined;\n readonly warnings: ReadonlyArray<esbuild.Message>;\n}\n\nconst captureBuildResultPlugin = (\n ref: Ref.Ref<CapturedBuildResult>,\n): esbuild.Plugin => ({\n name: \"confect:capture-build-result\",\n setup(build) {\n build.onEnd((result) => {\n Effect.runSync(\n Ref.set(ref, {\n metafile: result.metafile,\n warnings: result.warnings,\n }),\n );\n });\n },\n});\n\ninterface BatchCompilation {\n readonly entries: HashMap.HashMap<\n string,\n { readonly source: string; readonly output: string }\n >;\n readonly metafile: esbuild.Metafile;\n readonly warnings: ReadonlyArray<esbuild.Message>;\n readonly cwd: string;\n}\n\nclass BatchIncompatible extends Schema.TaggedError<BatchIncompatible>()(\n \"BatchIncompatible\",\n {\n reason: Schema.Literals([\n \"RuntimeConditions\",\n \"UnsupportedEntries\",\n \"MixedTsconfigs\",\n \"UnattributedWarnings\",\n ]),\n message: Schema.String,\n },\n) {}\n\nclass Batch extends Context.Service<\n Batch,\n {\n readonly entryPoints: ReadonlyArray<string>;\n readonly compilation: Effect.Effect<\n Option.Option<BatchCompilation>,\n never,\n Path.Path | FileSystem.FileSystem\n >;\n }\n>()(\"@confect/cli/Bundler/Batch\") {}\n\ninterface ExternalImport {\n readonly path: string;\n readonly original: string;\n}\n\nconst batchResolutionPlugin = (\n path: Path.Path,\n fs: FileSystem.FileSystem,\n skipPatterns: ReadonlyArray<RegExp>,\n conditions: string[],\n externalImports: Ref.Ref<\n HashMap.HashMap<string, ReadonlyArray<ExternalImport>>\n >,\n): esbuild.Plugin => ({\n name: \"confect:batch-resolution\",\n setup(build) {\n const external = (args: esbuild.OnResolveArgs, resolved: string) => {\n const importer = path.resolve(args.importer);\n Effect.runSync(\n Ref.update(\n externalImports,\n HashMap.modifyAt(importer, (imports) =>\n Option.some(\n Array.append(\n Option.getOrElse(imports, () => []),\n { path: resolved, original: args.path },\n ),\n ),\n ),\n ),\n );\n return { path: resolved, external: true };\n };\n build.onResolve({ filter: /.*/ }, (args) => {\n if (args.kind === \"entry-point\") return undefined;\n if (isBuiltin(args.path)) return { path: args.path, external: true };\n if (Array.some(skipPatterns, (pattern) => pattern.test(args.path)))\n return undefined;\n if (/[\\\\/]node_modules[\\\\/]/.test(args.path)) {\n return external(\n args,\n pathToFileURL(path.resolve(args.resolveDir, args.path)).href,\n );\n }\n if (args.path.startsWith(\".\") || path.isAbsolute(args.path))\n return undefined;\n\n const resolved = resolveModule(args.path, args.importer);\n if (Option.isNone(resolved)) {\n return {\n errors: [\n { text: `Could not resolve \"${args.path}\" from ${args.importer}` },\n ],\n };\n }\n return Effect.runPromise(\n fs\n .realPath(resolved.value)\n .pipe(Effect.orElseSucceed(() => resolved.value)),\n ).then((real) => {\n if (!/[\\\\/]node_modules[\\\\/]/.test(real)) return { path: real };\n if (args.kind === \"require-call\" || args.kind === \"require-resolve\") {\n return external(\n args,\n createRequire(args.importer).resolve(args.path),\n );\n }\n return external(\n args,\n Option.match(\n resolveExternalEsm(args.path, args.importer, conditions),\n {\n onNone: () => args.path,\n onSome: (resolvedPath) => pathToFileURL(resolvedPath).href,\n },\n ),\n );\n });\n });\n },\n});\n\nconst compileBatch = Effect.fn(\"Bundler.compileBatch\")(function* (\n entryPoints: ReadonlyArray<string>,\n) {\n const path = yield* Path.Path;\n const fs = yield* FileSystem.FileSystem;\n const nodeOptions = yield* Config.String(\"NODE_OPTIONS\").pipe(\n Config.withDefault(\"\"),\n );\n if (/--conditions|-C|--(?:no-)?addons/.test(nodeOptions))\n return yield* new BatchIncompatible({\n reason: \"RuntimeConditions\",\n message:\n \"NODE_OPTIONS changes Node export conditions; individual builds preserve native resolution.\",\n });\n const runtimeOptions = yield* Effect.try({\n try: () =>\n parseArgs({\n args: process.execArgv,\n options: {\n conditions: { type: \"string\", short: \"C\", multiple: true },\n \"no-addons\": { type: \"boolean\" },\n },\n strict: false,\n allowPositionals: true,\n }).values,\n catch: (cause) => new BundlerError({ cause }),\n });\n const conditions = [\n \"node\",\n \"import\",\n ...(process.features.require_module ? [\"module-sync\"] : []),\n ...(runtimeOptions[\"no-addons\"] ? [] : [\"node-addons\"]),\n ...(runtimeOptions.conditions ?? []).filter(\n (condition) => typeof condition === \"string\",\n ),\n ];\n const entries = Array.dedupe(entryPoints.map((entry) => path.resolve(entry)));\n const first = entries[0];\n if (\n first === undefined ||\n entries.some(\n (entry) => !JS_EXT_RE.test(entry) || /[\\\\/]node_modules[\\\\/]/.test(entry),\n )\n ) {\n return yield* new BatchIncompatible({\n reason: \"UnsupportedEntries\",\n message:\n \"Shared builds require JavaScript or TypeScript entries outside node_modules.\",\n });\n }\n const configs = yield* Effect.try({\n try: () => entries.map((entry) => loadTsConfig(path.dirname(entry))),\n catch: (cause) => new BundlerError({ cause }),\n });\n const config = configs[0];\n if (configs.some((other) => other?.path !== config?.path))\n return yield* new BatchIncompatible({\n reason: \"MixedTsconfigs\",\n message: `Entries use different tsconfigs: ${Array.dedupe(configs.map((item) => item?.path ?? \"(no tsconfig)\")).join(\", \")}`,\n });\n\n const cwd = yield* fs.realPath(path.dirname(first));\n const directory = yield* fs\n .makeTempDirectoryScoped({ prefix: \"confect-batch-\" })\n .pipe(Effect.flatMap((temporary) => fs.realPath(temporary)));\n const artifacts = yield* Effect.forEach(entries, (entry, index) =>\n Effect.map(\n fs.realPath(entry),\n (source) =>\n [\n entry,\n { source, output: path.join(directory, `${index}.mjs`) },\n ] as const,\n ),\n );\n const externalImports = yield* Ref.make(\n HashMap.empty<string, ReadonlyArray<ExternalImport>>(),\n );\n const result = yield* Effect.tryPromise({\n try: () =>\n esbuild.build({\n entryPoints: entries.map((entry, index) => ({\n in: entry,\n out: `${index}`,\n })),\n absWorkingDir: cwd,\n outdir: directory,\n outExtension: { \".js\": \".mjs\" },\n chunkNames: \"chunk-[hash]\",\n format: \"esm\",\n platform: \"node\",\n sourcemap: \"inline\",\n bundle: true,\n splitting: true,\n metafile: true,\n write: false,\n logLevel: \"silent\",\n ...(config?.path\n ? { tsconfig: config.path }\n : { tsconfigRaw: config?.data ?? {} }),\n plugins: [\n batchResolutionPlugin(\n path,\n fs,\n tsconfigPathsToRegExp(config?.data.compilerOptions?.paths ?? {}),\n conditions,\n externalImports,\n ),\n injectFileScopePlugin(),\n ],\n }),\n catch: (cause) => new BundlerError({ cause }),\n });\n const inputPaths = HashSet.fromIterable(\n Object.keys(result.metafile.inputs).map((input) =>\n path.resolve(cwd, input),\n ),\n );\n const unattributedWarnings = result.warnings.filter(\n (warning) =>\n !warning.location ||\n !HashSet.has(inputPaths, path.resolve(cwd, warning.location.file)),\n );\n if (unattributedWarnings.length > 0)\n return yield* new BatchIncompatible({\n reason: \"UnattributedWarnings\",\n message: `Cannot attribute build warnings to entries: ${unattributedWarnings.map((warning) => warning.text).join(\"; \")}`,\n });\n yield* Effect.forEach(result.outputFiles, (output) =>\n fs.writeFile(output.path, output.contents),\n );\n const capturedExternalImports = yield* Ref.get(externalImports);\n const inputs = Object.fromEntries(\n Object.entries(result.metafile.inputs).map(([input, metadata]) => {\n const originals = Option.getOrElse(\n HashMap.get(capturedExternalImports, path.resolve(cwd, input)),\n () => [],\n );\n return [\n input,\n {\n ...metadata,\n imports: metadata.imports.flatMap((imported) => {\n const matching = imported.external\n ? originals.filter((original) => original.path === imported.path)\n : [];\n return matching.length === 0\n ? [imported]\n : matching.map((original) =>\n Object.assign({}, imported, {\n original: original.original,\n }),\n );\n }),\n },\n ];\n }),\n );\n return {\n entries: HashMap.fromIterable(artifacts),\n metafile: absolutizeMetafile(path, { ...result.metafile, inputs }, cwd),\n warnings: result.warnings,\n cwd,\n } satisfies BatchCompilation;\n});\n\n/**\n * Lazily shares one compilation across ordinary bundle calls in this effect.\n * Different tsconfigs and failed compilations fall back to individual builds.\n * Runtime conditions supplied through NODE_OPTIONS also use individual builds.\n * Imports still run at each caller, and temporary chunks live until the effect\n * finishes. The disposable evaluator, not this scope, owns Node's import\n * cache.\n */\nexport const withBatch = <A, E, R>(\n entryPoints: ReadonlyArray<string>,\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<A, E, R> =>\n Effect.scopedWith((scope) =>\n Effect.gen(function* () {\n const current = yield* Effect.serviceOption(Batch);\n if (\n Option.isSome(current) &&\n entryPoints.every((entry) => current.value.entryPoints.includes(entry))\n )\n return yield* effect;\n const compilation = yield* Effect.cached(\n compileBatch(entryPoints).pipe(\n Effect.provideService(Scope.Scope, scope),\n Effect.asSome,\n Effect.catchTag(\"BatchIncompatible\", (error) =>\n Effect.logDebug(\n \"Shared build skipped; falling back to individual builds.\",\n {\n entryPoints,\n reason: error.reason,\n detail: error.message,\n },\n ).pipe(Effect.as(Option.none<BatchCompilation>())),\n ),\n Effect.catch((error) =>\n Effect.logDebug(\n \"Shared build failed; falling back to individual builds.\",\n {\n entryPoints,\n reason: \"CompileFailure\",\n },\n Cause.fail(error),\n ).pipe(Effect.as(Option.none<BatchCompilation>())),\n ),\n ),\n );\n return yield* Effect.provideService(effect, Batch, {\n entryPoints,\n compilation,\n });\n }),\n );\n\ninterface MetafileTraversal {\n readonly pending: Chunk.Chunk<string>;\n readonly visited: HashSet.HashSet<string>;\n}\n\nconst reachableMetafileEntries = <\n Metadata extends {\n readonly imports: ReadonlyArray<{\n readonly path: string;\n readonly external?: boolean;\n }>;\n },\n>(\n entries: Readonly<Record<string, Metadata>>,\n root: string,\n resolveImport: (path: string) => string,\n): Record<string, Metadata> =>\n Object.fromEntries(\n pipe(\n Iterable.unfold<\n MetafileTraversal,\n Option.Option<readonly [string, Metadata]>\n >(\n { pending: Chunk.of(root), visited: HashSet.empty() },\n ({ pending, visited }) => {\n if (!Chunk.isNonEmpty(pending)) return Option.none();\n const key = Chunk.headNonEmpty(pending);\n const remaining = Chunk.tailNonEmpty(pending);\n const metadata = entries[key];\n if (HashSet.has(visited, key) || metadata === undefined)\n return Option.some([\n Option.none(),\n { pending: remaining, visited },\n ]);\n return Option.some([\n Option.some([key, metadata] as const),\n {\n pending: Array.reduce(\n metadata.imports,\n remaining,\n (queue, imported) =>\n imported.external\n ? queue\n : Chunk.append(queue, resolveImport(imported.path)),\n ),\n visited: HashSet.add(visited, key),\n },\n ]);\n },\n ),\n Iterable.getSomes,\n ),\n );\n\nconst entryMetafile = (\n path: Path.Path,\n compilation: BatchCompilation,\n source: string,\n output: string,\n): esbuild.Metafile => ({\n inputs: reachableMetafileEntries(\n compilation.metafile.inputs,\n source,\n identity,\n ),\n outputs: reachableMetafileEntries(\n compilation.metafile.outputs,\n output,\n (key) => path.resolve(compilation.cwd, key),\n ),\n});\n\n/**\n * Bundle a TypeScript entry point with esbuild via {@link bundleRequire} and\n * import the result. `bundle-require` writes a temp `.mjs` next to the source,\n * `import()`s it, and deletes it—so third-party `node_modules` externals\n * resolve through the user's normal `node_modules` walk, while first-party\n * workspace deps are bundled by {@link bundleWorkspacePlugin} and tsconfig\n * `paths` aliases stay inside the bundle.\n *\n * `cwd` is set to the entry's directory so `bundle-require`'s `tsconfig.json`\n * discovery (which walks upward from `cwd`) lands on the project's tsconfig\n * regardless of where `confect codegen` was invoked from, and so esbuild\n * resolves relative imports against the entry's location.\n *\n * The returned pair carries both the imported module and the esbuild metafile\n * so callers can inspect the import graph (see {@link directlyImports}); the\n * metafile is captured via a small `onEnd` plugin because `bundle-require`\n * itself only exposes a flat `dependencies: string[]`.\n *\n * `options.plugins` are registered ahead of every other plugin—including\n * `bundle-require`'s own `externalPlugin`—so a caller-supplied plugin can claim\n * resolutions (e.g. `convex.config` imports) before the workspace and\n * externalization heuristics see them.\n */\nexport const bundle = Effect.fn(\"Bundler.bundle\")(function* (\n entryPoint: string,\n options?: { readonly plugins?: ReadonlyArray<esbuild.Plugin> },\n): Effect.fn.Return<Bundled, BundlerError, Path.Path | FileSystem.FileSystem> {\n const path = yield* Path.Path;\n const fs = yield* FileSystem.FileSystem;\n\n const batch = yield* Effect.serviceOption(Batch);\n if (\n Option.isSome(batch) &&\n !options?.plugins?.length &&\n batch.value.entryPoints.some(\n (entry) => path.resolve(entry) === path.resolve(entryPoint),\n )\n ) {\n const compilation = yield* batch.value.compilation;\n if (Option.isSome(compilation)) {\n const entry = HashMap.get(\n compilation.value.entries,\n path.resolve(entryPoint),\n );\n if (Option.isSome(entry)) {\n const metafile = entryMetafile(\n path,\n compilation.value,\n entry.value.source,\n entry.value.output,\n );\n const module = yield* Effect.tryPromise({\n try: () =>\n dynamicImport(pathToFileURL(entry.value.output).href, {\n format: \"esm\",\n }),\n catch: (cause) => new BundlerError({ cause }),\n }).pipe(\n Effect.ensuring(\n logCoalescedBuildWarnings(\n compilation.value.warnings.filter(\n (warning) =>\n warning.location &&\n metafile.inputs[\n path.resolve(compilation.value.cwd, warning.location.file)\n ],\n ),\n ),\n ),\n );\n return { module, metafile };\n }\n }\n }\n\n const buildResultRef = yield* Ref.make<CapturedBuildResult>({\n metafile: undefined,\n warnings: [],\n });\n\n const cwd = path.dirname(entryPoint);\n const skipPatterns = yield* Effect.try({\n try: () =>\n tsconfigPathsToRegExp(\n loadTsConfig(cwd)?.data.compilerOptions?.paths ?? {},\n ),\n catch: (cause) => new BundlerError({ cause }),\n });\n const result = yield* Effect.tryPromise({\n try: () =>\n bundleRequire({\n filepath: entryPoint,\n cwd,\n format: \"esm\",\n esbuildOptions: {\n plugins: [\n ...(options?.plugins ?? []),\n bundleWorkspacePlugin(path, fs, skipPatterns),\n captureBuildResultPlugin(buildResultRef),\n ],\n logLevel: \"silent\",\n },\n }),\n catch: (cause) => new BundlerError({ cause }),\n }).pipe(\n Effect.ensuring(\n Effect.andThen(Ref.get(buildResultRef), (captured) =>\n logCoalescedBuildWarnings(captured.warnings),\n ),\n ),\n );\n\n const { metafile } = yield* Ref.get(buildResultRef);\n if (!metafile) {\n return yield* Effect.die(new Error(\"esbuild metafile missing\"));\n }\n\n return {\n module: result.mod,\n metafile: absolutizeMetafile(path, metafile, cwd),\n };\n});\n\nconst findMetafileInputKey = Effect.fnUntraced(function* (\n metafile: esbuild.Metafile,\n absolutePath: string,\n) {\n const path = yield* Path.Path;\n const resolved = path.resolve(absolutePath);\n if (metafile.inputs[resolved] !== undefined) return Option.some(resolved);\n const fs = yield* FileSystem.FileSystem;\n const real = yield* fs\n .realPath(resolved)\n .pipe(Effect.orElseSucceed(() => resolved));\n return Array.findFirst(\n Object.keys(metafile.inputs),\n (key) => path.resolve(key) === real,\n );\n});\n\n/**\n * Returns `true` when the module bundled from `sourceAbsolutePath` declares a\n * direct import of `targetAbsolutePath` (according to the bundle's esbuild\n * metafile). Returns `false` if either path is missing from the metafile.\n */\nexport const directlyImports = Effect.fnUntraced(function* (\n bundled: Bundled,\n sourceAbsolutePath: string,\n targetAbsolutePath: string,\n) {\n const path = yield* Path.Path;\n const sourceKey = yield* findMetafileInputKey(\n bundled.metafile,\n sourceAbsolutePath,\n );\n const targetKey = yield* findMetafileInputKey(\n bundled.metafile,\n targetAbsolutePath,\n );\n\n return pipe(\n Option.all([sourceKey, targetKey]),\n Option.flatMap(([sourceKey_, targetKey_]) =>\n Option.fromNullishOr(bundled.metafile.inputs[sourceKey_]).pipe(\n Option.map((sourceInput) => {\n const targetResolved = path.resolve(targetKey_);\n return sourceInput.imports.some(\n (importedFile) =>\n path.resolve(importedFile.path) === targetResolved,\n );\n }),\n ),\n ),\n Option.getOrElse(() => false),\n );\n});\n\n/**\n * Returns the absolute paths of every module in the bundle that declares a\n * direct import of `packageName` (the package itself or one of its subpaths)\n * and satisfies `where`. Use `where` to restrict the search to the modules you\n * care about—the bundle's inputs include every transitive dependency.\n *\n * Matching is on the specifier as written rather than the resolved path,\n * because {@link bundleWorkspacePlugin} bundles first-party workspace\n * dependencies (so `@confect/server` resolves to a path inside the monorepo)\n * while a published install externalizes them (so it stays a bare specifier).\n * esbuild erases `import type` before it produces the metafile, so type-only\n * imports are not reported.\n */\nexport const importersOfPackage = (\n bundled: Bundled,\n packageName: string,\n where: (absolutePath: string) => boolean,\n): ReadonlyArray<string> => {\n const subpathPrefix = `${packageName}/`;\n\n return Object.entries(bundled.metafile.inputs)\n .filter(\n ([absolutePath, input]) =>\n where(absolutePath) &&\n input.imports.some(\n (imported) =>\n imported.original === packageName ||\n imported.original?.startsWith(subpathPrefix) === true,\n ),\n )\n .map(([absolutePath]) => absolutePath);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,MAAM,sBACJ,MACA,UACA,QACqB;CACrB,MAAM,cAAc,MAAc,KAAK,QAAQ,KAAK,CAAC;CAyBrD,OAAO;EAAE,QAxBM,OAAO,WAAW,SAAS,SAAS,OAAO,QAAQ,CAChE,WAAW,GAAG,GACd;GACE,GAAG;GACH,SAAS,MAAM,IAAI,MAAM,UAAU,OAAO;IACxC,GAAG;IACH,MAAM,WAAW,EAAE,IAAI;IACvB,UAAU,EAAE,YAAY,EAAE;GAC5B,EAAE;EACJ,CACF,CAcc;EAAG,SAbD,OAAO,WAAW,SAAS,UAAU,OAAO,QAAQ,CAClE,WAAW,GAAG,GACd;GACE,GAAG;GACH,GAAI,MAAM,aAAa,EAAE,YAAY,WAAW,MAAM,UAAU,EAAE,IAAI,CAAC;GACvE,QAAQ,OAAO,QAAQ,MAAM,QAAQ,UAAU;GAC/C,SAAS,MAAM,IAAI,MAAM,UAAU,aACjC,SAAS,WACL,WACA;IAAE,GAAG;IAAU,MAAM,WAAW,SAAS,IAAI;GAAE,CACrD;EACF,CACF,CACuB;CAAE;AAC3B;AAEA,MAAM,aAAa,OAAO,eAAe,WAAmB,aAC1D,kBAAkB,WAAW;CAC3B,MAAM;CACN,YAAY,CAAC,QAAQ,QAAQ;AAC/B,CAAC,CACH;AAEA,MAAM,aAAa,OAAO,eAAe,WAAmB,aAC1D,cAAc,QAAQ,CAAC,CAAC,QAAQ,SAAS,CAC3C;AAEA,MAAM,qBAAqB,OAAO,eAC/B,WAAmB,UAA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B;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"}
|
package/dist/CodegenError.mjs
CHANGED
|
@@ -141,7 +141,7 @@ const renderSpecImportsServerError = (error) => {
|
|
|
141
141
|
};
|
|
142
142
|
const renderImplMissingSpecImportError = (error) => {
|
|
143
143
|
const stem = stemFromSpecPath(error.expectedSpecPath);
|
|
144
|
-
return singleLine("Impl ", formatPath(error.implPath), ` does not import its sibling spec; add \`import ${stem} from "./${stem}.spec"\` and pass it to FunctionImpl.make/GroupImpl.make.`);
|
|
144
|
+
return singleLine("Impl ", formatPath(error.implPath), ` does not import its sibling spec; add \`import ${stem} from "./${stem}.spec.js"\` and pass it to FunctionImpl.make/GroupImpl.make.`);
|
|
145
145
|
};
|
|
146
146
|
const renderImplMissingDefaultLayerError = (error) => singleLine("Impl ", formatPath(error.implPath), " must default-export a GroupImpl layer; wrap your handlers with `GroupImpl.make(databaseSchema, groupSpec).pipe(Layer.provide(...))` and `export default` it.");
|
|
147
147
|
const renderImplNotFinalizedError = (error) => singleLine("Impl ", formatPath(error.implPath), " is not finalized; append `GroupImpl.finalize` to the end of the pipeline (e.g. `GroupImpl.make(databaseSchema, group).pipe(Layer.provide(...), GroupImpl.finalize)`).");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CodegenError.mjs","names":["Ansi.red"],"sources":["../src/CodegenError.ts"],"sourcesContent":["import * as Array from \"effect/Array\";\nimport * as Console from \"effect/Console\";\nimport { pipe } from \"effect/Function\";\nimport * as Effect from \"effect/Effect\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport { BuildError, isBuildError } from \"./BuildError\";\nimport { SnapshotError } from \"./SnapshotError\";\nimport * as Ansi from \"./Ansi\";\nimport { formatPath, renderBuildError } from \"./log\";\n\n// --- Variants ---\n\nexport class MissingImplFileError extends Schema.TaggedError<MissingImplFileError>()(\n \"MissingImplFileError\",\n {\n specPath: Schema.String,\n expectedImplPath: Schema.String,\n },\n) {}\n\nexport class MissingSpecFileError extends Schema.TaggedError<MissingSpecFileError>()(\n \"MissingSpecFileError\",\n {\n implPath: Schema.String,\n expectedSpecPath: Schema.String,\n },\n) {}\n\nexport class SpecMissingDefaultGroupSpecError extends Schema.TaggedError<SpecMissingDefaultGroupSpecError>()(\n \"SpecMissingDefaultGroupSpecError\",\n {\n specPath: Schema.String,\n },\n) {}\n\nexport class RemoveBusyError extends Schema.TaggedError<RemoveBusyError>()(\n \"RemoveBusyError\",\n { path: Schema.String, attempts: Schema.Finite, cause: Schema.Unknown },\n) {}\n\nexport class ComponentNodeGroupError extends Schema.TaggedError<ComponentNodeGroupError>()(\n \"ComponentNodeGroupError\",\n {\n specPath: Schema.String,\n groupPath: Schema.String,\n },\n) {}\n\nexport class SpecImportsServerError extends Schema.TaggedError<SpecImportsServerError>()(\n \"SpecImportsServerError\",\n {\n specPath: Schema.String,\n importerPaths: Schema.Array(Schema.String),\n },\n) {}\n\nexport class InvalidMiddlewareAttachmentError extends Schema.TaggedError<InvalidMiddlewareAttachmentError>()(\n \"InvalidMiddlewareAttachmentError\",\n { specPath: Schema.String, message: Schema.String },\n) {}\n\nexport class ImplMissingSpecImportError extends Schema.TaggedError<ImplMissingSpecImportError>()(\n \"ImplMissingSpecImportError\",\n {\n implPath: Schema.String,\n expectedSpecPath: Schema.String,\n },\n) {}\n\nexport class ImplMissingDefaultLayerError extends Schema.TaggedError<ImplMissingDefaultLayerError>()(\n \"ImplMissingDefaultLayerError\",\n {\n implPath: Schema.String,\n },\n) {}\n\nexport class ImplNotFinalizedError extends Schema.TaggedError<ImplNotFinalizedError>()(\n \"ImplNotFinalizedError\",\n {\n implPath: Schema.String,\n },\n) {}\n\nexport class ImplMissingFunctionsError extends Schema.TaggedError<ImplMissingFunctionsError>()(\n \"ImplMissingFunctionsError\",\n {\n implPath: Schema.String,\n groupPath: Schema.String,\n missingFunctionNames: Schema.Array(Schema.String),\n },\n) {}\n\nexport class ImplMissingMiddlewareError extends Schema.TaggedError<ImplMissingMiddlewareError>()(\n \"ImplMissingMiddlewareError\",\n {\n implPath: Schema.String,\n groupPath: Schema.String,\n missingMiddlewareKeys: Schema.Array(Schema.String),\n },\n) {}\n\nexport class ParentChildNameCollisionError extends Schema.TaggedError<ParentChildNameCollisionError>()(\n \"ParentChildNameCollisionError\",\n {\n parentSpecPath: Schema.String,\n childSpecPath: Schema.String,\n collisionName: Schema.String,\n collisionKind: Schema.Literals([\"function\", \"group\"]),\n },\n) {}\n\nexport class InvalidTableDefaultExportError extends Schema.TaggedError<InvalidTableDefaultExportError>()(\n \"InvalidTableDefaultExportError\",\n {\n tablePath: Schema.String,\n },\n) {}\n\nexport class InvalidTableFilenameError extends Schema.TaggedError<InvalidTableFilenameError>()(\n \"InvalidTableFilenameError\",\n {\n tablePath: Schema.String,\n reason: Schema.String,\n },\n) {}\n\nexport class DuplicateTableNameError extends Schema.TaggedError<DuplicateTableNameError>()(\n \"DuplicateTableNameError\",\n {\n // Every table name that more than one file resolves to, each paired with\n // the colliding file paths. All collisions are captured in a single pass\n // so the user can fix them together rather than re-running codegen once\n // per conflict.\n collisions: Schema.Array(\n Schema.Struct({\n tableName: Schema.String,\n tablePaths: Schema.Array(Schema.String),\n }),\n ),\n },\n) {}\n\nexport class LegacySchemaFileError extends Schema.TaggedError<LegacySchemaFileError>()(\n \"LegacySchemaFileError\",\n {\n schemaPath: Schema.String,\n },\n) {}\n\nexport class ConflictingDocNameError extends Schema.TaggedError<ConflictingDocNameError>()(\n \"ConflictingDocNameError\",\n {\n collisions: Schema.Array(\n Schema.Struct({\n docName: Schema.String,\n tableNames: Schema.Array(Schema.String),\n }),\n ),\n },\n) {}\n\nexport class InvalidConvexConfigError extends Schema.TaggedError<InvalidConvexConfigError>()(\n \"InvalidConvexConfigError\",\n {\n configPath: Schema.String,\n reason: Schema.String,\n },\n) {}\n\nexport class InvalidDeclarationError extends Schema.TaggedError<InvalidDeclarationError>()(\n \"InvalidDeclarationError\",\n {\n declarationPath: Schema.String,\n reason: Schema.String,\n },\n) {}\n\nexport class HandWrittenConvexFileError extends Schema.TaggedError<HandWrittenConvexFileError>()(\n \"HandWrittenConvexFileError\",\n {\n convexPath: Schema.String,\n declarationPath: Schema.String,\n },\n) {}\n\nexport class DeclarationKindMismatchError extends Schema.TaggedError<DeclarationKindMismatchError>()(\n \"DeclarationKindMismatchError\",\n {\n declarationPath: Schema.String,\n declaredKind: Schema.Literals([\"app\", \"component\"]),\n targetKind: Schema.Literals([\"app\", \"component\"]),\n },\n) {}\n\nexport class CallbackPrefixError extends Schema.TaggedError<CallbackPrefixError>()(\n \"CallbackPrefixError\",\n {\n declarationPath: Schema.String,\n contractId: Schema.String,\n componentName: Schema.String,\n },\n) {}\n\nexport const CodegenError = Schema.Union([\n SnapshotError,\n BuildError,\n MissingImplFileError,\n MissingSpecFileError,\n SpecMissingDefaultGroupSpecError,\n ComponentNodeGroupError,\n RemoveBusyError,\n SpecImportsServerError,\n InvalidMiddlewareAttachmentError,\n ImplMissingSpecImportError,\n ImplMissingDefaultLayerError,\n ImplNotFinalizedError,\n ImplMissingFunctionsError,\n ImplMissingMiddlewareError,\n ParentChildNameCollisionError,\n InvalidTableDefaultExportError,\n InvalidTableFilenameError,\n DuplicateTableNameError,\n LegacySchemaFileError,\n ConflictingDocNameError,\n InvalidConvexConfigError,\n InvalidDeclarationError,\n HandWrittenConvexFileError,\n DeclarationKindMismatchError,\n CallbackPrefixError,\n]);\nexport type CodegenError = typeof CodegenError.Type;\n\nexport const isCodegenError = (error: unknown): error is CodegenError => {\n if (isBuildError(error)) return true;\n return Schema.is(CodegenError)(error);\n};\n\n// --- Per-variant rendering ---\n\nconst cross = Ansi.red(\"✘\");\n\nconst stemFromSpecPath = (specPath: string): string => {\n const lastSep = Math.max(\n specPath.lastIndexOf(\"/\"),\n specPath.lastIndexOf(\"\\\\\"),\n );\n const basename = lastSep < 0 ? specPath : specPath.slice(lastSep + 1);\n return basename.endsWith(\".spec.ts\")\n ? basename.slice(0, -\".spec.ts\".length)\n : basename;\n};\n\nconst singleLine = (...parts: ReadonlyArray<string>): string =>\n `${cross} ${parts.join(\"\")}`;\n\nconst renderMissingImplFileError = (error: MissingImplFileError): string =>\n singleLine(\n \"Spec \",\n formatPath(error.specPath),\n \" has no sibling impl; create \",\n formatPath(error.expectedImplPath),\n \" and default-export a GroupImpl layer from it.\",\n );\n\nconst renderMissingSpecFileError = (error: MissingSpecFileError): string =>\n singleLine(\n \"Impl \",\n formatPath(error.implPath),\n \" has no sibling spec; create \",\n formatPath(error.expectedSpecPath),\n \" and default-export a GroupSpec from it, or remove the impl.\",\n );\n\nconst renderSpecMissingDefaultGroupSpecError = (\n error: SpecMissingDefaultGroupSpecError,\n): string =>\n singleLine(\n \"Spec \",\n formatPath(error.specPath),\n \" must default-export a GroupSpec; build it with GroupSpec.make() or GroupSpec.makeNode().\",\n );\n\nconst renderSpecImportsServerError = (\n error: SpecImportsServerError,\n): string => {\n const importers = error.importerPaths.join(\", \");\n return singleLine(\n \"Spec \",\n formatPath(error.specPath),\n ` reaches a module that imports \\`@confect/server\\`: ${importers}. Spec modules are bundled into your client, so anything they import ships to the browser—move the server logic into a \\`*.impl.ts\\` module, or use \\`import type\\` if you only need the types.`,\n );\n};\n\nconst renderImplMissingSpecImportError = (\n error: ImplMissingSpecImportError,\n): string => {\n const stem = stemFromSpecPath(error.expectedSpecPath);\n return singleLine(\n \"Impl \",\n formatPath(error.implPath),\n ` does not import its sibling spec; add \\`import ${stem} from \"./${stem}.spec\"\\` and pass it to FunctionImpl.make/GroupImpl.make.`,\n );\n};\n\nconst renderImplMissingDefaultLayerError = (\n error: ImplMissingDefaultLayerError,\n): string =>\n singleLine(\n \"Impl \",\n formatPath(error.implPath),\n \" must default-export a GroupImpl layer; wrap your handlers with `GroupImpl.make(databaseSchema, groupSpec).pipe(Layer.provide(...))` and `export default` it.\",\n );\n\nconst renderImplNotFinalizedError = (error: ImplNotFinalizedError): string =>\n singleLine(\n \"Impl \",\n formatPath(error.implPath),\n \" is not finalized; append `GroupImpl.finalize` to the end of the pipeline (e.g. `GroupImpl.make(databaseSchema, group).pipe(Layer.provide(...), GroupImpl.finalize)`).\",\n );\n\nconst renderImplMissingFunctionsError = (\n error: ImplMissingFunctionsError,\n): string => {\n const names = error.missingFunctionNames.join(\", \");\n return singleLine(\n \"Impl \",\n formatPath(error.implPath),\n ` does not implement every function declared by group \\`${error.groupPath}\\`; missing: ${names}. Add a \\`FunctionImpl.make\\` for each missing function and provide it to the group layer.`,\n );\n};\n\nconst renderImplMissingMiddlewareError = (\n error: ImplMissingMiddlewareError,\n): string => {\n const keys = error.missingMiddlewareKeys.join(\", \");\n return singleLine(\n \"Impl \",\n formatPath(error.implPath),\n ` does not implement every middleware attached to group \\`${error.groupPath}\\`; missing: ${keys}. Provide a \\`MiddlewareImpl.make\\` (or \\`makeByFunctionType\\`/\\`provides\\`) layer for each missing middleware to the group layer.`,\n );\n};\n\nconst renderInvalidTableDefaultExportError = (\n error: InvalidTableDefaultExportError,\n): string =>\n singleLine(\n \"Table \",\n formatPath(error.tablePath),\n \" must default-export a Table (e.g. `export default Table.make({ ... })`); convert any named export to a default export.\",\n );\n\nconst renderInvalidTableFilenameError = (\n error: InvalidTableFilenameError,\n): string =>\n singleLine(\n \"Table \",\n formatPath(error.tablePath),\n ` has an invalid filename: ${error.reason} Convex table names must start with a letter and contain only letters, numbers, and underscores; leading underscores are reserved for system tables.`,\n );\n\nconst renderDuplicateTableNameError = (\n error: DuplicateTableNameError,\n): string => {\n const conflicts = error.collisions\n .map(\n ({ tableName, tablePaths }) =>\n `\\`${tableName}\\` (${tablePaths.join(\", \")})`,\n )\n .join(\"; \");\n return singleLine(\n `Multiple files under \\`confect/tables/\\` resolve to the same table name. Table names are derived from filenames, so each must be unique across the directory (including subdirectories); rename or remove all but one. Conflicts: ${conflicts}.`,\n );\n};\n\nconst renderConflictingDocNameError = (\n error: ConflictingDocNameError,\n): string => {\n const conflicts = pipe(\n error.collisions,\n Array.map(\n ({ docName, tableNames }) =>\n `\\`${docName}\\` (${Array.join(tableNames, \", \")})`,\n ),\n Array.join(\"; \"),\n );\n return singleLine(\n `Multiple tables fold to the same generated document type name. Table names are converted to PascalCase (so \\`user_profiles\\` and \\`userProfiles\\` both become \\`UserProfilesDoc\\`); rename all but one of each colliding group. Conflicts: ${conflicts}.`,\n );\n};\n\nconst renderInvalidConvexConfigError = (\n error: InvalidConvexConfigError,\n): string =>\n singleLine(\n \"Convex config \",\n formatPath(error.configPath),\n ` could not be evaluated: ${error.reason}`,\n );\n\nconst renderLegacySchemaFileError = (error: LegacySchemaFileError): string =>\n singleLine(\n \"Found a legacy \",\n formatPath(error.schemaPath),\n \". Delete it: tables in `confect/tables/*.ts` are now the single source of truth, and the runtime schema is generated as `confect/_generated/schema.ts`.\",\n );\n\nconst renderParentChildNameCollisionError = (\n error: ParentChildNameCollisionError,\n): string =>\n singleLine(\n \"Spec \",\n formatPath(error.parentSpecPath),\n ` declares a ${error.collisionKind} \\`${error.collisionName}\\` whose name collides with the sibling subdirectory spec `,\n formatPath(error.childSpecPath),\n `. Rename one of them so the assembled spec has a unique key at this path.`,\n );\n\n/**\n * Render any {@link CodegenError} into a styled, ready-to-print string.\n * Single-error variants render to a one-line `✘`-prefixed message;\n * `BundleFailedError` (the only multi-error variant) renders to a header plus\n * an esbuild diagnostic block.\n */\nexport const renderCodegenError = (error: CodegenError): string => {\n if (isBuildError(error)) return renderBuildError(error);\n // The renderer pipeline below is at Effect's pipe arity limit, so the\n // fork's errors render here.\n if (error._tag === \"ComponentNodeGroupError\") {\n return singleLine(\n `Group \"${error.groupPath}\" in ${error.specPath} uses the Node runtime. Convex components do not support Node.js functions.`,\n );\n }\n if (error._tag === \"RemoveBusyError\") {\n return singleLine(\n \"Could not remove \",\n formatPath(error.path),\n ` after ${error.attempts} attempts because it is busy. Close other tools using it and try again.`,\n );\n }\n if (error._tag === \"InvalidDeclarationError\") {\n return singleLine(\n \"Declaration \",\n formatPath(error.declarationPath),\n ` is invalid: ${error.reason}`,\n );\n }\n if (error._tag === \"DeclarationKindMismatchError\") {\n return singleLine(\n \"Declaration \",\n formatPath(error.declarationPath),\n ` declares kind \"${error.declaredKind}\", but the target directory is kind \"${error.targetKind}\".`,\n );\n }\n if (error._tag === \"CallbackPrefixError\") {\n return singleLine(\n \"Callback contract \",\n `\"${error.contractId}\" in `,\n formatPath(error.declarationPath),\n ` must start with \"${error.componentName}/\" for component \"${error.componentName}\".`,\n );\n }\n if (error._tag === \"HandWrittenConvexFileError\") {\n return singleLine(\n \"Found a hand-written \",\n formatPath(error.convexPath),\n \". `confect codegen` writes it from \",\n formatPath(error.declarationPath),\n \" now; move its contents there and delete the file.\",\n );\n }\n return Match.value(error).pipe(\n Match.tag(\"SnapshotError\", ({ reason, relativePath, pathSegments }) =>\n singleLine(\n `Invalid generation metadata (${reason})`,\n relativePath === \"\" ? \"\" : ` for ${relativePath}`,\n pathSegments.length === 0 ? \".\" : ` at ${pathSegments.join(\"/\")}.`,\n ),\n ),\n Match.tag(\"MissingImplFileError\", renderMissingImplFileError),\n Match.tag(\"MissingSpecFileError\", renderMissingSpecFileError),\n Match.tag(\n \"SpecMissingDefaultGroupSpecError\",\n renderSpecMissingDefaultGroupSpecError,\n ),\n Match.tag(\"SpecImportsServerError\", renderSpecImportsServerError),\n Match.tag(\"InvalidMiddlewareAttachmentError\", (attachmentError) =>\n singleLine(\n \"Spec \",\n formatPath(attachmentError.specPath),\n `: ${attachmentError.message}`,\n ),\n ),\n Match.tag(\"ImplMissingSpecImportError\", renderImplMissingSpecImportError),\n Match.tag(\n \"ImplMissingDefaultLayerError\",\n renderImplMissingDefaultLayerError,\n ),\n Match.tag(\"ImplNotFinalizedError\", renderImplNotFinalizedError),\n Match.tag(\"ImplMissingFunctionsError\", renderImplMissingFunctionsError),\n Match.tag(\"ImplMissingMiddlewareError\", renderImplMissingMiddlewareError),\n Match.tag(\n \"ParentChildNameCollisionError\",\n renderParentChildNameCollisionError,\n ),\n Match.tag(\n \"InvalidTableDefaultExportError\",\n renderInvalidTableDefaultExportError,\n ),\n Match.tag(\"InvalidTableFilenameError\", renderInvalidTableFilenameError),\n Match.tag(\"DuplicateTableNameError\", renderDuplicateTableNameError),\n Match.tag(\"LegacySchemaFileError\", renderLegacySchemaFileError),\n Match.tag(\"ConflictingDocNameError\", renderConflictingDocNameError),\n Match.tag(\"InvalidConvexConfigError\", renderInvalidConvexConfigError),\n Match.exhaustive,\n );\n};\n\nexport const logCodegenError = (error: CodegenError) =>\n Console.error(renderCodegenError(error));\n\n// --- Effect combinators ---\n\n/**\n * Log any {@link CodegenError} thrown by `effect` and propagate the failure\n * unchanged so the caller's error channel is preserved.\n */\nexport const tapAndLog = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<A, E, R> =>\n effect.pipe(\n Effect.tapError((error) =>\n isCodegenError(error) ? logCodegenError(error) : Effect.void,\n ),\n );\n\n/**\n * Catch any {@link CodegenError} thrown by `effect`, log it, and resolve to\n * `Option.none()`. Success resolves to `Option.some(value)`.\n */\n// oxlint-disable effecttsgo/unsafe-effect-type-assertion -- catchIf removes the error variant selected by this refinement.\nexport const catchAndLog = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<Option.Option<A>, Exclude<E, CodegenError>, R> =>\n Effect.catchIf(Effect.map(effect, Option.some<A>), isCodegenError, (error) =>\n logCodegenError(error).pipe(Effect.as(Option.none<A>())),\n ) as Effect.Effect<Option.Option<A>, Exclude<E, CodegenError>, R>;\n// oxlint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AEA,OAAO,KACL,OAAO,UAAU,UACf,eAAe,KAAK,IAAI,gBAAgB,KAAK,IAAI,OAAO,IAC1D,CACF"}
|
|
1
|
+
{"version":3,"file":"CodegenError.mjs","names":["Ansi.red"],"sources":["../src/CodegenError.ts"],"sourcesContent":["import * as Array from \"effect/Array\";\nimport * as Console from \"effect/Console\";\nimport { pipe } from \"effect/Function\";\nimport * as Effect from \"effect/Effect\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport { BuildError, isBuildError } from \"./BuildError.js\";\nimport { SnapshotError } from \"./SnapshotError.js\";\nimport * as Ansi from \"./Ansi.js\";\nimport { formatPath, renderBuildError } from \"./log.js\";\n\n// --- Variants ---\n\nexport class MissingImplFileError extends Schema.TaggedError<MissingImplFileError>()(\n \"MissingImplFileError\",\n {\n specPath: Schema.String,\n expectedImplPath: Schema.String,\n },\n) {}\n\nexport class MissingSpecFileError extends Schema.TaggedError<MissingSpecFileError>()(\n \"MissingSpecFileError\",\n {\n implPath: Schema.String,\n expectedSpecPath: Schema.String,\n },\n) {}\n\nexport class SpecMissingDefaultGroupSpecError extends Schema.TaggedError<SpecMissingDefaultGroupSpecError>()(\n \"SpecMissingDefaultGroupSpecError\",\n {\n specPath: Schema.String,\n },\n) {}\n\nexport class RemoveBusyError extends Schema.TaggedError<RemoveBusyError>()(\n \"RemoveBusyError\",\n { path: Schema.String, attempts: Schema.Finite, cause: Schema.Unknown },\n) {}\n\nexport class ComponentNodeGroupError extends Schema.TaggedError<ComponentNodeGroupError>()(\n \"ComponentNodeGroupError\",\n {\n specPath: Schema.String,\n groupPath: Schema.String,\n },\n) {}\n\nexport class SpecImportsServerError extends Schema.TaggedError<SpecImportsServerError>()(\n \"SpecImportsServerError\",\n {\n specPath: Schema.String,\n importerPaths: Schema.Array(Schema.String),\n },\n) {}\n\nexport class InvalidMiddlewareAttachmentError extends Schema.TaggedError<InvalidMiddlewareAttachmentError>()(\n \"InvalidMiddlewareAttachmentError\",\n { specPath: Schema.String, message: Schema.String },\n) {}\n\nexport class ImplMissingSpecImportError extends Schema.TaggedError<ImplMissingSpecImportError>()(\n \"ImplMissingSpecImportError\",\n {\n implPath: Schema.String,\n expectedSpecPath: Schema.String,\n },\n) {}\n\nexport class ImplMissingDefaultLayerError extends Schema.TaggedError<ImplMissingDefaultLayerError>()(\n \"ImplMissingDefaultLayerError\",\n {\n implPath: Schema.String,\n },\n) {}\n\nexport class ImplNotFinalizedError extends Schema.TaggedError<ImplNotFinalizedError>()(\n \"ImplNotFinalizedError\",\n {\n implPath: Schema.String,\n },\n) {}\n\nexport class ImplMissingFunctionsError extends Schema.TaggedError<ImplMissingFunctionsError>()(\n \"ImplMissingFunctionsError\",\n {\n implPath: Schema.String,\n groupPath: Schema.String,\n missingFunctionNames: Schema.Array(Schema.String),\n },\n) {}\n\nexport class ImplMissingMiddlewareError extends Schema.TaggedError<ImplMissingMiddlewareError>()(\n \"ImplMissingMiddlewareError\",\n {\n implPath: Schema.String,\n groupPath: Schema.String,\n missingMiddlewareKeys: Schema.Array(Schema.String),\n },\n) {}\n\nexport class ParentChildNameCollisionError extends Schema.TaggedError<ParentChildNameCollisionError>()(\n \"ParentChildNameCollisionError\",\n {\n parentSpecPath: Schema.String,\n childSpecPath: Schema.String,\n collisionName: Schema.String,\n collisionKind: Schema.Literals([\"function\", \"group\"]),\n },\n) {}\n\nexport class InvalidTableDefaultExportError extends Schema.TaggedError<InvalidTableDefaultExportError>()(\n \"InvalidTableDefaultExportError\",\n {\n tablePath: Schema.String,\n },\n) {}\n\nexport class InvalidTableFilenameError extends Schema.TaggedError<InvalidTableFilenameError>()(\n \"InvalidTableFilenameError\",\n {\n tablePath: Schema.String,\n reason: Schema.String,\n },\n) {}\n\nexport class DuplicateTableNameError extends Schema.TaggedError<DuplicateTableNameError>()(\n \"DuplicateTableNameError\",\n {\n // Every table name that more than one file resolves to, each paired with\n // the colliding file paths. All collisions are captured in a single pass\n // so the user can fix them together rather than re-running codegen once\n // per conflict.\n collisions: Schema.Array(\n Schema.Struct({\n tableName: Schema.String,\n tablePaths: Schema.Array(Schema.String),\n }),\n ),\n },\n) {}\n\nexport class LegacySchemaFileError extends Schema.TaggedError<LegacySchemaFileError>()(\n \"LegacySchemaFileError\",\n {\n schemaPath: Schema.String,\n },\n) {}\n\nexport class ConflictingDocNameError extends Schema.TaggedError<ConflictingDocNameError>()(\n \"ConflictingDocNameError\",\n {\n collisions: Schema.Array(\n Schema.Struct({\n docName: Schema.String,\n tableNames: Schema.Array(Schema.String),\n }),\n ),\n },\n) {}\n\nexport class InvalidConvexConfigError extends Schema.TaggedError<InvalidConvexConfigError>()(\n \"InvalidConvexConfigError\",\n {\n configPath: Schema.String,\n reason: Schema.String,\n },\n) {}\n\nexport class InvalidDeclarationError extends Schema.TaggedError<InvalidDeclarationError>()(\n \"InvalidDeclarationError\",\n {\n declarationPath: Schema.String,\n reason: Schema.String,\n },\n) {}\n\nexport class HandWrittenConvexFileError extends Schema.TaggedError<HandWrittenConvexFileError>()(\n \"HandWrittenConvexFileError\",\n {\n convexPath: Schema.String,\n declarationPath: Schema.String,\n },\n) {}\n\nexport class DeclarationKindMismatchError extends Schema.TaggedError<DeclarationKindMismatchError>()(\n \"DeclarationKindMismatchError\",\n {\n declarationPath: Schema.String,\n declaredKind: Schema.Literals([\"app\", \"component\"]),\n targetKind: Schema.Literals([\"app\", \"component\"]),\n },\n) {}\n\nexport class CallbackPrefixError extends Schema.TaggedError<CallbackPrefixError>()(\n \"CallbackPrefixError\",\n {\n declarationPath: Schema.String,\n contractId: Schema.String,\n componentName: Schema.String,\n },\n) {}\n\nexport const CodegenError = Schema.Union([\n SnapshotError,\n BuildError,\n MissingImplFileError,\n MissingSpecFileError,\n SpecMissingDefaultGroupSpecError,\n ComponentNodeGroupError,\n RemoveBusyError,\n SpecImportsServerError,\n InvalidMiddlewareAttachmentError,\n ImplMissingSpecImportError,\n ImplMissingDefaultLayerError,\n ImplNotFinalizedError,\n ImplMissingFunctionsError,\n ImplMissingMiddlewareError,\n ParentChildNameCollisionError,\n InvalidTableDefaultExportError,\n InvalidTableFilenameError,\n DuplicateTableNameError,\n LegacySchemaFileError,\n ConflictingDocNameError,\n InvalidConvexConfigError,\n InvalidDeclarationError,\n HandWrittenConvexFileError,\n DeclarationKindMismatchError,\n CallbackPrefixError,\n]);\nexport type CodegenError = typeof CodegenError.Type;\n\nexport const isCodegenError = (error: unknown): error is CodegenError => {\n if (isBuildError(error)) return true;\n return Schema.is(CodegenError)(error);\n};\n\n// --- Per-variant rendering ---\n\nconst cross = Ansi.red(\"✘\");\n\nconst stemFromSpecPath = (specPath: string): string => {\n const lastSep = Math.max(\n specPath.lastIndexOf(\"/\"),\n specPath.lastIndexOf(\"\\\\\"),\n );\n const basename = lastSep < 0 ? specPath : specPath.slice(lastSep + 1);\n return basename.endsWith(\".spec.ts\")\n ? basename.slice(0, -\".spec.ts\".length)\n : basename;\n};\n\nconst singleLine = (...parts: ReadonlyArray<string>): string =>\n `${cross} ${parts.join(\"\")}`;\n\nconst renderMissingImplFileError = (error: MissingImplFileError): string =>\n singleLine(\n \"Spec \",\n formatPath(error.specPath),\n \" has no sibling impl; create \",\n formatPath(error.expectedImplPath),\n \" and default-export a GroupImpl layer from it.\",\n );\n\nconst renderMissingSpecFileError = (error: MissingSpecFileError): string =>\n singleLine(\n \"Impl \",\n formatPath(error.implPath),\n \" has no sibling spec; create \",\n formatPath(error.expectedSpecPath),\n \" and default-export a GroupSpec from it, or remove the impl.\",\n );\n\nconst renderSpecMissingDefaultGroupSpecError = (\n error: SpecMissingDefaultGroupSpecError,\n): string =>\n singleLine(\n \"Spec \",\n formatPath(error.specPath),\n \" must default-export a GroupSpec; build it with GroupSpec.make() or GroupSpec.makeNode().\",\n );\n\nconst renderSpecImportsServerError = (\n error: SpecImportsServerError,\n): string => {\n const importers = error.importerPaths.join(\", \");\n return singleLine(\n \"Spec \",\n formatPath(error.specPath),\n ` reaches a module that imports \\`@confect/server\\`: ${importers}. Spec modules are bundled into your client, so anything they import ships to the browser—move the server logic into a \\`*.impl.ts\\` module, or use \\`import type\\` if you only need the types.`,\n );\n};\n\nconst renderImplMissingSpecImportError = (\n error: ImplMissingSpecImportError,\n): string => {\n const stem = stemFromSpecPath(error.expectedSpecPath);\n return singleLine(\n \"Impl \",\n formatPath(error.implPath),\n ` does not import its sibling spec; add \\`import ${stem} from \"./${stem}.spec.js\"\\` and pass it to FunctionImpl.make/GroupImpl.make.`,\n );\n};\n\nconst renderImplMissingDefaultLayerError = (\n error: ImplMissingDefaultLayerError,\n): string =>\n singleLine(\n \"Impl \",\n formatPath(error.implPath),\n \" must default-export a GroupImpl layer; wrap your handlers with `GroupImpl.make(databaseSchema, groupSpec).pipe(Layer.provide(...))` and `export default` it.\",\n );\n\nconst renderImplNotFinalizedError = (error: ImplNotFinalizedError): string =>\n singleLine(\n \"Impl \",\n formatPath(error.implPath),\n \" is not finalized; append `GroupImpl.finalize` to the end of the pipeline (e.g. `GroupImpl.make(databaseSchema, group).pipe(Layer.provide(...), GroupImpl.finalize)`).\",\n );\n\nconst renderImplMissingFunctionsError = (\n error: ImplMissingFunctionsError,\n): string => {\n const names = error.missingFunctionNames.join(\", \");\n return singleLine(\n \"Impl \",\n formatPath(error.implPath),\n ` does not implement every function declared by group \\`${error.groupPath}\\`; missing: ${names}. Add a \\`FunctionImpl.make\\` for each missing function and provide it to the group layer.`,\n );\n};\n\nconst renderImplMissingMiddlewareError = (\n error: ImplMissingMiddlewareError,\n): string => {\n const keys = error.missingMiddlewareKeys.join(\", \");\n return singleLine(\n \"Impl \",\n formatPath(error.implPath),\n ` does not implement every middleware attached to group \\`${error.groupPath}\\`; missing: ${keys}. Provide a \\`MiddlewareImpl.make\\` (or \\`makeByFunctionType\\`/\\`provides\\`) layer for each missing middleware to the group layer.`,\n );\n};\n\nconst renderInvalidTableDefaultExportError = (\n error: InvalidTableDefaultExportError,\n): string =>\n singleLine(\n \"Table \",\n formatPath(error.tablePath),\n \" must default-export a Table (e.g. `export default Table.make({ ... })`); convert any named export to a default export.\",\n );\n\nconst renderInvalidTableFilenameError = (\n error: InvalidTableFilenameError,\n): string =>\n singleLine(\n \"Table \",\n formatPath(error.tablePath),\n ` has an invalid filename: ${error.reason} Convex table names must start with a letter and contain only letters, numbers, and underscores; leading underscores are reserved for system tables.`,\n );\n\nconst renderDuplicateTableNameError = (\n error: DuplicateTableNameError,\n): string => {\n const conflicts = error.collisions\n .map(\n ({ tableName, tablePaths }) =>\n `\\`${tableName}\\` (${tablePaths.join(\", \")})`,\n )\n .join(\"; \");\n return singleLine(\n `Multiple files under \\`confect/tables/\\` resolve to the same table name. Table names are derived from filenames, so each must be unique across the directory (including subdirectories); rename or remove all but one. Conflicts: ${conflicts}.`,\n );\n};\n\nconst renderConflictingDocNameError = (\n error: ConflictingDocNameError,\n): string => {\n const conflicts = pipe(\n error.collisions,\n Array.map(\n ({ docName, tableNames }) =>\n `\\`${docName}\\` (${Array.join(tableNames, \", \")})`,\n ),\n Array.join(\"; \"),\n );\n return singleLine(\n `Multiple tables fold to the same generated document type name. Table names are converted to PascalCase (so \\`user_profiles\\` and \\`userProfiles\\` both become \\`UserProfilesDoc\\`); rename all but one of each colliding group. Conflicts: ${conflicts}.`,\n );\n};\n\nconst renderInvalidConvexConfigError = (\n error: InvalidConvexConfigError,\n): string =>\n singleLine(\n \"Convex config \",\n formatPath(error.configPath),\n ` could not be evaluated: ${error.reason}`,\n );\n\nconst renderLegacySchemaFileError = (error: LegacySchemaFileError): string =>\n singleLine(\n \"Found a legacy \",\n formatPath(error.schemaPath),\n \". Delete it: tables in `confect/tables/*.ts` are now the single source of truth, and the runtime schema is generated as `confect/_generated/schema.ts`.\",\n );\n\nconst renderParentChildNameCollisionError = (\n error: ParentChildNameCollisionError,\n): string =>\n singleLine(\n \"Spec \",\n formatPath(error.parentSpecPath),\n ` declares a ${error.collisionKind} \\`${error.collisionName}\\` whose name collides with the sibling subdirectory spec `,\n formatPath(error.childSpecPath),\n `. Rename one of them so the assembled spec has a unique key at this path.`,\n );\n\n/**\n * Render any {@link CodegenError} into a styled, ready-to-print string.\n * Single-error variants render to a one-line `✘`-prefixed message;\n * `BundleFailedError` (the only multi-error variant) renders to a header plus\n * an esbuild diagnostic block.\n */\nexport const renderCodegenError = (error: CodegenError): string => {\n if (isBuildError(error)) return renderBuildError(error);\n // The renderer pipeline below is at Effect's pipe arity limit, so the\n // fork's errors render here.\n if (error._tag === \"ComponentNodeGroupError\") {\n return singleLine(\n `Group \"${error.groupPath}\" in ${error.specPath} uses the Node runtime. Convex components do not support Node.js functions.`,\n );\n }\n if (error._tag === \"RemoveBusyError\") {\n return singleLine(\n \"Could not remove \",\n formatPath(error.path),\n ` after ${error.attempts} attempts because it is busy. Close other tools using it and try again.`,\n );\n }\n if (error._tag === \"InvalidDeclarationError\") {\n return singleLine(\n \"Declaration \",\n formatPath(error.declarationPath),\n ` is invalid: ${error.reason}`,\n );\n }\n if (error._tag === \"DeclarationKindMismatchError\") {\n return singleLine(\n \"Declaration \",\n formatPath(error.declarationPath),\n ` declares kind \"${error.declaredKind}\", but the target directory is kind \"${error.targetKind}\".`,\n );\n }\n if (error._tag === \"CallbackPrefixError\") {\n return singleLine(\n \"Callback contract \",\n `\"${error.contractId}\" in `,\n formatPath(error.declarationPath),\n ` must start with \"${error.componentName}/\" for component \"${error.componentName}\".`,\n );\n }\n if (error._tag === \"HandWrittenConvexFileError\") {\n return singleLine(\n \"Found a hand-written \",\n formatPath(error.convexPath),\n \". `confect codegen` writes it from \",\n formatPath(error.declarationPath),\n \" now; move its contents there and delete the file.\",\n );\n }\n return Match.value(error).pipe(\n Match.tag(\"SnapshotError\", ({ reason, relativePath, pathSegments }) =>\n singleLine(\n `Invalid generation metadata (${reason})`,\n relativePath === \"\" ? \"\" : ` for ${relativePath}`,\n pathSegments.length === 0 ? \".\" : ` at ${pathSegments.join(\"/\")}.`,\n ),\n ),\n Match.tag(\"MissingImplFileError\", renderMissingImplFileError),\n Match.tag(\"MissingSpecFileError\", renderMissingSpecFileError),\n Match.tag(\n \"SpecMissingDefaultGroupSpecError\",\n renderSpecMissingDefaultGroupSpecError,\n ),\n Match.tag(\"SpecImportsServerError\", renderSpecImportsServerError),\n Match.tag(\"InvalidMiddlewareAttachmentError\", (attachmentError) =>\n singleLine(\n \"Spec \",\n formatPath(attachmentError.specPath),\n `: ${attachmentError.message}`,\n ),\n ),\n Match.tag(\"ImplMissingSpecImportError\", renderImplMissingSpecImportError),\n Match.tag(\n \"ImplMissingDefaultLayerError\",\n renderImplMissingDefaultLayerError,\n ),\n Match.tag(\"ImplNotFinalizedError\", renderImplNotFinalizedError),\n Match.tag(\"ImplMissingFunctionsError\", renderImplMissingFunctionsError),\n Match.tag(\"ImplMissingMiddlewareError\", renderImplMissingMiddlewareError),\n Match.tag(\n \"ParentChildNameCollisionError\",\n renderParentChildNameCollisionError,\n ),\n Match.tag(\n \"InvalidTableDefaultExportError\",\n renderInvalidTableDefaultExportError,\n ),\n Match.tag(\"InvalidTableFilenameError\", renderInvalidTableFilenameError),\n Match.tag(\"DuplicateTableNameError\", renderDuplicateTableNameError),\n Match.tag(\"LegacySchemaFileError\", renderLegacySchemaFileError),\n Match.tag(\"ConflictingDocNameError\", renderConflictingDocNameError),\n Match.tag(\"InvalidConvexConfigError\", renderInvalidConvexConfigError),\n Match.exhaustive,\n );\n};\n\nexport const logCodegenError = (error: CodegenError) =>\n Console.error(renderCodegenError(error));\n\n// --- Effect combinators ---\n\n/**\n * Log any {@link CodegenError} thrown by `effect` and propagate the failure\n * unchanged so the caller's error channel is preserved.\n */\nexport const tapAndLog = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<A, E, R> =>\n effect.pipe(\n Effect.tapError((error) =>\n isCodegenError(error) ? logCodegenError(error) : Effect.void,\n ),\n );\n\n/**\n * Catch any {@link CodegenError} thrown by `effect`, log it, and resolve to\n * `Option.none()`. Success resolves to `Option.some(value)`.\n */\n// oxlint-disable effecttsgo/unsafe-effect-type-assertion -- catchIf removes the error variant selected by this refinement.\nexport const catchAndLog = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<Option.Option<A>, Exclude<E, CodegenError>, R> =>\n Effect.catchIf(Effect.map(effect, Option.some<A>), isCodegenError, (error) =>\n logCodegenError(error).pipe(Effect.as(Option.none<A>())),\n ) as Effect.Effect<Option.Option<A>, Exclude<E, CodegenError>, R>;\n// oxlint-enable effecttsgo/unsafe-effect-type-assertion\n"],"mappings":";;;;;;;;;;;;AAcA,IAAa,uBAAb,cAA0C,OAAO,YAAkC,CAAC,CAClF,wBACA;CACE,UAAU,OAAO;CACjB,kBAAkB,OAAO;AAC3B,CACF,CAAC,CAAC,CAAC;AAEH,IAAa,uBAAb,cAA0C,OAAO,YAAkC,CAAC,CAClF,wBACA;CACE,UAAU,OAAO;CACjB,kBAAkB,OAAO;AAC3B,CACF,CAAC,CAAC,CAAC;AAEH,IAAa,mCAAb,cAAsD,OAAO,YAA8C,CAAC,CAC1G,oCACA,EACE,UAAU,OAAO,OACnB,CACF,CAAC,CAAC,CAAC;AAEH,IAAa,kBAAb,cAAqC,OAAO,YAA6B,CAAC,CACxE,mBACA;CAAE,MAAM,OAAO;CAAQ,UAAU,OAAO;CAAQ,OAAO,OAAO;AAAQ,CACxE,CAAC,CAAC,CAAC;AAEH,IAAa,0BAAb,cAA6C,OAAO,YAAqC,CAAC,CACxF,2BACA;CACE,UAAU,OAAO;CACjB,WAAW,OAAO;AACpB,CACF,CAAC,CAAC,CAAC;AAEH,IAAa,yBAAb,cAA4C,OAAO,YAAoC,CAAC,CACtF,0BACA;CACE,UAAU,OAAO;CACjB,eAAe,OAAO,MAAM,OAAO,MAAM;AAC3C,CACF,CAAC,CAAC,CAAC;AAEH,IAAa,mCAAb,cAAsD,OAAO,YAA8C,CAAC,CAC1G,oCACA;CAAE,UAAU,OAAO;CAAQ,SAAS,OAAO;AAAO,CACpD,CAAC,CAAC,CAAC;AAEH,IAAa,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,MAAM,IAAI,6BAA6B,+BAA+B,GACtE,MAAM,IAAI,2BAA2B,6BAA6B,GAClE,MAAM,IAAI,yBAAyB,2BAA2B,GAC9D,MAAM,IAAI,2BAA2B,6BAA6B,GAClE,MAAM,IAAI,4BAA4B,8BAA8B,GACpE,MAAM,UACR;AACF;AAEA,MAAa,mBAAmB,UAC9B,QAAQ,MAAM,mBAAmB,KAAK,CAAC;;;;;AAQzC,MAAa,aACX,WAEA,OAAO,KACL,OAAO,UAAU,UACf,eAAe,KAAK,IAAI,gBAAgB,KAAK,IAAI,OAAO,IAC1D,CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ConfectDirectory.mjs","names":["ConvexDirectory.layer"],"sources":["../src/ConfectDirectory.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Path from \"effect/Path\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as ConvexDirectory from \"./ConvexDirectory\";\n\nexport class ConfectDirectory extends Context.Service<\n ConfectDirectory,\n { readonly get: Effect.Effect<string> }\n>()(\"@confect/cli/ConfectDirectory\") {\n static readonly get = ConfectDirectory.use((service) => service.get);\n}\n\nexport class ConfectDirectoryNotFoundError extends Schema.TaggedError<ConfectDirectoryNotFoundError>()(\n \"ConfectDirectoryNotFoundError\",\n {},\n) {\n override get message(): string {\n return \"Could not find Confect directory\";\n }\n}\n\nexport const findConfectDirectory = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n\n const convexDirectory = yield* ConvexDirectory.ConvexDirectory.get;\n\n const confectDirectory = path.join(path.dirname(convexDirectory), \"confect\");\n\n if (yield* fs.exists(confectDirectory)) {\n return confectDirectory;\n } else {\n return yield* new ConfectDirectoryNotFoundError();\n }\n});\n\nexport const layerFromConvexDirectory = Layer.effect(\n ConfectDirectory,\n Effect.gen(function* () {\n const confectDirectory = yield* findConfectDirectory;\n\n const ref = yield* Ref.make<string>(confectDirectory);\n\n return { get: Ref.get(ref) } as const;\n }),\n);\n\nexport const layer = layerFromConvexDirectory.pipe(\n Layer.provide(ConvexDirectory.layer),\n);\n"],"mappings":";;;;;;;;;AASA,IAAa,mBAAb,MAAa,yBAAyB,QAAQ,QAG5C,CAAC,CAAC,+BAA+B,CAAC,CAAC;CACnC,OAAgB,MAAM,iBAAiB,KAAK,YAAY,QAAQ,GAAG;AACrE;AAEA,IAAa,gCAAb,cAAmD,OAAO,YAA2C,CAAC,CACpG,iCACA,CAAC,CACH,CAAC,CAAC;CACA,IAAa,UAAkB;EAC7B,OAAO;CACT;AACF;AAEA,MAAa,uBAAuB,OAAO,IAAI,aAAa;CAC1D,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,OAAO,OAAO,KAAK;CAEzB,MAAM,kBAAkB,OAAA,gBAAuC;CAE/D,MAAM,mBAAmB,KAAK,KAAK,KAAK,QAAQ,eAAe,GAAG,SAAS;CAE3E,IAAI,OAAO,GAAG,OAAO,gBAAgB,GACnC,OAAO;MAEP,OAAO,OAAO,IAAI,8BAA8B;AAEpD,CAAC;AAED,MAAa,2BAA2B,MAAM,OAC5C,kBACA,OAAO,IAAI,aAAa;CACtB,MAAM,mBAAmB,OAAO;CAEhC,MAAM,MAAM,OAAO,IAAI,KAAa,gBAAgB;CAEpD,OAAO,EAAE,KAAK,IAAI,IAAI,GAAG,EAAE;AAC7B,CAAC,CACH;AAEqB,yBAAyB,KAC5C,MAAM,QAAQA,OAAqB,CACrC"}
|
|
1
|
+
{"version":3,"file":"ConfectDirectory.mjs","names":["ConvexDirectory.layer"],"sources":["../src/ConfectDirectory.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Path from \"effect/Path\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as ConvexDirectory from \"./ConvexDirectory.js\";\n\nexport class ConfectDirectory extends Context.Service<\n ConfectDirectory,\n { readonly get: Effect.Effect<string> }\n>()(\"@confect/cli/ConfectDirectory\") {\n static readonly get = ConfectDirectory.use((service) => service.get);\n}\n\nexport class ConfectDirectoryNotFoundError extends Schema.TaggedError<ConfectDirectoryNotFoundError>()(\n \"ConfectDirectoryNotFoundError\",\n {},\n) {\n override get message(): string {\n return \"Could not find Confect directory\";\n }\n}\n\nexport const findConfectDirectory = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n\n const convexDirectory = yield* ConvexDirectory.ConvexDirectory.get;\n\n const confectDirectory = path.join(path.dirname(convexDirectory), \"confect\");\n\n if (yield* fs.exists(confectDirectory)) {\n return confectDirectory;\n } else {\n return yield* new ConfectDirectoryNotFoundError();\n }\n});\n\nexport const layerFromConvexDirectory = Layer.effect(\n ConfectDirectory,\n Effect.gen(function* () {\n const confectDirectory = yield* findConfectDirectory;\n\n const ref = yield* Ref.make<string>(confectDirectory);\n\n return { get: Ref.get(ref) } as const;\n }),\n);\n\nexport const layer = layerFromConvexDirectory.pipe(\n Layer.provide(ConvexDirectory.layer),\n);\n"],"mappings":";;;;;;;;;AASA,IAAa,mBAAb,MAAa,yBAAyB,QAAQ,QAG5C,CAAC,CAAC,+BAA+B,CAAC,CAAC;CACnC,OAAgB,MAAM,iBAAiB,KAAK,YAAY,QAAQ,GAAG;AACrE;AAEA,IAAa,gCAAb,cAAmD,OAAO,YAA2C,CAAC,CACpG,iCACA,CAAC,CACH,CAAC,CAAC;CACA,IAAa,UAAkB;EAC7B,OAAO;CACT;AACF;AAEA,MAAa,uBAAuB,OAAO,IAAI,aAAa;CAC1D,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,OAAO,OAAO,KAAK;CAEzB,MAAM,kBAAkB,OAAA,gBAAuC;CAE/D,MAAM,mBAAmB,KAAK,KAAK,KAAK,QAAQ,eAAe,GAAG,SAAS;CAE3E,IAAI,OAAO,GAAG,OAAO,gBAAgB,GACnC,OAAO;MAEP,OAAO,OAAO,IAAI,8BAA8B;AAEpD,CAAC;AAED,MAAa,2BAA2B,MAAM,OAC5C,kBACA,OAAO,IAAI,aAAa;CACtB,MAAM,mBAAmB,OAAO;CAEhC,MAAM,MAAM,OAAO,IAAI,KAAa,gBAAgB;CAEpD,OAAO,EAAE,KAAK,IAAI,IAAI,GAAG,EAAE;AAC7B,CAAC,CACH;AAEqB,yBAAyB,KAC5C,MAAM,QAAQA,OAAqB,CACrC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ConvexConfig.mjs","names":["Bundler.resolveModule","Bundler.bundle"],"sources":["../src/ConvexConfig.ts"],"sourcesContent":["import { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as Match from \"effect/Match\";\nimport type * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Order from \"effect/Order\";\nimport * as Path from \"effect/Path\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Record from \"effect/Record\";\nimport * as Schema from \"effect/Schema\";\nimport * as String from \"effect/String\";\nimport type * as esbuild from \"esbuild\";\nimport { fromBundlerError, type BuildError } from \"./BuildError\";\nimport * as Bundler from \"./Bundler\";\nimport { InvalidConvexConfigError } from \"./CodegenError\";\nimport { toPosixPath } from \"./utils\";\n\nexport const CONVEX_CONFIG_FILENAME = \"convex.config.ts\";\n\n/**\n * A component installed on the app via `app.use(...)` in\n * `convex/convex.config.ts`.\n */\nexport interface InstalledComponent {\n /**\n * The mount name (`app.use`'s `name` option, falling back to the name the\n * component was defined with).\n */\n readonly name: string;\n readonly httpPrefix?: string;\n /**\n * The directory the component's definition lives in, mirroring the Convex\n * runtime's convention (a `componentDefinitionPath` identifies the\n * definition's directory): the import specifier minus its trailing\n * `convex.config` segment when it was bare (e.g. `@convex-dev/workpool`), or\n * the resolved absolute directory when it was relative (a locally-defined\n * component).\n */\n readonly componentDefinitionPath: string;\n}\n\nconst COMPONENT_CONFIG_NAMESPACE = \"confect-component-config\";\n\n/**\n * Where the plugin records how a definition was imported: the specifier as\n * written and the file it resolved to. Codegen reads it to write the import of\n * each mounted component into the generated `convex.config.ts`.\n */\nexport const COMPONENT_IMPORT_KEY = \"~confect/componentImport\";\n\nexport interface ComponentImport {\n readonly specifier: string;\n readonly path: string;\n}\n\nexport const componentImportOf = (\n definition: unknown,\n): Option.Option<ComponentImport> => {\n if (!Predicate.hasProperty(definition, COMPONENT_IMPORT_KEY)) {\n return Option.none();\n }\n const recorded = definition[COMPONENT_IMPORT_KEY];\n return Predicate.hasProperty(recorded, \"specifier\") &&\n Predicate.isString(recorded.specifier) &&\n Predicate.hasProperty(recorded, \"path\") &&\n Predicate.isString(recorded.path)\n ? Option.some({ specifier: recorded.specifier, path: recorded.path })\n : Option.none();\n};\n\n/**\n * Matches the trailing `convex.config` segment of a component-definition import\n * (with or without an extension), e.g. `@convex-dev/workpool/convex.config` or\n * `./waitlist/convex.config.ts`.\n */\nconst CONVEX_CONFIG_SUFFIX = /[/\\\\]convex\\.config(\\.[cm]?[jt]s)?$/;\n\n/**\n * Resolve the same config spellings that Convex accepts, for configs and test\n * kits.\n */\nexport const resolveDefinition = (\n specifier: string,\n importer: string,\n path: Path.Path,\n): Option.Option<string> => {\n const extension = path.extname(specifier);\n const candidates = [\n specifier,\n ...(extension === \".js\" ? [specifier.slice(0, -3) + \".ts\"] : []),\n ...(extension !== \".js\" && extension !== \".ts\"\n ? [specifier + \".js\", specifier + \".ts\"]\n : []),\n ];\n return Option.firstSomeOf(\n candidates.map((candidate) => Bundler.resolveModule(candidate, importer)),\n );\n};\n\n/**\n * `convex/server`'s `app.use(definition)` rejects any definition object that\n * lacks a string `componentDefinitionPath` (\"This code only works in Convex\n * runtime\"): that property is normally stamped on by the Convex backend's\n * module system when it evaluates a definition bundle. To evaluate\n * `convex.config.ts` in plain Node, this plugin intercepts every non-entry\n * import of a `convex.config` module (mirroring the Convex CLI's own\n * `componentPlugin`) and swaps in a virtual wrapper that re-exports the real\n * definition with `componentDefinitionPath` and `defaultName` filled in—the\n * exact shape of Convex's `ImportedComponentDefinition`.\n */\nexport const componentConfigPlugin = (path: Path.Path): esbuild.Plugin => ({\n name: \"confect:component-config\",\n setup(build) {\n build.onResolve({ filter: /convex\\.config/ }, (args) => {\n // The app's own `convex.config.ts` is the entry point; only imports of\n // *component* definitions get wrapped.\n if (args.kind === \"entry-point\") return undefined;\n\n // Claim a wrapper's import of the real definition into the file\n // namespace: bundled, the definition's own nested `convex.config`\n // imports re-enter this plugin and get stamped; externalized, an npm\n // definition would be evaluated natively by Node, where its top-level\n // `component.use(...)` of unstamped nested definitions throws.\n if (args.namespace === COMPONENT_CONFIG_NAMESPACE) {\n return { path: args.path };\n }\n if (args.namespace !== \"file\" && args.namespace !== \"\") return undefined;\n\n const importer =\n args.importer !== \"\" ? args.importer : path.join(args.resolveDir, \"_\");\n\n // Component definitions are conventionally imported extensionless\n // (`.../convex.config`), which npm `exports` maps resolve but plain\n // file resolution may not—probe the same candidates Convex does.\n return pipe(\n resolveDefinition(args.path, importer, path),\n Option.match({\n onNone: () => undefined,\n onSome: (resolved) => ({\n path: resolved,\n namespace: COMPONENT_CONFIG_NAMESPACE,\n pluginData: { specifier: args.path },\n }),\n }),\n );\n });\n\n build.onLoad(\n { filter: /.*/, namespace: COMPONENT_CONFIG_NAMESPACE },\n (args) => {\n const specifier = (args.pluginData as { specifier: string }).specifier;\n // The injected path is the definition's *directory*, matching the\n // Convex runtime's convention—so even if a future convex version\n // stops reading `defaultName`, `app.use`'s last-resort fallback\n // (`componentDefinitionPath.split(\"/\").pop()`) still yields the\n // conventional component name rather than `convex.config`. Convex's\n // codegen doesn't trust relative specifiers as identifiers (the\n // importer's location is lost after bundling), so those are recorded\n // as the resolved absolute directory; bare specifiers keep their\n // package prefix so the generated type import stays a package\n // specifier.\n const isBareSpecifier =\n !String.startsWith(\".\")(specifier) && !path.isAbsolute(specifier);\n const componentDefinitionPath = isBareSpecifier\n ? String.replace(CONVEX_CONFIG_SUFFIX, \"\")(specifier)\n : path.dirname(args.path);\n\n // The real module is imported (not inlined) so any nested\n // `convex.config` imports resolve from the definition's own file\n // rather than from this virtual wrapper. `defaultName` comes from\n // `defineComponent(name)`'s `_name`, keeping `app.use`'s name\n // resolution identical to the Convex runtime's.\n return {\n loader: \"js\",\n resolveDir: path.dirname(args.path),\n contents: Array.join(\n [\n `import real from ${JSON.stringify(args.path)};`,\n `export default { ...real, componentDefinitionPath: ${JSON.stringify(componentDefinitionPath)}, defaultName: real._name, [${JSON.stringify(COMPONENT_IMPORT_KEY)}]: ${JSON.stringify({ specifier, path: args.path })} };`,\n ],\n \"\\n\",\n ),\n };\n },\n );\n },\n});\n\n/**\n * The subset of `app.export()` (Convex's `AppDefinitionAnalysis`) that the\n * registry needs: each installed component's mount name and the\n * `componentDefinitionPath` injected by {@link componentConfigPlugin}.\n */\nconst AppDefinitionAnalysis = Schema.Struct({\n httpMounts: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),\n childComponents: Schema.Array(\n Schema.Struct({\n name: Schema.String,\n path: Schema.String,\n }),\n ),\n});\n\nconst byName = Order.mapInput(\n Order.String,\n (component: InstalledComponent) => component.name,\n);\n\n/**\n * Convex component names must be alphanumeric plus underscores (see\n * `defineComponent`'s docs). Beyond rejecting genuinely invalid names, this is\n * a drift tripwire: if a future convex version stopped resolving names the way\n * we rely on (e.g. `defaultName` disappearing), the fallback name would be a\n * path segment like `convex.config`—caught here as a clear error instead of\n * silently emitting a broken registry.\n */\nconst VALID_COMPONENT_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/**\n * Bundle and evaluate `convex/convex.config.ts` and list the components\n * installed on the app, in mount-name order. `displayPath` is used in error\n * messages (mirroring how impl/spec bundling reports relative paths).\n */\nexport const discoverInstalledComponents = Effect.fn(\n \"ConvexConfig.discoverInstalledComponents\",\n)(function* (\n convexConfigPath: string,\n displayPath: string,\n kind: \"app\" | \"component\" = \"app\",\n): Effect.fn.Return<\n ReadonlyArray<InstalledComponent>,\n BuildError | InvalidConvexConfigError,\n Path.Path | FileSystem.FileSystem\n> {\n const path = yield* Path.Path;\n\n const { module } = yield* Bundler.bundle(convexConfigPath, {\n plugins: [componentConfigPlugin(path)],\n }).pipe(Effect.mapError((error) => fromBundlerError(displayPath, error)));\n\n const app = module.default as\n | { _isRoot?: unknown; export?: unknown }\n | null\n | undefined;\n\n const definition = Match.value(kind).pipe(\n Match.when(\"app\", () => ({ isRoot: true, constructor: \"defineApp\" })),\n Match.when(\"component\", () => ({\n isRoot: false,\n constructor: \"defineComponent\",\n })),\n Match.exhaustive,\n );\n\n if (\n app === null ||\n typeof app !== \"object\" ||\n app._isRoot !== definition.isRoot ||\n typeof app.export !== \"function\"\n ) {\n return yield* new InvalidConvexConfigError({\n configPath: displayPath,\n reason: `it must default-export the ${kind} definition created by \\`${definition.constructor}()\\`.`,\n });\n }\n\n const analysis = yield* Effect.try({\n try: () => (app.export as () => unknown)(),\n catch: (cause) =>\n new InvalidConvexConfigError({\n configPath: displayPath,\n reason: `exporting the app definition threw: ${globalThis.String(cause)}.`,\n }),\n });\n\n const decoded = yield* Schema.decodeUnknownEffect(AppDefinitionAnalysis)(\n analysis,\n ).pipe(\n Effect.mapError(\n (cause) =>\n new InvalidConvexConfigError({\n configPath: displayPath,\n reason: `the app definition's installed components could not be read: ${cause.message}.`,\n }),\n ),\n );\n\n const components = pipe(\n decoded.childComponents,\n Array.map(({ name, path: componentDefinitionPath }): InstalledComponent => {\n const httpPrefix = Object.entries(decoded.httpMounts ?? {}).find(\n ([, reference]) => reference === `_reference/childComponent/${name}`,\n )?.[0];\n return {\n name,\n componentDefinitionPath,\n ...(httpPrefix === undefined\n ? {}\n : { httpPrefix: httpPrefix.replace(/\\/$/, \"\") }),\n };\n }),\n Array.sort(byName),\n );\n\n const invalidNames = pipe(\n components,\n Array.map(({ name }) => name),\n Array.filter((name) =>\n Option.isNone(String.match(VALID_COMPONENT_NAME)(name)),\n ),\n );\n if (Array.isArrayNonEmpty(invalidNames)) {\n return yield* new InvalidConvexConfigError({\n configPath: displayPath,\n reason: `component names must be alphanumeric plus underscores, but got: ${pipe(\n invalidNames,\n Array.map((name) => `\"${name}\"`),\n Array.join(\", \"),\n )}. Pass a valid \\`name\\` to \\`app.use\\`.`,\n });\n }\n\n const duplicateNames = pipe(\n components,\n Array.groupBy(({ name }) => name),\n Record.toEntries,\n Array.filter(([, group]) => group.length > 1),\n Array.map(([name]) => name),\n );\n if (Array.isArrayNonEmpty(duplicateNames)) {\n return yield* new InvalidConvexConfigError({\n configPath: displayPath,\n reason: `multiple components are installed under the same name (${Array.join(duplicateNames, \", \")}); pass a unique \\`name\\` to \\`app.use\\` for each.`,\n });\n }\n\n return components;\n});\n\n/**\n * The name passed to `defineComponent`, independent of the package's ID scope.\n */\nexport const componentName = Effect.fnUntraced(function* (configPath: string) {\n const path = yield* Path.Path;\n const { module } = yield* Bundler.bundle(configPath, {\n plugins: [componentConfigPlugin(path)],\n }).pipe(\n Effect.mapError((error) =>\n fromBundlerError(\"convex/convex.config.ts\", error),\n ),\n );\n const definition: unknown = module.default;\n if (\n !Predicate.hasProperty(definition, \"_name\") ||\n !Predicate.isString(definition._name)\n ) {\n return yield* new InvalidConvexConfigError({\n configPath: \"convex/convex.config.ts\",\n reason: \"the component definition must have a string name.\",\n });\n }\n return definition._name;\n});\n\n/**\n * The module specifier the generated registry's `ComponentApi` type import\n * should use for a component, following Convex's own codegen convention:\n * `<definition directory>/_generated/component.js`. Bare (npm) definition\n * directories are used verbatim; locally-defined components (recorded as\n * absolute directories) become a relative path from `confect/_generated`.\n */\nexport const typeImportPath = (\n path: Path.Path,\n componentDefinitionPath: string,\n confectGeneratedDirectory: string,\n): string => {\n if (!path.isAbsolute(componentDefinitionPath)) {\n return componentDefinitionPath;\n }\n const relative = toPosixPath(\n path,\n path.relative(confectGeneratedDirectory, componentDefinitionPath),\n );\n return String.startsWith(\".\")(relative) ? relative : `./${relative}`;\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAkBA,MAAa,yBAAyB;AAwBtC,MAAM,6BAA6B;;;;;;AAOnC,MAAa,uBAAuB;AAOpC,MAAa,qBACX,eACmC;CACnC,IAAI,CAAC,UAAU,YAAY,YAAA,0BAAgC,GACzD,OAAO,OAAO,KAAK;CAErB,MAAM,WAAW,WAAW;CAC5B,OAAO,UAAU,YAAY,UAAU,WAAW,KAChD,UAAU,SAAS,SAAS,SAAS,KACrC,UAAU,YAAY,UAAU,MAAM,KACtC,UAAU,SAAS,SAAS,IAAI,IAC9B,OAAO,KAAK;EAAE,WAAW,SAAS;EAAW,MAAM,SAAS;CAAK,CAAC,IAClE,OAAO,KAAK;AAClB;;;;;;AAOA,MAAM,uBAAuB;;;;;AAM7B,MAAa,qBACX,WACA,UACA,SAC0B;CAC1B,MAAM,YAAY,KAAK,QAAQ,SAAS;CACxC,MAAM,aAAa;EACjB;EACA,GAAI,cAAc,QAAQ,CAAC,UAAU,MAAM,GAAG,EAAE,IAAI,KAAK,IAAI,CAAC;EAC9D,GAAI,cAAc,SAAS,cAAc,QACrC,CAAC,YAAY,OAAO,YAAY,KAAK,IACrC,CAAC;CACP;CACA,OAAO,OAAO,YACZ,WAAW,KAAK,cAAcA,cAAsB,WAAW,QAAQ,CAAC,CAC1E;AACF;;;;;;;;;;;;AAaA,MAAa,yBAAyB,UAAqC;CACzE,MAAM;CACN,MAAM,OAAO;EACX,MAAM,UAAU,EAAE,QAAQ,iBAAiB,IAAI,SAAS;GAGtD,IAAI,KAAK,SAAS,eAAe,OAAO,KAAA;GAOxC,IAAI,KAAK,cAAc,4BACrB,OAAO,EAAE,MAAM,KAAK,KAAK;GAE3B,IAAI,KAAK,cAAc,UAAU,KAAK,cAAc,IAAI,OAAO,KAAA;GAE/D,MAAM,WACJ,KAAK,aAAa,KAAK,KAAK,WAAW,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;CAET,MAAM,WAAW,YACf,MACA,KAAK,SAAS,2BAA2B,uBAAuB,CAClE;CACA,OAAO,OAAO,WAAW,GAAG,CAAC,CAAC,QAAQ,IAAI,WAAW,KAAK;AAC5D"}
|
|
1
|
+
{"version":3,"file":"ConvexConfig.mjs","names":["Bundler.resolveModule","Bundler.bundle"],"sources":["../src/ConvexConfig.ts"],"sourcesContent":["import { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as Match from \"effect/Match\";\nimport type * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Order from \"effect/Order\";\nimport * as Path from \"effect/Path\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Record from \"effect/Record\";\nimport * as Schema from \"effect/Schema\";\nimport * as String from \"effect/String\";\nimport type * as esbuild from \"esbuild\";\nimport { fromBundlerError, type BuildError } from \"./BuildError.js\";\nimport * as Bundler from \"./Bundler.js\";\nimport { InvalidConvexConfigError } from \"./CodegenError.js\";\nimport { toPosixPath } from \"./utils.js\";\n\nexport const CONVEX_CONFIG_FILENAME = \"convex.config.ts\";\n\n/**\n * A component installed on the app via `app.use(...)` in\n * `convex/convex.config.ts`.\n */\nexport interface InstalledComponent {\n /**\n * The mount name (`app.use`'s `name` option, falling back to the name the\n * component was defined with).\n */\n readonly name: string;\n readonly httpPrefix?: string;\n /**\n * The directory the component's definition lives in, mirroring the Convex\n * runtime's convention (a `componentDefinitionPath` identifies the\n * definition's directory): the import specifier minus its trailing\n * `convex.config` segment when it was bare (e.g. `@convex-dev/workpool`), or\n * the resolved absolute directory when it was relative (a locally-defined\n * component).\n */\n readonly componentDefinitionPath: string;\n}\n\nconst COMPONENT_CONFIG_NAMESPACE = \"confect-component-config\";\n\n/**\n * Where the plugin records how a definition was imported: the specifier as\n * written and the file it resolved to. Codegen reads it to write the import of\n * each mounted component into the generated `convex.config.ts`.\n */\nexport const COMPONENT_IMPORT_KEY = \"~confect/componentImport\";\n\nexport interface ComponentImport {\n readonly specifier: string;\n readonly path: string;\n}\n\nexport const componentImportOf = (\n definition: unknown,\n): Option.Option<ComponentImport> => {\n if (!Predicate.hasProperty(definition, COMPONENT_IMPORT_KEY)) {\n return Option.none();\n }\n const recorded = definition[COMPONENT_IMPORT_KEY];\n return Predicate.hasProperty(recorded, \"specifier\") &&\n Predicate.isString(recorded.specifier) &&\n Predicate.hasProperty(recorded, \"path\") &&\n Predicate.isString(recorded.path)\n ? Option.some({ specifier: recorded.specifier, path: recorded.path })\n : Option.none();\n};\n\n/**\n * Matches the trailing `convex.config` segment of a component-definition import\n * (with or without an extension), e.g. `@convex-dev/workpool/convex.config` or\n * `./waitlist/convex.config.ts`.\n */\nconst CONVEX_CONFIG_SUFFIX = /[/\\\\]convex\\.config(\\.[cm]?[jt]s)?$/;\n\n/**\n * Resolve the same config spellings that Convex accepts, for configs and test\n * kits.\n */\nexport const resolveDefinition = (\n specifier: string,\n importer: string,\n path: Path.Path,\n): Option.Option<string> => {\n const extension = path.extname(specifier);\n const candidates = [\n specifier,\n ...(extension === \".js\" ? [specifier.slice(0, -3) + \".ts\"] : []),\n ...(extension !== \".js\" && extension !== \".ts\"\n ? [specifier + \".js\", specifier + \".ts\"]\n : []),\n ];\n return Option.firstSomeOf(\n candidates.map((candidate) => Bundler.resolveModule(candidate, importer)),\n );\n};\n\n/**\n * `convex/server`'s `app.use(definition)` rejects any definition object that\n * lacks a string `componentDefinitionPath` (\"This code only works in Convex\n * runtime\"): that property is normally stamped on by the Convex backend's\n * module system when it evaluates a definition bundle. To evaluate\n * `convex.config.ts` in plain Node, this plugin intercepts every non-entry\n * import of a `convex.config` module (mirroring the Convex CLI's own\n * `componentPlugin`) and swaps in a virtual wrapper that re-exports the real\n * definition with `componentDefinitionPath` and `defaultName` filled in—the\n * exact shape of Convex's `ImportedComponentDefinition`.\n */\nexport const componentConfigPlugin = (path: Path.Path): esbuild.Plugin => ({\n name: \"confect:component-config\",\n setup(build) {\n build.onResolve({ filter: /convex\\.config/ }, (args) => {\n // The app's own `convex.config.ts` is the entry point; only imports of\n // *component* definitions get wrapped.\n if (args.kind === \"entry-point\") return undefined;\n\n // Claim a wrapper's import of the real definition into the file\n // namespace: bundled, the definition's own nested `convex.config`\n // imports re-enter this plugin and get stamped; externalized, an npm\n // definition would be evaluated natively by Node, where its top-level\n // `component.use(...)` of unstamped nested definitions throws.\n if (args.namespace === COMPONENT_CONFIG_NAMESPACE) {\n return { path: args.path };\n }\n if (args.namespace !== \"file\" && args.namespace !== \"\") return undefined;\n\n const importer =\n args.importer !== \"\" ? args.importer : path.join(args.resolveDir, \"_\");\n\n // Component definitions are conventionally imported extensionless\n // (`.../convex.config`), which npm `exports` maps resolve but plain\n // file resolution may not—probe the same candidates Convex does.\n return pipe(\n resolveDefinition(args.path, importer, path),\n Option.match({\n onNone: () => undefined,\n onSome: (resolved) => ({\n path: resolved,\n namespace: COMPONENT_CONFIG_NAMESPACE,\n pluginData: { specifier: args.path },\n }),\n }),\n );\n });\n\n build.onLoad(\n { filter: /.*/, namespace: COMPONENT_CONFIG_NAMESPACE },\n (args) => {\n const specifier = (args.pluginData as { specifier: string }).specifier;\n // The injected path is the definition's *directory*, matching the\n // Convex runtime's convention—so even if a future convex version\n // stops reading `defaultName`, `app.use`'s last-resort fallback\n // (`componentDefinitionPath.split(\"/\").pop()`) still yields the\n // conventional component name rather than `convex.config`. Convex's\n // codegen doesn't trust relative specifiers as identifiers (the\n // importer's location is lost after bundling), so those are recorded\n // as the resolved absolute directory; bare specifiers keep their\n // package prefix so the generated type import stays a package\n // specifier.\n const isBareSpecifier =\n !String.startsWith(\".\")(specifier) && !path.isAbsolute(specifier);\n const componentDefinitionPath = isBareSpecifier\n ? String.replace(CONVEX_CONFIG_SUFFIX, \"\")(specifier)\n : path.dirname(args.path);\n\n // The real module is imported (not inlined) so any nested\n // `convex.config` imports resolve from the definition's own file\n // rather than from this virtual wrapper. `defaultName` comes from\n // `defineComponent(name)`'s `_name`, keeping `app.use`'s name\n // resolution identical to the Convex runtime's.\n return {\n loader: \"js\",\n resolveDir: path.dirname(args.path),\n contents: Array.join(\n [\n `import real from ${JSON.stringify(args.path)};`,\n `export default { ...real, componentDefinitionPath: ${JSON.stringify(componentDefinitionPath)}, defaultName: real._name, [${JSON.stringify(COMPONENT_IMPORT_KEY)}]: ${JSON.stringify({ specifier, path: args.path })} };`,\n ],\n \"\\n\",\n ),\n };\n },\n );\n },\n});\n\n/**\n * The subset of `app.export()` (Convex's `AppDefinitionAnalysis`) that the\n * registry needs: each installed component's mount name and the\n * `componentDefinitionPath` injected by {@link componentConfigPlugin}.\n */\nconst AppDefinitionAnalysis = Schema.Struct({\n httpMounts: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),\n childComponents: Schema.Array(\n Schema.Struct({\n name: Schema.String,\n path: Schema.String,\n }),\n ),\n});\n\nconst byName = Order.mapInput(\n Order.String,\n (component: InstalledComponent) => component.name,\n);\n\n/**\n * Convex component names must be alphanumeric plus underscores (see\n * `defineComponent`'s docs). Beyond rejecting genuinely invalid names, this is\n * a drift tripwire: if a future convex version stopped resolving names the way\n * we rely on (e.g. `defaultName` disappearing), the fallback name would be a\n * path segment like `convex.config`—caught here as a clear error instead of\n * silently emitting a broken registry.\n */\nconst VALID_COMPONENT_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/**\n * Bundle and evaluate `convex/convex.config.ts` and list the components\n * installed on the app, in mount-name order. `displayPath` is used in error\n * messages (mirroring how impl/spec bundling reports relative paths).\n */\nexport const discoverInstalledComponents = Effect.fn(\n \"ConvexConfig.discoverInstalledComponents\",\n)(function* (\n convexConfigPath: string,\n displayPath: string,\n kind: \"app\" | \"component\" = \"app\",\n): Effect.fn.Return<\n ReadonlyArray<InstalledComponent>,\n BuildError | InvalidConvexConfigError,\n Path.Path | FileSystem.FileSystem\n> {\n const path = yield* Path.Path;\n\n const { module } = yield* Bundler.bundle(convexConfigPath, {\n plugins: [componentConfigPlugin(path)],\n }).pipe(Effect.mapError((error) => fromBundlerError(displayPath, error)));\n\n const app = module.default as\n | { _isRoot?: unknown; export?: unknown }\n | null\n | undefined;\n\n const definition = Match.value(kind).pipe(\n Match.when(\"app\", () => ({ isRoot: true, constructor: \"defineApp\" })),\n Match.when(\"component\", () => ({\n isRoot: false,\n constructor: \"defineComponent\",\n })),\n Match.exhaustive,\n );\n\n if (\n app === null ||\n typeof app !== \"object\" ||\n app._isRoot !== definition.isRoot ||\n typeof app.export !== \"function\"\n ) {\n return yield* new InvalidConvexConfigError({\n configPath: displayPath,\n reason: `it must default-export the ${kind} definition created by \\`${definition.constructor}()\\`.`,\n });\n }\n\n const analysis = yield* Effect.try({\n try: () => (app.export as () => unknown)(),\n catch: (cause) =>\n new InvalidConvexConfigError({\n configPath: displayPath,\n reason: `exporting the app definition threw: ${globalThis.String(cause)}.`,\n }),\n });\n\n const decoded = yield* Schema.decodeUnknownEffect(AppDefinitionAnalysis)(\n analysis,\n ).pipe(\n Effect.mapError(\n (cause) =>\n new InvalidConvexConfigError({\n configPath: displayPath,\n reason: `the app definition's installed components could not be read: ${cause.message}.`,\n }),\n ),\n );\n\n const components = pipe(\n decoded.childComponents,\n Array.map(({ name, path: componentDefinitionPath }): InstalledComponent => {\n const httpPrefix = Object.entries(decoded.httpMounts ?? {}).find(\n ([, reference]) => reference === `_reference/childComponent/${name}`,\n )?.[0];\n return {\n name,\n componentDefinitionPath,\n ...(httpPrefix === undefined\n ? {}\n : { httpPrefix: httpPrefix.replace(/\\/$/, \"\") }),\n };\n }),\n Array.sort(byName),\n );\n\n const invalidNames = pipe(\n components,\n Array.map(({ name }) => name),\n Array.filter((name) =>\n Option.isNone(String.match(VALID_COMPONENT_NAME)(name)),\n ),\n );\n if (Array.isArrayNonEmpty(invalidNames)) {\n return yield* new InvalidConvexConfigError({\n configPath: displayPath,\n reason: `component names must be alphanumeric plus underscores, but got: ${pipe(\n invalidNames,\n Array.map((name) => `\"${name}\"`),\n Array.join(\", \"),\n )}. Pass a valid \\`name\\` to \\`app.use\\`.`,\n });\n }\n\n const duplicateNames = pipe(\n components,\n Array.groupBy(({ name }) => name),\n Record.toEntries,\n Array.filter(([, group]) => group.length > 1),\n Array.map(([name]) => name),\n );\n if (Array.isArrayNonEmpty(duplicateNames)) {\n return yield* new InvalidConvexConfigError({\n configPath: displayPath,\n reason: `multiple components are installed under the same name (${Array.join(duplicateNames, \", \")}); pass a unique \\`name\\` to \\`app.use\\` for each.`,\n });\n }\n\n return components;\n});\n\n/**\n * The name passed to `defineComponent`, independent of the package's ID scope.\n */\nexport const componentName = Effect.fnUntraced(function* (configPath: string) {\n const path = yield* Path.Path;\n const { module } = yield* Bundler.bundle(configPath, {\n plugins: [componentConfigPlugin(path)],\n }).pipe(\n Effect.mapError((error) =>\n fromBundlerError(\"convex/convex.config.ts\", error),\n ),\n );\n const definition: unknown = module.default;\n if (\n !Predicate.hasProperty(definition, \"_name\") ||\n !Predicate.isString(definition._name)\n ) {\n return yield* new InvalidConvexConfigError({\n configPath: \"convex/convex.config.ts\",\n reason: \"the component definition must have a string name.\",\n });\n }\n return definition._name;\n});\n\n/**\n * The module specifier the generated registry's `ComponentApi` type import\n * should use for a component, following Convex's own codegen convention:\n * `<definition directory>/_generated/component.js`. Bare (npm) definition\n * directories are used verbatim; locally-defined components (recorded as\n * absolute directories) become a relative path from `confect/_generated`.\n */\nexport const typeImportPath = (\n path: Path.Path,\n componentDefinitionPath: string,\n confectGeneratedDirectory: string,\n): string => {\n if (!path.isAbsolute(componentDefinitionPath)) {\n return componentDefinitionPath;\n }\n const relative = toPosixPath(\n path,\n path.relative(confectGeneratedDirectory, componentDefinitionPath),\n );\n return String.startsWith(\".\")(relative) ? relative : `./${relative}`;\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAkBA,MAAa,yBAAyB;AAwBtC,MAAM,6BAA6B;;;;;;AAOnC,MAAa,uBAAuB;AAOpC,MAAa,qBACX,eACmC;CACnC,IAAI,CAAC,UAAU,YAAY,YAAA,0BA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ent":["import * as IdScope from \"@confect/core/IdScope\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as ProjectRoot from \"./ProjectRoot\";\nimport type * as DatabaseSchema from \"@confect/server/DatabaseSchema\";\n\nexport class ConvexDirectory extends Context.Service<\n ConvexDirectory,\n {\n readonly get: Effect.Effect<string>;\n readonly target?:\n | DatabaseSchema.AppTarget\n | DatabaseSchema.ComponentTarget<IdScope.Component<string>>;\n }\n>()(\"@confect/cli/ConvexDirectory\") {\n static readonly get = ConvexDirectory.use((service) => service.get);\n static readonly target = ConvexDirectory.use((service) =>\n Effect.succeed(\n service.target ?? { kind: \"app\" as const, scope: IdScope.app },\n ),\n );\n}\n\nexport class ConvexDirectoryNotFoundError extends Schema.TaggedError<ConvexDirectoryNotFoundError>()(\n \"ConvexDirectoryNotFoundError\",\n {},\n) {\n override get message(): string {\n return \"Could not find Convex directory\";\n }\n}\n\n/**\n * Schema for `convex.json` configuration file.\n *\n * @see https://docs.convex.dev/production/project-configuration\n */\nconst ConvexJsonConfig = Schema.fromJsonString(\n Schema.Struct({\n functions: Schema.optional(Schema.String),\n }),\n);\n\nexport class InvalidConvexJsonError extends Schema.TaggedError<InvalidConvexJsonError>()(\n \"InvalidConvexJsonError\",\n {\n cause: Schema.Unknown,\n },\n) {\n override get message(): string {\n const detail = Predicate.isError(this.cause)\n ? `: ${this.cause.message}`\n : \"\";\n return `Failed to parse convex.json${detail}`;\n }\n}\n\nconst findConvexDirectory = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n\n const projectRoot = yield* ProjectRoot.ProjectRoot.get;\n\n const defaultPath = path.join(projectRoot, \"convex\");\n\n const convexJsonPath = path.join(projectRoot, \"convex.json\");\n\n const convexDirectory = (yield* fs.exists(convexJsonPath))\n ? yield* fs.readFileString(convexJsonPath).pipe(\n Effect.flatMap((json) =>\n Schema.decodeEffect(ConvexJsonConfig)(json).pipe(\n Effect.mapError((cause) => new InvalidConvexJsonError({ cause })),\n ),\n ),\n Effect.map((config) =>\n Option.fromNullishOr(config.functions).pipe(\n Option.map((functionsDir) => path.join(projectRoot, functionsDir)),\n Option.getOrElse(() => defaultPath),\n ),\n ),\n )\n : defaultPath;\n\n if (yield* fs.exists(convexDirectory)) {\n return convexDirectory;\n } else {\n return yield* new ConvexDirectoryNotFoundError();\n }\n});\n\nexport const layer = Layer.effect(\n ConvexDirectory,\n Effect.gen(function* () {\n const convexDirectory = yield* findConvexDirectory;\n\n const ref = yield* Ref.make<string>(convexDirectory);\n\n return { get: Ref.get(ref) } as const;\n }),\n).pipe(Layer.provide(ProjectRoot.layer));\n"],"mappings":";;;;;;;;;;;;AAaA,IAAa,kBAAb,MAAa,wBAAwB,QAAQ,QAQ3C,CAAC,CAAC,8BAA8B,CAAC,CAAC;CAClC,OAAgB,MAAM,gBAAgB,KAAK,YAAY,QAAQ,GAAG;CAClE,OAAgB,SAAS,gBAAgB,KAAK,YAC5C,OAAO,QACL,QAAQ,UAAU;EAAE,MAAM;EAAgB,OAAO,QAAQ;CAAI,CAC/D,CACF;AACF;AAEA,IAAa,+BAAb,cAAkD,OAAO,YAA0C,CAAC,CAClG,gCACA,CAAC,CACH,CAAC,CAAC;CACA,IAAa,UAAkB;EAC7B,OAAO;CACT;AACF;;;;;;AAOA,MAAM,mBAAmB,OAAO,eAC9B,OAAO,OAAO,EACZ,WAAW,OAAO,SAAS,OAAO,MAAM,EAC1C,CAAC,CACH;AAEA,IAAa,yBAAb,cAA4C,OAAO,YAAoC,CAAC,CACtF,0BACA,EACE,OAAO,OAAO,QAChB,CACF,CAAC,CAAC;CACA,IAAa,UAAkB;EAI7B,OAAO,8BAHQ,UAAU,QAAQ,KAAK,KAAK,IACvC,KAAK,KAAK,MAAM,YAChB;CAEN;AACF;AAEA,MAAM,sBAAsB,OAAO,IAAI,aAAa;CAClD,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,OAAO,OAAO,KAAK;CAEzB,MAAM,cAAc,OAAA,YAA+B;CAEnD,MAAM,cAAc,KAAK,KAAK,aAAa,QAAQ;CAEnD,MAAM,iBAAiB,KAAK,KAAK,aAAa,aAAa;CAE3D,MAAM,mBAAmB,OAAO,GAAG,OAAO,cAAc,KACpD,OAAO,GAAG,eAAe,cAAc,CAAC,CAAC,KACvC,OAAO,SAAS,SACd,OAAO,aAAa,gBAAgB,CAAC,CAAC,IAAI,CAAC,CAAC,KAC1C,OAAO,UAAU,UAAU,IAAI,uBAAuB,EAAE,MAAM,CAAC,CAAC,CAClE,CACF,GACA,OAAO,KAAK,WACV,OAAO,cAAc,OAAO,SAAS,CAAC,CAAC,KACrC,OAAO,KAAK,iBAAiB,KAAK,KAAK,aAAa,YAAY,CAAC,GACjE,OAAO,gBAAgB,WAAW,CACpC,CACF,CACF,IACA;CAEJ,IAAI,OAAO,GAAG,OAAO,eAAe,GAClC,OAAO;MAEP,OAAO,OAAO,IAAI,6BAA6B;AAEnD,CAAC;AAED,MAAa,QAAQ,MAAM,OACzB,iBACA,OAAO,IAAI,aAAa;CACtB,MAAM,kBAAkB,OAAO;CAE/B,MAAM,MAAM,OAAO,IAAI,KAAa,eAAe;CAEnD,OAAO,EAAE,KAAK,IAAI,IAAI,GAAG,EAAE;AAC7B,CAAC,CACH,CAAC,CAAC,KAAK,MAAM,QAAQA,OAAiB,CAAC"}
|
|
1
|
+
{"version":3,"file":"ConvexDirectory.mjs","names":["ProjectRoot.layer"],"sources":["../src/ConvexDirectory.ts"],"sourcesContent":["import * as IdScope from \"@confect/core/IdScope\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as ProjectRoot from \"./ProjectRoot.js\";\nimport type * as DatabaseSchema from \"@confect/server/DatabaseSchema\";\n\nexport class ConvexDirectory extends Context.Service<\n ConvexDirectory,\n {\n readonly get: Effect.Effect<string>;\n readonly target?:\n | DatabaseSchema.AppTarget\n | DatabaseSchema.ComponentTarget<IdScope.Component<string>>;\n }\n>()(\"@confect/cli/ConvexDirectory\") {\n static readonly get = ConvexDirectory.use((service) => service.get);\n static readonly target = ConvexDirectory.use((service) =>\n Effect.succeed(\n service.target ?? { kind: \"app\" as const, scope: IdScope.app },\n ),\n );\n}\n\nexport class ConvexDirectoryNotFoundError extends Schema.TaggedError<ConvexDirectoryNotFoundError>()(\n \"ConvexDirectoryNotFoundError\",\n {},\n) {\n override get message(): string {\n return \"Could not find Convex directory\";\n }\n}\n\n/**\n * Schema for `convex.json` configuration file.\n *\n * @see https://docs.convex.dev/production/project-configuration\n */\nconst ConvexJsonConfig = Schema.fromJsonString(\n Schema.Struct({\n functions: Schema.optional(Schema.String),\n }),\n);\n\nexport class InvalidConvexJsonError extends Schema.TaggedError<InvalidConvexJsonError>()(\n \"InvalidConvexJsonError\",\n {\n cause: Schema.Unknown,\n },\n) {\n override get message(): string {\n const detail = Predicate.isError(this.cause)\n ? `: ${this.cause.message}`\n : \"\";\n return `Failed to parse convex.json${detail}`;\n }\n}\n\nconst findConvexDirectory = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n\n const projectRoot = yield* ProjectRoot.ProjectRoot.get;\n\n const defaultPath = path.join(projectRoot, \"convex\");\n\n const convexJsonPath = path.join(projectRoot, \"convex.json\");\n\n const convexDirectory = (yield* fs.exists(convexJsonPath))\n ? yield* fs.readFileString(convexJsonPath).pipe(\n Effect.flatMap((json) =>\n Schema.decodeEffect(ConvexJsonConfig)(json).pipe(\n Effect.mapError((cause) => new InvalidConvexJsonError({ cause })),\n ),\n ),\n Effect.map((config) =>\n Option.fromNullishOr(config.functions).pipe(\n Option.map((functionsDir) => path.join(projectRoot, functionsDir)),\n Option.getOrElse(() => defaultPath),\n ),\n ),\n )\n : defaultPath;\n\n if (yield* fs.exists(convexDirectory)) {\n return convexDirectory;\n } else {\n return yield* new ConvexDirectoryNotFoundError();\n }\n});\n\nexport const layer = Layer.effect(\n ConvexDirectory,\n Effect.gen(function* () {\n const convexDirectory = yield* findConvexDirectory;\n\n const ref = yield* Ref.make<string>(convexDirectory);\n\n return { get: Ref.get(ref) } as const;\n }),\n).pipe(Layer.provide(ProjectRoot.layer));\n"],"mappings":";;;;;;;;;;;;AAaA,IAAa,kBAAb,MAAa,wBAAwB,QAAQ,QAQ3C,CAAC,CAAC,8BAA8B,CAAC,CAAC;CAClC,OAAgB,MAAM,gBAAgB,KAAK,YAAY,QAAQ,GAAG;CAClE,OAAgB,SAAS,gBAAgB,KAAK,YAC5C,OAAO,QACL,QAAQ,UAAU;EAAE,MAAM;EAAgB,OAAO,QAAQ;CAAI,CAC/D,CACF;AACF;AAEA,IAAa,+BAAb,cAAkD,OAAO,YAA0C,CAAC,CAClG,gCACA,CAAC,CACH,CAAC,CAAC;CACA,IAAa,UAAkB;EAC7B,OAAO;CACT;AACF;;;;;;AAOA,MAAM,mBAAmB,OAAO,eAC9B,OAAO,OAAO,EACZ,WAAW,OAAO,SAAS,OAAO,MAAM,EAC1C,CAAC,CACH;AAEA,IAAa,yBAAb,cAA4C,OAAO,YAAoC,CAAC,CACtF,0BACA,EACE,OAAO,OAAO,QAChB,CACF,CAAC,CAAC;CACA,IAAa,UAAkB;EAI7B,OAAO,8BAHQ,UAAU,QAAQ,KAAK,KAAK,IACvC,KAAK,KAAK,MAAM,YAChB;CAEN;AACF;AAEA,MAAM,sBAAsB,OAAO,IAAI,aAAa;CAClD,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,OAAO,OAAO,KAAK;CAEzB,MAAM,cAAc,OAAA,YAA+B;CAEnD,MAAM,cAAc,KAAK,KAAK,aAAa,QAAQ;CAEnD,MAAM,iBAAiB,KAAK,KAAK,aAAa,aAAa;CAE3D,MAAM,mBAAmB,OAAO,GAAG,OAAO,cAAc,KACpD,OAAO,GAAG,eAAe,cAAc,CAAC,CAAC,KACvC,OAAO,SAAS,SACd,OAAO,aAAa,gBAAgB,CAAC,CAAC,IAAI,CAAC,CAAC,KAC1C,OAAO,UAAU,UAAU,IAAI,uBAAuB,EAAE,MAAM,CAAC,CAAC,CAClE,CACF,GACA,OAAO,KAAK,WACV,OAAO,cAAc,OAAO,SAAS,CAAC,CAAC,KACrC,OAAO,KAAK,iBAAiB,KAAK,KAAK,aAAa,YAAY,CAAC,GACjE,OAAO,gBAAgB,WAAW,CACpC,CACF,CACF,IACA;CAEJ,IAAI,OAAO,GAAG,OAAO,eAAe,GAClC,OAAO;MAEP,OAAO,OAAO,IAAI,6BAA6B;AAEnD,CAAC;AAED,MAAa,QAAQ,MAAM,OACzB,iBACA,OAAO,IAAI,aAAa;CACtB,MAAM,kBAAkB,OAAO;CAE/B,MAAM,MAAM,OAAO,IAAI,KAAa,eAAe;CAEnD,OAAO,EAAE,KAAK,IAAI,IAAI,GAAG,EAAE;AAC7B,CAAC,CACH,CAAC,CAAC,KAAK,MAAM,QAAQA,OAAiB,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DirectoryOptions.mjs","names":["ProjectRoot.layer","ProjectRoot.ProjectRoot","ProjectRoot.findProjectRootFrom","ConvexDirectory.layer","ConvexDirectory.ConvexDirectory","ConvexDirectory.ConvexDirectoryNotFoundError"],"sources":["../src/DirectoryOptions.ts"],"sourcesContent":["import { IdScope } from \"@confect/core\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport * as Flag from \"effect/cli/Flag\";\nimport * as ConfectDirectory from \"./ConfectDirectory\";\nimport * as ConvexDirectory from \"./ConvexDirectory\";\nimport * as ProjectRoot from \"./ProjectRoot\";\n\nexport const flags = {\n componentDir: Flag.String(\"component-dir\").pipe(\n Flag.withDescription(\n \"Generate a component instead of the application; its sibling confect/ directory contains the source.\",\n ),\n Flag.optional,\n ),\n};\n\nexport const layer = ({\n componentDir,\n}: {\n componentDir: Option.Option<string>;\n}) => {\n const projectRootLayer = Option.match(componentDir, {\n onNone: () => ProjectRoot.layer,\n onSome: (directory) =>\n Layer.effect(\n ProjectRoot.ProjectRoot,\n Effect.map(ProjectRoot.findProjectRootFrom(directory), (root) =>\n ProjectRoot.ProjectRoot.of({\n get: Effect.succeed(root),\n }),\n ),\n ),\n });\n const convex: Layer.Layer<\n ConvexDirectory.ConvexDirectory,\n Layer.Error<typeof ConvexDirectory.layer> | Schema.SchemaError,\n FileSystem.FileSystem | Path.Path\n > = Option.match(componentDir, {\n onNone: () => ConvexDirectory.layer,\n onSome: (directory) =>\n Layer.effect(\n ConvexDirectory.ConvexDirectory,\n Effect.gen(function* () {\n const path = yield* Path.Path;\n const fs = yield* FileSystem.FileSystem;\n const projectRoot = yield* ProjectRoot.ProjectRoot.get;\n const absolute = path.resolve(directory);\n // A declared component's `convex.config.ts` is codegen output, so\n // its sibling `confect/app.ts` also marks the directory.\n if (\n !(yield* fs.exists(path.join(absolute, \"convex.config.ts\"))) &&\n !(yield* fs.exists(\n path.join(path.dirname(absolute), \"confect\", \"app.ts\"),\n ))\n ) {\n return yield* new ConvexDirectory.ConvexDirectoryNotFoundError();\n }\n const pkg = yield* fs\n .readFileString(path.join(projectRoot, \"package.json\"))\n .pipe(\n Effect.flatMap(\n Schema.decodeEffect(\n Schema.fromJsonString(Schema.Struct({ name: Schema.String })),\n ),\n ),\n );\n const definition = `${pkg.name}:${path.relative(projectRoot, absolute).split(path.sep).join(\"/\")}`;\n return ConvexDirectory.ConvexDirectory.of({\n get: Effect.succeed(absolute),\n target: {\n kind: \"component\",\n scope: IdScope.component(definition),\n },\n });\n }),\n ).pipe(Layer.provide(projectRootLayer)),\n });\n return Layer.mergeAll(\n projectRootLayer,\n ConfectDirectory.layerFromConvexDirectory.pipe(Layer.provideMerge(convex)),\n );\n};\n"],"mappings":";;;;;;;;;;;;AAYA,MAAa,QAAQ,EACnB,cAAc,KAAK,OAAO,eAAe,CAAC,CAAC,KACzC,KAAK,gBACH,sGACF,GACA,KAAK,QACP,EACF;AAEA,MAAa,SAAS,EACpB,mBAGI;CACJ,MAAM,mBAAmB,OAAO,MAAM,cAAc;EAClD,cAAcA;EACd,SAAS,cACP,MAAM,OACJC,aACA,OAAO,IAAIC,oBAAgC,SAAS,IAAI,SAAA,YAC9B,GAAG,EACzB,KAAK,OAAO,QAAQ,IAAI,EAC1B,CAAC,CACH,CACF;CACJ,CAAC;CACD,MAAM,SAIF,OAAO,MAAM,cAAc;EAC7B,cAAcC;EACd,SAAS,cACP,MAAM,OACJC,iBACA,OAAO,IAAI,aAAa;GACtB,MAAM,OAAO,OAAO,KAAK;GACzB,MAAM,KAAK,OAAO,WAAW;GAC7B,MAAM,cAAc,OAAA,YAA+B;GACnD,MAAM,WAAW,KAAK,QAAQ,SAAS;GAGvC,IACE,EAAE,OAAO,GAAG,OAAO,KAAK,KAAK,UAAU,kBAAkB,CAAC,MAC1D,EAAE,OAAO,GAAG,OACV,KAAK,KAAK,KAAK,QAAQ,QAAQ,GAAG,WAAW,QAAQ,CACvD,IAEA,OAAO,OAAO,IAAIC,6BAA6C;GAWjE,MAAM,aAAa,IAAG,OATH,GAChB,eAAe,KAAK,KAAK,aAAa,cAAc,CAAC,CAAC,CACtD,KACC,OAAO,QACL,OAAO,aACL,OAAO,eAAe,OAAO,OAAO,EAAE,MAAM,OAAO,OAAO,CAAC,CAAC,CAC9D,CACF,CACF,EAAA,CACwB,KAAK,GAAG,KAAK,SAAS,aAAa,QAAQ,CAAC,CAAC,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG;GAC/F,OAAA,gBAAuC,GAAG;IACxC,KAAK,OAAO,QAAQ,QAAQ;IAC5B,QAAQ;KACN,MAAM;KACN,OAAO,QAAQ,UAAU,UAAU;IACrC;GACF,CAAC;EACH,CAAC,CACH,CAAC,CAAC,KAAK,MAAM,QAAQ,gBAAgB,CAAC;CAC1C,CAAC;CACD,OAAO,MAAM,SACX,kBAAA,yBAC0C,KAAK,MAAM,aAAa,MAAM,CAAC,CAC3E;AACF"}
|
|
1
|
+
{"version":3,"file":"DirectoryOptions.mjs","names":["ProjectRoot.layer","ProjectRoot.ProjectRoot","ProjectRoot.findProjectRootFrom","ConvexDirectory.layer","ConvexDirectory.ConvexDirectory","ConvexDirectory.ConvexDirectoryNotFoundError"],"sources":["../src/DirectoryOptions.ts"],"sourcesContent":["import { IdScope } from \"@confect/core\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport * as Flag from \"effect/cli/Flag\";\nimport * as ConfectDirectory from \"./ConfectDirectory.js\";\nimport * as ConvexDirectory from \"./ConvexDirectory.js\";\nimport * as ProjectRoot from \"./ProjectRoot.js\";\n\nexport const flags = {\n componentDir: Flag.String(\"component-dir\").pipe(\n Flag.withDescription(\n \"Generate a component instead of the application; its sibling confect/ directory contains the source.\",\n ),\n Flag.optional,\n ),\n};\n\nexport const layer = ({\n componentDir,\n}: {\n componentDir: Option.Option<string>;\n}) => {\n const projectRootLayer = Option.match(componentDir, {\n onNone: () => ProjectRoot.layer,\n onSome: (directory) =>\n Layer.effect(\n ProjectRoot.ProjectRoot,\n Effect.map(ProjectRoot.findProjectRootFrom(directory), (root) =>\n ProjectRoot.ProjectRoot.of({\n get: Effect.succeed(root),\n }),\n ),\n ),\n });\n const convex: Layer.Layer<\n ConvexDirectory.ConvexDirectory,\n Layer.Error<typeof ConvexDirectory.layer> | Schema.SchemaError,\n FileSystem.FileSystem | Path.Path\n > = Option.match(componentDir, {\n onNone: () => ConvexDirectory.layer,\n onSome: (directory) =>\n Layer.effect(\n ConvexDirectory.ConvexDirectory,\n Effect.gen(function* () {\n const path = yield* Path.Path;\n const fs = yield* FileSystem.FileSystem;\n const projectRoot = yield* ProjectRoot.ProjectRoot.get;\n const absolute = path.resolve(directory);\n // A declared component's `convex.config.ts` is codegen output, so\n // its sibling `confect/app.ts` also marks the directory.\n if (\n !(yield* fs.exists(path.join(absolute, \"convex.config.ts\"))) &&\n !(yield* fs.exists(\n path.join(path.dirname(absolute), \"confect\", \"app.ts\"),\n ))\n ) {\n return yield* new ConvexDirectory.ConvexDirectoryNotFoundError();\n }\n const pkg = yield* fs\n .readFileString(path.join(projectRoot, \"package.json\"))\n .pipe(\n Effect.flatMap(\n Schema.decodeEffect(\n Schema.fromJsonString(Schema.Struct({ name: Schema.String })),\n ),\n ),\n );\n const definition = `${pkg.name}:${path.relative(projectRoot, absolute).split(path.sep).join(\"/\")}`;\n return ConvexDirectory.ConvexDirectory.of({\n get: Effect.succeed(absolute),\n target: {\n kind: \"component\",\n scope: IdScope.component(definition),\n },\n });\n }),\n ).pipe(Layer.provide(projectRootLayer)),\n });\n return Layer.mergeAll(\n projectRootLayer,\n ConfectDirectory.layerFromConvexDirectory.pipe(Layer.provideMerge(convex)),\n );\n};\n"],"mappings":";;;;;;;;;;;;AAYA,MAAa,QAAQ,EACnB,cAAc,KAAK,OAAO,eAAe,CAAC,CAAC,KACzC,KAAK,gBACH,sGACF,GACA,KAAK,QACP,EACF;AAEA,MAAa,SAAS,EACpB,mBAGI;CACJ,MAAM,mBAAmB,OAAO,MAAM,cAAc;EAClD,cAAcA;EACd,SAAS,cACP,MAAM,OACJC,aACA,OAAO,IAAIC,oBAAgC,SAAS,IAAI,SAAA,YAC9B,GAAG,EACzB,KAAK,OAAO,QAAQ,IAAI,EAC1B,CAAC,CACH,CACF;CACJ,CAAC;CACD,MAAM,SAIF,OAAO,MAAM,cAAc;EAC7B,cAAcC;EACd,SAAS,cACP,MAAM,OACJC,iBACA,OAAO,IAAI,aAAa;GACtB,MAAM,OAAO,OAAO,KAAK;GACzB,MAAM,KAAK,OAAO,WAAW;GAC7B,MAAM,cAAc,OAAA,YAA+B;GACnD,MAAM,WAAW,KAAK,QAAQ,SAAS;GAGvC,IACE,EAAE,OAAO,GAAG,OAAO,KAAK,KAAK,UAAU,kBAAkB,CAAC,MAC1D,EAAE,OAAO,GAAG,OACV,KAAK,KAAK,KAAK,QAAQ,QAAQ,GAAG,WAAW,QAAQ,CACvD,IAEA,OAAO,OAAO,IAAIC,6BAA6C;GAWjE,MAAM,aAAa,IAAG,OATH,GAChB,eAAe,KAAK,KAAK,aAAa,cAAc,CAAC,CAAC,CACtD,KACC,OAAO,QACL,OAAO,aACL,OAAO,eAAe,OAAO,OAAO,EAAE,MAAM,OAAO,OAAO,CAAC,CAAC,CAC9D,CACF,CACF,EAAA,CACwB,KAAK,GAAG,KAAK,SAAS,aAAa,QAAQ,CAAC,CAAC,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG;GAC/F,OAAA,gBAAuC,GAAG;IACxC,KAAK,OAAO,QAAQ,QAAQ;IAC5B,QAAQ;KACN,MAAM;KACN,OAAO,QAAQ,UAAU,UAAU;IACrC;GACF,CAAC;EACH,CAAC,CACH,CAAC,CAAC,KAAK,MAAM,QAAQ,gBAAgB,CAAC;CAC1C,CAAC;CACD,OAAO,MAAM,SACX,kBAAA,yBAC0C,KAAK,MAAM,aAAa,MAAM,CAAC,CAC3E;AACF"}
|
package/dist/EntryPoint.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"EntryPoint.mjs","names":["SpecModulePath.SpecModulePath","SpecModulePath.toImpl"],"sources":["../src/EntryPoint.ts"],"sourcesContent":["import * as Array from \"effect/Array\";\nimport * as Chunk from \"effect/Chunk\";\nimport * as Data from \"effect/Data\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Schema from \"effect/Schema\";\nimport { ImplModulePath } from \"./ImplModulePath\";\nimport * as SpecModulePath from \"./SpecModulePath\";\nimport { TableModulePath } from \"./TableModulePath\";\nimport { ConfectDirectory } from \"./ConfectDirectory\";\nimport { ConvexDirectory } from \"./ConvexDirectory\";\nimport { CONVEX_CONFIG_FILENAME } from \"./ConvexConfig\";\nimport { discoverLeafImplFiles, discoverLeafSpecFiles } from \"./LeafModule\";\nimport { discoverTableFiles, type TableModule } from \"./TableModule\";\n\nexport type Kind = Data.TaggedEnum<{\n Env: { readonly relativePath: \"env.ts\" };\n App: { readonly relativePath: \"app.ts\" };\n Callbacks: { readonly relativePath: \"callbacks.ts\" };\n Spec: { readonly relativePath: SpecModulePath.SpecModulePath };\n Impl: { readonly relativePath: ImplModulePath };\n Table: { readonly relativePath: TableModulePath };\n Http: { readonly relativePath: \"http.ts\" };\n Crons: { readonly relativePath: \"crons.ts\" };\n Auth: { readonly relativePath: \"auth.ts\" };\n Config: {};\n}>;\n\nexport const Kind = Data.taggedEnum<Kind>();\nexport const Declaration = Schema.TaggedUnion({\n Spec: { relativePath: SpecModulePath.SpecModulePath },\n Table: { relativePath: TableModulePath },\n});\nexport type Declaration = typeof Declaration.Type;\n\nexport const planDeclarations = (\n declarations: Array.NonEmptyReadonlyArray<Declaration>,\n affectedImpls: ReadonlyArray<ImplModulePath>,\n path: Path.Path,\n): {\n readonly tables: ReadonlyArray<TableModule>;\n readonly paths: ReadonlyArray<ImplModulePath>;\n} => {\n const plan = Array.reduce(\n declarations,\n {\n tables: Chunk.empty<TableModule>(),\n paths: HashSet.fromIterable(affectedImpls),\n },\n (state, declaration) =>\n Declaration.match(declaration, {\n Spec: ({ relativePath }) => ({\n ...state,\n paths: HashSet.add(state.paths, SpecModulePath.toImpl(relativePath)),\n }),\n Table: ({ relativePath }) => ({\n ...state,\n tables: Chunk.append(state.tables, {\n relativePath,\n tableName: path.parse(relativePath).name,\n }),\n }),\n }),\n );\n return {\n tables: Chunk.toReadonlyArray(plan.tables),\n paths: Array.fromIterable(plan.paths),\n };\n};\n\nexport type EntryPoint = Kind & {\n readonly absolutePath: string;\n readonly inputPath: string;\n};\nexport type OptionalFile = \"Http\" | \"Crons\" | \"Auth\";\n\nexport const isOptional = Predicate.or(\n Kind.$is(\"Http\"),\n Predicate.or(Kind.$is(\"Crons\"), Kind.$is(\"Auth\")),\n);\n\nexport const parse = (\n relativePath: string,\n): Option.Option<Exclude<Kind, { readonly _tag: \"Config\" }>> => {\n if (relativePath === \"env.ts\") return Option.some(Kind.Env({ relativePath }));\n if (relativePath === \"app.ts\") return Option.some(Kind.App({ relativePath }));\n if (relativePath === \"callbacks.ts\")\n return Option.some(Kind.Callbacks({ relativePath }));\n if (relativePath === \"http.ts\")\n return Option.some(Kind.Http({ relativePath }));\n if (relativePath === \"crons.ts\")\n return Option.some(Kind.Crons({ relativePath }));\n if (relativePath === \"auth.ts\")\n return Option.some(Kind.Auth({ relativePath }));\n const tablePath = Schema.decodeOption(TableModulePath)(relativePath);\n if (Option.isSome(tablePath))\n return Option.some(Kind.Table({ relativePath: tablePath.value }));\n const specPath = Schema.decodeOption(SpecModulePath.SpecModulePath)(\n relativePath,\n );\n if (Option.isSome(specPath))\n return Option.some(Kind.Spec({ relativePath: specPath.value }));\n return Schema.decodeOption(ImplModulePath)(relativePath).pipe(\n Option.map((implPath) => Kind.Impl({ relativePath: implPath })),\n );\n};\n\nexport const discover = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const tryEntry = Effect.fnUntraced(function* (\n kind: Exclude<Kind, { readonly _tag: \"Config\" }>,\n ) {\n const absolutePath = path.join(confectDirectory, kind.relativePath);\n if (!(yield* fs.exists(absolutePath))) {\n return Option.none<EntryPoint>();\n }\n return Option.some<EntryPoint>({\n ...kind,\n absolutePath,\n inputPath: yield* fs\n .realPath(absolutePath)\n .pipe(Effect.orElseSucceed(() => absolutePath)),\n });\n });\n\n const declaration = yield* tryEntry(Kind.App({ relativePath: \"app.ts\" }));\n const fixedEntryOptions = yield* Effect.all([\n tryEntry(Kind.Env({ relativePath: \"env.ts\" })),\n Effect.succeed(declaration),\n (yield* ConvexDirectory.target).kind === \"component\"\n ? tryEntry(Kind.Callbacks({ relativePath: \"callbacks.ts\" }))\n : Effect.succeedNone,\n tryEntry(Kind.Http({ relativePath: \"http.ts\" })),\n tryEntry(Kind.Crons({ relativePath: \"crons.ts\" })),\n tryEntry(Kind.Auth({ relativePath: \"auth.ts\" })),\n ]);\n\n const moduleRelativePaths = yield* Effect.all([\n discoverLeafSpecFiles,\n discoverLeafImplFiles,\n discoverTableFiles,\n ]).pipe(Effect.map(Array.flatten));\n const moduleEntryOptions = yield* Effect.forEach(\n Array.getSomes(moduleRelativePaths.map(parse)),\n tryEntry,\n );\n\n // `convex/convex.config.ts` feeds the generated components registry, so\n // edits to it (or to a locally-defined component definition it imports—npm component definitions are externalized and not watched) must re-run\n // codegen.\n const convexDirectory = yield* ConvexDirectory.get;\n const convexConfigEntryOption = yield* Effect.gen(function* () {\n const absolutePath = path.join(convexDirectory, CONVEX_CONFIG_FILENAME);\n // A declared backend's `convex.config.ts` is codegen output, not input.\n if (Option.isSome(declaration) || !(yield* fs.exists(absolutePath))) {\n return Option.none<EntryPoint>();\n }\n return Option.some<EntryPoint>({\n ...Kind.Config(),\n absolutePath,\n inputPath: yield* fs\n .realPath(absolutePath)\n .pipe(Effect.orElseSucceed(() => absolutePath)),\n });\n });\n\n return Array.getSomes([\n ...fixedEntryOptions,\n convexConfigEntryOption,\n ...moduleEntryOptions,\n ]);\n}).pipe(\n Effect.retry({\n times: 3,\n while: (error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ACzB,OAAO,gBAAgB,OAAA,CAAQ,SAAS,cACrC,SAAS,KAAK,UAAU,EAAE,cAAc,eAAe,CAAC,CAAC,IACzD,OAAO;EACX,SAAS,KAAK,KAAK,EAAE,cAAc,UAAU,CAAC,CAAC;EAC/C,SAAS,KAAK,MAAM,EAAE,cAAc,WAAW,CAAC,CAAC;EACjD,SAAS,KAAK,KAAK,EAAE,cAAc,UAAU,CAAC,CAAC;CACjD,CAAC;CAED,MAAM,sBAAsB,OAAO,OAAO,IAAI;EAC5C;EACA;EACA;CACF,CAAC,CAAC,CAAC,KAAK,OAAO,IAAI,MAAM,OAAO,CAAC;CACjC,MAAM,qBAAqB,OAAO,OAAO,QACvC,MAAM,SAAS,oBAAoB,IAAI,KAAK,CAAC,GAC7C,QACF;CAKA,MAAM,kBAAkB,OAAO,gBAAgB;CAC/C,MAAM,0BAA0B,OAAO,OAAO,IAAI,aAAa;EAC7D,MAAM,eAAe,KAAK,KAAK,iBAAiB,sBAAsB;EAEtE,IAAI,OAAO,OAAO,WAAW,KAAK,EAAE,OAAO,GAAG,OAAO,YAAY,IAC/D,OAAO,OAAO,KAAiB;EAEjC,OAAO,OAAO,KAAiB;GAC7B,GAAG,KAAK,OAAO;GACf;GACA,WAAW,OAAO,GACf,SAAS,YAAY,CAAC,CACtB,KAAK,OAAO,oBAAoB,YAAY,CAAC;EAClD,CAAC;CACH,CAAC;CAED,OAAO,MAAM,SAAS;EACpB,GAAG;EACH;EACA,GAAG;CACL,CAAC;AACH,CAAC,CAAC,CAAC,KACD,OAAO,MAAM;CACX,OAAO;CACP,QAAQ,UACN,MAAM,SAAS,mBAAmB,MAAM,OAAO,SAAS;AAC5D,CAAC,CACH"}
|
|
1
|
+
{"version":3,"file":"EntryPoint.mjs","names":["SpecModulePath.SpecModulePath","SpecModulePath.toImpl"],"sources":["../src/EntryPoint.ts"],"sourcesContent":["import * as Array from \"effect/Array\";\nimport * as Chunk from \"effect/Chunk\";\nimport * as Data from \"effect/Data\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Schema from \"effect/Schema\";\nimport { ImplModulePath } from \"./ImplModulePath.js\";\nimport * as SpecModulePath from \"./SpecModulePath.js\";\nimport { TableModulePath } from \"./TableModulePath.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport { ConvexDirectory } from \"./ConvexDirectory.js\";\nimport { CONVEX_CONFIG_FILENAME } from \"./ConvexConfig.js\";\nimport { discoverLeafImplFiles, discoverLeafSpecFiles } from \"./LeafModule.js\";\nimport { discoverTableFiles, type TableModule } from \"./TableModule.js\";\n\nexport type Kind = Data.TaggedEnum<{\n Env: { readonly relativePath: \"env.ts\" };\n App: { readonly relativePath: \"app.ts\" };\n Callbacks: { readonly relativePath: \"callbacks.ts\" };\n Spec: { readonly relativePath: SpecModulePath.SpecModulePath };\n Impl: { readonly relativePath: ImplModulePath };\n Table: { readonly relativePath: TableModulePath };\n Http: { readonly relativePath: \"http.ts\" };\n Crons: { readonly relativePath: \"crons.ts\" };\n Auth: { readonly relativePath: \"auth.ts\" };\n Config: {};\n}>;\n\nexport const Kind = Data.taggedEnum<Kind>();\nexport const Declaration = Schema.TaggedUnion({\n Spec: { relativePath: SpecModulePath.SpecModulePath },\n Table: { relativePath: TableModulePath },\n});\nexport type Declaration = typeof Declaration.Type;\n\nexport const planDeclarations = (\n declarations: Array.NonEmptyReadonlyArray<Declaration>,\n affectedImpls: ReadonlyArray<ImplModulePath>,\n path: Path.Path,\n): {\n readonly tables: ReadonlyArray<TableModule>;\n readonly paths: ReadonlyArray<ImplModulePath>;\n} => {\n const plan = Array.reduce(\n declarations,\n {\n tables: Chunk.empty<TableModule>(),\n paths: HashSet.fromIterable(affectedImpls),\n },\n (state, declaration) =>\n Declaration.match(declaration, {\n Spec: ({ relativePath }) => ({\n ...state,\n paths: HashSet.add(state.paths, SpecModulePath.toImpl(relativePath)),\n }),\n Table: ({ relativePath }) => ({\n ...state,\n tables: Chunk.append(state.tables, {\n relativePath,\n tableName: path.parse(relativePath).name,\n }),\n }),\n }),\n );\n return {\n tables: Chunk.toReadonlyArray(plan.tables),\n paths: Array.fromIterable(plan.paths),\n };\n};\n\nexport type EntryPoint = Kind & {\n readonly absolutePath: string;\n readonly inputPath: string;\n};\nexport type OptionalFile = \"Http\" | \"Crons\" | \"Auth\";\n\nexport const isOptional = Predicate.or(\n Kind.$is(\"Http\"),\n Predicate.or(Kind.$is(\"Crons\"), Kind.$is(\"Auth\")),\n);\n\nexport const parse = (\n relativePath: string,\n): Option.Option<Exclude<Kind, { readonly _tag: \"Config\" }>> => {\n if (relativePath === \"env.ts\") return Option.some(Kind.Env({ relativePath }));\n if (relativePath === \"app.ts\") return Option.some(Kind.App({ relativePath }));\n if (relativePath === \"callbacks.ts\")\n return Option.some(Kind.Callbacks({ relativePath }));\n if (relativePath === \"http.ts\")\n return Option.some(Kind.Http({ relativePath }));\n if (relativePath === \"crons.ts\")\n return Option.some(Kind.Crons({ relativePath }));\n if (relativePath === \"auth.ts\")\n return Option.some(Kind.Auth({ relativePath }));\n const tablePath = Schema.decodeOption(TableModulePath)(relativePath);\n if (Option.isSome(tablePath))\n return Option.some(Kind.Table({ relativePath: tablePath.value }));\n const specPath = Schema.decodeOption(SpecModulePath.SpecModulePath)(\n relativePath,\n );\n if (Option.isSome(specPath))\n return Option.some(Kind.Spec({ relativePath: specPath.value }));\n return Schema.decodeOption(ImplModulePath)(relativePath).pipe(\n Option.map((implPath) => Kind.Impl({ relativePath: implPath })),\n );\n};\n\nexport const discover = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const tryEntry = Effect.fnUntraced(function* (\n kind: Exclude<Kind, { readonly _tag: \"Config\" }>,\n ) {\n const absolutePath = path.join(confectDirectory, kind.relativePath);\n if (!(yield* fs.exists(absolutePath))) {\n return Option.none<EntryPoint>();\n }\n return Option.some<EntryPoint>({\n ...kind,\n absolutePath,\n inputPath: yield* fs\n .realPath(absolutePath)\n .pipe(Effect.orElseSucceed(() => absolutePath)),\n });\n });\n\n const declaration = yield* tryEntry(Kind.App({ relativePath: \"app.ts\" }));\n const fixedEntryOptions = yield* Effect.all([\n tryEntry(Kind.Env({ relativePath: \"env.ts\" })),\n Effect.succeed(declaration),\n (yield* ConvexDirectory.target).kind === \"component\"\n ? tryEntry(Kind.Callbacks({ relativePath: \"callbacks.ts\" }))\n : Effect.succeedNone,\n tryEntry(Kind.Http({ relativePath: \"http.ts\" })),\n tryEntry(Kind.Crons({ relativePath: \"crons.ts\" })),\n tryEntry(Kind.Auth({ relativePath: \"auth.ts\" })),\n ]);\n\n const moduleRelativePaths = yield* Effect.all([\n discoverLeafSpecFiles,\n discoverLeafImplFiles,\n discoverTableFiles,\n ]).pipe(Effect.map(Array.flatten));\n const moduleEntryOptions = yield* Effect.forEach(\n Array.getSomes(moduleRelativePaths.map(parse)),\n tryEntry,\n );\n\n // `convex/convex.config.ts` feeds the generated components registry, so\n // edits to it (or to a locally-defined component definition it imports—npm component definitions are externalized and not watched) must re-run\n // codegen.\n const convexDirectory = yield* ConvexDirectory.get;\n const convexConfigEntryOption = yield* Effect.gen(function* () {\n const absolutePath = path.join(convexDirectory, CONVEX_CONFIG_FILENAME);\n // A declared backend's `convex.config.ts` is codegen output, not input.\n if (Option.isSome(declaration) || !(yield* fs.exists(absolutePath))) {\n return Option.none<EntryPoint>();\n }\n return Option.some<EntryPoint>({\n ...Kind.Config(),\n absolutePath,\n inputPath: yield* fs\n .realPath(absolutePath)\n .pipe(Effect.orElseSucceed(() => absolutePath)),\n });\n });\n\n return Array.getSomes([\n ...fixedEntryOptions,\n convexConfigEntryOption,\n ...moduleEntryOptions,\n ]);\n}).pipe(\n Effect.retry({\n times: 3,\n while: (error) =>\n error._tag === \"PlatformError\"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