@waffle-os/runtime 0.0.149 → 0.0.151

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 (41) hide show
  1. package/browser/diagnostic.ts +234 -2
  2. package/browser/process-broker.ts +42 -4
  3. package/browser/worker.ts +34 -5
  4. package/core/open-file.ts +126 -52
  5. package/dist/browser/diagnostic.js +150 -1
  6. package/dist/browser/process-broker.js +47 -2
  7. package/dist/browser/worker.js +24 -6
  8. package/dist/core/open-file.js +112 -50
  9. package/dist/fs/client.js +290 -46
  10. package/dist/fs/protocol.js +7 -4
  11. package/dist/fs/service.js +77 -16
  12. package/dist/fs/shared.js +6 -6
  13. package/dist/interrupt/rewriter-internal.js +2 -1
  14. package/dist/proc/abi.js +152 -16
  15. package/dist/proc/command-stdio.js +81 -33
  16. package/dist/proc/directory.js +111 -0
  17. package/dist/proc/errors.js +1 -0
  18. package/dist/proc/supervisor.js +130 -24
  19. package/dist/proc/table.js +9 -1
  20. package/dist/proc/types.js +5 -0
  21. package/dist/proc/worker-client.js +34 -5
  22. package/dist/runtime.js +3 -0
  23. package/dist/thread/service.js +85 -10
  24. package/dist/tooling/program/program-transformer.json +1 -1
  25. package/fs/client.ts +298 -44
  26. package/fs/protocol.ts +9 -4
  27. package/fs/service.ts +99 -19
  28. package/fs/shared.ts +7 -7
  29. package/interrupt/rewriter-internal.ts +2 -1
  30. package/package.json +1 -1
  31. package/proc/abi.ts +185 -17
  32. package/proc/command-stdio.ts +98 -41
  33. package/proc/directory.ts +131 -0
  34. package/proc/errors.ts +1 -0
  35. package/proc/supervisor.ts +173 -36
  36. package/proc/table.ts +11 -0
  37. package/proc/types.ts +6 -0
  38. package/proc/worker-client.ts +36 -5
  39. package/runtime.ts +3 -0
  40. package/thread/service.ts +125 -7
  41. package/tooling/program/program-transformer.json +1 -1
package/fs/client.ts CHANGED
@@ -54,8 +54,12 @@ import {
54
54
  atomicsAdd,
55
55
  atomicsCompareExchange,
56
56
  atomicsNotify,
57
+ PromiseConstructor,
58
+ scheduleTimeout,
59
+ cancelTimeout,
57
60
  atomicsWait,
58
61
  atomicsWaitAsync,
62
+ afterNativePromise,
59
63
  typedArrayLength,
60
64
  typedArraySet,
61
65
  typedArraySubarray,
@@ -137,8 +141,12 @@ export function resolveWriteFileMode(mode: WriteFileMode = false): {
137
141
  }
138
142
 
139
143
  /** Physical response room is at most one page; a larger result completes through overflow. */
144
+ const mathMin = Math.min;
145
+ const mathMax = Math.max;
146
+ const numberIsSafeInteger = Number.isSafeInteger;
147
+
140
148
  function validateResponseCapacity(capacity: number): number {
141
- if (!Number.isSafeInteger(capacity) || capacity < 0) throw new FilesystemError(28);
149
+ if (!numberIsSafeInteger(capacity) || capacity < 0) throw new FilesystemError(28);
142
150
  return capacity;
143
151
  }
144
152
  function privateInput(
@@ -180,6 +188,14 @@ let waitForObservedResolve: (
180
188
  cancellation: WaitCancellation,
181
189
  ) => ResolvedPath | number;
182
190
 
191
+ export interface DirectDisabledIOControl {
192
+ checkFatal(): void;
193
+ pending(): boolean;
194
+ wait(milliseconds: number, word: Int32Array, expected: number): void;
195
+ commitWrite?(result: { written: number; offset: number } | number): void;
196
+ deferWrite?(completion: FilesystemCompletion): void;
197
+ }
198
+
183
199
  export class FilesystemCompletion {
184
200
  static {
185
201
  waitForObservedResolve = (completion, cancellation) => completion.#wait(cancellation);
@@ -187,10 +203,12 @@ export class FilesystemCompletion {
187
203
 
188
204
  readonly cells: Int32Array;
189
205
  private changed: (() => void)[] = [];
206
+ private backendWaiters: (() => void)[] = [];
190
207
  private cancellations = new SetConstructor<() => void>();
191
208
  private decoded: unknown;
192
209
  private loading?: Promise<unknown>;
193
210
  private consumed = false;
211
+ private released = false;
194
212
  constructor(
195
213
  readonly id: number,
196
214
  readonly buffer: FilesystemRequestBuffer,
@@ -207,6 +225,22 @@ export class FilesystemCompletion {
207
225
  atomicsLoad(this.cells, 0) !== State.Pending
208
226
  );
209
227
  }
228
+ get backendSettled(): boolean {
229
+ if (atomicsLoad(this.cells, 0) !== State.Pending) return true;
230
+ const failure = this.client.transportError();
231
+ if (failure?.reason === "stale") return true;
232
+ try {
233
+ return (
234
+ requestMemoryRetired(this.client.connection.requests) &&
235
+ requestMemoryRetirementError(this.client.connection.requests) === 0
236
+ );
237
+ } catch {
238
+ return true;
239
+ }
240
+ }
241
+ get hasBackendWaiters(): boolean {
242
+ return this.backendWaiters.length > 0;
243
+ }
210
244
  get epoch(): number {
211
245
  return this.cells[5]!;
212
246
  }
@@ -214,6 +248,11 @@ export class FilesystemCompletion {
214
248
  const changed = this.changed;
215
249
  this.changed = [];
216
250
  for (let index = 0; index < changed.length; index++) changed[index]!();
251
+ if (this.backendSettled && this.backendWaiters.length) {
252
+ const waiters = this.backendWaiters;
253
+ this.backendWaiters = [];
254
+ for (let index = 0; index < waiters.length; index++) waiters[index]!();
255
+ }
217
256
  }
218
257
  cancel(): void {
219
258
  if (this.publication) this.client.cancelPublication(this.publication);
@@ -230,14 +269,50 @@ export class FilesystemCompletion {
230
269
  this.notify();
231
270
  }
232
271
  release(): void {
272
+ if (this.released) return;
273
+ this.released = true;
233
274
  // Shared state can be ready before its port notification wakes value(). An unconsumed
234
275
  // release cancels that value and notifies its waiters before removing the completion.
235
276
  if (!this.consumed) this.cancel();
236
- else this.client.connection.port.postMessage({ discard: this.id });
277
+ else {
278
+ this.client.connection.port.postMessage({ discard: this.id });
279
+ this.notify();
280
+ }
237
281
  mapDelete(this.client.completions, this.id);
238
282
  releaseRequestBuffer(this.buffer, REQUEST_CLIENT);
239
283
  if (!mapSize(this.client.completions)) wake(this.client.connection);
240
284
  }
285
+ /** Register a guest-safe callback invoked once the backend itself publishes a terminal state
286
+ * (not early on local revocation or cancellation while the service is still executing). */
287
+ onBackendSettled(callback: () => void): void {
288
+ if (this.backendSettled) {
289
+ callback();
290
+ return;
291
+ }
292
+ arrayAppend(this.backendWaiters, callback);
293
+ this.client.watchRevocation();
294
+ if (this.backendSettled) this.notify();
295
+ }
296
+ /** If the service already published State.Complete, decode and return the inline result even
297
+ * if local revocation raced after completion. Returns undefined otherwise. */
298
+ tryConsumeCommitted(): any {
299
+ if (this.consumed) return this.decoded;
300
+ if (atomicsLoad(this.cells, 0) !== State.Complete) return undefined;
301
+ const bytes = this.inlineBytes();
302
+ this.decoded = this.decode(bytes);
303
+ this.consumed = true;
304
+ return this.decoded;
305
+ }
306
+ /** Consume a ready inline response without waiting or touching Promise globals. */
307
+ consumeInline(): any {
308
+ this.check();
309
+ if (this.consumed) return this.decoded;
310
+ const bytes = this.inlineBytes();
311
+ this.check();
312
+ this.decoded = this.decode(bytes);
313
+ this.consumed = true;
314
+ return this.decoded;
315
+ }
241
316
  /** Release a ready result that the caller does not need, while still delivering failures.
242
317
  * This never waits, decodes bytes or requests an overflow transfer. */
243
318
  releaseReady(): void {
@@ -274,7 +349,7 @@ export class FilesystemCompletion {
274
349
  }
275
350
  private inlineBytes(): Uint8Array {
276
351
  const size = this.cells[2]!;
277
- const available = Math.min(size, this.buffer.length - HEADER);
352
+ const available = mathMin(size, this.buffer.length - HEADER);
278
353
  return new Uint8ArrayConstructor(typedArraySubarray(requestBytes(this.buffer), 0, available));
279
354
  }
280
355
  wait(): any {
@@ -360,6 +435,11 @@ interface StagedPreparation {
360
435
  append: boolean;
361
436
  bytes: Uint8Array;
362
437
  }
438
+ function chunkLength(chunks: readonly Uint8Array[]): number {
439
+ let total = 0;
440
+ for (let i = 0; i < chunks.length; i++) total += typedArrayLength(chunks[i]!);
441
+ return total;
442
+ }
363
443
  /** A private copy of the first bytes of a write, at most one transport page. */
364
444
  function stagedBytes(chunks: readonly Uint8Array[]): Uint8Array {
365
445
  let length = 0;
@@ -375,8 +455,9 @@ function stagedBytes(chunks: readonly Uint8Array[]): Uint8Array {
375
455
  return bytes;
376
456
  }
377
457
  function sameBytes(left: Uint8Array, right: Uint8Array): boolean {
378
- if (left.length !== right.length) return false;
379
- for (let index = 0; index < left.length; index++) if (left[index] !== right[index]) return false;
458
+ const length = typedArrayLength(left);
459
+ if (length !== typedArrayLength(right)) return false;
460
+ for (let index = 0; index < length; index++) if (left[index] !== right[index]) return false;
380
461
  return true;
381
462
  }
382
463
  /** Copies `bytes` into the iovecs, starting `skip` bytes into their combined range. */
@@ -528,7 +609,7 @@ export class FilesystemClient implements FileSystem {
528
609
  this.epoch = new Int32ArrayConstructor(connection.epoch);
529
610
  this.signal = new Int32ArrayConstructor(connection.signal);
530
611
  const revoked = sharedRevoked(connection);
531
- this.revoked = () => revoked() || !!this.transportError();
612
+ this.revoked = () => this.disposed || revoked() || !!this.transportError();
532
613
  if (connection.residentPublication)
533
614
  this.resident = new ResidentAttachment(connection.residentPublication, this.revoked);
534
615
  this.section = new FilesystemTransportSection(connection, this.requests.memory, this.revoked);
@@ -617,26 +698,104 @@ export class FilesystemClient implements FileSystem {
617
698
  /** A single shared-signal waiter handles service death without a port completion message.
618
699
  * Normal replies still use the port; the watcher exits when the last completion is released.
619
700
  */
701
+ private disposed = false;
702
+ private finishedDispose = false;
703
+ private deferredWriteCount = 0;
704
+ private deferredWaiters = new SetConstructor<() => void>();
705
+ trackDeferredWrite(completion: FilesystemCompletion, onSettled: () => void): void {
706
+ let done = false;
707
+ this.deferredWriteCount++;
708
+ completion.onBackendSettled(() => {
709
+ if (done) return;
710
+ done = true;
711
+ this.deferredWriteCount--;
712
+ try {
713
+ onSettled();
714
+ } finally {
715
+ if (this.deferredWriteCount === 0) {
716
+ this.notifyDeferredWaiters();
717
+ if (this.disposed) this.finishDispose();
718
+ }
719
+ }
720
+ });
721
+ }
722
+ private notifyDeferredWaiters(): void {
723
+ const waiters = this.deferredWaiters;
724
+ this.deferredWaiters = new SetConstructor();
725
+ setForEach(waiters, (waiter) => waiter());
726
+ }
727
+ hasDeferredWrites(): boolean {
728
+ return this.deferredWriteCount > 0;
729
+ }
730
+ /** Wait for deferred direct-disabled writes to settle authoritatively at the backend.
731
+ * With no timeout, waits until every deferred write settles; with a finite timeout, returns
732
+ * true if all settled in time or false if deferred writes are still pending. */
733
+ settleDeferredWrites(timeoutMs?: number): Promise<boolean> {
734
+ if (this.deferredWriteCount === 0)
735
+ return new PromiseConstructor<boolean>((resolve) => resolve(true));
736
+ return new PromiseConstructor<boolean>((resolve) => {
737
+ let finished = false;
738
+ let timer: ReturnType<typeof scheduleTimeout> | undefined;
739
+ const onSettled = () => done(true);
740
+ const done = (settled: boolean) => {
741
+ if (finished) return;
742
+ finished = true;
743
+ if (timer !== undefined) cancelTimeout(timer);
744
+ setDelete(this.deferredWaiters, onSettled);
745
+ resolve(settled);
746
+ };
747
+ if (timeoutMs !== undefined)
748
+ timer = scheduleTimeout(() => done(false), mathMax(1, timeoutMs));
749
+ setAdd(this.deferredWaiters, onSettled);
750
+ if (this.deferredWriteCount === 0) done(true);
751
+ });
752
+ }
753
+ private sweepRevokedCompletions(): boolean {
754
+ let waitingBackend = false;
755
+ mapForEach(this.completions, (completion) => {
756
+ if (!completion.hasBackendWaiters) completion.cancel();
757
+ else if (completion.backendSettled) completion.notify();
758
+ else waitingBackend = true;
759
+ });
760
+ return waitingBackend;
761
+ }
762
+ private notifySettledBackendWaiters(): void {
763
+ mapForEach(this.completions, (completion) => {
764
+ if (completion.hasBackendWaiters && completion.backendSettled) completion.notify();
765
+ });
766
+ }
620
767
  watchRevocation(): void {
621
768
  if (this.watchingRevocation) return;
622
769
  this.watchingRevocation = true;
623
- void this.monitorRevocation();
770
+ this.monitorRevocation();
624
771
  }
625
- private async monitorRevocation(): Promise<void> {
772
+ private monitorRevocation(): void {
626
773
  const signal = this.signal;
627
- try {
628
- while (mapSize(this.completions)) {
629
- const observed = atomicsLoad(signal, 0);
630
- if (this.revoked()) {
631
- mapForEach(this.completions, (completion) => completion.cancel());
632
- return;
774
+ const stop = () => {
775
+ this.watchingRevocation = false;
776
+ };
777
+ const step = () => {
778
+ try {
779
+ while (mapSize(this.completions)) {
780
+ const observed = atomicsLoad(signal, 0);
781
+ if (this.revoked()) {
782
+ if (!this.sweepRevokedCompletions()) break;
783
+ } else {
784
+ this.notifySettledBackendWaiters();
785
+ }
786
+ if (!mapSize(this.completions)) break;
787
+ const waiting = atomicsWaitAsync(signal, 0, observed);
788
+ if (waiting.async) {
789
+ afterNativePromise(waiting.value, step, stop);
790
+ return;
791
+ }
633
792
  }
634
- const waiting = atomicsWaitAsync(signal, 0, observed);
635
- if (waiting.async) await waiting.value;
793
+ } catch {
794
+ // Stop watching if the signal backing is retired or unavailable.
636
795
  }
637
- } finally {
638
- this.watchingRevocation = false;
639
- }
796
+ stop();
797
+ };
798
+ step();
640
799
  }
641
800
  fork(): FilesystemConnection {
642
801
  const failure = this.transportError();
@@ -815,9 +974,9 @@ export class FilesystemClient implements FileSystem {
815
974
  const inputLength = typedArrayLength(input);
816
975
  const total = inputLength + typedArrayLength(data);
817
976
  const privateLength = total > REQUEST_INLINE_BYTES ? total : 0;
818
- const room = Math.min(validateResponseCapacity(capacity), PAGE);
977
+ const room = mathMin(validateResponseCapacity(capacity), PAGE);
819
978
  const buffer = this.requests.allocate(
820
- privateLength ? room : Math.max(total, room),
979
+ privateLength ? room : mathMax(total, room),
821
980
  privateLength,
822
981
  );
823
982
  try {
@@ -889,16 +1048,10 @@ export class FilesystemClient implements FileSystem {
889
1048
  if (!options.signal?.aborted) setAdd(this.watchers, watcher);
890
1049
  return watcher;
891
1050
  }
892
- dispose(): void {
893
- this.resident?.invalidate();
894
- this.beginWorkspaceStop();
895
- // The disposing agent is quiescent: no synchronous file operation can be active here.
896
- reapFilesystem(this.connection);
1051
+ private clearDisposedCaches(): void {
897
1052
  setForEach(this.watchers, (watcher) => {
898
1053
  void watcher.close();
899
1054
  });
900
- mapForEach(this.completions, (completion) => completion.release());
901
- mapClear(this.completions);
902
1055
  mapClear(this.ioPreparations);
903
1056
  mapClear(this.stagedWrites);
904
1057
  this.stagedHandles = new SetConstructor();
@@ -909,9 +1062,34 @@ export class FilesystemClient implements FileSystem {
909
1062
  mapClear(this.openHandles);
910
1063
  mapClear(this.fileSlots);
911
1064
  mapClear(this.capabilityEntries);
1065
+ }
1066
+ private finishDispose(): void {
1067
+ if (this.finishedDispose) return;
1068
+ this.finishedDispose = true;
1069
+ this.disposed = true;
1070
+ // The disposing agent is quiescent: no synchronous file operation or deferred write is active.
1071
+ reapFilesystem(this.connection);
1072
+ this.clearDisposedCaches();
1073
+ mapForEach(this.completions, (completion) => completion.release());
1074
+ mapClear(this.completions);
912
1075
  this.sweep();
913
1076
  this.connection.port.close();
914
1077
  }
1078
+ dispose(): void {
1079
+ if (this.finishedDispose) return;
1080
+ this.disposed = true;
1081
+ this.resident?.invalidate();
1082
+ this.beginWorkspaceStop();
1083
+ if (this.deferredWriteCount > 0) {
1084
+ this.clearDisposedCaches();
1085
+ mapForEach(this.completions, (completion) => {
1086
+ if (!completion.hasBackendWaiters) completion.release();
1087
+ });
1088
+ this.watchRevocation();
1089
+ return;
1090
+ }
1091
+ this.finishDispose();
1092
+ }
915
1093
  private version(): number {
916
1094
  if (this.revoked()) throw new FilesystemError(11);
917
1095
  return atomicsLoad(this.epoch, 0);
@@ -1215,10 +1393,12 @@ export class FilesystemClient implements FileSystem {
1215
1393
  }
1216
1394
  private copyReadResult(chunks: readonly Uint8Array[], bytes: Uint8Array): number {
1217
1395
  let at = 0;
1218
- for (const chunk of chunks) {
1219
- const count = Math.min(chunk.length, bytes.length - at);
1220
- if (count <= 0) break;
1221
- typedArraySet(chunk, bytes.subarray(at, at + count));
1396
+ const total = typedArrayLength(bytes);
1397
+ for (let i = 0; i < chunks.length && at < total; i++) {
1398
+ const chunk = chunks[i]!;
1399
+ const count = Math.min(typedArrayLength(chunk), total - at);
1400
+ if (count <= 0) continue;
1401
+ typedArraySet(chunk, typedArraySubarray(bytes, at, at + count));
1222
1402
  at += count;
1223
1403
  }
1224
1404
  return at;
@@ -1263,8 +1443,7 @@ export class FilesystemClient implements FileSystem {
1263
1443
  * owner. A cold file is read as a range and is not loaded whole, so this stays a short read. */
1264
1444
  private readUnloaded(handle: FileHandle, chunks: readonly Uint8Array[], offset: number): number {
1265
1445
  try {
1266
- let requested = 0;
1267
- for (let i = 0; i < chunks.length; i++) requested += chunks[i]!.length;
1446
+ const requested = chunkLength(chunks);
1268
1447
  const bytes: Uint8Array = this.call("read", [handle, Math.min(PAGE, requested), offset]);
1269
1448
  return this.copyReadResult(chunks, bytes);
1270
1449
  } catch (failure) {
@@ -1285,12 +1464,78 @@ export class FilesystemClient implements FileSystem {
1285
1464
  this.section.exit();
1286
1465
  }
1287
1466
  }
1467
+ /** True when the backend disables direct shared-memory file I/O (e.g. multi-tab attach). */
1468
+ get directDisabled(): boolean {
1469
+ return this.shared.isDirectDisabled();
1470
+ }
1471
+ /** Bounded (<= PAGE) regular-file RPC used by ProcessABI when direct shared-memory I/O is
1472
+ * disabled. Yields immediately on pending signals before dispatch, interrupts in-flight reads on
1473
+ * handled signals, and checks fatal liveness on every wait slice. */
1474
+ directDisabledIO(
1475
+ operation: "read" | "write" | "append",
1476
+ handle: FileHandle,
1477
+ bytes: Uint8Array,
1478
+ offset: number,
1479
+ control: DirectDisabledIOControl,
1480
+ ): { written: number; offset: number } | number {
1481
+ if (operation !== "append" && (!numberIsSafeInteger(offset) || offset < 0)) return -28;
1482
+ control.checkFatal();
1483
+ if (control.pending()) return -6;
1484
+ const count = mathMin(PAGE, typedArrayLength(bytes));
1485
+ if (count === 0) return operation === "append" ? { written: 0, offset } : 0;
1486
+ const completion =
1487
+ operation === "read"
1488
+ ? this.submit("read", [handle, count, offset])
1489
+ : operation === "append"
1490
+ ? this.submit("append", [handle], typedArraySubarray(bytes, 0, count))
1491
+ : this.submit("write", [handle, offset], typedArraySubarray(bytes, 0, count));
1492
+ let handedOff = false;
1493
+ try {
1494
+ while (!completion.ready) {
1495
+ const observed = atomicsLoad(this.signal, 0);
1496
+ if (operation !== "read" && atomicsLoad(completion.cells, 0) === State.Complete) break;
1497
+ control.checkFatal();
1498
+ if (operation === "read" && control.pending()) {
1499
+ completion.cancel();
1500
+ return -6;
1501
+ }
1502
+ if (completion.ready) break;
1503
+ control.wait(10, this.signal, observed);
1504
+ }
1505
+ if (operation === "read") {
1506
+ control.checkFatal();
1507
+ const data = completion.consumeInline() as Uint8Array;
1508
+ typedArraySet(bytes, data, 0);
1509
+ return typedArrayLength(data);
1510
+ }
1511
+ const committed = completion.tryConsumeCommitted();
1512
+ if (committed !== undefined) return committed as { written: number; offset: number } | number;
1513
+ return completion.consumeInline() as { written: number; offset: number } | number;
1514
+ } catch (error) {
1515
+ if (operation !== "read") {
1516
+ const committed = completion.tryConsumeCommitted();
1517
+ if (committed !== undefined) {
1518
+ control.commitWrite?.(committed as { written: number; offset: number } | number);
1519
+ } else if (control.deferWrite) {
1520
+ handedOff = true;
1521
+ control.deferWrite(completion);
1522
+ }
1523
+ }
1524
+ if (isInstance(error, FilesystemError)) {
1525
+ control.checkFatal();
1526
+ return -error.errno;
1527
+ }
1528
+ throw error;
1529
+ } finally {
1530
+ if (!handedOff) completion.release();
1531
+ }
1532
+ }
1288
1533
  /** Nonblocking runtime_proc I/O. Never retain an iovec across an EAGAIN boundary. */
1289
1534
  tryRead(handle: FileHandle, chunks: readonly Uint8Array[], offset: number): number {
1290
1535
  if (this.shared.isDirectDisabled()) return -58;
1291
1536
  if (this.resident)
1292
1537
  return this.residentIO(() => this.resident?.client?.tryRead(handle, chunks, offset) ?? -6);
1293
- if (!(offset >= 0)) return -28;
1538
+ if (!Number.isSafeInteger(offset) || offset < 0) return -28;
1294
1539
  try {
1295
1540
  const prepared = this.preparedRead(handle, chunks, offset);
1296
1541
  if (prepared !== undefined) return prepared;
@@ -1327,7 +1572,7 @@ export class FilesystemClient implements FileSystem {
1327
1572
  if (this.resident)
1328
1573
  return this.residentIO(() => this.resident?.client?.tryWrite(handle, chunks, offset) ?? -6);
1329
1574
  if (this.shared.publication) return this.publishedWrite(handle, chunks, offset, true);
1330
- if (!(offset >= 0)) return -28;
1575
+ if (!Number.isSafeInteger(offset) || offset < 0) return -28;
1331
1576
  try {
1332
1577
  if (!this.preparedWrite(handle)) return -6;
1333
1578
  const slot = this.directSlot(handle);
@@ -1653,6 +1898,16 @@ export class FilesystemClient implements FileSystem {
1653
1898
  return { readable: true, writable: true, hangup: false };
1654
1899
  }
1655
1900
  }
1901
+ /** True while a nonblocking filesystem preparation or staged write is still in flight. */
1902
+ ioPending(handle: FileHandle, writing: boolean): boolean {
1903
+ if (this.shared.isDirectDisabled()) return false;
1904
+ const preparation = mapGet(this.ioPreparations, handle);
1905
+ if (preparation && !preparation.completion.ready)
1906
+ return preparation.kind === "read" ? !writing : true;
1907
+ if (!writing) return false;
1908
+ const stage = mapGet(this.stagedWrites, handle);
1909
+ return stage !== undefined && !stage.completion.ready;
1910
+ }
1656
1911
  resolveBorrowed(
1657
1912
  directory: FileHandle,
1658
1913
  path: string,
@@ -1835,7 +2090,7 @@ export class FilesystemClient implements FileSystem {
1835
2090
  if (this.connection.residentPublication?.kind === "file")
1836
2091
  return this.tryRead(handle, chunks, offset);
1837
2092
  if (this.resident) return this.workspaceRead(handle, chunks, offset);
1838
- if (!(offset >= 0)) return -28; // EINVAL: positions are never negative.
2093
+ if (!Number.isSafeInteger(offset) || offset < 0) return -28; // EINVAL: positions are never negative.
1839
2094
  if (this.shared.isDirectDisabled()) return this.readUnloaded(handle, chunks, offset);
1840
2095
  const slot = this.directSlot(handle);
1841
2096
  if (slot) {
@@ -1883,19 +2138,18 @@ export class FilesystemClient implements FileSystem {
1883
2138
  return this.tryWrite(handle, chunks, offset);
1884
2139
  if (this.resident) return this.workspaceWrite(handle, chunks, offset, false);
1885
2140
  if (this.shared.publication) return this.publishedWrite(handle, chunks, offset, false);
1886
- if (!(offset >= 0)) return -28; // EINVAL: positions are never negative.
2141
+ if (!Number.isSafeInteger(offset) || offset < 0) return -28; // EINVAL: positions are never negative.
1887
2142
  chunks = fixedWriteSources(chunks);
1888
2143
  if (this.shared.isDirectDisabled()) {
1889
2144
  try {
1890
- let total = 0;
1891
- for (let i = 0; i < chunks.length; i++) total += chunks[i]!.length;
2145
+ const total = chunkLength(chunks);
1892
2146
  const limit = Math.min(total, 1024 * 1024);
1893
2147
  const data = new Uint8ArrayConstructor(limit);
1894
2148
  let at = 0;
1895
2149
  for (let i = 0; i < chunks.length && at < limit; i++) {
1896
2150
  const chunk = chunks[i]!;
1897
- const count = Math.min(chunk.length, limit - at);
1898
- if (count > 0) typedArraySet(data, chunk.subarray(0, count), at);
2151
+ const count = Math.min(typedArrayLength(chunk), limit - at);
2152
+ if (count > 0) typedArraySet(data, typedArraySubarray(chunk, 0, count), at);
1899
2153
  at += count;
1900
2154
  }
1901
2155
  return this.call("write", [handle, offset], data);
@@ -1989,8 +2243,8 @@ export class FilesystemClient implements FileSystem {
1989
2243
  let at = 0;
1990
2244
  for (let i = 0; i < chunks.length && at < limit; i++) {
1991
2245
  const chunk = chunks[i]!;
1992
- const count = Math.min(chunk.length, limit - at);
1993
- if (count > 0) typedArraySet(data, chunk.subarray(0, count), at);
2246
+ const count = Math.min(typedArrayLength(chunk), limit - at);
2247
+ if (count > 0) typedArraySet(data, typedArraySubarray(chunk, 0, count), at);
1994
2248
  at += count;
1995
2249
  }
1996
2250
  return this.call("append", [handle], data);
package/fs/protocol.ts CHANGED
@@ -9,6 +9,8 @@ import { FilesystemSection } from "./section.js";
9
9
  export { FilesystemSection, isRevoked } from "./section.js";
10
10
  import { workspacePublication, type WorkspaceConfiguration } from "./workspace-protocol.js";
11
11
  import {
12
+ atomicsAdd,
13
+ atomicsNotify,
12
14
  BigIntConstructor,
13
15
  bigintToString,
14
16
  Int32ArrayConstructor,
@@ -16,6 +18,7 @@ import {
16
18
  objectKeys,
17
19
  stringIncludes,
18
20
  SharedArrayBufferConstructor,
21
+ typedArrayBuffer,
19
22
  Uint8ArrayConstructor,
20
23
  objectDefineProperty,
21
24
  } from "../proc/intrinsics.js";
@@ -456,9 +459,9 @@ export function reapFilesystem(connection: FilesystemIdentity): void {
456
459
  wake(connection);
457
460
  }
458
461
  export function wake(connection: FilesystemIdentity): void {
459
- const signal = new Int32Array(connection.signal);
460
- Atomics.add(signal, 0, 1);
461
- Atomics.notify(signal, 0);
462
+ const signal = new Int32ArrayConstructor(connection.signal);
463
+ atomicsAdd(signal, 0, 1);
464
+ atomicsNotify(signal, 0);
462
465
  }
463
466
  const encoder = new TextEncoder();
464
467
  const decoder = new TextDecoder();
@@ -496,7 +499,9 @@ function decodable(buffer: ArrayBufferLike): boolean {
496
499
  }
497
500
  export function unpack(bytes: Uint8Array): any {
498
501
  // TextDecoder rejects views over shared or resizable backing, so only those are copied.
499
- const text = decoder.decode(decodable(bytes.buffer) ? bytes : new Uint8Array(bytes));
502
+ const text = decoder.decode(
503
+ decodable(typedArrayBuffer(bytes)) ? bytes : new Uint8ArrayConstructor(bytes),
504
+ );
500
505
  const value: unknown = JSON.parse(text);
501
506
  // A tag is an own object key beginning with "$", which JSON writes as `"$` or as the escape
502
507
  // for U+0024. Without either, no object is tagged and the parsed tree is already the answer.