@output.ai/core 0.2.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/index.d.ts +41 -4
- package/src/interface/evaluator.js +22 -22
- package/src/interface/evaluator.spec.js +103 -0
- package/src/interface/workflow.js +44 -12
- package/src/utils/index.d.ts +34 -4
- package/src/utils/utils.js +35 -0
- package/src/utils/utils.spec.js +153 -2
package/package.json
CHANGED
package/src/index.d.ts
CHANGED
|
@@ -2,6 +2,18 @@ import type { z } from 'zod';
|
|
|
2
2
|
import type { ActivityOptions } from '@temporalio/workflow';
|
|
3
3
|
import type { SerializedFetchResponse } from './utils/index.d.ts';
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* Similar to `Partial<T>` but applies to nested properties recursively, creating a deep optional variant of `T`:
|
|
7
|
+
* - Objects: All properties become optional, recursively.
|
|
8
|
+
* - Functions: Preserved as‑is (only the property itself becomes optional).
|
|
9
|
+
* - Primitives: Returned unchanged.
|
|
10
|
+
* Useful for config overrides with strong IntelliSense on nested fields and methods.
|
|
11
|
+
*/
|
|
12
|
+
type DeepPartial<T> =
|
|
13
|
+
T extends ( ...args: any[] ) => unknown ? T : // eslint-disable-line @typescript-eslint/no-explicit-any
|
|
14
|
+
T extends object ? { [K in keyof T]?: DeepPartial<T[K]> } :
|
|
15
|
+
T;
|
|
16
|
+
|
|
5
17
|
/**
|
|
6
18
|
* Expose z from Zod as a convenience.
|
|
7
19
|
*/
|
|
@@ -211,7 +223,7 @@ export declare function step<
|
|
|
211
223
|
*
|
|
212
224
|
* Allows overriding Temporal Activity options for this workflow.
|
|
213
225
|
*/
|
|
214
|
-
export type WorkflowInvocationConfiguration = {
|
|
226
|
+
export type WorkflowInvocationConfiguration<Context extends WorkflowContext = WorkflowContext> = {
|
|
215
227
|
|
|
216
228
|
/**
|
|
217
229
|
* Native Temporal Activity options
|
|
@@ -223,6 +235,11 @@ export type WorkflowInvocationConfiguration = {
|
|
|
223
235
|
* Detached workflows called without explicitly awaiting the result are "fire-and-forget" and may outlive the parent.
|
|
224
236
|
*/
|
|
225
237
|
detached?: boolean
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Allow to overwrite properties of the "context" of workflows when called in tests environments.
|
|
241
|
+
*/
|
|
242
|
+
context?: DeepPartial<Context>
|
|
226
243
|
};
|
|
227
244
|
|
|
228
245
|
/**
|
|
@@ -265,7 +282,8 @@ export type WorkflowContext<
|
|
|
265
282
|
( input: z.infer<InputSchema> ) => ( OutputSchema extends AnyZodSchema ? z.infer<OutputSchema> : void ) :
|
|
266
283
|
() => ( OutputSchema extends AnyZodSchema ? z.infer<OutputSchema> : void ),
|
|
267
284
|
|
|
268
|
-
/**
|
|
285
|
+
/**
|
|
286
|
+
* Indicates whether the Temporal runtime suggests continuing this workflow as new.
|
|
269
287
|
*
|
|
270
288
|
* Use this to decide whether to `continueAsNew` before long waits or at loop boundaries.
|
|
271
289
|
* Prefer returning the `continueAsNew(...)` call immediately when this becomes `true`.
|
|
@@ -275,6 +293,18 @@ export type WorkflowContext<
|
|
|
275
293
|
* @returns True if a continue-as-new is suggested for the current run; otherwise false.
|
|
276
294
|
*/
|
|
277
295
|
isContinueAsNewSuggested: () => boolean
|
|
296
|
+
},
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Information about the workflow execution
|
|
300
|
+
*/
|
|
301
|
+
info: {
|
|
302
|
+
/**
|
|
303
|
+
* Internal Temporal workflow id.
|
|
304
|
+
*
|
|
305
|
+
* @see {@link https://docs.temporal.io/workflow-execution/workflowid-runid#workflow-id}
|
|
306
|
+
*/
|
|
307
|
+
workflowId: string
|
|
278
308
|
}
|
|
279
309
|
};
|
|
280
310
|
|
|
@@ -310,8 +340,10 @@ export type WorkflowFunction<
|
|
|
310
340
|
*/
|
|
311
341
|
export type WorkflowFunctionWrapper<WorkflowFunction> =
|
|
312
342
|
[Parameters<WorkflowFunction>[0]] extends [undefined | null] ?
|
|
313
|
-
( input?: undefined | null, config?: WorkflowInvocationConfiguration ) =>
|
|
314
|
-
|
|
343
|
+
( input?: undefined | null, config?: WorkflowInvocationConfiguration<Parameters<WorkflowFunction>[1]> ) =>
|
|
344
|
+
ReturnType<WorkflowFunction> :
|
|
345
|
+
( input: Parameters<WorkflowFunction>[0], config?: WorkflowInvocationConfiguration<Parameters<WorkflowFunction>[1]> ) =>
|
|
346
|
+
ReturnType<WorkflowFunction>;
|
|
315
347
|
|
|
316
348
|
/**
|
|
317
349
|
* Creates a workflow.
|
|
@@ -477,6 +509,11 @@ export class EvaluationResult {
|
|
|
477
509
|
* @returns The evaluation result reasoning
|
|
478
510
|
*/
|
|
479
511
|
get reasoning(): string;
|
|
512
|
+
|
|
513
|
+
/**
|
|
514
|
+
* @returns A zod schema representing this class
|
|
515
|
+
*/
|
|
516
|
+
get schema(): string;
|
|
480
517
|
}
|
|
481
518
|
|
|
482
519
|
/**
|
|
@@ -34,11 +34,17 @@ export class EvaluationResult {
|
|
|
34
34
|
*/
|
|
35
35
|
reasoning = undefined;
|
|
36
36
|
|
|
37
|
-
static
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
37
|
+
static get valueSchema() {
|
|
38
|
+
return z.any();
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
static get schema() {
|
|
42
|
+
return z.object( {
|
|
43
|
+
value: this.valueSchema,
|
|
44
|
+
confidence: z.number(),
|
|
45
|
+
reasoning: z.string().optional()
|
|
46
|
+
} );
|
|
47
|
+
};
|
|
42
48
|
|
|
43
49
|
/**
|
|
44
50
|
* @constructor
|
|
@@ -48,7 +54,7 @@ export class EvaluationResult {
|
|
|
48
54
|
* @param {string} [args.reasoning] - The reasoning behind the result
|
|
49
55
|
*/
|
|
50
56
|
constructor( args ) {
|
|
51
|
-
const result =
|
|
57
|
+
const result = this.constructor.schema.safeParse( args );
|
|
52
58
|
if ( result.error ) {
|
|
53
59
|
throw new EvaluationResultValidationError( z.prettifyError( result.error ) );
|
|
54
60
|
}
|
|
@@ -64,7 +70,9 @@ export class EvaluationResult {
|
|
|
64
70
|
* @property {string} value - The evaluation result value
|
|
65
71
|
*/
|
|
66
72
|
export class EvaluationStringResult extends EvaluationResult {
|
|
67
|
-
static
|
|
73
|
+
static get valueSchema() {
|
|
74
|
+
return z.string();
|
|
75
|
+
};
|
|
68
76
|
|
|
69
77
|
/**
|
|
70
78
|
* @constructor
|
|
@@ -74,10 +82,6 @@ export class EvaluationStringResult extends EvaluationResult {
|
|
|
74
82
|
* @param {string} [args.reasoning] - The reasoning behind the result
|
|
75
83
|
*/
|
|
76
84
|
constructor( args ) {
|
|
77
|
-
const result = EvaluationStringResult.#valueSchema.safeParse( args.value );
|
|
78
|
-
if ( result.error ) {
|
|
79
|
-
throw new EvaluationResultValidationError( z.prettifyError( result.error ) );
|
|
80
|
-
}
|
|
81
85
|
super( args );
|
|
82
86
|
}
|
|
83
87
|
};
|
|
@@ -88,7 +92,9 @@ export class EvaluationStringResult extends EvaluationResult {
|
|
|
88
92
|
* @property {boolean} value - The evaluation result value
|
|
89
93
|
*/
|
|
90
94
|
export class EvaluationBooleanResult extends EvaluationResult {
|
|
91
|
-
static
|
|
95
|
+
static get valueSchema() {
|
|
96
|
+
return z.boolean();
|
|
97
|
+
};
|
|
92
98
|
|
|
93
99
|
/**
|
|
94
100
|
* @constructor
|
|
@@ -98,10 +104,6 @@ export class EvaluationBooleanResult extends EvaluationResult {
|
|
|
98
104
|
* @param {string} [args.reasoning] - The reasoning behind the result
|
|
99
105
|
*/
|
|
100
106
|
constructor( args ) {
|
|
101
|
-
const result = EvaluationBooleanResult.#valueSchema.safeParse( args.value );
|
|
102
|
-
if ( result.error ) {
|
|
103
|
-
throw new EvaluationResultValidationError( z.prettifyError( result.error ) );
|
|
104
|
-
}
|
|
105
107
|
super( args );
|
|
106
108
|
}
|
|
107
109
|
};
|
|
@@ -112,7 +114,9 @@ export class EvaluationBooleanResult extends EvaluationResult {
|
|
|
112
114
|
* @property {number} value - The evaluation result value
|
|
113
115
|
*/
|
|
114
116
|
export class EvaluationNumberResult extends EvaluationResult {
|
|
115
|
-
static
|
|
117
|
+
static get valueSchema() {
|
|
118
|
+
return z.number();
|
|
119
|
+
};
|
|
116
120
|
|
|
117
121
|
/**
|
|
118
122
|
* @constructor
|
|
@@ -122,10 +126,6 @@ export class EvaluationNumberResult extends EvaluationResult {
|
|
|
122
126
|
* @param {string} [args.reasoning] - The reasoning behind the result
|
|
123
127
|
*/
|
|
124
128
|
constructor( args ) {
|
|
125
|
-
const result = EvaluationNumberResult.#valueSchema.safeParse( args.value );
|
|
126
|
-
if ( result.error ) {
|
|
127
|
-
throw new EvaluationResultValidationError( z.prettifyError( result.error ) );
|
|
128
|
-
}
|
|
129
129
|
super( args );
|
|
130
130
|
}
|
|
131
131
|
};
|
|
@@ -138,7 +138,7 @@ export function evaluator( { name, description, inputSchema, fn, options } ) {
|
|
|
138
138
|
|
|
139
139
|
const output = await fn( input );
|
|
140
140
|
|
|
141
|
-
if ( !output instanceof EvaluationResult ) {
|
|
141
|
+
if ( !( output instanceof EvaluationResult ) ) {
|
|
142
142
|
throw new ValidationError( 'Evaluators must return an EvaluationResult' );
|
|
143
143
|
}
|
|
144
144
|
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import {
|
|
3
|
+
EvaluationResult,
|
|
4
|
+
EvaluationStringResult,
|
|
5
|
+
EvaluationNumberResult,
|
|
6
|
+
EvaluationBooleanResult
|
|
7
|
+
} from './evaluator.js';
|
|
8
|
+
import { ValidationError } from '#errors';
|
|
9
|
+
|
|
10
|
+
describe( 'interface/evaluator - EvaluationResult classes', () => {
|
|
11
|
+
describe( 'class inheritance', () => {
|
|
12
|
+
it( 'subclasses extend EvaluationResult', () => {
|
|
13
|
+
const s = new EvaluationStringResult( { value: 'ok', confidence: 0.8 } );
|
|
14
|
+
const n = new EvaluationNumberResult( { value: 42, confidence: 1 } );
|
|
15
|
+
const b = new EvaluationBooleanResult( { value: true, confidence: 0.5 } );
|
|
16
|
+
|
|
17
|
+
expect( s ).toBeInstanceOf( EvaluationResult );
|
|
18
|
+
expect( n ).toBeInstanceOf( EvaluationResult );
|
|
19
|
+
expect( b ).toBeInstanceOf( EvaluationResult );
|
|
20
|
+
} );
|
|
21
|
+
} );
|
|
22
|
+
|
|
23
|
+
describe( 'constructor payload validation', () => {
|
|
24
|
+
it( 'base class validates presence and types of common fields', () => {
|
|
25
|
+
// valid
|
|
26
|
+
const base = new EvaluationResult( { value: { any: 'thing' }, confidence: 0.1 } );
|
|
27
|
+
expect( base.value ).toEqual( { any: 'thing' } );
|
|
28
|
+
expect( base.confidence ).toBe( 0.1 );
|
|
29
|
+
expect( base.reasoning ).toBeUndefined();
|
|
30
|
+
|
|
31
|
+
// invalid: missing confidence
|
|
32
|
+
expect( () => new EvaluationResult( { value: 1 } ) ).toThrow( ValidationError );
|
|
33
|
+
|
|
34
|
+
// invalid: confidence wrong type
|
|
35
|
+
expect( () => new EvaluationResult( { value: 'x', confidence: 'nope' } ) ).toThrow( ValidationError );
|
|
36
|
+
|
|
37
|
+
// invalid: reasoning wrong type
|
|
38
|
+
expect( () => new EvaluationResult( { value: 'x', confidence: 1, reasoning: 123 } ) ).toThrow( ValidationError );
|
|
39
|
+
} );
|
|
40
|
+
|
|
41
|
+
it( 'string subclass enforces string value', () => {
|
|
42
|
+
// valid
|
|
43
|
+
const r = new EvaluationStringResult( { value: 'hello', confidence: 0.9 } );
|
|
44
|
+
expect( r.value ).toBe( 'hello' );
|
|
45
|
+
|
|
46
|
+
// invalid
|
|
47
|
+
expect( () => new EvaluationStringResult( { value: 123, confidence: 0.2 } ) ).toThrow( ValidationError );
|
|
48
|
+
} );
|
|
49
|
+
|
|
50
|
+
it( 'number subclass enforces number value', () => {
|
|
51
|
+
// valid
|
|
52
|
+
const r = new EvaluationNumberResult( { value: 123, confidence: 0.2 } );
|
|
53
|
+
expect( r.value ).toBe( 123 );
|
|
54
|
+
|
|
55
|
+
// invalid
|
|
56
|
+
expect( () => new EvaluationNumberResult( { value: 'nope', confidence: 0.2 } ) ).toThrow( ValidationError );
|
|
57
|
+
} );
|
|
58
|
+
|
|
59
|
+
it( 'boolean subclass enforces boolean value', () => {
|
|
60
|
+
// valid
|
|
61
|
+
const r = new EvaluationBooleanResult( { value: true, confidence: 1 } );
|
|
62
|
+
expect( r.value ).toBe( true );
|
|
63
|
+
|
|
64
|
+
// invalid
|
|
65
|
+
expect( () => new EvaluationBooleanResult( { value: 'nope', confidence: 0.2 } ) ).toThrow( ValidationError );
|
|
66
|
+
} );
|
|
67
|
+
} );
|
|
68
|
+
|
|
69
|
+
describe( 'static schema getter', () => {
|
|
70
|
+
it( 'base schema accepts any value and optional reasoning', () => {
|
|
71
|
+
const ok = EvaluationResult.schema.safeParse( { value: 'x', confidence: 0.5, reasoning: 'why' } );
|
|
72
|
+
expect( ok.success ).toBe( true );
|
|
73
|
+
|
|
74
|
+
const ok2 = EvaluationResult.schema.safeParse( { value: 123, confidence: 0.5 } );
|
|
75
|
+
expect( ok2.success ).toBe( true );
|
|
76
|
+
} );
|
|
77
|
+
|
|
78
|
+
it( 'string schema requires value to be string', () => {
|
|
79
|
+
const ok = EvaluationStringResult.schema.safeParse( { value: 'x', confidence: 1 } );
|
|
80
|
+
expect( ok.success ).toBe( true );
|
|
81
|
+
|
|
82
|
+
const bad = EvaluationStringResult.schema.safeParse( { value: 123, confidence: 1 } );
|
|
83
|
+
expect( bad.success ).toBe( false );
|
|
84
|
+
} );
|
|
85
|
+
|
|
86
|
+
it( 'number schema requires value to be number', () => {
|
|
87
|
+
const ok = EvaluationNumberResult.schema.safeParse( { value: 10, confidence: 1 } );
|
|
88
|
+
expect( ok.success ).toBe( true );
|
|
89
|
+
|
|
90
|
+
const bad = EvaluationNumberResult.schema.safeParse( { value: '10', confidence: 1 } );
|
|
91
|
+
expect( bad.success ).toBe( false );
|
|
92
|
+
} );
|
|
93
|
+
|
|
94
|
+
it( 'boolean schema requires value to be boolean', () => {
|
|
95
|
+
const ok = EvaluationBooleanResult.schema.safeParse( { value: false, confidence: 1 } );
|
|
96
|
+
expect( ok.success ).toBe( true );
|
|
97
|
+
|
|
98
|
+
const bad = EvaluationBooleanResult.schema.safeParse( { value: 'false', confidence: 1 } );
|
|
99
|
+
expect( bad.success ).toBe( false );
|
|
100
|
+
} );
|
|
101
|
+
} );
|
|
102
|
+
} );
|
|
103
|
+
|
|
@@ -3,9 +3,41 @@ import { proxyActivities, inWorkflowContext, executeChild, workflowInfo, uuid4,
|
|
|
3
3
|
import { validateWorkflow } from './validations/static.js';
|
|
4
4
|
import { validateWithSchema } from './validations/runtime.js';
|
|
5
5
|
import { SHARED_STEP_PREFIX, ACTIVITY_GET_TRACE_DESTINATIONS } from '#consts';
|
|
6
|
-
import { mergeActivityOptions, resolveInvocationDir, setMetadata } from '#utils';
|
|
6
|
+
import { deepMerge, mergeActivityOptions, resolveInvocationDir, setMetadata } from '#utils';
|
|
7
7
|
import { FatalError, ValidationError } from '#errors';
|
|
8
8
|
|
|
9
|
+
/**
|
|
10
|
+
* Context instance builder
|
|
11
|
+
*/
|
|
12
|
+
class Context {
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Builds a new context instance
|
|
16
|
+
* @param {object} options - Arguments to build a new context instance
|
|
17
|
+
* @param {string} workflowId
|
|
18
|
+
* @param {function} continueAsNew
|
|
19
|
+
* @param {function} isContinueAsNewSuggested
|
|
20
|
+
* @returns {object} context
|
|
21
|
+
*/
|
|
22
|
+
static build( { workflowId, continueAsNew, isContinueAsNewSuggested } ) {
|
|
23
|
+
return {
|
|
24
|
+
/**
|
|
25
|
+
* Control namespace: This object adds functions to interact with Temporal flow mechanisms
|
|
26
|
+
*/
|
|
27
|
+
control: {
|
|
28
|
+
continueAsNew,
|
|
29
|
+
isContinueAsNewSuggested
|
|
30
|
+
},
|
|
31
|
+
/**
|
|
32
|
+
* Info namespace: abstracts workflowInfo()
|
|
33
|
+
*/
|
|
34
|
+
info: {
|
|
35
|
+
workflowId
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
|
|
9
41
|
const defaultActivityOptions = {
|
|
10
42
|
startToCloseTimeout: '20m',
|
|
11
43
|
retry: {
|
|
@@ -24,26 +56,26 @@ export function workflow( { name, description, inputSchema, outputSchema, fn, op
|
|
|
24
56
|
const activityOptions = mergeActivityOptions( defaultActivityOptions, options );
|
|
25
57
|
const steps = proxyActivities( activityOptions );
|
|
26
58
|
|
|
27
|
-
|
|
59
|
+
/**
|
|
60
|
+
* Wraps the `fn` function of the workflow
|
|
61
|
+
*
|
|
62
|
+
* @param {unknown} input - The input, must match the inputSchema
|
|
63
|
+
* @param {object} extra - Workflow configurations (received directly only in unit tests)
|
|
64
|
+
* @returns {unknown} The result, will match the outputSchema
|
|
65
|
+
*/
|
|
66
|
+
const wrapper = async ( input, extra = {} ) => {
|
|
28
67
|
// this returns a plain function, for example, in unit tests
|
|
29
68
|
if ( !inWorkflowContext() ) {
|
|
30
69
|
validateWithSchema( inputSchema, input, `Workflow ${name} input` );
|
|
31
|
-
const
|
|
70
|
+
const context = Context.build( { workflowId: 'test-workflow', continueAsNew: async () => {}, isContinueAsNewSuggested: () => false } );
|
|
71
|
+
const output = await fn( input, deepMerge( context, extra.context ?? {} ) );
|
|
32
72
|
validateWithSchema( outputSchema, output, `Workflow ${name} output` );
|
|
33
73
|
return output;
|
|
34
74
|
}
|
|
35
75
|
|
|
36
76
|
const { workflowId, memo, startTime } = workflowInfo();
|
|
37
77
|
|
|
38
|
-
|
|
39
|
-
- Control namespace: This object adds functions to interact with Temporal flow mechanisms
|
|
40
|
-
*/
|
|
41
|
-
const context = {
|
|
42
|
-
control: {
|
|
43
|
-
isContinueAsNewSuggested: () => workflowInfo().continueAsNewSuggested,
|
|
44
|
-
continueAsNew
|
|
45
|
-
}
|
|
46
|
-
};
|
|
78
|
+
const context = Context.build( { workflowId, continueAsNew, isContinueAsNewSuggested: () => workflowInfo().continueAsNewSuggested } );
|
|
47
79
|
|
|
48
80
|
// Root workflows will not have the execution context yet, since it is set here.
|
|
49
81
|
const isRoot = !memo.executionContext;
|
package/src/utils/index.d.ts
CHANGED
|
@@ -63,18 +63,48 @@ export type SerializedFetchResponse = {
|
|
|
63
63
|
};
|
|
64
64
|
|
|
65
65
|
/**
|
|
66
|
-
* Consumes
|
|
66
|
+
* Consumes an HTTP `Response` and serializes it to a plain object.
|
|
67
|
+
*
|
|
68
|
+
* @param response - The response to serialize.
|
|
69
|
+
* @returns SerializedFetchResponse
|
|
67
70
|
*/
|
|
68
71
|
export function serializeFetchResponse( response: Response ): SerializedFetchResponse;
|
|
69
72
|
|
|
70
73
|
export type SerializedBodyAndContentType = {
|
|
71
|
-
/** The body
|
|
74
|
+
/** The body as a string when possible; otherwise the original value */
|
|
72
75
|
body: string | unknown,
|
|
73
|
-
/** The inferred
|
|
76
|
+
/** The inferred `Content-Type` header value, if any */
|
|
74
77
|
contentType: string | undefined
|
|
75
78
|
};
|
|
76
79
|
|
|
77
80
|
/**
|
|
78
|
-
*
|
|
81
|
+
* Serializes a payload for use as a fetch POST body and infers its `Content-Type`.
|
|
82
|
+
*
|
|
83
|
+
* @param body - The payload to serialize.
|
|
84
|
+
* @returns The serialized body and inferred `Content-Type`.
|
|
79
85
|
*/
|
|
80
86
|
export function serializeBodyAndInferContentType( body: unknown ): SerializedBodyAndContentType;
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Returns true if the value is a plain object:
|
|
90
|
+
* - `{}`
|
|
91
|
+
* - `new Object()`
|
|
92
|
+
* - `Object.create(null)`
|
|
93
|
+
*
|
|
94
|
+
* @param object - The value to check.
|
|
95
|
+
* @returns Whether the value is a plain object.
|
|
96
|
+
*/
|
|
97
|
+
export function isPlainObject( object: unknown ): boolean;
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Creates a new object by merging object `b` onto object `a`, biased toward `b`:
|
|
101
|
+
* - Fields in `b` overwrite fields in `a`.
|
|
102
|
+
* - Fields in `b` that don't exist in `a` are created.
|
|
103
|
+
* - Fields in `a` that don't exist in `b` are left unchanged.
|
|
104
|
+
*
|
|
105
|
+
* @param a - The base object.
|
|
106
|
+
* @param b - The overriding object.
|
|
107
|
+
* @throws {Error} If either `a` or `b` is not a plain object.
|
|
108
|
+
* @returns A new merged object.
|
|
109
|
+
*/
|
|
110
|
+
export function deepMerge( a: object, b: object ): object;
|
package/src/utils/utils.js
CHANGED
|
@@ -7,6 +7,18 @@ import { METADATA_ACCESS_SYMBOL } from '#consts';
|
|
|
7
7
|
*/
|
|
8
8
|
export const clone = v => JSON.parse( JSON.stringify( v ) );
|
|
9
9
|
|
|
10
|
+
/**
|
|
11
|
+
* Detect a JS plain object.
|
|
12
|
+
*
|
|
13
|
+
* @param {unknown} v
|
|
14
|
+
* @returns {boolean}
|
|
15
|
+
*/
|
|
16
|
+
export const isPlainObject = v =>
|
|
17
|
+
typeof v === 'object' &&
|
|
18
|
+
!Array.isArray( v ) &&
|
|
19
|
+
v !== null &&
|
|
20
|
+
[ Object.prototype, null ].includes( Object.getPrototypeOf( v ) );
|
|
21
|
+
|
|
10
22
|
/**
|
|
11
23
|
* Throw given error
|
|
12
24
|
* @param {Error} e
|
|
@@ -149,3 +161,26 @@ export const serializeBodyAndInferContentType = payload => {
|
|
|
149
161
|
|
|
150
162
|
return { body: String( payload ), contentType: 'text/plain; charset=UTF-8' };
|
|
151
163
|
};
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Creates a new object merging object "b" onto object "a" biased to "b":
|
|
167
|
+
* - Object "b" will overwrite fields on object "a";
|
|
168
|
+
* - Object "b" fields that don't exist on object "a" will be created;
|
|
169
|
+
* - Object "a" fields that don't exist on object "b" will not be touched;
|
|
170
|
+
*
|
|
171
|
+
*
|
|
172
|
+
* @param {object} a - The base object
|
|
173
|
+
* @param {object} b - The target object
|
|
174
|
+
* @returns {object} A new object
|
|
175
|
+
*/
|
|
176
|
+
export const deepMerge = ( a, b ) => {
|
|
177
|
+
if ( !isPlainObject( a ) ) {
|
|
178
|
+
throw new Error( 'Parameter "a" is not an object.' );
|
|
179
|
+
}
|
|
180
|
+
if ( !isPlainObject( b ) ) {
|
|
181
|
+
throw new Error( 'Parameter "b" is not an object.' );
|
|
182
|
+
}
|
|
183
|
+
return Object.entries( b ).reduce( ( obj, [ k, v ] ) =>
|
|
184
|
+
Object.assign( obj, { [k]: isPlainObject( v ) && isPlainObject( a[k] ) ? deepMerge( a[k], v ) : v } )
|
|
185
|
+
, clone( a ) );
|
|
186
|
+
};
|
package/src/utils/utils.spec.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { describe, it, expect } from 'vitest';
|
|
2
2
|
import { Readable } from 'node:stream';
|
|
3
|
-
import { clone, mergeActivityOptions, serializeBodyAndInferContentType, serializeFetchResponse } from './utils.js';
|
|
4
|
-
// Response is available globally in Node 18+ (undici)
|
|
3
|
+
import { clone, mergeActivityOptions, serializeBodyAndInferContentType, serializeFetchResponse, deepMerge, isPlainObject } from './utils.js';
|
|
5
4
|
|
|
6
5
|
describe( 'clone', () => {
|
|
7
6
|
it( 'produces a deep copy without shared references', () => {
|
|
@@ -260,3 +259,155 @@ describe( 'mergeActivityOptions', () => {
|
|
|
260
259
|
} );
|
|
261
260
|
} );
|
|
262
261
|
|
|
262
|
+
describe( 'deepMerge', () => {
|
|
263
|
+
it( 'Overwrites properties in object "a"', () => {
|
|
264
|
+
const a = {
|
|
265
|
+
a: 1,
|
|
266
|
+
b: {
|
|
267
|
+
c: 2
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
const b = {
|
|
271
|
+
a: false,
|
|
272
|
+
b: {
|
|
273
|
+
c: true
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
expect( deepMerge( a, b ) ).toEqual( {
|
|
277
|
+
a: false,
|
|
278
|
+
b: {
|
|
279
|
+
c: true
|
|
280
|
+
}
|
|
281
|
+
} );
|
|
282
|
+
} );
|
|
283
|
+
|
|
284
|
+
it( 'Adds properties existing in "b" but absent in "a"', () => {
|
|
285
|
+
const a = {
|
|
286
|
+
a: 1
|
|
287
|
+
};
|
|
288
|
+
const b = {
|
|
289
|
+
a: false,
|
|
290
|
+
b: true
|
|
291
|
+
};
|
|
292
|
+
expect( deepMerge( a, b ) ).toEqual( {
|
|
293
|
+
a: false,
|
|
294
|
+
b: true
|
|
295
|
+
} );
|
|
296
|
+
} );
|
|
297
|
+
|
|
298
|
+
it( 'Keep extra properties in "a"', () => {
|
|
299
|
+
const a = {
|
|
300
|
+
a: 1
|
|
301
|
+
};
|
|
302
|
+
const b = {
|
|
303
|
+
b: true
|
|
304
|
+
};
|
|
305
|
+
expect( deepMerge( a, b ) ).toEqual( {
|
|
306
|
+
a: 1,
|
|
307
|
+
b: true
|
|
308
|
+
} );
|
|
309
|
+
} );
|
|
310
|
+
|
|
311
|
+
it( 'Throw error on non iterable object types', () => {
|
|
312
|
+
expect( () => deepMerge( Function, Function ) ).toThrow( Error );
|
|
313
|
+
expect( () => deepMerge( () => {}, () => {} ) ).toThrow( Error );
|
|
314
|
+
expect( () => deepMerge( 'a', 'a' ) ).toThrow( Error );
|
|
315
|
+
expect( () => deepMerge( true, true ) ).toThrow( Error );
|
|
316
|
+
expect( () => deepMerge( /a/, /a/ ) ).toThrow( Error );
|
|
317
|
+
expect( () => deepMerge( [], [] ) ).toThrow( Error );
|
|
318
|
+
expect( () => deepMerge( class Foo {}, class Foo {} ) ).toThrow( Error );
|
|
319
|
+
expect( () => deepMerge( Number.constructor, Number.constructor ) ).toThrow( Error );
|
|
320
|
+
expect( () => deepMerge( Number.constructor.prototype, Number.constructor.prototype ) ).toThrow( Error );
|
|
321
|
+
} );
|
|
322
|
+
} );
|
|
323
|
+
|
|
324
|
+
describe( 'isPlainObject', () => {
|
|
325
|
+
it( 'Detects plain objects', () => {
|
|
326
|
+
expect( isPlainObject( {} ) ).toBe( true );
|
|
327
|
+
expect( isPlainObject( { a: 1 } ) ).toBe( true );
|
|
328
|
+
expect( isPlainObject( new Object() ) ).toBe( true );
|
|
329
|
+
expect( isPlainObject( new Object( { foo: 'bar' } ) ) ).toBe( true );
|
|
330
|
+
expect( isPlainObject( Object.create( {}.constructor.prototype ) ) ).toBe( true );
|
|
331
|
+
expect( isPlainObject( Object.create( Object.prototype ) ) ).toBe( true );
|
|
332
|
+
} );
|
|
333
|
+
|
|
334
|
+
it( 'Detects plain objects with different prototypes than Object.prototype', () => {
|
|
335
|
+
// Object with null prototype
|
|
336
|
+
expect( isPlainObject( Object.create( null ) ) ).toBe( true );
|
|
337
|
+
} );
|
|
338
|
+
|
|
339
|
+
it( 'Detects non plain objects that had their __proto__ mutated to Object.prototype or null', () => {
|
|
340
|
+
class Foo {}
|
|
341
|
+
const x = new Foo();
|
|
342
|
+
x.__proto__ = Object.prototype;
|
|
343
|
+
expect( isPlainObject( x ) ).toBe( true );
|
|
344
|
+
|
|
345
|
+
const y = new Foo();
|
|
346
|
+
y.__proto__ = null;
|
|
347
|
+
expect( isPlainObject( y ) ).toBe( true );
|
|
348
|
+
} );
|
|
349
|
+
|
|
350
|
+
it( 'Returns false for object which the prototype is not Object.prototype or null', () => {
|
|
351
|
+
// Object which the prototype is a plain {}
|
|
352
|
+
expect( isPlainObject( Object.create( {} ) ) ).toBe( false );
|
|
353
|
+
// Object which prototype is a another object with null prototype
|
|
354
|
+
expect( isPlainObject( Object.create( Object.create( null ) ) ) ).toBe( false );
|
|
355
|
+
} );
|
|
356
|
+
|
|
357
|
+
it( 'Returns false for functions', () => {
|
|
358
|
+
expect( isPlainObject( Function ) ).toBe( false );
|
|
359
|
+
expect( isPlainObject( () => {} ) ).toBe( false );
|
|
360
|
+
expect( isPlainObject( class Foo {} ) ).toBe( false );
|
|
361
|
+
expect( isPlainObject( Number.constructor ) ).toBe( false );
|
|
362
|
+
expect( isPlainObject( Number.constructor.prototype ) ).toBe( false );
|
|
363
|
+
} );
|
|
364
|
+
|
|
365
|
+
it( 'Returns false for arrays', () => {
|
|
366
|
+
expect( isPlainObject( [ 1, 2, 3 ] ) ).toBe( false );
|
|
367
|
+
expect( isPlainObject( [] ) ).toBe( false );
|
|
368
|
+
expect( isPlainObject( Array( 3 ) ) ).toBe( false );
|
|
369
|
+
} );
|
|
370
|
+
|
|
371
|
+
it( 'Returns false for primitives', () => {
|
|
372
|
+
expect( isPlainObject( false ) ).toBe( false );
|
|
373
|
+
expect( isPlainObject( true ) ).toBe( false );
|
|
374
|
+
expect( isPlainObject( 1 ) ).toBe( false );
|
|
375
|
+
expect( isPlainObject( 0 ) ).toBe( false );
|
|
376
|
+
expect( isPlainObject( '' ) ).toBe( false );
|
|
377
|
+
expect( isPlainObject( 'foo' ) ).toBe( false );
|
|
378
|
+
expect( isPlainObject( Symbol( 'foo' ) ) ).toBe( false );
|
|
379
|
+
expect( isPlainObject( Symbol.for( 'foo' ) ) ).toBe( false );
|
|
380
|
+
} );
|
|
381
|
+
|
|
382
|
+
it( 'Returns true for built in objects', () => {
|
|
383
|
+
expect( isPlainObject( Math ) ).toBe( true );
|
|
384
|
+
expect( isPlainObject( JSON ) ).toBe( true );
|
|
385
|
+
} );
|
|
386
|
+
|
|
387
|
+
it( 'Returns false for built in types', () => {
|
|
388
|
+
expect( isPlainObject( String ) ).toBe( false );
|
|
389
|
+
expect( isPlainObject( Number ) ).toBe( false );
|
|
390
|
+
expect( isPlainObject( Date ) ).toBe( false );
|
|
391
|
+
} );
|
|
392
|
+
|
|
393
|
+
it( 'Returns false for other instance where prototype is not object or null', () => {
|
|
394
|
+
expect( isPlainObject( /foo/ ) ).toBe( false );
|
|
395
|
+
expect( isPlainObject( new RegExp( 'foo' ) ) ).toBe( false );
|
|
396
|
+
expect( isPlainObject( new Date() ) ).toBe( false );
|
|
397
|
+
class Foo {}
|
|
398
|
+
expect( isPlainObject( new Foo() ) ).toBe( false );
|
|
399
|
+
expect( isPlainObject( Object.create( ( class Foo {} ).prototype ) ) ).toBe( false );
|
|
400
|
+
} );
|
|
401
|
+
|
|
402
|
+
it( 'Returns false if tries to change the prototype to simulate an object', () => {
|
|
403
|
+
function Bar() {}
|
|
404
|
+
Bar.prototype = Object.create( null );
|
|
405
|
+
expect( isPlainObject( new Bar() ) ).toBe( false );
|
|
406
|
+
} );
|
|
407
|
+
|
|
408
|
+
it( 'Returns false if object proto was mutated to anything else than object or null', () => {
|
|
409
|
+
const zum = {};
|
|
410
|
+
zum.__proto__ = Number.prototype;
|
|
411
|
+
expect( isPlainObject( zum ) ).toBe( false );
|
|
412
|
+
} );
|
|
413
|
+
} );
|