@gaganref/confect-cli 10.3.1-fork.86 → 10.3.1-fork.88

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.
@@ -2,7 +2,7 @@ import { BundleFailedError, fromBundlerError } from "./BuildError.mjs";
2
2
  import { bundle, directlyImports, importersOfPackage, withBatch } from "./Bundler.mjs";
3
3
  import { ImplMissingDefaultLayerError, ImplMissingFunctionsError, ImplMissingMiddlewareError, ImplMissingSpecImportError, ImplNotFinalizedError, InvalidDeclarationError, InvalidMiddlewareAttachmentError, MissingImplFileError, MissingSpecFileError, RequiredMiddlewareError, SpecImportsServerError, SpecMissingDefaultGroupSpecError } from "./CodegenError.mjs";
4
4
  import { ConfectDirectory } from "./ConfectDirectory.mjs";
5
- import { removePathExtension, toPosixPath } from "./utils.mjs";
5
+ import { readDirectorySorted, removePathExtension, toPosixPath } from "./utils.mjs";
6
6
  import { ImplModulePath } from "./ImplModulePath.mjs";
7
7
  import * as Effect from "effect/Effect";
8
8
  import { GroupSpec, MiddlewareAttachment } from "@confect/core";
@@ -57,12 +57,11 @@ const registeredFunctionsRelativePath = Effect.fnUntraced(function* (leaf) {
57
57
  return (yield* Path.Path).join("registeredFunctions", ...leaf.pathSegments) + ".ts";
58
58
  });
59
59
  const discoverLeafSpecFiles = Effect.gen(function* () {
60
- const fs = yield* FileSystem.FileSystem;
61
60
  const path = yield* Path.Path;
62
61
  const confectDirectory = yield* ConfectDirectory.get;
63
62
  const excludedDirs = HashSet.make("_generated", "tables", "middleware");
64
63
  const excludedFiles = HashSet.make("nodeSpec.ts", "spec.ts");
65
- const allPaths = yield* fs.readDirectory(confectDirectory, { recursive: true });
64
+ const allPaths = yield* readDirectorySorted(confectDirectory);
66
65
  return Array.filter(allPaths, (relativePath) => {
67
66
  if (!isLeafSpecPath(relativePath)) return false;
68
67
  if (HashSet.has(excludedFiles, relativePath)) return false;
@@ -71,11 +70,10 @@ const discoverLeafSpecFiles = Effect.gen(function* () {
71
70
  });
72
71
  });
73
72
  const discoverLeafImplFiles = Effect.gen(function* () {
74
- const fs = yield* FileSystem.FileSystem;
75
73
  const path = yield* Path.Path;
76
74
  const confectDirectory = yield* ConfectDirectory.get;
77
75
  const excludedDirs = HashSet.make("_generated", "tables", "middleware");
78
- const allPaths = yield* fs.readDirectory(confectDirectory, { recursive: true });
76
+ const allPaths = yield* readDirectorySorted(confectDirectory);
79
77
  return Array.filter(Array.filterMap(allPaths, (relativePath) => Schema.decodeResult(ImplModulePath)(relativePath)), (relativePath) => {
80
78
  const segments = String.split(relativePath, path.sep);
81
79
  return !Array.some(segments, (segment) => HashSet.has(excludedDirs, segment));
@@ -1 +1 @@
1
- {"version":3,"file":"LeafModule.mjs","names":["Bundler.importersOfPackage","Bundler.bundle","Bundler.directlyImports","Bundler.withBatch"],"sources":["../src/LeafModule.ts"],"sourcesContent":["import { GroupSpec, MiddlewareAttachment } from \"@confect/core\";\nimport { Registry, RegistryItems } from \"@confect/server\";\nimport * as GroupImpl from \"@confect/server/GroupImpl\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport type { Context } from \"effect\";\nimport type * as esbuild from \"esbuild\";\nimport * as Array from \"effect/Array\";\nimport * as Brand from \"effect/Brand\";\nimport * as Effect from \"effect/Effect\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as String from \"effect/String\";\nimport { BundleFailedError, fromBundlerError } from \"./BuildError.js\";\nimport * as Bundler from \"./Bundler.js\";\nimport {\n InvalidDeclarationError,\n MissingImplFileError,\n MissingSpecFileError,\n ImplMissingDefaultLayerError,\n ImplMissingFunctionsError,\n ImplMissingMiddlewareError,\n RequiredMiddlewareError,\n ImplMissingSpecImportError,\n ImplNotFinalizedError,\n InvalidMiddlewareAttachmentError,\n SpecImportsServerError,\n SpecMissingDefaultGroupSpecError,\n} from \"./CodegenError.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport { ImplModulePath } from \"./ImplModulePath.js\";\nimport { removePathExtension, toPosixPath } from \"./utils.js\";\n\nexport interface LeafModule {\n readonly relativePath: string;\n readonly pathSegments: readonly [string, ...string[]];\n readonly groupPathDot: string;\n readonly exportName: string;\n readonly specImportPath: string;\n}\n\nexport type LoadedLeafModule = LeafModule & {\n readonly spec: GroupSpec.AnyWithProps;\n} & Brand.Brand<\"@confect/cli/LoadedLeafModule\">;\n\nconst LoadedLeafModule = Brand.nominal<LoadedLeafModule>();\n\nconst VALIDATION_CONCURRENCY = 4;\n\nexport const SPEC_SUFFIX = \".spec.ts\";\nexport const IMPL_SUFFIX = \".impl.ts\";\n\nconst swapModuleSuffix = Effect.fnUntraced(function* (\n relativePath: string,\n fromSuffix: string,\n toSuffix: string,\n) {\n const path = yield* Path.Path;\n const { dir, name, ext } = path.parse(relativePath);\n if (ext !== \".ts\" || !name.endsWith(fromSuffix.slice(0, -\".ts\".length))) {\n return relativePath;\n }\n\n const stem = name.slice(0, -fromSuffix.slice(0, -\".ts\".length).length);\n const nextName = `${stem}${toSuffix.slice(0, -\".ts\".length)}`;\n return dir.length > 0\n ? path.join(dir, `${nextName}${ext}`)\n : `${nextName}${ext}`;\n});\n\nexport const isLeafSpecPath = (relativePath: string) =>\n relativePath.endsWith(SPEC_SUFFIX);\n\nexport const exportNameFromModulePath = Effect.fnUntraced(function* (\n relativePath: string,\n) {\n const path = yield* Path.Path;\n const { name, ext } = path.parse(relativePath);\n if (ext !== \".ts\") {\n return name;\n }\n return name.endsWith(\".spec\") ? name.slice(0, -\".spec\".length) : name;\n});\n\nexport const groupPathFromRelativeModulePath = Effect.fnUntraced(function* (\n relativePath: string,\n) {\n const path = yield* Path.Path;\n const { dir, name, ext } = path.parse(relativePath);\n const stem =\n ext === \".ts\" && name.endsWith(\".spec\")\n ? name.slice(0, -\".spec\".length)\n : name;\n const dirSegments = Array.filter(\n String.split(dir, path.sep),\n String.isNonEmpty,\n );\n const pathSegments = Array.append(dirSegments, stem) as [string, ...string[]];\n return {\n pathSegments,\n groupPathDot: Array.join(pathSegments, \".\"),\n };\n});\n\nexport const specImportPathFromGenerated = Effect.fnUntraced(function* (\n specRelativePath: string,\n) {\n const path = yield* Path.Path;\n const withoutExt = toPosixPath(\n path,\n yield* removePathExtension(specRelativePath),\n );\n return `../${withoutExt}.js`;\n});\n\nexport const specPathForImpl = (implRelativePath: string) =>\n swapModuleSuffix(implRelativePath, IMPL_SUFFIX, SPEC_SUFFIX);\n\nexport const implPathForSpec = (specRelativePath: string) =>\n swapModuleSuffix(specRelativePath, SPEC_SUFFIX, IMPL_SUFFIX);\n\nexport const registeredFunctionsRelativePath = Effect.fnUntraced(function* (\n leaf: LeafModule,\n) {\n const path = yield* Path.Path;\n return path.join(\"registeredFunctions\", ...leaf.pathSegments) + \".ts\";\n});\n\nexport const discoverLeafSpecFiles = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const excludedDirs = HashSet.make(\"_generated\", \"tables\", \"middleware\");\n const excludedFiles = HashSet.make(\"nodeSpec.ts\", \"spec.ts\");\n\n const allPaths = yield* fs.readDirectory(confectDirectory, {\n recursive: true,\n });\n\n return Array.filter(allPaths, (relativePath) => {\n if (!isLeafSpecPath(relativePath)) {\n return false;\n }\n\n if (HashSet.has(excludedFiles, relativePath)) {\n return false;\n }\n\n const segments = String.split(relativePath, path.sep);\n return !Array.some(segments, (segment) =>\n HashSet.has(excludedDirs, segment),\n );\n });\n});\n\nexport const discoverLeafImplFiles = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const excludedDirs = HashSet.make(\"_generated\", \"tables\", \"middleware\");\n\n const allPaths = yield* fs.readDirectory(confectDirectory, {\n recursive: true,\n });\n\n return Array.filter(\n Array.filterMap(allPaths, (relativePath) =>\n Schema.decodeResult(ImplModulePath)(relativePath),\n ),\n (relativePath) => {\n const segments = String.split(relativePath, path.sep);\n return !Array.some(segments, (segment) =>\n HashSet.has(excludedDirs, segment),\n );\n },\n );\n});\n\nexport const toLeafModule = Effect.fnUntraced(function* (\n specRelativePath: string,\n) {\n const exportName = yield* exportNameFromModulePath(specRelativePath);\n const { pathSegments, groupPathDot } =\n yield* groupPathFromRelativeModulePath(specRelativePath);\n const specImportPath = yield* specImportPathFromGenerated(specRelativePath);\n\n return {\n relativePath: specRelativePath,\n pathSegments,\n groupPathDot,\n exportName,\n specImportPath,\n } satisfies LeafModule;\n});\n\nconst absoluteModulePath = Effect.fnUntraced(function* (relativePath: string) {\n const confectDirectory = yield* ConfectDirectory.get;\n const path = yield* Path.Path;\n return path.resolve(confectDirectory, relativePath);\n});\n\n/**\n * Every `*.spec.ts` is reachable from `_generated/spec.ts`, which the client\n * imports through `_generated/refs.ts`—so a spec's whole import graph is\n * bundled into the browser whether or not the client calls those functions.\n * Server logic co-located with a declaration therefore ships to users,\n * silently.\n *\n * `@confect/server` is a sound proxy for \"server logic lives here\": an\n * implementation can't be written without `FunctionImpl`/`MiddlewareImpl`, both\n * of which live there. Table `Doc`/`Fields` schemas live in `@confect/core`, so\n * the documented `notes.Doc` pattern in a spec must not reach `@confect/server`\n * even through `tables/` or `_generated/`. The check runs over the spec\n * bundle's transitive inputs rather than the spec module alone, so it also\n * covers middleware declarations under `confect/middleware/` (which codegen\n * otherwise never visits) and any shared helper a spec pulls in—while only ever\n * flagging modules that genuinely reach the client.\n */\nconst validateClientSafety = Effect.fnUntraced(function* (\n leaf: LeafModule,\n bundled: Bundler.Bundled,\n) {\n const path = yield* Path.Path;\n const confectDirectory = path.resolve(yield* ConfectDirectory.get);\n\n const isCheckedUserModule = (absolutePath: string) => {\n const relative = path.relative(confectDirectory, absolutePath);\n return !relative.startsWith(\"..\") && !path.isAbsolute(relative);\n };\n\n const importers = Bundler.importersOfPackage(\n bundled,\n \"@confect/server\",\n isCheckedUserModule,\n );\n\n if (importers.length > 0) {\n return yield* new SpecImportsServerError({\n specPath: leaf.relativePath,\n importerPaths: Array.map(importers, (absolutePath) =>\n toPosixPath(path, path.relative(confectDirectory, absolutePath)),\n ),\n });\n }\n});\n\nconst validateReservedArguments = Effect.fnUntraced(function* (\n group: GroupSpec.AnyWithProps,\n specPath: string,\n groupPath: string,\n): Effect.fn.Return<void, InvalidDeclarationError> {\n for (const spec of Object.values(group.functions)) {\n const name = spec.reservedArgument;\n const provenance = spec.functionProvenance;\n if (\n name !== undefined &&\n provenance._tag === \"Confect\" &&\n Object.hasOwn(provenance.args.fields, name)\n ) {\n return yield* new InvalidDeclarationError({\n declarationPath: `confect/${specPath}`,\n reason: `${groupPath}:${spec.name} declares the argument \"${name}\", which its profile reserves. Rename the argument.`,\n });\n }\n }\n for (const [name, child] of Object.entries(group.groups)) {\n yield* validateReservedArguments(child, specPath, `${groupPath}/${name}`);\n }\n});\n\n/**\n * Validate that the leaf's spec file default-exports a `GroupSpec`, and that\n * nothing it reaches drags server code into the client (see\n * {@link validateClientSafety}). Returns the leaf paired with its validated\n * spec, so subsequent operations reuse that association without re-bundling.\n * The runtime is declared by the spec, not its file location.\n */\nexport const loadSpec = Effect.fn(\"LeafModule.loadSpec\")(function* (\n leaf: LeafModule,\n) {\n const absolutePath = yield* absoluteModulePath(leaf.relativePath);\n const bundled = yield* Bundler.bundle(absolutePath).pipe(\n Effect.mapError((error) => fromBundlerError(leaf.relativePath, error)),\n );\n\n const groupSpec = bundled.module.default;\n\n if (!GroupSpec.isGroupSpec(groupSpec)) {\n return yield* new SpecMissingDefaultGroupSpecError({\n specPath: leaf.relativePath,\n });\n }\n\n yield* validateClientSafety(leaf, bundled);\n yield* validateReservedArguments(\n groupSpec,\n leaf.relativePath,\n leaf.pathSegments.join(\"/\"),\n );\n\n yield* Effect.fromResult(GroupSpec.validateMiddleware(groupSpec)).pipe(\n Effect.mapError(\n (error) =>\n new InvalidMiddlewareAttachmentError({\n specPath: leaf.relativePath,\n message: MiddlewareAttachment.formatValidationError(error),\n }),\n ),\n );\n\n return LoadedLeafModule({\n ...leaf,\n spec: groupSpec,\n });\n});\n\n/**\n * Walk the built `Context` for a `Finalized` `GroupImpl` service value. The\n * lookup is value-shaped (via `GroupImpl.isFinalizedGroupImpl`) so we don't\n * need to know the group's path up front to construct a typed tag for it.\n */\nconst findFinalizedGroupImpl = <S>(\n context: Context.Context<S>,\n): Option.Option<GroupImpl.AnyFinalized> =>\n Array.findFirst(context.mapUnsafe.values(), GroupImpl.isFinalizedGroupImpl);\n\n/**\n * Build the impl layer with a fresh `Registry` so each validation is isolated\n * from prior validations' `FunctionImpl.make` writes. Retain its items to check\n * required middleware against actual function attachments.\n */\nconst buildImplLayer = Effect.fnUntraced(function* (\n implLayer: Layer.Layer<unknown>,\n) {\n const registry = Ref.makeUnsafe<RegistryItems.RegistryItems>({});\n const context = yield* Layer.build(\n implLayer as Layer.Layer<unknown, never, never>,\n ).pipe(Effect.provideService(Registry.Registry, registry));\n return { context, items: yield* Ref.get(registry) };\n}, Effect.scoped);\n\n/**\n * Validate that the leaf's sibling impl file imports the spec, default-exports\n * a finalized `GroupImpl` layer, and provides a `FunctionImpl` for every\n * function declared by the spec. Return uncovered middleware requirements for\n * the caller to report across groups.\n */\n/**\n * An implementation's unresolved import of a `confect/_generated` file is a\n * section file that no declared section writes: every declared section's file\n * is on disk before implementations validate. Say so, at the import.\n */\nconst nameUnwrittenSectionFiles = Effect.fnUntraced(function* (\n error: BundleFailedError,\n bundleDirectory: string,\n) {\n const path = yield* Path.Path;\n const generated = path.join(yield* ConfectDirectory.get, \"_generated\");\n const errors = (error.errors as ReadonlyArray<esbuild.Message>).map(\n (message) => {\n const specifier = /^Could not resolve \"(.+)\"$/.exec(message.text)?.[1];\n if (specifier === undefined || message.location === null) return message;\n const file = path.relative(\n generated,\n path.resolve(\n bundleDirectory,\n path.dirname(message.location.file),\n specifier,\n ),\n );\n if (file.startsWith(\"..\") || path.isAbsolute(file)) return message;\n const extension = path.extname(file);\n const name = toPosixPath(\n path,\n extension === \"\"\n ? `${file}.ts`\n : extension === \".js\"\n ? `${file.slice(0, -extension.length)}.ts`\n : file,\n );\n return Object.assign({}, message, {\n text: `No manifest section this backend declares writes _generated/${name}. Declare its section on App.make({ manifestSections }) in confect/app.ts.`,\n });\n },\n );\n return new BundleFailedError({ file: error.file, errors });\n});\n\nexport const validateImpl = Effect.fn(\"LeafModule.validateImpl\")(function* (\n leaf: LoadedLeafModule,\n required: ReadonlyArray<{ readonly key: string }> = [],\n) {\n const path = yield* Path.Path;\n const implRelativePath = yield* implPathForSpec(leaf.relativePath);\n const implAbsolutePath = yield* absoluteModulePath(implRelativePath);\n const specAbsolutePath = yield* absoluteModulePath(leaf.relativePath);\n\n const bundled = yield* Bundler.bundle(implAbsolutePath).pipe(\n Effect.mapError((error) => fromBundlerError(implRelativePath, error)),\n Effect.catchTag(\"BundleFailedError\", (error) =>\n Effect.flip(\n nameUnwrittenSectionFiles(error, path.dirname(implAbsolutePath)),\n ),\n ),\n );\n\n if (\n !(yield* Bundler.directlyImports(\n bundled,\n implAbsolutePath,\n specAbsolutePath,\n ))\n ) {\n return yield* new ImplMissingSpecImportError({\n implPath: implRelativePath,\n expectedSpecPath: leaf.relativePath,\n });\n }\n\n if (!Layer.isLayer(bundled.module.default)) {\n return yield* new ImplMissingDefaultLayerError({\n implPath: implRelativePath,\n });\n }\n\n const groupSpec = leaf.spec;\n const expectedFunctionNames = Object.keys(groupSpec.functions);\n\n const { context, items } = yield* buildImplLayer(\n bundled.module.default as Layer.Layer<unknown>,\n );\n const finalizedGroupImpl = yield* Option.match(\n findFinalizedGroupImpl(context),\n {\n onNone: () => new ImplNotFinalizedError({ implPath: implRelativePath }),\n onSome: Effect.succeed,\n },\n );\n\n const registeredSet = HashSet.fromIterable(\n finalizedGroupImpl.registeredFunctionNames,\n );\n const missing = expectedFunctionNames.filter(\n (name) => !HashSet.has(registeredSet, name),\n );\n\n if (missing.length > 0) {\n return yield* new ImplMissingFunctionsError({\n implPath: implRelativePath,\n groupPath: leaf.groupPathDot,\n missingFunctionNames: missing,\n });\n }\n\n const expectedMiddlewareKeys = Array.dedupe([\n ...(groupSpec.middlewareSpecs ?? []).map(\n (middlewareSpec) => middlewareSpec.key,\n ),\n ...Object.values(groupSpec.functions).flatMap((function_) =>\n (function_.middlewareSpecs ?? []).map(\n (middlewareSpec) => middlewareSpec.key,\n ),\n ),\n ]);\n const registeredMiddlewareKeys = HashSet.fromIterable(\n finalizedGroupImpl.registeredMiddlewareKeys ?? [],\n );\n const missingMiddleware = Array.filter(\n expectedMiddlewareKeys,\n (key) => !HashSet.has(registeredMiddlewareKeys, key),\n );\n\n if (missingMiddleware.length > 0) {\n return yield* new ImplMissingMiddlewareError({\n implPath: implRelativePath,\n groupPath: leaf.groupPathDot,\n missingMiddlewareKeys: missingMiddleware,\n });\n }\n\n return RegistryItems.missingRequired(items, required, leaf.groupPathDot);\n});\n\nexport const withImplFiles = Effect.fnUntraced(function* <A, E, R>(\n relativePaths: ReadonlyArray<ImplModulePath>,\n use: (leaves: ReadonlyArray<LoadedLeafModule>) => Effect.Effect<A, E, R>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const pairs = yield* Effect.forEach(relativePaths, (implRelativePath) =>\n specPathForImpl(implRelativePath).pipe(\n Effect.map((specRelativePath) => ({\n implRelativePath,\n specRelativePath,\n })),\n ),\n );\n\n return yield* Bundler.withBatch(\n pairs.flatMap(({ implRelativePath, specRelativePath }) => [\n path.resolve(confectDirectory, implRelativePath),\n path.resolve(confectDirectory, specRelativePath),\n ]),\n Effect.gen(function* () {\n const leaves = yield* Effect.forEach(\n pairs,\n Effect.fnUntraced(function* ({ implRelativePath, specRelativePath }) {\n if (\n !(yield* fs.exists(path.join(confectDirectory, specRelativePath)))\n ) {\n return yield* new MissingSpecFileError({\n implPath: implRelativePath,\n expectedSpecPath: specRelativePath,\n });\n }\n if (\n !(yield* fs.exists(path.join(confectDirectory, implRelativePath)))\n ) {\n return yield* new MissingImplFileError({\n specPath: specRelativePath,\n expectedImplPath: implRelativePath,\n });\n }\n const leaf = yield* loadSpec(yield* toLeafModule(specRelativePath));\n return leaf;\n }),\n { concurrency: VALIDATION_CONCURRENCY },\n );\n return yield* use(leaves);\n }),\n );\n});\n\nexport const validateImplFiles = Effect.fn(\"LeafModule.validateImplFiles\")(\n (relativePaths: ReadonlyArray<ImplModulePath>) =>\n withImplFiles(relativePaths, validateAllImpls),\n);\n\nexport const validateAllImpls = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LoadedLeafModule>,\n required: ReadonlyArray<{ readonly key: string }> = [],\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const implementationPaths = yield* Effect.forEach(\n leaves,\n ({ relativePath }) =>\n implPathForSpec(relativePath).pipe(\n Effect.map((implPath) => path.resolve(confectDirectory, implPath)),\n ),\n );\n const missing = (yield* Bundler.withBatch(\n implementationPaths,\n Effect.forEach(leaves, (leaf) => validateImpl(leaf, required), {\n concurrency: VALIDATION_CONCURRENCY,\n }),\n ))\n .flat()\n .sort((left, right) => left.functionName.localeCompare(right.functionName));\n if (missing.length > 0) {\n return yield* new RequiredMiddlewareError({ missing });\n }\n});\n\nexport const loadAll = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const specFiles = yield* discoverLeafSpecFiles;\n\n const results = yield* Bundler.withBatch(\n specFiles.map((relativePath) =>\n path.resolve(confectDirectory, relativePath),\n ),\n Effect.forEach(\n specFiles,\n Effect.fnUntraced(function* (specRelativePath: string) {\n const discovered = yield* toLeafModule(specRelativePath);\n const leaf = yield* loadSpec(discovered);\n\n const implRelativePath = yield* implPathForSpec(specRelativePath);\n const implAbsolutePath = path.join(confectDirectory, implRelativePath);\n if (!(yield* fs.exists(implAbsolutePath))) {\n return yield* new MissingImplFileError({\n specPath: specRelativePath,\n expectedImplPath: implRelativePath,\n });\n }\n\n return leaf;\n }),\n { concurrency: VALIDATION_CONCURRENCY },\n ),\n );\n\n yield* validateOrphanImpls(specFiles);\n\n return results;\n});\n\n/**\n * Walk leaf ancestors and fail with a {@link ParentChildNameCollisionError} when\n * a parent leaf declares a function or subgroup whose name matches a sibling\n * subdirectory spec's segment. Without this check the colliding descendant\n * would overwrite the parent's entry in the assembled `GroupSpec.groups` map at\n * runtime, surfacing as a confusing `Refs.make` error rather than a\n * codegen-time diagnostic.\n */\nconst validateOrphanImpls = Effect.fnUntraced(function* (\n specFiles: ReadonlyArray<string>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const implFiles = yield* discoverLeafImplFiles;\n const specPaths = HashSet.fromIterable(specFiles);\n\n yield* Effect.forEach(\n implFiles,\n Effect.fnUntraced(function* (implRelativePath: string) {\n const specRelativePath = yield* specPathForImpl(implRelativePath);\n if (HashSet.has(specPaths, specRelativePath)) {\n return;\n }\n\n const specAbsolutePath = path.join(confectDirectory, specRelativePath);\n if (!(yield* fs.exists(specAbsolutePath))) {\n return yield* new MissingSpecFileError({\n implPath: implRelativePath,\n expectedSpecPath: specRelativePath,\n });\n }\n }),\n );\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAgDA,MAAM,mBAAmB,MAAM,QAA0B;AAEzD,MAAM,yBAAyB;AAE/B,MAAa,cAAc;AAC3B,MAAa,cAAc;AAE3B,MAAM,mBAAmB,OAAO,WAAW,WACzC,cACA,YACA,UACA;CACA,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,EAAE,KAAK,MAAM,QAAQ,KAAK,MAAM,YAAY;CAClD,IAAI,QAAQ,SAAS,CAAC,KAAK,SAAS,WAAW,MAAM,GAAG,EAAa,CAAC,GACpE,OAAO;CAIT,MAAM,WAAW,GADJ,KAAK,M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OAAO,QACZ,WACA,OAAO,WAAW,WAAW,kBAA0B;EACrD,MAAM,mBAAmB,OAAO,gBAAgB,gBAAgB;EAChE,IAAI,QAAQ,IAAI,WAAW,gBAAgB,GACzC;EAGF,MAAM,mBAAmB,KAAK,KAAK,kBAAkB,gBAAgB;EACrE,IAAI,EAAE,OAAO,GAAG,OAAO,gBAAgB,IACrC,OAAO,OAAO,IAAI,qBAAqB;GACrC,UAAU;GACV,kBAAkB;EACpB,CAAC;CAEL,CAAC,CACH;AACF,CAAC"}
1
+ {"version":3,"file":"LeafModule.mjs","names":["Bundler.importersOfPackage","Bundler.bundle","Bundler.directlyImports","Bundler.withBatch"],"sources":["../src/LeafModule.ts"],"sourcesContent":["import { GroupSpec, MiddlewareAttachment } from \"@confect/core\";\nimport { Registry, RegistryItems } from \"@confect/server\";\nimport * as GroupImpl from \"@confect/server/GroupImpl\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport type { Context } from \"effect\";\nimport type * as esbuild from \"esbuild\";\nimport * as Array from \"effect/Array\";\nimport * as Brand from \"effect/Brand\";\nimport * as Effect from \"effect/Effect\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as String from \"effect/String\";\nimport { BundleFailedError, fromBundlerError } from \"./BuildError.js\";\nimport * as Bundler from \"./Bundler.js\";\nimport {\n InvalidDeclarationError,\n MissingImplFileError,\n MissingSpecFileError,\n ImplMissingDefaultLayerError,\n ImplMissingFunctionsError,\n ImplMissingMiddlewareError,\n RequiredMiddlewareError,\n ImplMissingSpecImportError,\n ImplNotFinalizedError,\n InvalidMiddlewareAttachmentError,\n SpecImportsServerError,\n SpecMissingDefaultGroupSpecError,\n} from \"./CodegenError.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport { ImplModulePath } from \"./ImplModulePath.js\";\nimport {\n readDirectorySorted,\n removePathExtension,\n toPosixPath,\n} from \"./utils.js\";\n\nexport interface LeafModule {\n readonly relativePath: string;\n readonly pathSegments: readonly [string, ...string[]];\n readonly groupPathDot: string;\n readonly exportName: string;\n readonly specImportPath: string;\n}\n\nexport type LoadedLeafModule = LeafModule & {\n readonly spec: GroupSpec.AnyWithProps;\n} & Brand.Brand<\"@confect/cli/LoadedLeafModule\">;\n\nconst LoadedLeafModule = Brand.nominal<LoadedLeafModule>();\n\nconst VALIDATION_CONCURRENCY = 4;\n\nexport const SPEC_SUFFIX = \".spec.ts\";\nexport const IMPL_SUFFIX = \".impl.ts\";\n\nconst swapModuleSuffix = Effect.fnUntraced(function* (\n relativePath: string,\n fromSuffix: string,\n toSuffix: string,\n) {\n const path = yield* Path.Path;\n const { dir, name, ext } = path.parse(relativePath);\n if (ext !== \".ts\" || !name.endsWith(fromSuffix.slice(0, -\".ts\".length))) {\n return relativePath;\n }\n\n const stem = name.slice(0, -fromSuffix.slice(0, -\".ts\".length).length);\n const nextName = `${stem}${toSuffix.slice(0, -\".ts\".length)}`;\n return dir.length > 0\n ? path.join(dir, `${nextName}${ext}`)\n : `${nextName}${ext}`;\n});\n\nexport const isLeafSpecPath = (relativePath: string) =>\n relativePath.endsWith(SPEC_SUFFIX);\n\nexport const exportNameFromModulePath = Effect.fnUntraced(function* (\n relativePath: string,\n) {\n const path = yield* Path.Path;\n const { name, ext } = path.parse(relativePath);\n if (ext !== \".ts\") {\n return name;\n }\n return name.endsWith(\".spec\") ? name.slice(0, -\".spec\".length) : name;\n});\n\nexport const groupPathFromRelativeModulePath = Effect.fnUntraced(function* (\n relativePath: string,\n) {\n const path = yield* Path.Path;\n const { dir, name, ext } = path.parse(relativePath);\n const stem =\n ext === \".ts\" && name.endsWith(\".spec\")\n ? name.slice(0, -\".spec\".length)\n : name;\n const dirSegments = Array.filter(\n String.split(dir, path.sep),\n String.isNonEmpty,\n );\n const pathSegments = Array.append(dirSegments, stem) as [string, ...string[]];\n return {\n pathSegments,\n groupPathDot: Array.join(pathSegments, \".\"),\n };\n});\n\nexport const specImportPathFromGenerated = Effect.fnUntraced(function* (\n specRelativePath: string,\n) {\n const path = yield* Path.Path;\n const withoutExt = toPosixPath(\n path,\n yield* removePathExtension(specRelativePath),\n );\n return `../${withoutExt}.js`;\n});\n\nexport const specPathForImpl = (implRelativePath: string) =>\n swapModuleSuffix(implRelativePath, IMPL_SUFFIX, SPEC_SUFFIX);\n\nexport const implPathForSpec = (specRelativePath: string) =>\n swapModuleSuffix(specRelativePath, SPEC_SUFFIX, IMPL_SUFFIX);\n\nexport const registeredFunctionsRelativePath = Effect.fnUntraced(function* (\n leaf: LeafModule,\n) {\n const path = yield* Path.Path;\n return path.join(\"registeredFunctions\", ...leaf.pathSegments) + \".ts\";\n});\n\nexport const discoverLeafSpecFiles = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const excludedDirs = HashSet.make(\"_generated\", \"tables\", \"middleware\");\n const excludedFiles = HashSet.make(\"nodeSpec.ts\", \"spec.ts\");\n\n const allPaths = yield* readDirectorySorted(confectDirectory);\n\n return Array.filter(allPaths, (relativePath) => {\n if (!isLeafSpecPath(relativePath)) {\n return false;\n }\n\n if (HashSet.has(excludedFiles, relativePath)) {\n return false;\n }\n\n const segments = String.split(relativePath, path.sep);\n return !Array.some(segments, (segment) =>\n HashSet.has(excludedDirs, segment),\n );\n });\n});\n\nexport const discoverLeafImplFiles = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const excludedDirs = HashSet.make(\"_generated\", \"tables\", \"middleware\");\n\n const allPaths = yield* readDirectorySorted(confectDirectory);\n\n return Array.filter(\n Array.filterMap(allPaths, (relativePath) =>\n Schema.decodeResult(ImplModulePath)(relativePath),\n ),\n (relativePath) => {\n const segments = String.split(relativePath, path.sep);\n return !Array.some(segments, (segment) =>\n HashSet.has(excludedDirs, segment),\n );\n },\n );\n});\n\nexport const toLeafModule = Effect.fnUntraced(function* (\n specRelativePath: string,\n) {\n const exportName = yield* exportNameFromModulePath(specRelativePath);\n const { pathSegments, groupPathDot } =\n yield* groupPathFromRelativeModulePath(specRelativePath);\n const specImportPath = yield* specImportPathFromGenerated(specRelativePath);\n\n return {\n relativePath: specRelativePath,\n pathSegments,\n groupPathDot,\n exportName,\n specImportPath,\n } satisfies LeafModule;\n});\n\nconst absoluteModulePath = Effect.fnUntraced(function* (relativePath: string) {\n const confectDirectory = yield* ConfectDirectory.get;\n const path = yield* Path.Path;\n return path.resolve(confectDirectory, relativePath);\n});\n\n/**\n * Every `*.spec.ts` is reachable from `_generated/spec.ts`, which the client\n * imports through `_generated/refs.ts`—so a spec's whole import graph is\n * bundled into the browser whether or not the client calls those functions.\n * Server logic co-located with a declaration therefore ships to users,\n * silently.\n *\n * `@confect/server` is a sound proxy for \"server logic lives here\": an\n * implementation can't be written without `FunctionImpl`/`MiddlewareImpl`, both\n * of which live there. Table `Doc`/`Fields` schemas live in `@confect/core`, so\n * the documented `notes.Doc` pattern in a spec must not reach `@confect/server`\n * even through `tables/` or `_generated/`. The check runs over the spec\n * bundle's transitive inputs rather than the spec module alone, so it also\n * covers middleware declarations under `confect/middleware/` (which codegen\n * otherwise never visits) and any shared helper a spec pulls in—while only ever\n * flagging modules that genuinely reach the client.\n */\nconst validateClientSafety = Effect.fnUntraced(function* (\n leaf: LeafModule,\n bundled: Bundler.Bundled,\n) {\n const path = yield* Path.Path;\n const confectDirectory = path.resolve(yield* ConfectDirectory.get);\n\n const isCheckedUserModule = (absolutePath: string) => {\n const relative = path.relative(confectDirectory, absolutePath);\n return !relative.startsWith(\"..\") && !path.isAbsolute(relative);\n };\n\n const importers = Bundler.importersOfPackage(\n bundled,\n \"@confect/server\",\n isCheckedUserModule,\n );\n\n if (importers.length > 0) {\n return yield* new SpecImportsServerError({\n specPath: leaf.relativePath,\n importerPaths: Array.map(importers, (absolutePath) =>\n toPosixPath(path, path.relative(confectDirectory, absolutePath)),\n ),\n });\n }\n});\n\nconst validateReservedArguments = Effect.fnUntraced(function* (\n group: GroupSpec.AnyWithProps,\n specPath: string,\n groupPath: string,\n): Effect.fn.Return<void, InvalidDeclarationError> {\n for (const spec of Object.values(group.functions)) {\n const name = spec.reservedArgument;\n const provenance = spec.functionProvenance;\n if (\n name !== undefined &&\n provenance._tag === \"Confect\" &&\n Object.hasOwn(provenance.args.fields, name)\n ) {\n return yield* new InvalidDeclarationError({\n declarationPath: `confect/${specPath}`,\n reason: `${groupPath}:${spec.name} declares the argument \"${name}\", which its profile reserves. Rename the argument.`,\n });\n }\n }\n for (const [name, child] of Object.entries(group.groups)) {\n yield* validateReservedArguments(child, specPath, `${groupPath}/${name}`);\n }\n});\n\n/**\n * Validate that the leaf's spec file default-exports a `GroupSpec`, and that\n * nothing it reaches drags server code into the client (see\n * {@link validateClientSafety}). Returns the leaf paired with its validated\n * spec, so subsequent operations reuse that association without re-bundling.\n * The runtime is declared by the spec, not its file location.\n */\nexport const loadSpec = Effect.fn(\"LeafModule.loadSpec\")(function* (\n leaf: LeafModule,\n) {\n const absolutePath = yield* absoluteModulePath(leaf.relativePath);\n const bundled = yield* Bundler.bundle(absolutePath).pipe(\n Effect.mapError((error) => fromBundlerError(leaf.relativePath, error)),\n );\n\n const groupSpec = bundled.module.default;\n\n if (!GroupSpec.isGroupSpec(groupSpec)) {\n return yield* new SpecMissingDefaultGroupSpecError({\n specPath: leaf.relativePath,\n });\n }\n\n yield* validateClientSafety(leaf, bundled);\n yield* validateReservedArguments(\n groupSpec,\n leaf.relativePath,\n leaf.pathSegments.join(\"/\"),\n );\n\n yield* Effect.fromResult(GroupSpec.validateMiddleware(groupSpec)).pipe(\n Effect.mapError(\n (error) =>\n new InvalidMiddlewareAttachmentError({\n specPath: leaf.relativePath,\n message: MiddlewareAttachment.formatValidationError(error),\n }),\n ),\n );\n\n return LoadedLeafModule({\n ...leaf,\n spec: groupSpec,\n });\n});\n\n/**\n * Walk the built `Context` for a `Finalized` `GroupImpl` service value. The\n * lookup is value-shaped (via `GroupImpl.isFinalizedGroupImpl`) so we don't\n * need to know the group's path up front to construct a typed tag for it.\n */\nconst findFinalizedGroupImpl = <S>(\n context: Context.Context<S>,\n): Option.Option<GroupImpl.AnyFinalized> =>\n Array.findFirst(context.mapUnsafe.values(), GroupImpl.isFinalizedGroupImpl);\n\n/**\n * Build the impl layer with a fresh `Registry` so each validation is isolated\n * from prior validations' `FunctionImpl.make` writes. Retain its items to check\n * required middleware against actual function attachments.\n */\nconst buildImplLayer = Effect.fnUntraced(function* (\n implLayer: Layer.Layer<unknown>,\n) {\n const registry = Ref.makeUnsafe<RegistryItems.RegistryItems>({});\n const context = yield* Layer.build(\n implLayer as Layer.Layer<unknown, never, never>,\n ).pipe(Effect.provideService(Registry.Registry, registry));\n return { context, items: yield* Ref.get(registry) };\n}, Effect.scoped);\n\n/**\n * Validate that the leaf's sibling impl file imports the spec, default-exports\n * a finalized `GroupImpl` layer, and provides a `FunctionImpl` for every\n * function declared by the spec. Return uncovered middleware requirements for\n * the caller to report across groups.\n */\n/**\n * An implementation's unresolved import of a `confect/_generated` file is a\n * section file that no declared section writes: every declared section's file\n * is on disk before implementations validate. Say so, at the import.\n */\nconst nameUnwrittenSectionFiles = Effect.fnUntraced(function* (\n error: BundleFailedError,\n bundleDirectory: string,\n) {\n const path = yield* Path.Path;\n const generated = path.join(yield* ConfectDirectory.get, \"_generated\");\n const errors = (error.errors as ReadonlyArray<esbuild.Message>).map(\n (message) => {\n const specifier = /^Could not resolve \"(.+)\"$/.exec(message.text)?.[1];\n if (specifier === undefined || message.location === null) return message;\n const file = path.relative(\n generated,\n path.resolve(\n bundleDirectory,\n path.dirname(message.location.file),\n specifier,\n ),\n );\n if (file.startsWith(\"..\") || path.isAbsolute(file)) return message;\n const extension = path.extname(file);\n const name = toPosixPath(\n path,\n extension === \"\"\n ? `${file}.ts`\n : extension === \".js\"\n ? `${file.slice(0, -extension.length)}.ts`\n : file,\n );\n return Object.assign({}, message, {\n text: `No manifest section this backend declares writes _generated/${name}. Declare its section on App.make({ manifestSections }) in confect/app.ts.`,\n });\n },\n );\n return new BundleFailedError({ file: error.file, errors });\n});\n\nexport const validateImpl = Effect.fn(\"LeafModule.validateImpl\")(function* (\n leaf: LoadedLeafModule,\n required: ReadonlyArray<{ readonly key: string }> = [],\n) {\n const path = yield* Path.Path;\n const implRelativePath = yield* implPathForSpec(leaf.relativePath);\n const implAbsolutePath = yield* absoluteModulePath(implRelativePath);\n const specAbsolutePath = yield* absoluteModulePath(leaf.relativePath);\n\n const bundled = yield* Bundler.bundle(implAbsolutePath).pipe(\n Effect.mapError((error) => fromBundlerError(implRelativePath, error)),\n Effect.catchTag(\"BundleFailedError\", (error) =>\n Effect.flip(\n nameUnwrittenSectionFiles(error, path.dirname(implAbsolutePath)),\n ),\n ),\n );\n\n if (\n !(yield* Bundler.directlyImports(\n bundled,\n implAbsolutePath,\n specAbsolutePath,\n ))\n ) {\n return yield* new ImplMissingSpecImportError({\n implPath: implRelativePath,\n expectedSpecPath: leaf.relativePath,\n });\n }\n\n if (!Layer.isLayer(bundled.module.default)) {\n return yield* new ImplMissingDefaultLayerError({\n implPath: implRelativePath,\n });\n }\n\n const groupSpec = leaf.spec;\n const expectedFunctionNames = Object.keys(groupSpec.functions);\n\n const { context, items } = yield* buildImplLayer(\n bundled.module.default as Layer.Layer<unknown>,\n );\n const finalizedGroupImpl = yield* Option.match(\n findFinalizedGroupImpl(context),\n {\n onNone: () => new ImplNotFinalizedError({ implPath: implRelativePath }),\n onSome: Effect.succeed,\n },\n );\n\n const registeredSet = HashSet.fromIterable(\n finalizedGroupImpl.registeredFunctionNames,\n );\n const missing = expectedFunctionNames.filter(\n (name) => !HashSet.has(registeredSet, name),\n );\n\n if (missing.length > 0) {\n return yield* new ImplMissingFunctionsError({\n implPath: implRelativePath,\n groupPath: leaf.groupPathDot,\n missingFunctionNames: missing,\n });\n }\n\n const expectedMiddlewareKeys = Array.dedupe([\n ...(groupSpec.middlewareSpecs ?? []).map(\n (middlewareSpec) => middlewareSpec.key,\n ),\n ...Object.values(groupSpec.functions).flatMap((function_) =>\n (function_.middlewareSpecs ?? []).map(\n (middlewareSpec) => middlewareSpec.key,\n ),\n ),\n ]);\n const registeredMiddlewareKeys = HashSet.fromIterable(\n finalizedGroupImpl.registeredMiddlewareKeys ?? [],\n );\n const missingMiddleware = Array.filter(\n expectedMiddlewareKeys,\n (key) => !HashSet.has(registeredMiddlewareKeys, key),\n );\n\n if (missingMiddleware.length > 0) {\n return yield* new ImplMissingMiddlewareError({\n implPath: implRelativePath,\n groupPath: leaf.groupPathDot,\n missingMiddlewareKeys: missingMiddleware,\n });\n }\n\n return RegistryItems.missingRequired(items, required, leaf.groupPathDot);\n});\n\nexport const withImplFiles = Effect.fnUntraced(function* <A, E, R>(\n relativePaths: ReadonlyArray<ImplModulePath>,\n use: (leaves: ReadonlyArray<LoadedLeafModule>) => Effect.Effect<A, E, R>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const pairs = yield* Effect.forEach(relativePaths, (implRelativePath) =>\n specPathForImpl(implRelativePath).pipe(\n Effect.map((specRelativePath) => ({\n implRelativePath,\n specRelativePath,\n })),\n ),\n );\n\n return yield* Bundler.withBatch(\n pairs.flatMap(({ implRelativePath, specRelativePath }) => [\n path.resolve(confectDirectory, implRelativePath),\n path.resolve(confectDirectory, specRelativePath),\n ]),\n Effect.gen(function* () {\n const leaves = yield* Effect.forEach(\n pairs,\n Effect.fnUntraced(function* ({ implRelativePath, specRelativePath }) {\n if (\n !(yield* fs.exists(path.join(confectDirectory, specRelativePath)))\n ) {\n return yield* new MissingSpecFileError({\n implPath: implRelativePath,\n expectedSpecPath: specRelativePath,\n });\n }\n if (\n !(yield* fs.exists(path.join(confectDirectory, implRelativePath)))\n ) {\n return yield* new MissingImplFileError({\n specPath: specRelativePath,\n expectedImplPath: implRelativePath,\n });\n }\n const leaf = yield* loadSpec(yield* toLeafModule(specRelativePath));\n return leaf;\n }),\n { concurrency: VALIDATION_CONCURRENCY },\n );\n return yield* use(leaves);\n }),\n );\n});\n\nexport const validateImplFiles = Effect.fn(\"LeafModule.validateImplFiles\")(\n (relativePaths: ReadonlyArray<ImplModulePath>) =>\n withImplFiles(relativePaths, validateAllImpls),\n);\n\nexport const validateAllImpls = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LoadedLeafModule>,\n required: ReadonlyArray<{ readonly key: string }> = [],\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const implementationPaths = yield* Effect.forEach(\n leaves,\n ({ relativePath }) =>\n implPathForSpec(relativePath).pipe(\n Effect.map((implPath) => path.resolve(confectDirectory, implPath)),\n ),\n );\n const missing = (yield* Bundler.withBatch(\n implementationPaths,\n Effect.forEach(leaves, (leaf) => validateImpl(leaf, required), {\n concurrency: VALIDATION_CONCURRENCY,\n }),\n ))\n .flat()\n .sort((left, right) => left.functionName.localeCompare(right.functionName));\n if (missing.length > 0) {\n return yield* new RequiredMiddlewareError({ missing });\n }\n});\n\nexport const loadAll = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const specFiles = yield* discoverLeafSpecFiles;\n\n const results = yield* Bundler.withBatch(\n specFiles.map((relativePath) =>\n path.resolve(confectDirectory, relativePath),\n ),\n Effect.forEach(\n specFiles,\n Effect.fnUntraced(function* (specRelativePath: string) {\n const discovered = yield* toLeafModule(specRelativePath);\n const leaf = yield* loadSpec(discovered);\n\n const implRelativePath = yield* implPathForSpec(specRelativePath);\n const implAbsolutePath = path.join(confectDirectory, implRelativePath);\n if (!(yield* fs.exists(implAbsolutePath))) {\n return yield* new MissingImplFileError({\n specPath: specRelativePath,\n expectedImplPath: implRelativePath,\n });\n }\n\n return leaf;\n }),\n { concurrency: VALIDATION_CONCURRENCY },\n ),\n );\n\n yield* validateOrphanImpls(specFiles);\n\n return results;\n});\n\n/**\n * Walk leaf ancestors and fail with a {@link ParentChildNameCollisionError} when\n * a parent leaf declares a function or subgroup whose name matches a sibling\n * subdirectory spec's segment. Without this check the colliding descendant\n * would overwrite the parent's entry in the assembled `GroupSpec.groups` map at\n * runtime, surfacing as a confusing `Refs.make` error rather than a\n * codegen-time diagnostic.\n */\nconst validateOrphanImpls = Effect.fnUntraced(function* (\n specFiles: ReadonlyArray<string>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const implFiles = yield* discoverLeafImplFiles;\n const specPaths = HashSet.fromIterable(specFiles);\n\n yield* Effect.forEach(\n implFiles,\n Effect.fnUntraced(function* (implRelativePath: string) {\n const specRelativePath = yield* specPathForImpl(implRelativePath);\n if (HashSet.has(specPaths, specRelativePath)) {\n return;\n }\n\n const specAbsolutePath = path.join(confectDirectory, specRelativePath);\n if (!(yield* fs.exists(specAbsolutePath))) {\n return yield* new MissingSpecFileError({\n implPath: implRelativePath,\n expectedSpecPath: specRelativePath,\n });\n }\n }),\n );\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAoDA,MAAM,mBAAmB,MAAM,QAA0B;AAEzD,MAAM,yBAAyB;AAE/B,MAAa,cAAc;AAC3B,MAAa,cAAc;AAE3B,MAAM,mBAAmB,OAAO,WAAW,WACzC,cACA,YACA,UACA;CACA,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,EAAE,KAAK,MAAM,QAAQ,KAAK,MAAM,YAAY;CAClD,IAAI,QAAQ,SAAS,CAAC,KAAK,SAAS,WAAW,MAAM,GAAG,EAAa,CAAC,GACpE,OAAO;CAIT,MAAM,WAAW,GADJ,KAAK,MAAM,GAAG,CAAC,WAAW,MAAM,GAAG,EAAa,CAAC,CAAC,MACxC,IAAI,SAAS,MAAM,GAAG,EAAa;CAC1D,OAAO,IAAI,SAAS,IAChB,KAAK,KAAK,KAAK,GAAG,WAAW,KAAK,IA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;GACV,kBAAkB;EACpB,CAAC;CAEL,CAAC,CACH;AACF,CAAC"}
@@ -2,6 +2,7 @@ import { InvalidDeclarationError, InvalidManifestSectionError } from "./CodegenE
2
2
  import * as Result from "effect/Result";
3
3
  import * as Schema from "effect/Schema";
4
4
  import * as Predicate from "effect/Predicate";
5
+ import * as Order from "effect/Order";
5
6
  //#region src/ManifestSections.ts
6
7
  const reserved = new Set("name env http digest __proto__ constructor prototype".split(" "));
7
8
  const sections = (manifest) => Object.fromEntries(Object.entries(manifest).filter(([key]) => !reserved.has(key)));
@@ -60,7 +61,9 @@ const refuseSpecSections = (leaves) => visit(leaves, (spec, _, path, source) =>
60
61
  })) : Result.void);
61
62
  /**
62
63
  * One registry entry per declared section, each describing every registered
63
- * function. A backend with no functions keeps every section, with none.
64
+ * function in code-unit order of its path, so a section's data never depends on
65
+ * the order the leaves loaded in. A backend with no functions keeps every
66
+ * section, with none.
64
67
  */
65
68
  const collect = (entries, leaves) => Result.gen(function* () {
66
69
  const registry = new Map(entries.map(({ key, section }) => [key, {
@@ -71,24 +74,33 @@ const collect = (entries, leaves) => Result.gen(function* () {
71
74
  },
72
75
  sources: Object.create(null)
73
76
  }]));
74
- yield* visit(leaves, (spec, group, functionPath, source) => Result.gen(function* () {
75
- for (const [key, { section, data, sources }] of registry) {
76
- const invalid = (reason) => new InvalidDeclarationError({
77
- declarationPath: `confect/${source}`,
78
- reason: `Manifest section "${key}" (${functionPath}): ${reason}`
79
- });
80
- const description = yield* Result.try({
81
- try: () => section.describe({
82
- path: functionPath,
83
- spec,
84
- middleware: [...group.middlewareSpecs, ...spec.middlewareSpecs]
85
- }),
86
- catch: (cause) => invalid(String(cause))
87
- });
88
- data.functions[functionPath] = yield* Result.mapError(json(description), (reason) => invalid(`could not describe as JSON: ${reason}`));
89
- sources[functionPath] = source;
90
- }
91
- }));
77
+ const functions = [];
78
+ yield* visit(leaves, (spec, group, path, source) => {
79
+ functions.push({
80
+ spec,
81
+ group,
82
+ path,
83
+ source
84
+ });
85
+ return Result.void;
86
+ });
87
+ functions.sort(Order.mapInput(Order.String, ({ path }) => path));
88
+ for (const { spec, group, path, source } of functions) for (const [key, { section, data, sources }] of registry) {
89
+ const invalid = (reason) => new InvalidDeclarationError({
90
+ declarationPath: `confect/${source}`,
91
+ reason: `Manifest section "${key}" (${path}): ${reason}`
92
+ });
93
+ const description = yield* Result.try({
94
+ try: () => section.describe({
95
+ path,
96
+ spec,
97
+ middleware: [...group.middlewareSpecs, ...spec.middlewareSpecs]
98
+ }),
99
+ catch: (cause) => invalid(String(cause))
100
+ });
101
+ data.functions[path] = yield* Result.mapError(json(description), (reason) => invalid(`could not describe as JSON: ${reason}`));
102
+ sources[path] = source;
103
+ }
92
104
  return registry;
93
105
  });
94
106
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"ManifestSections.mjs","names":[],"sources":["../src/ManifestSections.ts"],"sourcesContent":["import type { FunctionSpec, GroupSpec, ManifestSection } from \"@confect/core\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport type { LoadedLeafModule } from \"./LeafModule.js\";\nimport {\n InvalidDeclarationError,\n InvalidManifestSectionError,\n} from \"./CodegenError.js\";\n\nconst reserved = new Set(\n \"name env http digest __proto__ constructor prototype\".split(\" \"),\n);\nexport const sections = (manifest: Readonly<Record<string, unknown>>) =>\n Object.fromEntries(\n Object.entries(manifest).filter(([key]) => !reserved.has(key)),\n );\n// Read only property descriptors, through static functions, so no getter,\n// `toJSON` or other method of the input runs before the check and nothing\n// `JSON.stringify` would call, skip or convert passes.\nconst nonJsonPath = (\n value: unknown,\n path = \"$\",\n ancestors: ReadonlyArray<object> = [],\n): string | undefined => {\n if (value === null || [\"string\", \"boolean\"].includes(typeof value))\n return undefined;\n if (typeof value === \"number\")\n return Number.isFinite(value) ? undefined : path;\n if (typeof value !== \"object\" || ancestors.includes(value)) return path;\n const isArray = Array.isArray(value);\n const prototypes = isArray ? [Array.prototype] : [Object.prototype, null];\n if (!prototypes.includes(Object.getPrototypeOf(value))) return path;\n const keys = isArray\n ? Array.from(\n { length: Object.getOwnPropertyDescriptor(value, \"length\")?.value },\n (_, index) => String(index),\n )\n : Reflect.ownKeys(value);\n for (const key of keys) {\n if (typeof key === \"symbol\") return path;\n const at = `${path}[${JSON.stringify(key)}]`;\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (\n key === \"__proto__\" ||\n !descriptor?.enumerable ||\n !(\"value\" in descriptor)\n )\n return at;\n const found = nonJsonPath(descriptor.value, at, [...ancestors, value]);\n if (found !== undefined) return found;\n }\n // Every index is an own data property by now, so any other key than `length`\n // is one `JSON.stringify` would drop or call.\n return isArray && Reflect.ownKeys(value).length !== keys.length + 1\n ? path\n : undefined;\n};\nconst json = (value: unknown): Result.Result<unknown, string> => {\n const path = nonJsonPath(value);\n return path === undefined\n ? Result.succeed(JSON.parse(JSON.stringify(value)))\n : Result.fail(`Expected JSON data at ${path}`);\n};\nexport type Registry = Map<\n string,\n {\n section: ManifestSection.Any;\n data: { format: number; functions: Record<string, unknown> };\n sources: Record<string, string>;\n }\n>;\nconst hasFormat = (format: number) =>\n Schema.is(Schema.Struct({ format: Schema.Literal(format) }));\ntype Summarized = {\n readonly section: ManifestSection.Any;\n readonly data: { readonly format: number };\n};\n\ntype Leaf = Pick<LoadedLeafModule, \"spec\" | \"pathSegments\" | \"relativePath\">;\n\nconst appDeclaration = (reason: string) =>\n new InvalidDeclarationError({ declarationPath: \"confect/app.ts\", reason });\n\n/**\n * Refuse a key `App.make` declares twice or that shadows one the manifest keeps\n * for itself.\n */\nexport const declared = (entries: ReadonlyArray<ManifestSection.Entry>) =>\n Result.gen(function* () {\n const seen = new Set<string>();\n for (const { key } of entries) {\n if (reserved.has(key))\n return yield* Result.fail(\n appDeclaration(`Manifest section \"${key}\" shadows a built-in key.`),\n );\n if (seen.has(key))\n return yield* Result.fail(\n appDeclaration(`Manifest section \"${key}\" is declared twice.`),\n );\n seen.add(key);\n }\n });\n\nconst visit = (\n leaves: ReadonlyArray<Leaf>,\n each: (\n spec: FunctionSpec.AnyWithProps,\n group: GroupSpec.AnyWithProps,\n path: string,\n source: string,\n ) => Result.Result<void, InvalidDeclarationError>,\n) =>\n Result.gen(function* () {\n const walk = (\n group: GroupSpec.AnyWithProps,\n path: string,\n source: string,\n ): Result.Result<void, InvalidDeclarationError> =>\n Result.gen(function* () {\n for (const spec of Object.values(group.functions))\n yield* each(spec, group, `${path}:${spec.name}`, source);\n for (const [name, child] of Object.entries(group.groups))\n yield* walk(child, `${path}/${name}`, source);\n });\n for (const leaf of leaves)\n yield* walk(leaf.spec, leaf.pathSegments.join(\"/\"), leaf.relativePath);\n });\n\n/**\n * Refuse a function spec that still carries `manifestSections`: codegen reads a\n * backend's sections only from `App.make`.\n */\nexport const refuseSpecSections = (leaves: ReadonlyArray<Leaf>) =>\n visit(leaves, (spec, _, path, source) =>\n Predicate.hasProperty(spec, \"manifestSections\")\n ? Result.fail(\n new InvalidDeclarationError({\n declarationPath: `confect/${source}`,\n reason: `${path} carries manifestSections, which codegen no longer reads from a function spec. Declare the backend's manifest sections once, on App.make({ manifestSections }) in confect/app.ts.`,\n }),\n )\n : Result.void,\n );\n\n/**\n * One registry entry per declared section, each describing every registered\n * function. A backend with no functions keeps every section, with none.\n */\nexport const collect = (\n entries: ReadonlyArray<ManifestSection.Entry>,\n leaves: ReadonlyArray<Leaf>,\n) =>\n Result.gen(function* () {\n const registry: Registry = new Map(\n entries.map(({ key, section }) => [\n key,\n {\n section,\n data: {\n format: section.format,\n functions: Object.create(null) as Record<string, unknown>,\n },\n sources: Object.create(null) as Record<string, string>,\n },\n ]),\n );\n yield* visit(leaves, (spec, group, functionPath, source) =>\n Result.gen(function* () {\n for (const [key, { section, data, sources }] of registry) {\n const invalid = (reason: string) =>\n new InvalidDeclarationError({\n declarationPath: `confect/${source}`,\n reason: `Manifest section \"${key}\" (${functionPath}): ${reason}`,\n });\n const description = yield* Result.try({\n try: () =>\n section.describe({\n path: functionPath,\n spec,\n middleware: [...group.middlewareSpecs, ...spec.middlewareSpecs],\n }),\n catch: (cause) => invalid(String(cause)),\n });\n data.functions[functionPath] = yield* Result.mapError(\n json(description),\n (reason) => invalid(`could not describe as JSON: ${reason}`),\n );\n sources[functionPath] = source;\n }\n }),\n );\n return registry;\n });\n\n/**\n * Replace the data of each section that has `summarize` with what it returns\n * from its matched modules, its functions' descriptions and their spec files.\n */\nexport const summarize = (\n registry: Registry,\n modules: ReadonlyMap<string, ManifestSection.GenerateInput[\"modules\"]>,\n) =>\n Result.gen(function* () {\n const summarized = new Map<string, Summarized>(registry);\n for (const [key, { section, data, sources }] of registry) {\n if (section.summarize === undefined) continue;\n const input = {\n modules: modules.get(key) ?? [],\n functions: data.functions,\n sources,\n };\n const invalid = (reason: string) =>\n new InvalidManifestSectionError({ sectionKey: key, reason });\n const summary = yield* Result.try({\n try: () => section.summarize?.(input),\n catch: (cause) => invalid(`summarize failed: ${String(cause)}`),\n });\n const parsed = yield* Result.mapError(json(summary), (reason) =>\n invalid(`could not summarize as JSON: ${reason}`),\n );\n if (!hasFormat(section.format)(parsed))\n return yield* Result.fail(\n invalid(`summarize must return data with format ${section.format}.`),\n );\n summarized.set(key, { section, data: parsed });\n }\n return summarized;\n });\n\nexport const check = (\n registry: ReadonlyMap<string, Summarized>,\n previous: Readonly<Record<string, unknown>>,\n) => {\n const errors: InvalidManifestSectionError[] = [];\n const notes: string[] = [];\n for (const [key, { section, data }] of registry) {\n try {\n const checked = section.check?.(data, previous[key]);\n if (checked === undefined) continue;\n notes.push(...checked.notes);\n if (checked.errors.length > 0)\n errors.push(\n new InvalidManifestSectionError({\n sectionKey: key,\n reason: [...new Set(checked.errors)].join(\"\\n\"),\n }),\n );\n } catch (cause) {\n errors.push(\n new InvalidManifestSectionError({\n sectionKey: key,\n reason: `check failed: ${String(cause)}`,\n }),\n );\n }\n }\n return { errors, notes };\n};\n"],"mappings":";;;;;AAUA,MAAM,WAAW,I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ACF;EACA,MAAM,WAAW,WACf,IAAI,4BAA4B;GAAE,YAAY;GAAK;EAAO,CAAC;EAC7D,MAAM,UAAU,OAAO,OAAO,IAAI;GAChC,WAAW,QAAQ,YAAY,KAAK;GACpC,QAAQ,UAAU,QAAQ,qBAAqB,OAAO,KAAK,GAAG;EAChE,CAAC;EACD,MAAM,SAAS,OAAO,OAAO,SAAS,KAAK,OAAO,IAAI,WACpD,QAAQ,gCAAgC,QAAQ,CAClD;EACA,IAAI,CAAC,UAAU,QAAQ,MAAM,CAAC,CAAC,MAAM,GACnC,OAAO,OAAO,OAAO,KACnB,QAAQ,0CAA0C,QAAQ,OAAO,EAAE,CACrE;EACF,WAAW,IAAI,KAAK;GAAE;GAAS,MAAM;EAAO,CAAC;CAC/C;CACA,OAAO;AACT,CAAC;AAEH,MAAa,SACX,UACA,aACG;CACH,MAAM,SAAwC,CAAC;CAC/C,MAAM,QAAkB,CAAC;CACzB,KAAK,MAAM,CAAC,KAAK,EAAE,SAAS,WAAW,UACrC,IAAI;EACF,MAAM,UAAU,QAAQ,QAAQ,MAAM,SAAS,IAAI;EACnD,IAAI,YAAY,KAAA,GAAW;EAC3B,MAAM,KAAK,GAAG,QAAQ,KAAK;EAC3B,IAAI,QAAQ,OAAO,SAAS,GAC1B,OAAO,KACL,IAAI,4BAA4B;GAC9B,YAAY;GACZ,QAAQ,CAAC,GAAG,IAAI,IAAI,QAAQ,MAAM,CAAC,CAAC,CAAC,KAAK,IAAI;EAChD,CAAC,CACH;CACJ,SAAS,OAAO;EACd,OAAO,KACL,IAAI,4BAA4B;GAC9B,YAAY;GACZ,QAAQ,iBAAiB,OAAO,KAAK;EACvC,CAAC,CACH;CACF;CAEF,OAAO;EAAE;EAAQ;CAAM;AACzB"}
1
+ {"version":3,"file":"ManifestSections.mjs","names":[],"sources":["../src/ManifestSections.ts"],"sourcesContent":["import type { FunctionSpec, GroupSpec, ManifestSection } from \"@confect/core\";\nimport * as Order from \"effect/Order\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport type { LoadedLeafModule } from \"./LeafModule.js\";\nimport {\n InvalidDeclarationError,\n InvalidManifestSectionError,\n} from \"./CodegenError.js\";\n\nconst reserved = new Set(\n \"name env http digest __proto__ constructor prototype\".split(\" \"),\n);\nexport const sections = (manifest: Readonly<Record<string, unknown>>) =>\n Object.fromEntries(\n Object.entries(manifest).filter(([key]) => !reserved.has(key)),\n );\n// Read only property descriptors, through static functions, so no getter,\n// `toJSON` or other method of the input runs before the check and nothing\n// `JSON.stringify` would call, skip or convert passes.\nconst nonJsonPath = (\n value: unknown,\n path = \"$\",\n ancestors: ReadonlyArray<object> = [],\n): string | undefined => {\n if (value === null || [\"string\", \"boolean\"].includes(typeof value))\n return undefined;\n if (typeof value === \"number\")\n return Number.isFinite(value) ? undefined : path;\n if (typeof value !== \"object\" || ancestors.includes(value)) return path;\n const isArray = Array.isArray(value);\n const prototypes = isArray ? [Array.prototype] : [Object.prototype, null];\n if (!prototypes.includes(Object.getPrototypeOf(value))) return path;\n const keys = isArray\n ? Array.from(\n { length: Object.getOwnPropertyDescriptor(value, \"length\")?.value },\n (_, index) => String(index),\n )\n : Reflect.ownKeys(value);\n for (const key of keys) {\n if (typeof key === \"symbol\") return path;\n const at = `${path}[${JSON.stringify(key)}]`;\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (\n key === \"__proto__\" ||\n !descriptor?.enumerable ||\n !(\"value\" in descriptor)\n )\n return at;\n const found = nonJsonPath(descriptor.value, at, [...ancestors, value]);\n if (found !== undefined) return found;\n }\n // Every index is an own data property by now, so any other key than `length`\n // is one `JSON.stringify` would drop or call.\n return isArray && Reflect.ownKeys(value).length !== keys.length + 1\n ? path\n : undefined;\n};\nconst json = (value: unknown): Result.Result<unknown, string> => {\n const path = nonJsonPath(value);\n return path === undefined\n ? Result.succeed(JSON.parse(JSON.stringify(value)))\n : Result.fail(`Expected JSON data at ${path}`);\n};\nexport type Registry = Map<\n string,\n {\n section: ManifestSection.Any;\n data: { format: number; functions: Record<string, unknown> };\n sources: Record<string, string>;\n }\n>;\nconst hasFormat = (format: number) =>\n Schema.is(Schema.Struct({ format: Schema.Literal(format) }));\ntype Summarized = {\n readonly section: ManifestSection.Any;\n readonly data: { readonly format: number };\n};\n\ntype Leaf = Pick<LoadedLeafModule, \"spec\" | \"pathSegments\" | \"relativePath\">;\n\nconst appDeclaration = (reason: string) =>\n new InvalidDeclarationError({ declarationPath: \"confect/app.ts\", reason });\n\n/**\n * Refuse a key `App.make` declares twice or that shadows one the manifest keeps\n * for itself.\n */\nexport const declared = (entries: ReadonlyArray<ManifestSection.Entry>) =>\n Result.gen(function* () {\n const seen = new Set<string>();\n for (const { key } of entries) {\n if (reserved.has(key))\n return yield* Result.fail(\n appDeclaration(`Manifest section \"${key}\" shadows a built-in key.`),\n );\n if (seen.has(key))\n return yield* Result.fail(\n appDeclaration(`Manifest section \"${key}\" is declared twice.`),\n );\n seen.add(key);\n }\n });\n\nconst visit = (\n leaves: ReadonlyArray<Leaf>,\n each: (\n spec: FunctionSpec.AnyWithProps,\n group: GroupSpec.AnyWithProps,\n path: string,\n source: string,\n ) => Result.Result<void, InvalidDeclarationError>,\n) =>\n Result.gen(function* () {\n const walk = (\n group: GroupSpec.AnyWithProps,\n path: string,\n source: string,\n ): Result.Result<void, InvalidDeclarationError> =>\n Result.gen(function* () {\n for (const spec of Object.values(group.functions))\n yield* each(spec, group, `${path}:${spec.name}`, source);\n for (const [name, child] of Object.entries(group.groups))\n yield* walk(child, `${path}/${name}`, source);\n });\n for (const leaf of leaves)\n yield* walk(leaf.spec, leaf.pathSegments.join(\"/\"), leaf.relativePath);\n });\n\n/**\n * Refuse a function spec that still carries `manifestSections`: codegen reads a\n * backend's sections only from `App.make`.\n */\nexport const refuseSpecSections = (leaves: ReadonlyArray<Leaf>) =>\n visit(leaves, (spec, _, path, source) =>\n Predicate.hasProperty(spec, \"manifestSections\")\n ? Result.fail(\n new InvalidDeclarationError({\n declarationPath: `confect/${source}`,\n reason: `${path} carries manifestSections, which codegen no longer reads from a function spec. Declare the backend's manifest sections once, on App.make({ manifestSections }) in confect/app.ts.`,\n }),\n )\n : Result.void,\n );\n\n/**\n * One registry entry per declared section, each describing every registered\n * function in code-unit order of its path, so a section's data never depends on\n * the order the leaves loaded in. A backend with no functions keeps every\n * section, with none.\n */\nexport const collect = (\n entries: ReadonlyArray<ManifestSection.Entry>,\n leaves: ReadonlyArray<Leaf>,\n) =>\n Result.gen(function* () {\n const registry: Registry = new Map(\n entries.map(({ key, section }) => [\n key,\n {\n section,\n data: {\n format: section.format,\n functions: Object.create(null) as Record<string, unknown>,\n },\n sources: Object.create(null) as Record<string, string>,\n },\n ]),\n );\n const functions: Array<{\n spec: FunctionSpec.AnyWithProps;\n group: GroupSpec.AnyWithProps;\n path: string;\n source: string;\n }> = [];\n yield* visit(leaves, (spec, group, path, source) => {\n functions.push({ spec, group, path, source });\n return Result.void;\n });\n functions.sort(Order.mapInput(Order.String, ({ path }) => path));\n for (const { spec, group, path, source } of functions) {\n for (const [key, { section, data, sources }] of registry) {\n const invalid = (reason: string) =>\n new InvalidDeclarationError({\n declarationPath: `confect/${source}`,\n reason: `Manifest section \"${key}\" (${path}): ${reason}`,\n });\n const description = yield* Result.try({\n try: () =>\n section.describe({\n path,\n spec,\n middleware: [...group.middlewareSpecs, ...spec.middlewareSpecs],\n }),\n catch: (cause) => invalid(String(cause)),\n });\n data.functions[path] = yield* Result.mapError(\n json(description),\n (reason) => invalid(`could not describe as JSON: ${reason}`),\n );\n sources[path] = source;\n }\n }\n return registry;\n });\n\n/**\n * Replace the data of each section that has `summarize` with what it returns\n * from its matched modules, its functions' descriptions and their spec files.\n */\nexport const summarize = (\n registry: Registry,\n modules: ReadonlyMap<string, ManifestSection.GenerateInput[\"modules\"]>,\n) =>\n Result.gen(function* () {\n const summarized = new Map<string, Summarized>(registry);\n for (const [key, { section, data, sources }] of registry) {\n if (section.summarize === undefined) continue;\n const input = {\n modules: modules.get(key) ?? [],\n functions: data.functions,\n sources,\n };\n const invalid = (reason: string) =>\n new InvalidManifestSectionError({ sectionKey: key, reason });\n const summary = yield* Result.try({\n try: () => section.summarize?.(input),\n catch: (cause) => invalid(`summarize failed: ${String(cause)}`),\n });\n const parsed = yield* Result.mapError(json(summary), (reason) =>\n invalid(`could not summarize as JSON: ${reason}`),\n );\n if (!hasFormat(section.format)(parsed))\n return yield* Result.fail(\n invalid(`summarize must return data with format ${section.format}.`),\n );\n summarized.set(key, { section, data: parsed });\n }\n return summarized;\n });\n\nexport const check = (\n registry: ReadonlyMap<string, Summarized>,\n previous: Readonly<Record<string, unknown>>,\n) => {\n const errors: InvalidManifestSectionError[] = [];\n const notes: string[] = [];\n for (const [key, { section, data }] of registry) {\n try {\n const checked = section.check?.(data, previous[key]);\n if (checked === undefined) continue;\n notes.push(...checked.notes);\n if (checked.errors.length > 0)\n errors.push(\n new InvalidManifestSectionError({\n sectionKey: key,\n reason: [...new Set(checked.errors)].join(\"\\n\"),\n }),\n );\n } catch (cause) {\n errors.push(\n new InvalidManifestSectionError({\n sectionKey: key,\n reason: `check failed: ${String(cause)}`,\n }),\n );\n }\n }\n return { errors, notes };\n};\n"],"mappings":";;;;;;AAWA,MAAM,WAAW,IAAI,IACnB,uDAAuD,MAAM,GAAG,CAClE;AACA,MAAa,YAAY,aACvB,OAAO,YACL,OAAO,QAAQ,QAAQ,CAAC,CAAC,QAAQ,CAAC,SAAS,CAAC,SAAS,IAAI,GAAG,CAAC,CAC/D;AAIF,MAAM,eACJ,OACA,OAAO,KACP,YAAmC,CAAC,MACb;CACvB,IAAI,UAAU,QAAQ,CAAC,UAAU,SAAS,CAAC,CAAC,SAAS,OAAO,KAAK,GAC/D,OAAO,KAAA;CACT,IAAI,OAAO,UAAU,UACnB,OAAO,OAAO,SAAS,KAAK,IAAI,KAAA,IAAY;CAC9C,IAAI,OAAO,UAAU,YAAY,UAAU,SAAS,KAAK,GAAG,OAA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I,WACpD,QAAQ,gCAAgC,QAAQ,CAClD;EACA,IAAI,CAAC,UAAU,QAAQ,MAAM,CAAC,CAAC,MAAM,GACnC,OAAO,OAAO,OAAO,KACnB,QAAQ,0CAA0C,QAAQ,OAAO,EAAE,CACrE;EACF,WAAW,IAAI,KAAK;GAAE;GAAS,MAAM;EAAO,CAAC;CAC/C;CACA,OAAO;AACT,CAAC;AAEH,MAAa,SACX,UACA,aACG;CACH,MAAM,SAAwC,CAAC;CAC/C,MAAM,QAAkB,CAAC;CACzB,KAAK,MAAM,CAAC,KAAK,EAAE,SAAS,WAAW,UACrC,IAAI;EACF,MAAM,UAAU,QAAQ,QAAQ,MAAM,SAAS,IAAI;EACnD,IAAI,YAAY,KAAA,GAAW;EAC3B,MAAM,KAAK,GAAG,QAAQ,KAAK;EAC3B,IAAI,QAAQ,OAAO,SAAS,GAC1B,OAAO,KACL,IAAI,4BAA4B;GAC9B,YAAY;GACZ,QAAQ,CAAC,GAAG,IAAI,IAAI,QAAQ,MAAM,CAAC,CAAC,CAAC,KAAK,IAAI;EAChD,CAAC,CACH;CACJ,SAAS,OAAO;EACd,OAAO,KACL,IAAI,4BAA4B;GAC9B,YAAY;GACZ,QAAQ,iBAAiB,OAAO,KAAK;EACvC,CAAC,CACH;CACF;CAEF,OAAO;EAAE;EAAQ;CAAM;AACzB"}
@@ -2,6 +2,7 @@ import { fromBundlerError } from "./BuildError.mjs";
2
2
  import { bundle, withBatch } from "./Bundler.mjs";
3
3
  import { DuplicateTableNameError, InvalidTableDefaultExportError, InvalidTableFilenameError } from "./CodegenError.mjs";
4
4
  import { ConfectDirectory } from "./ConfectDirectory.mjs";
5
+ import { readDirectorySorted } from "./utils.mjs";
5
6
  import * as Effect from "effect/Effect";
6
7
  import { Identifier } from "@confect/core";
7
8
  import * as FileSystem from "effect/FileSystem";
@@ -22,7 +23,7 @@ const discoverTableFiles = Effect.gen(function* () {
22
23
  const confectDirectory = yield* ConfectDirectory.get;
23
24
  const tablesDirectory = path.join(confectDirectory, TABLES_DIRNAME);
24
25
  if (!(yield* fs.exists(tablesDirectory))) return [];
25
- const allPaths = yield* fs.readDirectory(tablesDirectory, { recursive: true });
26
+ const allPaths = yield* readDirectorySorted(tablesDirectory);
26
27
  return pipe(allPaths, Array.filter((p) => p.endsWith(".ts") && !p.endsWith(".test.ts")), Array.map((p) => path.join(TABLES_DIRNAME, p)));
27
28
  });
28
29
  const byTableName = Order.mapInput(Order.String, (tableModule) => tableModule.tableName);
@@ -1 +1 @@
1
- {"version":3,"file":"TableModule.mjs","names":["Bundler.bundle","Bundler.withBatch"],"sources":["../src/TableModule.ts"],"sourcesContent":["import { Identifier } from \"@confect/core\";\nimport * as Table from \"@confect/core/Table\";\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 Effect from \"effect/Effect\";\nimport * as Order from \"effect/Order\";\nimport { fromBundlerError } from \"./BuildError.js\";\nimport * as Bundler from \"./Bundler.js\";\nimport {\n DuplicateTableNameError,\n InvalidTableDefaultExportError,\n InvalidTableFilenameError,\n} from \"./CodegenError.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\n\nexport const TABLES_DIRNAME = \"tables\";\n\n/**\n * Discovered metadata for a single user-authored table module under\n * `confect/tables/`.\n *\n * - `relativePath`—path from `confect/` to the file (e.g. `tables/notes.ts`).\n * - `tableName`—the file basename (e.g. `notes`). This is also the import binding\n * used in generated files, and the table name surfaced to Convex.\n */\nexport interface TableModule {\n readonly relativePath: string;\n readonly tableName: string;\n}\n\nconst tableNameFromRelativePath = Effect.fnUntraced(function* (\n relativePath: string,\n) {\n const path = yield* Path.Path;\n const { name } = path.parse(relativePath);\n return name;\n});\n\nexport const discoverTableFiles = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const tablesDirectory = path.join(confectDirectory, TABLES_DIRNAME);\n\n if (!(yield* fs.exists(tablesDirectory))) {\n return [] as ReadonlyArray<string>;\n }\n\n const allPaths = yield* fs.readDirectory(tablesDirectory, {\n recursive: true,\n });\n\n return pipe(\n allPaths,\n Array.filter((p) => p.endsWith(\".ts\") && !p.endsWith(\".test.ts\")),\n Array.map((p) => path.join(TABLES_DIRNAME, p)),\n );\n});\n\nconst byTableName = Order.mapInput(\n Order.String,\n (tableModule: TableModule) => tableModule.tableName,\n);\n\n/**\n * Discover every `confect/tables/**\\/*.ts` module by listing the directory.\n * Validates that each filename is a legal table identifier—the table name is\n * derived from the file basename, so the filename must be a valid JavaScript\n * identifier with no leading underscore (Convex reserves `_<name>` for system\n * tables).\n *\n * This step does _not_ bundle the table modules. It runs early in the codegen\n * pipeline so the `_generated/id.ts` constructor can be emitted _before_ any\n * user-authored table is bundled (those modules import from `_generated/id.ts`\n * for cross-table refs).\n *\n * A missing `confect/tables/` directory is allowed and produces an empty list.\n *\n * Fails with {@link InvalidTableFilenameError} if any filename is not a valid\n * table identifier, or {@link DuplicateTableNameError} if two files resolve to\n * the same table name (the directory is scanned recursively but names are\n * derived from the basename alone, so `tables/a/notes.ts` and\n * `tables/b/notes.ts` would collide).\n */\nexport const discover = Effect.gen(function* () {\n const relativePaths = yield* discoverTableFiles;\n\n const tableModules = yield* Effect.forEach(\n relativePaths,\n Effect.fnUntraced(function* (relativePath: string) {\n const tableName = yield* tableNameFromRelativePath(relativePath);\n yield* Effect.try({\n try: () => Identifier.validateConfectTableIdentifier(tableName),\n catch: (e) =>\n new InvalidTableFilenameError({\n tablePath: relativePath,\n reason: e instanceof Error ? e.message : String(e),\n }),\n });\n return { relativePath, tableName } satisfies TableModule;\n }),\n { concurrency: \"unbounded\" },\n );\n\n const sorted = pipe(tableModules, Array.sortBy(byTableName));\n\n const collisions = Object.entries(\n Array.groupBy(sorted, (tableModule) => tableModule.tableName),\n )\n .filter(([, group]) => group.length > 1)\n .map(([tableName, group]) => ({\n tableName,\n tablePaths: Array.map(group, (tableModule) => tableModule.relativePath),\n }));\n\n if (collisions.length > 0) {\n return yield* new DuplicateTableNameError({ collisions });\n }\n\n return sorted;\n});\n\n/**\n * Bundle every discovered table module and verify that its default export is an\n * {@link Table.UnnamedTable} (the result of `Table.make(...)` before a name has\n * been bound). Fails with {@link InvalidTableDefaultExportError} if any\n * module's default export is missing or has the wrong shape.\n *\n * Must run _after_ `_generated/id.ts` has been emitted, because user-authored\n * table modules typically `import { Id } from \"../_generated/id\"` for\n * cross-table references.\n */\nexport const validate = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const validateRelativePath = Effect.fnUntraced(function* (\n relativePath: string,\n ) {\n const absolutePath = path.resolve(confectDirectory, relativePath);\n const { module } = yield* Bundler.bundle(absolutePath).pipe(\n Effect.mapError((error) => fromBundlerError(relativePath, error)),\n );\n\n if (!Table.isUnnamedTable(module.default)) {\n return yield* new InvalidTableDefaultExportError({\n tablePath: relativePath,\n });\n }\n });\n\n const relativePaths = tableModules.map(({ relativePath }) => relativePath);\n yield* Bundler.withBatch(\n relativePaths.map((relativePath) =>\n path.resolve(confectDirectory, relativePath),\n ),\n Effect.forEach(relativePaths, validateRelativePath, { concurrency: 4 }),\n );\n});\n"],"mappings":";;;;;;;;;;;;;AAiBA,MAAa,iBAAiB;AAe9B,MAAM,4BAA4B,OAAO,WAAW,WAClD,cACA;CAEA,MAAM,EAAE,UAAS,OADG,KAAK,KAAA,CACH,MAAM,YAAY;CACxC,OAAO;AACT,CAAC;AAED,MAAa,qBAAqB,OAAO,IAAI,aAAa;CACxD,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,mBAAmB,OAAO,iBAAiB;CACjD,MAAM,kBAAkB,KAAK,KAAK,kBAAkB,cAAc;CAElE,IAAI,EAAE,OAAO,GAAG,OAAO,eAAe,IACpC,OAAO,CAAC;CAGV,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AiB;CAEjD,MAAM,uBAAuB,OAAO,WAAW,WAC7C,cACA;EACA,MAAM,eAAe,KAAK,QAAQ,kBAAkB,YAAY;EAChE,MAAM,EAAE,WAAW,OAAOA,OAAe,YAAY,CAAC,CAAC,KACrD,OAAO,UAAU,UAAU,iBAAiB,cAAc,KAAK,CAAC,CAClE;EAEA,IAAI,CAAC,MAAM,eAAe,OAAO,OAAO,GACtC,OAAO,OAAO,IAAI,+BAA+B,EAC/C,WAAW,aACb,CAAC;CAEL,CAAC;CAED,MAAM,gBAAgB,aAAa,KAAK,EAAE,mBAAmB,YAAY;CACzE,OAAOC,UACL,cAAc,KAAK,iBACjB,KAAK,QAAQ,kBAAkB,YAAY,CAC7C,GACA,OAAO,QAAQ,eAAe,sBAAsB,EAAE,aAAa,EAAE,CAAC,CACxE;AACF,CAAC"}
1
+ {"version":3,"file":"TableModule.mjs","names":["Bundler.bundle","Bundler.withBatch"],"sources":["../src/TableModule.ts"],"sourcesContent":["import { Identifier } from \"@confect/core\";\nimport * as Table from \"@confect/core/Table\";\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 Effect from \"effect/Effect\";\nimport * as Order from \"effect/Order\";\nimport { fromBundlerError } from \"./BuildError.js\";\nimport * as Bundler from \"./Bundler.js\";\nimport {\n DuplicateTableNameError,\n InvalidTableDefaultExportError,\n InvalidTableFilenameError,\n} from \"./CodegenError.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport { readDirectorySorted } from \"./utils.js\";\n\nexport const TABLES_DIRNAME = \"tables\";\n\n/**\n * Discovered metadata for a single user-authored table module under\n * `confect/tables/`.\n *\n * - `relativePath`—path from `confect/` to the file (e.g. `tables/notes.ts`).\n * - `tableName`—the file basename (e.g. `notes`). This is also the import binding\n * used in generated files, and the table name surfaced to Convex.\n */\nexport interface TableModule {\n readonly relativePath: string;\n readonly tableName: string;\n}\n\nconst tableNameFromRelativePath = Effect.fnUntraced(function* (\n relativePath: string,\n) {\n const path = yield* Path.Path;\n const { name } = path.parse(relativePath);\n return name;\n});\n\nexport const discoverTableFiles = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const tablesDirectory = path.join(confectDirectory, TABLES_DIRNAME);\n\n if (!(yield* fs.exists(tablesDirectory))) {\n return [] as ReadonlyArray<string>;\n }\n\n const allPaths = yield* readDirectorySorted(tablesDirectory);\n\n return pipe(\n allPaths,\n Array.filter((p) => p.endsWith(\".ts\") && !p.endsWith(\".test.ts\")),\n Array.map((p) => path.join(TABLES_DIRNAME, p)),\n );\n});\n\nconst byTableName = Order.mapInput(\n Order.String,\n (tableModule: TableModule) => tableModule.tableName,\n);\n\n/**\n * Discover every `confect/tables/**\\/*.ts` module by listing the directory.\n * Validates that each filename is a legal table identifier—the table name is\n * derived from the file basename, so the filename must be a valid JavaScript\n * identifier with no leading underscore (Convex reserves `_<name>` for system\n * tables).\n *\n * This step does _not_ bundle the table modules. It runs early in the codegen\n * pipeline so the `_generated/id.ts` constructor can be emitted _before_ any\n * user-authored table is bundled (those modules import from `_generated/id.ts`\n * for cross-table refs).\n *\n * A missing `confect/tables/` directory is allowed and produces an empty list.\n *\n * Fails with {@link InvalidTableFilenameError} if any filename is not a valid\n * table identifier, or {@link DuplicateTableNameError} if two files resolve to\n * the same table name (the directory is scanned recursively but names are\n * derived from the basename alone, so `tables/a/notes.ts` and\n * `tables/b/notes.ts` would collide).\n */\nexport const discover = Effect.gen(function* () {\n const relativePaths = yield* discoverTableFiles;\n\n const tableModules = yield* Effect.forEach(\n relativePaths,\n Effect.fnUntraced(function* (relativePath: string) {\n const tableName = yield* tableNameFromRelativePath(relativePath);\n yield* Effect.try({\n try: () => Identifier.validateConfectTableIdentifier(tableName),\n catch: (e) =>\n new InvalidTableFilenameError({\n tablePath: relativePath,\n reason: e instanceof Error ? e.message : String(e),\n }),\n });\n return { relativePath, tableName } satisfies TableModule;\n }),\n { concurrency: \"unbounded\" },\n );\n\n const sorted = pipe(tableModules, Array.sortBy(byTableName));\n\n const collisions = Object.entries(\n Array.groupBy(sorted, (tableModule) => tableModule.tableName),\n )\n .filter(([, group]) => group.length > 1)\n .map(([tableName, group]) => ({\n tableName,\n tablePaths: Array.map(group, (tableModule) => tableModule.relativePath),\n }));\n\n if (collisions.length > 0) {\n return yield* new DuplicateTableNameError({ collisions });\n }\n\n return sorted;\n});\n\n/**\n * Bundle every discovered table module and verify that its default export is an\n * {@link Table.UnnamedTable} (the result of `Table.make(...)` before a name has\n * been bound). Fails with {@link InvalidTableDefaultExportError} if any\n * module's default export is missing or has the wrong shape.\n *\n * Must run _after_ `_generated/id.ts` has been emitted, because user-authored\n * table modules typically `import { Id } from \"../_generated/id\"` for\n * cross-table references.\n */\nexport const validate = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const validateRelativePath = Effect.fnUntraced(function* (\n relativePath: string,\n ) {\n const absolutePath = path.resolve(confectDirectory, relativePath);\n const { module } = yield* Bundler.bundle(absolutePath).pipe(\n Effect.mapError((error) => fromBundlerError(relativePath, error)),\n );\n\n if (!Table.isUnnamedTable(module.default)) {\n return yield* new InvalidTableDefaultExportError({\n tablePath: relativePath,\n });\n }\n });\n\n const relativePaths = tableModules.map(({ relativePath }) => relativePath);\n yield* Bundler.withBatch(\n relativePaths.map((relativePath) =>\n path.resolve(confectDirectory, relativePath),\n ),\n Effect.forEach(relativePaths, validateRelativePath, { concurrency: 4 }),\n );\n});\n"],"mappings":";;;;;;;;;;;;;;AAkBA,MAAa,iBAAiB;AAe9B,MAAM,4BAA4B,OAAO,WAAW,WAClD,cACA;CAEA,MAAM,EAAE,UAAS,OADG,KAAK,KAAA,CACH,MAAM,YAAY;CACxC,OAAO;AACT,CAAC;AAED,MAAa,qBAAqB,OAAO,I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,SAAS,GACtB,OAAO,OAAO,IAAI,wBAAwB,EAAE,WAAW,CAAC;CAG1D,OAAO;AACT,CAAC;;;;;;;;;;;AAYD,MAAa,WAAW,OAAO,WAAW,WACxC,cACA;CACA,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,mBAAmB,OAAO,iBAAiB;CAEjD,MAAM,uBAAuB,OAAO,WAAW,WAC7C,cACA;EACA,MAAM,eAAe,KAAK,QAAQ,kBAAkB,YAAY;EAChE,MAAM,EAAE,WAAW,OAAOA,OAAe,YAAY,CAAC,CAAC,KACrD,OAAO,UAAU,UAAU,iBAAiB,cAAc,KAAK,CAAC,CAClE;EAEA,IAAI,CAAC,MAAM,eAAe,OAAO,OAAO,GACtC,OAAO,OAAO,IAAI,+BAA+B,EAC/C,WAAW,aACb,CAAC;CAEL,CAAC;CAED,MAAM,gBAAgB,aAAa,KAAK,EAAE,mBAAmB,YAAY;CACzE,OAAOC,UACL,cAAc,KAAK,iBACjB,KAAK,QAAQ,kBAAkB,YAAY,CAC7C,GACA,OAAO,QAAQ,eAAe,sBAAsB,EAAE,aAAa,EAAE,CAAC,CACxE;AACF,CAAC"}
package/dist/utils.mjs CHANGED
@@ -9,6 +9,7 @@ import * as Array from "effect/Array";
9
9
  import { pipe } from "effect/Function";
10
10
  import * as Option from "effect/Option";
11
11
  import * as String from "effect/String";
12
+ import * as Order from "effect/Order";
12
13
  import * as DateTime from "effect/DateTime";
13
14
  //#region src/utils.ts
14
15
  const removePathExtension = Effect.fnUntraced(function* (pathStr) {
@@ -17,6 +18,18 @@ const removePathExtension = Effect.fnUntraced(function* (pathStr) {
17
18
  });
18
19
  const toPosixPath = (path, pathStr) => pipe(String.split(pathStr, path.sep), Array.join("/"));
19
20
  /**
21
+ * Every path under `directory`, relative to it, in code-unit order of its POSIX
22
+ * form. Node's recursive `readdir` walks in an order that differs across Node
23
+ * versions, and codegen writes what it discovers in that order, so reading
24
+ * through here keeps the output the same on every Node and on every platform.
25
+ * The paths keep the host's separator.
26
+ */
27
+ const readDirectorySorted = Effect.fnUntraced(function* (directory) {
28
+ const fs = yield* FileSystem.FileSystem;
29
+ const path = yield* Path.Path;
30
+ return Array.sort(yield* fs.readDirectory(directory, { recursive: true }), Order.mapInput(Order.String, (relativePath) => toPosixPath(path, relativePath)));
31
+ });
32
+ /**
20
33
  * Ensures a relative path is a valid ESM/TS module specifier (e.g. `spec` →
21
34
  * `./spec`).
22
35
  */
@@ -100,6 +113,6 @@ const generateHttp = generateOptionalFile("http.ts", "http.ts", (importPath) =>
100
113
  const generateCrons = generateOptionalFile("crons.ts", "crons.ts", (importPath) => crons({ cronsImportPath: importPath }));
101
114
  const generateAuthConfig = generateOptionalFile("auth.ts", "auth.config.ts", (importPath) => authConfig({ authImportPath: importPath }));
102
115
  //#endregion
103
- export { generateAuthConfig, generateCrons, generateHttp, removePathExtension, removePathIfExists, toModuleImportPath, toPosixPath, touchConvexSchema, writeFileString, writeFileStringAndLog };
116
+ export { generateAuthConfig, generateCrons, generateHttp, readDirectorySorted, removePathExtension, removePathIfExists, toModuleImportPath, toPosixPath, touchConvexSchema, writeFileString, writeFileStringAndLog };
104
117
 
105
118
  //# sourceMappingURL=utils.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.mjs","names":["templates.http","templates.crons","templates.authConfig"],"sources":["../src/utils.ts"],"sourcesContent":["import * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport type { PlatformError } from \"effect/PlatformError\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Option from \"effect/Option\";\nimport * as String from \"effect/String\";\nimport { logFileAdded, logFileModified } from \"./log.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport { ConvexDirectory } from \"./ConvexDirectory.js\";\nimport * as templates from \"./templates.js\";\n\nexport const removePathExtension = Effect.fnUntraced(function* (\n pathStr: string,\n) {\n const path = yield* Path.Path;\n\n return String.slice(0, -path.extname(pathStr).length)(pathStr);\n});\n\nexport const toPosixPath = (path: Path.Path, pathStr: string): string =>\n pipe(String.split(pathStr, path.sep), Array.join(\"/\"));\n\n/**\n * Ensures a relative path is a valid ESM/TS module specifier (e.g. `spec` →\n * `./spec`).\n */\nexport const toModuleImportPath = Effect.fnUntraced(function* (\n relativePath: string,\n) {\n const path = yield* Path.Path;\n const withoutExt = toPosixPath(\n path,\n yield* removePathExtension(relativePath),\n );\n return String.startsWith(\".\")(withoutExt)\n ? `${withoutExt}.js`\n : `./${withoutExt}.js`;\n});\n\nexport const writeFileStringAndLog = Effect.fnUntraced(function* (\n filePath: string,\n contents: string,\n) {\n const fs = yield* FileSystem.FileSystem;\n if (!(yield* fs.exists(filePath))) {\n yield* fs.writeFileString(filePath, contents);\n yield* logFileAdded(filePath);\n return;\n }\n const existing = yield* fs.readFileString(filePath);\n if (existing !== contents) {\n yield* fs.writeFileString(filePath, contents);\n yield* logFileModified(filePath);\n }\n});\n\nexport const findProjectRoot = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n\n const startDir = path.resolve(\".\");\n const root = path.parse(startDir).root;\n\n const directories = Array.unfold(startDir, (dir) =>\n dir === root\n ? Option.none()\n : Option.some([dir, path.dirname(dir)] as const),\n );\n\n const projectRoot = yield* Effect.findFirst(directories, (dir) =>\n fs.exists(path.join(dir, \"package.json\")),\n );\n\n return Option.getOrElse(projectRoot, () => startDir);\n});\n\nexport type WriteChange = \"Added\" | \"Modified\" | \"Unchanged\";\n\nexport const writeFileString = Effect.fnUntraced(function* (\n filePath: string,\n contents: string,\n): Effect.fn.Return<WriteChange, PlatformError, FileSystem.FileSystem> {\n const fs = yield* FileSystem.FileSystem;\n\n if (!(yield* fs.exists(filePath))) {\n yield* fs.writeFileString(filePath, contents);\n return \"Added\";\n }\n const existing = yield* fs.readFileString(filePath);\n if (existing !== contents) {\n yield* fs.writeFileString(filePath, contents);\n return \"Modified\";\n }\n return \"Unchanged\";\n});\n\nexport const removePathIfExists = Effect.fnUntraced(function* (\n filePath: string,\n): Effect.fn.Return<void, PlatformError, FileSystem.FileSystem> {\n const fs = yield* FileSystem.FileSystem;\n\n if (!(yield* fs.exists(filePath))) {\n return;\n }\n\n yield* fs\n .remove(filePath)\n .pipe(\n Effect.catchTag(\"PlatformError\", (error) =>\n error.reason._tag === \"NotFound\" ? Effect.void : Effect.fail(error),\n ),\n );\n});\n\n/**\n * Bump the mtime of `convex/schema.ts` so the Convex CLI's chokidar watcher\n * emits a `change` event after explicit codegen, bootstrap, or recovery.\n * Recovery can leave generated contents unchanged, so it needs an explicit\n * notification to release Convex from a previous error. Ordinary successful\n * watch updates rely on their source/output changes instead of invalidating a\n * Convex push that may already be processing those changes.\n */\nexport const touchConvexSchema = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n const schemaPath = path.join(convexDirectory, \"schema.ts\");\n\n if (!(yield* fs.exists(schemaPath))) {\n return;\n }\n\n const now = yield* DateTime.nowAsDate;\n yield* fs.utimes(schemaPath, now, now);\n});\n\nconst generateOptionalFile = Effect.fnUntraced(function* (\n confectFile: string,\n convexFile: string,\n generateContents: (importPath: string) => Effect.Effect<string>,\n) {\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\n const confectFilePath = path.join(confectDirectory, confectFile);\n\n if (!(yield* fs.exists(confectFilePath))) {\n return Option.none();\n }\n\n const convexFilePath = path.join(convexDirectory, convexFile);\n const relativeImportPath = path.relative(\n path.dirname(convexFilePath),\n confectFilePath,\n );\n const contents = yield* generateContents(\n yield* toModuleImportPath(relativeImportPath),\n );\n const change = yield* writeFileString(convexFilePath, contents);\n return Option.some({ change, convexFilePath });\n});\n\nexport const generateHttp = generateOptionalFile(\n \"http.ts\",\n \"http.ts\",\n (importPath) => templates.http({ httpImportPath: importPath }),\n);\n\nexport const generateCrons = generateOptionalFile(\n \"crons.ts\",\n \"crons.ts\",\n (importPath) => templates.crons({ cronsImportPath: importPath }),\n);\n\nexport const generateAuthConfig = generateOptionalFile(\n \"auth.ts\",\n \"auth.config.ts\",\n (importPath) => templates.authConfig({ authImportPath: importPath }),\n);\n"],"mappings":";;;;;;;;;;;;;AAcA,MAAa,sBAAsB,OAAO,WAAW,WACnD,SACA;CACA,MAAM,OAAO,OAAO,KAAK;CAEzB,OAAO,OAAO,MAAM,GAAG,CAAC,KAAK,QAAQ,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,OAAO;AAC/D,CAAC;AAED,MAAa,eAAe,MAAiB,YAC3C,KAAK,OAAO,MAAM,SAAS,KAAK,GAAG,GAAG,MAAM,KAAK,GAAG,CAAC;;;;;AAMvD,MAAa,qBAAqB,OAAO,WAAW,WAClD,cACA;CACA,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,aAAa,YACjB,MACA,OAAO,oBAAoB,YAAY,CACzC;CACA,OAAO,OAAO,WAAW,GAAG,CAAC,CAAC,UAAU,IACpC,GAAG,WAAW,OACd,KAAK,WAAW;AACtB,CAAC;AAED,MAAa,wBAAwB,OAAO,WAAW,WACrD,UACA,UACA;CACA,MAAM,KAAK,OAAO,WAAW;CAC7B,IAAI,EAAE,OAAO,GAAG,OAAO,QAAQ,IAAI;EACjC,OAAO,GAAG,gBAAgB,UAAU,QAAQ;EAC5C,OAAO,aAAa,QAAQ;EAC5B;CACF;CAEA,KAAI,OADoB,GAAG,eAAe,QAAQ,OACjC,UAAU;EACzB,OAAO,GAAG,gBAAgB,UAAU,QAAQ;EAC5C,OAAO,gBAAgB,QAAQ;CACjC;AACF,CAAC;AAE8B,OAAO,IAAI,aAAa;CACrD,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,OAAO,OAAO,KAAK;CAEzB,MAAM,WAAW,KAAK,QAAQ,GAAG;CACjC,MAAM,OAAO,KAA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C;AAED,MAAM,uBAAuB,OAAO,WAAW,WAC7C,aACA,YACA,kBACA;CACA,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,mBAAmB,OAAO,iBAAiB;CACjD,MAAM,kBAAkB,OAAO,gBAAgB;CAE/C,MAAM,kBAAkB,KAAK,KAAK,kBAAkB,WAAW;CAE/D,IAAI,EAAE,OAAO,GAAG,OAAO,eAAe,IACpC,OAAO,OAAO,KAAK;CAGrB,MAAM,iBAAiB,KAAK,KAAK,iBAAiB,UAAU;CAC5D,MAAM,qBAAqB,KAAK,SAC9B,KAAK,QAAQ,cAAc,GAC3B,eACF;CACA,MAAM,WAAW,OAAO,iBACtB,OAAO,mBAAmB,kBAAkB,CAC9C;CACA,MAAM,SAAS,OAAO,gBAAgB,gBAAgB,QAAQ;CAC9D,OAAO,OAAO,KAAK;EAAE;EAAQ;CAAe,CAAC;AAC/C,CAAC;AAED,MAAa,eAAe,qBAC1B,WACA,YACC,eAAeA,KAAe,EAAE,gBAAgB,WAAW,CAAC,CAC/D;AAEA,MAAa,gBAAgB,qBAC3B,YACA,aACC,eAAeC,MAAgB,EAAE,iBAAiB,WAAW,CAAC,CACjE;AAEA,MAAa,qBAAqB,qBAChC,WACA,mBACC,eAAeC,WAAqB,EAAE,gBAAgB,WAAW,CAAC,CACrE"}
1
+ {"version":3,"file":"utils.mjs","names":["templates.http","templates.crons","templates.authConfig"],"sources":["../src/utils.ts"],"sourcesContent":["import * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport type { PlatformError } from \"effect/PlatformError\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Option from \"effect/Option\";\nimport * as Order from \"effect/Order\";\nimport * as String from \"effect/String\";\nimport { logFileAdded, logFileModified } from \"./log.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport { ConvexDirectory } from \"./ConvexDirectory.js\";\nimport * as templates from \"./templates.js\";\n\nexport const removePathExtension = Effect.fnUntraced(function* (\n pathStr: string,\n) {\n const path = yield* Path.Path;\n\n return String.slice(0, -path.extname(pathStr).length)(pathStr);\n});\n\nexport const toPosixPath = (path: Path.Path, pathStr: string): string =>\n pipe(String.split(pathStr, path.sep), Array.join(\"/\"));\n\n/**\n * Every path under `directory`, relative to it, in code-unit order of its POSIX\n * form. Node's recursive `readdir` walks in an order that differs across Node\n * versions, and codegen writes what it discovers in that order, so reading\n * through here keeps the output the same on every Node and on every platform.\n * The paths keep the host's separator.\n */\nexport const readDirectorySorted = Effect.fnUntraced(function* (\n directory: string,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n return Array.sort(\n yield* fs.readDirectory(directory, { recursive: true }),\n Order.mapInput(Order.String, (relativePath: string) =>\n toPosixPath(path, relativePath),\n ),\n );\n});\n\n/**\n * Ensures a relative path is a valid ESM/TS module specifier (e.g. `spec` →\n * `./spec`).\n */\nexport const toModuleImportPath = Effect.fnUntraced(function* (\n relativePath: string,\n) {\n const path = yield* Path.Path;\n const withoutExt = toPosixPath(\n path,\n yield* removePathExtension(relativePath),\n );\n return String.startsWith(\".\")(withoutExt)\n ? `${withoutExt}.js`\n : `./${withoutExt}.js`;\n});\n\nexport const writeFileStringAndLog = Effect.fnUntraced(function* (\n filePath: string,\n contents: string,\n) {\n const fs = yield* FileSystem.FileSystem;\n if (!(yield* fs.exists(filePath))) {\n yield* fs.writeFileString(filePath, contents);\n yield* logFileAdded(filePath);\n return;\n }\n const existing = yield* fs.readFileString(filePath);\n if (existing !== contents) {\n yield* fs.writeFileString(filePath, contents);\n yield* logFileModified(filePath);\n }\n});\n\nexport const findProjectRoot = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n\n const startDir = path.resolve(\".\");\n const root = path.parse(startDir).root;\n\n const directories = Array.unfold(startDir, (dir) =>\n dir === root\n ? Option.none()\n : Option.some([dir, path.dirname(dir)] as const),\n );\n\n const projectRoot = yield* Effect.findFirst(directories, (dir) =>\n fs.exists(path.join(dir, \"package.json\")),\n );\n\n return Option.getOrElse(projectRoot, () => startDir);\n});\n\nexport type WriteChange = \"Added\" | \"Modified\" | \"Unchanged\";\n\nexport const writeFileString = Effect.fnUntraced(function* (\n filePath: string,\n contents: string,\n): Effect.fn.Return<WriteChange, PlatformError, FileSystem.FileSystem> {\n const fs = yield* FileSystem.FileSystem;\n\n if (!(yield* fs.exists(filePath))) {\n yield* fs.writeFileString(filePath, contents);\n return \"Added\";\n }\n const existing = yield* fs.readFileString(filePath);\n if (existing !== contents) {\n yield* fs.writeFileString(filePath, contents);\n return \"Modified\";\n }\n return \"Unchanged\";\n});\n\nexport const removePathIfExists = Effect.fnUntraced(function* (\n filePath: string,\n): Effect.fn.Return<void, PlatformError, FileSystem.FileSystem> {\n const fs = yield* FileSystem.FileSystem;\n\n if (!(yield* fs.exists(filePath))) {\n return;\n }\n\n yield* fs\n .remove(filePath)\n .pipe(\n Effect.catchTag(\"PlatformError\", (error) =>\n error.reason._tag === \"NotFound\" ? Effect.void : Effect.fail(error),\n ),\n );\n});\n\n/**\n * Bump the mtime of `convex/schema.ts` so the Convex CLI's chokidar watcher\n * emits a `change` event after explicit codegen, bootstrap, or recovery.\n * Recovery can leave generated contents unchanged, so it needs an explicit\n * notification to release Convex from a previous error. Ordinary successful\n * watch updates rely on their source/output changes instead of invalidating a\n * Convex push that may already be processing those changes.\n */\nexport const touchConvexSchema = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n const schemaPath = path.join(convexDirectory, \"schema.ts\");\n\n if (!(yield* fs.exists(schemaPath))) {\n return;\n }\n\n const now = yield* DateTime.nowAsDate;\n yield* fs.utimes(schemaPath, now, now);\n});\n\nconst generateOptionalFile = Effect.fnUntraced(function* (\n confectFile: string,\n convexFile: string,\n generateContents: (importPath: string) => Effect.Effect<string>,\n) {\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\n const confectFilePath = path.join(confectDirectory, confectFile);\n\n if (!(yield* fs.exists(confectFilePath))) {\n return Option.none();\n }\n\n const convexFilePath = path.join(convexDirectory, convexFile);\n const relativeImportPath = path.relative(\n path.dirname(convexFilePath),\n confectFilePath,\n );\n const contents = yield* generateContents(\n yield* toModuleImportPath(relativeImportPath),\n );\n const change = yield* writeFileString(convexFilePath, contents);\n return Option.some({ change, convexFilePath });\n});\n\nexport const generateHttp = generateOptionalFile(\n \"http.ts\",\n \"http.ts\",\n (importPath) => templates.http({ httpImportPath: importPath }),\n);\n\nexport const generateCrons = generateOptionalFile(\n \"crons.ts\",\n \"crons.ts\",\n (importPath) => templates.crons({ cronsImportPath: importPath }),\n);\n\nexport const generateAuthConfig = generateOptionalFile(\n \"auth.ts\",\n \"auth.config.ts\",\n (importPath) => templates.authConfig({ authImportPath: importPath }),\n);\n"],"mappings":";;;;;;;;;;;;;;AAeA,MAAa,sBAAsB,OAAO,WAAW,WACnD,SACA;CACA,MAAM,OAAO,OAAO,KAAK;CAEzB,OAAO,OAAO,MAAM,GAAG,CAAC,KAAK,QAAQ,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,OAAO;AAC/D,CAAC;AAED,MAAa,eAAe,MAAiB,YAC3C,KAAK,OAAO,MAAM,SAAS,KAAK,GAAG,GAAG,MAAM,KAAK,GAAG,CAAC;;;;;;;;AASvD,MAAa,sBAAsB,OAAO,WAAW,WACnD,WACA;CACA,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,OAAO,OAAO,KAAK;CACzB,OAAO,MAAM,KACX,OAAO,GAAG,cAAc,WAAW,EAAE,WAAW,KAAK,CAAC,GACtD,MAAM,SAAS,MAAM,SAAS,iBAC5B,YAAY,MAAM,YAAY,CAChC,CACF;AACF,CAAC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AQ;CAC9D,OAAO,OAAO,KAAK;EAAE;EAAQ;CAAe,CAAC;AAC/C,CAAC;AAED,MAAa,eAAe,qBAC1B,WACA,YACC,eAAeA,KAAe,EAAE,gBAAgB,WAAW,CAAC,CAC/D;AAEA,MAAa,gBAAgB,qBAC3B,YACA,aACC,eAAeC,MAAgB,EAAE,iBAAiB,WAAW,CAAC,CACjE;AAEA,MAAa,qBAAqB,qBAChC,WACA,mBACC,eAAeC,WAAqB,EAAE,gBAAgB,WAAW,CAAC,CACrE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gaganref/confect-cli",
3
- "version": "10.3.1-fork.86",
3
+ "version": "10.3.1-fork.88",
4
4
  "dependencies": {
5
5
  "@effect/platform-node": ">=4.0.4 <4.1.0",
6
6
  "bundle-require": "^5.1.0",
@@ -9,8 +9,8 @@
9
9
  "exsolve": "^1.1.3"
10
10
  },
11
11
  "peerDependencies": {
12
- "@confect/core": "npm:@gaganref/confect-core@10.3.1-fork.86",
13
- "@confect/server": "npm:@gaganref/confect-server@10.3.1-fork.86",
12
+ "@confect/core": "npm:@gaganref/confect-core@10.3.1-fork.88",
13
+ "@confect/server": "npm:@gaganref/confect-server@10.3.1-fork.88",
14
14
  "@effect/platform-node-shared": ">=4.0.4 <4.1.0",
15
15
  "effect": ">=4.0.4 <4.1.0"
16
16
  },