@computekit/react 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,12 +1,160 @@
1
1
  import React, { ReactNode } from 'react';
2
- import { ComputeKitOptions, ComputeKit, ComputeProgress, ComputeOptions, PoolStats } from '@computekit/core';
3
- export { ComputeKit, ComputeKitOptions, ComputeOptions, ComputeProgress, PoolStats } from '@computekit/core';
2
+ import { ComputeOptions, ComputeKitOptions, ComputeKit, ComputeProgress, RegisteredFunctionName, FunctionInput, FunctionOutput, ComputeFunctionRegistry, ComputeFn, PoolStats } from '@computekit/core';
3
+ export { ComputeFn, ComputeFunctionRegistry, ComputeKit, ComputeKitOptions, ComputeOptions, ComputeProgress, DefineFunction, FunctionInput, FunctionOutput, HasRegisteredFunctions, InferComputeFn, PoolStats, RegisteredFunctionName } from '@computekit/core';
4
4
 
5
5
  /**
6
6
  * ComputeKit React Bindings
7
7
  * React hooks and utilities for ComputeKit
8
8
  */
9
9
 
10
+ /** Status of a pipeline stage */
11
+ type StageStatus = 'pending' | 'running' | 'completed' | 'failed' | 'skipped';
12
+ /** Detailed information about a single pipeline stage */
13
+ interface StageInfo<TInput = unknown, TOutput = unknown> {
14
+ /** Unique identifier for the stage */
15
+ id: string;
16
+ /** Display name for the stage */
17
+ name: string;
18
+ /** Name of the registered compute function to execute */
19
+ functionName: string;
20
+ /** Current status of this stage */
21
+ status: StageStatus;
22
+ /** Input data for this stage (set when stage starts) */
23
+ input?: TInput;
24
+ /** Output data from this stage (set when stage completes) */
25
+ output?: TOutput;
26
+ /** Error if stage failed */
27
+ error?: Error;
28
+ /** Start timestamp (ms since epoch) */
29
+ startedAt?: number;
30
+ /** End timestamp (ms since epoch) */
31
+ completedAt?: number;
32
+ /** Duration in milliseconds */
33
+ duration?: number;
34
+ /** Progress within this stage (0-100) */
35
+ progress?: number;
36
+ /** Number of retry attempts */
37
+ retryCount: number;
38
+ /** Compute options specific to this stage */
39
+ options?: ComputeOptions;
40
+ }
41
+ /** Configuration for a pipeline stage */
42
+ interface StageConfig<TInput = unknown, TOutput = unknown> {
43
+ /** Unique identifier for the stage */
44
+ id: string;
45
+ /** Display name for the stage */
46
+ name: string;
47
+ /** Name of the registered compute function */
48
+ functionName: string;
49
+ /** Transform input before passing to compute function */
50
+ transformInput?: (input: TInput, previousResults: unknown[]) => unknown;
51
+ /** Transform output after compute function returns */
52
+ transformOutput?: (output: unknown) => TOutput;
53
+ /** Whether to skip this stage based on previous results */
54
+ shouldSkip?: (input: TInput, previousResults: unknown[]) => boolean;
55
+ /** Maximum retry attempts on failure (default: 0) */
56
+ maxRetries?: number;
57
+ /** Delay between retries in ms (default: 1000) */
58
+ retryDelay?: number;
59
+ /** Compute options for this stage */
60
+ options?: ComputeOptions;
61
+ }
62
+ /** Overall pipeline status */
63
+ type PipelineStatus = 'idle' | 'running' | 'paused' | 'completed' | 'failed' | 'cancelled';
64
+ /** Metrics for pipeline debugging and reporting */
65
+ interface PipelineMetrics {
66
+ /** Total stages in pipeline */
67
+ totalStages: number;
68
+ /** Number of completed stages */
69
+ completedStages: number;
70
+ /** Number of failed stages */
71
+ failedStages: number;
72
+ /** Number of skipped stages */
73
+ skippedStages: number;
74
+ /** Total retry attempts across all stages */
75
+ totalRetries: number;
76
+ /** Slowest stage info */
77
+ slowestStage: {
78
+ id: string;
79
+ name: string;
80
+ duration: number;
81
+ } | null;
82
+ /** Fastest stage info */
83
+ fastestStage: {
84
+ id: string;
85
+ name: string;
86
+ duration: number;
87
+ } | null;
88
+ /** Average stage duration */
89
+ averageStageDuration: number;
90
+ /** Timestamp of each stage transition for timeline view */
91
+ timeline: Array<{
92
+ stageId: string;
93
+ stageName: string;
94
+ event: 'started' | 'completed' | 'failed' | 'skipped' | 'retry';
95
+ timestamp: number;
96
+ duration?: number;
97
+ error?: string;
98
+ }>;
99
+ }
100
+ /** Comprehensive pipeline state for debugging */
101
+ interface PipelineState<TInput = unknown, TOutput = unknown> {
102
+ /** Overall pipeline status */
103
+ status: PipelineStatus;
104
+ /** All stage information */
105
+ stages: StageInfo[];
106
+ /** Index of currently executing stage (-1 if not running) */
107
+ currentStageIndex: number;
108
+ /** Current stage info (convenience) */
109
+ currentStage: StageInfo | null;
110
+ /** Overall progress percentage (0-100) */
111
+ progress: number;
112
+ /** Final output from the last stage */
113
+ output: TOutput | null;
114
+ /** Initial input that started the pipeline */
115
+ input: TInput | null;
116
+ /** Error that caused pipeline failure */
117
+ error: Error | null;
118
+ /** Pipeline start timestamp */
119
+ startedAt: number | null;
120
+ /** Pipeline completion timestamp */
121
+ completedAt: number | null;
122
+ /** Total duration in milliseconds */
123
+ totalDuration: number | null;
124
+ /** Results from each completed stage */
125
+ stageResults: unknown[];
126
+ /** Execution metrics for debugging */
127
+ metrics: PipelineMetrics;
128
+ }
129
+ /** Result of a single item in parallel batch */
130
+ interface BatchItemResult<TOutput = unknown> {
131
+ /** Index of the item in original array */
132
+ index: number;
133
+ /** Whether this item succeeded */
134
+ success: boolean;
135
+ /** Result if successful */
136
+ data?: TOutput;
137
+ /** Error if failed */
138
+ error?: Error;
139
+ /** Duration in ms */
140
+ duration: number;
141
+ }
142
+ /** Aggregate result of parallel batch processing */
143
+ interface ParallelBatchResult<TOutput = unknown> {
144
+ /** All individual results */
145
+ results: BatchItemResult<TOutput>[];
146
+ /** Successfully processed items */
147
+ successful: TOutput[];
148
+ /** Failed items with their errors */
149
+ failed: Array<{
150
+ index: number;
151
+ error: Error;
152
+ }>;
153
+ /** Total duration */
154
+ totalDuration: number;
155
+ /** Success rate (0-1) */
156
+ successRate: number;
157
+ }
10
158
  /**
11
159
  * Props for ComputeKitProvider
12
160
  */
@@ -89,6 +237,7 @@ interface UseComputeOptions extends ComputeOptions {
89
237
  *
90
238
  * @example
91
239
  * ```tsx
240
+ * // Basic usage with explicit types
92
241
  * function FibonacciCalculator() {
93
242
  * const { data, loading, error, run } = useCompute<number, number>('fibonacci');
94
243
  *
@@ -103,14 +252,23 @@ interface UseComputeOptions extends ComputeOptions {
103
252
  * </div>
104
253
  * );
105
254
  * }
255
+ *
256
+ * // With typed registry (extend ComputeFunctionRegistry for autocomplete)
257
+ * // declare module '@computekit/core' {
258
+ * // interface ComputeFunctionRegistry {
259
+ * // fibonacci: { input: number; output: number };
260
+ * // }
261
+ * // }
262
+ * // const { data, run } = useCompute('fibonacci'); // Types are inferred!
106
263
  * ```
107
264
  */
108
- declare function useCompute<TInput = unknown, TOutput = unknown>(functionName: string, options?: UseComputeOptions): UseComputeReturn<TInput, TOutput>;
265
+ declare function useCompute<TName extends RegisteredFunctionName, TInput = FunctionInput<TName extends string ? TName : never>, TOutput = FunctionOutput<TName extends string ? TName : never>>(functionName: TName, options?: UseComputeOptions): UseComputeReturn<TName extends keyof ComputeFunctionRegistry ? ComputeFunctionRegistry[TName]['input'] : TInput, TName extends keyof ComputeFunctionRegistry ? ComputeFunctionRegistry[TName]['output'] : TOutput>;
109
266
  /**
110
267
  * Hook that returns a memoized async function for compute operations
111
268
  *
112
269
  * @example
113
270
  * ```tsx
271
+ * // Basic usage with explicit types
114
272
  * function Calculator() {
115
273
  * const calculate = useComputeCallback<number[], number>('sum');
116
274
  *
@@ -121,14 +279,18 @@ declare function useCompute<TInput = unknown, TOutput = unknown>(functionName: s
121
279
  *
122
280
  * return <button onClick={handleClick}>Calculate Sum</button>;
123
281
  * }
282
+ *
283
+ * // With typed registry - types are inferred!
284
+ * // const calculate = useComputeCallback('sum');
124
285
  * ```
125
286
  */
126
- declare function useComputeCallback<TInput = unknown, TOutput = unknown>(functionName: string, options?: ComputeOptions): (input: TInput, runOptions?: ComputeOptions) => Promise<TOutput>;
287
+ declare function useComputeCallback<TName extends RegisteredFunctionName, TInput = FunctionInput<TName extends string ? TName : never>, TOutput = FunctionOutput<TName extends string ? TName : never>>(functionName: TName, options?: ComputeOptions): (input: TName extends keyof ComputeFunctionRegistry ? ComputeFunctionRegistry[TName]['input'] : TInput, runOptions?: ComputeOptions) => Promise<TName extends keyof ComputeFunctionRegistry ? ComputeFunctionRegistry[TName]['output'] : TOutput>;
127
288
  /**
128
289
  * Hook to register and use a compute function
129
290
  *
130
291
  * @example
131
292
  * ```tsx
293
+ * // Basic usage
132
294
  * function MyComponent() {
133
295
  * const { run, loading, data } = useComputeFunction(
134
296
  * 'myFunction',
@@ -141,9 +303,16 @@ declare function useComputeCallback<TInput = unknown, TOutput = unknown>(functio
141
303
  * </button>
142
304
  * );
143
305
  * }
306
+ *
307
+ * // With typed registry - provides autocomplete and type safety
308
+ * // declare module '@computekit/core' {
309
+ * // interface ComputeFunctionRegistry {
310
+ * // myFunction: { input: number; output: number };
311
+ * // }
312
+ * // }
144
313
  * ```
145
314
  */
146
- declare function useComputeFunction<TInput = unknown, TOutput = unknown>(name: string, fn: (input: TInput) => TOutput | Promise<TOutput>, options?: UseComputeOptions): UseComputeReturn<TInput, TOutput>;
315
+ declare function useComputeFunction<TName extends RegisteredFunctionName, TInput = FunctionInput<TName extends string ? TName : never>, TOutput = FunctionOutput<TName extends string ? TName : never>>(name: TName, fn: TName extends keyof ComputeFunctionRegistry ? ComputeFn<ComputeFunctionRegistry[TName]['input'], ComputeFunctionRegistry[TName]['output']> : ComputeFn<TInput, TOutput>, options?: UseComputeOptions): UseComputeReturn<TName extends keyof ComputeFunctionRegistry ? ComputeFunctionRegistry[TName]['input'] : TInput, TName extends keyof ComputeFunctionRegistry ? ComputeFunctionRegistry[TName]['output'] : TOutput>;
147
316
  /**
148
317
  * Hook to get worker pool statistics
149
318
  *
@@ -167,5 +336,200 @@ declare function usePoolStats(refreshInterval?: number): PoolStats;
167
336
  * Hook to check WASM support
168
337
  */
169
338
  declare function useWasmSupport(): boolean;
339
+ /**
340
+ * Options for usePipeline hook
341
+ */
342
+ interface UsePipelineOptions {
343
+ /** Stop pipeline on first stage failure (default: true) */
344
+ stopOnError?: boolean;
345
+ /** Global timeout for entire pipeline in ms */
346
+ timeout?: number;
347
+ /** Enable detailed timeline tracking (default: true) */
348
+ trackTimeline?: boolean;
349
+ /** Called when pipeline state changes */
350
+ onStateChange?: (state: PipelineState) => void;
351
+ /** Called when a stage starts */
352
+ onStageStart?: (stage: StageInfo) => void;
353
+ /** Called when a stage completes */
354
+ onStageComplete?: (stage: StageInfo) => void;
355
+ /** Called when a stage fails */
356
+ onStageError?: (stage: StageInfo, error: Error) => void;
357
+ /** Called when a stage is retried */
358
+ onStageRetry?: (stage: StageInfo, attempt: number) => void;
359
+ /** Automatically run pipeline on mount */
360
+ autoRun?: boolean;
361
+ /** Initial input for autoRun */
362
+ initialInput?: unknown;
363
+ }
364
+ /**
365
+ * Actions returned by usePipeline
366
+ */
367
+ interface UsePipelineActions<TInput> {
368
+ /** Start the pipeline with input */
369
+ run: (input: TInput) => Promise<void>;
370
+ /** Cancel the running pipeline */
371
+ cancel: () => void;
372
+ /** Reset pipeline to initial state */
373
+ reset: () => void;
374
+ /** Pause the pipeline (if supported) */
375
+ pause: () => void;
376
+ /** Resume a paused pipeline */
377
+ resume: () => void;
378
+ /** Retry failed stages */
379
+ retry: () => Promise<void>;
380
+ /** Get a formatted report of the pipeline execution */
381
+ getReport: () => PipelineReport;
382
+ }
383
+ /**
384
+ * Formatted report for debugging
385
+ */
386
+ interface PipelineReport {
387
+ /** Human-readable summary */
388
+ summary: string;
389
+ /** Detailed stage-by-stage breakdown */
390
+ stageDetails: Array<{
391
+ name: string;
392
+ status: StageStatus;
393
+ duration: string;
394
+ error?: string;
395
+ }>;
396
+ /** Timeline of events */
397
+ timeline: string[];
398
+ /** Performance insights */
399
+ insights: string[];
400
+ /** Raw metrics */
401
+ metrics: PipelineMetrics;
402
+ }
403
+ /**
404
+ * Return type for usePipeline
405
+ */
406
+ type UsePipelineReturn<TInput, TOutput> = PipelineState<TInput, TOutput> & UsePipelineActions<TInput> & {
407
+ /** Whether pipeline is currently running */
408
+ isRunning: boolean;
409
+ /** Whether pipeline completed successfully */
410
+ isComplete: boolean;
411
+ /** Whether pipeline has failed */
412
+ isFailed: boolean;
413
+ /** Quick access to check if a specific stage is done */
414
+ isStageComplete: (stageId: string) => boolean;
415
+ /** Get a specific stage by ID */
416
+ getStage: (stageId: string) => StageInfo | undefined;
417
+ };
418
+ /**
419
+ * Hook for multi-stage pipeline processing
420
+ *
421
+ * Provides comprehensive debugging, progress tracking, and error handling
422
+ * for complex multi-stage compute workflows.
423
+ *
424
+ * @example
425
+ * ```tsx
426
+ * function FileProcessor() {
427
+ * const pipeline = usePipeline<string[], ProcessedFiles>([
428
+ * { id: 'download', name: 'Download Files', functionName: 'downloadFiles' },
429
+ * { id: 'process', name: 'Process Files', functionName: 'processFiles' },
430
+ * { id: 'compress', name: 'Compress Output', functionName: 'compressFiles' },
431
+ * ]);
432
+ *
433
+ * return (
434
+ * <div>
435
+ * <button onClick={() => pipeline.run(urls)} disabled={pipeline.isRunning}>
436
+ * Start Processing
437
+ * </button>
438
+ *
439
+ * <div>Status: {pipeline.status}</div>
440
+ * <div>Progress: {pipeline.progress.toFixed(0)}%</div>
441
+ *
442
+ * {pipeline.currentStage && (
443
+ * <div>Current: {pipeline.currentStage.name}</div>
444
+ * )}
445
+ *
446
+ * {pipeline.stages.map(stage => (
447
+ * <div key={stage.id}>
448
+ * {stage.name}: {stage.status}
449
+ * {stage.duration && ` (${stage.duration}ms)`}
450
+ * </div>
451
+ * ))}
452
+ *
453
+ * {pipeline.isFailed && (
454
+ * <button onClick={pipeline.retry}>Retry Failed</button>
455
+ * )}
456
+ *
457
+ * {pipeline.isComplete && (
458
+ * <pre>{JSON.stringify(pipeline.getReport(), null, 2)}</pre>
459
+ * )}
460
+ * </div>
461
+ * );
462
+ * }
463
+ * ```
464
+ */
465
+ declare function usePipeline<TInput = unknown, TOutput = unknown>(stageConfigs: StageConfig[], options?: UsePipelineOptions): UsePipelineReturn<TInput, TOutput>;
466
+ /**
467
+ * Result type for useParallelBatch
468
+ */
469
+ interface UseParallelBatchReturn<TItem, TOutput> {
470
+ /** Execute batch processing */
471
+ run: (items: TItem[]) => Promise<ParallelBatchResult<TOutput>>;
472
+ /** Current batch result */
473
+ result: ParallelBatchResult<TOutput> | null;
474
+ /** Loading state */
475
+ loading: boolean;
476
+ /** Current progress (0-100) */
477
+ progress: number;
478
+ /** Number of completed items */
479
+ completedCount: number;
480
+ /** Total items in current batch */
481
+ totalCount: number;
482
+ /** Cancel batch processing */
483
+ cancel: () => void;
484
+ /** Reset state */
485
+ reset: () => void;
486
+ }
487
+ /**
488
+ * Hook for parallel batch processing
489
+ *
490
+ * Useful for processing multiple items in parallel within a pipeline stage.
491
+ *
492
+ * @example
493
+ * ```tsx
494
+ * // Basic usage with explicit types
495
+ * function BatchProcessor() {
496
+ * const batch = useParallelBatch<string, ProcessedFile>('processFile', {
497
+ * concurrency: 4
498
+ * });
499
+ *
500
+ * return (
501
+ * <div>
502
+ * <button
503
+ * onClick={() => batch.run(fileUrls)}
504
+ * disabled={batch.loading}
505
+ * >
506
+ * Process {fileUrls.length} Files
507
+ * </button>
508
+ *
509
+ * {batch.loading && (
510
+ * <div>
511
+ * Processing: {batch.completedCount}/{batch.totalCount}
512
+ * ({batch.progress.toFixed(0)}%)
513
+ * </div>
514
+ * )}
515
+ *
516
+ * {batch.result && (
517
+ * <div>
518
+ * Success: {batch.result.successful.length}
519
+ * Failed: {batch.result.failed.length}
520
+ * </div>
521
+ * )}
522
+ * </div>
523
+ * );
524
+ * }
525
+ *
526
+ * // With typed registry - types are inferred!
527
+ * // const batch = useParallelBatch('processFile');
528
+ * ```
529
+ */
530
+ declare function useParallelBatch<TName extends RegisteredFunctionName, TItem = FunctionInput<TName extends string ? TName : never>, TOutput = FunctionOutput<TName extends string ? TName : never>>(functionName: TName, options?: {
531
+ concurrency?: number;
532
+ computeOptions?: ComputeOptions;
533
+ }): UseParallelBatchReturn<TName extends keyof ComputeFunctionRegistry ? ComputeFunctionRegistry[TName]['input'] : TItem, TName extends keyof ComputeFunctionRegistry ? ComputeFunctionRegistry[TName]['output'] : TOutput>;
170
534
 
171
- export { ComputeKitProvider, type ComputeKitProviderProps, type ComputeStatus, type UseComputeActions, type UseComputeOptions, type UseComputeReturn, type UseComputeState, useCompute, useComputeCallback, useComputeFunction, useComputeKit, usePoolStats, useWasmSupport };
535
+ export { type BatchItemResult, ComputeKitProvider, type ComputeKitProviderProps, type ComputeStatus, type ParallelBatchResult, type PipelineMetrics, type PipelineReport, type PipelineState, type PipelineStatus, type StageConfig, type StageInfo, type StageStatus, type UseComputeActions, type UseComputeOptions, type UseComputeReturn, type UseComputeState, type UseParallelBatchReturn, type UsePipelineActions, type UsePipelineOptions, type UsePipelineReturn, useCompute, useComputeCallback, useComputeFunction, useComputeKit, useParallelBatch, usePipeline, usePoolStats, useWasmSupport };