@powerhousedao/devtools 0.0.0-stage → 6.3.0-dev.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,693 @@
1
+ import { a as EDITORS_DIR, c as SUBGRAPHS_DIR, d as byText, f as listFiles, h as readTextWithin, l as documentModelsDirOf, m as readText, o as MANIFEST_FILE, p as projectRelativeMessage, s as PROCESSORS_DIR, u as byKey } from "./vite-INmnb9pz.mjs";
2
+ import { join, posix } from "node:path";
3
+ import { buildTsMorphProject, getBooleanPropertyValue, getEditorDirNames, getEditorMetadata, getProcessorDirNames, getProcessorMetadata, getProperyAssignmentByName, getStringArrayPropertyElements, getSubgraphDirNames, getSubgraphMetadata, readProjectDefinitions } from "@powerhousedao/codegen/utils";
4
+ import { kebabCase } from "change-case";
5
+ import { SyntaxKind, ts } from "ts-morph";
6
+ import { DocumentModelGlobalStateSchema } from "@powerhousedao/shared/document-model";
7
+ import { checkProjectDefinitions, documentModelChecks, schemaFirstSource } from "document-model/tooling";
8
+ import { Kind, parse, print } from "graphql";
9
+ //#region src/server/project/barrels.ts
10
+ /**
11
+ * Reads the modules a barrel names, without resolving or running anything. A
12
+ * relative specifier is taken from the barrel's directory. Any other one is
13
+ * taken from the project root, which is how generated projects alias
14
+ * `document-models/…` and `processors/…`.
15
+ */
16
+ function readBarrel(root, path) {
17
+ const text = readText(root, path);
18
+ const targets = text === void 0 ? [] : ts.createSourceFile(path, text, ts.ScriptTarget.Latest).statements.flatMap((statement) => (ts.isImportDeclaration(statement) || ts.isExportDeclaration(statement)) && statement.moduleSpecifier !== void 0 && ts.isStringLiteral(statement.moduleSpecifier) ? [statement.moduleSpecifier.text] : []).map((specifier) => specifier.startsWith(".") ? posix.join(posix.dirname(path), specifier) : specifier);
19
+ return {
20
+ path,
21
+ references: (folder) => targets.some((target) => target === folder || target.startsWith(`${folder}/`))
22
+ };
23
+ }
24
+ //#endregion
25
+ //#region src/server/project/checks.ts
26
+ const MANIFEST_SECTION = {
27
+ "document-model": "documentModels",
28
+ editor: "editors",
29
+ app: "apps",
30
+ subgraph: "subgraphs",
31
+ processor: "processors"
32
+ };
33
+ /** Reads `powerhouse.manifest.json` as plain JSON. Entries without a string id are dropped. */
34
+ function readManifest(root) {
35
+ const text = readText(root, MANIFEST_FILE);
36
+ if (text === void 0) return { state: "missing" };
37
+ let manifest;
38
+ try {
39
+ manifest = JSON.parse(text);
40
+ } catch {
41
+ return { state: "invalid" };
42
+ }
43
+ if (typeof manifest !== "object" || manifest === null) return { state: "invalid" };
44
+ const sections = manifest;
45
+ return {
46
+ state: "read",
47
+ entries: (kind) => {
48
+ const section = sections[MANIFEST_SECTION[kind]];
49
+ return (Array.isArray(section) ? section : []).flatMap((entry) => typeof entry?.id === "string" ? [{
50
+ id: entry.id,
51
+ name: typeof entry.name === "string" ? entry.name : ""
52
+ }] : []);
53
+ }
54
+ };
55
+ }
56
+ const GENERATE = {
57
+ "document-model": "ph generate document-model --all",
58
+ editor: "ph generate editor --all",
59
+ app: "ph generate app --all",
60
+ subgraph: "ph generate subgraph --all",
61
+ processor: "ph generate processor --all"
62
+ };
63
+ const NOUN = {
64
+ "document-model": "document model",
65
+ editor: "editor",
66
+ app: "app",
67
+ subgraph: "subgraph",
68
+ processor: "processor"
69
+ };
70
+ const list = (items, last) => items.length < 2 ? items.join("") : `${items.slice(0, -1).join(", ")} ${last} ${items.at(-1)}`;
71
+ /** Whether one of the barrels the host reads names the module's folder. */
72
+ function registeredCheck(kind, folder, barrels) {
73
+ const registering = barrels.filter((barrel) => barrel.references(folder));
74
+ if (registering.length > 0) return {
75
+ id: "registered",
76
+ state: "pass",
77
+ label: `Registered in ${list(registering.map(({ path }) => path), "and")}`
78
+ };
79
+ return {
80
+ id: "registered",
81
+ state: "warn",
82
+ label: `Not registered in ${list(barrels.map(({ path }) => path), "or")}`,
83
+ detail: `The host does not load this ${NOUN[kind]}. Run \`${GENERATE[kind]}\` to register it.`
84
+ };
85
+ }
86
+ /**
87
+ * Whether the manifest lists the module. `name` is compared only when the
88
+ * code declares a display name, which a processor and a subgraph do not.
89
+ */
90
+ function manifestCheck(manifest, kind, module) {
91
+ const warn = (label, detail) => ({
92
+ id: "manifest",
93
+ state: "warn",
94
+ label,
95
+ detail
96
+ });
97
+ if (manifest.state === "invalid") return warn(`${MANIFEST_FILE} is not a JSON object`, `Repair the JSON in ${MANIFEST_FILE}.`);
98
+ const entries = manifest.state === "read" ? manifest.entries(kind) : [];
99
+ const listed = entries.find(({ id }) => id === module.id);
100
+ if (listed === void 0) {
101
+ const renamed = entries.find(({ name }) => module.name !== void 0 && name === module.name);
102
+ return renamed === void 0 ? warn(`Not listed in ${MANIFEST_FILE}`, `Run \`${GENERATE[kind]}\` to add it.`) : warn(`Listed in ${MANIFEST_FILE} with the id ${renamed.id}`, `Change the entry's id to ${module.id} in ${MANIFEST_FILE}.`);
103
+ }
104
+ if (module.name !== void 0 && listed.name !== module.name) return warn(`Listed in ${MANIFEST_FILE} as ${listed.name}`, `Change the entry's name to ${module.name} in ${MANIFEST_FILE}. \`ph generate\` does not rename an entry it already wrote.`);
105
+ return {
106
+ id: "manifest",
107
+ state: "pass",
108
+ label: `Listed in ${MANIFEST_FILE}`
109
+ };
110
+ }
111
+ /**
112
+ * Whether each document type the module names is a model of this project or
113
+ * one of Powerhouse's own. `*` matches every type.
114
+ */
115
+ function documentTypesCheck(documentTypes, projectTypes) {
116
+ const unknown = documentTypes.filter((type) => type !== "*" && !type.startsWith("powerhouse/") && !projectTypes.has(type));
117
+ if (unknown.length === 0) return {
118
+ id: "document-types",
119
+ state: "pass",
120
+ label: "Document types are models of this project or Powerhouse's own"
121
+ };
122
+ return {
123
+ id: "document-types",
124
+ state: "warn",
125
+ label: `No model of type ${list(unknown, "or")} in the project`,
126
+ detail: "Fine if an installed package provides it."
127
+ };
128
+ }
129
+ /** Fails with the model's first error from the document model checks. */
130
+ function definitionCheck(errors) {
131
+ if (errors.length === 0) return {
132
+ id: "definition",
133
+ state: "pass",
134
+ label: "Definition passes the document model checks"
135
+ };
136
+ const [first] = errors;
137
+ return {
138
+ id: "definition",
139
+ state: "fail",
140
+ label: errors.length === 1 ? "Definition has 1 error" : `Definition has ${errors.length} errors`,
141
+ detail: [first.message, first.repair].filter(Boolean).join(" ")
142
+ };
143
+ }
144
+ //#endregion
145
+ //#region src/server/project/models.ts
146
+ /** The module the loader imports the project's scalars from. */
147
+ const PROJECT_SCALARS = "./scalars/index.ts";
148
+ const withoutDotSlash = (specifier) => specifier.replace(/^\.\//, "");
149
+ function projectDiagnostic(diagnostic) {
150
+ return {
151
+ severity: diagnostic.severity,
152
+ code: diagnostic.code,
153
+ message: diagnostic.message,
154
+ ...diagnostic.source !== void 0 && { file: withoutDotSlash(diagnostic.source.specifier) },
155
+ repair: diagnostic.repair
156
+ };
157
+ }
158
+ function operation(specification) {
159
+ return {
160
+ id: specification.id,
161
+ name: specification.name ?? "",
162
+ scope: specification.scope === "local" ? "local" : "global",
163
+ description: specification.description ?? "",
164
+ schema: specification.schema ?? "",
165
+ errors: specification.errors.map((error) => ({
166
+ name: error.name ?? "",
167
+ code: error.code ?? "",
168
+ description: error.description ?? ""
169
+ })),
170
+ examples: specification.examples.map(({ value }) => value)
171
+ };
172
+ }
173
+ function version(specification) {
174
+ const { global, local } = specification.state;
175
+ return {
176
+ version: specification.version,
177
+ changeLog: specification.changeLog,
178
+ state: {
179
+ global: {
180
+ schema: global.schema,
181
+ initialValue: global.initialValue
182
+ },
183
+ local: local.schema.trim() === "" ? null : {
184
+ schema: local.schema,
185
+ initialValue: local.initialValue
186
+ }
187
+ },
188
+ modules: specification.modules.map((module) => ({
189
+ id: module.id,
190
+ name: module.name,
191
+ description: module.description ?? "",
192
+ operations: module.operations.map(operation)
193
+ }))
194
+ };
195
+ }
196
+ /**
197
+ * One model in full. `specifications` are the versions the
198
+ * model serves, ascending.
199
+ */
200
+ function projectModel(model) {
201
+ const source = withoutDotSlash(model.specifier);
202
+ const folder = posix.dirname(source);
203
+ const stored = source.endsWith(".json");
204
+ const specifications = model.specifications.map(version);
205
+ const latest = specifications.at(-1);
206
+ return {
207
+ summary: {
208
+ documentType: model.global.id,
209
+ name: model.global.name,
210
+ extension: model.global.extension,
211
+ description: model.global.description,
212
+ author: model.global.author.name,
213
+ authorWebsite: model.global.author.website || null,
214
+ layout: stored ? "stored" : "code-first",
215
+ source,
216
+ folder,
217
+ versions: [...new Set(specifications.map((specification) => specification.version))],
218
+ modules: latest?.modules.length ?? 0,
219
+ operations: latest?.modules.reduce((count, module) => count + module.operations.length, 0) ?? 0
220
+ },
221
+ specifications,
222
+ errors: model.errors.map(projectDiagnostic)
223
+ };
224
+ }
225
+ /** The stored specification as its file holds it, when it is a document model's state. */
226
+ function readStoredState(root, specifier) {
227
+ try {
228
+ const parsed = DocumentModelGlobalStateSchema().safeParse(JSON.parse(readText(root, withoutDotSlash(specifier)) ?? ""));
229
+ return parsed.success ? parsed.data : void 0;
230
+ } catch {
231
+ return;
232
+ }
233
+ }
234
+ const folderOf = (specifier) => posix.dirname(withoutDotSlash(specifier));
235
+ /**
236
+ * Reads the project's document models with the loader and the checks
237
+ * `ph model check` uses. A stored model whose definition does not load is
238
+ * still listed, from its file, with the errors that kept it from loading.
239
+ * When two folders declare one document type, the folder that loaded wins,
240
+ * then the first by name, and a diagnostic names both. A project whose
241
+ * configuration cannot be read has no known list of models, so that throws.
242
+ * Aborting `signal` stops the loader, which otherwise waits for as long as a
243
+ * code-first module takes to evaluate.
244
+ */
245
+ async function readProjectModels(root, signal) {
246
+ return await readProjectDefinitions(root, async (project, modules) => {
247
+ const unconfigured = project.diagnostics.find(({ phase, severity }) => phase === "configuration" && severity === "error");
248
+ if (unconfigured !== void 0) throw new Error(`${unconfigured.message} ${unconfigured.repair}`);
249
+ const report = await checkProjectDefinitions(project, { checks: documentModelChecks });
250
+ const loaded = [...Map.groupBy(project.artifacts, ({ documentType, source }) => `${documentType}\0${folderOf(source.specifier)}`).values()].map((artifacts) => {
251
+ const latest = artifacts.at(-1);
252
+ return {
253
+ documentType: latest.documentType,
254
+ folder: folderOf(latest.source.specifier),
255
+ sources: new Set(artifacts.map(({ source }) => source.specifier)),
256
+ specifier: latest.source.specifier,
257
+ global: latest.documentModel.global,
258
+ specifications: artifacts.flatMap((artifact) => {
259
+ const served = servedSpecification(artifact);
260
+ return served === void 0 ? [] : [served];
261
+ }),
262
+ errors: []
263
+ };
264
+ });
265
+ const loadedSources = new Set(project.artifacts.map(({ source }) => source.specifier));
266
+ const unloaded = project.sourceSet.stored.flatMap(({ specifier }) => {
267
+ if (loadedSources.has(specifier)) return [];
268
+ const global = readStoredState(root, specifier);
269
+ if (global === void 0) return [];
270
+ return [{
271
+ documentType: global.id,
272
+ folder: folderOf(specifier),
273
+ sources: /* @__PURE__ */ new Set([specifier]),
274
+ specifier,
275
+ global,
276
+ specifications: global.specifications.toSorted((left, right) => left.version - right.version),
277
+ errors: []
278
+ }];
279
+ });
280
+ const duplicates = [];
281
+ const claimed = /* @__PURE__ */ new Set();
282
+ const models = [...Map.groupBy([...loaded.sort(byKey(({ folder }) => folder)), ...unloaded.sort(byKey(({ folder }) => folder))], ({ documentType }) => documentType)].map(([documentType, [winner, ...others]]) => {
283
+ for (const other of others) duplicates.push({
284
+ severity: "error",
285
+ message: `${winner.folder} and ${other.folder} both declare the document type ${documentType}. Only ${winner.folder} is read.`,
286
+ file: withoutDotSlash(other.specifier),
287
+ repair: `Give the model in ${other.folder} its own document type, or remove the folder.`
288
+ });
289
+ const elsewhere = new Set(others.flatMap(({ sources }) => [...sources]));
290
+ const errors = report.diagnostics.filter(({ severity, definition, source }) => {
291
+ if (severity !== "error") return false;
292
+ const from = source?.specifier ?? "";
293
+ if (winner.sources.has(from)) return true;
294
+ return !elsewhere.has(from) && definition?.kind === "document-model" && definition.key === documentType;
295
+ });
296
+ for (const error of errors) claimed.add(error);
297
+ return projectModel({
298
+ ...winner,
299
+ errors
300
+ });
301
+ });
302
+ return {
303
+ documentModelsDir: withoutDotSlash(project.sourceSet.documentModelsDir ?? "./document-models"),
304
+ models: models.sort(byKey(({ summary }) => summary.documentType)),
305
+ diagnostics: [...report.diagnostics.filter((diagnostic) => !claimed.has(diagnostic)).map(projectDiagnostic), ...duplicates],
306
+ importedFiles: [...new Set([...project.sourceSet.sources.map(({ specifier }) => specifier), PROJECT_SCALARS].flatMap((specifier) => modules.importedFiles(specifier)))],
307
+ importFailed: report.diagnostics.some(({ phase, severity }) => phase === "import" && severity === "error")
308
+ };
309
+ }, {
310
+ allowMissingConfig: true,
311
+ ...signal !== void 0 && { signal }
312
+ });
313
+ }
314
+ /** The specification an artifact serves. Each artifact of a family carries the whole history. */
315
+ function servedSpecification(artifact) {
316
+ const { specifications } = artifact.documentModel.global;
317
+ return specifications.find(({ version }) => version === artifact.version) ?? specifications.at(-1);
318
+ }
319
+ //#endregion
320
+ //#region src/drive-types.ts
321
+ /** The document types that make an editor a drive app: `DRIVE_DOCUMENT_TYPES`
322
+ * in `packages/reactor-browser/src/constants.ts`, a browser package the
323
+ * server does not load. */
324
+ const DRIVE_DOCUMENT_TYPES = ["powerhouse/document-drive", "powerhouse/reactor-drive"];
325
+ //#endregion
326
+ //#region src/server/project/dedent.ts
327
+ /** Removes the indentation every line shares, and the blank lines around. */
328
+ function dedent(text) {
329
+ const lines = text.replaceAll("\r\n", "\n").split("\n");
330
+ while (lines.length > 0 && lines[0].trim() === "") lines.shift();
331
+ while (lines.length > 0 && lines.at(-1)?.trim() === "") lines.pop();
332
+ const indent = Math.min(...lines.filter((line) => line.trim() !== "").map((line) => line.length - line.trimStart().length));
333
+ return lines.map((line) => line.slice(indent)).join("\n");
334
+ }
335
+ //#endregion
336
+ //#region src/server/project/subgraph-schema.ts
337
+ /** The gql templates of a module, as the definition tooling reads them
338
+ * (`sdlText` in document-model's `subgraph/schema-first/sdl-conflicts.ts`). */
339
+ const TEMPLATE = /\b(?:gql|graphql)\s*`((?:\\[\s\S]|[^`\\])*)`/g;
340
+ const noSchema = () => ({
341
+ schema: null,
342
+ queries: [],
343
+ mutations: []
344
+ });
345
+ function namedType(type) {
346
+ if (type.kind === Kind.NAMED_TYPE) return type.name.value;
347
+ return type.kind === Kind.NON_NULL_TYPE ? namedType(type.type) : void 0;
348
+ }
349
+ function signature(field) {
350
+ const args = (field.arguments ?? []).map((argument) => `${argument.name.value}: ${print(argument.type)}${argument.defaultValue === void 0 ? "" : ` = ${print(argument.defaultValue)}`}`);
351
+ return `${field.name.value}${args.length === 0 ? "" : `(${args.join(", ")})`}: ${print(field.type)}`;
352
+ }
353
+ /**
354
+ * The fields of the root type `root`, sorted. Generated subgraphs put theirs under a
355
+ * namespace field (`invoiceStats: InvoiceStatsSubgraphQueries!`), which is
356
+ * flattened one level: a field without arguments whose type is an object of
357
+ * this schema named `…Queries` under `Query`, `…Mutations` under `Mutation`.
358
+ */
359
+ function rootFields(document, root) {
360
+ const objects = document.definitions.filter((definition) => definition.kind === Kind.OBJECT_TYPE_DEFINITION || definition.kind === Kind.OBJECT_TYPE_EXTENSION);
361
+ const fieldsOf = (name) => objects.filter((object) => object.name.value === name).flatMap((object) => object.fields ?? []);
362
+ const suffix = root === "Query" ? "Queries" : "Mutations";
363
+ return fieldsOf(root).flatMap((field) => {
364
+ const type = namedType(field.type);
365
+ const namespaced = type !== void 0 && type.endsWith(suffix) && (field.arguments ?? []).length === 0 ? fieldsOf(type) : [];
366
+ return namespaced.length === 0 ? [signature(field)] : namespaced.map((inner) => `${field.name.value}.${signature(inner)}`);
367
+ }).sort(byText);
368
+ }
369
+ /**
370
+ * The SDL a schema-first subgraph declares in `schema.graphql`, or in the gql
371
+ * templates of `schema.ts` or `index.ts`, and its root fields. Nothing is
372
+ * imported or run, so SDL built at runtime (an interpolated template, or one
373
+ * imported from another module) reads as no schema.
374
+ */
375
+ function readSubgraphSchema(root, dir) {
376
+ const { source, language, text } = schemaFirstSource(root, dir);
377
+ if (text === null) return noSchema();
378
+ const templates = language === "graphql" ? [text] : [...text.matchAll(TEMPLATE)].map((match) => match[1]);
379
+ if (templates.length === 0 || language === "typescript" && templates.some((template) => template.includes("${"))) return noSchema();
380
+ const sdl = templates.map(dedent).join("\n\n");
381
+ const schema = {
382
+ source: sdl,
383
+ file: source.specifier.replace(/^\.\//, "")
384
+ };
385
+ try {
386
+ const document = parse(sdl, { noLocation: true });
387
+ return {
388
+ schema,
389
+ queries: rootFields(document, "Query"),
390
+ mutations: rootFields(document, "Mutation")
391
+ };
392
+ } catch {
393
+ return {
394
+ schema,
395
+ queries: [],
396
+ mutations: []
397
+ };
398
+ }
399
+ }
400
+ //#endregion
401
+ //#region src/server/project/modules.ts
402
+ /**
403
+ * One error for each module that repeats an id an earlier one declared, in
404
+ * the order given. `what` is the kind of id, for example `editor id`.
405
+ */
406
+ function duplicateDiagnostics(what, modules) {
407
+ const first = /* @__PURE__ */ new Map();
408
+ return modules.flatMap(({ id, folder, file }) => {
409
+ const earlier = first.get(id);
410
+ if (earlier === void 0) {
411
+ first.set(id, folder);
412
+ return [];
413
+ }
414
+ return [{
415
+ severity: "error",
416
+ message: `${earlier} and ${folder} both declare the ${what} ${id}.`,
417
+ file,
418
+ repair: `Give ${folder} its own ${what}.`
419
+ }];
420
+ });
421
+ }
422
+ /** An app's `allowedDocumentTypes`: empty when `config.ts` does not set it,
423
+ * null when there is no `config.ts` or the value is not an array literal. */
424
+ function allowedDocumentTypes(config) {
425
+ if (config === void 0) return null;
426
+ const property = getProperyAssignmentByName(config, "allowedDocumentTypes");
427
+ if (property === void 0) return [];
428
+ return property.getInitializerIfKind(SyntaxKind.ArrayLiteralExpression) ? getStringArrayPropertyElements(config, "allowedDocumentTypes") : null;
429
+ }
430
+ /**
431
+ * The editors of `editors/`, split into drive apps and the rest. A folder
432
+ * whose `module.ts` does not spell its id, name and document types as
433
+ * literals is reported, because nothing else can be said about it.
434
+ */
435
+ function readEditors(sources, root) {
436
+ const editors = [];
437
+ const apps = [];
438
+ const diagnostics = [];
439
+ for (const dirName of getEditorDirNames(sources)) {
440
+ const folder = `${EDITORS_DIR}/${dirName}`;
441
+ const metadata = getEditorMetadata(sources, dirName);
442
+ if (metadata === void 0) {
443
+ diagnostics.push({
444
+ severity: "warning",
445
+ message: `${folder}/module.ts does not declare its id, name and documentTypes as literals, so the editor is not listed.`,
446
+ file: `${folder}/module.ts`
447
+ });
448
+ continue;
449
+ }
450
+ const editor = {
451
+ id: metadata.id,
452
+ name: metadata.name,
453
+ folder,
454
+ documentTypes: metadata.documentTypes
455
+ };
456
+ if (!editor.documentTypes.some((type) => DRIVE_DOCUMENT_TYPES.includes(type))) {
457
+ editors.push(editor);
458
+ continue;
459
+ }
460
+ const config = sources.addSourceFileAtPathIfExists(join(root, EDITORS_DIR, dirName, "config.ts"));
461
+ apps.push({
462
+ ...editor,
463
+ allowedDocumentTypes: allowedDocumentTypes(config),
464
+ dragAndDrop: getBooleanPropertyValue(config, "isDragAndDropEnabled") ?? null
465
+ });
466
+ }
467
+ diagnostics.push(...duplicateDiagnostics("editor id", [...editors, ...apps].sort(byKey(({ folder }) => folder)).map(({ id, folder }) => ({
468
+ id,
469
+ folder,
470
+ file: `${folder}/module.ts`
471
+ }))));
472
+ return {
473
+ editors: editors.sort(byKey(({ id }) => id)),
474
+ apps: apps.sort(byKey(({ id }) => id)),
475
+ diagnostics
476
+ };
477
+ }
478
+ /** What a processor's own file says it is, by the marker it imports. Null when it imports neither. */
479
+ function processorType(sources, root, dirName) {
480
+ const file = ["processor.ts", "index.ts"].map((name) => sources.addSourceFileAtPathIfExists(join(root, PROCESSORS_DIR, dirName, name))).find((candidate) => candidate !== void 0);
481
+ const imported = new Set(file?.getImportDeclarations().flatMap((declaration) => declaration.getNamedImports()).map((specifier) => specifier.getName()));
482
+ if (imported.has("RelationalDbProcessor")) return "relationalDb";
483
+ return imported.has("IAnalyticsStore") ? "analytics" : null;
484
+ }
485
+ /** The processors of `processors/`. `apps` names the hosts whose factory builders file imports the processor. */
486
+ function readProcessors(sources, root, hosts) {
487
+ return getProcessorDirNames(sources).map((dirName) => {
488
+ const folder = `${PROCESSORS_DIR}/${dirName}`;
489
+ return {
490
+ name: dirName,
491
+ folder,
492
+ type: processorType(sources, root, dirName),
493
+ apps: ["connect", "switchboard"].filter((host) => hosts[host].references(folder)),
494
+ documentTypes: getProcessorMetadata(sources, dirName).documentTypes
495
+ };
496
+ }).sort(byKey(({ name }) => name));
497
+ }
498
+ /** The subgraphs of `subgraphs/`. Only a schema-first one has SDL to read from text. */
499
+ function readSubgraphs(sources, root) {
500
+ return getSubgraphDirNames(sources).map((dirName) => {
501
+ const { subgraphName, style } = getSubgraphMetadata(sources, dirName);
502
+ return {
503
+ name: subgraphName ?? dirName,
504
+ folder: `${SUBGRAPHS_DIR}/${dirName}`,
505
+ style,
506
+ ...style === "schema-first" ? readSubgraphSchema(root, dirName) : noSchema()
507
+ };
508
+ }).sort(byKey(({ name }) => name));
509
+ }
510
+ //#endregion
511
+ //#region src/server/project/build.ts
512
+ /** The most of one file's text an answer carries. */
513
+ const FILE_TEXT_LIMIT = 262144;
514
+ const section = (read, items) => read.ok ? {
515
+ ok: true,
516
+ items: items(read.value)
517
+ } : {
518
+ ok: false,
519
+ message: read.message
520
+ };
521
+ const itemsOf = (read) => read.ok ? read.items : [];
522
+ const failed = (root, error) => ({
523
+ ok: false,
524
+ message: projectRelativeMessage(root, error)
525
+ });
526
+ /**
527
+ * Reads the sections that come from TypeScript sources and joins them with
528
+ * the models into the snapshot. A section that cannot be read answers with
529
+ * the reason, and the others still answer. The ts-morph project lives only
530
+ * for this call.
531
+ */
532
+ function readSnapshot(root, revision, models) {
533
+ const attempt = (read) => {
534
+ try {
535
+ return {
536
+ ok: true,
537
+ value: read()
538
+ };
539
+ } catch (error) {
540
+ return failed(root, error);
541
+ }
542
+ };
543
+ const documentModelsDir = models.ok ? models.value.documentModelsDir : documentModelsDirOf(root);
544
+ /** Unknown when the models could not be read, so no type is called missing. */
545
+ const projectTypes = models.ok ? new Set(models.value.models.map(({ summary }) => summary.documentType)) : void 0;
546
+ const documentTypes = (types) => projectTypes === void 0 || types === null || types.length === 0 ? [] : [documentTypesCheck(types, projectTypes)];
547
+ const manifest = readManifest(root);
548
+ const modelsBarrel = readBarrel(root, `${documentModelsDir}/document-models.ts`);
549
+ const editorsBarrel = readBarrel(root, `${EDITORS_DIR}/editors.ts`);
550
+ const subgraphsBarrel = readBarrel(root, `${SUBGRAPHS_DIR}/index.ts`);
551
+ const processorHosts = {
552
+ connect: readBarrel(root, `${PROCESSORS_DIR}/connect.ts`),
553
+ switchboard: readBarrel(root, `${PROCESSORS_DIR}/switchboard.ts`)
554
+ };
555
+ const sources = attempt(() => buildTsMorphProject(root));
556
+ const withSources = (read) => sources.ok ? attempt(() => read(sources.value)) : sources;
557
+ const editors = withSources((project) => readEditors(project, root));
558
+ const processors = withSources((project) => readProcessors(project, root, processorHosts));
559
+ const subgraphs = withSources((project) => readSubgraphs(project, root));
560
+ return {
561
+ revision,
562
+ root,
563
+ documentModels: section(models, (value) => value.models.map(({ summary, errors }) => ({
564
+ ...summary,
565
+ checks: [
566
+ registeredCheck("document-model", summary.folder, [modelsBarrel]),
567
+ manifestCheck(manifest, "document-model", {
568
+ id: summary.documentType,
569
+ name: summary.name
570
+ }),
571
+ definitionCheck(errors)
572
+ ]
573
+ }))),
574
+ editors: section(editors, (value) => value.editors.map((editor) => ({
575
+ ...editor,
576
+ checks: [
577
+ registeredCheck("editor", editor.folder, [editorsBarrel]),
578
+ manifestCheck(manifest, "editor", editor),
579
+ ...documentTypes(editor.documentTypes)
580
+ ]
581
+ }))),
582
+ apps: section(editors, (value) => value.apps.map((app) => ({
583
+ ...app,
584
+ checks: [
585
+ registeredCheck("app", app.folder, [editorsBarrel]),
586
+ manifestCheck(manifest, "app", app),
587
+ ...documentTypes(app.allowedDocumentTypes)
588
+ ]
589
+ }))),
590
+ subgraphs: section(subgraphs, (value) => value.map((subgraph) => ({
591
+ ...subgraph,
592
+ checks: [registeredCheck("subgraph", subgraph.folder, [subgraphsBarrel]), manifestCheck(manifest, "subgraph", { id: kebabCase(subgraph.name) })]
593
+ }))),
594
+ processors: section(processors, (value) => value.map((processor) => ({
595
+ ...processor,
596
+ checks: [
597
+ registeredCheck("processor", processor.folder, Object.values(processorHosts)),
598
+ manifestCheck(manifest, "processor", { id: processor.name }),
599
+ ...documentTypes(processor.documentTypes)
600
+ ]
601
+ }))),
602
+ diagnostics: [
603
+ ...models.ok ? models.value.diagnostics : [],
604
+ ...editors.ok ? editors.value.diagnostics : [],
605
+ ...subgraphs.ok ? duplicateDiagnostics("subgraph name", subgraphs.value.map(({ name, folder }) => ({
606
+ id: name,
607
+ folder,
608
+ file: `${folder}/index.ts`
609
+ }))) : []
610
+ ]
611
+ };
612
+ }
613
+ /** The answers of one read. The file lists are read on first use and kept. */
614
+ function projectBuild(root, snapshot, models) {
615
+ const { revision } = snapshot;
616
+ const details = /* @__PURE__ */ new Map();
617
+ let fileList;
618
+ const readDetail = (documentType) => {
619
+ const summary = itemsOf(snapshot.documentModels).find((model) => model.documentType === documentType);
620
+ const model = models.ok && models.value.models.find((candidate) => candidate.summary.documentType === documentType);
621
+ if (summary === void 0 || !model) return void 0;
622
+ return {
623
+ ...summary,
624
+ revision,
625
+ specifications: model.specifications
626
+ };
627
+ };
628
+ const readFileList = () => ({
629
+ revision,
630
+ modules: [
631
+ ...itemsOf(snapshot.editors),
632
+ ...itemsOf(snapshot.apps),
633
+ ...itemsOf(snapshot.subgraphs),
634
+ ...itemsOf(snapshot.processors)
635
+ ].map(({ folder }) => ({
636
+ folder,
637
+ files: listFiles(root, folder).map((path) => ({ path }))
638
+ }))
639
+ });
640
+ const fileListOf = () => fileList ??= readFileList();
641
+ return {
642
+ snapshot,
643
+ documentModel: (documentType) => {
644
+ if (!details.has(documentType)) details.set(documentType, readDetail(documentType));
645
+ return details.get(documentType);
646
+ },
647
+ fileList: fileListOf,
648
+ file: (path) => {
649
+ if (!fileListOf().modules.some((module) => module.files.some((file) => file.path === path))) return void 0;
650
+ const read = readTextWithin(root, path, FILE_TEXT_LIMIT);
651
+ return read && {
652
+ revision,
653
+ path,
654
+ ...read
655
+ };
656
+ },
657
+ importedFiles: models.ok ? models.value.importedFiles : [],
658
+ modelsSettled: models.ok && !models.value.importFailed,
659
+ settled: !(models.ok && models.value.importFailed) && [
660
+ snapshot.documentModels,
661
+ snapshot.editors,
662
+ snapshot.apps,
663
+ snapshot.subgraphs,
664
+ snapshot.processors
665
+ ].every(({ ok }) => ok)
666
+ };
667
+ }
668
+ /**
669
+ * Builds the project's answers, one revision at a time. The read of the
670
+ * document models is kept under `modelsKey`, so a change that leaves the
671
+ * models' inputs alone does not load them again. Nothing is written.
672
+ */
673
+ function createProjectBuilder(root) {
674
+ let kept;
675
+ return async (revision, modelsKey, signal) => {
676
+ if (kept?.key !== modelsKey) {
677
+ const models = await readProjectModels(root, signal).then((value) => ({
678
+ ok: true,
679
+ value
680
+ }), (error) => failed(root, error));
681
+ signal.throwIfAborted();
682
+ kept = {
683
+ key: modelsKey,
684
+ models
685
+ };
686
+ }
687
+ return projectBuild(root, readSnapshot(root, revision, kept.models), kept.models);
688
+ };
689
+ }
690
+ //#endregion
691
+ export { createProjectBuilder };
692
+
693
+ //# sourceMappingURL=build-FMqn8eub.mjs.map