@overmvp/kumi 0.1.0 → 0.4.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 (201) hide show
  1. package/README.md +59 -6
  2. package/animation/index.ts +4 -0
  3. package/animation/motion-policy.ts +20 -0
  4. package/animation/slide.ts +61 -0
  5. package/animation/spring.ts +75 -0
  6. package/animation/staggered-reveal.ts +34 -0
  7. package/builder/css-gradients.mjs +74 -0
  8. package/builder/css-mask-assets.mjs +52 -0
  9. package/builder/css-mask-assets.test.mjs +31 -0
  10. package/builder/css-v1.mjs +127 -23
  11. package/builder/css-v1.test.mjs +82 -2
  12. package/builder/link-addon-package.mjs +47 -6
  13. package/builder/module-declarations.test.mjs +9 -18
  14. package/builder/native-kernels.mjs +1 -1
  15. package/builder/src/compiler.rs +205 -8
  16. package/builder/src/lua_upvalues.rs +641 -0
  17. package/builder/src/main.rs +20 -5
  18. package/builder/src/native_ir.rs +1 -1
  19. package/builder/src/native_signal.rs +46 -10
  20. package/builder/src/numbers.lua +14 -0
  21. package/builder/src/project-front.mjs +385 -34
  22. package/builder/src/routes.rs +11 -14
  23. package/builder/src/setup-store.lua +18 -0
  24. package/builder/src/signal-kernel.fingerprint +1 -1
  25. package/builder/src/ts-lower.mjs +2 -2
  26. package/builder/src/wow-reads.lua +22 -0
  27. package/builder/style-modules.mjs +111 -0
  28. package/builder/style-modules.test.mjs +24 -0
  29. package/builder/style-states.mjs +6 -4
  30. package/config.ts +56 -14
  31. package/eslint.mjs +74 -0
  32. package/form/index.ts +15 -11
  33. package/package.json +11 -7
  34. package/router/index.ts +10 -2
  35. package/router/link.tsx +32 -0
  36. package/router/navigation.ts +22 -0
  37. package/router/router-view.ts +134 -0
  38. package/scripts/addon-build.mjs +377 -0
  39. package/scripts/addon-project.mjs +89 -0
  40. package/scripts/kumi-cli.mjs +52 -17
  41. package/scripts/link-addons.mjs +12 -2
  42. package/src/bindings.ts +12 -6
  43. package/src/context.ts +31 -7
  44. package/src/css-tokens.ts +27 -13
  45. package/src/css-v1.ts +13 -0
  46. package/src/elements.ts +35 -0
  47. package/src/flex-layout.ts +26 -5
  48. package/src/frame-scheduler.ts +6 -2
  49. package/src/index.ts +2 -1
  50. package/src/jsx-runtime.ts +8 -1
  51. package/src/keyed-list.ts +17 -11
  52. package/src/module-ui.ts +163 -0
  53. package/src/module.ts +51 -8
  54. package/src/owned-collections.ts +8 -0
  55. package/src/providers.ts +7 -1
  56. package/src/reactive-scope.ts +3 -3
  57. package/src/reactivity.ts +42 -8
  58. package/src/result.ts +6 -0
  59. package/src/signal-kernel.ts +35 -2
  60. package/src/style-classes.ts +22 -1
  61. package/src/style-states.ts +13 -6
  62. package/state/index.ts +6 -0
  63. package/state/setup-store-persistence.ts +206 -0
  64. package/state/setup-store-view.ts +10 -0
  65. package/state/setup-store.ts +342 -0
  66. package/state/store.ts +2 -0
  67. package/templates/addon/.agents/skills/kumi-build-debug/SKILL.md +36 -0
  68. package/templates/addon/.agents/skills/kumi-feature/SKILL.md +50 -0
  69. package/templates/addon/.agents/skills/kumi-plugin/SKILL.md +36 -0
  70. package/templates/addon/.agents/skills/kumi-store/SKILL.md +47 -0
  71. package/templates/addon/.agents/skills/kumi-ui/SKILL.md +73 -0
  72. package/templates/addon/.agents/skills/kumi-wow-api/SKILL.md +30 -0
  73. package/templates/addon/.claude/skills/kumi-build-debug/SKILL.md +36 -0
  74. package/templates/addon/.claude/skills/kumi-feature/SKILL.md +50 -0
  75. package/templates/addon/.claude/skills/kumi-plugin/SKILL.md +36 -0
  76. package/templates/addon/.claude/skills/kumi-store/SKILL.md +47 -0
  77. package/templates/addon/.claude/skills/kumi-ui/SKILL.md +73 -0
  78. package/templates/addon/.claude/skills/kumi-wow-api/SKILL.md +30 -0
  79. package/templates/addon/AGENTS.md +34 -0
  80. package/templates/addon/Assets/Art/Corner10.tga +0 -0
  81. package/templates/addon/Assets/Art/Corner11.tga +0 -0
  82. package/templates/addon/Assets/Art/Corner12.tga +0 -0
  83. package/templates/addon/Assets/Art/Corner13.tga +0 -0
  84. package/templates/addon/Assets/Art/Corner14.tga +0 -0
  85. package/templates/addon/Assets/Art/Corner15.tga +0 -0
  86. package/templates/addon/Assets/Art/Corner16.tga +0 -0
  87. package/templates/addon/Assets/Art/Corner2.tga +0 -0
  88. package/templates/addon/Assets/Art/Corner3.tga +0 -0
  89. package/templates/addon/Assets/Art/Corner4.tga +0 -0
  90. package/templates/addon/Assets/Art/Corner5.tga +0 -0
  91. package/templates/addon/Assets/Art/Corner6.tga +0 -0
  92. package/templates/addon/Assets/Art/Corner7.tga +0 -0
  93. package/templates/addon/Assets/Art/Corner8.tga +0 -0
  94. package/templates/addon/Assets/Art/Corner9.tga +0 -0
  95. package/templates/addon/Assets/Art/Dot.tga +0 -0
  96. package/templates/addon/Assets/Art/Gear.tga +0 -0
  97. package/templates/addon/Assets/Art/Grip.tga +0 -0
  98. package/templates/addon/Assets/Art/Outline10.tga +0 -0
  99. package/templates/addon/Assets/Art/Outline12.tga +0 -0
  100. package/templates/addon/Assets/Art/Outline13.tga +0 -0
  101. package/templates/addon/Assets/Art/Outline14.tga +0 -0
  102. package/templates/addon/Assets/Art/Outline15.tga +0 -0
  103. package/templates/addon/Assets/Art/Outline2.tga +0 -0
  104. package/templates/addon/Assets/Art/Outline3.tga +0 -0
  105. package/templates/addon/Assets/Art/Outline5.tga +0 -0
  106. package/templates/addon/Assets/Art/Outline7.tga +0 -0
  107. package/templates/addon/Assets/Art/Outline9.tga +0 -0
  108. package/templates/addon/Assets/Art/Round11.tga +0 -0
  109. package/templates/addon/Assets/Art/Round11Border.tga +0 -0
  110. package/templates/addon/Assets/Art/Round4.tga +0 -0
  111. package/templates/addon/Assets/Art/Round4Border.tga +0 -0
  112. package/templates/addon/Assets/Art/Round6.tga +0 -0
  113. package/templates/addon/Assets/Art/Round6Border.tga +0 -0
  114. package/templates/addon/Assets/Art/Round8.tga +0 -0
  115. package/templates/addon/Assets/Art/Round8Border.tga +0 -0
  116. package/templates/addon/Assets/Art/Search.tga +0 -0
  117. package/templates/addon/CLAUDE.md +1 -0
  118. package/templates/addon/README.md +42 -7
  119. package/templates/addon/eslint.config.mjs +3 -9
  120. package/templates/addon/gitignore +1 -0
  121. package/templates/addon/kumi.config.ts +17 -0
  122. package/templates/addon/package.json +4 -5
  123. package/templates/addon/src/app/app.module.ts +18 -0
  124. package/templates/addon/src/app/commands.store.ts +11 -0
  125. package/templates/addon/src/app/layout/AppWindow.module.css +90 -0
  126. package/templates/addon/src/app/layout/AppWindow.tsx +32 -0
  127. package/templates/addon/src/app/main.ts +5 -0
  128. package/templates/addon/src/app/routes/(window)/home/page.tsx +8 -0
  129. package/templates/addon/src/app/routes/(window)/plugins/page.tsx +38 -0
  130. package/templates/addon/src/app/routes/(window)/settings/page.tsx +8 -0
  131. package/templates/addon/src/app/theme.ts +6 -0
  132. package/templates/addon/src/modules/greeting/api/player.api.ts +29 -0
  133. package/templates/addon/src/modules/greeting/greeting.module.ts +18 -0
  134. package/templates/addon/src/modules/greeting/model/greeting.store.ts +81 -0
  135. package/templates/addon/src/modules/greeting/services/greeting.service.ts +38 -0
  136. package/templates/addon/src/modules/greeting/ui/Greeting.module.css +103 -0
  137. package/templates/addon/src/modules/greeting/ui/GreetingCard.tsx +29 -0
  138. package/templates/addon/src/modules/greeting/widgets/GreetingHud.tsx +54 -0
  139. package/templates/addon/src/modules/greeting/widgets/GreetingOverview.tsx +18 -0
  140. package/templates/addon/src/modules/greeting/widgets/GreetingSettings.tsx +56 -0
  141. package/templates/addon/src/modules/playtime/api/clock.api.ts +6 -0
  142. package/templates/addon/src/modules/playtime/model/playtime.store.ts +19 -0
  143. package/templates/addon/src/modules/playtime/playtime.module.ts +18 -0
  144. package/templates/addon/src/modules/playtime/services/playtime.service.ts +18 -0
  145. package/templates/addon/src/modules/playtime/ui/Playtime.module.css +23 -0
  146. package/templates/addon/src/modules/playtime/ui/PlaytimeBadge.tsx +10 -0
  147. package/templates/addon/src/modules/playtime/widgets/PlaytimePage.tsx +16 -0
  148. package/templates/addon/src/shared/api/native-art.ts +28 -0
  149. package/templates/addon/src/shared/assets/close.png +0 -0
  150. package/templates/addon/src/shared/lib/format.ts +20 -0
  151. package/templates/addon/src/shared/styles/tokens.css +13 -0
  152. package/templates/addon/src/shared/ui/Button.tsx +29 -0
  153. package/templates/addon/src/shared/ui/Choice.tsx +34 -0
  154. package/templates/addon/src/shared/ui/Controls.module.css +91 -0
  155. package/templates/addon/src/shared/ui/Glyph.tsx +18 -0
  156. package/templates/addon/src/shared/ui/Slider.tsx +25 -0
  157. package/templates/addon/src/shared/ui/Toggle.tsx +29 -0
  158. package/templates/addon/src/shared/ui/focus-ref.ts +7 -0
  159. package/templates/addon/src/shared/ui/range-skin.tsx +15 -0
  160. package/templates/addon/tsconfig.json +49 -10
  161. package/wow/action-bar-layout.ts +108 -0
  162. package/wow/action-button.ts +244 -0
  163. package/wow/action-catalog.ts +98 -0
  164. package/wow/addon-manifest.ts +38 -0
  165. package/wow/animation.ts +3 -14
  166. package/wow/app-ui.ts +230 -0
  167. package/wow/cooldown-timing.ts +24 -0
  168. package/wow/css-background-image.ts +75 -0
  169. package/wow/css-box.ts +46 -10
  170. package/wow/css-image-mask.ts +32 -0
  171. package/wow/css-surfaces.ts +295 -43
  172. package/wow/cursor.ts +45 -0
  173. package/wow/element-events.ts +33 -13
  174. package/wow/frame-access.ts +23 -1
  175. package/wow/frame-timing.ts +13 -0
  176. package/wow/heal-prediction.ts +2 -4
  177. package/wow/hooks.ts +133 -0
  178. package/wow/index.ts +19 -4
  179. package/wow/layout-view.ts +44 -23
  180. package/wow/locale-font.ts +15 -0
  181. package/wow/module-replacements.ts +103 -0
  182. package/wow/native.ts +18 -0
  183. package/wow/panel-host.ts +97 -0
  184. package/wow/pixel.ts +35 -0
  185. package/wow/plugins.ts +246 -0
  186. package/wow/pointer-click.ts +35 -0
  187. package/wow/protect.ts +27 -3
  188. package/wow/protected-view.ts +139 -0
  189. package/wow/range-art.ts +7 -0
  190. package/wow/readable-api.ts +120 -0
  191. package/wow/rounded-texture.ts +38 -6
  192. package/wow/saved-variables.ts +67 -18
  193. package/wow/spell-cooldown.ts +36 -0
  194. package/wow/start-addon.ts +31 -8
  195. package/wow/state-paint.ts +5 -14
  196. package/wow/texture-fill.ts +10 -0
  197. package/wow/unit-cast.ts +6 -4
  198. package/wow/view.ts +458 -228
  199. package/templates/addon/__ADDON_NAME__.toc +0 -4
  200. package/templates/addon/scripts/build.mjs +0 -25
  201. package/templates/addon/src/app/main.tsx +0 -13
@@ -4,12 +4,18 @@ import type { OwnedArray, OwnedReadonlyArray } from "./owned-collections";
4
4
 
5
5
  export type StyleState = "hover" | "active" | "focus" | "disabled" | "checked";
6
6
 
7
+ export interface CssLinearGradient {
8
+ readonly axis: "HORIZONTAL" | "VERTICAL";
9
+ readonly min: string;
10
+ readonly max: string;
11
+ }
12
+
7
13
  export interface StatePaint {
8
14
  color?: string;
9
15
  backgroundColor?: string;
10
16
  borderColor?: string;
11
17
  opacity?: number;
12
- backgroundImage?: Readonly<{ path: string } | { atlas: string }>;
18
+ backgroundImage?: Readonly<{ path: string } | { atlas: string } | { gradient: CssLinearGradient }>;
13
19
  styleTokens?: readonly CssTokenRecipe[];
14
20
  }
15
21
 
@@ -51,12 +57,13 @@ function matches(required: number, active: number) {
51
57
  return true;
52
58
  }
53
59
 
54
- function sameImage(left: StatePaint["backgroundImage"], right: StatePaint["backgroundImage"]) {
60
+ export function sameBackgroundImage(left: StatePaint["backgroundImage"], right: StatePaint["backgroundImage"]) {
55
61
  if (left === right) return true;
56
62
  if (left === undefined || right === undefined) return false;
57
- return "path" in left
58
- ? "path" in right && left.path === right.path
59
- : "atlas" in right && left.atlas === right.atlas;
63
+ if ("path" in left) return "path" in right && left.path === right.path;
64
+ if ("atlas" in left) return "atlas" in right && left.atlas === right.atlas;
65
+ return "gradient" in right && left.gradient.axis === right.gradient.axis
66
+ && left.gradient.min === right.gradient.min && left.gradient.max === right.gradient.max;
60
67
  }
61
68
 
62
69
  function sameTokens(left: StatePaint["styleTokens"], right: StatePaint["styleTokens"]) {
@@ -100,7 +107,7 @@ export function prepareStyleStates(this: void, base: Readonly<StatePaint>, varia
100
107
  }
101
108
  for (const paint of snapshots) {
102
109
  if (paint.color === color && paint.backgroundColor === backgroundColor && paint.borderColor === borderColor && paint.opacity === opacity
103
- && sameImage(paint.backgroundImage, backgroundImage) && sameTokens(paint.styleTokens, styleTokens)) return paint;
110
+ && sameBackgroundImage(paint.backgroundImage, backgroundImage) && sameTokens(paint.styleTokens, styleTokens)) return paint;
104
111
  }
105
112
  const paint: StatePaint = {};
106
113
  if (color !== undefined) paint.color = color;
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
+ }
@@ -0,0 +1,342 @@
1
+ import { direct, fail, formatFailure, ok, type Result } from "../src/result";
2
+ import { withReactiveScope } from "../src/reactive-scope";
3
+ import { registerRefView, setupRefKind, type ComputedRef, type ReadonlyRef, type Ref, type SignalRef } from "../src/reactivity";
4
+ import type { RuntimeScope } from "../src/runtime";
5
+ import type { ServiceToken } from "../src/providers";
6
+ import { ownedArray, ownedMap, ownedWeakMap, type OwnedMap, type OwnedReadonlyArray, type OwnedWeakMap } from "../src/owned-collections";
7
+ import { batch, deferStoreWatches, hydrateSetupStore, type StorePersistence } from "./setup-store-persistence";
8
+ import { createSetupStoreView, type StoreAccessor } from "./setup-store-view";
9
+ import type { StoreStorage } from "./store";
10
+
11
+ declare const setupStoreShape: unique symbol;
12
+ declare const readonlySource: unique symbol;
13
+
14
+ /** A read-only view of a store ref. Actions still write the original ref. */
15
+ export interface StoreReadonly<T> extends ReadonlyRef<T> {
16
+ readonly [readonlySource]: true;
17
+ }
18
+
19
+ type StoreField<Value> = Value extends SignalRef<infer State> ? State
20
+ : Value extends ComputedRef<infer State> ? State
21
+ : Value extends StoreReadonly<infer State> ? State : Value;
22
+ type WritableStoreKeys<Source> = {
23
+ [Key in keyof Source]-?: Source[Key] extends SignalRef<unknown> ? Key : never
24
+ }[keyof Source];
25
+ type ReadonlyStoreKeys<Source> = {
26
+ [Key in keyof Source]-?: Source[Key] extends StoreReadonly<unknown> ? Key : never
27
+ }[keyof Source];
28
+ type StorePatch<Source> = { [Key in WritableStoreKeys<Source>]?: StoreField<Source[Key]> };
29
+
30
+ /** Members Kumi adds to every store. */
31
+ export interface StoreApi<Source extends object> {
32
+ /** The ID passed to defineStore. */
33
+ readonly $id: string;
34
+ /** Write several writable fields as one change. Persisted fields are saved once. */
35
+ $patch(this: void, values: StorePatch<Source>): Result<void>;
36
+ }
37
+
38
+ export type SetupStore<Source extends object> = {
39
+ -readonly [Key in WritableStoreKeys<Source>]: StoreField<Source[Key]>
40
+ } & {
41
+ readonly [Key in Exclude<keyof Source, WritableStoreKeys<Source>>]: StoreField<Source[Key]>
42
+ } & StoreApi<Source> & { readonly [setupStoreShape]: Source };
43
+
44
+ export type SetupStoreRefs<Source extends object> = {
45
+ [Key in keyof Source as Source[Key] extends SignalRef<unknown> | ComputedRef<unknown> | StoreReadonly<unknown> ? Key : never]:
46
+ Source[Key] extends ComputedRef<infer State> ? ReadonlyRef<State>
47
+ : Source[Key] extends StoreReadonly<infer State> ? ReadonlyRef<State> : Source[Key]
48
+ };
49
+
50
+ type PersistedStoreKey<Source> = (WritableStoreKeys<Source> | ReadonlyStoreKeys<Source>) & string;
51
+
52
+ export interface SetupStoreOptions<Source extends object, Key extends PersistedStoreKey<Source>> {
53
+ readonly persist?: {
54
+ /** Refs to save. A field exposed through readonly() can be saved too. */
55
+ readonly pick: readonly Key[];
56
+ /** Save in the addon's per-character SavedVariables instead of the account-wide one. */
57
+ readonly perCharacter?: boolean;
58
+ /** Defaults to the addon's SavedVariables, under this store's ID. */
59
+ readonly storage?: StoreStorage<{ [Field in NoInfer<Key>]: StoreField<Source[Field]> }>;
60
+ };
61
+ }
62
+
63
+ /** The function defineStore returns. Call it to get the store. */
64
+ export type StoreFactory<Source extends object> = (this: void, owner?: RuntimeScope) => SetupStore<Source>;
65
+ /** Any function returned by defineStore, as listed in a module's `stores`. */
66
+ export type AnyStoreFactory = (this: void, owner?: RuntimeScope) => object;
67
+
68
+ type Inject = (this: void, token: ServiceToken<object>) => Result<object>;
69
+ type DefaultStorage = (this: void, id: string, defaults: Readonly<Record<string, unknown>>, perCharacter: boolean) =>
70
+ StoreStorage<Record<string, unknown>> | undefined;
71
+
72
+ interface StoreDefinition {
73
+ readonly id: string;
74
+ readonly setup: (this: void) => object;
75
+ readonly persistence?: StorePersistence;
76
+ }
77
+
78
+ interface StoreSlot {
79
+ readonly definition: StoreDefinition;
80
+ store?: object;
81
+ }
82
+
83
+ interface Registration {
84
+ readonly owner: RuntimeScope;
85
+ readonly resolve?: Inject;
86
+ }
87
+
88
+ /** @internal The stores of one addon: one instance per store ID, shared by every module and load-on-demand part. */
89
+ export interface StoreHost {
90
+ readonly registrations: OwnedMap<StoreDefinition, Registration>;
91
+ readonly instances: OwnedMap<string, StoreSlot>;
92
+ readonly root: (this: void) => RuntimeScope | undefined;
93
+ storage?: DefaultStorage;
94
+ }
95
+
96
+ class ReadonlyView<T> implements ReadonlyRef<T> {
97
+ constructor(readonly source: Ref<T>) {}
98
+
99
+ get value(): T {
100
+ return this.source.value;
101
+ }
102
+ }
103
+
104
+ class StoreComputed<T> implements ReadonlyRef<T> {
105
+ constructor(private readonly source: ComputedRef<T>, private readonly name: string) {}
106
+
107
+ get value(): T {
108
+ const value = this.source.value;
109
+ if (!value.ok) throw new Error(this.name + ": " + formatFailure(value));
110
+ return value.value;
111
+ }
112
+ }
113
+
114
+ const definitions = ownedWeakMap<AnyStoreFactory, StoreDefinition>();
115
+ let owners: OwnedWeakMap<RuntimeScope, OwnedMap<string, StoreSlot>> | undefined;
116
+ let bindings: OwnedWeakMap<object, object> | undefined;
117
+ const opening: string[] = [];
118
+ let activeHost: StoreHost | undefined;
119
+ let activeInject: Inject | undefined;
120
+
121
+ /** Expose a ref read-only. Store actions keep writing the ref you pass in. */
122
+ export function readonly<T>(this: void, source: Ref<T>): StoreReadonly<T> {
123
+ return registerRefView(new ReadonlyView(source)) as unknown as StoreReadonly<T>;
124
+ }
125
+
126
+ /**
127
+ * Get a service inside a store's setup. The store must be listed in a module's `stores`,
128
+ * and the token must be one of that module's providers or an export of a module it imports.
129
+ */
130
+ export function inject<Value extends object>(this: void, token: abstract new (...dependencies: never[]) => Value): Value;
131
+ export function inject<Value extends object>(this: void, token: ServiceToken<Value>): Value;
132
+ export function inject<Value extends object>(this: void, token: ServiceToken<Value>): Value {
133
+ const resolve = activeInject;
134
+ if (resolve === undefined) {
135
+ throw new Error("inject(" + token.name + ") works only inside the setup of a store listed in a module's stores");
136
+ }
137
+ const result = resolve(token);
138
+ if (!result.ok) throw new Error(formatFailure(result));
139
+ return result.value as Value;
140
+ }
141
+
142
+ function createStoreFields(id: string, source: Record<string, unknown>) {
143
+ const fields: Record<string, unknown> = {};
144
+ const accessors: Record<string, StoreAccessor> = {};
145
+ const refs: Record<string, ReadonlyRef<unknown>> = {};
146
+ const cells: Record<string, Ref<unknown>> = {};
147
+ for (const key of Object.keys(source)) {
148
+ if (key === "$id" || key === "$patch") throw new Error("Store " + id + " cannot declare " + key);
149
+ const value = source[key];
150
+ const kind = setupRefKind(value);
151
+ if (kind === "signal") {
152
+ const cell = value as Ref<unknown>;
153
+ refs[key] = cell;
154
+ cells[key] = cell;
155
+ accessors[key] = { get: () => cell.value, set: next => { cell.value = next; }, enumerable: true };
156
+ } else if (kind === "computed") {
157
+ const cell = registerRefView(new StoreComputed(value as ComputedRef<unknown>, id + "." + key));
158
+ refs[key] = cell;
159
+ accessors[key] = { get: () => cell.value, enumerable: true };
160
+ } else if (value instanceof ReadonlyView) {
161
+ const view = value as ReadonlyView<unknown>;
162
+ refs[key] = view;
163
+ cells[key] = view.source;
164
+ accessors[key] = { get: () => view.value, enumerable: true };
165
+ } else {
166
+ fields[key] = value;
167
+ }
168
+ }
169
+ fields.$id = id;
170
+ fields.$patch = (values: Record<string, unknown>) => batch(() => {
171
+ for (const key of Object.keys(values)) {
172
+ const accessor = accessors[key];
173
+ const write = accessor?.set;
174
+ if (write === undefined) throw new Error("Store " + id + " cannot patch " + key + ": it is not a writable ref");
175
+ write(values[key]);
176
+ }
177
+ });
178
+ return { store: createSetupStoreView(fields, accessors), refs, cells };
179
+ }
180
+
181
+ function protectLocalSetup<T>(this: void, run: (this: void) => T): Result<T> {
182
+ try {
183
+ return ok(run());
184
+ } catch (problem) {
185
+ return fail(String(problem));
186
+ }
187
+ }
188
+
189
+ function defaultsOf(pick: OwnedReadonlyArray<string>, cells: Readonly<Record<string, Ref<unknown>>>) {
190
+ const defaults: Record<string, unknown> = {};
191
+ for (const key of pick) {
192
+ const cell = cells[key];
193
+ if (cell !== undefined) defaults[key] = cell.value;
194
+ }
195
+ return defaults;
196
+ }
197
+
198
+ /** Open one instance in a registry, or return the instance it already holds. */
199
+ function openStore(definition: StoreDefinition, owner: RuntimeScope, registry: OwnedMap<string, StoreSlot>,
200
+ resolve: Inject | undefined, storage: DefaultStorage | undefined): object {
201
+ const { id, setup, persistence } = definition;
202
+ if (!owner.isActive()) throw new Error("Store " + id + " needs an active owner");
203
+ const existing = registry.get(id);
204
+ if (existing !== undefined) {
205
+ if (existing.definition !== definition) throw new Error("Duplicate store ID: " + id);
206
+ if (existing.store === undefined) throw new Error("Circular store dependency: " + [...opening, id].join(" -> "));
207
+ return existing.store;
208
+ }
209
+
210
+ const scope = owner.fork();
211
+ if (scope.protect === direct) scope.protect = protectLocalSetup;
212
+ const slot: StoreSlot = { definition };
213
+ registry.set(id, slot);
214
+ opening.push(id);
215
+ const previousInject = activeInject;
216
+ activeInject = resolve;
217
+ let opened = false;
218
+ try {
219
+ const ready = withReactiveScope(scope, () => {
220
+ if (persistence === undefined || persistence.pick.length === 0) {
221
+ return createStoreFields(id, setup() as Record<string, unknown>);
222
+ }
223
+ const startWatches = deferStoreWatches(scope);
224
+ const fields = createStoreFields(id, setup() as Record<string, unknown>);
225
+ const perCharacter = persistence.perCharacter === true;
226
+ const chosen = persistence.storage ?? storage?.(id, defaultsOf(persistence.pick, fields.cells), perCharacter);
227
+ if (chosen === undefined) {
228
+ throw new Error("Store " + id + " persists fields but has no storage. Set addon."
229
+ + (perCharacter ? "savedVariablesPerCharacter" : "savedVariables") + " in kumi.config.ts or pass persist.storage.");
230
+ }
231
+ hydrateSetupStore(id, scope, persistence.pick, chosen, fields.cells);
232
+ startWatches();
233
+ return fields;
234
+ });
235
+ if (!ready.ok) throw new Error("Store " + id + ": " + formatFailure(ready));
236
+ const { store, refs } = ready.value;
237
+ const registered = scope.onDispose(() => {
238
+ bindings?.delete(store);
239
+ if (registry.get(id) === slot) registry.delete(id);
240
+ });
241
+ if (!registered.ok) throw new Error("Store " + id + ": " + formatFailure(registered));
242
+ const referenceMap = bindings ??= ownedWeakMap<object, object>();
243
+ referenceMap.set(store, refs);
244
+ slot.store = store;
245
+ opened = true;
246
+ return store;
247
+ } finally {
248
+ activeInject = previousInject;
249
+ opening.pop();
250
+ if (!opened) {
251
+ if (registry.get(id) === slot) registry.delete(id);
252
+ scope.dispose();
253
+ }
254
+ }
255
+ }
256
+
257
+ function openOwned(definition: StoreDefinition, owner: RuntimeScope) {
258
+ const registry = owners ??= ownedWeakMap<RuntimeScope, OwnedMap<string, StoreSlot>>();
259
+ let group = registry.get(owner);
260
+ if (group === undefined) {
261
+ group = ownedMap<string, StoreSlot>();
262
+ registry.set(owner, group);
263
+ }
264
+ return openStore(definition, owner, group, undefined, activeHost?.storage);
265
+ }
266
+
267
+ function openHosted(host: StoreHost, definition: StoreDefinition) {
268
+ const registration = host.registrations.get(definition);
269
+ const owner = registration?.owner ?? host.root();
270
+ if (owner === undefined) throw new Error("Store " + definition.id + " needs a running addon");
271
+ return openStore(definition, owner, host.instances, registration?.resolve, host.storage);
272
+ }
273
+
274
+ /**
275
+ * Define a store. Call the returned function anywhere in the addon to get its single instance.
276
+ * List it in a module's `stores` when its setup uses inject().
277
+ */
278
+ export function defineStore<Source extends object, Key extends PersistedStoreKey<Source> = PersistedStoreKey<Source>>(
279
+ id: string, setup: (this: void) => Source, options?: SetupStoreOptions<NoInfer<Source>, Key>,
280
+ ): StoreFactory<Source> {
281
+ const persist = options?.persist;
282
+ const definition: StoreDefinition = {
283
+ id,
284
+ setup: setup as (this: void) => object,
285
+ persistence: persist === undefined ? undefined : {
286
+ pick: persist.pick as unknown as OwnedReadonlyArray<string>,
287
+ perCharacter: persist.perCharacter,
288
+ storage: persist.storage as unknown as StoreStorage<Record<string, unknown>> | undefined,
289
+ },
290
+ };
291
+ const useStore = (owner?: RuntimeScope) => {
292
+ if (owner !== undefined) return openOwned(definition, owner) as SetupStore<Source>;
293
+ const host = activeHost;
294
+ if (host === undefined) throw new Error("Store " + id + " needs a running addon. Call it after startAddon, or pass an owner scope.");
295
+ return openHosted(host, definition) as SetupStore<Source>;
296
+ };
297
+ definitions.set(useStore, definition);
298
+ return useStore;
299
+ }
300
+
301
+ /** Return the store's refs for JSX bindings: writable refs stay writable, computed and readonly fields are read-only. */
302
+ export function storeToRefs<Source extends object>(store: SetupStore<Source>): SetupStoreRefs<Source> {
303
+ const refs = bindings?.get(store);
304
+ if (refs === undefined) throw new Error("Expected an active Kumi setup store");
305
+ return refs as SetupStoreRefs<Source>;
306
+ }
307
+
308
+ /** @internal Create the store host of a module container. */
309
+ export function createStoreHost(this: void, root: (this: void) => RuntimeScope | undefined): StoreHost {
310
+ const host: StoreHost = { registrations: ownedMap(), instances: ownedMap(), root };
311
+ activeHost = host;
312
+ return host;
313
+ }
314
+
315
+ /** @internal Make the host current, for example when an addon starts. */
316
+ export function activateStoreHost(this: void, host: StoreHost): void {
317
+ activeHost = host;
318
+ }
319
+
320
+ /** @internal Register and open a module's stores in the module scope. */
321
+ export function openModuleStores(this: void, host: StoreHost, moduleId: string, stores: OwnedReadonlyArray<AnyStoreFactory>,
322
+ owner: RuntimeScope, resolve: Inject): Result<void> {
323
+ const chosen = ownedArray<StoreDefinition>();
324
+ for (const factory of stores) {
325
+ const definition = definitions.get(factory);
326
+ if (definition === undefined) return fail("Module " + moduleId + ": stores accepts functions returned by defineStore");
327
+ const other = host.registrations.get(definition);
328
+ if (other !== undefined) return fail("Module " + moduleId + ": store " + definition.id + " is already provided by another module");
329
+ chosen.push(definition);
330
+ }
331
+ for (const definition of chosen) host.registrations.set(definition, { owner, resolve });
332
+ const released = owner.onDispose(() => {
333
+ for (const definition of chosen) host.registrations.delete(definition);
334
+ });
335
+ if (!released.ok) return released;
336
+ activeHost = host;
337
+ for (const definition of chosen) {
338
+ const opened = protectLocalSetup(() => openStore(definition, owner, host.instances, resolve, host.storage));
339
+ if (!opened.ok) return fail("Module " + moduleId + ": " + opened.reason);
340
+ }
341
+ return ok(undefined);
342
+ }
package/state/store.ts CHANGED
@@ -9,6 +9,8 @@ export { createStore };
9
9
  export interface StoreStorage<State extends object> {
10
10
  read(this: void): Result<Partial<State> | undefined>;
11
11
  write(this: void, snapshot: Readonly<State>): Result<void>;
12
+ /** Reserve the storage for one open store. Return the release callback, or fail when another store holds it. */
13
+ claim?(this: void, owner: string): Result<(this: void) => void>;
12
14
  }
13
15
 
14
16
  type StateKey<State> = keyof State & string;
@@ -0,0 +1,36 @@
1
+ ---
2
+ name: kumi-build-debug
3
+ description: Run, build and debug a Kumi addon - check, build, link to the game, and fix TypeScript, ESLint, style and native compiler errors. Use when npm run check or npm run build fails, or to test a change in the game.
4
+ ---
5
+
6
+ # Build and fix
7
+
8
+ ```powershell
9
+ npm run check
10
+ npm run build -- --target forever
11
+ npm run link -- "<game>/_forever_/Interface/AddOns" # once
12
+ ```
13
+
14
+ Then `/reload` in the game. Lua errors appear in BugSack or the default error frame.
15
+
16
+ ## Reading errors
17
+
18
+ Errors name `file:line:column`. Fix the first one and rerun.
19
+
20
+ | Message | Fix |
21
+ | --- | --- |
22
+ | `... import is restricted ...` | The code is in the wrong layer. Move the call down a layer (component → store action → service → api). |
23
+ | `Unsupported property X` | That CSS property is not supported. Use a supported one (see the kumi-ui skill). |
24
+ | `Iteration currently requires a native collection` | Loop over an array you created, or a store/ref value. For data from Lua tables, copy it into an array first. |
25
+ | `Array length requires a proven dense representation` | The array comes from outside; build your own array, or use a typed list from the SDK. |
26
+ | `Destructure native multiple results from calls` | Write `const [a, b] = api.F()` in one statement. |
27
+ | `Circular runtime import` | Two files import each other. Move the shared part into a third file. |
28
+ | `Method signatures require an explicit this type` | Often a RegExp or a library method. Use string methods instead of regular expressions. |
29
+ | `inject(X) works only inside the setup of a store listed in a module's stores` | List the store in its module's `stores`, and call `inject` at the top of setup. |
30
+ | `Store X persists fields but has no storage` | Set `addon.savedVariables` in `kumi.config.ts`. |
31
+ | `X belongs to plugin Y, but Z imports it` | Core code imports a plugin file. Use `import type` or move the code into a core module. |
32
+
33
+ ## In the game
34
+
35
+ - Nothing appears: check that the addon and its plugins are enabled in the addon list, and that the build was linked.
36
+ - A plugin shows "Failed" in the Plugins page: its error text says why; fix it, rebuild, `/reload`.