@zenflux/commands 0.0.0-stage → 0.0.2

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 (43) hide show
  1. package/LICENSE +674 -0
  2. package/package.json +25 -3
  3. package/readme.md +42 -0
  4. package/src/api.ts +166 -0
  5. package/src/core/commands-internal.ts +15 -0
  6. package/src/core/commands.ts +684 -0
  7. package/src/core/components.ts +107 -0
  8. package/src/core/hooks/base.ts +451 -0
  9. package/src/core/hooks/data.ts +58 -0
  10. package/src/core/hooks/ui.ts +44 -0
  11. package/src/core/hooks.ts +267 -0
  12. package/src/core/routes.ts +247 -0
  13. package/src/core/shortcuts.ts +358 -0
  14. package/src/core/store.ts +155 -0
  15. package/src/env.d.ts +15 -0
  16. package/src/extras/dev-tools.ts +443 -0
  17. package/src/index.ts +83 -0
  18. package/src/instance.ts +30 -0
  19. package/src/modules/args-object.ts +113 -0
  20. package/src/modules/command-base.ts +51 -0
  21. package/src/modules/command-callback-base.ts +42 -0
  22. package/src/modules/command-infra.ts +230 -0
  23. package/src/modules/command-internal-base.ts +19 -0
  24. package/src/modules/component-base.ts +483 -0
  25. package/src/modules/hook-base.ts +158 -0
  26. package/src/modules/hook-break.ts +8 -0
  27. package/src/modules/hooks/data/after.ts +19 -0
  28. package/src/modules/hooks/data/base.ts +15 -0
  29. package/src/modules/hooks/data/catch.ts +16 -0
  30. package/src/modules/hooks/data/dependency.ts +16 -0
  31. package/src/modules/hooks/data/index.ts +6 -0
  32. package/src/modules/hooks/ui/after.ts +18 -0
  33. package/src/modules/hooks/ui/base.ts +15 -0
  34. package/src/modules/hooks/ui/before.ts +16 -0
  35. package/src/modules/hooks/ui/catch.ts +16 -0
  36. package/src/modules/hooks/ui/index.ts +6 -0
  37. package/src/modules/instance-type.ts +119 -0
  38. package/src/modules/module.ts +224 -0
  39. package/src/types.ts +194 -0
  40. package/src/utils/instances-slice.ts +123 -0
  41. package/src/utils/object.ts +162 -0
  42. package/src/utils/value-store.ts +145 -0
  43. package/README.md +0 -3
@@ -0,0 +1,107 @@
1
+ import Module from "@zenflux/commands/src/modules/module";
2
+
3
+ import type ComponentBase from "@zenflux/commands/src/modules/component-base";
4
+ import type { ComponentName, ComponentRegistry } from "@zenflux/commands/src/types";
5
+
6
+ /**
7
+ * @param registered A component registered before.
8
+ * @param component One to register.
9
+ *
10
+ * @return whether the registered component is of the same class
11
+ */
12
+ const isOfSameClass = <TComponent extends ComponentBase>( registered: ComponentBase, component: TComponent ): registered is TComponent =>
13
+ registered.constructor === component.constructor;
14
+
15
+ export default class Components extends Module {
16
+ public static getName(): string {
17
+ return "ZenFlux/Commands/Core/Components";
18
+ }
19
+
20
+ public components: { [ namespace: string ]: ComponentBase | undefined };
21
+ public activeComponents: { [ namespace: string ]: true };
22
+
23
+ public constructor( args?: object ) {
24
+ super( args );
25
+
26
+ this.components = {};
27
+ this.activeComponents = {};
28
+ }
29
+
30
+ public getAll(): string[] {
31
+ return Object.keys( this.components ).sort();
32
+ }
33
+
34
+ /**
35
+ * Register a component and its API (commands, routes, hooks...), once per namespace.
36
+ *
37
+ * @param component
38
+ *
39
+ * @throws {Error} when another class's component has the namespace
40
+ *
41
+ * @return the namespace's component: the one registered before, of the same class, if there is one
42
+ */
43
+ public register<TComponent extends ComponentBase>( component: TComponent ): TComponent {
44
+ const namespace = component.getNamespace(),
45
+ registered = this.components[ namespace ];
46
+
47
+ if ( registered ) {
48
+ if ( ! isOfSameClass( registered, component ) ) {
49
+ throw Error( `Components: '${ namespace }' is registered already, by another class.` );
50
+ }
51
+
52
+ return registered;
53
+ }
54
+
55
+ component.registerAPI();
56
+
57
+ this.components[ namespace ] = component;
58
+
59
+ return component;
60
+ }
61
+
62
+ /**
63
+ * @param id A namespace in the app's ComponentRegistry.
64
+ *
65
+ * @throws {Error} when no component has the namespace
66
+ *
67
+ * @return its component
68
+ */
69
+ public get<TName extends ComponentName>( id: TName ): ComponentRegistry[ TName ] {
70
+ const component = this.components[ id ];
71
+
72
+ if ( ! component ) {
73
+ throw Error( `Components: '${ id }' is not registered.` );
74
+ }
75
+
76
+ // The component registered under the namespace: of the class the registry names for it, which TS can't check
77
+ // at runtime (the registry is types only).
78
+ return component as ComponentRegistry[ TName ];
79
+ }
80
+
81
+ /**
82
+ * @param namespace A namespace known at runtime.
83
+ *
84
+ * @return its component, if one is registered
85
+ */
86
+ public getByNamespace( namespace: string ): ComponentBase | undefined {
87
+ return this.components[ namespace ];
88
+ }
89
+
90
+ public getActive(): { [ namespace: string ]: true } {
91
+ return this.activeComponents;
92
+ }
93
+
94
+ public activate( namespace: string ): void {
95
+ // Add as last.
96
+ this.inactivate( namespace );
97
+ this.activeComponents[ namespace ] = true;
98
+ }
99
+
100
+ public inactivate( namespace: string ): void {
101
+ delete this.activeComponents[ namespace ];
102
+ }
103
+
104
+ public isActive( namespace: string ): boolean {
105
+ return !! this.activeComponents[ namespace ];
106
+ }
107
+ }
@@ -0,0 +1,451 @@
1
+ import { InitializeBase } from "@zenflux/core/src/bases/initialize-base";
2
+
3
+ import HookBreak from "@zenflux/commands/src/modules/hook-break";
4
+ import { $e } from "@zenflux/commands/src/instance";
5
+
6
+ import type { HookType, RunnableHook } from "@zenflux/commands/src/modules/hook-base";
7
+ import type { CommandArgs, HookReturn } from "@zenflux/commands/src/types";
8
+
9
+ /**
10
+ * A hook's `run()`, as the hooks keep it: with its command's args, and the value its event gives (the command's result
11
+ * after it, the error it failed with).
12
+ */
13
+ export type HookRunner = <TValue>( args: CommandArgs, value?: TValue ) => HookReturn;
14
+
15
+ export interface HookCallback {
16
+ id: string;
17
+
18
+ /**
19
+ * The hook's `run()`.
20
+ */
21
+ callback: HookRunner;
22
+ isActive: boolean;
23
+ activate(): void;
24
+ deactivate(): void;
25
+ }
26
+
27
+ /**
28
+ * A command's callbacks of an event, by container type ('all' for any).
29
+ */
30
+ export interface HookCallbacksByContainer {
31
+ [ containerType: string ]: HookCallback[];
32
+ }
33
+
34
+ /**
35
+ * Every callback, by id.
36
+ */
37
+ export interface HookCallbacksById {
38
+ [ id: string ]: HookCallback;
39
+ }
40
+
41
+ /**
42
+ * Every callback, by event, then command.
43
+ */
44
+ export interface HookCallbacksByEvent {
45
+ [ event: string ]: { command: string; callbacks: HookCallbacksByContainer }[];
46
+ }
47
+
48
+ /**
49
+ * The hooks of one type (data or UI): callbacks by event, then command, then container type ('all' for any).
50
+ */
51
+ export default class HooksBase extends InitializeBase {
52
+ public static getName(): string {
53
+ return "ZenFlux/Commands/Core/Hooks/HooksBase";
54
+ }
55
+
56
+ /**
57
+ * Current command.
58
+ */
59
+ public current: string;
60
+
61
+ /**
62
+ * Array of ids which in use.
63
+ */
64
+ public usedIds: string[];
65
+
66
+ /**
67
+ * Object of callbacks that was bound by container type.
68
+ */
69
+ public callbacks: { [ event: string ]: { [ command: string ]: HookCallbacksByContainer } };
70
+
71
+ /**
72
+ * Object of depth.
73
+ */
74
+ public depth: { [ event: string ]: { [ id: string ]: number } };
75
+
76
+ public callbacksFlatList: HookCallbacksById;
77
+
78
+ public constructor() {
79
+ super();
80
+
81
+ this.current = "";
82
+
83
+ this.usedIds = [];
84
+
85
+ this.callbacks = {
86
+ after: {},
87
+ catch: {},
88
+ };
89
+
90
+ this.depth = {
91
+ after: {},
92
+ catch: {},
93
+ };
94
+
95
+ this.callbacksFlatList = {};
96
+ }
97
+
98
+ public activate(): void {
99
+ Object.values( this.getAll( true ) ).forEach( ( callback ) => {
100
+ callback.activate();
101
+ } );
102
+ }
103
+
104
+ public deactivate(): void {
105
+ Object.values( this.getAll( true ) ).forEach( ( callback ) => {
106
+ callback.deactivate();
107
+ } );
108
+ }
109
+
110
+ /**
111
+ * Returns type eg: ( data, ui ).
112
+ *
113
+ * @return type
114
+ */
115
+ public getType(): HookType | "" {
116
+ return "";
117
+ }
118
+
119
+ public get( id: string ): HookCallback | undefined {
120
+ return this.callbacksFlatList[ id ];
121
+ }
122
+
123
+ /**
124
+ * Return all possible callbacks.
125
+ *
126
+ * @param flat By id.
127
+ *
128
+ * @return all callbacks
129
+ */
130
+ public getAll( flat: true ): HookCallbacksById;
131
+ public getAll( flat?: false ): HookCallbacksByEvent;
132
+ public getAll( flat?: boolean ): HookCallbacksById | HookCallbacksByEvent;
133
+ public getAll( flat = false ): HookCallbacksById | HookCallbacksByEvent {
134
+ if ( flat ) {
135
+ return this.callbacksFlatList;
136
+ }
137
+
138
+ const result: HookCallbacksByEvent = {};
139
+
140
+ Object.keys( this.callbacks ).forEach( ( event ) => {
141
+ const list = result[ event ] || [];
142
+
143
+ result[ event ] = list;
144
+
145
+ Object.keys( this.callbacks[ event ] ).forEach( ( command ) => {
146
+ list.push( {
147
+ command,
148
+ callbacks: this.callbacks[ event ][ command ],
149
+ } );
150
+ } );
151
+ } );
152
+
153
+ return result;
154
+ }
155
+
156
+ /**
157
+ * Return current command.
158
+ *
159
+ * @return current command
160
+ */
161
+ public getCurrent(): string {
162
+ return this.current;
163
+ }
164
+
165
+ /**
166
+ * Returns the current used ids.
167
+ *
168
+ * @return used IDs
169
+ */
170
+ public getUsedIds(): string[] {
171
+ return this.usedIds;
172
+ }
173
+
174
+ /**
175
+ * Get available callbacks for specific event and command.
176
+ *
177
+ * @param event
178
+ * @param command
179
+ * @param args
180
+ *
181
+ * @return callbacks
182
+ */
183
+ public getCallbacks( event: string, command: string, args: CommandArgs ): HookCallback[] | false {
184
+ // Most runs: no hook on the command, nothing to build.
185
+ const byContainer = this.callbacks[ event ]?.[ command ];
186
+
187
+ if ( ! byContainer ) {
188
+ return false;
189
+ }
190
+
191
+ const first = args.containers ? args.containers[ 0 ] : args.container,
192
+ ofType = first?.type ? byContainer[ first.type ] : undefined,
193
+ all = byContainer.all;
194
+
195
+ // A list of their own, as a hook may add or take back another while they run.
196
+ if ( ofType?.length ) {
197
+ return all?.length ? ofType.concat( all ) : ofType.slice();
198
+ }
199
+
200
+ return all?.length ? all.slice() : false;
201
+ }
202
+
203
+ /**
204
+ * Validate if the event is available.
205
+ *
206
+ * @param event
207
+ */
208
+ public checkEvent( event: string ): void {
209
+ if ( ! Object.keys( this.callbacks ).includes( event ) ) {
210
+ throw Error( `${ this.getType() }: '${ event }' is not available.` );
211
+ }
212
+ }
213
+
214
+ /**
215
+ * Validate given instance.
216
+ *
217
+ * @param instance
218
+ */
219
+ public checkInstance( instance: RunnableHook ): void {
220
+ if ( instance.getType() !== this.getType() ) {
221
+ throw new Error( `invalid instance, please use a '${ this.getType() }' hook.` );
222
+ }
223
+ }
224
+
225
+ /**
226
+ * Validate if the id is not used before.
227
+ *
228
+ * @param id
229
+ */
230
+ public checkId( id: string ): void {
231
+ if ( this.usedIds.includes( id ) ) {
232
+ throw Error( `id: '${ id }' is already in use.` );
233
+ }
234
+ }
235
+
236
+ /**
237
+ * Determine if the event should run.
238
+ *
239
+ * @param callbacks
240
+ *
241
+ * @return true if there are callbacks, otherwise false
242
+ */
243
+ public shouldRun( callbacks: HookCallback[] | false ): callbacks is HookCallback[] {
244
+ return !! callbacks && !! callbacks.length;
245
+ }
246
+
247
+ /**
248
+ * Register the callback instance.
249
+ *
250
+ * @param event
251
+ * @param instance
252
+ *
253
+ * @return Created callback
254
+ */
255
+ public register( event: string, instance: RunnableHook ): HookCallback {
256
+ const command = instance.getCommand(),
257
+ id = instance.getId(),
258
+ containerType = instance.getContainerType();
259
+
260
+ this.checkEvent( event );
261
+ this.checkInstance( instance );
262
+ this.checkId( id );
263
+
264
+ return this.registerCallback( id, event, command, instance, containerType );
265
+ }
266
+
267
+ /**
268
+ * Take a callback back, by its id: one registered for a while (a React hook's, as its component unmounts), whose id
269
+ * may then be used again.
270
+ *
271
+ * @param id
272
+ */
273
+ public unregister( id: string ): void {
274
+ Object.values( this.callbacks ).forEach( ( byCommand ) => Object.values( byCommand ).forEach( ( buckets ) => {
275
+ Object.keys( buckets ).forEach( ( bucket ) => {
276
+ buckets[ bucket ] = buckets[ bucket ].filter( ( callback ) => id !== callback.id );
277
+ } );
278
+ } ) );
279
+
280
+ delete this.callbacksFlatList[ id ];
281
+
282
+ this.usedIds = this.usedIds.filter( ( usedId ) => id !== usedId );
283
+ }
284
+
285
+ /**
286
+ * Register callback.
287
+ *
288
+ * @param id
289
+ * @param event
290
+ * @param command
291
+ * @param instance
292
+ * @param containerType
293
+ *
294
+ * @return callback
295
+ */
296
+ public registerCallback( id: string, event: string, command: string, instance: RunnableHook, containerType?: string ): HookCallback {
297
+ if ( ! this.callbacks[ event ][ command ] ) {
298
+ this.callbacks[ event ][ command ] = {};
299
+ }
300
+
301
+ // Save used id(s).
302
+ this.usedIds.push( id );
303
+
304
+ const callback: HookCallback = {
305
+ id,
306
+ // The hook takes the args and value of the command it hooks (its HookArgs, its result or error), which
307
+ // it runs with: TS can't follow them to it through the command's name.
308
+ callback: instance.run.bind( instance ) as HookRunner,
309
+ isActive: true,
310
+
311
+ activate() {
312
+ this.isActive = true;
313
+ },
314
+ deactivate() {
315
+ this.isActive = false;
316
+ },
317
+ };
318
+
319
+ const bucket = containerType || "all",
320
+ buckets = this.callbacks[ event ][ command ],
321
+ list = buckets[ bucket ] || [];
322
+
323
+ buckets[ bucket ] = list;
324
+
325
+ list.push( callback );
326
+
327
+ this.callbacksFlatList[ callback.id ] = callback;
328
+
329
+ return callback;
330
+ }
331
+
332
+ /**
333
+ * Run the callbacks.
334
+ *
335
+ * @param event
336
+ * @param command
337
+ * @param args
338
+ * @param result
339
+ *
340
+ * @return results
341
+ */
342
+ public run<TValue>( event: string, command: string, args: CommandArgs, result?: TValue ): HookReturn[] | false {
343
+ const callbacks = this.getCallbacks( event, command, args );
344
+
345
+ if ( this.shouldRun( callbacks ) ) {
346
+ this.current = command;
347
+
348
+ this.onRun( command, args, event );
349
+
350
+ return this.runCallbacks( event, command, callbacks, args, result );
351
+ }
352
+
353
+ return false;
354
+ }
355
+
356
+ /**
357
+ * Run's the given callbacks.
358
+ *
359
+ * @param event
360
+ * @param command
361
+ * @param callbacks
362
+ * @param args
363
+ * @param result
364
+ *
365
+ * @return callbacks results
366
+ */
367
+ public runCallbacks<TValue>( event: string, command: string, callbacks: HookCallback[], args: CommandArgs, result?: TValue ): HookReturn[] {
368
+ const callbacksResult: HookReturn[] = [],
369
+ depth = this.depth[ event ];
370
+
371
+ for ( const callback of callbacks ) {
372
+ if ( ! callback.isActive ) {
373
+ continue;
374
+ }
375
+
376
+ // If not exist, set zero.
377
+ if ( undefined === depth[ callback.id ] ) {
378
+ depth[ callback.id ] = 0;
379
+ }
380
+
381
+ depth[ callback.id ]++;
382
+
383
+ // Prevent recursive hooks.
384
+ if ( 1 === depth[ callback.id ] ) {
385
+ this.onCallback( command, args, event, callback.id );
386
+
387
+ try {
388
+ const callbackResult = this.runCallback( event, callback, args, result );
389
+
390
+ if ( ! callbackResult ) {
391
+ throw Error( `Callback failed, event: '${ event }'` );
392
+ }
393
+
394
+ callbacksResult.push( callbackResult );
395
+ } catch( e ) {
396
+ // If its 'Hook-Break' then parent `try {}` will handle it.
397
+ if ( e instanceof HookBreak ) {
398
+ throw e;
399
+ }
400
+
401
+ this.logger.error( this.run, `'${ event }' callback '${ callback.id }' failed:`, e );
402
+ }
403
+ }
404
+
405
+ depth[ callback.id ]--;
406
+ }
407
+
408
+ return callbacksResult;
409
+ }
410
+
411
+ /**
412
+ * Run's the given callback.
413
+ *
414
+ * @param event
415
+ * @param callback
416
+ * @param args
417
+ * @param result
418
+ *
419
+ * @return results
420
+ */
421
+ public runCallback<TValue>( _event: string, _callback: HookCallback, _args: CommandArgs, _result?: TValue ): HookReturn {
422
+ return false;
423
+ }
424
+
425
+ /**
426
+ * Called before run a set of callbacks.
427
+ *
428
+ * @param command
429
+ * @param args
430
+ * @param event
431
+ */
432
+ public onRun( command: string, args: CommandArgs, event: string ): void {
433
+ if ( $e.devTools ) {
434
+ $e.devTools.log.callbacks().run( this.getType(), command, args, event );
435
+ }
436
+ }
437
+
438
+ /**
439
+ * Called before a single callback.
440
+ *
441
+ * @param command
442
+ * @param args
443
+ * @param event
444
+ * @param id
445
+ */
446
+ public onCallback( command: string, args: CommandArgs, event: string, id: string ): void {
447
+ if ( $e.devTools ) {
448
+ $e.devTools.log.callbacks().callback( this.getType(), command, args, event, id );
449
+ }
450
+ }
451
+ }
@@ -0,0 +1,58 @@
1
+ import HooksBase from "./base";
2
+
3
+ import HookBreak from "@zenflux/commands/src/modules/hook-break";
4
+
5
+ import type { HookCallback } from "./base";
6
+
7
+ import type { HookType } from "@zenflux/commands/src/modules/hook-base";
8
+ import type { CommandArgs, HookReturn } from "@zenflux/commands/src/types";
9
+
10
+ /**
11
+ * Data hooks: 'dependency' before the command applies (false stops it), 'after' it applied (an async command waits
12
+ * for their promises), 'catch' when it failed.
13
+ */
14
+ export default class Data extends HooksBase {
15
+ public static getName(): string {
16
+ return "ZenFlux/Commands/Core/Hooks/Data";
17
+ }
18
+
19
+ public constructor() {
20
+ super();
21
+
22
+ this.callbacks.dependency = {};
23
+
24
+ this.depth.dependency = {};
25
+ }
26
+
27
+ public getType(): HookType {
28
+ return "data";
29
+ }
30
+
31
+ public runCallback<TValue>( event: string, callback: HookCallback, args: CommandArgs, result?: TValue ): HookReturn {
32
+ switch ( event ) {
33
+ case "dependency": {
34
+ // If callback returns false and its dependency, then 'Hook-Break'.
35
+ if ( ! callback.callback( args ) ) {
36
+ this.depth[ event ][ callback.id ]--;
37
+
38
+ // Throw custom break to be catch by the base for 'Safe' exit.
39
+ throw new HookBreak();
40
+ }
41
+
42
+ return true;
43
+ }
44
+
45
+ case "catch":
46
+ case "after": {
47
+ /**
48
+ * When handling HOOK which is data after (not breakable),
49
+ * even the result of the callback is negative, it is required to return positive,
50
+ * since result of runCallback determine if the callback succeeded.
51
+ */
52
+ return callback.callback( args, result ) || "after" === event;
53
+ }
54
+ }
55
+
56
+ return false;
57
+ }
58
+ }
@@ -0,0 +1,44 @@
1
+ import HooksBase from "./base";
2
+
3
+ import type { HookCallback } from "./base";
4
+ import type { HookType } from "@zenflux/commands/src/modules/hook-base";
5
+ import type { CommandArgs, HookReturn } from "@zenflux/commands/src/types";
6
+
7
+ /**
8
+ * UI hooks: 'before' the command runs, 'after' it ran, 'catch' when it failed.
9
+ */
10
+ export default class Ui extends HooksBase {
11
+ public static getName(): string {
12
+ return "ZenFlux/Commands/Core/Hooks/UI";
13
+ }
14
+
15
+ public constructor() {
16
+ super();
17
+
18
+ this.callbacks.before = {};
19
+
20
+ this.depth.before = {};
21
+ }
22
+
23
+ public getType(): HookType {
24
+ return "ui";
25
+ }
26
+
27
+ public runCallback<TValue>( event: string, callback: HookCallback, args: CommandArgs, result?: TValue ): HookReturn {
28
+ switch ( event ) {
29
+ case "before":
30
+ callback.callback( args );
31
+ break;
32
+
33
+ case "catch":
34
+ case "after":
35
+ callback.callback( args, result );
36
+ break;
37
+
38
+ default:
39
+ return false;
40
+ }
41
+
42
+ return true;
43
+ }
44
+ }