@confect/cli 8.0.0 → 9.0.0-next.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.
@@ -0,0 +1,317 @@
1
+ import { GroupSpec, Registry } from "@confect/core";
2
+ import * as GroupImpl from "@confect/server/GroupImpl";
3
+ import { FileSystem, Path } from "@effect/platform";
4
+ import type { Context } from "effect";
5
+ import { Array, Effect, Layer, Option, Ref, String } from "effect";
6
+ import { fromBundlerError } from "./BuildError";
7
+ import * as Bundler from "./Bundler";
8
+ import {
9
+ ImplMissingDefaultLayerError,
10
+ ImplMissingFunctionsError,
11
+ ImplMissingSpecImportError,
12
+ ImplNotFinalizedError,
13
+ SpecMissingDefaultGroupSpecError,
14
+ SpecRuntimeMismatchError,
15
+ } from "./CodegenError";
16
+ import { ConfectDirectory } from "./ConfectDirectory";
17
+ import { removePathExtension } from "./utils";
18
+
19
+ export interface LeafModule {
20
+ readonly relativePath: string;
21
+ readonly pathSegments: readonly [string, ...string[]];
22
+ readonly groupPathDot: string;
23
+ readonly registryGroupPathDot: string;
24
+ readonly exportName: string;
25
+ readonly runtime: "Convex" | "Node";
26
+ readonly specImportPath: string;
27
+ }
28
+
29
+ export const SPEC_SUFFIX = ".spec.ts";
30
+ export const IMPL_SUFFIX = ".impl.ts";
31
+
32
+ const swapModuleSuffix = (
33
+ relativePath: string,
34
+ fromSuffix: string,
35
+ toSuffix: string,
36
+ ) =>
37
+ Effect.gen(function* () {
38
+ const path = yield* Path.Path;
39
+ const { dir, name, ext } = path.parse(relativePath);
40
+ if (ext !== ".ts" || !name.endsWith(fromSuffix.slice(0, -".ts".length))) {
41
+ return relativePath;
42
+ }
43
+
44
+ const stem = name.slice(0, -fromSuffix.slice(0, -".ts".length).length);
45
+ const nextName = `${stem}${toSuffix.slice(0, -".ts".length)}`;
46
+ return dir.length > 0
47
+ ? path.join(dir, `${nextName}${ext}`)
48
+ : `${nextName}${ext}`;
49
+ });
50
+
51
+ export const isLeafSpecPath = (relativePath: string) =>
52
+ relativePath.endsWith(SPEC_SUFFIX);
53
+
54
+ export const isLeafImplPath = (relativePath: string) =>
55
+ relativePath.endsWith(IMPL_SUFFIX);
56
+
57
+ export const exportNameFromModulePath = (relativePath: string) =>
58
+ Effect.gen(function* () {
59
+ const path = yield* Path.Path;
60
+ const { name, ext } = path.parse(relativePath);
61
+ if (ext !== ".ts") {
62
+ return name;
63
+ }
64
+ return name.endsWith(".spec") ? name.slice(0, -".spec".length) : name;
65
+ });
66
+
67
+ export const groupPathFromRelativeModulePath = (relativePath: string) =>
68
+ Effect.gen(function* () {
69
+ const path = yield* Path.Path;
70
+ const { dir, name, ext } = path.parse(relativePath);
71
+ const stem =
72
+ ext === ".ts" && name.endsWith(".spec")
73
+ ? name.slice(0, -".spec".length)
74
+ : name;
75
+ const dirSegments = Array.filter(
76
+ String.split(dir, path.sep),
77
+ String.isNonEmpty,
78
+ );
79
+ const pathSegments = Array.append(dirSegments, stem) as [
80
+ string,
81
+ ...string[],
82
+ ];
83
+ return {
84
+ pathSegments,
85
+ groupPathDot: Array.join(pathSegments, "."),
86
+ };
87
+ });
88
+
89
+ export const specImportPathFromGenerated = (specRelativePath: string) =>
90
+ Effect.gen(function* () {
91
+ const withoutExt = yield* removePathExtension(specRelativePath);
92
+ return `../${withoutExt}`;
93
+ });
94
+
95
+ export const specPathForImpl = (implRelativePath: string) =>
96
+ swapModuleSuffix(implRelativePath, IMPL_SUFFIX, SPEC_SUFFIX);
97
+
98
+ export const implPathForSpec = (specRelativePath: string) =>
99
+ swapModuleSuffix(specRelativePath, SPEC_SUFFIX, IMPL_SUFFIX);
100
+
101
+ export const isNodeLeafModule = (relativePath: string) =>
102
+ relativePath.startsWith("node/") || relativePath.startsWith("node\\");
103
+
104
+ export const toNodeRegistryLeaf = (leaf: LeafModule): LeafModule => ({
105
+ ...leaf,
106
+ pathSegments: [leaf.exportName],
107
+ groupPathDot: leaf.exportName,
108
+ });
109
+
110
+ export const registeredFunctionsRelativePath = (leaf: LeafModule) =>
111
+ Effect.gen(function* () {
112
+ const path = yield* Path.Path;
113
+ return (
114
+ path.join(
115
+ "registeredFunctions",
116
+ ...leaf.pathSegments.slice(leaf.runtime === "Node" ? 1 : 0),
117
+ ) + ".ts"
118
+ );
119
+ });
120
+
121
+ export const discoverLeafSpecFiles = Effect.gen(function* () {
122
+ const fs = yield* FileSystem.FileSystem;
123
+ const path = yield* Path.Path;
124
+ const confectDirectory = yield* ConfectDirectory.get;
125
+
126
+ const excludedDirs = new Set(["_generated", "tables"]);
127
+ const excludedFiles = new Set(["nodeSpec.ts", "spec.ts"]);
128
+
129
+ const allPaths = yield* fs.readDirectory(confectDirectory, {
130
+ recursive: true,
131
+ });
132
+
133
+ return Array.filter(allPaths, (relativePath) => {
134
+ if (!isLeafSpecPath(relativePath)) {
135
+ return false;
136
+ }
137
+
138
+ if (excludedFiles.has(relativePath)) {
139
+ return false;
140
+ }
141
+
142
+ const segments = String.split(relativePath, path.sep);
143
+ return !Array.some(segments, (segment) => excludedDirs.has(segment));
144
+ });
145
+ });
146
+
147
+ export const discoverLeafImplFiles = Effect.gen(function* () {
148
+ const fs = yield* FileSystem.FileSystem;
149
+ const path = yield* Path.Path;
150
+ const confectDirectory = yield* ConfectDirectory.get;
151
+
152
+ const excludedDirs = new Set(["_generated", "tables"]);
153
+
154
+ const allPaths = yield* fs.readDirectory(confectDirectory, {
155
+ recursive: true,
156
+ });
157
+
158
+ return Array.filter(allPaths, (relativePath) => {
159
+ if (!isLeafImplPath(relativePath)) {
160
+ return false;
161
+ }
162
+
163
+ const segments = String.split(relativePath, path.sep);
164
+ return !Array.some(segments, (segment) => excludedDirs.has(segment));
165
+ });
166
+ });
167
+
168
+ export const toLeafModule = (specRelativePath: string) =>
169
+ Effect.gen(function* () {
170
+ const exportName = yield* exportNameFromModulePath(specRelativePath);
171
+ const { pathSegments, groupPathDot } =
172
+ yield* groupPathFromRelativeModulePath(specRelativePath);
173
+ const specImportPath = yield* specImportPathFromGenerated(specRelativePath);
174
+ const runtime = isNodeLeafModule(specRelativePath) ? "Node" : "Convex";
175
+
176
+ return {
177
+ relativePath: specRelativePath,
178
+ pathSegments,
179
+ groupPathDot,
180
+ exportName,
181
+ runtime,
182
+ registryGroupPathDot: runtime === "Node" ? exportName : groupPathDot,
183
+ specImportPath,
184
+ } satisfies LeafModule;
185
+ });
186
+
187
+ const absoluteModulePath = (relativePath: string) =>
188
+ Effect.gen(function* () {
189
+ const confectDirectory = yield* ConfectDirectory.get;
190
+ const path = yield* Path.Path;
191
+ return path.resolve(confectDirectory, relativePath);
192
+ });
193
+
194
+ /**
195
+ * Validate that the leaf's spec file default-exports a `GroupSpec` whose
196
+ * runtime matches the leaf's location (`Convex` for files outside
197
+ * `confect/node/`, `Node` for files inside it). Returns the validated
198
+ * `GroupSpec` so callers can avoid re-bundling for later inspection (e.g.
199
+ * parent/child name-collision checks at codegen time).
200
+ */
201
+ export const validateSpec = (leaf: LeafModule) =>
202
+ Effect.gen(function* () {
203
+ const absolutePath = yield* absoluteModulePath(leaf.relativePath);
204
+ const { module } = yield* Bundler.bundle(absolutePath).pipe(
205
+ Effect.mapError((error) => fromBundlerError(leaf.relativePath, error)),
206
+ );
207
+
208
+ const groupSpec = module.default;
209
+
210
+ if (!GroupSpec.isGroupSpec(groupSpec)) {
211
+ return yield* new SpecMissingDefaultGroupSpecError({
212
+ specPath: leaf.relativePath,
213
+ });
214
+ }
215
+
216
+ if (groupSpec.runtime !== leaf.runtime) {
217
+ return yield* new SpecRuntimeMismatchError({
218
+ specPath: leaf.relativePath,
219
+ expectedRuntime: leaf.runtime,
220
+ actualRuntime: groupSpec.runtime,
221
+ });
222
+ }
223
+
224
+ return groupSpec;
225
+ });
226
+
227
+ /**
228
+ * Walk the built `Context` for a `Finalized` `GroupImpl` service value. The
229
+ * lookup is value-shaped (via `GroupImpl.isFinalizedGroupImpl`) so we don't
230
+ * need to know the group's path up front to construct a typed tag for it.
231
+ */
232
+ const findFinalizedGroupImpl = <S>(
233
+ context: Context.Context<S>,
234
+ ): Option.Option<GroupImpl.AnyFinalized> =>
235
+ Array.findFirst(context.unsafeMap.values(), GroupImpl.isFinalizedGroupImpl);
236
+
237
+ /**
238
+ * Build the impl layer with a fresh `Registry` so each validation is
239
+ * isolated from prior validations' `FunctionImpl.make` writes. The CLI no
240
+ * longer reads the registry directly — `GroupImpl.finalize` snapshots the
241
+ * registered function names onto the produced `Finalized` `GroupImpl`
242
+ * service value — but a fresh `Ref` is still required because the default
243
+ * `Context.Reference` is cached globally and would otherwise accumulate
244
+ * items across impls.
245
+ */
246
+ const buildImplLayer = (implLayer: Layer.Layer<unknown>) =>
247
+ Effect.gen(function* () {
248
+ const registry = Ref.unsafeMake<Registry.RegistryItems>({});
249
+ return yield* Layer.build(
250
+ implLayer as Layer.Layer<unknown, never, never>,
251
+ ).pipe(Effect.provideService(Registry.Registry, registry));
252
+ }).pipe(Effect.scoped);
253
+
254
+ /**
255
+ * Validate that the leaf's sibling impl file imports the spec, default-exports
256
+ * a finalized `GroupImpl` layer, and provides a `FunctionImpl` for every
257
+ * function declared by the spec.
258
+ */
259
+ export const validateImpl = (leaf: LeafModule) =>
260
+ Effect.gen(function* () {
261
+ const implRelativePath = yield* implPathForSpec(leaf.relativePath);
262
+ const implAbsolutePath = yield* absoluteModulePath(implRelativePath);
263
+ const specAbsolutePath = yield* absoluteModulePath(leaf.relativePath);
264
+
265
+ const bundled = yield* Bundler.bundle(implAbsolutePath).pipe(
266
+ Effect.mapError((error) => fromBundlerError(implRelativePath, error)),
267
+ );
268
+
269
+ if (
270
+ !(yield* Bundler.directlyImports(
271
+ bundled,
272
+ implAbsolutePath,
273
+ specAbsolutePath,
274
+ ))
275
+ ) {
276
+ return yield* new ImplMissingSpecImportError({
277
+ implPath: implRelativePath,
278
+ expectedSpecPath: leaf.relativePath,
279
+ });
280
+ }
281
+
282
+ if (!Layer.isLayer(bundled.module.default)) {
283
+ return yield* new ImplMissingDefaultLayerError({
284
+ implPath: implRelativePath,
285
+ });
286
+ }
287
+
288
+ const { module: specModule } = yield* Bundler.bundle(specAbsolutePath).pipe(
289
+ Effect.mapError((error) => fromBundlerError(leaf.relativePath, error)),
290
+ );
291
+ const groupSpec = specModule.default as GroupSpec.AnyWithProps;
292
+ const expectedFunctionNames = Object.keys(groupSpec.functions);
293
+
294
+ const context = yield* buildImplLayer(
295
+ bundled.module.default as Layer.Layer<unknown>,
296
+ );
297
+ const finalizedGroupImpl = yield* Option.match(
298
+ findFinalizedGroupImpl(context),
299
+ {
300
+ onNone: () => new ImplNotFinalizedError({ implPath: implRelativePath }),
301
+ onSome: Effect.succeed,
302
+ },
303
+ );
304
+
305
+ const registeredSet = new Set(finalizedGroupImpl.registeredFunctionNames);
306
+ const missing = expectedFunctionNames.filter(
307
+ (name) => !registeredSet.has(name),
308
+ );
309
+
310
+ if (missing.length > 0) {
311
+ return yield* new ImplMissingFunctionsError({
312
+ implPath: implRelativePath,
313
+ groupPath: finalizedGroupImpl.groupPath,
314
+ missingFunctionNames: missing,
315
+ });
316
+ }
317
+ });
@@ -0,0 +1,82 @@
1
+ import type { LeafModule } from "./LeafModule";
2
+ import { Array, Option, Order, pipe, Record } from "effect";
3
+
4
+ export interface SpecImportBinding {
5
+ readonly importPath: string;
6
+ readonly exportName: string;
7
+ }
8
+
9
+ export interface SpecAssemblyNode {
10
+ readonly segment: string;
11
+ readonly importBinding: Option.Option<SpecImportBinding>;
12
+ readonly children: ReadonlyArray<SpecAssemblyNode>;
13
+ }
14
+
15
+ const importBindingFromLeaf = (leaf: LeafModule): SpecImportBinding => ({
16
+ importPath: leaf.specImportPath,
17
+ exportName: leaf.exportName,
18
+ });
19
+
20
+ const assemblyNodesAtDepth = (
21
+ leaves: ReadonlyArray<LeafModule>,
22
+ depth: number,
23
+ ): ReadonlyArray<SpecAssemblyNode> =>
24
+ pipe(
25
+ Array.groupBy(leaves, (leaf) => leaf.pathSegments[depth]!),
26
+ Record.toEntries,
27
+ Array.sortBy(Order.mapInput(Order.string, ([segment]) => segment)),
28
+ Array.map(([segment, groupLeaves]) => {
29
+ const terminal = Array.findFirst(
30
+ groupLeaves,
31
+ (leaf) => leaf.pathSegments.length === depth + 1,
32
+ );
33
+ const descendants = Array.filter(
34
+ groupLeaves,
35
+ (leaf) => leaf.pathSegments.length > depth + 1,
36
+ );
37
+ return {
38
+ segment,
39
+ importBinding: Option.map(terminal, importBindingFromLeaf),
40
+ children: assemblyNodesAtDepth(descendants, depth + 1),
41
+ };
42
+ }),
43
+ );
44
+
45
+ export const assemblyNodesFromLeaves = (
46
+ leaves: ReadonlyArray<LeafModule>,
47
+ ): ReadonlyArray<SpecAssemblyNode> => assemblyNodesAtDepth(leaves, 0);
48
+
49
+ export const partitionByRuntime = (
50
+ leaves: ReadonlyArray<LeafModule>,
51
+ ): {
52
+ readonly convex: ReadonlyArray<LeafModule>;
53
+ readonly node: ReadonlyArray<LeafModule>;
54
+ } => {
55
+ const [node, convex] = Array.partition(
56
+ leaves,
57
+ (leaf) => leaf.runtime === "Convex",
58
+ );
59
+ return { convex, node };
60
+ };
61
+
62
+ const importBindingsForNode = (
63
+ node: SpecAssemblyNode,
64
+ ): ReadonlyArray<SpecImportBinding> =>
65
+ pipe(node.children, Array.flatMap(importBindingsForNode), (childBindings) =>
66
+ Option.match(node.importBinding, {
67
+ onNone: () => childBindings,
68
+ onSome: (binding) => Array.prepend(childBindings, binding),
69
+ }),
70
+ );
71
+
72
+ export const collectImportBindings = (
73
+ nodes: ReadonlyArray<SpecAssemblyNode>,
74
+ ): ReadonlyArray<SpecImportBinding> =>
75
+ pipe(
76
+ Array.flatMap(nodes, importBindingsForNode),
77
+ (bindings) =>
78
+ Record.fromIterableBy(bindings, (binding) => binding.exportName),
79
+ Record.toEntries,
80
+ Array.sortBy(Order.mapInput(Order.string, ([exportName]) => exportName)),
81
+ Array.map(([, binding]) => binding),
82
+ );