@gaganref/confect-cli 10.3.1-fork.85 → 10.3.1-fork.87
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/LeafModule.mjs +28 -7
- package/dist/LeafModule.mjs.map +1 -1
- package/dist/ManifestSections.mjs +74 -38
- package/dist/ManifestSections.mjs.map +1 -1
- package/dist/SectionFiles.mjs +111 -45
- package/dist/SectionFiles.mjs.map +1 -1
- package/dist/TableModule.mjs +2 -1
- package/dist/TableModule.mjs.map +1 -1
- package/dist/Watcher.mjs +4 -3
- package/dist/Watcher.mjs.map +1 -1
- package/dist/confect/codegen.mjs +17 -7
- package/dist/confect/codegen.mjs.map +1 -1
- package/dist/confect/declaration.mjs +10 -5
- package/dist/confect/declaration.mjs.map +1 -1
- package/dist/utils.mjs +14 -1
- package/dist/utils.mjs.map +1 -1
- package/package.json +3 -3
package/dist/SectionFiles.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import { bundle } from "./Bundler.mjs";
|
|
|
4
4
|
import { InvalidManifestSectionError, logCodegenError } from "./CodegenError.mjs";
|
|
5
5
|
import { ConfectDirectory } from "./ConfectDirectory.mjs";
|
|
6
6
|
import { removePathIfExists, toPosixPath, writeFileStringAndLog } from "./utils.mjs";
|
|
7
|
+
import { componentConfigPlugin } from "./ConvexConfig.mjs";
|
|
7
8
|
import * as Effect from "effect/Effect";
|
|
8
9
|
import * as FileSystem from "effect/FileSystem";
|
|
9
10
|
import * as Path from "effect/Path";
|
|
@@ -24,6 +25,7 @@ const Sources = Schema.fromJsonString(Schema.Array(Schema.String));
|
|
|
24
25
|
const encodeSources = Schema.encodeSync(Sources);
|
|
25
26
|
const decodeSources = Schema.decodeUnknownOption(Sources);
|
|
26
27
|
const INPUTS = "sectionInputs.json";
|
|
28
|
+
const VERIFY_INPUTS = "verifyInputs.json";
|
|
27
29
|
const visit = (leaves, each) => {
|
|
28
30
|
const walk = (group, path, source) => {
|
|
29
31
|
for (const spec of Object.values(group.functions)) each(spec, `${path}:${spec.name}`, source);
|
|
@@ -32,15 +34,13 @@ const visit = (leaves, each) => {
|
|
|
32
34
|
for (const leaf of leaves) walk(leaf.spec, leaf.pathSegments.join("/"), leaf.relativePath);
|
|
33
35
|
};
|
|
34
36
|
/**
|
|
35
|
-
* One claim per section
|
|
36
|
-
* is built in, not a `.ts` file directly in `_generated`, or claimed by
|
|
37
|
-
* keys is refused.
|
|
37
|
+
* One claim per declared section that generates a file, ordered by file. A name
|
|
38
|
+
* that is built in, not a `.ts` file directly in `_generated`, or claimed by
|
|
39
|
+
* two keys is refused.
|
|
38
40
|
*/
|
|
39
|
-
const claims = (
|
|
41
|
+
const claims = (sections) => Result.gen(function* () {
|
|
40
42
|
const byKey = /* @__PURE__ */ new Map();
|
|
41
|
-
|
|
42
|
-
for (const { key, section } of spec.manifestSections ?? []) if (section.generate !== void 0 && !byKey.has(key)) byKey.set(key, section.generate);
|
|
43
|
-
});
|
|
43
|
+
for (const { key, section } of sections) if (section.generate !== void 0) byKey.set(key, section.generate);
|
|
44
44
|
const byFile = /* @__PURE__ */ new Map();
|
|
45
45
|
for (const [key, { file }] of byKey) {
|
|
46
46
|
const other = byFile.get(file);
|
|
@@ -62,33 +62,54 @@ const sourceFiles = Effect.gen(function* () {
|
|
|
62
62
|
const confectDirectory = yield* ConfectDirectory.get;
|
|
63
63
|
return (yield* fs.readDirectory(confectDirectory, { recursive: true })).map((file) => toPosixPath(path, file)).filter((file) => file.endsWith(".ts") && !file.endsWith(".d.ts") && !file.split("/").includes("_generated")).sort();
|
|
64
64
|
});
|
|
65
|
-
|
|
65
|
+
/**
|
|
66
|
+
* Bundle each matched `confect/` file and return its exports, adding it and
|
|
67
|
+
* every first-party file it imports to `watched`.
|
|
68
|
+
*/
|
|
69
|
+
const load = Effect.fnUntraced(function* (matched, watched, plugins = []) {
|
|
66
70
|
const path = yield* Path.Path;
|
|
67
71
|
const confectDirectory = yield* ConfectDirectory.get;
|
|
68
|
-
const failed = (cause) => new InvalidManifestSectionError({
|
|
69
|
-
sectionKey: key,
|
|
70
|
-
reason: `generate failed: ${String(cause)}`
|
|
71
|
-
});
|
|
72
|
-
const matched = yield* Effect.try({
|
|
73
|
-
try: () => input.files.filter((file) => generate.match(file)),
|
|
74
|
-
catch: failed
|
|
75
|
-
});
|
|
76
72
|
for (const file of matched) watched.add(file);
|
|
77
|
-
|
|
73
|
+
return yield* Effect.forEach(matched, (relativePath) => {
|
|
78
74
|
const entry = path.join(confectDirectory, relativePath);
|
|
79
|
-
|
|
75
|
+
const recordInputs = {
|
|
80
76
|
name: "confect:section-inputs",
|
|
81
77
|
setup: (build) => build.onEnd(({ metafile }) => {
|
|
82
78
|
for (const loaded of Object.keys(metafile?.inputs ?? {})) {
|
|
79
|
+
if (/^[^/\\]+:/.test(loaded) && !path.isAbsolute(loaded)) continue;
|
|
83
80
|
const file = toPosixPath(path, path.relative(confectDirectory, path.resolve(path.dirname(entry), loaded)));
|
|
84
81
|
if (!file.startsWith("../") && !file.startsWith("_generated/")) watched.add(file);
|
|
85
82
|
}
|
|
86
83
|
})
|
|
87
|
-
}
|
|
84
|
+
};
|
|
85
|
+
return bundle(entry, { plugins: [...plugins, recordInputs] }).pipe(Effect.map(({ module }) => ({
|
|
88
86
|
relativePath,
|
|
89
87
|
exports: module
|
|
90
88
|
})), Effect.mapError((error) => fromBundlerError(`confect/${relativePath}`, error)));
|
|
91
89
|
});
|
|
90
|
+
});
|
|
91
|
+
/**
|
|
92
|
+
* Fail with the first of a section's refusals after logging the rest.
|
|
93
|
+
*/
|
|
94
|
+
const refuse = Effect.fnUntraced(function* (key, reasons) {
|
|
95
|
+
const [error, ...more] = reasons.map((reason) => new InvalidManifestSectionError({
|
|
96
|
+
sectionKey: key,
|
|
97
|
+
reason
|
|
98
|
+
}));
|
|
99
|
+
for (const other of more) yield* logCodegenError(other);
|
|
100
|
+
if (error !== void 0) return yield* error;
|
|
101
|
+
});
|
|
102
|
+
const render = Effect.fnUntraced(function* ({ key, generate }, target, input, watched) {
|
|
103
|
+
const confectDirectory = yield* ConfectDirectory.get;
|
|
104
|
+
const failed = (cause) => new InvalidManifestSectionError({
|
|
105
|
+
sectionKey: key,
|
|
106
|
+
reason: `generate failed: ${String(cause)}`
|
|
107
|
+
});
|
|
108
|
+
const matched = yield* Effect.try({
|
|
109
|
+
try: () => input.files.filter((file) => generate.match(file)),
|
|
110
|
+
catch: failed
|
|
111
|
+
});
|
|
112
|
+
const modules = yield* load(matched, watched);
|
|
92
113
|
const { contents, errors } = yield* Effect.try({
|
|
93
114
|
try: () => generate.render({
|
|
94
115
|
...input,
|
|
@@ -98,12 +119,7 @@ const render = Effect.fnUntraced(function* ({ key, generate }, target, input, wa
|
|
|
98
119
|
}),
|
|
99
120
|
catch: failed
|
|
100
121
|
});
|
|
101
|
-
|
|
102
|
-
sectionKey: key,
|
|
103
|
-
reason
|
|
104
|
-
}));
|
|
105
|
-
for (const other of more) yield* logCodegenError(other);
|
|
106
|
-
if (error !== void 0) return yield* error;
|
|
122
|
+
yield* refuse(key, errors);
|
|
107
123
|
return {
|
|
108
124
|
modules,
|
|
109
125
|
contents: [
|
|
@@ -123,32 +139,34 @@ const written = Effect.gen(function* () {
|
|
|
123
139
|
if (!(yield* fs.exists(generated))) return [];
|
|
124
140
|
return yield* Effect.filter((yield* fs.readDirectory(generated)).filter((file) => file.endsWith(".ts")), (file) => fs.readFileString(path.join(generated, file)).pipe(Effect.map((contents) => contents.startsWith(PREFIX))));
|
|
125
141
|
});
|
|
126
|
-
|
|
127
|
-
* The `confect/` files the generating sections matched and the `confect/` files
|
|
128
|
-
* those import, as recorded by the last codegen run that loaded them.
|
|
129
|
-
*/
|
|
130
|
-
const inputs = Effect.gen(function* () {
|
|
142
|
+
const record = Effect.fnUntraced(function* (name) {
|
|
131
143
|
const fs = yield* FileSystem.FileSystem;
|
|
132
|
-
const
|
|
144
|
+
const file = (yield* Path.Path).join(yield* ConfectDirectory.get, "_generated", name);
|
|
133
145
|
const none = [];
|
|
134
|
-
if (!(yield* fs.exists(
|
|
135
|
-
return Option.getOrElse(decodeSources(yield* fs.readFileString(
|
|
146
|
+
if (!(yield* fs.exists(file))) return none;
|
|
147
|
+
return Option.getOrElse(decodeSources(yield* fs.readFileString(file)), () => none);
|
|
136
148
|
});
|
|
137
149
|
/**
|
|
138
|
-
*
|
|
139
|
-
*
|
|
140
|
-
*
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
*
|
|
150
|
+
* The `confect/` files the declared sections' `generate` and `verify` matched
|
|
151
|
+
* and the `confect/` files those import, as recorded by the last codegen run
|
|
152
|
+
* that loaded them.
|
|
153
|
+
*/
|
|
154
|
+
const inputs = Effect.map(Effect.all([record(INPUTS), record(VERIFY_INPUTS)]), ([rendered, verified]) => [.../* @__PURE__ */ new Set([...rendered, ...verified])].sort());
|
|
155
|
+
/**
|
|
156
|
+
* Write each claimed file into `confect/_generated` once every section the
|
|
157
|
+
* declared backend names has rendered for its target; an undeclared backend
|
|
158
|
+
* renders none. Every section renders before codegen fails with the first error
|
|
159
|
+
* after logging the rest. The record of section inputs is written either way,
|
|
160
|
+
* keeping the previous inputs after a failure, so `confect dev` sees the fix.
|
|
161
|
+
* Returns the claimed file names, whether they differ from the section files
|
|
162
|
+
* that existed before, and the modules each section key matched.
|
|
145
163
|
*/
|
|
146
|
-
const sync = Effect.fnUntraced(function* (
|
|
164
|
+
const sync = Effect.fnUntraced(function* (backend, leaves, mounts) {
|
|
147
165
|
const path = yield* Path.Path;
|
|
148
166
|
const generated = path.join(yield* ConfectDirectory.get, "_generated");
|
|
149
|
-
const claimed = Option.isSome(
|
|
167
|
+
const claimed = Option.isSome(backend) ? (yield* Effect.fromResult(claims(backend.value.sections))).map((claim) => ({
|
|
150
168
|
claim,
|
|
151
|
-
target:
|
|
169
|
+
target: backend.value.target
|
|
152
170
|
})) : [];
|
|
153
171
|
const functions = [];
|
|
154
172
|
visit(leaves, (_, functionPath, source) => functions.push({
|
|
@@ -165,7 +183,7 @@ const sync = Effect.fnUntraced(function* (declared, leaves, mounts) {
|
|
|
165
183
|
...claim,
|
|
166
184
|
...output
|
|
167
185
|
}))));
|
|
168
|
-
if (failures.length > 0) for (const file of yield*
|
|
186
|
+
if (failures.length > 0) for (const file of yield* record(INPUTS)) watched.add(file);
|
|
169
187
|
yield* claimed.length === 0 ? removePathIfExists(path.join(generated, INPUTS)) : writeFileStringAndLog(path.join(generated, INPUTS), encodeSources([...watched].sort()));
|
|
170
188
|
const [error, ...more] = failures;
|
|
171
189
|
for (const other of more) yield* logCodegenError(other);
|
|
@@ -180,6 +198,54 @@ const sync = Effect.fnUntraced(function* (declared, leaves, mounts) {
|
|
|
180
198
|
};
|
|
181
199
|
});
|
|
182
200
|
/**
|
|
201
|
+
* Run each declared section's `verify` once every `_generated` file exists:
|
|
202
|
+
* bundle the `confect/` files its `match` selects as codegen bundles a
|
|
203
|
+
* declaration, and hand their exports, the mounts and the target to its
|
|
204
|
+
* `check`. Every section checks before codegen fails with the first refusal
|
|
205
|
+
* after logging the rest. The files each loaded are recorded as section inputs,
|
|
206
|
+
* keeping the previous ones after a failure, so `confect dev` checks again when
|
|
207
|
+
* one changes.
|
|
208
|
+
*/
|
|
209
|
+
const verify = Effect.fnUntraced(function* (backend, mounts) {
|
|
210
|
+
const path = yield* Path.Path;
|
|
211
|
+
const recorded = path.join(yield* ConfectDirectory.get, "_generated", VERIFY_INPUTS);
|
|
212
|
+
const checks = Option.match(backend, {
|
|
213
|
+
onNone: () => [],
|
|
214
|
+
onSome: ({ sections }) => sections.flatMap(({ key, section }) => section.generate?.verify === void 0 ? [] : [{
|
|
215
|
+
key,
|
|
216
|
+
verifier: section.generate.verify
|
|
217
|
+
}])
|
|
218
|
+
});
|
|
219
|
+
if (Option.isNone(backend) || checks.length === 0) return yield* removePathIfExists(recorded);
|
|
220
|
+
const { target } = backend.value;
|
|
221
|
+
const files = yield* sourceFiles;
|
|
222
|
+
const watched = /* @__PURE__ */ new Set();
|
|
223
|
+
const [, failures] = yield* Effect.partition(checks, ({ key, verifier }) => Effect.gen(function* () {
|
|
224
|
+
const failed = (cause) => new InvalidManifestSectionError({
|
|
225
|
+
sectionKey: key,
|
|
226
|
+
reason: `verify failed: ${String(cause)}`
|
|
227
|
+
});
|
|
228
|
+
const matched = yield* Effect.try({
|
|
229
|
+
try: () => files.filter((file) => verifier.match(file)),
|
|
230
|
+
catch: failed
|
|
231
|
+
});
|
|
232
|
+
const modules = yield* load(matched, watched, [componentConfigPlugin(path)]);
|
|
233
|
+
yield* refuse(key, yield* Effect.try({
|
|
234
|
+
try: () => verifier.check({
|
|
235
|
+
modules,
|
|
236
|
+
mounts,
|
|
237
|
+
target
|
|
238
|
+
}),
|
|
239
|
+
catch: failed
|
|
240
|
+
}));
|
|
241
|
+
}));
|
|
242
|
+
if (failures.length > 0) for (const file of yield* record(VERIFY_INPUTS)) watched.add(file);
|
|
243
|
+
yield* writeFileStringAndLog(recorded, encodeSources([...watched].sort()));
|
|
244
|
+
const [error, ...more] = failures;
|
|
245
|
+
for (const other of more) yield* logCodegenError(other);
|
|
246
|
+
if (error !== void 0) return yield* error;
|
|
247
|
+
});
|
|
248
|
+
/**
|
|
183
249
|
* Remove each file a section wrote that is not in `files`. Codegen runs this
|
|
184
250
|
* after it rewrites the registration files and the HTTP router, so a run that
|
|
185
251
|
* fails earlier leaves no import of a removed file.
|
|
@@ -193,6 +259,6 @@ const removeUnclaimed = Effect.fnUntraced(function* (files) {
|
|
|
193
259
|
}
|
|
194
260
|
});
|
|
195
261
|
//#endregion
|
|
196
|
-
export { builtIn, claims, inputs, removeUnclaimed, sync, written };
|
|
262
|
+
export { builtIn, claims, inputs, removeUnclaimed, sync, verify, written };
|
|
197
263
|
|
|
198
264
|
//# sourceMappingURL=SectionFiles.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SectionFiles.mjs","names":["Bundler.bundle"],"sources":["../src/SectionFiles.ts"],"sourcesContent":["import type { FunctionSpec, GroupSpec, ManifestSection } from \"@confect/core\";\nimport type * as esbuild from \"esbuild\";\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 Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport { fromBundlerError } from \"./BuildError.js\";\nimport * as Bundler from \"./Bundler.js\";\nimport {\n InvalidManifestSectionError,\n logCodegenError,\n} from \"./CodegenError.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport type { LoadedLeafModule } from \"./LeafModule.js\";\nimport { logFileRemoved } from \"./log.js\";\nimport {\n removePathIfExists,\n toPosixPath,\n writeFileStringAndLog,\n} from \"./utils.js\";\n\ntype Leaf = Pick<LoadedLeafModule, \"spec\" | \"pathSegments\" | \"relativePath\">;\n\n/**\n * The files codegen writes directly in `confect/_generated`, current and\n * legacy, which no section may claim.\n */\nexport const builtIn: ReadonlySet<string> = new Set(\n `spec schema convexSchema id components component refs docs services manifest\n auth.providers testing api nodeApi impl nodeImpl nodeSpec registeredFunctions\n nodeRegisteredFunctions`\n .split(/\\s+/)\n .map((name) => `${name}.ts`),\n);\n\nconst PREFIX = \"// Generated by `confect codegen` from the manifest section \";\nconst header = (key: string) => `${PREFIX}${JSON.stringify(key)}. Do not edit.`;\nconst Sources = Schema.fromJsonString(Schema.Array(Schema.String));\nconst encodeSources = Schema.encodeSync(Sources);\nconst decodeSources = Schema.decodeUnknownOption(Sources);\nconst INPUTS = \"sectionInputs.json\";\n\ninterface Claim {\n readonly key: string;\n readonly generate: ManifestSection.Generate;\n}\n\nconst visit = (\n leaves: ReadonlyArray<Leaf>,\n each: (spec: FunctionSpec.AnyWithProps, path: string, source: string) => void,\n) => {\n const walk = (\n group: GroupSpec.AnyWithProps,\n path: string,\n source: string,\n ) => {\n for (const spec of Object.values(group.functions))\n each(spec, `${path}:${spec.name}`, source);\n for (const [name, child] of Object.entries(group.groups))\n walk(child, `${path}/${name}`, source);\n };\n for (const leaf of leaves)\n walk(leaf.spec, leaf.pathSegments.join(\"/\"), leaf.relativePath);\n};\n\n/**\n * One claim per section key that generates a file, ordered by file. A name that\n * is built in, not a `.ts` file directly in `_generated`, or claimed by two\n * keys is refused.\n */\nexport const claims = (leaves: ReadonlyArray<Leaf>) =>\n Result.gen(function* () {\n const byKey = new Map<string, ManifestSection.Generate>();\n visit(leaves, (spec) => {\n for (const { key, section } of spec.manifestSections ?? [])\n if (section.generate !== undefined && !byKey.has(key))\n byKey.set(key, section.generate);\n });\n const byFile = new Map<string, string>();\n for (const [key, { file }] of byKey) {\n const other = byFile.get(file);\n const refusal = builtIn.has(file)\n ? `claims confect/_generated/${file}, which codegen writes itself.`\n : !/^[\\w-]+\\.ts$/.test(file)\n ? `claims ${JSON.stringify(file)}; name a .ts file directly inside confect/_generated.`\n : other !== undefined\n ? `claims confect/_generated/${file}, which the manifest section ${JSON.stringify(other)} also claims.`\n : undefined;\n if (refusal !== undefined)\n return yield* Result.fail(\n new InvalidManifestSectionError({ sectionKey: key, reason: refusal }),\n );\n byFile.set(file, key);\n }\n return [...byKey]\n .map(([key, generate]) => ({ key, generate }))\n .sort((a, b) => a.generate.file.localeCompare(b.generate.file));\n });\n\nconst sourceFiles = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n return (yield* fs.readDirectory(confectDirectory, { recursive: true }))\n .map((file) => toPosixPath(path, file))\n .filter(\n (file) =>\n file.endsWith(\".ts\") &&\n !file.endsWith(\".d.ts\") &&\n !file.split(\"/\").includes(\"_generated\"),\n )\n .sort();\n});\n\nconst render = Effect.fnUntraced(function* (\n { key, generate }: Claim,\n target: ManifestSection.Target,\n input: Pick<ManifestSection.GenerateInput, \"functions\" | \"mounts\" | \"files\">,\n watched: Set<string>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const failed = (cause: unknown) =>\n new InvalidManifestSectionError({\n sectionKey: key,\n reason: `generate failed: ${String(cause)}`,\n });\n const matched = yield* Effect.try({\n try: () => input.files.filter((file) => generate.match(file)),\n catch: failed,\n });\n for (const file of matched) watched.add(file);\n const modules = yield* Effect.forEach(matched, (relativePath) => {\n const entry = path.join(confectDirectory, relativePath);\n // Inputs are recorded once esbuild finishes, before the module runs, so a\n // module that throws on load still has its imports watched. `confect dev`\n // sees changes only under `confect/`, and every run rewrites `_generated`,\n // so watching it would loop.\n const recordInputs: esbuild.Plugin = {\n name: \"confect:section-inputs\",\n setup: (build) =>\n build.onEnd(({ metafile }) => {\n for (const loaded of Object.keys(metafile?.inputs ?? {})) {\n const file = toPosixPath(\n path,\n path.relative(\n confectDirectory,\n path.resolve(path.dirname(entry), loaded),\n ),\n );\n if (!file.startsWith(\"../\") && !file.startsWith(\"_generated/\"))\n watched.add(file);\n }\n }),\n };\n return Bundler.bundle(entry, { plugins: [recordInputs] }).pipe(\n Effect.map(({ module }) => ({ relativePath, exports: module })),\n Effect.mapError((error) =>\n fromBundlerError(`confect/${relativePath}`, error),\n ),\n );\n });\n const { contents, errors } = yield* Effect.try({\n try: () => generate.render({ ...input, modules, target, confectDirectory }),\n catch: failed,\n });\n const [error, ...more] = errors.map(\n (reason) => new InvalidManifestSectionError({ sectionKey: key, reason }),\n );\n for (const other of more) yield* logCodegenError(other);\n if (error !== undefined) return yield* error;\n return {\n modules,\n contents: [\n header(key),\n `// Sources: ${encodeSources(matched)}`,\n contents,\n ].join(\"\\n\"),\n };\n});\n\n/**\n * The files in `confect/_generated` a section wrote, which carry its header.\n */\nexport const written = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const generated = path.join(yield* ConfectDirectory.get, \"_generated\");\n if (!(yield* fs.exists(generated))) return [];\n return yield* Effect.filter(\n (yield* fs.readDirectory(generated)).filter((file) => file.endsWith(\".ts\")),\n (file) =>\n fs\n .readFileString(path.join(generated, file))\n .pipe(Effect.map((contents) => contents.startsWith(PREFIX))),\n );\n});\n\n/**\n * The `confect/` files the generating sections matched and the `confect/` files\n * those import, as recorded by the last codegen run that loaded them.\n */\nexport const inputs = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const record = path.join(yield* ConfectDirectory.get, \"_generated\", INPUTS);\n const none: ReadonlyArray<string> = [];\n if (!(yield* fs.exists(record))) return none;\n return Option.getOrElse(\n decodeSources(yield* fs.readFileString(record)),\n () => none,\n );\n});\n\n/**\n * Write each claimed file into `confect/_generated` once every section has\n * rendered for the `declared` backend's target; an undeclared backend renders\n * none. Every section renders before codegen fails with the first error after\n * logging the rest. The record of section inputs is written either way, keeping\n * the previous inputs after a failure, so `confect dev` sees the fix. Returns\n * the claimed file names, whether they differ from the section files that\n * existed before, and the modules each section key matched.\n */\nexport const sync = Effect.fnUntraced(function* (\n declared: Option.Option<ManifestSection.Target>,\n leaves: ReadonlyArray<Leaf>,\n mounts: ManifestSection.GenerateInput[\"mounts\"],\n) {\n const path = yield* Path.Path;\n const generated = path.join(yield* ConfectDirectory.get, \"_generated\");\n const claimed = Option.isSome(declared)\n ? (yield* Effect.fromResult(claims(leaves))).map((claim) => ({\n claim,\n target: declared.value,\n }))\n : [];\n const functions: Array<{ path: string; source: string }> = [];\n visit(leaves, (_, functionPath, source) =>\n functions.push({ path: functionPath, source }),\n );\n const files = claimed.length === 0 ? [] : yield* sourceFiles;\n const watched = new Set<string>();\n const [rendered, failures] = yield* Effect.partition(\n claimed,\n ({ claim, target }) =>\n render(claim, target, { functions, mounts, files }, watched).pipe(\n Effect.map((output) => ({ ...claim, ...output })),\n ),\n );\n if (failures.length > 0) for (const file of yield* inputs) watched.add(file);\n yield* claimed.length === 0\n ? removePathIfExists(path.join(generated, INPUTS))\n : writeFileStringAndLog(\n path.join(generated, INPUTS),\n encodeSources([...watched].sort()),\n );\n const [error, ...more] = failures;\n for (const other of more) yield* logCodegenError(other);\n if (error !== undefined) return yield* error;\n const existing = yield* written;\n for (const { generate, contents } of rendered)\n yield* writeFileStringAndLog(path.join(generated, generate.file), contents);\n const names = rendered.map(({ generate }) => generate.file);\n return {\n modules: new Map(rendered.map(({ key, modules }) => [key, modules])),\n files: names,\n changed:\n names.length !== existing.length ||\n names.some((file) => !existing.includes(file)),\n };\n});\n\n/**\n * Remove each file a section wrote that is not in `files`. Codegen runs this\n * after it rewrites the registration files and the HTTP router, so a run that\n * fails earlier leaves no import of a removed file.\n */\nexport const removeUnclaimed = Effect.fnUntraced(function* (\n files: ReadonlyArray<string>,\n) {\n const path = yield* Path.Path;\n const generated = path.join(yield* ConfectDirectory.get, \"_generated\");\n for (const file of yield* written)\n if (!files.includes(file)) {\n yield* removePathIfExists(path.join(generated, file));\n yield* logFileRemoved(path.join(generated, file));\n }\n});\n"],"mappings":";;;;;;;;;;;;;;;;;AA6BA,MAAa,UAA+B,IAAI,IAC9C;;2BAGG,MAAM,KAAK,CAAC,CACZ,KAAK,SAAS,GAAG,KAAK,IAAI,CAC/B;AAEA,MAAM,SAAS;AACf,MAAM,UAAU,QAAgB,GAAG,SAAS,KAAK,UAAU,GAAG,EAAE;AAChE,MAAM,UAAU,OAAO,eAAe,OAAO,MAAM,OAAO,MAAM,CAAC;AACjE,MAAM,gBAAgB,OAAO,WAAW,OAAO;AAC/C,MAAM,gBAAgB,OAAO,oBAAoB,OAAO;AACxD,MAAM,SAAS;AAOf,MAAM,SACJ,QACA,SACG;CACH,MAAM,QACJ,OACA,MACA,WACG;EACH,KAAK,MAAM,QAAQ,OAAO,OAAO,MAAM,SAAS,GAC9C,KAAK,MAAM,GAAG,KAAK,GAAG,KAAK,QAAQ,MAAM;EAC3C,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,MAAM,MAAM,GACrD,KAAK,OAAO,GAAG,KAAK,GAAG,QAAQ,MAAM;CACzC;CACA,KAAK,MAAM,QAAQ,QACjB,KAAK,KAAK,MAAM,KAAK,aAAa,KAAK,GAAG,GAAG,KAAK,YAA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,KAAK,EAAE,KAAK,cAAc,CAAC,KAAK,OAAO,CAAC,CAAC;EACnE,OAAO;EACP,SACE,MAAM,WAAW,SAAS,UAC1B,MAAM,MAAM,SAAS,CAAC,SAAS,SAAS,IAAI,CAAC;CACjD;AACF,CAAC;;;;;;AAOD,MAAa,kBAAkB,OAAO,WAAW,WAC/C,OACA;CACA,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,YAAY,KAAK,KAAK,OAAO,iBAAiB,KAAK,YAAY;CACrE,KAAK,MAAM,QAAQ,OAAO,SACxB,IAAI,CAAC,MAAM,SAAS,IAAI,GAAG;EACzB,OAAO,mBAAmB,KAAK,KAAK,WAAW,IAAI,CAAC;EACpD,OAAO,eAAe,KAAK,KAAK,WAAW,IAAI,CAAC;CAClD;AACJ,CAAC"}
|
|
1
|
+
{"version":3,"file":"SectionFiles.mjs","names":["Bundler.bundle","ConvexConfig.componentConfigPlugin"],"sources":["../src/SectionFiles.ts"],"sourcesContent":["import type { FunctionSpec, GroupSpec, ManifestSection } from \"@confect/core\";\nimport type * as esbuild from \"esbuild\";\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 Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport { fromBundlerError } from \"./BuildError.js\";\nimport * as Bundler from \"./Bundler.js\";\nimport {\n InvalidManifestSectionError,\n logCodegenError,\n} from \"./CodegenError.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport * as ConvexConfig from \"./ConvexConfig.js\";\nimport type { LoadedLeafModule } from \"./LeafModule.js\";\nimport { logFileRemoved } from \"./log.js\";\nimport {\n removePathIfExists,\n toPosixPath,\n writeFileStringAndLog,\n} from \"./utils.js\";\n\ntype Leaf = Pick<LoadedLeafModule, \"spec\" | \"pathSegments\" | \"relativePath\">;\n\n/**\n * The files codegen writes directly in `confect/_generated`, current and\n * legacy, which no section may claim.\n */\nexport const builtIn: ReadonlySet<string> = new Set(\n `spec schema convexSchema id components component refs docs services manifest\n auth.providers testing api nodeApi impl nodeImpl nodeSpec registeredFunctions\n nodeRegisteredFunctions`\n .split(/\\s+/)\n .map((name) => `${name}.ts`),\n);\n\nconst PREFIX = \"// Generated by `confect codegen` from the manifest section \";\nconst header = (key: string) => `${PREFIX}${JSON.stringify(key)}. Do not edit.`;\nconst Sources = Schema.fromJsonString(Schema.Array(Schema.String));\nconst encodeSources = Schema.encodeSync(Sources);\nconst decodeSources = Schema.decodeUnknownOption(Sources);\nconst INPUTS = \"sectionInputs.json\";\nconst VERIFY_INPUTS = \"verifyInputs.json\";\n\ninterface Claim {\n readonly key: string;\n readonly generate: ManifestSection.Generate;\n}\n\n/**\n * A declared backend: the target codegen generates and the sections its\n * `App.make` names.\n */\nexport interface Backend {\n readonly target: ManifestSection.Target;\n readonly sections: ReadonlyArray<ManifestSection.Entry>;\n}\n\nconst visit = (\n leaves: ReadonlyArray<Leaf>,\n each: (spec: FunctionSpec.AnyWithProps, path: string, source: string) => void,\n) => {\n const walk = (\n group: GroupSpec.AnyWithProps,\n path: string,\n source: string,\n ) => {\n for (const spec of Object.values(group.functions))\n each(spec, `${path}:${spec.name}`, source);\n for (const [name, child] of Object.entries(group.groups))\n walk(child, `${path}/${name}`, source);\n };\n for (const leaf of leaves)\n walk(leaf.spec, leaf.pathSegments.join(\"/\"), leaf.relativePath);\n};\n\n/**\n * One claim per declared section that generates a file, ordered by file. A name\n * that is built in, not a `.ts` file directly in `_generated`, or claimed by\n * two keys is refused.\n */\nexport const claims = (sections: ReadonlyArray<ManifestSection.Entry>) =>\n Result.gen(function* () {\n const byKey = new Map<string, ManifestSection.Generate>();\n for (const { key, section } of sections)\n if (section.generate !== undefined) byKey.set(key, section.generate);\n const byFile = new Map<string, string>();\n for (const [key, { file }] of byKey) {\n const other = byFile.get(file);\n const refusal = builtIn.has(file)\n ? `claims confect/_generated/${file}, which codegen writes itself.`\n : !/^[\\w-]+\\.ts$/.test(file)\n ? `claims ${JSON.stringify(file)}; name a .ts file directly inside confect/_generated.`\n : other !== undefined\n ? `claims confect/_generated/${file}, which the manifest section ${JSON.stringify(other)} also claims.`\n : undefined;\n if (refusal !== undefined)\n return yield* Result.fail(\n new InvalidManifestSectionError({ sectionKey: key, reason: refusal }),\n );\n byFile.set(file, key);\n }\n return [...byKey]\n .map(([key, generate]) => ({ key, generate }))\n .sort((a, b) => a.generate.file.localeCompare(b.generate.file));\n });\n\nconst sourceFiles = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n return (yield* fs.readDirectory(confectDirectory, { recursive: true }))\n .map((file) => toPosixPath(path, file))\n .filter(\n (file) =>\n file.endsWith(\".ts\") &&\n !file.endsWith(\".d.ts\") &&\n !file.split(\"/\").includes(\"_generated\"),\n )\n .sort();\n});\n\n/**\n * Bundle each matched `confect/` file and return its exports, adding it and\n * every first-party file it imports to `watched`.\n */\nconst load = Effect.fnUntraced(function* (\n matched: ReadonlyArray<string>,\n watched: Set<string>,\n plugins: ReadonlyArray<esbuild.Plugin> = [],\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n for (const file of matched) watched.add(file);\n return yield* Effect.forEach(matched, (relativePath) => {\n const entry = path.join(confectDirectory, relativePath);\n // Inputs are recorded once esbuild finishes, before the module runs, so a\n // module that throws on load still has its imports watched. `confect dev`\n // sees changes only under `confect/`, and every run rewrites `_generated`,\n // so watching it would loop.\n const recordInputs: esbuild.Plugin = {\n name: \"confect:section-inputs\",\n setup: (build) =>\n build.onEnd(({ metafile }) => {\n for (const loaded of Object.keys(metafile?.inputs ?? {})) {\n // A plugin's own namespace, such as the component config\n // wrapper, is not a file.\n if (/^[^/\\\\]+:/.test(loaded) && !path.isAbsolute(loaded)) continue;\n const file = toPosixPath(\n path,\n path.relative(\n confectDirectory,\n path.resolve(path.dirname(entry), loaded),\n ),\n );\n if (!file.startsWith(\"../\") && !file.startsWith(\"_generated/\"))\n watched.add(file);\n }\n }),\n };\n return Bundler.bundle(entry, { plugins: [...plugins, recordInputs] }).pipe(\n Effect.map(({ module }) => ({ relativePath, exports: module })),\n Effect.mapError((error) =>\n fromBundlerError(`confect/${relativePath}`, error),\n ),\n );\n });\n});\n\n/**\n * Fail with the first of a section's refusals after logging the rest.\n */\nconst refuse = Effect.fnUntraced(function* (\n key: string,\n reasons: ReadonlyArray<string>,\n) {\n const [error, ...more] = reasons.map(\n (reason) => new InvalidManifestSectionError({ sectionKey: key, reason }),\n );\n for (const other of more) yield* logCodegenError(other);\n if (error !== undefined) return yield* error;\n});\n\nconst render = Effect.fnUntraced(function* (\n { key, generate }: Claim,\n target: ManifestSection.Target,\n input: Pick<ManifestSection.GenerateInput, \"functions\" | \"mounts\" | \"files\">,\n watched: Set<string>,\n) {\n const confectDirectory = yield* ConfectDirectory.get;\n const failed = (cause: unknown) =>\n new InvalidManifestSectionError({\n sectionKey: key,\n reason: `generate failed: ${String(cause)}`,\n });\n const matched = yield* Effect.try({\n try: () => input.files.filter((file) => generate.match(file)),\n catch: failed,\n });\n const modules = yield* load(matched, watched);\n const { contents, errors } = yield* Effect.try({\n try: () => generate.render({ ...input, modules, target, confectDirectory }),\n catch: failed,\n });\n yield* refuse(key, errors);\n return {\n modules,\n contents: [\n header(key),\n `// Sources: ${encodeSources(matched)}`,\n contents,\n ].join(\"\\n\"),\n };\n});\n\n/**\n * The files in `confect/_generated` a section wrote, which carry its header.\n */\nexport const written = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const generated = path.join(yield* ConfectDirectory.get, \"_generated\");\n if (!(yield* fs.exists(generated))) return [];\n return yield* Effect.filter(\n (yield* fs.readDirectory(generated)).filter((file) => file.endsWith(\".ts\")),\n (file) =>\n fs\n .readFileString(path.join(generated, file))\n .pipe(Effect.map((contents) => contents.startsWith(PREFIX))),\n );\n});\n\nconst record = Effect.fnUntraced(function* (name: string) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const file = path.join(yield* ConfectDirectory.get, \"_generated\", name);\n const none: ReadonlyArray<string> = [];\n if (!(yield* fs.exists(file))) return none;\n return Option.getOrElse(\n decodeSources(yield* fs.readFileString(file)),\n () => none,\n );\n});\n\n/**\n * The `confect/` files the declared sections' `generate` and `verify` matched\n * and the `confect/` files those import, as recorded by the last codegen run\n * that loaded them.\n */\nexport const inputs = Effect.map(\n Effect.all([record(INPUTS), record(VERIFY_INPUTS)]),\n ([rendered, verified]) => [...new Set([...rendered, ...verified])].sort(),\n);\n\n/**\n * Write each claimed file into `confect/_generated` once every section the\n * declared backend names has rendered for its target; an undeclared backend\n * renders none. Every section renders before codegen fails with the first error\n * after logging the rest. The record of section inputs is written either way,\n * keeping the previous inputs after a failure, so `confect dev` sees the fix.\n * Returns the claimed file names, whether they differ from the section files\n * that existed before, and the modules each section key matched.\n */\nexport const sync = Effect.fnUntraced(function* (\n backend: Option.Option<Backend>,\n leaves: ReadonlyArray<Leaf>,\n mounts: ManifestSection.GenerateInput[\"mounts\"],\n) {\n const path = yield* Path.Path;\n const generated = path.join(yield* ConfectDirectory.get, \"_generated\");\n const claimed = Option.isSome(backend)\n ? (yield* Effect.fromResult(claims(backend.value.sections))).map(\n (claim) => ({ claim, target: backend.value.target }),\n )\n : [];\n const functions: Array<{ path: string; source: string }> = [];\n visit(leaves, (_, functionPath, source) =>\n functions.push({ path: functionPath, source }),\n );\n const files = claimed.length === 0 ? [] : yield* sourceFiles;\n const watched = new Set<string>();\n const [rendered, failures] = yield* Effect.partition(\n claimed,\n ({ claim, target }) =>\n render(claim, target, { functions, mounts, files }, watched).pipe(\n Effect.map((output) => ({ ...claim, ...output })),\n ),\n );\n if (failures.length > 0)\n for (const file of yield* record(INPUTS)) watched.add(file);\n yield* claimed.length === 0\n ? removePathIfExists(path.join(generated, INPUTS))\n : writeFileStringAndLog(\n path.join(generated, INPUTS),\n encodeSources([...watched].sort()),\n );\n const [error, ...more] = failures;\n for (const other of more) yield* logCodegenError(other);\n if (error !== undefined) return yield* error;\n const existing = yield* written;\n for (const { generate, contents } of rendered)\n yield* writeFileStringAndLog(path.join(generated, generate.file), contents);\n const names = rendered.map(({ generate }) => generate.file);\n return {\n modules: new Map(rendered.map(({ key, modules }) => [key, modules])),\n files: names,\n changed:\n names.length !== existing.length ||\n names.some((file) => !existing.includes(file)),\n };\n});\n\n/**\n * Run each declared section's `verify` once every `_generated` file exists:\n * bundle the `confect/` files its `match` selects as codegen bundles a\n * declaration, and hand their exports, the mounts and the target to its\n * `check`. Every section checks before codegen fails with the first refusal\n * after logging the rest. The files each loaded are recorded as section inputs,\n * keeping the previous ones after a failure, so `confect dev` checks again when\n * one changes.\n */\nexport const verify = Effect.fnUntraced(function* (\n backend: Option.Option<Backend>,\n mounts: ManifestSection.VerifyInput[\"mounts\"],\n) {\n const path = yield* Path.Path;\n const recorded = path.join(\n yield* ConfectDirectory.get,\n \"_generated\",\n VERIFY_INPUTS,\n );\n const checks = Option.match(backend, {\n onNone: () => [],\n onSome: ({ sections }) =>\n sections.flatMap(({ key, section }) =>\n section.generate?.verify === undefined\n ? []\n : [{ key, verifier: section.generate.verify }],\n ),\n });\n if (Option.isNone(backend) || checks.length === 0)\n return yield* removePathIfExists(recorded);\n const { target } = backend.value;\n const files = yield* sourceFiles;\n const watched = new Set<string>();\n const [, failures] = yield* Effect.partition(checks, ({ key, verifier }) =>\n Effect.gen(function* () {\n const failed = (cause: unknown) =>\n new InvalidManifestSectionError({\n sectionKey: key,\n reason: `verify failed: ${String(cause)}`,\n });\n const matched = yield* Effect.try({\n try: () => files.filter((file) => verifier.match(file)),\n catch: failed,\n });\n const modules = yield* load(matched, watched, [\n ConvexConfig.componentConfigPlugin(path),\n ]);\n yield* refuse(\n key,\n yield* Effect.try({\n try: () => verifier.check({ modules, mounts, target }),\n catch: failed,\n }),\n );\n }),\n );\n if (failures.length > 0)\n for (const file of yield* record(VERIFY_INPUTS)) watched.add(file);\n yield* writeFileStringAndLog(recorded, encodeSources([...watched].sort()));\n const [error, ...more] = failures;\n for (const other of more) yield* logCodegenError(other);\n if (error !== undefined) return yield* error;\n});\n\n/**\n * Remove each file a section wrote that is not in `files`. Codegen runs this\n * after it rewrites the registration files and the HTTP router, so a run that\n * fails earlier leaves no import of a removed file.\n */\nexport const removeUnclaimed = Effect.fnUntraced(function* (\n files: ReadonlyArray<string>,\n) {\n const path = yield* Path.Path;\n const generated = path.join(yield* ConfectDirectory.get, \"_generated\");\n for (const file of yield* written)\n if (!files.includes(file)) {\n yield* removePathIfExists(path.join(generated, file));\n yield* logFileRemoved(path.join(generated, file));\n }\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;AA8BA,MAAa,UAA+B,IAAI,IAC9C;;2BAGG,MAAM,KAAK,CAAC,CACZ,KAAK,SAAS,GAAG,KAAK,IAAI,CAC/B;AAEA,MAAM,SAAS;AACf,MAAM,UAAU,QAAgB,GAAG,SAAS,KAAK,UAAU,GAAG,EAAE;AAChE,MAAM,UAAU,OAAO,eAAe,OAAO,MAAM,OAAO,MAAM,CAAC;AACjE,MAAM,gBAAgB,OAAO,WAAW,OAAO;AAC/C,MAAM,gBAAgB,OAAO,oBAAoB,OAAO;AACxD,MAAM,SAAS;AACf,MAAM,gBAAgB;AAgBtB,MAAM,SACJ,QACA,SACG;CACH,MAAM,QACJ,OACA,MACA,WACG;EACH,KAAK,MAAM,QAAQ,OAAO,OAAO,MAAM,SAAS,GAC9C,KAAK,MAAM,GAAG,KAAK,GAAG,KAAK,QAAQ,MAAM;EAC3C,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,MAAM,MAAM,GACrD,KAAK,OAAO,GAAG,KAAK,GAAG,QAAQ,MAAM;CACzC;CACA,KAAK,MAAM,QAAQ,QACjB,KAAK,KAAK,MAAM,KAAK,aAAa,KAAK,GAAG,GAAG,KAAK,YAAY;AAClE;;;;;;AAOA,MAAa,UAAU,aACrB,OAAO,IA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aAAa;EACtB,MAAM,UAAU,UACd,IAAI,4BAA4B;GAC9B,YAAY;GACZ,QAAQ,kBAAkB,OAAO,KAAK;EACxC,CAAC;EACH,MAAM,UAAU,OAAO,OAAO,IAAI;GAChC,WAAW,MAAM,QAAQ,SAAS,SAAS,MAAM,IAAI,CAAC;GACtD,OAAO;EACT,CAAC;EACD,MAAM,UAAU,OAAO,KAAK,SAAS,SAAS,CAC5CC,sBAAmC,IAAI,CACzC,CAAC;EACD,OAAO,OACL,KACA,OAAO,OAAO,IAAI;GAChB,WAAW,SAAS,MAAM;IAAE;IAAS;IAAQ;GAAO,CAAC;GACrD,OAAO;EACT,CAAC,CACH;CACF,CAAC,CACH;CACA,IAAI,SAAS,SAAS,GACpB,KAAK,MAAM,QAAQ,OAAO,OAAO,aAAa,GAAG,QAAQ,IAAI,IAAI;CACnE,OAAO,sBAAsB,UAAU,cAAc,CAAC,GAAG,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC;CACzE,MAAM,CAAC,OAAO,GAAG,QAAQ;CACzB,KAAK,MAAM,SAAS,MAAM,OAAO,gBAAgB,KAAK;CACtD,IAAI,UAAU,KAAA,GAAW,OAAO,OAAO;AACzC,CAAC;;;;;;AAOD,MAAa,kBAAkB,OAAO,WAAW,WAC/C,OACA;CACA,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,YAAY,KAAK,KAAK,OAAO,iBAAiB,KAAK,YAAY;CACrE,KAAK,MAAM,QAAQ,OAAO,SACxB,IAAI,CAAC,MAAM,SAAS,IAAI,GAAG;EACzB,OAAO,mBAAmB,KAAK,KAAK,WAAW,IAAI,CAAC;EACpD,OAAO,eAAe,KAAK,KAAK,WAAW,IAAI,CAAC;CAClD;AACJ,CAAC"}
|
package/dist/TableModule.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import { fromBundlerError } from "./BuildError.mjs";
|
|
|
2
2
|
import { bundle, withBatch } from "./Bundler.mjs";
|
|
3
3
|
import { DuplicateTableNameError, InvalidTableDefaultExportError, InvalidTableFilenameError } from "./CodegenError.mjs";
|
|
4
4
|
import { ConfectDirectory } from "./ConfectDirectory.mjs";
|
|
5
|
+
import { readDirectorySorted } from "./utils.mjs";
|
|
5
6
|
import * as Effect from "effect/Effect";
|
|
6
7
|
import { Identifier } from "@confect/core";
|
|
7
8
|
import * as FileSystem from "effect/FileSystem";
|
|
@@ -22,7 +23,7 @@ const discoverTableFiles = Effect.gen(function* () {
|
|
|
22
23
|
const confectDirectory = yield* ConfectDirectory.get;
|
|
23
24
|
const tablesDirectory = path.join(confectDirectory, TABLES_DIRNAME);
|
|
24
25
|
if (!(yield* fs.exists(tablesDirectory))) return [];
|
|
25
|
-
const allPaths = yield*
|
|
26
|
+
const allPaths = yield* readDirectorySorted(tablesDirectory);
|
|
26
27
|
return pipe(allPaths, Array.filter((p) => p.endsWith(".ts") && !p.endsWith(".test.ts")), Array.map((p) => path.join(TABLES_DIRNAME, p)));
|
|
27
28
|
});
|
|
28
29
|
const byTableName = Order.mapInput(Order.String, (tableModule) => tableModule.tableName);
|
package/dist/TableModule.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TableModule.mjs","names":["Bundler.bundle","Bundler.withBatch"],"sources":["../src/TableModule.ts"],"sourcesContent":["import { Identifier } from \"@confect/core\";\nimport * as Table from \"@confect/core/Table\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as Order from \"effect/Order\";\nimport { fromBundlerError } from \"./BuildError.js\";\nimport * as Bundler from \"./Bundler.js\";\nimport {\n DuplicateTableNameError,\n InvalidTableDefaultExportError,\n InvalidTableFilenameError,\n} from \"./CodegenError.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\n\nexport const TABLES_DIRNAME = \"tables\";\n\n/**\n * Discovered metadata for a single user-authored table module under\n * `confect/tables/`.\n *\n * - `relativePath`—path from `confect/` to the file (e.g. `tables/notes.ts`).\n * - `tableName`—the file basename (e.g. `notes`). This is also the import binding\n * used in generated files, and the table name surfaced to Convex.\n */\nexport interface TableModule {\n readonly relativePath: string;\n readonly tableName: string;\n}\n\nconst tableNameFromRelativePath = Effect.fnUntraced(function* (\n relativePath: string,\n) {\n const path = yield* Path.Path;\n const { name } = path.parse(relativePath);\n return name;\n});\n\nexport const discoverTableFiles = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const tablesDirectory = path.join(confectDirectory, TABLES_DIRNAME);\n\n if (!(yield* fs.exists(tablesDirectory))) {\n return [] as ReadonlyArray<string>;\n }\n\n const allPaths = yield*
|
|
1
|
+
{"version":3,"file":"TableModule.mjs","names":["Bundler.bundle","Bundler.withBatch"],"sources":["../src/TableModule.ts"],"sourcesContent":["import { Identifier } from \"@confect/core\";\nimport * as Table from \"@confect/core/Table\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as Order from \"effect/Order\";\nimport { fromBundlerError } from \"./BuildError.js\";\nimport * as Bundler from \"./Bundler.js\";\nimport {\n DuplicateTableNameError,\n InvalidTableDefaultExportError,\n InvalidTableFilenameError,\n} from \"./CodegenError.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport { readDirectorySorted } from \"./utils.js\";\n\nexport const TABLES_DIRNAME = \"tables\";\n\n/**\n * Discovered metadata for a single user-authored table module under\n * `confect/tables/`.\n *\n * - `relativePath`—path from `confect/` to the file (e.g. `tables/notes.ts`).\n * - `tableName`—the file basename (e.g. `notes`). This is also the import binding\n * used in generated files, and the table name surfaced to Convex.\n */\nexport interface TableModule {\n readonly relativePath: string;\n readonly tableName: string;\n}\n\nconst tableNameFromRelativePath = Effect.fnUntraced(function* (\n relativePath: string,\n) {\n const path = yield* Path.Path;\n const { name } = path.parse(relativePath);\n return name;\n});\n\nexport const discoverTableFiles = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const tablesDirectory = path.join(confectDirectory, TABLES_DIRNAME);\n\n if (!(yield* fs.exists(tablesDirectory))) {\n return [] as ReadonlyArray<string>;\n }\n\n const allPaths = yield* readDirectorySorted(tablesDirectory);\n\n return pipe(\n allPaths,\n Array.filter((p) => p.endsWith(\".ts\") && !p.endsWith(\".test.ts\")),\n Array.map((p) => path.join(TABLES_DIRNAME, p)),\n );\n});\n\nconst byTableName = Order.mapInput(\n Order.String,\n (tableModule: TableModule) => tableModule.tableName,\n);\n\n/**\n * Discover every `confect/tables/**\\/*.ts` module by listing the directory.\n * Validates that each filename is a legal table identifier—the table name is\n * derived from the file basename, so the filename must be a valid JavaScript\n * identifier with no leading underscore (Convex reserves `_<name>` for system\n * tables).\n *\n * This step does _not_ bundle the table modules. It runs early in the codegen\n * pipeline so the `_generated/id.ts` constructor can be emitted _before_ any\n * user-authored table is bundled (those modules import from `_generated/id.ts`\n * for cross-table refs).\n *\n * A missing `confect/tables/` directory is allowed and produces an empty list.\n *\n * Fails with {@link InvalidTableFilenameError} if any filename is not a valid\n * table identifier, or {@link DuplicateTableNameError} if two files resolve to\n * the same table name (the directory is scanned recursively but names are\n * derived from the basename alone, so `tables/a/notes.ts` and\n * `tables/b/notes.ts` would collide).\n */\nexport const discover = Effect.gen(function* () {\n const relativePaths = yield* discoverTableFiles;\n\n const tableModules = yield* Effect.forEach(\n relativePaths,\n Effect.fnUntraced(function* (relativePath: string) {\n const tableName = yield* tableNameFromRelativePath(relativePath);\n yield* Effect.try({\n try: () => Identifier.validateConfectTableIdentifier(tableName),\n catch: (e) =>\n new InvalidTableFilenameError({\n tablePath: relativePath,\n reason: e instanceof Error ? e.message : String(e),\n }),\n });\n return { relativePath, tableName } satisfies TableModule;\n }),\n { concurrency: \"unbounded\" },\n );\n\n const sorted = pipe(tableModules, Array.sortBy(byTableName));\n\n const collisions = Object.entries(\n Array.groupBy(sorted, (tableModule) => tableModule.tableName),\n )\n .filter(([, group]) => group.length > 1)\n .map(([tableName, group]) => ({\n tableName,\n tablePaths: Array.map(group, (tableModule) => tableModule.relativePath),\n }));\n\n if (collisions.length > 0) {\n return yield* new DuplicateTableNameError({ collisions });\n }\n\n return sorted;\n});\n\n/**\n * Bundle every discovered table module and verify that its default export is an\n * {@link Table.UnnamedTable} (the result of `Table.make(...)` before a name has\n * been bound). Fails with {@link InvalidTableDefaultExportError} if any\n * module's default export is missing or has the wrong shape.\n *\n * Must run _after_ `_generated/id.ts` has been emitted, because user-authored\n * table modules typically `import { Id } from \"../_generated/id\"` for\n * cross-table references.\n */\nexport const validate = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const validateRelativePath = Effect.fnUntraced(function* (\n relativePath: string,\n ) {\n const absolutePath = path.resolve(confectDirectory, relativePath);\n const { module } = yield* Bundler.bundle(absolutePath).pipe(\n Effect.mapError((error) => fromBundlerError(relativePath, error)),\n );\n\n if (!Table.isUnnamedTable(module.default)) {\n return yield* new InvalidTableDefaultExportError({\n tablePath: relativePath,\n });\n }\n });\n\n const relativePaths = tableModules.map(({ relativePath }) => relativePath);\n yield* Bundler.withBatch(\n relativePaths.map((relativePath) =>\n path.resolve(confectDirectory, relativePath),\n ),\n Effect.forEach(relativePaths, validateRelativePath, { concurrency: 4 }),\n );\n});\n"],"mappings":";;;;;;;;;;;;;;AAkBA,MAAa,iBAAiB;AAe9B,MAAM,4BAA4B,OAAO,WAAW,WAClD,cACA;CAEA,MAAM,EAAE,UAAS,OADG,KAAK,KAAA,CACH,MAAM,YAAY;CACxC,OAAO;AACT,CAAC;AAED,MAAa,qBAAqB,OAAO,IAAI,aAAa;CACxD,MAAM,KAAK,OAAO,WAAW;CAC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,WAAW,CAAC;CAG1D,OAAO;AACT,CAAC;;;;;;;;;;;AAYD,MAAa,WAAW,OAAO,WAAW,WACxC,cACA;CACA,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,mBAAmB,OAAO,iBAAiB;CAEjD,MAAM,uBAAuB,OAAO,WAAW,WAC7C,cACA;EACA,MAAM,eAAe,KAAK,QAAQ,kBAAkB,YAAY;EAChE,MAAM,EAAE,WAAW,OAAOA,OAAe,YAAY,CAAC,CAAC,KACrD,OAAO,UAAU,UAAU,iBAAiB,cAAc,KAAK,CAAC,CAClE;EAEA,IAAI,CAAC,MAAM,eAAe,OAAO,OAAO,GACtC,OAAO,OAAO,IAAI,+BAA+B,EAC/C,WAAW,aACb,CAAC;CAEL,CAAC;CAED,MAAM,gBAAgB,aAAa,KAAK,EAAE,mBAAmB,YAAY;CACzE,OAAOC,UACL,cAAc,KAAK,iBACjB,KAAK,QAAQ,kBAAkB,YAAY,CAC7C,GACA,OAAO,QAAQ,eAAe,sBAAsB,EAAE,aAAa,EAAE,CAAC,CACxE;AACF,CAAC"}
|
package/dist/Watcher.mjs
CHANGED
|
@@ -370,11 +370,12 @@ const handleConfectChange = ({ relativePath, eventTag, signal, pendingRef, resta
|
|
|
370
370
|
if (relativePath.split(/[/\\]/).includes("_generated")) return Effect.void;
|
|
371
371
|
if (!relativePath.endsWith(".ts")) return Effect.void;
|
|
372
372
|
const isLifecycleChange = Match.value(eventTag).pipe(Match.when("Update", () => false), Match.whenOr("Create", "Remove", () => true), Match.exhaustive);
|
|
373
|
+
const source = relativePath.split(/[/\\]/).join("/");
|
|
374
|
+
const regenerateIfInput = inputs.pipe(Effect.map((inputs) => inputs.includes(source)), Effect.orElseSucceed(() => false), Effect.flatMap((listed) => listed ? flipDirtyAndSignal(pendingRef, signal, restart, false) : Effect.void));
|
|
373
375
|
const entry = parse(relativePath);
|
|
374
|
-
if (Option.isSome(entry)) return isLifecycleChange ? restartEntry(entry.value) :
|
|
376
|
+
if (Option.isSome(entry)) return isLifecycleChange ? restartEntry(entry.value) : regenerateIfInput;
|
|
375
377
|
if (relativePath === "schema.ts") return flipDirtyAndSignal(pendingRef, signal, restart, isLifecycleChange);
|
|
376
|
-
|
|
377
|
-
return Match.value(eventTag).pipe(Match.whenOr("Create", "Remove", () => flipDirtyAndSignal(pendingRef, signal, restart, false)), Match.when("Update", () => inputs.pipe(Effect.map((inputs) => inputs.includes(source)), Effect.orElseSucceed(() => false), Effect.flatMap((listed) => listed ? flipDirtyAndSignal(pendingRef, signal, restart, false) : Effect.void))), Match.exhaustive);
|
|
378
|
+
return Match.value(eventTag).pipe(Match.whenOr("Create", "Remove", () => flipDirtyAndSignal(pendingRef, signal, restart, false)), Match.when("Update", () => regenerateIfInput), Match.exhaustive);
|
|
378
379
|
};
|
|
379
380
|
//#endregion
|
|
380
381
|
export { CoalesceQuiescence, OperationError, isRefreshSuccessful, make, parseFailure };
|
package/dist/Watcher.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Watcher.mjs","names":["SyncState.empty","WatchTopology.make","RestoreWatcher.make","SyncState.full","WatchBuild.diagnostics","Bundler.bundleWorkspacePlugin","WatchBuild.start","WatchBuild.emptyCapture","WatchBuild.parse","WatchBuild.observe","WatchBuild.diff","SyncState.add","SyncState.reconcile","WatchBuild.complete","EntryPoint.discover","EntryPoint.isOptional","WatchBuild.initialProgress","WatchBuild.makeRequestId","WatchBuild.verifyInputs","WatchBuild.captureBarrier","WatchBuild.request","WatchBuild.getCompletion","WatchBuild.joinedWithoutCompletion","WatchBuild.isFresh","WatchBuild.endRequest","EntryPoint.parse"],"sources":["../src/Watcher.ts"],"sourcesContent":["import * as Clock from \"effect/Clock\";\nimport * as Context from \"effect/Context\";\nimport * as Duration from \"effect/Duration\";\nimport * as NodeCrypto from \"@effect/platform-node/NodeCrypto\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Hex from \"effect/encoding/Hex\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Data from \"effect/Data\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as HashMap from \"effect/HashMap\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as Order from \"effect/Order\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Result from \"effect/Result\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Scope from \"effect/Scope\";\nimport * as Schema from \"effect/Schema\";\nimport * as Schedule from \"effect/Schedule\";\nimport * as Stream from \"effect/Stream\";\nimport {\n externalPlugin,\n loadTsConfig,\n tsconfigPathsToRegExp,\n} from \"bundle-require\";\nimport * as esbuild from \"esbuild\";\nimport * as Bundler from \"./Bundler.js\";\nimport * as WatchBuild from \"./WatchBuild.js\";\nimport * as WatchTopology from \"./WatchTopology.js\";\nimport * as SyncState from \"./SyncState.js\";\nimport type { Pending } from \"./SyncState.js\";\nimport * as EntryPoint from \"./EntryPoint.js\";\nimport type { EntryPoint as Entry } from \"./EntryPoint.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport { CONVEX_CONFIG_FILENAME } from \"./ConvexConfig.js\";\nimport { ConvexDirectory } from \"./ConvexDirectory.js\";\nimport { ProjectRoot } from \"./ProjectRoot.js\";\nimport * as RestoreWatcher from \"./RestoreWatcher.js\";\nimport * as SectionFiles from \"./SectionFiles.js\";\n\nexport const CoalesceQuiescence = Context.Reference<Duration.Duration>(\n \"@confect/cli/Watcher/CoalesceQuiescence\",\n { defaultValue: () => Duration.millis(50) },\n);\n\n// Upper bound on `drainUntilQuiescent` so a pathological infinite\n// signal stream can't pin the sync loop forever.\nconst COALESCE_MAX_WAIT = Duration.seconds(5);\n\ntype WatcherLifecycle = Data.TaggedEnum<{\n Uninitialized: {};\n Empty: {};\n Active: {\n readonly initial: Deferred.Deferred<void>;\n readonly key: string;\n readonly scope: Scope.Closeable;\n readonly entries: Array.NonEmptyReadonlyArray<Entry>;\n readonly context: esbuild.BuildContext;\n readonly identifyRequest: (\n promise: Promise<esbuild.BuildResult>,\n ) => WatchBuild.RequestId;\n readonly progress: Ref.Ref<WatchBuild.Progress>;\n readonly verifyInputs: (\n snapshot: WatchBuild.Snapshot,\n ) => ReturnType<typeof WatchBuild.verifyInputs>;\n };\n}>;\nconst WatcherLifecycle = Data.taggedEnum<WatcherLifecycle>();\n\ninterface State {\n readonly lifecycle: Ref.Ref<WatcherLifecycle>;\n readonly observation: Ref.Ref<WatchBuild.State>;\n readonly lock: Semaphore.Semaphore;\n readonly topology: WatchTopology.WatchTopology;\n // Whether the last discovery found `confect/app.ts`.\n readonly declared: Ref.Ref<boolean>;\n}\n\ntype RefreshOutcome = Data.TaggedEnum<{\n Empty: {};\n Observed: { readonly outcome: WatchBuild.Outcome };\n}>;\nconst RefreshOutcome = Data.taggedEnum<RefreshOutcome>();\n\nexport const isRefreshSuccessful = (outcome: RefreshOutcome): boolean =>\n RefreshOutcome.$match(outcome, {\n Empty: () => true,\n Observed: ({ outcome: observed }) =>\n WatchBuild.Outcome.$match(observed, {\n Succeeded: () => true,\n Failed: () => false,\n }),\n });\n\nexport class OperationError extends Schema.TaggedError<OperationError>()(\n \"WatcherOperationError\",\n {\n operation: Schema.Literals([\n \"create\",\n \"watch\",\n \"rebuild\",\n \"dispose\",\n \"refresh\",\n ]),\n cause: Schema.Unknown,\n },\n) {}\n\nconst ReportedBuildFailure = Schema.Struct({\n errors: Schema.NonEmptyArray(Schema.Struct({ text: Schema.String })),\n});\nexport const parseFailure = Schema.decodeUnknownOption(ReportedBuildFailure);\n\nexport const make = Effect.fnUntraced(function* () {\n const quiescence = yield* CoalesceQuiescence;\n const signal = yield* Queue.sliding<void>(1);\n const pendingRef = yield* Ref.make<Pending>(SyncState.empty);\n const restartQueue = yield* Queue.sliding<void>(1);\n const state: State = {\n lifecycle: yield* Ref.make<WatcherLifecycle>(\n WatcherLifecycle.Uninitialized(),\n ),\n observation: yield* Ref.make<WatchBuild.State>(WatchBuild.State.Initial()),\n lock: yield* Semaphore.make(1),\n topology: yield* WatchTopology.make(pendingRef),\n declared: yield* Ref.make(false),\n };\n const restartWith = (invalidation: Effect.Effect<void>) =>\n invalidation.pipe(\n Effect.andThen(Queue.offer(restartQueue, undefined)),\n Effect.andThen(Queue.offer(signal, undefined)),\n );\n const restart = restartWith(state.topology.invalidate);\n const restartEntry = (entry: EntryPoint.Kind) =>\n restartWith(state.topology.invalidateEntry(entry));\n const duringRestoreRef = yield* Ref.make<\n Effect.Effect<void, never, Scope.Scope>\n >(Effect.void);\n return {\n run: Effect.gen(function* () {\n const structure = yield* RestoreWatcher.make(\n confectStructureWatcher(signal, pendingRef, restart, restartEntry),\n );\n yield* Ref.set(duringRestoreRef, structure.duringRestore);\n yield* Effect.all(\n [\n Effect.scoped(\n entryPointsWatcher(signal, pendingRef, restartQueue, state),\n ),\n structure.failure,\n convexConfigStructureWatcher(restart, state.declared),\n ],\n { concurrency: \"unbounded\" },\n );\n }).pipe(Effect.scoped),\n duringRestore: Effect.flatten(Ref.get(duringRestoreRef)),\n // Restored output makes esbuild rebuild; observe that, then drop the work\n // it queued so the restore does not trigger another generation.\n discardRestoreEchoes: refresh(state).pipe(\n Effect.ignore,\n Effect.andThen(Ref.set(pendingRef, SyncState.empty)),\n ),\n refresh: refresh(state),\n next: Queue.take(signal).pipe(\n Effect.andThen(\n drainUntilQuiescent(signal, quiescence, COALESCE_MAX_WAIT),\n ),\n Effect.andThen(state.topology.takePending),\n Effect.onInterrupt(() => Queue.offer(signal, undefined)),\n ),\n pending: Ref.get(pendingRef),\n requestRetry: Ref.update(pendingRef, SyncState.full).pipe(\n Effect.andThen(Queue.offer(signal, undefined)),\n Effect.asVoid,\n ),\n diagnostics: Ref.get(state.observation).pipe(\n Effect.map(WatchBuild.diagnostics),\n ),\n } as const;\n});\n\nexport type Watcher = Effect.Success<ReturnType<typeof make>>;\n\nconst drainUntilQuiescent = Effect.fnUntraced(function* (\n signal: Queue.Queue<void>,\n quiescence: Duration.Duration,\n maxWait: Duration.Duration,\n) {\n const start = yield* Clock.currentTimeMillis;\n const maxMillis = Duration.toMillis(maxWait);\n const loop: Effect.Effect<void> = Effect.gen(function* () {\n const elapsed = (yield* Clock.currentTimeMillis) - start;\n yield* Effect.sleep(\n Duration.millis(\n Math.min(\n Duration.toMillis(quiescence),\n Math.max(0, maxMillis - elapsed),\n ),\n ),\n );\n const drained = yield* Queue.clear(signal);\n if (drained.length === 0) return;\n const now = yield* Clock.currentTimeMillis;\n if (now - start < maxMillis) {\n yield* loop;\n }\n });\n yield* loop;\n});\n\nconst esbuildOptions = (\n path: Path.Path,\n fs: FileSystem.FileSystem,\n crypto: Crypto.Crypto,\n projectRoot: string,\n generatedDirectory: string,\n entries: ReadonlyArray<Entry>,\n notExternal: ReadonlyArray<RegExp>,\n stateRef: Ref.Ref<WatchBuild.State>,\n captureRef: Ref.Ref<WatchBuild.Capture>,\n progressRef: Ref.Ref<WatchBuild.Progress>,\n signal: Queue.Queue<void>,\n pendingRef: Ref.Ref<Pending>,\n initial: Deferred.Deferred<void>,\n): esbuild.BuildOptions => {\n const encodeString = Schema.encodeSync(Schema.fromJsonString(Schema.String));\n return {\n absWorkingDir: projectRoot,\n stdin: {\n contents: entries\n .map((entry) => `import ${encodeString(entry.absolutePath)};`)\n .join(\"\\n\"),\n resolveDir: projectRoot,\n sourcefile: \"confect-watch.ts\",\n loader: \"ts\",\n },\n bundle: true,\n write: false,\n metafile: true,\n platform: \"node\",\n format: \"esm\",\n logLevel: \"silent\",\n plugins: [\n Bundler.bundleWorkspacePlugin(path, fs, notExternal),\n externalPlugin({ notExternal: [...notExternal] }),\n {\n name: \"notify-rebuild\",\n setup(build) {\n build.onStart(() =>\n Effect.runPromise(\n Effect.gen(function* () {\n yield* Ref.update(progressRef, WatchBuild.start);\n yield* Ref.set(captureRef, WatchBuild.emptyCapture);\n }).pipe(Effect.as(undefined)),\n ),\n );\n build.onLoad({ filter: /.*/ }, (args) =>\n Effect.runPromise(\n Effect.gen(function* () {\n const fingerprint = yield* fs.readFile(args.path).pipe(\n Effect.flatMap((contents) =>\n crypto.digest(\"SHA-256\", contents),\n ),\n Effect.map(Hex.encode),\n Effect.result,\n );\n yield* Ref.update(captureRef, (capture) =>\n Result.isSuccess(fingerprint)\n ? {\n ...capture,\n fingerprints: HashMap.set(\n capture.fingerprints,\n args.path,\n fingerprint.success,\n ),\n }\n : {\n ...capture,\n failures: HashMap.set(\n capture.failures,\n args.path,\n WatchBuild.Failure.InputCaptureFailed({\n file: args.path,\n cause: fingerprint.failure,\n }),\n ),\n },\n );\n }).pipe(Effect.as(undefined)),\n ),\n );\n build.onEnd((result) =>\n Effect.runPromise(\n Effect.gen(function* () {\n const { generation } = yield* Ref.get(progressRef);\n const previous = yield* Ref.get(stateRef);\n const outcome = yield* WatchBuild.parse(\n result,\n yield* Ref.get(captureRef),\n (file) => path.resolve(projectRoot, file),\n crypto,\n );\n const current = WatchBuild.observe(previous, outcome);\n yield* Ref.set(stateRef, current);\n const change = WatchBuild.diff(\n previous,\n current,\n generatedDirectory + path.sep,\n );\n yield* Ref.update(pendingRef, (pending) =>\n WatchBuild.Change.$match(change, {\n Full: () => SyncState.add(pending, entries, true),\n Affected: ({ paths }) =>\n SyncState.add(\n pending,\n entries.filter((entry) =>\n HashSet.has(paths, entry.inputPath),\n ),\n ),\n Recovered: ({ paths }) =>\n SyncState.reconcile(\n SyncState.add(\n pending,\n entries.filter((entry) =>\n HashSet.has(paths, entry.inputPath),\n ),\n ),\n ),\n }),\n );\n yield* Queue.offer(signal, undefined);\n yield* Ref.update(progressRef, (progress) =>\n WatchBuild.complete(progress, { generation, outcome }),\n );\n yield* Deferred.succeed(initial, undefined);\n }),\n ),\n );\n },\n },\n ],\n };\n};\n\nconst entryPointsWatcher = Effect.fnUntraced(function* (\n signal: Queue.Queue<void>,\n pendingRef: Ref.Ref<Pending>,\n restartQueue: Queue.Queue<void>,\n watcher: State,\n) {\n const parentScope = yield* Effect.scope;\n const path = yield* Path.Path;\n const fs = yield* FileSystem.FileSystem;\n const projectRoot = yield* ProjectRoot.get;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedDirectory = path.join(\n yield* fs.realPath(confectDirectory),\n \"_generated\",\n );\n const crypto = yield* Crypto.Crypto;\n const completedInitial = Deferred.make<void>().pipe(\n Effect.tap((initial) => Deferred.succeed(initial, undefined)),\n );\n\n const sync = Effect.gen(function* () {\n const revision = yield* watcher.topology.revision;\n const current = yield* Ref.get(watcher.lifecycle);\n const entries = yield* EntryPoint.discover;\n yield* Ref.set(watcher.declared, entries.some(EntryPoint.Kind.$is(\"App\")));\n const desiredPaths = HashSet.fromIterable(\n entries.map((entry) => entry.absolutePath),\n );\n const key = pipe(\n Array.fromIterable(desiredPaths),\n Array.sort(Order.String),\n Array.join(\"\\n\"),\n );\n const unchanged = WatcherLifecycle.$match(current, {\n Uninitialized: () => false,\n Empty: () => entries.length === 0,\n Active: ({ key: previousKey }) => previousKey === key,\n });\n if (unchanged) {\n const initial = yield* WatcherLifecycle.$match(current, {\n Uninitialized: () => completedInitial,\n Empty: () => completedInitial,\n Active: ({ initial: activeInitial }) => Effect.succeed(activeInitial),\n });\n yield* refreshCurrent(current).pipe(\n Effect.catchTag(\"WatcherOperationError\", () =>\n Ref.update(pendingRef, SyncState.full),\n ),\n );\n yield* watcher.topology.reconcile(revision, initial);\n return;\n }\n yield* WatcherLifecycle.$match(current, {\n Uninitialized: () => Effect.void,\n Empty: () => Ref.update(pendingRef, SyncState.full),\n Active: ({ entries: previousEntries, scope }) =>\n Effect.gen(function* () {\n const removedOptional = previousEntries.filter(\n (entry) =>\n EntryPoint.isOptional(entry) &&\n !HashSet.has(desiredPaths, entry.absolutePath),\n );\n yield* Ref.update(pendingRef, (pending) =>\n SyncState.add(SyncState.full(pending), removedOptional),\n );\n yield* Scope.close(scope, Exit.void);\n }),\n });\n yield* Ref.set(watcher.lifecycle, WatcherLifecycle.Uninitialized());\n yield* Ref.set(watcher.observation, WatchBuild.State.Initial());\n if (!Array.isReadonlyArrayNonEmpty(entries)) {\n yield* Ref.set(watcher.lifecycle, WatcherLifecycle.Empty());\n yield* Ref.update(pendingRef, SyncState.full);\n yield* Queue.offer(signal, undefined);\n const initial = yield* completedInitial;\n yield* watcher.topology.reconcile(revision, initial);\n return;\n }\n\n const scope = yield* Scope.fork(parentScope, \"sequential\");\n const captureRef = yield* Ref.make(WatchBuild.emptyCapture);\n const progress = yield* Ref.make(WatchBuild.initialProgress);\n const initial = yield* Deferred.make<void>();\n const tsconfig = loadTsConfig(projectRoot);\n const notExternal = tsconfigPathsToRegExp(\n tsconfig?.data.compilerOptions?.paths ?? {},\n );\n const context = yield* Effect.acquireRelease(\n Effect.tryPromise({\n try: () =>\n esbuild.context(\n esbuildOptions(\n path,\n fs,\n crypto,\n projectRoot,\n generatedDirectory,\n entries,\n notExternal,\n watcher.observation,\n captureRef,\n progress,\n signal,\n pendingRef,\n initial,\n ),\n ),\n catch: (cause) => new OperationError({ operation: \"create\", cause }),\n }),\n (ctx) =>\n Effect.tryPromise({\n try: () => ctx.dispose(),\n catch: (cause) => new OperationError({ operation: \"dispose\", cause }),\n }).pipe(Effect.orDie),\n ).pipe(Scope.provide(scope));\n const requestIds = new WeakMap<\n Promise<esbuild.BuildResult>,\n WatchBuild.RequestId\n >();\n yield* Ref.set(\n watcher.lifecycle,\n WatcherLifecycle.Active({\n initial,\n key,\n scope,\n entries,\n context,\n identifyRequest: (promise) => {\n const existing = requestIds.get(promise);\n if (existing !== undefined) return existing;\n const id = WatchBuild.makeRequestId();\n requestIds.set(promise, id);\n return id;\n },\n progress,\n verifyInputs: (snapshot) =>\n WatchBuild.verifyInputs(snapshot, fs, crypto),\n }),\n );\n yield* Effect.tryPromise({\n try: () => context.watch(),\n catch: (cause) => new OperationError({ operation: \"watch\", cause }),\n });\n yield* watcher.topology.reconcile(revision, initial);\n }).pipe(Semaphore.withPermit(watcher.lock));\n\n yield* sync;\n return yield* Effect.forever(\n Queue.take(restartQueue).pipe(Effect.andThen(sync)),\n );\n}, Effect.provide(NodeCrypto.layer));\n\nconst refreshCurrent = Effect.fnUntraced(function* (current: WatcherLifecycle) {\n return yield* WatcherLifecycle.$match(current, {\n Empty: () => Effect.succeed(RefreshOutcome.Empty()),\n Uninitialized: () =>\n Effect.fail(\n new OperationError({\n operation: \"refresh\",\n cause: \"The dependency watcher is not initialized\",\n }),\n ),\n Active: ({ context, identifyRequest, progress, verifyInputs }) =>\n Effect.gen(function* () {\n const runSync = Effect.runSyncWith(yield* Effect.context());\n const barrier = WatchBuild.captureBarrier(yield* Ref.get(progress));\n const rebuild = Effect.gen(function* () {\n const built = yield* Effect.tryPromise({\n try: () => {\n const promise = context.rebuild();\n runSync(\n Ref.update(progress, (currentProgress) =>\n WatchBuild.request(currentProgress, identifyRequest(promise)),\n ),\n );\n return promise;\n },\n catch: (cause) =>\n new OperationError({ operation: \"rebuild\", cause }),\n }).pipe(Effect.result);\n const currentProgress = yield* Ref.get(progress);\n const completed = WatchBuild.getCompletion(currentProgress);\n if (Result.isFailure(built)) {\n const rejected = parseFailure(built.failure.cause);\n if (Option.isNone(rejected)) return yield* built.failure;\n if (WatchBuild.joinedWithoutCompletion(currentProgress))\n return Option.none<WatchBuild.Completion>();\n if (\n Option.isNone(completed) ||\n !WatchBuild.Outcome.$is(\"Failed\")(completed.value.outcome)\n )\n return yield* new OperationError({\n operation: \"rebuild\",\n cause: rejected.value.errors,\n });\n }\n if (WatchBuild.joinedWithoutCompletion(currentProgress))\n return Option.none<WatchBuild.Completion>();\n const observed = yield* Effect.fromOption(completed).pipe(\n Effect.mapError(\n () =>\n new OperationError({\n operation: \"rebuild\",\n cause: \"esbuild completed without a build observation\",\n }),\n ),\n );\n if (\n WatchBuild.isFresh(barrier, observed) &&\n WatchBuild.Outcome.$is(\"Succeeded\")(observed.outcome)\n ) {\n const unchanged = yield* verifyInputs(\n observed.outcome.snapshot,\n ).pipe(\n Effect.mapError(\n ({ cause }) =>\n new OperationError({ operation: \"refresh\", cause }),\n ),\n );\n if (!unchanged) return Option.none<WatchBuild.Completion>();\n }\n return Option.some(observed);\n }).pipe(Effect.ensuring(Ref.update(progress, WatchBuild.endRequest)));\n const completed = yield* rebuild.pipe(\n Effect.repeat({\n while: (observed) =>\n Option.isNone(observed) ||\n !WatchBuild.isFresh(barrier, observed.value),\n }),\n Effect.flatMap((observed) =>\n Effect.fromOption(observed).pipe(Effect.orDie),\n ),\n );\n return RefreshOutcome.Observed({ outcome: completed.outcome });\n }),\n });\n});\n\nconst refresh = (watcher: State) =>\n watcher.lock.withPermit(\n Ref.get(watcher.lifecycle).pipe(Effect.flatMap(refreshCurrent)),\n );\n\nconst confectStructureWatcher = Effect.fnUntraced(function* (\n signal: Queue.Queue<void>,\n pendingRef: Ref.Ref<Pending>,\n restart: Effect.Effect<unknown>,\n restartEntry: (entry: EntryPoint.Kind) => Effect.Effect<unknown>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const removedDirectory = Schema.Struct({\n code: Schema.Literal(\"ENOENT\"),\n syscall: Schema.Literal(\"scandir\"),\n path: Schema.String,\n });\n\n yield* pipe(\n fs.watch(confectDirectory, { recursive: true }),\n Stream.runForEach((event) =>\n handleConfectChange({\n relativePath: path.relative(\n confectDirectory,\n path.resolve(confectDirectory, event.path),\n ),\n eventTag: event._tag,\n signal,\n pendingRef,\n restart,\n restartEntry,\n }),\n ),\n Effect.retry({\n schedule: Schedule.spaced(\"10 millis\"),\n while: (error) =>\n Effect.gen(function* () {\n const removed = Schema.decodeUnknownOption(removedDirectory)(\n error.reason.cause,\n );\n if (Option.isNone(removed)) return false;\n const relative = path.relative(confectDirectory, removed.value.path);\n if (\n relative === \"\" ||\n relative === \"..\" ||\n relative.startsWith(`..${path.sep}`) ||\n path.isAbsolute(relative)\n )\n return false;\n if (\n !(yield* fs\n .exists(confectDirectory)\n .pipe(Effect.orElseSucceed(() => false)))\n ) {\n return false;\n }\n yield* restart;\n return true;\n }),\n }),\n );\n});\n\n/**\n * Non-recursive `fs.watch` on the convex directory, reacting only to\n * `convex.config.ts`. Recursion is deliberately avoided: codegen (Confect's and\n * Convex's) writes into `convex/` and `convex/_generated/` constantly, and\n * reacting to those writes would loop. Create/Remove offers to `restartQueue`\n * so the entry-point watcher set picks up (or drops) the config's esbuild\n * watcher.\n */\nconst convexConfigStructureWatcher = Effect.fnUntraced(function* (\n restart: Effect.Effect<unknown>,\n declared: Ref.Ref<boolean>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n\n yield* pipe(\n fs.watch(convexDirectory),\n Stream.runForEach((event) =>\n Effect.gen(function* () {\n // A declared backend's config is codegen output; reacting to its\n // writes would rerun codegen for nothing.\n if (\n path.relative(convexDirectory, event.path) !==\n CONVEX_CONFIG_FILENAME ||\n (yield* Ref.get(declared))\n )\n return;\n yield* Match.value(event).pipe(\n Match.tag(\"Update\", () => Effect.void),\n Match.tag(\"Create\", \"Remove\", () => restart),\n Match.exhaustive,\n );\n }),\n ),\n );\n});\n\nconst flipDirtyAndSignal = (\n pendingRef: Ref.Ref<Pending>,\n signal: Queue.Queue<void>,\n restart: Effect.Effect<unknown>,\n isLifecycleChange: boolean,\n) =>\n isLifecycleChange\n ? restart\n : Ref.update(pendingRef, SyncState.full).pipe(\n Effect.andThen(Queue.offer(signal, undefined)),\n );\n\nconst handleConfectChange = ({\n relativePath,\n eventTag,\n signal,\n pendingRef,\n restart,\n restartEntry,\n}: {\n relativePath: string;\n eventTag: \"Create\" | \"Update\" | \"Remove\";\n signal: Queue.Queue<void>;\n pendingRef: Ref.Ref<Pending>;\n restart: Effect.Effect<unknown>;\n restartEntry: (entry: EntryPoint.Kind) => Effect.Effect<unknown>;\n}) => {\n if (relativePath.split(/[/\\\\]/).includes(\"_generated\")) {\n return Effect.void;\n }\n\n if (!relativePath.endsWith(\".ts\")) {\n return Effect.void;\n }\n\n const isLifecycleChange = Match.value(eventTag).pipe(\n Match.when(\"Update\", () => false),\n Match.whenOr(\"Create\", \"Remove\", () => true),\n Match.exhaustive,\n );\n\n const entry = EntryPoint.parse(relativePath);\n if (Option.isSome(entry)) {\n return isLifecycleChange ? restartEntry(entry.value) : Effect.void;\n }\n\n // A stray `confect/schema.ts` (now codegen-owned at\n // `_generated/schema.ts`) shouldn't exist; flagging it here ensures the\n // next codegen pass surfaces the migration error\n // (`LegacySchemaFileError`) instead of silently ignoring the file.\n if (relativePath === \"schema.ts\") {\n return flipDirtyAndSignal(pendingRef, signal, restart, isLifecycleChange);\n }\n\n // Any other `.ts` under `confect/` (helpers like `tables/notes.ts`).\n // Updates to such files are handled by the esbuild watcher for whichever\n // entry point imports them—its onEnd flips the right dirty flag.\n // Creates are our safety net: when a previously-missing import is added,\n // esbuild may not have its parent directory on a poll path, so we\n // re-run codegen on Create here. Every manifest section's `render` sees the\n // list of `confect/` files, so a Remove re-runs codegen too. A section's\n // input, whether a file it matched or one that file imports, may have no\n // entry point importing it and is read again only by a full run, even after\n // a refusal.\n const source = relativePath.split(/[/\\\\]/).join(\"/\");\n return Match.value(eventTag).pipe(\n Match.whenOr(\"Create\", \"Remove\", () =>\n flipDirtyAndSignal(pendingRef, signal, restart, false),\n ),\n Match.when(\"Update\", () =>\n SectionFiles.inputs.pipe(\n Effect.map((inputs) => inputs.includes(source)),\n Effect.orElseSucceed(() => false),\n Effect.flatMap((listed) =>\n listed\n ? flipDirtyAndSignal(pendingRef, signal, restart, false)\n : Effect.void,\n ),\n ),\n ),\n Match.exhaustive,\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,MAAa,qBAAqB,QAAQ,UACxC,2CACA,EAAE,oBAAoB,SAAS,OAAO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AAO,OAAO;CAGhB,MAAM,oBAAoB,MAAM,MAAM,QAAQ,CAAC,CAAC,KAC9C,MAAM,KAAK,gBAAgB,KAAK,GAChC,MAAM,OAAO,UAAU,gBAAgB,IAAI,GAC3C,MAAM,UACR;CAEA,MAAM,QAAQsB,MAAiB,YAAY;CAC3C,IAAI,OAAO,OAAO,KAAK,GACrB,OAAO,oBAAoB,aAAa,MAAM,KAAK,IAAI,OAAO;CAOhE,IAAI,iBAAiB,aACnB,OAAO,mBAAmB,YAAY,QAAQ,SAAS,iBAAiB;CAa1E,MAAM,SAAS,aAAa,MAAM,OAAO,CAAC,CAAC,KAAK,GAAG;CACnD,OAAO,MAAM,MAAM,QAAQ,CAAC,CAAC,KAC3B,MAAM,OAAO,UAAU,gBACrB,mBAAmB,YAAY,QAAQ,SAAS,KAAK,CACvD,GACA,MAAM,KAAK,gBAAA,OACW,KAClB,OAAO,KAAK,WAAW,OAAO,SAAS,MAAM,CAAC,GAC9C,OAAO,oBAAoB,KAAK,GAChC,OAAO,SAAS,WACd,SACI,mBAAmB,YAAY,QAAQ,SAAS,KAAK,IACrD,OAAO,IACb,CACF,CACF,GACA,MAAM,UACR;AACF"}
|
|
1
|
+
{"version":3,"file":"Watcher.mjs","names":["SyncState.empty","WatchTopology.make","RestoreWatcher.make","SyncState.full","WatchBuild.diagnostics","Bundler.bundleWorkspacePlugin","WatchBuild.start","WatchBuild.emptyCapture","WatchBuild.parse","WatchBuild.observe","WatchBuild.diff","SyncState.add","SyncState.reconcile","WatchBuild.complete","EntryPoint.discover","EntryPoint.isOptional","WatchBuild.initialProgress","WatchBuild.makeRequestId","WatchBuild.verifyInputs","WatchBuild.captureBarrier","WatchBuild.request","WatchBuild.getCompletion","WatchBuild.joinedWithoutCompletion","WatchBuild.isFresh","WatchBuild.endRequest","EntryPoint.parse"],"sources":["../src/Watcher.ts"],"sourcesContent":["import * as Clock from \"effect/Clock\";\nimport * as Context from \"effect/Context\";\nimport * as Duration from \"effect/Duration\";\nimport * as NodeCrypto from \"@effect/platform-node/NodeCrypto\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Hex from \"effect/encoding/Hex\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Data from \"effect/Data\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as HashMap from \"effect/HashMap\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as Order from \"effect/Order\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Result from \"effect/Result\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Scope from \"effect/Scope\";\nimport * as Schema from \"effect/Schema\";\nimport * as Schedule from \"effect/Schedule\";\nimport * as Stream from \"effect/Stream\";\nimport {\n externalPlugin,\n loadTsConfig,\n tsconfigPathsToRegExp,\n} from \"bundle-require\";\nimport * as esbuild from \"esbuild\";\nimport * as Bundler from \"./Bundler.js\";\nimport * as WatchBuild from \"./WatchBuild.js\";\nimport * as WatchTopology from \"./WatchTopology.js\";\nimport * as SyncState from \"./SyncState.js\";\nimport type { Pending } from \"./SyncState.js\";\nimport * as EntryPoint from \"./EntryPoint.js\";\nimport type { EntryPoint as Entry } from \"./EntryPoint.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport { CONVEX_CONFIG_FILENAME } from \"./ConvexConfig.js\";\nimport { ConvexDirectory } from \"./ConvexDirectory.js\";\nimport { ProjectRoot } from \"./ProjectRoot.js\";\nimport * as RestoreWatcher from \"./RestoreWatcher.js\";\nimport * as SectionFiles from \"./SectionFiles.js\";\n\nexport const CoalesceQuiescence = Context.Reference<Duration.Duration>(\n \"@confect/cli/Watcher/CoalesceQuiescence\",\n { defaultValue: () => Duration.millis(50) },\n);\n\n// Upper bound on `drainUntilQuiescent` so a pathological infinite\n// signal stream can't pin the sync loop forever.\nconst COALESCE_MAX_WAIT = Duration.seconds(5);\n\ntype WatcherLifecycle = Data.TaggedEnum<{\n Uninitialized: {};\n Empty: {};\n Active: {\n readonly initial: Deferred.Deferred<void>;\n readonly key: string;\n readonly scope: Scope.Closeable;\n readonly entries: Array.NonEmptyReadonlyArray<Entry>;\n readonly context: esbuild.BuildContext;\n readonly identifyRequest: (\n promise: Promise<esbuild.BuildResult>,\n ) => WatchBuild.RequestId;\n readonly progress: Ref.Ref<WatchBuild.Progress>;\n readonly verifyInputs: (\n snapshot: WatchBuild.Snapshot,\n ) => ReturnType<typeof WatchBuild.verifyInputs>;\n };\n}>;\nconst WatcherLifecycle = Data.taggedEnum<WatcherLifecycle>();\n\ninterface State {\n readonly lifecycle: Ref.Ref<WatcherLifecycle>;\n readonly observation: Ref.Ref<WatchBuild.State>;\n readonly lock: Semaphore.Semaphore;\n readonly topology: WatchTopology.WatchTopology;\n // Whether the last discovery found `confect/app.ts`.\n readonly declared: Ref.Ref<boolean>;\n}\n\ntype RefreshOutcome = Data.TaggedEnum<{\n Empty: {};\n Observed: { readonly outcome: WatchBuild.Outcome };\n}>;\nconst RefreshOutcome = Data.taggedEnum<RefreshOutcome>();\n\nexport const isRefreshSuccessful = (outcome: RefreshOutcome): boolean =>\n RefreshOutcome.$match(outcome, {\n Empty: () => true,\n Observed: ({ outcome: observed }) =>\n WatchBuild.Outcome.$match(observed, {\n Succeeded: () => true,\n Failed: () => false,\n }),\n });\n\nexport class OperationError extends Schema.TaggedError<OperationError>()(\n \"WatcherOperationError\",\n {\n operation: Schema.Literals([\n \"create\",\n \"watch\",\n \"rebuild\",\n \"dispose\",\n \"refresh\",\n ]),\n cause: Schema.Unknown,\n },\n) {}\n\nconst ReportedBuildFailure = Schema.Struct({\n errors: Schema.NonEmptyArray(Schema.Struct({ text: Schema.String })),\n});\nexport const parseFailure = Schema.decodeUnknownOption(ReportedBuildFailure);\n\nexport const make = Effect.fnUntraced(function* () {\n const quiescence = yield* CoalesceQuiescence;\n const signal = yield* Queue.sliding<void>(1);\n const pendingRef = yield* Ref.make<Pending>(SyncState.empty);\n const restartQueue = yield* Queue.sliding<void>(1);\n const state: State = {\n lifecycle: yield* Ref.make<WatcherLifecycle>(\n WatcherLifecycle.Uninitialized(),\n ),\n observation: yield* Ref.make<WatchBuild.State>(WatchBuild.State.Initial()),\n lock: yield* Semaphore.make(1),\n topology: yield* WatchTopology.make(pendingRef),\n declared: yield* Ref.make(false),\n };\n const restartWith = (invalidation: Effect.Effect<void>) =>\n invalidation.pipe(\n Effect.andThen(Queue.offer(restartQueue, undefined)),\n Effect.andThen(Queue.offer(signal, undefined)),\n );\n const restart = restartWith(state.topology.invalidate);\n const restartEntry = (entry: EntryPoint.Kind) =>\n restartWith(state.topology.invalidateEntry(entry));\n const duringRestoreRef = yield* Ref.make<\n Effect.Effect<void, never, Scope.Scope>\n >(Effect.void);\n return {\n run: Effect.gen(function* () {\n const structure = yield* RestoreWatcher.make(\n confectStructureWatcher(signal, pendingRef, restart, restartEntry),\n );\n yield* Ref.set(duringRestoreRef, structure.duringRestore);\n yield* Effect.all(\n [\n Effect.scoped(\n entryPointsWatcher(signal, pendingRef, restartQueue, state),\n ),\n structure.failure,\n convexConfigStructureWatcher(restart, state.declared),\n ],\n { concurrency: \"unbounded\" },\n );\n }).pipe(Effect.scoped),\n duringRestore: Effect.flatten(Ref.get(duringRestoreRef)),\n // Restored output makes esbuild rebuild; observe that, then drop the work\n // it queued so the restore does not trigger another generation.\n discardRestoreEchoes: refresh(state).pipe(\n Effect.ignore,\n Effect.andThen(Ref.set(pendingRef, SyncState.empty)),\n ),\n refresh: refresh(state),\n next: Queue.take(signal).pipe(\n Effect.andThen(\n drainUntilQuiescent(signal, quiescence, COALESCE_MAX_WAIT),\n ),\n Effect.andThen(state.topology.takePending),\n Effect.onInterrupt(() => Queue.offer(signal, undefined)),\n ),\n pending: Ref.get(pendingRef),\n requestRetry: Ref.update(pendingRef, SyncState.full).pipe(\n Effect.andThen(Queue.offer(signal, undefined)),\n Effect.asVoid,\n ),\n diagnostics: Ref.get(state.observation).pipe(\n Effect.map(WatchBuild.diagnostics),\n ),\n } as const;\n});\n\nexport type Watcher = Effect.Success<ReturnType<typeof make>>;\n\nconst drainUntilQuiescent = Effect.fnUntraced(function* (\n signal: Queue.Queue<void>,\n quiescence: Duration.Duration,\n maxWait: Duration.Duration,\n) {\n const start = yield* Clock.currentTimeMillis;\n const maxMillis = Duration.toMillis(maxWait);\n const loop: Effect.Effect<void> = Effect.gen(function* () {\n const elapsed = (yield* Clock.currentTimeMillis) - start;\n yield* Effect.sleep(\n Duration.millis(\n Math.min(\n Duration.toMillis(quiescence),\n Math.max(0, maxMillis - elapsed),\n ),\n ),\n );\n const drained = yield* Queue.clear(signal);\n if (drained.length === 0) return;\n const now = yield* Clock.currentTimeMillis;\n if (now - start < maxMillis) {\n yield* loop;\n }\n });\n yield* loop;\n});\n\nconst esbuildOptions = (\n path: Path.Path,\n fs: FileSystem.FileSystem,\n crypto: Crypto.Crypto,\n projectRoot: string,\n generatedDirectory: string,\n entries: ReadonlyArray<Entry>,\n notExternal: ReadonlyArray<RegExp>,\n stateRef: Ref.Ref<WatchBuild.State>,\n captureRef: Ref.Ref<WatchBuild.Capture>,\n progressRef: Ref.Ref<WatchBuild.Progress>,\n signal: Queue.Queue<void>,\n pendingRef: Ref.Ref<Pending>,\n initial: Deferred.Deferred<void>,\n): esbuild.BuildOptions => {\n const encodeString = Schema.encodeSync(Schema.fromJsonString(Schema.String));\n return {\n absWorkingDir: projectRoot,\n stdin: {\n contents: entries\n .map((entry) => `import ${encodeString(entry.absolutePath)};`)\n .join(\"\\n\"),\n resolveDir: projectRoot,\n sourcefile: \"confect-watch.ts\",\n loader: \"ts\",\n },\n bundle: true,\n write: false,\n metafile: true,\n platform: \"node\",\n format: \"esm\",\n logLevel: \"silent\",\n plugins: [\n Bundler.bundleWorkspacePlugin(path, fs, notExternal),\n externalPlugin({ notExternal: [...notExternal] }),\n {\n name: \"notify-rebuild\",\n setup(build) {\n build.onStart(() =>\n Effect.runPromise(\n Effect.gen(function* () {\n yield* Ref.update(progressRef, WatchBuild.start);\n yield* Ref.set(captureRef, WatchBuild.emptyCapture);\n }).pipe(Effect.as(undefined)),\n ),\n );\n build.onLoad({ filter: /.*/ }, (args) =>\n Effect.runPromise(\n Effect.gen(function* () {\n const fingerprint = yield* fs.readFile(args.path).pipe(\n Effect.flatMap((contents) =>\n crypto.digest(\"SHA-256\", contents),\n ),\n Effect.map(Hex.encode),\n Effect.result,\n );\n yield* Ref.update(captureRef, (capture) =>\n Result.isSuccess(fingerprint)\n ? {\n ...capture,\n fingerprints: HashMap.set(\n capture.fingerprints,\n args.path,\n fingerprint.success,\n ),\n }\n : {\n ...capture,\n failures: HashMap.set(\n capture.failures,\n args.path,\n WatchBuild.Failure.InputCaptureFailed({\n file: args.path,\n cause: fingerprint.failure,\n }),\n ),\n },\n );\n }).pipe(Effect.as(undefined)),\n ),\n );\n build.onEnd((result) =>\n Effect.runPromise(\n Effect.gen(function* () {\n const { generation } = yield* Ref.get(progressRef);\n const previous = yield* Ref.get(stateRef);\n const outcome = yield* WatchBuild.parse(\n result,\n yield* Ref.get(captureRef),\n (file) => path.resolve(projectRoot, file),\n crypto,\n );\n const current = WatchBuild.observe(previous, outcome);\n yield* Ref.set(stateRef, current);\n const change = WatchBuild.diff(\n previous,\n current,\n generatedDirectory + path.sep,\n );\n yield* Ref.update(pendingRef, (pending) =>\n WatchBuild.Change.$match(change, {\n Full: () => SyncState.add(pending, entries, true),\n Affected: ({ paths }) =>\n SyncState.add(\n pending,\n entries.filter((entry) =>\n HashSet.has(paths, entry.inputPath),\n ),\n ),\n Recovered: ({ paths }) =>\n SyncState.reconcile(\n SyncState.add(\n pending,\n entries.filter((entry) =>\n HashSet.has(paths, entry.inputPath),\n ),\n ),\n ),\n }),\n );\n yield* Queue.offer(signal, undefined);\n yield* Ref.update(progressRef, (progress) =>\n WatchBuild.complete(progress, { generation, outcome }),\n );\n yield* Deferred.succeed(initial, undefined);\n }),\n ),\n );\n },\n },\n ],\n };\n};\n\nconst entryPointsWatcher = Effect.fnUntraced(function* (\n signal: Queue.Queue<void>,\n pendingRef: Ref.Ref<Pending>,\n restartQueue: Queue.Queue<void>,\n watcher: State,\n) {\n const parentScope = yield* Effect.scope;\n const path = yield* Path.Path;\n const fs = yield* FileSystem.FileSystem;\n const projectRoot = yield* ProjectRoot.get;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedDirectory = path.join(\n yield* fs.realPath(confectDirectory),\n \"_generated\",\n );\n const crypto = yield* Crypto.Crypto;\n const completedInitial = Deferred.make<void>().pipe(\n Effect.tap((initial) => Deferred.succeed(initial, undefined)),\n );\n\n const sync = Effect.gen(function* () {\n const revision = yield* watcher.topology.revision;\n const current = yield* Ref.get(watcher.lifecycle);\n const entries = yield* EntryPoint.discover;\n yield* Ref.set(watcher.declared, entries.some(EntryPoint.Kind.$is(\"App\")));\n const desiredPaths = HashSet.fromIterable(\n entries.map((entry) => entry.absolutePath),\n );\n const key = pipe(\n Array.fromIterable(desiredPaths),\n Array.sort(Order.String),\n Array.join(\"\\n\"),\n );\n const unchanged = WatcherLifecycle.$match(current, {\n Uninitialized: () => false,\n Empty: () => entries.length === 0,\n Active: ({ key: previousKey }) => previousKey === key,\n });\n if (unchanged) {\n const initial = yield* WatcherLifecycle.$match(current, {\n Uninitialized: () => completedInitial,\n Empty: () => completedInitial,\n Active: ({ initial: activeInitial }) => Effect.succeed(activeInitial),\n });\n yield* refreshCurrent(current).pipe(\n Effect.catchTag(\"WatcherOperationError\", () =>\n Ref.update(pendingRef, SyncState.full),\n ),\n );\n yield* watcher.topology.reconcile(revision, initial);\n return;\n }\n yield* WatcherLifecycle.$match(current, {\n Uninitialized: () => Effect.void,\n Empty: () => Ref.update(pendingRef, SyncState.full),\n Active: ({ entries: previousEntries, scope }) =>\n Effect.gen(function* () {\n const removedOptional = previousEntries.filter(\n (entry) =>\n EntryPoint.isOptional(entry) &&\n !HashSet.has(desiredPaths, entry.absolutePath),\n );\n yield* Ref.update(pendingRef, (pending) =>\n SyncState.add(SyncState.full(pending), removedOptional),\n );\n yield* Scope.close(scope, Exit.void);\n }),\n });\n yield* Ref.set(watcher.lifecycle, WatcherLifecycle.Uninitialized());\n yield* Ref.set(watcher.observation, WatchBuild.State.Initial());\n if (!Array.isReadonlyArrayNonEmpty(entries)) {\n yield* Ref.set(watcher.lifecycle, WatcherLifecycle.Empty());\n yield* Ref.update(pendingRef, SyncState.full);\n yield* Queue.offer(signal, undefined);\n const initial = yield* completedInitial;\n yield* watcher.topology.reconcile(revision, initial);\n return;\n }\n\n const scope = yield* Scope.fork(parentScope, \"sequential\");\n const captureRef = yield* Ref.make(WatchBuild.emptyCapture);\n const progress = yield* Ref.make(WatchBuild.initialProgress);\n const initial = yield* Deferred.make<void>();\n const tsconfig = loadTsConfig(projectRoot);\n const notExternal = tsconfigPathsToRegExp(\n tsconfig?.data.compilerOptions?.paths ?? {},\n );\n const context = yield* Effect.acquireRelease(\n Effect.tryPromise({\n try: () =>\n esbuild.context(\n esbuildOptions(\n path,\n fs,\n crypto,\n projectRoot,\n generatedDirectory,\n entries,\n notExternal,\n watcher.observation,\n captureRef,\n progress,\n signal,\n pendingRef,\n initial,\n ),\n ),\n catch: (cause) => new OperationError({ operation: \"create\", cause }),\n }),\n (ctx) =>\n Effect.tryPromise({\n try: () => ctx.dispose(),\n catch: (cause) => new OperationError({ operation: \"dispose\", cause }),\n }).pipe(Effect.orDie),\n ).pipe(Scope.provide(scope));\n const requestIds = new WeakMap<\n Promise<esbuild.BuildResult>,\n WatchBuild.RequestId\n >();\n yield* Ref.set(\n watcher.lifecycle,\n WatcherLifecycle.Active({\n initial,\n key,\n scope,\n entries,\n context,\n identifyRequest: (promise) => {\n const existing = requestIds.get(promise);\n if (existing !== undefined) return existing;\n const id = WatchBuild.makeRequestId();\n requestIds.set(promise, id);\n return id;\n },\n progress,\n verifyInputs: (snapshot) =>\n WatchBuild.verifyInputs(snapshot, fs, crypto),\n }),\n );\n yield* Effect.tryPromise({\n try: () => context.watch(),\n catch: (cause) => new OperationError({ operation: \"watch\", cause }),\n });\n yield* watcher.topology.reconcile(revision, initial);\n }).pipe(Semaphore.withPermit(watcher.lock));\n\n yield* sync;\n return yield* Effect.forever(\n Queue.take(restartQueue).pipe(Effect.andThen(sync)),\n );\n}, Effect.provide(NodeCrypto.layer));\n\nconst refreshCurrent = Effect.fnUntraced(function* (current: WatcherLifecycle) {\n return yield* WatcherLifecycle.$match(current, {\n Empty: () => Effect.succeed(RefreshOutcome.Empty()),\n Uninitialized: () =>\n Effect.fail(\n new OperationError({\n operation: \"refresh\",\n cause: \"The dependency watcher is not initialized\",\n }),\n ),\n Active: ({ context, identifyRequest, progress, verifyInputs }) =>\n Effect.gen(function* () {\n const runSync = Effect.runSyncWith(yield* Effect.context());\n const barrier = WatchBuild.captureBarrier(yield* Ref.get(progress));\n const rebuild = Effect.gen(function* () {\n const built = yield* Effect.tryPromise({\n try: () => {\n const promise = context.rebuild();\n runSync(\n Ref.update(progress, (currentProgress) =>\n WatchBuild.request(currentProgress, identifyRequest(promise)),\n ),\n );\n return promise;\n },\n catch: (cause) =>\n new OperationError({ operation: \"rebuild\", cause }),\n }).pipe(Effect.result);\n const currentProgress = yield* Ref.get(progress);\n const completed = WatchBuild.getCompletion(currentProgress);\n if (Result.isFailure(built)) {\n const rejected = parseFailure(built.failure.cause);\n if (Option.isNone(rejected)) return yield* built.failure;\n if (WatchBuild.joinedWithoutCompletion(currentProgress))\n return Option.none<WatchBuild.Completion>();\n if (\n Option.isNone(completed) ||\n !WatchBuild.Outcome.$is(\"Failed\")(completed.value.outcome)\n )\n return yield* new OperationError({\n operation: \"rebuild\",\n cause: rejected.value.errors,\n });\n }\n if (WatchBuild.joinedWithoutCompletion(currentProgress))\n return Option.none<WatchBuild.Completion>();\n const observed = yield* Effect.fromOption(completed).pipe(\n Effect.mapError(\n () =>\n new OperationError({\n operation: \"rebuild\",\n cause: \"esbuild completed without a build observation\",\n }),\n ),\n );\n if (\n WatchBuild.isFresh(barrier, observed) &&\n WatchBuild.Outcome.$is(\"Succeeded\")(observed.outcome)\n ) {\n const unchanged = yield* verifyInputs(\n observed.outcome.snapshot,\n ).pipe(\n Effect.mapError(\n ({ cause }) =>\n new OperationError({ operation: \"refresh\", cause }),\n ),\n );\n if (!unchanged) return Option.none<WatchBuild.Completion>();\n }\n return Option.some(observed);\n }).pipe(Effect.ensuring(Ref.update(progress, WatchBuild.endRequest)));\n const completed = yield* rebuild.pipe(\n Effect.repeat({\n while: (observed) =>\n Option.isNone(observed) ||\n !WatchBuild.isFresh(barrier, observed.value),\n }),\n Effect.flatMap((observed) =>\n Effect.fromOption(observed).pipe(Effect.orDie),\n ),\n );\n return RefreshOutcome.Observed({ outcome: completed.outcome });\n }),\n });\n});\n\nconst refresh = (watcher: State) =>\n watcher.lock.withPermit(\n Ref.get(watcher.lifecycle).pipe(Effect.flatMap(refreshCurrent)),\n );\n\nconst confectStructureWatcher = Effect.fnUntraced(function* (\n signal: Queue.Queue<void>,\n pendingRef: Ref.Ref<Pending>,\n restart: Effect.Effect<unknown>,\n restartEntry: (entry: EntryPoint.Kind) => Effect.Effect<unknown>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const removedDirectory = Schema.Struct({\n code: Schema.Literal(\"ENOENT\"),\n syscall: Schema.Literal(\"scandir\"),\n path: Schema.String,\n });\n\n yield* pipe(\n fs.watch(confectDirectory, { recursive: true }),\n Stream.runForEach((event) =>\n handleConfectChange({\n relativePath: path.relative(\n confectDirectory,\n path.resolve(confectDirectory, event.path),\n ),\n eventTag: event._tag,\n signal,\n pendingRef,\n restart,\n restartEntry,\n }),\n ),\n Effect.retry({\n schedule: Schedule.spaced(\"10 millis\"),\n while: (error) =>\n Effect.gen(function* () {\n const removed = Schema.decodeUnknownOption(removedDirectory)(\n error.reason.cause,\n );\n if (Option.isNone(removed)) return false;\n const relative = path.relative(confectDirectory, removed.value.path);\n if (\n relative === \"\" ||\n relative === \"..\" ||\n relative.startsWith(`..${path.sep}`) ||\n path.isAbsolute(relative)\n )\n return false;\n if (\n !(yield* fs\n .exists(confectDirectory)\n .pipe(Effect.orElseSucceed(() => false)))\n ) {\n return false;\n }\n yield* restart;\n return true;\n }),\n }),\n );\n});\n\n/**\n * Non-recursive `fs.watch` on the convex directory, reacting only to\n * `convex.config.ts`. Recursion is deliberately avoided: codegen (Confect's and\n * Convex's) writes into `convex/` and `convex/_generated/` constantly, and\n * reacting to those writes would loop. Create/Remove offers to `restartQueue`\n * so the entry-point watcher set picks up (or drops) the config's esbuild\n * watcher.\n */\nconst convexConfigStructureWatcher = Effect.fnUntraced(function* (\n restart: Effect.Effect<unknown>,\n declared: Ref.Ref<boolean>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n\n yield* pipe(\n fs.watch(convexDirectory),\n Stream.runForEach((event) =>\n Effect.gen(function* () {\n // A declared backend's config is codegen output; reacting to its\n // writes would rerun codegen for nothing.\n if (\n path.relative(convexDirectory, event.path) !==\n CONVEX_CONFIG_FILENAME ||\n (yield* Ref.get(declared))\n )\n return;\n yield* Match.value(event).pipe(\n Match.tag(\"Update\", () => Effect.void),\n Match.tag(\"Create\", \"Remove\", () => restart),\n Match.exhaustive,\n );\n }),\n ),\n );\n});\n\nconst flipDirtyAndSignal = (\n pendingRef: Ref.Ref<Pending>,\n signal: Queue.Queue<void>,\n restart: Effect.Effect<unknown>,\n isLifecycleChange: boolean,\n) =>\n isLifecycleChange\n ? restart\n : Ref.update(pendingRef, SyncState.full).pipe(\n Effect.andThen(Queue.offer(signal, undefined)),\n );\n\nconst handleConfectChange = ({\n relativePath,\n eventTag,\n signal,\n pendingRef,\n restart,\n restartEntry,\n}: {\n relativePath: string;\n eventTag: \"Create\" | \"Update\" | \"Remove\";\n signal: Queue.Queue<void>;\n pendingRef: Ref.Ref<Pending>;\n restart: Effect.Effect<unknown>;\n restartEntry: (entry: EntryPoint.Kind) => Effect.Effect<unknown>;\n}) => {\n if (relativePath.split(/[/\\\\]/).includes(\"_generated\")) {\n return Effect.void;\n }\n\n if (!relativePath.endsWith(\".ts\")) {\n return Effect.void;\n }\n\n const isLifecycleChange = Match.value(eventTag).pipe(\n Match.when(\"Update\", () => false),\n Match.whenOr(\"Create\", \"Remove\", () => true),\n Match.exhaustive,\n );\n\n // Sections read the files they match and those files' imports, entry points\n // included. An entry point's own watcher only validates or updates that\n // entry, so an edit to a recorded section input reruns codegen in full.\n const source = relativePath.split(/[/\\\\]/).join(\"/\");\n const regenerateIfInput = SectionFiles.inputs.pipe(\n Effect.map((inputs) => inputs.includes(source)),\n Effect.orElseSucceed(() => false),\n Effect.flatMap((listed) =>\n listed\n ? flipDirtyAndSignal(pendingRef, signal, restart, false)\n : Effect.void,\n ),\n );\n\n const entry = EntryPoint.parse(relativePath);\n if (Option.isSome(entry)) {\n return isLifecycleChange ? restartEntry(entry.value) : regenerateIfInput;\n }\n\n // A stray `confect/schema.ts` (now codegen-owned at\n // `_generated/schema.ts`) shouldn't exist; flagging it here ensures the\n // next codegen pass surfaces the migration error\n // (`LegacySchemaFileError`) instead of silently ignoring the file.\n if (relativePath === \"schema.ts\") {\n return flipDirtyAndSignal(pendingRef, signal, restart, isLifecycleChange);\n }\n\n // Any other `.ts` under `confect/` (helpers like `tables/notes.ts`).\n // Updates to such files are handled by the esbuild watcher for whichever\n // entry point imports them—its onEnd flips the right dirty flag.\n // Creates are our safety net: when a previously-missing import is added,\n // esbuild may not have its parent directory on a poll path, so we\n // re-run codegen on Create here. Every manifest section's `render` sees the\n // list of `confect/` files, so a Remove re-runs codegen too. A section's\n // input, whether a file it matched or one that file imports, may have no\n // entry point importing it and is read again only by a full run, even after\n // a refusal.\n return Match.value(eventTag).pipe(\n Match.whenOr(\"Create\", \"Remove\", () =>\n flipDirtyAndSignal(pendingRef, signal, restart, false),\n ),\n Match.when(\"Update\", () => regenerateIfInput),\n Match.exhaustive,\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,MAAa,qBAAqB,QAAQ,UACxC,2CACA,EAAE,oBAAoB,SAAS,OAAO,EAAE,EAAE,CAC5C;AAIA,MAAM,oBAAoB,SAAS,QAAQ,CAAC;AAoB5C,MAAM,mBAAmB,KAAK,WAA6B;AAe3D,MAAM,iBAAiB,KAAK,WAA2B;AAEvD,MAAa,uBAAuB,YAClC,eAAe,OAAO,SAAS;CAC7B,aAAa;CACb,WAAW,EAAE,SAAS,eAAA,QACD,OAAO,UAAU;EAClC,iBAAiB;EACjB,cAAc;CAChB,CAAC;AACL,CAAC;AAEH,IAAa,iBAAb,cAAoC,OAAO,YAA4B,CAAC,CACtE,yBACA;CACE,WAAW,OAAO,SAAS;EACzB;EACA;EACA;EACA;EACA;CACF,CAAC;CACD,OAAO,OAAO;AAChB,CACF,CAAC,CAAC,CAAC;AAEH,MAAM,uBAAuB,OAAO,OAAO,EACzC,QAAQ,OAAO,cAAc,OAAO,OAAO,EAAE,MAAM,OAAO,OAAO,CAAC,CAAC,EACrE,CAAC;AACD,MAAa,eAAe,OAAO,oBAAoB,oBAAoB;AAE3E,MAAa,OAAO,OAAO,WAAW,aAAa;CACjD,MAAM,aAAa,OAAO;CAC1B,MAAM,SAAS,OAAO,MAAM,QAAc,CAAC;CAC3C,MAAM,aAAa,OAAO,IAAI,KAAcA,KAAe;CAC3D,MAAM,eAAe,OAAO,MAAM,QAAc,CAAC;CACjD,MAAM,QAAe;EACnB,WAAW,OAAO,IAAI,KACpB,iBAAiB,cAAc,CACjC;EACA,aAAa,OAAO,IAAI,KAAA,MAAwC,QAAQ,CAAC;EACzE,MAAM,OAAO,UAAU,KAAK,CAAC;EAC7B,UAAU,OAAOC,OAAmB,UAAU;EAC9C,UAAU,OAAO,I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