@coorax/core 0.0.0-canary.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 (78) hide show
  1. package/package.json +40 -0
  2. package/src/base/classes/component.class.ts +68 -0
  3. package/src/base/classes/container.class.ts +57 -0
  4. package/src/base/classes/field.class.ts +42 -0
  5. package/src/base/classes/tnode.class.ts +38 -0
  6. package/src/base/index.ts +23 -0
  7. package/src/base/types/components/components.ts +21 -0
  8. package/src/base/types/container/container.ts +37 -0
  9. package/src/base/types/container/division.types.ts +3 -0
  10. package/src/base/types/container/section.types.ts +3 -0
  11. package/src/base/types/container/ul-list.types.ts +3 -0
  12. package/src/base/types/css.types.ts +33 -0
  13. package/src/base/types/field/divider.types.ts +3 -0
  14. package/src/base/types/field/field.media.types.ts +6 -0
  15. package/src/base/types/field/field.text.types.ts +9 -0
  16. package/src/base/types/field/field.ts +46 -0
  17. package/src/base/types/field/heading.types.ts +3 -0
  18. package/src/base/types/field/paragraph.types.ts +3 -0
  19. package/src/base/types/global.types.ts +45 -0
  20. package/src/base/types/node/link.types.ts +3 -0
  21. package/src/base/types/node/node.ts +28 -0
  22. package/src/base/types/node/span.types.ts +3 -0
  23. package/src/base/types/tree/tree.ts +33 -0
  24. package/src/engine/engine.test.ts +27 -0
  25. package/src/engine/engine.ts +38 -0
  26. package/src/engine/index.ts +1 -0
  27. package/src/index.ts +13 -0
  28. package/src/modules/editor/editor.module.ts +119 -0
  29. package/src/modules/focus/focus.module.ts +185 -0
  30. package/src/modules/history/history.module.ts +60 -0
  31. package/src/modules/hover/hover.module.ts +121 -0
  32. package/src/modules/index.ts +10 -0
  33. package/src/modules/insertion/insertion.module.ts +140 -0
  34. package/src/modules/modules-manager.ts +132 -0
  35. package/src/modules/modules.types.ts +47 -0
  36. package/src/modules/selection/selection.module.ts +174 -0
  37. package/src/modules/selection/selection.test.ts +1 -0
  38. package/src/modules/text-editing/text-editing.constants.ts +6 -0
  39. package/src/modules/text-editing/text-editing.module.ts +377 -0
  40. package/src/modules/text-editing/text-editing.utils.ts +27 -0
  41. package/src/services/commandsbus/commandsbus.test.ts +312 -0
  42. package/src/services/commandsbus/commandsbus.ts +360 -0
  43. package/src/services/commandsbus/index.ts +1 -0
  44. package/src/services/document/document.ts +139 -0
  45. package/src/services/document/index.ts +1 -0
  46. package/src/services/eventbus/eventbus.test.ts +144 -0
  47. package/src/services/eventbus/eventbus.ts +162 -0
  48. package/src/services/eventbus/index.ts +2 -0
  49. package/src/services/eventbus/subscriber.ts +46 -0
  50. package/src/services/mutations/index.ts +2 -0
  51. package/src/services/mutations/mutations.errors.ts +12 -0
  52. package/src/services/mutations/mutations.test.ts +177 -0
  53. package/src/services/mutations/mutations.ts +457 -0
  54. package/src/services/shortcuts/shortcuts.ts +3 -0
  55. package/src/services/state/index.ts +2 -0
  56. package/src/services/state/state.errors.ts +12 -0
  57. package/src/services/state/state.ts +64 -0
  58. package/src/services/tasks/index.ts +1 -0
  59. package/src/services/tasks/tasks.service.test.ts +193 -0
  60. package/src/services/tasks/tasks.service.ts +288 -0
  61. package/src/services/text-marks/index.ts +2 -0
  62. package/src/services/text-marks/marks.types.ts +38 -0
  63. package/src/services/text-marks/text-marks.ts +244 -0
  64. package/src/services/ui/default-styles.ts +93 -0
  65. package/src/services/ui/index.ts +3 -0
  66. package/src/services/ui/ui.errors.ts +6 -0
  67. package/src/services/ui/ui.ts +148 -0
  68. package/src/services/ui/ui.types.ts +197 -0
  69. package/src/utils/components.utils.ts +26 -0
  70. package/src/utils/container.utils.ts +59 -0
  71. package/src/utils/fields.utils.ts +118 -0
  72. package/src/utils/global.utils.ts +128 -0
  73. package/src/utils/index.ts +7 -0
  74. package/src/utils/modules.utils.ts +110 -0
  75. package/src/utils/tnode.utils.ts +48 -0
  76. package/src/utils/tree.utils.ts +120 -0
  77. package/styles.css +178 -0
  78. package/tsconfig.json +9 -0
@@ -0,0 +1,312 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { CmdNotFoundError, CommandsBusService } from "./commandsbus";
3
+ import { Engine } from "../../engine/engine";
4
+ import { ModuleUtils } from "../../utils/modules.utils";
5
+
6
+ declare module "./commandsbus" {
7
+ interface CommandMap {
8
+ "test.sync": {
9
+ payload: { count: number };
10
+ result: number;
11
+ };
12
+ "test.async": {
13
+ payload: { value: string };
14
+ result: string;
15
+ };
16
+ }
17
+ }
18
+
19
+ describe("CommandsBusService", () => {
20
+ it("should register and execute synchronous command", () => {
21
+ const bus = new CommandsBusService();
22
+ bus.register("test.sync", ({ count }) => count * 2);
23
+
24
+ expect(bus.has("test.sync")).toBe(true);
25
+ expect(bus.execute("test.sync", { count: 3 })).toBe(6);
26
+ expect(bus.tryExecute("test.sync", { count: 5 })).toBe(10);
27
+ });
28
+
29
+ it("should throw CmdNotFoundError when command is not registered", () => {
30
+ const bus = new CommandsBusService();
31
+ expect(() => bus.execute("test.sync", { count: 1 })).toThrow(CmdNotFoundError);
32
+ expect(bus.tryExecute("test.sync", { count: 1 })).toBeNull();
33
+ });
34
+
35
+ it("should execute before and after hooks in order", () => {
36
+ const bus = new CommandsBusService();
37
+ const calls: string[] = [];
38
+
39
+ bus.before("test.sync", ({ count }) => {
40
+ calls.push(`before-1:${count}`);
41
+ return { count };
42
+ });
43
+
44
+ bus.before("test.sync", ({ count }) => {
45
+ calls.push(`before-2:${count}`);
46
+ return { count };
47
+ });
48
+
49
+ bus.register("test.sync", ({ count }) => {
50
+ calls.push(`handler:${count}`);
51
+ return count + 10;
52
+ });
53
+
54
+ bus.after("test.sync", ({ count }, result) => {
55
+ calls.push(`after-1:${count}:${result}`);
56
+ });
57
+
58
+ bus.after("test.sync", ({ count }, result) => {
59
+ calls.push(`after-2:${count}:${result}`);
60
+ });
61
+
62
+ const result = bus.execute("test.sync", { count: 5 });
63
+
64
+ expect(result).toBe(15);
65
+ expect(calls).toEqual([
66
+ "before-1:5",
67
+ "before-2:5",
68
+ "handler:5",
69
+ "after-1:5:15",
70
+ "after-2:5:15",
71
+ ]);
72
+ });
73
+
74
+ it("should allow disposing before and after hooks", () => {
75
+ const bus = new CommandsBusService();
76
+ const calls: string[] = [];
77
+
78
+ const disposeBefore = bus.before("test.sync", (payload) => {
79
+ calls.push("before");
80
+ return payload;
81
+ });
82
+ const disposeAfter = bus.after("test.sync", () => {
83
+ calls.push("after");
84
+ });
85
+
86
+ bus.register("test.sync", ({ count }) => count);
87
+
88
+ bus.execute("test.sync", { count: 1 });
89
+ expect(calls).toEqual(["before", "after"]);
90
+
91
+ disposeBefore();
92
+ disposeAfter();
93
+
94
+ bus.execute("test.sync", { count: 2 });
95
+ expect(calls).toEqual(["before", "after"]);
96
+ });
97
+
98
+ it("should register and execute asynchronous command with async hooks", async () => {
99
+ const bus = new CommandsBusService();
100
+ const calls: string[] = [];
101
+
102
+ bus.before("test.async", (payload) => {
103
+ calls.push(`sync-before:${payload.value}`);
104
+ return payload;
105
+ });
106
+
107
+ bus.beforeAsync("test.async", async (payload) => {
108
+ await new Promise((r) => setTimeout(r, 5));
109
+ calls.push(`async-before:${payload.value}`);
110
+ return payload;
111
+ });
112
+
113
+ bus.registerAsync("test.async", async ({ value }) => {
114
+ await new Promise((r) => setTimeout(r, 5));
115
+ calls.push(`async-handler:${value}`);
116
+ return `result:${value}`;
117
+ });
118
+
119
+ bus.after("test.async", ({ value }, result) => {
120
+ calls.push(`sync-after:${value}:${result}`);
121
+ });
122
+
123
+ bus.afterAsync("test.async", async ({ value }, result) => {
124
+ await new Promise((r) => setTimeout(r, 5));
125
+ calls.push(`async-after:${value}:${result}`);
126
+ });
127
+
128
+ expect(bus.has("test.async")).toBe(true);
129
+
130
+ const result = await bus.executeAsync("test.async", { value: "hello" });
131
+
132
+ expect(result).toBe("result:hello");
133
+ expect(calls).toEqual([
134
+ "sync-before:hello",
135
+ "async-before:hello",
136
+ "async-handler:hello",
137
+ "sync-after:hello:result:hello",
138
+ "async-after:hello:result:hello",
139
+ ]);
140
+ });
141
+
142
+ it("should throw when trying to execute an async command synchronously", () => {
143
+ const bus = new CommandsBusService();
144
+ bus.registerAsync("test.async", async ({ value }) => value);
145
+
146
+ expect(() => bus.execute("test.async", { value: "test" })).toThrow(/is asynchronous/);
147
+ });
148
+
149
+ it("should throw when trying to execute synchronously with async hooks", () => {
150
+ const bus = new CommandsBusService();
151
+ bus.register("test.sync", ({ count }) => count);
152
+ bus.beforeAsync("test.sync", (payload) => payload);
153
+
154
+ expect(() => bus.execute("test.sync", { count: 1 })).toThrow(/asynchronous hooks/);
155
+ });
156
+
157
+ it("should support tryExecuteAsync catching CmdNotFoundError", async () => {
158
+ const bus = new CommandsBusService();
159
+ const result = await bus.tryExecuteAsync("test.async", { value: "test" });
160
+ expect(result).toBeNull();
161
+ });
162
+
163
+ it("should transform payload through next functions in order", () => {
164
+ const bus = new CommandsBusService();
165
+ const calls: string[] = [];
166
+
167
+ bus.before("test.sync", (payload) => {
168
+ calls.push(`next-1:${payload.count}`);
169
+ return { count: payload.count + 1 };
170
+ });
171
+
172
+ bus.before("test.sync", (payload) => {
173
+ calls.push(`next-2:${payload.count}`);
174
+ return { count: payload.count * 2 };
175
+ });
176
+
177
+ bus.register("test.sync", ({ count }) => {
178
+ calls.push(`handler:${count}`);
179
+ return count;
180
+ });
181
+
182
+ const result = bus.execute("test.sync", { count: 5 });
183
+
184
+ // Payload: 5 -> next-1 -> 6 -> next-2 -> 12
185
+ expect(result).toBe(12);
186
+ expect(calls).toEqual(["next-1:5", "next-2:6", "handler:12"]);
187
+ });
188
+
189
+ it("should cancel execution when next function returns null", () => {
190
+ const bus = new CommandsBusService();
191
+ const calls: string[] = [];
192
+
193
+ bus.before("test.sync", (payload) => {
194
+ calls.push(`next:${payload.count}`);
195
+ if (payload.count < 10) {
196
+ return null; // Cancel execution
197
+ }
198
+ return payload;
199
+ });
200
+
201
+ bus.register("test.sync", ({ count }) => {
202
+ calls.push(`handler:${count}`);
203
+ return count;
204
+ });
205
+
206
+ const result1 = bus.execute("test.sync", { count: 5 });
207
+ expect(result1).toBeNull();
208
+ expect(calls).toEqual(["next:5"]);
209
+
210
+ calls.length = 0;
211
+
212
+ const result2 = bus.execute("test.sync", { count: 15 });
213
+ expect(result2).toBe(15);
214
+ expect(calls).toEqual(["next:15", "handler:15"]);
215
+ });
216
+
217
+ it("should transform payload through async next functions in order", async () => {
218
+ const bus = new CommandsBusService();
219
+ const calls: string[] = [];
220
+
221
+ bus.before("test.async", (payload) => {
222
+ calls.push(`next-sync:${payload.value}`);
223
+ return { value: payload.value.toUpperCase() };
224
+ });
225
+
226
+ bus.beforeAsync("test.async", async (payload) => {
227
+ await new Promise((r) => setTimeout(r, 5));
228
+ calls.push(`next-async:${payload.value}`);
229
+ return { value: `${payload.value}!!!` };
230
+ });
231
+
232
+ bus.registerAsync("test.async", async ({ value }) => {
233
+ calls.push(`handler:${value}`);
234
+ return value;
235
+ });
236
+
237
+ const result = await bus.executeAsync("test.async", { value: "hello" });
238
+
239
+ // Payload: hello -> HELLO -> HELLO!!!
240
+ expect(result).toBe("HELLO!!!");
241
+ expect(calls).toEqual(["next-sync:hello", "next-async:HELLO", "handler:HELLO!!!"]);
242
+ });
243
+
244
+ it("should cancel async execution when next function returns null", async () => {
245
+ const bus = new CommandsBusService();
246
+ const calls: string[] = [];
247
+
248
+ bus.beforeAsync("test.async", async (payload) => {
249
+ await new Promise((r) => setTimeout(r, 5));
250
+ calls.push(`next:${payload.value}`);
251
+ if (payload.value.length < 5) {
252
+ return null; // Cancel execution
253
+ }
254
+ return payload;
255
+ });
256
+
257
+ bus.registerAsync("test.async", async ({ value }) => {
258
+ calls.push(`handler:${value}`);
259
+ return value;
260
+ });
261
+
262
+ const result1 = await bus.executeAsync("test.async", { value: "hi" });
263
+ expect(result1).toBeNull();
264
+ expect(calls).toEqual(["next:hi"]);
265
+
266
+ calls.length = 0;
267
+
268
+ const result2 = await bus.executeAsync("test.async", { value: "hello" });
269
+ expect(result2).toBe("hello");
270
+ expect(calls).toEqual(["next:hello", "handler:hello"]);
271
+ });
272
+ });
273
+
274
+ describe("ModuleUtils.createScopedTCtx command integration", () => {
275
+ it("should forward all command methods and dispose them on module unload", async () => {
276
+ const engine = new Engine();
277
+ const { ctx, dispose } = ModuleUtils.createScopedTCtx(engine, "focus");
278
+
279
+ const calls: string[] = [];
280
+
281
+ ctx.commands.before("test.sync", (payload) => {
282
+ calls.push("before-sync");
283
+ return payload;
284
+ });
285
+ ctx.commands.after("test.sync", () => {
286
+ calls.push("after-sync");
287
+ });
288
+ ctx.commands.register("test.sync", ({ count }) => count + 1);
289
+
290
+ expect(ctx.commands.has("test.sync")).toBe(true);
291
+ expect(ctx.commands.execute("test.sync", { count: 10 })).toBe(11);
292
+ expect(calls).toEqual(["before-sync", "after-sync"]);
293
+
294
+ ctx.commands.beforeAsync("test.async", async (payload) => {
295
+ calls.push("before-async");
296
+ return payload;
297
+ });
298
+ ctx.commands.afterAsync("test.async", async () => {
299
+ calls.push("after-async");
300
+ });
301
+ ctx.commands.registerAsync("test.async", async ({ value }) => value.toUpperCase());
302
+
303
+ const asyncRes = await ctx.commands.executeAsync("test.async", { value: "abc" });
304
+ expect(asyncRes).toBe("ABC");
305
+
306
+ // Dispose module
307
+ dispose();
308
+
309
+ expect(engine.commands.has("test.sync")).toBe(false);
310
+ expect(engine.commands.has("test.async")).toBe(false);
311
+ });
312
+ });
@@ -0,0 +1,360 @@
1
+ export interface CommandMap {}
2
+
3
+ export type CommandType = keyof CommandMap;
4
+ export type CommandPayload<T extends CommandType> = CommandMap[T]["payload"];
5
+ export type CommandResult<T extends CommandType> = CommandMap[T]["result"];
6
+
7
+ export type CommandHandler<T extends CommandType> = (
8
+ payload: CommandPayload<T>,
9
+ ) => CommandResult<T>;
10
+ export type CommandDisposer = () => void;
11
+
12
+ export type HookNextFunction<
13
+ T extends CommandType = CommandType,
14
+ P extends CommandPayload<T> = CommandPayload<T>,
15
+ > = (payload: P) => P | null;
16
+
17
+ export type AsyncHookNextFunction<
18
+ T extends CommandType = CommandType,
19
+ P extends CommandPayload<T> = CommandPayload<T>,
20
+ > = (payload: P) => Promise<P | null> | P | null;
21
+
22
+ export type AfterHook<T extends CommandType = CommandType> = (
23
+ payload: CommandPayload<T>,
24
+ result: CommandResult<T>,
25
+ ) => void;
26
+
27
+ export type AsyncCommandHandler<T extends CommandType = CommandType> = (
28
+ payload: CommandPayload<T>,
29
+ ) => Promise<CommandResult<T>> | CommandResult<T>;
30
+
31
+ export type AsyncAfterHook<T extends CommandType = CommandType> = (
32
+ payload: CommandPayload<T>,
33
+ result: CommandResult<T>,
34
+ ) => Promise<void> | void;
35
+
36
+ export interface CommandsInterface {
37
+ /**
38
+ * Return null if a **CmdNotFoundError** error is catched
39
+ * else throw the error
40
+ * @param cmd CommandType
41
+ * @param payload CommandPayload<T>
42
+ */
43
+ tryExecute<T extends CommandType = CommandType>(
44
+ cmd: T,
45
+ payload: CommandPayload<T>,
46
+ ): CommandResult<T> | null;
47
+
48
+ tryExecuteAsync<T extends CommandType = CommandType>(
49
+ cmd: T,
50
+ payload: CommandPayload<T>,
51
+ ): Promise<CommandResult<T> | null>;
52
+
53
+ execute<T extends CommandType = CommandType>(
54
+ cmd: T,
55
+ payload: CommandPayload<T>,
56
+ ): CommandResult<T> | null;
57
+
58
+ executeAsync<T extends CommandType = CommandType>(
59
+ cmd: T,
60
+ payload: CommandPayload<T>,
61
+ ): Promise<CommandResult<T> | null>;
62
+
63
+ register<T extends CommandType = CommandType>(
64
+ cmd: T,
65
+ callback: CommandHandler<T>,
66
+ ): CommandDisposer;
67
+
68
+ registerAsync<T extends CommandType = CommandType>(
69
+ cmd: T,
70
+ callback: AsyncCommandHandler<T>,
71
+ ): CommandDisposer;
72
+
73
+ before<T extends CommandType = CommandType>(
74
+ cmd: T,
75
+ next: HookNextFunction<T, CommandPayload<T>>,
76
+ ): CommandDisposer;
77
+
78
+ beforeAsync<T extends CommandType = CommandType>(
79
+ cmd: T,
80
+ next: AsyncHookNextFunction<T, CommandPayload<T>>,
81
+ ): CommandDisposer;
82
+
83
+ after<T extends CommandType = CommandType>(cmd: T, callback: AfterHook<T>): CommandDisposer;
84
+
85
+ afterAsync<T extends CommandType = CommandType>(
86
+ cmd: T,
87
+ callback: AsyncAfterHook<T>,
88
+ ): CommandDisposer;
89
+
90
+ has<T extends CommandType = CommandType>(cmd: T): boolean;
91
+ }
92
+
93
+ export class CmdNotFoundError extends Error {
94
+ constructor(cmd: CommandType) {
95
+ super(`Command ${cmd} is not registered (module disabled?)`);
96
+ }
97
+ }
98
+
99
+ export class CommandsBusService implements CommandsInterface {
100
+ private handlers: Map<CommandType, CommandHandler<CommandType>> = new Map();
101
+ private asyncHandlers: Map<CommandType, AsyncCommandHandler<CommandType>> = new Map();
102
+
103
+ private afterHooks: Map<CommandType, AfterHook<any>[]> = new Map();
104
+ private asyncAfterHooks: Map<CommandType, AsyncAfterHook<any>[]> = new Map();
105
+
106
+ private nextFunctions: Map<CommandType, HookNextFunction<any, any>[]> = new Map();
107
+ private asyncNextFunctions: Map<CommandType, AsyncHookNextFunction<any, any>[]> = new Map();
108
+
109
+ tryExecute<T extends CommandType = CommandType>(
110
+ cmd: T,
111
+ payload: CommandPayload<T>,
112
+ ): CommandResult<T> | null {
113
+ try {
114
+ return this.execute(cmd, payload);
115
+ } catch (er) {
116
+ if (!(er instanceof CmdNotFoundError)) throw er;
117
+ console.error(er.message);
118
+ return null;
119
+ }
120
+ }
121
+
122
+ async tryExecuteAsync<T extends CommandType = CommandType>(
123
+ cmd: T,
124
+ payload: CommandPayload<T>,
125
+ ): Promise<CommandResult<T> | null> {
126
+ try {
127
+ return await this.executeAsync(cmd, payload);
128
+ } catch (er) {
129
+ if (!(er instanceof CmdNotFoundError)) throw er;
130
+ console.error(er.message);
131
+ return null;
132
+ }
133
+ }
134
+
135
+ execute<T extends CommandType = CommandType>(
136
+ cmd: T,
137
+ payload: CommandPayload<T>,
138
+ ): CommandResult<T> | null {
139
+ const handler = this.handlers.get(cmd);
140
+ if (!handler) {
141
+ if (this.asyncHandlers.has(cmd)) {
142
+ throw new Error(`Command "${String(cmd)}" is asynchronous, use executeAsync instead`);
143
+ }
144
+ throw new CmdNotFoundError(cmd);
145
+ }
146
+
147
+ if (this.asyncNextFunctions.has(cmd) || this.asyncAfterHooks.has(cmd)) {
148
+ throw new Error(`Command "${String(cmd)}" has asynchronous hooks, use executeAsync instead`);
149
+ }
150
+
151
+ // Apply next functions to transform payload
152
+ const nextFunctions = this.nextFunctions.get(cmd);
153
+ let transformedPayload: CommandPayload<T> | null = payload;
154
+ if (nextFunctions) {
155
+ for (const nextFn of nextFunctions) {
156
+ const result = nextFn(transformedPayload);
157
+ if (result === null) {
158
+ // Execution cancelled by next function
159
+ return null;
160
+ }
161
+ transformedPayload = result;
162
+ }
163
+ }
164
+
165
+ const result = handler(transformedPayload) as CommandResult<T>;
166
+
167
+ const afterHooks = this.afterHooks.get(cmd);
168
+ if (afterHooks) {
169
+ for (const hook of afterHooks) {
170
+ hook(transformedPayload, result);
171
+ }
172
+ }
173
+
174
+ return result;
175
+ }
176
+
177
+ async executeAsync<T extends CommandType = CommandType>(
178
+ cmd: T,
179
+ payload: CommandPayload<T>,
180
+ ): Promise<CommandResult<T> | null> {
181
+ const asyncHandler = this.asyncHandlers.get(cmd);
182
+ const syncHandler = this.handlers.get(cmd);
183
+ const handler = asyncHandler ?? syncHandler;
184
+
185
+ if (!handler) {
186
+ throw new CmdNotFoundError(cmd);
187
+ }
188
+
189
+ // Apply next functions to transform payload (sync)
190
+ const nextFunctions = this.nextFunctions.get(cmd);
191
+ let transformedPayload: CommandPayload<T> | null = payload;
192
+ if (nextFunctions) {
193
+ for (const nextFn of nextFunctions) {
194
+ const result = nextFn(transformedPayload);
195
+ if (result === null) {
196
+ // Execution cancelled by next function
197
+ return null;
198
+ }
199
+ transformedPayload = result;
200
+ }
201
+ }
202
+
203
+ // Apply async next functions to transform payload
204
+ const asyncNextFunctions = this.asyncNextFunctions.get(cmd);
205
+ if (asyncNextFunctions) {
206
+ for (const nextFn of asyncNextFunctions) {
207
+ const result = await nextFn(transformedPayload);
208
+ if (result === null) {
209
+ // Execution cancelled by async next function
210
+ return null;
211
+ }
212
+ transformedPayload = result;
213
+ }
214
+ }
215
+
216
+ const result = (await handler(transformedPayload)) as CommandResult<T>;
217
+
218
+ const afterHooks = this.afterHooks.get(cmd);
219
+ if (afterHooks) {
220
+ for (const hook of afterHooks) {
221
+ hook(transformedPayload, result);
222
+ }
223
+ }
224
+
225
+ const asyncAfterHooks = this.asyncAfterHooks.get(cmd);
226
+ if (asyncAfterHooks) {
227
+ for (const hook of asyncAfterHooks) {
228
+ await hook(transformedPayload, result);
229
+ }
230
+ }
231
+
232
+ return result;
233
+ }
234
+
235
+ register<T extends CommandType = CommandType>(
236
+ cmd: T,
237
+ handler: CommandHandler<T>,
238
+ ): CommandDisposer {
239
+ if (this.handlers.has(cmd) || this.asyncHandlers.has(cmd)) {
240
+ throw new Error(`Command ${cmd} already registered`);
241
+ }
242
+
243
+ this.handlers.set(cmd as CommandType, handler as unknown as CommandHandler<CommandType>);
244
+ return () => {
245
+ if (
246
+ this.handlers.get(cmd as CommandType) ===
247
+ (handler as unknown as CommandHandler<CommandType>)
248
+ )
249
+ this.handlers.delete(cmd);
250
+ };
251
+ }
252
+
253
+ registerAsync<T extends CommandType = CommandType>(
254
+ cmd: T,
255
+ handler: AsyncCommandHandler<T>,
256
+ ): CommandDisposer {
257
+ if (this.handlers.has(cmd) || this.asyncHandlers.has(cmd)) {
258
+ throw new Error(`Command ${cmd} already registered`);
259
+ }
260
+
261
+ this.asyncHandlers.set(
262
+ cmd as CommandType,
263
+ handler as unknown as AsyncCommandHandler<CommandType>,
264
+ );
265
+ return () => {
266
+ if (
267
+ this.asyncHandlers.get(cmd as CommandType) ===
268
+ (handler as unknown as AsyncCommandHandler<CommandType>)
269
+ )
270
+ this.asyncHandlers.delete(cmd);
271
+ };
272
+ }
273
+
274
+ before<T extends CommandType = CommandType>(
275
+ cmd: T,
276
+ next: HookNextFunction<T, CommandPayload<T>>,
277
+ ): CommandDisposer {
278
+ const nextFunctions = this.nextFunctions.get(cmd) ?? [];
279
+ nextFunctions.push(next as HookNextFunction<any, any>);
280
+ this.nextFunctions.set(cmd, nextFunctions);
281
+
282
+ return () => {
283
+ const currentNextFunctions = this.nextFunctions.get(cmd);
284
+ if (currentNextFunctions) {
285
+ const index = currentNextFunctions.indexOf(next as HookNextFunction<any, any>);
286
+ if (index !== -1) {
287
+ currentNextFunctions.splice(index, 1);
288
+ }
289
+ if (currentNextFunctions.length === 0) {
290
+ this.nextFunctions.delete(cmd);
291
+ }
292
+ }
293
+ };
294
+ }
295
+
296
+ beforeAsync<T extends CommandType = CommandType>(
297
+ cmd: T,
298
+ next: AsyncHookNextFunction<T, CommandPayload<T>>,
299
+ ): CommandDisposer {
300
+ const asyncNextFunctions = this.asyncNextFunctions.get(cmd) ?? [];
301
+ asyncNextFunctions.push(next as AsyncHookNextFunction<any, any>);
302
+ this.asyncNextFunctions.set(cmd, asyncNextFunctions);
303
+
304
+ return () => {
305
+ const currentAsyncNextFunctions = this.asyncNextFunctions.get(cmd);
306
+ if (currentAsyncNextFunctions) {
307
+ const index = currentAsyncNextFunctions.indexOf(next as AsyncHookNextFunction<any, any>);
308
+ if (index !== -1) {
309
+ currentAsyncNextFunctions.splice(index, 1);
310
+ }
311
+ if (currentAsyncNextFunctions.length === 0) {
312
+ this.asyncNextFunctions.delete(cmd);
313
+ }
314
+ }
315
+ };
316
+ }
317
+
318
+ after<T extends CommandType = CommandType>(cmd: T, callback: AfterHook<T>): CommandDisposer {
319
+ const hooks = this.afterHooks.get(cmd) ?? [];
320
+ hooks.push(callback as AfterHook<any>);
321
+ this.afterHooks.set(cmd, hooks);
322
+
323
+ return () => {
324
+ const currentHooks = this.afterHooks.get(cmd);
325
+ if (!currentHooks) return;
326
+ const index = currentHooks.indexOf(callback as AfterHook<any>);
327
+ if (index !== -1) {
328
+ currentHooks.splice(index, 1);
329
+ }
330
+ if (currentHooks.length === 0) {
331
+ this.afterHooks.delete(cmd);
332
+ }
333
+ };
334
+ }
335
+
336
+ afterAsync<T extends CommandType = CommandType>(
337
+ cmd: T,
338
+ callback: AsyncAfterHook<T>,
339
+ ): CommandDisposer {
340
+ const hooks = this.asyncAfterHooks.get(cmd) ?? [];
341
+ hooks.push(callback as AsyncAfterHook<any>);
342
+ this.asyncAfterHooks.set(cmd, hooks);
343
+
344
+ return () => {
345
+ const currentHooks = this.asyncAfterHooks.get(cmd);
346
+ if (!currentHooks) return;
347
+ const index = currentHooks.indexOf(callback as AsyncAfterHook<any>);
348
+ if (index !== -1) {
349
+ currentHooks.splice(index, 1);
350
+ }
351
+ if (currentHooks.length === 0) {
352
+ this.asyncAfterHooks.delete(cmd);
353
+ }
354
+ };
355
+ }
356
+
357
+ has<T extends CommandType = CommandType>(cmd: T): boolean {
358
+ return this.handlers.has(cmd) || this.asyncHandlers.has(cmd);
359
+ }
360
+ }
@@ -0,0 +1 @@
1
+ export * from "./commandsbus";