@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
package/README.md CHANGED
@@ -1,15 +1,68 @@
1
1
  # Kumi
2
2
 
3
- Build World of Warcraft Retail addons with TypeScript and TSX. Kumi compiles to Lua 5.1 and includes a native UI renderer, reactive state, forms, validation, routing, and animations.
3
+ Kumi lets you write World of Warcraft addons in TypeScript and TSX, the way you would write a web app with Vue or React. Kumi's own compiler turns your code into plain Lua 5.1 that the game runs. There is no runtime interpreter and no JavaScript engine in the game.
4
4
 
5
- ```sh
6
- npx @overmvp/kumi init MyAddon
5
+ You get:
6
+
7
+ - **Components in TSX** that update themselves when data changes.
8
+ - **Stores** for state, with saving to SavedVariables built in.
9
+ - **Modules and services** with dependency injection, so a big addon stays organized.
10
+ - **A window with pages** from files in `src/app/routes`.
11
+ - **Plugins** that players turn on or off in the addon list, and parts that load only when needed.
12
+ - **Forms, animations, SCSS styles** and a typed WoW API.
13
+ - **Clear rules**: ESLint and the compiler tell you when code is in the wrong place.
14
+
15
+ ```tsx
16
+ export const useCounter = defineStore("counter", () => {
17
+ const clicks = ref(0);
18
+ function click() { clicks.value += 1; }
19
+ return { clicks: readonly(clicks), click };
20
+ }, { persist: { pick: ["clicks"] } });
21
+
22
+ export function CounterButton() {
23
+ const counter = useCounter();
24
+ const { clicks } = storeToRefs(counter);
25
+ return <Button label={computed(() => "Clicked " + String(clicks.value) + " times")} onClick={counter.click} />;
26
+ }
27
+ ```
28
+
29
+ ## Start a project
30
+
31
+ You need Node.js 24 or newer and Rust with Cargo. Kumi also needs Blizzard's UI documentation export to know the WoW API; point `KUMI_WOW_DOCS` at it.
32
+
33
+ ```powershell
34
+ npx --yes @overmvp/kumi init MyAddon
7
35
  cd MyAddon
8
36
  npm install
9
37
  npm run check
10
- npm run build
38
+ npm run build -- --target forever
39
+ npm run link -- "D:/Games/World of Warcraft/_forever_/Interface/AddOns"
11
40
  ```
12
41
 
13
- The starter includes ESLint and a reactive counter. Building requires Node.js 24 or newer, Rust with Cargo, and `KUMI_WOW_DOCS` pointing to an exported set of Blizzard UI documentation for your Retail client.
42
+ Log in, type `/myaddon`, and the addon's window opens. Change some code, run `npm run build` again and `/reload` in the game.
43
+
44
+ ## Learn Kumi
45
+
46
+ Read the guides in order the first time:
47
+
48
+ 1. [Getting started](docs/getting-started.md): create, build and run an addon.
49
+ 2. [Project structure](docs/project-structure.md): where each kind of code goes.
50
+ 3. [Modules and services](docs/modules-and-services.md)
51
+ 4. [Stores](docs/stores.md): state, saving, sharing between modules.
52
+ 5. [Components](docs/components.md)
53
+ 6. [Reactivity and hooks](docs/reactivity-and-hooks.md)
54
+ 7. [Styling](docs/styling.md)
55
+ 8. [Forms](docs/forms.md)
56
+ 9. [Animation](docs/animation.md)
57
+ 10. [Windows and pages](docs/windows-and-pages.md)
58
+ 11. [Plugins](docs/plugins.md)
59
+ 12. [The WoW API](docs/wow-api.md): calling the game, secret values, secure buttons.
60
+ 13. [Configuration and CLI](docs/configuration.md)
61
+ 14. [Rules](docs/rules.md): what ESLint and the compiler enforce, and why.
62
+ 15. [Advanced](docs/advanced.md): low-level views, secure builders, native hooks.
63
+
64
+ Working on Kumi itself? See [Contributing](CONTRIBUTING.md) and [the compiler notes](docs/compiler.md).
65
+
66
+ ## License
14
67
 
15
- [Source and documentation](https://github.com/OverMVP/kumi) · [MIT license](https://opensource.org/license/mit)
68
+ MIT
@@ -8,7 +8,10 @@ const sides = ["top", "right", "bottom", "left"];
8
8
  const sidesByProperty = new Map(sides.flatMap((side, index) => [
9
9
  ["margin-" + side, ["margin", index]], [side, [side]], ["border-" + side, ["border", side]],
10
10
  ]));
11
- const ordered = new Set(["margin", "border", "inset", ...sidesByProperty.keys()]);
11
+ // Longhand border parts: `border-width`, `border-color` and their per-side forms.
12
+ const borderParts = new Map([["border-width", ["width"]], ["border-color", ["color"]],
13
+ ...sides.flatMap(side => [["border-" + side + "-width", ["width", side]], ["border-" + side + "-color", ["color", side]]])]);
14
+ const ordered = new Set(["margin", "border", "inset", "border-style", ...borderParts.keys(), ...sidesByProperty.keys()]);
12
15
  const decimal = String.raw`(?:\d+(?:\.\d+)?|\.\d+)`;
13
16
  const unitlessNumber = new RegExp(`^[+-]?${decimal}$`);
14
17
  const pixels = new RegExp(`^[+-]?${decimal}px$`);
@@ -235,6 +238,29 @@ export function compileCssDeclarations(declarations, {
235
238
  return true;
236
239
  }
237
240
  const side = sidesByProperty.get(property);
241
+ if ((property === "border" || side?.[0] === "border") && /^(none|0|0px)$/u.test(source)
242
+ || property === "border-style" && source === "none") {
243
+ // No border: zero widths need no color, and they replace a border from an earlier class.
244
+ for (const edge of side ? [side[1]] : sides) {
245
+ write(["border", edge, "width"], { value: 0 }, false);
246
+ if (output.border[edge].color !== undefined) delete output.border[edge].color;
247
+ recipes.delete(JSON.stringify(["border", edge, "color"]));
248
+ }
249
+ return true;
250
+ }
251
+ if (property === "border-style") return source === "solid";
252
+ const part = borderParts.get(property);
253
+ if (part !== undefined) {
254
+ const [field, edge] = part;
255
+ const spec = field === "width" ? length : color;
256
+ const words = edge === undefined ? pieces(source) : [source];
257
+ if (words.length < 1 || words.length > 4) return false;
258
+ const values = words.map(word => bind(word, spec, tokens));
259
+ if (values.some(value => value === undefined)) return false;
260
+ if (edge !== undefined) write(["border", edge, field], values[0]);
261
+ else rectangle(values).forEach((value, index) => write(["border", sides[index], field], value));
262
+ return true;
263
+ }
238
264
  if (property === "border" || side?.[0] === "border") {
239
265
  const fields = compound(source, "border", readBorder, ["width", "color"], tokens);
240
266
  if (fields === undefined) return false;
@@ -308,8 +334,10 @@ export function compileCssDeclarations(declarations, {
308
334
  return true;
309
335
  }
310
336
 
337
+ let borderDeclaration;
311
338
  for (const declaration of declarations) {
312
339
  const { prop } = declaration;
340
+ if (prop.startsWith("border") && prop !== "border-radius") borderDeclaration = declaration;
313
341
  try {
314
342
  if (state && !supportsStateProperty(prop)) throw new Error(`Unsupported property ${prop} in a style state`);
315
343
  if (reactive && prop === "overflow") throw new Error("Overflow is fixed at mount");
@@ -329,6 +357,31 @@ export function compileCssDeclarations(declarations, {
329
357
  throw declarationError(bounds.get(`max-${axis}`), `min-${axis} (${min}px) exceeds max-${axis} (${max}px)`);
330
358
  }
331
359
  }
360
+ const border = output.border;
361
+ if (border !== undefined && !state) {
362
+ for (const side of sides) {
363
+ const edge = border[side];
364
+ if (edge === undefined) continue;
365
+ if (edge.width === undefined) {
366
+ throw declarationError(borderDeclaration, `border-${side}-color needs a width in the same rule. Use the border shorthand or add border-width`);
367
+ }
368
+ if (edge.width > 0 && edge.color === undefined) {
369
+ throw declarationError(borderDeclaration, `border-${side}-width needs a color in the same rule. Use the border shorthand or add border-color`);
370
+ }
371
+ }
372
+ }
373
+ const top = border?.top;
374
+ if (top?.width > 0 && sides.every(side => {
375
+ const edge = border[side];
376
+ return edge?.width === top.width && edge.color === top.color
377
+ && !recipes.has(JSON.stringify(["border", side, "width"]))
378
+ && !recipes.has(JSON.stringify(["border", side, "color"]));
379
+ })) {
380
+ const { width, color: literal } = top;
381
+ const rgba = [1, 3, 5].map(offset => Number.parseInt(literal.slice(offset, offset + 2), 16) / 255);
382
+ rgba.push(literal.length === 9 ? Number.parseInt(literal.slice(7, 9), 16) / 255 : 1);
383
+ output.borderPaint = { width, literal, rgba };
384
+ }
332
385
  if (recipes.size > 0) output.styleTokens = [...recipes.values()];
333
386
  return output;
334
387
  }
@@ -84,6 +84,46 @@ test("compiles width and color for each border without losing declaration order"
84
84
  ]) assert.throws(() => single("border", value), /Invalid value for border/, value);
85
85
  });
86
86
 
87
+ test("compiles border-width, border-color and their per-side forms", () => {
88
+ const line = { width: 1, color: "#405168" };
89
+ assert.deepEqual(compile([["border", "1px solid #405168"], ["border-width", "0 0 2px"]]), {
90
+ border: { top: { width: 0, color: "#405168" }, right: { width: 0, color: "#405168" },
91
+ bottom: { width: 2, color: "#405168" }, left: { width: 0, color: "#405168" } },
92
+ });
93
+ assert.deepEqual(compile([["border-width", "1px"], ["border-color", "#405168"]]).border, { top: line, right: line, bottom: line, left: line });
94
+ assert.deepEqual(compile([["border", "1px solid #405168"], ["border-top-width", "3px"], ["border-left-color", "#efbf68"]]).border, {
95
+ top: { width: 3, color: "#405168" }, right: line, bottom: line, left: { width: 1, color: "#efbf68" },
96
+ });
97
+ assert.deepEqual(compile([["border-width", "1px 2px"], ["border-color", "#111111 #222222 #333333 #444444"]]).border, {
98
+ top: { width: 1, color: "#111111" }, right: { width: 2, color: "#222222" },
99
+ bottom: { width: 1, color: "#333333" }, left: { width: 2, color: "#444444" },
100
+ });
101
+ const none = { top: { width: 0 }, right: { width: 0 }, bottom: { width: 0 }, left: { width: 0 } };
102
+ for (const [property, value] of [["border", "none"], ["border", "0"], ["border-width", "0"], ["border-style", "none"]]) {
103
+ assert.deepEqual(single(property, value).border, none, property + ": " + value);
104
+ }
105
+ assert.deepEqual(compile([["border", "1px solid #405168"], ["border", "none"]]).border, none);
106
+ assert.equal(single("border-style", "solid").border, undefined);
107
+ assert.throws(() => single("border-width", "2px"), /border-top-width needs a color/);
108
+ assert.throws(() => single("border-color", "#405168"), /border-top-color needs a width/);
109
+ assert.throws(() => single("border-width", "1px 2px 3px 4px 5px"), /Invalid value for border-width/);
110
+ assert.throws(() => single("border-style", "dashed"), /Invalid value for border-style/);
111
+ });
112
+
113
+ test("prepares uniform literal border paint from the final ordered declarations", () => {
114
+ const border = ["border", "1px solid rgba(64, 128, 255, 0.5)"];
115
+ const dynamic = ["border-left", "var(--edge)"];
116
+ const options = { tokens: new Map([["--edge", "1px #4080ff80"]]) };
117
+ const plan = { width: 1, literal: "#4080ff80", rgba: [64 / 255, 128 / 255, 1, 128 / 255] };
118
+
119
+ assert.deepEqual(compile([border, ["border-radius", "6px"]]).borderPaint, plan);
120
+ assert.deepEqual(compile([dynamic, border], options).borderPaint, plan);
121
+ assert.equal(compile([border, dynamic], options).borderPaint, undefined);
122
+ assert.equal(compile([border, ["border-top", "2px #4080ff80"]]).borderPaint, undefined);
123
+ assert.equal(compile([border, ["border-top", "1px #ffffff"]]).borderPaint, undefined);
124
+ assert.equal(single("border", "0 #ffffff").borderPaint, undefined);
125
+ });
126
+
87
127
  test("validates exact registered radii and permits an explicit host registry", () => {
88
128
  assert.deepEqual(cssRadii, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12]);
89
129
  for (const radius of cssRadii) assert.deepEqual(single("border-radius", radius + "px"), { borderRadius: radius });
@@ -30,6 +30,18 @@ function readFragment(path, packet) {
30
30
  return { header, prelude, footer, modules };
31
31
  }
32
32
 
33
+ // Fragment keys use the Rust backend's Lua string encoding.
34
+ function moduleKeyLiteral(key) {
35
+ let literal = '"';
36
+ for (const character of key) {
37
+ const code = character.codePointAt(0);
38
+ if (code < 32 || code === 127) literal += "\\" + String(code).padStart(3, "0");
39
+ else if (character === '"' || character === "\\") literal += "\\" + character;
40
+ else literal += character;
41
+ }
42
+ return literal + '"';
43
+ }
44
+
33
45
  async function publish(path, parts, check) {
34
46
  const source = Buffer.concat(parts.map(part => typeof part === "string" ? Buffer.from(part) : part));
35
47
  if (check) {
@@ -39,13 +51,16 @@ async function publish(path, parts, check) {
39
51
  }
40
52
 
41
53
  /** Link opaque Rust codegen fragments. The entry order is fixed by the package manifest. */
42
- export async function linkAddonPackage(entries, output, check = false) {
54
+ export async function linkAddonPackage(entries, output, check = false, autoStamp) {
43
55
  if (!entries.length) throw new Error("A native package requires at least one entry");
44
56
  const chunks = [];
45
57
  const candidates = new Map();
46
58
  let prelude;
47
- for (const { fragment, lua } of entries) {
48
- const chunk = readFragment(fragment, await readFile(fragment));
59
+ const digest = autoStamp === undefined ? undefined : createHash("sha256");
60
+ for (const { fragment, lua, lazyModule, ownedFolder, name, pluginId } of entries) {
61
+ const packet = await readFile(fragment);
62
+ digest?.update(packet);
63
+ const chunk = readFragment(fragment, packet);
49
64
  prelude ??= chunk.prelude;
50
65
  if (!prelude.equals(chunk.prelude)) throw new Error(`Mixed native package build stamps: ${fragment}`);
51
66
  for (const module of chunk.modules) {
@@ -61,11 +76,37 @@ export async function linkAddonPackage(entries, output, check = false) {
61
76
  }
62
77
  module.shared = other;
63
78
  }
64
- chunks.push({ lua, ...chunk });
79
+ chunks.push({ lua, lazyModule, ownedFolder, name, pluginId, ...chunk });
80
+ }
81
+ for (const owner of chunks) {
82
+ if (owner.lazyModule === undefined) continue;
83
+ const key = moduleKeyLiteral(owner.lazyModule);
84
+ if (!owner.modules.some(module => module.key === key)) {
85
+ throw new Error("Missing plugin module " + owner.lazyModule + " in " + (owner.name ?? owner.lua));
86
+ }
87
+ // Every file in a plugin's folder belongs to that plugin. Another chunk must not bundle any of them.
88
+ const folder = owner.ownedFolder === undefined ? undefined : moduleKeyLiteral(owner.ownedFolder).slice(0, -1);
89
+ for (const other of chunks) {
90
+ if (other === owner) continue;
91
+ const leaked = other.modules.find(module => module.key === key || folder !== undefined && module.key.startsWith(folder));
92
+ if (leaked === undefined) continue;
93
+ const file = leaked.key.slice(1, -1).replace(/^addon\//u, "");
94
+ const plugin = owner.pluginId === undefined ? owner.lazyModule : "plugin " + owner.pluginId;
95
+ throw new Error(file + " belongs to " + plugin + ", but " + (other.name ?? other.lua) + " imports it. "
96
+ + "Use `import type` for the plugin's types, or move shared code into a core module.");
97
+ }
98
+ }
99
+ const stamp = digest?.digest("hex");
100
+ function stampHeader(header) {
101
+ if (stamp === undefined) return header;
102
+ const source = header.toString();
103
+ const before = "local nativeBuild = " + JSON.stringify(autoStamp) + "\n";
104
+ if (!source.includes(before)) throw new Error("The native linked header is missing its build stamp");
105
+ return source.replace(before, "local nativeBuild = " + JSON.stringify(stamp) + "\n");
65
106
  }
66
107
  let shared = 0;
67
108
  let duplicateBytes = 0;
68
- const pool = [prelude];
109
+ const pool = [stampHeader(prelude)];
69
110
  for (const candidate of candidates.values()) {
70
111
  if (candidate.count < 2) continue;
71
112
  candidate.slot = ++shared;
@@ -75,7 +116,7 @@ export async function linkAddonPackage(entries, output, check = false) {
75
116
  pool.push("nativeRegistry.definitions = definitions\n");
76
117
  let bytes = await publish(output, pool, check);
77
118
  for (const chunk of chunks) {
78
- const parts = [chunk.header];
119
+ const parts = [stampHeader(chunk.header)];
79
120
  for (const { prefix, shared, factory, suffix } of chunk.modules) {
80
121
  parts.push(prefix, shared.slot ? `nativeDefinitions[${shared.slot}]` : factory, suffix);
81
122
  }
@@ -342,7 +342,7 @@ class Service {
342
342
  assert.throws(() => foreign.transform("fixture.ts"), /Declare this class provider next to the module/);
343
343
  });
344
344
 
345
- test("emits the same Lua 5.1 class and provider as the manual constructor descriptor", () => {
345
+ test("lowers a decorated class to the manual constructor descriptor", () => {
346
346
  const body = `
347
347
  class Store { key = "ready"; }
348
348
 
@@ -360,23 +360,14 @@ export class Service {
360
360
  + 'exports: { service: Service } } as const;\nexport const Fixture = __kumiDefineModule(metadata);\n';
361
361
  const original = fixture({ "fixture.ts": decorated });
362
362
  const lowered = original.transform("fixture.ts");
363
- const { Transpiler } = load("typescript-to-lua");
364
- function lua(source) {
365
- const emitted = fixture({ "fixture.ts": source }, false, {
366
- luaTarget: "5.1", luaLibImport: "require-minimal", noImplicitSelf: true, noResolvePaths: ["@kumi/core"],
367
- });
368
- const result = new Transpiler().emit({ program: emitted.program, writeFile: (name, data) => emitted.output.set(name, data) });
369
- const diagnostics = [...ts.getPreEmitDiagnostics(emitted.program), ...result.diagnostics];
370
- assert.equal(diagnostics.map(item => ts.flattenDiagnosticMessageText(item.messageText, "\n")).join("\n"), "");
371
- assert.equal(result.emitSkipped, false);
372
- const unit = [...emitted.output].find(([name]) => name.replaceAll("\\", "/").split("/").pop() === "fixture.lua");
373
- assert.ok(unit, "Expected fixture.lua in " + [...emitted.output.keys()].join(", "));
374
- return unit[1];
375
- }
376
- const output = lua(lowered);
377
- assert.equal(output, lua(manual));
378
- assert.match(output, /function Service\.prototype\.read\(self\)/);
379
- assert.match(output, /inject\s*=\s*\{\s*Store,\s*moduleScope\s*\}/);
363
+ // The decorated class lowers to the same provider descriptor a manual module declares.
364
+ const compact = source => source.replace(/\s+/gu, " ");
365
+ const loweredProviders = compact(lowered).match(/providers: \[Store, \{[^\]]*\]/u)?.[0];
366
+ const manualProviders = compact(manual).match(/providers: \[Store, \{[^\]]*\]/u)?.[0];
367
+ assert.ok(loweredProviders, "Expected lowered providers in " + lowered);
368
+ assert.equal(loweredProviders.replace(/\s*,?\s*\}\s*$/u, "}"), manualProviders?.replace(/\s*,?\s*\}\s*$/u, "}"));
369
+ assert.match(compact(lowered), /inject: \[Store, moduleScope\]/);
370
+ assert.match(lowered, /__kumiDefineModule\(metadata\)/);
380
371
  });
381
372
 
382
373
  test("lowers feature hooks with the child scope and keeps module hooks separate", () => {
@@ -20,7 +20,7 @@ export async function prepareSignalKernel({ ts, program, sdkRoot, output, pack }
20
20
  await rm(join(scratch, "signal.lua"), { force: true });
21
21
  await rmdir(scratch);
22
22
  }
23
- if (!lua.startsWith(`-- kumi-native-1 / SignalFactoryV1 / ${lowered.source}\n`)) {
23
+ if (!lua.startsWith(`-- kumi-native-1 / SignalFactoryV3 / ${lowered.source}\n`)) {
24
24
  throw new Error("Signal emitter returned a mismatched native module");
25
25
  }
26
26
  let replaced = false;
@@ -39,7 +39,7 @@ fn identifier(name: &str) -> Compile<String> {
39
39
  if !matches!(bytes.next(), Some(b'A'..=b'Z' | b'a'..=b'z' | b'_'))
40
40
  || !bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
41
41
  {
42
- return Err("Invalid identifier in compiler input".into());
42
+ return Err(format!("Invalid identifier in compiler input: {name:?}").into());
43
43
  }
44
44
  Ok(format!("v_{name}"))
45
45
  }
@@ -77,6 +77,8 @@ struct Emitter<'a> {
77
77
  classes: bool,
78
78
  types: bool,
79
79
  numbers: bool,
80
+ wow_reads: bool,
81
+ store_views: bool,
80
82
  strings: bool,
81
83
  tables: bool,
82
84
  errors: bool,
@@ -119,6 +121,8 @@ impl<'a> Emitter<'a> {
119
121
  let pad = " ".repeat(indent);
120
122
  match (tag, args.as_slice()) {
121
123
  ("literal", [value @ ("true" | "false" | "nil")]) => Ok((*value).into()),
124
+ ("literal", ["nan"]) => Ok("(0/0)".into()),
125
+ ("literal", ["-inf"]) => Ok("(-math.huge)".into()),
122
126
  ("error-value", []) => {
123
127
  self.errors = true;
124
128
  Ok(format!("createError({})", self.expression(indent)?))
@@ -151,10 +155,21 @@ impl<'a> Emitter<'a> {
151
155
  | "math.tan" | "math.atan" | "math.random" | "math.exp" | "math.log"
152
156
  | "math.pow" | "string.lower" | "string.upper")],
153
157
  ) => Ok((*name).into()),
158
+ ("global", [name @ "setupStoreView"]) => {
159
+ self.store_views = true;
160
+ Ok((*name).into())
161
+ }
162
+ (
163
+ "global",
164
+ [name @ ("wowReadable" | "wowReadableSecond" | "wowReadableThird" | "wowOptionalReadable")],
165
+ ) => {
166
+ self.wow_reads = true;
167
+ Ok((*name).into())
168
+ }
154
169
  (
155
170
  "global",
156
171
  [name @ ("numberFinite" | "numberNaN" | "numberInteger" | "numberMin" | "numberMax"
157
- | "numberValue" | "numberRound" | "numberFixed")],
172
+ | "numberMin2" | "numberMax2" | "numberValue" | "numberRound" | "numberFixed")],
158
173
  ) => {
159
174
  self.numbers = true;
160
175
  Ok((*name).into())
@@ -480,6 +495,13 @@ impl<'a> Emitter<'a> {
480
495
  let else_value = self.expression(indent)?;
481
496
  Ok(format!("(function() if {condition} then return {then_value} else return {else_value} end end)()"))
482
497
  }
498
+ // The frontend proved the first branch is never nil or false, so `and`/`or` keeps lazy evaluation.
499
+ ("select-truthy", []) => {
500
+ let condition = self.expression(indent)?;
501
+ let then_value = self.expression(indent)?;
502
+ let else_value = self.expression(indent)?;
503
+ Ok(format!("(({condition}) and ({then_value}) or ({else_value}))"))
504
+ }
483
505
  ("nullish", []) => {
484
506
  let left = self.expression(indent)?;
485
507
  let right = self.expression(indent)?;
@@ -617,6 +639,88 @@ impl<'a> Emitter<'a> {
617
639
  Ok(out)
618
640
  }
619
641
 
642
+ /// Lower an assignment or `++`/`--` whose value is discarded into a plain Lua statement.
643
+ fn effect_statement(&mut self, indent: usize) -> Compile<String> {
644
+ let (tag, args) = self.record()?;
645
+ match (tag, args.as_slice()) {
646
+ ("update-local", [operator @ ("+" | "-"), "old" | "new", name]) => {
647
+ let name = identifier(name)?;
648
+ Ok(format!("{name} = {name} {operator} 1"))
649
+ }
650
+ ("update-property", [operator @ ("+" | "-"), "old" | "new", key]) => {
651
+ let target = self.expression(indent)?;
652
+ let key = quote(&decode(key)?);
653
+ Ok(format!(
654
+ "do local target = {target}; target[{key}] = target[{key}] {operator} 1 end"
655
+ ))
656
+ }
657
+ ("update-index", [operator @ ("+" | "-"), "old" | "new"]) => {
658
+ let target = self.expression(indent)?;
659
+ let key = self.expression(indent)?;
660
+ Ok(format!("do local target = {target}; local key = {key}; target[key] = target[key] {operator} 1 end"))
661
+ }
662
+ ("assignment", []) => self.assignment_statement(indent, None),
663
+ ("nullish-assignment", []) => self.assignment_statement(indent, Some("??")),
664
+ ("logical-assignment", [mode @ ("or" | "and")]) => {
665
+ self.assignment_statement(indent, Some(mode))
666
+ }
667
+ ("compound", [operator @ ("+" | "-" | "*" | "/" | "^" | "..")]) => {
668
+ self.assignment_statement(indent, Some(operator))
669
+ }
670
+ _ => Err(format!("Unexpected discarded assignment: {tag}").into()),
671
+ }
672
+ }
673
+
674
+ fn assignment_target(&mut self, indent: usize) -> Compile<(String, String)> {
675
+ let (kind, fields) = self.record()?;
676
+ let mut setup = String::new();
677
+ let target = match (kind, fields.as_slice()) {
678
+ ("target-local", [name]) => identifier(name)?,
679
+ ("target-property", [key]) => {
680
+ write!(setup, "local target = {}; ", self.expression(indent)?)?;
681
+ format!("target[{}]", quote(&decode(key)?))
682
+ }
683
+ ("target-index" | "target-array-index", []) => {
684
+ let target = self.expression(indent)?;
685
+ let key = self.expression(indent)?;
686
+ let key = if kind == "target-array-index" {
687
+ format!("({key}) + 1")
688
+ } else {
689
+ key
690
+ };
691
+ write!(setup, "local target = {target}; local key = {key}; ")?;
692
+ "target[key]".into()
693
+ }
694
+ _ => return Err("Invalid assignment target".into()),
695
+ };
696
+ Ok((setup, target))
697
+ }
698
+
699
+ fn assignment_statement(&mut self, indent: usize, compound: Option<&str>) -> Compile<String> {
700
+ let (setup, target) = self.assignment_target(indent)?;
701
+ let value = self.expression(indent)?;
702
+ let assign = match compound {
703
+ None => format!("{target} = {value}"),
704
+ Some("??") => {
705
+ format!("local current = {target}; if current == nil then {target} = {value} end")
706
+ }
707
+ Some("or") => {
708
+ format!("local current = {target}; if not current then {target} = {value} end")
709
+ }
710
+ Some("and") => {
711
+ format!("local current = {target}; if current then {target} = {value} end")
712
+ }
713
+ Some(operator) => {
714
+ format!("local current = {target}; {target} = current {operator} ({value})")
715
+ }
716
+ };
717
+ Ok(if setup.is_empty() && compound.is_none() {
718
+ assign
719
+ } else {
720
+ format!("do {setup}{assign} end")
721
+ })
722
+ }
723
+
620
724
  fn assignment(&mut self, indent: usize, compound: Option<&str>) -> Compile<String> {
621
725
  let (kind, fields) = self.record()?;
622
726
  let mut setup = String::new();
@@ -1104,6 +1208,50 @@ impl<'a> Emitter<'a> {
1104
1208
  out.push_str(&self.block(indent + 1)?);
1105
1209
  writeln!(out, "{pad}end")?;
1106
1210
  }
1211
+ ("readable-multi-local" | "readable-multi-binding", names) if !names.is_empty() => {
1212
+ let mut targets = Vec::new();
1213
+ let mut raw = Vec::new();
1214
+ let mut revealed = Vec::new();
1215
+ for (index, name) in names.iter().enumerate() {
1216
+ if *name == "-" {
1217
+ raw.push("_".into());
1218
+ } else {
1219
+ targets.push(identifier(name)?);
1220
+ raw.push(format!("raw{}", index + 1));
1221
+ revealed.push(format!("wowReadable({})", raw[index]));
1222
+ }
1223
+ }
1224
+ if targets.is_empty() {
1225
+ return Err(
1226
+ "A readable Lua tuple requires at least one result binding".into()
1227
+ );
1228
+ }
1229
+ self.wow_reads = true;
1230
+ let (operation, operands) = self.record()?;
1231
+ let values = self.call(operation, &operands, indent + 1)?;
1232
+ let guard = if targets.len() == 1 {
1233
+ let offset = names.iter().position(|name| *name != "-").unwrap_or(0);
1234
+ ["wowReadable", "wowReadableSecond", "wowReadableThird"].get(offset)
1235
+ } else {
1236
+ None
1237
+ };
1238
+ let targets = targets.join(", ");
1239
+ let revealed = revealed.join(", ");
1240
+ if let Some(guard) = guard {
1241
+ let local = if tag == "readable-multi-local" {
1242
+ "local "
1243
+ } else {
1244
+ ""
1245
+ };
1246
+ writeln!(out, "{pad}{local}{targets} = {guard}({values})")?;
1247
+ } else {
1248
+ if tag == "readable-multi-local" {
1249
+ writeln!(out, "{pad}local {targets}")?;
1250
+ }
1251
+ let raw = raw.join(", ");
1252
+ writeln!(out, "{pad}do\n{pad} local {raw} = {values}\n{pad} {targets} = {revealed}\n{pad}end")?;
1253
+ }
1254
+ }
1107
1255
  ("multi-local" | "multi-binding", names) if !names.is_empty() => {
1108
1256
  let omitted = names.contains(&"-");
1109
1257
  let names = names
@@ -1215,11 +1363,20 @@ impl<'a> Emitter<'a> {
1215
1363
  )?;
1216
1364
  }
1217
1365
  ("effect-value", []) => {
1218
- writeln!(
1219
- out,
1220
- "{pad}do local ignored = {} end",
1221
- self.expression(indent + 1)?
1222
- )?;
1366
+ // An assignment or update used as a statement needs no closure for its result.
1367
+ let next = self
1368
+ .records
1369
+ .clone()
1370
+ .next()
1371
+ .and_then(|line| line.split('\t').next());
1372
+ let statement = match next {
1373
+ Some(
1374
+ "assignment" | "compound" | "nullish-assignment" | "logical-assignment"
1375
+ | "update-local" | "update-property" | "update-index",
1376
+ ) => self.effect_statement(indent + 1)?,
1377
+ _ => format!("do local ignored = {} end", self.expression(indent + 1)?),
1378
+ };
1379
+ writeln!(out, "{pad}{statement}")?;
1223
1380
  }
1224
1381
  ("array-write" | "array-trim", []) => {
1225
1382
  self.arrays = true;
@@ -2017,6 +2174,12 @@ impl<'a> Emitter<'a> {
2017
2174
  if all || self.numbers {
2018
2175
  bundle.push_str(include_str!("numbers.lua"));
2019
2176
  }
2177
+ if all || self.wow_reads {
2178
+ bundle.push_str(include_str!("wow-reads.lua"));
2179
+ }
2180
+ if all || self.store_views {
2181
+ bundle.push_str(include_str!("setup-store.lua"));
2182
+ }
2020
2183
  if all || self.strings {
2021
2184
  bundle.push_str(include_str!("strings.lua"));
2022
2185
  }
@@ -2064,6 +2227,8 @@ pub struct ProjectCompile<'a> {
2064
2227
  pub output: &'a Path,
2065
2228
  pub check: bool,
2066
2229
  pub addon: bool,
2230
+ /// Compile an SDK test fixture: addon semantics plus its declared mock globals.
2231
+ pub test: bool,
2067
2232
  pub link: Option<&'a str>,
2068
2233
  pub assets: Option<&'a Path>,
2069
2234
  pub plugin: Option<AddonPlugin>,
@@ -2079,6 +2244,7 @@ pub fn compile(project: &Path, request: ProjectCompile<'_>) -> Compile<()> {
2079
2244
  output,
2080
2245
  check,
2081
2246
  addon,
2247
+ test,
2082
2248
  link,
2083
2249
  assets,
2084
2250
  plugin,
@@ -2092,7 +2258,11 @@ pub fn compile(project: &Path, request: ProjectCompile<'_>) -> Compile<()> {
2092
2258
  .arg(workspace)
2093
2259
  .arg(sdk)
2094
2260
  .arg(config.unwrap_or_else(|| Path::new("")))
2095
- .arg(if addon { "addon" } else { "standalone" })
2261
+ .arg(match (addon, test) {
2262
+ (_, true) => "test",
2263
+ (true, false) => "addon",
2264
+ (false, false) => "standalone",
2265
+ })
2096
2266
  .arg(link.unwrap_or(""))
2097
2267
  .arg(assets.unwrap_or_else(|| Path::new("")))
2098
2268
  .arg(if assets.is_some() {
@@ -2128,6 +2298,8 @@ pub fn compile(project: &Path, request: ProjectCompile<'_>) -> Compile<()> {
2128
2298
  classes: false,
2129
2299
  types: false,
2130
2300
  numbers: false,
2301
+ wow_reads: false,
2302
+ store_views: false,
2131
2303
  strings: false,
2132
2304
  tables: false,
2133
2305
  errors: false,