@zenflux/commands 0.0.0-stage → 0.0.1

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