@gaganref/confect-cli 10.3.1-fork.9 → 10.3.1-fork.90
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Bundler.mjs +22 -1
- package/dist/Bundler.mjs.map +1 -1
- package/dist/CodegenError.mjs +16 -1
- package/dist/CodegenError.mjs.map +1 -1
- package/dist/Declaration.mjs +139 -26
- package/dist/Declaration.mjs.map +1 -1
- package/dist/EntryPoint.mjs +2 -0
- package/dist/EntryPoint.mjs.map +1 -1
- package/dist/Evaluation.mjs +39 -13
- package/dist/Evaluation.mjs.map +1 -1
- package/dist/EvaluationWorker.mjs +13 -1
- package/dist/EvaluationWorker.mjs.map +1 -1
- package/dist/FunctionModule.mjs +109 -24
- package/dist/FunctionModule.mjs.map +1 -1
- package/dist/LeafModule.mjs +56 -23
- package/dist/LeafModule.mjs.map +1 -1
- package/dist/ManifestSections.mjs +161 -0
- package/dist/ManifestSections.mjs.map +1 -0
- package/dist/SectionFiles.mjs +264 -0
- package/dist/SectionFiles.mjs.map +1 -0
- package/dist/SyncState.mjs +1 -1
- package/dist/SyncState.mjs.map +1 -1
- package/dist/TableModule.mjs +2 -1
- package/dist/TableModule.mjs.map +1 -1
- package/dist/Watcher.mjs +13 -7
- package/dist/Watcher.mjs.map +1 -1
- package/dist/confect/codegen.mjs +124 -42
- package/dist/confect/codegen.mjs.map +1 -1
- package/dist/confect/declaration.mjs +160 -20
- package/dist/confect/declaration.mjs.map +1 -1
- package/dist/confect/dev.mjs +9 -4
- package/dist/confect/dev.mjs.map +1 -1
- package/dist/templates.mjs +74 -43
- package/dist/templates.mjs.map +1 -1
- package/dist/utils.mjs +14 -1
- package/dist/utils.mjs.map +1 -1
- package/package.json +6 -5
|
@@ -15,6 +15,7 @@ import * as Schema from "effect/Schema";
|
|
|
15
15
|
import * as esbuild from "esbuild";
|
|
16
16
|
import * as Layer from "effect/Layer";
|
|
17
17
|
import * as IdScope from "@confect/core/IdScope";
|
|
18
|
+
import * as Schedule from "effect/Schedule";
|
|
18
19
|
import * as References from "effect/References";
|
|
19
20
|
import * as NodeWorkerRunner from "@effect/platform-node/NodeWorkerRunner";
|
|
20
21
|
import * as RpcServer from "effect/rpc/RpcServer";
|
|
@@ -34,12 +35,23 @@ const evaluate = (requestContext, effect) => effect.pipe(Effect.provideService(R
|
|
|
34
35
|
return Effect.fail(new EvaluationError({ diagnostic: Option.isSome(failure) && isCodegenError(failure.value) ? renderCodegenError(failure.value) : Cause.pretty(cause) }));
|
|
35
36
|
}));
|
|
36
37
|
const handlers = requests.toLayer({
|
|
38
|
+
Ready: () => Effect.void,
|
|
37
39
|
Previous: (requestContext) => evaluate(requestContext, loadPreviousFunctionPaths),
|
|
38
40
|
Generate: (requestContext) => evaluate(requestContext, generateWithSnapshot.pipe(Effect.map(({ snapshot }) => snapshot))),
|
|
39
41
|
Validate: (request) => evaluate(request, validateImplFiles(request.paths)),
|
|
40
42
|
Update: (request) => evaluate(request, updateDeclarations(request.snapshot, request.declarations, request.paths))
|
|
41
43
|
});
|
|
42
|
-
|
|
44
|
+
const parentPid = process.ppid;
|
|
45
|
+
process.once("disconnect", () => process.exit(0));
|
|
46
|
+
const watchParent = Effect.sync(() => {
|
|
47
|
+
if (!process.connected || process.ppid !== parentPid) process.exit(0);
|
|
48
|
+
try {
|
|
49
|
+
process.kill(parentPid, 0);
|
|
50
|
+
} catch {
|
|
51
|
+
process.exit(0);
|
|
52
|
+
}
|
|
53
|
+
}).pipe(Effect.repeat({ schedule: Schedule.spaced("1 second") }));
|
|
54
|
+
RpcServer.layer(requests).pipe(Layer.provide(handlers), Layer.provide(NodeServices.layer), Layer.provide(RpcServer.layerProtocolWorkerRunner.pipe(Layer.provide(NodeWorkerRunner.layer))), Layer.launch, Effect.raceFirst(watchParent), Effect.ensuring(Effect.promise(() => esbuild.stop())), NodeRuntime.runMain);
|
|
43
55
|
//#endregion
|
|
44
56
|
export {};
|
|
45
57
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"EvaluationWorker.mjs","names":["CodegenError.ComponentNodeGroupError","CodegenError.isCodegenError","CodegenError.renderCodegenError"],"sources":["../src/EvaluationWorker.ts"],"sourcesContent":["import * as NodeRuntime from \"@effect/platform-node/NodeRuntime\";\nimport * as NodeServices from \"@effect/platform-node/NodeServices\";\nimport * as NodeWorkerRunner from \"@effect/platform-node/NodeWorkerRunner\";\nimport * as IdScope from \"@confect/core/IdScope\";\nimport * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as References from \"effect/References\";\nimport * as Schema from \"effect/Schema\";\nimport * as RpcServer from \"effect/rpc/RpcServer\";\nimport * as esbuild from \"esbuild\";\nimport * as CodegenError from \"./CodegenError.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport { ConvexDirectory } from \"./ConvexDirectory.js\";\nimport type { RequestContext } from \"./Evaluation.js\";\nimport { EvaluationError, requests } from \"./Evaluation.js\";\nimport { validateImplFiles } from \"./LeafModule.js\";\nimport { ProjectRoot } from \"./ProjectRoot.js\";\nimport {\n generateWithSnapshot,\n loadPreviousFunctionPaths,\n updateDeclarations,\n} from \"./confect/codegen.js\";\n\nconst evaluate = <A, E, R>(\n requestContext: RequestContext,\n effect: Effect.Effect<A, E, R>,\n) =>\n effect.pipe(\n Effect.provideService(\n References.MinimumLogLevel,\n requestContext.minimumLogLevel,\n ),\n Effect.provideService(ProjectRoot, {\n get: Effect.succeed(requestContext.projectRoot),\n }),\n Effect.provideService(ConfectDirectory, {\n get: Effect.succeed(requestContext.confectDirectory),\n }),\n Effect.provideService(ConvexDirectory, {\n get: Effect.succeed(requestContext.convexDirectory),\n target: Match.value(requestContext.target).pipe(\n Match.when({ kind: \"app\" }, () => ({\n kind: \"app\" as const,\n scope: IdScope.app,\n })),\n Match.when({ kind: \"component\" }, ({ definition }) => ({\n kind: \"component\" as const,\n scope: IdScope.component(definition),\n })),\n Match.exhaustive,\n ),\n }),\n Effect.catchCause(\n (\n cause,\n ): Effect.Effect<\n never,\n EvaluationError | CodegenError.ComponentNodeGroupError\n > => {\n const failure = Cause.findErrorOption(cause);\n if (\n Option.isSome(failure) &&\n Schema.is(CodegenError.ComponentNodeGroupError)(failure.value)\n )\n return Effect.fail(failure.value);\n return Effect.fail(\n new EvaluationError({\n diagnostic:\n Option.isSome(failure) &&\n CodegenError.isCodegenError(failure.value)\n ? CodegenError.renderCodegenError(failure.value)\n : Cause.pretty(cause),\n }),\n );\n },\n ),\n );\n\nconst handlers = requests.toLayer({\n Previous: (requestContext) =>\n evaluate(requestContext, loadPreviousFunctionPaths),\n Generate: (requestContext) =>\n evaluate(\n requestContext,\n generateWithSnapshot.pipe(Effect.map(({ snapshot }) => snapshot)),\n ),\n Validate: (request) => evaluate(request, validateImplFiles(request.paths)),\n Update: (request) =>\n evaluate(\n request,\n updateDeclarations(request.snapshot, request.declarations, request.paths),\n ),\n});\n\nRpcServer.layer(requests).pipe(\n Layer.provide(handlers),\n Layer.provide(NodeServices.layer),\n Layer.provide(\n RpcServer.layerProtocolWorkerRunner.pipe(\n Layer.provide(NodeWorkerRunner.layer),\n ),\n ),\n Layer.launch,\n Effect.ensuring(Effect.promise(() => esbuild.stop())),\n NodeRuntime.runMain,\n);\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"EvaluationWorker.mjs","names":["CodegenError.ComponentNodeGroupError","CodegenError.isCodegenError","CodegenError.renderCodegenError"],"sources":["../src/EvaluationWorker.ts"],"sourcesContent":["import * as NodeRuntime from \"@effect/platform-node/NodeRuntime\";\nimport * as NodeServices from \"@effect/platform-node/NodeServices\";\nimport * as NodeWorkerRunner from \"@effect/platform-node/NodeWorkerRunner\";\nimport * as IdScope from \"@confect/core/IdScope\";\nimport * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as References from \"effect/References\";\nimport * as Schema from \"effect/Schema\";\nimport * as Schedule from \"effect/Schedule\";\nimport * as RpcServer from \"effect/rpc/RpcServer\";\nimport * as esbuild from \"esbuild\";\nimport * as CodegenError from \"./CodegenError.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport { ConvexDirectory } from \"./ConvexDirectory.js\";\nimport type { RequestContext } from \"./Evaluation.js\";\nimport { EvaluationError, requests } from \"./Evaluation.js\";\nimport { validateImplFiles } from \"./LeafModule.js\";\nimport { ProjectRoot } from \"./ProjectRoot.js\";\nimport {\n generateWithSnapshot,\n loadPreviousFunctionPaths,\n updateDeclarations,\n} from \"./confect/codegen.js\";\n\nconst evaluate = <A, E, R>(\n requestContext: RequestContext,\n effect: Effect.Effect<A, E, R>,\n) =>\n effect.pipe(\n Effect.provideService(\n References.MinimumLogLevel,\n requestContext.minimumLogLevel,\n ),\n Effect.provideService(ProjectRoot, {\n get: Effect.succeed(requestContext.projectRoot),\n }),\n Effect.provideService(ConfectDirectory, {\n get: Effect.succeed(requestContext.confectDirectory),\n }),\n Effect.provideService(ConvexDirectory, {\n get: Effect.succeed(requestContext.convexDirectory),\n target: Match.value(requestContext.target).pipe(\n Match.when({ kind: \"app\" }, () => ({\n kind: \"app\" as const,\n scope: IdScope.app,\n })),\n Match.when({ kind: \"component\" }, ({ definition }) => ({\n kind: \"component\" as const,\n scope: IdScope.component(definition),\n })),\n Match.exhaustive,\n ),\n }),\n Effect.catchCause(\n (\n cause,\n ): Effect.Effect<\n never,\n EvaluationError | CodegenError.ComponentNodeGroupError\n > => {\n const failure = Cause.findErrorOption(cause);\n if (\n Option.isSome(failure) &&\n Schema.is(CodegenError.ComponentNodeGroupError)(failure.value)\n )\n return Effect.fail(failure.value);\n return Effect.fail(\n new EvaluationError({\n diagnostic:\n Option.isSome(failure) &&\n CodegenError.isCodegenError(failure.value)\n ? CodegenError.renderCodegenError(failure.value)\n : Cause.pretty(cause),\n }),\n );\n },\n ),\n );\n\nconst handlers = requests.toLayer({\n Ready: () => Effect.void,\n Previous: (requestContext) =>\n evaluate(requestContext, loadPreviousFunctionPaths),\n Generate: (requestContext) =>\n evaluate(\n requestContext,\n generateWithSnapshot.pipe(Effect.map(({ snapshot }) => snapshot)),\n ),\n Validate: (request) => evaluate(request, validateImplFiles(request.paths)),\n Update: (request) =>\n evaluate(\n request,\n updateDeclarations(request.snapshot, request.declarations, request.paths),\n ),\n});\n\n// Evaluators must not outlive the CLI, even when it is killed without cleanup.\nconst parentPid = process.ppid;\nprocess.once(\"disconnect\", () => process.exit(0));\nconst watchParent = Effect.sync(() => {\n if (!process.connected || process.ppid !== parentPid) process.exit(0);\n try {\n process.kill(parentPid, 0);\n } catch {\n process.exit(0);\n }\n}).pipe(Effect.repeat({ schedule: Schedule.spaced(\"1 second\") }));\n\nRpcServer.layer(requests).pipe(\n Layer.provide(handlers),\n Layer.provide(NodeServices.layer),\n Layer.provide(\n RpcServer.layerProtocolWorkerRunner.pipe(\n Layer.provide(NodeWorkerRunner.layer),\n ),\n ),\n Layer.launch,\n Effect.raceFirst(watchParent),\n Effect.ensuring(Effect.promise(() => esbuild.stop())),\n NodeRuntime.runMain,\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA2BA,MAAM,YACJ,gBACA,WAEA,OAAO,KACL,OAAO,eACL,WAAW,iBACX,eAAe,eACjB,GACA,OAAO,eAAe,aAAa,EACjC,KAAK,OAAO,QAAQ,eAAe,WAAW,EAChD,CAAC,GACD,OAAO,eAAe,kBAAkB,EACtC,KAAK,OAAO,QAAQ,eAAe,gBAAgB,EACrD,CAAC,GACD,OAAO,eAAe,iBAAiB;CACrC,KAAK,OAAO,QAAQ,eAAe,eAAe;CAClD,QAAQ,MAAM,MAAM,eAAe,MAAM,CAAC,CAAC,KACzC,MAAM,KAAK,EAAE,MAAM,MAAM,UAAU;EACjC,MAAM;EACN,OAAO,QAAQ;CACjB,EAAE,GACF,MAAM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AQ,GACtB,MAAM,QAAQ,aAAa,KAAK,GAChC,MAAM,QACJ,UAAU,0BAA0B,KAClC,MAAM,QAAQ,iBAAiB,KAAK,CACtC,CACF,GACA,MAAM,QACN,OAAO,UAAU,WAAW,GAC5B,OAAO,SAAS,OAAO,cAAc,QAAQ,KAAK,CAAC,CAAC,GACpD,YAAY,OACd"}
|
package/dist/FunctionModule.mjs
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
import { fromGroupModulePath, modulePath } from "./GroupPath.mjs";
|
|
2
|
+
import { ProjectRoot } from "./ProjectRoot.mjs";
|
|
2
3
|
import { logFileAdded, logFileModified, logFileRemoved } from "./log.mjs";
|
|
4
|
+
import { UnownedConvexEntrypointError } from "./CodegenError.mjs";
|
|
3
5
|
import { ConvexDirectory } from "./ConvexDirectory.mjs";
|
|
4
6
|
import { ConfectDirectory } from "./ConfectDirectory.mjs";
|
|
5
7
|
import { CodeBlockWriter } from "./CodeBlockWriter.mjs";
|
|
6
|
-
import {
|
|
8
|
+
import { crons, declaredHttp, http } from "./templates.mjs";
|
|
9
|
+
import { removePathIfExists, toModuleImportPath, toPosixPath } from "./utils.mjs";
|
|
7
10
|
import { GroupPaths } from "./GroupPaths.mjs";
|
|
11
|
+
import { isGenerated } from "./Declaration.mjs";
|
|
12
|
+
import { written } from "./SectionFiles.mjs";
|
|
8
13
|
import { functionPaths, plan } from "./GenerationSnapshot.mjs";
|
|
9
14
|
import * as Effect from "effect/Effect";
|
|
10
15
|
import * as FileSystem from "effect/FileSystem";
|
|
@@ -13,7 +18,96 @@ import * as Array from "effect/Array";
|
|
|
13
18
|
import { pipe } from "effect/Function";
|
|
14
19
|
import * as HashSet from "effect/HashSet";
|
|
15
20
|
import * as Match from "effect/Match";
|
|
21
|
+
import * as Schema from "effect/Schema";
|
|
16
22
|
//#region src/FunctionModule.ts
|
|
23
|
+
const RESERVED_CONVEX_TS_FILE_NAMES = /* @__PURE__ */ new Set([
|
|
24
|
+
"schema.ts",
|
|
25
|
+
"http.ts",
|
|
26
|
+
"crons.ts",
|
|
27
|
+
"auth.config.ts",
|
|
28
|
+
"convex.config.ts"
|
|
29
|
+
]);
|
|
30
|
+
const DEPLOY_MODULE = "confectDeploy.ts";
|
|
31
|
+
const getEntrypoints = Effect.gen(function* () {
|
|
32
|
+
const fs = yield* FileSystem.FileSystem;
|
|
33
|
+
const path = yield* Path.Path;
|
|
34
|
+
const convex = yield* ConvexDirectory.get;
|
|
35
|
+
const files = yield* fs.readDirectory(convex, { recursive: true });
|
|
36
|
+
const components = files.filter((file) => path.basename(file) === "convex.config.ts" && path.dirname(file) !== ".").map((file) => path.dirname(file) + path.sep);
|
|
37
|
+
return files.filter((file) => {
|
|
38
|
+
const base = path.basename(file);
|
|
39
|
+
return !file.startsWith("_generated" + path.sep) && !components.some((component) => file.startsWith(component)) && /\.(?:js|mjs|cjs|ts|tsx|mts|cts|jsx)$/.test(base) && !base.startsWith(".") && !base.startsWith("#") && (base.match(/\./g)?.length ?? 0) === 1 && base !== "schema.ts" && base !== "schema.js" && !file.includes(" ");
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
const tokenize = (source, modulePath, path) => {
|
|
43
|
+
const token = /\s+|\/\/[^\r\n]*|\/\*[\s\S]*?\*\/|"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[$A-Z_a-z][$\w]*|[{}()[\].,:;=]/y;
|
|
44
|
+
const tokens = [];
|
|
45
|
+
while (token.lastIndex < source.length) {
|
|
46
|
+
const match = token.exec(source);
|
|
47
|
+
if (match === null) return void 0;
|
|
48
|
+
const value = match[0];
|
|
49
|
+
if (/^\s|^\//.test(value)) continue;
|
|
50
|
+
if (value.startsWith("\"") || value.startsWith("'")) {
|
|
51
|
+
const literal = value.slice(1, -1);
|
|
52
|
+
tokens.push(JSON.stringify(literal.startsWith(".") ? path.resolve(path.dirname(modulePath), literal.replace(/\.js$/, "")) : literal));
|
|
53
|
+
} else tokens.push(value);
|
|
54
|
+
}
|
|
55
|
+
return tokens;
|
|
56
|
+
};
|
|
57
|
+
const encodeString = Schema.encodeSync(Schema.fromJsonString(Schema.String));
|
|
58
|
+
const matchesShape = (actual, expected) => {
|
|
59
|
+
let index = 0;
|
|
60
|
+
for (const token of expected) {
|
|
61
|
+
if (token === ";" && actual[index] !== ";") continue;
|
|
62
|
+
if (actual[index] === "," && (token === "}" || token === ")")) index++;
|
|
63
|
+
if (actual[index++] !== token) return false;
|
|
64
|
+
}
|
|
65
|
+
return index === actual.length;
|
|
66
|
+
};
|
|
67
|
+
const assertOwnedEntrypoints = Effect.gen(function* () {
|
|
68
|
+
const fs = yield* FileSystem.FileSystem;
|
|
69
|
+
const path = yield* Path.Path;
|
|
70
|
+
const convex = yield* ConvexDirectory.get;
|
|
71
|
+
const confect = yield* ConfectDirectory.get;
|
|
72
|
+
const projectRoot = yield* ProjectRoot.get;
|
|
73
|
+
const importFromConvex = (file) => toModuleImportPath(path.relative(convex, path.join(confect, file)));
|
|
74
|
+
const optional = /* @__PURE__ */ new Map([["http.ts", [
|
|
75
|
+
yield* http({ httpImportPath: yield* importFromConvex("http.ts") }),
|
|
76
|
+
yield* declaredHttp({
|
|
77
|
+
schemaImportPath: yield* importFromConvex("_generated/schema.ts"),
|
|
78
|
+
httpImportPath: yield* importFromConvex("http.ts")
|
|
79
|
+
}),
|
|
80
|
+
yield* declaredHttp({
|
|
81
|
+
schemaImportPath: yield* importFromConvex("_generated/schema.ts"),
|
|
82
|
+
httpImportPath: yield* importFromConvex("http.ts"),
|
|
83
|
+
runtimeImportPath: yield* importFromConvex("runtime.ts")
|
|
84
|
+
})
|
|
85
|
+
]], ["crons.ts", [yield* crons({ cronsImportPath: yield* importFromConvex("crons.ts") })]]]);
|
|
86
|
+
const sectionImports = new Set((yield* written).map((file) => encodeString(path.join(confect, "_generated", path.basename(file, ".ts")))));
|
|
87
|
+
const withoutSectionImports = (tokens) => tokens[0] === "import" && sectionImports.has(tokens[1] ?? "") ? withoutSectionImports(tokens.slice(tokens[2] === ";" ? 3 : 2)) : tokens;
|
|
88
|
+
const refused = [];
|
|
89
|
+
for (const relative of yield* getEntrypoints) {
|
|
90
|
+
const absolute = path.join(convex, relative);
|
|
91
|
+
const contents = yield* fs.readFileString(absolute);
|
|
92
|
+
if (relative === DEPLOY_MODULE && isGenerated(contents, [])) continue;
|
|
93
|
+
const tokens = tokenize(contents, absolute, path);
|
|
94
|
+
if (tokens !== void 0) {
|
|
95
|
+
if (optional.get(relative)?.some((template) => matchesShape(relative === "http.ts" ? withoutSectionImports(tokens) : tokens, tokenize(template, absolute, path)))) continue;
|
|
96
|
+
if (path.extname(relative) === ".ts") {
|
|
97
|
+
const names = tokens.flatMap((token, index) => token === "export" && tokens[index + 1] === "const" ? [tokens[index + 2]] : []);
|
|
98
|
+
const group = yield* fromGroupModulePath(relative);
|
|
99
|
+
const template = yield* render({
|
|
100
|
+
functionNames: names,
|
|
101
|
+
registeredFunctionsImportPath: yield* registeredFunctionsImportPathForGroup(group, absolute),
|
|
102
|
+
useNode: tokens[0] === "\"use node\""
|
|
103
|
+
});
|
|
104
|
+
if (names.length > 0 && new Set(names).size === names.length && matchesShape(tokens, tokenize(template, absolute, path))) continue;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
refused.push(toPosixPath(path, path.relative(projectRoot, absolute)));
|
|
108
|
+
}
|
|
109
|
+
if (refused.length > 0) return yield* new UnownedConvexEntrypointError({ filePaths: refused.sort() });
|
|
110
|
+
});
|
|
17
111
|
const render = ({ functionNames, registeredFunctionsImportPath, useNode = false }) => renderEffect({
|
|
18
112
|
functionNames,
|
|
19
113
|
registeredFunctionsImportPath,
|
|
@@ -41,20 +135,20 @@ const generateGroupModuleEffect = Effect.fnUntraced(function* ({ groupPath, func
|
|
|
41
135
|
const path = yield* Path.Path;
|
|
42
136
|
const convexDirectory = yield* ConvexDirectory.get;
|
|
43
137
|
const relativeModulePath = yield* modulePath(groupPath);
|
|
44
|
-
const modulePath$
|
|
45
|
-
const directoryPath = path.dirname(modulePath$
|
|
138
|
+
const modulePath$1 = path.join(convexDirectory, relativeModulePath);
|
|
139
|
+
const directoryPath = path.dirname(modulePath$1);
|
|
46
140
|
if (!(yield* fs.exists(directoryPath))) yield* fs.makeDirectory(directoryPath, { recursive: true });
|
|
47
141
|
const functionsContentsString = yield* render({
|
|
48
142
|
functionNames,
|
|
49
143
|
registeredFunctionsImportPath,
|
|
50
144
|
useNode
|
|
51
145
|
});
|
|
52
|
-
if (!(yield* fs.exists(modulePath$
|
|
53
|
-
yield* fs.writeFileString(modulePath$
|
|
146
|
+
if (!(yield* fs.exists(modulePath$1))) {
|
|
147
|
+
yield* fs.writeFileString(modulePath$1, functionsContentsString);
|
|
54
148
|
return "Added";
|
|
55
149
|
}
|
|
56
|
-
if ((yield* fs.readFileString(modulePath$
|
|
57
|
-
yield* fs.writeFileString(modulePath$
|
|
150
|
+
if ((yield* fs.readFileString(modulePath$1)) !== functionsContentsString) {
|
|
151
|
+
yield* fs.writeFileString(modulePath$1, functionsContentsString);
|
|
58
152
|
return "Modified";
|
|
59
153
|
}
|
|
60
154
|
return "Unchanged";
|
|
@@ -92,18 +186,9 @@ const applyFunctionPlan = Effect.fnUntraced(function* (plan) {
|
|
|
92
186
|
yield* writeGroups(plan.changed);
|
|
93
187
|
});
|
|
94
188
|
const getGroupPathsFromFs = Effect.gen(function* () {
|
|
95
|
-
const fs = yield* FileSystem.FileSystem;
|
|
96
189
|
const path = yield* Path.Path;
|
|
97
|
-
const
|
|
98
|
-
const
|
|
99
|
-
"schema.ts",
|
|
100
|
-
"http.ts",
|
|
101
|
-
"crons.ts",
|
|
102
|
-
"auth.config.ts",
|
|
103
|
-
"convex.config.ts"
|
|
104
|
-
]);
|
|
105
|
-
const allConvexPaths = yield* fs.readDirectory(convexDirectory, { recursive: true });
|
|
106
|
-
const groupPathArray = yield* pipe(allConvexPaths, Array.filter((convexPath) => path.extname(convexPath) === ".ts" && !RESERVED_CONVEX_TS_FILE_NAMES.has(path.basename(convexPath)) && path.basename(path.dirname(convexPath)) !== "_generated"), Effect.forEach((groupModulePath) => fromGroupModulePath(groupModulePath)));
|
|
190
|
+
const allConvexPaths = yield* getEntrypoints;
|
|
191
|
+
const groupPathArray = yield* pipe(allConvexPaths, Array.filter((convexPath) => path.extname(convexPath) === ".ts" && !RESERVED_CONVEX_TS_FILE_NAMES.has(path.basename(convexPath)) && convexPath !== DEPLOY_MODULE), Effect.forEach((groupModulePath) => fromGroupModulePath(groupModulePath)));
|
|
107
192
|
return GroupPaths.make(HashSet.fromIterable(groupPathArray));
|
|
108
193
|
});
|
|
109
194
|
const removeGroups = Effect.fnUntraced(function* (groupPaths) {
|
|
@@ -111,9 +196,9 @@ const removeGroups = Effect.fnUntraced(function* (groupPaths) {
|
|
|
111
196
|
const convexDirectory = yield* ConvexDirectory.get;
|
|
112
197
|
yield* Effect.all(HashSet.map(groupPaths, (groupPath) => Effect.gen(function* () {
|
|
113
198
|
const relativeModulePath = yield* modulePath(groupPath);
|
|
114
|
-
const modulePath$
|
|
199
|
+
const modulePath$3 = path.join(convexDirectory, relativeModulePath);
|
|
115
200
|
yield* Effect.logDebug(`Removing group '${relativeModulePath}'...`);
|
|
116
|
-
yield* removePathIfExists(modulePath$
|
|
201
|
+
yield* removePathIfExists(modulePath$3);
|
|
117
202
|
yield* Effect.logDebug(`Group '${relativeModulePath}' removed`);
|
|
118
203
|
})), { concurrency: "unbounded" });
|
|
119
204
|
});
|
|
@@ -121,17 +206,17 @@ const writeGroups = (groups) => Effect.forEach(groups, Effect.fnUntraced(functio
|
|
|
121
206
|
const path = yield* Path.Path;
|
|
122
207
|
const convexDirectory = yield* ConvexDirectory.get;
|
|
123
208
|
const relativeModulePath = yield* modulePath(group.path);
|
|
124
|
-
const modulePath$
|
|
125
|
-
const registeredFunctionsImportPath = yield* registeredFunctionsImportPathForGroup(group.path, modulePath$
|
|
209
|
+
const modulePath$2 = path.join(convexDirectory, relativeModulePath);
|
|
210
|
+
const registeredFunctionsImportPath = yield* registeredFunctionsImportPathForGroup(group.path, modulePath$2);
|
|
126
211
|
const change = yield* generateGroupModule({
|
|
127
212
|
groupPath: group.path,
|
|
128
213
|
functionNames: group.functionNames,
|
|
129
214
|
registeredFunctionsImportPath,
|
|
130
215
|
useNode: group.runtime === "Node"
|
|
131
216
|
});
|
|
132
|
-
yield* Match.value(change).pipe(Match.when("Added", () => logFileAdded(modulePath$
|
|
217
|
+
yield* Match.value(change).pipe(Match.when("Added", () => logFileAdded(modulePath$2)), Match.when("Modified", () => logFileModified(modulePath$2)), Match.when("Unchanged", () => Effect.void), Match.exhaustive);
|
|
133
218
|
}));
|
|
134
219
|
//#endregion
|
|
135
|
-
export { applyFunctionPlan, generateFunctions, generateGroupModule, registeredFunctionsImportPathForGroup, removeGroups, render, writeGroups };
|
|
220
|
+
export { applyFunctionPlan, assertOwnedEntrypoints, generateFunctions, generateGroupModule, registeredFunctionsImportPathForGroup, removeGroups, render, writeGroups };
|
|
136
221
|
|
|
137
222
|
//# sourceMappingURL=FunctionModule.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"FunctionModule.mjs","names":["GroupPath.modulePath","modulePath","GenerationSnapshot.plan","GenerationSnapshot.functionPaths","GroupPath.fromGroupModulePath"],"sources":["../src/FunctionModule.ts"],"sourcesContent":["import * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as Match from \"effect/Match\";\nimport * as GenerationSnapshot from \"./GenerationSnapshot.js\";\nimport * as GroupPath from \"./GroupPath.js\";\nimport * as GroupPaths from \"./GroupPaths.js\";\nimport { CodeBlockWriter } from \"./CodeBlockWriter.js\";\nimport { logFileAdded, logFileModified, logFileRemoved } from \"./log.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport { ConvexDirectory } from \"./ConvexDirectory.js\";\nimport { removePathIfExists, toModuleImportPath } from \"./utils.js\";\n\nexport const render = ({\n functionNames,\n registeredFunctionsImportPath,\n useNode = false,\n}: Parameters<typeof renderEffect>[0]) =>\n renderEffect({ functionNames, registeredFunctionsImportPath, useNode });\n\nconst renderEffect = Effect.fnUntraced(function* ({\n functionNames,\n registeredFunctionsImportPath,\n useNode = false,\n}: {\n functionNames: ReadonlyArray<string>;\n registeredFunctionsImportPath: string;\n useNode?: boolean;\n}) {\n const cbw = new CodeBlockWriter({ indentNumberOfSpaces: 2 });\n\n if (useNode) {\n yield* cbw.writeLine(`\"use node\";`);\n yield* cbw.blankLine();\n }\n\n yield* cbw.writeLine(\n `import registeredFunctions from \"${registeredFunctionsImportPath}\";`,\n );\n yield* cbw.newLine();\n yield* Effect.forEach(functionNames, (name) =>\n cbw.writeLine(`export const ${name} = registeredFunctions.${name};`),\n );\n\n return yield* cbw.toString();\n});\n\nexport const generateGroupModule = ({\n groupPath,\n functionNames,\n registeredFunctionsImportPath,\n useNode = false,\n}: Parameters<typeof generateGroupModuleEffect>[0]) =>\n generateGroupModuleEffect({\n groupPath,\n functionNames,\n registeredFunctionsImportPath,\n useNode,\n });\n\nconst generateGroupModuleEffect = Effect.fnUntraced(function* ({\n groupPath,\n functionNames,\n registeredFunctionsImportPath,\n useNode = false,\n}: {\n groupPath: GroupPath.GroupPath;\n functionNames: ReadonlyArray<string>;\n registeredFunctionsImportPath: string;\n useNode?: boolean;\n}) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n\n const relativeModulePath = yield* GroupPath.modulePath(groupPath);\n const modulePath = path.join(convexDirectory, relativeModulePath);\n\n const directoryPath = path.dirname(modulePath);\n if (!(yield* fs.exists(directoryPath))) {\n yield* fs.makeDirectory(directoryPath, { recursive: true });\n }\n\n const functionsContentsString = yield* render({\n functionNames,\n registeredFunctionsImportPath,\n useNode,\n });\n\n if (!(yield* fs.exists(modulePath))) {\n yield* fs.writeFileString(modulePath, functionsContentsString);\n return \"Added\" as const;\n }\n const existing = yield* fs.readFileString(modulePath);\n if (existing !== functionsContentsString) {\n yield* fs.writeFileString(modulePath, functionsContentsString);\n return \"Modified\" as const;\n }\n return \"Unchanged\" as const;\n});\n\n/**\n * Compute the module import specifier (relative to `modulePath`) for a group's\n * registry file under `confect/_generated/registeredFunctions/`. The registry\n * path mirrors the group's path one-to-one (see\n * `registeredFunctionsRelativePath` in `LeafModule.ts`) for both Convex and\n * Node groups.\n */\nexport const registeredFunctionsImportPathForGroup = Effect.fnUntraced(\n function* (groupPath: GroupPath.GroupPath, modulePath: string) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const registeredFunctionsPath =\n path.join(\n confectDirectory,\n \"_generated\",\n \"registeredFunctions\",\n ...groupPath.pathSegments,\n ) + \".ts\";\n\n return yield* toModuleImportPath(\n path.relative(path.dirname(modulePath), registeredFunctionsPath),\n );\n },\n);\n\nconst logGroupPaths = Effect.fnUntraced(function* <R>(\n groupPaths: GroupPaths.GroupPaths,\n logFn: (fullPath: string) => Effect.Effect<void, never, R>,\n): Effect.fn.Return<void, never, R | Path.Path | ConvexDirectory> {\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n\n yield* Effect.forEach(\n groupPaths,\n Effect.fnUntraced(function* (gp: GroupPath.GroupPath) {\n const relativeModulePath = yield* GroupPath.modulePath(gp);\n yield* logFn(path.join(convexDirectory, relativeModulePath));\n }),\n );\n});\n\nexport const generateFunctions = Effect.fnUntraced(function* (\n snapshot: GenerationSnapshot.GenerationSnapshot,\n) {\n const groupPathsFromFs = yield* getGroupPathsFromFs;\n yield* applyFunctionPlan(GenerationSnapshot.plan(snapshot, groupPathsFromFs));\n return GenerationSnapshot.functionPaths(snapshot);\n});\n\nexport const applyFunctionPlan = Effect.fnUntraced(function* (\n plan: GenerationSnapshot.ModulePlan,\n) {\n const removed = GroupPaths.GroupPaths.make(\n HashSet.fromIterable(plan.removed),\n );\n yield* removeGroups(removed);\n yield* logGroupPaths(removed, logFileRemoved);\n yield* writeGroups(plan.changed);\n});\n\nconst getGroupPathsFromFs = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n\n const RESERVED_CONVEX_TS_FILE_NAMES = new Set([\n \"schema.ts\",\n \"http.ts\",\n \"crons.ts\",\n \"auth.config.ts\",\n \"convex.config.ts\",\n ]);\n\n const allConvexPaths = yield* fs.readDirectory(convexDirectory, {\n recursive: true,\n });\n const groupPathArray = yield* pipe(\n allConvexPaths,\n Array.filter(\n (convexPath) =>\n path.extname(convexPath) === \".ts\" &&\n !RESERVED_CONVEX_TS_FILE_NAMES.has(path.basename(convexPath)) &&\n path.basename(path.dirname(convexPath)) !== \"_generated\",\n ),\n Effect.forEach((groupModulePath) =>\n GroupPath.fromGroupModulePath(groupModulePath),\n ),\n );\n return GroupPaths.GroupPaths.make(HashSet.fromIterable(groupPathArray));\n});\n\nexport const removeGroups = Effect.fnUntraced(function* (\n groupPaths: GroupPaths.GroupPaths,\n) {\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n\n yield* Effect.all(\n HashSet.map(groupPaths, (groupPath) =>\n Effect.gen(function* () {\n const relativeModulePath = yield* GroupPath.modulePath(groupPath);\n const modulePath = path.join(convexDirectory, relativeModulePath);\n\n yield* Effect.logDebug(`Removing group '${relativeModulePath}'...`);\n\n yield* removePathIfExists(modulePath);\n yield* Effect.logDebug(`Group '${relativeModulePath}' removed`);\n }),\n ),\n { concurrency: \"unbounded\" },\n );\n});\n\nexport const writeGroups = (\n groups: ReadonlyArray<GenerationSnapshot.GroupSummary>,\n) =>\n Effect.forEach(\n groups,\n Effect.fnUntraced(function* (group: GenerationSnapshot.GroupSummary) {\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n const relativeModulePath = yield* GroupPath.modulePath(group.path);\n const modulePath = path.join(convexDirectory, relativeModulePath);\n const registeredFunctionsImportPath =\n yield* registeredFunctionsImportPathForGroup(group.path, modulePath);\n const change = yield* generateGroupModule({\n groupPath: group.path,\n functionNames: group.functionNames,\n registeredFunctionsImportPath,\n useNode: group.runtime === \"Node\",\n });\n yield* Match.value(change).pipe(\n Match.when(\"Added\", () => logFileAdded(modulePath)),\n Match.when(\"Modified\", () => logFileModified(modulePath)),\n Match.when(\"Unchanged\", () => Effect.void),\n Match.exhaustive,\n );\n }),\n );\n"],"mappings":";;;;;;;;;;;;;;;;AAgBA,MAAa,UAAU,EACrB,eACA,+BACA,UAAU,YAEV,aAAa;CAAE;CAAe;CAA+B;AAAQ,CAAC;AAExE,MAAM,eAAe,OAAO,WAAW,WAAW,EAChD,eACA,+BACA,UAAU,SAKT;CACD,MAAM,MAAM,IAAI,gBAAgB,EAAE,sBAAsB,EAAE,CAAC;CAE3D,IAAI,SAAS;EACX,OAAO,IAAI,UAAU,aAAa;EAClC,OAAO,IAAI,UAAU;CACvB;CAEA,OAAO,IAAI,UACT,oCAAoC,8BAA8B,GACpE;CACA,OAAO,IAAI,QAAQ;CACnB,OAAO,OAAO,QAAQ,gBAAgB,SACpC,IAAI,UAAU,gBAAgB,KAAK,yBAAyB,KAAK,EAAE,CACrE;CAEA,OAAO,OAAO,IAAI,SAAS;AAC7B,CAAC;AAED,MAAa,uBAAuB,EAClC,WACA,eACA,+BACA,UAAU,YAEV,0BAA0B;CACxB;CACA;CACA;CACA;AACF,CAAC;AAEH,MAAM,4BAA4B,OAAO,WAAW,WAAW,EAC7D,WACA,eACA,+BACA,UAAU,SAMT;CACD,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,kBAAkB,OAAO,gBAAgB;CAE/C,MAAM,qBAAqB,OAAOA,WAAqB,SAAS;CAChE,MAAMC,eAAa,KAAK,KAAK,iBAAiB,kBAAkB;CAEhE,MAAM,gBAAgB,KAAK,QAAQA,YAAU;CAC7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O,gBAAgB;CAC/C,MAAM,qBAAqB,OAAOD,WAAqB,MAAM,IAAI;CACjE,MAAMC,eAAa,KAAK,KAAK,iBAAiB,kBAAkB;CAChE,MAAM,gCACJ,OAAO,sCAAsC,MAAM,MAAMA,YAAU;CACrE,MAAM,SAAS,OAAO,oBAAoB;EACxC,WAAW,MAAM;EACjB,eAAe,MAAM;EACrB;EACA,SAAS,MAAM,YAAY;CAC7B,CAAC;CACD,OAAO,MAAM,MAAM,MAAM,CAAC,CAAC,KACzB,MAAM,KAAK,eAAe,aAAaA,YAAU,CAAC,GAClD,MAAM,KAAK,kBAAkB,gBAAgBA,YAAU,CAAC,GACxD,MAAM,KAAK,mBAAmB,OAAO,IAAI,GACzC,MAAM,UACR;AACF,CAAC,CACH"}
|
|
1
|
+
{"version":3,"file":"FunctionModule.mjs","names":["templates.http","templates.declaredHttp","templates.crons","SectionFiles.written","Declaration.isGenerated","GroupPath.fromGroupModulePath","GroupPath.modulePath","modulePath","GenerationSnapshot.plan","GenerationSnapshot.functionPaths"],"sources":["../src/FunctionModule.ts"],"sourcesContent":["import * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as Match from \"effect/Match\";\nimport * as Schema from \"effect/Schema\";\nimport { UnownedConvexEntrypointError } from \"./CodegenError.js\";\nimport * as Declaration from \"./Declaration.js\";\nimport * as SectionFiles from \"./SectionFiles.js\";\nimport * as templates from \"./templates.js\";\nimport * as GenerationSnapshot from \"./GenerationSnapshot.js\";\nimport * as GroupPath from \"./GroupPath.js\";\nimport * as GroupPaths from \"./GroupPaths.js\";\nimport { CodeBlockWriter } from \"./CodeBlockWriter.js\";\nimport { logFileAdded, logFileModified, logFileRemoved } from \"./log.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport { ConvexDirectory } from \"./ConvexDirectory.js\";\nimport {\n removePathIfExists,\n toModuleImportPath,\n toPosixPath,\n} from \"./utils.js\";\nimport { ProjectRoot } from \"./ProjectRoot.js\";\n\nconst RESERVED_CONVEX_TS_FILE_NAMES = new Set([\n \"schema.ts\",\n \"http.ts\",\n \"crons.ts\",\n \"auth.config.ts\",\n \"convex.config.ts\",\n]);\n\n// Only the root module is codegen's; a nested group may take the name.\nconst DEPLOY_MODULE = \"confectDeploy.ts\";\n\n// Keep ownership and removal aligned with Convex's bundler entryPoints filter.\nconst getEntrypoints = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convex = yield* ConvexDirectory.get;\n const files = yield* fs.readDirectory(convex, { recursive: true });\n const components = files\n .filter(\n (file) =>\n path.basename(file) === \"convex.config.ts\" &&\n path.dirname(file) !== \".\",\n )\n .map((file) => path.dirname(file) + path.sep);\n return files.filter((file) => {\n const base = path.basename(file);\n return (\n !file.startsWith(\"_generated\" + path.sep) &&\n !components.some((component) => file.startsWith(component)) &&\n /\\.(?:js|mjs|cjs|ts|tsx|mts|cts|jsx)$/.test(base) &&\n !base.startsWith(\".\") &&\n !base.startsWith(\"#\") &&\n (base.match(/\\./g)?.length ?? 0) === 1 &&\n base !== \"schema.ts\" &&\n base !== \"schema.js\" &&\n !file.includes(\" \")\n );\n });\n});\n\nconst tokenize = (\n source: string,\n modulePath: string,\n path: Path.Path,\n): string[] | undefined => {\n const token =\n /\\s+|\\/\\/[^\\r\\n]*|\\/\\*[\\s\\S]*?\\*\\/|\"(?:\\\\.|[^\"\\\\\\r\\n])*\"|'(?:\\\\.|[^'\\\\\\r\\n])*'|[$A-Z_a-z][$\\w]*|[{}()[\\].,:;=]/y;\n const tokens: string[] = [];\n while (token.lastIndex < source.length) {\n const match = token.exec(source);\n if (match === null) return undefined;\n const value = match[0];\n if (/^\\s|^\\//.test(value)) continue;\n if (value.startsWith('\"') || value.startsWith(\"'\")) {\n const literal = value.slice(1, -1);\n tokens.push(\n JSON.stringify(\n literal.startsWith(\".\")\n ? path.resolve(\n path.dirname(modulePath),\n literal.replace(/\\.js$/, \"\"),\n )\n : literal,\n ),\n );\n } else tokens.push(value);\n }\n return tokens;\n};\n\nconst encodeString = Schema.encodeSync(Schema.fromJsonString(Schema.String));\n\nconst matchesShape = (\n actual: readonly string[],\n expected: readonly string[],\n) => {\n let index = 0;\n for (const token of expected) {\n if (token === \";\" && actual[index] !== \";\") continue;\n if (actual[index] === \",\" && (token === \"}\" || token === \")\")) index++;\n if (actual[index++] !== token) return false;\n }\n return index === actual.length;\n};\n\nexport const assertOwnedEntrypoints = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convex = yield* ConvexDirectory.get;\n const confect = yield* ConfectDirectory.get;\n const projectRoot = yield* ProjectRoot.get;\n const importFromConvex = (file: string) =>\n toModuleImportPath(path.relative(convex, path.join(confect, file)));\n const optional = new Map([\n [\n \"http.ts\",\n [\n yield* templates.http({\n httpImportPath: yield* importFromConvex(\"http.ts\"),\n }),\n yield* templates.declaredHttp({\n schemaImportPath: yield* importFromConvex(\"_generated/schema.ts\"),\n httpImportPath: yield* importFromConvex(\"http.ts\"),\n }),\n yield* templates.declaredHttp({\n schemaImportPath: yield* importFromConvex(\"_generated/schema.ts\"),\n httpImportPath: yield* importFromConvex(\"http.ts\"),\n runtimeImportPath: yield* importFromConvex(\"runtime.ts\"),\n }),\n ],\n ],\n [\n \"crons.ts\",\n [\n yield* templates.crons({\n cronsImportPath: yield* importFromConvex(\"crons.ts\"),\n }),\n ],\n ],\n ]);\n // The declared HTTP router first imports each file a manifest section wrote.\n const sectionImports = new Set(\n (yield* SectionFiles.written).map((file) =>\n encodeString(\n path.join(confect, \"_generated\", path.basename(file, \".ts\")),\n ),\n ),\n );\n const withoutSectionImports = (\n tokens: ReadonlyArray<string>,\n ): ReadonlyArray<string> =>\n tokens[0] === \"import\" && sectionImports.has(tokens[1] ?? \"\")\n ? withoutSectionImports(tokens.slice(tokens[2] === \";\" ? 3 : 2))\n : tokens;\n const refused: string[] = [];\n for (const relative of yield* getEntrypoints) {\n const absolute = path.join(convex, relative);\n const contents = yield* fs.readFileString(absolute);\n if (relative === DEPLOY_MODULE && Declaration.isGenerated(contents, []))\n continue;\n const tokens = tokenize(contents, absolute, path);\n if (tokens !== undefined) {\n if (\n optional\n .get(relative)\n ?.some((template) =>\n matchesShape(\n relative === \"http.ts\" ? withoutSectionImports(tokens) : tokens,\n tokenize(template, absolute, path)!,\n ),\n )\n )\n continue;\n if (path.extname(relative) === \".ts\") {\n const names = tokens.flatMap((token, index) =>\n token === \"export\" && tokens[index + 1] === \"const\"\n ? [tokens[index + 2]!]\n : [],\n );\n const group = yield* GroupPath.fromGroupModulePath(relative);\n const template = yield* render({\n functionNames: names,\n registeredFunctionsImportPath:\n yield* registeredFunctionsImportPathForGroup(group, absolute),\n useNode: tokens[0] === '\"use node\"',\n });\n if (\n names.length > 0 &&\n new Set(names).size === names.length &&\n matchesShape(tokens, tokenize(template, absolute, path)!)\n )\n continue;\n }\n }\n refused.push(toPosixPath(path, path.relative(projectRoot, absolute)));\n }\n if (refused.length > 0)\n return yield* new UnownedConvexEntrypointError({\n filePaths: refused.sort(),\n });\n});\n\nexport const render = ({\n functionNames,\n registeredFunctionsImportPath,\n useNode = false,\n}: Parameters<typeof renderEffect>[0]) =>\n renderEffect({ functionNames, registeredFunctionsImportPath, useNode });\n\nconst renderEffect = Effect.fnUntraced(function* ({\n functionNames,\n registeredFunctionsImportPath,\n useNode = false,\n}: {\n functionNames: ReadonlyArray<string>;\n registeredFunctionsImportPath: string;\n useNode?: boolean;\n}) {\n const cbw = new CodeBlockWriter({ indentNumberOfSpaces: 2 });\n\n if (useNode) {\n yield* cbw.writeLine(`\"use node\";`);\n yield* cbw.blankLine();\n }\n\n yield* cbw.writeLine(\n `import registeredFunctions from \"${registeredFunctionsImportPath}\";`,\n );\n yield* cbw.newLine();\n yield* Effect.forEach(functionNames, (name) =>\n cbw.writeLine(`export const ${name} = registeredFunctions.${name};`),\n );\n\n return yield* cbw.toString();\n});\n\nexport const generateGroupModule = ({\n groupPath,\n functionNames,\n registeredFunctionsImportPath,\n useNode = false,\n}: Parameters<typeof generateGroupModuleEffect>[0]) =>\n generateGroupModuleEffect({\n groupPath,\n functionNames,\n registeredFunctionsImportPath,\n useNode,\n });\n\nconst generateGroupModuleEffect = Effect.fnUntraced(function* ({\n groupPath,\n functionNames,\n registeredFunctionsImportPath,\n useNode = false,\n}: {\n groupPath: GroupPath.GroupPath;\n functionNames: ReadonlyArray<string>;\n registeredFunctionsImportPath: string;\n useNode?: boolean;\n}) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n\n const relativeModulePath = yield* GroupPath.modulePath(groupPath);\n const modulePath = path.join(convexDirectory, relativeModulePath);\n\n const directoryPath = path.dirname(modulePath);\n if (!(yield* fs.exists(directoryPath))) {\n yield* fs.makeDirectory(directoryPath, { recursive: true });\n }\n\n const functionsContentsString = yield* render({\n functionNames,\n registeredFunctionsImportPath,\n useNode,\n });\n\n if (!(yield* fs.exists(modulePath))) {\n yield* fs.writeFileString(modulePath, functionsContentsString);\n return \"Added\" as const;\n }\n const existing = yield* fs.readFileString(modulePath);\n if (existing !== functionsContentsString) {\n yield* fs.writeFileString(modulePath, functionsContentsString);\n return \"Modified\" as const;\n }\n return \"Unchanged\" as const;\n});\n\n/**\n * Compute the module import specifier (relative to `modulePath`) for a group's\n * registry file under `confect/_generated/registeredFunctions/`. The registry\n * path mirrors the group's path one-to-one (see\n * `registeredFunctionsRelativePath` in `LeafModule.ts`) for both Convex and\n * Node groups.\n */\nexport const registeredFunctionsImportPathForGroup = Effect.fnUntraced(\n function* (groupPath: GroupPath.GroupPath, modulePath: string) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const registeredFunctionsPath =\n path.join(\n confectDirectory,\n \"_generated\",\n \"registeredFunctions\",\n ...groupPath.pathSegments,\n ) + \".ts\";\n\n return yield* toModuleImportPath(\n path.relative(path.dirname(modulePath), registeredFunctionsPath),\n );\n },\n);\n\nconst logGroupPaths = Effect.fnUntraced(function* <R>(\n groupPaths: GroupPaths.GroupPaths,\n logFn: (fullPath: string) => Effect.Effect<void, never, R>,\n): Effect.fn.Return<void, never, R | Path.Path | ConvexDirectory> {\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n\n yield* Effect.forEach(\n groupPaths,\n Effect.fnUntraced(function* (gp: GroupPath.GroupPath) {\n const relativeModulePath = yield* GroupPath.modulePath(gp);\n yield* logFn(path.join(convexDirectory, relativeModulePath));\n }),\n );\n});\n\nexport const generateFunctions = Effect.fnUntraced(function* (\n snapshot: GenerationSnapshot.GenerationSnapshot,\n) {\n const groupPathsFromFs = yield* getGroupPathsFromFs;\n yield* applyFunctionPlan(GenerationSnapshot.plan(snapshot, groupPathsFromFs));\n return GenerationSnapshot.functionPaths(snapshot);\n});\n\nexport const applyFunctionPlan = Effect.fnUntraced(function* (\n plan: GenerationSnapshot.ModulePlan,\n) {\n const removed = GroupPaths.GroupPaths.make(\n HashSet.fromIterable(plan.removed),\n );\n yield* removeGroups(removed);\n yield* logGroupPaths(removed, logFileRemoved);\n yield* writeGroups(plan.changed);\n});\n\nconst getGroupPathsFromFs = Effect.gen(function* () {\n const path = yield* Path.Path;\n const allConvexPaths = yield* getEntrypoints;\n const groupPathArray = yield* pipe(\n allConvexPaths,\n Array.filter(\n (convexPath) =>\n path.extname(convexPath) === \".ts\" &&\n !RESERVED_CONVEX_TS_FILE_NAMES.has(path.basename(convexPath)) &&\n convexPath !== DEPLOY_MODULE,\n ),\n Effect.forEach((groupModulePath) =>\n GroupPath.fromGroupModulePath(groupModulePath),\n ),\n );\n return GroupPaths.GroupPaths.make(HashSet.fromIterable(groupPathArray));\n});\n\nexport const removeGroups = Effect.fnUntraced(function* (\n groupPaths: GroupPaths.GroupPaths,\n) {\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n\n yield* Effect.all(\n HashSet.map(groupPaths, (groupPath) =>\n Effect.gen(function* () {\n const relativeModulePath = yield* GroupPath.modulePath(groupPath);\n const modulePath = path.join(convexDirectory, relativeModulePath);\n\n yield* Effect.logDebug(`Removing group '${relativeModulePath}'...`);\n\n yield* removePathIfExists(modulePath);\n yield* Effect.logDebug(`Group '${relativeModulePath}' removed`);\n }),\n ),\n { concurrency: \"unbounded\" },\n );\n});\n\nexport const writeGroups = (\n groups: ReadonlyArray<GenerationSnapshot.GroupSummary>,\n) =>\n Effect.forEach(\n groups,\n Effect.fnUntraced(function* (group: GenerationSnapshot.GroupSummary) {\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n const relativeModulePath = yield* GroupPath.modulePath(group.path);\n const modulePath = path.join(convexDirectory, relativeModulePath);\n const registeredFunctionsImportPath =\n yield* registeredFunctionsImportPathForGroup(group.path, modulePath);\n const change = yield* generateGroupModule({\n groupPath: group.path,\n functionNames: group.functionNames,\n registeredFunctionsImportPath,\n useNode: group.runtime === \"Node\",\n });\n yield* Match.value(change).pipe(\n Match.when(\"Added\", () => logFileAdded(modulePath)),\n Match.when(\"Modified\", () => logFileModified(modulePath)),\n Match.when(\"Unchanged\", () => Effect.void),\n Match.exhaustive,\n );\n }),\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAM,gDAAgC,IAAI,IAAI;CAC5C;CACA;CACA;CACA;CACA;AACF,CAAC;AAGD,MAAM,gBAAgB;AAGtB,MAAM,iBAAiB,OAAO,IAAI,aAAa;CAC7C,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,SAAS,OAAO,gBAAgB;CACtC,MAAM,QAAQ,OAAO,GAAG,cAAc,QAAQ,EAAE,WAAW,KAAK,CAAC;CACjE,MAAM,aAAa,MAChB,QACE,SACC,KAAK,SAAS,IAAI,MAAM,sBACxB,KAAK,QAAQ,IAAI,MA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;EACtB,MAAM,qBAAqB,OAAOC,WAAqB,SAAS;EAChE,MAAMC,eAAa,KAAK,KAAK,iBAAiB,kBAAkB;EAEhE,OAAO,OAAO,SAAS,mBAAmB,mBAAmB,KAAK;EAElE,OAAO,mBAAmBA,YAAU;EACpC,OAAO,OAAO,SAAS,UAAU,mBAAmB,UAAU;CAChE,CAAC,CACH,GACA,EAAE,aAAa,YAAY,CAC7B;AACF,CAAC;AAED,MAAa,eACX,WAEA,OAAO,QACL,QACA,OAAO,WAAW,WAAW,OAAwC;CACnE,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,kBAAkB,OAAO,gBAAgB;CAC/C,MAAM,qBAAqB,OAAOD,WAAqB,MAAM,IAAI;CACjE,MAAMC,eAAa,KAAK,KAAK,iBAAiB,kBAAkB;CAChE,MAAM,gCACJ,OAAO,sCAAsC,MAAM,MAAMA,YAAU;CACrE,MAAM,SAAS,OAAO,oBAAoB;EACxC,WAAW,MAAM;EACjB,eAAe,MAAM;EACrB;EACA,SAAS,MAAM,YAAY;CAC7B,CAAC;CACD,OAAO,MAAM,MAAM,MAAM,CAAC,CAAC,KACzB,MAAM,KAAK,eAAe,aAAaA,YAAU,CAAC,GAClD,MAAM,KAAK,kBAAkB,gBAAgBA,YAAU,CAAC,GACxD,MAAM,KAAK,mBAAmB,OAAO,IAAI,GACzC,MAAM,UACR;AACF,CAAC,CACH"}
|
package/dist/LeafModule.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { fromBundlerError } from "./BuildError.mjs";
|
|
1
|
+
import { BundleFailedError, fromBundlerError } from "./BuildError.mjs";
|
|
2
2
|
import { bundle, directlyImports, importersOfPackage, withBatch } from "./Bundler.mjs";
|
|
3
|
-
import { ImplMissingDefaultLayerError, ImplMissingFunctionsError, ImplMissingMiddlewareError, ImplMissingSpecImportError, ImplNotFinalizedError, InvalidMiddlewareAttachmentError, MissingImplFileError, MissingSpecFileError, SpecImportsServerError, SpecMissingDefaultGroupSpecError } from "./CodegenError.mjs";
|
|
3
|
+
import { ImplMissingDefaultLayerError, ImplMissingFunctionsError, ImplMissingMiddlewareError, ImplMissingSpecImportError, ImplNotFinalizedError, InvalidDeclarationError, InvalidMiddlewareAttachmentError, MissingImplFileError, MissingSpecFileError, RequiredMiddlewareError, SpecImportsServerError, SpecMissingDefaultGroupSpecError } from "./CodegenError.mjs";
|
|
4
4
|
import { ConfectDirectory } from "./ConfectDirectory.mjs";
|
|
5
|
-
import { removePathExtension, toPosixPath } from "./utils.mjs";
|
|
5
|
+
import { readDirectorySorted, removePathExtension, toPosixPath } from "./utils.mjs";
|
|
6
6
|
import { ImplModulePath } from "./ImplModulePath.mjs";
|
|
7
7
|
import * as Effect from "effect/Effect";
|
|
8
8
|
import { GroupSpec, MiddlewareAttachment } from "@confect/core";
|
|
@@ -16,7 +16,7 @@ import * as Schema from "effect/Schema";
|
|
|
16
16
|
import * as String from "effect/String";
|
|
17
17
|
import * as Layer from "effect/Layer";
|
|
18
18
|
import * as Brand from "effect/Brand";
|
|
19
|
-
import { Registry } from "@confect/server";
|
|
19
|
+
import { Registry, RegistryItems } from "@confect/server";
|
|
20
20
|
import * as GroupImpl from "@confect/server/GroupImpl";
|
|
21
21
|
//#region src/LeafModule.ts
|
|
22
22
|
const LoadedLeafModule = Brand.nominal();
|
|
@@ -57,12 +57,11 @@ const registeredFunctionsRelativePath = Effect.fnUntraced(function* (leaf) {
|
|
|
57
57
|
return (yield* Path.Path).join("registeredFunctions", ...leaf.pathSegments) + ".ts";
|
|
58
58
|
});
|
|
59
59
|
const discoverLeafSpecFiles = Effect.gen(function* () {
|
|
60
|
-
const fs = yield* FileSystem.FileSystem;
|
|
61
60
|
const path = yield* Path.Path;
|
|
62
61
|
const confectDirectory = yield* ConfectDirectory.get;
|
|
63
62
|
const excludedDirs = HashSet.make("_generated", "tables", "middleware");
|
|
64
63
|
const excludedFiles = HashSet.make("nodeSpec.ts", "spec.ts");
|
|
65
|
-
const allPaths = yield*
|
|
64
|
+
const allPaths = yield* readDirectorySorted(confectDirectory);
|
|
66
65
|
return Array.filter(allPaths, (relativePath) => {
|
|
67
66
|
if (!isLeafSpecPath(relativePath)) return false;
|
|
68
67
|
if (HashSet.has(excludedFiles, relativePath)) return false;
|
|
@@ -71,11 +70,10 @@ const discoverLeafSpecFiles = Effect.gen(function* () {
|
|
|
71
70
|
});
|
|
72
71
|
});
|
|
73
72
|
const discoverLeafImplFiles = Effect.gen(function* () {
|
|
74
|
-
const fs = yield* FileSystem.FileSystem;
|
|
75
73
|
const path = yield* Path.Path;
|
|
76
74
|
const confectDirectory = yield* ConfectDirectory.get;
|
|
77
75
|
const excludedDirs = HashSet.make("_generated", "tables", "middleware");
|
|
78
|
-
const allPaths = yield*
|
|
76
|
+
const allPaths = yield* readDirectorySorted(confectDirectory);
|
|
79
77
|
return Array.filter(Array.filterMap(allPaths, (relativePath) => Schema.decodeResult(ImplModulePath)(relativePath)), (relativePath) => {
|
|
80
78
|
const segments = String.split(relativePath, path.sep);
|
|
81
79
|
return !Array.some(segments, (segment) => HashSet.has(excludedDirs, segment));
|
|
@@ -126,6 +124,17 @@ const validateClientSafety = Effect.fnUntraced(function* (leaf, bundled) {
|
|
|
126
124
|
importerPaths: Array.map(importers, (absolutePath) => toPosixPath(path, path.relative(confectDirectory, absolutePath)))
|
|
127
125
|
});
|
|
128
126
|
});
|
|
127
|
+
const validateReservedArguments = Effect.fnUntraced(function* (group, specPath, groupPath) {
|
|
128
|
+
for (const spec of Object.values(group.functions)) {
|
|
129
|
+
const name = spec.reservedArgument;
|
|
130
|
+
const provenance = spec.functionProvenance;
|
|
131
|
+
if (name !== void 0 && provenance._tag === "Confect" && Object.hasOwn(provenance.args.fields, name)) return yield* new InvalidDeclarationError({
|
|
132
|
+
declarationPath: `confect/${specPath}`,
|
|
133
|
+
reason: `${groupPath}:${spec.name} declares the argument "${name}", which its profile reserves. Rename the argument.`
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
for (const [name, child] of Object.entries(group.groups)) yield* validateReservedArguments(child, specPath, `${groupPath}/${name}`);
|
|
137
|
+
});
|
|
129
138
|
/**
|
|
130
139
|
* Validate that the leaf's spec file default-exports a `GroupSpec`, and that
|
|
131
140
|
* nothing it reaches drags server code into the client (see
|
|
@@ -139,6 +148,7 @@ const loadSpec = Effect.fn("LeafModule.loadSpec")(function* (leaf) {
|
|
|
139
148
|
const groupSpec = bundled.module.default;
|
|
140
149
|
if (!GroupSpec.isGroupSpec(groupSpec)) return yield* new SpecMissingDefaultGroupSpecError({ specPath: leaf.relativePath });
|
|
141
150
|
yield* validateClientSafety(leaf, bundled);
|
|
151
|
+
yield* validateReservedArguments(groupSpec, leaf.relativePath, leaf.pathSegments.join("/"));
|
|
142
152
|
yield* Effect.fromResult(GroupSpec.validateMiddleware(groupSpec)).pipe(Effect.mapError((error) => new InvalidMiddlewareAttachmentError({
|
|
143
153
|
specPath: leaf.relativePath,
|
|
144
154
|
message: MiddlewareAttachment.formatValidationError(error)
|
|
@@ -156,26 +166,50 @@ const loadSpec = Effect.fn("LeafModule.loadSpec")(function* (leaf) {
|
|
|
156
166
|
const findFinalizedGroupImpl = (context) => Array.findFirst(context.mapUnsafe.values(), GroupImpl.isFinalizedGroupImpl);
|
|
157
167
|
/**
|
|
158
168
|
* Build the impl layer with a fresh `Registry` so each validation is isolated
|
|
159
|
-
* from prior validations' `FunctionImpl.make` writes.
|
|
160
|
-
*
|
|
161
|
-
* names onto the produced `Finalized` `GroupImpl` service value—but a fresh
|
|
162
|
-
* `Ref` is still required because the default `Context.Reference` is cached
|
|
163
|
-
* globally and would otherwise accumulate items across impls.
|
|
169
|
+
* from prior validations' `FunctionImpl.make` writes. Retain its items to check
|
|
170
|
+
* required middleware against actual function attachments.
|
|
164
171
|
*/
|
|
165
172
|
const buildImplLayer = Effect.fnUntraced(function* (implLayer) {
|
|
166
173
|
const registry = Ref.makeUnsafe({});
|
|
167
|
-
return
|
|
174
|
+
return {
|
|
175
|
+
context: yield* Layer.build(implLayer).pipe(Effect.provideService(Registry.Registry, registry)),
|
|
176
|
+
items: yield* Ref.get(registry)
|
|
177
|
+
};
|
|
168
178
|
}, Effect.scoped);
|
|
169
179
|
/**
|
|
170
180
|
* Validate that the leaf's sibling impl file imports the spec, default-exports
|
|
171
181
|
* a finalized `GroupImpl` layer, and provides a `FunctionImpl` for every
|
|
172
|
-
* function declared by the spec.
|
|
182
|
+
* function declared by the spec. Return uncovered middleware requirements for
|
|
183
|
+
* the caller to report across groups.
|
|
184
|
+
*/
|
|
185
|
+
/**
|
|
186
|
+
* An implementation's unresolved import of a `confect/_generated` file is a
|
|
187
|
+
* section file that no declared section writes: every declared section's file
|
|
188
|
+
* is on disk before implementations validate. Say so, at the import.
|
|
173
189
|
*/
|
|
174
|
-
const
|
|
190
|
+
const nameUnwrittenSectionFiles = Effect.fnUntraced(function* (error, bundleDirectory) {
|
|
191
|
+
const path = yield* Path.Path;
|
|
192
|
+
const generated = path.join(yield* ConfectDirectory.get, "_generated");
|
|
193
|
+
const errors = error.errors.map((message) => {
|
|
194
|
+
const specifier = /^Could not resolve "(.+)"$/.exec(message.text)?.[1];
|
|
195
|
+
if (specifier === void 0 || message.location === null) return message;
|
|
196
|
+
const file = path.relative(generated, path.resolve(bundleDirectory, path.dirname(message.location.file), specifier));
|
|
197
|
+
if (file.startsWith("..") || path.isAbsolute(file)) return message;
|
|
198
|
+
const extension = path.extname(file);
|
|
199
|
+
const name = toPosixPath(path, extension === "" ? `${file}.ts` : extension === ".js" ? `${file.slice(0, -extension.length)}.ts` : file);
|
|
200
|
+
return Object.assign({}, message, { text: `No manifest section this backend declares writes _generated/${name}. Declare its section on App.make({ manifestSections }) in confect/app.ts.` });
|
|
201
|
+
});
|
|
202
|
+
return new BundleFailedError({
|
|
203
|
+
file: error.file,
|
|
204
|
+
errors
|
|
205
|
+
});
|
|
206
|
+
});
|
|
207
|
+
const validateImpl = Effect.fn("LeafModule.validateImpl")(function* (leaf, required = []) {
|
|
208
|
+
const path = yield* Path.Path;
|
|
175
209
|
const implRelativePath = yield* implPathForSpec(leaf.relativePath);
|
|
176
210
|
const implAbsolutePath = yield* absoluteModulePath(implRelativePath);
|
|
177
211
|
const specAbsolutePath = yield* absoluteModulePath(leaf.relativePath);
|
|
178
|
-
const bundled = yield* bundle(implAbsolutePath).pipe(Effect.mapError((error) => fromBundlerError(implRelativePath, error)));
|
|
212
|
+
const bundled = yield* bundle(implAbsolutePath).pipe(Effect.mapError((error) => fromBundlerError(implRelativePath, error)), Effect.catchTag("BundleFailedError", (error) => Effect.flip(nameUnwrittenSectionFiles(error, path.dirname(implAbsolutePath)))));
|
|
179
213
|
if (!(yield* directlyImports(bundled, implAbsolutePath, specAbsolutePath))) return yield* new ImplMissingSpecImportError({
|
|
180
214
|
implPath: implRelativePath,
|
|
181
215
|
expectedSpecPath: leaf.relativePath
|
|
@@ -183,7 +217,7 @@ const validateImpl = Effect.fn("LeafModule.validateImpl")(function* (leaf) {
|
|
|
183
217
|
if (!Layer.isLayer(bundled.module.default)) return yield* new ImplMissingDefaultLayerError({ implPath: implRelativePath });
|
|
184
218
|
const groupSpec = leaf.spec;
|
|
185
219
|
const expectedFunctionNames = Object.keys(groupSpec.functions);
|
|
186
|
-
const context = yield* buildImplLayer(bundled.module.default);
|
|
220
|
+
const { context, items } = yield* buildImplLayer(bundled.module.default);
|
|
187
221
|
const finalizedGroupImpl = yield* Option.match(findFinalizedGroupImpl(context), {
|
|
188
222
|
onNone: () => new ImplNotFinalizedError({ implPath: implRelativePath }),
|
|
189
223
|
onSome: Effect.succeed
|
|
@@ -203,6 +237,7 @@ const validateImpl = Effect.fn("LeafModule.validateImpl")(function* (leaf) {
|
|
|
203
237
|
groupPath: leaf.groupPathDot,
|
|
204
238
|
missingMiddlewareKeys: missingMiddleware
|
|
205
239
|
});
|
|
240
|
+
return RegistryItems.missingRequired(items, required, leaf.groupPathDot);
|
|
206
241
|
});
|
|
207
242
|
const withImplFiles = Effect.fnUntraced(function* (relativePaths, use) {
|
|
208
243
|
const fs = yield* FileSystem.FileSystem;
|
|
@@ -227,14 +262,12 @@ const withImplFiles = Effect.fnUntraced(function* (relativePaths, use) {
|
|
|
227
262
|
}));
|
|
228
263
|
});
|
|
229
264
|
const validateImplFiles = Effect.fn("LeafModule.validateImplFiles")((relativePaths) => withImplFiles(relativePaths, validateAllImpls));
|
|
230
|
-
const validateAllImpls = Effect.fnUntraced(function* (leaves) {
|
|
265
|
+
const validateAllImpls = Effect.fnUntraced(function* (leaves, required = []) {
|
|
231
266
|
const path = yield* Path.Path;
|
|
232
267
|
const confectDirectory = yield* ConfectDirectory.get;
|
|
233
268
|
const implementationPaths = yield* Effect.forEach(leaves, ({ relativePath }) => implPathForSpec(relativePath).pipe(Effect.map((implPath) => path.resolve(confectDirectory, implPath))));
|
|
234
|
-
yield* withBatch(implementationPaths, Effect.forEach(leaves, validateImpl, {
|
|
235
|
-
|
|
236
|
-
discard: true
|
|
237
|
-
}));
|
|
269
|
+
const missing = (yield* withBatch(implementationPaths, Effect.forEach(leaves, (leaf) => validateImpl(leaf, required), { concurrency: VALIDATION_CONCURRENCY }))).flat().sort((left, right) => left.functionName.localeCompare(right.functionName));
|
|
270
|
+
if (missing.length > 0) return yield* new RequiredMiddlewareError({ missing });
|
|
238
271
|
});
|
|
239
272
|
const loadAll = Effect.gen(function* () {
|
|
240
273
|
const fs = yield* FileSystem.FileSystem;
|