@expressive/mvc 0.88.0 → 0.89.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.
- package/README.md +18 -18
- package/dist/component.d.ts +11 -19
- package/dist/component.js +5 -51
- package/dist/component.js.map +1 -1
- package/dist/context.d.ts +27 -27
- package/dist/context.js +18 -18
- package/dist/context.js.map +1 -1
- package/dist/field/def.d.ts +3 -3
- package/dist/field/def.js +6 -6
- package/dist/field/def.js.map +1 -1
- package/dist/field/get.d.ts +16 -16
- package/dist/field/get.js +3 -3
- package/dist/field/get.js.map +1 -1
- package/dist/field/has.d.ts +8 -8
- package/dist/field/has.js +3 -3
- package/dist/field/has.js.map +1 -1
- package/dist/field/map.d.ts +2 -2
- package/dist/field/map.js +2 -2
- package/dist/field/map.js.map +1 -1
- package/dist/field/ref.d.ts +8 -8
- package/dist/field/ref.js +3 -3
- package/dist/field/ref.js.map +1 -1
- package/dist/field/set.js.map +1 -1
- package/dist/hot.d.ts +4 -4
- package/dist/hot.js +7 -11
- package/dist/hot.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/jsx-runtime.d.ts +2 -2
- package/dist/jsx-runtime.js +1 -3
- package/dist/jsx-runtime.js.map +1 -1
- package/dist/observable.d.ts +7 -4
- package/dist/observable.js +94 -27
- package/dist/observable.js.map +1 -1
- package/dist/state.d.ts +110 -96
- package/dist/state.js +53 -39
- package/dist/state.js.map +1 -1
- package/package.json +1 -1
package/dist/state.js
CHANGED
|
@@ -8,7 +8,7 @@ const define = Object.defineProperty;
|
|
|
8
8
|
const ID = /* @__PURE__ */ new WeakMap();
|
|
9
9
|
/** Internal state assigned to states. */
|
|
10
10
|
const STORE = /* @__PURE__ */ new WeakMap();
|
|
11
|
-
/**
|
|
11
|
+
/** Models under construction - added on `new`, removed when activated or released.
|
|
12
12
|
* Also carries work to run at the deadline, which `def` uses to bound its registry. */
|
|
13
13
|
const PENDING = /* @__PURE__ */ new Set();
|
|
14
14
|
const SETUP = /* @__PURE__ */ new WeakMap();
|
|
@@ -28,25 +28,25 @@ const REFRESH = Symbol.for("@expressive/mvc.refresh");
|
|
|
28
28
|
const STALE = /* @__PURE__ */ new WeakSet();
|
|
29
29
|
/** Whether the deadline which drains `PENDING` is already queued for this tick. */
|
|
30
30
|
let QUEUED = false;
|
|
31
|
-
/** Global list each loaded copy of this module adds its `
|
|
31
|
+
/** Global list each loaded copy of this module adds its `Model` to, on first construction. */
|
|
32
32
|
const COPIES = Symbol.for("@expressive/mvc");
|
|
33
33
|
let ANNOUNCED = false;
|
|
34
|
-
/** Adopters for managed properties which have held a child
|
|
34
|
+
/** Adopters for managed properties which have held a child Model. */
|
|
35
35
|
const ADOPT = /* @__PURE__ */ new WeakMap();
|
|
36
36
|
const CHILDREN = /* @__PURE__ */ new WeakMap();
|
|
37
37
|
const OWNS = /* @__PURE__ */ new WeakMap();
|
|
38
38
|
const OWNED = /* @__PURE__ */ new WeakMap();
|
|
39
|
-
var
|
|
39
|
+
var Model = class Model {
|
|
40
40
|
/**
|
|
41
41
|
* Whether an instance activated with no enclosing context registers itself
|
|
42
42
|
* to the process-global root, where `get()` can resolve it from anywhere.
|
|
43
43
|
* `false` (the default) keeps a context-less instance fully functional but
|
|
44
44
|
* private - not injectable, though it can still read declared globals. Opt in
|
|
45
|
-
* with `static readonly global = true`; a resolver (see {@link
|
|
45
|
+
* with `static readonly global = true`; a resolver (see {@link Model.Global})
|
|
46
46
|
* makes the choice conditional. It must be declared per class - a subclass
|
|
47
47
|
* that would inherit a global without its own declaration throws on
|
|
48
|
-
* activation, so an accidental global (a forgotten
|
|
49
|
-
* global) cannot leak into the shared root.
|
|
48
|
+
* activation, so an accidental global (a forgotten `<Component for>`, an
|
|
49
|
+
* extended global) cannot leak into the shared root.
|
|
50
50
|
*/
|
|
51
51
|
static global = false;
|
|
52
52
|
constructor(...args) {
|
|
@@ -56,8 +56,8 @@ var State = class State {
|
|
|
56
56
|
get(arg1, arg2, arg3) {
|
|
57
57
|
const self = this.is;
|
|
58
58
|
if (arg1 === void 0) return values(self);
|
|
59
|
-
if (arg1 ===
|
|
60
|
-
if (
|
|
59
|
+
if (arg1 === Model) return typeof arg2 == "function" ? owned(self, arg2) : observed(this, arg1, owner(self, arg2));
|
|
60
|
+
if (Model.is(arg1)) return observed(this, arg1, Context.get(self).get(arg1, arg2, arg3, self));
|
|
61
61
|
if (typeof arg1 == "function") return watch(self, unbind(arg1));
|
|
62
62
|
if (typeof arg2 == "function") return callback(self, arg2, arg1);
|
|
63
63
|
if (arg1 === null) return observer(self) === null;
|
|
@@ -75,7 +75,7 @@ var State = class State {
|
|
|
75
75
|
return queued(self);
|
|
76
76
|
}
|
|
77
77
|
/**
|
|
78
|
-
* Iterate over managed properties in this instance of
|
|
78
|
+
* Iterate over managed properties in this instance of Model.
|
|
79
79
|
* Yeilds the key and current value for each property.
|
|
80
80
|
*/
|
|
81
81
|
[Symbol.iterator]() {
|
|
@@ -110,14 +110,14 @@ var State = class State {
|
|
|
110
110
|
return () => setup.delete(handler);
|
|
111
111
|
}
|
|
112
112
|
};
|
|
113
|
-
define(
|
|
113
|
+
define(Model.prototype, "toString", { value() {
|
|
114
114
|
return ID.get(this.is);
|
|
115
115
|
} });
|
|
116
|
-
define(
|
|
116
|
+
define(Model, "toString", { value() {
|
|
117
117
|
return this.name;
|
|
118
118
|
} });
|
|
119
119
|
function observed(from, key, value) {
|
|
120
|
-
return value instanceof
|
|
120
|
+
return value instanceof Model ? touch(from, key, value) : value;
|
|
121
121
|
}
|
|
122
122
|
/** Register a user OnEvent callback, preserving `this` and `source`. */
|
|
123
123
|
function callback(self, cb, select) {
|
|
@@ -129,10 +129,10 @@ function callback(self, cb, select) {
|
|
|
129
129
|
**/
|
|
130
130
|
function init(state, ...args) {
|
|
131
131
|
const T = state.constructor;
|
|
132
|
-
if (T ===
|
|
132
|
+
if (T === Model) throw new Error("Cannot create base Model.");
|
|
133
133
|
if (!ANNOUNCED) {
|
|
134
134
|
ANNOUNCED = true;
|
|
135
|
-
(globalThis[COPIES] ||= []).push(
|
|
135
|
+
(globalThis[COPIES] ||= []).push(Model);
|
|
136
136
|
}
|
|
137
137
|
const { before, after } = bootstrap(T);
|
|
138
138
|
ID.set(state, `${T}-${uid()}`);
|
|
@@ -151,7 +151,7 @@ function init(state, ...args) {
|
|
|
151
151
|
const g = type.global;
|
|
152
152
|
if (!(typeof g == "function" ? g(state) : g)) return;
|
|
153
153
|
if (!Object.prototype.hasOwnProperty.call(type, "global")) throw new Error(`${state} would register as a global by inheritance alone - re-declare \`static global\` on ${type.name} (\`true\` to keep it, \`false\` to opt out).`);
|
|
154
|
-
for (let T = type; T !==
|
|
154
|
+
for (let T = type; T !== Model; T = Object.getPrototypeOf(T)) {
|
|
155
155
|
const found = Context.root.get(T, false);
|
|
156
156
|
if (found && (T === type || found.constructor === T)) throw new Error(`Cannot register ${state} as a global - ${found} already exists in root. Destroy the existing instance first, or provide additional ones via explicit context.`);
|
|
157
157
|
}
|
|
@@ -216,7 +216,7 @@ function unmanaged(state, key, value) {
|
|
|
216
216
|
/**
|
|
217
217
|
* Apply instructions and inherited event listeners. Ensure class metadata is ready.
|
|
218
218
|
*
|
|
219
|
-
* @param T -
|
|
219
|
+
* @param T - Model class to bootstrap.
|
|
220
220
|
* @return Array of init functions to run on instance, in order of class hierarchy.
|
|
221
221
|
*/
|
|
222
222
|
function bootstrap(T) {
|
|
@@ -228,7 +228,7 @@ function bootstrap(T) {
|
|
|
228
228
|
let getters = /* @__PURE__ */ new Map();
|
|
229
229
|
while (true) {
|
|
230
230
|
chain.unshift(T);
|
|
231
|
-
if (T ===
|
|
231
|
+
if (T === Model) break;
|
|
232
232
|
T = Object.getPrototypeOf(T);
|
|
233
233
|
}
|
|
234
234
|
for (const type of chain) {
|
|
@@ -237,7 +237,7 @@ function bootstrap(T) {
|
|
|
237
237
|
if (handler.ready) after.add(handler.ready);
|
|
238
238
|
if (handler.type) onType.add(handler.type);
|
|
239
239
|
}
|
|
240
|
-
if (type ===
|
|
240
|
+
if (type === Model) continue;
|
|
241
241
|
if (METHODS.has(type)) {
|
|
242
242
|
keys = METHODS.get(type);
|
|
243
243
|
getters = GETTERS.get(type);
|
|
@@ -301,7 +301,7 @@ function classify(type, keys, getters) {
|
|
|
301
301
|
}
|
|
302
302
|
/** Handlers of one stage along the class chain - ancestor first, in registration order, each once. */
|
|
303
303
|
function stages(T, key) {
|
|
304
|
-
const found = T ===
|
|
304
|
+
const found = T === Model ? /* @__PURE__ */ new Set() : stages(Object.getPrototypeOf(T), key);
|
|
305
305
|
for (const handler of SETUP.get(T) || []) if (handler[key]) found.add(handler[key]);
|
|
306
306
|
return found;
|
|
307
307
|
}
|
|
@@ -317,6 +317,8 @@ function compute(getter, key) {
|
|
|
317
317
|
const store = STORE.get(this);
|
|
318
318
|
let reset;
|
|
319
319
|
let isAsync;
|
|
320
|
+
let suspended = false;
|
|
321
|
+
let waiting;
|
|
320
322
|
let proxy;
|
|
321
323
|
const connect = () => {
|
|
322
324
|
reset = watch(this, (current) => {
|
|
@@ -332,15 +334,27 @@ function compute(getter, key) {
|
|
|
332
334
|
};
|
|
333
335
|
const run = (initial) => {
|
|
334
336
|
let next;
|
|
337
|
+
waiting = void 0;
|
|
335
338
|
try {
|
|
336
339
|
next = latest(getter).call(proxy, proxy);
|
|
337
340
|
} catch (err) {
|
|
338
|
-
if (
|
|
341
|
+
if (err instanceof Promise) {
|
|
342
|
+
if (initial) {
|
|
343
|
+
suspended = true;
|
|
344
|
+
throw err;
|
|
345
|
+
}
|
|
346
|
+
const retry = () => {
|
|
347
|
+
if (waiting === err && observer(this) !== null) run();
|
|
348
|
+
};
|
|
349
|
+
waiting = err;
|
|
350
|
+
err.then(retry, retry);
|
|
351
|
+
if (suspended) return;
|
|
352
|
+
} else if (initial) {
|
|
339
353
|
console.warn(`An exception was thrown while initializing ${this}.${key}.`);
|
|
340
354
|
throw err;
|
|
341
|
-
}
|
|
342
|
-
if (!(err instanceof Promise)) report("getter", this, err, key);
|
|
355
|
+
} else report("getter", this, err, key);
|
|
343
356
|
}
|
|
357
|
+
suspended = false;
|
|
344
358
|
update(this, key, next, !isAsync);
|
|
345
359
|
};
|
|
346
360
|
apply(this, key, {
|
|
@@ -353,7 +367,7 @@ function compute(getter, key) {
|
|
|
353
367
|
isAsync = true;
|
|
354
368
|
}
|
|
355
369
|
if (STALE.delete(run)) run();
|
|
356
|
-
return access(this, key,
|
|
370
|
+
return access(this, key, suspended);
|
|
357
371
|
}
|
|
358
372
|
}, true);
|
|
359
373
|
}
|
|
@@ -362,7 +376,7 @@ function compute(getter, key) {
|
|
|
362
376
|
* If the property already is managed, config will only accept value.
|
|
363
377
|
* If the property does not exist, it will be created and made reactive.
|
|
364
378
|
*
|
|
365
|
-
* @param state -
|
|
379
|
+
* @param state - Model to apply property to.
|
|
366
380
|
* @param key - Property to define or update.
|
|
367
381
|
* @param config - Descriptor config with value, get, set, enumerable, and/or destroy.
|
|
368
382
|
* @param silent - If an update does occur, listeners will not be refreshed automatically.
|
|
@@ -420,7 +434,7 @@ function child(state) {
|
|
|
420
434
|
listener(state, reset, null);
|
|
421
435
|
return (value) => {
|
|
422
436
|
reset();
|
|
423
|
-
if (!(value instanceof
|
|
437
|
+
if (!(value instanceof Model)) return;
|
|
424
438
|
if (parent(value, state)) {
|
|
425
439
|
const remove = join(state, value);
|
|
426
440
|
cleanup = () => {
|
|
@@ -435,18 +449,18 @@ function child(state) {
|
|
|
435
449
|
};
|
|
436
450
|
}
|
|
437
451
|
/**
|
|
438
|
-
* Pending
|
|
452
|
+
* Pending Models constructed after this one - in a parent, the products of
|
|
439
453
|
* its own initializers, until the last one it kept.
|
|
440
454
|
*/
|
|
441
455
|
function trailing(state) {
|
|
442
456
|
const rest = [];
|
|
443
457
|
let seen = false;
|
|
444
458
|
for (const item of PENDING) if (!seen) seen = item === state;
|
|
445
|
-
else if (item instanceof
|
|
459
|
+
else if (item instanceof Model) rest.push(item);
|
|
446
460
|
return rest;
|
|
447
461
|
}
|
|
448
462
|
/**
|
|
449
|
-
* Report
|
|
463
|
+
* Report Models adopted by a parent - those already held, then each one
|
|
450
464
|
* claimed later. Returns a callback to stop watching.
|
|
451
465
|
*/
|
|
452
466
|
function children(state, callback) {
|
|
@@ -454,7 +468,7 @@ function children(state, callback) {
|
|
|
454
468
|
const keys = ADOPT.get(state);
|
|
455
469
|
if (keys) for (const key of keys.keys()) {
|
|
456
470
|
const value = store[key];
|
|
457
|
-
if (value instanceof
|
|
471
|
+
if (value instanceof Model) callback(value);
|
|
458
472
|
}
|
|
459
473
|
let set = CHILDREN.get(state);
|
|
460
474
|
if (!set) CHILDREN.set(state, set = /* @__PURE__ */ new Set());
|
|
@@ -467,8 +481,8 @@ function owner(state, required) {
|
|
|
467
481
|
throw new Error(`${state} has no owner.`);
|
|
468
482
|
}
|
|
469
483
|
/**
|
|
470
|
-
* Report
|
|
471
|
-
* activates. A function returned by `callback` runs when that
|
|
484
|
+
* Report Models owned by this one - those active now, then each one as it
|
|
485
|
+
* activates. A function returned by `callback` runs when that Model is destroyed.
|
|
472
486
|
*/
|
|
473
487
|
function owned(state, callback) {
|
|
474
488
|
function each(child) {
|
|
@@ -548,7 +562,7 @@ function assign(state, data, silent) {
|
|
|
548
562
|
*/
|
|
549
563
|
function update(state, key, value, silent, own) {
|
|
550
564
|
const store = STORE.get(state);
|
|
551
|
-
if (value instanceof
|
|
565
|
+
if (value instanceof Model) value = value.is;
|
|
552
566
|
if (observer(state) === null) {
|
|
553
567
|
if (!silent) report("dead", state, /* @__PURE__ */ new Error(`Tried to update ${state}.${String(key)} but state is destroyed.`), String(key));
|
|
554
568
|
store[key] = value;
|
|
@@ -567,7 +581,7 @@ function update(state, key, value, silent, own) {
|
|
|
567
581
|
* so does a handler's throw.
|
|
568
582
|
*/
|
|
569
583
|
function report(kind, owner, error, key) {
|
|
570
|
-
const state = owner instanceof
|
|
584
|
+
const state = owner instanceof Model ? owner : owner && PARENT.get(owner);
|
|
571
585
|
if (!state) return REPORT.error(error);
|
|
572
586
|
try {
|
|
573
587
|
for (const handler of [...stages(state.constructor, "catch")].reverse()) if ((error = handler.call(state, error, kind, key)) === void 0) return;
|
|
@@ -580,19 +594,19 @@ function report(kind, owner, error, key) {
|
|
|
580
594
|
REPORT.as = report;
|
|
581
595
|
/**
|
|
582
596
|
* Hand a value stored by an owning writer to that property's adopter,
|
|
583
|
-
* creating one the first time a
|
|
584
|
-
* held a
|
|
597
|
+
* creating one the first time a Model is stored there. A property which has
|
|
598
|
+
* held a Model keeps its adopter, so a later non-Model value releases the
|
|
585
599
|
* previous child.
|
|
586
600
|
*/
|
|
587
601
|
function adopt(state, key, value) {
|
|
588
602
|
let keys = ADOPT.get(state);
|
|
589
603
|
if (!keys) {
|
|
590
|
-
if (!(value instanceof
|
|
604
|
+
if (!(value instanceof Model)) return;
|
|
591
605
|
ADOPT.set(state, keys = /* @__PURE__ */ new Map());
|
|
592
606
|
}
|
|
593
607
|
let claim = keys.get(key);
|
|
594
608
|
if (!claim) {
|
|
595
|
-
if (!(value instanceof
|
|
609
|
+
if (!(value instanceof Model)) return;
|
|
596
610
|
keys.set(key, claim = child(state));
|
|
597
611
|
}
|
|
598
612
|
claim(value);
|
|
@@ -617,5 +631,5 @@ function parent(child, value) {
|
|
|
617
631
|
}
|
|
618
632
|
|
|
619
633
|
//#endregion
|
|
620
|
-
export { GETTERS, LATEST, METHODS, PENDING, SETUP, STORE,
|
|
634
|
+
export { GETTERS, LATEST, METHODS, Model, PENDING, SETUP, STORE, UNBIND, access, adopt, apply, children, classify, compute, event, owned, parent, trailing, uid, unbind, update };
|
|
621
635
|
//# sourceMappingURL=state.js.map
|
package/dist/state.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"state.js","names":[],"sources":["../src/state.ts"],"sourcesContent":["import { Context, host, join } from './context';\nimport { REPORT } from './dispatch';\nimport {\n capture,\n event,\n listener,\n Observer,\n observer,\n queued,\n touch,\n watch\n} from './observable';\n\nconst define = Object.defineProperty;\n\n/** Register for all active states via string identifiers (usually unique). */\nconst ID = new WeakMap<State, string>();\n\n/** Internal state assigned to states. */\nconst STORE = new WeakMap<State, Record<string | number | symbol, unknown>>();\n\n/** States under construction - added on `new`, removed when activated or released.\n * Also carries work to run at the deadline, which `def` uses to bound its registry. */\nconst PENDING = new Set<State | (() => void)>();\n\n/** External lifecycle listeners for any given State class. */\ntype Handler = State.On<any>;\n\nconst SETUP = new WeakMap<State.Extends, Set<Handler>>();\n\n/** Parent-child relationships. */\nconst PARENT = new WeakMap<object, State | null>();\n\n/** Reference bound instance methods, or their getter, to real one. */\nconst UNBIND = new WeakMap<any, any>();\n\n/** List of methods defined by a given type. */\nconst METHODS = new WeakMap<Function, Map<string, (value: any) => void>>();\n\n/** List of reactive getters defined by a given type. */\nconst GETTERS = new WeakMap<Function, Map<string, () => unknown>>();\n\n/** Replacement for a getter captured by live computed properties, for hot patching. */\nconst LATEST = new WeakMap<Function, Function>();\n\n/** Event every observer treats as watched, forcing a refresh after a hot patch. */\nconst REFRESH = Symbol.for('@expressive/mvc.refresh');\n\n/** Stale flags for compute closures awaiting refresh on next access. */\nconst STALE = new WeakSet<() => void>();\n\n/** Whether the deadline which drains `PENDING` is already queued for this tick. */\nlet QUEUED = false;\n\n/** Global list each loaded copy of this module adds its `State` to, on first construction. */\nconst COPIES = Symbol.for('@expressive/mvc');\n\nlet ANNOUNCED = false;\n\n/** Adopters for managed properties which have held a child State. */\nconst ADOPT = new WeakMap<State, Map<unknown, (value: unknown) => void>>();\nconst CHILDREN = new WeakMap<State, Set<(child: State) => void>>();\nconst OWNS = new WeakMap<State, Set<State>>();\nconst OWNED = new WeakMap<State, Set<(child: State) => void>>();\n\ndeclare namespace State {\n /** Any type of State, using own class constructor as its identifier. */\n type Extends<T extends State = State> = (abstract new (...args: any[]) => T) &\n typeof State;\n\n /** A State constructor which may be instanciated. */\n type Type<T extends State = State> = (new (...args: State.Args<T>) => T) &\n Omit<typeof State, never>;\n\n /** State constructor arguments */\n type Args<T extends State = any> = (Args<T> | Init<T> | Assign<T> | void)[];\n\n /**\n * Value of `static global`. A boolean opts a State in or out of the\n * process-global root; a resolver decides at activation, receiving the\n * instance and returning whether it registers - use it to make the choice\n * conditional (e.g. per environment). A bare literal (`= true` / `= false`)\n * seals the choice for subclasses; widen a subclass's `static global` type to\n * `State.Global` to permit a resolver or a later override.\n */\n type Global<T extends State = any> = boolean | ((self: T) => boolean);\n\n /**\n * State constructor callback - runs during activation, in argument order,\n * before the `new()` lifecycle hook (so it may configure state `new()`\n * will observe). Returned function will run when state is destroyed.\n */\n type Init<T extends State = State> = (\n this: T,\n thisArg: T\n ) => Promise<void> | (() => void) | Args<T> | Assign<T> | void;\n\n /** Lifecycle handlers for `State.on`, keyed by when they run. */\n interface On<T extends State = State> {\n /**\n * Per-class setup, run once when the class is first bootstrapped - before\n * its members are classified and bound. Receives the class, so a handler\n * may inspect or reshape the prototype first. A handler registered on a\n * base class runs for each subclass too.\n */\n type?(type: State.Extends<T>): void;\n\n /**\n * Per-instance, once constructed - before own values are observed and\n * before constructor args and `new()`. May return a cleanup, constructor\n * args, or an assign overlay.\n */\n setup?(this: T, self: T): void | (() => void) | Promise<void> | Args<T> | Assign<T>;\n\n /**\n * Per-instance, once ready - after own values are observed, constructor\n * args applied and `new()` has run. May return a cleanup function.\n */\n ready?(this: T, self: T): void | (() => void);\n\n /**\n * Runs each time a method is bound to an instance - first access,\n * reassignment, and the rebind after a hot patch - with the key, the bound\n * function and the instance. Tooling and development use.\n */\n method?(this: T, key: string, fn: Function, self: T): void;\n\n /**\n * Receives what an effect, refreshing getter or async initializer of this State\n * or a subclass threw, a destroyed write, or an instance never activated - with\n * its `kind` (`effect`, `getter`, `setup`, `dead`, `unused`) and `key` where\n * one applies. Most-derived class first, last registered first, each once. Return the error\n * (or another) to pass it on; return nothing to handle it; throw to let it escape.\n * Passed off the end, a destroyed write outputs nothing, `unused` warns,\n * anything else escapes uncaught.\n */\n catch?(this: T, error: unknown, kind: 'effect' | 'getter' | 'setup' | 'dead' | 'unused', key?: string): unknown;\n }\n\n /** Object overlay to override values and methods on a state. */\n type Assign<T> = Record<string, unknown> & {\n [K in Property<T>]?: T[K] extends (...args: infer A) => infer R\n ? (this: T, ...args: A) => R\n : T[K];\n };\n\n /** Subset of `keyof T` not defined by base State. **/\n type Property<T> = Exclude<keyof T, keyof State>;\n\n /** Managed subset of Property<T> - excludes unmanaged `_` keys. **/\n type Field<T> = Exclude<Property<T>, `_${string}`>;\n\n /** Any valid key for state, including but not limited to Field<T>. */\n type Event<T = State> = Field<T> | number | symbol | (string & {});\n\n /** Any event signal dispatched to listeners, including lifecycle meta events. */\n type Signal<T = State> = Event<T> | true | false | null;\n\n /** Export/Import compatible value for a given property in a State. */\n type Export<R> = R extends State\n ? Values<R>\n : R extends { get(): infer T }\n ? T\n : R;\n\n /**\n * Values from current state of given state.\n * Differs from `Values` as values here will drill\n * into \"real\" values held by exotics like ref.Object.\n */\n type Values<T> = { [P in Field<T>]: Export<T[P]> };\n\n /** Object comperable to data found in T. */\n type Partial<T> = { [P in Field<T>]?: Export<T[P]> };\n\n /** Value for a property applied by a state. */\n type Value<T extends State, K extends State.Event<T>> = K extends keyof T\n ? Export<T[K]>\n : unknown;\n\n type Setter<T> = (value: T, previous: T) => T | void;\n\n /** Descriptor config for a managed property. */\n type Apply<T = any> = {\n value?: T;\n get?: ((source: State) => T) | boolean;\n set?: Setter<T> | boolean;\n enumerable?: boolean;\n // destroy?: () => void;\n };\n\n /** Descriptor config for set() overload - enforces type when key is a known field. */\n type Define<T, K> = K extends Field<T> ? Apply<T[K] | Export<T[K]>> : Apply;\n\n type OnEvent<T extends State> = (\n this: T,\n key: Signal<T>,\n source: T\n ) => void | (() => void) | null;\n\n /** Exotic value, where actual value is contained within. */\n type Ref<T = any> = {\n (next: T): void;\n current: T | null;\n };\n\n /**\n * A callback function which is subscribed to parent and updates when accessed properties change.\n *\n * @param current - Current state of this state. This is a proxy which detects properties which\n * where accessed, and thus depended upon to stay current.\n *\n * @param update - Set of properties which have changed, and events fired, since last update.\n *\n * @returns A callback function which will be called when this effect is stale.\n */\n type Effect<T> = (\n this: T,\n current: T,\n update: readonly State.Event<T>[] | undefined\n ) => EffectCallback | Promise<void> | null | void;\n\n /**\n * A callback function returned by effect. Will be called when effect is stale.\n *\n * @param update - `true` if update is pending, `false` effect has been cancelled, `null` if state is destroyed.\n */\n type EffectCallback = (update: boolean | null) => void;\n\n /**\n * A list of keys updated, or events fired, since last update.\n * This may be awaited to get full list (same array) when update is settled.\n */\n type Updated<T extends State> = readonly Event<T>[] &\n PromiseLike<readonly Event<T>[]>;\n}\n\nabstract class State {\n /**\n * Whether an instance activated with no enclosing context registers itself\n * to the process-global root, where `get()` can resolve it from anywhere.\n * `false` (the default) keeps a context-less instance fully functional but\n * private - not injectable, though it can still read declared globals. Opt in\n * with `static readonly global = true`; a resolver (see {@link State.Global})\n * makes the choice conditional. It must be declared per class - a subclass\n * that would inherit a global without its own declaration throws on\n * activation, so an accidental global (a forgotten `Provider`, an extended\n * global) cannot leak into the shared root.\n */\n static readonly global: State.Global = false;\n\n /**\n * Loopback to instance of this state. This is useful when in a subscribed context,\n * to keep write access to `this` after a destructure. You can use it to read variables silently as well.\n **/\n declare is: this;\n\n constructor(...args: State.Args) {\n define(this, 'is', { value: this });\n init(this, args, this.new);\n }\n\n /**\n * Optional lifecycle hook called during State initialization.\n * Can return a cleanup function to run when state is destroyed.\n *\n * It is recommended you protect this method.\n */\n protected new?(): void | (() => void);\n\n /**\n * Pull current values from state. Flattens all states and exotic values recursively.\n *\n * @returns Object with all values from this state.\n **/\n get(): State.Values<this>;\n\n /**\n * Run a function to run automatically when accessed values change.\n *\n * @param effect Function to run, and whenever accessed values change.\n * If effect returns a function, it will be called when a change occurs (syncronously),\n * effect is cancelled, or parent state is destroyed.\n * @returns Function to cancel listener.\n */\n get(effect: State.Effect<this>): () => void;\n\n /**\n * Get value of a property. Will fetch underlying value from exotic values like ref.Object.\n *\n * Any value which implements `get()` (with no arguments) will be treated as such.\n *\n * @param key - Property to get value of.\n * @param required - If true, will throw an error if property is not available.\n * @returns Value of property.\n */\n get<T extends State.Event<this>>(\n key: T,\n required?: boolean\n ): State.Value<this, T>;\n\n /**\n * Check if state is destroyed.\n *\n * @param status - `null` to check if state is destroyed.\n * @returns `true` if state is destroyed, `false` otherwise.\n */\n get(status: null): boolean;\n\n /**\n * Callback when state is to be destroyed.\n *\n * @param callback - Function to call when state is destroyed.\n * @returns Function to cancel listener.\n */\n get(status: null, callback: () => void): () => void;\n\n /** Fetch State of type from context. Throws if not found. */\n get<T extends State>(type: State.Type<T>, required?: true): T;\n\n /** Fetch a State from context. Undefined if not found. */\n get<T extends State>(type: State.Type<T>, required: boolean): T | undefined;\n\n /**\n * Subscribe to State becoming available in context.\n *\n * Will search both up and downstream by default.\n * Normally you can ignore this because State you expect is rarely both.\n *\n * Specify downstream if you only want to watch for State in children, which can be useful if you expect multiple of the same State in different branches of the tree.\n *\n * @param type - Type of State to watch for.\n * @param callback - Function to call when State is found. Will be called immediately if State is already available.\n * @param downstream - If true, will only watch for State in children, if false will only for parents.\n * @returns Function to cancel listener.\n */\n get<T extends State>(\n type: State.Type<T>,\n callback: Context.Expect<T>,\n downstream?: boolean\n ): () => void;\n\n // Owner overloads take `State` itself only - a subclass would otherwise match\n // them in TypeScript's subtype pass, before the `State.Type<T>` overloads.\n\n /** Owner of this State. Throws if it has none. */\n get<T extends typeof State>(\n type: T & (typeof State extends T ? unknown : never),\n required?: true\n ): State;\n\n /** Owner of this State. Undefined if it has none. */\n get<T extends typeof State>(\n type: T & (typeof State extends T ? unknown : never),\n required: boolean\n ): State | undefined;\n\n /**\n * Run a callback for each State this one owns - those owned now, then each\n * one as it activates. Callback may return a function, called when that State\n * is destroyed.\n *\n * @returns Function to stop watching.\n */\n get<T extends typeof State>(\n type: T & (typeof State extends T ? unknown : never),\n callback: (child: State) => void | (() => void),\n downstream: true\n ): () => void;\n\n get(\n arg1?: State.Effect<this> | State.Type | typeof State | string | null,\n arg2?: boolean | Context.Expect | (() => void),\n arg3?: boolean\n ) {\n const self = this.is;\n\n if (arg1 === undefined) return values(self);\n if (arg1 === State)\n return typeof arg2 == 'function'\n ? owned(self, arg2 as (child: State) => void)\n : observed(this, arg1, owner(self, arg2 as boolean));\n if (State.is(arg1))\n return observed(this, arg1, Context.get(self).get(arg1, arg2, arg3, self));\n if (typeof arg1 == 'function') return watch(self, unbind(arg1));\n if (typeof arg2 == 'function') return callback(self, arg2, arg1);\n if (arg1 === null) return observer(self) === null;\n return access(self, arg1, arg2);\n }\n\n /**\n * Get update in progress.\n *\n * @returns Promise which resolves object with updated values, `undefined` if there no update is pending.\n **/\n set(): State.Updated<this>;\n\n /**\n * Merge argument with current state, updating one or more properties at once.\n * Properties which are not managed by this state will be ignored.\n *\n * @param assign - Object with properties to update.\n * @param silent - If true, listeners will not be notified. If state is destroyed, stores the update without reporting it.\n * @returns Array of keys updated, syncronously contains keys updated immediately and may be resolved (to itself) when all updates are settled.\n */\n set(assign?: State.Assign<this>, silent?: boolean): State.Updated<this>;\n\n /**\n * Call a function when update occurs.\n *\n * Given function is called for every assignment (which changes value) or explicit `set`.\n *\n * To run logic on final value only, callback may return a function. The same\n * function for one or more events will be called only once when update is settled.\n *\n * Return `null` from callback to stop listening.\n *\n * @param callback - Function to call when update occurs.\n * @returns Function to remove listener. Will return `true` if removed, `false` if inactive already.\n */\n set(callback: State.OnEvent<this>): () => boolean;\n\n /**\n * Push an update. This will not change the value of associated property.\n *\n * Useful where a property value internally has changed, but the object is the same.\n * For example: An array has pushed a new value, or a nested property is updated.\n *\n * You can also use this to dispatch arbitrary events.\n * Symbols are recommended as non-property events, however you can use any string.\n * If doing so, be sure to avoid collisions using property names. An easy way to do this is\n * to prefix an event with \"!\" and/or use dash-case. e.g. `set(\"!event\")` or `set(\"my-event\")`.\n *\n * @param key - Property or event to dispatch.\n * @returns Promise resolves an array of keys updated.\n */\n set(key: State.Event<this>): State.Updated<this>;\n\n /**\n * Declare an end to updates. This event is final - later writes are stored but never dispatched.\n * This event can be watched for as well, to run cleanup logic and internally will remove all listeners.\n *\n * @param status - `null` to end updates.\n */\n set(status: null): void;\n\n /**\n * Register a callback for a specific property or event.\n *\n * Callback receives the key, current value, and source instance.\n *\n * @param event - Property or event to watch. If `null`, will callback on destroy.\n * @param callback - Function to call when event occurs.\n * @returns Function to remove listener.\n */\n set<K extends State.Event<this>>(\n event: K | null,\n callback: State.OnEvent<this>\n ): () => boolean;\n\n /**\n * Define or update a managed property using a descriptor config.\n * If the property already is managed, config will only accept value.\n * If the property does not exist, it will be created and made reactive.\n *\n * @param key - Property to define or update.\n * @param config - Descriptor config with value, get, set, enumerable, and/or destroy.\n * @returns Promise resolves an array of keys updated.\n */\n set<K extends State.Event<this>>(\n key: K,\n config: State.Define<this, K>\n ): State.Updated<this>;\n\n set(\n arg1?: State.OnEvent<this> | State.Assign<this> | State.Event<this> | null,\n arg2?: unknown\n ) {\n const self = this.is;\n\n if (typeof arg1 == 'function')\n return listener(self, (key) => {\n if (\n typeof key == 'string' ||\n typeof key == 'number' ||\n typeof key == 'symbol' && key !== REFRESH\n )\n return arg1.call(self, key, self);\n });\n\n if (typeof arg2 == 'function')\n return callback(self, arg2, arg1 as State.Signal);\n\n if (arg1 && typeof arg1 == 'object') assign(self, arg1, arg2 === true);\n else if (arg2) apply(self, arg1 as string, arg2);\n else event(self, arg1);\n\n return queued(self) as State.Updated<this>;\n }\n\n /**\n * Iterate over managed properties in this instance of State.\n * Yeilds the key and current value for each property.\n */\n [Symbol.iterator](): Iterator<[string, unknown]> {\n return Object.entries(STORE.get(this.is)!)[Symbol.iterator]();\n }\n\n /**\n * Create and activate a new instance of this state.\n *\n * **Important** - Unlike `new this(...)` - this method also activates state.\n *\n * @param args - arguments sent to constructor\n */\n static new<T extends State>(this: State.Type<T>, ...args: State.Args<T>): T {\n const instance = new this(...args);\n event(instance);\n return instance;\n }\n\n /**\n * Static equivalent of `x instanceof this`.\n * Determines if provided class is a subtype of this one.\n * If so, language server will make available all static\n * methods and properties of this class.\n */\n static is<T extends State.Extends>(this: T, maybe: unknown): maybe is T {\n return (\n maybe === this ||\n (typeof maybe == 'function' && maybe.prototype instanceof this)\n );\n }\n\n /**\n * Register a lifecycle handler for this State and its subclasses.\n *\n * Hooks by cadence - `type` (per-class, at bootstrap), `setup` (per-instance,\n * before values are observed), `ready` (per-instance, after `new()`), and\n * `method` (per method binding). A function alone is a `setup` handler. A\n * function returned from `setup` or `ready` runs when the instance is destroyed.\n *\n * @returns Function to remove the handler.\n */\n static on<T extends State>(\n this: State.Extends<T>,\n setup: NonNullable<State.On<T>['setup']>\n ): () => boolean;\n static on<T extends State>(\n this: State.Extends<T>,\n handler: State.On<T>\n ): () => boolean;\n static on<T extends State>(\n this: State.Extends<T>,\n handler: State.On<T> | NonNullable<State.On<T>['setup']>\n ) {\n if (typeof handler == 'function') handler = { setup: handler };\n\n let setup = SETUP.get(this);\n\n if (!setup) SETUP.set(this, (setup = new Set()));\n\n setup.add(handler);\n\n return () => setup.delete(handler);\n }\n}\n\ndefine(State.prototype, 'toString', {\n value() {\n return ID.get(this.is);\n }\n});\n\ndefine(State, 'toString', {\n value() {\n return this.name;\n }\n});\n\nfunction observed<T>(from: State, key: unknown, value: T): T {\n return value instanceof State ? touch(from, key, value) : value;\n}\n\n/** Register a user OnEvent callback, preserving `this` and `source`. */\nfunction callback<T extends State>(\n self: T,\n cb: Function,\n select?: Observer.Signal | Set<Observer.Signal>\n) {\n return listener(self, (key) => cb.call(self, key, self), select);\n}\n\n/**\n * Apply state arguemnts, run callbacks and observe properties.\n * Accumulate and handle cleanup events.\n **/\nfunction init(state: State, ...args: State.Args) {\n const T = state.constructor as State.Extends;\n\n if (T === State) throw new Error('Cannot create base State.');\n\n if (!ANNOUNCED) {\n ANNOUNCED = true;\n ((globalThis as { [COPIES]?: unknown[] })[COPIES] ||= []).push(State);\n }\n\n const { before, after } = bootstrap(T);\n\n ID.set(state, `${T}-${uid()}`);\n STORE.set(state, {});\n\n function observe() {\n for (const key in state) {\n const desc: PropertyDescriptor = Object.getOwnPropertyDescriptor(state, key) || {};\n\n if (!('value' in desc) || !desc.configurable) continue;\n\n if (key[0] == '_') unmanaged(state, key, desc.value);\n else apply(state, key, desc, true);\n }\n }\n\n function register() {\n if (Context.get(state) !== Context.root) return;\n\n const type = state.constructor as typeof State;\n const g = type.global;\n\n if (!(typeof g == 'function' ? g(state) : g)) return;\n\n if (!Object.prototype.hasOwnProperty.call(type, 'global'))\n throw new Error(\n `${state} would register as a global by inheritance alone - re-declare \\`static global\\` on ${type.name} (\\`true\\` to keep it, \\`false\\` to opt out).`\n );\n\n for (let T: State.Extends = type; T !== State; T = Object.getPrototypeOf(T)) {\n const found = Context.root.get(T, false);\n\n if (found && (T === type || found.constructor === T))\n throw new Error(\n `Cannot register ${state} as a global - ${found} already exists in root. Destroy the existing instance first, or provide additional ones via explicit context.`\n );\n }\n\n return Context.root.add(state);\n }\n\n listener(state, (key) => {\n const rest = trailing(state);\n\n PENDING.delete(state);\n\n if (key === null) return null;\n\n if (!PARENT.has(state)) parent(state, host(state) || null);\n\n const above = PARENT.get(state);\n const owns = above && (OWNS.get(above) || OWNS.set(above, new Set()).get(above)!);\n\n if (owns) listener(state, () => void owns.delete(state), null);\n\n const queue = [...before, observe, ...args, ...after, register];\n\n capture((release) => {\n listener(state, () => release(null), null);\n\n for (let i = 0; i < queue.length; i++) {\n const arg = queue[i];\n const out = typeof arg == 'function' ? arg.call(state, state) : arg;\n\n if (out instanceof Promise)\n out.catch((err) => report('setup', state, err));\n else if (Array.isArray(out)) queue.splice(i + 1, 0, ...out);\n else if (typeof out == 'function') listener(state, out, null);\n else if (typeof out == 'object') assign(state, out, true);\n }\n });\n\n if (owns) {\n owns.add(state);\n OWNED.get(above)?.forEach((cb) => cb(state));\n }\n\n let end = rest.length;\n\n while (end-- > 0 && PENDING.has(rest[end]));\n\n for (let i = 0; i < end; i++) PENDING.delete(rest[i]);\n\n return null;\n });\n\n if (!QUEUED) {\n QUEUED = true;\n\n queueMicrotask(() => {\n QUEUED = false;\n\n for (const item of PENDING)\n if (typeof item == 'function') item();\n else report('unused', item, new Error(`${item} was constructed but never activated.`));\n\n PENDING.clear();\n });\n }\n\n PENDING.add(state);\n}\n\nfunction unmanaged(state: State, key: string, value: unknown) {\n define(state, key, {\n configurable: true,\n enumerable: false,\n get: () => value,\n set: (next) => { value = next }\n });\n}\n\n/**\n * Apply instructions and inherited event listeners. Ensure class metadata is ready.\n *\n * @param T - State class to bootstrap.\n * @return Array of init functions to run on instance, in order of class hierarchy.\n */\nfunction bootstrap(T: State.Extends) {\n const chain = [] as State.Extends[];\n const before = new Set<State.Init>();\n const after = new Set<State.Init>();\n const onType = new Set<NonNullable<State.On['type']>>();\n let keys = new Map<string, (value: any) => void>();\n let getters = new Map<string, () => unknown>();\n\n while (true) {\n chain.unshift(T);\n if (T === State) break;\n T = Object.getPrototypeOf(T);\n }\n\n for (const type of chain) {\n for (const handler of SETUP.get(type) || []) {\n if (handler.setup) before.add(handler.setup);\n if (handler.ready) after.add(handler.ready);\n if (handler.type) onType.add(handler.type);\n }\n\n if (type === State) continue;\n\n if (METHODS.has(type)) {\n keys = METHODS.get(type)!;\n getters = GETTERS.get(type)!;\n continue;\n }\n\n for (const setupType of onType) setupType(type);\n\n METHODS.set(type, (keys = new Map(keys)));\n GETTERS.set(type, (getters = new Map(getters)));\n\n classify(type, keys, getters);\n }\n\n if (getters.size)\n before.add((self) => getters.forEach(compute, self));\n\n return { before, after };\n}\n\n/** Bind own configurable methods of a type and collect its reactive getters. */\nfunction classify(\n type: State.Extends,\n keys: Map<string, (value: any) => void>,\n getters: Map<string, () => unknown>\n) {\n for (const [key, desc] of Object.entries(\n Object.getOwnPropertyDescriptors(type.prototype)\n )) {\n if (key == 'constructor' || !desc.configurable) continue;\n\n const { get, set } = desc;\n\n if (key[0] == '_' && (get || set)) {\n define(type.prototype, key, {\n ...desc,\n get: get && function (this: State) { return get.call(this.is || this) },\n set: set && function (this: State, value: unknown) { set.call(this.is || this, value) }\n });\n\n continue;\n }\n\n if (typeof get == 'function') {\n if (typeof set != 'function') getters.set(key, get);\n\n continue;\n }\n\n const { value } = desc;\n\n if (typeof value !== 'function') continue;\n\n function bind(this: State, original?: Function) {\n const { is } = this;\n\n if (is.hasOwnProperty(key) && !original) return value as Function;\n\n const fn = original || value;\n const bound = fn.bind(is);\n\n UNBIND.set(bound, fn);\n define(is, key, { value: bound, writable: true, configurable: true });\n\n for (const handler of stages(is.constructor as State.Extends, 'method')) handler.call(is, key, bound, is);\n\n return bound;\n }\n\n UNBIND.set(bind, value);\n\n keys.set(key, bind);\n define(type.prototype, key, { get: bind, set: bind });\n }\n}\n\n/** Handlers of one stage along the class chain - ancestor first, in registration order, each once. */\nfunction stages<K extends 'method' | 'catch'>(T: State.Extends, key: K): Set<NonNullable<State.On[K]>> {\n const found = T === State ? new Set<NonNullable<State.On[K]>>() : stages(Object.getPrototypeOf(T), key);\n\n for (const handler of SETUP.get(T) || []) if (handler[key]) found.add(handler[key]!);\n\n return found;\n}\n\n/**\n * Install a reactive computed property on a state instance, derived from a prototype\n * getter or an arity-bearing `set` factory.\n *\n * The getter is invoked with the tracking proxy as both `this` and its first argument;\n * reads of managed properties through it create subscriptions. Result is cached and\n * emits a keyed event when stale.\n */\nfunction compute(this: State, getter: (self: any) => unknown, key: string) {\n const store = STORE.get(this)!;\n let reset: (() => void) | undefined;\n let isAsync: boolean;\n let proxy: any;\n\n const connect = () => {\n reset = watch(\n this,\n (current) => {\n proxy = current;\n\n if (!(key in store) || STALE.delete(run)) run(!reset);\n\n return (didUpdate) => {\n if (didUpdate) {\n STALE.add(run);\n event(this, key, true);\n }\n };\n },\n false\n );\n };\n\n const run = (initial?: boolean) => {\n let next: unknown;\n\n try {\n next = latest(getter).call(proxy, proxy);\n } catch (err) {\n if (initial) {\n console.warn(`An exception was thrown while initializing ${this}.${key}.`);\n throw err;\n }\n\n if (!(err instanceof Promise)) report('getter', this, err, key);\n }\n\n update(this, key, next, !isAsync);\n };\n\n apply(\n this,\n key,\n {\n enumerable: true,\n set: false,\n get: () => {\n if (!proxy) {\n if (observer(this) === null) return store[key];\n\n connect();\n isAsync = true;\n }\n\n if (STALE.delete(run)) run();\n\n return access(this, key, !proxy);\n }\n },\n true\n );\n}\n\n/**\n * Define or update a managed property using a descriptor config.\n * If the property already is managed, config will only accept value.\n * If the property does not exist, it will be created and made reactive.\n *\n * @param state - State to apply property to.\n * @param key - Property to define or update.\n * @param config - Descriptor config with value, get, set, enumerable, and/or destroy.\n * @param silent - If an update does occur, listeners will not be refreshed automatically.\n */\nfunction apply(\n state: State,\n key: string,\n config: State.Apply,\n silent?: boolean\n) {\n const desc = Object.getOwnPropertyDescriptor(state, key);\n\n if (desc && 'get' in desc) {\n if (Object.keys(config).some((k) => k != 'value'))\n throw new Error(`Property ${key} on ${state} is already defined.`);\n if ('value' in config) update(state, key, config.value, silent);\n return;\n }\n\n function set(value: unknown, silent?: boolean) {\n update(state, key, value, silent, true);\n }\n\n define(state, key, {\n configurable: true,\n enumerable: config.enumerable !== false,\n get(this: State) {\n const value =\n typeof config.get == 'function'\n ? config.get(this)\n : access(state, key, config.get);\n\n return touch(this, key, value);\n },\n set(next: any, silent?: boolean) {\n if (config.set === false)\n throw new Error(`${state}.${String(key)} is read-only.`);\n\n if (typeof config.set == 'function')\n try {\n const output = config.set(next, STORE.get(state)![key]);\n if (output !== undefined) next = output;\n } catch (err: unknown) {\n if (err === false) return;\n if (err === true) {\n set(next, true);\n return;\n }\n throw err;\n }\n\n set(next, silent);\n }\n });\n\n if ('value' in config) set(config.value, silent);\n}\n\nfunction provides(ctx: Context, value: State) {\n while (ctx = ctx.parent!) {\n const entries = ctx.provide.get(value.constructor as State.Extends);\n if (entries) for (const [state] of entries) if (state === value) return true;\n }\n}\n\nfunction child(state: State) {\n let cleanup: (() => void) | undefined;\n const ctx = Context.get(state);\n\n function reset() {\n if (cleanup) cleanup();\n cleanup = undefined;\n }\n\n listener(state, reset, null);\n\n return (value: unknown) => {\n reset();\n\n if (!(value instanceof State)) return;\n\n if (parent(value, state)) {\n const remove = join(state, value);\n cleanup = () => {\n cancel();\n remove();\n event(value, null);\n };\n const cancel = listener(state, cleanup, null);\n } else if (!provides(ctx, value)) {\n cleanup = join(state, value);\n }\n\n event(value);\n\n CHILDREN.get(state)?.forEach((cb) => cb(value));\n };\n}\n\n/**\n * Pending States constructed after this one - in a parent, the products of\n * its own initializers, until the last one it kept.\n */\nfunction trailing(state: State) {\n const rest: State[] = [];\n let seen = false;\n\n for (const item of PENDING)\n if (!seen) seen = item === state;\n else if (item instanceof State) rest.push(item);\n\n return rest;\n}\n\n/**\n * Report States adopted by a parent - those already held, then each one\n * claimed later. Returns a callback to stop watching.\n */\nfunction children(state: State, callback: (child: State) => void) {\n const store = STORE.get(state)!;\n const keys = ADOPT.get(state);\n\n if (keys)\n for (const key of keys.keys()) {\n const value = store[key as string];\n if (value instanceof State) callback(value);\n }\n\n let set = CHILDREN.get(state);\n\n if (!set) CHILDREN.set(state, (set = new Set()));\n\n set.add(callback);\n\n return () => set!.delete(callback);\n}\n\nfunction owner(state: State, required?: boolean) {\n const found = PARENT.get(state);\n\n if (found || required === false) return found || undefined;\n\n throw new Error(`${state} has no owner.`);\n}\n\n/**\n * Report States owned by this one - those active now, then each one as it\n * activates. A function returned by `callback` runs when that State is destroyed.\n */\nfunction owned(state: State, callback: (child: State) => void | (() => void)) {\n function each(child: State) {\n const done = callback(child);\n if (typeof done == 'function') listener(child, () => void done(), null);\n }\n\n OWNS.get(state)?.forEach(each);\n\n let set = OWNED.get(state);\n\n if (!set) OWNED.set(state, (set = new Set()));\n\n set.add(each);\n\n return () => void set!.delete(each);\n}\n\n/** Currently accumulating export. Stores real values of placeholder properties such as ref() or child states. */\nlet EXPORT: Map<any, any> | undefined;\n\nfunction values<T extends State>(state: T): State.Values<T> {\n const values = {} as any;\n let notRecursive;\n\n if (!EXPORT) {\n notRecursive = true;\n EXPORT = new Map();\n }\n\n EXPORT.set(state, values);\n\n for (let [key, value] of state) {\n if (EXPORT.has(value)) value = EXPORT.get(value);\n else if (\n value &&\n typeof value == 'object' &&\n 'get' in value &&\n typeof value.get === 'function'\n )\n value = value.get();\n\n values[key] = value;\n }\n\n if (notRecursive) EXPORT = undefined;\n\n return Object.freeze(values);\n}\n\nfunction access(state: State, property: string, required?: boolean) {\n const store = STORE.get(state)!;\n\n if (property in store || required === false) {\n const value = store[property];\n\n if (value !== undefined || !required) return value;\n }\n\n if (METHODS.get(state.constructor)!.has(property))\n return unbind((state as any)[property]);\n\n if (observer(state) === null) return undefined;\n\n const error = new Error(`${state}.${property} is not yet available.`);\n const promise = new Promise<any>((resolve, reject) => {\n listener(state, (key) => {\n if (key === property) {\n resolve(store[key]);\n return null;\n }\n\n if (key === null) {\n reject(new Error(`${state} is destroyed.`));\n }\n });\n });\n\n throw Object.assign(promise, {\n toString: () => String(error),\n name: 'Suspense',\n message: error.message,\n stack: error.stack\n });\n}\n\nfunction assign(state: State, data: State.Assign<State>, silent?: boolean) {\n if (!silent && observer(state) !== null) event(state);\n\n const methods = METHODS.get(state.constructor)!;\n const getters = GETTERS.get(state.constructor);\n\n for (const key in data) {\n const bind = methods.get(key);\n\n if (bind) bind.call(state, data[key]);\n else if (getters?.has(key)) continue;\n else if (key in state && key !== 'is') {\n const desc: PropertyDescriptor = Object.getOwnPropertyDescriptor(state, key) || {};\n const set = desc.set as (value: any, silent?: boolean) => void;\n\n if (set) {\n set.call(state, data[key], silent);\n } else {\n Reflect.set(state, key, data[key]);\n }\n }\n }\n}\n\n/**\n * Update a property on a state instance and notify listeners.\n *\n * This is used internally to update properties, but can also be used to update properties which are not managed by state, or to update values without triggering setters.\n *\n * A destroyed state stores the write without dispatch, reports it unless `silent`, and returns `false`.\n */\nfunction update<T>(\n state: State,\n key: State.Event<T>,\n value: T,\n silent?: boolean,\n own?: boolean\n) {\n const store = STORE.get(state)!;\n\n if (value instanceof State) value = value.is as T;\n\n if (observer(state) === null) {\n if (!silent) report('dead', state, new Error(`Tried to update ${state}.${String(key)} but state is destroyed.`), String(key));\n store[key] = value;\n return false;\n }\n\n if (key in store && value === store[key]) return false;\n\n store[key] = value;\n\n if (!silent) event(state, key);\n\n if (own) adopt(state, key, value);\n\n return true;\n}\n\n/**\n * Pass an error along `catch` handlers - most-derived class first, last registered\n * first, one on several classes once at the outermost - until one returns nothing. Passed off\n * the end, a destroyed write outputs nothing, `unused` warns, anything else escapes uncaught;\n * so does a handler's throw.\n */\nfunction report(kind: Parameters<NonNullable<State.On['catch']>>[1], owner: object | undefined, error: unknown, key?: string) {\n const state = owner instanceof State ? owner : owner && PARENT.get(owner);\n\n if (!state) return REPORT.error(error);\n\n try {\n for (const handler of [...stages(state.constructor as State.Extends, 'catch')].reverse())\n if ((error = handler.call(state, error, kind, key)) === undefined) return;\n\n if (kind == 'unused') console.warn(error);\n else if (kind != 'dead') REPORT.error(error);\n } catch (err) {\n REPORT.error(err);\n }\n}\n\nREPORT.as = report;\n\n/**\n * Hand a value stored by an owning writer to that property's adopter,\n * creating one the first time a State is stored there. A property which has\n * held a State keeps its adopter, so a later non-State value releases the\n * previous child.\n */\nfunction adopt(state: State, key: unknown, value: unknown) {\n let keys = ADOPT.get(state);\n\n if (!keys) {\n if (!(value instanceof State)) return;\n ADOPT.set(state, (keys = new Map()));\n }\n\n let claim = keys.get(key);\n\n if (!claim) {\n if (!(value instanceof State)) return;\n keys.set(key, (claim = child(state)));\n }\n\n claim(value);\n}\n\n/** Resolve a getter to its latest hot-patched replacement. */\nfunction latest(getter: Function) {\n for (let next; (next = LATEST.get(getter)); ) getter = next;\n return getter;\n}\n\n/** Random alphanumberic of length 6; always starts with a letter. */\nfunction uid() {\n return (0.278 + Math.random() * 0.722)\n .toString(36)\n .substring(2, 8)\n .toUpperCase();\n}\n\nfunction unbind<T extends Function>(fn: T): T;\nfunction unbind<T extends Function>(fn?: T): T | undefined;\nfunction unbind(fn?: Function) {\n return UNBIND.get(fn) || fn;\n}\n\n/**\n * Read or claim a parent for a given child. In read mode (one argument) returns\n * the current parent, or `undefined` if never assigned. In write mode assigns\n * only if unclaimed and returns whether the assignment applied - `true` means\n * this call freshly claimed it, `false` means it was already parented.\n */\nfunction parent(child: object): State | null | undefined;\nfunction parent(child: object, value: State | null): boolean;\nfunction parent(child: object, value?: State | null) {\n if (arguments.length < 2) return PARENT.get(child as State);\n if (PARENT.has(child as State)) return false;\n PARENT.set(child as State, value ?? null);\n return true;\n}\n\nexport type { Handler };\nexport { adopt, event, unbind, State, parent, children, owned, trailing, PENDING, STORE, uid, access, update, apply, compute, classify, METHODS, GETTERS, SETUP, UNBIND, LATEST };\n"],"mappings":";;;;;AAaA,MAAM,SAAS,OAAO;;AAGtB,MAAM,qBAAK,IAAI,SAAwB;;AAGvC,MAAM,wBAAQ,IAAI,SAA2D;;;AAI7E,MAAM,0BAAU,IAAI,KAA2B;AAK/C,MAAM,wBAAQ,IAAI,SAAsC;;AAGxD,MAAM,yBAAS,IAAI,SAA+B;;AAGlD,MAAM,yBAAS,IAAI,SAAmB;;AAGtC,MAAM,0BAAU,IAAI,SAAsD;;AAG1E,MAAM,0BAAU,IAAI,SAA+C;;AAGnE,MAAM,yBAAS,IAAI,SAA6B;;AAGhD,MAAM,UAAU,OAAO,IAAI,0BAA0B;;AAGrD,MAAM,wBAAQ,IAAI,SAAqB;;AAGvC,IAAI,SAAS;;AAGb,MAAM,SAAS,OAAO,IAAI,kBAAkB;AAE5C,IAAI,YAAY;;AAGhB,MAAM,wBAAQ,IAAI,SAAwD;AAC1E,MAAM,2BAAW,IAAI,SAA6C;AAClE,MAAM,uBAAO,IAAI,SAA4B;AAC7C,MAAM,wBAAQ,IAAI,SAA6C;AA8K/D,IAAe,QAAf,MAAe,MAAM;;;;;;;;;;;;CAYnB,OAAgB,SAAuB;CAQvC,YAAY,GAAG,MAAkB;AAC/B,SAAO,M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SAAO,MAAM,IAAI;;;AAIrB,OAAO,KAAK;;;;;;;AAQZ,SAAS,MAAM,OAAc,KAAc,OAAgB;CACzD,IAAI,OAAO,MAAM,IAAI,MAAM;AAE3B,KAAI,CAAC,MAAM;AACT,MAAI,EAAE,iBAAiB,OAAQ;AAC/B,QAAM,IAAI,OAAQ,uBAAO,IAAI,KAAK,CAAE;;CAGtC,IAAI,QAAQ,KAAK,IAAI,IAAI;AAEzB,KAAI,CAAC,OAAO;AACV,MAAI,EAAE,iBAAiB,OAAQ;AAC/B,OAAK,IAAI,KAAM,QAAQ,MAAM,MAAM,CAAE;;AAGvC,OAAM,MAAM;;;AAId,SAAS,OAAO,QAAkB;AAChC,MAAK,IAAI,MAAO,OAAO,OAAO,IAAI,OAAO,EAAK,UAAS;AACvD,QAAO;;;AAIT,SAAS,MAAM;AACb,SAAQ,OAAQ,KAAK,QAAQ,GAAG,MAC7B,SAAS,GAAG,CACZ,UAAU,GAAG,EAAE,CACf,aAAa;;AAKlB,SAAS,OAAO,IAAe;AAC7B,QAAO,OAAO,IAAI,GAAG,IAAI;;AAW3B,SAAS,OAAO,OAAe,OAAsB;AACnD,KAAI,UAAU,SAAS,EAAG,QAAO,OAAO,IAAI,MAAe;AAC3D,KAAI,OAAO,IAAI,MAAe,CAAE,QAAO;AACvC,QAAO,IAAI,OAAgB,SAAS,KAAK;AACzC,QAAO"}
|
|
1
|
+
{"version":3,"file":"state.js","names":[],"sources":["../src/state.ts"],"sourcesContent":["import { Context, host, join } from './context';\nimport { REPORT } from './dispatch';\nimport {\n capture,\n event,\n listener,\n Observer,\n observer,\n queued,\n touch,\n watch\n} from './observable';\n\nconst define = Object.defineProperty;\n\n/** Register for all active states via string identifiers (usually unique). */\nconst ID = new WeakMap<Model, string>();\n\n/** Internal state assigned to states. */\nconst STORE = new WeakMap<Model, Record<string | number | symbol, unknown>>();\n\n/** Models under construction - added on `new`, removed when activated or released.\n * Also carries work to run at the deadline, which `def` uses to bound its registry. */\nconst PENDING = new Set<Model | (() => void)>();\n\n/** External lifecycle listeners for any given Model class. */\ntype Handler = Model.On<any>;\n\nconst SETUP = new WeakMap<Model.Extends, Set<Handler>>();\n\n/** Parent-child relationships. */\nconst PARENT = new WeakMap<object, Model | null>();\n\n/** Reference bound instance methods, or their getter, to real one. */\nconst UNBIND = new WeakMap<any, any>();\n\n/** List of methods defined by a given type. */\nconst METHODS = new WeakMap<Function, Map<string, (value: any) => void>>();\n\n/** List of reactive getters defined by a given type. */\nconst GETTERS = new WeakMap<Function, Map<string, () => unknown>>();\n\n/** Replacement for a getter captured by live computed properties, for hot patching. */\nconst LATEST = new WeakMap<Function, Function>();\n\n/** Event every observer treats as watched, forcing a refresh after a hot patch. */\nconst REFRESH = Symbol.for('@expressive/mvc.refresh');\n\n/** Stale flags for compute closures awaiting refresh on next access. */\nconst STALE = new WeakSet<() => void>();\n\n/** Whether the deadline which drains `PENDING` is already queued for this tick. */\nlet QUEUED = false;\n\n/** Global list each loaded copy of this module adds its `Model` to, on first construction. */\nconst COPIES = Symbol.for('@expressive/mvc');\n\nlet ANNOUNCED = false;\n\n/** Adopters for managed properties which have held a child Model. */\nconst ADOPT = new WeakMap<Model, Map<unknown, (value: unknown) => void>>();\nconst CHILDREN = new WeakMap<Model, Set<(child: Model) => void>>();\nconst OWNS = new WeakMap<Model, Set<Model>>();\nconst OWNED = new WeakMap<Model, Set<(child: Model) => void>>();\n\ntype Overlay<T> = Record<string, unknown> & {\n [K in Model.Property<T>]?: T[K] extends (...args: infer A) => infer R\n ? (this: T, ...args: A) => R\n : T[K];\n};\n\ndeclare namespace Model {\n /** Any type of Model, using own class constructor as its identifier. */\n type Extends<T extends Model = Model> = (abstract new (...args: any[]) => T) &\n typeof Model;\n\n /** A Model constructor which may be instanciated. */\n type Type<T extends Model = Model> = (new (...args: Model.Args<T>) => T) &\n Omit<typeof Model, never>;\n\n /** Model constructor arguments */\n type Args<T extends Model = any> = (Args<T> | Init<T> | Overlay<T> | void)[];\n\n /**\n * Value of `static global`. A boolean opts a Model in or out of the\n * process-global root; a resolver decides at activation, receiving the\n * instance and returning whether it registers - use it to make the choice\n * conditional (e.g. per environment). A bare literal (`= true` / `= false`)\n * seals the choice for subclasses; widen a subclass's `static global` type to\n * `Model.Global` to permit a resolver or a later override.\n */\n type Global<T extends Model = any> = boolean | ((self: T) => boolean);\n\n /**\n * Model constructor callback - runs during activation, in argument order,\n * before the `new()` lifecycle hook (so it may configure state `new()`\n * will observe). Returned function will run when state is destroyed.\n */\n type Init<T extends Model = Model> = (\n this: T,\n thisArg: T\n ) => Promise<void> | (() => void) | Args<T> | Overlay<T> | void;\n\n /** Lifecycle handlers for `Model.on`, keyed by when they run. */\n interface On<T extends Model = Model> {\n /**\n * Per-class setup, run once when the class is first bootstrapped - before\n * its members are classified and bound. Receives the class, so a handler\n * may inspect or reshape the prototype first. A handler registered on a\n * base class runs for each subclass too.\n */\n type?(type: Model.Extends<T>): void;\n\n /**\n * Per-instance, once constructed - before own values are observed and\n * before constructor args and `new()`. May return a cleanup, constructor\n * args, or an assign overlay.\n */\n setup?(this: T, self: T): void | (() => void) | Promise<void> | Args<T> | Overlay<T>;\n\n /**\n * Per-instance, once ready - after own values are observed, constructor\n * args applied and `new()` has run. May return a cleanup function.\n */\n ready?(this: T, self: T): void | (() => void);\n\n /**\n * Runs each time a method is bound to an instance - first access,\n * reassignment, and the rebind after a hot patch - with the key, the bound\n * function and the instance. Tooling and development use.\n */\n method?(this: T, key: string, fn: Function, self: T): void;\n\n /**\n * Receives what an effect, refreshing getter or async initializer of this Model\n * or a subclass threw, a destroyed write, or an instance never activated - with\n * its `kind` (`effect`, `getter`, `setup`, `dead`, `unused`) and `key` where\n * one applies. Most-derived class first, last registered first, each once. Return the error\n * (or another) to pass it on; return nothing to handle it; throw to let it escape.\n * Passed off the end, a destroyed write outputs nothing, `unused` warns,\n * anything else escapes uncaught.\n */\n catch?(this: T, error: unknown, kind: 'effect' | 'getter' | 'setup' | 'dead' | 'unused', key?: string): unknown;\n }\n\n /** Object overlay to override values and methods on a state. */\n type Assign<T> = Record<string, unknown> & {\n [K in Property<T>]?: T[K];\n } & ThisType<T>;\n\n /** Subset of `keyof T` not defined by base Model. **/\n type Property<T> = Exclude<keyof T, keyof Model>;\n\n /** Managed subset of Property<T> - excludes unmanaged `_` keys. **/\n type Field<T> = Exclude<Property<T>, `_${string}`>;\n\n /** Any valid key for state, including but not limited to Field<T>. */\n type Event<T = Model> = Field<T> | number | symbol | (string & {});\n\n /** Any event signal dispatched to listeners, including lifecycle meta events. */\n type Signal<T = Model> = Event<T> | true | false | null;\n\n /** Export/Import compatible value for a given property in a Model. */\n type Export<R> = R extends Model\n ? Values<R>\n : R extends { get(): infer T }\n ? T\n : R;\n\n /**\n * Values from current state of given state.\n * Differs from `Values` as values here will drill\n * into \"real\" values held by exotics like ref.Object.\n */\n type Values<T> = { [P in Field<T>]: Export<T[P]> };\n\n /** Object comperable to data found in T. */\n type Partial<T> = { [P in Field<T>]?: Export<T[P]> };\n\n /** Value for a property applied by a state. */\n type Value<T extends Model, K extends Model.Event<T>> = K extends keyof T\n ? Export<T[K]>\n : unknown;\n\n type Setter<T> = (value: T, previous: T) => T | void;\n\n /** Descriptor config for a managed property. */\n type Apply<T = any> = {\n value?: T;\n get?: ((source: Model) => T) | boolean;\n set?: Setter<T> | boolean;\n enumerable?: boolean;\n // destroy?: () => void;\n };\n\n /** Descriptor config for set() overload - enforces type when key is a known field. */\n type Define<T, K> = K extends Field<T> ? Apply<T[K] | Export<T[K]>> : Apply;\n\n type OnEvent<T extends Model> = (\n this: T,\n key: Signal<T>,\n source: T\n ) => void | (() => void) | null;\n\n /** Exotic value, where actual value is contained within. */\n type Ref<T = any> = {\n (next: T): void;\n current: T | null;\n };\n\n /**\n * A callback function which is subscribed to parent and updates when accessed properties change.\n *\n * @param current - Current state of this state. This is a proxy which detects properties which\n * where accessed, and thus depended upon to stay current.\n *\n * @param update - Set of properties which have changed, and events fired, since last update.\n *\n * @returns A callback function which will be called when this effect is stale.\n */\n type Effect<T, R = EffectCallback | Promise<void> | null | void> = (\n this: T,\n current: T,\n update: readonly Model.Event<T>[] | undefined\n ) => R;\n\n /**\n * Returned by `get(effect)`. Call to stop the effect. Await to stop it once it\n * has run clean and receive that run's value - a sync run's output, or what its\n * promise resolved to.\n */\n type Release<R = void> = (() => void) & PromiseLike<R>;\n\n /**\n * A callback function returned by effect. Will be called when effect is stale.\n *\n * @param update - `true` if update is pending, `false` effect has been cancelled, `null` if state is destroyed.\n */\n type EffectCallback = (update: boolean | null) => void;\n\n /**\n * A list of keys updated, or events fired, since last update.\n * This may be awaited to get full list (same array) when update is settled.\n */\n type Updated<T extends Model> = readonly Event<T>[] &\n PromiseLike<readonly Event<T>[]>;\n}\n\nabstract class Model {\n /**\n * Whether an instance activated with no enclosing context registers itself\n * to the process-global root, where `get()` can resolve it from anywhere.\n * `false` (the default) keeps a context-less instance fully functional but\n * private - not injectable, though it can still read declared globals. Opt in\n * with `static readonly global = true`; a resolver (see {@link Model.Global})\n * makes the choice conditional. It must be declared per class - a subclass\n * that would inherit a global without its own declaration throws on\n * activation, so an accidental global (a forgotten `<Component for>`, an\n * extended global) cannot leak into the shared root.\n */\n static readonly global: Model.Global = false;\n\n /**\n * Loopback to instance of this state. This is useful when in a subscribed context,\n * to keep write access to `this` after a destructure. You can use it to read variables silently as well.\n **/\n declare is: this;\n\n constructor(...args: Model.Args) {\n define(this, 'is', { value: this });\n init(this, args, this.new);\n }\n\n /**\n * Optional lifecycle hook called during Model initialization.\n * Can return a cleanup function to run when state is destroyed.\n *\n * It is recommended you protect this method.\n */\n protected new?(): void | (() => void);\n\n /**\n * Pull current values from state. Flattens all states and exotic values recursively.\n *\n * @returns Object with all values from this state.\n **/\n get(): Model.Values<this>;\n\n /**\n * Run a function to run automatically when accessed values change.\n *\n * @param effect Function to run, and whenever accessed values change.\n * If effect returns a function, it will be called when a change occurs (syncronously),\n * effect is cancelled, or parent state is destroyed. A returned promise\n * defers re-runs until it settles; its resolved value is treated the same way.\n * @returns Function to cancel listener - awaited, cancels and yields the effect's value.\n */\n get(effect: Model.Effect<this>): Model.Release;\n\n /**\n * Run a function to run automatically when accessed values change, which\n * produces a value - sync or async. Await the returned function to cancel the\n * effect once a run completes and receive what it returned.\n */\n get<R>(effect: Model.Effect<this, Promise<R>>): Model.Release<R>;\n\n /**\n * Get value of a property. Will fetch underlying value from exotic values like ref.Object.\n *\n * Any value which implements `get()` (with no arguments) will be treated as such.\n *\n * @param key - Property to get value of.\n * @param required - If true, will throw an error if property is not available.\n * @returns Value of property.\n */\n get<T extends Model.Event<this>>(\n key: T,\n required?: boolean\n ): Model.Value<this, T>;\n\n /**\n * Check if state is destroyed.\n *\n * @param status - `null` to check if state is destroyed.\n * @returns `true` if state is destroyed, `false` otherwise.\n */\n get(status: null): boolean;\n\n /**\n * Callback when state is to be destroyed.\n *\n * @param callback - Function to call when state is destroyed.\n * @returns Function to cancel listener.\n */\n get(status: null, callback: () => void): () => void;\n\n /** Fetch Model of type from context. Throws if not found. */\n get<T extends Model>(type: Model.Type<T>, required?: true): T;\n\n /** Fetch a Model from context. Undefined if not found. */\n get<T extends Model>(type: Model.Type<T>, required: boolean): T | undefined;\n\n /**\n * Subscribe to Model becoming available in context.\n *\n * Will search both up and downstream by default.\n * Normally you can ignore this because Model you expect is rarely both.\n *\n * Specify downstream if you only want to watch for Model in children, which can be useful if you expect multiple of the same Model in different branches of the tree.\n *\n * @param type - Type of Model to watch for.\n * @param callback - Function to call when Model is found. Will be called immediately if Model is already available.\n * @param downstream - If true, will only watch for Model in children, if false will only for parents.\n * @returns Function to cancel listener.\n */\n get<T extends Model>(\n type: Model.Type<T>,\n callback: Context.Expect<T>,\n downstream?: boolean\n ): () => void;\n\n // Owner overloads take `Model` itself only - a subclass would otherwise match\n // them in TypeScript's subtype pass, before the `Model.Type<T>` overloads.\n\n /** Owner of this Model. Throws if it has none. */\n get<T extends typeof Model>(\n type: T & (typeof Model extends T ? unknown : never),\n required?: true\n ): Model;\n\n /** Owner of this Model. Undefined if it has none. */\n get<T extends typeof Model>(\n type: T & (typeof Model extends T ? unknown : never),\n required: boolean\n ): Model | undefined;\n\n /**\n * Run a callback for each Model this one owns - those owned now, then each\n * one as it activates. Callback may return a function, called when that Model\n * is destroyed.\n *\n * @returns Function to stop watching.\n */\n get<T extends typeof Model>(\n type: T & (typeof Model extends T ? unknown : never),\n callback: (child: Model) => void | (() => void),\n downstream: true\n ): () => void;\n\n get(\n arg1?: Model.Effect<this> | Model.Type | typeof Model | string | null,\n arg2?: boolean | Context.Expect | (() => void),\n arg3?: boolean\n ) {\n const self = this.is;\n\n if (arg1 === undefined) return values(self);\n if (arg1 === Model)\n return typeof arg2 == 'function'\n ? owned(self, arg2 as (child: Model) => void)\n : observed(this, arg1, owner(self, arg2 as boolean));\n if (Model.is(arg1))\n return observed(this, arg1, Context.get(self).get(arg1, arg2, arg3, self));\n if (typeof arg1 == 'function') return watch(self, unbind(arg1));\n if (typeof arg2 == 'function') return callback(self, arg2, arg1);\n if (arg1 === null) return observer(self) === null;\n return access(self, arg1, arg2);\n }\n\n /**\n * Get update in progress.\n *\n * @returns Promise which resolves object with updated values, `undefined` if there no update is pending.\n **/\n set(): Model.Updated<this>;\n\n /**\n * Merge argument with current state, updating one or more properties at once.\n * Properties which are not managed by this state will be ignored.\n *\n * @param assign - Object with properties to update.\n * @param silent - If true, listeners will not be notified. If state is destroyed, stores the update without reporting it.\n * @returns Array of keys updated, syncronously contains keys updated immediately and may be resolved (to itself) when all updates are settled.\n */\n set(assign?: Model.Assign<this>, silent?: boolean): Model.Updated<this>;\n\n /**\n * Call a function when update occurs.\n *\n * Given function is called for every assignment (which changes value) or explicit `set`.\n *\n * To run logic on final value only, callback may return a function. The same\n * function for one or more events will be called only once when update is settled.\n *\n * Return `null` from callback to stop listening.\n *\n * @param callback - Function to call when update occurs.\n * @returns Function to remove listener. Will return `true` if removed, `false` if inactive already.\n */\n set(callback: Model.OnEvent<this>): () => boolean;\n\n /**\n * Push an update. This will not change the value of associated property.\n *\n * Useful where a property value internally has changed, but the object is the same.\n * For example: An array has pushed a new value, or a nested property is updated.\n *\n * You can also use this to dispatch arbitrary events.\n * Symbols are recommended as non-property events, however you can use any string.\n * If doing so, be sure to avoid collisions using property names. An easy way to do this is\n * to prefix an event with \"!\" and/or use dash-case. e.g. `set(\"!event\")` or `set(\"my-event\")`.\n *\n * @param key - Property or event to dispatch.\n * @returns Promise resolves an array of keys updated.\n */\n set(key: Model.Event<this>): Model.Updated<this>;\n\n /**\n * Declare an end to updates. This event is final - later writes are stored but never dispatched.\n * This event can be watched for as well, to run cleanup logic and internally will remove all listeners.\n *\n * @param status - `null` to end updates.\n */\n set(status: null): void;\n\n /**\n * Register a callback for a specific property or event.\n *\n * Callback receives the key, current value, and source instance.\n *\n * @param event - Property or event to watch. If `null`, will callback on destroy.\n * @param callback - Function to call when event occurs.\n * @returns Function to remove listener.\n */\n set<K extends Model.Event<this>>(\n event: K | null,\n callback: Model.OnEvent<this>\n ): () => boolean;\n\n /**\n * Define or update a managed property using a descriptor config.\n * If the property already is managed, config will only accept value.\n * If the property does not exist, it will be created and made reactive.\n *\n * @param key - Property to define or update.\n * @param config - Descriptor config with value, get, set, enumerable, and/or destroy.\n * @returns Promise resolves an array of keys updated.\n */\n set<K extends Model.Event<this>>(\n key: K,\n config: Model.Define<this, K>\n ): Model.Updated<this>;\n\n set(\n arg1?: Model.OnEvent<this> | Model.Assign<this> | Model.Event<this> | null,\n arg2?: unknown\n ) {\n const self = this.is;\n\n if (typeof arg1 == 'function')\n return listener(self, (key) => {\n if (\n typeof key == 'string' ||\n typeof key == 'number' ||\n typeof key == 'symbol' && key !== REFRESH\n )\n return arg1.call(self, key, self);\n });\n\n if (typeof arg2 == 'function')\n return callback(self, arg2, arg1 as Model.Signal);\n\n if (arg1 && typeof arg1 == 'object') assign(self, arg1, arg2 === true);\n else if (arg2) apply(self, arg1 as string, arg2);\n else event(self, arg1);\n\n return queued(self) as Model.Updated<this>;\n }\n\n /**\n * Iterate over managed properties in this instance of Model.\n * Yeilds the key and current value for each property.\n */\n [Symbol.iterator](): Iterator<[string, unknown]> {\n return Object.entries(STORE.get(this.is)!)[Symbol.iterator]();\n }\n\n /**\n * Create and activate a new instance of this state.\n *\n * **Important** - Unlike `new this(...)` - this method also activates state.\n *\n * @param args - arguments sent to constructor\n */\n static new<T extends Model>(this: Model.Type<T>, ...args: Model.Args<T>): T {\n const instance = new this(...args);\n event(instance);\n return instance;\n }\n\n /**\n * Static equivalent of `x instanceof this`.\n * Determines if provided class is a subtype of this one.\n * If so, language server will make available all static\n * methods and properties of this class.\n */\n static is<T extends Model.Extends>(this: T, maybe: unknown): maybe is T {\n return (\n maybe === this ||\n (typeof maybe == 'function' && maybe.prototype instanceof this)\n );\n }\n\n /**\n * Register a lifecycle handler for this Model and its subclasses.\n *\n * Hooks by cadence - `type` (per-class, at bootstrap), `setup` (per-instance,\n * before values are observed), `ready` (per-instance, after `new()`), and\n * `method` (per method binding). A function alone is a `setup` handler. A\n * function returned from `setup` or `ready` runs when the instance is destroyed.\n *\n * @returns Function to remove the handler.\n */\n static on<T extends Model>(\n this: Model.Extends<T>,\n setup: NonNullable<Model.On<T>['setup']>\n ): () => boolean;\n static on<T extends Model>(\n this: Model.Extends<T>,\n handler: Model.On<T>\n ): () => boolean;\n static on<T extends Model>(\n this: Model.Extends<T>,\n handler: Model.On<T> | NonNullable<Model.On<T>['setup']>\n ) {\n if (typeof handler == 'function') handler = { setup: handler };\n\n let setup = SETUP.get(this);\n\n if (!setup) SETUP.set(this, (setup = new Set()));\n\n setup.add(handler);\n\n return () => setup.delete(handler);\n }\n}\n\ndefine(Model.prototype, 'toString', {\n value() {\n return ID.get(this.is);\n }\n});\n\ndefine(Model, 'toString', {\n value() {\n return this.name;\n }\n});\n\nfunction observed<T>(from: Model, key: unknown, value: T): T {\n return value instanceof Model ? touch(from, key, value) : value;\n}\n\n/** Register a user OnEvent callback, preserving `this` and `source`. */\nfunction callback<T extends Model>(\n self: T,\n cb: Function,\n select?: Observer.Signal | Set<Observer.Signal>\n) {\n return listener(self, (key) => cb.call(self, key, self), select);\n}\n\n/**\n * Apply state arguemnts, run callbacks and observe properties.\n * Accumulate and handle cleanup events.\n **/\nfunction init(state: Model, ...args: Model.Args) {\n const T = state.constructor as Model.Extends;\n\n if (T === Model) throw new Error('Cannot create base Model.');\n\n if (!ANNOUNCED) {\n ANNOUNCED = true;\n ((globalThis as { [COPIES]?: unknown[] })[COPIES] ||= []).push(Model);\n }\n\n const { before, after } = bootstrap(T);\n\n ID.set(state, `${T}-${uid()}`);\n STORE.set(state, {});\n\n function observe() {\n for (const key in state) {\n const desc: PropertyDescriptor = Object.getOwnPropertyDescriptor(state, key) || {};\n\n if (!('value' in desc) || !desc.configurable) continue;\n\n if (key[0] == '_') unmanaged(state, key, desc.value);\n else apply(state, key, desc, true);\n }\n }\n\n function register() {\n if (Context.get(state) !== Context.root) return;\n\n const type = state.constructor as typeof Model;\n const g = type.global;\n\n if (!(typeof g == 'function' ? g(state) : g)) return;\n\n if (!Object.prototype.hasOwnProperty.call(type, 'global'))\n throw new Error(\n `${state} would register as a global by inheritance alone - re-declare \\`static global\\` on ${type.name} (\\`true\\` to keep it, \\`false\\` to opt out).`\n );\n\n for (let T: Model.Extends = type; T !== Model; T = Object.getPrototypeOf(T)) {\n const found = Context.root.get(T, false);\n\n if (found && (T === type || found.constructor === T))\n throw new Error(\n `Cannot register ${state} as a global - ${found} already exists in root. Destroy the existing instance first, or provide additional ones via explicit context.`\n );\n }\n\n return Context.root.add(state);\n }\n\n listener(state, (key) => {\n const rest = trailing(state);\n\n PENDING.delete(state);\n\n if (key === null) return null;\n\n if (!PARENT.has(state)) parent(state, host(state) || null);\n\n const above = PARENT.get(state);\n const owns = above && (OWNS.get(above) || OWNS.set(above, new Set()).get(above)!);\n\n if (owns) listener(state, () => void owns.delete(state), null);\n\n const queue = [...before, observe, ...args, ...after, register];\n\n capture((release) => {\n listener(state, () => release(null), null);\n\n for (let i = 0; i < queue.length; i++) {\n const arg = queue[i];\n const out = typeof arg == 'function' ? arg.call(state, state) : arg;\n\n if (out instanceof Promise)\n out.catch((err) => report('setup', state, err));\n else if (Array.isArray(out)) queue.splice(i + 1, 0, ...out);\n else if (typeof out == 'function') listener(state, out, null);\n else if (typeof out == 'object') assign(state, out, true);\n }\n });\n\n if (owns) {\n owns.add(state);\n OWNED.get(above)?.forEach((cb) => cb(state));\n }\n\n let end = rest.length;\n\n while (end-- > 0 && PENDING.has(rest[end]));\n\n for (let i = 0; i < end; i++) PENDING.delete(rest[i]);\n\n return null;\n });\n\n if (!QUEUED) {\n QUEUED = true;\n\n queueMicrotask(() => {\n QUEUED = false;\n\n for (const item of PENDING)\n if (typeof item == 'function') item();\n else report('unused', item, new Error(`${item} was constructed but never activated.`));\n\n PENDING.clear();\n });\n }\n\n PENDING.add(state);\n}\n\nfunction unmanaged(state: Model, key: string, value: unknown) {\n define(state, key, {\n configurable: true,\n enumerable: false,\n get: () => value,\n set: (next) => { value = next }\n });\n}\n\n/**\n * Apply instructions and inherited event listeners. Ensure class metadata is ready.\n *\n * @param T - Model class to bootstrap.\n * @return Array of init functions to run on instance, in order of class hierarchy.\n */\nfunction bootstrap(T: Model.Extends) {\n const chain = [] as Model.Extends[];\n const before = new Set<Model.Init>();\n const after = new Set<Model.Init>();\n const onType = new Set<NonNullable<Model.On['type']>>();\n let keys = new Map<string, (value: any) => void>();\n let getters = new Map<string, () => unknown>();\n\n while (true) {\n chain.unshift(T);\n if (T === Model) break;\n T = Object.getPrototypeOf(T);\n }\n\n for (const type of chain) {\n for (const handler of SETUP.get(type) || []) {\n if (handler.setup) before.add(handler.setup);\n if (handler.ready) after.add(handler.ready);\n if (handler.type) onType.add(handler.type);\n }\n\n if (type === Model) continue;\n\n if (METHODS.has(type)) {\n keys = METHODS.get(type)!;\n getters = GETTERS.get(type)!;\n continue;\n }\n\n for (const setupType of onType) setupType(type);\n\n METHODS.set(type, (keys = new Map(keys)));\n GETTERS.set(type, (getters = new Map(getters)));\n\n classify(type, keys, getters);\n }\n\n if (getters.size)\n before.add((self) => getters.forEach(compute, self));\n\n return { before, after };\n}\n\n/** Bind own configurable methods of a type and collect its reactive getters. */\nfunction classify(\n type: Model.Extends,\n keys: Map<string, (value: any) => void>,\n getters: Map<string, () => unknown>\n) {\n for (const [key, desc] of Object.entries(\n Object.getOwnPropertyDescriptors(type.prototype)\n )) {\n if (key == 'constructor' || !desc.configurable) continue;\n\n const { get, set } = desc;\n\n if (key[0] == '_' && (get || set)) {\n define(type.prototype, key, {\n ...desc,\n get: get && function (this: Model) { return get.call(this.is || this) },\n set: set && function (this: Model, value: unknown) { set.call(this.is || this, value) }\n });\n\n continue;\n }\n\n if (typeof get == 'function') {\n if (typeof set != 'function') getters.set(key, get);\n\n continue;\n }\n\n const { value } = desc;\n\n if (typeof value !== 'function') continue;\n\n function bind(this: Model, original?: Function) {\n const { is } = this;\n\n if (is.hasOwnProperty(key) && !original) return value as Function;\n\n const fn = original || value;\n const bound = fn.bind(is);\n\n UNBIND.set(bound, fn);\n define(is, key, { value: bound, writable: true, configurable: true });\n\n for (const handler of stages(is.constructor as Model.Extends, 'method')) handler.call(is, key, bound, is);\n\n return bound;\n }\n\n UNBIND.set(bind, value);\n\n keys.set(key, bind);\n define(type.prototype, key, { get: bind, set: bind });\n }\n}\n\n/** Handlers of one stage along the class chain - ancestor first, in registration order, each once. */\nfunction stages<K extends 'method' | 'catch'>(T: Model.Extends, key: K): Set<NonNullable<Model.On[K]>> {\n const found = T === Model ? new Set<NonNullable<Model.On[K]>>() : stages(Object.getPrototypeOf(T), key);\n\n for (const handler of SETUP.get(T) || []) if (handler[key]) found.add(handler[key]!);\n\n return found;\n}\n\n/**\n * Install a reactive computed property on a state instance, derived from a prototype\n * getter or an arity-bearing `set` factory.\n *\n * The getter is invoked with the tracking proxy as both `this` and its first argument;\n * reads of managed properties through it create subscriptions. Result is cached and\n * emits a keyed event when stale.\n */\nfunction compute(this: Model, getter: (self: any) => unknown, key: string) {\n const store = STORE.get(this)!;\n let reset: (() => void) | undefined;\n let isAsync: boolean;\n let suspended = false;\n let waiting: Promise<unknown> | undefined;\n let proxy: any;\n\n const connect = () => {\n reset = watch(\n this,\n (current) => {\n proxy = current;\n\n if (!(key in store) || STALE.delete(run)) run(!reset);\n\n return (didUpdate) => {\n if (didUpdate) {\n STALE.add(run);\n event(this, key, true);\n }\n };\n },\n false\n );\n };\n\n const run = (initial?: boolean) => {\n let next: unknown;\n\n waiting = undefined;\n\n try {\n next = latest(getter).call(proxy, proxy);\n } catch (err) {\n if (err instanceof Promise) {\n if (initial) {\n suspended = true;\n throw err;\n }\n\n const retry = () => {\n if (waiting === err && observer(this) !== null) run();\n };\n\n waiting = err;\n err.then(retry, retry);\n\n if (suspended) return;\n } else if (initial) {\n console.warn(`An exception was thrown while initializing ${this}.${key}.`);\n throw err;\n } else report('getter', this, err, key);\n }\n\n suspended = false;\n update(this, key, next, !isAsync);\n };\n\n apply(\n this,\n key,\n {\n enumerable: true,\n set: false,\n get: () => {\n if (!proxy) {\n if (observer(this) === null) return store[key];\n\n connect();\n isAsync = true;\n }\n\n if (STALE.delete(run)) run();\n\n return access(this, key, suspended);\n }\n },\n true\n );\n}\n\n/**\n * Define or update a managed property using a descriptor config.\n * If the property already is managed, config will only accept value.\n * If the property does not exist, it will be created and made reactive.\n *\n * @param state - Model to apply property to.\n * @param key - Property to define or update.\n * @param config - Descriptor config with value, get, set, enumerable, and/or destroy.\n * @param silent - If an update does occur, listeners will not be refreshed automatically.\n */\nfunction apply(\n state: Model,\n key: string,\n config: Model.Apply,\n silent?: boolean\n) {\n const desc = Object.getOwnPropertyDescriptor(state, key);\n\n if (desc && 'get' in desc) {\n if (Object.keys(config).some((k) => k != 'value'))\n throw new Error(`Property ${key} on ${state} is already defined.`);\n if ('value' in config) update(state, key, config.value, silent);\n return;\n }\n\n function set(value: unknown, silent?: boolean) {\n update(state, key, value, silent, true);\n }\n\n define(state, key, {\n configurable: true,\n enumerable: config.enumerable !== false,\n get(this: Model) {\n const value =\n typeof config.get == 'function'\n ? config.get(this)\n : access(state, key, config.get);\n\n return touch(this, key, value);\n },\n set(next: any, silent?: boolean) {\n if (config.set === false)\n throw new Error(`${state}.${String(key)} is read-only.`);\n\n if (typeof config.set == 'function')\n try {\n const output = config.set(next, STORE.get(state)![key]);\n if (output !== undefined) next = output;\n } catch (err: unknown) {\n if (err === false) return;\n if (err === true) {\n set(next, true);\n return;\n }\n throw err;\n }\n\n set(next, silent);\n }\n });\n\n if ('value' in config) set(config.value, silent);\n}\n\nfunction provides(ctx: Context, value: Model) {\n while (ctx = ctx.parent!) {\n const entries = ctx.provide.get(value.constructor as Model.Extends);\n if (entries) for (const [state] of entries) if (state === value) return true;\n }\n}\n\nfunction child(state: Model) {\n let cleanup: (() => void) | undefined;\n const ctx = Context.get(state);\n\n function reset() {\n if (cleanup) cleanup();\n cleanup = undefined;\n }\n\n listener(state, reset, null);\n\n return (value: unknown) => {\n reset();\n\n if (!(value instanceof Model)) return;\n\n if (parent(value, state)) {\n const remove = join(state, value);\n cleanup = () => {\n cancel();\n remove();\n event(value, null);\n };\n const cancel = listener(state, cleanup, null);\n } else if (!provides(ctx, value)) {\n cleanup = join(state, value);\n }\n\n event(value);\n\n CHILDREN.get(state)?.forEach((cb) => cb(value));\n };\n}\n\n/**\n * Pending Models constructed after this one - in a parent, the products of\n * its own initializers, until the last one it kept.\n */\nfunction trailing(state: Model) {\n const rest: Model[] = [];\n let seen = false;\n\n for (const item of PENDING)\n if (!seen) seen = item === state;\n else if (item instanceof Model) rest.push(item);\n\n return rest;\n}\n\n/**\n * Report Models adopted by a parent - those already held, then each one\n * claimed later. Returns a callback to stop watching.\n */\nfunction children(state: Model, callback: (child: Model) => void) {\n const store = STORE.get(state)!;\n const keys = ADOPT.get(state);\n\n if (keys)\n for (const key of keys.keys()) {\n const value = store[key as string];\n if (value instanceof Model) callback(value);\n }\n\n let set = CHILDREN.get(state);\n\n if (!set) CHILDREN.set(state, (set = new Set()));\n\n set.add(callback);\n\n return () => set!.delete(callback);\n}\n\nfunction owner(state: Model, required?: boolean) {\n const found = PARENT.get(state);\n\n if (found || required === false) return found || undefined;\n\n throw new Error(`${state} has no owner.`);\n}\n\n/**\n * Report Models owned by this one - those active now, then each one as it\n * activates. A function returned by `callback` runs when that Model is destroyed.\n */\nfunction owned(state: Model, callback: (child: Model) => void | (() => void)) {\n function each(child: Model) {\n const done = callback(child);\n if (typeof done == 'function') listener(child, () => void done(), null);\n }\n\n OWNS.get(state)?.forEach(each);\n\n let set = OWNED.get(state);\n\n if (!set) OWNED.set(state, (set = new Set()));\n\n set.add(each);\n\n return () => void set!.delete(each);\n}\n\n/** Currently accumulating export. Stores real values of placeholder properties such as ref() or child states. */\nlet EXPORT: Map<any, any> | undefined;\n\nfunction values<T extends Model>(state: T): Model.Values<T> {\n const values = {} as any;\n let notRecursive;\n\n if (!EXPORT) {\n notRecursive = true;\n EXPORT = new Map();\n }\n\n EXPORT.set(state, values);\n\n for (let [key, value] of state) {\n if (EXPORT.has(value)) value = EXPORT.get(value);\n else if (\n value &&\n typeof value == 'object' &&\n 'get' in value &&\n typeof value.get === 'function'\n )\n value = value.get();\n\n values[key] = value;\n }\n\n if (notRecursive) EXPORT = undefined;\n\n return Object.freeze(values);\n}\n\nfunction access(state: Model, property: string, required?: boolean) {\n const store = STORE.get(state)!;\n\n if (property in store || required === false) {\n const value = store[property];\n\n if (value !== undefined || !required) return value;\n }\n\n if (METHODS.get(state.constructor)!.has(property))\n return unbind((state as any)[property]);\n\n if (observer(state) === null) return undefined;\n\n const error = new Error(`${state}.${property} is not yet available.`);\n const promise = new Promise<any>((resolve, reject) => {\n listener(state, (key) => {\n if (key === property) {\n resolve(store[key]);\n return null;\n }\n\n if (key === null) {\n reject(new Error(`${state} is destroyed.`));\n }\n });\n });\n\n throw Object.assign(promise, {\n toString: () => String(error),\n name: 'Suspense',\n message: error.message,\n stack: error.stack\n });\n}\n\nfunction assign(state: Model, data: Model.Assign<Model>, silent?: boolean) {\n if (!silent && observer(state) !== null) event(state);\n\n const methods = METHODS.get(state.constructor)!;\n const getters = GETTERS.get(state.constructor);\n\n for (const key in data) {\n const bind = methods.get(key);\n\n if (bind) bind.call(state, data[key]);\n else if (getters?.has(key)) continue;\n else if (key in state && key !== 'is') {\n const desc: PropertyDescriptor = Object.getOwnPropertyDescriptor(state, key) || {};\n const set = desc.set as (value: any, silent?: boolean) => void;\n\n if (set) {\n set.call(state, data[key], silent);\n } else {\n Reflect.set(state, key, data[key]);\n }\n }\n }\n}\n\n/**\n * Update a property on a state instance and notify listeners.\n *\n * This is used internally to update properties, but can also be used to update properties which are not managed by state, or to update values without triggering setters.\n *\n * A destroyed state stores the write without dispatch, reports it unless `silent`, and returns `false`.\n */\nfunction update<T>(\n state: Model,\n key: Model.Event<T>,\n value: T,\n silent?: boolean,\n own?: boolean\n) {\n const store = STORE.get(state)!;\n\n if (value instanceof Model) value = value.is as T;\n\n if (observer(state) === null) {\n if (!silent) report('dead', state, new Error(`Tried to update ${state}.${String(key)} but state is destroyed.`), String(key));\n store[key] = value;\n return false;\n }\n\n if (key in store && value === store[key]) return false;\n\n store[key] = value;\n\n if (!silent) event(state, key);\n\n if (own) adopt(state, key, value);\n\n return true;\n}\n\n/**\n * Pass an error along `catch` handlers - most-derived class first, last registered\n * first, one on several classes once at the outermost - until one returns nothing. Passed off\n * the end, a destroyed write outputs nothing, `unused` warns, anything else escapes uncaught;\n * so does a handler's throw.\n */\nfunction report(kind: Parameters<NonNullable<Model.On['catch']>>[1], owner: object | undefined, error: unknown, key?: string) {\n const state = owner instanceof Model ? owner : owner && PARENT.get(owner);\n\n if (!state) return REPORT.error(error);\n\n try {\n for (const handler of [...stages(state.constructor as Model.Extends, 'catch')].reverse())\n if ((error = handler.call(state, error, kind, key)) === undefined) return;\n\n if (kind == 'unused') console.warn(error);\n else if (kind != 'dead') REPORT.error(error);\n } catch (err) {\n REPORT.error(err);\n }\n}\n\nREPORT.as = report;\n\n/**\n * Hand a value stored by an owning writer to that property's adopter,\n * creating one the first time a Model is stored there. A property which has\n * held a Model keeps its adopter, so a later non-Model value releases the\n * previous child.\n */\nfunction adopt(state: Model, key: unknown, value: unknown) {\n let keys = ADOPT.get(state);\n\n if (!keys) {\n if (!(value instanceof Model)) return;\n ADOPT.set(state, (keys = new Map()));\n }\n\n let claim = keys.get(key);\n\n if (!claim) {\n if (!(value instanceof Model)) return;\n keys.set(key, (claim = child(state)));\n }\n\n claim(value);\n}\n\n/** Resolve a getter to its latest hot-patched replacement. */\nfunction latest(getter: Function) {\n for (let next; (next = LATEST.get(getter)); ) getter = next;\n return getter;\n}\n\n/** Random alphanumberic of length 6; always starts with a letter. */\nfunction uid() {\n return (0.278 + Math.random() * 0.722)\n .toString(36)\n .substring(2, 8)\n .toUpperCase();\n}\n\nfunction unbind<T extends Function>(fn: T): T;\nfunction unbind<T extends Function>(fn?: T): T | undefined;\nfunction unbind(fn?: Function) {\n return UNBIND.get(fn) || fn;\n}\n\n/**\n * Read or claim a parent for a given child. In read mode (one argument) returns\n * the current parent, or `undefined` if never assigned. In write mode assigns\n * only if unclaimed and returns whether the assignment applied - `true` means\n * this call freshly claimed it, `false` means it was already parented.\n */\nfunction parent(child: object): Model | null | undefined;\nfunction parent(child: object, value: Model | null): boolean;\nfunction parent(child: object, value?: Model | null) {\n if (arguments.length < 2) return PARENT.get(child as Model);\n if (PARENT.has(child as Model)) return false;\n PARENT.set(child as Model, value ?? null);\n return true;\n}\n\nexport type { Handler };\nexport { adopt, event, unbind, Model, parent, children, owned, trailing, PENDING, STORE, uid, access, update, apply, compute, classify, METHODS, GETTERS, SETUP, UNBIND, LATEST };\n"],"mappings":";;;;;AAaA,MAAM,SAAS,OAAO;;AAGtB,MAAM,qBAAK,IAAI,SAAwB;;AAGvC,MAAM,wBAAQ,IAAI,SAA2D;;;AAI7E,MAAM,0BAAU,IAAI,KAA2B;AAK/C,MAAM,wBAAQ,IAAI,SAAsC;;AAGx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