doxum 0.1.26 → 0.1.28

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 (39) hide show
  1. package/README.md +86 -3
  2. package/dist/advanced.cjs +40 -30
  3. package/dist/advanced.cjs.map +1 -1
  4. package/dist/advanced.d.cts +34 -2
  5. package/dist/advanced.d.ts +34 -2
  6. package/dist/advanced.js +31 -22
  7. package/dist/advanced.js.map +1 -1
  8. package/dist/{definition-xgk3YNBp.d.ts → dependency-B3E65M1E.d.cts} +27 -3
  9. package/dist/{definition-CDOuvb5C.d.cts → dependency-BYbdDHNa.d.ts} +27 -3
  10. package/dist/driver-B5vdPohL.js.map +1 -1
  11. package/dist/driver-BL91gn7_.cjs.map +1 -1
  12. package/dist/index.cjs +885 -394
  13. package/dist/index.cjs.map +1 -1
  14. package/dist/index.d.cts +33 -18
  15. package/dist/index.d.ts +33 -18
  16. package/dist/index.js +784 -293
  17. package/dist/index.js.map +1 -1
  18. package/dist/local-sync.cjs.map +1 -1
  19. package/dist/local-sync.js.map +1 -1
  20. package/dist/transform-B4T3AcJr.js +938 -0
  21. package/dist/transform-B4T3AcJr.js.map +1 -0
  22. package/dist/transform-DUleAsG0.cjs +1105 -0
  23. package/dist/transform-DUleAsG0.cjs.map +1 -0
  24. package/package.json +1 -1
  25. package/skills/doxum-runtime/SKILL.md +16 -6
  26. package/skills/doxum-runtime/references/api.en.md +49 -15
  27. package/skills/doxum-runtime/references/api.zh-CN.md +47 -13
  28. package/skills/doxum-runtime/references/guide.en.md +2 -1
  29. package/skills/doxum-runtime/references/guide.zh-CN.md +2 -1
  30. package/skills/doxum-runtime/references/invariants.en.md +2 -2
  31. package/skills/doxum-runtime/references/invariants.zh-CN.md +2 -2
  32. package/skills/doxum-runtime/references/patterns.en.md +1 -1
  33. package/skills/doxum-runtime/references/patterns.zh-CN.md +1 -1
  34. package/skills/doxum-runtime/references/projections.en.md +77 -4
  35. package/skills/doxum-runtime/references/projections.zh-CN.md +74 -3
  36. package/dist/scheduler--137L3j-.js +0 -500
  37. package/dist/scheduler--137L3j-.js.map +0 -1
  38. package/dist/scheduler-D4VthaaK.cjs +0 -589
  39. package/dist/scheduler-D4VthaaK.cjs.map +0 -1
@@ -1,500 +0,0 @@
1
- const profile = {
2
- projection: (key, amount = 1) => {},
3
- recorder: (key, amount = 1) => {},
4
- access: (key) => {},
5
- copy: {
6
- structure: () => {},
7
- treeNode: () => {},
8
- shallowRecord: (items) => {}
9
- },
10
- equality: {
11
- call: () => {},
12
- container: () => {}
13
- },
14
- address: {
15
- listIndex: (items) => {},
16
- schemaStep: () => {},
17
- documentStep: () => {},
18
- prefixComparison: () => {},
19
- segmentCompared: () => {}
20
- },
21
- impact: {
22
- index: () => {},
23
- affects: () => {}
24
- },
25
- dependency: {
26
- comparison: () => {},
27
- segmentCompared: () => {}
28
- },
29
- collectionIndex: {
30
- node: () => {},
31
- build: (items) => {}
32
- },
33
- collectionView: {
34
- mapped: () => {},
35
- idsScanned: (amount = 1) => {},
36
- arrayCopied: () => {}
37
- },
38
- materialized: {
39
- updated: () => {},
40
- rebuilt: () => {},
41
- notification: () => {}
42
- }
43
- };
44
- //#endregion
45
- //#region core/src/projection/definition.ts
46
- const projections = /* @__PURE__ */ new WeakMap();
47
- const defineRef = (producer, output) => {
48
- const handle = Object.freeze({});
49
- projections.set(handle, Object.freeze({
50
- producer,
51
- output
52
- }));
53
- return handle;
54
- };
55
- const projectionRef = (projection) => {
56
- const ref = projections.get(projection);
57
- if (!ref) throw new TypeError("Unknown projection definition.");
58
- return ref;
59
- };
60
- const producerOf = (projection) => projectionRef(projection).producer;
61
- const isProjection = (value) => value !== null && typeof value === "object" && projections.has(value);
62
- const ownProjections = (projections, owner) => {
63
- const producers = new Set(projections.map(producerOf));
64
- for (const producer of producers) {
65
- if (producer.owner !== void 0 && producer.owner !== owner) throw new TypeError("Projection producer already belongs to another scope.");
66
- if (producer.owner === void 0 && producer.materialized) throw new TypeError("A materialized root projection cannot become scope-owned.");
67
- if (producer.kind !== "processor") continue;
68
- for (const dependency of producer.dependencies) {
69
- const dependencyOwner = producerOf(dependency).owner;
70
- if (dependencyOwner !== void 0 && dependencyOwner !== owner) throw new TypeError("A scope cannot depend on another scope.");
71
- }
72
- }
73
- for (const producer of producers) producer.owner = owner;
74
- };
75
- const freezeOutput = (output) => Object.freeze({
76
- kind: output.kind,
77
- equality: output.equality,
78
- ...output.path ? { path: Object.freeze([...output.path]) } : {}
79
- });
80
- const defineProcessor = (definition) => {
81
- if (!Array.isArray(definition.dependencies)) throw new TypeError("Projection dependencies must be an array.");
82
- definition.dependencies.forEach(projectionRef);
83
- if (!definition.outputs.length) throw new TypeError("Projection processor requires an output.");
84
- const producer = {
85
- kind: "processor",
86
- dependencies: Object.freeze([...definition.dependencies]),
87
- outputs: Object.freeze(definition.outputs.map(freezeOutput)),
88
- create: definition.create,
89
- ...definition.name ? { name: definition.name } : {}
90
- };
91
- return Object.freeze(producer.outputs.map((_, output) => defineRef(producer, output)));
92
- };
93
- const defineSource = (source, output) => {
94
- return defineRef({
95
- kind: "source",
96
- source,
97
- output: freezeOutput(output)
98
- }, 0);
99
- };
100
- //#endregion
101
- //#region core/src/projection/collection/view.ts
102
- const mapRead = (value) => ({
103
- get: (key) => value.get(key),
104
- has: (key) => value.has(key),
105
- ids: () => Object.freeze([...value.keys()])
106
- });
107
- /** Immutable map-like view over a CollectionRead. */
108
- const collectionView = (read) => {
109
- const ids = read.ids();
110
- const entries = function* () {
111
- for (const key of ids) yield [key, read.get(key)];
112
- };
113
- const values = function* () {
114
- for (const key of ids) yield read.get(key);
115
- };
116
- const view = {
117
- get: (key) => read.get(key),
118
- has: (key) => read.has(key),
119
- get size() {
120
- return ids.length;
121
- },
122
- keys: () => ids[Symbol.iterator](),
123
- values,
124
- entries,
125
- forEach: (callback, thisArg) => {
126
- for (const key of ids) callback.call(thisArg, read.get(key), key, view);
127
- },
128
- [Symbol.iterator]: entries
129
- };
130
- return Object.freeze(view);
131
- };
132
- /** Eager durable view used when a processor result may retain its dependency value. */
133
- const snapshotCollectionView = (read) => {
134
- const ids = read.ids();
135
- const values = /* @__PURE__ */ new Map();
136
- for (const key of ids) values.set(key, read.get(key));
137
- return collectionView(mapRead(values));
138
- };
139
- //#endregion
140
- //#region core/src/projection/contract.ts
141
- var ProjectionError = class extends Error {
142
- cause;
143
- constructor(phase, cause) {
144
- super(`Projection ${phase} failed.`, { cause });
145
- this.phase = phase;
146
- this.name = "ProjectionError";
147
- this.cause = cause;
148
- }
149
- };
150
- var ProjectionDisposedError = class extends Error {
151
- constructor() {
152
- super("Projection has been disposed.");
153
- this.name = "ProjectionDisposedError";
154
- }
155
- };
156
- //#endregion
157
- //#region core/src/projection/graph/scheduler.ts
158
- const createScheduler = (onError) => {
159
- let disposed = false;
160
- let depth = 0;
161
- let batchSequence = 0;
162
- let activeBatch;
163
- let phase = "idle";
164
- let sequence = 0;
165
- const sources = /* @__PURE__ */ new Set();
166
- const processors = /* @__PURE__ */ new Set();
167
- const pendingSources = /* @__PURE__ */ new Set();
168
- const heap = [];
169
- const queued = /* @__PURE__ */ new Set();
170
- const completed = /* @__PURE__ */ new Set();
171
- const emissions = /* @__PURE__ */ new Set();
172
- const errors = [];
173
- let reportingFailures = [];
174
- const guards = /* @__PURE__ */ new Set();
175
- const assertActive = () => {
176
- if (disposed) throw new ProjectionDisposedError();
177
- };
178
- const assertIdle = () => {
179
- assertActive();
180
- if (phase !== "idle") throw new Error("Projection cannot be re-entered during processing or notification.");
181
- };
182
- const lock = (value) => guards.forEach((guard) => guard(value));
183
- const enqueue = (processor) => {
184
- if (processor.disposed || queued.has(processor)) return;
185
- queued.add(processor);
186
- profile.projection("scheduledNodes");
187
- let index = heap.length;
188
- heap.push(processor);
189
- while (index > 0) {
190
- const parent = index - 1 >> 1;
191
- if (heap[parent].order < processor.order) break;
192
- heap[index] = heap[parent];
193
- index = parent;
194
- }
195
- heap[index] = processor;
196
- };
197
- const pop = () => {
198
- const first = heap[0];
199
- const last = heap.pop();
200
- if (heap.length) {
201
- let index = 0;
202
- while (index * 2 + 1 < heap.length) {
203
- let child = index * 2 + 1;
204
- if (child + 1 < heap.length && heap[child + 1].order < heap[child].order) child++;
205
- if (last.order < heap[child].order) break;
206
- heap[index] = heap[child];
207
- index = child;
208
- }
209
- heap[index] = last;
210
- }
211
- return first;
212
- };
213
- const errorFor = (producer, cause, kind = producer.kind === "source" ? "source" : "processor") => new ProjectionError(kind, cause);
214
- const capture = (source) => {
215
- if (disposed) return;
216
- if (phase !== "idle") {
217
- source.fault = errorFor(source, /* @__PURE__ */ new Error("Source changed while projection was running."), "source");
218
- errors.push(source.fault);
219
- throw source.fault;
220
- }
221
- pendingSources.add(source);
222
- profile.projection("sourceEvents");
223
- if (source.fault) errors.push(source.fault);
224
- };
225
- const settleCause = () => {
226
- if (activeBatch?.cause !== void 0) return activeBatch.cause;
227
- for (const source of pendingSources) {
228
- const cause = source.pendingCause();
229
- if (cause !== void 0) return cause;
230
- }
231
- };
232
- const settle = () => {
233
- if (disposed || depth || phase !== "idle") return;
234
- phase = "compute";
235
- lock(true);
236
- const cause = settleCause();
237
- try {
238
- for (const source of pendingSources) {
239
- if (source.disposed) continue;
240
- const wasFaulted = source.fault !== void 0;
241
- let changed = false;
242
- let force = false;
243
- if (!source.fault || source.recovering()) try {
244
- const prepared = source.prepare(cause);
245
- changed = prepared.changed;
246
- force = prepared.force;
247
- source.fault = void 0;
248
- } catch (failure) {
249
- source.fault = errorFor(source, failure, "source");
250
- errors.push(source.fault);
251
- }
252
- const recovered = wasFaulted && !source.fault;
253
- if (changed) source.publish();
254
- if (source.fault || changed || force || recovered) {
255
- const output = source.outputs[0];
256
- emissions.add(output);
257
- output.forEachConsumer(enqueue);
258
- }
259
- }
260
- while (heap.length) {
261
- const processor = pop();
262
- if (processor.disposed) continue;
263
- const wasFaulted = processor.fault !== void 0;
264
- profile.projection("processedNodes");
265
- let changedOutputs = Object.freeze([]);
266
- const blocked = processor.dependencies.find((output) => output.owner.fault || output.owner.disposed);
267
- if (blocked) processor.fault = errorFor(processor, blocked.owner.fault ?? new ProjectionDisposedError(), "blocked");
268
- else {
269
- const reset = wasFaulted || processor.dependencies.some((output) => output.reset());
270
- try {
271
- changedOutputs = processor.evaluate(reset, cause, wasFaulted);
272
- const dependencyFailure = processor.dependencies.find((output) => output.owner.fault)?.owner.fault;
273
- if (dependencyFailure) throw dependencyFailure;
274
- processor.fault = void 0;
275
- } catch (failure) {
276
- const error = errorFor(processor, failure);
277
- processor.fault = error;
278
- if (!reset) try {
279
- changedOutputs = processor.evaluate(true, cause, true);
280
- const dependencyFailure = processor.dependencies.find((output) => output.owner.fault)?.owner.fault;
281
- if (dependencyFailure) throw dependencyFailure;
282
- processor.fault = void 0;
283
- errors.push(error);
284
- } catch (rebuildFailure) {
285
- processor.fault = errorFor(processor, rebuildFailure);
286
- errors.push(processor.fault);
287
- }
288
- else errors.push(error);
289
- }
290
- }
291
- completed.add(processor);
292
- const recovered = wasFaulted && !processor.fault;
293
- if (processor.fault) processor.outputs.forEach((output) => {
294
- emissions.add(output);
295
- output.forEachConsumer(enqueue);
296
- });
297
- else {
298
- if (changedOutputs.length) {
299
- processor.publish();
300
- changedOutputs.forEach((output) => emissions.add(output));
301
- }
302
- (recovered ? processor.outputs : changedOutputs).forEach((output) => output.forEachConsumer(enqueue));
303
- }
304
- if (processor.fault || changedOutputs.length) profile.projection("publishedNodes");
305
- }
306
- } finally {
307
- lock(false);
308
- phase = "idle";
309
- }
310
- };
311
- const flush = () => {
312
- if (disposed || depth) return [];
313
- if (pendingSources.size || completed.size) profile.projection("flushes");
314
- phase = "notify";
315
- lock(true);
316
- const reportFailures = [];
317
- try {
318
- emissions.forEach((output) => output.emit((listener) => {
319
- try {
320
- listener();
321
- } catch (cause) {
322
- errors.push(errorFor(output.owner, cause, "listener"));
323
- }
324
- }));
325
- for (const error of errors.slice()) try {
326
- onError(error);
327
- } catch (cause) {
328
- reportFailures.push(cause);
329
- }
330
- return Object.freeze([...errors.map((error) => Object.freeze({
331
- phase: error.phase === "listener" ? "listener" : "processor",
332
- error
333
- })), ...reportFailures.map((error) => Object.freeze({
334
- phase: "listener",
335
- error
336
- }))]);
337
- } finally {
338
- pendingSources.forEach((source) => source.clear());
339
- completed.forEach((processor) => processor.clear());
340
- pendingSources.clear();
341
- queued.clear();
342
- completed.clear();
343
- emissions.clear();
344
- errors.length = 0;
345
- reportingFailures = reportFailures;
346
- lock(false);
347
- phase = "idle";
348
- }
349
- };
350
- const run = () => {
351
- settle();
352
- const result = flush();
353
- const failures = reportingFailures;
354
- reportingFailures = [];
355
- if (failures.length) throw new AggregateError(failures, "Projection error reporter failed.");
356
- return result;
357
- };
358
- const batch = (callback, options) => {
359
- assertIdle();
360
- if (depth === 0) activeBatch = Object.freeze({
361
- id: ++batchSequence,
362
- ...options?.cause === void 0 ? {} : { cause: options.cause }
363
- });
364
- depth++;
365
- let failed = false;
366
- try {
367
- const value = callback();
368
- assertSynchronous(value);
369
- return value;
370
- } catch (error) {
371
- failed = true;
372
- throw error;
373
- } finally {
374
- depth--;
375
- if (!depth) try {
376
- if (failed) try {
377
- run();
378
- } catch {}
379
- else run();
380
- } finally {
381
- activeBatch = void 0;
382
- }
383
- }
384
- };
385
- const releaseProducer = (producer) => {
386
- assertIdle();
387
- if (producer.outputs.some((output) => output.hasConsumers())) throw new Error("Projection producer is still used by another processor.");
388
- producer.disposed = true;
389
- if (producer.kind === "processor") {
390
- producer.dependencies.forEach((output) => output.detachConsumer(producer));
391
- processors.delete(producer);
392
- queued.delete(producer);
393
- completed.delete(producer);
394
- } else {
395
- sources.delete(producer);
396
- pendingSources.delete(producer);
397
- }
398
- const failures = [];
399
- try {
400
- producer.release();
401
- } catch (error) {
402
- failures.push(error);
403
- }
404
- try {
405
- producer.clear();
406
- } catch (error) {
407
- failures.push(error);
408
- }
409
- producer.outputs.forEach((output) => emissions.delete(output));
410
- if (failures.length) throw failures[0];
411
- };
412
- return {
413
- assertActive,
414
- assertIdle,
415
- capture,
416
- settle,
417
- flush,
418
- run,
419
- registerGuard(guard) {
420
- assertActive();
421
- guards.add(guard);
422
- let registered = true;
423
- return () => {
424
- if (!registered) return;
425
- registered = false;
426
- guards.delete(guard);
427
- };
428
- },
429
- get active() {
430
- return !disposed;
431
- },
432
- addSource(source) {
433
- assertIdle();
434
- sources.add(source);
435
- },
436
- addProcessor(processor) {
437
- assertIdle();
438
- processors.add(processor);
439
- processor.dependencies.forEach((output) => output.attachConsumer(processor));
440
- },
441
- releaseProducer,
442
- order: () => sequence++,
443
- initialize(callback) {
444
- assertIdle();
445
- phase = "compute";
446
- lock(true);
447
- try {
448
- return callback();
449
- } finally {
450
- lock(false);
451
- phase = "idle";
452
- }
453
- },
454
- batch,
455
- batchContext: () => activeBatch,
456
- dispose() {
457
- if (disposed) return;
458
- assertIdle();
459
- disposed = true;
460
- const failures = [];
461
- processors.forEach((processor) => {
462
- processor.disposed = true;
463
- try {
464
- processor.release();
465
- } catch (error) {
466
- failures.push(error);
467
- }
468
- });
469
- sources.forEach((source) => {
470
- source.disposed = true;
471
- try {
472
- source.release();
473
- } catch (error) {
474
- failures.push(error);
475
- }
476
- });
477
- processors.clear();
478
- sources.clear();
479
- pendingSources.clear();
480
- heap.length = 0;
481
- queued.clear();
482
- completed.clear();
483
- emissions.clear();
484
- guards.clear();
485
- errors.length = 0;
486
- reportingFailures = [];
487
- if (failures.length) throw new AggregateError(failures, "Projection cleanup failed.");
488
- }
489
- };
490
- };
491
- const assertSynchronous = (value) => {
492
- if (value != null && (typeof value === "object" || typeof value === "function") && "then" in value && typeof value.then === "function") throw new TypeError("Projection callbacks must be synchronous.");
493
- };
494
- const assertScope = (active) => {
495
- if (!active()) throw new Error("Projection reader or writer is no longer active.");
496
- };
497
- //#endregion
498
- export { ProjectionError as a, snapshotCollectionView as c, isProjection as d, ownProjections as f, profile as h, ProjectionDisposedError as i, defineProcessor as l, projectionRef as m, assertSynchronous as n, collectionView as o, producerOf as p, createScheduler as r, mapRead as s, assertScope as t, defineSource as u };
499
-
500
- //# sourceMappingURL=scheduler--137L3j-.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"scheduler--137L3j-.js","names":[],"sources":["../core/src/profile.ts","../core/src/projection/definition.ts","../core/src/projection/collection/view.ts","../core/src/projection/contract.ts","../core/src/projection/graph/scheduler.ts"],"sourcesContent":["const counters = () => ({\n projection: {\n sourceEvents: 0,\n scheduledNodes: 0,\n processedNodes: 0,\n touchedKeys: 0,\n changedKeys: 0,\n publishedNodes: 0,\n flushes: 0,\n },\n copy: { structures: 0, treeNodes: 0, shallowRecordItems: 0 },\n equality: { calls: 0, containers: 0 },\n recorder: {\n facts: 0,\n groups: 0,\n transitions: 0,\n absorbed: 0,\n orderSnapshots: 0,\n orderCaptures: 0,\n orderItems: 0,\n publishedOrderItems: 0,\n treeNodes: 0,\n sealed: 0,\n indexedGroups: 0,\n },\n access: { scopes: 0, proxies: 0, snapshots: 0, addresses: 0, resolutions: 0 },\n address: {\n schemaSteps: 0,\n documentSteps: 0,\n prefixComparisons: 0,\n segmentsCompared: 0,\n listIndexes: 0,\n listItems: 0,\n },\n impact: { affectsChecks: 0, indexes: 0 },\n dependency: { comparisons: 0, segmentsCompared: 0 },\n collectionIndex: { nodes: 0, builds: 0, builtItems: 0 },\n collectionView: { mappedItems: 0, idsScanned: 0, arraysCopied: 0 },\n materialized: { updated: 0, rebuilt: 0, notifications: 0 },\n});\ntype Counters = ReturnType<typeof counters>;\ntype DeepReadonly<T> = { readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K] };\nexport type ProfileSnapshot = DeepReadonly<Counters>;\nlet active: Counters | undefined;\nconst freeze = <T extends object>(value: T): DeepReadonly<T> => {\n Object.values(value).forEach(child => {\n if (child && typeof child === 'object') freeze(child);\n });\n return Object.freeze(value) as DeepReadonly<T>;\n};\nexport const profile = {\n projection: (key: keyof Counters['projection'], amount = 1) => {\n if (active) active.projection[key] += amount;\n },\n recorder: (key: keyof Counters['recorder'], amount = 1) => {\n if (active) active.recorder[key] += amount;\n },\n access: (key: keyof Counters['access']) => {\n if (active) active.access[key]++;\n },\n copy: {\n structure: () => {\n if (active) active.copy.structures++;\n },\n treeNode: () => {\n if (active) active.copy.treeNodes++;\n },\n shallowRecord: (items: number) => {\n if (active) active.copy.shallowRecordItems += items;\n },\n },\n equality: {\n call: () => {\n if (active) active.equality.calls++;\n },\n container: () => {\n if (active) active.equality.containers++;\n },\n },\n address: {\n listIndex: (items: number) => {\n if (active) {\n active.address.listIndexes++;\n active.address.listItems += items;\n }\n },\n schemaStep: () => {\n if (active) active.address.schemaSteps++;\n },\n documentStep: () => {\n if (active) active.address.documentSteps++;\n },\n prefixComparison: () => {\n if (active) active.address.prefixComparisons++;\n },\n segmentCompared: () => {\n if (active) active.address.segmentsCompared++;\n },\n },\n impact: {\n index: () => {\n if (active) active.impact.indexes++;\n },\n affects: () => {\n if (active) active.impact.affectsChecks++;\n },\n },\n dependency: {\n comparison: () => {\n if (active) active.dependency.comparisons++;\n },\n segmentCompared: () => {\n if (active) active.dependency.segmentsCompared++;\n },\n },\n collectionIndex: {\n node: () => {\n if (active) active.collectionIndex.nodes++;\n },\n build: (items: number) => {\n if (active) {\n active.collectionIndex.builds++;\n active.collectionIndex.builtItems += items;\n }\n },\n },\n collectionView: {\n mapped: () => {\n if (active) active.collectionView.mappedItems++;\n },\n idsScanned: (amount = 1) => {\n if (active) active.collectionView.idsScanned += amount;\n },\n arrayCopied: () => {\n if (active) active.collectionView.arraysCopied++;\n },\n },\n materialized: {\n updated: () => {\n if (active) active.materialized.updated++;\n },\n rebuilt: () => {\n if (active) active.materialized.rebuilt++;\n },\n notification: () => {\n if (active) active.materialized.notifications++;\n },\n },\n};\nexport type ProfileSession = { snapshot(): ProfileSnapshot; stop(): ProfileSnapshot };\nexport const startProfile = (): ProfileSession => {\n if (active) throw new Error('A document profile session is already active.');\n const value = counters();\n active = value;\n const snapshot = () => freeze(structuredClone(value));\n return {\n snapshot,\n stop: () => {\n if (active === value) active = undefined;\n return snapshot();\n },\n };\n};\nexport const measureProfile = <T>(run: () => T): { value: T; profile: ProfileSnapshot } => {\n const session = startProfile();\n try {\n return { value: run(), profile: session.stop() };\n } finally {\n session.stop();\n }\n};\n","import type { ReadonlyDocument } from '../runtime/contract';\nimport type { ObjectSchema } from '../schema/model';\nimport type { CollectionSelector, ValueSelector } from '../schema/path';\nimport type {\n CollectionChange,\n CollectionDraft,\n CollectionRead,\n ExternalCollectionSource,\n ExternalValueSource,\n SourceContext,\n} from './contract';\nimport type { Readable } from '../readable';\n\ndeclare const projectionDefinition: unique symbol;\ndeclare const keyedProjection: unique symbol;\ndeclare const writableInput: unique symbol;\ndeclare const writableCollectionInput: unique symbol;\n\n/** A lazy output reference with no materialized Runtime state. */\nexport type Projection<T> = {\n readonly [projectionDefinition]: T;\n};\n\n/** A projection whose output is a keyed collection with per-key change semantics. */\nexport type KeyedProjection<K extends string, V> = Projection<ReadonlyMap<K, V>> & {\n readonly [keyedProjection]: { readonly key: K; readonly value: V };\n};\n\n/** A writable source projection. */\nexport type Input<T> = Projection<T> & { readonly [writableInput]: true };\n\n/** A writable keyed collection source projection. */\nexport type CollectionInput<K extends string, V> = KeyedProjection<K, V> & {\n readonly [writableCollectionInput]: { readonly key: K; readonly value: V };\n};\n\nexport type CollectionInputDraft<K extends string, V> = {\n get(key: K): V | undefined;\n has(key: K): boolean;\n set(key: K, value: V): void;\n remove(key: K): void;\n};\n\nexport type ProjectionChange<P> =\n P extends KeyedProjection<infer K, infer V> ? CollectionChange<K, V> : undefined;\n\nexport type Equality = (a: unknown, b: unknown) => boolean;\n\nexport type OutputDefinition =\n | {\n readonly kind: 'value';\n readonly equality: Equality;\n readonly path?: readonly string[];\n }\n | {\n readonly kind: 'collection';\n readonly equality: Equality;\n readonly path?: readonly string[];\n };\n\nexport type ValueOutputEvaluation = {\n readonly kind: 'value';\n readonly previous: unknown;\n readonly next: () => unknown;\n readonly output: { set(value: unknown): void };\n};\n\nexport type CollectionOutputEvaluation = {\n readonly kind: 'collection';\n readonly previous: CollectionRead<string, unknown>;\n readonly next: CollectionRead<string, unknown>;\n readonly output: CollectionDraft<string, unknown>;\n};\n\nexport type OutputEvaluation = ValueOutputEvaluation | CollectionOutputEvaluation;\n\nexport type ProcessorEvaluation = {\n readonly reset: boolean;\n readonly cause: unknown;\n readonly sources: readonly SourceContext[];\n readonly outputs: readonly OutputEvaluation[];\n};\n\nexport type ProcessorInstance = {\n evaluate(input: ProcessorEvaluation): void;\n release?(): void;\n};\n\nexport type SourceAdapter =\n | {\n readonly kind: 'value-input';\n readonly initial: unknown;\n readonly equality: Equality;\n }\n | {\n readonly kind: 'collection-input';\n readonly initial: ReadonlyMap<string, unknown>;\n readonly equality: Equality;\n }\n | {\n readonly kind: 'readable';\n readonly readable: Readable<unknown>;\n readonly equality: Equality;\n }\n | {\n readonly kind: 'external-value';\n readonly source: ExternalValueSource<unknown>;\n readonly equality: Equality;\n }\n | {\n readonly kind: 'external-collection';\n readonly source: ExternalCollectionSource<string, unknown>;\n }\n | {\n readonly kind: 'document';\n readonly document: ReadonlyDocument<ObjectSchema<object>>;\n readonly selector: ValueSelector | CollectionSelector;\n };\n\nexport type SourceDefinition = {\n readonly kind: 'source';\n readonly source: SourceAdapter;\n readonly output: OutputDefinition;\n owner?: object;\n materialized?: true;\n};\n\nexport type ProcessorDefinition = {\n readonly kind: 'processor';\n readonly dependencies: readonly Projection<unknown>[];\n readonly outputs: readonly OutputDefinition[];\n readonly create: () => ProcessorInstance;\n readonly name?: string;\n owner?: object;\n materialized?: true;\n};\n\nexport type ProducerDefinition = SourceDefinition | ProcessorDefinition;\n\nexport type ProjectionRef = {\n readonly producer: ProducerDefinition;\n readonly output: number;\n};\n\nconst projections = new WeakMap<object, ProjectionRef>();\n\nconst defineRef = <T>(producer: ProducerDefinition, output: number): Projection<T> => {\n const handle = Object.freeze({}) as Projection<T>;\n projections.set(handle, Object.freeze({ producer, output }));\n return handle;\n};\n\nexport const projectionRef = (projection: Projection<unknown>): ProjectionRef => {\n const ref = projections.get(projection);\n if (!ref) throw new TypeError('Unknown projection definition.');\n return ref;\n};\n\nexport const producerOf = (projection: Projection<unknown>): ProducerDefinition =>\n projectionRef(projection).producer;\n\nexport const isProjection = (value: unknown): value is Projection<unknown> =>\n value !== null && typeof value === 'object' && projections.has(value);\n\nexport const ownProjections = (\n projections: readonly Projection<unknown>[],\n owner: object\n): void => {\n const producers = new Set(projections.map(producerOf));\n for (const producer of producers) {\n if (producer.owner !== undefined && producer.owner !== owner)\n throw new TypeError('Projection producer already belongs to another scope.');\n if (producer.owner === undefined && producer.materialized)\n throw new TypeError('A materialized root projection cannot become scope-owned.');\n if (producer.kind !== 'processor') continue;\n for (const dependency of producer.dependencies) {\n const dependencyOwner = producerOf(dependency).owner;\n if (dependencyOwner !== undefined && dependencyOwner !== owner)\n throw new TypeError('A scope cannot depend on another scope.');\n }\n }\n for (const producer of producers) producer.owner = owner;\n};\n\nconst freezeOutput = (output: OutputDefinition): OutputDefinition =>\n Object.freeze({\n kind: output.kind,\n equality: output.equality,\n ...(output.path ? { path: Object.freeze([...output.path]) } : {}),\n });\n\nexport const defineProcessor = (definition: {\n readonly dependencies: readonly Projection<unknown>[];\n readonly outputs: readonly OutputDefinition[];\n readonly create: () => ProcessorInstance;\n readonly name?: string;\n}): readonly Projection<unknown>[] => {\n if (!Array.isArray(definition.dependencies))\n throw new TypeError('Projection dependencies must be an array.');\n definition.dependencies.forEach(projectionRef);\n if (!definition.outputs.length) throw new TypeError('Projection processor requires an output.');\n const producer: ProcessorDefinition = {\n kind: 'processor',\n dependencies: Object.freeze([...definition.dependencies]),\n outputs: Object.freeze(definition.outputs.map(freezeOutput)),\n create: definition.create,\n ...(definition.name ? { name: definition.name } : {}),\n };\n return Object.freeze(producer.outputs.map((_, output) => defineRef<unknown>(producer, output)));\n};\n\nexport const defineSource = <T>(source: SourceAdapter, output: OutputDefinition): Projection<T> => {\n const producer: SourceDefinition = {\n kind: 'source',\n source,\n output: freezeOutput(output),\n };\n return defineRef<T>(producer, 0);\n};\n","import type { CollectionRead } from '../contract';\n\nexport const mapRead = <K extends string, V>(value: ReadonlyMap<K, V>): CollectionRead<K, V> => ({\n get: key => value.get(key),\n has: key => value.has(key),\n ids: () => Object.freeze([...value.keys()]),\n});\n\n/** Immutable map-like view over a CollectionRead. */\nexport const collectionView = <K extends string, V>(\n read: CollectionRead<K, V>\n): ReadonlyMap<K, V> => {\n const ids = read.ids();\n const entries = function* (): IterableIterator<[K, V]> {\n for (const key of ids) yield [key, read.get(key) as V];\n };\n const values = function* (): IterableIterator<V> {\n for (const key of ids) yield read.get(key) as V;\n };\n const view: ReadonlyMap<K, V> = {\n get: key => read.get(key),\n has: key => read.has(key),\n get size() {\n return ids.length;\n },\n keys: () => ids[Symbol.iterator](),\n values,\n entries,\n forEach: (callback, thisArg) => {\n for (const key of ids) callback.call(thisArg, read.get(key) as V, key, view);\n },\n [Symbol.iterator]: entries,\n };\n return Object.freeze(view);\n};\n\n/** Eager durable view used when a processor result may retain its dependency value. */\nexport const snapshotCollectionView = <K extends string, V>(\n read: CollectionRead<K, V>\n): ReadonlyMap<K, V> => {\n const ids = read.ids();\n const values = new Map<K, V>();\n for (const key of ids) values.set(key, read.get(key) as V);\n return collectionView(mapRead(values));\n};\n","import type { CollectionImpact } from '../impact';\nimport type { Unsubscribe } from '../runtime/contract';\n\n/** Scheduler-owned metadata for one Runtime batch. */\nexport type BatchContext = {\n readonly id: number;\n readonly cause?: unknown;\n};\n\n/** The one processor-facing collection transition protocol. */\nexport type CollectionChange<K extends string, V> =\n | { readonly kind: 'reset' }\n | {\n readonly kind: 'incremental';\n readonly added: readonly { readonly key: K; readonly after: V }[];\n readonly updated: readonly {\n readonly key: K;\n readonly before: V;\n readonly after: V;\n }[];\n readonly removed: readonly { readonly key: K; readonly before: V }[];\n readonly order?: {\n readonly before: readonly K[];\n readonly after: readonly K[];\n };\n };\n\nexport type ValueContext<T> = {\n readonly kind: 'value';\n readonly value: T;\n readonly revision: number;\n readonly reset: boolean;\n readonly cause?: unknown;\n};\n\nexport type CollectionRead<K extends string, V> = {\n get(key: K): V | undefined;\n has(key: K): boolean;\n ids(): readonly K[];\n};\n\nexport type ExternalCollectionRead<K extends string, V> = {\n readonly get: (key: K) => V | undefined;\n readonly has: (key: K) => boolean;\n readonly ids: () => readonly K[];\n};\n\nexport type CollectionContext<K extends string, V> = {\n readonly kind: 'collection';\n readonly read: CollectionRead<K, V>;\n readonly change: CollectionChange<K, V> | undefined;\n readonly revision: number;\n readonly reset: boolean;\n readonly cause?: unknown;\n};\n\nexport type SourceContext = ValueContext<unknown> | CollectionContext<string, unknown>;\n\nexport type ExternalValueSource<T> = {\n readonly kind: 'value';\n current(): T;\n revision(): number;\n subscribe(listener: (event: ExternalValueEvent<T>) => void): Unsubscribe;\n};\n\nexport type ExternalCollectionSource<K extends string, V> = {\n readonly kind: 'collection';\n current(): ExternalCollectionRead<K, V>;\n revision(): number;\n subscribe(listener: (event: ExternalCollectionEvent<K, V>) => void): Unsubscribe;\n};\n\nexport type ExternalValueEvent<T> = {\n readonly value: T;\n readonly revision: number;\n readonly reset?: boolean;\n readonly cause?: unknown;\n};\n\nexport type ExternalCollectionEvent<K extends string, V> = {\n /** Stable read from the source before this event or external batch. */\n readonly previous: ExternalCollectionRead<K, V>;\n readonly revision: number;\n /** Optional document-style hint; the adapter resolves the canonical change. */\n readonly impact?: CollectionImpact<K>;\n readonly cause?: unknown;\n};\n\nexport type CollectionDraft<K extends string, V> = {\n set(key: K, value: V): void;\n remove(key: K): void;\n order(ids: readonly K[]): void;\n};\n\nexport class ProjectionError extends Error {\n readonly cause: unknown;\n\n constructor(\n readonly phase: 'processor' | 'listener' | 'source' | 'blocked',\n cause: unknown\n ) {\n super(`Projection ${phase} failed.`, { cause });\n this.name = 'ProjectionError';\n this.cause = cause;\n }\n}\n\nexport class ProjectionDisposedError extends Error {\n constructor() {\n super('Projection has been disposed.');\n this.name = 'ProjectionDisposedError';\n }\n}\n","import { profile } from '../../profile';\nimport type { ObserverError, Unsubscribe } from '../../runtime/contract';\nimport type { BatchContext, SourceContext } from '../contract';\nimport { ProjectionDisposedError, ProjectionError } from '../contract';\n\ntype BatchOptions = { readonly cause?: unknown };\n\ntype ProducerBase = {\n readonly name: string;\n readonly outputs: readonly OutputRecord[];\n fault: ProjectionError | undefined;\n disposed: boolean;\n clear(): void;\n release(): void;\n};\n\nexport type OutputRecord = {\n readonly kind: 'value' | 'collection';\n readonly owner: ProducerRecord;\n context(active: () => boolean): SourceContext;\n current(): unknown;\n revision(): number;\n reset(): boolean;\n subscribe(listener: () => void): Unsubscribe;\n emit(call: (listener: () => void) => void): void;\n hasConsumers(): boolean;\n forEachConsumer(run: (consumer: ProcessorRecord) => void): void;\n attachConsumer(consumer: ProcessorRecord): void;\n detachConsumer(consumer: ProcessorRecord): void;\n clear(): void;\n release(): void;\n};\n\nexport type SourceBoundaryRecord = ProducerBase & {\n readonly kind: 'source';\n readonly outputs: readonly [OutputRecord];\n pendingCause(): unknown;\n recovering(): boolean;\n prepare(cause: unknown): { readonly changed: boolean; readonly force: boolean };\n publish(): void;\n};\n\nexport type ProcessorRecord = ProducerBase & {\n readonly kind: 'processor';\n readonly dependencies: readonly OutputRecord[];\n readonly order: number;\n evaluate(reset: boolean, cause: unknown, recreate?: boolean): readonly OutputRecord[];\n publish(): void;\n};\n\nexport type ProducerRecord = SourceBoundaryRecord | ProcessorRecord;\n\nexport const createScheduler = (onError: (error: ProjectionError) => void) => {\n let disposed = false;\n let depth = 0;\n let batchSequence = 0;\n let activeBatch: BatchContext | undefined;\n let phase: 'idle' | 'compute' | 'notify' = 'idle';\n let sequence = 0;\n const sources = new Set<SourceBoundaryRecord>();\n const processors = new Set<ProcessorRecord>();\n const pendingSources = new Set<SourceBoundaryRecord>();\n const heap: ProcessorRecord[] = [];\n const queued = new Set<ProcessorRecord>();\n const completed = new Set<ProcessorRecord>();\n const emissions = new Set<OutputRecord>();\n const errors: ProjectionError[] = [];\n let reportingFailures: unknown[] = [];\n const guards = new Set<(locked: boolean) => void>();\n\n const assertActive = () => {\n if (disposed) throw new ProjectionDisposedError();\n };\n const assertIdle = () => {\n assertActive();\n if (phase !== 'idle')\n throw new Error('Projection cannot be re-entered during processing or notification.');\n };\n const lock = (value: boolean) => guards.forEach(guard => guard(value));\n\n const enqueue = (processor: ProcessorRecord) => {\n if (processor.disposed || queued.has(processor)) return;\n queued.add(processor);\n profile.projection('scheduledNodes');\n let index = heap.length;\n heap.push(processor);\n while (index > 0) {\n const parent = (index - 1) >> 1;\n if (heap[parent].order < processor.order) break;\n heap[index] = heap[parent];\n index = parent;\n }\n heap[index] = processor;\n };\n\n const pop = (): ProcessorRecord => {\n const first = heap[0];\n const last = heap.pop()!;\n if (heap.length) {\n let index = 0;\n while (index * 2 + 1 < heap.length) {\n let child = index * 2 + 1;\n if (child + 1 < heap.length && heap[child + 1].order < heap[child].order) child++;\n if (last.order < heap[child].order) break;\n heap[index] = heap[child];\n index = child;\n }\n heap[index] = last;\n }\n return first;\n };\n\n const errorFor = (\n producer: ProducerRecord,\n cause: unknown,\n kind: ProjectionError['phase'] = producer.kind === 'source' ? 'source' : 'processor'\n ) => new ProjectionError(kind, cause);\n\n const capture = (source: SourceBoundaryRecord) => {\n if (disposed) return;\n if (phase !== 'idle') {\n source.fault = errorFor(\n source,\n new Error('Source changed while projection was running.'),\n 'source'\n );\n errors.push(source.fault);\n throw source.fault;\n }\n pendingSources.add(source);\n profile.projection('sourceEvents');\n if (source.fault) errors.push(source.fault);\n };\n\n const settleCause = (): unknown => {\n if (activeBatch?.cause !== undefined) return activeBatch.cause;\n for (const source of pendingSources) {\n const cause = source.pendingCause();\n if (cause !== undefined) return cause;\n }\n return undefined;\n };\n\n const settle = () => {\n if (disposed || depth || phase !== 'idle') return;\n phase = 'compute';\n lock(true);\n const cause = settleCause();\n try {\n for (const source of pendingSources) {\n if (source.disposed) continue;\n const wasFaulted = source.fault !== undefined;\n let changed = false;\n let force = false;\n if (!source.fault || source.recovering()) {\n try {\n const prepared = source.prepare(cause);\n changed = prepared.changed;\n force = prepared.force;\n source.fault = undefined;\n } catch (failure) {\n source.fault = errorFor(source, failure, 'source');\n errors.push(source.fault);\n }\n }\n const recovered = wasFaulted && !source.fault;\n if (changed) source.publish();\n if (source.fault || changed || force || recovered) {\n const output = source.outputs[0];\n emissions.add(output);\n output.forEachConsumer(enqueue);\n }\n }\n\n while (heap.length) {\n const processor = pop();\n if (processor.disposed) continue;\n const wasFaulted = processor.fault !== undefined;\n profile.projection('processedNodes');\n let changedOutputs: readonly OutputRecord[] = Object.freeze([]);\n const blocked = processor.dependencies.find(\n output => output.owner.fault || output.owner.disposed\n );\n if (blocked) {\n processor.fault = errorFor(\n processor,\n blocked.owner.fault ?? new ProjectionDisposedError(),\n 'blocked'\n );\n } else {\n const reset = wasFaulted || processor.dependencies.some(output => output.reset());\n try {\n changedOutputs = processor.evaluate(reset, cause, wasFaulted);\n const dependencyFailure = processor.dependencies.find(output => output.owner.fault)\n ?.owner.fault;\n if (dependencyFailure) throw dependencyFailure;\n processor.fault = undefined;\n } catch (failure) {\n const error = errorFor(processor, failure);\n processor.fault = error;\n if (!reset) {\n try {\n changedOutputs = processor.evaluate(true, cause, true);\n const dependencyFailure = processor.dependencies.find(output => output.owner.fault)\n ?.owner.fault;\n if (dependencyFailure) throw dependencyFailure;\n processor.fault = undefined;\n errors.push(error);\n } catch (rebuildFailure) {\n processor.fault = errorFor(processor, rebuildFailure);\n errors.push(processor.fault);\n }\n } else errors.push(error);\n }\n }\n completed.add(processor);\n const recovered = wasFaulted && !processor.fault;\n if (processor.fault) {\n processor.outputs.forEach(output => {\n emissions.add(output);\n output.forEachConsumer(enqueue);\n });\n } else {\n if (changedOutputs.length) {\n processor.publish();\n changedOutputs.forEach(output => emissions.add(output));\n }\n const propagated = recovered ? processor.outputs : changedOutputs;\n propagated.forEach(output => output.forEachConsumer(enqueue));\n }\n if (processor.fault || changedOutputs.length) {\n profile.projection('publishedNodes');\n }\n }\n } finally {\n lock(false);\n phase = 'idle';\n }\n };\n\n const flush = (): readonly ObserverError[] => {\n if (disposed || depth) return [];\n if (pendingSources.size || completed.size) profile.projection('flushes');\n phase = 'notify';\n lock(true);\n const reportFailures: unknown[] = [];\n try {\n emissions.forEach(output =>\n output.emit(listener => {\n try {\n listener();\n } catch (cause) {\n errors.push(errorFor(output.owner, cause, 'listener'));\n }\n })\n );\n for (const error of errors.slice()) {\n try {\n onError(error);\n } catch (cause) {\n reportFailures.push(cause);\n }\n }\n return Object.freeze([\n ...errors.map(error =>\n Object.freeze({\n phase: error.phase === 'listener' ? ('listener' as const) : ('processor' as const),\n error,\n })\n ),\n ...reportFailures.map(error => Object.freeze({ phase: 'listener' as const, error })),\n ]);\n } finally {\n pendingSources.forEach(source => source.clear());\n completed.forEach(processor => processor.clear());\n pendingSources.clear();\n queued.clear();\n completed.clear();\n emissions.clear();\n errors.length = 0;\n reportingFailures = reportFailures;\n lock(false);\n phase = 'idle';\n }\n };\n\n const run = () => {\n settle();\n const result = flush();\n const failures = reportingFailures;\n reportingFailures = [];\n if (failures.length) throw new AggregateError(failures, 'Projection error reporter failed.');\n return result;\n };\n\n const batch = <T>(callback: () => T, options?: BatchOptions): T => {\n assertIdle();\n const outer = depth === 0;\n if (outer)\n activeBatch = Object.freeze({\n id: ++batchSequence,\n ...(options?.cause === undefined ? {} : { cause: options.cause }),\n });\n depth++;\n let failed = false;\n try {\n const value = callback();\n assertSynchronous(value);\n return value;\n } catch (error) {\n failed = true;\n throw error;\n } finally {\n depth--;\n if (!depth) {\n try {\n if (failed) {\n try {\n run();\n } catch {\n /* The original application error retains priority. */\n }\n } else run();\n } finally {\n activeBatch = undefined;\n }\n }\n }\n };\n\n const releaseProducer = (producer: ProducerRecord) => {\n assertIdle();\n if (producer.outputs.some(output => output.hasConsumers()))\n throw new Error('Projection producer is still used by another processor.');\n producer.disposed = true;\n if (producer.kind === 'processor') {\n producer.dependencies.forEach(output => output.detachConsumer(producer));\n processors.delete(producer);\n queued.delete(producer);\n completed.delete(producer);\n } else {\n sources.delete(producer);\n pendingSources.delete(producer);\n }\n const failures: unknown[] = [];\n try {\n producer.release();\n } catch (error) {\n failures.push(error);\n }\n try {\n producer.clear();\n } catch (error) {\n failures.push(error);\n }\n producer.outputs.forEach(output => emissions.delete(output));\n if (failures.length) throw failures[0];\n };\n\n return {\n assertActive,\n assertIdle,\n capture,\n settle,\n flush,\n run,\n registerGuard(guard: (locked: boolean) => void): Unsubscribe {\n assertActive();\n guards.add(guard);\n let registered = true;\n return () => {\n if (!registered) return;\n registered = false;\n guards.delete(guard);\n };\n },\n get active() {\n return !disposed;\n },\n addSource(source: SourceBoundaryRecord) {\n assertIdle();\n sources.add(source);\n },\n addProcessor(processor: ProcessorRecord) {\n assertIdle();\n processors.add(processor);\n processor.dependencies.forEach(output => output.attachConsumer(processor));\n },\n releaseProducer,\n order: () => sequence++,\n initialize<T>(callback: () => T): T {\n assertIdle();\n phase = 'compute';\n lock(true);\n try {\n return callback();\n } finally {\n lock(false);\n phase = 'idle';\n }\n },\n batch,\n batchContext: () => activeBatch,\n dispose() {\n if (disposed) return;\n assertIdle();\n disposed = true;\n const failures: unknown[] = [];\n processors.forEach(processor => {\n processor.disposed = true;\n try {\n processor.release();\n } catch (error) {\n failures.push(error);\n }\n });\n sources.forEach(source => {\n source.disposed = true;\n try {\n source.release();\n } catch (error) {\n failures.push(error);\n }\n });\n processors.clear();\n sources.clear();\n pendingSources.clear();\n heap.length = 0;\n queued.clear();\n completed.clear();\n emissions.clear();\n guards.clear();\n errors.length = 0;\n reportingFailures = [];\n if (failures.length) throw new AggregateError(failures, 'Projection cleanup failed.');\n },\n };\n};\n\nexport type Scheduler = ReturnType<typeof createScheduler>;\n\nexport const assertSynchronous = (value: unknown): void => {\n if (\n value != null &&\n (typeof value === 'object' || typeof value === 'function') &&\n 'then' in value &&\n typeof value.then === 'function'\n )\n throw new TypeError('Projection callbacks must be synchronous.');\n};\n\nexport const assertScope = (active: () => boolean) => {\n if (!active()) throw new Error('Projection reader or writer is no longer active.');\n};\n"],"mappings":"AAkDA,MAAa,UAAU;CACrB,aAAa,KAAmC,SAAS,MAAM;CAG/D,WAAW,KAAiC,SAAS,MAAM;CAG3D,SAAS,QAAkC;CAG3C,MAAM;EACJ,iBAAiB;EAGjB,gBAAgB;EAGhB,gBAAgB,UAAkB;EAGnC;CACD,UAAU;EACR,YAAY;EAGZ,iBAAiB;EAGlB;CACD,SAAS;EACP,YAAY,UAAkB;EAM9B,kBAAkB;EAGlB,oBAAoB;EAGpB,wBAAwB;EAGxB,uBAAuB;EAGxB;CACD,QAAQ;EACN,aAAa;EAGb,eAAe;EAGhB;CACD,YAAY;EACV,kBAAkB;EAGlB,uBAAuB;EAGxB;CACD,iBAAiB;EACf,YAAY;EAGZ,QAAQ,UAAkB;EAM3B;CACD,gBAAgB;EACd,cAAc;EAGd,aAAa,SAAS,MAAM;EAG5B,mBAAmB;EAGpB;CACD,cAAc;EACZ,eAAe;EAGf,eAAe;EAGf,oBAAoB;EAGrB;CACF;;;ACJD,MAAM,8BAAc,IAAI,SAAgC;AAExD,MAAM,aAAgB,UAA8B,WAAkC;CACpF,MAAM,SAAS,OAAO,OAAO,EAAE,CAAC;AAChC,aAAY,IAAI,QAAQ,OAAO,OAAO;EAAE;EAAU;EAAQ,CAAC,CAAC;AAC5D,QAAO;;AAGT,MAAa,iBAAiB,eAAmD;CAC/E,MAAM,MAAM,YAAY,IAAI,WAAW;AACvC,KAAI,CAAC,IAAK,OAAM,IAAI,UAAU,iCAAiC;AAC/D,QAAO;;AAGT,MAAa,cAAc,eACzB,cAAc,WAAW,CAAC;AAE5B,MAAa,gBAAgB,UAC3B,UAAU,QAAQ,OAAO,UAAU,YAAY,YAAY,IAAI,MAAM;AAEvE,MAAa,kBACX,aACA,UACS;CACT,MAAM,YAAY,IAAI,IAAI,YAAY,IAAI,WAAW,CAAC;AACtD,MAAK,MAAM,YAAY,WAAW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