@skmtc/core 0.33.0 → 0.34.0

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.
@@ -10,216 +10,69 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
12
  var _ResultsLog_instances, _ResultsLog_results, _ResultsLog_incomingResultIsWorse;
13
- import set from 'lodash-es/set.js';
14
13
  /**
15
- * Manages and organizes generation results with intelligent prioritization.
14
+ * Records one result per stack trail and builds the `manifest.results` tree.
16
15
  *
17
- * `ResultsLog` tracks the outcomes of code generation operations, maintaining
18
- * a hierarchical structure of results organized by stack trail paths. It implements
19
- * intelligent result prioritization, ensuring that more severe results (errors)
20
- * take precedence over less severe ones (success, warnings) when multiple results
21
- * exist for the same path.
16
+ * When several results are captured at the same trail, the most severe one
17
+ * wins (see `resultRankings`).
22
18
  *
23
- * The class is designed to work with the SKMTC tracing system, using stack trail
24
- * identifiers to organize results in a meaningful hierarchical structure that
25
- * reflects the execution flow of the generation process.
26
- *
27
- * ## Key Features
28
- *
29
- * - **Result Prioritization**: Automatically prioritizes more severe results
30
- * - **Hierarchical Organization**: Organizes results by stack trail paths
31
- * - **Tree Structure**: Converts flat result logs into nested tree structures
32
- * - **Duplicate Handling**: Prevents less severe results from overwriting more severe ones
33
- *
34
- * @example Basic usage
19
+ * @example
35
20
  * ```typescript
36
- * import { ResultsLog } from '@skmtc/core';
37
- *
38
- * const resultsLog = new ResultsLog();
39
- *
40
- * // Capture results from different parts of generation
41
- * resultsLog.capture('models:User', 'success');
42
- * resultsLog.capture('models:Product', 'error');
43
- * resultsLog.capture('types:Status', 'success');
44
- *
45
- * // Convert to hierarchical structure
46
- * const tree = resultsLog.toTree();
47
- * console.log(tree);
48
- * // {
49
- * // models: {
50
- * // User: 'success',
51
- * // Product: 'error'
52
- * // },
53
- * // types: {
54
- * // Status: 'success'
55
- * // }
56
- * // }
57
- * ```
58
- *
59
- * @example Result prioritization
60
- * ```typescript
61
- * const resultsLog = new ResultsLog();
62
- *
63
- * // First capture a success
64
- * resultsLog.capture('api:createUser', 'success');
65
- *
66
- * // Later encounter an error at the same path
67
- * resultsLog.capture('api:createUser', 'error');
21
+ * const resultsLog = new ResultsLog()
68
22
  *
69
- * // Error takes precedence
70
- * const tree = resultsLog.toTree();
71
- * console.log(tree.api.createUser); // 'error'
23
+ * resultsLog.capture(new StackTrail(['generate', '/pets', 'get']), 'success')
24
+ * resultsLog.capture(new StackTrail(['generate', '/pets/{id}:archive', 'post']), 'error')
72
25
  *
73
- * // But success won't overwrite error
74
- * resultsLog.capture('api:createUser', 'success');
75
- * console.log(resultsLog.toTree().api.createUser); // Still 'error'
76
- * ```
77
- *
78
- * @example Complex nested paths
79
- * ```typescript
80
- * const resultsLog = new ResultsLog();
81
- *
82
- * resultsLog.capture('generation:models:User:properties:name', 'success');
83
- * resultsLog.capture('generation:models:User:properties:email', 'warning');
84
- * resultsLog.capture('generation:models:Product:validation', 'error');
85
- * resultsLog.capture('generation:operations:createUser', 'success');
86
- *
87
- * const tree = resultsLog.toTree();
88
- * console.log(tree);
89
- * // {
90
- * // generation: {
91
- * // models: {
92
- * // User: {
93
- * // properties: {
94
- * // name: 'success',
95
- * // email: 'warning'
96
- * // }
97
- * // },
98
- * // Product: {
99
- * // validation: 'error'
100
- * // }
101
- * // },
102
- * // operations: {
103
- * // createUser: 'success'
104
- * // }
105
- * // }
106
- * // }
107
- * ```
108
- *
109
- * @example Integration with tracing
110
- * ```typescript
111
- * class TrackedGenerator {
112
- * private resultsLog = new ResultsLog();
113
- *
114
- * generateModel(name: string, schema: OasSchema) {
115
- * const stackPath = `models:${name}`;
116
- *
117
- * try {
118
- * const model = this.processSchema(schema);
119
- * this.resultsLog.capture(stackPath, 'success');
120
- * return model;
121
- * } catch (error) {
122
- * this.resultsLog.capture(stackPath, 'error');
123
- * throw error;
124
- * }
125
- * }
126
- *
127
- * generateOperation(operationId: string, operation: OasOperation) {
128
- * const stackPath = `operations:${operationId}`;
129
- *
130
- * if (!this.supportsOperation(operation)) {
131
- * this.resultsLog.capture(stackPath, 'notSupported');
132
- * return null;
133
- * }
134
- *
135
- * const result = this.processOperation(operation);
136
- * this.resultsLog.capture(stackPath, 'success');
137
- * return result;
138
- * }
139
- *
140
- * getResults(): ResultsItem {
141
- * return this.resultsLog.toTree();
142
- * }
143
- * }
26
+ * resultsLog.toTree()
27
+ * // { generate: { '/pets': { get: 'success' }, '/pets/{id}:archive': { post: 'error' } } }
144
28
  * ```
145
29
  */
146
30
  export class ResultsLog {
147
- /**
148
- * Creates a new ResultsLog instance.
149
- *
150
- * Initializes an empty results tracking system ready to capture
151
- * generation outcomes from various parts of the pipeline.
152
- */
153
31
  constructor() {
154
32
  _ResultsLog_instances.add(this);
33
+ /**
34
+ * Keyed by `StackTrail.toString()`. The key is one-to-one with the frames,
35
+ * except that `[]` and `['']` both give `''`.
36
+ */
155
37
  _ResultsLog_results.set(this, void 0);
156
- __classPrivateFieldSet(this, _ResultsLog_results, {}, "f");
38
+ __classPrivateFieldSet(this, _ResultsLog_results, new Map(), "f");
157
39
  }
158
40
  /**
159
- * Captures a generation result for a specific stack trail path.
160
- *
161
- * This method records the outcome of a generation operation, using intelligent
162
- * prioritization to ensure that more severe results take precedence over less
163
- * severe ones. For example, an error result will not be overwritten by a
164
- * success result, but a success can be overwritten by an error.
165
- *
166
- * @param stackTrail - Colon-separated path identifying the operation location
167
- * @param result - The result type to capture (error, warning, success, etc.)
168
- *
169
- * @example
170
- * ```typescript
171
- * const resultsLog = new ResultsLog();
41
+ * Captures `result` at `stackTrail`, unless a more severe result is
42
+ * already recorded there.
172
43
  *
173
- * // Capture various results
174
- * resultsLog.capture('models:User:properties:email', 'success');
175
- * resultsLog.capture('models:User:validation', 'warning');
176
- * resultsLog.capture('operations:createUser', 'error');
177
- * ```
44
+ * Stores a copy of the frames: `StackTrail.trace` pops the live array
45
+ * after its callback returns.
178
46
  */
179
47
  capture(stackTrail, result) {
180
- if (__classPrivateFieldGet(this, _ResultsLog_instances, "m", _ResultsLog_incomingResultIsWorse).call(this, __classPrivateFieldGet(this, _ResultsLog_results, "f")[stackTrail], result)) {
181
- __classPrivateFieldGet(this, _ResultsLog_results, "f")[stackTrail] = result;
48
+ const key = stackTrail.toString();
49
+ if (__classPrivateFieldGet(this, _ResultsLog_instances, "m", _ResultsLog_incomingResultIsWorse).call(this, __classPrivateFieldGet(this, _ResultsLog_results, "f").get(key)?.result, result)) {
50
+ __classPrivateFieldGet(this, _ResultsLog_results, "f").set(key, { frames: [...stackTrail.stackTrail], result });
182
51
  }
183
52
  }
184
53
  /**
185
- * Converts the flat results structure into a hierarchical tree.
186
- *
187
- * This method transforms the internal flat storage (using colon-separated paths)
188
- * into a nested object structure that reflects the hierarchy of generation
189
- * operations. This makes it easier to understand and process results in
190
- * a structured way.
191
- *
192
- * @returns Nested object structure representing the results hierarchy
193
- *
194
- * @example
195
- * ```typescript
196
- * const resultsLog = new ResultsLog();
197
- * resultsLog.capture('api:models:User', 'success');
198
- * resultsLog.capture('api:operations:getUser', 'error');
199
- * resultsLog.capture('types:Status', 'success');
200
- *
201
- * const tree = resultsLog.toTree();
202
- * console.log(tree);
203
- * // {
204
- * // api: {
205
- * // models: {
206
- * // User: 'success'
207
- * // },
208
- * // operations: {
209
- * // getUser: 'error'
210
- * // }
211
- * // },
212
- * // types: {
213
- * // Status: 'success'
214
- * // }
215
- * // }
216
- * ```
54
+ * Nests the captured results by their frames, one object level per frame.
55
+ * Frames are used as own-property keys verbatim, so a frame such as
56
+ * `constructor`, `toString` or `0` is a key like any other. A result
57
+ * captured at the empty trail has no key and is left out.
217
58
  */
218
59
  toTree() {
219
60
  const tree = {};
220
- Object.entries(__classPrivateFieldGet(this, _ResultsLog_results, "f")).forEach(([key, value]) => {
221
- const keys = key.split(':');
222
- set(tree, keys, value);
61
+ __classPrivateFieldGet(this, _ResultsLog_results, "f").forEach(({ frames, result }) => {
62
+ const leafFrame = frames.at(-1);
63
+ if (leafFrame === undefined) {
64
+ return;
65
+ }
66
+ const parent = frames.slice(0, -1).reduce((node, frame) => {
67
+ const existing = Object.hasOwn(node, frame) ? node[frame] : undefined;
68
+ if (typeof existing === 'object' && existing !== null && !Array.isArray(existing)) {
69
+ return existing;
70
+ }
71
+ const child = {};
72
+ defineOwn(node, frame, child);
73
+ return child;
74
+ }, tree);
75
+ defineOwn(parent, leafFrame, result);
223
76
  });
224
77
  return tree;
225
78
  }
@@ -230,25 +83,13 @@ _ResultsLog_results = new WeakMap(), _ResultsLog_instances = new WeakSet(), _Res
230
83
  }
231
84
  return resultRankings[current] < resultRankings[incoming];
232
85
  };
86
+ /** Writes an own, enumerable property, even for keys such as `__proto__`. */
87
+ const defineOwn = (node, key, value) => {
88
+ Object.defineProperty(node, key, { value, enumerable: true, writable: true, configurable: true });
89
+ };
233
90
  /**
234
- * Priority rankings for different result types.
235
- *
236
- * This mapping defines the severity hierarchy used by the ResultsLog to determine
237
- * which results should take precedence when multiple results are captured for the
238
- * same path. Higher numbers indicate higher severity/priority.
239
- *
240
- * The ranking system ensures that critical issues (errors) are never masked by
241
- * less important results (success), while still allowing for proper escalation
242
- * when more severe conditions are encountered.
243
- *
244
- * @example Ranking hierarchy (high to low priority)
245
- * ```
246
- * error (50) - Critical failures that prevent generation
247
- * warning (40) - Issues that allow generation but need attention
248
- * success (30) - Normal successful completion
249
- * skipped (20) - Operations that were intentionally bypassed
250
- * notSupported (10) - Features not yet implemented
251
- * ```
91
+ * Severity of each result type. A higher number replaces a lower one
92
+ * captured at the same trail.
252
93
  */
253
94
  const resultRankings = {
254
95
  error: 50,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skmtc/core",
3
- "version": "0.33.0",
3
+ "version": "0.34.0",
4
4
  "description": "Skmtc is a declarative code generation framework",
5
5
  "keywords": [
6
6
  "openapi",
@@ -305,31 +305,18 @@ export declare class CoreContext {
305
305
  parseIssues: ParseIssue[];
306
306
  };
307
307
  /**
308
- * Captures a result at the current execution position in the stack trail.
309
- *
310
- * This method records processing results (success, warning, error, etc.) at the
311
- * current location in the document traversal stack. Results are associated with
312
- * the current stack trail position, enabling detailed error reporting and
313
- * debugging of OpenAPI processing issues.
308
+ * Captures a result at `stackTrail`. Each frame of the trail becomes one
309
+ * level of the `manifest.results` tree.
314
310
  *
315
311
  * @param result - The type of result to capture (success, warning, error, etc.)
312
+ * @param stackTrail - The trail the result belongs to
316
313
  *
317
- * @example Capturing a warning result
318
- * ```typescript
319
- * context.captureCurrentResult('warning');
320
- * // Result captured at current stack position like: "components.schemas.User.properties.email"
321
- * ```
322
- *
323
- * @example Usage during schema processing
314
+ * @example
324
315
  * ```typescript
325
- * context.trace(['components', 'schemas', 'User'], () => {
326
- * try {
327
- * processUserSchema();
328
- * context.captureCurrentResult('success');
329
- * } catch (error) {
330
- * context.captureCurrentResult('error');
331
- * }
332
- * });
316
+ * stackTrail.trace(['/pets', 'get'], opTrail => {
317
+ * context.captureCurrentResult('success', opTrail)
318
+ * })
319
+ * // manifest.results: { …, '/pets': { get: 'success' } }
333
320
  * ```
334
321
  */
335
322
  captureCurrentResult(result: ResultType, stackTrail: StackTrail): void;
@@ -448,35 +448,22 @@ class CoreContext {
448
448
  }
449
449
  }
450
450
  /**
451
- * Captures a result at the current execution position in the stack trail.
452
- *
453
- * This method records processing results (success, warning, error, etc.) at the
454
- * current location in the document traversal stack. Results are associated with
455
- * the current stack trail position, enabling detailed error reporting and
456
- * debugging of OpenAPI processing issues.
451
+ * Captures a result at `stackTrail`. Each frame of the trail becomes one
452
+ * level of the `manifest.results` tree.
457
453
  *
458
454
  * @param result - The type of result to capture (success, warning, error, etc.)
455
+ * @param stackTrail - The trail the result belongs to
459
456
  *
460
- * @example Capturing a warning result
461
- * ```typescript
462
- * context.captureCurrentResult('warning');
463
- * // Result captured at current stack position like: "components.schemas.User.properties.email"
464
- * ```
465
- *
466
- * @example Usage during schema processing
457
+ * @example
467
458
  * ```typescript
468
- * context.trace(['components', 'schemas', 'User'], () => {
469
- * try {
470
- * processUserSchema();
471
- * context.captureCurrentResult('success');
472
- * } catch (error) {
473
- * context.captureCurrentResult('error');
474
- * }
475
- * });
459
+ * stackTrail.trace(['/pets', 'get'], opTrail => {
460
+ * context.captureCurrentResult('success', opTrail)
461
+ * })
462
+ * // manifest.results: { …, '/pets': { get: 'success' } }
476
463
  * ```
477
464
  */
478
465
  captureCurrentResult(result, stackTrail) {
479
- __classPrivateFieldGet(this, _CoreContext_results, "f").capture(stackTrail.toString(), result);
466
+ __classPrivateFieldGet(this, _CoreContext_results, "f").capture(stackTrail, result);
480
467
  }
481
468
  }
482
469
  exports.CoreContext = CoreContext;
@@ -871,7 +871,7 @@ _GenerateContext_files = new WeakMap(), _GenerateContext_previews = new WeakMap(
871
871
  }
872
872
  }, _GenerateContext_runOasOperationGenerator = function _GenerateContext_runOasOperationGenerator(oasDocument, generatorConfig, include, skip, stackTrail) {
873
873
  oasDocument.operations.forEach(operation => {
874
- stackTrail.trace(`${operation.path}:${operation.method}`, opTrail => {
874
+ stackTrail.trace([operation.path, operation.method], opTrail => {
875
875
  // Resolve the variant list to fan out over. The consumer's
876
876
  // enrichments are keyed `[generatorId][path][method][variant]`;
877
877
  // the block at `[path][method]` is therefore a record of
@@ -894,7 +894,7 @@ _GenerateContext_files = new WeakMap(), _GenerateContext_previews = new WeakMap(
894
894
  operationLabel: `${operation.method.toUpperCase()} ${operation.path}`
895
895
  });
896
896
  variants.forEach(variant => {
897
- opTrail.trace(`variant: ${variant}`, st => {
897
+ opTrail.trace(['variant', variant], st => {
898
898
  try {
899
899
  if (typeof generatorConfig?.isSupported === 'function' &&
900
900
  !generatorConfig.isSupported({ operation, context: this, variant })) {
@@ -960,7 +960,7 @@ _GenerateContext_files = new WeakMap(), _GenerateContext_previews = new WeakMap(
960
960
  });
961
961
  }, _GenerateContext_runWebhookGenerator = function _GenerateContext_runWebhookGenerator(oasDocument, generatorConfig, include, skip, stackTrail) {
962
962
  oasDocument.webhooks.forEach(webhook => {
963
- stackTrail.trace(`webhook:${webhook.name}:${webhook.method}`, webhookTrail => {
963
+ stackTrail.trace(['webhook', webhook.name, webhook.method], webhookTrail => {
964
964
  // Variant fan-out, keyed `[generatorId][name][method][variant]` —
965
965
  // the webhook analogue of the operation routing. `toVariantList`
966
966
  // handles absent / non-object / object enrichment blocks and
@@ -976,7 +976,7 @@ _GenerateContext_files = new WeakMap(), _GenerateContext_previews = new WeakMap(
976
976
  operationLabel: `webhook '${webhook.name}' (${webhook.method.toUpperCase()})`
977
977
  });
978
978
  variants.forEach(variant => {
979
- webhookTrail.trace(`variant: ${variant}`, st => {
979
+ webhookTrail.trace(['variant', variant], st => {
980
980
  try {
981
981
  if (typeof generatorConfig?.isSupported === 'function' &&
982
982
  !generatorConfig.isSupported({ webhook, context: this, variant })) {
@@ -1041,7 +1041,7 @@ _GenerateContext_files = new WeakMap(), _GenerateContext_previews = new WeakMap(
1041
1041
  });
1042
1042
  }, _GenerateContext_runGqlOperationGenerator = function _GenerateContext_runGqlOperationGenerator(gqlDocument, generatorConfig, stackTrail) {
1043
1043
  gqlDocument.operations.forEach(operation => {
1044
- stackTrail.trace(operation.identifier, opTrail => {
1044
+ stackTrail.trace([operation.rootKind, operation.fieldName], opTrail => {
1045
1045
  // GraphQL enrichment routing key is
1046
1046
  // `[generatorId][rootKind][fieldName][variant]`.
1047
1047
  const opEnrichments = this.readEnrichment([
@@ -1055,7 +1055,7 @@ _GenerateContext_files = new WeakMap(), _GenerateContext_previews = new WeakMap(
1055
1055
  operationLabel: `${operation.rootKind} ${operation.fieldName}`
1056
1056
  });
1057
1057
  variants.forEach(variant => {
1058
- opTrail.trace(`variant: ${variant}`, st => {
1058
+ opTrail.trace(['variant', variant], st => {
1059
1059
  try {
1060
1060
  if (typeof generatorConfig.isSupported === 'function' &&
1061
1061
  !generatorConfig.isSupported({ operation, context: this, variant })) {
@@ -1107,7 +1107,7 @@ _GenerateContext_files = new WeakMap(), _GenerateContext_previews = new WeakMap(
1107
1107
  operationLabel: refName
1108
1108
  });
1109
1109
  variants.forEach(variant => {
1110
- refTrail.trace(`variant: ${variant}`, st => {
1110
+ refTrail.trace(['variant', variant], st => {
1111
1111
  try {
1112
1112
  if (typeof generatorConfig.isSupported === 'function' &&
1113
1113
  !generatorConfig.isSupported({ refName, context: this, variant })) {
@@ -194,7 +194,7 @@ export declare class ParseContext {
194
194
  * For tree-position issues, prefer {@link logIssueNoKey} so the
195
195
  * stack trail composes with the surrounding traces.
196
196
  *
197
- * Internally constructs a `StackTrail` from `location.split(':')`
197
+ * Internally constructs a `StackTrail` with `StackTrail.fromString(location)`
198
198
  * and delegates to {@link logIssueNoKey} — the underlying issue
199
199
  * recording logic (protocol tagging, optional ref-error
200
200
  * auto-registration, logger mirror with parent context) is shared.
@@ -469,13 +469,13 @@ class ParseContext {
469
469
  * For tree-position issues, prefer {@link logIssueNoKey} so the
470
470
  * stack trail composes with the surrounding traces.
471
471
  *
472
- * Internally constructs a `StackTrail` from `location.split(':')`
472
+ * Internally constructs a `StackTrail` with `StackTrail.fromString(location)`
473
473
  * and delegates to {@link logIssueNoKey} — the underlying issue
474
474
  * recording logic (protocol tagging, optional ref-error
475
475
  * auto-registration, logger mirror with parent context) is shared.
476
476
  */
477
477
  log({ location, parent, type, ...issue }) {
478
- const stackTrail = new StackTrail_js_1.StackTrail(location.split(':'));
478
+ const stackTrail = StackTrail_js_1.StackTrail.fromString(location);
479
479
  this.logIssueNoKey({ stackTrail, parent, type, ...issue });
480
480
  }
481
481
  /**
@@ -29,7 +29,8 @@ export declare class StackTrail {
29
29
  */
30
30
  clone(): StackTrail;
31
31
  /**
32
- * Gets a copy of the current stack frames.
32
+ * The live array of stack frames, not a copy: {@link trace} pops it after
33
+ * `fn` returns. Copy it (`[...trail.stackTrail]`) to keep the frames.
33
34
  *
34
35
  * @returns Array of stack frames in order
35
36
  *
@@ -64,8 +65,13 @@ export declare class StackTrail {
64
65
  * ```
65
66
  */
66
67
  append(frame: string | string[]): StackTrail;
67
- trace<T>(key: string, fn: (st: StackTrail) => T): T;
68
- traceAsync<T>(key: string, fn: (st: StackTrail) => Promise<T>): Promise<T>;
68
+ /**
69
+ * Runs `fn` on a copy of the trail with `key` appended: one frame for a
70
+ * string, one frame per element for an array.
71
+ */
72
+ trace<T>(key: string | string[], fn: (st: StackTrail) => T): T;
73
+ /** Async form of {@link trace}. */
74
+ traceAsync<T>(key: string | string[], fn: (st: StackTrail) => Promise<T>): Promise<T>;
69
75
  /**
70
76
  * Converts the trail to an OpenAPI reference string if applicable.
71
77
  *
@@ -187,22 +193,33 @@ export declare class StackTrail {
187
193
  */
188
194
  toJSON(): string;
189
195
  /**
190
- * Converts the trail to a colon-separated string representation.
196
+ * Converts the trail to a colon-separated string.
191
197
  *
192
- * Colons within frame names are escaped as '%3A' to avoid conflicts
193
- * with the separator character.
194
- *
195
- * @returns String representation of the trail
198
+ * Inside a frame, `%` is escaped as `%25` and `:` as `%3A`, so
199
+ * {@link StackTrail.fromString} reads the same frames back.
196
200
  *
197
201
  * @example
198
202
  * ```typescript
199
- * const trail = new StackTrail(['components', 'schemas', 'User']);
200
- * console.log(trail.toString()); // 'components:schemas:User'
203
+ * new StackTrail(['components', 'schemas', 'User']).toString()
204
+ * // 'components:schemas:User'
201
205
  *
202
- * // With colon in frame name
203
- * const trailWithColon = new StackTrail(['components', 'schemas', 'User:Type']);
204
- * console.log(trailWithColon.toString()); // 'components:schemas:User%3AType'
206
+ * new StackTrail(['paths', '/pets/{id}:archive', '100%']).toString()
207
+ * // 'paths:/pets/{id}%3Aarchive:100%25'
205
208
  * ```
206
209
  */
207
210
  toString(): string;
211
+ /**
212
+ * Reads a string written by {@link StackTrail.toString} back into a trail.
213
+ *
214
+ * Splits on `:` and decodes `%25` and `%3A` in each frame. The empty
215
+ * string gives the empty trail, so a trail of one empty frame is the one
216
+ * trail that does not round-trip.
217
+ *
218
+ * @example
219
+ * ```typescript
220
+ * StackTrail.fromString('paths:/pets/{id}%3Aarchive:post').stackTrail
221
+ * // ['paths', '/pets/{id}:archive', 'post']
222
+ * ```
223
+ */
224
+ static fromString(value: string): StackTrail;
208
225
  }
@@ -54,7 +54,8 @@ class StackTrail {
54
54
  return new StackTrail([...__classPrivateFieldGet(this, _StackTrail_stack, "f")]);
55
55
  }
56
56
  /**
57
- * Gets a copy of the current stack frames.
57
+ * The live array of stack frames, not a copy: {@link trace} pops it after
58
+ * `fn` returns. Copy it (`[...trail.stackTrail]`) to keep the frames.
58
59
  *
59
60
  * @returns Array of stack frames in order
60
61
  *
@@ -101,6 +102,10 @@ class StackTrail {
101
102
  }
102
103
  throw new Error(`Unexpected stack frame: ${frame}`);
103
104
  }
105
+ /**
106
+ * Runs `fn` on a copy of the trail with `key` appended: one frame for a
107
+ * string, one frame per element for an array.
108
+ */
104
109
  trace(key, fn) {
105
110
  const stackTrail = this.clone();
106
111
  stackTrail.append(key);
@@ -114,6 +119,7 @@ class StackTrail {
114
119
  throw error;
115
120
  }
116
121
  }
122
+ /** Async form of {@link trace}. */
117
123
  async traceAsync(key, fn) {
118
124
  const stackTrail = this.clone();
119
125
  stackTrail.append(key);
@@ -287,30 +293,46 @@ class StackTrail {
287
293
  return this.toString();
288
294
  }
289
295
  /**
290
- * Converts the trail to a colon-separated string representation.
296
+ * Converts the trail to a colon-separated string.
291
297
  *
292
- * Colons within frame names are escaped as '%3A' to avoid conflicts
293
- * with the separator character.
294
- *
295
- * @returns String representation of the trail
298
+ * Inside a frame, `%` is escaped as `%25` and `:` as `%3A`, so
299
+ * {@link StackTrail.fromString} reads the same frames back.
296
300
  *
297
301
  * @example
298
302
  * ```typescript
299
- * const trail = new StackTrail(['components', 'schemas', 'User']);
300
- * console.log(trail.toString()); // 'components:schemas:User'
303
+ * new StackTrail(['components', 'schemas', 'User']).toString()
304
+ * // 'components:schemas:User'
301
305
  *
302
- * // With colon in frame name
303
- * const trailWithColon = new StackTrail(['components', 'schemas', 'User:Type']);
304
- * console.log(trailWithColon.toString()); // 'components:schemas:User%3AType'
306
+ * new StackTrail(['paths', '/pets/{id}:archive', '100%']).toString()
307
+ * // 'paths:/pets/{id}%3Aarchive:100%25'
305
308
  * ```
306
309
  */
307
310
  toString() {
308
311
  return __classPrivateFieldGet(this, _StackTrail_stack, "f")
309
- .map(item => {
310
- return typeof item === 'string' ? item.replaceAll(':', '%3A') : item;
311
- })
312
+ .map(frame => frame.replace(/[%:]/g, character => escapes[character]))
312
313
  .join(':');
313
314
  }
315
+ /**
316
+ * Reads a string written by {@link StackTrail.toString} back into a trail.
317
+ *
318
+ * Splits on `:` and decodes `%25` and `%3A` in each frame. The empty
319
+ * string gives the empty trail, so a trail of one empty frame is the one
320
+ * trail that does not round-trip.
321
+ *
322
+ * @example
323
+ * ```typescript
324
+ * StackTrail.fromString('paths:/pets/{id}%3Aarchive:post').stackTrail
325
+ * // ['paths', '/pets/{id}:archive', 'post']
326
+ * ```
327
+ */
328
+ static fromString(value) {
329
+ if (value === '') {
330
+ return new StackTrail([]);
331
+ }
332
+ return new StackTrail(value.split(':').map(frame => frame.replace(/%(25|3A)/g, (_, code) => decodes[code])));
333
+ }
314
334
  }
315
335
  exports.StackTrail = StackTrail;
316
336
  _StackTrail_stack = new WeakMap();
337
+ const escapes = { '%': '%25', ':': '%3A' };
338
+ const decodes = { '25': '%', '3A': ':' };