@skmtc/core 0.55.1 → 0.56.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skmtc/core",
3
- "version": "0.55.1",
3
+ "version": "0.56.1",
4
4
  "description": "Skmtc is a declarative code generation framework",
5
5
  "keywords": [
6
6
  "openapi",
@@ -109,6 +109,27 @@ export type ToArtifactsArgs = {
109
109
  * is otherwise untouched.
110
110
  */
111
111
  inspect?: boolean;
112
+ /**
113
+ * Called with each file of the run when the file is complete: its path, as
114
+ * a key of `artifacts`, and its text. The run then keeps no file's text,
115
+ * and `artifacts` of the result is empty; `manifest.files` has every file.
116
+ *
117
+ * For an OpenAPI document the run gives a file as soon as no subject left
118
+ * to run can write to it or read from it, so that a host can write it and
119
+ * the run can let it go. That run goes subject by subject, and writes the
120
+ * same files. A file can have its definitions in another order when more
121
+ * than one generator inserts into it: each subject runs every generator
122
+ * before the next subject runs, and the models run first. With an
123
+ * operation generator listed before the model generators, the definitions
124
+ * in a shared file, the names in its import lines, and in a `$ref` cycle
125
+ * the model that gets the type annotation can all differ. A run with
126
+ * `attribution.postPass` or `inspect`, or of a GraphQL document, gives
127
+ * every file at the end.
128
+ *
129
+ * A run that fails has no files. What it gave before it failed, the host
130
+ * must drop. After the first subject that fails it gives no more.
131
+ */
132
+ onArtifact?: (path: string, content: string) => void;
112
133
  };
113
134
  /**
114
135
  * The main orchestration class for the SKMTC transformation pipeline.
@@ -291,7 +312,7 @@ export declare class CoreContext {
291
312
  *
292
313
  * @throws Will throw an error if any phase of the pipeline fails
293
314
  */
294
- toArtifacts({ document, settings, toGeneratorConfigMap, stackTrail, attribution, inspect }: ToArtifactsArgs): ToArtifactsResult;
315
+ toArtifacts({ document, settings, toGeneratorConfigMap, stackTrail, attribution, inspect, onArtifact }: ToArtifactsArgs): ToArtifactsResult;
295
316
  /**
296
317
  * Capability-only sibling of {@link toArtifacts}: parse the document, then
297
318
  * evaluate each generator's `isSupported` over its subjects — no transform,
@@ -51,6 +51,7 @@ exports.skmtcJsonFormatter = skmtcJsonFormatter;
51
51
  const GenerateContext_js_1 = require("./GenerateContext.js");
52
52
  const toInspection_js_1 = require("../run/toInspection.js");
53
53
  const RenderContext_js_1 = require("./RenderContext.js");
54
+ const renderFile_js_1 = require("./renderFile.js");
54
55
  const ParseContext_js_1 = require("./ParseContext.js");
55
56
  const log = __importStar(require("../deps/jsr.io/@std/log/0.224.14/mod.js"));
56
57
  const levels_js_1 = require("../deps/jsr.io/@std/log/0.224.14/levels.js");
@@ -335,7 +336,7 @@ class CoreContext {
335
336
  *
336
337
  * @throws Will throw an error if any phase of the pipeline fails
337
338
  */
338
- toArtifacts({ document, settings, toGeneratorConfigMap, stackTrail, attribution, inspect }) {
339
+ toArtifacts({ document, settings, toGeneratorConfigMap, stackTrail, attribution, inspect, onArtifact }) {
339
340
  const runStartedAt = performance.now();
340
341
  try {
341
342
  // Parse phase: one unified ParseContext handles both protocols
@@ -359,6 +360,9 @@ class CoreContext {
359
360
  const captureChannel = attribution?.postPass
360
361
  ? { sink: undefined }
361
362
  : undefined;
363
+ // The files a run with `onArtifact` gave before the render phase, as `files` of the result has them.
364
+ const givenFiles = {};
365
+ let givenBytes = 0;
362
366
  const { files, previews, inspection, enrichmentWarnings } = stackTrail.trace('generate', st => {
363
367
  __classPrivateFieldSet(this, _CoreContext_phaseName, 'generate', "f");
364
368
  const generatePhase = __classPrivateFieldGet(this, _CoreContext_instances, "m", _CoreContext_setupGeneratePhase).call(this, {
@@ -368,7 +372,35 @@ class CoreContext {
368
372
  captureChannel
369
373
  });
370
374
  __classPrivateFieldSet(this, _CoreContext_phase, generatePhase, "f");
371
- const generated = generatePhase.context.toArtifacts(st);
375
+ // A capturing render and an inspection read every file at the end
376
+ // of the run, so such a run gives no file before then.
377
+ const givesFilesEarly = onArtifact !== undefined && !attribution?.postPass && !inspect;
378
+ const generated = generatePhase.context.toArtifacts(st, givesFilesEarly
379
+ ? {
380
+ reach: phase.context.toReach(),
381
+ onFile: (path, file) => {
382
+ // A file that is complete is rendered now, as the render
383
+ // phase renders the others, with its result at the same place.
384
+ __classPrivateFieldSet(this, _CoreContext_phaseName, 'render', "f");
385
+ const rendered = (0, renderFile_js_1.renderFile)({
386
+ content: file.toString(),
387
+ destinationPath: path,
388
+ basePath: settings?.basePath
389
+ });
390
+ onArtifact(rendered.path, rendered.content);
391
+ if (__classPrivateFieldGet(this, _CoreContext_logsPhaseLines, "f")) {
392
+ givenBytes += toByteCount({ [rendered.path]: rendered.content });
393
+ }
394
+ givenFiles[rendered.path] = {
395
+ destinationPath: rendered.destinationPath,
396
+ lines: rendered.lines,
397
+ characters: rendered.characters
398
+ };
399
+ this.captureCurrentResult('success', stackTrail.clone().append(['render', path]));
400
+ __classPrivateFieldSet(this, _CoreContext_phaseName, 'generate', "f");
401
+ }
402
+ }
403
+ : undefined);
372
404
  __classPrivateFieldSet(this, _CoreContext_enrichmentWarnings, generated.enrichmentWarnings, "f");
373
405
  // Opt-in snapshot of the live files graph, taken after generate populates
374
406
  // it and before render replaces the phase. Off unless `inspect` is set.
@@ -396,15 +428,26 @@ class CoreContext {
396
428
  return __classPrivateFieldGet(this, _CoreContext_phase, "f").context.render(st);
397
429
  });
398
430
  if (__classPrivateFieldGet(this, _CoreContext_logsPhaseLines, "f")) {
399
- const fileCount = (0, toCountPhrase_js_1.toCountPhrase)(Object.keys(renderOutput.artifacts).length, 'file');
400
- const byteCount = (0, toCountPhrase_js_1.toCountPhrase)(toByteCount(renderOutput.artifacts), 'byte');
401
- this.logger.info(`render: ${fileCount}, ${byteCount}, ${toElapsedMs(renderStartedAt)} ms`);
431
+ // The render line counts what the render phase rendered. The run's
432
+ // line counts every file, also those given before that phase.
433
+ const renderedFiles = Object.keys(renderOutput.artifacts).length;
434
+ const renderedBytes = toByteCount(renderOutput.artifacts);
435
+ const fileCount = (0, toCountPhrase_js_1.toCountPhrase)(renderedFiles + Object.keys(givenFiles).length, 'file');
436
+ const byteCount = (0, toCountPhrase_js_1.toCountPhrase)(renderedBytes + givenBytes, 'byte');
437
+ this.logger.info(`render: ${(0, toCountPhrase_js_1.toCountPhrase)(renderedFiles, 'file')}, ${(0, toCountPhrase_js_1.toCountPhrase)(renderedBytes, 'byte')}, ` +
438
+ `${toElapsedMs(renderStartedAt)} ms`);
402
439
  this.logger.info(`toArtifacts: ${(0, toCountPhrase_js_1.toCountPhrase)(Object.keys(toGeneratorConfigMap()).length, 'generator')}, ` +
403
440
  `${fileCount}, ${byteCount}, ${toIssueCounts(phase.context.issues)}, ` +
404
441
  `${toElapsedMs(runStartedAt)} ms`);
405
442
  }
443
+ if (onArtifact !== undefined) {
444
+ Object.entries(renderOutput.artifacts).forEach(([path, content]) => onArtifact(path, content));
445
+ }
406
446
  return {
407
447
  ...renderOutput,
448
+ ...(onArtifact !== undefined
449
+ ? { artifacts: {}, files: { ...givenFiles, ...renderOutput.files } }
450
+ : {}),
408
451
  results: __classPrivateFieldGet(this, _CoreContext_results, "f").toTree(),
409
452
  parseIssues: phase.context.issues,
410
453
  enrichmentWarnings,
@@ -57,6 +57,13 @@ type ConstructorArgs = {
57
57
  */
58
58
  logsGeneratorLines?: boolean;
59
59
  };
60
+ /** What a run needs to give each file to its host when the file is complete. */
61
+ type FileRelease = {
62
+ /** What each subject of the document reaches, from the parse of it. */
63
+ reach: Reach;
64
+ /** Called with a file when no subject left to run holds it. The context then lets the file go. */
65
+ onFile: (path: WorkspacePath, file: FileBase) => void;
66
+ };
60
67
  type ToFilePlanArgs = {
61
68
  /** The subjects of the run, of each kind. */
62
69
  subjects: readonly PlannedSubject[];
@@ -204,7 +211,7 @@ export declare class GenerateContext implements GenerateContextType {
204
211
  /**
205
212
  * @internal
206
213
  */
207
- toArtifacts(stackTrail: StackTrail): GenerateResult;
214
+ toArtifacts(stackTrail: StackTrail, release?: FileRelease): GenerateResult;
208
215
  /**
209
216
  * @internal
210
217
  * The file plan of a run of this context: which of `subjects` hold each
@@ -241,7 +248,8 @@ export declare class GenerateContext implements GenerateContextType {
241
248
  toEnrichmentDefaults(): EnrichmentDefaults;
242
249
  /**
243
250
  * Look up an already-registered file by path, or `undefined` if none
244
- * exists. Neutral primitive: returns the abstract `FileBase` and never
251
+ * exists. In a run with `onArtifact`, a lookup of a file that was given
252
+ * to the host throws. Neutral primitive: returns the abstract `FileBase` and never
245
253
  * constructs anything, so a (future) language-owned `register` can ask
246
254
  * "does this file exist yet?" without the engine knowing the language.
247
255
  * To create on a miss, add a file your language constructs with
@@ -259,7 +267,8 @@ export declare class GenerateContext implements GenerateContextType {
259
267
  getFileByWorkspacePath(path: WorkspacePath): FileBase | undefined;
260
268
  /**
261
269
  * Read-only view of every file generated so far, keyed by (normalized)
262
- * export path. An **inspection / tooling** seam — NOT a coordination
270
+ * export path. In a run with `onArtifact` it does not have the files that
271
+ * were given to the host. An **inspection / tooling** seam — NOT a coordination
263
272
  * surface: generators must still register via `register` / `insert*`, and
264
273
  * the storage stays `#`-private so nothing outside can mutate or re-bind it.
265
274
  *
@@ -13,7 +13,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
13
13
  var __importDefault = (this && this.__importDefault) || function (mod) {
14
14
  return (mod && mod.__esModule) ? mod : { "default": mod };
15
15
  };
16
- var _GenerateContext_instances, _GenerateContext_files, _GenerateContext_failedItems, _GenerateContext_foldedPaths, _GenerateContext_previews, _GenerateContext_captureChannel, _GenerateContext_enrichmentAudit, _GenerateContext_currentSubjectTrail, _GenerateContext_logsGeneratorLines, _GenerateContext_subjectCounts, _GenerateContext_reportSkippedEnrichment, _GenerateContext_logError, _GenerateContext_failItem, _GenerateContext_captureSubjectResult, _GenerateContext_logGeneratorLine, _GenerateContext_runGenerator, _GenerateContext_schemaRefNames, _GenerateContext_subjectDefaults, _GenerateContext_runSubjects, _GenerateContext_addPreview, _GenerateContext_toContentSettingsExportPath, _GenerateContext_ejectedBySuffixedPath_get, _GenerateContext_ejectedBySuffixedPathCache, _GenerateContext_findContainer, _GenerateContext_toContainer;
16
+ var _GenerateContext_instances, _GenerateContext_files, _GenerateContext_failedItems, _GenerateContext_foldedPaths, _GenerateContext_released, _GenerateContext_previews, _GenerateContext_captureChannel, _GenerateContext_enrichmentAudit, _GenerateContext_currentSubjectTrail, _GenerateContext_logsGeneratorLines, _GenerateContext_subjectCounts, _GenerateContext_reportSkippedEnrichment, _GenerateContext_logError, _GenerateContext_failItem, _GenerateContext_captureSubjectResult, _GenerateContext_runByGenerator, _GenerateContext_runBySubject, _GenerateContext_toGeneratorRuns, _GenerateContext_toSteps, _GenerateContext_release, _GenerateContext_affirmNotReleased, _GenerateContext_logGeneratorLine, _GenerateContext_runGenerator, _GenerateContext_schemaRefNames, _GenerateContext_subjectDefaults, _GenerateContext_runSubjects, _GenerateContext_addPreview, _GenerateContext_toContentSettingsExportPath, _GenerateContext_ejectedBySuffixedPath_get, _GenerateContext_ejectedBySuffixedPathCache, _GenerateContext_findContainer, _GenerateContext_toContainer;
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.GenerateContext = exports.toWebhookSource = exports.toOasOperationSource = exports.toModelSource = exports.toGqlOperationSource = void 0;
19
19
  const normalizeWorkspacePath_js_1 = require("../helpers/normalizeWorkspacePath.js");
@@ -123,7 +123,11 @@ class GenerateContext {
123
123
  /** Each file's path folded (case, Unicode form) → the path: a file system that ignores case sees one file. */
124
124
  );
125
125
  /** Each file's path folded (case, Unicode form) → the path: a file system that ignores case sees one file. */
126
- _GenerateContext_foldedPaths.set(this, new Map());
126
+ _GenerateContext_foldedPaths.set(this, new Map()
127
+ /** The paths of the files that were given to the host and let go. */
128
+ );
129
+ /** The paths of the files that were given to the host and let go. */
130
+ _GenerateContext_released.set(this, new Set());
127
131
  _GenerateContext_previews.set(this, void 0);
128
132
  /**
129
133
  * Parsed source document, wrapped in the {@link SkmtcParsedDocument}
@@ -264,27 +268,18 @@ class GenerateContext {
264
268
  /**
265
269
  * @internal
266
270
  */
267
- toArtifacts(stackTrail) {
271
+ toArtifacts(stackTrail, release) {
268
272
  const generators = Object.values(this.toGeneratorConfigMap());
269
- generators.forEach(generatorConfig => {
270
- stackTrail.trace(generatorConfig.id, st => {
271
- // Whole-generator skip (string entry in `skip`). No per-operation
272
- // `skipped` results emitted.
273
- if (this.settings?.skip?.includes(generatorConfig.id)) {
274
- __classPrivateFieldGet(this, _GenerateContext_instances, "m", _GenerateContext_logGeneratorLine).call(this, st, `${generatorConfig.id}: skipped by settings.skip`);
275
- return;
276
- }
277
- const startedAt = performance.now();
278
- const fileCountBefore = __classPrivateFieldGet(this, _GenerateContext_files, "f").size;
279
- __classPrivateFieldSet(this, _GenerateContext_subjectCounts, { offered: 0, transformed: 0, failed: 0 }, "f");
280
- __classPrivateFieldGet(this, _GenerateContext_instances, "m", _GenerateContext_runGenerator).call(this, generatorConfig, st);
281
- const { offered, transformed, failed } = __classPrivateFieldGet(this, _GenerateContext_subjectCounts, "f");
282
- const fileCount = __classPrivateFieldGet(this, _GenerateContext_files, "f").size - fileCountBefore;
283
- const milliseconds = Math.round(performance.now() - startedAt);
284
- __classPrivateFieldGet(this, _GenerateContext_instances, "m", _GenerateContext_logGeneratorLine).call(this, st, `${generatorConfig.id}: ${transformed} of ${(0, toCountPhrase_js_1.toCountPhrase)(offered, toSubjectNoun(generatorConfig))}, ` +
285
- `${failed} failed, ${(0, toCountPhrase_js_1.toCountPhrase)(fileCount, 'file')}, ${milliseconds} ms`);
286
- });
287
- });
273
+ // A run that gives each file when it is complete goes subject by
274
+ // subject. Any other run goes generator by generator. Both write the
275
+ // same files; a file that more than one generator inserts into can have
276
+ // its definitions in another order.
277
+ if (release !== undefined && this.document.type === 'oas') {
278
+ __classPrivateFieldGet(this, _GenerateContext_instances, "m", _GenerateContext_runBySubject).call(this, this.document.value, generators, stackTrail, release);
279
+ }
280
+ else {
281
+ __classPrivateFieldGet(this, _GenerateContext_instances, "m", _GenerateContext_runByGenerator).call(this, generators, stackTrail);
282
+ }
288
283
  // Post-walk consumption audit: every enrichment lookup above was
289
284
  // recorded; configured paths no lookup touched are dead config —
290
285
  // typo'd ids / paths / methods / model names, or entries orphaned by
@@ -511,7 +506,8 @@ class GenerateContext {
511
506
  }
512
507
  /**
513
508
  * Look up an already-registered file by path, or `undefined` if none
514
- * exists. Neutral primitive: returns the abstract `FileBase` and never
509
+ * exists. In a run with `onArtifact`, a lookup of a file that was given
510
+ * to the host throws. Neutral primitive: returns the abstract `FileBase` and never
515
511
  * constructs anything, so a (future) language-owned `register` can ask
516
512
  * "does this file exist yet?" without the engine knowing the language.
517
513
  * To create on a miss, add a file your language constructs with
@@ -521,7 +517,11 @@ class GenerateContext {
521
517
  * key: a key is a normalized path. The file's own `path` is the key.
522
518
  */
523
519
  getFile(filePath) {
524
- return (0, getByWorkspacePath_js_1.getByWorkspacePath)(__classPrivateFieldGet(this, _GenerateContext_files, "f"), filePath);
520
+ const file = (0, getByWorkspacePath_js_1.getByWorkspacePath)(__classPrivateFieldGet(this, _GenerateContext_files, "f"), filePath);
521
+ if (file === undefined && __classPrivateFieldGet(this, _GenerateContext_released, "f").size > 0) {
522
+ __classPrivateFieldGet(this, _GenerateContext_instances, "m", _GenerateContext_affirmNotReleased).call(this, (0, normalizeWorkspacePath_js_1.normalizeWorkspacePath)(filePath));
523
+ }
524
+ return file;
525
525
  }
526
526
  /**
527
527
  * The file whose normalized path is `path`, or `undefined`. A normalized
@@ -529,11 +529,16 @@ class GenerateContext {
529
529
  * {@link getFile}: there is no file there in any spelling.
530
530
  */
531
531
  getFileByWorkspacePath(path) {
532
- return __classPrivateFieldGet(this, _GenerateContext_files, "f").get(path);
532
+ const file = __classPrivateFieldGet(this, _GenerateContext_files, "f").get(path);
533
+ if (file === undefined && __classPrivateFieldGet(this, _GenerateContext_released, "f").size > 0) {
534
+ __classPrivateFieldGet(this, _GenerateContext_instances, "m", _GenerateContext_affirmNotReleased).call(this, path);
535
+ }
536
+ return file;
533
537
  }
534
538
  /**
535
539
  * Read-only view of every file generated so far, keyed by (normalized)
536
- * export path. An **inspection / tooling** seam — NOT a coordination
540
+ * export path. In a run with `onArtifact` it does not have the files that
541
+ * were given to the host. An **inspection / tooling** seam — NOT a coordination
537
542
  * surface: generators must still register via `register` / `insert*`, and
538
543
  * the storage stays `#`-private so nothing outside can mutate or re-bind it.
539
544
  *
@@ -558,6 +563,7 @@ class GenerateContext {
558
563
  if (__classPrivateFieldGet(this, _GenerateContext_files, "f").has(normalizedPath)) {
559
564
  throw new Error(`File already exists: ${normalizedPath}`);
560
565
  }
566
+ __classPrivateFieldGet(this, _GenerateContext_instances, "m", _GenerateContext_affirmNotReleased).call(this, normalizedPath);
561
567
  // Two paths that differ only in case are one file on a file system that
562
568
  // ignores case, as macOS's and Windows' do by default: writing the
563
569
  // second would replace the first without a word.
@@ -939,7 +945,7 @@ class GenerateContext {
939
945
  }
940
946
  }
941
947
  exports.GenerateContext = GenerateContext;
942
- _GenerateContext_files = new WeakMap(), _GenerateContext_failedItems = new WeakMap(), _GenerateContext_foldedPaths = new WeakMap(), _GenerateContext_previews = new WeakMap(), _GenerateContext_captureChannel = new WeakMap(), _GenerateContext_enrichmentAudit = new WeakMap(), _GenerateContext_currentSubjectTrail = new WeakMap(), _GenerateContext_logsGeneratorLines = new WeakMap(), _GenerateContext_subjectCounts = new WeakMap(), _GenerateContext_ejectedBySuffixedPathCache = new WeakMap(), _GenerateContext_instances = new WeakSet(), _GenerateContext_reportSkippedEnrichment = function _GenerateContext_reportSkippedEnrichment(block, variant, path) {
948
+ _GenerateContext_files = new WeakMap(), _GenerateContext_failedItems = new WeakMap(), _GenerateContext_foldedPaths = new WeakMap(), _GenerateContext_released = new WeakMap(), _GenerateContext_previews = new WeakMap(), _GenerateContext_captureChannel = new WeakMap(), _GenerateContext_enrichmentAudit = new WeakMap(), _GenerateContext_currentSubjectTrail = new WeakMap(), _GenerateContext_logsGeneratorLines = new WeakMap(), _GenerateContext_subjectCounts = new WeakMap(), _GenerateContext_ejectedBySuffixedPathCache = new WeakMap(), _GenerateContext_instances = new WeakSet(), _GenerateContext_reportSkippedEnrichment = function _GenerateContext_reportSkippedEnrichment(block, variant, path) {
943
949
  if (!(0, EnrichmentAudit_js_1.hasVariantEnrichment)(block, variant))
944
950
  return;
945
951
  __classPrivateFieldGet(this, _GenerateContext_enrichmentAudit, "f").report({
@@ -964,6 +970,126 @@ _GenerateContext_files = new WeakMap(), _GenerateContext_failedItems = new WeakM
964
970
  if (result === 'error') {
965
971
  __classPrivateFieldGet(this, _GenerateContext_subjectCounts, "f").failed += 1;
966
972
  }
973
+ }, _GenerateContext_runByGenerator = function _GenerateContext_runByGenerator(generators, stackTrail) {
974
+ generators.forEach(generatorConfig => {
975
+ stackTrail.trace(generatorConfig.id, st => {
976
+ // Whole-generator skip (string entry in `skip`). No per-operation
977
+ // `skipped` results emitted.
978
+ if (this.settings?.skip?.includes(generatorConfig.id)) {
979
+ __classPrivateFieldGet(this, _GenerateContext_instances, "m", _GenerateContext_logGeneratorLine).call(this, st, `${generatorConfig.id}: skipped by settings.skip`);
980
+ return;
981
+ }
982
+ const startedAt = performance.now();
983
+ const fileCountBefore = __classPrivateFieldGet(this, _GenerateContext_files, "f").size;
984
+ __classPrivateFieldSet(this, _GenerateContext_subjectCounts, { offered: 0, transformed: 0, failed: 0 }, "f");
985
+ __classPrivateFieldGet(this, _GenerateContext_instances, "m", _GenerateContext_runGenerator).call(this, generatorConfig, st);
986
+ const { offered, transformed, failed } = __classPrivateFieldGet(this, _GenerateContext_subjectCounts, "f");
987
+ const fileCount = __classPrivateFieldGet(this, _GenerateContext_files, "f").size - fileCountBefore;
988
+ const milliseconds = Math.round(performance.now() - startedAt);
989
+ __classPrivateFieldGet(this, _GenerateContext_instances, "m", _GenerateContext_logGeneratorLine).call(this, st, `${generatorConfig.id}: ${transformed} of ${(0, toCountPhrase_js_1.toCountPhrase)(offered, toSubjectNoun(generatorConfig))}, ` +
990
+ `${failed} failed, ${(0, toCountPhrase_js_1.toCountPhrase)(fileCount, 'file')}, ${milliseconds} ms`);
991
+ });
992
+ });
993
+ }, _GenerateContext_runBySubject = function _GenerateContext_runBySubject(oasDocument, generators, stackTrail, { reach, onFile }) {
994
+ const runs = __classPrivateFieldGet(this, _GenerateContext_instances, "m", _GenerateContext_toGeneratorRuns).call(this, generators, stackTrail);
995
+ const models = __classPrivateFieldGet(this, _GenerateContext_instances, "m", _GenerateContext_schemaRefNames).call(this).map(refName => new Subject_js_1.ModelSubject((0, refFns_js_1.toSchemaComponentRef)(refName)));
996
+ const modelSteps = __classPrivateFieldGet(this, _GenerateContext_instances, "m", _GenerateContext_toSteps).call(this, models, runs.models);
997
+ const laterSteps = [
998
+ ...__classPrivateFieldGet(this, _GenerateContext_instances, "m", _GenerateContext_toSteps).call(this, oasDocument.operations.map(operation => new Subject_js_1.OasOperationSubject(operation)), runs.operations),
999
+ ...__classPrivateFieldGet(this, _GenerateContext_instances, "m", _GenerateContext_toSteps).call(this, oasDocument.webhooks.map(webhook => new Subject_js_1.WebhookSubject(webhook)), runs.webhooks)
1000
+ ];
1001
+ const position = new Map(models.map((subject, index) => [(0, refFns_js_1.toModelKey)(subject.ref), index]));
1002
+ // How many models a step waits for: each model up to the last one it can get to.
1003
+ const toModelCount = ({ subject }) => subject
1004
+ .toNamedModels(reach)
1005
+ .flatMap(key => reach.ofModel((0, refFns_js_1.fromModelKey)(key)))
1006
+ .reduce((count, key) => Math.max(count, (position.get(key) ?? -1) + 1), 0);
1007
+ // The operations stay in document order too, so a step waits for no fewer
1008
+ // models than the step before it. A file that every operation adds to
1009
+ // then has its entries in the order of the document.
1010
+ const waitsFor = [];
1011
+ laterSteps.forEach(step => {
1012
+ waitsFor.push(Math.max(waitsFor.at(-1) ?? 0, toModelCount(step)));
1013
+ });
1014
+ const readyAfter = Map.groupBy(laterSteps, (_step, index) => waitsFor[index]);
1015
+ const steps = [
1016
+ ...(readyAfter.get(0) ?? []),
1017
+ ...modelSteps.flatMap((step, index) => [step, ...(readyAfter.get(index + 1) ?? [])])
1018
+ ];
1019
+ const plan = this.toFilePlan({ subjects: steps.map(({ subject }) => subject), reach });
1020
+ steps.forEach(step => {
1021
+ step.run();
1022
+ // A run that has failed gives no more files: it will write nothing.
1023
+ const complete = plan.finish(step.subject);
1024
+ if (__classPrivateFieldGet(this, _GenerateContext_failedItems, "f").length === 0) {
1025
+ complete.forEach(path => __classPrivateFieldGet(this, _GenerateContext_instances, "m", _GenerateContext_release).call(this, path, onFile));
1026
+ }
1027
+ });
1028
+ [...runs.models, ...runs.operations, ...runs.webhooks].forEach(run => {
1029
+ __classPrivateFieldGet(this, _GenerateContext_instances, "m", _GenerateContext_logGeneratorLine).call(this, run.trail, `${run.entry.id}: ${run.counts.transformed} of ${(0, toCountPhrase_js_1.toCountPhrase)(run.counts.offered, toSubjectNoun(run.entry))}, ` +
1030
+ `${run.counts.failed} failed, ${(0, toCountPhrase_js_1.toCountPhrase)(run.files, 'file')}, ${Math.round(run.milliseconds)} ms`);
1031
+ });
1032
+ }, _GenerateContext_toGeneratorRuns = function _GenerateContext_toGeneratorRuns(generators, stackTrail) {
1033
+ const toRun = (entry, filters) => ({
1034
+ entry,
1035
+ trail: stackTrail.clone().append(entry.id),
1036
+ filters,
1037
+ counts: { offered: 0, transformed: 0, failed: 0 },
1038
+ milliseconds: 0,
1039
+ files: 0
1040
+ });
1041
+ const toFilter = (kind, id) => toGeneratorFilter(this.settings?.[kind], id);
1042
+ const toPathFilters = (id) => ({
1043
+ include: toIncludePaths(toFilter('include', id), id),
1044
+ skip: toSkipPaths(toFilter('skip', id), id)
1045
+ });
1046
+ const active = generators.filter(({ id }) => {
1047
+ const isSkipped = this.settings?.skip?.includes(id) ?? false;
1048
+ if (isSkipped) {
1049
+ __classPrivateFieldGet(this, _GenerateContext_instances, "m", _GenerateContext_logGeneratorLine).call(this, stackTrail.clone().append(id), `${id}: skipped by settings.skip`);
1050
+ }
1051
+ return !isSkipped;
1052
+ });
1053
+ return {
1054
+ models: active.flatMap(entry => entry.type === 'model'
1055
+ ? [
1056
+ toRun(entry, {
1057
+ include: toIncludeModels(toFilter('include', entry.id), entry.id),
1058
+ skip: toSkipModels(toFilter('skip', entry.id), entry.id)
1059
+ })
1060
+ ]
1061
+ : []),
1062
+ operations: active.flatMap(entry => entry.type === 'oasOperation' ? [toRun(entry, toPathFilters(entry.id))] : []),
1063
+ webhooks: active.flatMap(entry => (entry.type === 'webhook' ? [toRun(entry, toPathFilters(entry.id))] : []))
1064
+ };
1065
+ }, _GenerateContext_toSteps = function _GenerateContext_toSteps(subjects, runs) {
1066
+ return subjects.map(subject => ({
1067
+ subject,
1068
+ run: () => {
1069
+ runs.forEach(run => {
1070
+ const startedAt = performance.now();
1071
+ const fileCountBefore = __classPrivateFieldGet(this, _GenerateContext_files, "f").size;
1072
+ __classPrivateFieldSet(this, _GenerateContext_subjectCounts, run.counts, "f");
1073
+ __classPrivateFieldGet(this, _GenerateContext_instances, "m", _GenerateContext_runSubjects).call(this, run.entry, [subject], run.filters, run.trail);
1074
+ run.milliseconds += performance.now() - startedAt;
1075
+ run.files += __classPrivateFieldGet(this, _GenerateContext_files, "f").size - fileCountBefore;
1076
+ });
1077
+ }
1078
+ }));
1079
+ }, _GenerateContext_release = function _GenerateContext_release(path, onFile) {
1080
+ const file = __classPrivateFieldGet(this, _GenerateContext_files, "f").get(path);
1081
+ if (file === undefined) {
1082
+ return;
1083
+ }
1084
+ onFile(path, file);
1085
+ __classPrivateFieldGet(this, _GenerateContext_files, "f").delete(path);
1086
+ __classPrivateFieldGet(this, _GenerateContext_released, "f").add(path);
1087
+ }, _GenerateContext_affirmNotReleased = function _GenerateContext_affirmNotReleased(path) {
1088
+ if (__classPrivateFieldGet(this, _GenerateContext_released, "f").has(path)) {
1089
+ throw new Error(`File '${path}' was complete and given to the host before this subject used it. ` +
1090
+ `A generator inserts a projection that its entry does not list in 'projections', ` +
1091
+ `or inserts a model that this subject does not reach through '$ref's.`);
1092
+ }
967
1093
  }, _GenerateContext_logGeneratorLine = function _GenerateContext_logGeneratorLine(generatorTrail, message) {
968
1094
  if (!__classPrivateFieldGet(this, _GenerateContext_logsGeneratorLines, "f")) {
969
1095
  return;
@@ -19,7 +19,7 @@ exports.RenderContext = void 0;
19
19
  const tiny_invariant_1 = __importDefault(require("tiny-invariant"));
20
20
  const getByWorkspacePath_js_1 = require("../helpers/getByWorkspacePath.js");
21
21
  const normalizeWorkspacePath_js_1 = require("../helpers/normalizeWorkspacePath.js");
22
- const toResolvedArtifactPath_js_1 = require("../helpers/toResolvedArtifactPath.js");
22
+ const renderFile_js_1 = require("./renderFile.js");
23
23
  const CodeFileBase_js_1 = require("../dsl/CodeFileBase.js");
24
24
  const CaptureSink_js_1 = require("../anchors/CaptureSink.js");
25
25
  const postPass_js_1 = require("../anchors/postPass.js");
@@ -212,7 +212,7 @@ class RenderContext {
212
212
  const captured = capture && file instanceof CodeFileBase_js_1.CodeFileBase
213
213
  ? capture.sink.captureFile(() => file.toString())
214
214
  : undefined;
215
- const renderedFile = renderFile({
215
+ const renderedFile = (0, renderFile_js_1.renderFile)({
216
216
  content: captured?.text ?? file.toString(),
217
217
  destinationPath,
218
218
  basePath: this.basePath
@@ -328,37 +328,3 @@ const addSidecar = (capture, { artifactPath, filePath, source, spans }) => {
328
328
  capture.generationMap.push(entry);
329
329
  }
330
330
  };
331
- /**
332
- * Renders a single file with metadata calculation.
333
- *
334
- * This function processes a single file through the rendering pipeline,
335
- * calculating file metadata such as line count and character count. It
336
- * resolves the final path using the base path configuration.
337
- *
338
- * @param args - File rendering arguments
339
- * @returns A FileObject with content and metadata
340
- *
341
- * @example
342
- * ```typescript
343
- * const fileObject = renderFile({
344
- * content: 'const x = 1;',
345
- * destinationPath: 'utils.ts',
346
- * basePath: './src'
347
- * });
348
- *
349
- * console.log(fileObject.path); // './src/utils.ts'
350
- * console.log(fileObject.content); // 'const x = 1;'
351
- * console.log(fileObject.lines); // 1
352
- * console.log(fileObject.characters); // 12
353
- * ```
354
- */
355
- const renderFile = ({ content, destinationPath, basePath }) => {
356
- const path = (0, toResolvedArtifactPath_js_1.toResolvedArtifactPath)({ basePath, destinationPath });
357
- return {
358
- content: content,
359
- path,
360
- destinationPath,
361
- lines: content.split('\n').length,
362
- characters: content.length
363
- };
364
- };
@@ -475,11 +475,11 @@ export type GenerateContextType = {
475
475
  registerJson: ({ destinationPath, json }: RegisterJsonArgs) => void;
476
476
  registerMarkdown: ({ destinationPath, markdown }: RegisterMarkdownArgs) => void;
477
477
  register: (args: ContextRegisterArgs) => void;
478
- /** Look up an existing file by path (no creation); the neutral read primitive. */
478
+ /** Look up an existing file by path (no creation); the neutral read primitive. Throws for a file given to the host by `onArtifact`. */
479
479
  getFile: (filePath: string) => FileBase | undefined;
480
- /** Look up an existing file by its normalized path, which is its key: a miss is not normalized again. */
480
+ /** Look up an existing file by its normalized path, which is its key: a miss is not normalized again. Throws for a file given to the host by `onArtifact`. */
481
481
  getFileByWorkspacePath: (path: WorkspacePath) => FileBase | undefined;
482
- /** Read-only view of every file generated so far — an inspection/tooling seam (not coordination). */
482
+ /** Read-only view of every file generated so far, without those given to the host by `onArtifact` — an inspection/tooling seam (not coordination). */
483
483
  inspectedFiles: ReadonlyMap<string, FileBase>;
484
484
  /** Store a language-constructed file; the neutral write primitive. Returns the stored file. */
485
485
  addFile: <File extends FileBase>(file: File) => File;
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Represents a rendered file with metadata.
3
+ */
4
+ export type FileObject = {
5
+ /** The rendered file content */
6
+ content: string;
7
+ /** The original file path */
8
+ path: string;
9
+ /** The resolved destination path */
10
+ destinationPath: string;
11
+ /** Number of lines in the rendered content */
12
+ lines: number;
13
+ /** Number of characters in the rendered content */
14
+ characters: number;
15
+ };
16
+ /**
17
+ * Arguments for rendering a single file.
18
+ */
19
+ type RenderFileArgs = {
20
+ /** The raw file content to render */
21
+ content: string;
22
+ /** The destination path for the file */
23
+ destinationPath: string;
24
+ /** Optional base path for path resolution */
25
+ basePath?: string;
26
+ };
27
+ /**
28
+ * Renders a single file with metadata calculation.
29
+ *
30
+ * This function processes a single file through the rendering pipeline,
31
+ * calculating file metadata such as line count and character count. It
32
+ * resolves the final path using the base path configuration.
33
+ *
34
+ * @param args - File rendering arguments
35
+ * @returns A FileObject with content and metadata
36
+ *
37
+ * @example
38
+ * ```typescript
39
+ * const fileObject = renderFile({
40
+ * content: 'const x = 1;',
41
+ * destinationPath: 'utils.ts',
42
+ * basePath: './src'
43
+ * });
44
+ *
45
+ * console.log(fileObject.path); // './src/utils.ts'
46
+ * console.log(fileObject.content); // 'const x = 1;'
47
+ * console.log(fileObject.lines); // 1
48
+ * console.log(fileObject.characters); // 12
49
+ * ```
50
+ */
51
+ export declare const renderFile: ({ content, destinationPath, basePath }: RenderFileArgs) => FileObject;
52
+ export {};
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.renderFile = void 0;
4
+ const toResolvedArtifactPath_js_1 = require("../helpers/toResolvedArtifactPath.js");
5
+ /**
6
+ * Renders a single file with metadata calculation.
7
+ *
8
+ * This function processes a single file through the rendering pipeline,
9
+ * calculating file metadata such as line count and character count. It
10
+ * resolves the final path using the base path configuration.
11
+ *
12
+ * @param args - File rendering arguments
13
+ * @returns A FileObject with content and metadata
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * const fileObject = renderFile({
18
+ * content: 'const x = 1;',
19
+ * destinationPath: 'utils.ts',
20
+ * basePath: './src'
21
+ * });
22
+ *
23
+ * console.log(fileObject.path); // './src/utils.ts'
24
+ * console.log(fileObject.content); // 'const x = 1;'
25
+ * console.log(fileObject.lines); // 1
26
+ * console.log(fileObject.characters); // 12
27
+ * ```
28
+ */
29
+ const renderFile = ({ content, destinationPath, basePath }) => {
30
+ const path = (0, toResolvedArtifactPath_js_1.toResolvedArtifactPath)({ basePath, destinationPath });
31
+ return {
32
+ content: content,
33
+ path,
34
+ destinationPath,
35
+ lines: content.split('\n').length,
36
+ characters: content.length
37
+ };
38
+ };
39
+ exports.renderFile = renderFile;
@@ -67,6 +67,27 @@ type TransformArgs = {
67
67
  * the generate/render pipeline is unaffected.
68
68
  */
69
69
  inspect?: boolean;
70
+ /**
71
+ * Called with each file of the run when the file is complete: its path, as
72
+ * a key of `artifacts`, and its text. The run then keeps no file's text,
73
+ * and `artifacts` of the result is empty; `manifest.files` has every file.
74
+ *
75
+ * For an OpenAPI document the run gives a file as soon as no subject left
76
+ * to run can write to it or read from it, so that a host can write it and
77
+ * the run can let it go. That run goes subject by subject, and writes the
78
+ * same files. A file can have its definitions in another order when more
79
+ * than one generator inserts into it: each subject runs every generator
80
+ * before the next subject runs, and the models run first. With an
81
+ * operation generator listed before the model generators, the definitions
82
+ * in a shared file, the names in its import lines, and in a `$ref` cycle
83
+ * the model that gets the type annotation can all differ. A run with
84
+ * `attribution.postPass` or `inspect`, or of a GraphQL document, gives
85
+ * every file at the end.
86
+ *
87
+ * A run that fails has no files. What it gave before it failed, the host
88
+ * must drop. After the first subject that fails it gives no more.
89
+ */
90
+ onArtifact?: (path: string, content: string) => void;
70
91
  };
71
92
  /**
72
93
  * Transforms an OpenAPI v3 document into generated code artifacts and metadata.
@@ -136,7 +157,7 @@ type TransformArgs = {
136
157
  * }
137
158
  * ```
138
159
  */
139
- export declare const toArtifacts: ({ traceId, spanId, document, settings, toGeneratorConfigMap, logsPath, startAt, silent, logLevel, stackTrail, attribution, inspect }: TransformArgs) => {
160
+ export declare const toArtifacts: ({ traceId, spanId, document, settings, toGeneratorConfigMap, logsPath, startAt, silent, logLevel, stackTrail, attribution, inspect, onArtifact }: TransformArgs) => {
140
161
  artifacts: Record<string, string>;
141
162
  manifest: ManifestContent;
142
163
  /** The run's log lines (see {@link LogLine}). Not part of the manifest. */