@zlink-systems/stream-wire 0.32.2 → 0.34.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.
@@ -154,6 +154,9 @@ var ZlinkStreamCloseReasonCode = /* @__PURE__ */ ((ZlinkStreamCloseReasonCode2)
154
154
  return ZlinkStreamCloseReasonCode2;
155
155
  })(ZlinkStreamCloseReasonCode || {});
156
156
  var unicodeWhiteSpaceOnly = /^\p{White_Space}*$/u;
157
+ var utf8Encoder = new TextEncoder();
158
+ var utf8Decoder = new TextDecoder();
159
+ var controlTextDecoder = new TextDecoder("utf-8", { fatal: true });
157
160
  var validMessageKinds = new Set(
158
161
  Object.values(ZlinkStreamMessageKind).filter((value) => typeof value === "number")
159
162
  );
@@ -270,7 +273,7 @@ function decodeStreamWireSessionClosing(payload) {
270
273
  return { closeReason, diagnostic };
271
274
  }
272
275
  function decodeControlText(value) {
273
- return new TextDecoder("utf-8", { fatal: true }).decode(value);
276
+ return controlTextDecoder.decode(value);
274
277
  }
275
278
  function splitStreamWireFrames(chunk) {
276
279
  if (chunk.length === 0) throw new Error("Stream frame prefix is incomplete.");
@@ -612,10 +615,10 @@ function lz4UnpicklePayload2(payload, maxDecompressedSize) {
612
615
  return lz4UnpicklePayload(payload, maxDecompressedSize ?? defaultMaxDecompressedPayloadSize);
613
616
  }
614
617
  function utf8Encode(value) {
615
- return new TextEncoder().encode(value);
618
+ return utf8Encoder.encode(value);
616
619
  }
617
620
  function utf8Decode(value) {
618
- return new TextDecoder().decode(value);
621
+ return utf8Decoder.decode(value);
619
622
  }
620
623
  function decodeStreamWireHeaderMetadata(header, offset) {
621
624
  if (header.length - offset < UINT16_BYTES) {
@@ -4,5 +4,7 @@ export interface FrameworkJsonParseOptions {
4
4
  readonly rejectPropertyName?: (name: string) => boolean;
5
5
  readonly onDuplicateProperty?: (name: string, path: readonly string[]) => void;
6
6
  }
7
- export declare function stringifyFrameworkJsonV1(value: unknown, schema?: ZLinkJsonSchema, replacer?: (this: unknown, key: string, value: unknown) => unknown): string;
8
- export declare function parseFrameworkJsonV1(text: string, options?: FrameworkJsonParseOptions, schema?: ZLinkJsonSchema, reviver?: (this: unknown, key: string, value: unknown) => unknown): unknown;
7
+ export declare const stringifyFrameworkJsonV1: (value: unknown, schema?: ZLinkJsonSchema, replacer?: (this: unknown, key: string, value: unknown) => unknown) => string;
8
+ /** @internal Configures byte conversion once while keeping JSON policy shared. */
9
+ export declare function createFrameworkJsonV1Stringifier(encodeBytes: (bytes: Uint8Array) => string): (value: unknown, schema?: ZLinkJsonSchema, replacer?: (this: unknown, key: string, value: unknown) => unknown) => string;
10
+ export declare function parseFrameworkJsonV1(text: string, options?: FrameworkJsonParseOptions, schema?: ZLinkJsonSchema, reviver?: (this: unknown, key: string, value: unknown) => unknown, decodeBytes?: (value: string) => Uint8Array): unknown;
package/dist/index.js CHANGED
@@ -65,6 +65,10 @@ var ZlinkStreamCloseReasonCode;
65
65
  ZlinkStreamCloseReasonCode[ZlinkStreamCloseReasonCode["TransportError"] = 6] = "TransportError";
66
66
  })(ZlinkStreamCloseReasonCode || (exports.ZlinkStreamCloseReasonCode = ZlinkStreamCloseReasonCode = {}));
67
67
  const unicodeWhiteSpaceOnly = /^\p{White_Space}*$/u;
68
+ const utf8Encoder = new TextEncoder();
69
+ // Each non-streaming decode resets its state, including after invalid input.
70
+ const utf8Decoder = new TextDecoder();
71
+ const controlTextDecoder = new TextDecoder('utf-8', { fatal: true });
68
72
  const validMessageKinds = new Set(Object.values(ZlinkStreamMessageKind).filter((value) => typeof value === 'number'));
69
73
  const validCodecs = new Set(Object.values(ZlinkStreamCodec).filter((value) => typeof value === 'number'));
70
74
  function isStreamWireMessageKind(value) {
@@ -185,7 +189,7 @@ function decodeStreamWireSessionClosing(payload) {
185
189
  return { closeReason, diagnostic };
186
190
  }
187
191
  function decodeControlText(value) {
188
- return new TextDecoder('utf-8', { fatal: true }).decode(value);
192
+ return controlTextDecoder.decode(value);
189
193
  }
190
194
  function splitStreamWireFrames(chunk) {
191
195
  if (chunk.length === 0)
@@ -549,10 +553,10 @@ function lz4UnpicklePayload(payload, maxDecompressedSize) {
549
553
  return (0, lz4_pickle_1.lz4UnpicklePayload)(payload, maxDecompressedSize ?? lz4_pickle_1.defaultMaxDecompressedPayloadSize);
550
554
  }
551
555
  function utf8Encode(value) {
552
- return new TextEncoder().encode(value);
556
+ return utf8Encoder.encode(value);
553
557
  }
554
558
  function utf8Decode(value) {
555
- return new TextDecoder().decode(value);
559
+ return utf8Decoder.decode(value);
556
560
  }
557
561
  function decodeStreamWireHeaderMetadata(header, offset) {
558
562
  if (header.length - offset < UINT16_BYTES) {
@@ -4,5 +4,7 @@ export interface FrameworkJsonParseOptions {
4
4
  readonly rejectPropertyName?: (name: string) => boolean;
5
5
  readonly onDuplicateProperty?: (name: string, path: readonly string[]) => void;
6
6
  }
7
- export declare function stringifyFrameworkJsonV1(value: unknown, schema?: ZLinkJsonSchema, replacer?: (this: unknown, key: string, value: unknown) => unknown): string;
8
- export declare function parseFrameworkJsonV1(text: string, options?: FrameworkJsonParseOptions, schema?: ZLinkJsonSchema, reviver?: (this: unknown, key: string, value: unknown) => unknown): unknown;
7
+ export declare const stringifyFrameworkJsonV1: (value: unknown, schema?: ZLinkJsonSchema, replacer?: (this: unknown, key: string, value: unknown) => unknown) => string;
8
+ /** @internal Configures byte conversion once while keeping JSON policy shared. */
9
+ export declare function createFrameworkJsonV1Stringifier(encodeBytes: (bytes: Uint8Array) => string): (value: unknown, schema?: ZLinkJsonSchema, replacer?: (this: unknown, key: string, value: unknown) => unknown) => string;
10
+ export declare function parseFrameworkJsonV1(text: string, options?: FrameworkJsonParseOptions, schema?: ZLinkJsonSchema, reviver?: (this: unknown, key: string, value: unknown) => unknown, decodeBytes?: (value: string) => Uint8Array): unknown;
@@ -1,37 +1,40 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.FRAMEWORK_JSON_V1_PROFILE = void 0;
4
- exports.stringifyFrameworkJsonV1 = stringifyFrameworkJsonV1;
3
+ exports.stringifyFrameworkJsonV1 = exports.FRAMEWORK_JSON_V1_PROFILE = void 0;
4
+ exports.createFrameworkJsonV1Stringifier = createFrameworkJsonV1Stringifier;
5
5
  exports.parseFrameworkJsonV1 = parseFrameworkJsonV1;
6
6
  exports.FRAMEWORK_JSON_V1_PROFILE = 'framework-json-v1';
7
7
  const SIGNED_64_MIN = -(1n << 63n);
8
8
  const UNSIGNED_64_MAX = (1n << 64n) - 1n;
9
- function stringifyFrameworkJsonV1(value, schema, replacer) {
10
- if (value === undefined || typeof value === 'function' || typeof value === 'symbol') {
11
- throw new TypeError('framework-json-v1 payload is not a JSON value.');
9
+ exports.stringifyFrameworkJsonV1 = createFrameworkJsonV1Stringifier(encodeBase64);
10
+ /** @internal Configures byte conversion once while keeping JSON policy shared. */
11
+ function createFrameworkJsonV1Stringifier(encodeBytes) {
12
+ // JSON.stringify has already called toJSON. Read the raw source from the
13
+ // holder, including the root wrapper, before applying the shared policy.
14
+ function frameworkJsonV1Replacer(key, item) {
15
+ return frameworkJsonV1Value(this[key], item, encodeBytes);
12
16
  }
13
- const encoded = replacer === undefined
14
- ? JSON.stringify(value, frameworkJsonV1Replacer)
15
- : stringifyWithReplacer(value, replacer);
16
- if (schema !== undefined) {
17
- validateFrameworkJsonV1Value(JSON.parse(encoded), schema, '$', false);
18
- }
19
- return encoded;
17
+ return function stringifyFrameworkJsonV1(value, schema, replacer) {
18
+ if (value === undefined || typeof value === 'function' || typeof value === 'symbol') {
19
+ throw new TypeError('framework-json-v1 payload is not a JSON value.');
20
+ }
21
+ const encoded = replacer === undefined
22
+ ? JSON.stringify(value, frameworkJsonV1Replacer)
23
+ : stringifyWithReplacer(value, replacer, encodeBytes);
24
+ if (schema !== undefined) {
25
+ validateFrameworkJsonV1Value(JSON.parse(encoded), schema, '$', false);
26
+ }
27
+ return encoded;
28
+ };
20
29
  }
21
30
  // Keep custom callback captures off the default encoding path.
22
- function stringifyWithReplacer(value, replacer) {
31
+ function stringifyWithReplacer(value, replacer, encodeBytes) {
23
32
  return JSON.stringify(value, function (key, item) {
24
33
  const transformed = replacer.call(this, key, item);
25
- return frameworkJsonV1Value(transformed, transformed);
34
+ return frameworkJsonV1Value(transformed, transformed, encodeBytes);
26
35
  });
27
36
  }
28
- // Module-level so JSON.stringify does not allocate a fresh closure per
29
- // encoded message. On the root call `this` is the {'': value} wrapper, so
30
- // this[key] resolves the raw (pre-toJSON) source for every key including ''.
31
- function frameworkJsonV1Replacer(key, item) {
32
- return frameworkJsonV1Value(this[key], item);
33
- }
34
- function frameworkJsonV1Value(source, item) {
37
+ function frameworkJsonV1Value(source, item, encodeBytes) {
35
38
  if (typeof source === 'number' && !Number.isFinite(source)) {
36
39
  throw new TypeError('framework-json-v1 only accepts finite JSON numbers.');
37
40
  }
@@ -42,7 +45,7 @@ function frameworkJsonV1Value(source, item) {
42
45
  return source.toString(10);
43
46
  }
44
47
  if (source instanceof Uint8Array) {
45
- return encodeBase64(source);
48
+ return encodeBytes(source);
46
49
  }
47
50
  if (source instanceof Date) {
48
51
  throw new TypeError('framework-json-v1 does not implicitly encode Date values.');
@@ -54,13 +57,15 @@ function frameworkJsonV1Value(source, item) {
54
57
  }
55
58
  return item;
56
59
  }
57
- function parseFrameworkJsonV1(text, options = {}, schema, reviver) {
60
+ function parseFrameworkJsonV1(text, options = {}, schema, reviver, decodeBytes = decodeBase64) {
58
61
  if (text.charCodeAt(0) === 0xfeff) {
59
62
  throw new SyntaxError('framework-json-v1 does not allow a UTF-8 BOM.');
60
63
  }
61
- new JsonPropertyScanner(text, options).scan();
64
+ new JsonPropertyScanner(text, options).scan(schema);
62
65
  const parsed = JSON.parse(text, reviver);
63
- return schema === undefined ? parsed : validateFrameworkJsonV1Value(parsed, schema, '$', true);
66
+ return schema === undefined
67
+ ? parsed
68
+ : validateFrameworkJsonV1Value(parsed, schema, '$', true, decodeBytes);
64
69
  }
65
70
  // Sticky pattern shared across scans; matching happens synchronously so the
66
71
  // mutable lastIndex never crosses calls.
@@ -69,7 +74,7 @@ const BASE64_PATTERN = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/
69
74
  const INT32_MIN = -2_147_483_648;
70
75
  const INT32_MAX = 2_147_483_647;
71
76
  const UINT32_MAX = 4_294_967_295;
72
- function validateFrameworkJsonV1Value(value, schema, path, decode) {
77
+ function validateFrameworkJsonV1Value(value, schema, path, decode, decodeBytes = decodeBase64) {
73
78
  switch (schema.type) {
74
79
  case 'boolean':
75
80
  if (typeof value !== 'boolean')
@@ -105,8 +110,8 @@ function validateFrameworkJsonV1Value(value, schema, path, decode) {
105
110
  }
106
111
  if (!hasCanonicalBase64Padding(value))
107
112
  schemaFailure(path, 'canonical padded RFC 4648 base64');
108
- // decodeBase64 returns fresh storage owned by this value.
109
- return decode ? decodeBase64(value) : value;
113
+ // The selected decoder returns fresh storage owned by this value.
114
+ return decode ? decodeBytes(value) : value;
110
115
  }
111
116
  case 'enum':
112
117
  if (typeof value !== 'string' || !schema.names.includes(value)) {
@@ -116,17 +121,17 @@ function validateFrameworkJsonV1Value(value, schema, path, decode) {
116
121
  case 'nullable':
117
122
  return value === null
118
123
  ? null
119
- : validateFrameworkJsonV1Value(value, schema.value, path, decode);
124
+ : validateFrameworkJsonV1Value(value, schema.value, path, decode, decodeBytes);
120
125
  case 'array':
121
126
  if (!Array.isArray(value))
122
127
  schemaFailure(path, 'an array');
123
- return value.map((item, index) => validateFrameworkJsonV1Value(item, schema.items, `${path}[${index}]`, decode));
128
+ return value.map((item, index) => validateFrameworkJsonV1Value(item, schema.items, `${path}[${index}]`, decode, decodeBytes));
124
129
  case 'record': {
125
130
  if (!isJsonObject(value))
126
131
  schemaFailure(path, 'an object');
127
132
  const result = {};
128
133
  for (const [name, item] of Object.entries(value)) {
129
- result[name] = validateFrameworkJsonV1Value(item, schema.values, `${path}.${name}`, decode);
134
+ result[name] = validateFrameworkJsonV1Value(item, schema.values, `${path}.${name}`, decode, decodeBytes);
130
135
  }
131
136
  return decode ? result : value;
132
137
  }
@@ -134,21 +139,26 @@ function validateFrameworkJsonV1Value(value, schema, path, decode) {
134
139
  if (!isJsonObject(value))
135
140
  schemaFailure(path, 'an object');
136
141
  const input = value;
137
- for (const name of schema.required) {
142
+ const { properties, required } = schema;
143
+ for (let index = 0; index < required.length; index++) {
144
+ const name = required[index];
138
145
  if (!Object.prototype.hasOwnProperty.call(input, name)) {
139
146
  throw new TypeError(`framework-json-v1 required property '${path}.${name}' is missing.`);
140
147
  }
141
148
  }
142
149
  const result = {};
143
- for (const [name, item] of Object.entries(input)) {
144
- const propertySchema = schema.properties[name];
150
+ const entries = Object.entries(input);
151
+ for (let index = 0; index < entries.length; index++) {
152
+ const entry = entries[index];
153
+ const name = entry[0];
154
+ const propertySchema = properties[name];
145
155
  if (propertySchema === undefined) {
146
156
  if (schema.additionalProperties === false) {
147
157
  throw new TypeError(`framework-json-v1 property '${path}.${name}' is not allowed.`);
148
158
  }
149
159
  continue;
150
160
  }
151
- result[name] = validateFrameworkJsonV1Value(item, propertySchema, `${path}.${name}`, decode);
161
+ result[name] = validateFrameworkJsonV1Value(entry[1], propertySchema, `${path}.${name}`, decode, decodeBytes);
152
162
  }
153
163
  return decode ? result : value;
154
164
  }
@@ -171,6 +181,21 @@ function isJsonObject(value) {
171
181
  function schemaFailure(path, expected) {
172
182
  throw new TypeError(`framework-json-v1 value '${path}' must be ${expected}.`);
173
183
  }
184
+ const propertyPlans = new WeakMap();
185
+ function knownProperties(properties) {
186
+ const cached = propertyPlans.get(properties);
187
+ if (cached !== undefined)
188
+ return cached;
189
+ const plan = new Map();
190
+ let index = 0;
191
+ for (const [name, schema] of Object.entries(properties)) {
192
+ plan.set(name, { schema, mask: index >= 32 ? 0 : 1 << index });
193
+ index++;
194
+ }
195
+ if (Object.isFrozen(properties))
196
+ propertyPlans.set(properties, plan);
197
+ return plan;
198
+ }
174
199
  class JsonPropertyScanner {
175
200
  text;
176
201
  options;
@@ -182,22 +207,24 @@ class JsonPropertyScanner {
182
207
  const escape = text.indexOf('\\');
183
208
  this.firstEscape = escape === -1 ? text.length : escape;
184
209
  }
185
- scan() {
186
- this.skipWhitespace();
187
- this.scanValue([]);
210
+ scan(schema) {
211
+ this.scanValue(this.options.onDuplicateProperty === undefined ? undefined : [], schema);
188
212
  this.skipWhitespace();
189
213
  if (this.index !== this.text.length)
190
214
  this.fail('trailing data');
191
215
  }
192
- scanValue(path) {
216
+ scanValue(path, schema) {
193
217
  this.skipWhitespace();
194
218
  const token = this.text[this.index];
195
- if (token === '{')
196
- return this.scanObject(path);
197
- if (token === '[')
198
- return this.scanArray(path);
219
+ if (token === '{' || token === '[') {
220
+ while (schema?.type === 'nullable')
221
+ schema = schema.value;
222
+ return token === '{'
223
+ ? this.scanObject(path, schema)
224
+ : this.scanArray(path, schema?.type === 'array' ? schema.items : undefined);
225
+ }
199
226
  if (token === '"') {
200
- this.scanString();
227
+ this.scanString(false);
201
228
  return;
202
229
  }
203
230
  if (token === 't')
@@ -208,28 +235,41 @@ class JsonPropertyScanner {
208
235
  return this.scanLiteral('null');
209
236
  this.scanNumber();
210
237
  }
211
- scanObject(path) {
238
+ scanObject(path, schema) {
212
239
  this.index++;
213
240
  this.skipWhitespace();
214
241
  if (this.text[this.index] === '}') {
215
242
  this.index++;
216
243
  return;
217
244
  }
218
- const properties = new Set();
245
+ const plan = schema?.type === 'object' ? knownProperties(schema.properties) : undefined;
246
+ const recordValue = schema?.type === 'record' ? schema.values : undefined;
247
+ let seen = 0;
248
+ let other;
219
249
  for (;;) {
220
- this.skipWhitespace();
221
250
  if (this.text[this.index] !== '"')
222
251
  this.fail('object property name');
223
- const property = this.scanString();
224
- if (properties.has(property)) {
252
+ const property = this.scanString(true);
253
+ const known = plan?.get(property);
254
+ const mask = known?.mask ?? 0;
255
+ let duplicate;
256
+ if (mask === 0) {
257
+ other ??= new Set();
258
+ duplicate = other.has(property);
259
+ other.add(property);
260
+ }
261
+ else {
262
+ duplicate = (seen & mask) !== 0;
263
+ seen |= mask;
264
+ }
265
+ if (duplicate) {
225
266
  if (this.options.onDuplicateProperty !== undefined) {
226
- this.options.onDuplicateProperty(property, path);
267
+ this.options.onDuplicateProperty(property, path ?? []);
227
268
  }
228
269
  else {
229
270
  throw new SyntaxError(`framework-json-v1 duplicate property '${property}'.`);
230
271
  }
231
272
  }
232
- properties.add(property);
233
273
  if (this.options.rejectPropertyName?.(property) === true) {
234
274
  throw new SyntaxError(`framework-json-v1 property '${property}' is not allowed.`);
235
275
  }
@@ -237,16 +277,17 @@ class JsonPropertyScanner {
237
277
  if (this.text[this.index] !== ':')
238
278
  this.fail("':' after object property");
239
279
  this.index++;
240
- this.scanValue(this.options.onDuplicateProperty === undefined ? path : [...path, property]);
280
+ this.scanValue(path === undefined ? undefined : [...path, property], known?.schema ?? recordValue);
241
281
  this.skipWhitespace();
242
282
  const delimiter = this.text[this.index++];
243
283
  if (delimiter === '}')
244
284
  return;
245
285
  if (delimiter !== ',')
246
286
  this.fail("',' or '}' after object property");
287
+ this.skipWhitespace();
247
288
  }
248
289
  }
249
- scanArray(path) {
290
+ scanArray(path, itemSchema) {
250
291
  this.index++;
251
292
  this.skipWhitespace();
252
293
  if (this.text[this.index] === ']') {
@@ -254,7 +295,7 @@ class JsonPropertyScanner {
254
295
  return;
255
296
  }
256
297
  for (;;) {
257
- this.scanValue(this.options.onDuplicateProperty === undefined ? path : [...path, '[]']);
298
+ this.scanValue(path === undefined ? undefined : [...path, '[]'], itemSchema);
258
299
  this.skipWhitespace();
259
300
  const delimiter = this.text[this.index++];
260
301
  if (delimiter === ']')
@@ -263,7 +304,7 @@ class JsonPropertyScanner {
263
304
  this.fail("',' or ']' after array item");
264
305
  }
265
306
  }
266
- scanString() {
307
+ scanString(readProperty) {
267
308
  const text = this.text;
268
309
  const start = this.index;
269
310
  let index = start + 1;
@@ -272,7 +313,7 @@ class JsonPropertyScanner {
272
313
  const end = text.indexOf('"', index);
273
314
  if (end !== -1 && end < this.firstEscape) {
274
315
  this.index = end + 1;
275
- return text.slice(index, end);
316
+ return readProperty ? text.slice(index, end) : undefined;
276
317
  }
277
318
  let sawEscape = false;
278
319
  for (;;) {
@@ -283,11 +324,9 @@ class JsonPropertyScanner {
283
324
  const character = text[index++];
284
325
  if (character === '"') {
285
326
  this.index = index;
286
- // Without escapes the token content is verbatim; the outer
287
- // JSON.parse pass still rejects any raw control characters.
288
- return sawEscape
289
- ? JSON.parse(text.slice(start, index))
290
- : text.slice(start + 1, index - 1);
327
+ if (sawEscape)
328
+ return JSON.parse(text.slice(start, index));
329
+ return readProperty ? text.slice(start + 1, index - 1) : undefined;
291
330
  }
292
331
  if (character === '\\') {
293
332
  sawEscape = true;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zlink-systems/stream-wire",
3
- "version": "0.32.2",
3
+ "version": "0.34.0",
4
4
  "license": "Apache-2.0",
5
5
  "repository": {
6
6
  "type": "git",