@zenflux/react-commander 0.0.11 → 0.0.12

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.
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "$schema": "https://raw.githubusercontent.com/SchemaStore/schemastore/master/src/schemas/json/package.json",
3
3
  "name": "@zenflux/react-commander",
4
4
  "author": "Leonid Vinikov <leonidvinikov@gmail.com> (https://github.com/iNewLegend)",
5
- "version": "0.0.11",
5
+ "version": "0.0.12",
6
6
  "type": "module",
7
7
  "sideEffects": false,
8
8
  "types": "src/index.ts",
@@ -48,15 +48,19 @@
48
48
  "access": "public"
49
49
  },
50
50
  "dependencies": {
51
+ "@zenflux/core": "0.1.29",
51
52
  "eventemitter3": "^5.0.1"
52
53
  },
53
54
  "devDependencies": {
54
55
  "@types/react": "^19.2.0",
55
- "@types/react-dom": "^19.2.0"
56
+ "@types/react-dom": "^19.2.0",
57
+ "react": "^19.2.0",
58
+ "react-dom": "^19.2.0",
59
+ "vite": "^8.2.2"
56
60
  },
57
61
  "peerDependencies": {
58
- "vite": "^5.4.5",
59
62
  "react": "^19.2.0",
60
- "react-dom": "^19.2.0"
63
+ "react-dom": "^19.2.0",
64
+ "vite": "^8.2.2"
61
65
  }
62
66
  }
@@ -8,6 +8,8 @@ import {
8
8
  UNREGISTER_INTERNAL_SYMBOL
9
9
  } from "./constants";
10
10
 
11
+ import { logger } from "./logger";
12
+
11
13
  import { version } from "../../package.json";
12
14
 
13
15
  import type { DCoreContext, DCoreInterface, DCoreRegisterArgs } from "./definitions";
@@ -227,7 +229,7 @@ const core = getOrCreateCore();
227
229
  if ( /* from vite */ import.meta.env.DEV ) {
228
230
  if ( DEBUG_ENABLED ) {
229
231
  core.__devDebug = ( ... args: Parameters<DCoreInterface[ "__devDebug" ]> ) => {
230
- console.log( ... args );
232
+ logger.debug( core.__devDebug, ... args );
231
233
  };
232
234
  }
233
235
 
@@ -1,8 +1,6 @@
1
- import type React from "react";
2
-
3
1
  import { DEBUG_ENABLED } from "./constants";
4
2
 
5
- export { DEBUG_ENABLED };
3
+ import type React from "react";
6
4
 
7
5
  import type {
8
6
  GET_INTERNAL_MATCH_SYMBOL,
@@ -16,6 +14,8 @@ import type { DCommandSingleComponentContext } from "@zenflux/react-commander/de
16
14
 
17
15
  import type EventEmitter from "eventemitter3";
18
16
 
17
+ export { DEBUG_ENABLED };
18
+
19
19
  export type DCoreContext = {
20
20
  [componentNameUnique: string]: DCommandSingleComponentContext;
21
21
  };
@@ -0,0 +1,3 @@
1
+ import { createLogger } from "@zenflux/core/src/modules/logger/create-logger";
2
+
3
+ export const logger = createLogger( "@zenflux/react-commander" );
@@ -1,23 +1,34 @@
1
1
  import EventEmitter from "eventemitter3";
2
2
 
3
+ import { CommandPublic } from "@zenflux/core/src/command-bases/command-public";
4
+
3
5
  import type { DCommandOptions, DCommandArgs, DCommandRegisterArgs } from "@zenflux/react-commander/definitions";
4
6
 
5
7
  import type React from "react";
6
8
 
7
9
  /**
8
10
  * Each created command is registered within the commands manager, and the instance created only once per command.
11
+ *
12
+ * Extends `CommandPublic` from `@zenflux/core` to inherit:
13
+ * - `ObjectBase`: unique id, `getName()`, `getUniqueId()`, `getHierarchyNames()`
14
+ * - `CommandBase`: logger, `onBeforeApply`/`onAfterApply` lifecycle hooks, `run()` method
15
+ * - `CommandPublic`: semantic marker for user-facing commands
9
16
  */
10
- export abstract class CommandBase<TState = React.ComponentState, TArgs = DCommandArgs> {
17
+ export abstract class CommandBase<TState = React.ComponentState, TArgs = DCommandArgs> extends CommandPublic {
11
18
  private static globalEmitter: EventEmitter = new EventEmitter();
12
19
 
13
20
  public readonly commandName: string;
14
21
 
15
- private options: DCommandOptions<TState> = {};
22
+ private reactOptions: DCommandOptions<TState> = {};
16
23
 
17
24
  public static getName(): string {
18
25
  throw new Error( "You have should implement `static getName()` method, since the commands run by name ;)" );
19
26
  }
20
27
 
28
+ public static getSourcePath(): string {
29
+ return "@zenflux/react-commander";
30
+ }
31
+
21
32
  public static globalHook( callback: ( result?: any, args?: DCommandArgs ) => any ) {
22
33
  this.globalEmitter.on( this.getName(), callback );
23
34
  }
@@ -28,7 +39,13 @@ export abstract class CommandBase<TState = React.ComponentState, TArgs = DComman
28
39
  } );
29
40
  }
30
41
 
31
- public constructor( private args: DCommandRegisterArgs ) {
42
+ /**
43
+ * React-commander creates command instances during registration (not per-execution),
44
+ * so we pass empty args/options to core's CommandBase constructor.
45
+ */
46
+ public constructor( private registerArgs: DCommandRegisterArgs ) {
47
+ super( {}, {} );
48
+
32
49
  this.commandName = ( new.target as typeof CommandBase ).getName();
33
50
  }
34
51
 
@@ -44,14 +61,26 @@ export abstract class CommandBase<TState = React.ComponentState, TArgs = DComman
44
61
  };
45
62
  }
46
63
 
64
+ /**
65
+ * React-aware command execution entry point.
66
+ *
67
+ * Integrates core's lifecycle hooks (`onBeforeApply`/`onAfterApply`) while
68
+ * preserving react-commander's event emission and state management.
69
+ */
47
70
  public async execute( emitter: EventEmitter, args: TArgs, options?: DCommandOptions<TState> ): Promise<any> {
48
71
  if ( options ) {
49
- this.options = options;
72
+ this.reactOptions = options;
50
73
  }
51
74
 
52
75
  this.validateArgs?.( args, options );
53
76
 
54
- const result = await this.apply?.( args );
77
+ // Core lifecycle: before
78
+ this.onBeforeApply?.();
79
+
80
+ const result = await this.apply( args as any );
81
+
82
+ // Core lifecycle: after
83
+ this.onAfterApply?.();
55
84
 
56
85
  const listeners = emitter.listeners( this.commandName );
57
86
  for ( const listener of listeners ) {
@@ -63,7 +92,7 @@ export abstract class CommandBase<TState = React.ComponentState, TArgs = DComman
63
92
  await globalListener( result, args );
64
93
  }
65
94
 
66
- this.options = {};
95
+ this.reactOptions = {};
67
96
 
68
97
  return result;
69
98
  }
@@ -72,14 +101,18 @@ export abstract class CommandBase<TState = React.ComponentState, TArgs = DComman
72
101
  protected validateArgs?( args: TArgs, options?: DCommandOptions<TState> ) {
73
102
  }
74
103
 
104
+ /**
105
+ * Override core's `apply()` (which throws `ForceMethodImplementation`) to be
106
+ * optional — react-commander commands may or may not implement apply.
107
+ */
75
108
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
76
- protected apply?( args: TArgs ): Promise<any> | any {
109
+ protected apply( args?: any, _options?: any ): Promise<any> | any {
77
110
  }
78
111
 
79
112
  protected get state(): TState {
80
113
  this.validateState();
81
114
 
82
- return this.options.state;
115
+ return this.reactOptions.state;
83
116
  }
84
117
 
85
118
  protected setState<K extends keyof TState>(
@@ -89,7 +122,7 @@ export abstract class CommandBase<TState = React.ComponentState, TArgs = DComman
89
122
  this.validateState();
90
123
 
91
124
  return new Promise( ( resolve ) => {
92
- this.options.setState!( state, ( currentState: React.ComponentState ) => {
125
+ this.reactOptions.setState!( state, ( currentState: React.ComponentState ) => {
93
126
  callback?.( currentState );
94
127
 
95
128
  resolve( currentState );
@@ -98,9 +131,8 @@ export abstract class CommandBase<TState = React.ComponentState, TArgs = DComman
98
131
  }
99
132
 
100
133
  private validateState() {
101
- if ( "undefined" === typeof this.options.state || "function" !== typeof this.options.setState ) {
134
+ if ( "undefined" === typeof this.reactOptions.state || "function" !== typeof this.reactOptions.setState ) {
102
135
  throw new Error( "There is no state for the current command, you should use `withCommands( component, class, state, commands )` including the state to enable it" );
103
136
  }
104
137
  }
105
138
  }
106
-
@@ -1,9 +1,17 @@
1
1
 
2
+ import { Commands as CoreCommands } from "@zenflux/core/src/managers/commands";
3
+
4
+ import { CommandNotFound } from "@zenflux/core/src/errors/command-not-found";
5
+
2
6
  import { DEBUG_ENABLED, GET_INTERNAL_SYMBOL } from "./_internal/constants";
7
+ import { logger } from "./_internal/logger";
3
8
 
4
9
  import core from "./_internal/core.ts";
5
10
 
11
+ import type { TCommandCallbackType } from "@zenflux/core/src/interfaces";
12
+
6
13
  import type { CommandBase } from "@zenflux/react-commander/command-base";
14
+ import type { CommandBase as CoreCommandBase } from "@zenflux/core/src/command-bases/command-base";
7
15
 
8
16
  import type {
9
17
  DCommandArgs,
@@ -14,7 +22,34 @@ import type {
14
22
  DCommandSingleComponentContext
15
23
  } from "@zenflux/react-commander/definitions";
16
24
 
25
+ /**
26
+ * Adapter that exposes core Commands' protected hook-firing methods.
27
+ */
28
+ class CoreCommandsAdapter extends CoreCommands {
29
+ public static getName() {
30
+ return "@zenflux/react-commander/CoreCommandsAdapter";
31
+ }
32
+
33
+ public static getSourcePath() {
34
+ return "@zenflux/react-commander";
35
+ }
36
+
37
+ public fireBeforeRun( command: CoreCommandBase, args: any = {}, options = {} ) {
38
+ this.onBeforeRun( command, args, options );
39
+ }
40
+
41
+ public async fireAfterRun( command: CoreCommandBase, args: any, options: {}, result: any ) {
42
+ return this.onAfterRun( command, args, options, result );
43
+ }
44
+ }
45
+
17
46
  class CommandsManager {
47
+ /**
48
+ * Core Commands instance providing hook infrastructure
49
+ * (onBefore, onAfter, onAfterUI, onAfterOnce, onAfterAffect).
50
+ */
51
+ private coreCommands = new CoreCommandsAdapter();
52
+
18
53
  private commands: {
19
54
  [ componentName: string ]: {
20
55
  [ commandName: string ]: CommandBase
@@ -62,10 +97,13 @@ class CommandsManager {
62
97
  const command = this.commands[ componentName ]?.[ commandName ];
63
98
 
64
99
  if ( ! command ) {
65
- throw new Error( `Command '${ commandName }' not registered for component '${ componentName }'` );
100
+ throw new CommandNotFound( commandName );
66
101
  }
67
102
 
68
- if ( DEBUG_ENABLED ) console.log( `Commands.run() '${ commandName }' for component '${ componentNameUnique }'`, args );
103
+ if ( DEBUG_ENABLED ) logger.debug( this.run, `Commands.run() '${ commandName }' for component '${ componentNameUnique }'`, args );
104
+
105
+ // Fire core's before-run hooks
106
+ this.coreCommands.fireBeforeRun( command as unknown as CoreCommandBase, args );
69
107
 
70
108
  const singleComponentContext = core[ GET_INTERNAL_SYMBOL ]( componentNameUnique );
71
109
 
@@ -80,6 +118,9 @@ class CommandsManager {
80
118
  executionResult = await command.execute( singleComponentContext.emitter, args );
81
119
  }
82
120
 
121
+ // Fire core's after-run hooks
122
+ await this.coreCommands.fireAfterRun( command as unknown as CoreCommandBase, args, {}, executionResult );
123
+
83
124
  if ( callback ) {
84
125
  callback( executionResult );
85
126
  }
@@ -113,7 +154,7 @@ class CommandsManager {
113
154
 
114
155
  // Check if id exist within the component context
115
156
  if ( ! singleComponentContext.commands[ commandName ] ) {
116
- throw new Error( `Command '${ commandName }' not registered for component '${ componentNameUnique }'` );
157
+ throw new CommandNotFound( commandName );
117
158
  }
118
159
 
119
160
  const listeners = singleComponentContext.emitter.listeners( commandName );
@@ -121,7 +162,7 @@ class CommandsManager {
121
162
  if ( ! options?.__ignoreDuplicatedHookError ) {
122
163
  // Check if the same callback is already registered
123
164
  if ( listeners.length > 0 && listeners.find( l => l.name === callback.name ) ) {
124
- console.warn(
165
+ logger.warn( this.hook,
125
166
  `Probably duplicated hook in '${ commandName }'\n` +
126
167
  `callback '${ callback.name }()' already hooked for component '${ componentNameUnique }'` +
127
168
  "The hook will be ignored, to avoid this error bound the callback or pass options: { __ignoreDuplicatedHookError: true }"
@@ -153,7 +194,7 @@ class CommandsManager {
153
194
  const singleComponentContext = core[ GET_INTERNAL_SYMBOL ]( componentNameUnique ) as DCommandSingleComponentContext;
154
195
 
155
196
  if ( ! singleComponentContext.commands[ commandName ] ) {
156
- throw new Error( `Command '${ commandName }' not registered for component '${ componentNameUnique }'` );
197
+ throw new CommandNotFound( commandName );
157
198
  }
158
199
  const wrapped = ( result?: any, args?: DCommandArgs ) => callback( result, args );
159
200
  singleComponentContext.emitter.on( commandName, wrapped );
@@ -191,7 +232,7 @@ class CommandsManager {
191
232
 
192
233
  // Check if id exist within the component context
193
234
  if ( ! singleComponentContext.commands[ commandName ] ) {
194
- throw new Error( `Command '${ commandName }' not registered for component '${ componentNameUnique }'` );
235
+ throw new CommandNotFound( commandName );
195
236
  }
196
237
 
197
238
  singleComponentContext.emitter.removeAllListeners( commandName );
@@ -265,7 +306,7 @@ class CommandsManager {
265
306
  const contexts = core.__devGetContextValues?.() || [];
266
307
  const matches = contexts.filter( c => c.componentName === componentName && !!c.commands[ commandName ] );
267
308
  const ctx = matches[ index ];
268
- if ( ! ctx ) throw new Error( `Command '${ commandName }' for component '${ componentName }' not found` );
309
+ if ( ! ctx ) throw new CommandNotFound( commandName );
269
310
  return { commandName, componentName, componentNameUnique: ctx.componentNameUnique };
270
311
  }
271
312
 
@@ -283,6 +324,50 @@ class CommandsManager {
283
324
  return !! core[ GET_INTERNAL_SYMBOL ]( componentNameUnique, true );
284
325
  }
285
326
 
327
+ // --- Core Commands hook API delegation ---
328
+
329
+ /**
330
+ * Register a data-only before hook for a command.
331
+ */
332
+ public onBefore( hookCommand: string, callback: TCommandCallbackType ) {
333
+ this.coreCommands.onBefore( hookCommand, callback );
334
+ }
335
+
336
+ /**
337
+ * Register a UI-only before hook for a command.
338
+ */
339
+ public onBeforeUI( hookCommand: string, callback: TCommandCallbackType ) {
340
+ this.coreCommands.onBeforeUI( hookCommand, callback );
341
+ }
342
+
343
+ /**
344
+ * Register a data-only after hook for a command.
345
+ */
346
+ public onAfter( hookCommand: string, callback: TCommandCallbackType ) {
347
+ this.coreCommands.onAfter( hookCommand, callback );
348
+ }
349
+
350
+ /**
351
+ * Register a UI-only after hook for a command.
352
+ */
353
+ public onAfterUI( command: string, callback: TCommandCallbackType ) {
354
+ this.coreCommands.onAfterUI( command, callback );
355
+ }
356
+
357
+ /**
358
+ * Register a one-time after hook for a command.
359
+ */
360
+ public onAfterOnce( command: string, callback: TCommandCallbackType ) {
361
+ this.coreCommands.onAfterOnce( command, callback );
362
+ }
363
+
364
+ /**
365
+ * Register a trigger that runs a command after another command runs.
366
+ */
367
+ public onAfterAffect( hookCommand: string, affectCommand: string ) {
368
+ this.coreCommands.onAfterAffect( hookCommand, affectCommand );
369
+ }
370
+
286
371
  public devShowComponents() {
287
372
  console.group( "🔧 CommandsManager Dev Info" );
288
373
 
@@ -20,7 +20,7 @@ export function queryCreateAutoSaveManager<TState extends object, TSave extends
20
20
  const debounceMs = options.debounceMs ?? 800;
21
21
  const intervalMs = options.intervalMs ?? 5000;
22
22
 
23
- const queryFlush = async () => {
23
+ const queryFlush = async() => {
24
24
  const entries = Array.from( pending.values() );
25
25
  if ( ! entries.length ) return;
26
26
  pending.clear();
@@ -39,7 +39,7 @@ export function queryCreateAutoSaveManager<TState extends object, TSave extends
39
39
  return schedule( Boolean( immediate ) );
40
40
  };
41
41
 
42
- const queryFlushKey = async ( key: string ) => {
42
+ const queryFlushKey = async( key: string ) => {
43
43
  const s = pending.get( key );
44
44
  if ( ! s ) return;
45
45
  pending.delete( key );
@@ -77,7 +77,7 @@ export function queryCreateMemoryCache(): QueryCache {
77
77
  return get<T>( queryKey );
78
78
  };
79
79
 
80
- const invalidateQueries = async ( options: { queryKey: QueryCacheKey } ): Promise<void> => {
80
+ const invalidateQueries = async( options: { queryKey: QueryCacheKey } ): Promise<void> => {
81
81
  const prefix = serializeKey( options.queryKey );
82
82
  for ( const key of Array.from( data.keys() ) ) {
83
83
  if ( keyStartsWith( key, prefix ) ) {
@@ -47,7 +47,7 @@ export class QueryComponent<
47
47
 
48
48
  public render() {
49
49
  // The resource will start loading
50
- const resource = wrapPromiseSuspendable( ( async () => {
50
+ const resource = wrapPromiseSuspendable( ( async() => {
51
51
  const data = await this.queryModule.getData<TData, TProps & { $data: TData }, TState>( this.props.component, this.props.props as Record<string, unknown> );
52
52
 
53
53
  return {
@@ -1,3 +1,5 @@
1
+ import { logger } from "../_internal/logger";
2
+
1
3
  import { DEBUG_ENABLED } from "@zenflux/react-commander/constants";
2
4
  import { QueryRouterBase } from "@zenflux/react-commander/query/router";
3
5
 
@@ -131,7 +133,7 @@ export abstract class QueryModuleBase<TResource extends object = object> {
131
133
  throw new Error( `Cannot find route for ${ name }` );
132
134
  }
133
135
 
134
- if ( DEBUG_ENABLED ) console.log( "request", { name, args, found: { method: found.method, path: found.route.path } } );
136
+ if ( DEBUG_ENABLED ) logger.debug( this.request, "request", { name, args, found: { method: found.method, path: found.route.path } } );
135
137
  const payload = args ?? {};
136
138
 
137
139
  const result = await this.api.fetch( found.method!, found.route.path, payload, async( response ) => {
@@ -141,7 +143,7 @@ export abstract class QueryModuleBase<TResource extends object = object> {
141
143
  return await response.json();
142
144
  } );
143
145
 
144
- if ( DEBUG_ENABLED ) console.log( "request result", { name, result } );
146
+ if ( DEBUG_ENABLED ) logger.debug( this.request, "request result", { name, result } );
145
147
  return result as TResult;
146
148
  }
147
149
 
@@ -18,19 +18,19 @@ export abstract class QueryRouterBase<Resource, Model extends QueryModel = Query
18
18
  this.model = model;
19
19
  }
20
20
 
21
- protected fetchList = async (): Promise<Resource[]> => {
21
+ protected fetchList = async(): Promise<Resource[]> => {
22
22
  return this.api.fetch( "GET", `v1/${ this.resource }`, {}, ( r ) => r.json() ) as Promise<Resource[]>;
23
23
  };
24
24
 
25
- protected fetchItem = async ( key: string ): Promise<Resource> => {
25
+ protected fetchItem = async( key: string ): Promise<Resource> => {
26
26
  return this.api.fetch( "GET", `v1/${ this.resource }/:key`, { key }, ( r ) => r.json() ) as Promise<Resource>;
27
27
  };
28
28
 
29
- protected saveItem = async ( input: Resource & { key: string } ): Promise<void> => {
29
+ protected saveItem = async( input: Resource & { key: string } ): Promise<void> => {
30
30
  await this.api.fetch( "POST", `v1/${ this.resource }/:key`, input as unknown as Record<string, unknown>, ( r ) => r.json() );
31
31
  };
32
32
 
33
- protected deleteItem = async ( key: string ): Promise<void> => {
33
+ protected deleteItem = async( key: string ): Promise<void> => {
34
34
  await this.api.fetch( "DELETE", `v1/${ this.resource }/${ key }`, {}, ( r ) => r.json() );
35
35
  };
36
36
 
@@ -128,7 +128,7 @@ export function withCommands(
128
128
  originalName = Component.displayName || Component.name || "Component";
129
129
 
130
130
  // This approach give us ability to inject second argument to the functional component.
131
- Component = function ( props: any ) {
131
+ Component = function( props: any ) {
132
132
  return originalFunction( props, state );
133
133
  };
134
134