@gaganref/confect-cli 10.6.0-fork.2 → 10.6.0-fork.20
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/Declaration.mjs +12 -2
- package/dist/Declaration.mjs.map +1 -1
- package/dist/FunctionModule.mjs +17 -4
- package/dist/FunctionModule.mjs.map +1 -1
- package/dist/SectionFiles.mjs +3 -1
- package/dist/SectionFiles.mjs.map +1 -1
- package/dist/SyncState.mjs +2 -2
- package/dist/SyncState.mjs.map +1 -1
- package/dist/confect/codegen.mjs +19 -1
- package/dist/confect/codegen.mjs.map +1 -1
- package/dist/confect/dev.mjs +1 -1
- package/dist/confect/dev.mjs.map +1 -1
- package/dist/templates.mjs +19 -3
- package/dist/templates.mjs.map +1 -1
- package/dist/utils.mjs +10 -1
- package/dist/utils.mjs.map +1 -1
- package/package.json +3 -3
package/dist/confect/codegen.mjs
CHANGED
|
@@ -121,7 +121,7 @@ const generateWithSnapshot = Effect.gen(function* () {
|
|
|
121
121
|
onNone: () => generateHttp,
|
|
122
122
|
onSome: (app) => syncDeclaredHttp(app, sections.files)
|
|
123
123
|
})),
|
|
124
|
-
logGenerated(generateCrons),
|
|
124
|
+
logGenerated(Option.isNone(declared) ? generateCrons() : syncDeclaredCrons(sections.crons)),
|
|
125
125
|
Option.isNone(declared) ? logGenerated(generateAuthConfig) : Effect.succeedNone
|
|
126
126
|
], { concurrency: "unbounded" });
|
|
127
127
|
yield* removeUnclaimed(sections.files);
|
|
@@ -172,6 +172,7 @@ const updateDeclarations = Effect.fn("Cli.updateDeclarations")(function* (snapsh
|
|
|
172
172
|
yield* validateAllImpls(leaves, required);
|
|
173
173
|
yield* generateGroupRegisteredFunctions(sections.changed ? all : leaves, required, sections.files);
|
|
174
174
|
if (sections.changed && Option.isSome(declared)) yield* logGenerated(syncDeclaredHttp(declared.value, sections.files));
|
|
175
|
+
if (Option.isSome(declared)) yield* logGenerated(generateCrons(sections.crons));
|
|
175
176
|
yield* removeUnclaimed(sections.files);
|
|
176
177
|
yield* applyFunctionPlan(diff(snapshot, next));
|
|
177
178
|
yield* verify(backend, mounts);
|
|
@@ -582,6 +583,23 @@ const provisionalComponents = Effect.gen(function* () {
|
|
|
582
583
|
const components2 = yield* components({ components: [] });
|
|
583
584
|
yield* writeFileStringAndLog(registry, components2);
|
|
584
585
|
});
|
|
586
|
+
/**
|
|
587
|
+
* Write a declared backend's `convex/crons.ts`, or remove it once
|
|
588
|
+
* `confect/crons.ts` is gone. Its edits run full generation, so
|
|
589
|
+
* `assertOwnedEntrypoints` has proved an existing file is codegen's.
|
|
590
|
+
*/
|
|
591
|
+
const syncDeclaredCrons = Effect.fnUntraced(function* (sectionFiles) {
|
|
592
|
+
const written = yield* generateCrons(sectionFiles);
|
|
593
|
+
const fs = yield* FileSystem.FileSystem;
|
|
594
|
+
const path = yield* Path.Path;
|
|
595
|
+
const convexDirectory = yield* ConvexDirectory.get;
|
|
596
|
+
const convexCrons = path.join(convexDirectory, "crons.ts");
|
|
597
|
+
if (Option.isNone(written) && (yield* fs.exists(convexCrons))) {
|
|
598
|
+
yield* fs.remove(convexCrons);
|
|
599
|
+
yield* logFileRemoved(convexCrons);
|
|
600
|
+
}
|
|
601
|
+
return written;
|
|
602
|
+
});
|
|
585
603
|
const logGenerated = (effect) => effect.pipe(Effect.tap(Option.match({
|
|
586
604
|
onNone: () => Effect.void,
|
|
587
605
|
onSome: ({ change, convexFilePath }) => Match.value(change).pipe(Match.when("Added", () => logFileAdded(convexFilePath)), Match.when("Modified", () => logFileModified(convexFilePath)), Match.when("Unchanged", () => Effect.void), Match.exhaustive)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codegen.mjs","names":["DirectoryOptions.flags","CodegenError.tapAndLog","DirectoryOptions.layer","TableModule.discover","TableModule.validate","ManifestSections.refuseSpecSections","SectionFiles.sync","FunctionModule.assertOwnedEntrypoints","GenerationSnapshot.fromLoadedLeaves","FunctionModule.generateFunctions","SectionFiles.removeUnclaimed","SectionFiles.verify","Bundler.withBatch","Bundler.check","EntryPoint.planDeclarations","GenerationSnapshot.update","FunctionModule.applyFunctionPlan","GenerationSnapshot.diff","ConvexConfig.componentName","ConvexConfig.CONVEX_CONFIG_FILENAME","Bundler.bundle","templates.componentContract","templates.assembledSpec","templates.registeredFunctionsForGroup","FunctionPaths.make","TableModule.TABLES_DIRNAME","templates.id","templates.tableWrapper","templates.runtimeSchema","templates.convexSchema","templates.schema","templates.services","DocName.fromTableName","templates.docs","templates.refs","ConvexConfig.discoverInstalledComponents","ConvexConfig.typeImportPath","templates.components","Bundler.resolveModule","Bundler.exportNames","ConvexConfig.resolveDefinition"],"sources":["../../src/confect/codegen.ts"],"sourcesContent":["import { App, Callback, Env, type GroupSpec, Spec } from \"@confect/core\";\nimport * as Command from \"effect/cli/Command\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as Array from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as Result from \"effect/Result\";\nimport type * as PlatformError from \"effect/PlatformError\";\nimport type { BuildError } from \"../BuildError.js\";\nimport { pipe } from \"effect/Function\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as Record from \"effect/Record\";\nimport type * as Scope from \"effect/Scope\";\nimport * as Bundler from \"../Bundler.js\";\nimport { fromBundlerError } from \"../BuildError.js\";\nimport * as CodegenError from \"../CodegenError.js\";\nimport { LegacySchemaFileError } from \"../CodegenError.js\";\nimport { ConfectDirectory } from \"../ConfectDirectory.js\";\nimport * as ConvexConfig from \"../ConvexConfig.js\";\nimport { ConvexDirectory } from \"../ConvexDirectory.js\";\nimport * as DirectoryOptions from \"../DirectoryOptions.js\";\nimport * as DocName from \"../DocName.js\";\nimport * as FunctionPaths from \"../FunctionPaths.js\";\nimport * as FunctionModule from \"../FunctionModule.js\";\nimport * as GenerationSnapshot from \"../GenerationSnapshot.js\";\nimport * as EntryPoint from \"../EntryPoint.js\";\nimport type { ImplModulePath } from \"../ImplModulePath.js\";\nimport {\n discoverLeafSpecFiles,\n implPathForSpec,\n loadAll,\n registeredFunctionsRelativePath,\n toLeafModule,\n validateAllImpls,\n withImplFiles,\n type LeafModule,\n type LoadedLeafModule,\n} from \"../LeafModule.js\";\nimport {\n logFileAdded,\n logFileModified,\n logFileRemoved,\n logPending,\n logSuccess,\n logWarn,\n} from \"../log.js\";\nimport { ProjectRoot } from \"../ProjectRoot.js\";\nimport { preserveComponentOutput } from \"../Rollback.js\";\nimport { assemblyNodesFromLeaves } from \"../SpecAssemblyNode.js\";\nimport * as ManifestSections from \"../ManifestSections.js\";\nimport * as SectionFiles from \"../SectionFiles.js\";\nimport * as TableModule from \"../TableModule.js\";\nimport * as templates from \"../templates.js\";\nimport {\n generateAuthConfig,\n generateCrons,\n generateHttp,\n removePathIfExists,\n toModuleImportPath,\n touchConvexSchema,\n writeFileStringAndLog,\n} from \"../utils.js\";\nimport {\n syncManifestSections,\n readPrevious,\n syncDeclaration,\n syncDeployModule,\n syncDeclaredHttp,\n} from \"./declaration.js\";\nimport * as String from \"effect/String\";\nimport { quote } from \"../Json.js\";\n\nconst GENERATED_DIRNAME = \"_generated\";\n\nconst declaredSections = (backend: Option.Option<SectionFiles.Backend>) =>\n Option.match(backend, {\n onNone: () => [],\n onSome: ({ sections }) => sections,\n });\n\nconst isComponent = Effect.map(\n ConvexDirectory.target,\n (target) => target.kind === \"component\",\n);\n\nconst GENERATED_SPEC_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"spec.ts\"),\n);\nconst GENERATED_SCHEMA_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"schema.ts\"),\n);\nconst GENERATED_CONVEX_SCHEMA_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"convexSchema.ts\"),\n);\nconst GENERATED_ID_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"id.ts\"),\n);\nconst GENERATED_COMPONENTS_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"components.ts\"),\n);\nconst GENERATED_TABLES_DIRNAME = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"tables\"),\n);\n\nconst LEGACY_PATHS = Effect.gen(function* () {\n const path = yield* Path.Path;\n\n return [\n \"spec.ts\",\n \"nodeSpec.ts\",\n \"impl.ts\",\n \"nodeImpl.ts\",\n path.join(GENERATED_DIRNAME, \"registeredFunctions.ts\"),\n path.join(GENERATED_DIRNAME, \"nodeRegisteredFunctions.ts\"),\n path.join(GENERATED_DIRNAME, \"impl.ts\"),\n path.join(GENERATED_DIRNAME, \"nodeImpl.ts\"),\n // `_generated/nodeSpec.ts` is not part of the generated output (all groups\n // live in `_generated/spec.ts`); delete any copy left by an older version.\n path.join(GENERATED_DIRNAME, \"nodeSpec.ts\"),\n ];\n});\n\n/**\n * @internal\n */\nexport const codegen = Command.make(\"codegen\", DirectoryOptions.flags, () =>\n Effect.gen(function* () {\n yield* logPending(\"Performing initial sync…\");\n yield* codegenHandler.pipe(\n Effect.asVoid,\n Effect.tap(() => logSuccess(\"Generated files are up-to-date\")),\n CodegenError.tapAndLog,\n );\n }),\n).pipe(\n Command.provide(DirectoryOptions.layer),\n Command.withDescription(\n \"Generate `confect/_generated` files and the contents of the `convex` directory (except `tsconfig.json`, and `convex.config.ts` unless `confect/app.ts` declares the backend)\",\n ),\n);\n\nconst runCodegen = Effect.gen(function* () {\n yield* validateComponentConfiguration;\n yield* rejectDeployModuleGroup;\n yield* generateConfectGeneratedDirectory;\n const previousManifest = yield* readPrevious;\n // Reject a legacy `confect/schema.ts` up front so the user-facing\n // migration message surfaces before any bundler error from impl\n // validation (each impl imports `_generated/schema.ts`).\n yield* rejectLegacySchemaFile;\n // List `confect/tables/*.ts` (filename-only—no bundling yet) so the\n // `_generated/id.ts` constructor can be emitted *before* we bundle any\n // user-authored table module. Tables import from `_generated/id.ts` for\n // cross-table id refs, so it must exist on disk first.\n const tableModules = yield* TableModule.discover;\n yield* warnIfNoTables(tableModules);\n yield* generateIdConstructor(tableModules);\n // The declaration can import `_generated/refs` (a mount's callback arg),\n // which imports the assembled spec, the leaf specs and their table\n // wrappers. Their text follows from the file layout alone, so they are\n // written before the declaration is bundled, even on a first run.\n yield* generateTableWrappers(tableModules);\n yield* removeObsoleteTableWrappers(tableModules);\n const leafSpecFiles = yield* discoverLeafSpecFiles;\n const forEach2 = yield* Effect.forEach(leafSpecFiles, toLeafModule);\n yield* generateAssembledSpecs(forEach2);\n yield* generateRefs;\n // Specs and tables can import the components registry, but the registry\n // reads the `convex.config.ts` that the declaration writes. Only its type\n // depends on the config, so any registry on disk, or an empty one on a first\n // run, serves the declaration bundle until the real one is written below.\n yield* provisionalComponents;\n // A declared backend's `convex.config.ts` and manifest come next: the\n // registry below reads the config, and nothing may validate against a\n // manifest the current declaration did not produce.\n const {\n app: declared,\n digest,\n backend,\n } = yield* syncDeclaration(previousManifest);\n const mounts = yield* generateComponents;\n yield* validateCallbackPrefixes(declared);\n // Now that `_generated/id.ts` is on disk, bundle each table module and\n // check its default export is an `UnnamedTable`. Surface diagnostics\n // here (rather than later) so they appear before impl-validation noise.\n yield* TableModule.validate(tableModules);\n yield* validateNoDocNameCollisions(tableModules);\n yield* generateRuntimeSchema(tableModules);\n const leaves = yield* loadAll;\n yield* rejectComponentNodeGroups(leaves);\n yield* Effect.fromResult(ManifestSections.refuseSpecSections(leaves));\n const sections = yield* SectionFiles.sync(backend, leaves, mounts);\n // Nothing above writes a Convex entrypoint. The check waits for this run's\n // section files, because the HTTP router may import any of them.\n yield* FunctionModule.assertOwnedEntrypoints;\n yield* syncManifestSections(\n declaredSections(backend),\n leaves,\n previousManifest,\n digest,\n sections.modules,\n );\n yield* removeLegacyFiles;\n const snapshot = yield* Effect.fromResult(\n GenerationSnapshot.fromLoadedLeaves(leaves),\n );\n // `_generated/api.ts`/`nodeApi.ts` are no longer imported by generated or\n // impl code (impls take the database schema from `_generated/schema`\n // directly), so remove any copies left over from earlier versions before\n // impl validation runs.\n yield* Effect.all(\n [\n removeGeneratedApi,\n generateComponentContract(tableModules),\n removeGeneratedNodeApi,\n generateDocs(tableModules),\n generateServices,\n generateConvexSchema(tableModules),\n ],\n { concurrency: \"unbounded\" },\n );\n const required = Option.isSome(declared)\n ? declared.value.requiresMiddleware\n : [];\n yield* validateAllImpls(leaves, required);\n yield* generateGroupRegisteredFunctions(leaves, required, sections.files);\n yield* removeObsoleteRegisteredFunctions(leaves);\n const [functionPaths] = yield* Effect.all(\n [\n FunctionModule.generateFunctions(snapshot),\n generateConvexSchemaReexport,\n logGenerated(\n Option.match(declared, {\n onNone: () => generateHttp,\n onSome: (app) => syncDeclaredHttp(app, sections.files),\n }),\n ),\n logGenerated(generateCrons),\n Option.isNone(declared)\n ? logGenerated(generateAuthConfig)\n : Effect.succeedNone,\n ],\n { concurrency: \"unbounded\" },\n );\n yield* SectionFiles.removeUnclaimed(sections.files);\n yield* syncDeployModule(declared);\n if (Option.isSome(declared)) yield* generateTesting(declared.value);\n yield* SectionFiles.verify(backend, mounts);\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const optionalFiles = yield* Effect.filter(\n [\"http.ts\", \"crons.ts\", \"auth.ts\"],\n (file) => fs.exists(path.join(confectDirectory, file)),\n );\n yield* Bundler.withBatch(\n Array.map(optionalFiles, (file) => path.join(confectDirectory, file)),\n Effect.forEach(\n optionalFiles,\n (file) =>\n Bundler.check(path.join(confectDirectory, file)).pipe(\n Effect.mapError((error) => fromBundlerError(file, error)),\n ),\n { discard: true },\n ),\n );\n return {\n functionPaths,\n snapshot,\n };\n});\n\n/**\n * @internal\n */\nexport const generateWithSnapshot = runCodegen.pipe(\n Effect.withSpan(\"Cli.codegen\"),\n);\n\n/**\n * @internal\n */\nexport const makeCodegenHandler = (\n duringRestore?: Effect.Effect<void, never, Scope.Scope>,\n) =>\n preserveComponentOutput(generateWithSnapshot, duringRestore).pipe(\n Effect.tap(() => touchConvexSchema),\n Effect.map(({ functionPaths }) => ({ functionPaths })),\n );\n\n/**\n * @internal\n */\nexport const codegenHandler = makeCodegenHandler();\n\n/**\n * @internal\n */\nexport const updateDeclarations = Effect.fn(\"Cli.updateDeclarations\")(\n function* (\n snapshot: GenerationSnapshot.GenerationSnapshot,\n declarations: Array.NonEmptyReadonlyArray<EntryPoint.Declaration>,\n affectedImpls: ReadonlyArray<ImplModulePath>,\n ) {\n yield* rejectDeployModuleGroup;\n const previousManifest = yield* readPrevious;\n const path = yield* Path.Path;\n const { paths, tables } = EntryPoint.planDeclarations(\n declarations,\n affectedImpls,\n path,\n );\n yield* TableModule.validate(tables);\n return yield* withImplFiles(paths, (leaves) =>\n Effect.gen(function* () {\n yield* rejectComponentNodeGroups(leaves);\n yield* Effect.fromResult(ManifestSections.refuseSpecSections(leaves));\n const next = yield* Effect.fromResult(\n GenerationSnapshot.update(snapshot, leaves),\n );\n const {\n app: declared,\n digest,\n backend,\n } = yield* syncDeclaration(previousManifest);\n const all = Option.isSome(declared) ? yield* loadAll : [];\n const mounts = Option.isSome(backend) ? yield* installedMounts : [];\n const sections = yield* SectionFiles.sync(backend, all, mounts);\n if (Option.isSome(declared))\n yield* syncManifestSections(\n declaredSections(backend),\n all,\n previousManifest,\n digest,\n sections.modules,\n );\n const required = Option.isSome(declared)\n ? declared.value.requiresMiddleware\n : [];\n yield* validateAllImpls(leaves, required);\n // A section file that appeared or went changes every registration\n // file's imports and the HTTP router's, not only the edited groups'.\n yield* generateGroupRegisteredFunctions(\n sections.changed ? all : leaves,\n required,\n sections.files,\n );\n if (sections.changed && Option.isSome(declared))\n yield* logGenerated(syncDeclaredHttp(declared.value, sections.files));\n yield* SectionFiles.removeUnclaimed(sections.files);\n yield* FunctionModule.applyFunctionPlan(\n GenerationSnapshot.diff(snapshot, next),\n );\n yield* SectionFiles.verify(backend, mounts);\n return next;\n }),\n );\n },\n);\n\n// Convex components cannot run Node.js functions, at any nesting depth.\nconst validateComponentGroupRuntime = (\n group: GroupSpec.AnyWithProps,\n groupPath: string,\n specPath: string,\n): Result.Result<void, CodegenError.ComponentNodeGroupError> =>\n Result.gen(function* () {\n if (group.runtime === \"Node\") {\n return yield* Result.fail(\n CodegenError.ComponentNodeGroupError.make({ specPath, groupPath }),\n );\n }\n for (const [name, child] of Record.toEntries(group.groups)) {\n yield* validateComponentGroupRuntime(\n child,\n `${groupPath}.${name}`,\n specPath,\n );\n }\n });\n\nconst rejectComponentNodeGroups = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LoadedLeafModule>,\n) {\n if ((yield* ConvexDirectory.target).kind === \"app\") return;\n yield* Effect.forEach(leaves, (leaf) =>\n Effect.fromResult(\n validateComponentGroupRuntime(\n leaf.spec,\n leaf.groupPathDot,\n leaf.relativePath,\n ),\n ),\n );\n});\n\nconst validateCallbackPrefixes = Effect.fnUntraced(function* (\n declared: Option.Option<App.Any>,\n) {\n if ((yield* ConvexDirectory.target).kind !== \"component\") return;\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const callbacksPath = path.join(confectDirectory, \"callbacks.ts\");\n if (!(yield* fs.exists(callbacksPath))) return;\n const name = Option.isSome(declared)\n ? Env.name(App.env(declared.value))\n : yield* Effect.flatMap(ConvexDirectory.get, (convexDirectory) =>\n ConvexConfig.componentName(\n path.join(convexDirectory, ConvexConfig.CONVEX_CONFIG_FILENAME),\n ),\n );\n const { module } = yield* Bundler.bundle(callbacksPath).pipe(\n Effect.mapError((error) => fromBundlerError(\"confect/callbacks.ts\", error)),\n );\n for (const contract of Record.values(module)) {\n if (\n Callback.isContract(contract) &&\n !pipe(contract.id, String.startsWith(`${name}/`))\n ) {\n return yield* CodegenError.CallbackPrefixError.make({\n declarationPath: \"confect/callbacks.ts\",\n contractId: contract.id,\n componentName: name,\n });\n }\n }\n});\n\nconst validateComponentConfiguration = Effect.gen(function* () {\n return yield* Match.value((yield* ConvexDirectory.target).kind).pipe(\n Match.when(\"app\", () => Effect.void),\n Match.when(\"component\", () =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const authPath = path.join(confectDirectory, \"auth.ts\");\n if (yield* fs.exists(authPath)) {\n return yield* CodegenError.InvalidConvexConfigError.make({\n configPath: authPath,\n reason:\n \"Components cannot configure application authentication. Pass identity explicitly through function arguments.\",\n });\n }\n }),\n ),\n Match.exhaustive,\n );\n});\n\nconst generateComponentContract = Effect.fnUntraced(function* (\n tables: ReadonlyArray<TableModule.TableModule>,\n) {\n return yield* Match.value((yield* ConvexDirectory.target).kind).pipe(\n Match.when(\"app\", () => Effect.void),\n Match.when(\"component\", () =>\n Effect.gen(function* () {\n const path = yield* Path.Path;\n const directory = yield* ConfectDirectory.get;\n const contents = yield* templates.componentContract({\n tableNames: Array.map(tables, (table) => table.tableName),\n });\n yield* writeFileStringAndLog(\n path.join(directory, GENERATED_DIRNAME, \"component.ts\"),\n contents,\n );\n }),\n ),\n Match.exhaustive,\n );\n});\n\nconst generateConfectGeneratedDirectory = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n if (!(yield* fs.exists(path.join(confectDirectory, \"_generated\")))) {\n yield* fs.makeDirectory(path.join(confectDirectory, \"_generated\"), {\n recursive: true,\n });\n yield* logFileAdded(path.join(confectDirectory, \"_generated\") + \"/\");\n }\n});\n\nconst removeLegacyFiles = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const legacyPaths = yield* LEGACY_PATHS;\n\n yield* Effect.forEach(\n legacyPaths,\n Effect.fnUntraced(function* (relativePath: string) {\n const absolutePath = path.join(confectDirectory, relativePath);\n if (yield* fs.exists(absolutePath)) {\n yield* removePathIfExists(absolutePath);\n yield* logFileRemoved(absolutePath);\n }\n }),\n );\n});\n\nconst generateAssembledSpecs = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LeafModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedSpecPath = yield* GENERATED_SPEC_PATH;\n\n // A single assembled spec holds every group regardless of runtime—a Node\n // group's `makeNode()` lives in its imported leaf spec, so the assembled\n // file is runtime-agnostic. Always emit it (even empty) so downstream\n // readers (`loadGeneratedSpec`, `generateRefs`) always find a spec module.\n const nodes = assemblyNodesFromLeaves(leaves);\n const specContents = yield* templates.assembledSpec({ nodes });\n yield* writeFileStringAndLog(\n path.join(confectDirectory, generatedSpecPath),\n specContents,\n );\n});\n\nconst generateGroupRegisteredFunctions = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LoadedLeafModule>,\n required: ReadonlyArray<{ readonly key: string }>,\n sectionFiles: ReadonlyArray<string>,\n) {\n const path = yield* Path.Path;\n const fs = yield* FileSystem.FileSystem;\n const confectDirectory = yield* ConfectDirectory.get;\n const runtimePath = path.join(confectDirectory, \"runtime.ts\");\n const hasRuntime = yield* fs.exists(runtimePath);\n\n yield* Effect.forEach(\n leaves,\n Effect.fnUntraced(function* (leaf: LoadedLeafModule) {\n const registryRelativePath = yield* registeredFunctionsRelativePath(leaf);\n const registryPath = path.join(\n confectDirectory,\n \"_generated\",\n registryRelativePath,\n );\n const registryDir = path.dirname(registryPath);\n if (!(yield* fs.exists(registryDir))) {\n yield* fs.makeDirectory(registryDir, { recursive: true });\n }\n\n const implRelativePath = yield* implPathForSpec(leaf.relativePath);\n const schemaImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(registryPath),\n path.join(confectDirectory, \"_generated\", \"schema.ts\"),\n ),\n );\n // The group's own leaf spec (sibling of its impl), referenced\n // type-only by the registry to shape its returned record.\n const specImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(registryPath),\n path.join(confectDirectory, leaf.relativePath),\n ),\n );\n const implImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(registryPath),\n path.join(confectDirectory, implRelativePath),\n ),\n );\n\n const contents = yield* templates.registeredFunctionsForGroup({\n spec: leaf.spec,\n required,\n groupPath: leaf.groupPathDot,\n schemaImportPath,\n specImportPath,\n implImportPath,\n runtimeImportPath: hasRuntime\n ? yield* toModuleImportPath(path.relative(registryDir, runtimePath))\n : undefined,\n sectionImportPaths: yield* Effect.forEach(sectionFiles, (file) =>\n toModuleImportPath(\n path.relative(\n registryDir,\n path.join(confectDirectory, \"_generated\", file),\n ),\n ),\n ),\n });\n\n yield* writeFileStringAndLog(registryPath, contents);\n }),\n );\n});\n\nconst removeObsoleteRegisteredFunctions = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LeafModule>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const registryRoot = path.join(\n confectDirectory,\n \"_generated\",\n \"registeredFunctions\",\n );\n\n if (!(yield* fs.exists(registryRoot))) {\n return;\n }\n\n const expectedPaths = yield* Effect.forEach(leaves, (leaf) =>\n registeredFunctionsRelativePath(leaf),\n );\n const expected = new Set(expectedPaths);\n\n const existing = yield* fs.readDirectory(registryRoot, { recursive: true });\n yield* Effect.forEach(existing, (relativePath) => {\n if (path.extname(relativePath) !== \".ts\") {\n return Effect.void;\n }\n const normalized = path.join(\"registeredFunctions\", relativePath);\n if (!expected.has(normalized)) {\n return Effect.gen(function* () {\n const absolutePath = path.join(registryRoot, relativePath);\n if (yield* fs.exists(absolutePath)) {\n yield* removePathIfExists(absolutePath);\n yield* logFileRemoved(absolutePath);\n }\n });\n }\n return Effect.void;\n });\n});\n\nconst getGeneratedSpecPath = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedSpecPath = yield* GENERATED_SPEC_PATH;\n return path.join(confectDirectory, generatedSpecPath);\n});\n\nconst loadGeneratedSpec = Effect.gen(function* () {\n const specPath = yield* getGeneratedSpecPath;\n const { module: specModule } = yield* Bundler.bundle(specPath);\n const spec = specModule.default;\n\n if (!Spec.isSpec(spec)) {\n return yield* Effect.die(\n new Error(\"_generated/spec.ts does not export a valid Spec\"),\n );\n }\n\n return spec;\n});\n\nconst emptyFunctionPaths = FunctionPaths.FunctionPaths.make(HashSet.empty());\n\n/**\n * @internal\n */\nexport const loadPreviousFunctionPaths = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const specPath = yield* getGeneratedSpecPath;\n\n if (!(yield* fs.exists(specPath))) {\n return emptyFunctionPaths;\n }\n\n const specResult = yield* loadGeneratedSpec.pipe(Effect.result);\n\n return Result.match(specResult, {\n onFailure: () => emptyFunctionPaths,\n onSuccess: (spec) => FunctionPaths.make(spec),\n });\n});\n\n/**\n * Remove a now-obsolete `_generated/<name>.ts` if present (and log it), for\n * projects upgrading from a version that still emitted it.\n */\nconst removeObsoleteGeneratedFile = Effect.fnUntraced(function* (\n fileName: string,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const filePath = path.join(confectDirectory, \"_generated\", fileName);\n\n if (yield* fs.exists(filePath)) {\n yield* removePathIfExists(filePath);\n yield* logFileRemoved(filePath);\n }\n});\n\n// `_generated/api.ts` is no longer imported by generated or impl code: impls\n// take the database schema (`_generated/schema`) directly, and per-group\n// registries reference the spec type-only. Remove any stale copy.\nconst removeGeneratedApi = removeObsoleteGeneratedFile(\"api.ts\");\n\n// `_generated/nodeApi.ts` is obsolete for the same reason.\nconst removeGeneratedNodeApi = removeObsoleteGeneratedFile(\"nodeApi.ts\");\n\n/**\n * The user-authored `confect/schema.ts` is no longer supported: codegen now\n * owns both `_generated/schema.ts` (runtime) and `_generated/convexSchema.ts`\n * (deploy), derived from a single scan of `confect/tables/*.ts`. Detect a stray\n * file and fail with a clear migration message—leaving it in place would\n * silently shadow the codegen-owned\n * `_generated/schema.ts`/`_generated/convexSchema.ts`.\n */\nconst rejectLegacySchemaFile = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const legacyPath = path.join(confectDirectory, \"schema.ts\");\n\n if (yield* fs.exists(legacyPath)) {\n return yield* LegacySchemaFileError.make({ schemaPath: \"schema.ts\" });\n }\n});\n\n// A root group named `confectDeploy` would write the entrypoint\n// `syncDeployModule` owns, so refuse it before anything is written.\nconst rejectDeployModuleGroup = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n if (yield* fs.exists(path.join(confectDirectory, \"confectDeploy.spec.ts\")))\n return yield* CodegenError.InvalidDeclarationError.make({\n declarationPath: \"confect/confectDeploy.spec.ts\",\n reason:\n \"its functions would go in convex/confectDeploy.ts, which codegen writes for the mounts a push initialises. Rename the group, for example to confect/deploy.spec.ts.\",\n });\n});\n\n/**\n * Surface a yellow `⚠` warning when codegen sees no tables—either the\n * `confect/tables/` directory is missing or it contains no `.ts` files.\n * Generation still succeeds (emitting an empty `DatabaseSchema` and\n * `defineSchema({})`), since action-only/table-free Confect backends are\n * legal—but the warning catches the much more common case of a typoed directory\n * or files placed under the wrong root.\n */\nconst warnIfNoTables = (tableModules: ReadonlyArray<TableModule.TableModule>) =>\n tableModules.length === 0\n ? logWarn(\n `No tables discovered in \\`confect/${TableModule.TABLES_DIRNAME}/\\`. ` +\n `Generating an empty schema; add a \\`Table.make(...)\\` module under that ` +\n `directory unless this backend is intentionally tables-free.`,\n )\n : Effect.void;\n\nconst tableModuleBindings = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n generatedFilePath: string,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedDir = path.dirname(generatedFilePath);\n\n const generatedTablesDirname = yield* GENERATED_TABLES_DIRNAME;\n\n return yield* Effect.forEach(\n tableModules,\n Effect.fnUntraced(function* (tableModule: TableModule.TableModule) {\n const wrapperAbsolutePath = path.join(\n confectDirectory,\n generatedTablesDirname,\n `${tableModule.tableName}.ts`,\n );\n const importPath = yield* toModuleImportPath(\n path.relative(generatedDir, wrapperAbsolutePath),\n );\n return {\n importPath,\n tableName: tableModule.tableName,\n };\n }),\n );\n});\n\nconst generateIdConstructor = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedIdPath = yield* GENERATED_ID_PATH;\n const idPath = path.join(confectDirectory, generatedIdPath);\n\n const tableNames = Array.map(\n tableModules,\n (tableModule) => tableModule.tableName,\n );\n const convexDirectory = yield* ConvexDirectory.target;\n const contents = yield* Match.value(convexDirectory).pipe(\n Match.when({ kind: \"app\" }, () => templates.id({ tableNames })),\n Match.when({ kind: \"component\" }, ({ scope }) =>\n templates.id({ tableNames, scope }),\n ),\n Match.exhaustive,\n );\n\n yield* writeFileStringAndLog(idPath, contents);\n});\n\nconst generateTableWrappers = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedTablesDirname = yield* GENERATED_TABLES_DIRNAME;\n const wrappersDir = path.join(confectDirectory, generatedTablesDirname);\n\n if (!(yield* fs.exists(wrappersDir))) {\n yield* fs.makeDirectory(wrappersDir, { recursive: true });\n }\n\n yield* Effect.forEach(\n tableModules,\n Effect.fnUntraced(function* (tableModule: TableModule.TableModule) {\n const wrapperPath = path.join(\n confectDirectory,\n generatedTablesDirname,\n `${tableModule.tableName}.ts`,\n );\n const unnamedAbsolutePath = path.join(\n confectDirectory,\n tableModule.relativePath,\n );\n const unnamedImportPath = yield* toModuleImportPath(\n path.relative(path.dirname(wrapperPath), unnamedAbsolutePath),\n );\n const contents = yield* templates.tableWrapper({\n tableName: tableModule.tableName,\n unnamedImportPath,\n component: yield* isComponent,\n });\n yield* writeFileStringAndLog(wrapperPath, contents);\n }),\n { concurrency: \"unbounded\" },\n );\n});\n\n/**\n * Remove any stale `_generated/tables/*.ts` wrapper whose source table has been\n * deleted or renamed. Mirrors `removeObsoleteRegisteredFunctions` for the\n * wrapper directory.\n */\nconst removeObsoleteTableWrappers = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedTablesDirname = yield* GENERATED_TABLES_DIRNAME;\n const wrappersDir = path.join(confectDirectory, generatedTablesDirname);\n\n if (!(yield* fs.exists(wrappersDir))) {\n return;\n }\n\n const expected = new Set(\n Array.map(tableModules, (tableModule) => `${tableModule.tableName}.ts`),\n );\n const existing = yield* fs.readDirectory(wrappersDir, { recursive: true });\n yield* Effect.forEach(existing, (entry) => {\n if (path.extname(entry) !== \".ts\") {\n return Effect.void;\n }\n if (!expected.has(entry)) {\n return Effect.gen(function* () {\n const absolutePath = path.join(wrappersDir, entry);\n if (yield* fs.exists(absolutePath)) {\n yield* removePathIfExists(absolutePath);\n yield* logFileRemoved(absolutePath);\n }\n });\n }\n return Effect.void;\n });\n});\n\nconst generateRuntimeSchema = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedSchemaPath = yield* GENERATED_SCHEMA_PATH;\n const schemaPath = path.join(confectDirectory, generatedSchemaPath);\n\n const bindings = yield* tableModuleBindings(tableModules, schemaPath);\n const contents = yield* templates.runtimeSchema({\n tableModules: bindings,\n component: yield* isComponent,\n });\n\n yield* writeFileStringAndLog(schemaPath, contents);\n});\n\nconst generateConvexSchema = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedConvexSchemaPath = yield* GENERATED_CONVEX_SCHEMA_PATH;\n const convexSchemaPath = path.join(\n confectDirectory,\n generatedConvexSchemaPath,\n );\n\n const bindings = yield* tableModuleBindings(tableModules, convexSchemaPath);\n const contents = yield* templates.convexSchema({ tableModules: bindings });\n\n yield* writeFileStringAndLog(convexSchemaPath, contents);\n});\n\nconst generateConvexSchemaReexport = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const convexDirectory = yield* ConvexDirectory.get;\n const generatedConvexSchemaRelativePath = yield* GENERATED_CONVEX_SCHEMA_PATH;\n\n const convexSchemaPath = path.join(convexDirectory, \"schema.ts\");\n const generatedConvexSchemaPath = path.join(\n confectDirectory,\n generatedConvexSchemaRelativePath,\n );\n\n const convexSchemaImportPath = yield* toModuleImportPath(\n path.relative(path.dirname(convexSchemaPath), generatedConvexSchemaPath),\n );\n\n const schemaContents = yield* templates.schema({\n convexSchemaImportPath,\n });\n\n yield* writeFileStringAndLog(convexSchemaPath, schemaContents);\n});\n\nconst generateServices = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const confectGeneratedDirectory = path.join(confectDirectory, \"_generated\");\n\n const servicesPath = path.join(confectGeneratedDirectory, \"services.ts\");\n const generatedSchemaPath = yield* GENERATED_SCHEMA_PATH;\n const schemaImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(servicesPath),\n path.join(confectDirectory, generatedSchemaPath),\n ),\n );\n\n const servicesContentsString = yield* templates.services({\n schemaImportPath,\n component: yield* isComponent,\n });\n\n yield* writeFileStringAndLog(servicesPath, servicesContentsString);\n});\n\n/**\n * Two tables whose names fold to the same PascalCase document type name (e.g.\n * `user_profiles` and `userProfiles` → `UserProfilesDoc`) would emit duplicate\n * interfaces in `_generated/docs.ts`. Catch that up front with a clear error\n * rather than letting `tsc` report a duplicate-identifier later.\n */\nconst validateNoDocNameCollisions = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const collisions = pipe(\n tableModules,\n Array.groupBy((tableModule) =>\n DocName.fromTableName(tableModule.tableName),\n ),\n Record.toEntries,\n Array.filter(([, group]) => group.length > 1),\n Array.map(([docName, group]) => ({\n docName,\n tableNames: Array.map(group, (tableModule) => tableModule.tableName),\n })),\n );\n\n if (Array.isReadonlyArrayNonEmpty(collisions)) {\n return yield* CodegenError.ConflictingDocNameError.make({ collisions });\n }\n});\n\nconst generateDocs = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const confectGeneratedDirectory = path.join(confectDirectory, \"_generated\");\n\n const docsPath = path.join(confectGeneratedDirectory, \"docs.ts\");\n const generatedSchemaPath = yield* GENERATED_SCHEMA_PATH;\n const schemaImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(docsPath),\n path.join(confectDirectory, generatedSchemaPath),\n ),\n );\n\n const docsContentsString = yield* templates.docs({\n schemaImportPath,\n tables: Array.map(tableModules, (tableModule) => ({\n tableName: tableModule.tableName,\n docName: DocName.fromTableName(tableModule.tableName),\n })),\n });\n\n yield* writeFileStringAndLog(docsPath, docsContentsString);\n});\n\nconst generateRefs = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const confectGeneratedDirectory = path.join(confectDirectory, \"_generated\");\n const refsPath = path.join(confectGeneratedDirectory, \"refs.ts\");\n const refsDir = path.dirname(refsPath);\n const generatedSpecPath = yield* GENERATED_SPEC_PATH;\n\n const specImportPath = yield* toModuleImportPath(\n path.relative(refsDir, path.join(confectDirectory, generatedSpecPath)),\n );\n\n const refsContents = yield* templates.refs({ specImportPath });\n\n yield* writeFileStringAndLog(refsPath, refsContents);\n});\n\nconst installedMounts = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const convexDirectory = yield* ConvexDirectory.get;\n const projectRoot = yield* ProjectRoot.get;\n const convexConfigPath = path.join(\n convexDirectory,\n ConvexConfig.CONVEX_CONFIG_FILENAME,\n );\n const installedComponents = (yield* fs.exists(convexConfigPath))\n ? yield* ConvexConfig.discoverInstalledComponents(\n convexConfigPath,\n path.relative(projectRoot, convexConfigPath),\n (yield* ConvexDirectory.target).kind,\n )\n : [];\n return Array.map(\n installedComponents,\n ({ name, componentDefinitionPath }) => ({\n name,\n definition: ConvexConfig.typeImportPath(\n path,\n componentDefinitionPath,\n path.join(confectDirectory, GENERATED_DIRNAME),\n ),\n }),\n );\n});\n\n/**\n * Generate `confect/_generated/components.ts`—the typed registry of Convex\n * components installed in `convex/convex.config.ts` (see\n * {@link templates.components}). The file is emitted even when there is no\n * `convex.config.ts` (as an empty registry) so the import surface stays stable.\n * It must exist before loading tables and specs because they may import bound\n * component IDs and schemas. Returns each mount with the specifier of its\n * definition, relative to `_generated` for an in-repo component.\n *\n * @internal\n */\nexport const generateComponents = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const mounts = yield* installedMounts;\n const contents = yield* templates.components({\n components: Array.map(mounts, ({ name, definition }) => ({\n name,\n typeImportPath: definition,\n })),\n });\n\n const gENERATEDCOMPONENTSPATH = yield* GENERATED_COMPONENTS_PATH;\n yield* writeFileStringAndLog(\n path.join(confectDirectory, gENERATEDCOMPONENTSPATH),\n contents,\n );\n return mounts;\n});\n\nconst provisionalComponents = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const gENERATEDCOMPONENTSPATH = yield* GENERATED_COMPONENTS_PATH;\n const registry = path.join(confectDirectory, gENERATEDCOMPONENTSPATH);\n if (yield* fs.exists(registry)) return;\n const components2 = yield* templates.components({ components: [] });\n yield* writeFileStringAndLog(registry, components2);\n});\n\nconst logGenerated = <E, R>(\n effect: Effect.Effect<\n Option.Option<{\n readonly change: \"Added\" | \"Modified\" | \"Unchanged\";\n readonly convexFilePath: string;\n }>,\n E,\n R\n >,\n) =>\n effect.pipe(\n Effect.tap(\n Option.match({\n onNone: () => Effect.void,\n onSome: ({ change, convexFilePath }) =>\n Match.value(change).pipe(\n Match.when(\"Added\", () => logFileAdded(convexFilePath)),\n Match.when(\"Modified\", () => logFileModified(convexFilePath)),\n Match.when(\"Unchanged\", () => Effect.void),\n Match.exhaustive,\n ),\n }),\n ),\n );\n\n/**\n * A descriptor's `testing` kit must be a package specifier, so the generated\n * registry holds no machine-specific path, and must export `register`. A kit\n * whose exports cannot be listed without running it passes here, and\n * `TestConfect.layer` names the mount if it has no `register`.\n */\nconst checkTestKit = Effect.fnUntraced(function* (\n mount: string,\n specifier: string,\n config: string,\n configDisplay: string,\n) {\n const path = yield* Path.Path;\n const invalid = (problem: string) =>\n CodegenError.InvalidDeclarationError.make({\n declarationPath: \"confect/app.ts\",\n reason: `the mount ${quote(mount)} names the test kit ${quote(specifier)} in its component descriptor${problem}`,\n });\n if (pipe(specifier, String.startsWith(\".\")) || path.isAbsolute(specifier)) {\n return yield* invalid(\n '; name it by a package specifier, such as \"<package>/testing\".',\n );\n }\n const resolved = Bundler.resolveModule(specifier, config);\n if (Option.isNone(resolved)) {\n return yield* invalid(`, which does not resolve from ${configDisplay}.`);\n }\n const exports = yield* Bundler.exportNames(resolved.value).pipe(\n Effect.mapError((error) => fromBundlerError(specifier, error)),\n );\n if (Option.isSome(exports) && !exports.value.includes(\"register\")) {\n return yield* invalid(\", which does not export `register(t, name)`.\");\n }\n});\n\nconst generateTesting = Effect.fnUntraced(function* (app: App.Any) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const convexDirectory = yield* ConvexDirectory.get;\n const generated = path.join(confectDirectory, \"_generated\");\n const projectRoot = yield* ProjectRoot.get;\n const configDisplay = Array.join(\n pipe(\n path.relative(\n projectRoot,\n path.join(convexDirectory, ConvexConfig.CONVEX_CONFIG_FILENAME),\n ),\n String.split(path.sep),\n ),\n \"/\",\n );\n const relative = (file: string) => {\n const value = Array.join(\n pipe(path.relative(generated, file), String.split(path.sep)),\n \"/\",\n );\n return pipe(value, String.startsWith(\".\")) ? value : `./${value}`;\n };\n const imports = [\n 'import schema from \"./schema.js\";',\n 'import convexSchema from \"./convexSchema.js\";',\n ];\n const moduleMap = Effect.fnUntraced(function* (directory: string) {\n const directory2 = yield* fs.readDirectory(directory, { recursive: true });\n const files = Array.filter(\n directory2,\n (file) =>\n /\\.[cm]?[jt]s$/.test(file) &&\n !pipe(file, String.endsWith(\".d.ts\")) &&\n !pipe(file, String.split(path.sep)).includes(\"_generated\") &&\n !pipe(file, String.includes(\".config.\")),\n ).sort();\n return `{ \"_generated/testing.ts\": () => Promise.resolve({}),\\n${pipe(\n files,\n Array.map((file) => {\n const specifier = relative(path.join(directory, file));\n return `${quote(Array.join(pipe(file, String.split(path.sep)), \"/\"))}: () => import(${quote(pipe(specifier, String.replace(/\\.([cm]?)[jt]s$/, \".$1js\")))}),`;\n }),\n Array.join(\"\\n\"),\n )}\\n}`;\n });\n const declarations: Array<string> = [];\n const identifiers = new Set([\"schema\", \"convexSchema\"]);\n const components: Array<string> = [];\n const httpMounts: Array<string> = [];\n const kits = new Map<string, string>();\n const visit = Effect.fnUntraced(function* (\n directory: string,\n prefix: string,\n kind: \"app\" | \"component\",\n parentHttpPrefix: string | undefined,\n ): Effect.fn.Return<\n void,\n | PlatformError.PlatformError\n | BuildError\n | CodegenError.InvalidConvexConfigError\n | CodegenError.InvalidDeclarationError,\n FileSystem.FileSystem | Path.Path\n > {\n const config = path.join(directory, ConvexConfig.CONVEX_CONFIG_FILENAME);\n if (!(yield* fs.exists(config))) return;\n const installed = yield* ConvexConfig.discoverInstalledComponents(\n config,\n relative(config),\n kind,\n );\n for (const component of installed) {\n const name = prefix + component.name;\n const mount =\n prefix === \"\"\n ? Option.getOrUndefined(\n Array.findFirst(\n App.mounts(app),\n (declared) => declared.name === component.name,\n ),\n )\n : undefined;\n // A bare definition belongs to another package. Its directory is read\n // here but never written out; tests use the kit its descriptor names,\n // else its public test entry.\n const fromPackage = !path.isAbsolute(component.componentDefinitionPath);\n const named = fromPackage ? mount?.component.testing : undefined;\n if (named !== undefined) {\n yield* checkTestKit(name, named, config, configDisplay);\n }\n const kitEntries =\n named !== undefined\n ? [named]\n : fromPackage\n ? [\n `${component.componentDefinitionPath}/testing`,\n `${component.componentDefinitionPath}/test`,\n ]\n : [];\n const kitEntry = Option.getOrUndefined(\n Array.findFirst(kitEntries, (entry) =>\n Option.isSome(Bundler.resolveModule(entry, config)),\n ),\n );\n const resolved = fromPackage\n ? yield* ConvexConfig.resolveDefinition(\n `${component.componentDefinitionPath}/convex.config`,\n config,\n path,\n ).pipe(\n Effect.fromOption,\n Effect.mapBoth({\n onFailure: () =>\n CodegenError.InvalidConvexConfigError.make({\n configPath: relative(config),\n reason: `Cannot resolve component ${component.componentDefinitionPath} for testing.`,\n }),\n onSuccess: (definition) => path.dirname(definition),\n }),\n )\n : component.componentDefinitionPath;\n const localPrefix =\n prefix === \"\" ? mount?.httpPrefix : component.httpPrefix;\n const httpPrefix =\n parentHttpPrefix === undefined || localPrefix === undefined\n ? undefined\n : pipe(\n `${pipe(parentHttpPrefix, String.replace(/\\/+$/, \"\"))}${localPrefix}`,\n String.replace(/\\/+$/, \"\"),\n (joined) => (joined === \"\" ? \"/\" : joined),\n );\n if (\n httpPrefix !== undefined &&\n ((yield* fs.exists(path.join(resolved, \"http.ts\"))) ||\n (yield* fs.exists(path.join(resolved, \"http.js\"))))\n ) {\n httpMounts.push(\n `{ componentPath: ${quote(name)}, httpPrefix: ${quote(httpPrefix)} }`,\n );\n }\n const kitKey = kitEntry ?? resolved;\n let identifier = kits.get(kitKey);\n if (identifier === undefined) {\n const cleaned = pipe(name, String.replaceAll(/[^A-Za-z0-9_$]/g, \"_\"));\n const base = /^[A-Za-z_$]/.test(cleaned) ? cleaned : `_${cleaned}`;\n identifier = `${base}Kit`;\n let schemaIdentifier = `${base}Schema`;\n for (\n let n = 2;\n identifiers.has(identifier) || identifiers.has(schemaIdentifier);\n n++\n ) {\n identifier = `${base}Kit${n}`;\n schemaIdentifier = `${base}Schema${n}`;\n }\n identifiers.add(identifier);\n identifiers.add(schemaIdentifier);\n kits.set(kitKey, identifier);\n if (!fromPackage) {\n imports.push(\n `import ${schemaIdentifier} from ${quote(relative(path.join(resolved, \"schema.js\")))};`,\n );\n declarations.push(\n `const ${identifier} = { schema: ${schemaIdentifier}, modules: ${yield* moduleMap(resolved)} };`,\n );\n } else {\n if (kitEntry === undefined) {\n return yield* CodegenError.InvalidConvexConfigError.make({\n configPath: relative(config),\n reason: `the component package ${quote(component.componentDefinitionPath)} has no ${pipe(kitEntries, Array.map(quote), Array.join(\" or \"))} export. Tests register a component from another package through that entry's \\`register(t, name)\\`.`,\n });\n }\n imports.push(`import * as ${identifier} from ${quote(kitEntry)};`);\n }\n }\n components.push(`${quote(name)}: ${identifier},`);\n // A package's own `register` installs its children.\n if (!fromPackage) {\n yield* visit(resolved, `${name}/`, \"component\", httpPrefix);\n }\n }\n });\n yield* visit(convexDirectory, \"\", (yield* ConvexDirectory.target).kind, \"\");\n yield* writeFileStringAndLog(\n path.join(generated, \"testing.ts\"),\n Array.join(\n [\n \"// Generated by `confect codegen`. Test-only; do not import in backend functions.\",\n ...imports,\n ...declarations,\n `export default { httpMounts: [${Array.join(httpMounts, \",\")}], schema, convexSchema, modules: ${yield* moduleMap(convexDirectory)}, components: {${Array.join(components, \"\\n\")}} };`,\n ],\n \"\\n\",\n ),\n );\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0EA,MAAM,oBAAoB;AAE1B,MAAM,oBAAoB,YACxB,OAAO,MAAM,SAAS;CACpB,cAAc,CAAC;CACf,SAAS,EAAE,eAAe;AAC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,IAAI,KAAK,GAAG,MAAM,KAAK,MAAM,CAAC,EAAE;KAC7I,CAAC;KAEH,QAAQ,KAAK,eAAe,WAAW,QAAQ,MAAM,QAAQ,EAAE,EAAE;IACnE;GACF;GACA,WAAW,KAAK,GAAG,MAAM,IAAI,EAAE,IAAI,WAAW,EAAE;GAEhD,IAAI,CAAC,aACH,OAAO,MAAM,UAAU,GAAG,KAAK,IAAI,aAAa,UAAU;EAE9D;CACF,CAAC;CACD,OAAO,MAAM,iBAAiB,KAAK,OAAO,gBAAgB,OAAA,CAAQ,MAAM,EAAE;CAC1E,OAAO,sBACL,KAAK,KAAK,WAAW,YAAY,GACjC,MAAM,KACJ;EACE;EACA,GAAG;EACH,GAAG;EACH,iCAAiC,MAAM,KAAK,YAAY,GAAG,EAAE,oCAAoC,OAAO,UAAU,eAAe,EAAE,iBAAiB,MAAM,KAAK,YAAY,IAAI,EAAE;CACnL,GACA,IACF,CACF;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"codegen.mjs","names":["DirectoryOptions.flags","CodegenError.tapAndLog","DirectoryOptions.layer","TableModule.discover","TableModule.validate","ManifestSections.refuseSpecSections","SectionFiles.sync","FunctionModule.assertOwnedEntrypoints","GenerationSnapshot.fromLoadedLeaves","FunctionModule.generateFunctions","SectionFiles.removeUnclaimed","SectionFiles.verify","Bundler.withBatch","Bundler.check","EntryPoint.planDeclarations","GenerationSnapshot.update","FunctionModule.applyFunctionPlan","GenerationSnapshot.diff","ConvexConfig.componentName","ConvexConfig.CONVEX_CONFIG_FILENAME","Bundler.bundle","templates.componentContract","templates.assembledSpec","templates.registeredFunctionsForGroup","FunctionPaths.make","TableModule.TABLES_DIRNAME","templates.id","templates.tableWrapper","templates.runtimeSchema","templates.convexSchema","templates.schema","templates.services","DocName.fromTableName","templates.docs","templates.refs","ConvexConfig.discoverInstalledComponents","ConvexConfig.typeImportPath","templates.components","Bundler.resolveModule","Bundler.exportNames","ConvexConfig.resolveDefinition"],"sources":["../../src/confect/codegen.ts"],"sourcesContent":["import { App, Callback, Env, type GroupSpec, Spec } from \"@confect/core\";\nimport * as Command from \"effect/cli/Command\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as Array from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as Result from \"effect/Result\";\nimport type * as PlatformError from \"effect/PlatformError\";\nimport type { BuildError } from \"../BuildError.js\";\nimport { pipe } from \"effect/Function\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as Record from \"effect/Record\";\nimport type * as Scope from \"effect/Scope\";\nimport * as Bundler from \"../Bundler.js\";\nimport { fromBundlerError } from \"../BuildError.js\";\nimport * as CodegenError from \"../CodegenError.js\";\nimport { LegacySchemaFileError } from \"../CodegenError.js\";\nimport { ConfectDirectory } from \"../ConfectDirectory.js\";\nimport * as ConvexConfig from \"../ConvexConfig.js\";\nimport { ConvexDirectory } from \"../ConvexDirectory.js\";\nimport * as DirectoryOptions from \"../DirectoryOptions.js\";\nimport * as DocName from \"../DocName.js\";\nimport * as FunctionPaths from \"../FunctionPaths.js\";\nimport * as FunctionModule from \"../FunctionModule.js\";\nimport * as GenerationSnapshot from \"../GenerationSnapshot.js\";\nimport * as EntryPoint from \"../EntryPoint.js\";\nimport type { ImplModulePath } from \"../ImplModulePath.js\";\nimport {\n discoverLeafSpecFiles,\n implPathForSpec,\n loadAll,\n registeredFunctionsRelativePath,\n toLeafModule,\n validateAllImpls,\n withImplFiles,\n type LeafModule,\n type LoadedLeafModule,\n} from \"../LeafModule.js\";\nimport {\n logFileAdded,\n logFileModified,\n logFileRemoved,\n logPending,\n logSuccess,\n logWarn,\n} from \"../log.js\";\nimport { ProjectRoot } from \"../ProjectRoot.js\";\nimport { preserveComponentOutput } from \"../Rollback.js\";\nimport { assemblyNodesFromLeaves } from \"../SpecAssemblyNode.js\";\nimport * as ManifestSections from \"../ManifestSections.js\";\nimport * as SectionFiles from \"../SectionFiles.js\";\nimport * as TableModule from \"../TableModule.js\";\nimport * as templates from \"../templates.js\";\nimport {\n generateAuthConfig,\n generateCrons,\n generateHttp,\n removePathIfExists,\n toModuleImportPath,\n touchConvexSchema,\n writeFileStringAndLog,\n} from \"../utils.js\";\nimport {\n syncManifestSections,\n readPrevious,\n syncDeclaration,\n syncDeployModule,\n syncDeclaredHttp,\n} from \"./declaration.js\";\nimport * as String from \"effect/String\";\nimport { quote } from \"../Json.js\";\n\nconst GENERATED_DIRNAME = \"_generated\";\n\nconst declaredSections = (backend: Option.Option<SectionFiles.Backend>) =>\n Option.match(backend, {\n onNone: () => [],\n onSome: ({ sections }) => sections,\n });\n\nconst isComponent = Effect.map(\n ConvexDirectory.target,\n (target) => target.kind === \"component\",\n);\n\nconst GENERATED_SPEC_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"spec.ts\"),\n);\nconst GENERATED_SCHEMA_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"schema.ts\"),\n);\nconst GENERATED_CONVEX_SCHEMA_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"convexSchema.ts\"),\n);\nconst GENERATED_ID_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"id.ts\"),\n);\nconst GENERATED_COMPONENTS_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"components.ts\"),\n);\nconst GENERATED_TABLES_DIRNAME = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"tables\"),\n);\n\nconst LEGACY_PATHS = Effect.gen(function* () {\n const path = yield* Path.Path;\n\n return [\n \"spec.ts\",\n \"nodeSpec.ts\",\n \"impl.ts\",\n \"nodeImpl.ts\",\n path.join(GENERATED_DIRNAME, \"registeredFunctions.ts\"),\n path.join(GENERATED_DIRNAME, \"nodeRegisteredFunctions.ts\"),\n path.join(GENERATED_DIRNAME, \"impl.ts\"),\n path.join(GENERATED_DIRNAME, \"nodeImpl.ts\"),\n // `_generated/nodeSpec.ts` is not part of the generated output (all groups\n // live in `_generated/spec.ts`); delete any copy left by an older version.\n path.join(GENERATED_DIRNAME, \"nodeSpec.ts\"),\n ];\n});\n\n/**\n * @internal\n */\nexport const codegen = Command.make(\"codegen\", DirectoryOptions.flags, () =>\n Effect.gen(function* () {\n yield* logPending(\"Performing initial sync…\");\n yield* codegenHandler.pipe(\n Effect.asVoid,\n Effect.tap(() => logSuccess(\"Generated files are up-to-date\")),\n CodegenError.tapAndLog,\n );\n }),\n).pipe(\n Command.provide(DirectoryOptions.layer),\n Command.withDescription(\n \"Generate `confect/_generated` files and the contents of the `convex` directory (except `tsconfig.json`, and `convex.config.ts` unless `confect/app.ts` declares the backend)\",\n ),\n);\n\nconst runCodegen = Effect.gen(function* () {\n yield* validateComponentConfiguration;\n yield* rejectDeployModuleGroup;\n yield* generateConfectGeneratedDirectory;\n const previousManifest = yield* readPrevious;\n // Reject a legacy `confect/schema.ts` up front so the user-facing\n // migration message surfaces before any bundler error from impl\n // validation (each impl imports `_generated/schema.ts`).\n yield* rejectLegacySchemaFile;\n // List `confect/tables/*.ts` (filename-only—no bundling yet) so the\n // `_generated/id.ts` constructor can be emitted *before* we bundle any\n // user-authored table module. Tables import from `_generated/id.ts` for\n // cross-table id refs, so it must exist on disk first.\n const tableModules = yield* TableModule.discover;\n yield* warnIfNoTables(tableModules);\n yield* generateIdConstructor(tableModules);\n // The declaration can import `_generated/refs` (a mount's callback arg),\n // which imports the assembled spec, the leaf specs and their table\n // wrappers. Their text follows from the file layout alone, so they are\n // written before the declaration is bundled, even on a first run.\n yield* generateTableWrappers(tableModules);\n yield* removeObsoleteTableWrappers(tableModules);\n const leafSpecFiles = yield* discoverLeafSpecFiles;\n const forEach2 = yield* Effect.forEach(leafSpecFiles, toLeafModule);\n yield* generateAssembledSpecs(forEach2);\n yield* generateRefs;\n // Specs and tables can import the components registry, but the registry\n // reads the `convex.config.ts` that the declaration writes. Only its type\n // depends on the config, so any registry on disk, or an empty one on a first\n // run, serves the declaration bundle until the real one is written below.\n yield* provisionalComponents;\n // A declared backend's `convex.config.ts` and manifest come next: the\n // registry below reads the config, and nothing may validate against a\n // manifest the current declaration did not produce.\n const {\n app: declared,\n digest,\n backend,\n } = yield* syncDeclaration(previousManifest);\n const mounts = yield* generateComponents;\n yield* validateCallbackPrefixes(declared);\n // Now that `_generated/id.ts` is on disk, bundle each table module and\n // check its default export is an `UnnamedTable`. Surface diagnostics\n // here (rather than later) so they appear before impl-validation noise.\n yield* TableModule.validate(tableModules);\n yield* validateNoDocNameCollisions(tableModules);\n yield* generateRuntimeSchema(tableModules);\n const leaves = yield* loadAll;\n yield* rejectComponentNodeGroups(leaves);\n yield* Effect.fromResult(ManifestSections.refuseSpecSections(leaves));\n const sections = yield* SectionFiles.sync(backend, leaves, mounts);\n // Nothing above writes a Convex entrypoint. The check waits for this run's\n // section files, because the HTTP router may import any of them.\n yield* FunctionModule.assertOwnedEntrypoints;\n yield* syncManifestSections(\n declaredSections(backend),\n leaves,\n previousManifest,\n digest,\n sections.modules,\n );\n yield* removeLegacyFiles;\n const snapshot = yield* Effect.fromResult(\n GenerationSnapshot.fromLoadedLeaves(leaves),\n );\n // `_generated/api.ts`/`nodeApi.ts` are no longer imported by generated or\n // impl code (impls take the database schema from `_generated/schema`\n // directly), so remove any copies left over from earlier versions before\n // impl validation runs.\n yield* Effect.all(\n [\n removeGeneratedApi,\n generateComponentContract(tableModules),\n removeGeneratedNodeApi,\n generateDocs(tableModules),\n generateServices,\n generateConvexSchema(tableModules),\n ],\n { concurrency: \"unbounded\" },\n );\n const required = Option.isSome(declared)\n ? declared.value.requiresMiddleware\n : [];\n yield* validateAllImpls(leaves, required);\n yield* generateGroupRegisteredFunctions(leaves, required, sections.files);\n yield* removeObsoleteRegisteredFunctions(leaves);\n const [functionPaths] = yield* Effect.all(\n [\n FunctionModule.generateFunctions(snapshot),\n generateConvexSchemaReexport,\n logGenerated(\n Option.match(declared, {\n onNone: () => generateHttp,\n onSome: (app) => syncDeclaredHttp(app, sections.files),\n }),\n ),\n logGenerated(\n Option.isNone(declared)\n ? generateCrons()\n : syncDeclaredCrons(sections.crons),\n ),\n Option.isNone(declared)\n ? logGenerated(generateAuthConfig)\n : Effect.succeedNone,\n ],\n { concurrency: \"unbounded\" },\n );\n yield* SectionFiles.removeUnclaimed(sections.files);\n yield* syncDeployModule(declared);\n if (Option.isSome(declared)) yield* generateTesting(declared.value);\n yield* SectionFiles.verify(backend, mounts);\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const optionalFiles = yield* Effect.filter(\n [\"http.ts\", \"crons.ts\", \"auth.ts\"],\n (file) => fs.exists(path.join(confectDirectory, file)),\n );\n yield* Bundler.withBatch(\n Array.map(optionalFiles, (file) => path.join(confectDirectory, file)),\n Effect.forEach(\n optionalFiles,\n (file) =>\n Bundler.check(path.join(confectDirectory, file)).pipe(\n Effect.mapError((error) => fromBundlerError(file, error)),\n ),\n { discard: true },\n ),\n );\n return {\n functionPaths,\n snapshot,\n };\n});\n\n/**\n * @internal\n */\nexport const generateWithSnapshot = runCodegen.pipe(\n Effect.withSpan(\"Cli.codegen\"),\n);\n\n/**\n * @internal\n */\nexport const makeCodegenHandler = (\n duringRestore?: Effect.Effect<void, never, Scope.Scope>,\n) =>\n preserveComponentOutput(generateWithSnapshot, duringRestore).pipe(\n Effect.tap(() => touchConvexSchema),\n Effect.map(({ functionPaths }) => ({ functionPaths })),\n );\n\n/**\n * @internal\n */\nexport const codegenHandler = makeCodegenHandler();\n\n/**\n * @internal\n */\nexport const updateDeclarations = Effect.fn(\"Cli.updateDeclarations\")(\n function* (\n snapshot: GenerationSnapshot.GenerationSnapshot,\n declarations: Array.NonEmptyReadonlyArray<EntryPoint.Declaration>,\n affectedImpls: ReadonlyArray<ImplModulePath>,\n ) {\n yield* rejectDeployModuleGroup;\n const previousManifest = yield* readPrevious;\n const path = yield* Path.Path;\n const { paths, tables } = EntryPoint.planDeclarations(\n declarations,\n affectedImpls,\n path,\n );\n yield* TableModule.validate(tables);\n return yield* withImplFiles(paths, (leaves) =>\n Effect.gen(function* () {\n yield* rejectComponentNodeGroups(leaves);\n yield* Effect.fromResult(ManifestSections.refuseSpecSections(leaves));\n const next = yield* Effect.fromResult(\n GenerationSnapshot.update(snapshot, leaves),\n );\n const {\n app: declared,\n digest,\n backend,\n } = yield* syncDeclaration(previousManifest);\n const all = Option.isSome(declared) ? yield* loadAll : [];\n const mounts = Option.isSome(backend) ? yield* installedMounts : [];\n const sections = yield* SectionFiles.sync(backend, all, mounts);\n if (Option.isSome(declared))\n yield* syncManifestSections(\n declaredSections(backend),\n all,\n previousManifest,\n digest,\n sections.modules,\n );\n const required = Option.isSome(declared)\n ? declared.value.requiresMiddleware\n : [];\n yield* validateAllImpls(leaves, required);\n // A section file that appeared or went changes every registration\n // file's imports and the HTTP router's, not only the edited groups'.\n yield* generateGroupRegisteredFunctions(\n sections.changed ? all : leaves,\n required,\n sections.files,\n );\n if (sections.changed && Option.isSome(declared))\n yield* logGenerated(syncDeclaredHttp(declared.value, sections.files));\n // Which sections wrap crons can change while the section files stay.\n if (Option.isSome(declared))\n yield* logGenerated(generateCrons(sections.crons));\n yield* SectionFiles.removeUnclaimed(sections.files);\n yield* FunctionModule.applyFunctionPlan(\n GenerationSnapshot.diff(snapshot, next),\n );\n yield* SectionFiles.verify(backend, mounts);\n return next;\n }),\n );\n },\n);\n\n// Convex components cannot run Node.js functions, at any nesting depth.\nconst validateComponentGroupRuntime = (\n group: GroupSpec.AnyWithProps,\n groupPath: string,\n specPath: string,\n): Result.Result<void, CodegenError.ComponentNodeGroupError> =>\n Result.gen(function* () {\n if (group.runtime === \"Node\") {\n return yield* Result.fail(\n CodegenError.ComponentNodeGroupError.make({ specPath, groupPath }),\n );\n }\n for (const [name, child] of Record.toEntries(group.groups)) {\n yield* validateComponentGroupRuntime(\n child,\n `${groupPath}.${name}`,\n specPath,\n );\n }\n });\n\nconst rejectComponentNodeGroups = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LoadedLeafModule>,\n) {\n if ((yield* ConvexDirectory.target).kind === \"app\") return;\n yield* Effect.forEach(leaves, (leaf) =>\n Effect.fromResult(\n validateComponentGroupRuntime(\n leaf.spec,\n leaf.groupPathDot,\n leaf.relativePath,\n ),\n ),\n );\n});\n\nconst validateCallbackPrefixes = Effect.fnUntraced(function* (\n declared: Option.Option<App.Any>,\n) {\n if ((yield* ConvexDirectory.target).kind !== \"component\") return;\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const callbacksPath = path.join(confectDirectory, \"callbacks.ts\");\n if (!(yield* fs.exists(callbacksPath))) return;\n const name = Option.isSome(declared)\n ? Env.name(App.env(declared.value))\n : yield* Effect.flatMap(ConvexDirectory.get, (convexDirectory) =>\n ConvexConfig.componentName(\n path.join(convexDirectory, ConvexConfig.CONVEX_CONFIG_FILENAME),\n ),\n );\n const { module } = yield* Bundler.bundle(callbacksPath).pipe(\n Effect.mapError((error) => fromBundlerError(\"confect/callbacks.ts\", error)),\n );\n for (const contract of Record.values(module)) {\n if (\n Callback.isContract(contract) &&\n !pipe(contract.id, String.startsWith(`${name}/`))\n ) {\n return yield* CodegenError.CallbackPrefixError.make({\n declarationPath: \"confect/callbacks.ts\",\n contractId: contract.id,\n componentName: name,\n });\n }\n }\n});\n\nconst validateComponentConfiguration = Effect.gen(function* () {\n return yield* Match.value((yield* ConvexDirectory.target).kind).pipe(\n Match.when(\"app\", () => Effect.void),\n Match.when(\"component\", () =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const authPath = path.join(confectDirectory, \"auth.ts\");\n if (yield* fs.exists(authPath)) {\n return yield* CodegenError.InvalidConvexConfigError.make({\n configPath: authPath,\n reason:\n \"Components cannot configure application authentication. Pass identity explicitly through function arguments.\",\n });\n }\n }),\n ),\n Match.exhaustive,\n );\n});\n\nconst generateComponentContract = Effect.fnUntraced(function* (\n tables: ReadonlyArray<TableModule.TableModule>,\n) {\n return yield* Match.value((yield* ConvexDirectory.target).kind).pipe(\n Match.when(\"app\", () => Effect.void),\n Match.when(\"component\", () =>\n Effect.gen(function* () {\n const path = yield* Path.Path;\n const directory = yield* ConfectDirectory.get;\n const contents = yield* templates.componentContract({\n tableNames: Array.map(tables, (table) => table.tableName),\n });\n yield* writeFileStringAndLog(\n path.join(directory, GENERATED_DIRNAME, \"component.ts\"),\n contents,\n );\n }),\n ),\n Match.exhaustive,\n );\n});\n\nconst generateConfectGeneratedDirectory = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n if (!(yield* fs.exists(path.join(confectDirectory, \"_generated\")))) {\n yield* fs.makeDirectory(path.join(confectDirectory, \"_generated\"), {\n recursive: true,\n });\n yield* logFileAdded(path.join(confectDirectory, \"_generated\") + \"/\");\n }\n});\n\nconst removeLegacyFiles = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const legacyPaths = yield* LEGACY_PATHS;\n\n yield* Effect.forEach(\n legacyPaths,\n Effect.fnUntraced(function* (relativePath: string) {\n const absolutePath = path.join(confectDirectory, relativePath);\n if (yield* fs.exists(absolutePath)) {\n yield* removePathIfExists(absolutePath);\n yield* logFileRemoved(absolutePath);\n }\n }),\n );\n});\n\nconst generateAssembledSpecs = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LeafModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedSpecPath = yield* GENERATED_SPEC_PATH;\n\n // A single assembled spec holds every group regardless of runtime—a Node\n // group's `makeNode()` lives in its imported leaf spec, so the assembled\n // file is runtime-agnostic. Always emit it (even empty) so downstream\n // readers (`loadGeneratedSpec`, `generateRefs`) always find a spec module.\n const nodes = assemblyNodesFromLeaves(leaves);\n const specContents = yield* templates.assembledSpec({ nodes });\n yield* writeFileStringAndLog(\n path.join(confectDirectory, generatedSpecPath),\n specContents,\n );\n});\n\nconst generateGroupRegisteredFunctions = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LoadedLeafModule>,\n required: ReadonlyArray<{ readonly key: string }>,\n sectionFiles: ReadonlyArray<string>,\n) {\n const path = yield* Path.Path;\n const fs = yield* FileSystem.FileSystem;\n const confectDirectory = yield* ConfectDirectory.get;\n const runtimePath = path.join(confectDirectory, \"runtime.ts\");\n const hasRuntime = yield* fs.exists(runtimePath);\n\n yield* Effect.forEach(\n leaves,\n Effect.fnUntraced(function* (leaf: LoadedLeafModule) {\n const registryRelativePath = yield* registeredFunctionsRelativePath(leaf);\n const registryPath = path.join(\n confectDirectory,\n \"_generated\",\n registryRelativePath,\n );\n const registryDir = path.dirname(registryPath);\n if (!(yield* fs.exists(registryDir))) {\n yield* fs.makeDirectory(registryDir, { recursive: true });\n }\n\n const implRelativePath = yield* implPathForSpec(leaf.relativePath);\n const schemaImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(registryPath),\n path.join(confectDirectory, \"_generated\", \"schema.ts\"),\n ),\n );\n // The group's own leaf spec (sibling of its impl), referenced\n // type-only by the registry to shape its returned record.\n const specImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(registryPath),\n path.join(confectDirectory, leaf.relativePath),\n ),\n );\n const implImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(registryPath),\n path.join(confectDirectory, implRelativePath),\n ),\n );\n\n const contents = yield* templates.registeredFunctionsForGroup({\n spec: leaf.spec,\n required,\n groupPath: leaf.groupPathDot,\n schemaImportPath,\n specImportPath,\n implImportPath,\n runtimeImportPath: hasRuntime\n ? yield* toModuleImportPath(path.relative(registryDir, runtimePath))\n : undefined,\n sectionImportPaths: yield* Effect.forEach(sectionFiles, (file) =>\n toModuleImportPath(\n path.relative(\n registryDir,\n path.join(confectDirectory, \"_generated\", file),\n ),\n ),\n ),\n });\n\n yield* writeFileStringAndLog(registryPath, contents);\n }),\n );\n});\n\nconst removeObsoleteRegisteredFunctions = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LeafModule>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const registryRoot = path.join(\n confectDirectory,\n \"_generated\",\n \"registeredFunctions\",\n );\n\n if (!(yield* fs.exists(registryRoot))) {\n return;\n }\n\n const expectedPaths = yield* Effect.forEach(leaves, (leaf) =>\n registeredFunctionsRelativePath(leaf),\n );\n const expected = new Set(expectedPaths);\n\n const existing = yield* fs.readDirectory(registryRoot, { recursive: true });\n yield* Effect.forEach(existing, (relativePath) => {\n if (path.extname(relativePath) !== \".ts\") {\n return Effect.void;\n }\n const normalized = path.join(\"registeredFunctions\", relativePath);\n if (!expected.has(normalized)) {\n return Effect.gen(function* () {\n const absolutePath = path.join(registryRoot, relativePath);\n if (yield* fs.exists(absolutePath)) {\n yield* removePathIfExists(absolutePath);\n yield* logFileRemoved(absolutePath);\n }\n });\n }\n return Effect.void;\n });\n});\n\nconst getGeneratedSpecPath = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedSpecPath = yield* GENERATED_SPEC_PATH;\n return path.join(confectDirectory, generatedSpecPath);\n});\n\nconst loadGeneratedSpec = Effect.gen(function* () {\n const specPath = yield* getGeneratedSpecPath;\n const { module: specModule } = yield* Bundler.bundle(specPath);\n const spec = specModule.default;\n\n if (!Spec.isSpec(spec)) {\n return yield* Effect.die(\n new Error(\"_generated/spec.ts does not export a valid Spec\"),\n );\n }\n\n return spec;\n});\n\nconst emptyFunctionPaths = FunctionPaths.FunctionPaths.make(HashSet.empty());\n\n/**\n * @internal\n */\nexport const loadPreviousFunctionPaths = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const specPath = yield* getGeneratedSpecPath;\n\n if (!(yield* fs.exists(specPath))) {\n return emptyFunctionPaths;\n }\n\n const specResult = yield* loadGeneratedSpec.pipe(Effect.result);\n\n return Result.match(specResult, {\n onFailure: () => emptyFunctionPaths,\n onSuccess: (spec) => FunctionPaths.make(spec),\n });\n});\n\n/**\n * Remove a now-obsolete `_generated/<name>.ts` if present (and log it), for\n * projects upgrading from a version that still emitted it.\n */\nconst removeObsoleteGeneratedFile = Effect.fnUntraced(function* (\n fileName: string,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const filePath = path.join(confectDirectory, \"_generated\", fileName);\n\n if (yield* fs.exists(filePath)) {\n yield* removePathIfExists(filePath);\n yield* logFileRemoved(filePath);\n }\n});\n\n// `_generated/api.ts` is no longer imported by generated or impl code: impls\n// take the database schema (`_generated/schema`) directly, and per-group\n// registries reference the spec type-only. Remove any stale copy.\nconst removeGeneratedApi = removeObsoleteGeneratedFile(\"api.ts\");\n\n// `_generated/nodeApi.ts` is obsolete for the same reason.\nconst removeGeneratedNodeApi = removeObsoleteGeneratedFile(\"nodeApi.ts\");\n\n/**\n * The user-authored `confect/schema.ts` is no longer supported: codegen now\n * owns both `_generated/schema.ts` (runtime) and `_generated/convexSchema.ts`\n * (deploy), derived from a single scan of `confect/tables/*.ts`. Detect a stray\n * file and fail with a clear migration message—leaving it in place would\n * silently shadow the codegen-owned\n * `_generated/schema.ts`/`_generated/convexSchema.ts`.\n */\nconst rejectLegacySchemaFile = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const legacyPath = path.join(confectDirectory, \"schema.ts\");\n\n if (yield* fs.exists(legacyPath)) {\n return yield* LegacySchemaFileError.make({ schemaPath: \"schema.ts\" });\n }\n});\n\n// A root group named `confectDeploy` would write the entrypoint\n// `syncDeployModule` owns, so refuse it before anything is written.\nconst rejectDeployModuleGroup = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n if (yield* fs.exists(path.join(confectDirectory, \"confectDeploy.spec.ts\")))\n return yield* CodegenError.InvalidDeclarationError.make({\n declarationPath: \"confect/confectDeploy.spec.ts\",\n reason:\n \"its functions would go in convex/confectDeploy.ts, which codegen writes for the mounts a push initialises. Rename the group, for example to confect/deploy.spec.ts.\",\n });\n});\n\n/**\n * Surface a yellow `⚠` warning when codegen sees no tables—either the\n * `confect/tables/` directory is missing or it contains no `.ts` files.\n * Generation still succeeds (emitting an empty `DatabaseSchema` and\n * `defineSchema({})`), since action-only/table-free Confect backends are\n * legal—but the warning catches the much more common case of a typoed directory\n * or files placed under the wrong root.\n */\nconst warnIfNoTables = (tableModules: ReadonlyArray<TableModule.TableModule>) =>\n tableModules.length === 0\n ? logWarn(\n `No tables discovered in \\`confect/${TableModule.TABLES_DIRNAME}/\\`. ` +\n `Generating an empty schema; add a \\`Table.make(...)\\` module under that ` +\n `directory unless this backend is intentionally tables-free.`,\n )\n : Effect.void;\n\nconst tableModuleBindings = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n generatedFilePath: string,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedDir = path.dirname(generatedFilePath);\n\n const generatedTablesDirname = yield* GENERATED_TABLES_DIRNAME;\n\n return yield* Effect.forEach(\n tableModules,\n Effect.fnUntraced(function* (tableModule: TableModule.TableModule) {\n const wrapperAbsolutePath = path.join(\n confectDirectory,\n generatedTablesDirname,\n `${tableModule.tableName}.ts`,\n );\n const importPath = yield* toModuleImportPath(\n path.relative(generatedDir, wrapperAbsolutePath),\n );\n return {\n importPath,\n tableName: tableModule.tableName,\n };\n }),\n );\n});\n\nconst generateIdConstructor = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedIdPath = yield* GENERATED_ID_PATH;\n const idPath = path.join(confectDirectory, generatedIdPath);\n\n const tableNames = Array.map(\n tableModules,\n (tableModule) => tableModule.tableName,\n );\n const convexDirectory = yield* ConvexDirectory.target;\n const contents = yield* Match.value(convexDirectory).pipe(\n Match.when({ kind: \"app\" }, () => templates.id({ tableNames })),\n Match.when({ kind: \"component\" }, ({ scope }) =>\n templates.id({ tableNames, scope }),\n ),\n Match.exhaustive,\n );\n\n yield* writeFileStringAndLog(idPath, contents);\n});\n\nconst generateTableWrappers = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedTablesDirname = yield* GENERATED_TABLES_DIRNAME;\n const wrappersDir = path.join(confectDirectory, generatedTablesDirname);\n\n if (!(yield* fs.exists(wrappersDir))) {\n yield* fs.makeDirectory(wrappersDir, { recursive: true });\n }\n\n yield* Effect.forEach(\n tableModules,\n Effect.fnUntraced(function* (tableModule: TableModule.TableModule) {\n const wrapperPath = path.join(\n confectDirectory,\n generatedTablesDirname,\n `${tableModule.tableName}.ts`,\n );\n const unnamedAbsolutePath = path.join(\n confectDirectory,\n tableModule.relativePath,\n );\n const unnamedImportPath = yield* toModuleImportPath(\n path.relative(path.dirname(wrapperPath), unnamedAbsolutePath),\n );\n const contents = yield* templates.tableWrapper({\n tableName: tableModule.tableName,\n unnamedImportPath,\n component: yield* isComponent,\n });\n yield* writeFileStringAndLog(wrapperPath, contents);\n }),\n { concurrency: \"unbounded\" },\n );\n});\n\n/**\n * Remove any stale `_generated/tables/*.ts` wrapper whose source table has been\n * deleted or renamed. Mirrors `removeObsoleteRegisteredFunctions` for the\n * wrapper directory.\n */\nconst removeObsoleteTableWrappers = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedTablesDirname = yield* GENERATED_TABLES_DIRNAME;\n const wrappersDir = path.join(confectDirectory, generatedTablesDirname);\n\n if (!(yield* fs.exists(wrappersDir))) {\n return;\n }\n\n const expected = new Set(\n Array.map(tableModules, (tableModule) => `${tableModule.tableName}.ts`),\n );\n const existing = yield* fs.readDirectory(wrappersDir, { recursive: true });\n yield* Effect.forEach(existing, (entry) => {\n if (path.extname(entry) !== \".ts\") {\n return Effect.void;\n }\n if (!expected.has(entry)) {\n return Effect.gen(function* () {\n const absolutePath = path.join(wrappersDir, entry);\n if (yield* fs.exists(absolutePath)) {\n yield* removePathIfExists(absolutePath);\n yield* logFileRemoved(absolutePath);\n }\n });\n }\n return Effect.void;\n });\n});\n\nconst generateRuntimeSchema = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedSchemaPath = yield* GENERATED_SCHEMA_PATH;\n const schemaPath = path.join(confectDirectory, generatedSchemaPath);\n\n const bindings = yield* tableModuleBindings(tableModules, schemaPath);\n const contents = yield* templates.runtimeSchema({\n tableModules: bindings,\n component: yield* isComponent,\n });\n\n yield* writeFileStringAndLog(schemaPath, contents);\n});\n\nconst generateConvexSchema = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedConvexSchemaPath = yield* GENERATED_CONVEX_SCHEMA_PATH;\n const convexSchemaPath = path.join(\n confectDirectory,\n generatedConvexSchemaPath,\n );\n\n const bindings = yield* tableModuleBindings(tableModules, convexSchemaPath);\n const contents = yield* templates.convexSchema({ tableModules: bindings });\n\n yield* writeFileStringAndLog(convexSchemaPath, contents);\n});\n\nconst generateConvexSchemaReexport = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const convexDirectory = yield* ConvexDirectory.get;\n const generatedConvexSchemaRelativePath = yield* GENERATED_CONVEX_SCHEMA_PATH;\n\n const convexSchemaPath = path.join(convexDirectory, \"schema.ts\");\n const generatedConvexSchemaPath = path.join(\n confectDirectory,\n generatedConvexSchemaRelativePath,\n );\n\n const convexSchemaImportPath = yield* toModuleImportPath(\n path.relative(path.dirname(convexSchemaPath), generatedConvexSchemaPath),\n );\n\n const schemaContents = yield* templates.schema({\n convexSchemaImportPath,\n });\n\n yield* writeFileStringAndLog(convexSchemaPath, schemaContents);\n});\n\nconst generateServices = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const confectGeneratedDirectory = path.join(confectDirectory, \"_generated\");\n\n const servicesPath = path.join(confectGeneratedDirectory, \"services.ts\");\n const generatedSchemaPath = yield* GENERATED_SCHEMA_PATH;\n const schemaImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(servicesPath),\n path.join(confectDirectory, generatedSchemaPath),\n ),\n );\n\n const servicesContentsString = yield* templates.services({\n schemaImportPath,\n component: yield* isComponent,\n });\n\n yield* writeFileStringAndLog(servicesPath, servicesContentsString);\n});\n\n/**\n * Two tables whose names fold to the same PascalCase document type name (e.g.\n * `user_profiles` and `userProfiles` → `UserProfilesDoc`) would emit duplicate\n * interfaces in `_generated/docs.ts`. Catch that up front with a clear error\n * rather than letting `tsc` report a duplicate-identifier later.\n */\nconst validateNoDocNameCollisions = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const collisions = pipe(\n tableModules,\n Array.groupBy((tableModule) =>\n DocName.fromTableName(tableModule.tableName),\n ),\n Record.toEntries,\n Array.filter(([, group]) => group.length > 1),\n Array.map(([docName, group]) => ({\n docName,\n tableNames: Array.map(group, (tableModule) => tableModule.tableName),\n })),\n );\n\n if (Array.isReadonlyArrayNonEmpty(collisions)) {\n return yield* CodegenError.ConflictingDocNameError.make({ collisions });\n }\n});\n\nconst generateDocs = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const confectGeneratedDirectory = path.join(confectDirectory, \"_generated\");\n\n const docsPath = path.join(confectGeneratedDirectory, \"docs.ts\");\n const generatedSchemaPath = yield* GENERATED_SCHEMA_PATH;\n const schemaImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(docsPath),\n path.join(confectDirectory, generatedSchemaPath),\n ),\n );\n\n const docsContentsString = yield* templates.docs({\n schemaImportPath,\n tables: Array.map(tableModules, (tableModule) => ({\n tableName: tableModule.tableName,\n docName: DocName.fromTableName(tableModule.tableName),\n })),\n });\n\n yield* writeFileStringAndLog(docsPath, docsContentsString);\n});\n\nconst generateRefs = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const confectGeneratedDirectory = path.join(confectDirectory, \"_generated\");\n const refsPath = path.join(confectGeneratedDirectory, \"refs.ts\");\n const refsDir = path.dirname(refsPath);\n const generatedSpecPath = yield* GENERATED_SPEC_PATH;\n\n const specImportPath = yield* toModuleImportPath(\n path.relative(refsDir, path.join(confectDirectory, generatedSpecPath)),\n );\n\n const refsContents = yield* templates.refs({ specImportPath });\n\n yield* writeFileStringAndLog(refsPath, refsContents);\n});\n\nconst installedMounts = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const convexDirectory = yield* ConvexDirectory.get;\n const projectRoot = yield* ProjectRoot.get;\n const convexConfigPath = path.join(\n convexDirectory,\n ConvexConfig.CONVEX_CONFIG_FILENAME,\n );\n const installedComponents = (yield* fs.exists(convexConfigPath))\n ? yield* ConvexConfig.discoverInstalledComponents(\n convexConfigPath,\n path.relative(projectRoot, convexConfigPath),\n (yield* ConvexDirectory.target).kind,\n )\n : [];\n return Array.map(\n installedComponents,\n ({ name, componentDefinitionPath }) => ({\n name,\n definition: ConvexConfig.typeImportPath(\n path,\n componentDefinitionPath,\n path.join(confectDirectory, GENERATED_DIRNAME),\n ),\n }),\n );\n});\n\n/**\n * Generate `confect/_generated/components.ts`—the typed registry of Convex\n * components installed in `convex/convex.config.ts` (see\n * {@link templates.components}). The file is emitted even when there is no\n * `convex.config.ts` (as an empty registry) so the import surface stays stable.\n * It must exist before loading tables and specs because they may import bound\n * component IDs and schemas. Returns each mount with the specifier of its\n * definition, relative to `_generated` for an in-repo component.\n *\n * @internal\n */\nexport const generateComponents = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const mounts = yield* installedMounts;\n const contents = yield* templates.components({\n components: Array.map(mounts, ({ name, definition }) => ({\n name,\n typeImportPath: definition,\n })),\n });\n\n const gENERATEDCOMPONENTSPATH = yield* GENERATED_COMPONENTS_PATH;\n yield* writeFileStringAndLog(\n path.join(confectDirectory, gENERATEDCOMPONENTSPATH),\n contents,\n );\n return mounts;\n});\n\nconst provisionalComponents = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const gENERATEDCOMPONENTSPATH = yield* GENERATED_COMPONENTS_PATH;\n const registry = path.join(confectDirectory, gENERATEDCOMPONENTSPATH);\n if (yield* fs.exists(registry)) return;\n const components2 = yield* templates.components({ components: [] });\n yield* writeFileStringAndLog(registry, components2);\n});\n\n/**\n * Write a declared backend's `convex/crons.ts`, or remove it once\n * `confect/crons.ts` is gone. Its edits run full generation, so\n * `assertOwnedEntrypoints` has proved an existing file is codegen's.\n */\nconst syncDeclaredCrons = Effect.fnUntraced(function* (\n sectionFiles: ReadonlyArray<string>,\n) {\n const written = yield* generateCrons(sectionFiles);\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n const convexCrons = path.join(convexDirectory, \"crons.ts\");\n if (Option.isNone(written) && (yield* fs.exists(convexCrons))) {\n yield* fs.remove(convexCrons);\n yield* logFileRemoved(convexCrons);\n }\n return written;\n});\n\nconst logGenerated = <E, R>(\n effect: Effect.Effect<\n Option.Option<{\n readonly change: \"Added\" | \"Modified\" | \"Unchanged\";\n readonly convexFilePath: string;\n }>,\n E,\n R\n >,\n) =>\n effect.pipe(\n Effect.tap(\n Option.match({\n onNone: () => Effect.void,\n onSome: ({ change, convexFilePath }) =>\n Match.value(change).pipe(\n Match.when(\"Added\", () => logFileAdded(convexFilePath)),\n Match.when(\"Modified\", () => logFileModified(convexFilePath)),\n Match.when(\"Unchanged\", () => Effect.void),\n Match.exhaustive,\n ),\n }),\n ),\n );\n\n/**\n * A descriptor's `testing` kit must be a package specifier, so the generated\n * registry holds no machine-specific path, and must export `register`. A kit\n * whose exports cannot be listed without running it passes here, and\n * `TestConfect.layer` names the mount if it has no `register`.\n */\nconst checkTestKit = Effect.fnUntraced(function* (\n mount: string,\n specifier: string,\n config: string,\n configDisplay: string,\n) {\n const path = yield* Path.Path;\n const invalid = (problem: string) =>\n CodegenError.InvalidDeclarationError.make({\n declarationPath: \"confect/app.ts\",\n reason: `the mount ${quote(mount)} names the test kit ${quote(specifier)} in its component descriptor${problem}`,\n });\n if (pipe(specifier, String.startsWith(\".\")) || path.isAbsolute(specifier)) {\n return yield* invalid(\n '; name it by a package specifier, such as \"<package>/testing\".',\n );\n }\n const resolved = Bundler.resolveModule(specifier, config);\n if (Option.isNone(resolved)) {\n return yield* invalid(`, which does not resolve from ${configDisplay}.`);\n }\n const exports = yield* Bundler.exportNames(resolved.value).pipe(\n Effect.mapError((error) => fromBundlerError(specifier, error)),\n );\n if (Option.isSome(exports) && !exports.value.includes(\"register\")) {\n return yield* invalid(\", which does not export `register(t, name)`.\");\n }\n});\n\nconst generateTesting = Effect.fnUntraced(function* (app: App.Any) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const convexDirectory = yield* ConvexDirectory.get;\n const generated = path.join(confectDirectory, \"_generated\");\n const projectRoot = yield* ProjectRoot.get;\n const configDisplay = Array.join(\n pipe(\n path.relative(\n projectRoot,\n path.join(convexDirectory, ConvexConfig.CONVEX_CONFIG_FILENAME),\n ),\n String.split(path.sep),\n ),\n \"/\",\n );\n const relative = (file: string) => {\n const value = Array.join(\n pipe(path.relative(generated, file), String.split(path.sep)),\n \"/\",\n );\n return pipe(value, String.startsWith(\".\")) ? value : `./${value}`;\n };\n const imports = [\n 'import schema from \"./schema.js\";',\n 'import convexSchema from \"./convexSchema.js\";',\n ];\n const moduleMap = Effect.fnUntraced(function* (directory: string) {\n const directory2 = yield* fs.readDirectory(directory, { recursive: true });\n const files = Array.filter(\n directory2,\n (file) =>\n /\\.[cm]?[jt]s$/.test(file) &&\n !pipe(file, String.endsWith(\".d.ts\")) &&\n !pipe(file, String.split(path.sep)).includes(\"_generated\") &&\n !pipe(file, String.includes(\".config.\")),\n ).sort();\n return `{ \"_generated/testing.ts\": () => Promise.resolve({}),\\n${pipe(\n files,\n Array.map((file) => {\n const specifier = relative(path.join(directory, file));\n return `${quote(Array.join(pipe(file, String.split(path.sep)), \"/\"))}: () => import(${quote(pipe(specifier, String.replace(/\\.([cm]?)[jt]s$/, \".$1js\")))}),`;\n }),\n Array.join(\"\\n\"),\n )}\\n}`;\n });\n const declarations: Array<string> = [];\n const identifiers = new Set([\"schema\", \"convexSchema\"]);\n const components: Array<string> = [];\n const httpMounts: Array<string> = [];\n const kits = new Map<string, string>();\n const visit = Effect.fnUntraced(function* (\n directory: string,\n prefix: string,\n kind: \"app\" | \"component\",\n parentHttpPrefix: string | undefined,\n ): Effect.fn.Return<\n void,\n | PlatformError.PlatformError\n | BuildError\n | CodegenError.InvalidConvexConfigError\n | CodegenError.InvalidDeclarationError,\n FileSystem.FileSystem | Path.Path\n > {\n const config = path.join(directory, ConvexConfig.CONVEX_CONFIG_FILENAME);\n if (!(yield* fs.exists(config))) return;\n const installed = yield* ConvexConfig.discoverInstalledComponents(\n config,\n relative(config),\n kind,\n );\n for (const component of installed) {\n const name = prefix + component.name;\n const mount =\n prefix === \"\"\n ? Option.getOrUndefined(\n Array.findFirst(\n App.mounts(app),\n (declared) => declared.name === component.name,\n ),\n )\n : undefined;\n // A bare definition belongs to another package. Its directory is read\n // here but never written out; tests use the kit its descriptor names,\n // else its public test entry.\n const fromPackage = !path.isAbsolute(component.componentDefinitionPath);\n const named = fromPackage ? mount?.component.testing : undefined;\n if (named !== undefined) {\n yield* checkTestKit(name, named, config, configDisplay);\n }\n const kitEntries =\n named !== undefined\n ? [named]\n : fromPackage\n ? [\n `${component.componentDefinitionPath}/testing`,\n `${component.componentDefinitionPath}/test`,\n ]\n : [];\n const kitEntry = Option.getOrUndefined(\n Array.findFirst(kitEntries, (entry) =>\n Option.isSome(Bundler.resolveModule(entry, config)),\n ),\n );\n const resolved = fromPackage\n ? yield* ConvexConfig.resolveDefinition(\n `${component.componentDefinitionPath}/convex.config`,\n config,\n path,\n ).pipe(\n Effect.fromOption,\n Effect.mapBoth({\n onFailure: () =>\n CodegenError.InvalidConvexConfigError.make({\n configPath: relative(config),\n reason: `Cannot resolve component ${component.componentDefinitionPath} for testing.`,\n }),\n onSuccess: (definition) => path.dirname(definition),\n }),\n )\n : component.componentDefinitionPath;\n const localPrefix =\n prefix === \"\" ? mount?.httpPrefix : component.httpPrefix;\n const httpPrefix =\n parentHttpPrefix === undefined || localPrefix === undefined\n ? undefined\n : pipe(\n `${pipe(parentHttpPrefix, String.replace(/\\/+$/, \"\"))}${localPrefix}`,\n String.replace(/\\/+$/, \"\"),\n (joined) => (joined === \"\" ? \"/\" : joined),\n );\n if (\n httpPrefix !== undefined &&\n ((yield* fs.exists(path.join(resolved, \"http.ts\"))) ||\n (yield* fs.exists(path.join(resolved, \"http.js\"))))\n ) {\n httpMounts.push(\n `{ componentPath: ${quote(name)}, httpPrefix: ${quote(httpPrefix)} }`,\n );\n }\n const kitKey = kitEntry ?? resolved;\n let identifier = kits.get(kitKey);\n if (identifier === undefined) {\n const cleaned = pipe(name, String.replaceAll(/[^A-Za-z0-9_$]/g, \"_\"));\n const base = /^[A-Za-z_$]/.test(cleaned) ? cleaned : `_${cleaned}`;\n identifier = `${base}Kit`;\n let schemaIdentifier = `${base}Schema`;\n for (\n let n = 2;\n identifiers.has(identifier) || identifiers.has(schemaIdentifier);\n n++\n ) {\n identifier = `${base}Kit${n}`;\n schemaIdentifier = `${base}Schema${n}`;\n }\n identifiers.add(identifier);\n identifiers.add(schemaIdentifier);\n kits.set(kitKey, identifier);\n if (!fromPackage) {\n imports.push(\n `import ${schemaIdentifier} from ${quote(relative(path.join(resolved, \"schema.js\")))};`,\n );\n declarations.push(\n `const ${identifier} = { schema: ${schemaIdentifier}, modules: ${yield* moduleMap(resolved)} };`,\n );\n } else {\n if (kitEntry === undefined) {\n return yield* CodegenError.InvalidConvexConfigError.make({\n configPath: relative(config),\n reason: `the component package ${quote(component.componentDefinitionPath)} has no ${pipe(kitEntries, Array.map(quote), Array.join(\" or \"))} export. Tests register a component from another package through that entry's \\`register(t, name)\\`.`,\n });\n }\n imports.push(`import * as ${identifier} from ${quote(kitEntry)};`);\n }\n }\n components.push(`${quote(name)}: ${identifier},`);\n // A package's own `register` installs its children.\n if (!fromPackage) {\n yield* visit(resolved, `${name}/`, \"component\", httpPrefix);\n }\n }\n });\n yield* visit(convexDirectory, \"\", (yield* ConvexDirectory.target).kind, \"\");\n yield* writeFileStringAndLog(\n path.join(generated, \"testing.ts\"),\n Array.join(\n [\n \"// Generated by `confect codegen`. Test-only; do not import in backend functions.\",\n ...imports,\n ...declarations,\n `export default { httpMounts: [${Array.join(httpMounts, \",\")}], schema, convexSchema, modules: ${yield* moduleMap(convexDirectory)}, components: {${Array.join(components, \"\\n\")}} };`,\n ],\n \"\\n\",\n ),\n );\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0EA,MAAM,oBAAoB;AAE1B,MA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Loop = Effect.fnUntraced(function* (initialFunctionPaths, watcher) {
|
|
|
165
165
|
if (!Outcome.$is("Succeeded")(outcome)) return;
|
|
166
166
|
const dirtyOptionalFiles = [
|
|
167
167
|
...HashSet.has(optional, "Http") ? [syncOptionalFile(generateHttp, "http.ts")] : [],
|
|
168
|
-
...HashSet.has(optional, "Crons") ? [syncOptionalFile(generateCrons, "crons.ts")] : [],
|
|
168
|
+
...HashSet.has(optional, "Crons") ? [syncOptionalFile(generateCrons(), "crons.ts")] : [],
|
|
169
169
|
...HashSet.has(optional, "Auth") ? [syncOptionalFile(generateAuthConfig, "auth.config.ts")] : []
|
|
170
170
|
];
|
|
171
171
|
yield* Array.isReadonlyArrayNonEmpty(dirtyOptionalFiles) ? Effect.all(dirtyOptionalFiles, { concurrency: "unbounded" }) : Effect.void;
|
package/dist/confect/dev.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dev.mjs","names":["Ansi.green","Ansi.red","Ansi.magenta","Ansi.blackBright","FunctionPaths.diff","Evaluation.loadPreviousFunctionPaths","Watcher.make","Evaluation.prewarmedLayer","DirectoryOptions.flags","Watcher.CoalesceQuiescence","DirectoryOptions.layer","SyncState.isDirty","SyncState.forBackend","SyncState.plan","GenerationSnapshot.functionPaths","Evaluation.catchAndLog","Watcher.isRefreshSuccessful","validate","Evaluation.validate","Evaluation.updateDeclarations","SyncState.transition","SyncState.shouldRetry","SyncState.needsDeploymentNotification"],"sources":["../../src/confect/dev.ts"],"sourcesContent":["import * as Command from \"effect/cli/Command\";\nimport * as Flag from \"effect/cli/Flag\";\nimport * as Duration from \"effect/Duration\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Console from \"effect/Console\";\nimport * as Effect from \"effect/Effect\";\nimport * as Equal from \"effect/Equal\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as Order from \"effect/Order\";\nimport * as Ref from \"effect/Ref\";\nimport * as Result from \"effect/Result\";\nimport * as String from \"effect/String\";\nimport type * as esbuild from \"esbuild\";\nimport * as Ansi from \"../Ansi.js\";\nimport { renderCodegenError } from \"../CodegenError.js\";\nimport * as SyncState from \"../SyncState.js\";\nimport type { OptionalFile } from \"../EntryPoint.js\";\nimport * as Watcher from \"../Watcher.js\";\nimport * as Evaluation from \"../Evaluation.js\";\nimport { ConvexDirectory } from \"../ConvexDirectory.js\";\nimport * as DirectoryOptions from \"../DirectoryOptions.js\";\nimport * as FunctionPaths from \"../FunctionPaths.js\";\nimport * as GenerationSnapshot from \"../GenerationSnapshot.js\";\nimport type { ImplModulePath } from \"../ImplModulePath.js\";\nimport type * as GroupPath from \"../GroupPath.js\";\nimport type * as GroupPaths from \"../GroupPaths.js\";\nimport {\n logCoalescedBuildErrors,\n logCoalescedBuildWarnings,\n logFunctionAdded,\n logFunctionRemoved,\n logPending,\n logSuccess,\n} from \"../log.js\";\nimport { ProjectRoot } from \"../ProjectRoot.js\";\nimport { preserveComponentOutput } from \"../Rollback.js\";\nimport {\n generateAuthConfig,\n generateCrons,\n generateHttp,\n touchConvexSchema,\n} from \"../utils.js\";\nimport { isDeclared } from \"./declaration.js\";\n\nconst changeChar = (change: \"Added\" | \"Removed\" | \"Modified\") =>\n Match.value(change).pipe(\n Match.when(\"Added\", () => ({ char: \"+\", color: Ansi.green })),\n Match.when(\"Removed\", () => ({ char: \"-\", color: Ansi.red })),\n Match.when(\"Modified\", () => ({ char: \"~\", color: Ansi.magenta })),\n Match.exhaustive,\n );\n\nconst logFileChangeIndented = Effect.fnUntraced(function* (\n change: \"Added\" | \"Removed\" | \"Modified\",\n fullPath: string,\n) {\n const projectRoot = yield* ProjectRoot.get;\n const path = yield* Path.Path;\n\n const prefix = projectRoot + path.sep;\n const suffix = pipe(fullPath, String.startsWith(prefix))\n ? pipe(fullPath, String.slice(prefix.length))\n : fullPath;\n\n const { char, color } = changeChar(change);\n\n yield* Console.log(\n `${color(char)} ${Ansi.blackBright(prefix)}${color(suffix)}`,\n );\n});\n\nconst logFunctionPathDiff = Effect.fnUntraced(function* (\n previous: FunctionPaths.FunctionPaths,\n current: FunctionPaths.FunctionPaths,\n) {\n const {\n functionsAdded,\n functionsRemoved,\n groupsRemoved,\n groupsAdded,\n groupsChanged,\n } = FunctionPaths.diff(previous, current);\n\n const logForGroups = (\n groupPaths: GroupPaths.GroupPaths,\n fnPaths: FunctionPaths.FunctionPaths,\n logFn: typeof logFunctionAdded,\n ) =>\n Effect.forEach(groupPaths, (gp) =>\n Effect.forEach(\n Array.fromIterable(\n HashSet.filter(fnPaths, (fp) => Equal.equals(fp.groupPath, gp)),\n ),\n logFn,\n ),\n );\n\n yield* logForGroups(groupsRemoved, functionsRemoved, logFunctionRemoved);\n yield* logForGroups(groupsAdded, functionsAdded, logFunctionAdded);\n yield* Effect.forEach(\n groupsChanged,\n Effect.fnUntraced(function* (gp: GroupPath.GroupPath) {\n yield* Effect.forEach(\n Array.fromIterable(\n HashSet.filter(functionsAdded, (fp) =>\n Equal.equals(fp.groupPath, gp),\n ),\n ),\n logFunctionAdded,\n );\n yield* Effect.forEach(\n Array.fromIterable(\n HashSet.filter(functionsRemoved, (fp) =>\n Equal.equals(fp.groupPath, gp),\n ),\n ),\n logFunctionRemoved,\n );\n }),\n );\n});\n\n/**\n * @internal\n */\nexport const devHandler = Effect.gen(function* () {\n yield* logPending(\"Performing initial sync…\");\n const previousFunctionPaths = yield* Evaluation.loadPreviousFunctionPaths;\n\n const watcher = yield* Watcher.make();\n\n yield* Effect.all([watcher.run, syncLoop(previousFunctionPaths, watcher)], {\n concurrency: \"unbounded\",\n });\n // oxlint-disable-next-line effecttsgo/strict-effect-provide -- `confect dev` is an entry point: its watch loop runs under the prewarmed evaluator for the whole session.\n}).pipe(Effect.provide(Evaluation.prewarmedLayer));\n\n/**\n * @internal\n */\nexport const dev = Command.make(\n \"dev\",\n {\n ...DirectoryOptions.flags,\n coalesceMs: Flag.Int(\"coalesce-ms\").pipe(\n Flag.filter(\n (ms) => ms >= 0 && ms <= 5000,\n () =>\n \"Set --coalesce-ms to an integer between 0 and 5000 milliseconds.\",\n ),\n Flag.withDefault(\n Duration.toMillis(Watcher.CoalesceQuiescence.defaultValue()),\n ),\n Flag.withDescription(\n \"Quiet period before processing saved files, in milliseconds.\",\n ),\n ),\n },\n ({ coalesceMs }) =>\n devHandler.pipe(\n Effect.provideService(\n Watcher.CoalesceQuiescence,\n Duration.millis(coalesceMs),\n ),\n ),\n).pipe(\n Command.withDescription(\"Start the Confect development server\"),\n Command.provide(\n (options: { componentDir: Option.Option<string>; coalesceMs: number }) =>\n DirectoryOptions.layer(options),\n ),\n);\n\nconst esbuildMessageKey = (m: esbuild.Message): string =>\n `${m.location?.file ?? \"\"}:${m.location?.line ?? \"\"}:${m.location?.column ?? \"\"}:${m.text}`;\n\nconst dedupeWatcherMessages = (\n messages: ReadonlyArray<esbuild.Message>,\n): ReadonlyArray<esbuild.Message> =>\n pipe(\n messages,\n Array.dedupeWith(\n (messageA, messageB) =>\n esbuildMessageKey(messageA) === esbuildMessageKey(messageB),\n ),\n );\n\nconst watcherMessagesSignature = (\n messages: ReadonlyArray<esbuild.Message>,\n): string =>\n pipe(\n messages,\n Array.map(esbuildMessageKey),\n Array.dedupe,\n Array.sort(Order.String),\n Array.join(\"\\n\"),\n );\n\n/**\n * Log any watcher messages (errors or warnings) that haven't already been\n * logged at their current signature. Suppresses the per-watcher fanout that\n * happens when one root cause (e.g. a missing import) breaks every entry\n * point's build at the same source location.\n */\nconst logChangedWatcherMessages = Effect.fnUntraced(function* (\n messages: ReadonlyArray<esbuild.Message>,\n lastLoggedSignatureRef: Ref.Ref<string>,\n log: (messages: ReadonlyArray<esbuild.Message>) => Effect.Effect<void>,\n) {\n const signature = watcherMessagesSignature(messages);\n const previous = yield* Ref.get(lastLoggedSignatureRef);\n if (signature === previous) return;\n yield* Ref.set(lastLoggedSignatureRef, signature);\n if (messages.length === 0) return;\n yield* log(dedupeWatcherMessages(messages));\n});\n\nconst syncLoop = Effect.fnUntraced(function* (\n initialFunctionPaths: FunctionPaths.FunctionPaths,\n watcher: Watcher.Watcher,\n) {\n const functionPathsRef = yield* Ref.make(initialFunctionPaths);\n const lastLoggedErrorsRef = yield* Ref.make<string>(\"\");\n const lastLoggedWarningsRef = yield* Ref.make<string>(\"\");\n const phaseRef = yield* Ref.make<SyncState.Phase>(\n SyncState.Phase.Bootstrapping(),\n );\n const optionalPendingRef = yield* Ref.make(HashSet.empty<OptionalFile>());\n const logMessages = Effect.gen(function* () {\n const { errors, warnings } = yield* watcher.diagnostics;\n yield* logChangedWatcherMessages(\n errors,\n lastLoggedErrorsRef,\n logCoalescedBuildErrors,\n );\n yield* logChangedWatcherMessages(\n warnings,\n lastLoggedWarningsRef,\n logCoalescedBuildWarnings,\n );\n });\n\n return yield* Effect.forever(\n Effect.gen(function* () {\n yield* Effect.logDebug(\"Running sync loop…\");\n const taken = yield* watcher.next;\n\n const phase = yield* Ref.get(phaseRef);\n const firstSync = SyncState.Phase.$is(\"Bootstrapping\")(phase);\n if (!firstSync) yield* logMessages;\n\n if (!SyncState.isDirty(taken)) return;\n\n const declared = yield* isDeclared;\n const pending = SyncState.forBackend(\n {\n ...taken,\n optional: yield* Ref.updateAndGet(\n optionalPendingRef,\n HashSet.union(taken.optional),\n ),\n },\n {\n declared,\n component: (yield* ConvexDirectory.target).kind === \"component\",\n },\n );\n const optional = pending.optional;\n const operation = SyncState.plan(phase, pending);\n yield* Effect.logDebug(\"Planned development sync\").pipe(\n Effect.annotateLogs({\n phase: phase._tag,\n work: pending.work._tag,\n operation: operation._tag,\n }),\n );\n if (\n !firstSync &&\n !(\n SyncState.Operation.$is(\"Validate\")(operation) &&\n operation.paths.length === 0\n )\n )\n yield* logPending(\"Dependencies may have changed, reloading…\");\n\n const regenerate = <R>(\n generation: Effect.Effect<\n GenerationSnapshot.GenerationSnapshot,\n Effect.Error<typeof Evaluation.generateSnapshot>,\n R\n >,\n ) =>\n Effect.gen(function* () {\n const current = yield* generation.pipe(\n Effect.tap((snapshot) =>\n Effect.gen(function* () {\n const nextFunctionPaths =\n GenerationSnapshot.functionPaths(snapshot);\n const previous = yield* Ref.get(functionPathsRef);\n yield* logFunctionPathDiff(previous, nextFunctionPaths);\n yield* Ref.set(functionPathsRef, nextFunctionPaths);\n }),\n ),\n Evaluation.catchAndLog,\n );\n if (Option.isNone(current)) {\n return SyncState.Outcome.GenerationFailed();\n }\n const refreshed = yield* watcher.refresh.pipe(Effect.result);\n if (Result.isFailure(refreshed)) {\n yield* Console.error(\n `Dependency watcher could not ${refreshed.failure.operation}: ${globalThis.String(refreshed.failure.cause)}`,\n );\n return SyncState.Outcome.ReconciliationFailed();\n }\n if (!Watcher.isRefreshSuccessful(refreshed.success)) {\n yield* logMessages;\n return SyncState.Outcome.ReconciliationFailed();\n }\n return SyncState.Outcome.Succeeded({ snapshot: current.value });\n });\n const preserved = <R>(\n generation: Effect.Effect<\n GenerationSnapshot.GenerationSnapshot,\n Effect.Error<typeof Evaluation.generateSnapshot>,\n R\n >,\n ) =>\n preserveComponentOutput(generation, watcher.duringRestore).pipe(\n Effect.tapErrorTag(\n \"ComponentNodeGroupError\",\n () => watcher.discardRestoreEchoes,\n ),\n Effect.catchTags({\n RemoveBusyError: (error) =>\n Effect.fail(\n Evaluation.EvaluationError.make({\n diagnostic: renderCodegenError(error),\n }),\n ),\n // Output that cannot be restored leaves nothing to serve.\n PlatformError: Effect.die,\n }),\n );\n const validate = (\n paths: ReadonlyArray<ImplModulePath>,\n snapshot: GenerationSnapshot.GenerationSnapshot,\n ) =>\n Effect.gen(function* () {\n if (Array.isReadonlyArrayNonEmpty(paths)) {\n const validated = yield* Evaluation.validate(paths).pipe(\n Evaluation.catchAndLog,\n );\n if (Option.isNone(validated)) {\n return SyncState.Outcome.ValidationFailed({ paths, snapshot });\n }\n }\n return SyncState.Outcome.Succeeded({ snapshot });\n });\n const outcome = yield* SyncState.Operation.$match(operation, {\n Generate: () => Evaluation.generateSnapshot.pipe(preserved, regenerate),\n Validate: ({ paths, snapshot }) => validate(paths, snapshot),\n Update: ({ snapshot, declarations, paths }) =>\n Evaluation.updateDeclarations(snapshot, declarations, paths).pipe(\n preserved,\n regenerate,\n ),\n });\n yield* Ref.set(phaseRef, SyncState.transition(outcome));\n if (SyncState.shouldRetry(phase, outcome)) {\n yield* watcher.requestRetry;\n }\n if (!SyncState.Outcome.$is(\"Succeeded\")(outcome)) return;\n\n const dirtyOptionalFiles = [\n ...(HashSet.has(optional, \"Http\")\n ? [syncOptionalFile(generateHttp, \"http.ts\")]\n : []),\n ...(HashSet.has(optional, \"Crons\")\n ? [syncOptionalFile(generateCrons, \"crons.ts\")]\n : []),\n ...(HashSet.has(optional, \"Auth\")\n ? [syncOptionalFile(generateAuthConfig, \"auth.config.ts\")]\n : []),\n ];\n\n yield* Array.isReadonlyArrayNonEmpty(dirtyOptionalFiles)\n ? Effect.all(dirtyOptionalFiles, { concurrency: \"unbounded\" })\n : Effect.void;\n yield* Ref.set(optionalPendingRef, HashSet.empty());\n\n if (SyncState.needsDeploymentNotification(phase))\n yield* touchConvexSchema;\n\n const remaining = yield* watcher.pending;\n if (!SyncState.isDirty(remaining)) {\n yield* logSuccess(\"Generated files are up-to-date\");\n }\n }),\n );\n});\n\nconst syncOptionalFile = (generate: typeof generateHttp, convexFile: string) =>\n pipe(\n generate,\n Effect.andThen(\n Option.match({\n onSome: ({ change, convexFilePath }) =>\n Match.value(change).pipe(\n Match.when(\"Unchanged\", () => Effect.void),\n Match.whenOr(\"Added\", \"Modified\", (addedOrModified) =>\n logFileChangeIndented(addedOrModified, convexFilePath),\n ),\n Match.exhaustive,\n ),\n onNone: () =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n const convexFilePath = path.join(convexDirectory, convexFile);\n\n if (yield* fs.exists(convexFilePath)) {\n yield* fs.remove(convexFilePath);\n yield* logFileChangeIndented(\"Removed\", convexFilePath);\n }\n }),\n }),\n ),\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAM,cAAc,WAClB,MAAM,MAAM,MAAM,CAAC,CAAC,KAClB,MAAM,KAAK,gBAAgB;CAAE,MAAM;CAAK,OAAOA;AAAW,EAAE,GAC5D,MAAM,KAAK,kBAAkB;CAAE,MAAM;CAAK,OAAOC;AAAS,EAAE,GAC5D,MAAM,KAAK,mBAAmB;CAAE,MAAM;CAAK,OAAOC;AAAa,EAAE,GACjE,MAAM,UACR;AAEF,MAAM,wBAAwB,OAAO,WAAW,WAC9C,QACA,UACA;CAIA,MAAM,UAAS,OAHY,YAAY,QAGV,OAFT,KAAK,KAAA,CAES;CAClC,MAAM,SAAS,KAAK,UAAU,OAAO,WAAW,MAAM,CAAC,IACnD,KAAK,UAAU,OAAO,MAAM,OAAO,MAAM,CAAC,IAC1C;CAEJ,MAAM,EAAE,MAAM,UAAU,WAAW,MAAM;CAEzC,OAAO,QAAQ,IACb,GAAG,MAAM,IAAI,EAAE,GAAGC,YAAiB,MAAM,IAAI,MAAM,MAAM,GAC3D;AACF,CAAC;AAED,MAAM,sBAAsB,OAAO,WAAW,WAC5C,UACA,SACA;CACA,MAAM,EACJ,gBACA,kBACA,eACA,aACA,kBACEC,KAAmB,UAAU,OAAO;CAExC,MAAM,gBACJ,YACA,SACA,UAEA,OAAO,QAAQ,aAAa,OAC1B,OAAO,QACL,MAAM,aACJ,QAAQ,OAAO,UAAU,OAAO,MAAM,OAAO,GAAG,WAAW,EAAE,CAAC,CAChE,GACA,KACF,CACF;CAEF,OAAO,aAAa,eAAe,kBAAkB,kBAAkB;CACvE,OAAO,aAAa,aAAa,gBAAgB,gBAAgB;CACjE,OAAO,OAAO,QACZ,eACA,OAAO,WAAW,WAAW,IAAyB;EACpD,OAAO,OAAO,QACZ,MAAM,aACJ,Q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IC,4BAAsC,KAAK,GAC7C,OAAO;EAET,MAAM,YAAY,OAAO,QAAQ;EACjC,IAAI,CAACX,QAAkB,SAAS,GAC9B,OAAO,WAAW,gCAAgC;CAEtD,CAAC,CACH;AACF,CAAC;AAED,MAAM,oBAAoB,UAA+B,eACvD,KACE,UACA,OAAO,QACL,OAAO,MAAM;CACX,SAAS,EAAE,QAAQ,qBACjB,MAAM,MAAM,MAAM,CAAC,CAAC,KAClB,MAAM,KAAK,mBAAmB,OAAO,IAAI,GACzC,MAAM,OAAO,SAAS,aAAa,oBACjC,sBAAsB,iBAAiB,cAAc,CACvD,GACA,MAAM,UACR;CACF,cACE,OAAO,IAAI,aAAa;EACtB,MAAM,KAAK,OAAO,WAAW;EAC7B,MAAM,OAAO,OAAO,KAAK;EACzB,MAAM,kBAAkB,OAAO,gBAAgB;EAC/C,MAAM,iBAAiB,KAAK,KAAK,iBAAiB,UAAU;EAE5D,IAAI,OAAO,GAAG,OAAO,cAAc,GAAG;GACpC,OAAO,GAAG,OAAO,cAAc;GAC/B,OAAO,sBAAsB,WAAW,cAAc;EACxD;CACF,CAAC;AACL,CAAC,CACH,CACF"}
|
|
1
|
+
{"version":3,"file":"dev.mjs","names":["Ansi.green","Ansi.red","Ansi.magenta","Ansi.blackBright","FunctionPaths.diff","Evaluation.loadPreviousFunctionPaths","Watcher.make","Evaluation.prewarmedLayer","DirectoryOptions.flags","Watcher.CoalesceQuiescence","DirectoryOptions.layer","SyncState.isDirty","SyncState.forBackend","SyncState.plan","GenerationSnapshot.functionPaths","Evaluation.catchAndLog","Watcher.isRefreshSuccessful","validate","Evaluation.validate","Evaluation.updateDeclarations","SyncState.transition","SyncState.shouldRetry","SyncState.needsDeploymentNotification"],"sources":["../../src/confect/dev.ts"],"sourcesContent":["import * as Command from \"effect/cli/Command\";\nimport * as Flag from \"effect/cli/Flag\";\nimport * as Duration from \"effect/Duration\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Console from \"effect/Console\";\nimport * as Effect from \"effect/Effect\";\nimport * as Equal from \"effect/Equal\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as Order from \"effect/Order\";\nimport * as Ref from \"effect/Ref\";\nimport * as Result from \"effect/Result\";\nimport * as String from \"effect/String\";\nimport type * as esbuild from \"esbuild\";\nimport * as Ansi from \"../Ansi.js\";\nimport { renderCodegenError } from \"../CodegenError.js\";\nimport * as SyncState from \"../SyncState.js\";\nimport type { OptionalFile } from \"../EntryPoint.js\";\nimport * as Watcher from \"../Watcher.js\";\nimport * as Evaluation from \"../Evaluation.js\";\nimport { ConvexDirectory } from \"../ConvexDirectory.js\";\nimport * as DirectoryOptions from \"../DirectoryOptions.js\";\nimport * as FunctionPaths from \"../FunctionPaths.js\";\nimport * as GenerationSnapshot from \"../GenerationSnapshot.js\";\nimport type { ImplModulePath } from \"../ImplModulePath.js\";\nimport type * as GroupPath from \"../GroupPath.js\";\nimport type * as GroupPaths from \"../GroupPaths.js\";\nimport {\n logCoalescedBuildErrors,\n logCoalescedBuildWarnings,\n logFunctionAdded,\n logFunctionRemoved,\n logPending,\n logSuccess,\n} from \"../log.js\";\nimport { ProjectRoot } from \"../ProjectRoot.js\";\nimport { preserveComponentOutput } from \"../Rollback.js\";\nimport {\n generateAuthConfig,\n generateCrons,\n generateHttp,\n touchConvexSchema,\n} from \"../utils.js\";\nimport { isDeclared } from \"./declaration.js\";\n\nconst changeChar = (change: \"Added\" | \"Removed\" | \"Modified\") =>\n Match.value(change).pipe(\n Match.when(\"Added\", () => ({ char: \"+\", color: Ansi.green })),\n Match.when(\"Removed\", () => ({ char: \"-\", color: Ansi.red })),\n Match.when(\"Modified\", () => ({ char: \"~\", color: Ansi.magenta })),\n Match.exhaustive,\n );\n\nconst logFileChangeIndented = Effect.fnUntraced(function* (\n change: \"Added\" | \"Removed\" | \"Modified\",\n fullPath: string,\n) {\n const projectRoot = yield* ProjectRoot.get;\n const path = yield* Path.Path;\n\n const prefix = projectRoot + path.sep;\n const suffix = pipe(fullPath, String.startsWith(prefix))\n ? pipe(fullPath, String.slice(prefix.length))\n : fullPath;\n\n const { char, color } = changeChar(change);\n\n yield* Console.log(\n `${color(char)} ${Ansi.blackBright(prefix)}${color(suffix)}`,\n );\n});\n\nconst logFunctionPathDiff = Effect.fnUntraced(function* (\n previous: FunctionPaths.FunctionPaths,\n current: FunctionPaths.FunctionPaths,\n) {\n const {\n functionsAdded,\n functionsRemoved,\n groupsRemoved,\n groupsAdded,\n groupsChanged,\n } = FunctionPaths.diff(previous, current);\n\n const logForGroups = (\n groupPaths: GroupPaths.GroupPaths,\n fnPaths: FunctionPaths.FunctionPaths,\n logFn: typeof logFunctionAdded,\n ) =>\n Effect.forEach(groupPaths, (gp) =>\n Effect.forEach(\n Array.fromIterable(\n HashSet.filter(fnPaths, (fp) => Equal.equals(fp.groupPath, gp)),\n ),\n logFn,\n ),\n );\n\n yield* logForGroups(groupsRemoved, functionsRemoved, logFunctionRemoved);\n yield* logForGroups(groupsAdded, functionsAdded, logFunctionAdded);\n yield* Effect.forEach(\n groupsChanged,\n Effect.fnUntraced(function* (gp: GroupPath.GroupPath) {\n yield* Effect.forEach(\n Array.fromIterable(\n HashSet.filter(functionsAdded, (fp) =>\n Equal.equals(fp.groupPath, gp),\n ),\n ),\n logFunctionAdded,\n );\n yield* Effect.forEach(\n Array.fromIterable(\n HashSet.filter(functionsRemoved, (fp) =>\n Equal.equals(fp.groupPath, gp),\n ),\n ),\n logFunctionRemoved,\n );\n }),\n );\n});\n\n/**\n * @internal\n */\nexport const devHandler = Effect.gen(function* () {\n yield* logPending(\"Performing initial sync…\");\n const previousFunctionPaths = yield* Evaluation.loadPreviousFunctionPaths;\n\n const watcher = yield* Watcher.make();\n\n yield* Effect.all([watcher.run, syncLoop(previousFunctionPaths, watcher)], {\n concurrency: \"unbounded\",\n });\n // oxlint-disable-next-line effecttsgo/strict-effect-provide -- `confect dev` is an entry point: its watch loop runs under the prewarmed evaluator for the whole session.\n}).pipe(Effect.provide(Evaluation.prewarmedLayer));\n\n/**\n * @internal\n */\nexport const dev = Command.make(\n \"dev\",\n {\n ...DirectoryOptions.flags,\n coalesceMs: Flag.Int(\"coalesce-ms\").pipe(\n Flag.filter(\n (ms) => ms >= 0 && ms <= 5000,\n () =>\n \"Set --coalesce-ms to an integer between 0 and 5000 milliseconds.\",\n ),\n Flag.withDefault(\n Duration.toMillis(Watcher.CoalesceQuiescence.defaultValue()),\n ),\n Flag.withDescription(\n \"Quiet period before processing saved files, in milliseconds.\",\n ),\n ),\n },\n ({ coalesceMs }) =>\n devHandler.pipe(\n Effect.provideService(\n Watcher.CoalesceQuiescence,\n Duration.millis(coalesceMs),\n ),\n ),\n).pipe(\n Command.withDescription(\"Start the Confect development server\"),\n Command.provide(\n (options: { componentDir: Option.Option<string>; coalesceMs: number }) =>\n DirectoryOptions.layer(options),\n ),\n);\n\nconst esbuildMessageKey = (m: esbuild.Message): string =>\n `${m.location?.file ?? \"\"}:${m.location?.line ?? \"\"}:${m.location?.column ?? \"\"}:${m.text}`;\n\nconst dedupeWatcherMessages = (\n messages: ReadonlyArray<esbuild.Message>,\n): ReadonlyArray<esbuild.Message> =>\n pipe(\n messages,\n Array.dedupeWith(\n (messageA, messageB) =>\n esbuildMessageKey(messageA) === esbuildMessageKey(messageB),\n ),\n );\n\nconst watcherMessagesSignature = (\n messages: ReadonlyArray<esbuild.Message>,\n): string =>\n pipe(\n messages,\n Array.map(esbuildMessageKey),\n Array.dedupe,\n Array.sort(Order.String),\n Array.join(\"\\n\"),\n );\n\n/**\n * Log any watcher messages (errors or warnings) that haven't already been\n * logged at their current signature. Suppresses the per-watcher fanout that\n * happens when one root cause (e.g. a missing import) breaks every entry\n * point's build at the same source location.\n */\nconst logChangedWatcherMessages = Effect.fnUntraced(function* (\n messages: ReadonlyArray<esbuild.Message>,\n lastLoggedSignatureRef: Ref.Ref<string>,\n log: (messages: ReadonlyArray<esbuild.Message>) => Effect.Effect<void>,\n) {\n const signature = watcherMessagesSignature(messages);\n const previous = yield* Ref.get(lastLoggedSignatureRef);\n if (signature === previous) return;\n yield* Ref.set(lastLoggedSignatureRef, signature);\n if (messages.length === 0) return;\n yield* log(dedupeWatcherMessages(messages));\n});\n\nconst syncLoop = Effect.fnUntraced(function* (\n initialFunctionPaths: FunctionPaths.FunctionPaths,\n watcher: Watcher.Watcher,\n) {\n const functionPathsRef = yield* Ref.make(initialFunctionPaths);\n const lastLoggedErrorsRef = yield* Ref.make<string>(\"\");\n const lastLoggedWarningsRef = yield* Ref.make<string>(\"\");\n const phaseRef = yield* Ref.make<SyncState.Phase>(\n SyncState.Phase.Bootstrapping(),\n );\n const optionalPendingRef = yield* Ref.make(HashSet.empty<OptionalFile>());\n const logMessages = Effect.gen(function* () {\n const { errors, warnings } = yield* watcher.diagnostics;\n yield* logChangedWatcherMessages(\n errors,\n lastLoggedErrorsRef,\n logCoalescedBuildErrors,\n );\n yield* logChangedWatcherMessages(\n warnings,\n lastLoggedWarningsRef,\n logCoalescedBuildWarnings,\n );\n });\n\n return yield* Effect.forever(\n Effect.gen(function* () {\n yield* Effect.logDebug(\"Running sync loop…\");\n const taken = yield* watcher.next;\n\n const phase = yield* Ref.get(phaseRef);\n const firstSync = SyncState.Phase.$is(\"Bootstrapping\")(phase);\n if (!firstSync) yield* logMessages;\n\n if (!SyncState.isDirty(taken)) return;\n\n const declared = yield* isDeclared;\n const pending = SyncState.forBackend(\n {\n ...taken,\n optional: yield* Ref.updateAndGet(\n optionalPendingRef,\n HashSet.union(taken.optional),\n ),\n },\n {\n declared,\n component: (yield* ConvexDirectory.target).kind === \"component\",\n },\n );\n const optional = pending.optional;\n const operation = SyncState.plan(phase, pending);\n yield* Effect.logDebug(\"Planned development sync\").pipe(\n Effect.annotateLogs({\n phase: phase._tag,\n work: pending.work._tag,\n operation: operation._tag,\n }),\n );\n if (\n !firstSync &&\n !(\n SyncState.Operation.$is(\"Validate\")(operation) &&\n operation.paths.length === 0\n )\n )\n yield* logPending(\"Dependencies may have changed, reloading…\");\n\n const regenerate = <R>(\n generation: Effect.Effect<\n GenerationSnapshot.GenerationSnapshot,\n Effect.Error<typeof Evaluation.generateSnapshot>,\n R\n >,\n ) =>\n Effect.gen(function* () {\n const current = yield* generation.pipe(\n Effect.tap((snapshot) =>\n Effect.gen(function* () {\n const nextFunctionPaths =\n GenerationSnapshot.functionPaths(snapshot);\n const previous = yield* Ref.get(functionPathsRef);\n yield* logFunctionPathDiff(previous, nextFunctionPaths);\n yield* Ref.set(functionPathsRef, nextFunctionPaths);\n }),\n ),\n Evaluation.catchAndLog,\n );\n if (Option.isNone(current)) {\n return SyncState.Outcome.GenerationFailed();\n }\n const refreshed = yield* watcher.refresh.pipe(Effect.result);\n if (Result.isFailure(refreshed)) {\n yield* Console.error(\n `Dependency watcher could not ${refreshed.failure.operation}: ${globalThis.String(refreshed.failure.cause)}`,\n );\n return SyncState.Outcome.ReconciliationFailed();\n }\n if (!Watcher.isRefreshSuccessful(refreshed.success)) {\n yield* logMessages;\n return SyncState.Outcome.ReconciliationFailed();\n }\n return SyncState.Outcome.Succeeded({ snapshot: current.value });\n });\n const preserved = <R>(\n generation: Effect.Effect<\n GenerationSnapshot.GenerationSnapshot,\n Effect.Error<typeof Evaluation.generateSnapshot>,\n R\n >,\n ) =>\n preserveComponentOutput(generation, watcher.duringRestore).pipe(\n Effect.tapErrorTag(\n \"ComponentNodeGroupError\",\n () => watcher.discardRestoreEchoes,\n ),\n Effect.catchTags({\n RemoveBusyError: (error) =>\n Effect.fail(\n Evaluation.EvaluationError.make({\n diagnostic: renderCodegenError(error),\n }),\n ),\n // Output that cannot be restored leaves nothing to serve.\n PlatformError: Effect.die,\n }),\n );\n const validate = (\n paths: ReadonlyArray<ImplModulePath>,\n snapshot: GenerationSnapshot.GenerationSnapshot,\n ) =>\n Effect.gen(function* () {\n if (Array.isReadonlyArrayNonEmpty(paths)) {\n const validated = yield* Evaluation.validate(paths).pipe(\n Evaluation.catchAndLog,\n );\n if (Option.isNone(validated)) {\n return SyncState.Outcome.ValidationFailed({ paths, snapshot });\n }\n }\n return SyncState.Outcome.Succeeded({ snapshot });\n });\n const outcome = yield* SyncState.Operation.$match(operation, {\n Generate: () => Evaluation.generateSnapshot.pipe(preserved, regenerate),\n Validate: ({ paths, snapshot }) => validate(paths, snapshot),\n Update: ({ snapshot, declarations, paths }) =>\n Evaluation.updateDeclarations(snapshot, declarations, paths).pipe(\n preserved,\n regenerate,\n ),\n });\n yield* Ref.set(phaseRef, SyncState.transition(outcome));\n if (SyncState.shouldRetry(phase, outcome)) {\n yield* watcher.requestRetry;\n }\n if (!SyncState.Outcome.$is(\"Succeeded\")(outcome)) return;\n\n const dirtyOptionalFiles = [\n ...(HashSet.has(optional, \"Http\")\n ? [syncOptionalFile(generateHttp, \"http.ts\")]\n : []),\n ...(HashSet.has(optional, \"Crons\")\n ? [syncOptionalFile(generateCrons(), \"crons.ts\")]\n : []),\n ...(HashSet.has(optional, \"Auth\")\n ? [syncOptionalFile(generateAuthConfig, \"auth.config.ts\")]\n : []),\n ];\n\n yield* Array.isReadonlyArrayNonEmpty(dirtyOptionalFiles)\n ? Effect.all(dirtyOptionalFiles, { concurrency: \"unbounded\" })\n : Effect.void;\n yield* Ref.set(optionalPendingRef, HashSet.empty());\n\n if (SyncState.needsDeploymentNotification(phase))\n yield* touchConvexSchema;\n\n const remaining = yield* watcher.pending;\n if (!SyncState.isDirty(remaining)) {\n yield* logSuccess(\"Generated files are up-to-date\");\n }\n }),\n );\n});\n\nconst syncOptionalFile = (generate: typeof generateHttp, convexFile: string) =>\n pipe(\n generate,\n Effect.andThen(\n Option.match({\n onSome: ({ change, convexFilePath }) =>\n Match.value(change).pipe(\n Match.when(\"Unchanged\", () => Effect.void),\n Match.whenOr(\"Added\", \"Modified\", (addedOrModified) =>\n logFileChangeIndented(addedOrModified, convexFilePath),\n ),\n Match.exhaustive,\n ),\n onNone: () =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n const convexFilePath = path.join(convexDirectory, convexFile);\n\n if (yield* fs.exists(convexFilePath)) {\n yield* fs.remove(convexFilePath);\n yield* logFileChangeIndented(\"Removed\", convexFilePath);\n }\n }),\n }),\n ),\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAM,cAAc,WAClB,MAAM,MAAM,MAAM,CAAC,CAAC,KAClB,MAAM,KAAK,gBAAgB;CAAE,MAAM;CAAK,OAAOA;AAAW,EAAE,GAC5D,MAAM,KAAK,kBAAkB;CAAE,MAAM;CAAK,OAAOC;AAAS,EAAE,GAC5D,MAAM,KAAK,mBAAmB;CAAE,MAAM;CAAK,OAAOC;AAAa,EAAE,GACjE,MAAM,UACR;AAEF,MAAM,wBAAwB,OAAO,WAAW,WAC9C,QACA,UACA;CAIA,MAAM,UAAS,OAHY,YAAY,QAGV,OAFT,KAAK,KAAA,CAES;CAClC,MAAM,SAAS,KAAK,UAAU,OAAO,WAAW,MAAM,CAAC,IACnD,KAAK,UAAU,OAAO,MAAM,OAAO,MAAM,CAAC,IAC1C;CAEJ,MAAM,EAAE,MAAM,UAAU,WAAW,MAAM;CAEzC,OAAO,QAAQ,IACb,GAAG,MAAM,IAAI,EAAE,GAAGC,YAAiB,MAAM,IAAI,MAAM,MAAM,GAC3D;AACF,CAAC;AAED,MAAM,sBAAsB,OAAO,WAAW,WAC5C,UACA,SACA;CACA,MAAM,EACJ,gBACA,kBACA,eACA,aACA,kBACEC,KAAmB,UAAU,OAAO;CAExC,MAAM,gBACJ,YACA,SACA,UAEA,OAAO,QAAQ,aAAa,OAC1B,OAAO,QACL,MAAM,aACJ,QAAQ,OAAO,UAAU,OAAO,MAAM,OAAO,GAAG,WAAW,EAAE,CAAC,CAChE,GACA,KACF,CACF;CAEF,OAAO,aA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;EACP;EAEA,OAAO,MAAM,wBAAwB,kBAAkB,IACnD,OAAO,IAAI,oBAAoB,EAAE,aAAa,YAAY,CAAC,IAC3D,OAAO;EACX,OAAO,IAAI,IAAI,oBAAoB,QAAQ,MAAM,CAAC;EAElD,IAAIC,4BAAsC,KAAK,GAC7C,OAAO;EAET,MAAM,YAAY,OAAO,QAAQ;EACjC,IAAI,CAACX,QAAkB,SAAS,GAC9B,OAAO,WAAW,gCAAgC;CAEtD,CAAC,CACH;AACF,CAAC;AAED,MAAM,oBAAoB,UAA+B,eACvD,KACE,UACA,OAAO,QACL,OAAO,MAAM;CACX,SAAS,EAAE,QAAQ,qBACjB,MAAM,MAAM,MAAM,CAAC,CAAC,KAClB,MAAM,KAAK,mBAAmB,OAAO,IAAI,GACzC,MAAM,OAAO,SAAS,aAAa,oBACjC,sBAAsB,iBAAiB,cAAc,CACvD,GACA,MAAM,UACR;CACF,cACE,OAAO,IAAI,aAAa;EACtB,MAAM,KAAK,OAAO,WAAW;EAC7B,MAAM,OAAO,OAAO,KAAK;EACzB,MAAM,kBAAkB,OAAO,gBAAgB;EAC/C,MAAM,iBAAiB,KAAK,KAAK,iBAAiB,UAAU;EAE5D,IAAI,OAAO,GAAG,OAAO,cAAc,GAAG;GACpC,OAAO,GAAG,OAAO,cAAc;GAC/B,OAAO,sBAAsB,WAAW,cAAc;EACxD;CACF,CAAC;AACL,CAAC,CACH,CACF"}
|
package/dist/templates.mjs
CHANGED
|
@@ -178,12 +178,28 @@ const declaredHttp = Effect.fnUntraced(function* ({ schemaImportPath, httpImport
|
|
|
178
178
|
yield* cbw.writeLine(`export default HttpRouter.make(schema, http.routes, { api: http.api${runtimeImportPath === void 0 ? "" : ", observability"} });`);
|
|
179
179
|
return yield* cbw.toString();
|
|
180
180
|
});
|
|
181
|
-
|
|
182
|
-
|
|
181
|
+
/**
|
|
182
|
+
* Emit `convex/crons.ts`, which deploys `confect/crons.ts`'s jobs after passing
|
|
183
|
+
* them through the `crons` export of each section file in `sectionImportPaths`,
|
|
184
|
+
* in order.
|
|
185
|
+
*/
|
|
186
|
+
const crons = Effect.fnUntraced(function* ({ cronsImportPath, sectionImportPaths = [] }) {
|
|
183
187
|
const cbw = new CodeBlockWriter({ indentNumberOfSpaces: 2 });
|
|
188
|
+
if (sectionImportPaths.length === 0) {
|
|
189
|
+
yield* cbw.writeLine(`import crons from "${cronsImportPath}";`);
|
|
190
|
+
yield* cbw.newLine();
|
|
191
|
+
yield* cbw.writeLine(`export default crons.convexCronJobs;`);
|
|
192
|
+
return yield* cbw.toString();
|
|
193
|
+
}
|
|
194
|
+
const wraps = Array.map(sectionImportPaths, (_, index) => `wrap${index}`);
|
|
195
|
+
yield* cbw.writeLine("// Generated by `confect codegen` from confect/crons.ts. Do not edit.");
|
|
196
|
+
yield* cbw.writeLine(`import type { CronJobs } from "@confect/server";`);
|
|
197
|
+
for (const [index, sectionImportPath] of sectionImportPaths.entries()) yield* cbw.writeLine(`import { crons as wrap${index} } from "${sectionImportPath}";`);
|
|
184
198
|
yield* cbw.writeLine(`import crons from "${cronsImportPath}";`);
|
|
185
199
|
yield* cbw.newLine();
|
|
186
|
-
yield* cbw.writeLine(`
|
|
200
|
+
yield* cbw.writeLine(`const wraps: ReadonlyArray<(crons: CronJobs.CronJobs) => CronJobs.CronJobs> = [${Array.join(wraps, ", ")}];`);
|
|
201
|
+
yield* cbw.newLine();
|
|
202
|
+
yield* cbw.writeLine(`export default wraps.reduce<CronJobs.CronJobs>((jobs, wrap) => wrap(jobs), crons).convexCronJobs;`);
|
|
187
203
|
return yield* cbw.toString();
|
|
188
204
|
});
|
|
189
205
|
const authConfig = ({ authImportPath }) => authConfigEffect({ authImportPath });
|