@overmvp/kumi 0.0.0-stage → 0.1.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 (205) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +14 -2
  3. package/animation/color-transition.ts +196 -0
  4. package/animation/cycle.ts +151 -0
  5. package/animation/ease.ts +29 -0
  6. package/animation/index.ts +13 -0
  7. package/animation/package.json +12 -0
  8. package/animation/presets.ts +376 -0
  9. package/animation/spec.ts +197 -0
  10. package/builder/Cargo.lock +192 -0
  11. package/builder/Cargo.toml +7 -0
  12. package/builder/css-v1.mjs +334 -0
  13. package/builder/css-v1.test.mjs +321 -0
  14. package/builder/generated-output.mjs +61 -0
  15. package/builder/generated-output.test.mjs +132 -0
  16. package/builder/jsx-form.mjs +93 -0
  17. package/builder/jsx-form.test.mjs +48 -0
  18. package/builder/jsx-lists.mjs +209 -0
  19. package/builder/link-addon-package.mjs +86 -0
  20. package/builder/lua-assets.mjs +74 -0
  21. package/builder/lua-builtin-values.mjs +57 -0
  22. package/builder/lua-builtin-values.test.mjs +155 -0
  23. package/builder/lua-loop-closures.mjs +183 -0
  24. package/builder/lua-loop-closures.test.mjs +89 -0
  25. package/builder/lua-truthiness.mjs +61 -0
  26. package/builder/lua-truthiness.test.mjs +113 -0
  27. package/builder/module-declarations.mjs +594 -0
  28. package/builder/module-declarations.test.mjs +444 -0
  29. package/builder/native-kernels.mjs +60 -0
  30. package/builder/native-lua.d.ts +57 -0
  31. package/builder/native-routes.mjs +51 -0
  32. package/builder/no-static-ref-read.mjs +93 -0
  33. package/builder/no-static-ref-read.test.mjs +181 -0
  34. package/builder/secure-snippet.mjs +317 -0
  35. package/builder/secure-snippet.test.mjs +101 -0
  36. package/builder/shared-lua-runtime.mjs +150 -0
  37. package/builder/src/addon-link.lua +29 -0
  38. package/builder/src/arrays.lua +260 -0
  39. package/builder/src/assets.rs +177 -0
  40. package/builder/src/classes.lua +75 -0
  41. package/builder/src/collections.lua +190 -0
  42. package/builder/src/compiler.rs +2164 -0
  43. package/builder/src/config.rs +42 -0
  44. package/builder/src/entries.rs +166 -0
  45. package/builder/src/errors.lua +15 -0
  46. package/builder/src/lua_data.rs +231 -0
  47. package/builder/src/main.rs +367 -0
  48. package/builder/src/native_ir.rs +65 -0
  49. package/builder/src/native_signal.rs +47 -0
  50. package/builder/src/numbers.lua +62 -0
  51. package/builder/src/project-front.mjs +3331 -0
  52. package/builder/src/records.lua +75 -0
  53. package/builder/src/routes.rs +127 -0
  54. package/builder/src/signal-kernel.fingerprint +1 -0
  55. package/builder/src/strings.lua +103 -0
  56. package/builder/src/ts-lower.mjs +68 -0
  57. package/builder/src/wow_client.rs +253 -0
  58. package/builder/src/wow_types.rs +564 -0
  59. package/builder/style-states.mjs +100 -0
  60. package/builder/style-states.test.mjs +103 -0
  61. package/builder/vite-assets.mjs +53 -0
  62. package/builder/vite-project.mjs +10 -0
  63. package/config.ts +17 -0
  64. package/form/index.ts +522 -0
  65. package/form/package.json +13 -0
  66. package/motion/index.ts +2 -0
  67. package/motion/package.json +10 -0
  68. package/package.json +22 -4
  69. package/router/index.ts +43 -0
  70. package/router/package.json +12 -0
  71. package/router/routes.ts +64 -0
  72. package/scripts/kumi-cli.mjs +70 -0
  73. package/scripts/link-addons.mjs +51 -0
  74. package/src/bindings.ts +35 -0
  75. package/src/context.ts +15 -0
  76. package/src/css-tokens.ts +234 -0
  77. package/src/css-v1.ts +58 -0
  78. package/src/cvars.ts +91 -0
  79. package/src/element-node.ts +32 -0
  80. package/src/elements.ts +479 -0
  81. package/src/feature-scope.ts +82 -0
  82. package/src/flex-layout.ts +807 -0
  83. package/src/frame-scheduler.ts +334 -0
  84. package/src/grid-tracks.ts +165 -0
  85. package/src/image-imports.d.ts +24 -0
  86. package/src/images.ts +79 -0
  87. package/src/index.ts +28 -0
  88. package/src/jsx-dev-runtime.ts +2 -0
  89. package/src/jsx-runtime.ts +22 -0
  90. package/src/jsx.d.ts +12 -0
  91. package/src/keyed-list.ts +363 -0
  92. package/src/media-query.ts +144 -0
  93. package/src/module.ts +277 -0
  94. package/src/node-selectors.ts +114 -0
  95. package/src/owned-collections.ts +44 -0
  96. package/src/providers.ts +235 -0
  97. package/src/reactive-scope.ts +34 -0
  98. package/src/reactivity.ts +254 -0
  99. package/src/result.ts +58 -0
  100. package/src/runtime.ts +52 -0
  101. package/src/scheduler.ts +185 -0
  102. package/src/signal-kernel.ts +30 -0
  103. package/src/style-classes.ts +51 -0
  104. package/src/style-states.ts +134 -0
  105. package/src/style-variables.ts +53 -0
  106. package/src/text-children.ts +42 -0
  107. package/src/theme.ts +50 -0
  108. package/src/transition.ts +18 -0
  109. package/state/index.ts +3 -0
  110. package/state/package.json +12 -0
  111. package/state/store-bindings.ts +25 -0
  112. package/state/store.ts +82 -0
  113. package/styles/_layers.scss +14 -0
  114. package/templates/addon/README.md +14 -0
  115. package/templates/addon/__ADDON_NAME__.toc +4 -0
  116. package/templates/addon/eslint.config.mjs +12 -0
  117. package/templates/addon/gitignore +8 -0
  118. package/templates/addon/package.json +21 -0
  119. package/templates/addon/scripts/build.mjs +25 -0
  120. package/templates/addon/src/app/main.tsx +13 -0
  121. package/templates/addon/tsconfig.json +24 -0
  122. package/translate/index.ts +14 -0
  123. package/translate/package.json +9 -0
  124. package/utils/colors.ts +76 -0
  125. package/utils/format.ts +37 -0
  126. package/utils/index.ts +4 -0
  127. package/utils/number.ts +17 -0
  128. package/utils/package.json +7 -0
  129. package/utils/text.ts +6 -0
  130. package/validate/index.ts +119 -0
  131. package/validate/package.json +9 -0
  132. package/wow/absolute-position.ts +142 -0
  133. package/wow/animation.ts +428 -0
  134. package/wow/aura-button.ts +76 -0
  135. package/wow/aura-container.ts +591 -0
  136. package/wow/aura-countdown.ts +201 -0
  137. package/wow/aura-slot.ts +153 -0
  138. package/wow/bar-shade.ts +93 -0
  139. package/wow/borrowed-slot.ts +216 -0
  140. package/wow/button-drag.ts +48 -0
  141. package/wow/cast-clock.ts +153 -0
  142. package/wow/cast-text.ts +83 -0
  143. package/wow/class-colors.ts +126 -0
  144. package/wow/clock.ts +7 -0
  145. package/wow/color-picker.ts +128 -0
  146. package/wow/commands.ts +17 -0
  147. package/wow/contained-frame.ts +128 -0
  148. package/wow/contract.ts +42 -0
  149. package/wow/css-box.ts +110 -0
  150. package/wow/css-color.ts +12 -0
  151. package/wow/css-style.ts +109 -0
  152. package/wow/css-surfaces.ts +398 -0
  153. package/wow/css-text.ts +399 -0
  154. package/wow/cvar-schema.ts +32 -0
  155. package/wow/cvars.ts +98 -0
  156. package/wow/dropdown-art.ts +39 -0
  157. package/wow/element-click.ts +20 -0
  158. package/wow/element-event-coordinator.ts +219 -0
  159. package/wow/element-events.ts +317 -0
  160. package/wow/event-dispatcher.ts +151 -0
  161. package/wow/events.ts +50 -0
  162. package/wow/font-cache.ts +92 -0
  163. package/wow/frame-access.ts +31 -0
  164. package/wow/frame-layer.ts +5 -0
  165. package/wow/frames.ts +236 -0
  166. package/wow/heal-prediction.ts +305 -0
  167. package/wow/image-layers.ts +55 -0
  168. package/wow/index.ts +97 -0
  169. package/wow/layout-view.ts +651 -0
  170. package/wow/lua-string.ts +18 -0
  171. package/wow/lua-table.ts +18 -0
  172. package/wow/macro-book.ts +84 -0
  173. package/wow/map-position.ts +27 -0
  174. package/wow/media-query.ts +65 -0
  175. package/wow/module-events.ts +11 -0
  176. package/wow/native-hooks.ts +168 -0
  177. package/wow/native-placement.ts +88 -0
  178. package/wow/native.ts +135 -0
  179. package/wow/number-format.ts +8 -0
  180. package/wow/number-input.ts +10 -0
  181. package/wow/protect.ts +24 -0
  182. package/wow/protected-layout.ts +133 -0
  183. package/wow/range-art.ts +74 -0
  184. package/wow/reparent-frame.ts +99 -0
  185. package/wow/rounded-texture.ts +156 -0
  186. package/wow/saved-variables.ts +60 -0
  187. package/wow/scroll-view.ts +64 -0
  188. package/wow/secret-ref.ts +14 -0
  189. package/wow/secure-bindings.ts +89 -0
  190. package/wow/secure-clicks.ts +432 -0
  191. package/wow/secure-snippet.ts +235 -0
  192. package/wow/secure-state.ts +130 -0
  193. package/wow/secure-target-visibility.ts +89 -0
  194. package/wow/secure-transaction.ts +331 -0
  195. package/wow/special-window.ts +269 -0
  196. package/wow/start-addon.ts +99 -0
  197. package/wow/state-paint.ts +256 -0
  198. package/wow/transition.ts +86 -0
  199. package/wow/unit-button.ts +39 -0
  200. package/wow/unit-cast.ts +92 -0
  201. package/wow/unit-health-text.ts +47 -0
  202. package/wow/view-nodes.ts +304 -0
  203. package/wow/view.ts +1746 -0
  204. package/wow/visible-frame-job.ts +34 -0
  205. package/wow/width-reserve.ts +108 -0
@@ -0,0 +1,18 @@
1
+ type LuaKey = string | number | object;
2
+
3
+ declare function rawget(this: void, value: object, key: LuaKey): unknown;
4
+ declare function rawset(this: void, value: object, key: LuaKey, entry: unknown): void;
5
+ declare function setmetatable<T extends object>(this: void, value: T, meta: { __mode: "k" }): T;
6
+
7
+ export function rawField<T = unknown>(value: unknown, key: LuaKey): T | undefined {
8
+ return typeof value === "object" && value ? rawget(value, key) as T | undefined : undefined;
9
+ }
10
+
11
+ /** Writes a Lua table field without invoking its metatable. Pass undefined to clear the key. */
12
+ export function setRawField(table: object, key: LuaKey, value: unknown): void {
13
+ rawset(table, key, value);
14
+ }
15
+
16
+ export function weakKeys<T extends object>(table: T): T {
17
+ return setmetatable(table, { __mode: "k" });
18
+ }
@@ -0,0 +1,84 @@
1
+ import { fail, ok } from "../src";
2
+ import { api, reveal } from "./native";
3
+ import { protect } from "./protect";
4
+
5
+ const defaultMacroIcon = 134400;
6
+
7
+ function createMacroBook() {
8
+ function limits() {
9
+ const limits = api.Constants?.MacroConsts;
10
+ return { account: limits?.MAX_ACCOUNT_MACROS ?? 120, character: limits?.MAX_CHARACTER_MACROS ?? 30 };
11
+ }
12
+
13
+ function read(index: number): { name?: string; icon?: number; body?: string } {
14
+ const get = api.GetMacroInfo;
15
+ if (get === undefined) return {};
16
+ const [name, icon, body] = get(index);
17
+ return { name: reveal(name), icon: reveal(icon), body: reveal(body) };
18
+ }
19
+
20
+ function index(name: string) {
21
+ const find = api.GetMacroIndexByName;
22
+ if (find !== undefined) {
23
+ const value = reveal(find(name));
24
+ return value !== undefined && value > 0 ? value : undefined;
25
+ }
26
+ const counts = api.GetNumMacros;
27
+ if (counts === undefined) return;
28
+ const [account, character] = counts();
29
+ const { account: characterOffset } = limits();
30
+ for (let slot = 1; slot <= account; slot++) {
31
+ if (read(slot).name === name) return slot;
32
+ }
33
+ for (let slot = 1; slot <= character; slot++) {
34
+ if (read(characterOffset + slot).name === name) return characterOffset + slot;
35
+ }
36
+ }
37
+
38
+ function freeSlots() {
39
+ const counts = api.GetNumMacros;
40
+ if (counts === undefined) return { account: 0, character: 0 };
41
+ const [account, character] = counts();
42
+ const maximum = limits();
43
+ return { account: maximum.account - account, character: maximum.character - character };
44
+ }
45
+
46
+ function iconID(icon: string | number) {
47
+ if (typeof icon === "number") return icon > 0 ? icon : defaultMacroIcon;
48
+ const fileID = api.GetFileIDFromPath;
49
+ if (typeof fileID !== "function") return defaultMacroIcon;
50
+ let value = reveal(fileID(icon));
51
+ if ((value === undefined || value <= 0) && !icon.endsWith(".blp")) value = reveal(fileID(icon + ".blp"));
52
+ return value !== undefined && value > 0 ? value : defaultMacroIcon;
53
+ }
54
+
55
+ function create(name: string, icon: number, body: string, perCharacter: boolean) {
56
+ const call = api.CreateMacro;
57
+ if (call === undefined) return fail("CreateMacro is unavailable");
58
+ if (api.InCombatLockdown() === true) return fail("Cannot create macros in combat");
59
+ const result = protect(() => call(name, icon, body, perCharacter));
60
+ if (!result.ok) return result;
61
+ const slot = reveal(result.value);
62
+ return slot !== undefined && slot > 0 ? ok(slot) : fail("The client did not create the macro");
63
+ }
64
+
65
+ function edit(slot: number, name: string, icon?: number, body?: string) {
66
+ const call = api.EditMacro;
67
+ if (call === undefined) return fail("EditMacro is unavailable");
68
+ if (api.InCombatLockdown() === true) return fail("Cannot edit macros in combat");
69
+ const result = protect(() => call(slot, name, icon, body));
70
+ if (!result.ok) return result;
71
+ return result.value === undefined || result.value > 0 ? ok(result.value) : fail("The client did not edit the macro");
72
+ }
73
+
74
+ function pickup(name: string) {
75
+ const call = api.PickupMacro;
76
+ if (call === undefined) return fail("PickupMacro is unavailable");
77
+ if (api.InCombatLockdown() === true) return fail("Cannot pick up macros in combat");
78
+ return protect(() => call(name));
79
+ }
80
+
81
+ return { index, read, freeSlots, iconID, create, edit, pickup };
82
+ }
83
+
84
+ export const macroBook = createMacroBook();
@@ -0,0 +1,27 @@
1
+ import { luaString } from "./lua-string";
2
+ import { api, reveal, type LuaMultiReturn, type SecretValue } from "./native";
3
+
4
+ declare const $multi: (<Value extends unknown[]>(this: void, ...values: Value) => LuaMultiReturn<Value>) & {
5
+ readonly __tstlExtension: "MultiFunction";
6
+ };
7
+
8
+ type MapPosition = {
9
+ GetXY(this: object): LuaMultiReturn<[number | SecretValue<number>, number | SecretValue<number>]>;
10
+ };
11
+
12
+ /** Read the player's map coordinates as normalized fractions. Each axis may be unavailable independently. */
13
+ export function readPlayerMapPosition(this: void): LuaMultiReturn<[x: number | undefined, y: number | undefined]> {
14
+ const maps = api.C_Map;
15
+ if (!maps?.GetBestMapForUnit || !maps.GetPlayerMapPosition) return $multi(undefined, undefined);
16
+ const map = reveal(maps.GetBestMapForUnit("player"));
17
+ if (map === undefined) return $multi(undefined, undefined);
18
+ const point = reveal(maps.GetPlayerMapPosition(map, "player")) as MapPosition | undefined;
19
+ if (point === undefined) return $multi(undefined, undefined);
20
+ const [x, y] = point.GetXY();
21
+ return $multi(reveal(x), reveal(y));
22
+ }
23
+
24
+ /** Format normalized map coordinates using the client's Lua number formatting. */
25
+ export function formatMapCoordinates(this: void, x: number, y: number): string {
26
+ return luaString.format("%.1f, %.1f", x * 100, y * 100);
27
+ }
@@ -0,0 +1,65 @@
1
+ import { createMediaObserver, type BreakpointTable, type MediaObserver } from "../src/media-query";
2
+ import { ownedMap, type OwnedMap } from "../src/owned-collections";
3
+ import type { ReadonlyRef } from "../src/reactivity";
4
+ import { ok, type Result } from "../src/result";
5
+ import type { RuntimeScope } from "../src/runtime";
6
+ import type { EventApi } from "./contract";
7
+ import type { Frame } from "./frames";
8
+ import { api, reveal } from "./native";
9
+ import { hookScript } from "./native-hooks";
10
+
11
+ export interface NativeMediaOptions {
12
+ readonly breakpoints: BreakpointTable;
13
+ readonly reducedMotion: ReadonlyRef<boolean>;
14
+ readonly events: EventApi;
15
+ }
16
+
17
+ interface Entry {
18
+ readonly observer: MediaObserver<string>;
19
+ readonly owner: RuntimeScope;
20
+ users: number;
21
+ }
22
+
23
+ const environments = new Map<NativeMediaOptions, OwnedMap<Frame, Entry>>();
24
+
25
+ export function observeContainer(this: void, options: NativeMediaOptions, nearest: Frame | undefined, consumer: RuntimeScope,
26
+ newScope: (this: void) => RuntimeScope): Result<MediaObserver<string>> {
27
+ const container = nearest ?? api.UIParent as Frame;
28
+ const containers = environments.get(options) ?? ownedMap<Frame, Entry>();
29
+ let entry = containers.get(container);
30
+ if (entry === undefined) {
31
+ const owner = newScope();
32
+ const observer = createMediaObserver(options.breakpoints, options.reducedMotion);
33
+ // GetWidth and OnSizeChanged report the same layout units used by the native layout solver.
34
+ const measure = () => {
35
+ const width = reveal(container.GetWidth());
36
+ if (width !== undefined) observer.resize(width);
37
+ };
38
+ const hooked = hookScript(container, "OnSizeChanged", (_, width) => {
39
+ const next = reveal(width);
40
+ if (next !== undefined) observer.resize(next);
41
+ }, owner);
42
+ const scaled = hooked.ok ? options.events.on(owner, "UI_SCALE_CHANGED", measure) : hooked;
43
+ if (!scaled.ok) {
44
+ owner.dispose();
45
+ return scaled;
46
+ }
47
+ measure();
48
+ entry = { observer, owner, users: 0 };
49
+ containers.set(container, entry);
50
+ environments.set(options, containers);
51
+ }
52
+
53
+ const active = entry;
54
+ active.users += 1;
55
+ const release = () => {
56
+ active.users -= 1;
57
+ if (active.users !== 0) return;
58
+ containers.delete(container);
59
+ if (containers.size === 0) environments.delete(options);
60
+ active.owner.dispose();
61
+ };
62
+ const binding = consumer.onDispose(release);
63
+ if (!binding.ok) { release(); return binding; }
64
+ return ok(active.observer);
65
+ }
@@ -0,0 +1,11 @@
1
+ import { moduleInput } from "../src/module";
2
+ import type { EventApi, EventOptions, WoWEvent, WoWEventMap } from "./contract";
3
+
4
+ /** Bind a host's shared dispatcher before resolving modules with declared event handlers. */
5
+ export const moduleEvents = moduleInput<EventApi>("kumi/wow/module-events");
6
+
7
+ /** Build-time declaration of a module-scoped WoW event handler. */
8
+ export declare function OnEvent<Event extends WoWEvent>(event: Event, options?: Pick<EventOptions, "unit" | "units">):
9
+ <Handler extends (this: object, ...payload: WoWEventMap[Event]) => void>(
10
+ this: void, target: object, key: string | symbol, descriptor: TypedPropertyDescriptor<Handler>,
11
+ ) => void;
@@ -0,0 +1,168 @@
1
+ import { currentScope } from "../src/reactive-scope";
2
+ import { ownedSet, type OwnedSet } from "../src/owned-collections";
3
+ import { fail, ok, type Result } from "../src/result";
4
+ import type { RuntimeScope } from "../src/runtime";
5
+ import type { Cancel } from "../src/scheduler";
6
+ import { canAccessRegion } from "./frame-access";
7
+ import type { Button, CommonScripts, Frame } from "./frames";
8
+ import { rawField, weakKeys } from "./lua-table";
9
+ import { api, reveal } from "./native";
10
+ import { protectNative } from "./protect";
11
+
12
+ type Callback = (this: void, self: Frame, ...args: unknown[]) => void;
13
+ type Install = (this: void, dispatch: Callback) => void;
14
+ type SecureHook = (this: void, frame: Frame, method: string, dispatch: Callback) => void;
15
+ type MethodKeys<Native> = {
16
+ [Key in keyof Native]-?: NonNullable<Native[Key]> extends (this: infer Receiver, ...args: never[]) => unknown
17
+ ? Receiver extends object ? Key : never
18
+ : never;
19
+ }[keyof Native] & string;
20
+ type MethodArgs<Method> = Method extends (...args: infer Args) => unknown ? Args : never;
21
+
22
+ interface Listener {
23
+ scope?: RuntimeScope;
24
+ callback?: Callback;
25
+ unlink?: Cancel;
26
+ }
27
+
28
+ interface Entry {
29
+ installed: boolean;
30
+ listeners: OwnedSet<Listener>;
31
+ }
32
+
33
+ type Slots = Partial<Record<string, Entry | false>>;
34
+
35
+ declare function rawget(this: void, registry: object, frame: Frame): Slots | undefined;
36
+ declare function rawset(this: void, registry: object, frame: Frame, slots: Slots): void;
37
+ declare function setmetatable<T extends object>(this: void, table: T, metatable: { __mode: "v" }): T;
38
+
39
+ const scripts = weakKeys({});
40
+ const methods = weakKeys({});
41
+
42
+ function nativeFailure(problem: unknown) {
43
+ const reason = reveal(problem);
44
+ return fail(typeof reason === "string" ? reason : "Native hook registration failed");
45
+ }
46
+
47
+ function subscribe(entry: Entry, scope: RuntimeScope, callback: Callback): Result<Cancel> {
48
+ const listener: Listener = { scope, callback };
49
+ let listeners: OwnedSet<Listener> | undefined = entry.listeners;
50
+ function cancel() {
51
+ if (listeners === undefined) return;
52
+ listeners.delete(listener);
53
+ listeners = undefined;
54
+ const unlink = listener.unlink;
55
+ listener.unlink = undefined;
56
+ listener.callback = undefined;
57
+ listener.scope = undefined;
58
+ unlink?.();
59
+ }
60
+ const cleanup = scope.onDispose(cancel);
61
+ if (!cleanup.ok) return cleanup;
62
+ listener.unlink = cleanup.value;
63
+ listeners.add(listener);
64
+ return ok(cancel);
65
+ }
66
+
67
+ function dispatcher(entry: Entry): Callback {
68
+ return (self, ...args) => {
69
+ const { listeners } = entry;
70
+ if (!entry.installed || listeners.size === 0) return;
71
+ const single = listeners.size === 1;
72
+ const delivery: Iterable<Listener> = single ? listeners : [...listeners];
73
+ for (const listener of delivery) {
74
+ const callback = listener.callback;
75
+ if (callback !== undefined && listener.scope?.isActive()) {
76
+ const [success, problem] = protectNative(callback, self, ...args);
77
+ if (!success) protectNative(() => api.geterrorhandler()(problem));
78
+ }
79
+ // The sole listener can add another listener or dispatch a nested event.
80
+ if (single) break;
81
+ }
82
+ };
83
+ }
84
+
85
+ function register(registry: object, frame: Frame, key: string, callback: Callback, scope: RuntimeScope | undefined,
86
+ prepare: (this: void) => Result<Install>): Result<Cancel> {
87
+ if (scope === undefined || !scope.isActive()) return fail("Native hooks require an active scope");
88
+ const [readable, result] = protectNative(() => {
89
+ if (!canAccessRegion(frame)) return fail("Frame is inaccessible");
90
+ let slots = rawget(registry, frame);
91
+ const existing = slots?.[key];
92
+ if (existing === false) return fail("An earlier native hook install could not be confirmed");
93
+ if (existing !== undefined) {
94
+ if (!existing.installed) return fail("The native hook is being installed");
95
+ return subscribe(existing, scope, callback);
96
+ }
97
+
98
+ const lockdown = reveal(api.InCombatLockdown());
99
+ const [protectedState] = frame.IsProtected();
100
+ const protectedFrame = reveal(protectedState);
101
+ if (typeof lockdown !== "boolean" || typeof protectedFrame !== "boolean") {
102
+ return fail("Frame protection or combat lockdown is unreadable");
103
+ }
104
+ if (lockdown && protectedFrame) return fail("Cannot install a hook on a protected frame in combat; retry out of combat");
105
+
106
+ const prepared = prepare();
107
+ if (!prepared.ok) return prepared;
108
+ const entry: Entry = { installed: false, listeners: ownedSet<Listener>() };
109
+ const registered = subscribe(entry, scope, callback);
110
+ if (!registered.ok) return registered;
111
+ if (slots === undefined) {
112
+ // The native hook owns the live entry. A listener may itself close over the frame.
113
+ slots = setmetatable<Slots>({}, { __mode: "v" });
114
+ rawset(registry, frame, slots);
115
+ }
116
+ slots[key] = entry;
117
+ const [installed, problem] = protectNative(() => prepared.value(dispatcher(entry)));
118
+ if (!installed) {
119
+ slots[key] = false;
120
+ registered.value();
121
+ return nativeFailure(problem);
122
+ }
123
+ entry.installed = true;
124
+ if (!scope.isActive()) {
125
+ registered.value();
126
+ return fail("The hook scope closed during installation");
127
+ }
128
+ return registered;
129
+ });
130
+ return readable ? result : nativeFailure(result);
131
+ }
132
+
133
+ /** Run after a native frame script while its owner scope is active. */
134
+ export function hookScript<Native extends Button>(this: void, frame: Native, script: "OnEnable" | "OnDisable",
135
+ callback: (this: void, self: NoInfer<Native>) => void, ownerScope?: RuntimeScope): Result<Cancel>;
136
+ export function hookScript<Native extends Frame, Script extends keyof CommonScripts>(this: void, frame: Native, script: Script,
137
+ callback: (this: void, self: NoInfer<Native>, ...args: CommonScripts[Script]) => void,
138
+ ownerScope?: RuntimeScope): Result<Cancel>;
139
+ export function hookScript(this: void, frame: Frame, script: keyof CommonScripts | "OnEnable" | "OnDisable",
140
+ callback: Callback, ownerScope: RuntimeScope | undefined = currentScope()): Result<Cancel> {
141
+ return register(scripts, frame, script, callback, ownerScope, () => {
142
+ const native = frame as Button;
143
+ if (typeof reveal(frame.HasScript) !== "function" || typeof reveal(frame.HookScript) !== "function"
144
+ || reveal(native.HasScript(script)) !== true) return fail("Frame does not support the script");
145
+ return ok<Install>(dispatch => native.HookScript(script, dispatch));
146
+ });
147
+ }
148
+
149
+ export function hookButtonClick(this: void, button: Button,
150
+ callback: (this: void, self: Button, button: string, down: boolean) => void, scope: RuntimeScope): Result<Cancel> {
151
+ return register(scripts, button, "OnClick", callback as Callback, scope, () => {
152
+ if (typeof reveal(button.HasScript) !== "function" || typeof reveal(button.HookScript) !== "function"
153
+ || reveal(button.HasScript("OnClick")) !== true) return fail("Button does not support the click script");
154
+ return ok<Install>(dispatch => button.HookScript("OnClick", dispatch));
155
+ });
156
+ }
157
+
158
+ /** Observe a native receiver method after it runs without changing its return values. */
159
+ export function hookSecureMethod<Native extends Frame, Method extends MethodKeys<Native>>(this: void, frame: Native, method: Method,
160
+ callback: (this: void, self: NoInfer<Native>, ...args: MethodArgs<Native[Method]>) => void,
161
+ ownerScope: RuntimeScope | undefined = currentScope()): Result<Cancel> {
162
+ return register(methods, frame, method, callback as Callback, ownerScope, () => {
163
+ const hook = reveal(rawField<SecureHook>(api, "hooksecurefunc"));
164
+ if (typeof hook !== "function") return fail("hooksecurefunc is unavailable");
165
+ if (typeof reveal(frame[method]) !== "function") return fail("Frame does not support the method");
166
+ return ok<Install>(dispatch => hook(frame, method, dispatch));
167
+ });
168
+ }
@@ -0,0 +1,88 @@
1
+ import type { SimpleFrame } from "@kumi/wow-generated";
2
+ import type { OwnedReadonlyArray } from "../src/owned-collections";
3
+ import type { Frame, FrameParent } from "./frames";
4
+ import { rawField } from "./lua-table";
5
+ import { isSecret, reveal } from "./native";
6
+ import { protect } from "./protect";
7
+
8
+ export type NativeAnchorPoint = Parameters<Frame["SetPoint"]>[0];
9
+ export type NativeAnchorRegion = Pick<Frame, "SetPoint">;
10
+ type ReadableAnchors = Pick<Frame, "GetNumPoints" | "GetPoint">;
11
+ type ExplicitAnchorRegion = Pick<SimpleFrame, "SetPoint">;
12
+ interface AnchorWriter {
13
+ SetPoint(this: object, point: NativeAnchorPoint, x: number, y: number): void;
14
+ SetPoint(this: object, point: NativeAnchorPoint, target?: FrameParent | string, relative?: NativeAnchorPoint, x?: number, y?: number): void;
15
+ }
16
+
17
+ export interface NativeAnchor {
18
+ point: NativeAnchorPoint;
19
+ target?: FrameParent | string;
20
+ relative?: NativeAnchorPoint;
21
+ x?: number;
22
+ y?: number;
23
+ }
24
+
25
+ /** Set one anchor of a caller-owned native region without taking ownership of its other anchors. */
26
+ export function anchorNativeRegion(this: void, region: NativeAnchorRegion, point: NativeAnchorPoint, x: number, y: number): void;
27
+ export function anchorNativeRegion(this: void, region: NativeAnchorRegion, point: NativeAnchorPoint,
28
+ target?: FrameParent | string, relative?: NativeAnchorPoint, x?: number, y?: number): void;
29
+ export function anchorNativeRegion(this: void, region: ExplicitAnchorRegion, point: NativeAnchorPoint,
30
+ target: FrameParent | string, relative: NativeAnchorPoint, x: number, y: number): void;
31
+ export function anchorNativeRegion(this: void, region: NativeAnchorRegion | ExplicitAnchorRegion, point: NativeAnchorPoint,
32
+ target?: FrameParent | string | number, relative?: NativeAnchorPoint | number, x?: number, y?: number): void {
33
+ const writer = region as AnchorWriter;
34
+ if (typeof target === "number" && typeof relative === "number") writer.SetPoint(point, target, relative);
35
+ else if (target === undefined && relative === undefined && x === undefined && y === undefined) writer.SetPoint(point);
36
+ else writer.SetPoint(point, target as NativeAnchor["target"], relative as NativeAnchor["relative"], x, y);
37
+ }
38
+
39
+ export function readNativeAnchor(this: void, region: ReadableAnchors, index: number): NativeAnchor | undefined {
40
+ const [rawPoint, target, relative, x, y] = region.GetPoint(index);
41
+ const point = reveal(rawPoint);
42
+ if (point === undefined || isSecret(target) || isSecret(relative) || isSecret(x) || isSecret(y)) return;
43
+ return { point, target: target as NativeAnchor["target"], relative: reveal(relative), x: reveal(x), y: reveal(y) };
44
+ }
45
+
46
+ export function captureNativeAnchors(this: void, region: ReadableAnchors): NativeAnchor[] | undefined {
47
+ const count = reveal(region.GetNumPoints());
48
+ if (count === undefined) return;
49
+ const anchors: NativeAnchor[] = [];
50
+ for (let index = 1; index <= count; index++) {
51
+ const anchor = readNativeAnchor(region, index);
52
+ if (anchor === undefined) return;
53
+ anchors.push(anchor);
54
+ }
55
+ return anchors;
56
+ }
57
+
58
+ export function restoreNativeAnchors(this: void, region: NativeAnchorRegion & Pick<Frame, "ClearAllPoints">, anchors: readonly NativeAnchor[]) {
59
+ region.ClearAllPoints();
60
+ for (const anchor of anchors as OwnedReadonlyArray<NativeAnchor>) {
61
+ const { point, target, relative, x, y } = anchor;
62
+ if (target === undefined && relative === undefined) anchorNativeRegion(region, point, x ?? 0, y ?? 0);
63
+ else anchorNativeRegion(region, point, target, relative, x, y);
64
+ }
65
+ }
66
+
67
+ type FrameLookup = (this: void, frame: Frame, name: string) => unknown;
68
+ type BaseClear = (this: void, frame: Frame) => void;
69
+ type BasePoint = (this: void, frame: Frame, point: NativeAnchorPoint, target: FrameParent, relative: NativeAnchorPoint,
70
+ x: number, y: number) => void;
71
+ declare function getmetatable(this: void, value: object): unknown;
72
+
73
+ /** Place a native frame whose instance layout methods are overridden by the host. The owner checks lockdown. */
74
+ export function centerNativeFrameWithBaseMethods(this: void, frame: Frame, parent: FrameParent, x: number, y: number): boolean {
75
+ const result = protect(() => {
76
+ const metadata = reveal(getmetatable(frame));
77
+ const lookup = reveal(rawField<object | FrameLookup>(metadata, "__index"));
78
+ const method = (name: string) => typeof lookup === "function" ? lookup(frame, name) : rawField(lookup, name);
79
+ const clear = reveal(method("ClearAllPoints")) as BaseClear | undefined;
80
+ const set = reveal(method("SetPoint")) as BasePoint | undefined;
81
+ const scale = reveal(frame.GetScale());
82
+ if (typeof clear !== "function" || typeof set !== "function" || typeof scale !== "number" || !Number.isFinite(scale) || scale <= 0) return false;
83
+ clear(frame);
84
+ set(frame, "CENTER", parent, "CENTER", x / scale, y / scale);
85
+ return true;
86
+ });
87
+ return result.ok && result.value;
88
+ }
package/wow/native.ts ADDED
@@ -0,0 +1,135 @@
1
+ import type { LuaMultiReturn, SecretValue, SimpleFont, WoWGlobals } from "@kumi/wow-generated";
2
+ import type { FrameParent } from "./frames";
3
+ import type { SecureFrame, SecureScript } from "./secure-transaction";
4
+
5
+ export type { LuaMultiReturn, SecretValue, WoWGlobals } from "@kumi/wow-generated";
6
+
7
+ type BaseUnitToken = Lowercase<Exclude<keyof WoWGlobals["Enum"]["UnitTokenType"], "None">>;
8
+ export type UnitToken = BaseUnitToken | `${BaseUnitToken}target` | `${BaseUnitToken}targettarget`;
9
+
10
+ type UnitClassResult = ReturnType<WoWGlobals["UnitClass"]>;
11
+
12
+ interface TimerHandle {
13
+ Cancel(this: TimerHandle): void;
14
+ IsCancelled(this: TimerHandle): boolean;
15
+ }
16
+
17
+ // Blizzard describes the callback for these functions. The value they return is the timer handle.
18
+ type TimerApi = Omit<WoWGlobals["C_Timer"], "NewTimer" | "NewTicker"> & {
19
+ NewTimer(this: void, seconds: number, callback: (this: void, timer: TimerHandle) => void): TimerHandle;
20
+ NewTicker(this: void, seconds: number, callback: (this: void, timer: TimerHandle) => void, iterations?: number): TimerHandle;
21
+ };
22
+
23
+ interface MerchantApi {
24
+ GetNumJunkItems?(this: void): number;
25
+ IsSellAllJunkEnabled?(this: void): boolean;
26
+ SellAllJunkItems?(this: void): void;
27
+ }
28
+
29
+ // Native globals omitted by Blizzard's generated API documentation.
30
+ interface LegacyGlobals {
31
+ CreateFont(this: void, name: string): SimpleFont;
32
+ CreateColor?(this: void, red: number, green: number, blue: number, alpha: number): unknown;
33
+ readonly CurveConstants?: { readonly ScaleTo100?: Parameters<WoWGlobals["UnitHealthPercent"]>[2] };
34
+ readonly C_MerchantFrame?: MerchantApi;
35
+ readonly C_PetBattles?: WoWGlobals["C_PetBattles"] & { CancelPVPDuel?(this: void): void };
36
+ readonly NUM_BAG_SLOTS?: number;
37
+ readonly NUM_TOTAL_EQUIPPED_BAG_SLOTS?: number;
38
+ readonly GetItemInfo?: WoWGlobals["C_Item"]["GetItemInfo"];
39
+ readonly LE_PARTY_CATEGORY_HOME?: number;
40
+ readonly LE_PARTY_CATEGORY_INSTANCE?: number;
41
+ GetNumGroupMembers(this: void, category?: number): number;
42
+ GetNumSubgroupMembers?(this: void, category?: number): number;
43
+ GetInventoryItemDurability?(this: void, slot: number): LuaMultiReturn<[
44
+ current?: number | SecretValue<number>, maximum?: number | SecretValue<number>,
45
+ ]>;
46
+ GetInventoryItemTexture?(this: void, unit: string, slot: number): number | string | SecretValue<number | string> | undefined;
47
+ IsInRaid(this: void, category?: number): boolean;
48
+ readonly RAID_CLASS_COLORS?: Readonly<Partial<Record<string, { readonly r: number; readonly g: number; readonly b: number }>>>;
49
+ readonly SlashCmdList?: Record<string, (this: void, input: string) => void>;
50
+ readonly TooltipDataProcessor?: {
51
+ readonly AllTypes?: unknown;
52
+ AddTooltipPostCall?(this: void, type: unknown, callback: (this: void, tooltip: unknown, data: unknown) => void): void;
53
+ };
54
+ AcceptQuest?(this: void): void;
55
+ CompleteQuest?(this: void): void;
56
+ IsQuestCompletable?(this: void): boolean;
57
+ GetNumQuestChoices?(this: void): number;
58
+ GetQuestReward?(this: void, choice: number): void;
59
+ GetNumLootItems?(this: void): number;
60
+ LootSlot?(this: void, slot: number): void;
61
+ GetLFGRoleUpdate?(this: void): LuaMultiReturn<[
62
+ active: boolean | SecretValue<boolean>, firstRole: unknown, secondRole: unknown, thirdRole: unknown,
63
+ fourthRole: unknown, isPvP?: boolean | SecretValue<boolean>,
64
+ ]>;
65
+ LFDRoleCheckPopup_GetRolesChecked?(this: void): LuaMultiReturn<[
66
+ tank: boolean | SecretValue<boolean>, healer: boolean | SecretValue<boolean>, damage: boolean | SecretValue<boolean>,
67
+ ]>;
68
+ CompleteLFGRoleCheck?(this: void, accepted: boolean): boolean | undefined;
69
+ GetLFGRoles?(this: void): LuaMultiReturn<[
70
+ leader: boolean | SecretValue<boolean>, tank: boolean, healer: boolean, damage: boolean,
71
+ ]>;
72
+ SetLFGRoles?(this: void, leader: boolean, tank: boolean, healer: boolean, damage: boolean): void;
73
+ SetPVPRoles?(this: void, tank: boolean, healer: boolean, damage: boolean): void;
74
+ IsGuildMember?(this: void, guid: string): boolean;
75
+ AcceptGroup?(this: void): void;
76
+ CancelDuel?(this: void): void;
77
+ CanCancelScene?(this: void): boolean;
78
+ CancelScene?(this: void): void;
79
+ CanMerchantRepair?(this: void): boolean;
80
+ CanGuildBankRepair?(this: void): boolean;
81
+ GetGuildBankMoney?(this: void): number;
82
+ GetGuildBankWithdrawMoney?(this: void): number;
83
+ GetMerchantNumItems?(this: void): number;
84
+ GetMoneyString?(this: void, copper: number, separateThousands?: boolean): string;
85
+ GetRepairAllCost?(this: void): LuaMultiReturn<[cost: number, canRepair: boolean]>;
86
+ RepairAllItems?(this: void, guildBank?: boolean): void;
87
+ GetNumMacros?(this: void): LuaMultiReturn<[account: number, character: number]>;
88
+ GetMacroIndexByName?(this: void, name: string): number;
89
+ GetMacroInfo?(this: void, macro: number | string): LuaMultiReturn<[name?: string, icon?: number, body?: string]>;
90
+ CreateMacro?(this: void, name: string, icon: number | string, body: string, perCharacter: boolean): number | undefined;
91
+ EditMacro?(this: void, index: number, name?: string, icon?: number | string, body?: string): number | undefined;
92
+ PickupMacro?(this: void, macro: number | string): void;
93
+ IsPlayerSpell?(this: void, spellID: number): boolean;
94
+ SecureHandlerWrapScript(this: void, frame: SecureFrame, script: SecureScript, header: SecureFrame,
95
+ preBody: string, postBody?: string): void;
96
+ SecureHandlerUnwrapScript(this: void, frame: SecureFrame, script: SecureScript): LuaMultiReturn<[
97
+ header?: SecureFrame, preBody?: string, postBody?: string,
98
+ ]>;
99
+ SecureHandlerSetFrameRef(this: void, frame: SecureFrame, label: string, reference: SecureFrame): void;
100
+ SecureHandler_StateOnAttributeChanged(this: void, self: SecureFrame, name: string, value: unknown): void;
101
+ RegisterStateDriver(this: void, frame: SecureFrame, state: string, macroCondition: string): void;
102
+ UnregisterStateDriver(this: void, frame: SecureFrame, state: string): void;
103
+ SetOverrideBindingClick(this: void, owner: SecureFrame, priority: boolean, key: string, button: string, mouseButton?: string): void;
104
+ ClearOverrideBindings(this: void, owner: SecureFrame): void;
105
+ geterrorhandler(this: void): (this: void, error: unknown) => void;
106
+ }
107
+
108
+ declare const _G: Omit<WoWGlobals, keyof LegacyGlobals | "C_NamePlate" | "C_PartyInfo" | "C_Timer" | "Constants" | "IsInGroup" | "UnitClass"> & LegacyGlobals & {
109
+ readonly C_NamePlate: Omit<WoWGlobals["C_NamePlate"], "GetNamePlates"> & {
110
+ GetNamePlates(this: void, includeForbidden?: boolean): unknown[];
111
+ };
112
+ readonly C_PartyInfo: WoWGlobals["C_PartyInfo"] & { InitiateRolePoll?(this: void): boolean | void };
113
+ readonly C_Timer: TimerApi;
114
+ readonly Constants: Omit<WoWGlobals["Constants"], "MacroConsts"> & {
115
+ readonly MacroConsts?: { readonly MAX_ACCOUNT_MACROS?: number; readonly MAX_CHARACTER_MACROS?: number };
116
+ };
117
+ readonly UIParent: FrameParent;
118
+ IsInGroup(this: void, category?: number): boolean;
119
+ UnitClass(this: void, unit: UnitToken): UnitClassResult;
120
+ // The client can return a token as a plain string, even when its documentation lists UnitToken.
121
+ UnitClass<const Token extends string>(this: void, unit: Token & (string extends Token ? unknown : never)): UnitClassResult;
122
+ };
123
+ declare const issecretvalue: ((this: void, value: unknown) => boolean) | undefined;
124
+
125
+ /** Direct Lua API. Calls can still be restricted by the client. */
126
+ export const api = _G;
127
+
128
+ export function isSecret(value: unknown): boolean {
129
+ const check = issecretvalue;
130
+ return check !== undefined && check(value) === true;
131
+ }
132
+
133
+ export function reveal<T>(value: T | SecretValue<T> | undefined): T | undefined {
134
+ return isSecret(value) ? undefined : value as T;
135
+ }
@@ -0,0 +1,8 @@
1
+ import { api, reveal, type SecretValue } from "./native";
2
+
3
+ /** Format a readable number with the client's grouping separators. */
4
+ export function formatWoWNumber(this: void, value: number | SecretValue<number> | undefined): string | undefined {
5
+ const readable = reveal(value);
6
+ if (typeof readable !== "number" || !Number.isFinite(readable)) return undefined;
7
+ return api.BreakUpLargeNumbers?.(readable) ?? String(readable);
8
+ }
@@ -0,0 +1,10 @@
1
+ import { clamp } from "../utils/number";
2
+ import { isSecret } from "./native";
3
+
4
+ declare function tonumber(this: void, value: unknown): number | undefined;
5
+
6
+ /** Clamps a Lua numeric input, using the fallback when the input has no readable number. */
7
+ export function clampWoWNumber(value: unknown, minimum: number, maximum: number, fallback = minimum): number {
8
+ const numeric = isSecret(value) ? undefined : tonumber(value);
9
+ return clamp(numeric === undefined || numeric !== numeric ? fallback : numeric, minimum, maximum);
10
+ }
package/wow/protect.ts ADDED
@@ -0,0 +1,24 @@
1
+ import { fail, ok, type Result } from "../src/result";
2
+ import type { LuaMultiReturn } from "@kumi/wow-generated";
3
+
4
+ type ProtectedNative<Values extends unknown[]> = LuaMultiReturn<
5
+ [success: true, ...values: Values] | [success: false, error: unknown]
6
+ >;
7
+
8
+ declare function pcall<Receiver extends object, Args extends unknown[], Values extends unknown[]>(
9
+ this: void, run: (this: Receiver, ...args: Args) => LuaMultiReturn<Values>, receiver: Receiver, ...args: Args
10
+ ): ProtectedNative<Values>;
11
+ declare function pcall<Args extends unknown[], Value>(
12
+ this: void, run: (this: void, ...args: Args) => Value, ...args: Args
13
+ ): ProtectedNative<[Value]>;
14
+ declare function pcall<Receiver extends object, Args extends unknown[], Value>(
15
+ this: void, run: (this: Receiver, ...args: Args) => Value, receiver: Receiver, ...args: Args
16
+ ): ProtectedNative<[Value]>;
17
+
18
+ /** Preserve native multiple returns and leave error objects opaque. */
19
+ export const protectNative = pcall;
20
+
21
+ export function protect<T>(run: (this: void) => T): Result<T> {
22
+ const [success, value] = protectNative(run);
23
+ return success ? ok(value) : fail(String(value));
24
+ }