@tschk/moonshine-vue 0.4.4 → 0.4.80

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/src/reactive.ts CHANGED
@@ -6,43 +6,148 @@ import {
6
6
  createRoot,
7
7
  createSignal,
8
8
  getOwner,
9
+ getRenderScheduler,
9
10
  onCleanup,
11
+ runWithOwner,
10
12
  untrack,
13
+ type Owner,
11
14
  } from "@tschk/moonshine-dom/reactive";
12
15
  import { createMemo } from "@tschk/moonshine";
13
- import { createMutable } from "@tschk/moonshine-dom/store";
16
+ import {
17
+ collectDeps,
18
+ isTracking,
19
+ trackDependency,
20
+ type Trackable,
21
+ } from "@tschk/moonshine/tracking";
22
+ import { createTrackedMap } from "./map";
23
+ import { createTrackedSet } from "./set";
24
+ import {
25
+ getComponentContext,
26
+ nativeRefSet,
27
+ peekComponentContext,
28
+ withComponentConsumer,
29
+ type ComponentContext,
30
+ } from "@tschk/moonshine-dom/component";
31
+ import { createEmitter } from "./events";
32
+ import { peekSSRContext } from "./context";
33
+ export {
34
+ hasInjectionContext,
35
+ inject,
36
+ peekSSRContext,
37
+ provide,
38
+ useAttrs,
39
+ useId,
40
+ useSlots,
41
+ useSSRContext,
42
+ type AppConfig,
43
+ type AppContextState,
44
+ type InjectionKey,
45
+ type Slots,
46
+ type SSRContext,
47
+ } from "./context";
48
+ import { peekServerPrefetchSession } from "./lifecycle";
49
+ export {
50
+ onActivated,
51
+ onBeforeMount,
52
+ onBeforeUnmount,
53
+ onBeforeUpdate,
54
+ onDeactivated,
55
+ onErrorCaptured,
56
+ onMounted,
57
+ onServerPrefetch,
58
+ onUnmounted,
59
+ onUpdated,
60
+ type ErrorCapturedHook,
61
+ } from "./lifecycle";
62
+ import { normalizeClass, normalizeStyle } from "./normalize";
63
+ import {
64
+ createMutable,
65
+ unwrap as unwrapStore,
66
+ } from "@tschk/moonshine-dom/store";
14
67
 
15
- const refs = new WeakSet<object>();
68
+ const refs = nativeRefSet;
69
+ const readonlyRefs = new WeakSet<object>();
70
+ const refTriggers = new WeakMap<Ref<any>, () => void>();
71
+ const refTriggerVersions = new WeakMap<Ref<any>, number>();
16
72
  declare const refBrand: unique symbol;
17
- export class Ref<T> {
73
+ export class Ref<T, S = T> {
18
74
  declare readonly [refBrand]: true;
19
75
  private readonly read: () => T;
20
- private readonly write?: (value: T) => void;
21
- constructor(read: () => T, write?: (value: T) => void) {
76
+ private readonly write?: (value: any) => void;
77
+ constructor(read: () => T, write?: (value: S) => void) {
22
78
  this.read = read;
23
79
  this.write = write;
24
80
  refs.add(this);
81
+ if (!write) readonlyRefs.add(this);
25
82
  }
26
83
  get value(): T {
27
84
  return this.read();
28
85
  }
29
- set value(value: T) {
86
+ set value(value: S) {
30
87
  if (!this.write) throw new TypeError("Native ref is readonly");
31
88
  this.write(value);
32
89
  }
33
90
  }
34
- export function isRef(value: unknown): value is Ref<any> {
91
+ export function isRef(value: unknown): value is Ref<any, any> {
35
92
  return typeof value === "object" && value !== null && refs.has(value);
36
93
  }
37
- function plain(value: unknown): value is object {
94
+ export type MaybeRef<T = any> = T | Ref<T> | Readonly<Ref<T>>;
95
+ export type MaybeRefOrGetter<T = any> = MaybeRef<T> | (() => T);
96
+ function plain(value: unknown): value is Record<PropertyKey, unknown> {
38
97
  if (value === null || typeof value !== "object") return false;
39
98
  const proto = Object.getPrototypeOf(value);
40
99
  return Array.isArray(value) || proto === Object.prototype || proto === null;
41
100
  }
42
101
  const proxies = new WeakMap<object, object>();
102
+ const shallowReactiveMap = new WeakMap<object, object>();
103
+ const readonlyMap = new WeakMap<object, object>();
104
+ const shallowReadonlyMap = new WeakMap<object, object>();
43
105
  const targets = new WeakMap<object, object>();
106
+ const reactiveProxies = new WeakSet<object>();
107
+ const readonlyProxies = new WeakSet<object>();
108
+ const shallowProxies = new WeakSet<object>();
109
+ const rawMarked = new WeakSet<object>();
110
+
111
+ export function markRaw<T extends object>(value: T): T {
112
+ if (
113
+ value !== null &&
114
+ (typeof value === "object" || typeof value === "function")
115
+ ) {
116
+ rawMarked.add(value);
117
+ }
118
+ return value;
119
+ }
120
+ export function toRaw<T>(observed: T): T {
121
+ if (observed === null || typeof observed !== "object") return observed;
122
+ const target = targets.get(observed);
123
+ return target ? toRaw(target as T) : observed;
124
+ }
44
125
  export function isReactive(value: unknown): value is object {
45
- return value !== null && typeof value === "object" && targets.has(value);
126
+ if (value === null || typeof value !== "object") return false;
127
+ if (readonlyProxies.has(value)) {
128
+ const target = targets.get(value);
129
+ return target ? isReactive(target) : false;
130
+ }
131
+ return reactiveProxies.has(value);
132
+ }
133
+ export function isReadonly(value: unknown): boolean {
134
+ return (
135
+ value !== null &&
136
+ typeof value === "object" &&
137
+ (readonlyProxies.has(value) || readonlyRefs.has(value))
138
+ );
139
+ }
140
+ export function isShallow(value: unknown): boolean {
141
+ return (
142
+ value !== null && typeof value === "object" && shallowProxies.has(value)
143
+ );
144
+ }
145
+ export function isProxy(value: unknown): boolean {
146
+ return (
147
+ value !== null &&
148
+ typeof value === "object" &&
149
+ (reactiveProxies.has(value) || readonlyProxies.has(value))
150
+ );
46
151
  }
47
152
  const arrayIndex = (key: PropertyKey) =>
48
153
  typeof key === "string" &&
@@ -51,23 +156,119 @@ const arrayIndex = (key: PropertyKey) =>
51
156
  export type Unwrap<T> =
52
157
  T extends Readonly<Ref<infer V>>
53
158
  ? V
54
- : T extends Function | Date | Map<unknown, unknown> | Set<unknown>
55
- ? T
56
- : T extends readonly unknown[]
57
- ? {
58
- [K in keyof T]: T[K] extends Readonly<Ref<any>>
59
- ? T[K]
60
- : Unwrap<T[K]>;
61
- }
62
- : T extends object
63
- ? { [K in keyof T]: Unwrap<T[K]> }
64
- : T;
159
+ : T extends Map<infer K, infer V>
160
+ ? Map<
161
+ K extends Readonly<Ref<any>> ? K : Unwrap<K>,
162
+ V extends Readonly<Ref<any>> ? V : Unwrap<V>
163
+ >
164
+ : T extends ReadonlyMap<infer K, infer V>
165
+ ? ReadonlyMap<
166
+ K extends Readonly<Ref<any>> ? K : Unwrap<K>,
167
+ V extends Readonly<Ref<any>> ? V : Unwrap<V>
168
+ >
169
+ : T extends Set<infer V>
170
+ ? Set<V extends Readonly<Ref<any>> ? V : Unwrap<V>>
171
+ : T extends ReadonlySet<infer V>
172
+ ? ReadonlySet<V extends Readonly<Ref<any>> ? V : Unwrap<V>>
173
+ : T extends Function | Date | Node | Window
174
+ ? T
175
+ : T extends readonly unknown[]
176
+ ? {
177
+ [K in keyof T]: T[K] extends Readonly<Ref<any>>
178
+ ? T[K]
179
+ : Unwrap<T[K]>;
180
+ }
181
+ : T extends object
182
+ ? { [K in keyof T]: Unwrap<T[K]> }
183
+ : T;
184
+ export type DeepReadonly<T> = T extends
185
+ ((...args: any[]) => any) | Date | RegExp | Node | Window
186
+ ? T
187
+ : T extends Readonly<Ref<infer V>>
188
+ ? Readonly<Ref<DeepReadonly<Unwrap<V>>>>
189
+ : T extends Map<infer K, infer V> | ReadonlyMap<infer K, infer V>
190
+ ? ReadonlyMap<DeepReadonly<K>, DeepReadonly<V>>
191
+ : T extends Set<infer V> | ReadonlySet<infer V>
192
+ ? ReadonlySet<DeepReadonly<V>>
193
+ : T extends readonly unknown[]
194
+ ? { readonly [K in keyof T]: DeepReadonly<T[K]> }
195
+ : T extends object
196
+ ? { readonly [K in keyof T]: DeepReadonly<Unwrap<T[K]>> }
197
+ : T;
198
+ function rawValue<T>(value: T): T {
199
+ return toRaw(value);
200
+ }
201
+ function usePrefetchCell<T>(create: () => T): T {
202
+ const session = peekServerPrefetchSession();
203
+ if (
204
+ session &&
205
+ !activeEffectScope &&
206
+ peekComponentContext()?.active &&
207
+ peekComponentContext()?.mode === "ssr"
208
+ ) {
209
+ if (session.phase === "replay" && session.cursor < session.cells.length) {
210
+ return session.cells[session.cursor++] as T;
211
+ }
212
+ if (session.phase === "collect") {
213
+ const cell = create();
214
+ session.cells.push(cell);
215
+ return cell;
216
+ }
217
+ }
218
+ return create();
219
+ }
220
+ function wrapValue<T>(value: T): T {
221
+ if (value === null || typeof value !== "object") return value;
222
+ const raw: object = unwrapStore(value);
223
+ if (rawMarked.has(value) || rawMarked.has(raw)) return raw as T;
224
+ return plain(raw) || raw instanceof Set || raw instanceof Map
225
+ ? (createReactive(value) as T)
226
+ : value;
227
+ }
228
+ function wrapReadonly<T>(value: T): T {
229
+ if (value === null || typeof value !== "object") return value;
230
+ const raw: object = toRaw(value);
231
+ if (rawMarked.has(value) || rawMarked.has(raw)) return value;
232
+ return plain(raw) || raw instanceof Set || raw instanceof Map
233
+ ? (readonly(value) as T)
234
+ : value;
235
+ }
65
236
  export function reactive<T extends object>(value: T): Unwrap<T> {
66
- if (!plain(value))
67
- throw new TypeError("Native reactive requires a plain object or array");
237
+ return usePrefetchCell(() => createReactive(value));
238
+ }
239
+ function createReactive<T extends object>(value: T): Unwrap<T> {
240
+ if (readonlyProxies.has(value)) return value as Unwrap<T>;
68
241
  const existing = proxies.get(value);
69
242
  if (existing) return existing as Unwrap<T>;
70
- const mutable = createMutable(value, { equals: Object.is });
243
+ const rawTarget = unwrapStore(value);
244
+ if (rawMarked.has(value) || rawMarked.has(rawTarget))
245
+ return rawTarget as Unwrap<T>;
246
+ const cachedRaw = proxies.get(rawTarget);
247
+ if (cachedRaw) return cachedRaw as Unwrap<T>;
248
+ if (rawTarget instanceof Set) {
249
+ if (!Object.isExtensible(rawTarget)) return rawTarget as Unwrap<T>;
250
+ const proxy = createTrackedSet(rawTarget, wrapValue, rawValue);
251
+ reactiveProxies.add(proxy);
252
+ targets.set(proxy, rawTarget);
253
+ proxies.set(rawTarget, proxy);
254
+ proxies.set(proxy, proxy);
255
+ return proxy as Unwrap<T>;
256
+ }
257
+ if (rawTarget instanceof Map) {
258
+ if (!Object.isExtensible(rawTarget)) return rawTarget as Unwrap<T>;
259
+ const proxy = createTrackedMap(rawTarget, wrapValue, rawValue);
260
+ reactiveProxies.add(proxy);
261
+ targets.set(proxy, rawTarget);
262
+ proxies.set(rawTarget, proxy);
263
+ proxies.set(proxy, proxy);
264
+ return proxy as Unwrap<T>;
265
+ }
266
+ if (!plain(rawTarget))
267
+ throw new TypeError(
268
+ "Native reactive requires a plain object, array, Set or Map",
269
+ );
270
+ if (!Object.isExtensible(rawTarget)) return rawTarget as Unwrap<T>;
271
+ const mutable = createMutable(rawTarget, { equals: Object.is });
71
272
  const cached = proxies.get(mutable);
72
273
  if (cached) return cached as Unwrap<T>;
73
274
  const proxy = new Proxy(mutable, {
@@ -75,11 +276,10 @@ export function reactive<T extends object>(value: T): Unwrap<T> {
75
276
  const next = Reflect.get(target, key, receiver);
76
277
  if (isRef(next))
77
278
  return Array.isArray(target) && arrayIndex(key) ? next : next.value;
78
- return plain(next) ? reactive(next) : next;
279
+ return wrapValue(next);
79
280
  },
80
281
  set(target, key, next) {
81
- if (typeof next === "object" && next !== null)
82
- next = targets.get(next) ?? next;
282
+ if (typeof next === "object" && next !== null) next = toRaw(next);
83
283
  return batch(() =>
84
284
  untrack(() => {
85
285
  const previous = Reflect.get(target, key);
@@ -95,35 +295,588 @@ export function reactive<T extends object>(value: T): Unwrap<T> {
95
295
  );
96
296
  },
97
297
  });
98
- targets.set(proxy, mutable);
298
+ reactiveProxies.add(proxy);
299
+ targets.set(proxy, rawTarget);
300
+ proxies.set(rawTarget, proxy);
99
301
  proxies.set(mutable, proxy);
100
302
  proxies.set(proxy, proxy);
101
303
  return proxy as Unwrap<T>;
102
304
  }
305
+
306
+ type ShallowCell = ReturnType<typeof createSignal<number>>;
307
+ type ShallowState = {
308
+ reads: Map<PropertyKey, ShallowCell>;
309
+ has: Map<PropertyKey, ShallowCell>;
310
+ keys?: ShallowCell;
311
+ };
312
+ const shallowStates = new WeakMap<object, ShallowState>();
313
+ const shallowArrayMutations = new Set([
314
+ "push",
315
+ "pop",
316
+ "shift",
317
+ "unshift",
318
+ "splice",
319
+ "sort",
320
+ "reverse",
321
+ "fill",
322
+ "copyWithin",
323
+ ]);
324
+ function getShallowState(target: object): ShallowState {
325
+ let node = shallowStates.get(target);
326
+ if (!node) {
327
+ node = { reads: new Map(), has: new Map() };
328
+ shallowStates.set(target, node);
329
+ }
330
+ return node;
331
+ }
332
+ function trackShallow(
333
+ map: Map<PropertyKey, ShallowCell>,
334
+ key: PropertyKey,
335
+ ): void {
336
+ if (!isTracking()) return;
337
+ let cell = map.get(key);
338
+ if (!cell) map.set(key, (cell = createSignal(0, { equals: false })));
339
+ cell[0]();
340
+ }
341
+ function notifyShallow(cell: ShallowCell | undefined): void {
342
+ cell?.[1]((version) => version + 1);
343
+ }
344
+
345
+ export function shallowReactive<T extends object>(value: T): T {
346
+ return usePrefetchCell(() => createShallowReactive(value));
347
+ }
348
+ function createShallowReactive<T extends object>(value: T): T {
349
+ if (readonlyProxies.has(value)) return value;
350
+ if (shallowProxies.has(value) && reactiveProxies.has(value)) return value;
351
+ const rawTarget = toRaw(value);
352
+ if (
353
+ rawMarked.has(value) ||
354
+ rawMarked.has(rawTarget) ||
355
+ !Object.isExtensible(rawTarget)
356
+ )
357
+ return rawTarget;
358
+ const existing = shallowReactiveMap.get(rawTarget);
359
+ if (existing) return existing as T;
360
+ if (rawTarget instanceof Set) {
361
+ const proxy = createTrackedSet(rawTarget, (v) => v, rawValue);
362
+ reactiveProxies.add(proxy);
363
+ shallowProxies.add(proxy);
364
+ targets.set(proxy, rawTarget);
365
+ shallowReactiveMap.set(rawTarget, proxy);
366
+ shallowReactiveMap.set(proxy, proxy);
367
+ return proxy as unknown as T;
368
+ }
369
+ if (rawTarget instanceof Map) {
370
+ const proxy = createTrackedMap(rawTarget, (v) => v, rawValue);
371
+ reactiveProxies.add(proxy);
372
+ shallowProxies.add(proxy);
373
+ targets.set(proxy, rawTarget);
374
+ shallowReactiveMap.set(rawTarget, proxy);
375
+ shallowReactiveMap.set(proxy, proxy);
376
+ return proxy as unknown as T;
377
+ }
378
+ if (!plain(rawTarget))
379
+ throw new TypeError(
380
+ "Native shallowReactive requires a plain object, array, Set or Map",
381
+ );
382
+ const methods = new Map<PropertyKey, Function>();
383
+ const proxy = new Proxy(rawTarget, {
384
+ get(target, key, receiver) {
385
+ const descriptor = Object.getOwnPropertyDescriptor(target, key);
386
+ if (
387
+ !descriptor?.get &&
388
+ (Object.hasOwn(target, key) ||
389
+ typeof (target as Record<PropertyKey, unknown>)[key] !== "function")
390
+ ) {
391
+ trackShallow(getShallowState(target).reads, key);
392
+ }
393
+ const result = Reflect.get(target, key, receiver);
394
+ if (
395
+ Array.isArray(target) &&
396
+ typeof key === "string" &&
397
+ shallowArrayMutations.has(key) &&
398
+ result === Reflect.get(Array.prototype, key)
399
+ ) {
400
+ let method = methods.get(key);
401
+ if (!method) {
402
+ method = function (this: unknown, ...args: unknown[]) {
403
+ return batch(() =>
404
+ untrack(() => Reflect.apply(result as Function, this, args)),
405
+ );
406
+ };
407
+ methods.set(key, method);
408
+ }
409
+ return method;
410
+ }
411
+ return result;
412
+ },
413
+ has(target, key) {
414
+ trackShallow(getShallowState(target).has, key);
415
+ return Reflect.has(target, key);
416
+ },
417
+ ownKeys(target) {
418
+ if (isTracking()) {
419
+ const node = getShallowState(target);
420
+ if (Array.isArray(target)) trackShallow(node.reads, "length");
421
+ else (node.keys ??= createSignal(0, { equals: false }))[0]();
422
+ }
423
+ return Reflect.ownKeys(target);
424
+ },
425
+ set(target, key, next, receiver) {
426
+ return batch(() =>
427
+ untrack(() => {
428
+ const isArray = Array.isArray(target);
429
+ const prevLength = isArray ? target.length : 0;
430
+ const hadKey = Object.hasOwn(target, key);
431
+ const previous = (target as Record<PropertyKey, unknown>)[key];
432
+ const ok = Reflect.set(target, key, next, receiver);
433
+ if (!ok) return false;
434
+ const node = shallowStates.get(target);
435
+ if (!node) return true;
436
+ if (!hadKey) {
437
+ notifyShallow(node.reads.get(key));
438
+ notifyShallow(node.has.get(key));
439
+ notifyShallow(node.keys);
440
+ if (isArray && target.length !== prevLength) {
441
+ notifyShallow(node.reads.get("length"));
442
+ }
443
+ } else if (!Object.is(previous, next)) {
444
+ notifyShallow(node.reads.get(key));
445
+ if (isArray) {
446
+ if (key === "length" && target.length < prevLength) {
447
+ for (let i = target.length; i < prevLength; i++) {
448
+ const idxKey = String(i);
449
+ notifyShallow(node.reads.get(idxKey));
450
+ notifyShallow(node.has.get(idxKey));
451
+ }
452
+ notifyShallow(node.keys);
453
+ } else if (key !== "length" && target.length !== prevLength) {
454
+ notifyShallow(node.reads.get("length"));
455
+ }
456
+ }
457
+ }
458
+ return true;
459
+ }),
460
+ );
461
+ },
462
+ deleteProperty(target, key) {
463
+ return batch(() =>
464
+ untrack(() => {
465
+ const hadKey = Object.hasOwn(target, key);
466
+ const ok = Reflect.deleteProperty(target, key);
467
+ if (ok && hadKey) {
468
+ const node = shallowStates.get(target);
469
+ if (node) {
470
+ notifyShallow(node.reads.get(key));
471
+ notifyShallow(node.has.get(key));
472
+ notifyShallow(node.keys);
473
+ }
474
+ }
475
+ return ok;
476
+ }),
477
+ );
478
+ },
479
+ });
480
+ reactiveProxies.add(proxy);
481
+ shallowProxies.add(proxy);
482
+ targets.set(proxy, rawTarget);
483
+ shallowReactiveMap.set(rawTarget, proxy);
484
+ shallowReactiveMap.set(proxy, proxy);
485
+ return proxy as T;
486
+ }
487
+
488
+ const readonlySetStates = new WeakMap<
489
+ object,
490
+ { target: Set<unknown>; deep: boolean }
491
+ >();
492
+ function readonlySetState(value: object) {
493
+ const found = readonlySetStates.get(value);
494
+ if (!found) throw new TypeError("Set method requires a native readonly Set");
495
+ return found;
496
+ }
497
+ function readonlySetIterator(
498
+ receiver: Set<unknown>,
499
+ entries: boolean,
500
+ ): SetIterator<any> {
501
+ const s = readonlySetState(receiver);
502
+ return (function* () {
503
+ for (const value of s.target) {
504
+ const wrapped = s.deep ? wrapReadonly(value) : value;
505
+ yield entries ? [wrapped, wrapped] : wrapped;
506
+ }
507
+ return undefined;
508
+ })();
509
+ }
510
+ const readonlySetMethods = {
511
+ get size() {
512
+ return readonlySetState(this).target.size;
513
+ },
514
+ has(this: Set<unknown>, key: unknown) {
515
+ const { target } = readonlySetState(this);
516
+ const raw = toRaw(key);
517
+ return target.has(key) || target.has(raw);
518
+ },
519
+ add() {
520
+ throw new TypeError("Cannot mutate a readonly Set");
521
+ },
522
+ delete() {
523
+ throw new TypeError("Cannot mutate a readonly Set");
524
+ },
525
+ clear() {
526
+ throw new TypeError("Cannot mutate a readonly Set");
527
+ },
528
+ keys(this: Set<unknown>) {
529
+ return readonlySetIterator(this, false);
530
+ },
531
+ values(this: Set<unknown>) {
532
+ return readonlySetIterator(this, false);
533
+ },
534
+ entries(this: Set<unknown>) {
535
+ return readonlySetIterator(this, true);
536
+ },
537
+ [Symbol.iterator](this: Set<unknown>) {
538
+ return readonlySetIterator(this, false);
539
+ },
540
+ forEach(
541
+ this: Set<unknown>,
542
+ callback: (value: unknown, key: unknown, set: Set<unknown>) => void,
543
+ thisArg?: unknown,
544
+ ) {
545
+ if (typeof callback !== "function")
546
+ throw new TypeError("Set callback must be a function");
547
+ const s = readonlySetState(this);
548
+ s.target.forEach((value) => {
549
+ const wrapped = s.deep ? wrapReadonly(value) : value;
550
+ callback.call(thisArg, wrapped, wrapped, this);
551
+ });
552
+ },
553
+ };
554
+ function createReadonlySet(target: Set<unknown>, deep: boolean): Set<unknown> {
555
+ const proxy = new Proxy(target, {
556
+ get(source, key, receiver) {
557
+ return Object.hasOwn(readonlySetMethods, key) && key in source
558
+ ? Reflect.get(readonlySetMethods, key, receiver)
559
+ : Reflect.get(source, key, receiver);
560
+ },
561
+ });
562
+ readonlySetStates.set(proxy, { target, deep });
563
+ return proxy;
564
+ }
565
+
566
+ const readonlyMapStates = new WeakMap<
567
+ object,
568
+ { target: Map<unknown, unknown>; deep: boolean }
569
+ >();
570
+ function readonlyMapState(value: object) {
571
+ const found = readonlyMapStates.get(value);
572
+ if (!found) throw new TypeError("Map method requires a native readonly Map");
573
+ return found;
574
+ }
575
+ function readonlyMapIterator(
576
+ receiver: Map<unknown, unknown>,
577
+ mode: "keys" | "values" | "entries",
578
+ ): MapIterator<any> {
579
+ const s = readonlyMapState(receiver);
580
+ return (function* () {
581
+ for (const [key, value] of s.target.entries()) {
582
+ const wrappedKey = s.deep ? wrapReadonly(key) : key;
583
+ const wrappedValue = s.deep ? wrapReadonly(value) : value;
584
+ yield mode === "keys"
585
+ ? wrappedKey
586
+ : mode === "values"
587
+ ? wrappedValue
588
+ : [wrappedKey, wrappedValue];
589
+ }
590
+ return undefined;
591
+ })();
592
+ }
593
+ const readonlyMapMethods = {
594
+ get size() {
595
+ return readonlyMapState(this).target.size;
596
+ },
597
+ has(this: Map<unknown, unknown>, key: unknown) {
598
+ const { target } = readonlyMapState(this);
599
+ const raw = toRaw(key);
600
+ return target.has(key) || (raw !== key && target.has(raw));
601
+ },
602
+ get(this: Map<unknown, unknown>, key: unknown) {
603
+ const { target, deep } = readonlyMapState(this);
604
+ const raw = toRaw(key);
605
+ let value: unknown;
606
+ if (target.has(key)) {
607
+ value = target.get(key);
608
+ } else if (raw !== key && target.has(raw)) {
609
+ value = target.get(raw);
610
+ } else {
611
+ value = target.get(key);
612
+ }
613
+ return deep ? wrapReadonly(value) : value;
614
+ },
615
+ set() {
616
+ throw new TypeError("Cannot mutate a readonly Map");
617
+ },
618
+ delete() {
619
+ throw new TypeError("Cannot mutate a readonly Map");
620
+ },
621
+ clear() {
622
+ throw new TypeError("Cannot mutate a readonly Map");
623
+ },
624
+ keys(this: Map<unknown, unknown>) {
625
+ return readonlyMapIterator(this, "keys");
626
+ },
627
+ values(this: Map<unknown, unknown>) {
628
+ return readonlyMapIterator(this, "values");
629
+ },
630
+ entries(this: Map<unknown, unknown>) {
631
+ return readonlyMapIterator(this, "entries");
632
+ },
633
+ [Symbol.iterator](this: Map<unknown, unknown>) {
634
+ return readonlyMapIterator(this, "entries");
635
+ },
636
+ forEach(
637
+ this: Map<unknown, unknown>,
638
+ callback: (
639
+ value: unknown,
640
+ key: unknown,
641
+ map: Map<unknown, unknown>,
642
+ ) => void,
643
+ thisArg?: unknown,
644
+ ) {
645
+ if (typeof callback !== "function")
646
+ throw new TypeError("Map callback must be a function");
647
+ const s = readonlyMapState(this);
648
+ s.target.forEach((value, key) => {
649
+ const wrappedKey = s.deep ? wrapReadonly(key) : key;
650
+ const wrappedValue = s.deep ? wrapReadonly(value) : value;
651
+ callback.call(thisArg, wrappedValue, wrappedKey, this);
652
+ });
653
+ },
654
+ };
655
+ function createReadonlyMap(
656
+ target: Map<unknown, unknown>,
657
+ deep: boolean,
658
+ ): Map<unknown, unknown> {
659
+ const proxy = new Proxy(target, {
660
+ get(source, key, receiver) {
661
+ return Object.hasOwn(readonlyMapMethods, key) && key in source
662
+ ? Reflect.get(readonlyMapMethods, key, receiver)
663
+ : Reflect.get(source, key, receiver);
664
+ },
665
+ });
666
+ readonlyMapStates.set(proxy, { target, deep });
667
+ return proxy;
668
+ }
669
+
670
+ function createReadonly<T extends object>(value: T, shallow: boolean): any {
671
+ if (isRef(value)) {
672
+ if (readonlyRefs.has(value) && (!shallow || shallowProxies.has(value))) {
673
+ return value;
674
+ }
675
+ const cache = shallow ? shallowReadonlyMap : readonlyMap;
676
+ const cachedRef = cache.get(value);
677
+ if (cachedRef) return cachedRef;
678
+ const roRef = new Ref(() =>
679
+ shallow ? value.value : wrapReadonly(value.value),
680
+ );
681
+ if (shallow) shallowProxies.add(roRef);
682
+ targets.set(roRef, value);
683
+ cache.set(value, roRef);
684
+ return roRef;
685
+ }
686
+ if (!shallow && readonlyProxies.has(value) && !shallowProxies.has(value)) {
687
+ return value;
688
+ }
689
+ if (shallow && readonlyProxies.has(value) && shallowProxies.has(value)) {
690
+ return value;
691
+ }
692
+ const underlying = readonlyProxies.has(value)
693
+ ? ((targets.get(value) as T) ?? value)
694
+ : value;
695
+ const rawCandidate = toRaw(underlying);
696
+ if (
697
+ rawMarked.has(value) ||
698
+ rawMarked.has(underlying) ||
699
+ rawMarked.has(rawCandidate) ||
700
+ !Object.isExtensible(rawCandidate)
701
+ ) {
702
+ return value;
703
+ }
704
+ const cache = shallow ? shallowReadonlyMap : readonlyMap;
705
+ const existing = cache.get(underlying);
706
+ if (existing) return existing;
707
+ if (rawCandidate instanceof Set) {
708
+ const proxy = createReadonlySet(
709
+ underlying as unknown as Set<unknown>,
710
+ !shallow,
711
+ );
712
+ readonlyProxies.add(proxy);
713
+ if (shallow) shallowProxies.add(proxy);
714
+ targets.set(proxy, underlying);
715
+ cache.set(underlying, proxy);
716
+ cache.set(proxy, proxy);
717
+ return proxy;
718
+ }
719
+ if (rawCandidate instanceof Map) {
720
+ const proxy = createReadonlyMap(
721
+ underlying as unknown as Map<unknown, unknown>,
722
+ !shallow,
723
+ );
724
+ readonlyProxies.add(proxy);
725
+ if (shallow) shallowProxies.add(proxy);
726
+ targets.set(proxy, underlying);
727
+ cache.set(underlying, proxy);
728
+ cache.set(proxy, proxy);
729
+ return proxy;
730
+ }
731
+ if (!plain(rawCandidate))
732
+ throw new TypeError(
733
+ "Native readonly requires a plain object, array, Set or Map",
734
+ );
735
+ const proxy = new Proxy(underlying, {
736
+ get(target, key, receiver) {
737
+ const next = Reflect.get(target, key, receiver);
738
+ if (shallow) return next;
739
+ if (isRef(next)) {
740
+ return Array.isArray(target) && arrayIndex(key)
741
+ ? readonly(next)
742
+ : wrapReadonly(next.value);
743
+ }
744
+ return wrapReadonly(next);
745
+ },
746
+ set(_target, key) {
747
+ throw new TypeError(
748
+ `Cannot assign to read only property '${String(key)}'`,
749
+ );
750
+ },
751
+ deleteProperty(_target, key) {
752
+ throw new TypeError(
753
+ `Cannot delete property '${String(key)}' of a readonly object`,
754
+ );
755
+ },
756
+ defineProperty(_target, key) {
757
+ throw new TypeError(
758
+ `Cannot define property '${String(key)}' on a readonly object`,
759
+ );
760
+ },
761
+ });
762
+ readonlyProxies.add(proxy);
763
+ if (shallow) shallowProxies.add(proxy);
764
+ targets.set(proxy, underlying);
765
+ cache.set(underlying, proxy);
766
+ cache.set(proxy, proxy);
767
+ return proxy;
768
+ }
769
+
770
+ export function readonly<T extends object>(value: T): DeepReadonly<T> {
771
+ return createReadonly(value, false);
772
+ }
773
+ export function shallowReadonly<T extends object>(value: T): Readonly<T> {
774
+ return createReadonly(value, true);
775
+ }
776
+
103
777
  export function ref<T>(value: Ref<T>): Ref<T>;
104
778
  export function ref<T>(value: T): Ref<Unwrap<T>>;
105
- export function ref<T>(value: T | Ref<T>): Ref<any> {
779
+ export function ref<T = any>(): Ref<T | undefined>;
780
+ export function ref<T>(value?: T | Ref<T>): Ref<any> {
781
+ return usePrefetchCell(() => createRef(value));
782
+ }
783
+ function createRef<T>(value?: T | Ref<T>): Ref<any> {
106
784
  if (isRef(value)) return value;
107
- const convert = (next: T): T => (plain(next) ? (reactive(next) as T) : next);
785
+ const convert = wrapValue<T>;
786
+ let forceTrigger = false;
108
787
  const [read, write] = createSignal(convert(value as T), {
109
- equals: Object.is,
788
+ equals: (prev, next) => !forceTrigger && Object.is(prev, next),
110
789
  });
111
- return new Ref(read, (next) => write(() => convert(next)));
790
+ const refObject = new Ref(read, (next) => write(() => convert(next)));
791
+ refTriggers.set(refObject, () => {
792
+ forceTrigger = true;
793
+ try {
794
+ refTriggerVersions.set(
795
+ refObject,
796
+ (refTriggerVersions.get(refObject) ?? 0) + 1,
797
+ );
798
+ write((current) => current);
799
+ } finally {
800
+ forceTrigger = false;
801
+ }
802
+ });
803
+ return refObject;
112
804
  }
113
- /** Keep external snapshots intact; only replacing .value notifies this ref. */
805
+ /** Keep external snapshots intact; only replacing .value or triggerRef notifies this ref. */
114
806
  export function shallowRef<T extends Readonly<Ref<any>>>(value: T): T;
115
807
  export function shallowRef<T>(value: T): Ref<T>;
116
808
  export function shallowRef<T = any>(): Ref<T | undefined>;
117
809
  export function shallowRef(value?: unknown): Ref<any> {
810
+ return usePrefetchCell(() => createShallowRef(value));
811
+ }
812
+ function createShallowRef(value?: unknown): Ref<any> {
118
813
  if (isRef(value)) return value;
119
- const [read, write] = createSignal(value, { equals: Object.is });
120
- return new Ref(read, (next) => write(() => next));
814
+ let forceTrigger = false;
815
+ const [read, write] = createSignal<unknown>(value, {
816
+ equals: (prev, next) => !forceTrigger && Object.is(prev, next),
817
+ });
818
+ const refObject = new Ref(read, (next) => write(() => next));
819
+ shallowProxies.add(refObject);
820
+ refTriggers.set(refObject, () => {
821
+ forceTrigger = true;
822
+ try {
823
+ refTriggerVersions.set(
824
+ refObject,
825
+ (refTriggerVersions.get(refObject) ?? 0) + 1,
826
+ );
827
+ write((current: unknown) => current);
828
+ } finally {
829
+ forceTrigger = false;
830
+ }
831
+ });
832
+ return refObject;
833
+ }
834
+ export function triggerRef(target: Readonly<Ref<any>>): void {
835
+ if (!isRef(target)) throw new TypeError("triggerRef requires a native ref");
836
+ refTriggers.get(target)?.();
837
+ }
838
+ export type CustomRefFactory<T> = (
839
+ track: () => void,
840
+ trigger: () => void,
841
+ ) => {
842
+ get: () => T;
843
+ set: (value: T) => void;
844
+ };
845
+ export function customRef<T>(factory: CustomRefFactory<T>): Ref<T> {
846
+ if (typeof factory !== "function")
847
+ throw new TypeError("customRef requires a factory function");
848
+ const [readVersion, writeVersion] = createSignal(0, { equals: false });
849
+ let refObject!: Ref<T>;
850
+ const track = () => {
851
+ readVersion();
852
+ };
853
+ const trigger = () => {
854
+ refTriggerVersions.set(
855
+ refObject,
856
+ (refTriggerVersions.get(refObject) ?? 0) + 1,
857
+ );
858
+ writeVersion((v) => v + 1);
859
+ };
860
+ const { get, set } = factory(track, trigger);
861
+ if (typeof get !== "function" || typeof set !== "function")
862
+ throw new TypeError("customRef factory must return get and set functions");
863
+ refObject = new Ref(
864
+ () => get(),
865
+ (value) => set(value),
866
+ );
867
+ refTriggers.set(refObject, trigger);
868
+ return refObject;
121
869
  }
122
870
  /** Unwrap native refs without invoking ordinary function values. */
123
871
  export function unref<T>(value: T): T extends Readonly<Ref<infer V>> ? V : T;
124
872
  export function unref(value: unknown): unknown {
125
873
  return isRef(value) ? value.value : value;
126
874
  }
875
+ /** Normalize values, refs, and zero-arg getters to their underlying value. */
876
+ export function toValue<T>(source: MaybeRefOrGetter<T>): T;
877
+ export function toValue(source: unknown): unknown {
878
+ return typeof source === "function" ? source() : unref(source);
879
+ }
127
880
  export type ToRef<T> = [T] extends [Readonly<Ref<any>>] ? T : Ref<T>;
128
881
  export function toRef<T extends Readonly<Ref<any>>>(value: T): T;
129
882
  export function toRef<T>(getter: () => T): Readonly<Ref<T>>;
@@ -159,7 +912,7 @@ export function toRef(
159
912
  },
160
913
  );
161
914
  }
162
- return ref(source);
915
+ return createRef(source);
163
916
  }
164
917
  /** Link the currently enumerable string properties, preserving array holes. */
165
918
  export type ToRefs<T = any> = { [K in keyof T]: ToRef<T[K]> };
@@ -178,6 +931,41 @@ export function toRefs<T extends object>(object: T): ToRefs<T> {
178
931
  }
179
932
  return result;
180
933
  }
934
+ type DistributeRef<T> = T extends Readonly<Ref<infer V>> ? V : T;
935
+ export type ShallowUnwrapRef<T> = {
936
+ [K in keyof T]: DistributeRef<T[K]>;
937
+ };
938
+ const proxyRefsCache = new WeakMap<object, object>();
939
+ export function proxyRefs<T extends object>(
940
+ objectWithRefs: T,
941
+ ): ShallowUnwrapRef<T> {
942
+ if (objectWithRefs === null || typeof objectWithRefs !== "object") {
943
+ throw new TypeError("proxyRefs requires an object");
944
+ }
945
+ if (isReactive(objectWithRefs)) {
946
+ return objectWithRefs as unknown as ShallowUnwrapRef<T>;
947
+ }
948
+ const existing = proxyRefsCache.get(objectWithRefs);
949
+ if (existing) {
950
+ return existing as ShallowUnwrapRef<T>;
951
+ }
952
+ const proxy = new Proxy(objectWithRefs, {
953
+ get(target, key, receiver) {
954
+ return unref(Reflect.get(target, key, receiver));
955
+ },
956
+ set(target, key, value, receiver) {
957
+ const oldValue: unknown = Reflect.get(target, key, target);
958
+ if (isRef(oldValue) && !isRef(value)) {
959
+ oldValue.value = value;
960
+ return true;
961
+ }
962
+ return Reflect.set(target, key, value, receiver);
963
+ },
964
+ });
965
+ proxyRefsCache.set(objectWithRefs, proxy);
966
+ proxyRefsCache.set(proxy, proxy);
967
+ return proxy as unknown as ShallowUnwrapRef<T>;
968
+ }
181
969
  export function computed<T>(
182
970
  getter: (previous: T | undefined) => T,
183
971
  ): Readonly<Ref<T>>;
@@ -205,128 +993,360 @@ export function computed<T>(
205
993
  );
206
994
  }
207
995
  export type WatchSource<T = unknown> = Readonly<Ref<T>> | (() => T);
208
- export type WatchOptions = { flush: "sync"; immediate?: boolean };
996
+ export type WatchOptions = {
997
+ flush: "sync";
998
+ immediate?: boolean;
999
+ deep?: boolean | number;
1000
+ once?: boolean;
1001
+ };
1002
+ export type WatchStopHandle = () => void;
1003
+ export interface WatchHandle extends WatchStopHandle {
1004
+ pause: () => void;
1005
+ resume: () => void;
1006
+ stop: () => void;
1007
+ }
1008
+ export type WatchCallback<V = any, OV = any> = (
1009
+ value: V,
1010
+ previous: OV,
1011
+ onCleanup: (fn: () => void) => void,
1012
+ ) => void;
1013
+ type MapWatchSources<T> = {
1014
+ -readonly [K in keyof T]: T[K] extends WatchSource<infer V>
1015
+ ? V
1016
+ : T[K] extends object
1017
+ ? T[K]
1018
+ : never;
1019
+ };
1020
+
1021
+ let activeWatcherCleanup: ((fn: () => void) => void) | undefined;
1022
+
1023
+ export function onWatcherCleanup(
1024
+ cleanupFn: () => void,
1025
+ failSilently = false,
1026
+ ): void {
1027
+ if (typeof cleanupFn !== "function")
1028
+ throw new TypeError("Watcher cleanup must be a function");
1029
+ if (activeWatcherCleanup) {
1030
+ activeWatcherCleanup(cleanupFn);
1031
+ } else if (!failSilently) {
1032
+ throw new Error("onWatcherCleanup requires an active watcher");
1033
+ }
1034
+ }
1035
+
1036
+ type DepSnapshot = Array<{ node: Trackable; version: number }>;
1037
+ function captureDeps(fn: () => void): DepSnapshot {
1038
+ const nodes = collectDeps(fn, undefined, true);
1039
+ return nodes.map((node) => ({ node, version: node.version }));
1040
+ }
1041
+ function depsChanged(prev: DepSnapshot, next: DepSnapshot): boolean {
1042
+ if (prev.length !== next.length) return true;
1043
+ for (let i = 0; i < next.length; i++) {
1044
+ if (
1045
+ prev[i]!.node !== next[i]!.node ||
1046
+ prev[i]!.version !== next[i]!.version
1047
+ )
1048
+ return true;
1049
+ }
1050
+ return false;
1051
+ }
1052
+ function traverse(
1053
+ value: unknown,
1054
+ depth = Infinity,
1055
+ seen = new Set<unknown>(),
1056
+ ): unknown {
1057
+ if (
1058
+ depth <= 0 ||
1059
+ value === null ||
1060
+ typeof value !== "object" ||
1061
+ rawMarked.has(value) ||
1062
+ rawMarked.has(toRaw(value))
1063
+ )
1064
+ return value;
1065
+ if (seen.has(value)) return value;
1066
+ seen.add(value);
1067
+ depth--;
1068
+ if (isRef(value)) {
1069
+ const inner = value.value;
1070
+ if (depth > 0) traverse(inner, depth, seen);
1071
+ } else if (Array.isArray(value)) {
1072
+ for (let i = 0; i < value.length; i++) {
1073
+ traverse(value[i], depth, seen);
1074
+ }
1075
+ } else if (value instanceof Set) {
1076
+ value.forEach((entry) => {
1077
+ traverse(entry, depth, seen);
1078
+ });
1079
+ } else if (value instanceof Map) {
1080
+ value.forEach((entry, key) => {
1081
+ traverse(key, depth, seen);
1082
+ traverse(entry, depth, seen);
1083
+ });
1084
+ } else if (plain(value)) {
1085
+ for (const key in value) {
1086
+ traverse(value[key], depth, seen);
1087
+ }
1088
+ for (const symbol of Object.getOwnPropertySymbols(value)) {
1089
+ if (Object.prototype.propertyIsEnumerable.call(value, symbol)) {
1090
+ traverse(value[symbol], depth, seen);
1091
+ }
1092
+ }
1093
+ }
1094
+ return value;
1095
+ }
1096
+ function createWatchHandle(
1097
+ stop: () => void,
1098
+ pause: () => void,
1099
+ resume: () => void,
1100
+ ): WatchHandle {
1101
+ const handle = (() => {
1102
+ stop();
1103
+ }) as WatchHandle;
1104
+ handle.stop = stop;
1105
+ handle.pause = pause;
1106
+ handle.resume = resume;
1107
+ return handle;
1108
+ }
1109
+
209
1110
  export function watch<T>(
210
1111
  source: WatchSource<T>,
211
- callback: (
212
- value: T,
213
- previous: T | undefined,
214
- onCleanup: (fn: () => void) => void,
215
- ) => void,
1112
+ callback: WatchCallback<T, T | undefined>,
216
1113
  options: WatchOptions,
217
- ): () => void;
1114
+ ): WatchHandle;
218
1115
  export function watch<T extends readonly unknown[]>(
219
1116
  source: { [K in keyof T]: WatchSource<T[K]> },
220
- callback: (
221
- value: T,
222
- previous: T | undefined,
223
- onCleanup: (fn: () => void) => void,
224
- ) => void,
1117
+ callback: WatchCallback<T, T | undefined>,
1118
+ options: WatchOptions,
1119
+ ): WatchHandle;
1120
+ export function watch<T extends readonly (WatchSource<unknown> | object)[]>(
1121
+ source: readonly [...T],
1122
+ callback: WatchCallback<MapWatchSources<T>, MapWatchSources<T> | undefined>,
225
1123
  options: WatchOptions,
226
- ): () => void;
1124
+ ): WatchHandle;
1125
+ export function watch<T extends object>(
1126
+ source: T,
1127
+ callback: WatchCallback<T, T | undefined>,
1128
+ options: WatchOptions,
1129
+ ): WatchHandle;
227
1130
  export function watch(
228
- source: WatchSource<any> | readonly WatchSource<any>[],
229
- callback: (
230
- value: any,
231
- previous: any,
232
- onCleanup: (fn: () => void) => void,
233
- ) => void,
1131
+ source: WatchSource<any> | object | readonly (WatchSource<any> | object)[],
1132
+ callback: WatchCallback<any, any>,
234
1133
  options: WatchOptions,
235
- ): () => void {
1134
+ ): WatchHandle {
236
1135
  if (
237
1136
  !options ||
238
1137
  options.flush !== "sync" ||
239
- Object.keys(options).some((key) => key !== "flush" && key !== "immediate")
1138
+ Object.keys(options).some(
1139
+ (key) =>
1140
+ key !== "flush" &&
1141
+ key !== "immediate" &&
1142
+ key !== "deep" &&
1143
+ key !== "once",
1144
+ ) ||
1145
+ (options.immediate !== undefined &&
1146
+ typeof options.immediate !== "boolean") ||
1147
+ (options.once !== undefined && typeof options.once !== "boolean") ||
1148
+ (options.deep !== undefined &&
1149
+ typeof options.deep !== "boolean" &&
1150
+ (typeof options.deep !== "number" || Number.isNaN(options.deep)))
240
1151
  )
241
1152
  throw new TypeError(
242
- "Native watch supports only flush:'sync' and immediate",
1153
+ "Native watch supports only flush:'sync', immediate, deep, and once",
243
1154
  );
244
1155
  const sources = Array.isArray(source) ? source : [source];
245
- if (sources.some((item) => !isRef(item) && typeof item !== "function"))
246
- throw new TypeError("Native watch requires refs or getters");
1156
+ if (
1157
+ sources.some(
1158
+ (item) => !isRef(item) && !isReactive(item) && typeof item !== "function",
1159
+ )
1160
+ )
1161
+ throw new TypeError(
1162
+ "Native watch requires refs, reactive objects, or getters",
1163
+ );
247
1164
  const outer = getOwner();
248
1165
  if (outer?.disposed)
249
1166
  throw new Error("Cannot watch from a disposed native owner");
250
1167
  const reportError = captureWatchErrorHandler();
1168
+ const depths = sources.map((item) => {
1169
+ if (typeof options.deep === "number")
1170
+ return options.deep <= 0 ? 0 : options.deep;
1171
+ if (options.deep === true) return Infinity;
1172
+ if (options.deep === false) return isReactive(item) ? 1 : 0;
1173
+ return isReactive(item) ? (isShallow(item) ? 1 : Infinity) : 0;
1174
+ });
251
1175
  let stop!: () => void;
1176
+ let pause!: () => void;
1177
+ let resume!: () => void;
252
1178
  createRoot((dispose) => {
253
1179
  stop = dispose;
254
1180
  let previous: any[] | undefined;
1181
+ let previousVersions: number[] | undefined;
1182
+ let previousDepSnapshots: Array<DepSnapshot | undefined> | undefined;
255
1183
  let reading = false;
256
- const cleanups: Array<() => void> = [];
257
1184
  let active = true;
1185
+ let paused = false;
1186
+ let dirtyWhilePaused = false;
1187
+ let lastDeps: Array<Parameters<typeof trackDependency>[0]> = [];
1188
+ const [readResume, writeResume] = createSignal(0, { equals: false });
1189
+ const cleanups: Array<() => void> = [];
1190
+ pause = () => {
1191
+ if (active) paused = true;
1192
+ };
1193
+ resume = () => {
1194
+ if (!active || !paused) return;
1195
+ paused = false;
1196
+ if (dirtyWhilePaused) {
1197
+ dirtyWhilePaused = false;
1198
+ writeResume((v) => v + 1);
1199
+ }
1200
+ };
258
1201
  const clean = () => {
259
1202
  let failed = false;
260
1203
  let failure: unknown;
261
- for (const fn of cleanups.splice(0)) {
262
- try {
263
- untrack(() =>
264
- reportError ? invokeWatch(reportError, "watch cleanup", fn) : fn(),
265
- );
266
- } catch (error) {
267
- if (!failed) failure = error;
268
- failed = true;
1204
+ const prevCleanup = activeWatcherCleanup;
1205
+ activeWatcherCleanup = undefined;
1206
+ try {
1207
+ for (const fn of cleanups.splice(0)) {
1208
+ try {
1209
+ untrack(() =>
1210
+ reportError
1211
+ ? invokeWatch(reportError, "watch cleanup", fn)
1212
+ : fn(),
1213
+ );
1214
+ } catch (error) {
1215
+ if (!failed) failure = error;
1216
+ failed = true;
1217
+ }
269
1218
  }
1219
+ } finally {
1220
+ activeWatcherCleanup = prevCleanup;
270
1221
  }
271
1222
  if (failed) throw failure;
272
1223
  };
273
1224
  onCleanup(() => {
274
1225
  active = false;
1226
+ paused = false;
1227
+ dirtyWhilePaused = false;
275
1228
  clean();
276
1229
  });
277
1230
  createComputed(() => {
1231
+ readResume();
278
1232
  // Getter reporting may write its source; callback feedback remains reentrant.
279
- if (reportError && reading) return;
280
- let values: any[];
1233
+ if ((reportError && reading) || !active) return;
1234
+ if (paused) {
1235
+ dirtyWhilePaused = true;
1236
+ for (const dep of lastDeps) {
1237
+ dep.validate?.();
1238
+ trackDependency(dep);
1239
+ }
1240
+ return;
1241
+ }
1242
+ let values!: any[];
1243
+ const depSnapshots: Array<DepSnapshot | undefined> = [];
1244
+ const prevCleanup = activeWatcherCleanup;
1245
+ activeWatcherCleanup = undefined;
281
1246
  reading = true;
282
1247
  try {
283
- values = sources.map((item) =>
284
- isRef(item)
285
- ? item.value
286
- : reportError
287
- ? invokeWatch(reportError, "watch getter", item)
288
- : item(),
289
- );
1248
+ lastDeps = collectDeps(
1249
+ () => {
1250
+ values = sources.map((item, i) => {
1251
+ const depth = depths[i]!;
1252
+ let value: any;
1253
+ if (depth > 0) {
1254
+ depSnapshots[i] = captureDeps(() => {
1255
+ value = isRef(item)
1256
+ ? item.value
1257
+ : typeof item === "function"
1258
+ ? reportError
1259
+ ? invokeWatch(reportError, "watch getter", item)
1260
+ : item()
1261
+ : item;
1262
+ traverse(value, depth);
1263
+ });
1264
+ } else {
1265
+ value = isRef(item)
1266
+ ? item.value
1267
+ : typeof item === "function"
1268
+ ? reportError
1269
+ ? invokeWatch(reportError, "watch getter", item)
1270
+ : item()
1271
+ : item;
1272
+ }
1273
+ return value;
1274
+ });
1275
+ },
1276
+ undefined,
1277
+ true,
1278
+ ) as Array<Parameters<typeof trackDependency>[0]>;
290
1279
  } finally {
291
1280
  reading = false;
1281
+ activeWatcherCleanup = prevCleanup;
292
1282
  }
1283
+ const versions = sources.map((item) =>
1284
+ isRef(item) ? (refTriggerVersions.get(item) ?? 0) : 0,
1285
+ );
293
1286
  if (
294
1287
  previous &&
295
- values.every((value, i) => Object.is(value, previous![i]))
1288
+ values.every(
1289
+ (value, i) =>
1290
+ Object.is(value, previous![i]) &&
1291
+ versions[i] === previousVersions![i] &&
1292
+ (depths[i] === 0 ||
1293
+ !depsChanged(previousDepSnapshots![i]!, depSnapshots[i]!)),
1294
+ )
296
1295
  )
297
1296
  return;
298
1297
  const old = previous;
299
1298
  previous = values;
1299
+ previousVersions = versions;
1300
+ previousDepSnapshots = depSnapshots;
300
1301
  if (!old && !options.immediate) return;
301
1302
  untrack(() => {
302
1303
  clean();
303
1304
  if (!active) return;
304
- const invoke = () =>
305
- callback(
306
- Array.isArray(source) ? values : values[0],
307
- Array.isArray(source) ? old : old?.[0],
308
- (fn) => {
309
- if (typeof fn !== "function")
310
- throw new TypeError("Watcher cleanup must be a function");
311
- if (active) cleanups.push(fn);
312
- else if (reportError)
313
- invokeWatch(reportError, "watch cleanup", fn);
314
- else fn();
315
- },
316
- );
317
- if (reportError) invokeWatch(reportError, "watch callback", invoke);
318
- else invoke();
1305
+ const registerCleanup = (fn: () => void) => {
1306
+ if (typeof fn !== "function")
1307
+ throw new TypeError("Watcher cleanup must be a function");
1308
+ if (active) cleanups.push(fn);
1309
+ else if (reportError) invokeWatch(reportError, "watch cleanup", fn);
1310
+ else fn();
1311
+ };
1312
+ const invoke = () => {
1313
+ const previousCleanup = activeWatcherCleanup;
1314
+ activeWatcherCleanup = registerCleanup;
1315
+ try {
1316
+ return callback(
1317
+ Array.isArray(source) ? values : values[0],
1318
+ Array.isArray(source) ? old : old?.[0],
1319
+ registerCleanup,
1320
+ );
1321
+ } finally {
1322
+ activeWatcherCleanup = previousCleanup;
1323
+ }
1324
+ };
1325
+ try {
1326
+ if (reportError) invokeWatch(reportError, "watch callback", invoke);
1327
+ else invoke();
1328
+ } catch (error) {
1329
+ if (options.once && active) {
1330
+ try {
1331
+ stop();
1332
+ } catch {
1333
+ /* Preserve callback failure when once-stop cleanup also throws. */
1334
+ }
1335
+ }
1336
+ throw error;
1337
+ }
1338
+ if (options.once && active) stop();
319
1339
  });
320
1340
  });
321
1341
  });
322
1342
  if (outer) onCleanup(stop);
323
- return stop;
1343
+ return createWatchHandle(stop, pause, resume);
324
1344
  }
325
1345
 
326
1346
  /** Synchronously track an owned effect; no component render scheduler is implied. */
327
1347
  export function watchSyncEffect(
328
1348
  effect: (onCleanup: (fn: () => void) => void) => void,
329
- ): () => void {
1349
+ ): WatchHandle {
330
1350
  if (typeof effect !== "function")
331
1351
  throw new TypeError("Watcher effect must be a function");
332
1352
  const outer = getOwner();
@@ -334,57 +1354,1340 @@ export function watchSyncEffect(
334
1354
  throw new Error("Cannot watch from a disposed native owner");
335
1355
  const reportError = captureWatchErrorHandler();
336
1356
  let stop!: () => void;
1357
+ let pause!: () => void;
1358
+ let resume!: () => void;
337
1359
  createRoot((dispose) => {
338
1360
  stop = dispose;
339
1361
  let active = true;
340
1362
  let running = false;
1363
+ let paused = false;
1364
+ let dirtyWhilePaused = false;
1365
+ let lastDeps: Array<Parameters<typeof trackDependency>[0]> = [];
1366
+ const [readResume, writeResume] = createSignal(0, { equals: false });
341
1367
  const cleanups: Array<() => void> = [];
1368
+ pause = () => {
1369
+ if (active) paused = true;
1370
+ };
1371
+ resume = () => {
1372
+ if (!active || !paused) return;
1373
+ paused = false;
1374
+ if (dirtyWhilePaused) {
1375
+ dirtyWhilePaused = false;
1376
+ writeResume((v) => v + 1);
1377
+ }
1378
+ };
342
1379
  const clean = () => {
343
1380
  let failed = false;
344
1381
  let failure: unknown;
345
- for (const fn of cleanups.splice(0)) {
346
- try {
347
- untrack(() =>
348
- reportError ? invokeWatch(reportError, "watch cleanup", fn) : fn(),
349
- );
350
- } catch (error) {
351
- if (!failed) failure = error;
352
- failed = true;
1382
+ const prevCleanup = activeWatcherCleanup;
1383
+ activeWatcherCleanup = undefined;
1384
+ try {
1385
+ for (const fn of cleanups.splice(0)) {
1386
+ try {
1387
+ untrack(() =>
1388
+ reportError
1389
+ ? invokeWatch(reportError, "watch cleanup", fn)
1390
+ : fn(),
1391
+ );
1392
+ } catch (error) {
1393
+ if (!failed) failure = error;
1394
+ failed = true;
1395
+ }
353
1396
  }
1397
+ } finally {
1398
+ activeWatcherCleanup = prevCleanup;
354
1399
  }
355
1400
  if (failed) throw failure;
356
1401
  };
357
1402
  onCleanup(() => {
358
1403
  active = false;
1404
+ paused = false;
1405
+ dirtyWhilePaused = false;
359
1406
  clean();
360
1407
  });
361
1408
  createComputed(() => {
1409
+ readResume();
362
1410
  if (running || !active) return;
1411
+ if (paused) {
1412
+ dirtyWhilePaused = true;
1413
+ for (const dep of lastDeps) {
1414
+ dep.validate?.();
1415
+ trackDependency(dep);
1416
+ }
1417
+ return;
1418
+ }
363
1419
  running = true;
364
1420
  try {
365
1421
  untrack(clean);
366
1422
  if (!active) return;
367
- const invoke = () =>
368
- effect((fn) => {
369
- if (typeof fn !== "function")
370
- throw new TypeError("Watcher cleanup must be a function");
371
- if (active) cleanups.push(fn);
372
- });
373
- if (reportError) invokeWatch(reportError, "watch effect", invoke);
374
- else invoke();
1423
+ const registerCleanup = (fn: () => void) => {
1424
+ if (typeof fn !== "function")
1425
+ throw new TypeError("Watcher cleanup must be a function");
1426
+ if (active) cleanups.push(fn);
1427
+ };
1428
+ const invoke = () => {
1429
+ const previousCleanup = activeWatcherCleanup;
1430
+ activeWatcherCleanup = registerCleanup;
1431
+ try {
1432
+ return effect(registerCleanup);
1433
+ } finally {
1434
+ activeWatcherCleanup = previousCleanup;
1435
+ }
1436
+ };
1437
+ lastDeps = collectDeps(
1438
+ () => {
1439
+ if (reportError) invokeWatch(reportError, "watch effect", invoke);
1440
+ else invoke();
1441
+ },
1442
+ undefined,
1443
+ true,
1444
+ ) as Array<Parameters<typeof trackDependency>[0]>;
1445
+ } catch (error) {
1446
+ try {
1447
+ untrack(clean);
1448
+ } catch {
1449
+ /* Preserve the effect failure. */
1450
+ }
1451
+ throw error;
1452
+ } finally {
1453
+ running = false;
1454
+ }
1455
+ });
1456
+ });
1457
+ if (outer) onCleanup(stop);
1458
+ return createWatchHandle(stop, pause, resume);
1459
+ }
1460
+
1461
+ let activeEffectScope: EffectScope | undefined;
1462
+ const componentScopes = new WeakMap<ComponentContext, EffectScope>();
1463
+ const scopeCleanups = new WeakMap<EffectScope, Array<() => void>>();
1464
+
1465
+ function runEffectScope<T>(
1466
+ scope: EffectScope,
1467
+ scopeOwner: Owner,
1468
+ fn: () => T,
1469
+ ): T {
1470
+ const prev = activeEffectScope;
1471
+ activeEffectScope = scope;
1472
+ try {
1473
+ return runWithOwner(scopeOwner, fn);
1474
+ } finally {
1475
+ activeEffectScope = prev;
1476
+ }
1477
+ }
1478
+
1479
+ export class EffectScope {
1480
+ private isActive = true;
1481
+ private readonly owner: Owner;
1482
+ private readonly disposeOwner: () => void;
1483
+ private readonly scopes: Set<EffectScope> = new Set();
1484
+ private readonly parent?: EffectScope;
1485
+
1486
+ constructor(detached = false) {
1487
+ let disposeOwner!: () => void;
1488
+ let scopeOwner!: Owner;
1489
+ createRoot((dispose) => {
1490
+ disposeOwner = dispose;
1491
+ scopeOwner = getOwner()!;
1492
+ });
1493
+ this.disposeOwner = disposeOwner;
1494
+ this.owner = scopeOwner;
1495
+ scopeCleanups.set(this, []);
1496
+ if (!detached) {
1497
+ const parent = getCurrentScope();
1498
+ if (parent && parent.active) {
1499
+ this.parent = parent;
1500
+ parent.scopes.add(this);
1501
+ } else {
1502
+ const outer = getOwner();
1503
+ if (outer && !outer.disposed) {
1504
+ onCleanup(() => this.stop(true));
1505
+ }
1506
+ }
1507
+ }
1508
+ }
1509
+
1510
+ get active(): boolean {
1511
+ return this.isActive;
1512
+ }
1513
+
1514
+ run<T>(fn: () => T): T | undefined {
1515
+ if (!this.isActive) return undefined;
1516
+ return runEffectScope(this, this.owner, fn);
1517
+ }
1518
+
1519
+ stop(fromParent = false): void {
1520
+ if (!this.isActive) return;
1521
+ this.isActive = false;
1522
+ let failed = false;
1523
+ let failure: unknown;
1524
+ try {
1525
+ this.disposeOwner();
1526
+ } catch (error) {
1527
+ failed = true;
1528
+ failure = error;
1529
+ }
1530
+ for (const child of Array.from(this.scopes)) {
1531
+ this.scopes.delete(child);
1532
+ try {
1533
+ child.stop(true);
375
1534
  } catch (error) {
376
- if (!reportError)
1535
+ if (!failed) failure = error;
1536
+ failed = true;
1537
+ }
1538
+ }
1539
+ const cleanups = scopeCleanups.get(this);
1540
+ if (cleanups) {
1541
+ for (const cleanup of cleanups.splice(0)) {
1542
+ try {
1543
+ untrack(cleanup);
1544
+ } catch (error) {
1545
+ if (!failed) failure = error;
1546
+ failed = true;
1547
+ }
1548
+ }
1549
+ }
1550
+ if (!fromParent && this.parent) {
1551
+ this.parent.scopes.delete(this);
1552
+ }
1553
+ if (failed) throw failure;
1554
+ }
1555
+ }
1556
+
1557
+ export function effectScope(detached?: boolean): EffectScope {
1558
+ return new EffectScope(detached);
1559
+ }
1560
+
1561
+ export function getCurrentScope(): EffectScope | undefined {
1562
+ if (activeEffectScope) {
1563
+ return activeEffectScope.active ? activeEffectScope : undefined;
1564
+ }
1565
+ const frame = peekComponentContext();
1566
+ if (frame?.active && !frame.owner.disposed) {
1567
+ let scope = componentScopes.get(frame);
1568
+ if (!scope) {
1569
+ scope = new EffectScope(true);
1570
+ componentScopes.set(frame, scope);
1571
+ runWithOwner(frame.owner, () => {
1572
+ onCleanup(() => scope!.stop(true));
1573
+ });
1574
+ }
1575
+ return scope.active ? scope : undefined;
1576
+ }
1577
+ return undefined;
1578
+ }
1579
+
1580
+ export function onScopeDispose(fn: () => void, failSilently = false): void {
1581
+ if (typeof fn !== "function")
1582
+ throw new TypeError("onScopeDispose callback must be a function");
1583
+ const scope = getCurrentScope();
1584
+ if (scope) {
1585
+ scopeCleanups.get(scope)?.push(fn);
1586
+ } else if (!failSilently) {
1587
+ throw new Error("onScopeDispose requires an active effectScope");
1588
+ }
1589
+ }
1590
+
1591
+ export type TemplateRef<T = unknown> = Readonly<Ref<T | null>>;
1592
+
1593
+ const templateRefBindings = new WeakMap<
1594
+ Ref<any>,
1595
+ {
1596
+ get: () => any;
1597
+ set: (value: any) => void;
1598
+ }
1599
+ >();
1600
+ const componentTemplateRefKeys = new WeakMap<ComponentContext, Set<string>>();
1601
+
1602
+ /** Internal binder lookup for readonly useTemplateRef instances. */
1603
+ export function getTemplateRefBinding<T>(target: Readonly<Ref<T | null>>):
1604
+ | {
1605
+ get: () => T | null | undefined;
1606
+ set: (value: T | null) => void;
1607
+ }
1608
+ | undefined {
1609
+ return templateRefBindings.get(target as Ref<any>);
1610
+ }
1611
+
1612
+ /** Native component template ref; readonly to user code, bound by template ref wave. */
1613
+ export function useTemplateRef<T = unknown, K extends string = string>(
1614
+ key: K,
1615
+ ): TemplateRef<T> {
1616
+ const frame = getComponentContext();
1617
+ if (typeof key !== "string" || key.length === 0)
1618
+ throw new TypeError("Template ref key must be a non-empty string");
1619
+ let keys = componentTemplateRefKeys.get(frame);
1620
+ if (!keys) {
1621
+ keys = new Set();
1622
+ componentTemplateRefKeys.set(frame, keys);
1623
+ }
1624
+ if (keys.has(key))
1625
+ throw new Error(`useTemplateRef(${JSON.stringify(key)}) already exists`);
1626
+ keys.add(key);
1627
+ if (frame.mode === "ssr") return new Ref<T | null>(() => null);
1628
+ const [read, write] = createSignal<T | null>(null, { equals: Object.is });
1629
+ const refObject = new Ref<T | null>(read);
1630
+ templateRefBindings.set(refObject, { get: read, set: write });
1631
+ return refObject;
1632
+ }
1633
+
1634
+ export interface DefineModelOptions<T = any, G = T, S = T> {
1635
+ default?: any;
1636
+ required?: boolean;
1637
+ get?: (v: T) => G;
1638
+ set?: (v: S) => any;
1639
+ }
1640
+
1641
+ export type ModelRef<T, M extends PropertyKey = string, G = T, S = T> = Ref<
1642
+ G,
1643
+ S
1644
+ > &
1645
+ [ModelRef<T, M, G, S>, Record<M, true | undefined>];
1646
+
1647
+ const camelizeModelKey = (key: string) =>
1648
+ key.replace(/-(\w)/g, (_, letter: string) => letter.toUpperCase());
1649
+ const hyphenateModelKey = (key: string) =>
1650
+ key.replace(/\B([A-Z])/g, "-$1").toLowerCase();
1651
+ const emptyModelModifiers: Record<PropertyKey, true | undefined> =
1652
+ /* @__PURE__ */ Object.freeze({});
1653
+ const unsetModelValue = /* @__PURE__ */ Symbol("moonshine.vue.model.unset");
1654
+ const hasListenerOn = (target: object, key: string) =>
1655
+ key in target && Reflect.get(target, key, target) != null;
1656
+
1657
+ export function createModel<V, M extends PropertyKey = string, G = V, S = V>(
1658
+ props: Record<string, any>,
1659
+ name: string,
1660
+ options?: DefineModelOptions<V, G, S>,
1661
+ booleanCast?: boolean,
1662
+ soleFunction = false,
1663
+ ): ModelRef<V, M, G, S> {
1664
+ const frame = getComponentContext();
1665
+ if (props === null || typeof props !== "object" || Array.isArray(props)) {
1666
+ throw new TypeError("useModel requires a props object");
1667
+ }
1668
+ if (typeof name !== "string" || name.length === 0) {
1669
+ throw new TypeError("useModel requires a non-empty string prop name");
1670
+ }
1671
+ if (
1672
+ options !== undefined &&
1673
+ (options === null || typeof options !== "object" || Array.isArray(options))
1674
+ ) {
1675
+ throw new TypeError("useModel options must be an object");
1676
+ }
1677
+ if (options?.get !== undefined && typeof options.get !== "function") {
1678
+ throw new TypeError("useModel get option must be a function");
1679
+ }
1680
+ if (options?.set !== undefined && typeof options.set !== "function") {
1681
+ throw new TypeError("useModel set option must be a function");
1682
+ }
1683
+ const raw = (
1684
+ frame.props !== null &&
1685
+ typeof frame.props === "object" &&
1686
+ !Array.isArray(frame.props)
1687
+ ? frame.props
1688
+ : props
1689
+ ) as Record<string, unknown>;
1690
+ const emit = createEmitter<Record<string, readonly unknown[]>>(raw);
1691
+ const camelName = camelizeModelKey(name);
1692
+ const hyphenName = hyphenateModelKey(camelName);
1693
+ const rawUpdateEvent = "update:" + name;
1694
+ const camelUpdateKey = "onUpdate:" + camelName;
1695
+ const rawUpdateKey = "onUpdate:" + name;
1696
+ const hyphenUpdateKey = "onUpdate:" + hyphenName;
1697
+
1698
+ const hasUpdateListener = () =>
1699
+ hasListenerOn(raw, camelUpdateKey) ||
1700
+ hasListenerOn(raw, rawUpdateKey) ||
1701
+ hasListenerOn(raw, hyphenUpdateKey) ||
1702
+ hasListenerOn(raw, camelUpdateKey + "Once") ||
1703
+ hasListenerOn(raw, rawUpdateKey + "Once") ||
1704
+ hasListenerOn(raw, hyphenUpdateKey + "Once") ||
1705
+ (props !== raw &&
1706
+ (hasListenerOn(props, camelUpdateKey) ||
1707
+ hasListenerOn(props, rawUpdateKey) ||
1708
+ hasListenerOn(props, hyphenUpdateKey)));
1709
+
1710
+ const hasDefaultOption = options !== undefined && "default" in options;
1711
+ let hasCachedDefault = false;
1712
+ let cachedDefault: unknown;
1713
+ const resolveDefault = () => {
1714
+ if (!hasDefaultOption) return undefined;
1715
+ const def = options!.default;
1716
+ if (!soleFunction && typeof def === "function") {
1717
+ if (!hasCachedDefault) {
1718
+ cachedDefault = withComponentConsumer(frame, () =>
1719
+ untrack(() => (def as () => unknown)()),
1720
+ );
1721
+ hasCachedDefault = true;
1722
+ }
1723
+ return cachedDefault;
1724
+ }
1725
+ return def;
1726
+ };
1727
+
1728
+ let prevRawOnly: unknown = unsetModelValue;
1729
+ const readIncomingProp = (): {
1730
+ hasProp: boolean;
1731
+ rawValue: unknown;
1732
+ resolved: V;
1733
+ } => {
1734
+ let hasProp = false;
1735
+ let propValue: unknown;
1736
+ if (name in raw) {
1737
+ hasProp = true;
1738
+ propValue = Reflect.get(raw, name, raw);
1739
+ } else if (camelName in raw) {
1740
+ hasProp = true;
1741
+ propValue = Reflect.get(raw, camelName, raw);
1742
+ } else if (hyphenName in raw) {
1743
+ hasProp = true;
1744
+ propValue = Reflect.get(raw, hyphenName, raw);
1745
+ }
1746
+ const rawOnly = propValue;
1747
+ if (props !== raw) {
1748
+ const fromProps =
1749
+ name in props
1750
+ ? Reflect.get(props, name, props)
1751
+ : Reflect.get(props, camelName, props);
1752
+ if (!hasProp && fromProps !== undefined) {
1753
+ hasProp = true;
1754
+ propValue = fromProps;
1755
+ } else if (
1756
+ hasProp &&
1757
+ propValue === undefined &&
1758
+ fromProps !== undefined &&
1759
+ (prevRawOnly === unsetModelValue || !Object.is(fromProps, prevRawOnly))
1760
+ ) {
1761
+ propValue = fromProps;
1762
+ }
1763
+ }
1764
+ if (rawOnly !== undefined) prevRawOnly = rawOnly;
1765
+ let resolved = propValue;
1766
+ if (resolved === undefined && hasDefaultOption) {
1767
+ resolved = resolveDefault();
1768
+ }
1769
+ if (booleanCast !== undefined) {
1770
+ if (!hasProp && !hasDefaultOption) {
1771
+ resolved = false;
1772
+ } else if (booleanCast && (resolved === "" || resolved === hyphenName)) {
1773
+ resolved = true;
1774
+ }
1775
+ }
1776
+ return { hasProp, rawValue: propValue, resolved: resolved as V };
1777
+ };
1778
+
1779
+ let forceTrigger = false;
1780
+ let writing = false;
1781
+ const initial = untrack(readIncomingProp);
1782
+ const [readLocal, writeLocal] = createSignal<V>(initial.resolved, {
1783
+ equals: (prev, next) => !forceTrigger && Object.is(prev, next),
1784
+ });
1785
+ let prevHasProp = initial.hasProp;
1786
+ let prevRawValue = initial.rawValue;
1787
+ let prevSetValue: unknown = unsetModelValue;
1788
+ let localWrittenInSSR = false;
1789
+
1790
+ if (frame.mode === "dom") {
1791
+ let initialized = false;
1792
+ createComputed(() => {
1793
+ const next = readIncomingProp();
1794
+ if (!initialized) {
1795
+ initialized = true;
1796
+ prevHasProp = next.hasProp;
1797
+ prevRawValue = next.rawValue;
1798
+ untrack(() => writeLocal(() => next.resolved));
1799
+ return;
1800
+ }
1801
+ if (
1802
+ next.hasProp !== prevHasProp ||
1803
+ !Object.is(next.rawValue, prevRawValue)
1804
+ ) {
1805
+ prevHasProp = next.hasProp;
1806
+ prevRawValue = next.rawValue;
1807
+ if (!writing) prevSetValue = unsetModelValue;
1808
+ untrack(() => writeLocal(() => next.resolved));
1809
+ }
1810
+ });
1811
+ }
1812
+
1813
+ const getter = options?.get;
1814
+ const setter = options?.set;
1815
+ let modelRef!: ModelRef<V, M, G, S>;
1816
+
1817
+ const read = (): G => {
1818
+ const value =
1819
+ frame.mode === "ssr" && !localWrittenInSSR
1820
+ ? readIncomingProp().resolved
1821
+ : readLocal();
1822
+ return getter ? getter(value) : (value as unknown as G);
1823
+ };
1824
+
1825
+ const write = (next: S): void => {
1826
+ const currentLocal =
1827
+ frame.mode === "ssr" && !localWrittenInSSR
1828
+ ? untrack(readIncomingProp).resolved
1829
+ : untrack(readLocal);
1830
+ const emittedValue = (setter ? setter(next) : next) as unknown as V;
1831
+ if (
1832
+ Object.is(emittedValue, currentLocal) &&
1833
+ Object.is(next, emittedValue) &&
1834
+ (prevSetValue === unsetModelValue || Object.is(next, prevSetValue))
1835
+ ) {
1836
+ return;
1837
+ }
1838
+ prevSetValue = next;
1839
+ localWrittenInSSR = true;
1840
+ refTriggerVersions.set(
1841
+ modelRef,
1842
+ (refTriggerVersions.get(modelRef) ?? 0) + 1,
1843
+ );
1844
+ writing = true;
1845
+ try {
1846
+ if (!Object.is(next, emittedValue)) {
1847
+ forceTrigger = true;
1848
+ }
1849
+ try {
1850
+ writeLocal(() => emittedValue);
1851
+ } finally {
1852
+ forceTrigger = false;
1853
+ }
1854
+ emit(rawUpdateEvent, emittedValue);
1855
+ const post = untrack(readIncomingProp);
1856
+ if (post.hasProp && hasUpdateListener()) {
1857
+ prevHasProp = post.hasProp;
1858
+ prevRawValue = post.rawValue;
1859
+ writeLocal(() => post.resolved);
1860
+ }
1861
+ } finally {
1862
+ writing = false;
1863
+ }
1864
+ };
1865
+
1866
+ const resolveModifiers = (): Record<PropertyKey, true | undefined> => {
1867
+ const mod =
1868
+ (camelName === "modelValue"
1869
+ ? (Reflect.get(raw, "modelModifiers", raw) ??
1870
+ Reflect.get(raw, "modelValueModifiers", raw) ??
1871
+ Reflect.get(raw, "model-valueModifiers", raw))
1872
+ : undefined) ??
1873
+ Reflect.get(raw, name + "Modifiers", raw) ??
1874
+ Reflect.get(raw, camelName + "Modifiers", raw) ??
1875
+ Reflect.get(raw, hyphenName + "Modifiers", raw) ??
1876
+ (props !== raw
1877
+ ? ((camelName === "modelValue"
1878
+ ? (Reflect.get(props, "modelModifiers", props) ??
1879
+ Reflect.get(props, "modelValueModifiers", props))
1880
+ : undefined) ??
1881
+ Reflect.get(props, name + "Modifiers", props) ??
1882
+ Reflect.get(props, camelName + "Modifiers", props))
1883
+ : undefined);
1884
+ if (!mod || typeof mod !== "object") return emptyModelModifiers;
1885
+ const normalized: Record<PropertyKey, true | undefined> = {};
1886
+ for (const key of Reflect.ownKeys(mod)) {
1887
+ if (Reflect.get(mod, key, mod)) {
1888
+ normalized[key] = true;
1889
+ }
1890
+ }
1891
+ return Object.freeze(normalized);
1892
+ };
1893
+ const modifiers = resolveModifiers() as Record<M, true | undefined>;
1894
+
1895
+ modelRef = new Ref<G, S>(read, write) as ModelRef<V, M, G, S>;
1896
+ refTriggers.set(modelRef, () => {
1897
+ forceTrigger = true;
1898
+ try {
1899
+ refTriggerVersions.set(
1900
+ modelRef,
1901
+ (refTriggerVersions.get(modelRef) ?? 0) + 1,
1902
+ );
1903
+ writeLocal((current) => current);
1904
+ } finally {
1905
+ forceTrigger = false;
1906
+ }
1907
+ });
1908
+ Object.defineProperty(modelRef, Symbol.iterator, {
1909
+ value: function* () {
1910
+ yield modelRef;
1911
+ yield modifiers;
1912
+ },
1913
+ writable: false,
1914
+ enumerable: false,
1915
+ configurable: true,
1916
+ });
1917
+ return modelRef;
1918
+ }
1919
+
1920
+ export function useModel<
1921
+ T extends Record<string, any>,
1922
+ K extends keyof T & string,
1923
+ M extends PropertyKey = string,
1924
+ G = Exclude<T[K], undefined>,
1925
+ S = Exclude<T[K], undefined>,
1926
+ >(
1927
+ props: T,
1928
+ name: K,
1929
+ options: DefineModelOptions<Exclude<T[K], undefined>, G, S> & {
1930
+ default: Exclude<T[K], undefined> | (() => Exclude<T[K], undefined>);
1931
+ },
1932
+ ): ModelRef<Exclude<T[K], undefined>, M, G, S>;
1933
+ export function useModel<
1934
+ T extends Record<string, any>,
1935
+ K extends keyof T & string,
1936
+ M extends PropertyKey = string,
1937
+ G = T[K],
1938
+ S = T[K],
1939
+ >(
1940
+ props: T,
1941
+ name: K,
1942
+ options?: DefineModelOptions<T[K], G, S>,
1943
+ ): ModelRef<T[K], M, G, S>;
1944
+ export function useModel<
1945
+ T extends Record<string, any>,
1946
+ K extends keyof T & string,
1947
+ M extends PropertyKey = string,
1948
+ G = T[K],
1949
+ S = T[K],
1950
+ >(
1951
+ props: T,
1952
+ name: K,
1953
+ options?: DefineModelOptions<T[K], G, S>,
1954
+ ): ModelRef<T[K], M, G, S> {
1955
+ return createModel<T[K], M, G, S>(props, name, options);
1956
+ }
1957
+
1958
+ export type WatchEffect = (onCleanup: (fn: () => void) => void) => void;
1959
+
1960
+ export interface WatchEffectOptions {
1961
+ flush?: "pre" | "post" | "sync";
1962
+ onTrack?: (event: unknown) => void;
1963
+ onTrigger?: (event: unknown) => void;
1964
+ }
1965
+
1966
+ const pendingPostJobs: Array<() => void> = [];
1967
+ let postFlushScheduled = false;
1968
+
1969
+ function queueVuePostJob(fn: () => void): void {
1970
+ const scheduler = getRenderScheduler();
1971
+ if (scheduler) {
1972
+ scheduler.post(fn);
1973
+ return;
1974
+ }
1975
+ pendingPostJobs.push(fn);
1976
+ if (!postFlushScheduled) {
1977
+ postFlushScheduled = true;
1978
+ queueMicrotask(() => {
1979
+ postFlushScheduled = false;
1980
+ let failed = false;
1981
+ let failure: unknown;
1982
+ while (pendingPostJobs.length > 0) {
1983
+ const batchJobs = pendingPostJobs.splice(0);
1984
+ for (const job of batchJobs) {
1985
+ try {
1986
+ job();
1987
+ } catch (error) {
1988
+ if (!failed) failure = error;
1989
+ failed = true;
1990
+ }
1991
+ }
1992
+ }
1993
+ if (failed) throw failure;
1994
+ });
1995
+ }
1996
+ }
1997
+
1998
+ export function watchEffect(
1999
+ effect: WatchEffect,
2000
+ options?: WatchEffectOptions,
2001
+ ): WatchHandle {
2002
+ if (typeof effect !== "function") {
2003
+ throw new TypeError("Watcher effect must be a function");
2004
+ }
2005
+ if (!options || options.flush !== "post") {
2006
+ return watchSyncEffect(effect);
2007
+ }
2008
+ const outer = getOwner();
2009
+ if (outer?.disposed) {
2010
+ throw new Error("Cannot watch from a disposed native owner");
2011
+ }
2012
+ const reportError = captureWatchErrorHandler();
2013
+ let stop!: () => void;
2014
+ let pause!: () => void;
2015
+ let resume!: () => void;
2016
+
2017
+ createRoot((dispose) => {
2018
+ stop = dispose;
2019
+ let active = true;
2020
+ let running = false;
2021
+ let paused = false;
2022
+ let dirtyWhilePaused = false;
2023
+ let scheduled = false;
2024
+ let lastDeps: Array<Parameters<typeof trackDependency>[0]> = [];
2025
+ const [readTrigger, writeTrigger] = createSignal(0, { equals: false });
2026
+ const cleanups: Array<() => void> = [];
2027
+
2028
+ const clean = () => {
2029
+ let failed = false;
2030
+ let failure: unknown;
2031
+ const prevCleanup = activeWatcherCleanup;
2032
+ activeWatcherCleanup = undefined;
2033
+ try {
2034
+ for (const fn of cleanups.splice(0)) {
2035
+ try {
2036
+ untrack(() =>
2037
+ reportError
2038
+ ? invokeWatch(reportError, "watch cleanup", fn)
2039
+ : fn(),
2040
+ );
2041
+ } catch (error) {
2042
+ if (!failed) failure = error;
2043
+ failed = true;
2044
+ }
2045
+ }
2046
+ } finally {
2047
+ activeWatcherCleanup = prevCleanup;
2048
+ }
2049
+ if (failed) throw failure;
2050
+ };
2051
+
2052
+ const executeEffect = () => {
2053
+ scheduled = false;
2054
+ if (running || !active || paused) return;
2055
+ running = true;
2056
+ try {
2057
+ untrack(clean);
2058
+ if (!active) return;
2059
+ const registerCleanup = (fn: () => void) => {
2060
+ if (typeof fn !== "function") {
2061
+ throw new TypeError("Watcher cleanup must be a function");
2062
+ }
2063
+ if (active) cleanups.push(fn);
2064
+ };
2065
+ const invoke = () => {
2066
+ const previousCleanup = activeWatcherCleanup;
2067
+ activeWatcherCleanup = registerCleanup;
377
2068
  try {
378
- untrack(clean);
379
- } catch {
380
- /* Preserve the effect failure. */
2069
+ return effect(registerCleanup);
2070
+ } finally {
2071
+ activeWatcherCleanup = previousCleanup;
381
2072
  }
2073
+ };
2074
+ lastDeps = collectDeps(
2075
+ () => {
2076
+ if (reportError) invokeWatch(reportError, "watch effect", invoke);
2077
+ else invoke();
2078
+ },
2079
+ undefined,
2080
+ true,
2081
+ ) as Array<Parameters<typeof trackDependency>[0]>;
2082
+ writeTrigger((v) => v + 1);
2083
+ } catch (error) {
2084
+ try {
2085
+ untrack(clean);
2086
+ } catch {
2087
+ /* Preserve effect failure. */
2088
+ }
382
2089
  throw error;
383
2090
  } finally {
384
2091
  running = false;
385
2092
  }
2093
+ };
2094
+
2095
+ pause = () => {
2096
+ if (active) paused = true;
2097
+ };
2098
+ resume = () => {
2099
+ if (!active || !paused) return;
2100
+ paused = false;
2101
+ if (dirtyWhilePaused) {
2102
+ dirtyWhilePaused = false;
2103
+ if (!scheduled) {
2104
+ scheduled = true;
2105
+ queueVuePostJob(executeEffect);
2106
+ }
2107
+ }
2108
+ };
2109
+
2110
+ onCleanup(() => {
2111
+ active = false;
2112
+ paused = false;
2113
+ dirtyWhilePaused = false;
2114
+ scheduled = false;
2115
+ clean();
2116
+ });
2117
+
2118
+ let initialSubscriptionPass = true;
2119
+ createComputed(() => {
2120
+ readTrigger();
2121
+ for (const dep of lastDeps) {
2122
+ dep.validate?.();
2123
+ trackDependency(dep);
2124
+ }
2125
+ if (initialSubscriptionPass) {
2126
+ initialSubscriptionPass = false;
2127
+ scheduled = true;
2128
+ queueVuePostJob(executeEffect);
2129
+ return;
2130
+ }
2131
+ if (!active || running) return;
2132
+ if (paused) {
2133
+ dirtyWhilePaused = true;
2134
+ return;
2135
+ }
2136
+ if (!scheduled) {
2137
+ scheduled = true;
2138
+ queueVuePostJob(executeEffect);
2139
+ }
386
2140
  });
387
2141
  });
2142
+
388
2143
  if (outer) onCleanup(stop);
389
- return stop;
2144
+ return createWatchHandle(stop, pause, resume);
2145
+ }
2146
+
2147
+ export function watchPostEffect(
2148
+ effect: WatchEffect,
2149
+ options?: Omit<WatchEffectOptions, "flush">,
2150
+ ): WatchHandle {
2151
+ return watchEffect(effect, { ...options, flush: "post" });
2152
+ }
2153
+
2154
+ export function nextTick<R = void>(fn?: () => R): Promise<Awaited<R>> {
2155
+ return new Promise<Awaited<R>>((resolve, reject) => {
2156
+ queueVuePostJob(() => {
2157
+ try {
2158
+ const result = fn ? fn() : undefined;
2159
+ resolve(result as Awaited<R>);
2160
+ } catch (error) {
2161
+ reject(error);
2162
+ }
2163
+ });
2164
+ });
2165
+ }
2166
+
2167
+ function isOnEventKey(key: string): boolean {
2168
+ return (
2169
+ key.length > 2 &&
2170
+ key.charCodeAt(0) === 111 &&
2171
+ key.charCodeAt(1) === 110 &&
2172
+ key.charCodeAt(2) <= 96
2173
+ );
2174
+ }
2175
+
2176
+ export function mergeProps(
2177
+ ...args: Array<Record<string, any> | null | undefined>
2178
+ ): Record<string, any> {
2179
+ const ret: Record<string, any> = {};
2180
+ for (const toMerge of args) {
2181
+ if (!toMerge || typeof toMerge !== "object") continue;
2182
+ for (const key of Object.keys(toMerge)) {
2183
+ const incoming = toMerge[key];
2184
+ if (key === "class") {
2185
+ if (ret.class !== incoming) {
2186
+ ret.class = normalizeClass([ret.class, incoming]);
2187
+ }
2188
+ } else if (key === "style") {
2189
+ ret.style = normalizeStyle([ret.style, incoming]);
2190
+ } else if (isOnEventKey(key)) {
2191
+ const existing = ret[key];
2192
+ if (
2193
+ incoming &&
2194
+ existing !== incoming &&
2195
+ !(Array.isArray(existing) && existing.includes(incoming))
2196
+ ) {
2197
+ ret[key] = existing
2198
+ ? [].concat(existing as any, incoming as any)
2199
+ : incoming;
2200
+ }
2201
+ } else if (key !== "") {
2202
+ ret[key] = incoming;
2203
+ }
2204
+ }
2205
+ }
2206
+ return ret;
2207
+ }
2208
+
2209
+ export function defineComponent<T>(options: T): T {
2210
+ return options;
2211
+ }
2212
+
2213
+ export interface AsyncComponentOptions<T = any> {
2214
+ loader: () => Promise<T | { default: T }>;
2215
+ loadingComponent?: (...args: any[]) => any;
2216
+ errorComponent?: (...args: any[]) => any;
2217
+ delay?: number;
2218
+ timeout?: number;
2219
+ onError?: (
2220
+ error: Error,
2221
+ retry: () => void,
2222
+ fail: () => void,
2223
+ attempts: number,
2224
+ ) => any;
2225
+ }
2226
+
2227
+ export function defineAsyncComponent<
2228
+ T extends (...args: any[]) => any = (...args: any[]) => any,
2229
+ >(source: (() => Promise<T | { default: T }>) | AsyncComponentOptions<T>): T {
2230
+ const options: AsyncComponentOptions<T> =
2231
+ typeof source === "function" ? { loader: source } : source;
2232
+ let resolvedComp: T | undefined;
2233
+ let pendingPromise: Promise<T> | undefined;
2234
+
2235
+ const wrapper = ((props: Record<string, any>) => {
2236
+ if (resolvedComp) {
2237
+ return resolvedComp(props);
2238
+ }
2239
+ const [loaded, setLoaded] = createSignal<T | undefined>(resolvedComp);
2240
+ const [error, setError] = createSignal<Error | undefined>(undefined);
2241
+ const [showLoading, setShowLoading] = createSignal(
2242
+ (options.delay ?? 200) <= 0,
2243
+ );
2244
+
2245
+ let disposed = false;
2246
+ if (getOwner()) {
2247
+ onCleanup(() => {
2248
+ disposed = true;
2249
+ });
2250
+ }
2251
+
2252
+ const delayMs = options.delay ?? 200;
2253
+ const delayTimer =
2254
+ delayMs > 0
2255
+ ? setTimeout(() => {
2256
+ if (!disposed && !resolvedComp) setShowLoading(true);
2257
+ }, delayMs)
2258
+ : undefined;
2259
+
2260
+ const timeoutTimer =
2261
+ options.timeout !== undefined && options.timeout > 0
2262
+ ? setTimeout(() => {
2263
+ if (!disposed && !resolvedComp) {
2264
+ setError(
2265
+ new Error(
2266
+ `Async component timed out after ${options.timeout}ms.`,
2267
+ ),
2268
+ );
2269
+ }
2270
+ }, options.timeout)
2271
+ : undefined;
2272
+
2273
+ let attempts = 0;
2274
+ const loadAttempt = (): Promise<T> => {
2275
+ attempts++;
2276
+ return options
2277
+ .loader()
2278
+ .then((mod) => {
2279
+ const comp =
2280
+ mod && typeof mod === "object" && "default" in mod
2281
+ ? mod.default
2282
+ : (mod as T);
2283
+ resolvedComp = comp;
2284
+ if (!disposed) {
2285
+ setLoaded(() => comp);
2286
+ }
2287
+ return comp;
2288
+ })
2289
+ .catch((err) => {
2290
+ const normalized =
2291
+ err instanceof Error ? err : new Error(String(err));
2292
+ if (options.onError) {
2293
+ return new Promise<T>((resolve, reject) => {
2294
+ options.onError!(
2295
+ normalized,
2296
+ () => resolve(loadAttempt()),
2297
+ () => reject(normalized),
2298
+ attempts,
2299
+ );
2300
+ });
2301
+ }
2302
+ throw normalized;
2303
+ });
2304
+ };
2305
+
2306
+ if (!pendingPromise) {
2307
+ pendingPromise = loadAttempt();
2308
+ }
2309
+ pendingPromise
2310
+ .then((comp) => {
2311
+ if (!disposed) setLoaded(() => comp);
2312
+ })
2313
+ .catch((err) => {
2314
+ pendingPromise = undefined;
2315
+ if (!disposed) {
2316
+ setError(err instanceof Error ? err : new Error(String(err)));
2317
+ }
2318
+ })
2319
+ .finally(() => {
2320
+ if (delayTimer !== undefined) clearTimeout(delayTimer);
2321
+ if (timeoutTimer !== undefined) clearTimeout(timeoutTimer);
2322
+ });
2323
+
2324
+ return () => {
2325
+ const err = error();
2326
+ if (err) {
2327
+ return options.errorComponent
2328
+ ? options.errorComponent({ error: err })
2329
+ : null;
2330
+ }
2331
+ const comp = loaded();
2332
+ if (comp) {
2333
+ return comp(props);
2334
+ }
2335
+ if (showLoading() && options.loadingComponent) {
2336
+ return options.loadingComponent(props);
2337
+ }
2338
+ return null;
2339
+ };
2340
+ }) as unknown as T;
2341
+
2342
+ return wrapper;
2343
+ }
2344
+
2345
+ import {
2346
+ createInsertionRange,
2347
+ h as hDOM,
2348
+ insertionRangeEnd,
2349
+ prepareInsertionRange,
2350
+ } from "@tschk/moonshine-dom";
2351
+ import {
2352
+ escapeHtml,
2353
+ h as hSSR,
2354
+ rawHTML,
2355
+ renderToString as renderSSRToString,
2356
+ } from "@tschk/moonshine-dom/ssr";
2357
+ import { isSSRRendering } from "@tschk/moonshine-dom/ssr-owner";
2358
+ import { getDefaultSlotFactory } from "./slots";
2359
+
2360
+ function resolveBuiltinSlot(
2361
+ props: Record<string, any> | null | undefined,
2362
+ slotName = "default",
2363
+ ): any {
2364
+ if (!props || typeof props !== "object") return null;
2365
+ if (slotName === "default") {
2366
+ const frame = peekComponentContext();
2367
+ const defaultFactory = getDefaultSlotFactory(props, frame);
2368
+ if (defaultFactory) return defaultFactory();
2369
+ }
2370
+ const explicitSlots =
2371
+ (props.$slots && typeof props.$slots === "object"
2372
+ ? (props.$slots as Record<string, (...args: any[]) => any>)
2373
+ : undefined) ??
2374
+ (props.slots && typeof props.slots === "object"
2375
+ ? (props.slots as Record<string, (...args: any[]) => any>)
2376
+ : undefined);
2377
+ if (explicitSlots && typeof explicitSlots[slotName] === "function") {
2378
+ return explicitSlots[slotName]!();
2379
+ }
2380
+ if (slotName === "default") {
2381
+ if (typeof props.children === "function") return props.children();
2382
+ if (props.children !== undefined) return props.children;
2383
+ } else if (slotName === "fallback" && props.fallback !== undefined) {
2384
+ return typeof props.fallback === "function"
2385
+ ? props.fallback()
2386
+ : props.fallback;
2387
+ }
2388
+ return null;
390
2389
  }
2390
+
2391
+ export interface TeleportProps {
2392
+ to?: string | Element | ShadowRoot | null;
2393
+ disabled?: boolean;
2394
+ defer?: boolean;
2395
+ children?: any;
2396
+ [key: string]: any;
2397
+ }
2398
+
2399
+ export function Teleport(props: TeleportProps = {}): any {
2400
+ const frame = peekComponentContext();
2401
+ if (frame?.mode === "ssr" || isSSRRendering()) {
2402
+ const content = resolveBuiltinSlot(props);
2403
+ if (!props.disabled && typeof props.to === "string" && props.to) {
2404
+ const ssrCtx = peekSSRContext();
2405
+ if (ssrCtx) {
2406
+ const htmlStr =
2407
+ content === null ||
2408
+ content === undefined ||
2409
+ typeof content === "boolean"
2410
+ ? ""
2411
+ : typeof content === "string" || typeof content === "number"
2412
+ ? escapeHtml(String(content))
2413
+ : renderSSRToString(() => content);
2414
+ ssrCtx.teleports ??= {};
2415
+ ssrCtx.teleports[props.to] =
2416
+ (ssrCtx.teleports[props.to] ?? "") + htmlStr;
2417
+ return rawHTML("<!--teleport start--><!--teleport end-->");
2418
+ }
2419
+ }
2420
+ return content;
2421
+ }
2422
+ const renderTeleport = () => {
2423
+ const content = resolveBuiltinSlot(props);
2424
+ if (props.disabled || typeof document === "undefined" || !props.to) {
2425
+ return content;
2426
+ }
2427
+ const target =
2428
+ typeof props.to === "string"
2429
+ ? document.querySelector(props.to)
2430
+ : props.to;
2431
+ if (
2432
+ target &&
2433
+ typeof Element !== "undefined" &&
2434
+ (target instanceof Element ||
2435
+ (typeof ShadowRoot !== "undefined" && target instanceof ShadowRoot))
2436
+ ) {
2437
+ const owner = getOwner();
2438
+ if (owner && !owner.disposed) {
2439
+ const start = createInsertionRange(content);
2440
+ const end = insertionRangeEnd(start);
2441
+ target.appendChild(start);
2442
+ target.appendChild(end);
2443
+ prepareInsertionRange(start);
2444
+ return null;
2445
+ }
2446
+ if (typeof Node !== "undefined" && content instanceof Node) {
2447
+ target.appendChild(content);
2448
+ return null;
2449
+ }
2450
+ }
2451
+ return content;
2452
+ };
2453
+ if (getOwner()) {
2454
+ return () => renderTeleport();
2455
+ }
2456
+ return renderTeleport();
2457
+ }
2458
+
2459
+ export type MatchPattern = string | RegExp | (string | RegExp)[];
2460
+
2461
+ export interface KeepAliveProps {
2462
+ include?: MatchPattern;
2463
+ exclude?: MatchPattern;
2464
+ max?: number | string;
2465
+ is?: ((props?: any) => any) | (() => (props?: any) => any) | null;
2466
+ componentProps?: Record<string, any>;
2467
+ children?: any;
2468
+ [key: string]: any;
2469
+ }
2470
+
2471
+ function matchesPattern(pattern: MatchPattern, name: string): boolean {
2472
+ if (Array.isArray(pattern)) {
2473
+ return pattern.some((p) => matchesPattern(p, name));
2474
+ }
2475
+ if (typeof pattern === "string") {
2476
+ return pattern
2477
+ .split(",")
2478
+ .map((s) => s.trim())
2479
+ .includes(name);
2480
+ }
2481
+ if (pattern instanceof RegExp) {
2482
+ pattern.lastIndex = 0;
2483
+ return pattern.test(name);
2484
+ }
2485
+ return false;
2486
+ }
2487
+
2488
+ export function KeepAlive(props: KeepAliveProps = {}): any {
2489
+ const frame = peekComponentContext();
2490
+ if (frame?.mode === "ssr" || isSSRRendering()) {
2491
+ const raw = props.is !== undefined ? props.is : resolveBuiltinSlot(props);
2492
+ if (typeof raw === "function") {
2493
+ return hSSR(raw as any, props.componentProps ?? {});
2494
+ }
2495
+ return raw;
2496
+ }
2497
+
2498
+ const keepAliveOwner = getOwner();
2499
+ const cache = new Map<unknown, { view: any; dispose: () => void }>();
2500
+ if (keepAliveOwner) {
2501
+ onCleanup(() => {
2502
+ for (const entry of cache.values()) {
2503
+ entry.dispose();
2504
+ }
2505
+ cache.clear();
2506
+ });
2507
+ }
2508
+
2509
+ const resolveKeepAlive = () => {
2510
+ const candidate =
2511
+ props.is !== undefined ? props.is : resolveBuiltinSlot(props);
2512
+ if (typeof candidate === "function") {
2513
+ const compName = candidate.name || "";
2514
+ const shouldCache =
2515
+ (!props.include ||
2516
+ (Boolean(compName) && matchesPattern(props.include, compName))) &&
2517
+ (!props.exclude ||
2518
+ !compName ||
2519
+ !matchesPattern(props.exclude, compName));
2520
+
2521
+ if (!shouldCache) {
2522
+ return untrack(() =>
2523
+ hDOM(candidate as any, props.componentProps ?? {}),
2524
+ );
2525
+ }
2526
+
2527
+ if (cache.has(candidate)) {
2528
+ const cached = cache.get(candidate)!;
2529
+ cache.delete(candidate);
2530
+ cache.set(candidate, cached);
2531
+ return cached.view;
2532
+ }
2533
+
2534
+ let disposeEntry = () => {};
2535
+ const rendered = createRoot((dispose) => {
2536
+ disposeEntry = dispose;
2537
+ return untrack(() =>
2538
+ hDOM(candidate as any, props.componentProps ?? {}),
2539
+ );
2540
+ });
2541
+ cache.set(candidate, { view: rendered, dispose: disposeEntry });
2542
+ const maxNum =
2543
+ props.max !== undefined ? Number(props.max) : Number.POSITIVE_INFINITY;
2544
+ if (Number.isFinite(maxNum) && maxNum > 0 && cache.size > maxNum) {
2545
+ const oldestKey = cache.keys().next().value;
2546
+ if (oldestKey !== undefined) {
2547
+ const evicted = cache.get(oldestKey);
2548
+ cache.delete(oldestKey);
2549
+ evicted?.dispose();
2550
+ }
2551
+ }
2552
+ return rendered;
2553
+ }
2554
+ return candidate;
2555
+ };
2556
+
2557
+ if (keepAliveOwner) {
2558
+ return () => resolveKeepAlive();
2559
+ }
2560
+ return resolveKeepAlive();
2561
+ }
2562
+
2563
+ export interface TransitionProps {
2564
+ name?: string;
2565
+ type?: "transition" | "animation";
2566
+ css?: boolean;
2567
+ duration?: number | { enter: number; leave: number };
2568
+ enterFromClass?: string;
2569
+ enterActiveClass?: string;
2570
+ enterToClass?: string;
2571
+ appearFromClass?: string;
2572
+ appearActiveClass?: string;
2573
+ appearToClass?: string;
2574
+ leaveFromClass?: string;
2575
+ leaveActiveClass?: string;
2576
+ leaveToClass?: string;
2577
+ mode?: "in-out" | "out-in" | "default";
2578
+ appear?: boolean;
2579
+ persisted?: boolean;
2580
+ children?: any;
2581
+ [key: string]: any;
2582
+ }
2583
+
2584
+ export function Transition(props: TransitionProps = {}): any {
2585
+ const frame = peekComponentContext();
2586
+ if (frame?.mode === "ssr" || isSSRRendering() || !getOwner()) {
2587
+ return resolveBuiltinSlot(props);
2588
+ }
2589
+ return () => resolveBuiltinSlot(props);
2590
+ }
2591
+
2592
+ export interface TransitionGroupProps extends Omit<TransitionProps, "mode"> {
2593
+ tag?: string;
2594
+ moveClass?: string;
2595
+ }
2596
+
2597
+ const TRANSITION_GROUP_KEYS = /* @__PURE__ */ new Set([
2598
+ "tag",
2599
+ "moveClass",
2600
+ "name",
2601
+ "type",
2602
+ "css",
2603
+ "duration",
2604
+ "enterFromClass",
2605
+ "enterActiveClass",
2606
+ "enterToClass",
2607
+ "appearFromClass",
2608
+ "appearActiveClass",
2609
+ "appearToClass",
2610
+ "leaveFromClass",
2611
+ "leaveActiveClass",
2612
+ "leaveToClass",
2613
+ "appear",
2614
+ "persisted",
2615
+ "children",
2616
+ "slots",
2617
+ "$slots",
2618
+ ]);
2619
+
2620
+ export function TransitionGroup(props: TransitionGroupProps = {}): any {
2621
+ const frame = peekComponentContext();
2622
+ const isSSR = frame?.mode === "ssr" || isSSRRendering();
2623
+ if (!props.tag) {
2624
+ return isSSR || !getOwner()
2625
+ ? resolveBuiltinSlot(props)
2626
+ : () => resolveBuiltinSlot(props);
2627
+ }
2628
+ const attrs: Record<string, any> = {};
2629
+ for (const [key, value] of Object.entries(props)) {
2630
+ if (TRANSITION_GROUP_KEYS.has(key) || value === undefined) continue;
2631
+ attrs[key] = value;
2632
+ }
2633
+ if (isSSR) {
2634
+ return hSSR(props.tag, attrs, resolveBuiltinSlot(props));
2635
+ }
2636
+ return hDOM(
2637
+ props.tag as any,
2638
+ attrs,
2639
+ getOwner() ? () => resolveBuiltinSlot(props) : resolveBuiltinSlot(props),
2640
+ );
2641
+ }
2642
+
2643
+ export interface SuspenseProps {
2644
+ timeout?: string | number;
2645
+ suspensible?: boolean;
2646
+ onPending?: () => void;
2647
+ onResolve?: () => void;
2648
+ onFallback?: () => void;
2649
+ fallback?: any;
2650
+ children?: any;
2651
+ [key: string]: any;
2652
+ }
2653
+
2654
+ export function Suspense(props: SuspenseProps = {}): any {
2655
+ if (typeof props.onResolve === "function") {
2656
+ props.onResolve();
2657
+ }
2658
+ const resolveSuspense = () => {
2659
+ const defaultContent = resolveBuiltinSlot(props, "default");
2660
+ if (defaultContent !== null && defaultContent !== undefined) {
2661
+ return defaultContent;
2662
+ }
2663
+ return resolveBuiltinSlot(props, "fallback");
2664
+ };
2665
+ const frame = peekComponentContext();
2666
+ if (frame?.mode === "ssr" || isSSRRendering() || !getOwner()) {
2667
+ return resolveSuspense();
2668
+ }
2669
+ return () => resolveSuspense();
2670
+ }
2671
+
2672
+ export {
2673
+ createApp,
2674
+ createSSRApp,
2675
+ definePlugin,
2676
+ resolveComponent,
2677
+ resolveDirective,
2678
+ warn,
2679
+ withDirectives,
2680
+ type App,
2681
+ type Directive,
2682
+ type DirectiveArguments,
2683
+ type DirectiveBinding,
2684
+ type DirectiveHook,
2685
+ type FunctionDirective,
2686
+ type FunctionPlugin,
2687
+ type NativeApplication,
2688
+ type ObjectDirective,
2689
+ type ObjectPlugin,
2690
+ type Plugin,
2691
+ } from "./app";
2692
+
2693
+ export const version = "3.5.13";