@andrew_l/app 0.3.8 → 0.4.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.
package/dist/index.d.mts CHANGED
@@ -1,21 +1,25 @@
1
- import { IfAny, Data, Logger, AnyFunction, Awaitable, SimpleEventEmitter, ExecResult, LogLevel, Scheduler, AsyncIterableQueue, ResourcePool, CancellablePromise } from '@andrew_l/toolkit';
2
- import * as cp from 'node:child_process';
3
- import { EventEmitter } from 'node:events';
4
-
1
+ import { AnyFunction, AsyncIterableQueue, Awaitable, CancellablePromise, Data, ExecResult, LogLevel, Logger, ResourcePool, Scheduler, SimpleEventEmitter } from "@andrew_l/toolkit";
2
+ import * as cp from "node:child_process";
3
+ import { EventEmitter } from "node:events";
4
+ import { Option } from "commander";
5
5
  /**
6
6
  * Declaration for a single typed app prop.
7
7
  * @group Types
8
8
  */
9
9
  interface PropOptions<T = any> {
10
- type: PropType<T> | null;
11
- description?: string;
12
- alias?: string;
13
- required?: boolean;
14
- env?: string | string[];
15
- default?: () => InferPropType<T>;
16
- parser?: (value: string) => InferPropType<T>;
17
- enum?: string[];
10
+ type: PropType<T> | null;
11
+ description?: string;
12
+ alias?: string;
13
+ required?: boolean;
14
+ env?: string | string[];
15
+ default?: () => InferPropType<T>;
16
+ parser?: (value: string) => InferPropType<T>;
17
+ enum?: string[];
18
18
  }
19
+ /**
20
+ * @group Types
21
+ */
22
+ type Prop<T> = PropOptions<T> | PropType<T>;
19
23
  /**
20
24
  * @group Types
21
25
  */
@@ -24,146 +28,129 @@ type PropType<T> = PropConstructor<T> | PropConstructor<T>[];
24
28
  * Map of prop declarations keyed by name — passed as `props` in `defineApp`.
25
29
  * @group Types
26
30
  */
27
- type ObjectPropsOptions<P = Data> = {
28
- [K in keyof P]: PropOptions<P[K]>;
29
- };
31
+ type ObjectPropsOptions<P = Data> = { [K in keyof P]: PropOptions<P[K]> };
30
32
  type PropConstructor<T = any> = {
31
- new (...args: any[]): T & {};
33
+ new (...args: any[]): T & {};
32
34
  } | {
33
- (): T;
35
+ (): T;
34
36
  } | PropMethod<T>;
35
- type PropMethod<T, TConstructor = any> = [T] extends [
36
- ((...args: any) => any) | undefined
37
- ] ? {
38
- new (): TConstructor;
39
- (): T;
40
- readonly prototype: TConstructor;
37
+ type PropMethod<T, TConstructor = any> = [T] extends [((...args: any) => any) | undefined] ? {
38
+ new (): TConstructor;
39
+ (): T;
40
+ readonly prototype: TConstructor;
41
41
  } : never;
42
42
  type OptionalKeys<T> = Exclude<keyof T, RequiredKeys<T>>;
43
- type RequiredKeys<T> = {
44
- [K in keyof T]: T[K] extends {
45
- required: true;
46
- } ? K : never;
47
- }[keyof T];
48
- type InferPropType<T> = [T] extends [null] ? any : [T] extends [{
49
- type: null;
43
+ type RequiredKeys<T> = { [K in keyof T]: T[K] extends {
44
+ required: true;
45
+ } ? K : never }[keyof T];
46
+ type InferPropType<T, NullAsAny = true> = [T] extends [null] ? NullAsAny extends true ? any : null : [T] extends [{
47
+ type: null | true;
50
48
  }] ? any : [T] extends [ObjectConstructor | {
51
- type: ObjectConstructor;
49
+ type: ObjectConstructor;
52
50
  }] ? Record<string, any> : [T] extends [BooleanConstructor | {
53
- type: BooleanConstructor;
51
+ type: BooleanConstructor;
54
52
  }] ? boolean : [T] extends [DateConstructor | {
55
- type: DateConstructor;
56
- }] ? Date : [T] extends [DateConstructor | {
57
- type: DateConstructor;
58
- }] ? Date : [T] extends [StringConstructor | {
59
- type: StringConstructor;
60
- }] ? string : [T] extends [(infer U)[] | {
61
- type: (infer U)[];
62
- }] ? U extends DateConstructor ? Date | InferPropType<U> : InferPropType<U> : [T] extends [PropOptions<infer V>] ? unknown extends V ? IfAny<V, V, V> : V : T;
53
+ type: DateConstructor;
54
+ }] ? Date : [T] extends [(infer U)[] | {
55
+ type: (infer U)[];
56
+ }] ? U extends DateConstructor ? Date | InferPropType<U, false> : InferPropType<U, false> : [T] extends [Prop<infer V>] ? V : T;
63
57
  /**
64
58
  * Resolve the concrete prop value types from an `ObjectPropsOptions` declaration.
65
59
  * @group Types
66
60
  */
67
- type ExtractPropTypes<O> = {
68
- [K in keyof Pick<O, RequiredKeys<O>>]: InferPropType<O[K]>;
69
- } & {
70
- [K in keyof Pick<O, OptionalKeys<O>>]?: InferPropType<O[K]>;
71
- };
72
-
61
+ type ExtractPropTypes<O> = { [K in keyof Pick<O, RequiredKeys<O>>]: InferPropType<O[K]> } & { [K in keyof Pick<O, OptionalKeys<O>>]?: InferPropType<O[K]> };
73
62
  declare namespace AppDefinition {
74
- type EntryContext<T extends Data = Data> = T & {
75
- log: Logger;
76
- };
77
- type SetupContext<T extends Data = Data> = T & {
78
- log: Logger;
79
- };
80
- type RuntimeContext<T extends Data = Data> = T & {
81
- log: Logger;
82
- };
63
+ type EntryContext<T extends Data = Data> = T & {
64
+ log: Logger;
65
+ };
66
+ type SetupContext<T extends Data = Data> = T & {
67
+ log: Logger;
68
+ };
69
+ type RuntimeContext<T extends Data = Data> = T & {
70
+ log: Logger;
71
+ };
83
72
  }
84
73
  /**
85
74
  * Shape of an application — name, typed props, lifecycle hooks, and optional methods.
86
75
  * @group Types
87
76
  */
88
77
  interface AppDefinition<P extends ObjectPropsOptions = {}, S extends Record<string, any> = {}, M extends Record<string, AnyFunction> = {}, RuntimeContext extends AppDefinition.RuntimeContext = AppDefinition.RuntimeContext<S & M>, EntryContext extends AppDefinition.EntryContext = AppDefinition.EntryContext<S & M>, SetupContext extends AppDefinition.SetupContext = AppDefinition.SetupContext<M>> {
89
- /**
90
- * Name of your awesome application
91
- */
92
- name: string;
93
- /**
94
- * Describe what your application does
95
- */
96
- description?: string;
97
- /**
98
- * Props options to be parsed from cli arguments of env variables
99
- */
100
- props?: P;
101
- /**
102
- * Path to the file where this definition exports default
103
- * Usually you should not use this option, because it tracks automatically
104
- */
105
- filePath?: string | null;
106
- /**
107
- * Logger instance or constructor function
108
- */
109
- logger?: false | Logger | ((definition: AppDefinition) => Logger);
110
- /**
111
- * Setup function to initialize application. Will be called once
112
- */
113
- setup?(this: SetupContext, props: ExtractPropTypes<P>): Awaitable<S>;
114
- /**
115
- * Custom methods which will be available under `this` context
116
- */
117
- methods?: M & ThisType<RuntimeContext>;
118
- /**
119
- * Entry function that will be called each time when application starts
120
- */
121
- entry?(this: EntryContext, props: ExtractPropTypes<P>): Awaitable<any>;
122
- /**
123
- * Stop function that will be called each time when application stops
124
- */
125
- stop?(this: RuntimeContext, props: ExtractPropTypes<P>): Awaitable<void>;
126
- /**
127
- * Shutdown function that will be called before application/process graceful shutdown
128
- */
129
- shutdown?(this: RuntimeContext, props: ExtractPropTypes<P>): Awaitable<void>;
78
+ /**
79
+ * Name of your awesome application
80
+ */
81
+ name: string;
82
+ /**
83
+ * Describe what your application does
84
+ */
85
+ description?: string;
86
+ /**
87
+ * Props options to be parsed from cli arguments of env variables
88
+ */
89
+ props?: P;
90
+ /**
91
+ * Path to the file where this definition exports default
92
+ * Usually you should not use this option, because it tracks automatically
93
+ */
94
+ filePath?: string | null;
95
+ /**
96
+ * Logger instance or constructor function
97
+ */
98
+ logger?: false | Logger | ((definition: AppDefinition) => Logger);
99
+ /**
100
+ * Setup function to initialize application. Will be called once
101
+ */
102
+ setup?(this: SetupContext, props: ExtractPropTypes<P>): Awaitable<S>;
103
+ /**
104
+ * Custom methods which will be available under `this` context
105
+ */
106
+ methods?: M & ThisType<RuntimeContext>;
107
+ /**
108
+ * Entry function that will be called each time when application starts
109
+ */
110
+ entry?(this: EntryContext, props: ExtractPropTypes<P>, ...args: any[]): Awaitable<any>;
111
+ /**
112
+ * Stop function that will be called each time when application stops
113
+ */
114
+ stop?(this: RuntimeContext, props: ExtractPropTypes<P>): Awaitable<void>;
115
+ /**
116
+ * Shutdown function that will be called before application/process graceful shutdown
117
+ */
118
+ shutdown?(this: RuntimeContext, props: ExtractPropTypes<P>): Awaitable<void>;
130
119
  }
131
120
  declare const APP_INSTANCE_STATE: {
132
- readonly INIT: "init";
133
- readonly IN_SETUP: "in-setup";
134
- readonly SETUP: "setup";
135
- readonly IN_STOP: "in-stop";
136
- readonly IN_RUN: "in-run";
137
- readonly RUN: "run";
138
- readonly STOP: "stop";
139
- readonly IN_SHUTDOWN: "in-shutdown";
140
- readonly SHUTDOWN: "shutdown";
141
- readonly ERROR: "error";
121
+ readonly INIT: "init";
122
+ readonly IN_SETUP: "in-setup";
123
+ readonly SETUP: "setup";
124
+ readonly IN_STOP: "in-stop";
125
+ readonly IN_RUN: "in-run";
126
+ readonly RUN: "run";
127
+ readonly STOP: "stop";
128
+ readonly IN_SHUTDOWN: "in-shutdown";
129
+ readonly SHUTDOWN: "shutdown";
130
+ readonly ERROR: "error";
142
131
  };
143
132
  declare namespace AppInstance {
144
- type EventMap = {
145
- state: [newState: State, oldState: State];
146
- error: [err: Error];
147
- } & {
148
- [K in State as `state:${K}`]: [];
149
- };
150
- type State = (typeof APP_INSTANCE_STATE)[keyof typeof APP_INSTANCE_STATE];
133
+ type EventMap = {
134
+ state: [newState: State, oldState: State];
135
+ error: [err: Error];
136
+ } & { [K in State as `state:${K}`]: [] };
137
+ type State = (typeof APP_INSTANCE_STATE)[keyof typeof APP_INSTANCE_STATE];
151
138
  }
152
139
  /**
153
140
  * Runtime state of a created app instance.
154
141
  * @group Types
155
142
  */
156
143
  interface AppInstance<P extends ObjectPropsOptions = {}, S extends Record<string, any> = {}, M extends Record<string, AnyFunction> = {}> {
157
- definition: AppDefinition<P, S, M>;
158
- props: ExtractPropTypes<P> | null;
159
- setupState: AppDefinition.SetupContext<Data>;
160
- eventBus: SimpleEventEmitter<AppInstance.EventMap>;
161
- /** @internal */
162
- mutexName: string | null;
163
- /** @internal */
164
- mutexQueue: Promise<void>;
165
- readonly state: AppInstance.State;
166
- logger: Logger;
144
+ definition: AppDefinition<P, S, M>;
145
+ props: ExtractPropTypes<P> | null;
146
+ setupState: AppDefinition.SetupContext<Data>;
147
+ eventBus: SimpleEventEmitter<AppInstance.EventMap>;
148
+ /** @internal */
149
+ mutexName: string | null;
150
+ /** @internal */
151
+ mutexQueue: Promise<void>;
152
+ readonly state: AppInstance.State;
153
+ logger: Logger;
167
154
  }
168
155
  /**
169
156
  * Define an application with typed props and lifecycle hooks.
@@ -220,7 +207,7 @@ declare function isAppDefinition(value: unknown): value is AppDefinition;
220
207
  * ```
221
208
  */
222
209
  declare function startApp<P extends ObjectPropsOptions, S extends Record<string, any>>(app: AppDefinition<P, S> | AppInstance<P, S>, props: ExtractPropTypes<P>): Promise<ExecResult<{
223
- app: AppInstance<P, S>;
210
+ app: AppInstance<P, S>;
224
211
  }>>;
225
212
  /**
226
213
  * Run the setup phase of an app instance.
@@ -243,7 +230,7 @@ declare function setupApp(instance: AppInstance, props: Data): Promise<ExecResul
243
230
  * await runApp(instance);
244
231
  * ```
245
232
  */
246
- declare function runApp$1(instance: AppInstance): Promise<ExecResult>;
233
+ declare function runApp(instance: AppInstance): Promise<ExecResult>;
247
234
  /**
248
235
  * Stop a running app instance and call its `stop` hook.
249
236
  * @group App Lifecycle
@@ -278,7 +265,6 @@ declare function shutdownApp(instance: AppInstance): Promise<ExecResult>;
278
265
  * ```
279
266
  */
280
267
  declare function appWaitShutdown(instance: AppInstance): Promise<void>;
281
-
282
268
  /**
283
269
  * Combine multiple app definitions into a single orchestrated app.
284
270
  * Props from each definition are namespaced by their app name.
@@ -287,7 +273,6 @@ declare function appWaitShutdown(instance: AppInstance): Promise<void>;
287
273
  declare function createAppHub(definitions: AppDefinition[]): AppDefinition;
288
274
  declare function getPrefixedProps(definition: AppDefinition, props: Data): Data;
289
275
  declare function prefixifyProps(definitions: AppDefinition[]): ObjectPropsOptions;
290
-
291
276
  /**
292
277
  * Wrap an app definition to run across N child processes. Adds a
293
278
  * `threads` prop and manages the full lifecycle of each child.
@@ -295,10 +280,10 @@ declare function prefixifyProps(definitions: AppDefinition[]): ObjectPropsOption
295
280
  */
296
281
  declare function createAppThread(definition: AppDefinition): AppDefinition;
297
282
  interface CreateAppThreadInstanceParams {
298
- definition: AppDefinition;
299
- parentPort: ParentPortLike;
300
- threadId: number;
301
- onShutdown?: () => void;
283
+ definition: AppDefinition;
284
+ parentPort: ParentPortLike;
285
+ threadId: number;
286
+ onShutdown?: () => void;
302
287
  }
303
288
  /**
304
289
  * A minimal port abstraction implemented by both IPC `MessagePort`
@@ -306,110 +291,114 @@ interface CreateAppThreadInstanceParams {
306
291
  * @group Types
307
292
  */
308
293
  interface ParentPortLike {
309
- on(event: 'message', cb: (msg: unknown) => void): unknown;
310
- postMessage(msg: unknown, cb?: () => void): unknown;
311
- close?(): unknown;
294
+ on(event: 'message', cb: (msg: unknown) => void): unknown;
295
+ postMessage(msg: unknown, cb?: () => void): unknown;
296
+ close?(): unknown;
312
297
  }
313
298
  /**
314
299
  * Create app instance with IPC fully managed lifecycle
315
300
  * @group Threads
316
301
  */
317
- declare function createAppThreadInstance({ definition, parentPort, threadId, onShutdown, }: CreateAppThreadInstanceParams): AppInstance;
318
-
302
+ declare function createAppThreadInstance({
303
+ definition,
304
+ parentPort,
305
+ threadId,
306
+ onShutdown
307
+ }: CreateAppThreadInstanceParams): AppInstance;
319
308
  interface RunAppOptions {
320
- scriptFile?: string;
321
- cliName?: string;
322
- cliDescription?: string;
323
- argv?: string[];
309
+ scriptFile?: string;
310
+ cliName?: string;
311
+ cliDescription?: string;
312
+ argv?: string[];
324
313
  }
325
- declare function runApp({ scriptFile, cliName, cliDescription, argv, }: RunAppOptions): Promise<void>;
326
-
314
+ declare function runApp$1({
315
+ scriptFile,
316
+ cliName,
317
+ cliDescription,
318
+ argv
319
+ }: RunAppOptions): Promise<void>;
327
320
  /**
328
321
  * Programmatic access to the `vrun` CLI internals.
329
322
  * @group Utils
330
323
  */
331
324
  declare const cli: Readonly<{
332
- readonly runApp: typeof runApp;
325
+ readonly runApp: typeof runApp$1;
333
326
  }>;
334
-
335
327
  type LogEventFields = Record<string, any>;
336
-
337
328
  /**
338
329
  * @group Types
339
330
  */
340
331
  declare namespace ManagedThread {
341
- type State = AppInstance.State | 'ready';
342
- interface LogEntry {
343
- ts: number;
344
- level: LogLevel;
345
- text: string;
332
+ type State = AppInstance.State | 'ready';
333
+ interface LogEntry {
334
+ ts: number;
335
+ level: LogLevel;
336
+ text: string;
337
+ }
338
+ type EventMap = {
339
+ ready: [];
340
+ state: [newState: State, oldState: State];
341
+ log: [entry: LogEntry];
342
+ pid: [pid: number];
343
+ exit: [code: number | null, signal: NodeJS.Signals | null];
344
+ message: [message: ManagedThread.ThreadMessage];
345
+ error: [err: Error];
346
+ } & { [K in ManagedThread.ThreadMessage as `msg:${K['type']}`]: [msg: K] };
347
+ type ThreadMessage = ThreadMessage.AppState | ThreadMessage.Ping | ThreadMessage.Pong | ThreadMessage.Ready | ThreadMessage.Shutdown | ThreadMessage.ShutdownDone | ThreadMessage.Start | ThreadMessage.StartDone | ThreadMessage.Setup | ThreadMessage.SetupDone | ThreadMessage.Stop | ThreadMessage.StopDone;
348
+ type ThreadMessageMap = { [K in ManagedThread.ThreadMessage as K['type']]: K };
349
+ type ThreadMessageDone<T extends string> = `${T}_done` extends keyof ThreadMessageMap ? `${T}_done` : never;
350
+ namespace ThreadMessage {
351
+ interface Base<T extends string> {
352
+ type: T;
353
+ vrun_app_thread_message: true;
346
354
  }
347
- type EventMap = {
348
- ready: [];
349
- state: [newState: State, oldState: State];
350
- log: [entry: LogEntry];
351
- pid: [pid: number];
352
- exit: [code: number | null, signal: NodeJS.Signals | null];
353
- message: [message: ManagedThread.ThreadMessage];
354
- error: [err: Error];
355
- } & {
356
- [K in ManagedThread.ThreadMessage as `msg:${K['type']}`]: [msg: K];
355
+ type AppState = Base<'app-state'> & {
356
+ state: AppInstance.State;
357
357
  };
358
- type ThreadMessage = ThreadMessage.AppState | ThreadMessage.Ping | ThreadMessage.Pong | ThreadMessage.Ready | ThreadMessage.Shutdown | ThreadMessage.ShutdownDone | ThreadMessage.Start | ThreadMessage.StartDone | ThreadMessage.Setup | ThreadMessage.SetupDone | ThreadMessage.Stop | ThreadMessage.StopDone;
359
- type ThreadMessageMap = {
360
- [K in ManagedThread.ThreadMessage as K['type']]: K;
358
+ type Start = Base<'start'>;
359
+ type StartDone = Base<'start_done'> & {
360
+ result: ExecResult;
361
361
  };
362
- type ThreadMessageDone<T extends string> = `${T}_done` extends keyof ThreadMessageMap ? `${T}_done` : never;
363
- namespace ThreadMessage {
364
- interface Base<T extends string> {
365
- type: T;
366
- vrun_app_thread_message: true;
367
- }
368
- type AppState = Base<'app-state'> & {
369
- state: AppInstance.State;
370
- };
371
- type Start = Base<'start'>;
372
- type StartDone = Base<'start_done'> & {
373
- result: ExecResult;
374
- };
375
- type Setup = Base<'setup'> & {
376
- props: Data;
377
- };
378
- type SetupDone = Base<'setup_done'> & {
379
- result: ExecResult;
380
- };
381
- type Stop = Base<'stop'>;
382
- type StopDone = Base<'stop_done'> & {
383
- result: ExecResult;
384
- };
385
- type Shutdown = Base<'shutdown'>;
386
- type ShutdownDone = Base<'shutdown_done'> & {
387
- result: ExecResult;
388
- };
389
- type Ping = Base<'ping'>;
390
- type Pong = Base<'pong'>;
391
- type Ready = Base<'ready'> & {
392
- pid: number;
393
- };
394
- }
362
+ type Setup = Base<'setup'> & {
363
+ props: Data;
364
+ };
365
+ type SetupDone = Base<'setup_done'> & {
366
+ result: ExecResult;
367
+ };
368
+ type Stop = Base<'stop'>;
369
+ type StopDone = Base<'stop_done'> & {
370
+ result: ExecResult;
371
+ };
372
+ type Shutdown = Base<'shutdown'>;
373
+ type ShutdownDone = Base<'shutdown_done'> & {
374
+ result: ExecResult;
375
+ };
376
+ type Ping = Base<'ping'>;
377
+ type Pong = Base<'pong'>;
378
+ type Ready = Base<'ready'> & {
379
+ pid: number;
380
+ };
381
+ }
395
382
  }
396
383
  /**
397
384
  * A child process managed by the parent.
398
385
  * @group Types
399
386
  */
400
387
  interface ManagedThread {
401
- child: cp.ChildProcess;
402
- threadId: number;
403
- pid: number;
404
- state: ManagedThread.State;
405
- restartCount: number;
406
- scriptFile: string;
407
- threadProps: Record<string, unknown>;
408
- eventBus: EventEmitter<ManagedThread.EventMap>;
409
- scheduler: Scheduler;
410
- writeLog(level: LogLevel, event: string, fields?: LogEventFields): void;
411
- /** @internal */ heartbeatTimer?: NodeJS.Timeout;
412
- /** @internal */ lastPong: number;
388
+ child: cp.ChildProcess;
389
+ threadId: number;
390
+ pid: number;
391
+ state: ManagedThread.State;
392
+ restartCount: number;
393
+ scriptFile: string;
394
+ threadProps: Record<string, unknown>;
395
+ eventBus: EventEmitter<ManagedThread.EventMap>;
396
+ scheduler: Scheduler;
397
+ writeLog(level: LogLevel, event: string, fields?: LogEventFields): void;
398
+ /** @internal */
399
+ heartbeatTimer?: NodeJS.Timeout;
400
+ /** @internal */
401
+ lastPong: number;
413
402
  }
414
403
  /**
415
404
  * Wait for thread ready signal
@@ -450,91 +439,90 @@ declare function restartThreadApp(w: ManagedThread): Promise<void>;
450
439
  declare function isThreadMessage(value: unknown): value is ManagedThread.ThreadMessage;
451
440
  declare function createThreadMessage<T extends keyof ManagedThread.ThreadMessageMap>(type: T, msg: Omit<ManagedThread.ThreadMessageMap[T], 'type' | 'vrun_app_thread_message'>): ManagedThread.ThreadMessageMap[T];
452
441
  declare function isThreadExit(w: ManagedThread): boolean;
453
-
454
442
  type WorkerSuccessData = {
455
- [x: string]: unknown;
443
+ [x: string]: unknown;
456
444
  };
457
445
  type WorkerSkipData = {
458
- error?: boolean;
459
- [x: string]: unknown;
446
+ error?: boolean;
447
+ [x: string]: unknown;
460
448
  };
461
449
  type WorkerResult = ExecResult<WorkerSuccessData, WorkerSkipData>;
462
450
  /**
463
451
  * @group Types
464
452
  */
465
453
  declare namespace WorkerStrategy {
466
- /**
467
- * Base context bag emitted by strategies per task. Strategies extend this with typed fields.
468
- * @group Types
469
- */
470
- interface Context {
471
- [key: string]: unknown;
472
- }
454
+ /**
455
+ * Base context bag emitted by strategies per task. Strategies extend this with typed fields.
456
+ * @group Types
457
+ */
458
+ interface Context {
459
+ [key: string]: unknown;
460
+ }
473
461
  }
474
462
  /**
475
463
  * Pluggable trigger source. Drives when tasks are enqueued.
476
464
  * @group Types
477
465
  */
478
466
  interface WorkerStrategy<C extends WorkerStrategy.Context = WorkerStrategy.Context> {
479
- doSetup(opts: {
480
- worker: WorkerInstance;
481
- }): Awaitable<void>;
482
- startSignal(): void;
483
- stopSignal(done: () => void): void;
484
- doShutdown(): Awaitable<void>;
485
- createTask(...args: any[]): C;
486
- executeSignal?(ctx: WorkerDefinition.EntryContext<WorkerStrategy<C>>): Awaitable<ExecResult>;
487
- completeSignal?(ctx: WorkerDefinition.EntryContext<WorkerStrategy<C>>, result: WorkerResult | WorkerResult[]): Awaitable<void>;
488
- overloadedSignal?(): void;
489
- availableSignal?(): void;
490
- handleEntryError?(err: Error): WorkerResult;
467
+ doSetup(opts: {
468
+ worker: WorkerInstance;
469
+ }): Awaitable<void>;
470
+ startSignal(): void;
471
+ stopSignal(done: () => void): void;
472
+ doShutdown(): Awaitable<void>;
473
+ createTask(...args: any[]): C;
474
+ executeSignal?(ctx: WorkerDefinition.EntryContext<WorkerStrategy<C>>): Awaitable<ExecResult>;
475
+ completeSignal?(ctx: WorkerDefinition.EntryContext<WorkerStrategy<C>>, result: WorkerResult | WorkerResult[]): Awaitable<void>;
476
+ overloadedSignal?(): void;
477
+ availableSignal?(): void;
478
+ handleEntryError?(err: Error): WorkerResult;
491
479
  }
492
480
  declare namespace WorkerDefinition {
493
- /**
494
- * Entry function that will be called each time when worker handle a job
495
- */
496
- type EntryFn<Context extends Data, Props extends Data> = (this: Context, props: Props) => Awaitable<WorkerResult | WorkerResult[] | void>;
497
- type SetupFn<Context extends Data, Props extends Data, Result> = (this: Context, props: Props) => Awaitable<Result>;
498
- type EntryContext<T extends WorkerStrategy = WorkerStrategy> = AppDefinition.EntryContext<{
499
- worker: WorkerInstance<T>;
500
- } & TaskContext<T>>;
501
- type SetupContext<T extends Data = Data> = AppDefinition.SetupContext<T & {
502
- worker: WorkerInstance;
503
- }>;
504
- type RuntimeContext<T extends Data = Data> = AppDefinition.RuntimeContext<T & {
505
- worker: WorkerInstance;
506
- }>;
507
- type TaskContext<T extends WorkerStrategy> = T extends WorkerStrategy<infer X> ? X : never;
481
+ /**
482
+ * Entry function that will be called each time when worker handle a job
483
+ */
484
+ type EntryFn<Context extends Data, Props extends Data> = (this: Context, props: Props) => Awaitable<WorkerResult | WorkerResult[] | void>;
485
+ type SetupFn<Context extends Data, Props extends Data, Result> = (this: Context, props: Props) => Awaitable<Result>;
486
+ type EntryContext<T extends WorkerStrategy = WorkerStrategy> = AppDefinition.EntryContext<{
487
+ worker: WorkerInstance<T>;
488
+ } & TaskContext<T>>;
489
+ type SetupContext<T extends Data = Data> = AppDefinition.SetupContext<T & {
490
+ worker: WorkerInstance;
491
+ }>;
492
+ type RuntimeContext<T extends Data = Data> = AppDefinition.RuntimeContext<T & {
493
+ worker: WorkerInstance;
494
+ }>;
495
+ type TaskContext<T extends WorkerStrategy> = T extends WorkerStrategy<infer X> ? X : never;
508
496
  }
509
497
  /**
510
498
  * Worker definition — extends AppDefinition with strategy, per-task entry, and concurrency config.
511
499
  * @group Types
512
500
  */
513
501
  interface WorkerDefinition<P extends ObjectPropsOptions = {}, S extends Record<string, any> = {}, M extends Record<string, AnyFunction> = {}, C extends WorkerStrategy = WorkerStrategy, RuntimeContext extends WorkerDefinition.RuntimeContext = WorkerDefinition.RuntimeContext<S & M>, EntryContext extends WorkerDefinition.EntryContext = WorkerDefinition.EntryContext<C> & S & M, SetupContext extends WorkerDefinition.SetupContext = WorkerDefinition.SetupContext<M>> extends AppDefinition<P, S, M, RuntimeContext, EntryContext, SetupContext> {
514
- /**
515
- * Entry function that will be called each time when worker handle a job
516
- */
517
- entry?(this: EntryContext, props: ExtractPropTypes<P>): Awaitable<WorkerResult | WorkerResult[] | void>;
518
- /**
519
- * Setup function will be called once while worker setup.
520
- */
521
- setup?(this: SetupContext, props: ExtractPropTypes<P>): Awaitable<S>;
522
- executeStrategy: C;
523
- /**
524
- * Maximum limit of queued tasks
525
- * @default 50
526
- */
527
- taskLimit?: number;
528
- /**
529
- * Amount of task to be executed in parallel
530
- * @default 2
531
- */
532
- taskParallel?: number;
533
- /**
534
- * Disable worker
535
- * @default false
536
- */
537
- disabled?: boolean;
502
+ /**
503
+ * Entry function that will be called each time when worker handle a job
504
+ */
505
+ entry?(this: EntryContext, props: ExtractPropTypes<P>, abortSignal: AbortSignal): Awaitable<WorkerResult | WorkerResult[] | void>;
506
+ /**
507
+ * Setup function will be called once while worker setup.
508
+ */
509
+ setup?(this: SetupContext, props: ExtractPropTypes<P>): Awaitable<S>;
510
+ executeStrategy: C | ((props: ExtractPropTypes<P>) => C);
511
+ /**
512
+ * Maximum limit of queued tasks
513
+ * @default 50
514
+ */
515
+ taskLimit?: number;
516
+ /**
517
+ * Amount of task to be executed in parallel
518
+ * @default 2
519
+ */
520
+ taskParallel?: number;
521
+ /**
522
+ * Disable worker
523
+ * @default false
524
+ */
525
+ disabled?: boolean;
538
526
  }
539
527
  /**
540
528
  * Runtime state of a worker instance. Extends AppInstance with task queue and pool.
@@ -542,37 +530,38 @@ interface WorkerDefinition<P extends ObjectPropsOptions = {}, S extends Record<s
542
530
  * @group Types
543
531
  */
544
532
  interface WorkerInstance<C extends WorkerStrategy = WorkerStrategy> {
545
- definition: WorkerDefinition<{}, {}, {}, C>;
546
- queue: AsyncIterableQueue<WorkerDefinition.TaskContext<C>>;
547
- pool: ResourcePool<symbol>;
548
- runTask: CancellablePromise<void> | null;
549
- overloadedSignaled: boolean;
550
- log: Logger;
551
- readonly queueMaxSize: number;
552
- readonly taskParallel: number;
553
- /**
554
- * Tasks queue size
555
- */
556
- readonly queueSize: number;
557
- /**
558
- * Check if the worker is overloaded (e.g., queue length is high)
559
- */
560
- readonly isOverloaded: boolean;
561
- /**
562
- * Returns true when worker do nothing
563
- */
564
- readonly isIdle: boolean;
565
- /**
566
- * Add task into execution queue
567
- */
568
- addTask(ctx: WorkerDefinition.TaskContext<C>): void;
533
+ definition: WorkerDefinition<{}, {}, {}, C>;
534
+ queue: AsyncIterableQueue<WorkerDefinition.TaskContext<C>>;
535
+ pool: ResourcePool<symbol>;
536
+ runTask: CancellablePromise<void> | null;
537
+ executeStrategy: C | null;
538
+ overloadedSignaled: boolean;
539
+ log: Logger;
540
+ readonly queueMaxSize: number;
541
+ readonly taskParallel: number;
542
+ /**
543
+ * Tasks queue size
544
+ */
545
+ readonly queueSize: number;
546
+ /**
547
+ * Check if the worker is overloaded (e.g., queue length is high)
548
+ */
549
+ readonly isOverloaded: boolean;
550
+ /**
551
+ * Returns true when worker do nothing
552
+ */
553
+ readonly isIdle: boolean;
554
+ /**
555
+ * Add task into execution queue
556
+ */
557
+ addTask(ctx: WorkerDefinition.TaskContext<C>): void;
569
558
  }
570
559
  /**
571
560
  * Create a runtime WorkerInstance from a WorkerDefinition.
572
561
  * Use with startApp / stopApp / shutdownApp.
573
562
  * @group Worker
574
563
  */
575
- declare function createWorkerInstance<C extends WorkerStrategy>(definition: WorkerDefinition<{}, {}, {}, C>, logger: Logger): WorkerInstance<C>;
564
+ declare function createWorkerInstance<C extends WorkerStrategy>(definition: WorkerDefinition<any, {}, {}, C>, logger: Logger): WorkerInstance<C>;
576
565
  /**
577
566
  * Enqueue a task context on the worker. Fires backpressure signals at 80% capacity.
578
567
  * @group Worker
@@ -613,20 +602,23 @@ declare function isWorkerDefinition(value: unknown): value is WorkerDefinition;
613
602
  * @group Utils
614
603
  */
615
604
  declare function isWorkerInstance(value: unknown): value is WorkerInstance;
616
-
617
605
  declare namespace IntervalStrategy {
606
+ /**
607
+ * Options for the built-in IntervalStrategy.
608
+ */
609
+ interface Options {
610
+ intervalSeconds: number;
618
611
  /**
619
- * Options for the built-in IntervalStrategy.
612
+ * @default true
620
613
  */
621
- interface Options {
622
- intervalSeconds: number;
623
- }
624
- /**
625
- * Context emitted by IntervalStrategy on each tick.
626
- */
627
- interface Context extends WorkerStrategy.Context {
628
- timerSequence: number;
629
- }
614
+ warnOnBusy?: boolean;
615
+ }
616
+ /**
617
+ * Context emitted by IntervalStrategy on each tick.
618
+ */
619
+ interface Context extends WorkerStrategy.Context {
620
+ timerSequence: number;
621
+ }
630
622
  }
631
623
  /**
632
624
  * Triggers a worker task on a fixed interval.
@@ -634,18 +626,21 @@ declare namespace IntervalStrategy {
634
626
  * @group Worker Strategies
635
627
  */
636
628
  declare class IntervalStrategy implements WorkerStrategy<IntervalStrategy.Context> {
637
- private readonly options;
638
- private timerSequence;
639
- private timer;
640
- private worker;
641
- constructor(options: IntervalStrategy.Options);
642
- doSetup({ worker }: {
643
- worker: WorkerInstance;
644
- }): void;
645
- startSignal(): void;
646
- stopSignal(done: () => void): void;
647
- doShutdown(): void;
648
- createTask(): IntervalStrategy.Context;
629
+ private readonly options;
630
+ private timerSequence;
631
+ private timer;
632
+ private worker;
633
+ private warnOnBusy;
634
+ constructor(options: IntervalStrategy.Options);
635
+ doSetup({
636
+ worker
637
+ }: {
638
+ worker: WorkerInstance;
639
+ }): void;
640
+ startSignal(): void;
641
+ stopSignal(done: () => void): void;
642
+ doShutdown(): void;
643
+ createTask(): IntervalStrategy.Context;
649
644
  }
650
-
651
- export { APP_INSTANCE_STATE, AppDefinition, AppInstance, type CreateAppThreadInstanceParams, type ExtractPropTypes, IntervalStrategy, ManagedThread, type ObjectPropsOptions, type ParentPortLike, type PropOptions, WorkerDefinition, type WorkerInstance, type WorkerResult, type WorkerSkipData, WorkerStrategy, type WorkerSuccessData, addWorkerTask, appWaitShutdown, cli, createAppHub, createAppInstance, createAppThread, createAppThreadInstance, createThreadMessage, createWorkerInstance, defineApp, defineWorker, getPrefixedProps, initThread, isAppDefinition, isThreadExit, isThreadMessage, isWorkerDefinition, isWorkerInstance, prefixifyProps, restartThreadApp, runApp$1 as runApp, setupApp, setupThreadApp, shutdownApp, shutdownThreadApp, startApp, startThreadApp, stopApp, stopThreadApp, waitForThreadReady };
645
+ export { APP_INSTANCE_STATE, AppDefinition, AppInstance, CreateAppThreadInstanceParams, type ExtractPropTypes, IntervalStrategy, ManagedThread, type ObjectPropsOptions, ParentPortLike, type PropOptions, type PropType, WorkerDefinition, WorkerInstance, WorkerResult, WorkerSkipData, WorkerStrategy, WorkerSuccessData, addWorkerTask, appWaitShutdown, cli, createAppHub, createAppInstance, createAppThread, createAppThreadInstance, createThreadMessage, createWorkerInstance, defineApp, defineWorker, getPrefixedProps, initThread, isAppDefinition, isThreadExit, isThreadMessage, isWorkerDefinition, isWorkerInstance, prefixifyProps, restartThreadApp, runApp, setupApp, setupThreadApp, shutdownApp, shutdownThreadApp, startApp, startThreadApp, stopApp, stopThreadApp, waitForThreadReady };
646
+ //# sourceMappingURL=index.d.mts.map