@oxidezap/baileyrs 0.3.13 → 0.3.14

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.
@@ -379,11 +379,13 @@ const ADAPTERS = {
379
379
  connected: asBoolOr(data?.connected, false)
380
380
  }),
381
381
  /**
382
- * The QR refs ran out. Upstream ends the socket with `timedOut` when its own
383
- * QR timer gives up (`Socket/socket.ts`), which is the same end state, so
384
- * this becomes the same terminal close rather than a new signal to learn.
382
+ * QR exhaustion can leave a pair-code flow alive. Older bridges omit the
383
+ * flag, so preserve their terminal-timeout behavior by default.
385
384
  */
386
- pairing_qr_codes_exhausted: () => ({ type: 'qrCodesExhausted' }),
385
+ pairing_qr_codes_exhausted: data => ({
386
+ type: 'qrCodesExhausted',
387
+ disconnected: asBoolOr(data?.disconnected, true)
388
+ }),
387
389
  /**
388
390
  * Another linked device turned link previews on or off account-wide.
389
391
  *
@@ -495,13 +495,12 @@ export interface CanonicalLabelAssociation {
495
495
  labeled: boolean;
496
496
  }
497
497
  /**
498
- * The server ran out of QR refs before anyone scanned one.
499
- *
500
- * Terminal: nothing else is coming on this socket, and the consumer builds a
501
- * new one to be shown a fresh code.
498
+ * QR refs ran out, but an outstanding pair code may keep the socket alive.
502
499
  */
503
500
  export interface CanonicalQrCodesExhausted {
504
501
  type: 'qrCodesExhausted';
502
+ /** False when the engine keeps an outstanding pair-code flow alive. */
503
+ disconnected: boolean;
505
504
  }
506
505
  /**
507
506
  * A batched app-state sync that did not leave every collection synced.
@@ -7,7 +7,7 @@ const EMPTY_ARRAY = Object.freeze([]);
7
7
  const EMPTY_OBJECT = Object.freeze({});
8
8
  const JSON_OPTIONS = Object.freeze({ longs: String, enums: String, bytes: String, json: true });
9
9
  const WORD_BASE = 1n << 32n;
10
- const hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
10
+ const hasOwn = Object.hasOwn;
11
11
  const isObject = (value) => typeof value === 'object' && value !== null;
12
12
  const isReaderLike = (value) => isObject(value) && value.buf instanceof Uint8Array && typeof value.pos === 'number' && typeof value.len === 'number';
13
13
  const asUint8Array = (value) => {
@@ -530,13 +530,60 @@ export const projectProtoMessage = (path, message) => {
530
530
  * null check, because an instance carries its defaults on the prototype: an absent
531
531
  * public field reads as `0` there and the bridge key would never be reached.
532
532
  */
533
- const fieldValue = (data, field, alias) => !hasOwn(data, field[0]) && alias !== undefined && alias[0] === field[0] && hasOwn(data, alias[1])
533
+ const fieldValue = (data, field, alias) =>
534
+ // The alias test first: only one field of a handful of schemas has a second
535
+ // spelling, and every other field is read without an own-property lookup.
536
+ alias !== undefined && alias[0] === field[0] && !hasOwn(data, field[0]) && hasOwn(data, alias[1])
534
537
  ? data[alias[1]]
535
538
  : data[field[0]];
539
+ /**
540
+ * Schema positions of the fields `value` holds as own properties, ascending.
541
+ *
542
+ * `toObject` and `projectForEncode` only act on own fields (prototype defaults
543
+ * are empty collections or are excluded by `hasOwn`), so visiting these
544
+ * positions instead of every field in the schema gives the same result in the
545
+ * same order. `Message` has 95 fields and a typical one sets one or two, so the
546
+ * walk follows the message rather than its schema. Returns `undefined` when the
547
+ * object's own keys are not fewer than the candidate fields, or its prototype
548
+ * could carry a field value, so the caller keeps the full walk. Instances of
549
+ * this runtime's constructors qualify only when `allowInstances` is set: their
550
+ * prototype defaults are skipped by `toObject` and `projectForEncode`, but
551
+ * `fromObject` would convert them.
552
+ */
553
+ const ownFieldPositions = (value, positions, candidates, allowInstances = true) => {
554
+ const prototype = Object.getPrototypeOf(value);
555
+ if (prototype !== null &&
556
+ prototype !== Object.prototype &&
557
+ !(allowInstances && hasOwn(prototype, INSTANCE_SCHEMA))) {
558
+ return undefined;
559
+ }
560
+ const keys = Object.getOwnPropertyNames(value);
561
+ if (keys.length >= candidates)
562
+ return undefined;
563
+ const found = [];
564
+ for (let k = 0; k < keys.length; k++) {
565
+ const position = positions.get(keys[k]);
566
+ if (position === undefined)
567
+ continue;
568
+ // Insertion sort: own keys are few and usually already in schema order.
569
+ let at = found.length;
570
+ while (at > 0 && found[at - 1] > position)
571
+ at--;
572
+ // Both spellings of an aliased field map to one position.
573
+ if (at > 0 && found[at - 1] === position)
574
+ continue;
575
+ found.splice(at, 0, position);
576
+ }
577
+ return found;
578
+ };
536
579
  /** True when either spelling is an own property, which is what keeps prototype defaults out of `toObject`. */
537
580
  const hasOwnField = (data, field, alias) => hasOwn(data, field[0]) || (alias !== undefined && alias[0] === field[0] && hasOwn(data, alias[1]));
538
581
  class ProtoCompatibilityRuntime {
539
582
  constructor(sourceNamespace) {
583
+ /** Schema position by field name (either spelling), built per schema on first use. */
584
+ this.fieldPositions = [];
585
+ /** Position in `messageFields` by field name, built per schema on first use. */
586
+ this.messageFieldPositions = [];
540
587
  this.namespace = { ...sourceNamespace };
541
588
  this.enums = PROTO_ENUM_SCHEMAS.map(([, entries]) => this.makeEnum(entries));
542
589
  // Only the 64-bit names are indexed: `hydrate` looks up every key a partial or a
@@ -593,6 +640,32 @@ class ProtoCompatibilityRuntime {
593
640
  return node.value;
594
641
  });
595
642
  }
643
+ fieldPositionsOf(schemaId) {
644
+ const existing = this.fieldPositions[schemaId];
645
+ if (existing)
646
+ return existing;
647
+ const fields = PROTO_MESSAGE_SCHEMAS[schemaId][1];
648
+ const alias = aliasFor(schemaId);
649
+ const positions = new Map();
650
+ for (let i = 0; i < fields.length; i++) {
651
+ positions.set(fields[i][0], i);
652
+ if (alias !== undefined && alias[0] === fields[i][0])
653
+ positions.set(alias[1], i);
654
+ }
655
+ this.fieldPositions[schemaId] = positions;
656
+ return positions;
657
+ }
658
+ messageFieldPositionsOf(schemaId) {
659
+ const existing = this.messageFieldPositions[schemaId];
660
+ if (existing)
661
+ return existing;
662
+ const fields = this.messageFields[schemaId];
663
+ const positions = new Map();
664
+ for (let i = 0; i < fields.length; i++)
665
+ positions.set(fields[i][0], i);
666
+ this.messageFieldPositions[schemaId] = positions;
667
+ return positions;
668
+ }
596
669
  constructorFor(schemaId) {
597
670
  var _a;
598
671
  return ((_a = this.constructors)[schemaId] ?? (_a[schemaId] = this.makeConstructor(schemaId, PROTO_MESSAGE_SCHEMAS[schemaId][1], this.sourceCodecs[schemaId])));
@@ -615,15 +688,19 @@ class ProtoCompatibilityRuntime {
615
688
  makeConstructor(schemaId, fields, sourceCodec) {
616
689
  const convertToObject = (message) => this.toObject(schemaId, message, JSON_OPTIONS);
617
690
  const path = PROTO_MESSAGE_SCHEMAS[schemaId][0];
691
+ // Only repeated and map fields get an own value per instance, so the
692
+ // constructor walks just those, in schema order, instead of every field:
693
+ // `Message` has 95 fields and none of them is a collection.
694
+ const collections = fields.filter(field => field[3] & (PROTO_FIELD_FLAG.repeated | PROTO_FIELD_FLAG.map));
618
695
  // Indexed loops: these run for every constructed instance and stay on
619
696
  // the megamorphic path at runtime, where V8 does not elide for..of
620
697
  // iterator allocations.
621
698
  const constructor = function (properties) {
622
- for (let i = 0; i < fields.length; i++) {
623
- const field = fields[i];
699
+ for (let i = 0; i < collections.length; i++) {
700
+ const field = collections[i];
624
701
  if (field[3] & PROTO_FIELD_FLAG.repeated)
625
702
  this[field[0]] = [];
626
- else if (field[3] & PROTO_FIELD_FLAG.map)
703
+ else
627
704
  this[field[0]] = {};
628
705
  }
629
706
  if (properties) {
@@ -776,8 +853,14 @@ class ProtoCompatibilityRuntime {
776
853
  // allocations (~90 iterator results per WebMessageInfo envelope).
777
854
  const fields = PROTO_MESSAGE_SCHEMAS[schemaId][1];
778
855
  const alias = aliasFor(schemaId);
779
- for (let i = 0; i < fields.length; i++) {
780
- const field = fields[i];
856
+ // A plain object reads `undefined` for every field it does not own, so
857
+ // only the positions it holds are visited, in schema order.
858
+ const positions = isObject(data)
859
+ ? ownFieldPositions(data, this.fieldPositionsOf(schemaId), fields.length, false)
860
+ : undefined;
861
+ const count = positions === undefined ? fields.length : positions.length;
862
+ for (let n = 0; n < count; n++) {
863
+ const field = fields[positions === undefined ? n : positions[n]];
781
864
  const value = fieldValue(data, field, alias);
782
865
  if (value === null || value === undefined)
783
866
  continue;
@@ -839,20 +922,29 @@ class ProtoCompatibilityRuntime {
839
922
  const output = {};
840
923
  const fields = PROTO_MESSAGE_SCHEMAS[schemaId][1];
841
924
  const alias = aliasFor(schemaId);
842
- for (const field of fields) {
843
- if (field[3] & PROTO_FIELD_FLAG.repeated) {
844
- if (options.arrays || options.defaults)
845
- output[field[0]] = [];
846
- }
847
- else if (field[3] & PROTO_FIELD_FLAG.map) {
848
- if (options.objects || options.defaults)
849
- output[field[0]] = {};
850
- }
851
- else if (options.defaults && !oneofName(field)) {
852
- output[field[0]] = this.toObjectDefault(field, options);
925
+ // Without these options the pass below writes nothing; `toJSON` sets none of them.
926
+ if (options.arrays || options.defaults || options.objects) {
927
+ for (const field of fields) {
928
+ if (field[3] & PROTO_FIELD_FLAG.repeated) {
929
+ if (options.arrays || options.defaults)
930
+ output[field[0]] = [];
931
+ }
932
+ else if (field[3] & PROTO_FIELD_FLAG.map) {
933
+ if (options.objects || options.defaults)
934
+ output[field[0]] = {};
935
+ }
936
+ else if (options.defaults && !oneofName(field)) {
937
+ output[field[0]] = this.toObjectDefault(field, options);
938
+ }
853
939
  }
854
940
  }
855
- for (const field of fields) {
941
+ // Only own fields can produce output, so a message with few of them visits
942
+ // just those positions, in schema order, and the output is unchanged.
943
+ const positions = ownFieldPositions(data, this.fieldPositionsOf(schemaId), fields.length);
944
+ const count = positions === undefined ? fields.length : positions.length;
945
+ // Indexed for the same reason as `fromObject`: no iterator result per field.
946
+ for (let n = 0; n < count; n++) {
947
+ const field = fields[positions === undefined ? n : positions[n]];
856
948
  const value = fieldValue(data, field, alias);
857
949
  if (field[3] & PROTO_FIELD_FLAG.repeated) {
858
950
  if (value &&
@@ -874,9 +966,13 @@ class ProtoCompatibilityRuntime {
874
966
  if (value === null || value === undefined || !hasOwnField(data, field, alias))
875
967
  continue;
876
968
  output[field[0]] = this.toObjectField(field, value, options);
877
- const group = oneofName(field);
878
- if (group && options.oneofs)
879
- output[group] = field[0];
969
+ // `oneofName` builds a string for every proto3-optional field, which is
970
+ // most of them, so it only runs when the option asks for the group.
971
+ if (options.oneofs) {
972
+ const group = oneofName(field);
973
+ if (group)
974
+ output[group] = field[0];
975
+ }
880
976
  }
881
977
  return output;
882
978
  }
@@ -1006,7 +1102,14 @@ class ProtoCompatibilityRuntime {
1006
1102
  (output ?? (output = { ...value }))[alias[1]] = value[alias[0]];
1007
1103
  delete output[alias[0]];
1008
1104
  }
1009
- for (const field of this.messageFields[schemaId]) {
1105
+ const messageFields = this.messageFields[schemaId];
1106
+ // Only own fields are projected, so visiting the positions the message
1107
+ // actually holds keeps schema order (and which missing codec is reported
1108
+ // first) while skipping the rest of the schema.
1109
+ const positions = ownFieldPositions(value, this.messageFieldPositionsOf(schemaId), messageFields.length);
1110
+ const count = positions === undefined ? messageFields.length : positions.length;
1111
+ for (let n = 0; n < count; n++) {
1112
+ const field = messageFields[positions === undefined ? n : positions[n]];
1010
1113
  if (!hasOwn(value, field[0]))
1011
1114
  continue;
1012
1115
  const nested = value[field[0]];
@@ -53,12 +53,24 @@ export const bytesEqual = (a, b) => {
53
53
  };
54
54
  export const utf8Encode = (text) => new TextEncoder().encode(text);
55
55
  export const utf8Decode = (bytes) => new TextDecoder('utf-8', { fatal: false }).decode(bytes);
56
+ /**
57
+ * Two-digit lowercase hex for every byte value, so encoding does one append per
58
+ * byte. Built on first use: hosts with `Buffer` never need it.
59
+ */
60
+ let hexPairs;
56
61
  export const hexEncode = (bytes) => {
62
+ // Node's native encoder when the optional global exists. `hexSlice` reads any
63
+ // Uint8Array in place. A `Buffer.from(bytes.buffer, ...)` view is avoided on
64
+ // purpose: V8 keeps typed arrays of up to 64 bytes (hashes, IDs, keys) inside
65
+ // the JS heap, and reading `.buffer` moves their bytes to a new native allocation.
66
+ const hexSlice = globalThis.Buffer
67
+ ?.prototype?.hexSlice;
68
+ if (typeof hexSlice === 'function')
69
+ return hexSlice.call(bytes, 0, bytes.length);
70
+ const pairs = (hexPairs ?? (hexPairs = Array.from({ length: 256 }, (_, byte) => HEX_DIGITS[byte >> 4] + HEX_DIGITS[byte & 0x0f])));
57
71
  let out = '';
58
- for (let i = 0; i < bytes.length; i++) {
59
- const byte = bytes[i];
60
- out += HEX_DIGITS[byte >> 4] + HEX_DIGITS[byte & 0x0f];
61
- }
72
+ for (let i = 0; i < bytes.length; i++)
73
+ out += pairs[bytes[i]];
62
74
  return out;
63
75
  };
64
76
  export const hexDecode = (text) => {
@@ -674,10 +674,13 @@ const DISPATCHERS = {
674
674
  connected: evt.connected
675
675
  });
676
676
  },
677
- // Upstream ends the socket with `timedOut` when its own QR timer gives up
678
- // (`Socket/socket.ts`), so the canonical reconnect handler already knows
679
- // this state. Reporting anything else would make it learn a second one.
680
- qrCodesExhausted: (_, dispatchCtx) => emitClose(dispatchCtx, 'QR refs attempts ended', DisconnectReason.timedOut),
677
+ qrCodesExhausted: (evt, dispatchCtx) => {
678
+ // Rust owns pairing deadlines. A live pair code must survive QR expiry
679
+ // without a close or connecting update clearing it on the consumer.
680
+ if (!evt.disconnected)
681
+ return;
682
+ emitClose(dispatchCtx, 'QR refs attempts ended', DisconnectReason.timedOut);
683
+ },
681
684
  // Straight onto upstream's own channel for this: `settings.update` already
682
685
  // declares the `disableLinkPreviews` arm, and a consumer that reads it is
683
686
  // reading the account-wide setting whichever device changed it.
@@ -4,6 +4,17 @@ export type OrdinaryStoreCallbacks = Omit<JsStoreCallbacks, keyof AtomicStoreCal
4
4
  flush?(): Promise<void>;
5
5
  };
6
6
  export type AtomicRows = Map<string, Uint8Array>;
7
+ /**
8
+ * What an atomic change reads and writes. A full `AtomicRows` map satisfies it,
9
+ * and a store can instead pass a view that reads through to its own rows and
10
+ * stages the writes, so a change costs the rows it touches.
11
+ */
12
+ export interface AtomicRowView {
13
+ get(key: string): Uint8Array | undefined;
14
+ has(key: string): boolean;
15
+ set(key: string, value: Uint8Array): unknown;
16
+ delete(key: string): boolean;
17
+ }
7
18
  export declare const rowKey: (store: string, key: string) => string;
8
19
  export declare const signedTimestamp: (value: string) => bigint;
9
20
  export type TokenRow = {
@@ -14,7 +25,7 @@ export type TokenRow = {
14
25
  export declare const decodeTokenRow: (bytes: Uint8Array) => TokenRow;
15
26
  export declare const encodeTokenRow: (row: TokenRow) => Uint8Array;
16
27
  /** The caller supplies a real transaction covering all reads and writes. */
17
- export declare const atomicCallbacks: (transaction: (change: (rows: AtomicRows) => void) => Promise<void>) => AtomicStoreCallbacks;
28
+ export declare const atomicCallbacks: (transaction: (change: (rows: AtomicRowView) => void) => Promise<void>) => AtomicStoreCallbacks;
18
29
  /** Validate migration requirements before hydration or other storage I/O. */
19
30
  export declare function assertStoreCallbacks(store: unknown): asserts store is JsStoreCallbacks;
20
31
  //# sourceMappingURL=atomic-store.d.ts.map
@@ -397,6 +397,10 @@ export const makeEventBuffer = (logger, timers = defaultEventBufferTimers, emitt
397
397
  let bufferCount = 0;
398
398
  let bufferTimeout;
399
399
  let flushPendingTimeout;
400
+ // Whether a `messages.upsert` was buffered since the last release, and its
401
+ // type. Lets `emit` skip scanning the pending upserts on every message.
402
+ let hasPendingUpserts = false;
403
+ let pendingUpsertType;
400
404
  ev.on('event', (events) => {
401
405
  for (const event of Object.keys(events)) {
402
406
  if (event === 'connection.update') {
@@ -459,6 +463,7 @@ export const makeEventBuffer = (logger, timers = defaultEventBufferTimers, emitt
459
463
  if (Object.keys(consolidated).length)
460
464
  ev.emit('event', consolidated);
461
465
  data = next;
466
+ hasPendingUpserts = false;
462
467
  logger.trace({ conditionalChatUpdatesLeft: conditionalUpdates }, 'released buffered events');
463
468
  return true;
464
469
  };
@@ -486,18 +491,29 @@ export const makeEventBuffer = (logger, timers = defaultEventBufferTimers, emitt
486
491
  return () => ev.off('event', listener);
487
492
  },
488
493
  emit(event, eventData) {
489
- if (event === 'messages.upsert') {
490
- const type = eventData.type;
494
+ const isUpsert = event === 'messages.upsert';
495
+ const upsertType = isUpsert ? eventData.type : undefined;
496
+ // Only a type change can release the pending upserts, so the pending map
497
+ // is materialized only then. Doing it on every upsert made a buffered
498
+ // burst quadratic: each message copied every message buffered before it.
499
+ if (isUpsert && hasPendingUpserts && pendingUpsertType !== upsertType) {
491
500
  const pending = Object.values(data.messageUpserts);
492
- if (pending.length && pending[0].type !== type) {
501
+ if (pending.length && pending[0].type !== upsertType) {
493
502
  ev.emit('event', {
494
503
  'messages.upsert': { messages: pending.map(item => item.message), type: pending[0].type }
495
504
  });
496
505
  data.messageUpserts = {};
497
506
  }
507
+ hasPendingUpserts = false;
498
508
  }
499
509
  if (buffering && BUFFERABLE_EVENT_SET.has(event)) {
500
510
  append(data, historyCache, event, eventData, logger);
511
+ // Every upsert buffered since the last release shares this type: a
512
+ // different one releases the batch above before it is appended.
513
+ if (isUpsert) {
514
+ hasPendingUpserts = true;
515
+ pendingUpsertType = upsertType;
516
+ }
501
517
  return true;
502
518
  }
503
519
  return ev.emit('event', { [event]: eventData });
@@ -538,6 +554,7 @@ export const makeEventBuffer = (logger, timers = defaultEventBufferTimers, emitt
538
554
  timers.clearTimeout(flushPendingTimeout);
539
555
  historyCache.clear();
540
556
  data = makeBufferData();
557
+ hasPendingUpserts = false;
541
558
  buffering = false;
542
559
  bufferCount = 0;
543
560
  ev.removeAllListeners();
@@ -13,7 +13,12 @@ export const getKeyAuthor = (key, meId = 'me') => (key?.fromMe ? meId : key?.par
13
13
  export const isStringNullOrEmpty = (value) => value == null || value === '';
14
14
  export const writeRandomPadMax16 = (msg) => {
15
15
  const padLength = (randomBytes(1)[0] & 0x0f) + 1;
16
- return Buffer.concat([msg, Buffer.alloc(padLength, padLength)]);
16
+ // One allocation, the same one `Buffer.concat` makes, without the zeroed
17
+ // pad buffer and the list it would be concatenated from.
18
+ const padded = Buffer.allocUnsafe(msg.length + padLength);
19
+ padded.set(msg, 0);
20
+ padded.fill(padLength, msg.length);
21
+ return padded;
17
22
  };
18
23
  export const unpadRandomMax16 = (e) => {
19
24
  const bytes = new Uint8Array(e);
@@ -171,11 +176,24 @@ export const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connect
171
176
  */
172
177
  export const BufferJSON = {
173
178
  replacer: (_, value) => {
179
+ // Most calls see a primitive (every string, number and boolean in the
180
+ // tree), which none of the checks below can match.
181
+ if (value === null || typeof value !== 'object')
182
+ return value;
174
183
  // Buffer.toJSON() fires before replacer sees the value, so by the time we
175
184
  // get here the replacer mostly sees `{ type: 'Buffer', data: [..] }`. Cover
176
185
  // both that case and the rare raw-Buffer case (e.g. inside a Map serializer).
177
- if (Buffer.isBuffer(value) || value instanceof Uint8Array) {
178
- return { type: 'Buffer', data: Buffer.from(value).toString('base64') };
186
+ // A Buffer is a Uint8Array, so one check covers both.
187
+ if (value instanceof Uint8Array) {
188
+ // A Buffer encodes itself. A large plain array is off-heap, so a view
189
+ // over it avoids a copy; reading `.buffer` on a small (<= 64 byte,
190
+ // on-heap) one would instead move its bytes to a new native allocation.
191
+ const data = Buffer.isBuffer(value)
192
+ ? value.toString('base64')
193
+ : value.byteLength > 64
194
+ ? Buffer.from(value.buffer, value.byteOffset, value.byteLength).toString('base64')
195
+ : Buffer.from(value).toString('base64');
196
+ return { type: 'Buffer', data };
179
197
  }
180
198
  if (value !== null && typeof value === 'object' && value.type === 'Buffer') {
181
199
  const data = value.data;
@@ -312,7 +312,9 @@ async function usePerKeyBridgeStore(folder, options) {
312
312
  throw e;
313
313
  }
314
314
  uncertain.delete(cacheKey);
315
- rememberDurable(cacheKey, copyBytes(value));
315
+ // `value` is already a private copy (taken at admission in `doSet`) that
316
+ // nothing mutates and every read copies, so it is remembered as is.
317
+ rememberDurable(cacheKey, value);
316
318
  };
317
319
  // Flush one pending key. Runs under the key lock (not tracked in
318
320
  // `admitted`: the drain loop drives it, so tracking it would make
@@ -496,10 +498,15 @@ async function usePerKeyBridgeStore(folder, options) {
496
498
  return null;
497
499
  throw e;
498
500
  }
499
- const arr = copyBytes(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
501
+ // `readFile` returns a fresh buffer this read owns, so the cache keeps a
502
+ // view of it and only the caller's array is copied. A buffer carved from
503
+ // a shared pool (sizes unknown up front) is copied instead, so the cache
504
+ // never pins a larger slab.
505
+ const read = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
506
+ const owned = data.byteOffset === 0 && data.buffer.byteLength === data.byteLength;
500
507
  if (!keyUncertain)
501
- rememberDurable(cacheKey, copyBytes(arr));
502
- return arr;
508
+ rememberDurable(cacheKey, owned ? read : copyBytes(read));
509
+ return copyBytes(read);
503
510
  };
504
511
  const doGet = (store, key) => {
505
512
  const cacheKey = `${store}\0${key}`;
@@ -1,4 +1,4 @@
1
- import { atomicCallbacks, rowKey } from './atomic-store.js';
1
+ import { atomicCallbacks } from './atomic-store.js';
2
2
  import { markNativeMemoryStore } from '../Compatibility/internal/native-memory-store.js';
3
3
  /**
4
4
  * Creates a purely in-memory authentication store.
@@ -24,15 +24,46 @@ export function useMemoryStore(options = {}) {
24
24
  };
25
25
  const memoryStore = {
26
26
  ...atomicCallbacks(async (change) => {
27
- const rows = new Map();
28
- for (const [namespace, bucket] of stores)
29
- for (const [key, value] of bucket)
30
- rows.set(rowKey(namespace, key), value);
27
+ // Reads go through to the buckets and writes are staged, so a change
28
+ // costs the rows it touches instead of a copy of every stored row (each
29
+ // key re-parsed) per transaction. Nothing is applied when `change`
30
+ // throws, and replaying the writes in order onto the buckets leaves the
31
+ // same rows in the same order as rebuilding them from a full copy.
32
+ const staged = new Map();
33
+ const writes = [];
34
+ const read = (rawKey) => {
35
+ if (staged.has(rawKey))
36
+ return staged.get(rawKey);
37
+ const [namespace, key] = JSON.parse(rawKey);
38
+ return stores.get(namespace)?.get(key);
39
+ };
40
+ const rows = {
41
+ get: read,
42
+ has: rawKey => read(rawKey) !== undefined,
43
+ set(rawKey, value) {
44
+ staged.set(rawKey, value);
45
+ writes.push([rawKey, value]);
46
+ return rows;
47
+ },
48
+ delete(rawKey) {
49
+ const existed = read(rawKey) !== undefined;
50
+ staged.set(rawKey, undefined);
51
+ writes.push([rawKey, undefined]);
52
+ return existed;
53
+ }
54
+ };
31
55
  change(rows);
32
- stores.clear();
33
- for (const [rawKey, value] of rows) {
56
+ for (const [rawKey, value] of writes) {
34
57
  const [namespace, key] = JSON.parse(rawKey);
35
- bucketForWrite(namespace).set(key, value);
58
+ if (value !== undefined) {
59
+ bucketForWrite(namespace).set(key, value);
60
+ continue;
61
+ }
62
+ const bucket = stores.get(namespace);
63
+ if (!bucket)
64
+ continue;
65
+ bucket.delete(key);
66
+ deleteEmptyBucket(namespace, bucket);
36
67
  }
37
68
  }),
38
69
  async get(store, key) {
@@ -69,13 +69,26 @@ export const assertNodeErrorFree = (node) => {
69
69
  });
70
70
  }
71
71
  };
72
- export const reduceBinaryNodeToDictionary = (node, tag) => getBinaryNodeChildren(node, tag).reduce((dictionary, { attrs }) => {
73
- if (typeof attrs.name === 'string')
74
- dictionary[attrs.name] = attrs.value || attrs.config_value;
75
- else
76
- dictionary[attrs.config_code] = attrs.value || attrs.config_value;
72
+ export const reduceBinaryNodeToDictionary = (node, tag) => {
73
+ const dictionary = {};
74
+ const content = node?.content;
75
+ if (!Array.isArray(content))
76
+ return dictionary;
77
+ // One pass, without the intermediate child list.
78
+ for (let index = 0; index < content.length; index++) {
79
+ const item = content[index];
80
+ if (item === undefined && !(index in content))
81
+ continue;
82
+ if (item.tag !== tag)
83
+ continue;
84
+ const { attrs } = item;
85
+ if (typeof attrs.name === 'string')
86
+ dictionary[attrs.name] = attrs.value || attrs.config_value;
87
+ else
88
+ dictionary[attrs.config_code] = attrs.value || attrs.config_value;
89
+ }
77
90
  return dictionary;
78
- }, {});
91
+ };
79
92
  export const getBinaryNodeMessages = ({ content }) => {
80
93
  const messages = [];
81
94
  if (Array.isArray(content)) {
@@ -95,13 +108,33 @@ export function binaryNodeToString(node, i = 0) {
95
108
  return tabs(i) + node;
96
109
  if (node instanceof Uint8Array)
97
110
  return tabs(i) + hexEncode(node);
98
- if (Array.isArray(node))
99
- return node.map(child => tabs(i + 1) + binaryNodeToString(child, i + 1)).join('\n');
111
+ if (Array.isArray(node)) {
112
+ // Same text as `node.map(...).join('\n')`, a hole included (it renders
113
+ // empty), built in one pass without the intermediate array.
114
+ const indent = tabs(i + 1);
115
+ let out = '';
116
+ for (let index = 0; index < node.length; index++) {
117
+ if (index > 0)
118
+ out += '\n';
119
+ if (index in node)
120
+ out += indent + binaryNodeToString(node[index], i + 1);
121
+ }
122
+ return out;
123
+ }
100
124
  const children = binaryNodeToString(node.content, i + 1);
101
- const tag = `<${node.tag} ${Object.entries(node.attrs || {})
102
- .filter(([, value]) => value !== undefined)
103
- .map(([key, value]) => `${key}='${value}'`)
104
- .join(' ')}`;
125
+ // Same text as filtering `Object.entries(attrs)` and joining, without the
126
+ // entry tuples and the two arrays: this formats every stanza a debug log
127
+ // prints, and large group stanzas carry an attrs object per participant.
128
+ const attrs = node.attrs || {};
129
+ let tag = `<${node.tag} `;
130
+ let separator = '';
131
+ for (const key of Object.keys(attrs)) {
132
+ const value = attrs[key];
133
+ if (value === undefined)
134
+ continue;
135
+ tag += `${separator}${key}='${value}'`;
136
+ separator = ' ';
137
+ }
105
138
  const content = children ? `>\n${children}\n${tabs(i)}</${node.tag}>` : '/>';
106
139
  return tag + content;
107
140
  }