@gaganref/confect-cli 10.3.1-fork.95 → 10.6.0-fork.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +78 -0
- package/dist/Ansi.mjs +1 -2
- package/dist/BuildError.mjs +5 -5
- package/dist/BuildError.mjs.map +1 -1
- package/dist/Bundler.mjs +103 -76
- package/dist/Bundler.mjs.map +1 -1
- package/dist/CodeBlockWriter.mjs +1 -2
- package/dist/CodegenError.mjs +27 -17
- package/dist/CodegenError.mjs.map +1 -1
- package/dist/ConfectDirectory.mjs +8 -3
- package/dist/ConfectDirectory.mjs.map +1 -1
- package/dist/ConvexConfig.mjs +23 -15
- package/dist/ConvexConfig.mjs.map +1 -1
- package/dist/ConvexDirectory.mjs +6 -4
- package/dist/ConvexDirectory.mjs.map +1 -1
- package/dist/Declaration.mjs +92 -56
- package/dist/Declaration.mjs.map +1 -1
- package/dist/DirectoryOptions.mjs +13 -8
- package/dist/DirectoryOptions.mjs.map +1 -1
- package/dist/DocName.mjs +1 -2
- package/dist/EntryPoint.mjs +17 -15
- package/dist/EntryPoint.mjs.map +1 -1
- package/dist/Evaluation.mjs +24 -13
- package/dist/Evaluation.mjs.map +1 -1
- package/dist/EvaluationWorker.mjs +5 -6
- package/dist/EvaluationWorker.mjs.map +1 -1
- package/dist/FunctionModule.mjs +85 -47
- package/dist/FunctionModule.mjs.map +1 -1
- package/dist/FunctionPath.mjs +1 -2
- package/dist/FunctionPath.mjs.map +1 -1
- package/dist/FunctionPaths.mjs +2 -3
- package/dist/GenerationSnapshot.mjs +30 -22
- package/dist/GenerationSnapshot.mjs.map +1 -1
- package/dist/GroupPath.mjs +6 -3
- package/dist/GroupPath.mjs.map +1 -1
- package/dist/GroupPaths.mjs +1 -2
- package/dist/ImplModulePath.mjs +1 -2
- package/dist/Json.mjs +13 -0
- package/dist/Json.mjs.map +1 -0
- package/dist/LeafModule.mjs +121 -41
- package/dist/LeafModule.mjs.map +1 -1
- package/dist/ManifestSections.mjs +23 -19
- package/dist/ManifestSections.mjs.map +1 -1
- package/dist/PackageSelfReference.mjs +32 -0
- package/dist/PackageSelfReference.mjs.map +1 -0
- package/dist/ProjectRoot.mjs +11 -3
- package/dist/ProjectRoot.mjs.map +1 -1
- package/dist/RelativeModulePath.mjs +1 -2
- package/dist/Remove.mjs +2 -3
- package/dist/Remove.mjs.map +1 -1
- package/dist/RestoreWatcher.mjs +1 -2
- package/dist/Rollback.mjs +7 -6
- package/dist/Rollback.mjs.map +1 -1
- package/dist/SectionFiles.mjs +77 -48
- package/dist/SectionFiles.mjs.map +1 -1
- package/dist/SnapshotError.mjs +3 -3
- package/dist/SnapshotError.mjs.map +1 -1
- package/dist/SpecAssemblyNode.mjs +1 -2
- package/dist/SpecModulePath.mjs +4 -4
- package/dist/SpecModulePath.mjs.map +1 -1
- package/dist/SyncState.mjs +3 -4
- package/dist/SyncState.mjs.map +1 -1
- package/dist/TableModule.mjs +18 -10
- package/dist/TableModule.mjs.map +1 -1
- package/dist/TableModulePath.mjs +3 -3
- package/dist/TableModulePath.mjs.map +1 -1
- package/dist/TypeScriptConfig.mjs +135 -0
- package/dist/TypeScriptConfig.mjs.map +1 -0
- package/dist/WatchBuild.mjs +107 -32
- package/dist/WatchBuild.mjs.map +1 -1
- package/dist/WatchGraph.mjs +4 -4
- package/dist/WatchGraph.mjs.map +1 -1
- package/dist/WatchTopology.mjs +5 -4
- package/dist/WatchTopology.mjs.map +1 -1
- package/dist/Watcher.mjs +179 -108
- package/dist/Watcher.mjs.map +1 -1
- package/dist/cliApp.mjs +5 -3
- package/dist/cliApp.mjs.map +1 -1
- package/dist/confect/codegen.mjs +95 -53
- package/dist/confect/codegen.mjs.map +1 -1
- package/dist/confect/declaration.mjs +76 -42
- package/dist/confect/declaration.mjs.map +1 -1
- package/dist/confect/dev.mjs +18 -12
- package/dist/confect/dev.mjs.map +1 -1
- package/dist/confect.mjs +4 -2
- package/dist/confect.mjs.map +1 -1
- package/dist/index.mjs +1 -2
- package/dist/log.mjs +13 -5
- package/dist/log.mjs.map +1 -1
- package/dist/package.json.mjs +5 -0
- package/dist/package.json.mjs.map +1 -0
- package/dist/templates.mjs +34 -22
- package/dist/templates.mjs.map +1 -1
- package/dist/utils.mjs +36 -5
- package/dist/utils.mjs.map +1 -1
- package/package.json +10 -10
- package/dist/package.mjs +0 -6
- package/dist/package.mjs.map +0 -1
package/dist/LeafModule.mjs.map
CHANGED
|
@@ -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 {\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,IAClC,GAA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BAAkB;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 * as Record from \"effect/Record\";\nimport { 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 Iterable from \"effect/Iterable\";\nimport { pipe } from \"effect/Function\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Ref from \"effect/Ref\";\nimport * as Result from \"effect/Result\";\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 InvalidContextReuseError,\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\";\nimport { logWarn } from \"./log.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 (\n ext !== \".ts\" ||\n !String.endsWith(String.slice(0, -\".ts\".length)(fromSuffix))(name)\n ) {\n return relativePath;\n }\n\n const stem = String.slice(\n 0,\n -String.slice(0, -\".ts\".length)(fromSuffix).length,\n )(name);\n const nextName = `${stem}${String.slice(0, -\".ts\".length)(toSuffix)}`;\n return dir.length > 0\n ? path.join(dir, `${nextName}${ext}`)\n : `${nextName}${ext}`;\n});\n\nexport const isLeafSpecPath = (relativePath: string) =>\n String.endsWith(SPEC_SUFFIX)(relativePath);\n\n/**\n * @internal\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 String.endsWith(\".spec\")(name)\n ? String.slice(0, -\".spec\".length)(name)\n : name;\n});\n\n/**\n * @internal\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\" && String.endsWith(\".spec\")(name)\n ? String.slice(0, -\".spec\".length)(name)\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\n/**\n * @internal\n */\nexport const specImportPathFromGenerated = Effect.fnUntraced(function* (\n specRelativePath: string,\n) {\n const path = yield* Path.Path;\n const pathWithoutExtension = yield* removePathExtension(specRelativePath);\n const withoutExt = toPosixPath(path, pathWithoutExtension);\n return `../${withoutExt}.js`;\n});\n\n/**\n * @internal\n */\nexport const specPathForImpl = (implRelativePath: string) =>\n swapModuleSuffix(implRelativePath, IMPL_SUFFIX, SPEC_SUFFIX);\n\n/**\n * @internal\n */\nexport const implPathForSpec = (specRelativePath: string) =>\n swapModuleSuffix(specRelativePath, SPEC_SUFFIX, IMPL_SUFFIX);\n\n/**\n * @internal\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\n/**\n * @internal\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\n/**\n * @internal\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\n/**\n * @internal\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 directory = yield* ConfectDirectory.get;\n const confectDirectory = path.resolve(directory);\n\n const isCheckedUserModule = (absolutePath: string) => {\n const relative = path.relative(confectDirectory, absolutePath);\n return !String.startsWith(\"..\")(relative) && !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* SpecImportsServerError.make({\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 Record.values(group.functions)) {\n const name = spec.reservedArgument;\n const provenance = spec.functionProvenance;\n if (\n name !== undefined &&\n provenance._tag === \"Confect\" &&\n Record.has(provenance.args.fields, name)\n ) {\n return yield* InvalidDeclarationError.make({\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 Record.toEntries(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 *\n * @internal\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* SpecMissingDefaultGroupSpecError.make({\n specPath: leaf.relativePath,\n });\n }\n\n yield* validateClientSafety(leaf, bundled);\n yield* validateReservedArguments(\n groupSpec,\n leaf.relativePath,\n Array.join(leaf.pathSegments, \"/\"),\n );\n\n const warnings = yield* Effect.fromResult(\n validateContextReuse(groupSpec, leaf.relativePath, leaf.groupPathDot),\n );\n for (const groupPath of warnings) {\n yield* logWarn(\n `${leaf.relativePath}, group ${groupPath}: experimental_reuseContext has no effect on actions; this group contains only actions.`,\n );\n }\n\n yield* Effect.fromResult(GroupSpec.validateMiddleware(groupSpec)).pipe(\n Effect.mapError((error) =>\n InvalidMiddlewareAttachmentError.make({\n specPath: leaf.relativePath,\n message: MiddlewareAttachment.formatValidationError(error),\n }),\n ),\n );\n\n return LoadedLeafModule({\n ...leaf,\n spec: groupSpec,\n });\n});\n\nconst validateContextReuse = (\n group: GroupSpec.AnyWithProps,\n specPath: string,\n groupPath: string,\n): Result.Result<ReadonlyArray<string>, InvalidContextReuseError> =>\n Result.gen(function* () {\n const isEnabled = group.experimental_reuseContext;\n if (isEnabled !== undefined && typeof isEnabled !== \"boolean\") {\n return yield* Result.fail(\n InvalidContextReuseError.make({\n specPath,\n groupPath,\n reason: \"InvalidOption\",\n }),\n );\n }\n if (isEnabled) {\n if (group.runtime === \"Node\") {\n return yield* Result.fail(\n InvalidContextReuseError.make({\n specPath,\n groupPath,\n reason: \"NodeRuntime\",\n }),\n );\n }\n if (Record.has(group.functions, \"experimental_reuseContext\")) {\n return yield* Result.fail(\n InvalidContextReuseError.make({\n specPath,\n groupPath,\n reason: \"ReservedFunctionName\",\n }),\n );\n }\n }\n const functions = Record.values(group.functions);\n const warnings =\n isEnabled &&\n functions.length > 0 &&\n Array.every(\n functions,\n (fn) => fn.runtimeAndFunctionType.functionType === \"action\",\n )\n ? [groupPath]\n : [];\n const childWarnings = yield* pipe(\n group.groups,\n Record.toEntries,\n Iterable.map(([name, child]) =>\n validateContextReuse(child, specPath, `${groupPath}.${name}`),\n ),\n Result.all,\n );\n return [...warnings, ...Array.flatten(childWarnings)];\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 * @internal\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 confectDirectory = yield* ConfectDirectory.get;\n const generated = path.join(confectDirectory, \"_generated\");\n const errors = Array.map(\n error.errors as ReadonlyArray<esbuild.Message>,\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 (pipe(file, String.startsWith(\"..\")) || path.isAbsolute(file))\n return message;\n const extension = path.extname(file);\n const name = toPosixPath(\n path,\n extension === \"\"\n ? `${file}.ts`\n : extension === \".js\"\n ? `${pipe(file, String.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 BundleFailedError.make({ file: error.file, errors });\n});\n\n/**\n * @internal\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* ImplMissingSpecImportError.make({\n implPath: implRelativePath,\n expectedSpecPath: leaf.relativePath,\n });\n }\n\n if (!Layer.isLayer(bundled.module.default)) {\n return yield* ImplMissingDefaultLayerError.make({\n implPath: implRelativePath,\n });\n }\n\n const groupSpec = leaf.spec;\n const expectedFunctionNames = Record.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: () => ImplNotFinalizedError.make({ implPath: implRelativePath }),\n onSome: Effect.succeed,\n },\n );\n\n const registeredSet = HashSet.fromIterable(\n finalizedGroupImpl.registeredFunctionNames,\n );\n const missing = Array.filter(\n expectedFunctionNames,\n (name) => !HashSet.has(registeredSet, name),\n );\n\n if (missing.length > 0) {\n return yield* ImplMissingFunctionsError.make({\n implPath: implRelativePath,\n groupPath: leaf.groupPathDot,\n missingFunctionNames: missing,\n });\n }\n\n const expectedMiddlewareKeys = Array.dedupe([\n ...Array.map(\n groupSpec.middlewareSpecs ?? [],\n (middlewareSpec) => middlewareSpec.key,\n ),\n ...Array.flatMap(Record.values(groupSpec.functions), (function_) =>\n Array.map(\n function_.middlewareSpecs ?? [],\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* ImplMissingMiddlewareError.make({\n implPath: implRelativePath,\n groupPath: leaf.groupPathDot,\n missingMiddlewareKeys: missingMiddleware,\n });\n }\n\n return RegistryItems.missingRequired(items, required, leaf.groupPathDot);\n});\n\n/**\n * @internal\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 Array.flatMap(pairs, ({ 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* MissingSpecFileError.make({\n implPath: implRelativePath,\n expectedSpecPath: specRelativePath,\n });\n }\n if (\n !(yield* fs.exists(path.join(confectDirectory, implRelativePath)))\n ) {\n return yield* MissingImplFileError.make({\n specPath: specRelativePath,\n expectedImplPath: implRelativePath,\n });\n }\n const leafModule = yield* toLeafModule(specRelativePath);\n const leaf = yield* loadSpec(leafModule);\n return leaf;\n }),\n { concurrency: VALIDATION_CONCURRENCY },\n );\n return yield* use(leaves);\n }),\n );\n});\n\n/**\n * @internal\n */\nexport const validateImplFiles = Effect.fn(\"LeafModule.validateImplFiles\")(\n (relativePaths: ReadonlyArray<ImplModulePath>) =>\n withImplFiles(relativePaths, validateAllImpls),\n);\n\n/**\n * @internal\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) =>\n pipe(left.functionName, String.localeCompare(right.functionName)),\n );\n if (missing.length > 0) {\n return yield* RequiredMiddlewareError.make({ missing });\n }\n});\n\n/**\n * @internal\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 Array.map(specFiles, (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* MissingImplFileError.make({\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* MissingSpecFileError.make({\n implPath: implRelativePath,\n expectedSpecPath: specRelativePath,\n });\n }\n }),\n );\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA0DA,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,IACE,QAAQ,SACR,CAAC,OAAO,SAAS,OAAO,MAAM,GAAG,EAAa,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,GAEjE,OAAO;CAOT,MAAM,WAAW,GAJJ,OAAO,MAClB,GACA,CAAC,OAAO,MAAM,GAAG,EAAa,CAAC,CAAC,UAAU,CAAC,CAAC,MAC9C,CAAC,CAAC,IACqB,IAA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ACrD,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,qBAAqB,KAAK;GACtC,UAAU;GACV,kBAAkB;EACpB,CAAC;CAEL,CAAC,CACH;AACF,CAAC"}
|
|
@@ -1,23 +1,28 @@
|
|
|
1
1
|
import { InvalidDeclarationError, InvalidManifestSectionError } from "./CodegenError.mjs";
|
|
2
|
+
import { quote, stringify } from "./Json.mjs";
|
|
3
|
+
import * as Arr from "effect/Array";
|
|
2
4
|
import * as Result from "effect/Result";
|
|
5
|
+
import { pipe } from "effect/Function";
|
|
6
|
+
import * as Rec from "effect/Record";
|
|
3
7
|
import * as Schema from "effect/Schema";
|
|
8
|
+
import * as Str from "effect/String";
|
|
4
9
|
import * as Predicate from "effect/Predicate";
|
|
5
10
|
import * as Order from "effect/Order";
|
|
6
|
-
|
|
7
|
-
const reserved = new Set("name env http digest __proto__ constructor prototype".split(" "));
|
|
8
|
-
const sections = (manifest) =>
|
|
11
|
+
// src/ManifestSections.ts
|
|
12
|
+
const reserved = new Set(pipe("name env http digest __proto__ constructor prototype", Str.split(" ")));
|
|
13
|
+
const sections = (manifest) => Rec.fromEntries(Arr.filter(Rec.toEntries(manifest), ([key]) => !reserved.has(key)));
|
|
9
14
|
const nonJsonPath = (value, path = "$", ancestors = []) => {
|
|
10
15
|
if (value === null || ["string", "boolean"].includes(typeof value)) return void 0;
|
|
11
16
|
if (typeof value === "number") return Number.isFinite(value) ? void 0 : path;
|
|
12
17
|
if (typeof value !== "object" || ancestors.includes(value)) return path;
|
|
13
|
-
const isArray =
|
|
18
|
+
const isArray = Arr.isArray(value);
|
|
14
19
|
if (!(isArray ? [Array.prototype] : [Object.prototype, null]).includes(Object.getPrototypeOf(value))) return path;
|
|
15
20
|
const keys = isArray ? Array.from({ length: Object.getOwnPropertyDescriptor(value, "length")?.value }, (_, index) => String(index)) : Reflect.ownKeys(value);
|
|
16
21
|
for (const key of keys) {
|
|
17
22
|
if (typeof key === "symbol") return path;
|
|
18
|
-
const at = `${path}[${
|
|
23
|
+
const at = `${path}[${quote(key)}]`;
|
|
19
24
|
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
20
|
-
if (key === "__proto__" ||
|
|
25
|
+
if (key === "__proto__" || descriptor?.enumerable !== true || !("value" in descriptor)) return at;
|
|
21
26
|
const found = nonJsonPath(descriptor.value, at, [...ancestors, value]);
|
|
22
27
|
if (found !== void 0) return found;
|
|
23
28
|
}
|
|
@@ -25,10 +30,10 @@ const nonJsonPath = (value, path = "$", ancestors = []) => {
|
|
|
25
30
|
};
|
|
26
31
|
const json = (value) => {
|
|
27
32
|
const path = nonJsonPath(value);
|
|
28
|
-
return path === void 0 ? Result.succeed(JSON.parse(
|
|
33
|
+
return path === void 0 ? Result.succeed(JSON.parse(stringify(value))) : Result.fail(`Expected JSON data at ${path}`);
|
|
29
34
|
};
|
|
30
35
|
const hasFormat = (format) => Schema.is(Schema.Struct({ format: Schema.Literal(format) }));
|
|
31
|
-
const appDeclaration = (reason) =>
|
|
36
|
+
const appDeclaration = (reason) => InvalidDeclarationError.make({
|
|
32
37
|
declarationPath: "confect/app.ts",
|
|
33
38
|
reason
|
|
34
39
|
});
|
|
@@ -46,16 +51,16 @@ const declared = (entries) => Result.gen(function* () {
|
|
|
46
51
|
});
|
|
47
52
|
const visit = (leaves, each) => Result.gen(function* () {
|
|
48
53
|
const walk = (group, path, source) => Result.gen(function* () {
|
|
49
|
-
for (const spec of
|
|
50
|
-
for (const [name, child] of
|
|
54
|
+
for (const spec of Rec.values(group.functions)) yield* each(spec, group, `${path}:${spec.name}`, source);
|
|
55
|
+
for (const [name, child] of Rec.toEntries(group.groups)) yield* walk(child, `${path}/${name}`, source);
|
|
51
56
|
});
|
|
52
|
-
for (const leaf of leaves) yield* walk(leaf.spec, leaf.pathSegments
|
|
57
|
+
for (const leaf of leaves) yield* walk(leaf.spec, Arr.join(leaf.pathSegments, "/"), leaf.relativePath);
|
|
53
58
|
});
|
|
54
59
|
/**
|
|
55
60
|
* Refuse a function spec that still carries `manifestSections`: codegen reads a
|
|
56
61
|
* backend's sections only from `App.make`.
|
|
57
62
|
*/
|
|
58
|
-
const refuseSpecSections = (leaves) => visit(leaves, (spec, _, path, source) => Predicate.hasProperty(spec, "manifestSections") ? Result.fail(
|
|
63
|
+
const refuseSpecSections = (leaves) => visit(leaves, (spec, _, path, source) => Predicate.hasProperty(spec, "manifestSections") ? Result.fail(InvalidDeclarationError.make({
|
|
59
64
|
declarationPath: `confect/${source}`,
|
|
60
65
|
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.`
|
|
61
66
|
})) : Result.void);
|
|
@@ -66,7 +71,7 @@ const refuseSpecSections = (leaves) => visit(leaves, (spec, _, path, source) =>
|
|
|
66
71
|
* section, with none.
|
|
67
72
|
*/
|
|
68
73
|
const collect = (entries, leaves) => Result.gen(function* () {
|
|
69
|
-
const registry = new Map(
|
|
74
|
+
const registry = new Map(Arr.map(entries, ({ key, section }) => [key, {
|
|
70
75
|
section,
|
|
71
76
|
data: {
|
|
72
77
|
format: section.format,
|
|
@@ -86,7 +91,7 @@ const collect = (entries, leaves) => Result.gen(function* () {
|
|
|
86
91
|
});
|
|
87
92
|
functions.sort(Order.mapInput(Order.String, ({ path }) => path));
|
|
88
93
|
for (const { spec, group, path, source } of functions) for (const [key, { section, data, sources }] of registry) {
|
|
89
|
-
const invalid = (reason) =>
|
|
94
|
+
const invalid = (reason) => InvalidDeclarationError.make({
|
|
90
95
|
declarationPath: `confect/${source}`,
|
|
91
96
|
reason: `Manifest section "${key}" (${path}): ${reason}`
|
|
92
97
|
});
|
|
@@ -116,7 +121,7 @@ const summarize = (registry, modules) => Result.gen(function* () {
|
|
|
116
121
|
functions: data.functions,
|
|
117
122
|
sources
|
|
118
123
|
};
|
|
119
|
-
const invalid = (reason) =>
|
|
124
|
+
const invalid = (reason) => InvalidManifestSectionError.make({
|
|
120
125
|
sectionKey: key,
|
|
121
126
|
reason
|
|
122
127
|
});
|
|
@@ -140,12 +145,12 @@ const check = (registry, previous) => {
|
|
|
140
145
|
const checked = section.check?.(data, previous[key]);
|
|
141
146
|
if (checked === void 0) continue;
|
|
142
147
|
notes.push(...checked.notes);
|
|
143
|
-
if (checked.errors.length > 0) errors.push(
|
|
148
|
+
if (checked.errors.length > 0) errors.push(InvalidManifestSectionError.make({
|
|
144
149
|
sectionKey: key,
|
|
145
|
-
reason: [...new Set(checked.errors)]
|
|
150
|
+
reason: Arr.join([...new Set(checked.errors)], "\n")
|
|
146
151
|
}));
|
|
147
152
|
} catch (cause) {
|
|
148
|
-
errors.push(
|
|
153
|
+
errors.push(InvalidManifestSectionError.make({
|
|
149
154
|
sectionKey: key,
|
|
150
155
|
reason: `check failed: ${String(cause)}`
|
|
151
156
|
}));
|
|
@@ -155,7 +160,6 @@ const check = (registry, previous) => {
|
|
|
155
160
|
notes
|
|
156
161
|
};
|
|
157
162
|
};
|
|
158
|
-
//#endregion
|
|
159
163
|
export { check, collect, declared, refuseSpecSections, sections, summarize };
|
|
160
164
|
|
|
161
165
|
//# sourceMappingURL=ManifestSections.mjs.map
|
|
@@ -1 +1 @@
|
|
|
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,OAAO;CACnE,MAAM,UAAU,MAAM,QAAQ,KAAK;CAEnC,IAAI,EADe,UAAU,CAAC,MAAM,SAAS,IAAI,CAAC,OAAO,WAAW,IAAI,EAAA,CACxD,SAAS,OAAO,eAAe,KAAK,CAAC,GAAG,OAAO;CAC/D,MAAM,OAAO,UACT,MAAM,KACJ,E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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\";\nimport * as Str from \"effect/String\";\nimport { pipe } from \"effect/Function\";\nimport * as Arr from \"effect/Array\";\nimport * as Rec from \"effect/Record\";\nimport { quote, stringify } from \"./Json.js\";\n\nconst reserved = new Set(\n pipe(\"name env http digest __proto__ constructor prototype\", Str.split(\" \")),\n);\nexport const sections = (manifest: Readonly<Record<string, unknown>>) =>\n Rec.fromEntries(\n Arr.filter(Rec.toEntries(manifest), ([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 = Arr.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}[${quote(key)}]`;\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (\n key === \"__proto__\" ||\n descriptor?.enumerable !== true ||\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 ? // oxlint-disable-next-line effecttsgo/global-json -- A sync clone of data the path check above proved is JSON, so it cannot throw; json returns a Result for callers outside an Effect.\n Result.succeed(JSON.parse(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 InvalidDeclarationError.make({ 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 Rec.values(group.functions))\n yield* each(spec, group, `${path}:${spec.name}`, source);\n for (const [name, child] of Rec.toEntries(group.groups))\n yield* walk(child, `${path}/${name}`, source);\n });\n for (const leaf of leaves)\n yield* walk(\n leaf.spec,\n Arr.join(leaf.pathSegments, \"/\"),\n leaf.relativePath,\n );\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 InvalidDeclarationError.make({\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 Arr.map(entries, ({ 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 InvalidDeclarationError.make({\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 InvalidManifestSectionError.make({ 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 InvalidManifestSectionError.make({\n sectionKey: key,\n reason: Arr.join([...new Set(checked.errors)], \"\\n\"),\n }),\n );\n } catch (cause) {\n errors.push(\n InvalidManifestSectionError.make({\n sectionKey: key,\n reason: `check failed: ${String(cause)}`,\n }),\n );\n }\n }\n return { errors, notes };\n};\n"],"mappings":";;;;;;;;;;;AAgBA,MAAM,WAAW,IAAI,IACnB,KAAK,wDAAwD,IAAI,MAAM,GAAG,CAAC,CAC7E;AACA,MAAa,YAAY,aACvB,IAAI,YACF,IAAI,OAAO,IAAI,UAAU,QAAQ,IAAI,CAAC,SAAS,CAAC,SAAS,IAAI,GAAG,CAAC,CACnE;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,OAAO;CACnE,MAAM,UAAU,IAAI,QAAQ,KAAK;CAEjC,IAAI,EADe,UAAU,CAAC,MAAM,SAAS,IAAI,CAAC,OAAO,WAAW,IAAI,EAAA,CACxD,SAAS,OAAO,eAAe,KAAK,CAAC,GAAG,OAAO;CAC/D,MAAM,O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AK;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,4BAA4B,KAAK;GAC/B,YAAY;GACZ,QAAQ,IAAI,KAAK,CAAC,GAAG,IAAI,IAAI,QAAQ,MAAM,CAAC,GAAG,IAAI;EACrD,CAAC,CACH;CACJ,SAAS,OAAO;EACd,OAAO,KACL,4BAA4B,KAAK;GAC/B,YAAY;GACZ,QAAQ,iBAAiB,OAAO,KAAK;EACvC,CAAC,CACH;CACF;CAEF,OAAO;EAAE;EAAQ;CAAM;AACzB"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { BundlerError } from "./BuildError.mjs";
|
|
2
|
+
import * as Effect from "effect/Effect";
|
|
3
|
+
import * as FileSystem from "effect/FileSystem";
|
|
4
|
+
import * as Path from "effect/Path";
|
|
5
|
+
import * as Array from "effect/Array";
|
|
6
|
+
import * as Option from "effect/Option";
|
|
7
|
+
import * as Schema from "effect/Schema";
|
|
8
|
+
// src/PackageSelfReference.ts
|
|
9
|
+
const PackageSelfReference = Schema.String.pipe(Schema.brand("PackageSelfReference"));
|
|
10
|
+
const PackageMetadata = Schema.fromJsonString(Schema.Struct({
|
|
11
|
+
name: Schema.optionalKey(PackageSelfReference),
|
|
12
|
+
exports: Schema.optionalKey(Schema.Unknown)
|
|
13
|
+
}));
|
|
14
|
+
/**
|
|
15
|
+
* @internal
|
|
16
|
+
*/
|
|
17
|
+
const discover = Effect.fnUntraced(function* (directory) {
|
|
18
|
+
const fs = yield* FileSystem.FileSystem;
|
|
19
|
+
const path = yield* Path.Path;
|
|
20
|
+
const start = path.resolve(directory);
|
|
21
|
+
const root = path.parse(start).root;
|
|
22
|
+
const directories = Array.append(Array.unfold(start, (current) => current === root ? Option.none() : Option.some([current, path.dirname(current)])), root);
|
|
23
|
+
const nearest = yield* Effect.findFirst(directories, (current) => fs.exists(path.join(current, "package.json")));
|
|
24
|
+
if (Option.isNone(nearest)) return Option.none();
|
|
25
|
+
const contents = yield* fs.readFileString(path.join(nearest.value, "package.json"));
|
|
26
|
+
const metadata = yield* Schema.decodeEffect(PackageMetadata)(contents);
|
|
27
|
+
if (metadata.name === void 0 || metadata.name.length === 0 || metadata.exports === void 0 || metadata.exports === null) return Option.none();
|
|
28
|
+
else return Option.some(metadata.name);
|
|
29
|
+
}, Effect.mapError((cause) => BundlerError.make({ cause })));
|
|
30
|
+
export { PackageSelfReference, discover };
|
|
31
|
+
|
|
32
|
+
//# sourceMappingURL=PackageSelfReference.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PackageSelfReference.mjs","names":[],"sources":["../src/PackageSelfReference.ts"],"sourcesContent":["import * as Array from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport * as BuildError from \"./BuildError.js\";\n\nexport const PackageSelfReference = Schema.String.pipe(\n Schema.brand(\"PackageSelfReference\"),\n);\nexport type PackageSelfReference = typeof PackageSelfReference.Type;\n\nconst PackageMetadata = Schema.fromJsonString(\n Schema.Struct({\n name: Schema.optionalKey(PackageSelfReference),\n exports: Schema.optionalKey(Schema.Unknown),\n }),\n);\n\n/**\n * @internal\n */\nexport const discover = Effect.fnUntraced(\n function* (directory: string) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const start = path.resolve(directory);\n const root = path.parse(start).root;\n const directories = Array.append(\n Array.unfold(start, (current) =>\n current === root\n ? Option.none()\n : Option.some([current, path.dirname(current)] as const),\n ),\n root,\n );\n const nearest = yield* Effect.findFirst(directories, (current) =>\n fs.exists(path.join(current, \"package.json\")),\n );\n if (Option.isNone(nearest)) return Option.none<PackageSelfReference>();\n const contents = yield* fs.readFileString(\n path.join(nearest.value, \"package.json\"),\n );\n const metadata = yield* Schema.decodeEffect(PackageMetadata)(contents);\n if (\n metadata.name === undefined ||\n metadata.name.length === 0 ||\n metadata.exports === undefined ||\n metadata.exports === null\n ) {\n return Option.none<PackageSelfReference>();\n } else {\n return Option.some(metadata.name);\n }\n },\n Effect.mapError((cause) => BuildError.BundlerError.make({ cause })),\n);\n"],"mappings":";;;;;;;;AAQA,MAAa,uBAAuB,OAAO,OAAO,KAChD,OAAO,MAAM,sBAAsB,CACrC;AAGA,MAAM,kBAAkB,OAAO,eAC7B,OAAO,OAAO;CACZ,MAAM,OAAO,YAAY,oBAAoB;CAC7C,SAAS,OAAO,YAAY,OAAO,OAAO;AAC5C,CAAC,CACH;;;;AAKA,MAAa,WAAW,OAAO,WAC7B,WAAW,WAAmB;CAC5B,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,QAAQ,KAAK,QAAQ,SAAS;CACpC,MAAM,OAAO,KAAK,MAAM,KAAK,CAAC,CAAC;CAC/B,MAAM,cAAc,MAAM,OACxB,MAAM,OAAO,QAAQ,YACnB,YAAY,OACR,OAAO,KAAK,IACZ,OAAO,KAAK,CAAC,SAAS,KAAK,QAAQ,OAAO,CAAC,CAAU,CAC3D,GACA,IACF;CACA,MAAM,UAAU,OAAO,OAAO,UAAU,cAAc,YACpD,GAAG,OAAO,KAAK,KAAK,SAAS,cAAc,CAAC,CAC9C;CACA,IAAI,OAAO,OAAO,OAAO,GAAG,OAAO,OAAO,KAA2B;CACrE,MAAM,WAAW,OAAO,GAAG,eACzB,KAAK,KAAK,QAAQ,OAAO,cAAc,CACzC;CACA,MAAM,WAAW,OAAO,OAAO,aAAa,eAAe,CAAC,CAAC,QAAQ;CACrE,IACE,SAAS,SAAS,KAAA,KAClB,SAAS,KAAK,WAAW,KACzB,SAAS,YAAY,KAAA,KACrB,SAAS,YAAY,MAErB,OAAO,OAAO,KAA2B;MAEzC,OAAO,OAAO,KAAK,SAAS,IAAI;AAEpC,GACA,OAAO,UAAU,UAAA,aAAkC,KAAK,EAAE,MAAM,CAAC,CAAC,CACpE"}
|
package/dist/ProjectRoot.mjs
CHANGED
|
@@ -8,10 +8,13 @@ import * as Ref from "effect/Ref";
|
|
|
8
8
|
import * as Schema from "effect/Schema";
|
|
9
9
|
import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
|
|
10
10
|
import * as Layer from "effect/Layer";
|
|
11
|
-
|
|
11
|
+
// src/ProjectRoot.ts
|
|
12
12
|
var ProjectRoot = class ProjectRoot extends Context.Service()("@confect/cli/ProjectRoot") {
|
|
13
13
|
static get = ProjectRoot.use((service) => service.get);
|
|
14
14
|
};
|
|
15
|
+
/**
|
|
16
|
+
* @internal
|
|
17
|
+
*/
|
|
15
18
|
const findProjectRootFrom = Effect.fnUntraced(function* (directory) {
|
|
16
19
|
const fs = yield* FileSystem.FileSystem;
|
|
17
20
|
const path = yield* Path.Path;
|
|
@@ -19,9 +22,15 @@ const findProjectRootFrom = Effect.fnUntraced(function* (directory) {
|
|
|
19
22
|
const root = path.parse(startDir).root;
|
|
20
23
|
const directories = Array.unfold(startDir, (dir) => dir === root ? Option.none() : Option.some([dir, path.dirname(dir)]));
|
|
21
24
|
const projectRoot = yield* Effect.findFirst(directories, (dir) => fs.exists(path.join(dir, "package.json")));
|
|
22
|
-
return yield* Effect.fromOption(projectRoot, () =>
|
|
25
|
+
return yield* Effect.fromOption(projectRoot, () => ProjectRootNotFoundError.make());
|
|
23
26
|
});
|
|
27
|
+
/**
|
|
28
|
+
* @internal
|
|
29
|
+
*/
|
|
24
30
|
const findProjectRoot = findProjectRootFrom(".");
|
|
31
|
+
/**
|
|
32
|
+
* @internal
|
|
33
|
+
*/
|
|
25
34
|
const layer = Layer.effect(ProjectRoot, Effect.gen(function* () {
|
|
26
35
|
const projectRoot = yield* findProjectRoot;
|
|
27
36
|
const ref = yield* Ref.make(projectRoot);
|
|
@@ -32,7 +41,6 @@ var ProjectRootNotFoundError = class extends Schema.TaggedError()("ProjectRootNo
|
|
|
32
41
|
return "Could not find project root (no 'package.json' found)";
|
|
33
42
|
}
|
|
34
43
|
};
|
|
35
|
-
//#endregion
|
|
36
44
|
export { ProjectRoot, ProjectRootNotFoundError, findProjectRoot, findProjectRootFrom, layer };
|
|
37
45
|
|
|
38
46
|
//# sourceMappingURL=ProjectRoot.mjs.map
|
package/dist/ProjectRoot.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProjectRoot.mjs","names":[],"sources":["../src/ProjectRoot.ts"],"sourcesContent":["import * as NodeFileSystem from \"@effect/platform-node/NodeFileSystem\";\nimport * as Array from \"effect/Array\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\n\nexport class ProjectRoot extends Context.Service<\n ProjectRoot,\n { readonly get: Effect.Effect<string> }\n>()(\"@confect/cli/ProjectRoot\") {\n static readonly get = ProjectRoot.use((service) => service.get);\n}\n\nexport const findProjectRootFrom = Effect.fnUntraced(function* (\n directory: string,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n\n const startDir = path.resolve(directory);\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 yield* Effect.fromOption(
|
|
1
|
+
{"version":3,"file":"ProjectRoot.mjs","names":[],"sources":["../src/ProjectRoot.ts"],"sourcesContent":["import * as NodeFileSystem from \"@effect/platform-node/NodeFileSystem\";\nimport * as Array from \"effect/Array\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\n\nexport class ProjectRoot extends Context.Service<\n ProjectRoot,\n { readonly get: Effect.Effect<string> }\n>()(\"@confect/cli/ProjectRoot\") {\n static readonly get = ProjectRoot.use((service) => service.get);\n}\n\n/**\n * @internal\n */\nexport const findProjectRootFrom = Effect.fnUntraced(function* (\n directory: string,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n\n const startDir = path.resolve(directory);\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 yield* Effect.fromOption(projectRoot, () =>\n ProjectRootNotFoundError.make(),\n );\n});\n\n/**\n * @internal\n */\nexport const findProjectRoot = findProjectRootFrom(\".\");\n\n/**\n * @internal\n */\nexport const layer = Layer.effect(\n ProjectRoot,\n Effect.gen(function* () {\n const projectRoot = yield* findProjectRoot;\n\n const ref = yield* Ref.make<string>(projectRoot);\n\n return { get: Ref.get(ref) } as const;\n }),\n).pipe(Layer.provide(NodeFileSystem.layer));\n\nexport class ProjectRootNotFoundError extends Schema.TaggedError<\n ProjectRootNotFoundError,\n { readonly brand: unique symbol }\n>()(\"ProjectRootNotFoundError\", {}) {\n override get message(): string {\n return \"Could not find project root (no 'package.json' found)\";\n }\n}\n"],"mappings":";;;;;;;;;;;AAWA,IAAa,cAAb,MAAa,oBAAoB,QAAQ,QAGvC,CAAC,CAAC,0BAA0B,CAAC,CAAC;CAC9B,OAAgB,MAAM,YAAY,KAAK,YAAY,QAAQ,GAAG;AAChE;;;;AAKA,MAAa,sBAAsB,OAAO,WAAW,WACnD,WACA;CACA,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,OAAO,OAAO,KAAK;CAEzB,MAAM,WAAW,KAAK,QAAQ,SAAS;CACvC,MAAM,OAAO,KAAK,MAAM,QAAQ,CAAC,CAAC;CAElC,MAAM,cAAc,MAAM,OAAO,WAAW,QAC1C,QAAQ,OACJ,OAAO,KAAK,IACZ,OAAO,KAAK,CAAC,KAAK,KAAK,QAAQ,GAAG,CAAC,CAAU,CACnD;CAEA,MAAM,cAAc,OAAO,OAAO,UAAU,cAAc,QACxD,GAAG,OAAO,KAAK,KAAK,KAAK,cAAc,CAAC,CAC1C;CAEA,OAAO,OAAO,OAAO,WAAW,mBAC9B,yBAAyB,KAAK,CAChC;AACF,CAAC;;;;AAKD,MAAa,kBAAkB,oBAAoB,GAAG;;;;AAKtD,MAAa,QAAQ,MAAM,OACzB,aACA,OAAO,IAAI,aAAa;CACtB,MAAM,cAAc,OAAO;CAE3B,MAAM,MAAM,OAAO,IAAI,KAAa,WAAW;CAE/C,OAAO,EAAE,KAAK,IAAI,IAAI,GAAG,EAAE;AAC7B,CAAC,CACH,CAAC,CAAC,KAAK,MAAM,QAAQ,eAAe,KAAK,CAAC;AAE1C,IAAa,2BAAb,cAA8C,OAAO,YAGnD,CAAC,CAAC,4BAA4B,CAAC,CAAC,CAAC,CAAC;CAClC,IAAa,UAAkB;EAC7B,OAAO;CACT;AACF"}
|
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
import * as Array from "effect/Array";
|
|
2
2
|
import * as Schema from "effect/Schema";
|
|
3
3
|
import * as String from "effect/String";
|
|
4
|
-
|
|
4
|
+
// src/RelativeModulePath.ts
|
|
5
5
|
const RelativeModulePath = Schema.String.check(Schema.makeFilter((value) => !/^[A-Za-z]:/.test(value) && !String.includes("\0")(value) && Array.every(String.split(value, /[/\\]/), (segment) => String.isNonEmpty(segment) && segment !== "." && segment !== ".."))).pipe(Schema.brand("@confect/cli/RelativeModulePath"));
|
|
6
6
|
const withSuffix = (suffix) => RelativeModulePath.check(Schema.makeFilter((value) => {
|
|
7
7
|
const filename = Array.lastNonEmpty(String.split(value, /[/\\]/));
|
|
8
8
|
return String.endsWith(suffix)(filename) && filename.length > suffix.length;
|
|
9
9
|
}));
|
|
10
|
-
//#endregion
|
|
11
10
|
export { RelativeModulePath, withSuffix };
|
|
12
11
|
|
|
13
12
|
//# sourceMappingURL=RelativeModulePath.mjs.map
|
package/dist/Remove.mjs
CHANGED
|
@@ -2,7 +2,7 @@ import { RemoveBusyError } from "./CodegenError.mjs";
|
|
|
2
2
|
import * as Effect from "effect/Effect";
|
|
3
3
|
import * as FileSystem from "effect/FileSystem";
|
|
4
4
|
import * as Schedule from "effect/Schedule";
|
|
5
|
-
|
|
5
|
+
// src/Remove.ts
|
|
6
6
|
const MAX_ATTEMPTS = 4;
|
|
7
7
|
const remove = Effect.fn("Remove.remove")(function* (path) {
|
|
8
8
|
yield* (yield* FileSystem.FileSystem).remove(path, {
|
|
@@ -12,13 +12,12 @@ const remove = Effect.fn("Remove.remove")(function* (path) {
|
|
|
12
12
|
while: (error) => error.reason._tag === "Busy",
|
|
13
13
|
times: 3,
|
|
14
14
|
schedule: Schedule.exponential("25 millis")
|
|
15
|
-
}), Effect.mapError((error) => error.reason._tag === "Busy" ?
|
|
15
|
+
}), Effect.mapError((error) => error.reason._tag === "Busy" ? RemoveBusyError.make({
|
|
16
16
|
path,
|
|
17
17
|
attempts: MAX_ATTEMPTS,
|
|
18
18
|
cause: error
|
|
19
19
|
}) : error));
|
|
20
20
|
});
|
|
21
|
-
//#endregion
|
|
22
21
|
export { remove };
|
|
23
22
|
|
|
24
23
|
//# sourceMappingURL=Remove.mjs.map
|
package/dist/Remove.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Remove.mjs","names":[],"sources":["../src/Remove.ts"],"sourcesContent":["import * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Schedule from \"effect/Schedule\";\nimport { RemoveBusyError } from \"./CodegenError.js\";\n\nconst MAX_ATTEMPTS = 4;\n\nexport const remove = Effect.fn(\"Remove.remove\")(function* (path: string) {\n const fs = yield* FileSystem.FileSystem;\n yield* fs.remove(path, { recursive: true, force: true }).pipe(\n Effect.retry({\n while: (error) => error.reason._tag === \"Busy\",\n times: MAX_ATTEMPTS - 1,\n schedule: Schedule.exponential(\"25 millis\"),\n }),\n Effect.mapError((error) =>\n error.reason._tag === \"Busy\"\n ?
|
|
1
|
+
{"version":3,"file":"Remove.mjs","names":[],"sources":["../src/Remove.ts"],"sourcesContent":["import * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Schedule from \"effect/Schedule\";\nimport { RemoveBusyError } from \"./CodegenError.js\";\n\nconst MAX_ATTEMPTS = 4;\n\nexport const remove = Effect.fn(\"Remove.remove\")(function* (path: string) {\n const fs = yield* FileSystem.FileSystem;\n yield* fs.remove(path, { recursive: true, force: true }).pipe(\n Effect.retry({\n while: (error) => error.reason._tag === \"Busy\",\n times: MAX_ATTEMPTS - 1,\n schedule: Schedule.exponential(\"25 millis\"),\n }),\n Effect.mapError((error) =>\n error.reason._tag === \"Busy\"\n ? RemoveBusyError.make({ path, attempts: MAX_ATTEMPTS, cause: error })\n : error,\n ),\n );\n});\n"],"mappings":";;;;;AAKA,MAAM,eAAe;AAErB,MAAa,SAAS,OAAO,GAAG,eAAe,CAAC,CAAC,WAAW,MAAc;CAExE,QAAO,OADW,WAAW,WAAA,CACnB,OAAO,MAAM;EAAE,WAAW;EAAM,OAAO;CAAK,CAAC,CAAC,CAAC,KACvD,OAAO,MAAM;EACX,QAAQ,UAAU,MAAM,OAAO,SAAS;EACxC,OAAO;EACP,UAAU,SAAS,YAAY,WAAW;CAC5C,CAAC,GACD,OAAO,UAAU,UACf,MAAM,OAAO,SAAS,SAClB,gBAAgB,KAAK;EAAE;EAAM,UAAU;EAAc,OAAO;CAAM,CAAC,IACnE,KACN,CACF;AACF,CAAC"}
|
package/dist/RestoreWatcher.mjs
CHANGED
|
@@ -3,7 +3,7 @@ import * as Cause from "effect/Cause";
|
|
|
3
3
|
import * as Scope from "effect/Scope";
|
|
4
4
|
import * as Deferred from "effect/Deferred";
|
|
5
5
|
import * as Exit from "effect/Exit";
|
|
6
|
-
|
|
6
|
+
// src/RestoreWatcher.ts
|
|
7
7
|
/**
|
|
8
8
|
* Run a directory watch that a restore can pause: Windows refuses to remove a
|
|
9
9
|
* directory while a recursive watch holds it open.
|
|
@@ -25,7 +25,6 @@ const make = Effect.fnUntraced(function* (watch) {
|
|
|
25
25
|
}))))
|
|
26
26
|
};
|
|
27
27
|
});
|
|
28
|
-
//#endregion
|
|
29
28
|
export { make };
|
|
30
29
|
|
|
31
30
|
//# sourceMappingURL=RestoreWatcher.mjs.map
|
package/dist/Rollback.mjs
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import { logFileRemoved, logWarn } from "./log.mjs";
|
|
2
1
|
import { ComponentNodeGroupError, logCodegenError } from "./CodegenError.mjs";
|
|
3
|
-
import { ConvexDirectory } from "./ConvexDirectory.mjs";
|
|
4
2
|
import { ConfectDirectory } from "./ConfectDirectory.mjs";
|
|
5
3
|
import { CONVEX_CONFIG_FILENAME } from "./ConvexConfig.mjs";
|
|
4
|
+
import { ConvexDirectory } from "./ConvexDirectory.mjs";
|
|
5
|
+
import { logFileRemoved, logWarn } from "./log.mjs";
|
|
6
6
|
import { remove } from "./Remove.mjs";
|
|
7
7
|
import * as Effect from "effect/Effect";
|
|
8
8
|
import * as FileSystem from "effect/FileSystem";
|
|
9
9
|
import * as Path from "effect/Path";
|
|
10
10
|
import * as Schema from "effect/Schema";
|
|
11
|
-
|
|
11
|
+
// src/Rollback.ts
|
|
12
12
|
const isNodeGroupRejection = Schema.is(ComponentNodeGroupError);
|
|
13
13
|
/**
|
|
14
14
|
* Keep a component's previous generated output when generation rejects a Node
|
|
@@ -21,8 +21,10 @@ const preserveComponentOutput = (generation, duringRestore = Effect.void) => Eff
|
|
|
21
21
|
const fs = yield* FileSystem.FileSystem;
|
|
22
22
|
const path = yield* Path.Path;
|
|
23
23
|
const backupDirectory = yield* fs.makeTempDirectoryScoped();
|
|
24
|
-
const
|
|
25
|
-
const
|
|
24
|
+
const convexDirectory = yield* ConvexDirectory.get;
|
|
25
|
+
const configPath = path.join(convexDirectory, CONVEX_CONFIG_FILENAME);
|
|
26
|
+
const confectDirectory = yield* ConfectDirectory.get;
|
|
27
|
+
const snapshots = yield* Effect.forEach([path.join(confectDirectory, "_generated"), configPath], Effect.fnUntraced(function* (original, index) {
|
|
26
28
|
const backup = path.join(backupDirectory, String(index));
|
|
27
29
|
const existed = yield* fs.exists(original);
|
|
28
30
|
if (existed) yield* fs.copy(original, backup);
|
|
@@ -44,7 +46,6 @@ const preserveComponentOutput = (generation, duringRestore = Effect.void) => Eff
|
|
|
44
46
|
}).pipe(Effect.scoped, Effect.tapError(() => logCodegenError(rejection)));
|
|
45
47
|
return yield* generation.pipe(Effect.tapError((error) => isNodeGroupRejection(error) ? restore(error) : Effect.void));
|
|
46
48
|
}).pipe(Effect.scoped);
|
|
47
|
-
//#endregion
|
|
48
49
|
export { preserveComponentOutput };
|
|
49
50
|
|
|
50
51
|
//# sourceMappingURL=Rollback.mjs.map
|
package/dist/Rollback.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Rollback.mjs","names":[],"sources":["../src/Rollback.ts"],"sourcesContent":["import * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport type * as Scope from \"effect/Scope\";\nimport { ComponentNodeGroupError, logCodegenError } from \"./CodegenError.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport { CONVEX_CONFIG_FILENAME } from \"./ConvexConfig.js\";\nimport { ConvexDirectory } from \"./ConvexDirectory.js\";\nimport { logFileRemoved, logWarn } from \"./log.js\";\nimport { remove } from \"./Remove.js\";\n\nconst isNodeGroupRejection = Schema.is(ComponentNodeGroupError);\n\n/**\n * Keep a component's previous generated output when generation rejects a Node\n * group. Specs can import bootstrap output, so generation writes it before\n * their runtimes are known. `duringRestore` pauses whatever watches the output\n * while it is replaced.\n */\nexport const preserveComponentOutput = <A, E, R>(\n generation: Effect.Effect<A, E, R>,\n duringRestore: Effect.Effect<void, never, Scope.Scope> = Effect.void,\n) =>\n Effect.gen(function* () {\n if ((yield* ConvexDirectory.target).kind === \"app\")\n return yield* generation;\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const backupDirectory = yield* fs.makeTempDirectoryScoped();\n const configPath = path.join(
|
|
1
|
+
{"version":3,"file":"Rollback.mjs","names":[],"sources":["../src/Rollback.ts"],"sourcesContent":["import * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport type * as Scope from \"effect/Scope\";\nimport { ComponentNodeGroupError, logCodegenError } from \"./CodegenError.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport { CONVEX_CONFIG_FILENAME } from \"./ConvexConfig.js\";\nimport { ConvexDirectory } from \"./ConvexDirectory.js\";\nimport { logFileRemoved, logWarn } from \"./log.js\";\nimport { remove } from \"./Remove.js\";\n\nconst isNodeGroupRejection = Schema.is(ComponentNodeGroupError);\n\n/**\n * Keep a component's previous generated output when generation rejects a Node\n * group. Specs can import bootstrap output, so generation writes it before\n * their runtimes are known. `duringRestore` pauses whatever watches the output\n * while it is replaced.\n */\nexport const preserveComponentOutput = <A, E, R>(\n generation: Effect.Effect<A, E, R>,\n duringRestore: Effect.Effect<void, never, Scope.Scope> = Effect.void,\n) =>\n Effect.gen(function* () {\n if ((yield* ConvexDirectory.target).kind === \"app\")\n return yield* generation;\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const backupDirectory = yield* fs.makeTempDirectoryScoped();\n const convexDirectory = yield* ConvexDirectory.get;\n const configPath = path.join(convexDirectory, CONVEX_CONFIG_FILENAME);\n const confectDirectory = yield* ConfectDirectory.get;\n const snapshots = yield* Effect.forEach(\n [path.join(confectDirectory, \"_generated\"), configPath],\n Effect.fnUntraced(function* (original, index) {\n const backup = path.join(backupDirectory, String(index));\n const existed = yield* fs.exists(original);\n if (existed) yield* fs.copy(original, backup);\n return { original, backup, existed };\n }),\n );\n const restore = (rejection: ComponentNodeGroupError) =>\n Effect.gen(function* () {\n yield* duringRestore;\n yield* Effect.forEach(snapshots, ({ original, backup, existed }) =>\n Effect.gen(function* () {\n if (\n existed &&\n original === configPath &&\n (yield* fs.exists(original)) &&\n (yield* fs.readFileString(original)) ===\n (yield* fs.readFileString(backup))\n ) {\n return;\n }\n if (yield* fs.exists(original)) {\n yield* remove(original);\n }\n if (existed) yield* fs.copy(backup, original);\n else yield* logFileRemoved(original);\n }),\n );\n yield* logWarn(\n \"Restored generated output after rejecting the Node group.\",\n );\n }).pipe(\n Effect.scoped,\n Effect.tapError(() => logCodegenError(rejection)),\n );\n return yield* generation.pipe(\n Effect.tapError((error) =>\n isNodeGroupRejection(error) ? restore(error) : Effect.void,\n ),\n );\n }).pipe(Effect.scoped);\n"],"mappings":";;;;;;;;;;;AAYA,MAAM,uBAAuB,OAAO,GAAG,uBAAuB;;;;;;;AAQ9D,MAAa,2BACX,YACA,gBAAyD,OAAO,SAEhE,OAAO,IAAI,aAAa;CACtB,KAAK,OAAO,gBAAgB,OAAA,CAAQ,SAAS,OAC3C,OAAO,OAAO;CAChB,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,kBAAkB,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