@chaos-maker/core 0.4.0 → 0.6.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.
Files changed (35) hide show
  1. package/README.md +131 -10
  2. package/dist/chaos-config.schema.json +1314 -0
  3. package/dist/chaos-config.schema.notes.md +32 -0
  4. package/dist/chaos-maker.cjs +30 -5
  5. package/dist/chaos-maker.js +3845 -2400
  6. package/dist/chaos-maker.umd.js +30 -5
  7. package/dist/sw.js +1 -1
  8. package/dist/sw.mjs +861 -451
  9. package/dist/types/ChaosMaker.d.ts +46 -0
  10. package/dist/types/builder.d.ts +24 -0
  11. package/dist/types/config.d.ts +82 -14
  12. package/dist/types/debug.d.ts +58 -0
  13. package/dist/types/errors.d.ts +14 -2
  14. package/dist/types/events.d.ts +59 -1
  15. package/dist/types/format-event.d.ts +13 -0
  16. package/dist/types/groups.d.ts +71 -0
  17. package/dist/types/index.d.ts +33 -5
  18. package/dist/types/interceptors/domAssailant.d.ts +2 -1
  19. package/dist/types/interceptors/eventSource.d.ts +2 -1
  20. package/dist/types/interceptors/networkFetch.d.ts +2 -1
  21. package/dist/types/interceptors/networkXHR.d.ts +2 -1
  22. package/dist/types/interceptors/websocket.d.ts +2 -1
  23. package/dist/types/presets.d.ts +63 -2
  24. package/dist/types/runtime-state.d.ts +6 -0
  25. package/dist/types/seed-reporting.d.ts +1 -0
  26. package/dist/types/session-errors.d.ts +18 -0
  27. package/dist/types/sw-bridge-source.d.ts +5 -2
  28. package/dist/types/sw.d.ts +7 -0
  29. package/dist/types/utils.d.ts +46 -1
  30. package/dist/types/validation-deprecation.d.ts +7 -0
  31. package/dist/types/validation-format.d.ts +10 -0
  32. package/dist/types/validation-strip.d.ts +11 -0
  33. package/dist/types/validation-types.d.ts +34 -0
  34. package/dist/types/validation.d.ts +52 -0
  35. package/package.json +5 -3
package/README.md CHANGED
@@ -49,14 +49,82 @@ chaos.stop(); // restores original fetch/XHR
49
49
 
50
50
  ### Presets
51
51
 
52
+ Presets are reusable bundles of rules. Drop them into a config by name with the `presets` field, and the engine merges them at construction time.
53
+
52
54
  ```ts
53
- import { ChaosMaker, presets } from '@chaos-maker/core';
55
+ import { ChaosMaker } from '@chaos-maker/core';
54
56
 
55
- // Available: unstableApi, slowNetwork, offlineMode, flakyConnection, degradedUi
56
- const chaos = new ChaosMaker(presets.slowNetwork);
57
+ const chaos = new ChaosMaker({
58
+ presets: ['slow-api'],
59
+ network: {
60
+ failures: [{ urlPattern: '/api/checkout', statusCode: 500, probability: 1 }],
61
+ },
62
+ });
57
63
  chaos.start();
58
64
  ```
59
65
 
66
+ **Built-in catalog**
67
+
68
+ | camelCase name | Kebab alias | Behavior |
69
+ | ----------------------- | --------------- | ----------------------------------------------------------------- |
70
+ | `slowNetwork` | `slow-api` | 2000ms latency on every request |
71
+ | `flakyConnection` | `flaky-api` | 5% aborts plus 3000ms latency on 10% of requests |
72
+ | `offlineMode` | `offline-mode` | Force CORS failure on every request |
73
+ | `unstableApi` | `high-latency` | 10% failures + 20% 1000ms latency, scoped to `/api/` |
74
+ | `degradedUi` | | 20% disable buttons, 10% hide links |
75
+ | `unreliableWebSocket` | | 10% drops, 500ms inbound delay, 5% inbound truncation |
76
+ | `unreliableEventStream` | | 5% drops, 200ms delay, 2% close after 2000ms |
77
+
78
+ Kebab-case aliases (`slow-api`, `flaky-api`, `offline-mode`, `high-latency`) are registry-only. They resolve via `presets: ['slow-api']` and `new PresetRegistry().get('slow-api')`. They are NOT keys on the legacy `presets` record export - `presets['slow-api']` is `undefined` by design. Use the camelCase key (`presets.slowNetwork`) when reading from the record.
79
+
80
+ **Custom presets**
81
+
82
+ Register your own bundle inline via `customPresets`. Names collide fail-fast against built-ins and against each other.
83
+
84
+ ```ts
85
+ new ChaosMaker({
86
+ customPresets: {
87
+ 'team-flow': {
88
+ network: {
89
+ failures: [{ urlPattern: '/checkout', statusCode: 503, probability: 1 }],
90
+ },
91
+ },
92
+ },
93
+ presets: ['team-flow'],
94
+ });
95
+ ```
96
+
97
+ Custom preset values may carry only rule arrays plus the optional `groups` field - `presets`, `customPresets`, `seed`, and `debug` are rejected at validation. Dependency chains are out of scope.
98
+
99
+ **Builder helper**
100
+
101
+ ```ts
102
+ import { ChaosConfigBuilder } from '@chaos-maker/core';
103
+
104
+ const config = new ChaosConfigBuilder()
105
+ .usePreset('slow-api')
106
+ .failRequests('/api/checkout', 500, 1)
107
+ .build();
108
+ ```
109
+
110
+ **Validation**
111
+
112
+ Unknown preset names, chain attempts, forbidden subfields, duplicate registrations, and group-name collisions across preset+user all surface as `ChaosConfigError` at construction time, never at runtime.
113
+
114
+ **Mutability**
115
+
116
+ Built-in preset configs are deep-frozen - `presets.slowNetwork.network!.latencies![0].delayMs = 1` throws. Your own custom presets passed via `customPresets` are NOT frozen - keep treating them as your data. The engine takes a deep clone at expansion, so any tweaks you make after construction are not observed.
117
+
118
+ **Legacy spread**
119
+
120
+ ```ts
121
+ import { presets } from '@chaos-maker/core';
122
+
123
+ new ChaosMaker({ ...presets.slowNetwork, network: { failures: [{ urlPattern: '/api', statusCode: 500, probability: 1 }] } });
124
+ ```
125
+
126
+ Still supported for migration. Prefer the declarative `presets:` field for new code.
127
+
60
128
  ### Config Builder
61
129
 
62
130
  ```ts
@@ -191,22 +259,75 @@ Event types: `network:failure`, `network:latency`, `network:abort`, `network:cor
191
259
 
192
260
  ## Config Validation
193
261
 
194
- All configs are validated with Zod in strict mode. Unknown keys are rejected. Invalid values throw `ChaosConfigError` with descriptive messages.
262
+ All configs are validated with Zod in strict mode. Unknown keys are rejected by default. Invalid values throw `ChaosConfigError` whose `issues` is a `ValidationIssue[]` with structured `path` / `code` / `ruleType` / `message` / `expected` / `received`.
195
263
 
196
264
  ```ts
197
- import { validateConfig, ChaosConfigError } from '@chaos-maker/core';
265
+ import { validateChaosConfig, ChaosConfigError } from '@chaos-maker/core';
198
266
 
199
267
  try {
200
- validateConfig({ network: { failures: [{ urlPattern: '', statusCode: 999 }] } });
268
+ validateChaosConfig({
269
+ network: { failures: [{ urlPattern: '', statusCode: 999, probability: 2 }] },
270
+ });
201
271
  } catch (e) {
202
272
  if (e instanceof ChaosConfigError) {
203
- console.log(e.issues);
204
- // ['network.failures.0.urlPattern: urlPattern must not be empty',
205
- // 'network.failures.0.statusCode: Number must be less than or equal to 599']
273
+ for (const issue of e.issues) {
274
+ console.log(issue.path, issue.code, issue.message);
275
+ }
276
+ // legacy v0.4.x string array still available:
277
+ console.log(e.messages);
206
278
  }
207
279
  }
208
280
  ```
209
281
 
282
+ `validateChaosConfig(input, opts?)` accepts:
283
+
284
+ - `unknownFields: 'reject' | 'warn' | 'ignore'` - strict by default. `'warn'` and `'ignore'` strip unknowns from the returned config; `'warn'` emits exactly one aggregated `console.warn` per call.
285
+ - `customValidators: Partial<Record<RuleType, (rule, ctx) => ValidationIssue[] | void>>` - run extra checks per rule type.
286
+ - `onDeprecation: (issue) => void` - receive `ValidationIssue` events for deprecated fields. The registry is empty for this release.
287
+
288
+ A JSON Schema artifact ships at `node_modules/@chaos-maker/core/dist/chaos-config.schema.json` for IDE / `"$schema"` autocomplete plus a sidecar `chaos-config.schema.notes.md` listing parity caveats. The artifact is a tooling approximation - runtime canonical validation is always Zod via `validateChaosConfig`.
289
+
290
+ See the [Rule Validation concept page](https://chaos-maker-dev.github.io/chaos-maker/concepts/validation/) for the full pipeline, brand semantics, and migration notes.
291
+
292
+ ## Lifecycle and isolation
293
+
294
+ `start()` and `stop()` are the only entry points to the patched runtime. On `stop()` each restore step - `fetch`, `XMLHttpRequest`, `WebSocket`, `EventSource`, and the DOM observer - runs inside its own `try` / `catch`, so one failing step does not block the others from running. The failing step is reported via a `cleanup-step-failed:<step>` debug event and a `console.warn`. Some edge cases (frozen prototypes, third-party code that re-wraps a global between `start()` and `stop()`, host objects that reject property writes) may still leave a global patched; treat the diagnostics surface as the source of truth rather than assuming an absolute restore guarantee.
295
+
296
+ ```ts
297
+ const chaos = new ChaosMaker(config);
298
+ chaos.start();
299
+ try {
300
+ // ... drive the page ...
301
+ } finally {
302
+ chaos.stop(); // safe to call twice; idempotent.
303
+ }
304
+ ```
305
+
306
+ Concurrent instances against the same target are rejected. A second `start()` on a target that already has an active instance throws `[chaos-maker] target already has an active runtime instance` so the first instance keeps owning the patched globals. Use one `ChaosMaker` per realm (page, worker, jsdom) and call `stop()` before constructing a replacement.
307
+
308
+ ## Leak diagnostics
309
+
310
+ When debug mode is enabled, the engine emits structured invariant events whenever it sees signs of a leaked runtime - patched globals on start, stale wrapper handles, or another instance owning the target.
311
+
312
+ ```ts
313
+ const chaos = new ChaosMaker(config, { debug: true });
314
+ chaos.start();
315
+ // ...
316
+ chaos.stop();
317
+
318
+ const issues = chaos.getLog().filter((event) =>
319
+ event.type === 'debug' &&
320
+ (event.detail.reason?.includes('already-patched') ||
321
+ event.detail.reason?.includes('stale') ||
322
+ event.detail.reason?.includes('orphaned') ||
323
+ event.detail.reason === 'active-instance-conflict'),
324
+ );
325
+ ```
326
+
327
+ Reasons emitted include `target-fetch-already-patched`, `target-xhr-open-already-patched`, `target-xhr-send-already-patched`, `target-websocket-already-patched`, `target-eventsource-already-patched`, `stale-websocket-handle`, `stale-eventsource-handle`, `orphaned-dom-observer`, `active-instance-conflict`, and `cleanup-step-failed:<step>`. The same reasons appear with `phase: 'engine:stop'` when a global stays patched after `stop()` runs.
328
+
329
+ Diagnostics are surfaced through `getLog()` only when `debug: true`; the runtime never throws on these conditions (the active-instance check is the one exception). They are intended for CI noise reduction and bug reports, not control flow.
330
+
210
331
  ## Service Worker chaos
211
332
 
212
333
  Chaos applies to SW-originated fetches via the `@chaos-maker/core/sw` subpath. Zod + UI + builder are excluded from this bundle so it stays small enough for production SW deploys.
@@ -227,7 +348,7 @@ installChaosSW({ source: 'message' });
227
348
 
228
349
  Page-side config is delivered via `postMessage` + `MessageChannel` ack. Use the adapter helpers (`injectSWChaos` / `removeSWChaos` / `getSWChaosLog`) in `@chaos-maker/{playwright,cypress,webdriverio,puppeteer}`.
229
350
 
230
- Limitations: `caches.match` hits bypass chaos (planned for v0.5.0); push/sync events not covered; cross-origin SWs not supported.
351
+ Limitations: `caches.match` hits bypass chaos; push/sync events not covered; cross-origin SWs not supported.
231
352
 
232
353
  ## License
233
354