@tschk/moonshine-vue 0.4.49 → 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,6 +6,7 @@ import {
6
6
  createRoot,
7
7
  createSignal,
8
8
  getOwner,
9
+ getRenderScheduler,
9
10
  onCleanup,
10
11
  runWithOwner,
11
12
  untrack,
@@ -18,21 +19,53 @@ import {
18
19
  trackDependency,
19
20
  type Trackable,
20
21
  } from "@tschk/moonshine/tracking";
22
+ import { createTrackedMap } from "./map";
21
23
  import { createTrackedSet } from "./set";
22
24
  import {
23
25
  getComponentContext,
26
+ nativeRefSet,
24
27
  peekComponentContext,
25
28
  withComponentConsumer,
26
29
  type ComponentContext,
27
30
  } from "@tschk/moonshine-dom/component";
28
31
  import { createEmitter } from "./events";
29
- export { useId } from "./context";
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";
30
63
  import {
31
64
  createMutable,
32
65
  unwrap as unwrapStore,
33
66
  } from "@tschk/moonshine-dom/store";
34
67
 
35
- const refs = new WeakSet<object>();
68
+ const refs = nativeRefSet;
36
69
  const readonlyRefs = new WeakSet<object>();
37
70
  const refTriggers = new WeakMap<Ref<any>, () => void>();
38
71
  const refTriggerVersions = new WeakMap<Ref<any>, number>();
@@ -123,30 +156,40 @@ const arrayIndex = (key: PropertyKey) =>
123
156
  export type Unwrap<T> =
124
157
  T extends Readonly<Ref<infer V>>
125
158
  ? V
126
- : T extends Set<infer V>
127
- ? Set<V extends Readonly<Ref<any>> ? V : Unwrap<V>>
128
- : T extends ReadonlySet<infer V>
129
- ? ReadonlySet<V extends Readonly<Ref<any>> ? V : Unwrap<V>>
130
- : T extends Function | Date | Map<unknown, unknown> | Node | Window
131
- ? T
132
- : T extends readonly unknown[]
133
- ? {
134
- [K in keyof T]: T[K] extends Readonly<Ref<any>>
135
- ? T[K]
136
- : Unwrap<T[K]>;
137
- }
138
- : T extends object
139
- ? { [K in keyof T]: Unwrap<T[K]> }
140
- : 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;
141
184
  export type DeepReadonly<T> = T extends
142
185
  ((...args: any[]) => any) | Date | RegExp | Node | Window
143
186
  ? T
144
187
  : T extends Readonly<Ref<infer V>>
145
188
  ? Readonly<Ref<DeepReadonly<Unwrap<V>>>>
146
- : T extends Set<infer V> | ReadonlySet<infer V>
147
- ? ReadonlySet<DeepReadonly<V>>
148
- : T extends Map<infer K, infer V> | ReadonlyMap<infer K, infer V>
149
- ? ReadonlyMap<DeepReadonly<K>, DeepReadonly<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>>
150
193
  : T extends readonly unknown[]
151
194
  ? { readonly [K in keyof T]: DeepReadonly<T[K]> }
152
195
  : T extends object
@@ -155,19 +198,45 @@ export type DeepReadonly<T> = T extends
155
198
  function rawValue<T>(value: T): T {
156
199
  return toRaw(value);
157
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
+ }
158
220
  function wrapValue<T>(value: T): T {
159
221
  if (value === null || typeof value !== "object") return value;
160
222
  const raw: object = unwrapStore(value);
161
223
  if (rawMarked.has(value) || rawMarked.has(raw)) return raw as T;
162
- return plain(raw) || raw instanceof Set ? (reactive(value) as T) : value;
224
+ return plain(raw) || raw instanceof Set || raw instanceof Map
225
+ ? (createReactive(value) as T)
226
+ : value;
163
227
  }
164
228
  function wrapReadonly<T>(value: T): T {
165
229
  if (value === null || typeof value !== "object") return value;
166
230
  const raw: object = toRaw(value);
167
231
  if (rawMarked.has(value) || rawMarked.has(raw)) return value;
168
- return plain(raw) || raw instanceof Set ? (readonly(value) as T) : value;
232
+ return plain(raw) || raw instanceof Set || raw instanceof Map
233
+ ? (readonly(value) as T)
234
+ : value;
169
235
  }
170
236
  export function reactive<T extends object>(value: T): Unwrap<T> {
237
+ return usePrefetchCell(() => createReactive(value));
238
+ }
239
+ function createReactive<T extends object>(value: T): Unwrap<T> {
171
240
  if (readonlyProxies.has(value)) return value as Unwrap<T>;
172
241
  const existing = proxies.get(value);
173
242
  if (existing) return existing as Unwrap<T>;
@@ -185,9 +254,18 @@ export function reactive<T extends object>(value: T): Unwrap<T> {
185
254
  proxies.set(proxy, proxy);
186
255
  return proxy as Unwrap<T>;
187
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
+ }
188
266
  if (!plain(rawTarget))
189
267
  throw new TypeError(
190
- "Native reactive requires a plain object, array or Set",
268
+ "Native reactive requires a plain object, array, Set or Map",
191
269
  );
192
270
  if (!Object.isExtensible(rawTarget)) return rawTarget as Unwrap<T>;
193
271
  const mutable = createMutable(rawTarget, { equals: Object.is });
@@ -265,6 +343,9 @@ function notifyShallow(cell: ShallowCell | undefined): void {
265
343
  }
266
344
 
267
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 {
268
349
  if (readonlyProxies.has(value)) return value;
269
350
  if (shallowProxies.has(value) && reactiveProxies.has(value)) return value;
270
351
  const rawTarget = toRaw(value);
@@ -285,9 +366,18 @@ export function shallowReactive<T extends object>(value: T): T {
285
366
  shallowReactiveMap.set(proxy, proxy);
286
367
  return proxy as unknown as T;
287
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
+ }
288
378
  if (!plain(rawTarget))
289
379
  throw new TypeError(
290
- "Native shallowReactive requires a plain object, array or Set",
380
+ "Native shallowReactive requires a plain object, array, Set or Map",
291
381
  );
292
382
  const methods = new Map<PropertyKey, Function>();
293
383
  const proxy = new Proxy(rawTarget, {
@@ -473,6 +563,110 @@ function createReadonlySet(target: Set<unknown>, deep: boolean): Set<unknown> {
473
563
  return proxy;
474
564
  }
475
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
+
476
670
  function createReadonly<T extends object>(value: T, shallow: boolean): any {
477
671
  if (isRef(value)) {
478
672
  if (readonlyRefs.has(value) && (!shallow || shallowProxies.has(value))) {
@@ -522,9 +716,21 @@ function createReadonly<T extends object>(value: T, shallow: boolean): any {
522
716
  cache.set(proxy, proxy);
523
717
  return proxy;
524
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
+ }
525
731
  if (!plain(rawCandidate))
526
732
  throw new TypeError(
527
- "Native readonly requires a plain object, array or Set",
733
+ "Native readonly requires a plain object, array, Set or Map",
528
734
  );
529
735
  const proxy = new Proxy(underlying, {
530
736
  get(target, key, receiver) {
@@ -572,6 +778,9 @@ export function ref<T>(value: Ref<T>): Ref<T>;
572
778
  export function ref<T>(value: T): Ref<Unwrap<T>>;
573
779
  export function ref<T = any>(): Ref<T | undefined>;
574
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> {
575
784
  if (isRef(value)) return value;
576
785
  const convert = wrapValue<T>;
577
786
  let forceTrigger = false;
@@ -598,6 +807,9 @@ export function shallowRef<T extends Readonly<Ref<any>>>(value: T): T;
598
807
  export function shallowRef<T>(value: T): Ref<T>;
599
808
  export function shallowRef<T = any>(): Ref<T | undefined>;
600
809
  export function shallowRef(value?: unknown): Ref<any> {
810
+ return usePrefetchCell(() => createShallowRef(value));
811
+ }
812
+ function createShallowRef(value?: unknown): Ref<any> {
601
813
  if (isRef(value)) return value;
602
814
  let forceTrigger = false;
603
815
  const [read, write] = createSignal<unknown>(value, {
@@ -700,7 +912,7 @@ export function toRef(
700
912
  },
701
913
  );
702
914
  }
703
- return ref(source);
915
+ return createRef(source);
704
916
  }
705
917
  /** Link the currently enumerable string properties, preserving array holes. */
706
918
  export type ToRefs<T = any> = { [K in keyof T]: ToRef<T[K]> };
@@ -719,6 +931,41 @@ export function toRefs<T extends object>(object: T): ToRefs<T> {
719
931
  }
720
932
  return result;
721
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
+ }
722
969
  export function computed<T>(
723
970
  getter: (previous: T | undefined) => T,
724
971
  ): Readonly<Ref<T>>;
@@ -825,10 +1072,15 @@ function traverse(
825
1072
  for (let i = 0; i < value.length; i++) {
826
1073
  traverse(value[i], depth, seen);
827
1074
  }
828
- } else if (value instanceof Set || value instanceof Map) {
1075
+ } else if (value instanceof Set) {
829
1076
  value.forEach((entry) => {
830
1077
  traverse(entry, depth, seen);
831
1078
  });
1079
+ } else if (value instanceof Map) {
1080
+ value.forEach((entry, key) => {
1081
+ traverse(key, depth, seen);
1082
+ traverse(entry, depth, seen);
1083
+ });
832
1084
  } else if (plain(value)) {
833
1085
  for (const key in value) {
834
1086
  traverse(value[key], depth, seen);
@@ -1702,3 +1954,740 @@ export function useModel<
1702
1954
  ): ModelRef<T[K], M, G, S> {
1703
1955
  return createModel<T[K], M, G, S>(props, name, options);
1704
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;
2068
+ try {
2069
+ return effect(registerCleanup);
2070
+ } finally {
2071
+ activeWatcherCleanup = previousCleanup;
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
+ }
2089
+ throw error;
2090
+ } finally {
2091
+ running = false;
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
+ }
2140
+ });
2141
+ });
2142
+
2143
+ if (outer) onCleanup(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;
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";