-
Notifications
You must be signed in to change notification settings - Fork 215
Expand file tree
/
Copy pathserialization.ts
More file actions
1898 lines (1721 loc) · 61.8 KB
/
serialization.ts
File metadata and controls
1898 lines (1721 loc) · 61.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { types } from 'node:util';
import { WorkflowRuntimeError } from '@workflow/errors';
import { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE } from '@workflow/serde';
import { DevalueError, parse, stringify, unflatten } from 'devalue';
import { monotonicFactory } from 'ulid';
import { getSerializationClass } from './class-serialization.js';
import {
decrypt as aesGcmDecrypt,
encrypt as aesGcmEncrypt,
type CryptoKey,
} from './encryption.js';
/**
* Encryption key parameter type. Accepts a resolved key, undefined (no encryption),
* or a promise that resolves to either. This allows synchronous function signatures
* (e.g., getReadable()) to thread the key through without awaiting it — the promise
* is resolved lazily inside the first async transform() call.
*/
export type EncryptionKeyParam =
| CryptoKey
| undefined
| Promise<CryptoKey | undefined>;
import {
createFlushableState,
flushablePipe,
pollReadableLock,
pollWritableLock,
} from './flushable-stream.js';
import { runtimeLogger } from './logger.js';
import { getStepFunction } from './private.js';
import { getWorld } from './runtime/world.js';
import { contextStorage } from './step/context-storage.js';
import {
BODY_INIT_SYMBOL,
STABLE_ULID,
STREAM_NAME_SYMBOL,
STREAM_TYPE_SYMBOL,
WEBHOOK_RESPONSE_WRITABLE,
} from './symbols.js';
// ============================================================================
// Serialization Format Prefix System
// ============================================================================
//
// All serialized payloads are prefixed with a 4-byte format identifier that
// allows the client to determine how to decode the payload. This enables:
//
// 1. Self-describing payloads - The World layer is agnostic to serialization format
// 2. Gradual migration - Old runs keep working, new runs can use new formats
// 3. Composability - Encryption can wrap any format (e.g., "encr" wrapping "devl")
// 4. Debugging - Raw data inspection immediately reveals the format
//
// Format: [4 bytes: format identifier][payload]
//
// The 4-character prefix convention matches other workflow IDs (wrun, step, wait, etc.)
//
// Current formats:
// - "devl" - devalue stringify/parse with TextEncoder/TextDecoder (current default)
// - "encr" - Encrypted payload (inner payload has its own format prefix)
//
// Future formats (reserved):
// - "cbor" - CBOR binary serialization
/**
* Known serialization format identifiers.
* Each format ID is exactly 4 ASCII characters, matching the convention
* used for other workflow IDs (wrun, step, wait, etc.)
*/
export const SerializationFormat = {
/** devalue stringify/parse with TextEncoder/TextDecoder */
DEVALUE_V1: 'devl',
/** Encrypted payload (inner payload has its own format prefix) */
ENCRYPTED: 'encr',
} as const;
export type SerializationFormatType =
(typeof SerializationFormat)[keyof typeof SerializationFormat];
/** Length of the format prefix in bytes */
const FORMAT_PREFIX_LENGTH = 4;
/** TextEncoder instance for format prefix encoding */
const formatEncoder = new TextEncoder();
/** TextDecoder instance for format prefix decoding */
const formatDecoder = new TextDecoder();
/**
* Encode a payload with a format prefix.
*
* @param format - The format identifier (must be exactly 4 ASCII characters)
* @param payload - The serialized payload bytes
* @returns A new Uint8Array with format prefix prepended
*/
export function encodeWithFormatPrefix(
format: SerializationFormatType,
payload: Uint8Array | unknown
): Uint8Array | unknown {
if (!(payload instanceof Uint8Array)) {
return payload;
}
const prefixBytes = formatEncoder.encode(format);
if (prefixBytes.length !== FORMAT_PREFIX_LENGTH) {
throw new Error(
`Format identifier must be exactly ${FORMAT_PREFIX_LENGTH} ASCII characters, got "${format}" (${prefixBytes.length} bytes)`
);
}
const result = new Uint8Array(FORMAT_PREFIX_LENGTH + payload.length);
result.set(prefixBytes, 0);
result.set(payload, FORMAT_PREFIX_LENGTH);
return result;
}
/**
* Peek at the format prefix without consuming it.
* Useful for checking if data is encrypted before deciding how to process it.
*
* @param data - The format-prefixed data
* @returns The format identifier, or null if data is legacy/non-binary
*/
export function peekFormatPrefix(
data: Uint8Array | unknown
): SerializationFormatType | null {
if (!(data instanceof Uint8Array) || data.length < FORMAT_PREFIX_LENGTH) {
return null;
}
const prefixBytes = data.subarray(0, FORMAT_PREFIX_LENGTH);
const format = formatDecoder.decode(prefixBytes);
const knownFormats = Object.values(SerializationFormat) as string[];
if (!knownFormats.includes(format)) {
return null;
}
return format as SerializationFormatType;
}
/**
* Check if data is encrypted (has 'encr' format prefix).
*
* @param data - The format-prefixed data
* @returns true if data has the encrypted format prefix
*/
export function isEncrypted(data: Uint8Array | unknown): boolean {
return peekFormatPrefix(data) === SerializationFormat.ENCRYPTED;
}
/**
* Decode a format-prefixed payload.
*
* @param data - The format-prefixed data
* @returns An object with the format identifier and payload
* @throws Error if the data is too short or has an unknown format
*/
export function decodeFormatPrefix(data: Uint8Array | unknown): {
format: SerializationFormatType;
payload: Uint8Array;
} {
// Compat for legacy specVersion 1 runs that don't have a format prefix,
// and don't have a binary payload
if (!(data instanceof Uint8Array)) {
return {
format: SerializationFormat.DEVALUE_V1,
payload: new TextEncoder().encode(JSON.stringify(data)),
};
}
if (data.length < FORMAT_PREFIX_LENGTH) {
throw new Error(
`Data too short to contain format prefix: expected at least ${FORMAT_PREFIX_LENGTH} bytes, got ${data.length}`
);
}
const prefixBytes = data.subarray(0, FORMAT_PREFIX_LENGTH);
const format = formatDecoder.decode(prefixBytes);
// Validate the format is known
const knownFormats = Object.values(SerializationFormat) as string[];
if (!knownFormats.includes(format)) {
throw new WorkflowRuntimeError(
`Unknown serialization format: "${format}". Known formats: ${knownFormats.join(', ')}`
);
}
const payload = data.subarray(FORMAT_PREFIX_LENGTH);
return { format: format as SerializationFormatType, payload };
}
/**
* Default ULID generator for contexts where VM's seeded `stableUlid` isn't available.
* Used as a fallback when serializing streams outside the workflow VM context
* (e.g., when starting a workflow or handling step return values).
*/
const defaultUlid = monotonicFactory();
/**
* Format a serialization error with context about what failed.
* Extracts path, value, and reason from devalue's DevalueError when available.
* Logs the problematic value to the console for better debugging.
*/
function formatSerializationError(context: string, error: unknown): string {
// Use "returning" for return values, "passing" for arguments/inputs
const verb = context.includes('return value') ? 'returning' : 'passing';
// Build the error message with path info if available from DevalueError
let message = `Failed to serialize ${context}`;
if (error instanceof DevalueError && error.path) {
message += ` at path "${error.path}"`;
}
message += `. Ensure you're ${verb} serializable types (plain objects, arrays, primitives, Date, RegExp, Map, Set).`;
// Log the problematic value for debugging
if (error instanceof DevalueError && error.value !== undefined) {
runtimeLogger.error('Serialization failed', {
context,
problematicValue: error.value,
});
}
return message;
}
/**
* Detect if a readable stream is a byte stream.
*
* @param stream
* @returns `"bytes"` if the stream is a byte stream, `undefined` otherwise
*/
export function getStreamType(stream: ReadableStream): 'bytes' | undefined {
try {
const reader = stream.getReader({ mode: 'byob' });
reader.releaseLock();
return 'bytes';
} catch {}
}
/**
* Frame format for stream chunks:
* [4-byte big-endian length][format-prefixed payload]
*
* Each chunk is independently framed so the deserializer can find
* chunk boundaries even when multiple chunks are concatenated or
* split across transport reads.
*/
const FRAME_HEADER_SIZE = 4;
export function getSerializeStream(
reducers: Reducers,
cryptoKey: EncryptionKeyParam
): TransformStream<any, Uint8Array> {
const encoder = new TextEncoder();
// Resolve the key promise once on first use and cache the result.
// Note: if the cryptoKey promise rejects (e.g., network error fetching
// the derived key), the rejection won't surface until the first chunk
// is processed — not at stream construction time.
const keyState = { resolved: false, key: undefined as CryptoKey | undefined };
const stream = new TransformStream<any, Uint8Array>({
async transform(chunk, controller) {
try {
if (!keyState.resolved) {
keyState.key = await cryptoKey;
keyState.resolved = true;
}
const serialized = stringify(chunk, reducers);
const payload = encoder.encode(serialized);
let prefixed = encodeWithFormatPrefix(
SerializationFormat.DEVALUE_V1,
payload
) as Uint8Array;
// Encrypt the frame payload if a key is provided.
// The length header remains in the clear so the deserializer can
// find frame boundaries regardless of transport chunking.
if (keyState.key) {
const encrypted = await aesGcmEncrypt(keyState.key, prefixed);
prefixed = encodeWithFormatPrefix(
SerializationFormat.ENCRYPTED,
encrypted
) as Uint8Array;
}
// Write length-prefixed frame: [4-byte length][prefixed data]
const frame = new Uint8Array(FRAME_HEADER_SIZE + prefixed.length);
new DataView(frame.buffer).setUint32(0, prefixed.length, false);
frame.set(prefixed, FRAME_HEADER_SIZE);
controller.enqueue(frame);
} catch (error) {
controller.error(
new WorkflowRuntimeError(
formatSerializationError('stream chunk', error),
{ slug: 'serialization-failed', cause: error }
)
);
}
},
});
return stream;
}
export function getDeserializeStream(
revivers: Revivers,
cryptoKey: EncryptionKeyParam
): TransformStream<Uint8Array, any> {
const decoder = new TextDecoder();
let buffer = new Uint8Array(0);
// Resolve the key promise once on first use and cache the result.
const keyState = { resolved: false, key: undefined as CryptoKey | undefined };
function appendToBuffer(data: Uint8Array) {
const newBuffer = new Uint8Array(buffer.length + data.length);
newBuffer.set(buffer, 0);
newBuffer.set(data, buffer.length);
buffer = newBuffer;
}
async function processFrames(
controller: TransformStreamDefaultController<any>
) {
// Resolve the key promise once on first use and cache the result
if (!keyState.resolved) {
keyState.key = await cryptoKey;
keyState.resolved = true;
}
// Try to extract complete length-prefixed frames
while (buffer.length >= FRAME_HEADER_SIZE) {
const frameLength = new DataView(
buffer.buffer,
buffer.byteOffset,
buffer.byteLength
).getUint32(0, false);
if (buffer.length < FRAME_HEADER_SIZE + frameLength) {
break; // Incomplete frame, wait for more data
}
const frameData = buffer.slice(
FRAME_HEADER_SIZE,
FRAME_HEADER_SIZE + frameLength
);
buffer = buffer.slice(FRAME_HEADER_SIZE + frameLength);
let { format, payload } = decodeFormatPrefix(frameData);
// If the frame payload is encrypted, decrypt it first to reveal
// the inner format-prefixed data (e.g., 'devl' + serialized text),
// then fall through to the normal deserialization path.
if (format === SerializationFormat.ENCRYPTED) {
if (!keyState.key) {
controller.error(
new WorkflowRuntimeError(
'Encrypted stream data encountered but no encryption key is available. ' +
'Encryption is not configured or no key was provided for this run.'
)
);
return;
}
const decrypted = await aesGcmDecrypt(keyState.key, payload);
({ format, payload } = decodeFormatPrefix(decrypted));
}
if (format === SerializationFormat.DEVALUE_V1) {
const text = decoder.decode(payload);
controller.enqueue(parse(text, revivers));
}
}
}
const stream = new TransformStream<Uint8Array, any>({
async transform(chunk, controller) {
// First, try to detect if this is length-prefixed framed data
// by checking if the first 4 bytes form a plausible length.
if (buffer.length === 0 && chunk.length >= FRAME_HEADER_SIZE) {
const possibleLength = new DataView(
chunk.buffer,
chunk.byteOffset,
chunk.byteLength
).getUint32(0, false);
if (
possibleLength > 0 &&
possibleLength < 100_000_000 // sanity check: < 100MB
) {
// Looks like framed data
appendToBuffer(chunk);
await processFrames(controller);
return;
}
} else if (buffer.length > 0) {
// Already in framed mode (have buffered data)
appendToBuffer(chunk);
await processFrames(controller);
return;
}
// Legacy format: newline-delimited devalue text (no framing)
const text = decoder.decode(chunk);
const lines = text.split('\n');
for (const line of lines) {
if (line.length > 0) {
controller.enqueue(parse(line, revivers));
}
}
},
async flush(controller) {
// Process any remaining framed data
if (buffer.length > 0) {
await processFrames(controller);
}
},
});
return stream;
}
export class WorkflowServerReadableStream extends ReadableStream<Uint8Array> {
#reader?: ReadableStreamDefaultReader<Uint8Array>;
constructor(name: string, startIndex?: number) {
if (typeof name !== 'string' || name.length === 0) {
throw new Error(`"name" is required, got "${name}"`);
}
super({
// @ts-expect-error Not sure why TypeScript is complaining about this
type: 'bytes',
pull: async (controller) => {
let reader = this.#reader;
if (!reader) {
const world = getWorld();
const stream = await world.readFromStream(name, startIndex);
reader = this.#reader = stream.getReader();
}
if (!reader) {
controller.error(new Error('Failed to get reader'));
return;
}
const result = await reader.read();
if (result.done) {
this.#reader = undefined;
controller.close();
} else {
// Forward raw bytes; encryption/decryption is handled at the
// framing level by getSerializeStream/getDeserializeStream.
controller.enqueue(result.value);
}
},
cancel: async (reason) => {
if (this.#reader) {
await this.#reader.cancel(reason).catch(() => {});
this.#reader = undefined;
}
},
});
}
}
/**
* Default flush interval in milliseconds for buffered stream writes.
* Chunks are accumulated and flushed together to reduce network overhead.
*/
const STREAM_FLUSH_INTERVAL_MS = 10;
export class WorkflowServerWritableStream extends WritableStream<Uint8Array> {
constructor(name: string, runId: string) {
if (typeof runId !== 'string') {
throw new Error(`"runId" must be a string, got "${typeof runId}"`);
}
if (typeof name !== 'string' || name.length === 0) {
throw new Error(`"name" is required, got "${name}"`);
}
const world = getWorld();
// Buffering state for batched writes
// Encryption/decryption is handled at the framing level by
// getSerializeStream/getDeserializeStream, not here.
let buffer: Uint8Array[] = [];
let flushTimer: ReturnType<typeof setTimeout> | null = null;
let flushPromise: Promise<void> | null = null;
const flush = async (): Promise<void> => {
if (flushTimer) {
clearTimeout(flushTimer);
flushTimer = null;
}
if (buffer.length === 0) return;
// Copy chunks to flush, but don't clear buffer until write succeeds
// This prevents data loss if the write operation fails
const chunksToFlush = buffer.slice();
// Use writeToStreamMulti if available for batch writes
if (
typeof world.writeToStreamMulti === 'function' &&
chunksToFlush.length > 1
) {
await world.writeToStreamMulti(name, runId, chunksToFlush);
} else {
// Fall back to sequential writes
for (const chunk of chunksToFlush) {
await world.writeToStream(name, runId, chunk);
}
}
// Only clear buffer after successful write to prevent data loss
buffer = [];
};
const scheduleFlush = (): void => {
if (flushTimer) return; // Already scheduled
flushTimer = setTimeout(() => {
flushTimer = null;
flushPromise = flush();
}, STREAM_FLUSH_INTERVAL_MS);
};
super({
async write(chunk) {
// Wait for any in-progress flush to complete before adding to buffer
if (flushPromise) {
await flushPromise;
flushPromise = null;
}
buffer.push(chunk);
scheduleFlush();
},
async close() {
// Wait for any in-progress flush to complete
if (flushPromise) {
await flushPromise;
flushPromise = null;
}
// Flush any remaining buffered chunks
await flush();
await world.closeStream(name, runId);
},
abort() {
// Clean up timer to prevent leaks
if (flushTimer) {
clearTimeout(flushTimer);
flushTimer = null;
}
// Discard buffered chunks - they won't be written
buffer = [];
},
});
}
}
// Types that need specialized handling when serialized/deserialized
// ! If a type is added here, it MUST also be added to the `Serializable` type in `schemas.ts`
export interface SerializableSpecial {
ArrayBuffer: string; // base64 string
BigInt: string; // string representation of bigint
BigInt64Array: string; // base64 string
BigUint64Array: string; // base64 string
Date: string; // ISO string
Float32Array: string; // base64 string
Float64Array: string; // base64 string
Error: Record<string, any>;
Headers: [string, string][];
Int8Array: string; // base64 string
Int16Array: string; // base64 string
Int32Array: string; // base64 string
Map: [any, any][];
ReadableStream:
| { name: string; type?: 'bytes'; startIndex?: number }
| { bodyInit: any };
RegExp: { source: string; flags: string };
Request: {
method: string;
url: string;
headers: Headers;
body: Request['body'];
duplex: Request['duplex'];
// This is specifically for the `RequestWithResponse` type which is used for webhooks
responseWritable?: WritableStream<Response>;
};
Response: {
type: Response['type'];
url: string;
status: number;
statusText: string;
headers: Headers;
body: Response['body'];
redirected: boolean;
};
Class: {
classId: string;
};
/**
* Custom serialized class instance.
* The class must have a `classId` property and be registered for deserialization.
*/
Instance: {
classId: string; // Unique identifier for the class (used for lookup during deserialization)
data: unknown; // The serialized instance data
};
Set: any[];
StepFunction: {
stepId: string;
closureVars?: Record<string, any>;
};
URL: string;
URLSearchParams: string;
Uint8Array: string; // base64 string
Uint8ClampedArray: string; // base64 string
Uint16Array: string; // base64 string
Uint32Array: string; // base64 string
WritableStream: { name: string };
}
type Reducers = {
[K in keyof SerializableSpecial]: (
value: any
) => SerializableSpecial[K] | false;
};
type Revivers = {
[K in keyof SerializableSpecial]: (value: SerializableSpecial[K]) => any;
};
function revive(str: string) {
// biome-ignore lint/security/noGlobalEval: Eval is safe here - we are only passing value from `devalue.stringify()`
// biome-ignore lint/complexity/noCommaOperator: This is how you do global scope eval
return (0, eval)(`(${str})`);
}
function getCommonReducers(global: Record<string, any> = globalThis) {
const abToBase64 = (
value: ArrayBufferLike,
offset: number,
length: number
) => {
// Avoid returning falsy value for zero-length buffers
if (length === 0) return '.';
// Create a proper copy to avoid ArrayBuffer detachment issues
// Buffer.from(ArrayBuffer, offset, length) creates a view, not a copy
const uint8 = new Uint8Array(value, offset, length);
return Buffer.from(uint8).toString('base64');
};
const viewToBase64 = (value: ArrayBufferView) =>
abToBase64(value.buffer, value.byteOffset, value.byteLength);
return {
ArrayBuffer: (value) =>
value instanceof global.ArrayBuffer &&
abToBase64(value, 0, value.byteLength),
BigInt: (value) => typeof value === 'bigint' && value.toString(),
BigInt64Array: (value) =>
value instanceof global.BigInt64Array && viewToBase64(value),
BigUint64Array: (value) =>
value instanceof global.BigUint64Array && viewToBase64(value),
// Class and Instance are intentionally placed before Error so that
// custom Error subclasses with WORKFLOW_SERIALIZE take precedence
// over the generic Error serialization (devalue uses first-match-wins).
Class: (value) => {
// Check if this is a class constructor with a classId property
// (set by the SWC plugin for classes with static step/workflow methods)
if (typeof value !== 'function') return false;
const classId = (value as any).classId;
if (typeof classId !== 'string') return false;
return { classId };
},
Instance: (value) => {
// Check if this is an instance of a class with custom serialization
if (value === null || typeof value !== 'object') return false;
const cls = value.constructor;
if (!cls || typeof cls !== 'function') return false;
// Check if the class has a static WORKFLOW_SERIALIZE method
const serialize = cls[WORKFLOW_SERIALIZE];
if (typeof serialize !== 'function') {
return false;
}
// Get the classId from the static class property (set by SWC plugin)
const classId = cls.classId;
if (typeof classId !== 'string') {
throw new Error(
`Class "${cls.name}" with ${String(WORKFLOW_SERIALIZE)} must have a static "classId" property.`
);
}
// Serialize the instance using the custom serializer
const data = serialize.call(cls, value);
return { classId, data };
},
Date: (value) => {
if (!(value instanceof global.Date)) return false;
const valid = !Number.isNaN(value.getDate());
// Note: "." is to avoid returning a falsy value when the date is invalid
return valid ? value.toISOString() : '.';
},
Error: (value) => {
// Use types.isNativeError() instead of `instanceof global.Error`
// because errors may originate from a different VM context (e.g.
// FatalError from the host context passed into a VM-context workflow).
// `instanceof` checks fail across VM boundaries since each context
// has its own Error constructor, but isNativeError() uses V8's
// internal type tag which works across all contexts.
if (!types.isNativeError(value)) return false;
return {
name: value.name,
message: value.message,
stack: value.stack,
};
},
Float32Array: (value) =>
value instanceof global.Float32Array && viewToBase64(value),
Float64Array: (value) =>
value instanceof global.Float64Array && viewToBase64(value),
Headers: (value) => value instanceof global.Headers && Array.from(value),
Int8Array: (value) =>
value instanceof global.Int8Array && viewToBase64(value),
Int16Array: (value) =>
value instanceof global.Int16Array && viewToBase64(value),
Int32Array: (value) =>
value instanceof global.Int32Array && viewToBase64(value),
Map: (value) => value instanceof global.Map && Array.from(value),
RegExp: (value) =>
value instanceof global.RegExp && {
source: value.source,
flags: value.flags,
},
Request: (value) => {
if (!(value instanceof global.Request)) return false;
const data: SerializableSpecial['Request'] = {
method: value.method,
url: value.url,
headers: value.headers,
body: value.body,
duplex: value.duplex,
};
const responseWritable = value[WEBHOOK_RESPONSE_WRITABLE];
if (responseWritable) {
data.responseWritable = responseWritable;
}
return data;
},
Response: (value) => {
if (!(value instanceof global.Response)) return false;
return {
type: value.type,
url: value.url,
status: value.status,
statusText: value.statusText,
headers: value.headers,
body: value.body,
redirected: value.redirected,
};
},
Set: (value) => value instanceof global.Set && Array.from(value),
StepFunction: (value) => {
if (typeof value !== 'function') return false;
const stepId = (value as any).stepId;
if (typeof stepId !== 'string') return false;
// Check if the step function has closure variables
const closureVarsFn = (value as any).__closureVarsFn;
if (closureVarsFn && typeof closureVarsFn === 'function') {
// Invoke the closure variables function and serialize along with stepId
const closureVars = closureVarsFn();
return { stepId, closureVars };
}
// No closure variables - return object with just stepId
return { stepId };
},
URL: (value) => value instanceof global.URL && value.href,
URLSearchParams: (value) => {
if (!(value instanceof global.URLSearchParams)) return false;
// Avoid returning a falsy value when the URLSearchParams is empty
if (value.size === 0) return '.';
return String(value);
},
Uint8Array: (value) =>
value instanceof global.Uint8Array && viewToBase64(value),
Uint8ClampedArray: (value) =>
value instanceof global.Uint8ClampedArray && viewToBase64(value),
Uint16Array: (value) =>
value instanceof global.Uint16Array && viewToBase64(value),
Uint32Array: (value) =>
value instanceof global.Uint32Array && viewToBase64(value),
} as const satisfies Partial<Reducers>;
}
/**
* Reducers for serialization boundary from the client side, passing arguments
* to the workflow handler.
*
* @param global
* @param ops
* @returns
*/
export function getExternalReducers(
global: Record<string, any> = globalThis,
ops: Promise<void>[],
runId: string,
cryptoKey: EncryptionKeyParam
): Reducers {
return {
...getCommonReducers(global),
ReadableStream: (value) => {
if (!(value instanceof global.ReadableStream)) return false;
// Stream must not be locked when passing across execution boundary
if (value.locked) {
throw new Error('ReadableStream is locked');
}
const streamId = ((global as any)[STABLE_ULID] || defaultUlid)();
const name = `strm_${streamId}`;
const type = getStreamType(value);
const writable = new WorkflowServerWritableStream(name, runId);
if (type === 'bytes') {
ops.push(value.pipeTo(writable));
} else {
ops.push(
value
.pipeThrough(
getSerializeStream(
getExternalReducers(global, ops, runId, cryptoKey),
cryptoKey
)
)
.pipeTo(writable)
);
}
const s: SerializableSpecial['ReadableStream'] = { name };
if (type) s.type = type;
return s;
},
WritableStream: (value) => {
if (!(value instanceof global.WritableStream)) return false;
const streamId = ((global as any)[STABLE_ULID] || defaultUlid)();
const name = `strm_${streamId}`;
const readable = new WorkflowServerReadableStream(name);
ops.push(readable.pipeTo(value));
return { name };
},
};
}
/**
* Reducers for serialization boundary from within the workflow execution
* environment, passing return value to the client side and into step arguments.
*
* @param global
* @returns
*/
export function getWorkflowReducers(
global: Record<string, any> = globalThis
): Reducers {
return {
...getCommonReducers(global),
// Readable/Writable streams from within the workflow execution environment
// are simply "handles" that can be passed around to other steps.
ReadableStream: (value) => {
if (!(value instanceof global.ReadableStream)) return false;
// Check if this is a fake stream storing BodyInit from Request/Response constructor
const bodyInit = value[BODY_INIT_SYMBOL];
if (bodyInit !== undefined) {
// This is a fake stream - serialize the BodyInit directly
// devalue will handle serializing strings, Uint8Array, etc.
return { bodyInit };
}
const name = value[STREAM_NAME_SYMBOL];
if (!name) {
throw new Error('ReadableStream `name` is not set');
}
const s: SerializableSpecial['ReadableStream'] = { name };
const type = value[STREAM_TYPE_SYMBOL];
if (type) s.type = type;
return s;
},
WritableStream: (value) => {
if (!(value instanceof global.WritableStream)) return false;
const name = value[STREAM_NAME_SYMBOL];
if (!name) {
throw new Error('WritableStream `name` is not set');
}
return { name };
},
};
}
/**
* Reducers for serialization boundary from within the step execution
* environment, passing return value to the workflow handler.
*
* @param global
* @param ops
* @param runId
* @returns
*/
function getStepReducers(
global: Record<string, any> = globalThis,
ops: Promise<void>[],
runId: string,
cryptoKey: EncryptionKeyParam
): Reducers {
return {
...getCommonReducers(global),
ReadableStream: (value) => {
if (!(value instanceof global.ReadableStream)) return false;
// Stream must not be locked when passing across execution boundary
if (value.locked) {
throw new Error('ReadableStream is locked');
}
// Check if the stream already has the name symbol set, in which case
// it's already being sunk to the server and we can just return the
// name and type.
let name = value[STREAM_NAME_SYMBOL];
let type = value[STREAM_TYPE_SYMBOL];
if (!name) {
const streamId = ((global as any)[STABLE_ULID] || defaultUlid)();
name = `strm_${streamId}`;
type = getStreamType(value);
const writable = new WorkflowServerWritableStream(name, runId);
if (type === 'bytes') {
ops.push(value.pipeTo(writable));
} else {
ops.push(
value
.pipeThrough(
getSerializeStream(
getStepReducers(global, ops, runId, cryptoKey),
cryptoKey
)
)
.pipeTo(writable)
);
}
}
const s: SerializableSpecial['ReadableStream'] = { name };
if (type) s.type = type;
return s;
},
WritableStream: (value) => {
if (!(value instanceof global.WritableStream)) return false;
let name = value[STREAM_NAME_SYMBOL];
if (!name) {
const streamId = ((global as any)[STABLE_ULID] || defaultUlid)();
name = `strm_${streamId}`;
ops.push(
new WorkflowServerReadableStream(name)
.pipeThrough(
getDeserializeStream(
getStepRevivers(global, ops, runId, cryptoKey),
cryptoKey
)
)
.pipeTo(value)
);
}
return { name };
},
};
}
export function getCommonRevivers(global: Record<string, any> = globalThis) {
function reviveArrayBuffer(value: string) {
// Handle sentinel value for zero-length buffers
const base64 = value === '.' ? '' : value;
const buffer = Buffer.from(base64, 'base64');
const arrayBuffer = new global.ArrayBuffer(buffer.length);
const uint8Array = new global.Uint8Array(arrayBuffer);
uint8Array.set(buffer);
return arrayBuffer;
}
return {
ArrayBuffer: reviveArrayBuffer,