tywrap 0.2.0 → 0.3.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.
Files changed (163) hide show
  1. package/README.md +65 -31
  2. package/dist/cli.js +49 -2
  3. package/dist/cli.js.map +1 -1
  4. package/dist/config/index.d.ts +11 -7
  5. package/dist/config/index.d.ts.map +1 -1
  6. package/dist/config/index.js +43 -7
  7. package/dist/config/index.js.map +1 -1
  8. package/dist/core/analyzer.d.ts +1 -0
  9. package/dist/core/analyzer.d.ts.map +1 -1
  10. package/dist/core/analyzer.js +47 -12
  11. package/dist/core/analyzer.js.map +1 -1
  12. package/dist/core/annotation-parser.d.ts +8 -0
  13. package/dist/core/annotation-parser.d.ts.map +1 -0
  14. package/dist/core/annotation-parser.js +409 -0
  15. package/dist/core/annotation-parser.js.map +1 -0
  16. package/dist/core/discovery.d.ts +1 -0
  17. package/dist/core/discovery.d.ts.map +1 -1
  18. package/dist/core/discovery.js +9 -9
  19. package/dist/core/discovery.js.map +1 -1
  20. package/dist/core/generator.d.ts +9 -1
  21. package/dist/core/generator.d.ts.map +1 -1
  22. package/dist/core/generator.js +738 -104
  23. package/dist/core/generator.js.map +1 -1
  24. package/dist/core/mapper.d.ts +9 -7
  25. package/dist/core/mapper.d.ts.map +1 -1
  26. package/dist/core/mapper.js +129 -44
  27. package/dist/core/mapper.js.map +1 -1
  28. package/dist/index.d.ts +23 -7
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +23 -3
  31. package/dist/index.js.map +1 -1
  32. package/dist/runtime/base.d.ts +17 -7
  33. package/dist/runtime/base.d.ts.map +1 -1
  34. package/dist/runtime/base.js +18 -1
  35. package/dist/runtime/base.js.map +1 -1
  36. package/dist/runtime/bounded-context.d.ts +252 -0
  37. package/dist/runtime/bounded-context.d.ts.map +1 -0
  38. package/dist/runtime/bounded-context.js +454 -0
  39. package/dist/runtime/bounded-context.js.map +1 -0
  40. package/dist/runtime/bridge-core.d.ts +1 -0
  41. package/dist/runtime/bridge-core.d.ts.map +1 -1
  42. package/dist/runtime/bridge-core.js +52 -17
  43. package/dist/runtime/bridge-core.js.map +1 -1
  44. package/dist/runtime/bridge-protocol.d.ts +184 -0
  45. package/dist/runtime/bridge-protocol.d.ts.map +1 -0
  46. package/dist/runtime/bridge-protocol.js +344 -0
  47. package/dist/runtime/bridge-protocol.js.map +1 -0
  48. package/dist/runtime/disposable.d.ts +40 -0
  49. package/dist/runtime/disposable.d.ts.map +1 -0
  50. package/dist/runtime/disposable.js +49 -0
  51. package/dist/runtime/disposable.js.map +1 -0
  52. package/dist/runtime/errors.d.ts +10 -0
  53. package/dist/runtime/errors.d.ts.map +1 -1
  54. package/dist/runtime/errors.js +9 -0
  55. package/dist/runtime/errors.js.map +1 -1
  56. package/dist/runtime/http-io.d.ts +91 -0
  57. package/dist/runtime/http-io.d.ts.map +1 -0
  58. package/dist/runtime/http-io.js +195 -0
  59. package/dist/runtime/http-io.js.map +1 -0
  60. package/dist/runtime/http.d.ts +48 -13
  61. package/dist/runtime/http.d.ts.map +1 -1
  62. package/dist/runtime/http.js +60 -73
  63. package/dist/runtime/http.js.map +1 -1
  64. package/dist/runtime/node.d.ts +97 -130
  65. package/dist/runtime/node.d.ts.map +1 -1
  66. package/dist/runtime/node.js +392 -521
  67. package/dist/runtime/node.js.map +1 -1
  68. package/dist/runtime/optimized-node.d.ts +1 -1
  69. package/dist/runtime/optimized-node.d.ts.map +1 -1
  70. package/dist/runtime/optimized-node.js +1 -1
  71. package/dist/runtime/optimized-node.js.map +1 -1
  72. package/dist/runtime/pooled-transport.d.ts +135 -0
  73. package/dist/runtime/pooled-transport.d.ts.map +1 -0
  74. package/dist/runtime/pooled-transport.js +177 -0
  75. package/dist/runtime/pooled-transport.js.map +1 -0
  76. package/dist/runtime/process-io.d.ts +209 -0
  77. package/dist/runtime/process-io.d.ts.map +1 -0
  78. package/dist/runtime/process-io.js +729 -0
  79. package/dist/runtime/process-io.js.map +1 -0
  80. package/dist/runtime/pyodide-io.d.ts +154 -0
  81. package/dist/runtime/pyodide-io.d.ts.map +1 -0
  82. package/dist/runtime/pyodide-io.js +459 -0
  83. package/dist/runtime/pyodide-io.js.map +1 -0
  84. package/dist/runtime/pyodide.d.ts +51 -19
  85. package/dist/runtime/pyodide.d.ts.map +1 -1
  86. package/dist/runtime/pyodide.js +57 -186
  87. package/dist/runtime/pyodide.js.map +1 -1
  88. package/dist/runtime/safe-codec.d.ts +103 -0
  89. package/dist/runtime/safe-codec.d.ts.map +1 -0
  90. package/dist/runtime/safe-codec.js +519 -0
  91. package/dist/runtime/safe-codec.js.map +1 -0
  92. package/dist/runtime/transport.d.ts +191 -0
  93. package/dist/runtime/transport.d.ts.map +1 -0
  94. package/dist/runtime/transport.js +86 -0
  95. package/dist/runtime/transport.js.map +1 -0
  96. package/dist/runtime/validators.d.ts +120 -0
  97. package/dist/runtime/validators.d.ts.map +1 -0
  98. package/dist/runtime/validators.js +229 -0
  99. package/dist/runtime/validators.js.map +1 -0
  100. package/dist/runtime/worker-pool.d.ts +208 -0
  101. package/dist/runtime/worker-pool.d.ts.map +1 -0
  102. package/dist/runtime/worker-pool.js +419 -0
  103. package/dist/runtime/worker-pool.js.map +1 -0
  104. package/dist/types/index.d.ts +51 -1
  105. package/dist/types/index.d.ts.map +1 -1
  106. package/dist/tywrap.d.ts.map +1 -1
  107. package/dist/tywrap.js +227 -328
  108. package/dist/tywrap.js.map +1 -1
  109. package/dist/utils/cache.d.ts.map +1 -1
  110. package/dist/utils/cache.js +53 -5
  111. package/dist/utils/cache.js.map +1 -1
  112. package/dist/utils/codec.d.ts.map +1 -1
  113. package/dist/utils/codec.js +114 -1
  114. package/dist/utils/codec.js.map +1 -1
  115. package/dist/utils/ir-cache.d.ts +28 -0
  116. package/dist/utils/ir-cache.d.ts.map +1 -0
  117. package/dist/utils/ir-cache.js +29 -0
  118. package/dist/utils/ir-cache.js.map +1 -0
  119. package/dist/utils/parallel-processor.d.ts +1 -1
  120. package/dist/utils/parallel-processor.d.ts.map +1 -1
  121. package/dist/utils/parallel-processor.js +111 -40
  122. package/dist/utils/parallel-processor.js.map +1 -1
  123. package/dist/utils/runtime.d.ts +5 -1
  124. package/dist/utils/runtime.d.ts.map +1 -1
  125. package/dist/utils/runtime.js +112 -18
  126. package/dist/utils/runtime.js.map +1 -1
  127. package/package.json +40 -18
  128. package/runtime/python_bridge.py +108 -15
  129. package/runtime/safe_codec.py +344 -0
  130. package/src/cli.ts +61 -2
  131. package/src/config/index.ts +63 -17
  132. package/src/core/analyzer.ts +52 -15
  133. package/src/core/annotation-parser.ts +500 -0
  134. package/src/core/discovery.ts +26 -12
  135. package/src/core/generator.ts +956 -116
  136. package/src/core/mapper.ts +158 -51
  137. package/src/index.ts +78 -6
  138. package/src/runtime/base.ts +18 -26
  139. package/src/runtime/bounded-context.ts +608 -0
  140. package/src/runtime/bridge-core.ts +58 -18
  141. package/src/runtime/bridge-protocol.ts +483 -0
  142. package/src/runtime/disposable.ts +65 -0
  143. package/src/runtime/errors.ts +14 -0
  144. package/src/runtime/http-io.ts +245 -0
  145. package/src/runtime/http.ts +76 -115
  146. package/src/runtime/node.ts +563 -676
  147. package/src/runtime/optimized-node.ts +4 -1
  148. package/src/runtime/pooled-transport.ts +263 -0
  149. package/src/runtime/process-io.ts +930 -0
  150. package/src/runtime/pyodide-io.ts +551 -0
  151. package/src/runtime/pyodide.ts +75 -215
  152. package/src/runtime/safe-codec.ts +651 -0
  153. package/src/runtime/transport.ts +278 -0
  154. package/src/runtime/validators.ts +252 -0
  155. package/src/runtime/worker-pool.ts +559 -0
  156. package/src/types/global.d.ts +11 -1
  157. package/src/types/index.ts +63 -0
  158. package/src/tywrap.ts +279 -358
  159. package/src/utils/cache.ts +59 -5
  160. package/src/utils/codec.ts +122 -1
  161. package/src/utils/ir-cache.ts +51 -0
  162. package/src/utils/parallel-processor.ts +119 -43
  163. package/src/utils/runtime.ts +129 -18
@@ -0,0 +1,651 @@
1
+ /**
2
+ * SafeCodec - Unified validation and serialization for JS<->Python boundary crossing.
3
+ *
4
+ * Provides safe encoding/decoding with configurable guardrails for:
5
+ * - Special float rejection (NaN, Infinity)
6
+ * - Non-string key detection
7
+ * - Payload size limits
8
+ * - Binary data handling
9
+ */
10
+
11
+ import { BridgeCodecError, BridgeProtocolError, BridgeExecutionError } from './errors.js';
12
+ import { containsSpecialFloat } from './validators.js';
13
+ import { decodeValueAsync as decodeArrowValue } from '../utils/codec.js';
14
+ import { PROTOCOL_ID } from './transport.js';
15
+
16
+ // ═══════════════════════════════════════════════════════════════════════════
17
+ // TYPES
18
+ // ═══════════════════════════════════════════════════════════════════════════
19
+
20
+ /**
21
+ * Configuration options for SafeCodec behavior.
22
+ */
23
+ export interface CodecOptions {
24
+ /** Reject NaN/Infinity in arguments. Default: true */
25
+ rejectSpecialFloats?: boolean;
26
+ /** Reject non-string keys in objects. Default: true */
27
+ rejectNonStringKeys?: boolean;
28
+ /** Max payload size in bytes. Default: 10MB */
29
+ maxPayloadBytes?: number;
30
+ /** How to handle bytes/bytearray. Default: 'base64' */
31
+ bytesHandling?: 'base64' | 'reject' | 'passthrough';
32
+ }
33
+
34
+ /**
35
+ * Python error response format from the bridge.
36
+ */
37
+ interface PythonErrorResponse {
38
+ error: {
39
+ type: string;
40
+ message: string;
41
+ traceback?: string;
42
+ };
43
+ }
44
+
45
+ interface NormalizedPythonError {
46
+ type: string;
47
+ message: string;
48
+ traceback?: string;
49
+ }
50
+
51
+ interface ProtocolEnvelope {
52
+ id: number;
53
+ protocol?: string;
54
+ result?: unknown;
55
+ error?: unknown;
56
+ }
57
+
58
+ // ═══════════════════════════════════════════════════════════════════════════
59
+ // CONSTANTS
60
+ // ═══════════════════════════════════════════════════════════════════════════
61
+
62
+ const DEFAULT_MAX_PAYLOAD_BYTES = 10 * 1024 * 1024; // 10MB
63
+ const ERROR_PAYLOAD_SNIPPET_LENGTH = 200;
64
+
65
+ // ═══════════════════════════════════════════════════════════════════════════
66
+ // HELPER FUNCTIONS
67
+ // ═══════════════════════════════════════════════════════════════════════════
68
+
69
+ /**
70
+ * Check if a value is a plain object (not null, not array, not Map/Set/etc).
71
+ */
72
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
73
+ if (value === null || typeof value !== 'object') {
74
+ return false;
75
+ }
76
+ const proto = Object.getPrototypeOf(value);
77
+ return proto === Object.prototype || proto === null;
78
+ }
79
+
80
+ /**
81
+ * Build a path string for error messages.
82
+ */
83
+ function buildPath(basePath: string, key: string | number): string {
84
+ if (basePath === '') {
85
+ return typeof key === 'number' ? `[${key}]` : key;
86
+ }
87
+ return typeof key === 'number' ? `${basePath}[${key}]` : `${basePath}.${key}`;
88
+ }
89
+
90
+ /**
91
+ * Recursively check for non-string keys in objects and Maps.
92
+ * Throws BridgeCodecError with path indication if found.
93
+ */
94
+ function assertStringKeys(
95
+ value: unknown,
96
+ path: string = '',
97
+ visited: WeakSet<object> = new WeakSet<object>()
98
+ ): void {
99
+ if (value === null || typeof value !== 'object') {
100
+ return;
101
+ }
102
+ if (visited.has(value)) {
103
+ return;
104
+ }
105
+ visited.add(value);
106
+
107
+ // Check Map instances for non-string keys
108
+ if (value instanceof Map) {
109
+ for (const key of value.keys()) {
110
+ if (typeof key !== 'string') {
111
+ const keyDesc = typeof key === 'symbol' ? key.toString() : String(key);
112
+ const location = path ? ` at ${path}` : '';
113
+ throw new BridgeCodecError(
114
+ `Non-string key found in Map${location}: ${keyDesc} (${typeof key})`,
115
+ { codecPhase: 'encode' }
116
+ );
117
+ }
118
+ }
119
+ // Recurse into Map values
120
+ for (const [key, val] of value.entries()) {
121
+ assertStringKeys(val, buildPath(path, key), visited);
122
+ }
123
+ return;
124
+ }
125
+
126
+ // Check arrays
127
+ if (Array.isArray(value)) {
128
+ for (const [index, item] of value.entries()) {
129
+ assertStringKeys(item, buildPath(path, index), visited);
130
+ }
131
+ return;
132
+ }
133
+
134
+ // Check plain objects for symbol keys
135
+ if (isPlainObject(value)) {
136
+ // Symbol keys are not enumerated by Object.keys, use getOwnPropertySymbols
137
+ const symbolKeys = Object.getOwnPropertySymbols(value);
138
+ const firstSymbol = symbolKeys[0];
139
+ if (firstSymbol !== undefined) {
140
+ const symbolDesc = firstSymbol.toString();
141
+ const location = path ? ` at ${path}` : '';
142
+ throw new BridgeCodecError(`Symbol key found in object${location}: ${symbolDesc}`, {
143
+ codecPhase: 'encode',
144
+ });
145
+ }
146
+
147
+ // Recurse into object values
148
+ for (const [key, item] of Object.entries(value)) {
149
+ assertStringKeys(item, buildPath(path, key), visited);
150
+ }
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Check if a value is a Python error response.
156
+ */
157
+ function isPythonErrorResponse(value: unknown): value is PythonErrorResponse {
158
+ if (value === null || typeof value !== 'object') {
159
+ return false;
160
+ }
161
+ const obj = value as Record<string, unknown>;
162
+ if (!obj.error || typeof obj.error !== 'object' || obj.error === null) {
163
+ return false;
164
+ }
165
+ const error = obj.error as Record<string, unknown>;
166
+ return typeof error.type === 'string' && typeof error.message === 'string';
167
+ }
168
+
169
+ /**
170
+ * Type guard for protocol response envelope.
171
+ * Envelopes must include a numeric id.
172
+ */
173
+ function isProtocolEnvelope(value: unknown): value is ProtocolEnvelope {
174
+ if (value === null || typeof value !== 'object') {
175
+ return false;
176
+ }
177
+ const obj = value as Record<string, unknown>;
178
+ return typeof obj.id === 'number';
179
+ }
180
+
181
+ function hasOwnKey(value: object, key: string): boolean {
182
+ return Object.prototype.hasOwnProperty.call(value, key);
183
+ }
184
+
185
+ function normalizeErrorPayload(err: unknown): NormalizedPythonError | null {
186
+ if (!err || typeof err !== 'object' || Array.isArray(err)) {
187
+ return null;
188
+ }
189
+ const candidate = err as Record<string, unknown>;
190
+ if (typeof candidate.type !== 'string' || typeof candidate.message !== 'string') {
191
+ return null;
192
+ }
193
+ if (hasOwnKey(candidate, 'traceback') && typeof candidate.traceback !== 'string') {
194
+ return null;
195
+ }
196
+ const normalized: NormalizedPythonError = {
197
+ type: candidate.type,
198
+ message: candidate.message,
199
+ };
200
+ if (typeof candidate.traceback === 'string') {
201
+ normalized.traceback = candidate.traceback;
202
+ }
203
+ return normalized;
204
+ }
205
+
206
+ function describeInvalidErrorPayload(err: unknown): string {
207
+ if (!err || typeof err !== 'object' || Array.isArray(err)) {
208
+ return 'expected an object with string "type" and "message" fields';
209
+ }
210
+ const candidate = err as Record<string, unknown>;
211
+ if (typeof candidate.type !== 'string') {
212
+ return '"type" must be a string';
213
+ }
214
+ if (typeof candidate.message !== 'string') {
215
+ return '"message" must be a string';
216
+ }
217
+ if (hasOwnKey(candidate, 'traceback') && typeof candidate.traceback !== 'string') {
218
+ return '"traceback" must be a string when provided';
219
+ }
220
+ return 'expected an object with string "type" and "message" fields';
221
+ }
222
+
223
+ function summarizePayloadForError(payload: string): string {
224
+ const trimmed = payload.trim();
225
+ if (!trimmed) {
226
+ return '[empty payload]';
227
+ }
228
+ if (trimmed.length <= ERROR_PAYLOAD_SNIPPET_LENGTH) {
229
+ return trimmed;
230
+ }
231
+ return `${trimmed.slice(0, ERROR_PAYLOAD_SNIPPET_LENGTH)}...`;
232
+ }
233
+
234
+ /**
235
+ * Validate the protocol version in a response.
236
+ * Only validates when the response looks like a protocol envelope (has 'id' field).
237
+ * Throws if protocol is present but doesn't match expected version.
238
+ * Allows missing protocol for backwards compatibility.
239
+ */
240
+ function validateProtocolVersion(value: unknown): void {
241
+ if (value === null || typeof value !== 'object') {
242
+ return;
243
+ }
244
+ const obj = value as Record<string, unknown>;
245
+ // Only validate protocol on protocol envelopes (responses with 'id' field)
246
+ // This avoids false positives on user data that happens to contain 'protocol' key
247
+ if (!('id' in obj)) {
248
+ return;
249
+ }
250
+ if ('protocol' in obj && obj.protocol !== PROTOCOL_ID) {
251
+ throw new BridgeProtocolError(
252
+ `Invalid protocol version: expected "${PROTOCOL_ID}", got "${obj.protocol}"`
253
+ );
254
+ }
255
+ }
256
+
257
+ /**
258
+ * Find the path to a special float in a value structure.
259
+ * Returns undefined if no special float is found.
260
+ */
261
+ function findSpecialFloatPath(
262
+ value: unknown,
263
+ path: string = '',
264
+ visited: WeakSet<object> = new WeakSet<object>()
265
+ ): string | undefined {
266
+ if (typeof value === 'number' && !Number.isFinite(value)) {
267
+ return path || 'root';
268
+ }
269
+ if (value === null || typeof value !== 'object') {
270
+ return undefined;
271
+ }
272
+ if (visited.has(value)) {
273
+ return undefined;
274
+ }
275
+ visited.add(value);
276
+ if (Array.isArray(value)) {
277
+ for (const [index, item] of value.entries()) {
278
+ const result = findSpecialFloatPath(item, buildPath(path, index), visited);
279
+ if (result !== undefined) {
280
+ return result;
281
+ }
282
+ }
283
+ }
284
+ if (isPlainObject(value)) {
285
+ for (const [key, item] of Object.entries(value)) {
286
+ const result = findSpecialFloatPath(item, buildPath(path, key), visited);
287
+ if (result !== undefined) {
288
+ return result;
289
+ }
290
+ }
291
+ }
292
+ return undefined;
293
+ }
294
+
295
+ // ═══════════════════════════════════════════════════════════════════════════
296
+ // SAFE CODEC CLASS
297
+ // ═══════════════════════════════════════════════════════════════════════════
298
+
299
+ /**
300
+ * SafeCodec provides unified validation and serialization for JS<->Python
301
+ * boundary crossing with configurable guardrails.
302
+ *
303
+ * @example
304
+ * ```typescript
305
+ * const codec = new SafeCodec({ rejectSpecialFloats: true });
306
+ *
307
+ * // Encoding a request
308
+ * const payload = codec.encodeRequest({ data: [1, 2, 3] });
309
+ *
310
+ * // Decoding a response
311
+ * const result = codec.decodeResponse<MyType>(responsePayload);
312
+ *
313
+ * // Async decoding with Arrow support
314
+ * const dataframe = await codec.decodeResponseAsync<ArrowTable>(arrowPayload);
315
+ * ```
316
+ */
317
+ export class SafeCodec {
318
+ private readonly rejectSpecialFloats: boolean;
319
+ private readonly rejectNonStringKeys: boolean;
320
+ private readonly maxPayloadBytes: number;
321
+ private readonly bytesHandling: 'base64' | 'reject' | 'passthrough';
322
+ private readonly reviveValueBound: (key: string, value: unknown) => unknown;
323
+ private static readonly base64Pattern =
324
+ /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
325
+
326
+ constructor(options: CodecOptions = {}) {
327
+ this.rejectSpecialFloats = options.rejectSpecialFloats ?? true;
328
+ this.rejectNonStringKeys = options.rejectNonStringKeys ?? true;
329
+ this.maxPayloadBytes = options.maxPayloadBytes ?? DEFAULT_MAX_PAYLOAD_BYTES;
330
+ this.bytesHandling = options.bytesHandling ?? 'base64';
331
+ this.reviveValueBound = this.reviveValue.bind(this);
332
+ }
333
+
334
+ private assertValidBase64(b64: string): void {
335
+ if (!SafeCodec.base64Pattern.test(b64)) {
336
+ throw new BridgeCodecError('Invalid base64 in bytes envelope', {
337
+ codecPhase: 'decode',
338
+ valueType: 'bytes',
339
+ });
340
+ }
341
+ }
342
+
343
+ /**
344
+ * Convert base64 string to Uint8Array.
345
+ *
346
+ * Why: Python bridge represents bytes/bytearray as base64 envelopes. Decoding them here
347
+ * restores ergonomic JS types at the boundary.
348
+ */
349
+ private fromBase64(b64: string): Uint8Array {
350
+ this.assertValidBase64(b64);
351
+
352
+ if (typeof Buffer !== 'undefined') {
353
+ const buf = Buffer.from(b64, 'base64');
354
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.length);
355
+ }
356
+ if (globalThis.atob) {
357
+ const bin = globalThis.atob(b64);
358
+ const arr = Array.from(bin, c => c.charCodeAt(0));
359
+ return new Uint8Array(arr);
360
+ }
361
+ throw new BridgeCodecError('Base64 decoding is not available in this runtime', {
362
+ codecPhase: 'decode',
363
+ valueType: 'bytes',
364
+ });
365
+ }
366
+
367
+ /**
368
+ * JSON.parse reviver that decodes bytes envelopes.
369
+ *
370
+ * Supported shapes:
371
+ * - { "__tywrap_bytes__": true, "b64": "..." } (JS SafeCodec.encodeRequest; also allowed in responses)
372
+ * - { "__type__": "bytes", "encoding": "base64", "data": "..." } (Python SafeCodec default encoder)
373
+ */
374
+ private reviveValue(_key: string, value: unknown): unknown {
375
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
376
+ return value;
377
+ }
378
+ const obj = value as Record<string, unknown>;
379
+
380
+ if (obj.__tywrap_bytes__ === true && typeof obj.b64 === 'string') {
381
+ try {
382
+ return this.fromBase64(obj.b64);
383
+ } catch (err) {
384
+ const errorMessage = err instanceof Error ? err.message : String(err);
385
+ throw new BridgeCodecError(`Bytes envelope decode failed: ${errorMessage}`, {
386
+ codecPhase: 'decode',
387
+ valueType: 'bytes',
388
+ });
389
+ }
390
+ }
391
+
392
+ if (obj.__type__ === 'bytes' && obj.encoding === 'base64' && typeof obj.data === 'string') {
393
+ try {
394
+ return this.fromBase64(obj.data);
395
+ } catch (err) {
396
+ const errorMessage = err instanceof Error ? err.message : String(err);
397
+ throw new BridgeCodecError(`Bytes envelope decode failed: ${errorMessage}`, {
398
+ codecPhase: 'decode',
399
+ valueType: 'bytes',
400
+ });
401
+ }
402
+ }
403
+
404
+ return value;
405
+ }
406
+
407
+ private toBridgeExecutionError(error: NormalizedPythonError): BridgeExecutionError {
408
+ const bridgeError = new BridgeExecutionError(`${error.type}: ${error.message}`);
409
+ bridgeError.traceback = error.traceback;
410
+ return bridgeError;
411
+ }
412
+
413
+ private extractResultFromResponseEnvelope(parsed: unknown): unknown {
414
+ if (isProtocolEnvelope(parsed)) {
415
+ const envelope = parsed;
416
+ const hasResult = hasOwnKey(envelope, 'result');
417
+ const hasError = hasOwnKey(envelope, 'error');
418
+
419
+ if (hasResult && hasError) {
420
+ throw new BridgeProtocolError('Protocol response cannot include both "result" and "error"');
421
+ }
422
+
423
+ if (hasError) {
424
+ const normalizedError = normalizeErrorPayload(envelope.error);
425
+ if (!normalizedError) {
426
+ const details = describeInvalidErrorPayload(envelope.error);
427
+ throw new BridgeProtocolError(`Invalid response "error" payload: ${details}`);
428
+ }
429
+ throw this.toBridgeExecutionError(normalizedError);
430
+ }
431
+
432
+ if (!hasResult) {
433
+ throw new BridgeProtocolError('Protocol response missing "result" or "error" field');
434
+ }
435
+
436
+ return envelope.result;
437
+ }
438
+
439
+ if (isPythonErrorResponse(parsed)) {
440
+ throw this.toBridgeExecutionError(parsed.error);
441
+ }
442
+
443
+ return parsed;
444
+ }
445
+
446
+ /**
447
+ * Validate and encode a request payload.
448
+ * Called before sending to Python.
449
+ *
450
+ * @param message - The message to encode
451
+ * @returns JSON string ready to send
452
+ * @throws BridgeCodecError if validation fails or encoding fails
453
+ */
454
+ encodeRequest(message: unknown): string {
455
+ // Validate special floats if enabled
456
+ if (this.rejectSpecialFloats && containsSpecialFloat(message)) {
457
+ const floatPath = findSpecialFloatPath(message);
458
+ throw new BridgeCodecError(
459
+ `Cannot encode request: contains non-finite number (NaN or Infinity) at ${floatPath}`,
460
+ { codecPhase: 'encode', valueType: 'number' }
461
+ );
462
+ }
463
+
464
+ // Validate string keys if enabled
465
+ if (this.rejectNonStringKeys) {
466
+ assertStringKeys(message);
467
+ }
468
+
469
+ // Serialize to JSON with error handling
470
+ let payload: string;
471
+ try {
472
+ payload = JSON.stringify(message, (key, value) => {
473
+ // Handle bytes based on configuration
474
+ if (value instanceof Uint8Array || value instanceof ArrayBuffer) {
475
+ switch (this.bytesHandling) {
476
+ case 'reject':
477
+ throw new BridgeCodecError(
478
+ `Cannot encode request: binary data found at ${key || 'root'} (bytesHandling: reject)`,
479
+ { codecPhase: 'encode', valueType: 'bytes' }
480
+ );
481
+ case 'base64': {
482
+ const bytes = value instanceof ArrayBuffer ? new Uint8Array(value) : value;
483
+ const b64 = this.toBase64(bytes);
484
+ return { __tywrap_bytes__: true, b64 };
485
+ }
486
+ case 'passthrough':
487
+ default:
488
+ return value;
489
+ }
490
+ }
491
+ return value;
492
+ });
493
+ } catch (err) {
494
+ if (err instanceof BridgeCodecError) {
495
+ throw err;
496
+ }
497
+ if (err instanceof BridgeProtocolError) {
498
+ throw err;
499
+ }
500
+ const errorMessage = err instanceof Error ? err.message : String(err);
501
+ throw new BridgeCodecError(`JSON serialization failed: ${errorMessage}`, {
502
+ codecPhase: 'encode',
503
+ });
504
+ }
505
+
506
+ // Check payload size
507
+ const payloadBytes = new TextEncoder().encode(payload).length;
508
+ if (payloadBytes > this.maxPayloadBytes) {
509
+ throw new BridgeCodecError(
510
+ `Payload size ${payloadBytes} bytes exceeds maximum ${this.maxPayloadBytes} bytes`,
511
+ { codecPhase: 'encode', valueType: 'payload' }
512
+ );
513
+ }
514
+
515
+ return payload;
516
+ }
517
+
518
+ /**
519
+ * Decode and validate a response payload.
520
+ * Called after receiving from Python.
521
+ *
522
+ * @param payload - The JSON string received from Python
523
+ * @returns Decoded and validated result
524
+ * @throws BridgeCodecError if payload is invalid or decoding fails
525
+ * @throws BridgeProtocolError if protocol envelope is invalid
526
+ * @throws BridgeExecutionError if response contains a Python error
527
+ */
528
+ decodeResponse<T>(payload: string): T {
529
+ // Check payload size first
530
+ const payloadBytes = new TextEncoder().encode(payload).length;
531
+ if (payloadBytes > this.maxPayloadBytes) {
532
+ throw new BridgeCodecError(
533
+ `Response payload size ${payloadBytes} bytes exceeds maximum ${this.maxPayloadBytes} bytes`,
534
+ { codecPhase: 'decode', valueType: 'payload' }
535
+ );
536
+ }
537
+
538
+ // Parse JSON
539
+ let parsed: unknown;
540
+ try {
541
+ parsed = JSON.parse(payload, this.reviveValueBound);
542
+ } catch (err) {
543
+ if (err instanceof BridgeCodecError || err instanceof BridgeProtocolError) {
544
+ throw err;
545
+ }
546
+ const errorMessage = err instanceof Error ? err.message : String(err);
547
+ throw new BridgeCodecError(
548
+ `JSON parse failed: ${errorMessage}. Payload snippet: ${summarizePayloadForError(payload)}`,
549
+ { codecPhase: 'decode', valueType: 'json' }
550
+ );
551
+ }
552
+
553
+ // Validate protocol version (if present)
554
+ validateProtocolVersion(parsed);
555
+
556
+ const result = this.extractResultFromResponseEnvelope(parsed);
557
+
558
+ // Post-decode validation for special floats if enabled
559
+ if (this.rejectSpecialFloats && containsSpecialFloat(result)) {
560
+ const floatPath = findSpecialFloatPath(result);
561
+ throw new BridgeCodecError(
562
+ `Response contains non-finite number (NaN or Infinity) at ${floatPath}`,
563
+ { codecPhase: 'decode', valueType: 'number' }
564
+ );
565
+ }
566
+
567
+ return result as T;
568
+ }
569
+
570
+ /**
571
+ * Async version that applies Arrow decoders.
572
+ * Use this when the response may contain encoded DataFrames or ndarrays.
573
+ *
574
+ * @param payload - The JSON string received from Python
575
+ * @returns Decoded and validated result with Arrow decoding applied
576
+ * @throws BridgeCodecError if payload is invalid or decoding fails
577
+ * @throws BridgeProtocolError if protocol envelope is invalid
578
+ * @throws BridgeExecutionError if response contains a Python error
579
+ */
580
+ async decodeResponseAsync<T>(payload: string): Promise<T> {
581
+ // Check payload size first
582
+ const payloadBytes = new TextEncoder().encode(payload).length;
583
+ if (payloadBytes > this.maxPayloadBytes) {
584
+ throw new BridgeCodecError(
585
+ `Response payload size ${payloadBytes} bytes exceeds maximum ${this.maxPayloadBytes} bytes`,
586
+ { codecPhase: 'decode', valueType: 'payload' }
587
+ );
588
+ }
589
+
590
+ // Parse JSON
591
+ let parsed: unknown;
592
+ try {
593
+ parsed = JSON.parse(payload, this.reviveValueBound);
594
+ } catch (err) {
595
+ if (err instanceof BridgeCodecError || err instanceof BridgeProtocolError) {
596
+ throw err;
597
+ }
598
+ const errorMessage = err instanceof Error ? err.message : String(err);
599
+ throw new BridgeCodecError(
600
+ `JSON parse failed: ${errorMessage}. Payload snippet: ${summarizePayloadForError(payload)}`,
601
+ { codecPhase: 'decode', valueType: 'json' }
602
+ );
603
+ }
604
+
605
+ // Validate protocol version (if present)
606
+ validateProtocolVersion(parsed);
607
+
608
+ const result = this.extractResultFromResponseEnvelope(parsed);
609
+
610
+ // Apply Arrow decoding to the result
611
+ let decoded: unknown;
612
+ try {
613
+ decoded = await decodeArrowValue(result);
614
+ } catch (err) {
615
+ const errorMessage = err instanceof Error ? err.message : String(err);
616
+ throw new BridgeCodecError(`Arrow decoding failed: ${errorMessage}`, {
617
+ codecPhase: 'decode',
618
+ valueType: 'arrow',
619
+ });
620
+ }
621
+
622
+ // Post-decode validation for special floats if enabled
623
+ // Note: Arrow decoders can introduce NaN/Infinity from binary representations.
624
+ if (this.rejectSpecialFloats && containsSpecialFloat(decoded)) {
625
+ const floatPath = findSpecialFloatPath(decoded);
626
+ throw new BridgeCodecError(
627
+ `Response contains non-finite number (NaN or Infinity) at ${floatPath}`,
628
+ { codecPhase: 'decode', valueType: 'number' }
629
+ );
630
+ }
631
+
632
+ return decoded as T;
633
+ }
634
+
635
+ /**
636
+ * Convert Uint8Array to base64 string.
637
+ */
638
+ private toBase64(bytes: Uint8Array): string {
639
+ if (typeof Buffer !== 'undefined') {
640
+ return Buffer.from(bytes).toString('base64');
641
+ }
642
+ if (globalThis.btoa) {
643
+ const binary = String.fromCharCode(...bytes);
644
+ return globalThis.btoa(binary);
645
+ }
646
+ throw new BridgeCodecError('Base64 encoding is not available in this runtime', {
647
+ codecPhase: 'encode',
648
+ valueType: 'bytes',
649
+ });
650
+ }
651
+ }