@orkestrel/test 0.0.30 → 0.0.32

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.
@@ -51,6 +51,16 @@ export declare function buildRetryExhausted(description: string, budget: number,
51
51
  */
52
52
  export declare function captureError(thunk: () => unknown): unknown;
53
53
 
54
+ /**
55
+ * Captures a synchronous or asynchronous producer's value or exact refusal.
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * await captureProduction(() => 7) // { status: 'fulfilled', value: 7 }
60
+ * ```
61
+ */
62
+ export declare function captureProduction<T>(produce: () => T | Promise<T>): Promise<Readonly<PromiseSettledResult<T>>>;
63
+
54
64
  /**
55
65
  * Checks the resolved bounds one bounded wait runs under.
56
66
  *
@@ -535,6 +545,16 @@ export declare function executeScenario<TState extends string, TEvent extends st
535
545
  readonly [K in TName]: RecorderInterface<TMap[K]>;
536
546
  };
537
547
 
548
+ /**
549
+ * Renders a retry value as JSON, plain text, or an unreadable-value marker.
550
+ *
551
+ * @example
552
+ * ```ts
553
+ * renderRetryValue({ ready: false }) // '{"ready":false}'
554
+ * ```
555
+ */
556
+ export declare function renderRetryValue(value: unknown): string;
557
+
538
558
  /**
539
559
  * Narrows a value away from `null` and `undefined`, throwing when it is absent.
540
560
  *
@@ -580,6 +600,14 @@ export declare function executeScenario<TState extends string, TEvent extends st
580
600
  destroy(id: number): void;
581
601
  }
582
602
 
603
+ /** Holds the latest produced text and producer refusal across a retry history. */
604
+ export declare interface RetryObservation {
605
+ /** Holds the latest rendered value, when a producer has returned. */
606
+ readonly last: string | undefined;
607
+ /** Holds the latest refusal, preserved across successful producer calls. */
608
+ readonly cause: unknown;
609
+ }
610
+
583
611
  /** Configures a bounded retry, adding an optional producer-call limit to a bounded wait's bounds. */
584
612
  export declare interface RetryOptions extends WaitOptions {
585
613
  /** Caps the number of producer calls. When omitted, only the time budget bounds the retry. */
@@ -816,6 +844,21 @@ export declare function executeScenario<TState extends string, TEvent extends st
816
844
  readonly absent?: string;
817
845
  }
818
846
 
847
+ /**
848
+ * Bounds how far a real timer can end short of its duration, in whole milliseconds.
849
+ *
850
+ * @remarks Node stamps an armed timer with libuv's whole-millisecond loop clock. Truncation and
851
+ * a coarse clock tick can each contribute under 1 ms of lead. Subtract this lead from an elapsed
852
+ * lower bound measured with `performance.now()` before arming the timer.
853
+ * @example
854
+ * ```ts
855
+ * const started = performance.now()
856
+ * await waitForDelay(10)
857
+ * performance.now() - started >= 10 - TIMER_LEAD // true
858
+ * ```
859
+ */
860
+ export declare const TIMER_LEAD = 2;
861
+
819
862
  /**
820
863
  * Waits until an abort signal is aborted.
821
864
  *
@@ -51,6 +51,16 @@ export declare function buildRetryExhausted(description: string, budget: number,
51
51
  */
52
52
  export declare function captureError(thunk: () => unknown): unknown;
53
53
 
54
+ /**
55
+ * Captures a synchronous or asynchronous producer's value or exact refusal.
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * await captureProduction(() => 7) // { status: 'fulfilled', value: 7 }
60
+ * ```
61
+ */
62
+ export declare function captureProduction<T>(produce: () => T | Promise<T>): Promise<Readonly<PromiseSettledResult<T>>>;
63
+
54
64
  /**
55
65
  * Checks the resolved bounds one bounded wait runs under.
56
66
  *
@@ -535,6 +545,16 @@ export declare function executeScenario<TState extends string, TEvent extends st
535
545
  readonly [K in TName]: RecorderInterface<TMap[K]>;
536
546
  };
537
547
 
548
+ /**
549
+ * Renders a retry value as JSON, plain text, or an unreadable-value marker.
550
+ *
551
+ * @example
552
+ * ```ts
553
+ * renderRetryValue({ ready: false }) // '{"ready":false}'
554
+ * ```
555
+ */
556
+ export declare function renderRetryValue(value: unknown): string;
557
+
538
558
  /**
539
559
  * Narrows a value away from `null` and `undefined`, throwing when it is absent.
540
560
  *
@@ -580,6 +600,14 @@ export declare function executeScenario<TState extends string, TEvent extends st
580
600
  destroy(id: number): void;
581
601
  }
582
602
 
603
+ /** Holds the latest produced text and producer refusal across a retry history. */
604
+ export declare interface RetryObservation {
605
+ /** Holds the latest rendered value, when a producer has returned. */
606
+ readonly last: string | undefined;
607
+ /** Holds the latest refusal, preserved across successful producer calls. */
608
+ readonly cause: unknown;
609
+ }
610
+
583
611
  /** Configures a bounded retry, adding an optional producer-call limit to a bounded wait's bounds. */
584
612
  export declare interface RetryOptions extends WaitOptions {
585
613
  /** Caps the number of producer calls. When omitted, only the time budget bounds the retry. */
@@ -816,6 +844,21 @@ export declare function executeScenario<TState extends string, TEvent extends st
816
844
  readonly absent?: string;
817
845
  }
818
846
 
847
+ /**
848
+ * Bounds how far a real timer can end short of its duration, in whole milliseconds.
849
+ *
850
+ * @remarks Node stamps an armed timer with libuv's whole-millisecond loop clock. Truncation and
851
+ * a coarse clock tick can each contribute under 1 ms of lead. Subtract this lead from an elapsed
852
+ * lower bound measured with `performance.now()` before arming the timer.
853
+ * @example
854
+ * ```ts
855
+ * const started = performance.now()
856
+ * await waitForDelay(10)
857
+ * performance.now() - started >= 10 - TIMER_LEAD // true
858
+ * ```
859
+ */
860
+ export declare const TIMER_LEAD = 2;
861
+
819
862
  /**
820
863
  * Waits until an abort signal is aborted.
821
864
  *
@@ -1,5 +1,19 @@
1
1
  import { attempt, holds, isArray, isDefined, isError, isFiniteNumber, isFunction, isInteger, isNumber, isObject, isSymbol } from "@orkestrel/contract";
2
- //#region src/core/constants.ts
2
+ // src/core/constants.ts
3
+ /**
4
+ * Bounds how far a real timer can end short of its duration, in whole milliseconds.
5
+ *
6
+ * @remarks Node stamps an armed timer with libuv's whole-millisecond loop clock. Truncation and
7
+ * a coarse clock tick can each contribute under 1 ms of lead. Subtract this lead from an elapsed
8
+ * lower bound measured with `performance.now()` before arming the timer.
9
+ * @example
10
+ * ```ts
11
+ * const started = performance.now()
12
+ * await waitForDelay(10)
13
+ * performance.now() - started >= 10 - TIMER_LEAD // true
14
+ * ```
15
+ */
16
+ var TIMER_LEAD = 2;
3
17
  /**
4
18
  * Names the attributes a statechart harness publishes, keyed by the fact each one carries.
5
19
  *
@@ -58,8 +72,7 @@ var STATECHART_STATUSES = Object.freeze([
58
72
  "passed",
59
73
  "failed"
60
74
  ]);
61
- //#endregion
62
- //#region src/core/validators.ts
75
+ // src/core/validators.ts
63
76
  /**
64
77
  * Checks whether a value contains a recorder for every listed event.
65
78
  *
@@ -96,8 +109,28 @@ function isRecorderMapComplete(value, events) {
96
109
  });
97
110
  });
98
111
  }
99
- //#endregion
100
- //#region src/core/helpers.ts
112
+ // src/core/Production.ts
113
+ /** Holds one producer attempt across its native await and catch boundary. */
114
+ var Production = class {
115
+ #result;
116
+ get result() {
117
+ if (this.#result === void 0) throw new Error("Producer attempt has not settled");
118
+ return this.#result;
119
+ }
120
+ accept(value) {
121
+ this.#result = {
122
+ status: "fulfilled",
123
+ value
124
+ };
125
+ }
126
+ refuse(reason) {
127
+ this.#result = {
128
+ status: "rejected",
129
+ reason
130
+ };
131
+ }
132
+ };
133
+ // src/core/helpers.ts
101
134
  /**
102
135
  * Checks the resolved bounds one bounded wait runs under.
103
136
  *
@@ -298,12 +331,14 @@ async function waitForText(description, read, text, options) {
298
331
  if (absent !== void 0 && absent.length === 0) throw new Error("Text expectation must not be empty");
299
332
  if (absent !== void 0 && text.includes(absent)) throw new Error("Text departure must not appear in the text expectation");
300
333
  const exact = options?.exact ?? false;
301
- let observed = "";
334
+ const accepted = Promise.withResolvers();
302
335
  await waitForCondition(description, () => {
303
- observed = read();
304
- return (exact ? observed === text : observed.includes(text)) && (absent === void 0 || !observed.includes(absent));
336
+ const observed = read();
337
+ const held = (exact ? observed === text : observed.includes(text)) && (absent === void 0 || !observed.includes(absent));
338
+ if (held) accepted.resolve(observed);
339
+ return held;
305
340
  }, options);
306
- return observed;
341
+ return accepted.promise;
307
342
  }
308
343
  /**
309
344
  * Repeats a producer until one produced value satisfies a predicate.
@@ -327,47 +362,48 @@ async function retryUntil(description, produce, satisfied, options) {
327
362
  checkBounds("Retry", budget, interval);
328
363
  if (isDefined(attempts) && (!isInteger(attempts) || attempts < 1)) throw new Error("Retry attempts must be a positive integer");
329
364
  const start = performance.now();
330
- let count = 0;
331
- let cause;
332
- let last;
365
+ const outcomes = [];
333
366
  while (true) {
334
367
  options?.signal?.throwIfAborted();
335
- if (count > 0) {
368
+ const previous = outcomes.reduce((summary, outcome) => outcome.success ? {
369
+ ...summary,
370
+ last: outcome.value
371
+ } : {
372
+ ...summary,
373
+ cause: outcome.error
374
+ }, {
375
+ last: void 0,
376
+ cause: void 0
377
+ });
378
+ if (outcomes.length > 0) {
336
379
  const elapsed = performance.now() - start;
337
- if (elapsed >= budget) throw buildRetryExhausted(description, budget, elapsed, last, cause);
380
+ if (elapsed >= budget) throw buildRetryExhausted(description, budget, elapsed, previous.last, previous.cause);
338
381
  }
339
- let produced;
382
+ const production = new Production();
340
383
  try {
341
- produced = {
342
- success: true,
343
- value: await produce()
344
- };
384
+ production.accept(await produce());
345
385
  } catch (error) {
346
- produced = {
347
- success: false,
348
- error
349
- };
386
+ production.refuse(error);
350
387
  }
351
- count += 1;
388
+ const produced = production.result;
352
389
  options?.signal?.throwIfAborted();
353
- if (produced.success) {
390
+ if (produced.status === "fulfilled") {
354
391
  if (satisfied(produced.value)) return produced.value;
355
- let rendered;
356
- try {
357
- const serialized = JSON.stringify(produced.value);
358
- rendered = serialized === void 0 ? String(produced.value) : serialized;
359
- } catch {
360
- try {
361
- rendered = String(produced.value);
362
- } catch {
363
- rendered = "[unrenderable]";
364
- }
365
- }
366
- last = rendered.length > 200 ? `${rendered.slice(0, 197)}...` : rendered;
367
- } else cause = produced.error;
392
+ const rendered = renderRetryValue(produced.value);
393
+ outcomes.push({
394
+ success: true,
395
+ value: rendered.length > 200 ? `${rendered.slice(0, 197)}...` : rendered
396
+ });
397
+ } else outcomes.push({
398
+ success: false,
399
+ error: produced.reason
400
+ });
401
+ const latest = outcomes.at(-1);
402
+ const last = latest?.success === true ? latest.value : previous.last;
403
+ const cause = latest?.success === false ? latest.error : previous.cause;
368
404
  const elapsed = performance.now() - start;
369
405
  if (elapsed >= budget) throw buildRetryExhausted(description, budget, elapsed, last, cause);
370
- if (attempts !== void 0 && count >= attempts) throw new Error(`Retry "${description}" did not succeed within ${attempts} attempts${last === void 0 ? "" : ` (last value: ${last})`}`, { cause });
406
+ if (attempts !== void 0 && outcomes.length >= attempts) throw new Error(`Retry "${description}" did not succeed within ${attempts} attempts${last === void 0 ? "" : ` (last value: ${last})`}`, { cause });
371
407
  await waitForDelay(Math.min(interval, budget - elapsed));
372
408
  }
373
409
  }
@@ -433,30 +469,25 @@ async function waitForEvent(subscribe, description, options) {
433
469
  signal?.throwIfAborted();
434
470
  const delivery = Promise.withResolvers();
435
471
  const controller = new AbortController();
436
- let timeout;
437
- const pending = [delivery.promise, new Promise((_resolve, reject) => {
438
- timeout = setTimeout(() => {
439
- reject(/* @__PURE__ */ new Error(`Event "${description}" was not delivered within ${budget}ms`));
440
- }, budget);
441
- })];
472
+ const expiry = Promise.withResolvers();
473
+ const timeout = setTimeout(() => {
474
+ expiry.reject(/* @__PURE__ */ new Error(`Event "${description}" was not delivered within ${budget}ms`));
475
+ }, budget);
476
+ const pending = [delivery.promise, expiry.promise];
442
477
  if (signal !== void 0) pending.push(new Promise((_resolve, reject) => {
443
478
  AbortSignal.any([signal, controller.signal]).addEventListener("abort", () => {
444
479
  if (signal.aborted) reject(signal.reason);
445
480
  }, { once: true });
446
481
  }));
447
482
  const result = Promise.race(pending);
448
- let cleanup = void 0;
483
+ const subscription = attempt(() => subscribe((...args) => delivery.resolve(args)));
449
484
  try {
450
- try {
451
- cleanup = subscribe((...args) => delivery.resolve(args));
452
- } catch (error) {
453
- delivery.reject(error);
454
- }
485
+ if (!subscription.success) delivery.reject(subscription.error);
455
486
  return await result;
456
487
  } finally {
457
488
  controller.abort();
458
- if (timeout !== void 0) clearTimeout(timeout);
459
- cleanup?.();
489
+ clearTimeout(timeout);
490
+ if (subscription.success) subscription.value?.();
460
491
  }
461
492
  }
462
493
  /**
@@ -697,17 +728,73 @@ async function executeScenario(scenario, context) {
697
728
  */
698
729
  async function executeScenarios(scenarios, build) {
699
730
  for (const scenario of scenarios) {
700
- let context;
701
- try {
702
- context = await build(scenario);
703
- } catch (cause) {
704
- throw buildRefusal(scenario.transition.name, cause);
705
- }
706
- await executeScenario(scenario, context);
731
+ const context = await captureProduction(() => build(scenario));
732
+ if (context.status === "rejected") throw buildRefusal(scenario.transition.name, context.reason);
733
+ await executeScenario(scenario, context.value);
734
+ }
735
+ }
736
+ /**
737
+ * Captures a synchronous or asynchronous producer's value or exact refusal.
738
+ *
739
+ * @example
740
+ * ```ts
741
+ * await captureProduction(() => 7) // { status: 'fulfilled', value: 7 }
742
+ * ```
743
+ */
744
+ async function captureProduction(produce) {
745
+ try {
746
+ return {
747
+ status: "fulfilled",
748
+ value: await produce()
749
+ };
750
+ } catch (error) {
751
+ return {
752
+ status: "rejected",
753
+ reason: error
754
+ };
707
755
  }
708
756
  }
709
- //#endregion
710
- //#region src/core/factories.ts
757
+ /**
758
+ * Renders a retry value as JSON, plain text, or an unreadable-value marker.
759
+ *
760
+ * @example
761
+ * ```ts
762
+ * renderRetryValue({ ready: false }) // '{"ready":false}'
763
+ * ```
764
+ */
765
+ function renderRetryValue(value) {
766
+ const serialized = attempt(() => {
767
+ const text = JSON.stringify(value);
768
+ return text === void 0 ? String(value) : text;
769
+ });
770
+ if (serialized.success) return serialized.value;
771
+ const text = attempt(() => String(value));
772
+ return text.success ? text.value : "[unrenderable]";
773
+ }
774
+ // src/core/Teardown.ts
775
+ /** Owns the handlers behind a teardown projection. */
776
+ var Teardown = class {
777
+ #handlers = [];
778
+ get count() {
779
+ return this.#handlers.length;
780
+ }
781
+ add(handler) {
782
+ this.#handlers.push(handler);
783
+ }
784
+ async destroy() {
785
+ const snapshot = this.#handlers;
786
+ this.#handlers = [];
787
+ const failures = [];
788
+ for (const handler of snapshot.reverse()) try {
789
+ await handler();
790
+ } catch (error) {
791
+ failures.push(error);
792
+ }
793
+ if (failures.length === 1) throw failures[0];
794
+ if (failures.length > 1) throw new AggregateError(failures);
795
+ }
796
+ };
797
+ // src/core/factories.ts
711
798
  /**
712
799
  * Creates values that make common object readers throw or violate their assumptions.
713
800
  *
@@ -955,29 +1042,15 @@ function createResourceFactory() {
955
1042
  * @returns A teardown list that awaits every handler and collects failures.
956
1043
  */
957
1044
  function createTeardown() {
958
- let handlers = [];
1045
+ const teardown = new Teardown();
959
1046
  return {
960
1047
  get count() {
961
- return handlers.length;
962
- },
963
- add(handler) {
964
- handlers.push(handler);
1048
+ return teardown.count;
965
1049
  },
966
- async destroy() {
967
- const snapshot = handlers;
968
- handlers = [];
969
- const failures = [];
970
- for (const handler of snapshot.reverse()) try {
971
- await handler();
972
- } catch (error) {
973
- failures.push(error);
974
- }
975
- if (failures.length === 1) throw failures[0];
976
- if (failures.length > 1) throw new AggregateError(failures);
977
- }
1050
+ add: teardown.add.bind(teardown),
1051
+ destroy: teardown.destroy.bind(teardown)
978
1052
  };
979
1053
  }
980
- //#endregion
981
- export { STATECHART_ATTRIBUTES, STATECHART_STATUSES, buildRefusal, buildRetryExhausted, captureError, checkBounds, collect, collectSelectorClasses, collectStream, createHostileValues, createRecorder, createRecorders, createResourceFactory, createSignal, createTeardown, decodeJSONLines, dropRegistration, executeScenario, executeScenarios, flattenHeaders, invokeUnchecked, isRecorderMapComplete, readProperty, requireValue, resolveRoot, retryUntil, roundTripJSON, waitForAbort, waitForCondition, waitForDelay, waitForEvent, waitForText };
1054
+ export { STATECHART_ATTRIBUTES, STATECHART_STATUSES, TIMER_LEAD, buildRefusal, buildRetryExhausted, captureError, captureProduction, checkBounds, collect, collectSelectorClasses, collectStream, createHostileValues, createRecorder, createRecorders, createResourceFactory, createSignal, createTeardown, decodeJSONLines, dropRegistration, executeScenario, executeScenarios, flattenHeaders, invokeUnchecked, isRecorderMapComplete, readProperty, renderRetryValue, requireValue, resolveRoot, retryUntil, roundTripJSON, waitForAbort, waitForCondition, waitForDelay, waitForEvent, waitForText };
982
1055
 
983
1056
  //# sourceMappingURL=index.js.map