@overmvp/kumi 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/README.md +59 -6
  2. package/builder/css-v1.mjs +54 -1
  3. package/builder/css-v1.test.mjs +40 -0
  4. package/builder/link-addon-package.mjs +47 -6
  5. package/builder/module-declarations.test.mjs +9 -18
  6. package/builder/native-kernels.mjs +1 -1
  7. package/builder/src/compiler.rs +180 -8
  8. package/builder/src/main.rs +19 -5
  9. package/builder/src/native_ir.rs +1 -1
  10. package/builder/src/native_signal.rs +46 -10
  11. package/builder/src/numbers.lua +14 -0
  12. package/builder/src/project-front.mjs +385 -34
  13. package/builder/src/routes.rs +11 -14
  14. package/builder/src/setup-store.lua +18 -0
  15. package/builder/src/signal-kernel.fingerprint +1 -1
  16. package/builder/src/ts-lower.mjs +2 -2
  17. package/builder/src/wow-reads.lua +22 -0
  18. package/builder/style-modules.mjs +93 -0
  19. package/config.ts +56 -14
  20. package/eslint.mjs +74 -0
  21. package/form/index.ts +15 -11
  22. package/package.json +11 -7
  23. package/router/index.ts +9 -2
  24. package/router/navigation.ts +22 -0
  25. package/router/router-view.ts +134 -0
  26. package/scripts/addon-build.mjs +364 -0
  27. package/scripts/addon-project.mjs +78 -0
  28. package/scripts/kumi-cli.mjs +52 -17
  29. package/scripts/link-addons.mjs +12 -2
  30. package/src/bindings.ts +2 -2
  31. package/src/css-tokens.ts +16 -11
  32. package/src/css-v1.ts +10 -0
  33. package/src/elements.ts +26 -0
  34. package/src/frame-scheduler.ts +3 -1
  35. package/src/index.ts +1 -0
  36. package/src/jsx-runtime.ts +8 -1
  37. package/src/keyed-list.ts +8 -5
  38. package/src/module-ui.ts +147 -0
  39. package/src/module.ts +42 -8
  40. package/src/owned-collections.ts +8 -0
  41. package/src/providers.ts +7 -1
  42. package/src/reactive-scope.ts +3 -3
  43. package/src/reactivity.ts +28 -7
  44. package/src/result.ts +6 -0
  45. package/src/signal-kernel.ts +35 -2
  46. package/state/index.ts +6 -0
  47. package/state/setup-store-persistence.ts +206 -0
  48. package/state/setup-store-view.ts +10 -0
  49. package/state/setup-store.ts +342 -0
  50. package/state/store.ts +2 -0
  51. package/templates/addon/.agents/skills/kumi-build-debug/SKILL.md +36 -0
  52. package/templates/addon/.agents/skills/kumi-feature/SKILL.md +50 -0
  53. package/templates/addon/.agents/skills/kumi-plugin/SKILL.md +36 -0
  54. package/templates/addon/.agents/skills/kumi-store/SKILL.md +47 -0
  55. package/templates/addon/.agents/skills/kumi-ui/SKILL.md +73 -0
  56. package/templates/addon/.agents/skills/kumi-wow-api/SKILL.md +30 -0
  57. package/templates/addon/.claude/skills/kumi-build-debug/SKILL.md +36 -0
  58. package/templates/addon/.claude/skills/kumi-feature/SKILL.md +50 -0
  59. package/templates/addon/.claude/skills/kumi-plugin/SKILL.md +36 -0
  60. package/templates/addon/.claude/skills/kumi-store/SKILL.md +47 -0
  61. package/templates/addon/.claude/skills/kumi-ui/SKILL.md +73 -0
  62. package/templates/addon/.claude/skills/kumi-wow-api/SKILL.md +30 -0
  63. package/templates/addon/AGENTS.md +34 -0
  64. package/templates/addon/Assets/Art/Corner10.tga +0 -0
  65. package/templates/addon/Assets/Art/Corner11.tga +0 -0
  66. package/templates/addon/Assets/Art/Corner12.tga +0 -0
  67. package/templates/addon/Assets/Art/Corner13.tga +0 -0
  68. package/templates/addon/Assets/Art/Corner14.tga +0 -0
  69. package/templates/addon/Assets/Art/Corner15.tga +0 -0
  70. package/templates/addon/Assets/Art/Corner16.tga +0 -0
  71. package/templates/addon/Assets/Art/Corner2.tga +0 -0
  72. package/templates/addon/Assets/Art/Corner3.tga +0 -0
  73. package/templates/addon/Assets/Art/Corner4.tga +0 -0
  74. package/templates/addon/Assets/Art/Corner5.tga +0 -0
  75. package/templates/addon/Assets/Art/Corner6.tga +0 -0
  76. package/templates/addon/Assets/Art/Corner7.tga +0 -0
  77. package/templates/addon/Assets/Art/Corner8.tga +0 -0
  78. package/templates/addon/Assets/Art/Corner9.tga +0 -0
  79. package/templates/addon/Assets/Art/Dot.tga +0 -0
  80. package/templates/addon/Assets/Art/Gear.tga +0 -0
  81. package/templates/addon/Assets/Art/Grip.tga +0 -0
  82. package/templates/addon/Assets/Art/Outline10.tga +0 -0
  83. package/templates/addon/Assets/Art/Outline12.tga +0 -0
  84. package/templates/addon/Assets/Art/Outline13.tga +0 -0
  85. package/templates/addon/Assets/Art/Outline14.tga +0 -0
  86. package/templates/addon/Assets/Art/Outline15.tga +0 -0
  87. package/templates/addon/Assets/Art/Outline2.tga +0 -0
  88. package/templates/addon/Assets/Art/Outline3.tga +0 -0
  89. package/templates/addon/Assets/Art/Outline5.tga +0 -0
  90. package/templates/addon/Assets/Art/Outline7.tga +0 -0
  91. package/templates/addon/Assets/Art/Outline9.tga +0 -0
  92. package/templates/addon/Assets/Art/Round11.tga +0 -0
  93. package/templates/addon/Assets/Art/Round11Border.tga +0 -0
  94. package/templates/addon/Assets/Art/Round4.tga +0 -0
  95. package/templates/addon/Assets/Art/Round4Border.tga +0 -0
  96. package/templates/addon/Assets/Art/Round6.tga +0 -0
  97. package/templates/addon/Assets/Art/Round6Border.tga +0 -0
  98. package/templates/addon/Assets/Art/Round8.tga +0 -0
  99. package/templates/addon/Assets/Art/Round8Border.tga +0 -0
  100. package/templates/addon/Assets/Art/Search.tga +0 -0
  101. package/templates/addon/CLAUDE.md +1 -0
  102. package/templates/addon/README.md +42 -7
  103. package/templates/addon/eslint.config.mjs +3 -9
  104. package/templates/addon/gitignore +1 -0
  105. package/templates/addon/kumi.config.ts +17 -0
  106. package/templates/addon/package.json +4 -5
  107. package/templates/addon/src/app/app.module.ts +18 -0
  108. package/templates/addon/src/app/commands.store.ts +11 -0
  109. package/templates/addon/src/app/layout/AppWindow.module.scss +92 -0
  110. package/templates/addon/src/app/layout/AppWindow.tsx +32 -0
  111. package/templates/addon/src/app/main.ts +5 -0
  112. package/templates/addon/src/app/routes/(window)/home/page.tsx +8 -0
  113. package/templates/addon/src/app/routes/(window)/plugins/page.tsx +38 -0
  114. package/templates/addon/src/app/routes/(window)/settings/page.tsx +8 -0
  115. package/templates/addon/src/app/theme.ts +6 -0
  116. package/templates/addon/src/modules/greeting/api/player.api.ts +29 -0
  117. package/templates/addon/src/modules/greeting/greeting.module.ts +18 -0
  118. package/templates/addon/src/modules/greeting/model/greeting.store.ts +81 -0
  119. package/templates/addon/src/modules/greeting/services/greeting.service.ts +38 -0
  120. package/templates/addon/src/modules/greeting/ui/Greeting.module.scss +105 -0
  121. package/templates/addon/src/modules/greeting/ui/GreetingCard.tsx +29 -0
  122. package/templates/addon/src/modules/greeting/widgets/GreetingHud.tsx +54 -0
  123. package/templates/addon/src/modules/greeting/widgets/GreetingOverview.tsx +18 -0
  124. package/templates/addon/src/modules/greeting/widgets/GreetingSettings.tsx +56 -0
  125. package/templates/addon/src/modules/playtime/api/clock.api.ts +6 -0
  126. package/templates/addon/src/modules/playtime/model/playtime.store.ts +19 -0
  127. package/templates/addon/src/modules/playtime/playtime.module.ts +18 -0
  128. package/templates/addon/src/modules/playtime/services/playtime.service.ts +18 -0
  129. package/templates/addon/src/modules/playtime/ui/Playtime.module.scss +25 -0
  130. package/templates/addon/src/modules/playtime/ui/PlaytimeBadge.tsx +10 -0
  131. package/templates/addon/src/modules/playtime/widgets/PlaytimePage.tsx +16 -0
  132. package/templates/addon/src/shared/api/native-art.ts +28 -0
  133. package/templates/addon/src/shared/assets/close.png +0 -0
  134. package/templates/addon/src/shared/lib/format.ts +20 -0
  135. package/templates/addon/src/shared/styles/_tokens.scss +12 -0
  136. package/templates/addon/src/shared/ui/Button.tsx +29 -0
  137. package/templates/addon/src/shared/ui/Choice.tsx +34 -0
  138. package/templates/addon/src/shared/ui/Controls.module.scss +93 -0
  139. package/templates/addon/src/shared/ui/Glyph.tsx +18 -0
  140. package/templates/addon/src/shared/ui/Slider.tsx +25 -0
  141. package/templates/addon/src/shared/ui/Toggle.tsx +29 -0
  142. package/templates/addon/src/shared/ui/focus-ref.ts +7 -0
  143. package/templates/addon/src/shared/ui/range-skin.tsx +15 -0
  144. package/templates/addon/tsconfig.json +49 -10
  145. package/wow/action-bar-layout.ts +108 -0
  146. package/wow/action-button.ts +219 -0
  147. package/wow/action-catalog.ts +98 -0
  148. package/wow/addon-manifest.ts +36 -0
  149. package/wow/app-ui.ts +221 -0
  150. package/wow/cooldown-timing.ts +24 -0
  151. package/wow/css-box.ts +40 -6
  152. package/wow/css-surfaces.ts +229 -24
  153. package/wow/cursor.ts +45 -0
  154. package/wow/frame-access.ts +23 -1
  155. package/wow/frame-timing.ts +13 -0
  156. package/wow/hooks.ts +133 -0
  157. package/wow/index.ts +18 -4
  158. package/wow/layout-view.ts +26 -14
  159. package/wow/locale-font.ts +15 -0
  160. package/wow/native.ts +18 -0
  161. package/wow/panel-host.ts +97 -0
  162. package/wow/pixel.ts +35 -0
  163. package/wow/plugins.ts +246 -0
  164. package/wow/protect.ts +27 -3
  165. package/wow/protected-view.ts +103 -0
  166. package/wow/range-art.ts +7 -0
  167. package/wow/readable-api.ts +120 -0
  168. package/wow/rounded-texture.ts +33 -6
  169. package/wow/saved-variables.ts +67 -18
  170. package/wow/spell-cooldown.ts +36 -0
  171. package/wow/start-addon.ts +31 -8
  172. package/wow/view.ts +201 -83
  173. package/templates/addon/__ADDON_NAME__.toc +0 -4
  174. package/templates/addon/scripts/build.mjs +0 -25
  175. package/templates/addon/src/app/main.tsx +0 -13
@@ -9,6 +9,10 @@ export interface OwnedReadonlyMap<Key, Value> extends ReadonlyMap<Key, Value> {
9
9
  readonly [collectionOwner]: "map";
10
10
  }
11
11
 
12
+ export interface OwnedWeakMap<Key extends object, Value> extends WeakMap<Key, Value> {
13
+ readonly [collectionOwner]: "weakmap";
14
+ }
15
+
12
16
  export interface OwnedSet<Value> extends Set<Value> {
13
17
  readonly [collectionOwner]: "set";
14
18
  }
@@ -34,6 +38,10 @@ export function ownedMap<Key, Value>(): OwnedMap<Key, Value> {
34
38
  return new Map<Key, Value>() as OwnedMap<Key, Value>;
35
39
  }
36
40
 
41
+ export function ownedWeakMap<Key extends object, Value>(): OwnedWeakMap<Key, Value> {
42
+ return new WeakMap<Key, Value>() as OwnedWeakMap<Key, Value>;
43
+ }
44
+
37
45
  export function ownedSet<Value>(): OwnedSet<Value> {
38
46
  return new Set<Value>() as OwnedSet<Value>;
39
47
  }
package/src/providers.ts CHANGED
@@ -111,7 +111,8 @@ export function resolveProviders<Exports extends ServiceExports>(moduleId: strin
111
111
  providers: readonly ServiceProvider[], publicTokens: Exports,
112
112
  imported: ReadonlyMap<ServiceToken<object>, object> = new Map(),
113
113
  resolveInput?: (this: void, token: ServiceToken<object>) => Result<object> | undefined,
114
- resolveScope?: (this: void) => Result<RuntimeScope>, feature?: FeatureLifecycle): Result<PublicServices<Exports>> {
114
+ resolveScope?: (this: void) => Result<RuntimeScope>, feature?: FeatureLifecycle,
115
+ ready?: (this: void, resolve: (this: void, token: ServiceToken<object>) => Result<object>) => Result<void>): Result<PublicServices<Exports>> {
115
116
  const definitions = new Map<ServiceToken<object>, ServiceProvider>();
116
117
  const inherited = imported as OwnedMap<ServiceToken<object>, object>;
117
118
  const values = new Map(inherited);
@@ -225,6 +226,11 @@ export function resolveProviders<Exports extends ServiceExports>(moduleId: strin
225
226
  }
226
227
  }
227
228
 
229
+ // Stores open after every provider and its lifecycle, so their setup can inject initialized services.
230
+ if (ready !== undefined) {
231
+ const injected = ready(token => resolve(token));
232
+ if (!injected.ok) return injected;
233
+ }
228
234
  const exports: Record<string, object> = {};
229
235
  for (const [name, token] of Object.entries(publicTokens)) {
230
236
  const result = resolve(token);
@@ -1,5 +1,5 @@
1
1
  import { createContext } from "./context";
2
- import { ref } from "./reactivity";
2
+ import { ref, type ComputedRef } from "./reactivity";
3
3
  import { fail, type Result } from "./result";
4
4
  import type { RuntimeScope } from "./runtime";
5
5
 
@@ -20,11 +20,11 @@ function missingComputationScope(operation: "computed" | "computedResult", name?
20
20
  }
21
21
 
22
22
  export function computed<Value>(read: (this: void) => Value, name?: string) {
23
- return context.use()?.computed(read, name) ?? ref<Result<Value>>(missingComputationScope("computed", name));
23
+ return context.use()?.computed(read, name) ?? ref<Result<Value>>(missingComputationScope("computed", name)) as unknown as ComputedRef<Value>;
24
24
  }
25
25
 
26
26
  export function computedResult<Value>(read: (this: void) => Result<Value>, name?: string) {
27
- return context.use()?.computedResult(read, name) ?? ref<Result<Value>>(missingComputationScope("computedResult", name));
27
+ return context.use()?.computedResult(read, name) ?? ref<Result<Value>>(missingComputationScope("computedResult", name)) as unknown as ComputedRef<Value>;
28
28
  }
29
29
 
30
30
  export const watch: RuntimeScope["watch"] = (read, change, options) =>
package/src/reactivity.ts CHANGED
@@ -11,6 +11,17 @@ export interface Ref<T> extends ReadonlyRef<T> {
11
11
  value: T;
12
12
  }
13
13
 
14
+ declare const signalSource: unique symbol;
15
+ declare const computedSource: unique symbol;
16
+
17
+ export interface SignalRef<T> extends Ref<T> {
18
+ readonly [signalSource]: true;
19
+ }
20
+
21
+ export interface ComputedRef<T> extends ReadonlyRef<Result<T>> {
22
+ readonly [computedSource]: true;
23
+ }
24
+
14
25
  /** A pure comparison, or false to invalidate on every write or tracked read. */
15
26
  export type Equality<T> = false | ((this: void, previous: T, next: T) => boolean);
16
27
 
@@ -104,10 +115,13 @@ function collect<T>(observer: Observer, read: (this: void) => T, protect: Protec
104
115
  return result;
105
116
  }
106
117
 
107
- const newSignal = createSignalFactory(track, notify, createDependency);
118
+ const signalFactory = createSignalFactory(track, notify, createDependency);
119
+ const newSignal = signalFactory.create;
120
+ /** @internal Used only by setup-store persistence. Ordinary signals keep their original setter. */
121
+ export const guardSetupSignal = signalFactory.guard;
108
122
 
109
- export function ref<T>(value: T, options?: RefOptions<T>): Ref<T> {
110
- return newSignal(value, options?.equals);
123
+ export function ref<T>(value: T, options?: RefOptions<T>): SignalRef<T> {
124
+ return newSignal(value, options?.equals) as SignalRef<T>;
111
125
  }
112
126
 
113
127
  class Computed<T> implements ReadonlyRef<Result<T>> {
@@ -154,6 +168,13 @@ class Computed<T> implements ReadonlyRef<Result<T>> {
154
168
  }
155
169
  }
156
170
 
171
+ export function setupRefKind(value: unknown): "signal" | "computed" | undefined {
172
+ if (value == null || typeof value !== "object") return undefined;
173
+ if (signalFactory.owns(value)) return "signal";
174
+ if (value instanceof Computed) return "computed";
175
+ return undefined;
176
+ }
177
+
157
178
  function cleanupFailure(value: unknown): Failure | undefined {
158
179
  if (value == null || typeof value !== "object") return;
159
180
  const candidate = value as Partial<Failure>;
@@ -172,14 +193,14 @@ export function createScope(scheduler: Scheduler) {
172
193
  return ok(() => cleanup.delete(stop));
173
194
  }
174
195
 
175
- function computedResult<T>(read: (this: void) => Result<T>, name?: string): ReadonlyRef<Result<T>> {
176
- if (disposed) return ref<Result<T>>(closed);
196
+ function computedResult<T>(read: (this: void) => Result<T>, name?: string): ComputedRef<T> {
197
+ if (disposed) return ref<Result<T>>(closed) as unknown as ComputedRef<T>;
177
198
  const value = new Computed(read, protect, name);
178
199
  cleanup.add(() => value.stop());
179
- return value;
200
+ return value as unknown as ComputedRef<T>;
180
201
  }
181
202
 
182
- function computed<T>(read: (this: void) => T, name?: string): ReadonlyRef<Result<T>> {
203
+ function computed<T>(read: (this: void) => T, name?: string): ComputedRef<T> {
183
204
  return computedResult(() => ok(read()), name);
184
205
  }
185
206
 
package/src/result.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export interface Failure {
2
2
  readonly ok: false;
3
3
  readonly reason: string;
4
+ readonly trace?: string;
4
5
  }
5
6
 
6
7
  export interface Success<Value> {
@@ -18,6 +19,11 @@ export function fail(reason: string): Failure {
18
19
  return { ok: false, reason };
19
20
  }
20
21
 
22
+ /** Format a diagnostic while keeping the reason available separately to callers. */
23
+ export function formatFailure(failure: Failure): string {
24
+ return failure.trace === undefined ? failure.reason : failure.reason + "\n" + failure.trace;
25
+ }
26
+
21
27
  export type Protect = <Value>(this: void, run: (this: void) => Value) => Result<Value>;
22
28
 
23
29
  /** For callbacks which already report errors as values. Hosts may inject a protected boundary. */
@@ -5,7 +5,12 @@ export function createSignalFactory<Dependency>(
5
5
  track: (this: void, dependency: Dependency) => void,
6
6
  notify: (this: void, dependency: Dependency) => void,
7
7
  makeDependency: (this: void) => Dependency,
8
- ): <Value>(this: void, initial: Value, equals?: Equality<Value>) => Ref<Value> {
8
+ ): {
9
+ create<Value>(this: void, initial: Value, equals?: Equality<Value>): Ref<Value>;
10
+ owns(this: void, value: unknown): boolean;
11
+ guard<Value>(this: void, signal: Ref<Value>, before: (this: void, next: Value) => void):
12
+ { peek(this: void): Value; detach(this: void): void } | undefined;
13
+ } {
9
14
  class Signal<Value> implements Ref<Value> {
10
15
  private readonly observers = makeDependency();
11
16
 
@@ -24,7 +29,35 @@ export function createSignalFactory<Dependency>(
24
29
  this.current = next;
25
30
  notify(this.observers);
26
31
  }
32
+
33
+ guard(before: (this: void, next: Value) => void) {
34
+ if (Object.getOwnPropertyDescriptor(this, "value") !== undefined) return undefined;
35
+ Object.defineProperty(this, "value", {
36
+ configurable: true,
37
+ get: () => {
38
+ track(this.observers);
39
+ return this.current;
40
+ },
41
+ set: (next: Value) => {
42
+ const { current, equals } = this;
43
+ if (equals === true) {
44
+ if (next === current) return;
45
+ } else if (equals !== false && equals(current, next)) return;
46
+ before(next);
47
+ this.current = next;
48
+ notify(this.observers);
49
+ },
50
+ });
51
+ return {
52
+ peek: () => this.current,
53
+ detach: () => { delete (this as { value?: Value }).value; },
54
+ };
55
+ }
27
56
  }
28
57
 
29
- return (initial, equals) => new Signal(initial, equals);
58
+ return {
59
+ create: (initial, equals) => new Signal(initial, equals),
60
+ owns: value => value instanceof Signal,
61
+ guard: (signal, before) => signal instanceof Signal ? signal.guard(before) : undefined,
62
+ };
30
63
  }
package/state/index.ts CHANGED
@@ -1,3 +1,9 @@
1
1
  export { computed, computedResult, watch, watchEffect, withReactiveScope } from "../src/reactive-scope";
2
2
  export { ref, type Equality, type ReadonlyRef, type Ref, type RefOptions, type WatchOptions } from "../src/reactivity";
3
3
  export { createStateStore, createStore, type StateStore, type StoreStorage } from "./store";
4
+ export { batch } from "./setup-store-persistence";
5
+ export {
6
+ defineStore, inject, readonly, storeToRefs,
7
+ type AnyStoreFactory, type SetupStore, type SetupStoreOptions, type SetupStoreRefs, type StoreApi, type StoreFactory, type StoreReadonly,
8
+ } from "./setup-store";
9
+ export type { ComputedRef, SignalRef } from "../src/reactivity";
@@ -0,0 +1,206 @@
1
+ import { ownedArray, ownedSet, type OwnedArray, type OwnedReadonlyArray, type OwnedRecord, type OwnedSet } from "../src/owned-collections";
2
+ import { guardSetupSignal, setupRefKind, type Ref } from "../src/reactivity";
3
+ import { fail, formatFailure, ok, type Result } from "../src/result";
4
+ import type { RuntimeScope } from "../src/runtime";
5
+ import type { Cancel } from "../src/scheduler";
6
+ import type { StoreStorage } from "./store";
7
+
8
+ type Snapshot = Record<string, unknown>;
9
+ export interface StorePersistence {
10
+ readonly pick: OwnedReadonlyArray<string>;
11
+ readonly perCharacter?: boolean;
12
+ readonly storage?: StoreStorage<Snapshot>;
13
+ }
14
+
15
+ /** Saves one store's batched field writes, or puts the fields back when storage rejects them. */
16
+ interface PendingSave {
17
+ flush(this: void): Result<void>;
18
+ rollback(this: void): void;
19
+ }
20
+
21
+ let batchDepth = 0;
22
+ let pendingSaves: OwnedArray<PendingSave> | undefined;
23
+
24
+ function requireSuccess<T>(result: Result<T>): T {
25
+ if (!result.ok) throw new Error(formatFailure(result));
26
+ return result.value;
27
+ }
28
+
29
+ function settle(failure?: Result<never>) {
30
+ const saves = pendingSaves;
31
+ pendingSaves = undefined;
32
+ if (saves === undefined) return failure;
33
+ if (failure !== undefined) {
34
+ for (const save of saves) save.rollback();
35
+ return failure;
36
+ }
37
+ let result: Result<never> | undefined;
38
+ for (const save of saves) {
39
+ if (result !== undefined) {
40
+ save.rollback();
41
+ continue;
42
+ }
43
+ const saved = save.flush();
44
+ if (!saved.ok) result = saved;
45
+ }
46
+ return result;
47
+ }
48
+
49
+ /**
50
+ * Run several store writes as one change. Each store saves its persisted fields once at the end.
51
+ * If the callback throws or storage rejects a save, that store's fields return to their previous values.
52
+ */
53
+ export function batch<T>(this: void, run: (this: void) => T): Result<T> {
54
+ batchDepth++;
55
+ let value: T;
56
+ try {
57
+ value = run();
58
+ } catch (problem) {
59
+ batchDepth--;
60
+ const failure = fail(String(problem));
61
+ return batchDepth === 0 ? settle(failure) ?? failure : failure;
62
+ }
63
+ batchDepth--;
64
+ if (batchDepth > 0) return ok(value);
65
+ return settle() ?? ok(value);
66
+ }
67
+
68
+ export function deferStoreWatches(scope: RuntimeScope) {
69
+ const { watch, watchEffect } = scope;
70
+ const pending = ownedArray<(this: void) => void>();
71
+
72
+ function defer(start: (this: void) => Result<Cancel>): Result<Cancel> {
73
+ let cancelled = false;
74
+ let stop: Cancel | undefined;
75
+ pending.push(() => {
76
+ if (cancelled) return;
77
+ const attached = requireSuccess(start());
78
+ if (cancelled) attached();
79
+ else stop = attached;
80
+ });
81
+ return ok(() => {
82
+ cancelled = true;
83
+ stop?.();
84
+ stop = undefined;
85
+ });
86
+ }
87
+
88
+ scope.watch = (read, change, options) => defer(() => watch(read, change, options));
89
+ scope.watchEffect = effect => defer(() => watchEffect(effect));
90
+ const restore = () => {
91
+ scope.watch = watch;
92
+ scope.watchEffect = watchEffect;
93
+ };
94
+ const unregister = requireSuccess(scope.onDispose(restore));
95
+ return () => {
96
+ unregister();
97
+ restore();
98
+ for (const start of pending) start();
99
+ };
100
+ }
101
+
102
+ export function hydrateSetupStore(id: string, scope: RuntimeScope, pick: OwnedReadonlyArray<string>, storage: StoreStorage<Snapshot>,
103
+ cells: Readonly<Record<string, Ref<unknown>>>) {
104
+ const selected = ownedArray<{ key: string; cell: Ref<unknown> }>();
105
+ const peek = ownedArray<(this: void) => unknown>();
106
+ const seen = ownedSet<Ref<unknown>>();
107
+ for (const key of pick) {
108
+ const cell = cells[key];
109
+ if (cell === undefined || setupRefKind(cell) !== "signal") throw new Error("Persisted field " + key + " needs a Kumi ref");
110
+ if (seen.has(cell)) throw new Error("Persisted field " + key + " repeats a ref");
111
+ seen.add(cell);
112
+ selected.push({ key, cell });
113
+ }
114
+
115
+ if (storage.claim !== undefined) requireSuccess(scope.onDispose(requireSuccess(storage.claim(id))));
116
+ const restored = requireSuccess(storage.read());
117
+ let committed: Snapshot = {};
118
+ let writing = false;
119
+ let hydrated = false;
120
+ let restoring = false;
121
+ // Lua tables drop nil values, so the changed keys are tracked separately from their previous values.
122
+ let changed: OwnedSet<string> | undefined;
123
+ let previous: Snapshot = {};
124
+
125
+ function snapshot(): Snapshot {
126
+ const next: Snapshot = {};
127
+ for (let index = 0; index < selected.length; index++) next[selected[index].key] = peek[index]();
128
+ return next;
129
+ }
130
+
131
+ function write(next: Snapshot, name: string) {
132
+ writing = true;
133
+ try {
134
+ const written = storage.write(next);
135
+ if (!written.ok) return fail("Could not save " + name + ": " + formatFailure(written));
136
+ committed = next;
137
+ return ok(undefined);
138
+ } finally {
139
+ writing = false;
140
+ }
141
+ }
142
+
143
+ const save: PendingSave = {
144
+ flush: () => {
145
+ if (changed === undefined) return ok(undefined);
146
+ const saved = write(snapshot(), "store " + id);
147
+ if (!saved.ok) {
148
+ save.rollback();
149
+ return saved;
150
+ }
151
+ changed = undefined;
152
+ previous = {};
153
+ return saved;
154
+ },
155
+ rollback: () => {
156
+ const keys = changed;
157
+ const values = previous;
158
+ changed = undefined;
159
+ previous = {};
160
+ if (keys === undefined) return;
161
+ restoring = true;
162
+ try {
163
+ for (const { key, cell } of selected) {
164
+ if (keys.has(key)) cell.value = values[key];
165
+ }
166
+ } finally {
167
+ restoring = false;
168
+ }
169
+ },
170
+ };
171
+
172
+ for (const field of selected) {
173
+ const { key, cell } = field;
174
+ const name = id + "." + key;
175
+ const guard = guardSetupSignal(cell, next => {
176
+ if (!hydrated || restoring) return;
177
+ if (writing) throw new Error("Reentrant write to persisted field " + name);
178
+ if (batchDepth > 0) {
179
+ let keys = changed;
180
+ if (keys === undefined) {
181
+ keys = ownedSet<string>();
182
+ changed = keys;
183
+ const saves = pendingSaves ??= ownedArray<PendingSave>();
184
+ saves.push(save);
185
+ }
186
+ if (!keys.has(key)) {
187
+ keys.add(key);
188
+ previous[key] = committed[key];
189
+ }
190
+ return;
191
+ }
192
+ const result = write({ ...(committed as OwnedRecord<Snapshot>), [key]: next }, "field " + name);
193
+ if (!result.ok) throw new Error(result.reason);
194
+ });
195
+ if (guard === undefined) throw new Error("Persisted field " + key + " already has a storage owner");
196
+ requireSuccess(scope.onDispose(guard.detach));
197
+ peek.push(guard.peek);
198
+ }
199
+ for (let index = 0; index < selected.length; index++) {
200
+ const { key, cell } = selected[index];
201
+ const value = restored?.[key];
202
+ if (value !== undefined) cell.value = value;
203
+ committed[key] = peek[index]();
204
+ }
205
+ hydrated = true;
206
+ }
@@ -0,0 +1,10 @@
1
+ /** @internal The native compiler lowers this accessor view to a Lua metatable. */
2
+ export interface StoreAccessor {
3
+ readonly get: (this: void) => unknown;
4
+ readonly set?: (this: void, value: unknown) => void;
5
+ readonly enumerable: true;
6
+ }
7
+
8
+ export function createSetupStoreView(fields: Record<string, unknown>, accessors: Record<string, StoreAccessor>): object {
9
+ return Object.defineProperties(fields, accessors);
10
+ }