@ai-ecoverse/slicc-kernel 1.193.3 → 1.194.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.
@@ -492,14 +492,14 @@ var KernelSide = class {
492
492
  Atomics.store(this.header, SAB_I_STATE, SAB_STATE_IDLE);
493
493
  const mirror = this.mirror(true);
494
494
  const total = payload.byteLength;
495
- const reply = total > this.max ? {
495
+ const reply2 = total > this.max ? {
496
496
  status,
497
497
  bytes: payload.slice(0, this.max),
498
498
  total,
499
499
  part: this.keep(payload),
500
500
  mirror
501
501
  } : { status, bytes: payload, total, mirror };
502
- pending.resolve(reply);
502
+ pending.resolve(reply2);
503
503
  }
504
504
  end() {
505
505
  if (this.ended) return;
@@ -739,6 +739,156 @@ function remoteWorker(open, options = {}) {
739
739
  };
740
740
  }
741
741
 
742
+ // src/cdp/lease.ts
743
+ var CDP_LEASE_VERSION = 1;
744
+ var LEASE_MAX_MESSAGE = 128 * 1024;
745
+ var BOOT_FIELDS = {
746
+ browser: /* @__PURE__ */ new Set(["cdpLease", "metadata", "media", "ca"]),
747
+ node: /* @__PURE__ */ new Set(["cdpLease"]),
748
+ cloudflare: /* @__PURE__ */ new Set(["cdpLease", "loader"])
749
+ };
750
+ function checkedLease(options, host) {
751
+ const lease = options.cdpLease;
752
+ if (lease === void 0) return void 0;
753
+ if (typeof lease?.tag !== "string" || Reflect.ownKeys(lease).some((k) => k !== "tag" && k !== "adapter") || !/^[a-zA-Z0-9:_-]{1,128}$/.test(lease.tag) || typeof lease.adapter?.request !== "function" || typeof lease.adapter?.action !== "function") {
754
+ throw new TypeError("cdpLease requires one job tag and a request/action adapter");
755
+ }
756
+ if (Object.getPrototypeOf(options) !== Object.prototype || Reflect.ownKeys(options).some((k) => typeof k !== "string" || !BOOT_FIELDS[host].has(k))) {
757
+ throw new TypeError("unexpected boot option for a lease-only kernel");
758
+ }
759
+ return { tag: lease.tag, adapter: lease.adapter };
760
+ }
761
+ var LEASE_MAX_CONNECTIONS = 8;
762
+ var ERRORS = /* @__PURE__ */ new Map([
763
+ ["E_PENDING", "Waiting for the owner."],
764
+ ["E_SCOPE", "Outside the approved lease."],
765
+ ["E_EXPIRED", "The lease expired."],
766
+ ["E_REVOKED", "The lease is no longer active."],
767
+ ["E_DENIED", "The owner declined the request."],
768
+ ["E_UNSUPPORTED", "Lease operation unavailable."],
769
+ ["E_REPLACED", "The lease was replaced."],
770
+ ["E_STALE", "The element reference is stale."],
771
+ ["E_UNAVAILABLE", "No job-scoped adapter is available."],
772
+ ["E_OUTCOME_UNKNOWN", "The action may have taken effect. Do not automatically retry."]
773
+ ]);
774
+ function record(value2) {
775
+ return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
776
+ }
777
+ function fields(obj, ...keys2) {
778
+ return Object.keys(obj).every((k) => keys2.includes(k));
779
+ }
780
+ function opaque(v) {
781
+ return typeof v === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(v);
782
+ }
783
+ function hasControl(text) {
784
+ for (let i = 0; i < text.length; i++) {
785
+ const n = text.charCodeAt(i);
786
+ if (n < 32 || n === 127) return true;
787
+ }
788
+ return false;
789
+ }
790
+ function https(v) {
791
+ if (typeof v !== "string" || v.length > 8192 || !v.startsWith("https://") || /\s/u.test(v) || v.includes("\\") || hasControl(v))
792
+ return false;
793
+ const url = URL.parse(v);
794
+ return url !== null && !url.username && !url.password && !/^https:\/\/[^/?#]*@/.test(v);
795
+ }
796
+ function rule(v) {
797
+ if (!record(v) || !fields(v, "kind", "url") || !https(v.url) || /\*|%(?![0-9a-f]{2})/i.test(v.url))
798
+ return false;
799
+ const url = new URL(v.url);
800
+ if (v.kind === "origin") return url.origin === v.url;
801
+ if (url.href !== v.url || /%2f|%5c/i.test(url.pathname)) return false;
802
+ if (v.kind === "exact") return true;
803
+ return v.kind === "path-prefix" && url.origin + url.pathname === v.url && (url.pathname === "/" || !url.pathname.endsWith("/"));
804
+ }
805
+ function request(p) {
806
+ return fields(p, "allow", "ttlSeconds", "lease", "reason") && Array.isArray(p.allow) && p.allow.length > 0 && p.allow.length <= 64 && p.allow.every(rule) && new Set(p.allow.map(({ kind, url }) => `${kind}:${url}`)).size === p.allow.length && (p.lease === void 0 ? Number.isSafeInteger(p.ttlSeconds) && p.ttlSeconds > 0 : opaque(p.lease) && p.ttlSeconds === void 0) && (p.reason === void 0 || typeof p.reason === "string" && p.reason.length > 0 && p.reason.length <= 1024);
807
+ }
808
+ function action(p) {
809
+ if (!fields(p, "lease", "op", "args") || !opaque(p.lease) || !record(p.args)) return false;
810
+ const a = p.args;
811
+ switch (p.op) {
812
+ case "goto":
813
+ return fields(a, "url") && https(a.url);
814
+ case "snapshot":
815
+ return fields(a);
816
+ default:
817
+ return false;
818
+ }
819
+ }
820
+ async function dispatch(adapter, ctx, method, p) {
821
+ if (record(p) && method === "Slicc.leaseRequest" && request(p)) {
822
+ const reply2 = await adapter.request(p, ctx);
823
+ if (opaque(reply2.request) && opaque(reply2.lease) && typeof reply2.jkt === "string" && /^[A-Za-z0-9_-]{43}$/.test(reply2.jkt)) {
824
+ return { request: reply2.request, lease: reply2.lease, jkt: reply2.jkt };
825
+ }
826
+ }
827
+ if (record(p) && method === "Slicc.leaseAction" && action(p)) {
828
+ let result;
829
+ try {
830
+ ({ result } = await adapter.action(p, ctx));
831
+ } catch (err) {
832
+ if (record(err) && typeof err.reason === "string" && ERRORS.has(err.reason)) throw err;
833
+ throw { reason: "E_OUTCOME_UNKNOWN" };
834
+ }
835
+ if (record(result)) {
836
+ if (p.op !== "snapshot" && fields(result)) return { result: {} };
837
+ if (p.op === "snapshot" && fields(result, "text") && typeof result.text === "string" && result.text.length <= 65536)
838
+ return { result: { text: result.text } };
839
+ }
840
+ throw { reason: "E_OUTCOME_UNKNOWN" };
841
+ }
842
+ throw new Error();
843
+ }
844
+ async function reply(adapter, ctx, message3, busy) {
845
+ let id2 = null;
846
+ try {
847
+ const cmd = JSON.parse(message3);
848
+ if (!record(cmd) || !Number.isSafeInteger(cmd.id) || cmd.id < 1) throw new Error();
849
+ id2 = cmd.id;
850
+ if (!fields(cmd, "id", "method", "params")) throw new Error();
851
+ if (busy) throw { reason: "E_UNAVAILABLE" };
852
+ const result = await dispatch(adapter, ctx, cmd.method, cmd.params);
853
+ const text = JSON.stringify({ id: id2, result });
854
+ if (new TextEncoder().encode(text).length > LEASE_MAX_MESSAGE) throw new Error();
855
+ return text;
856
+ } catch (err) {
857
+ const reason = record(err) && typeof err.reason === "string" && ERRORS.has(err.reason) ? err.reason : "E_UNSUPPORTED";
858
+ return JSON.stringify({
859
+ id: id2,
860
+ error: { code: -32e3, message: ERRORS.get(reason), data: { reason } }
861
+ });
862
+ }
863
+ }
864
+ function leaseHook({ tag, adapter }) {
865
+ let pending = 0;
866
+ return async ({ stamp }) => {
867
+ if (!stamp || stamp.tag !== tag) throw new Error("lease unavailable");
868
+ const stop = new AbortController();
869
+ const conn = {
870
+ onmessage: null,
871
+ onclose: null,
872
+ send(message3) {
873
+ if (stop.signal.aborted) return;
874
+ const busy = pending >= LEASE_MAX_CONNECTIONS;
875
+ pending++;
876
+ void reply(
877
+ adapter,
878
+ { stamp: structuredClone(stamp), signal: stop.signal },
879
+ message3,
880
+ busy
881
+ ).then((text) => {
882
+ pending--;
883
+ if (!stop.signal.aborted) conn.onmessage?.(text);
884
+ });
885
+ },
886
+ close: () => stop.abort()
887
+ };
888
+ return conn;
889
+ };
890
+ }
891
+
742
892
  // src/bytes.ts
743
893
  function fresh(bytes, start2 = 0, end = bytes.length) {
744
894
  return new Uint8Array(bytes.subarray(start2, end));
@@ -869,7 +1019,7 @@ function heldConnection(send3, close) {
869
1019
  }
870
1020
 
871
1021
  // src/cdp/port.ts
872
- function serveCdpPort(port, hook, request, onDone) {
1022
+ function serveCdpPort(port, hook, request2, onDone) {
873
1023
  let conn;
874
1024
  let done4 = false;
875
1025
  const end = () => {
@@ -890,7 +1040,7 @@ function serveCdpPort(port, hook, request, onDone) {
890
1040
  }
891
1041
  });
892
1042
  port.start?.();
893
- new Promise((resolve2) => resolve2(hook(request))).then(
1043
+ new Promise((resolve2) => resolve2(hook(request2))).then(
894
1044
  (opened2) => {
895
1045
  conn = opened2;
896
1046
  if (done4) return opened2.close();
@@ -913,7 +1063,7 @@ function serveCdpPort(port, hook, request, onDone) {
913
1063
  };
914
1064
  }
915
1065
  function portCdpHook(ask, gone, ports = messageChannel) {
916
- return (request) => new Promise((resolve2, reject) => {
1066
+ return (request2) => new Promise((resolve2, reject) => {
917
1067
  const { port1, port2 } = ports();
918
1068
  let closed = false;
919
1069
  const held2 = heldConnection(
@@ -951,7 +1101,7 @@ function portCdpHook(ask, gone, ports = messageChannel) {
951
1101
  port1.addEventListener("close", () => lost("the CDP host closed its port"));
952
1102
  port1.start();
953
1103
  void gone?.then(() => lost("the CDP host is gone"));
954
- ask(request, port2);
1104
+ ask(request2, port2);
955
1105
  });
956
1106
  }
957
1107
 
@@ -1022,7 +1172,7 @@ function devicesAsker(port) {
1022
1172
  }
1023
1173
  });
1024
1174
  const hookFor = (client2) => ({
1025
- open: async (request) => {
1175
+ open: async (request2) => {
1026
1176
  const id2 = ++next3;
1027
1177
  const remote = {
1028
1178
  opened: Promise.withResolvers(),
@@ -1036,15 +1186,15 @@ function devicesAsker(port) {
1036
1186
  const abort = () => {
1037
1187
  remotes.delete(id2);
1038
1188
  post({ id: id2, cancel: "interrupted" });
1039
- remote.opened.reject(request.signal.reason);
1189
+ remote.opened.reject(request2.signal.reason);
1040
1190
  };
1041
- request.signal.addEventListener("abort", abort, { once: true });
1042
- const { path, flags: flags2, stamp } = request;
1191
+ request2.signal.addEventListener("abort", abort, { once: true });
1192
+ const { path, flags: flags2, stamp } = request2;
1043
1193
  post({ id: id2, open: { client: client2, path, flags: flags2, stamp } });
1044
1194
  try {
1045
1195
  await remote.opened.promise;
1046
1196
  } finally {
1047
- request.signal.removeEventListener("abort", abort);
1197
+ request2.signal.removeEventListener("abort", abort);
1048
1198
  }
1049
1199
  return streams(id2, remote);
1050
1200
  }
@@ -1192,7 +1342,7 @@ function embedderAsker(port) {
1192
1342
  asked.chunks.push(item);
1193
1343
  asked.wake?.();
1194
1344
  };
1195
- const reply = (id2, asked) => new ReadableStream(
1345
+ const reply2 = (id2, asked) => new ReadableStream(
1196
1346
  {
1197
1347
  pull: async (controller) => {
1198
1348
  if (asked.chunks.length === 0) {
@@ -1228,30 +1378,30 @@ function embedderAsker(port) {
1228
1378
  };
1229
1379
  const hookFor = (client2, kinds) => ({
1230
1380
  kinds,
1231
- handle: async (request) => {
1381
+ handle: async (request2) => {
1232
1382
  const id2 = ++next3;
1233
1383
  const asked = {
1234
1384
  ready: Promise.withResolvers(),
1235
1385
  chunks: [],
1236
1386
  wake: void 0,
1237
- body: request.body.getReader(),
1238
- progress: request.progress
1387
+ body: request2.body.getReader(),
1388
+ progress: request2.progress
1239
1389
  };
1240
1390
  asks.set(id2, asked);
1241
1391
  const cancel = () => {
1242
1392
  asks.delete(id2);
1243
1393
  post({
1244
1394
  id: id2,
1245
- cancel: String(request.signal.reason?.message ?? "closed")
1395
+ cancel: String(request2.signal.reason?.message ?? "closed")
1246
1396
  });
1247
- asked.ready.reject(request.signal.reason);
1397
+ asked.ready.reject(request2.signal.reason);
1248
1398
  push(asked, { name: "AbortError", message: "cancelled" });
1249
1399
  };
1250
- request.signal.addEventListener("abort", cancel, { once: true });
1251
- const { kind, options, stamp } = request;
1400
+ request2.signal.addEventListener("abort", cancel, { once: true });
1401
+ const { kind, options, stamp } = request2;
1252
1402
  post({ ask: { id: id2, client: client2, kind, options, stamp } });
1253
1403
  await asked.ready.promise;
1254
- return reply(id2, asked);
1404
+ return reply2(id2, asked);
1255
1405
  }
1256
1406
  });
1257
1407
  const answer2 = (message3) => {
@@ -1273,9 +1423,9 @@ function embedderAsker(port) {
1273
1423
  };
1274
1424
  return { hookFor, answer: answer2 };
1275
1425
  }
1276
- function bytesOf(reply) {
1277
- if (reply instanceof ReadableStream) return reply;
1278
- const bytes = typeof reply === "string" ? new TextEncoder().encode(reply) : reply instanceof Uint8Array ? reply : new Uint8Array(0);
1426
+ function bytesOf(reply2) {
1427
+ if (reply2 instanceof ReadableStream) return reply2;
1428
+ const bytes = typeof reply2 === "string" ? new TextEncoder().encode(reply2) : reply2 instanceof Uint8Array ? reply2 : new Uint8Array(0);
1279
1429
  return new ReadableStream({
1280
1430
  start(controller) {
1281
1431
  if (bytes.length > 0) controller.enqueue(bytes);
@@ -1319,7 +1469,7 @@ function embedderAnswerer(port, hookFor) {
1319
1469
  name: "NotSupportedError"
1320
1470
  });
1321
1471
  const body = bodyStream(ask.id, state, post);
1322
- const reply = await hook.handle({
1472
+ const reply2 = await hook.handle({
1323
1473
  kind: ask.kind,
1324
1474
  options: ask.options,
1325
1475
  body,
@@ -1327,8 +1477,8 @@ function embedderAnswerer(port, hookFor) {
1327
1477
  signal: state.abort.signal,
1328
1478
  progress: (line) => post({ id: ask.id, progress: String(line) })
1329
1479
  });
1330
- if (!(reply instanceof ReadableStream)) post({ id: ask.id, bodyCancel: true });
1331
- state.reader = bytesOf(reply).getReader();
1480
+ if (!(reply2 instanceof ReadableStream)) post({ id: ask.id, bodyCancel: true });
1481
+ state.reader = bytesOf(reply2).getReader();
1332
1482
  post({ id: ask.id, ready: true });
1333
1483
  } catch (err) {
1334
1484
  fail4(ask.id, err);
@@ -4501,11 +4651,21 @@ var CdpFacade = class {
4501
4651
  }
4502
4652
  }
4503
4653
  async route(conn, incoming, req) {
4654
+ const { hosts } = this.options;
4655
+ if (hosts.leaseOnly) {
4656
+ hosts.authorize(conn);
4657
+ if (req.method !== "GET") throw new HttpError(405, "expected GET");
4658
+ if (req.target === hosts.path && isUpgrade(req.headers))
4659
+ return this.upgrade(conn, incoming, req);
4660
+ if (req.target === "/json/version")
4661
+ return this.write(conn, json({ Browser: "cdp-lease-v1", webSocketDebuggerUrl: hosts.url }));
4662
+ if (req.target === "/json" || req.target === "/json/list") return this.write(conn, json([]));
4663
+ throw new HttpError(404, "lease route unavailable");
4664
+ }
4504
4665
  const url = new URL(req.target, "http://127.0.0.1");
4505
4666
  const runtime = url.searchParams.get("runtime") ?? void 0;
4506
4667
  const host = req.headers.find(([n]) => n.toLowerCase() === "host")?.[1] ?? "127.0.0.1";
4507
4668
  if (req.method !== "GET") throw new HttpError(405, `${req.method} is not supported here`);
4508
- const { hosts } = this.options;
4509
4669
  if (url.pathname === hosts.path && isUpgrade(req.headers)) {
4510
4670
  return this.upgrade(conn, incoming, req, runtime);
4511
4671
  }
@@ -4527,12 +4687,12 @@ var CdpFacade = class {
4527
4687
  );
4528
4688
  return;
4529
4689
  }
4530
- await this.write(conn, json(await this.list(runtime, conn.peerStamp)));
4690
+ await this.write(conn, json(await this.list(conn, runtime)));
4531
4691
  }
4532
- async list(runtime, stamp) {
4533
- const conn = await this.host(runtime, stamp);
4692
+ async list(peer, runtime) {
4693
+ const conn = await this.options.hosts.connect(peer, runtime);
4534
4694
  try {
4535
- const reply = await new Promise(
4695
+ const reply2 = await new Promise(
4536
4696
  (resolve2, reject) => {
4537
4697
  const timer = setTimeout(
4538
4698
  () => reject(new HttpError(504, "the CDP host did not answer Target.getTargets")),
@@ -4551,10 +4711,10 @@ var CdpFacade = class {
4551
4711
  conn.send(JSON.stringify({ id: 1, method: "Target.getTargets" }));
4552
4712
  }
4553
4713
  );
4554
- if (!reply.result) {
4555
- throw new HttpError(502, `Target.getTargets failed: ${JSON.stringify(reply.error)}`);
4714
+ if (!reply2.result) {
4715
+ throw new HttpError(502, `Target.getTargets failed: ${JSON.stringify(reply2.error)}`);
4556
4716
  }
4557
- return (reply.result.targetInfos ?? []).map((t) => ({
4717
+ return (reply2.result.targetInfos ?? []).map((t) => ({
4558
4718
  description: "",
4559
4719
  id: t.targetId,
4560
4720
  title: t.title,
@@ -4565,17 +4725,12 @@ var CdpFacade = class {
4565
4725
  conn.close();
4566
4726
  }
4567
4727
  }
4568
- host(runtime, stamp) {
4569
- return this.options.hosts.connect({
4570
- ...runtime ? { runtime } : {},
4571
- ...stamp ? { stamp } : {}
4572
- });
4573
- }
4574
4728
  async upgrade(conn, incoming, req, runtime) {
4575
4729
  const accept2 = await acceptKey(req.headers);
4576
- const host = await this.host(runtime, conn.peerStamp);
4730
+ const host = await this.options.hosts.connect(conn, runtime);
4577
4731
  const limits2 = {
4578
- max: this.options.maxMessage ?? MAX_MESSAGE,
4732
+ max: this.options.hosts.leaseOnly ? LEASE_MAX_MESSAGE : this.options.maxMessage ?? MAX_MESSAGE,
4733
+ serial: this.options.hosts.leaseOnly,
4579
4734
  closeWaitMs: this.options.closeWaitMs ?? CLOSE_WAIT_MS
4580
4735
  };
4581
4736
  await new Relay(conn, incoming, host, limits2, this.stop.signal).start(switchingHead(accept2)).finally(() => host.close());
@@ -4584,6 +4739,8 @@ var CdpFacade = class {
4584
4739
  var Relay = class {
4585
4740
  writes = Promise.resolve();
4586
4741
  ended = false;
4742
+ busy = false;
4743
+ serial;
4587
4744
  conn;
4588
4745
  incoming;
4589
4746
  host;
@@ -4595,6 +4752,7 @@ var Relay = class {
4595
4752
  this.incoming = incoming;
4596
4753
  this.host = host;
4597
4754
  this.max = limits2.max;
4755
+ this.serial = limits2.serial;
4598
4756
  this.closeWaitMs = limits2.closeWaitMs;
4599
4757
  this.stop = stop;
4600
4758
  }
@@ -4608,7 +4766,8 @@ var Relay = class {
4608
4766
  return this.send(closeFrame(code, reason));
4609
4767
  }
4610
4768
  async start(head) {
4611
- await this.send(head);
4769
+ const handshake2 = this.send(head);
4770
+ if (!this.serial) await handshake2;
4612
4771
  const hostGone = new Promise((resolve2) => {
4613
4772
  this.host.onclose = (reason) => {
4614
4773
  void this.end(reason ? CLOSE.error : CLOSE.normal, reason ?? "").then(() => resolve2());
@@ -4619,8 +4778,13 @@ var Relay = class {
4619
4778
  const bytes = new TextEncoder().encode(message3);
4620
4779
  if (bytes.length > this.max)
4621
4780
  void this.end(CLOSE.tooBig, `a message is over ${this.max} bytes`);
4622
- else void this.send(frame(OP_TEXT, bytes));
4781
+ else if (!this.serial) void this.send(frame(OP_TEXT, bytes));
4782
+ else
4783
+ void this.send(frame(OP_TEXT, bytes)).then(() => {
4784
+ this.busy = false;
4785
+ });
4623
4786
  };
4787
+ await handshake2;
4624
4788
  const pumping = this.pump();
4625
4789
  await Promise.race([pumping, hostGone]);
4626
4790
  await this.writes;
@@ -4636,10 +4800,18 @@ var Relay = class {
4636
4800
  try {
4637
4801
  for (; ; ) {
4638
4802
  const event = await reader.next(this.stop);
4639
- if (!event) return;
4640
- if (event.kind === "text") this.host.send(event.text);
4641
- else if (event.kind === "ping") void this.send(pongFrame(event.payload));
4642
- else {
4803
+ if (!event || this.serial && this.ended) return;
4804
+ if (event.kind === "text") {
4805
+ if (this.serial && this.busy) {
4806
+ await this.end(CLOSE.protocol, "one lease operation at a time");
4807
+ return;
4808
+ }
4809
+ this.busy = this.serial;
4810
+ this.host.send(event.text);
4811
+ } else if (event.kind === "ping") {
4812
+ const pong = this.send(pongFrame(event.payload));
4813
+ if (this.serial) await pong;
4814
+ } else {
4643
4815
  await this.end(event.code === 1005 ? CLOSE.normal : event.code, "");
4644
4816
  return;
4645
4817
  }
@@ -4669,12 +4841,43 @@ var CdpHosts = class {
4669
4841
  embedder;
4670
4842
  clients = [];
4671
4843
  closed = false;
4672
- path = `/devtools/browser/${crypto.randomUUID()}`;
4673
- url = `ws://127.0.0.1:${CDP_PORT}${this.path}`;
4674
- constructor(hook) {
4844
+ leaseTag;
4845
+ sessionOf;
4846
+ session;
4847
+ opening = 0;
4848
+ path;
4849
+ url;
4850
+ constructor(hook, leaseTag, sessionOf2 = (_pid) => -1) {
4851
+ this.leaseTag = leaseTag;
4852
+ this.sessionOf = sessionOf2;
4853
+ this.path = `${this.leaseOnly ? "/slicc/lease/v1/" : "/devtools/browser/"}${crypto.randomUUID()}`;
4854
+ this.url = `ws://127.0.0.1:${CDP_PORT}${this.path}`;
4675
4855
  this.embedder = hook ? { hook, runtime: void 0, open: /* @__PURE__ */ new Set() } : void 0;
4676
4856
  }
4857
+ get leaseOnly() {
4858
+ return this.leaseTag !== void 0;
4859
+ }
4860
+ env(session) {
4861
+ if (!this.leaseOnly) return { SLICC_CDP_URL: this.url };
4862
+ if (session === void 0 || this.session !== session || this.closed) return {};
4863
+ return { SLICC_CDP_LEASE_URL: this.url };
4864
+ }
4865
+ bindClient(session, tag, extraHost) {
4866
+ if (!this.leaseOnly) return void 0;
4867
+ if (this.closed || this.session !== void 0 || tag !== this.leaseTag || extraHost) {
4868
+ throw new Error("lease unavailable for this client");
4869
+ }
4870
+ this.session = session;
4871
+ return () => this.close();
4872
+ }
4873
+ authorize(socket) {
4874
+ if (!this.leaseOnly) return;
4875
+ if (this.closed || this.session === void 0 || socket.peerStamp?.tag !== this.leaseTag || !socket.peerCred || this.sessionOf(socket.peerCred.pid) !== this.session) {
4876
+ throw new HttpError(403, "lease unavailable");
4877
+ }
4878
+ }
4677
4879
  register(hook, runtime) {
4880
+ if (this.leaseOnly) throw new Error("a lease-only kernel cannot register a CDP host");
4678
4881
  const entry = { hook, runtime, open: /* @__PURE__ */ new Set() };
4679
4882
  this.clients.push(entry);
4680
4883
  return () => {
@@ -4685,20 +4888,28 @@ var CdpHosts = class {
4685
4888
  }
4686
4889
  pick(runtime) {
4687
4890
  if (this.closed) return void 0;
4891
+ if (this.leaseOnly) return runtime === void 0 ? this.embedder : void 0;
4688
4892
  const named = runtime ? this.clients.findLast((c) => c.runtime === runtime) : void 0;
4689
4893
  return named ?? this.embedder ?? this.clients.at(-1);
4690
4894
  }
4691
4895
  available(runtime) {
4692
4896
  return this.pick(runtime) !== void 0;
4693
4897
  }
4694
- async connect(request) {
4695
- const entry = this.pick(request.runtime);
4898
+ async connect(peer, runtime) {
4899
+ this.authorize(peer);
4900
+ const entry = this.pick(runtime);
4696
4901
  if (!entry) throw new HttpError(503, NO_CDP_HOST);
4902
+ if (this.leaseOnly && this.opening + entry.open.size >= LEASE_MAX_CONNECTIONS)
4903
+ throw new HttpError(503, "lease busy");
4697
4904
  let conn;
4905
+ this.opening++;
4698
4906
  try {
4699
- conn = held(await entry.hook(hookRequest(request)));
4907
+ conn = held(await entry.hook(hookRequest(peer, runtime)));
4700
4908
  } catch (e) {
4909
+ if (this.leaseOnly) throw new HttpError(502, "lease unavailable");
4701
4910
  throw new HttpError(502, `CDP host: ${e instanceof Error ? e.message : String(e)}`);
4911
+ } finally {
4912
+ this.opening--;
4702
4913
  }
4703
4914
  if (this.closed || !(entry === this.embedder || this.clients.includes(entry))) {
4704
4915
  conn.close();
@@ -4725,7 +4936,7 @@ function held(host) {
4725
4936
  host.onclose = end;
4726
4937
  return conn;
4727
4938
  }
4728
- function hookRequest({ runtime, stamp }) {
4939
+ function hookRequest({ peerStamp: stamp }, runtime) {
4729
4940
  return {
4730
4941
  ...runtime ? { runtime } : {},
4731
4942
  ...stamp ? { stamp: structuredClone(stamp) } : {}
@@ -4738,6 +4949,15 @@ function closeAll(entry) {
4738
4949
  }
4739
4950
  }
4740
4951
 
4952
+ // src/cdp/lease-cli.ts
4953
+ var CLI_PKG = "/node_modules/@ai-ecoverse/slicc-cdp";
4954
+ var CLI_FILE = `${CLI_PKG}/bin/playwright-cli.wasm`;
4955
+ var CLI_MAX = 8 * 1024 * 1024;
4956
+ var MANIFEST = JSON.stringify({
4957
+ name: "@ai-ecoverse/slicc-cdp",
4958
+ slicc: { abi: "wasi", commands: { "playwright-cli": { wasm: "bin/playwright-cli.wasm" } } }
4959
+ });
4960
+
4741
4961
  // src/fs/engines.ts
4742
4962
  var NUMBER = /^(0|[1-9]\d*)$/;
4743
4963
  var PART = /^(?:0|[1-9]\d*|[xX*])$/;
@@ -4889,7 +5109,7 @@ function satisfies(version, range2) {
4889
5109
  }
4890
5110
 
4891
5111
  // src/version.ts
4892
- var KERNEL_VERSION = true ? "1.193.3" : "0.0.0-dev";
5112
+ var KERNEL_VERSION = true ? "1.194.0" : "0.0.0-dev";
4893
5113
  var OS_RELEASE = "6.0.0-slicc";
4894
5114
  function procVersion() {
4895
5115
  return `Linux version ${OS_RELEASE} (slicc-kernel ${KERNEL_VERSION}) #1 SMP PREEMPT_DYNAMIC
@@ -5765,16 +5985,16 @@ function split(text, count3) {
5765
5985
  return [words3, rest2.trim()];
5766
5986
  }
5767
5987
  function jobOf(content, pending, ctx, env) {
5768
- const fields = content.startsWith("@") ? 1 : 5;
5769
- const parts2 = split(content, fields + (ctx.system ? 1 : 0));
5988
+ const fields2 = content.startsWith("@") ? 1 : 5;
5989
+ const parts2 = split(content, fields2 + (ctx.system ? 1 : 0));
5770
5990
  if (!parts2 || parts2[1] === "") throw new Error("no command");
5771
5991
  const [words3, command] = parts2;
5772
- const schedule = words3.slice(0, fields).join(" ");
5992
+ const schedule = words3.slice(0, fields2).join(" ");
5773
5993
  const when = parseWhen(schedule);
5774
5994
  const zone = env.CRON_TZ;
5775
5995
  if (zone && !when.reboot && canonicalZone(zone) === void 0)
5776
5996
  throw new Error(`CRON_TZ: unknown time zone "${zone}"`);
5777
- const user = ctx.system ? words3[fields] : void 0;
5997
+ const user = ctx.system ? words3[fields2] : void 0;
5778
5998
  if (user !== void 0 && !USER_NAME.test(user)) throw new Error(`bad user name ${user}`);
5779
5999
  if (pending !== void 0 && !JOB_NAME.test(pending))
5780
6000
  throw new Error(`bad job name "${pending}"`);
@@ -5853,15 +6073,15 @@ function merged(old, caller) {
5853
6073
  }
5854
6074
  var ACTIONS = /* @__PURE__ */ new Set(["list", "remove", "install"]);
5855
6075
  function crontabCall(req) {
5856
- const { action, user, text } = req;
5857
- if (typeof action !== "string" || !ACTIONS.has(action)) return void 0;
6076
+ const { action: action2, user, text } = req;
6077
+ if (typeof action2 !== "string" || !ACTIONS.has(action2)) return void 0;
5858
6078
  if (user !== void 0 && typeof user !== "string") return void 0;
5859
- if (action === "install" && typeof text !== "string") return void 0;
6079
+ if (action2 === "install" && typeof text !== "string") return void 0;
5860
6080
  return {
5861
6081
  op: "proc-crontab",
5862
- action,
6082
+ action: action2,
5863
6083
  ...user !== void 0 ? { user } : {},
5864
- ...action === "install" ? { text } : {}
6084
+ ...action2 === "install" ? { text } : {}
5865
6085
  };
5866
6086
  }
5867
6087
  var Crontabs = class {
@@ -6987,11 +7207,11 @@ function headersCarry(headers, known) {
6987
7207
  function urlCarries(url, known) {
6988
7208
  return carries(url, known) || URL.canParse(url) && carries(new URL(url).href, known);
6989
7209
  }
6990
- function detected(request, known) {
6991
- return urlCarries(request.url, known) || headersCarry(request.headers, known);
7210
+ function detected(request2, known) {
7211
+ return urlCarries(request2.url, known) || headersCarry(request2.headers, known);
6992
7212
  }
6993
- function refuseSocket(request, known) {
6994
- if (detected(request, known) || request.protocols.some((p) => carries(p, known))) {
7213
+ function refuseSocket(request2, known) {
7214
+ if (detected(request2, known) || request2.protocols.some((p) => carries(p, known))) {
6995
7215
  throw new PlaceholderRefused();
6996
7216
  }
6997
7217
  }
@@ -7002,15 +7222,15 @@ function placeholderFloor(inner, { known = () => [], fill: fill2 } = {}) {
7002
7222
  return inner.traits;
7003
7223
  },
7004
7224
  ...open ? {
7005
- websocket: async (request) => {
7006
- refuseSocket(request, known());
7007
- return open(request);
7225
+ websocket: async (request2) => {
7226
+ refuseSocket(request2, known());
7227
+ return open(request2);
7008
7228
  }
7009
7229
  } : {},
7010
- async fetch(request, owner, stamp) {
7011
- if (!detected(request, known())) return inner.fetch(request, owner, stamp);
7230
+ async fetch(request2, owner, stamp) {
7231
+ if (!detected(request2, known())) return inner.fetch(request2, owner, stamp);
7012
7232
  if (!fill2 || !stamp) throw new PlaceholderRefused();
7013
- return fill2(request, stamp);
7233
+ return fill2(request2, stamp);
7014
7234
  }
7015
7235
  };
7016
7236
  }
@@ -7883,7 +8103,8 @@ async function attest(fs, asked, o) {
7883
8103
  if (before.isSymbolicLink) refuse("EACCES", path, "is a symlink");
7884
8104
  if (!before.isFile)
7885
8105
  refuse(before.isDirectory ? "EISDIR" : "EINVAL", path, "is not a regular file");
7886
- if (before.size > ATTEST_MAX) refuse("EFBIG", path, `is over ${ATTEST_MAX} bytes`);
8106
+ if (before.size > (o.maxBytes ?? ATTEST_MAX))
8107
+ refuse("EFBIG", path, `is over ${o.maxBytes ?? ATTEST_MAX} bytes`);
7887
8108
  const bytes = (await fs.readFileBuffer(path)).slice();
7888
8109
  const after = await fs.lstat(path);
7889
8110
  if (unchanged(before, after, bytes)) {
@@ -9018,6 +9239,10 @@ function under2(path, root) {
9018
9239
  }
9019
9240
  var MemoryMeta = class {
9020
9241
  entries = new PathMap();
9242
+ limit;
9243
+ constructor(limit = Infinity) {
9244
+ this.limit = limit;
9245
+ }
9021
9246
  async get(paths) {
9022
9247
  return paths.map((path) => this.entries.get(path));
9023
9248
  }
@@ -9028,6 +9253,8 @@ var MemoryMeta = class {
9028
9253
  this.set(path, change(this.entries.get(path)));
9029
9254
  }
9030
9255
  set(path, entry) {
9256
+ if (entry && this.entries.size >= this.limit && !this.entries.has(path))
9257
+ throw Object.assign(new Error("metadata quota"), { code: "ENOSPC" });
9031
9258
  if (entry) this.entries.set(path, entry);
9032
9259
  else this.entries.delete(path);
9033
9260
  }
@@ -9037,14 +9264,14 @@ var MemoryMeta = class {
9037
9264
  for (const entry of carried) this.entries.delete(entry.path);
9038
9265
  for (const entry of carried) {
9039
9266
  const path = to + entry.path.slice(from.length);
9040
- if (path !== to) this.entries.set(path, moved(entry, path));
9267
+ if (path !== to) this.set(path, moved(entry, path));
9041
9268
  }
9042
- this.entries.set(to, moved(root(carried.find((entry) => entry.path === from)), to));
9043
- if (left) this.entries.set(from, left);
9269
+ this.set(to, moved(root(carried.find((entry) => entry.path === from)), to));
9270
+ if (left) this.set(from, left);
9044
9271
  }
9045
9272
  async remove(paths, left) {
9046
9273
  for (const path of paths) this.entries.deleteTree(path);
9047
- if (left) this.entries.set(left.path, left);
9274
+ if (left) this.set(left.path, left);
9048
9275
  }
9049
9276
  absent(path) {
9050
9277
  return !this.entries.has(path);
@@ -10228,9 +10455,9 @@ function endsWith(stream2, ended) {
10228
10455
  { highWaterMark: 0 }
10229
10456
  );
10230
10457
  }
10231
- function replyStream(reply) {
10232
- if (reply instanceof ReadableStream) return reply;
10233
- const bytes = typeof reply === "string" ? new TextEncoder().encode(reply) : reply instanceof Uint8Array ? reply : new Uint8Array(0);
10458
+ function replyStream(reply2) {
10459
+ if (reply2 instanceof ReadableStream) return reply2;
10460
+ const bytes = typeof reply2 === "string" ? new TextEncoder().encode(reply2) : reply2 instanceof Uint8Array ? reply2 : new Uint8Array(0);
10234
10461
  return new ReadableStream({
10235
10462
  start(controller) {
10236
10463
  if (bytes.length > 0) controller.enqueue(bytes);
@@ -10316,9 +10543,9 @@ var EmbedderChannel = class {
10316
10543
  signal: this.abort.signal,
10317
10544
  progress
10318
10545
  })
10319
- ).then((reply) => {
10320
- if (!(reply instanceof ReadableStream)) body.drop();
10321
- return endsWith(replyStream(reply), () => body.drop()).getReader();
10546
+ ).then((reply2) => {
10547
+ if (!(reply2 instanceof ReadableStream)) body.drop();
10548
+ return endsWith(replyStream(reply2), () => body.drop()).getReader();
10322
10549
  });
10323
10550
  this.replied = asked.catch((err) => {
10324
10551
  body.end();
@@ -11038,7 +11265,7 @@ function want(access2) {
11038
11265
  }
11039
11266
  function devicesHook(hook) {
11040
11267
  if (typeof hook?.open !== "function") throw new TypeError("devices needs open");
11041
- return { open: (request) => hook.open(request) };
11268
+ return { open: (request2) => hook.open(request2) };
11042
11269
  }
11043
11270
  function checkMeta(node, change, uid, gid, guard2) {
11044
11271
  const { cred } = guard2;
@@ -11456,9 +11683,9 @@ var DeviceChannel = class {
11456
11683
  throw embedderFailure(err);
11457
11684
  }
11458
11685
  }
11459
- async ioctl(request, arg, signal) {
11686
+ async ioctl(request2, arg, signal) {
11460
11687
  this.check();
11461
- switch (request) {
11688
+ switch (request2) {
11462
11689
  case IOCTL.TCGETS:
11463
11690
  case IOCTL.TCGETS2:
11464
11691
  return this.termios();
@@ -11468,8 +11695,8 @@ var DeviceChannel = class {
11468
11695
  case IOCTL.TCSETS2:
11469
11696
  case IOCTL.TCSETSW2:
11470
11697
  case IOCTL.TCSETSF2: {
11471
- const extended = request > 65535;
11472
- const kind = (request & 255) - (extended ? 43 : 2);
11698
+ const extended = request2 > 65535;
11699
+ const kind = (request2 & 255) - (extended ? 43 : 2);
11473
11700
  await this.setTermios(
11474
11701
  arg,
11475
11702
  { drain: kind > 0, flush: kind === 2, extended },
@@ -11490,7 +11717,7 @@ var DeviceChannel = class {
11490
11717
  return null;
11491
11718
  case IOCTL.TIOCSBRK:
11492
11719
  case IOCTL.TIOCCBRK:
11493
- await this.signals({ break: request === IOCTL.TIOCSBRK });
11720
+ await this.signals({ break: request2 === IOCTL.TIOCSBRK });
11494
11721
  return null;
11495
11722
  case IOCTL.TCSBRK:
11496
11723
  if (Number(arg) === 0) await this.sendBreak(BREAK_MS, signal);
@@ -11576,8 +11803,8 @@ var TicketBook = class {
11576
11803
  get size() {
11577
11804
  return this.booked.size;
11578
11805
  }
11579
- async record(req, reply, pid) {
11580
- const { ticket: ticket2, error } = reply;
11806
+ async record(req, reply2, pid) {
11807
+ const { ticket: ticket2, error } = reply2;
11581
11808
  if (error !== void 0 || typeof ticket2 !== "string" || !TICKET.test(ticket2)) return;
11582
11809
  const { path, argv, cwd } = req;
11583
11810
  const entry = {
@@ -14369,7 +14596,7 @@ function attachSyncSabResponder(port, sab, token, opts) {
14369
14596
  const { header: header5, window } = views;
14370
14597
  const pending = /* @__PURE__ */ new Map();
14371
14598
  let disposed = false;
14372
- const { dispatch: dispatch2 } = opts;
14599
+ const { dispatch: dispatch3 } = opts;
14373
14600
  function drop(id2) {
14374
14601
  const entry = pending.get(id2);
14375
14602
  if (!entry) return;
@@ -14428,7 +14655,7 @@ function attachSyncSabResponder(port, sab, token, opts) {
14428
14655
  const req = { ...body, token };
14429
14656
  let dispatched;
14430
14657
  try {
14431
- dispatched = dispatch2(req);
14658
+ dispatched = dispatch3(req);
14432
14659
  } catch (err) {
14433
14660
  settle(id2, {
14434
14661
  ok: false,
@@ -14593,12 +14820,12 @@ var ProcessClocks = class {
14593
14820
  ...[...this.threads].map(([tid, c]) => ({ tid, state: state(c) }))
14594
14821
  ];
14595
14822
  }
14596
- timed(clock, dispatch2) {
14823
+ timed(clock, dispatch3) {
14597
14824
  const c = clock ?? this.main;
14598
14825
  const block = () => c.block();
14599
14826
  return (req) => {
14600
14827
  c.enter();
14601
- return dispatch2(req, block).finally(() => c.leave());
14828
+ return dispatch3(req, block).finally(() => c.leave());
14602
14829
  };
14603
14830
  }
14604
14831
  all() {
@@ -14982,7 +15209,7 @@ function ticks(ms) {
14982
15209
  return Math.max(0, Math.floor(ms * HZ / 1e3));
14983
15210
  }
14984
15211
  function pidStat(info, boot, state = info.state) {
14985
- const fields = [
15212
+ const fields2 = [
14986
15213
  info.pid,
14987
15214
  `(${commOf(info)})`,
14988
15215
  state,
@@ -15019,7 +15246,7 @@ function pidStat(info, boot, state = info.state) {
15019
15246
  ...Array(7).fill(0),
15020
15247
  0
15021
15248
  ];
15022
- return `${fields.join(" ")}
15249
+ return `${fields2.join(" ")}
15023
15250
  `;
15024
15251
  }
15025
15252
  var sigMask = (mask = 0) => (mask >>> 1).toString(16).padStart(16, "0");
@@ -15937,8 +16164,8 @@ function refused3(engine, session, err, opening2) {
15937
16164
  const code = verifyCode(flags2);
15938
16165
  if (code && flags2 !== -1)
15939
16166
  return new KernelError("EPROTO", `${code}: ${engine.verifyInfo(flags2).trim()}`);
15940
- const record3 = recordRefusal(opening2);
15941
- if (record3) return record3;
16167
+ const record4 = recordRefusal(opening2);
16168
+ if (record4) return record4;
15942
16169
  const text = err instanceof TlsError ? err.message : String(err);
15943
16170
  return new KernelError("EPROTO", `ERR_SSL_HANDSHAKE_FAILURE: ${text}${alertOf(session)}`);
15944
16171
  }
@@ -16169,14 +16396,14 @@ function tlv(der2, at) {
16169
16396
  return end > der2.length ? void 0 : { start: at, body, end };
16170
16397
  }
16171
16398
  function children(der2, outer, max) {
16172
- const fields = [];
16173
- for (let at = outer.body; at < outer.end && fields.length < max; ) {
16399
+ const fields2 = [];
16400
+ for (let at = outer.body; at < outer.end && fields2.length < max; ) {
16174
16401
  const field4 = tlv(der2, at);
16175
16402
  if (!field4) return void 0;
16176
- fields.push(field4);
16403
+ fields2.push(field4);
16177
16404
  at = field4.end;
16178
16405
  }
16179
- return fields;
16406
+ return fields2;
16180
16407
  }
16181
16408
  function tbsFields(der2) {
16182
16409
  const outer = tlv(der2, 0);
@@ -16191,8 +16418,8 @@ function spkiOf(der2) {
16191
16418
  return spki ? raw(der2, spki) : void 0;
16192
16419
  }
16193
16420
  function names(der2) {
16194
- const fields = tbsFields(der2)?.tbs;
16195
- const [, , issuer, , subject] = fields ?? [];
16421
+ const fields2 = tbsFields(der2)?.tbs;
16422
+ const [, , issuer, , subject] = fields2 ?? [];
16196
16423
  if (!issuer || !subject) return void 0;
16197
16424
  return [raw(der2, issuer), raw(der2, subject)];
16198
16425
  }
@@ -16347,9 +16574,9 @@ function der(text) {
16347
16574
  return void 0;
16348
16575
  }
16349
16576
  }
16350
- function anchorsOf(reply) {
16351
- if (typeof reply !== "object" || reply === null || Array.isArray(reply)) return void 0;
16352
- const r = reply;
16577
+ function anchorsOf(reply2) {
16578
+ if (typeof reply2 !== "object" || reply2 === null || Array.isArray(reply2)) return void 0;
16579
+ const r = reply2;
16353
16580
  if (r.error !== void 0 || !Array.isArray(r.anchors) || !Array.isArray(r.pins))
16354
16581
  return void 0;
16355
16582
  if (r.anchors.length + r.pins.length > ANCHORS_MAX) return void 0;
@@ -17172,14 +17399,14 @@ var NAME2 = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
17172
17399
  var PROVIDER = /^[a-z0-9][a-z0-9-]{0,127}$/;
17173
17400
  var PLACEHOLDER2 = /^fnox_proxy_[0-9a-f]{24}$/;
17174
17401
  var CONTROL = /[\u0000-\u001f\u007f-\u009f]/;
17175
- function record(value2) {
17402
+ function record2(value2) {
17176
17403
  return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
17177
17404
  }
17178
17405
  function keys(value2, allowed) {
17179
17406
  return Object.keys(value2).every((key) => allowed.includes(key));
17180
17407
  }
17181
- function exact(value2, fields) {
17182
- return Object.keys(value2).length === fields.length && keys(value2, fields);
17408
+ function exact(value2, fields2) {
17409
+ return Object.keys(value2).length === fields2.length && keys(value2, fields2);
17183
17410
  }
17184
17411
  function nonempty(value2) {
17185
17412
  return typeof value2 === "string" && value2.length > 0;
@@ -17192,7 +17419,7 @@ function sealedOAuthOperation(op) {
17192
17419
  }
17193
17420
  function validateSealedOAuth(req) {
17194
17421
  const config = req.oauth;
17195
- if (UNSUPPORTED.some((key) => Object.hasOwn(req, key)) || record(config) && UNSUPPORTED.some((key) => Object.hasOwn(config, key)))
17422
+ if (UNSUPPORTED.some((key) => Object.hasOwn(req, key)) || record2(config) && UNSUPPORTED.some((key) => Object.hasOwn(config, key)))
17196
17423
  throw new KernelError("ENOTSUP");
17197
17424
  const allowed = req.op === "capabilities" ? COMMON : req.op === "oauthGrant" ? GRANT : IDENTITY;
17198
17425
  if (!keys(req, allowed)) throw new KernelError("EINVAL");
@@ -17200,7 +17427,7 @@ function validateSealedOAuth(req) {
17200
17427
  if (typeof req.name !== "string" || !NAME2.test(req.name) || typeof req.provider !== "string" || !PROVIDER.test(req.provider) || !nonempty(req.account) || req.account.length > 256 || CONTROL.test(req.account))
17201
17428
  throw new KernelError("EINVAL");
17202
17429
  if (req.op !== "oauthGrant") return;
17203
- if (!nonempty(req.accessToken) || req.refreshToken !== void 0 && !nonempty(req.refreshToken) || req.tokenType !== void 0 && typeof req.tokenType !== "string" || req.expiresAt !== void 0 && !epoch(req.expiresAt) || !record(config) || !keys(config, CONFIG) || !nonempty(config.tokenUrl) || !nonempty(config.clientId) || typeof config.authMethod !== "string" || config.scope !== void 0 && typeof config.scope !== "string" || config.resource !== void 0 && !nonempty(config.resource))
17430
+ if (!nonempty(req.accessToken) || req.refreshToken !== void 0 && !nonempty(req.refreshToken) || req.tokenType !== void 0 && typeof req.tokenType !== "string" || req.expiresAt !== void 0 && !epoch(req.expiresAt) || !record2(config) || !keys(config, CONFIG) || !nonempty(config.tokenUrl) || !nonempty(config.clientId) || typeof config.authMethod !== "string" || config.scope !== void 0 && typeof config.scope !== "string" || config.resource !== void 0 && !nonempty(config.resource))
17204
17431
  throw new KernelError("EINVAL");
17205
17432
  if (config.authMethod !== "none" || typeof req.tokenType === "string" && req.tokenType.toLowerCase() !== "bearer")
17206
17433
  throw new KernelError("ENOTSUP");
@@ -17220,7 +17447,7 @@ function sealedOAuthReply(op, value2) {
17220
17447
  }
17221
17448
  function checkedError(value2) {
17222
17449
  const error = value2.error;
17223
- if (!exact(value2, ["v", "error"]) || !record(error) || !Object.hasOwn(error, "code") || !Object.hasOwn(error, "message"))
17450
+ if (!exact(value2, ["v", "error"]) || !record2(error) || !Object.hasOwn(error, "code") || !Object.hasOwn(error, "message"))
17224
17451
  return void 0;
17225
17452
  const { code, cause, message: message3 } = error;
17226
17453
  if (!keys(error, ["code", "cause", "message"]) || typeof code !== "string" || !Object.hasOwn(MESSAGES, code) || typeof message3 !== "string" || cause !== void 0 && (typeof cause !== "string" || !Object.hasOwn(CAUSES, cause)))
@@ -17228,11 +17455,11 @@ function checkedError(value2) {
17228
17455
  return sealedOAuthError(code, cause);
17229
17456
  }
17230
17457
  function checkedReply(op, value2) {
17231
- if (!record(value2) || !Object.hasOwn(value2, "v") || value2.v !== 1) return void 0;
17458
+ if (!record2(value2) || !Object.hasOwn(value2, "v") || value2.v !== 1) return void 0;
17232
17459
  if (Object.hasOwn(value2, "error")) return checkedError(value2);
17233
17460
  if (op === "capabilities") {
17234
17461
  const caps = value2.capabilities;
17235
- if (!exact(value2, ["v", "capabilities"]) || !record(caps) || !keys(caps, ["kernelOAuth"]))
17462
+ if (!exact(value2, ["v", "capabilities"]) || !record2(caps) || !keys(caps, ["kernelOAuth"]))
17236
17463
  return void 0;
17237
17464
  if (Object.hasOwn(caps, "kernelOAuth") && caps.kernelOAuth !== 1) return void 0;
17238
17465
  return { v: 1, capabilities: Object.hasOwn(caps, "kernelOAuth") ? { kernelOAuth: 1 } : {} };
@@ -17350,9 +17577,9 @@ function sessionRequest(f) {
17350
17577
  } : {}
17351
17578
  };
17352
17579
  }
17353
- function sessionValues(reply, asked) {
17354
- if (typeof reply !== "object" || reply === null || Array.isArray(reply)) return void 0;
17355
- const { error, values } = reply;
17580
+ function sessionValues(reply2, asked) {
17581
+ if (typeof reply2 !== "object" || reply2 === null || Array.isArray(reply2)) return void 0;
17582
+ const { error, values } = reply2;
17356
17583
  if (error !== void 0 || typeof values !== "object" || values === null) return void 0;
17357
17584
  const out = {};
17358
17585
  const keys2 = Object.keys(values);
@@ -17436,14 +17663,14 @@ function askable(req) {
17436
17663
  return false;
17437
17664
  return [reveal, replace].every((flag) => flag === void 0 || typeof flag === "boolean");
17438
17665
  }
17439
- function askRequest(fields, caller, requester) {
17666
+ function askRequest(fields2, caller, requester) {
17440
17667
  return {
17441
17668
  v: 1,
17442
17669
  op: "ask",
17443
- name: fields.name,
17444
- ...fields.prompt !== void 0 ? { prompt: fields.prompt } : {},
17445
- reveal: fields.reveal === true,
17446
- replace: fields.replace === true,
17670
+ name: fields2.name,
17671
+ ...fields2.prompt !== void 0 ? { prompt: fields2.prompt } : {},
17672
+ reveal: fields2.reveal === true,
17673
+ replace: fields2.replace === true,
17447
17674
  caller,
17448
17675
  requester
17449
17676
  };
@@ -17454,10 +17681,10 @@ function errorReply(code, message3) {
17454
17681
  function isRecord(value2) {
17455
17682
  return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
17456
17683
  }
17457
- function serialized(reply) {
17684
+ function serialized(reply2) {
17458
17685
  let plain3;
17459
17686
  try {
17460
- const text = JSON.stringify(reply);
17687
+ const text = JSON.stringify(reply2);
17461
17688
  plain3 = text === void 0 ? void 0 : JSON.parse(text);
17462
17689
  } catch (err) {
17463
17690
  return JSON.stringify(errorReply("EIO", lineOf3(err)));
@@ -17486,38 +17713,38 @@ var SealedChannel = class {
17486
17713
  throw new KernelError("EBADF");
17487
17714
  }
17488
17715
  const length2 = bytes.length;
17489
- const fields = parseSealed(bytes);
17716
+ const fields2 = parseSealed(bytes);
17490
17717
  this.drop();
17491
17718
  this.inflight?.control.abort("replaced");
17492
17719
  const control = new AbortController();
17493
17720
  const withdraw = () => control.abort("withdrawn");
17494
17721
  if (gone.aborted) withdraw();
17495
17722
  else gone.addEventListener("abort", withdraw, { once: true });
17496
- const ask = fields.op === "ask";
17723
+ const ask = fields2.op === "ask";
17497
17724
  const timer = setTimeout(
17498
17725
  () => control.abort(ask ? "expired" : "timeout"),
17499
- ask ? this.broker.askTimeoutMs : SEALED_OAUTH_OPS.has(fields.op) ? this.broker.oauthTimeoutMs : this.broker.timeoutMs
17726
+ ask ? this.broker.askTimeoutMs : SEALED_OAUTH_OPS.has(fields2.op) ? this.broker.oauthTimeoutMs : this.broker.timeoutMs
17500
17727
  );
17501
- const req = { ...fields, v: 1, op: fields.op, caller };
17502
- const asked = ask ? this.asking(fields, caller, requester, control.signal) : void 0;
17728
+ const req = { ...fields2, v: 1, op: fields2.op, caller };
17729
+ const asked = ask ? this.asking(fields2, caller, requester, control.signal) : void 0;
17503
17730
  const flight = { control, done: Promise.resolve() };
17504
- flight.done = (asked ?? this.answer(req, control.signal)).then(async (reply) => {
17731
+ flight.done = (asked ?? this.answer(req, control.signal)).then(async (reply2) => {
17505
17732
  clearTimeout(timer);
17506
17733
  gone.removeEventListener("abort", withdraw);
17507
- if (reply && req.op === "materialize")
17508
- await this.broker.tickets.record(req, reply, caller.pid);
17734
+ if (reply2 && req.op === "materialize")
17735
+ await this.broker.tickets.record(req, reply2, caller.pid);
17509
17736
  if (this.inflight !== flight) return;
17510
17737
  this.inflight = void 0;
17511
- if (reply) this.reply = encoder7.encode(serialized(reply));
17738
+ if (reply2) this.reply = encoder7.encode(serialized(reply2));
17512
17739
  });
17513
17740
  this.inflight = flight;
17514
17741
  return length2;
17515
17742
  }
17516
- async asking(fields, caller, requester, signal) {
17743
+ async asking(fields2, caller, requester, signal) {
17517
17744
  const facts = await requester().catch(() => void 0);
17518
17745
  if (signal.aborted) return this.stopped(signal);
17519
17746
  if (!facts) return errorReply("EIO", "the kernel has no record of this process");
17520
- return this.answer(askRequest(fields, caller, facts), signal);
17747
+ return this.answer(askRequest(fields2, caller, facts), signal);
17521
17748
  }
17522
17749
  stopped(signal, oauth = false) {
17523
17750
  if (signal.reason === "timeout")
@@ -17534,11 +17761,11 @@ var SealedChannel = class {
17534
17761
  });
17535
17762
  if (signal.aborted) return void 0;
17536
17763
  const asked = Promise.resolve().then(() => hook(req, { signal })).then(
17537
- (reply2) => oauth ? sealedOAuthReply(req.op, reply2) : isRecord(reply2) ? reply2 : errorReply("EIO", "the vault gave no reply"),
17764
+ (reply3) => oauth ? sealedOAuthReply(req.op, reply3) : isRecord(reply3) ? reply3 : errorReply("EIO", "the vault gave no reply"),
17538
17765
  (err) => oauth ? sealedOAuthError() : errorReply("EIO", lineOf3(err))
17539
17766
  );
17540
- const reply = await Promise.race([asked, stopped]);
17541
- return signal.aborted ? this.stopped(signal, oauth) : reply;
17767
+ const reply2 = await Promise.race([asked, stopped]);
17768
+ return signal.aborted ? this.stopped(signal, oauth) : reply2;
17542
17769
  }
17543
17770
  drop() {
17544
17771
  this.reply?.fill(0);
@@ -17587,10 +17814,10 @@ var SealedChannel = class {
17587
17814
  this.drop();
17588
17815
  }
17589
17816
  };
17590
- function swapOf(reply) {
17591
- if (!isRecord(reply) || reply.error !== void 0) return void 0;
17592
- const values = stringRecord(reply.values);
17593
- const placeholders = stringRecord(reply.placeholders);
17817
+ function swapOf(reply2) {
17818
+ if (!isRecord(reply2) || reply2.error !== void 0) return void 0;
17819
+ const values = stringRecord(reply2.values);
17820
+ const placeholders = stringRecord(reply2.placeholders);
17594
17821
  return values && placeholders ? { values, placeholders } : void 0;
17595
17822
  }
17596
17823
  var SealedBroker = class {
@@ -17623,18 +17850,18 @@ var SealedBroker = class {
17623
17850
  ...tagFields(tags)
17624
17851
  };
17625
17852
  }
17626
- async consume(fields) {
17627
- const req = { ...fields, v: 1, op: "materializeConsume", caller: fields.stamp };
17853
+ async consume(fields2) {
17854
+ const req = { ...fields2, v: 1, op: "materializeConsume", caller: fields2.stamp };
17628
17855
  return this.ask(req, swapOf);
17629
17856
  }
17630
- async sessionMaterialize(fields, now = Date.now()) {
17631
- if (!sessionAskable(fields, now)) return void 0;
17632
- const req = sessionRequest(fields);
17633
- return this.ask(req, (reply) => sessionValues(reply, req.placeholders));
17857
+ async sessionMaterialize(fields2, now = Date.now()) {
17858
+ if (!sessionAskable(fields2, now)) return void 0;
17859
+ const req = sessionRequest(fields2);
17860
+ return this.ask(req, (reply2) => sessionValues(reply2, req.placeholders));
17634
17861
  }
17635
- async sessionAnchors(fields) {
17636
- if (!anchorsAskable(fields)) return void 0;
17637
- return this.ask(anchorsRequest(fields), anchorsOf);
17862
+ async sessionAnchors(fields2) {
17863
+ if (!anchorsAskable(fields2)) return void 0;
17864
+ return this.ask(anchorsRequest(fields2), anchorsOf);
17638
17865
  }
17639
17866
  async ask(req, parse) {
17640
17867
  const { hook } = this;
@@ -17766,7 +17993,7 @@ var SUDOERS_SYNTAX = "<user|%group|ALL> ALL=[(<target>[,<target>\u2026])] [NOPAS
17766
17993
  var EXPECTED = `expected '${KERNEL_SYNTAX}' or '${SUDOERS_SYNTAX}'`;
17767
17994
  var TIMESTAMP_TIMEOUT = 5;
17768
17995
  var TIMESTAMP_TYPE = "tty";
17769
- function hasControl(text) {
17996
+ function hasControl2(text) {
17770
17997
  return CONTROL2.test(text);
17771
17998
  }
17772
17999
  function withoutControl(text) {
@@ -17806,7 +18033,7 @@ function splitWords(text) {
17806
18033
  return words3;
17807
18034
  }
17808
18035
  function quoteWord(word) {
17809
- const text = hasControl(word) ? withoutControl(word) : word;
18036
+ const text = hasControl2(word) ? withoutControl(word) : word;
17810
18037
  return PLAIN.test(text) ? text : `'${text.replaceAll("'", `'\\''`)}'`;
17811
18038
  }
17812
18039
  function addPart(word, part) {
@@ -17961,7 +18188,7 @@ function kernelRules(m) {
17961
18188
  if (stdin !== void 0 && stdin !== "none") return `Stdin takes none, not ${shown(stdin)}`;
17962
18189
  const sha2564 = sha256Of(sums);
17963
18190
  if (typeof sha2564 === "string") return sha2564;
17964
- const rule = {
18191
+ const rule2 = {
17965
18192
  nopasswd: !!nopasswd,
17966
18193
  who,
17967
18194
  target,
@@ -17970,9 +18197,9 @@ function kernelRules(m) {
17970
18197
  ...sums === "" ? {} : { sha256: sha2564 }
17971
18198
  };
17972
18199
  const text = rest2.trim();
17973
- if (text === "*") return [{ ...rule, cmnd: "*" }];
18200
+ if (text === "*") return [{ ...rule2, cmnd: "*" }];
17974
18201
  const cmnd = commandOf2(text, "Cmnd: an absolute path, or *");
17975
- return typeof cmnd === "string" ? cmnd : [{ ...rule, cmnd }];
18202
+ return typeof cmnd === "string" ? cmnd : [{ ...rule2, cmnd }];
17976
18203
  }
17977
18204
  function runasOf(list) {
17978
18205
  const colon = list.indexOf(":");
@@ -18073,15 +18300,15 @@ function directiveError(text) {
18073
18300
  }
18074
18301
  return void 0;
18075
18302
  }
18076
- function recordedBare(line, file, rule) {
18077
- if (rule.cmnd === "*" || rule.cmnd.args !== void 0 || !rule.nopasswd) return false;
18078
- if (file !== `${SUDOERS_D}/${rule.who}` || !NAME3.test(rule.who) || !NAME3.test(rule.target)) {
18303
+ function recordedBare(line, file, rule2) {
18304
+ if (rule2.cmnd === "*" || rule2.cmnd.args !== void 0 || !rule2.nopasswd) return false;
18305
+ if (file !== `${SUDOERS_D}/${rule2.who}` || !NAME3.test(rule2.who) || !NAME3.test(rule2.target)) {
18079
18306
  return false;
18080
18307
  }
18081
- const head = `NOPASSWD ${rule.who} (${rule.target}) `;
18082
- const cmnd = `Cmnd ${quoteWord(rule.cmnd.path)}`;
18083
- const cwd = rule.cwd === void 0 ? "" : `Cwd ${quoteWord(rule.cwd)} `;
18084
- const stdin = rule.stdin === void 0 ? "" : "Stdin none ";
18308
+ const head = `NOPASSWD ${rule2.who} (${rule2.target}) `;
18309
+ const cmnd = `Cmnd ${quoteWord(rule2.cmnd.path)}`;
18310
+ const cwd = rule2.cwd === void 0 ? "" : `Cwd ${quoteWord(rule2.cwd)} `;
18311
+ const stdin = rule2.stdin === void 0 ? "" : "Stdin none ";
18085
18312
  return line.trimEnd() === `${head}${cwd}${stdin}${cmnd}`;
18086
18313
  }
18087
18314
  function kernelLine(m, line, file) {
@@ -18089,7 +18316,7 @@ function kernelLine(m, line, file) {
18089
18316
  if (typeof rules === "string") return { error: rules };
18090
18317
  return {
18091
18318
  rules: rules.map(
18092
- (rule) => recordedBare(line, file, rule) && rule.cmnd !== "*" ? { ...rule, cmnd: { path: rule.cmnd.path, args: [] } } : rule
18319
+ (rule2) => recordedBare(line, file, rule2) && rule2.cmnd !== "*" ? { ...rule2, cmnd: { path: rule2.cmnd.path, args: [] } } : rule2
18093
18320
  )
18094
18321
  };
18095
18322
  }
@@ -18129,7 +18356,7 @@ function keepParam(param, bangs, op, raw2) {
18129
18356
  const quoted = /^"(.*)"$/s.exec(raw2);
18130
18357
  const value2 = (quoted ? quoted[1] : raw2).trim();
18131
18358
  const names2 = value2 === "" ? [] : value2.split(/[ \t]+/);
18132
- const named = names2.every((name2) => !/["\\]/.test(name2) && !hasControl(name2));
18359
+ const named = names2.every((name2) => !/["\\]/.test(name2) && !hasControl2(name2));
18133
18360
  const listed = quoted ? named : named && names2.length === 1;
18134
18361
  if (bangs !== "" || op === void 0 || !KEEP_OPS.includes(op) || !listed) {
18135
18362
  return `env_keep takes a double-quoted, space-separated list of names, or one name without quotes, after =, += or -= (!env_keep empties the list), not ${shown(param)}`;
@@ -18702,11 +18929,11 @@ function userWritable(bound3) {
18702
18929
  const files = Object.entries(bound3).map(([path, hex5]) => ({ path, sha256: hex5 }));
18703
18930
  return files.length > 0 ? { userWritable: files } : {};
18704
18931
  }
18705
- function stdinMatches(rule, stdin) {
18706
- return rule.stdin === void 0 || stdin === "tty" || stdin === "none";
18932
+ function stdinMatches(rule2, stdin) {
18933
+ return rule2.stdin === void 0 || stdin === "tty" || stdin === "none";
18707
18934
  }
18708
18935
  function recordable(cwd, argv) {
18709
- return !hasControl(cwd) && !argv.some(hasControl);
18936
+ return !hasControl2(cwd) && !argv.some(hasControl2);
18710
18937
  }
18711
18938
  function changedText(file) {
18712
18939
  return `sudo: ${file} changed since it was approved`;
@@ -18718,8 +18945,8 @@ function changedFile(approved, now) {
18718
18945
  const files = /* @__PURE__ */ new Set([...Object.keys(approved), ...Object.keys(now)]);
18719
18946
  return [...files].find((file) => approved[file] !== now[file]);
18720
18947
  }
18721
- function pinned(rule, bound3) {
18722
- return rule.sha256 === void 0 || changedFile(rule.sha256, bound3) === void 0;
18948
+ function pinned(rule2, bound3) {
18949
+ return rule2.sha256 === void 0 || changedFile(rule2.sha256, bound3) === void 0;
18723
18950
  }
18724
18951
  var REPLAY_ID = /^[!-~]{1,256}$/;
18725
18952
  var REPLAY_TAGS_MAX = 64;
@@ -18817,9 +19044,9 @@ function denialText(answer2) {
18817
19044
  }
18818
19045
  }
18819
19046
  async function answerOf(approve, req, signal) {
18820
- let reply;
19047
+ let reply2;
18821
19048
  let cut;
18822
- const snapshot = () => reply === void 0 ? Promise.resolve(ABORTED) : Promise.race([reply, Promise.resolve(ABORTED)]).catch(() => "deny");
19049
+ const snapshot = () => reply2 === void 0 ? Promise.resolve(ABORTED) : Promise.race([reply2, Promise.resolve(ABORTED)]).catch(() => "deny");
18823
19050
  const aborted4 = new Promise(
18824
19051
  (resolve2) => signal.addEventListener(
18825
19052
  "abort",
@@ -18831,12 +19058,12 @@ async function answerOf(approve, req, signal) {
18831
19058
  )
18832
19059
  );
18833
19060
  try {
18834
- reply = Promise.resolve(approve(req, { signal }));
19061
+ reply2 = Promise.resolve(approve(req, { signal }));
18835
19062
  } catch {
18836
- reply = Promise.resolve("deny");
19063
+ reply2 = Promise.resolve("deny");
18837
19064
  }
18838
19065
  try {
18839
- const answer2 = await Promise.race([reply, aborted4]);
19066
+ const answer2 = await Promise.race([reply2, aborted4]);
18840
19067
  return cut === void 0 ? answer2 : await cut;
18841
19068
  } catch {
18842
19069
  return cut === void 0 ? "deny" : await cut;
@@ -18912,13 +19139,13 @@ function usable(parsed3) {
18912
19139
  function policyOf(settings) {
18913
19140
  return { type: settings.timestampType, minutes: settings.timestampTimeout };
18914
19141
  }
18915
- function described(rule, writable3) {
18916
- const cmnd = rule.cmnd === "*" ? "ALL" : commandText(rule.cmnd);
18917
- const cwd = rule.cwd === void 0 ? "" : `CWD=${quoteWord(rule.cwd)} `;
18918
- const stdin = rule.stdin === void 0 ? "" : "STDIN=none ";
18919
- const sums = Object.entries(rule.sha256 ?? {}).map(([path, hex5]) => `SHA256=${quoteWord(path)}:${hex5} `).join("");
19142
+ function described(rule2, writable3) {
19143
+ const cmnd = rule2.cmnd === "*" ? "ALL" : commandText(rule2.cmnd);
19144
+ const cwd = rule2.cwd === void 0 ? "" : `CWD=${quoteWord(rule2.cwd)} `;
19145
+ const stdin = rule2.stdin === void 0 ? "" : "STDIN=none ";
19146
+ const sums = Object.entries(rule2.sha256 ?? {}).map(([path, hex5]) => `SHA256=${quoteWord(path)}:${hex5} `).join("");
18920
19147
  const flag = writable3 ? " # user-writable command" : "";
18921
- return ` (${rule.target}) ${cwd}${stdin}${sums}${rule.nopasswd ? "NOPASSWD: " : ""}${cmnd}${flag}`;
19148
+ return ` (${rule2.target}) ${cwd}${stdin}${sums}${rule2.nopasswd ? "NOPASSWD: " : ""}${cmnd}${flag}`;
18922
19149
  }
18923
19150
  var Sudo = class {
18924
19151
  o;
@@ -19128,9 +19355,9 @@ var Sudo = class {
19128
19355
  const bound3 = files && await this.digests([path, ...files]);
19129
19356
  return bound3 && !Object.values(bound3).includes("") ? bound3 : void 0;
19130
19357
  }
19131
- async writable(rule) {
19132
- if (rule.cmnd === "*") return false;
19133
- const { path } = rule.cmnd;
19358
+ async writable(rule2) {
19359
+ if (rule2.cmnd === "*") return false;
19360
+ const { path } = rule2.cmnd;
19134
19361
  const bound3 = await this.bound(path, "/");
19135
19362
  if (bound3) return Object.keys(bound3).length > 0;
19136
19363
  return !await this.trusted(await this.existing(path));
@@ -19177,7 +19404,7 @@ var Sudo = class {
19177
19404
  if (!target) return failed2("ENOENT", `sudo: unknown user ${parsed3.user}`);
19178
19405
  const root = cred.euid === 0;
19179
19406
  const rules = root ? [] : policy.rules;
19180
- const mine = rules.filter((rule) => applies(rule.who));
19407
+ const mine = rules.filter((rule2) => applies(rule2.who));
19181
19408
  if (parsed3.list) return await this.listed(self, root, mine, settings.matching);
19182
19409
  const kept = keptEnv(call.env ?? {}, settings.envKeep);
19183
19410
  const session = {
@@ -19245,7 +19472,7 @@ var Sudo = class {
19245
19472
  const { rules } = await this.policyRules({ cred, pid: 0, stdin: r.stdin });
19246
19473
  const applies = await this.applies(self, cred);
19247
19474
  return rules.some(
19248
- (rule) => applies(rule.who) && (rule.target === "ALL" || rule.target === target.name) && (rule.cwd === void 0 || rule.cwd === r.cwd) && stdinMatches(rule, r.stdin) && commandMatches(rule.cmnd, argv) && pinned(rule, r.bound)
19475
+ (rule2) => applies(rule2.who) && (rule2.target === "ALL" || rule2.target === target.name) && (rule2.cwd === void 0 || rule2.cwd === r.cwd) && stdinMatches(rule2, r.stdin) && commandMatches(rule2.cmnd, argv) && pinned(rule2, r.bound)
19249
19476
  );
19250
19477
  }
19251
19478
  async command(s, root, mine, call) {
@@ -19264,10 +19491,10 @@ var Sudo = class {
19264
19491
  if (!path || !bound3) return failed2("ENOENT", `sudo: ${word}: command not found`);
19265
19492
  const argv = [path, ...args];
19266
19493
  const matching = mine.filter(
19267
- (rule) => (rule.target === "ALL" || rule.target === target.name) && (rule.cwd === void 0 || rule.cwd === cwd) && stdinMatches(rule, caller.stdin) && commandMatches(rule.cmnd, argv) && pinned(rule, bound3)
19494
+ (rule2) => (rule2.target === "ALL" || rule2.target === target.name) && (rule2.cwd === void 0 || rule2.cwd === cwd) && stdinMatches(rule2, caller.stdin) && commandMatches(rule2.cmnd, argv) && pinned(rule2, bound3)
19268
19495
  );
19269
19496
  const grant = () => this.grant(self, target, cred, parsed3.command, path, cwd, call.term, bound3, s.kept);
19270
- if (root || matching.some((rule) => rule.nopasswd)) return grant();
19497
+ if (root || matching.some((rule2) => rule2.nopasswd)) return grant();
19271
19498
  const quoted = argv.map(quoteWord).join(" ");
19272
19499
  if (matching.length === 0) {
19273
19500
  return failed2(
@@ -19301,7 +19528,7 @@ var Sudo = class {
19301
19528
  if (mine.length === 0) {
19302
19529
  return failed2("EPERM", `Sorry, user ${self.name} may not run sudo on ${this.o.hostname}.`);
19303
19530
  }
19304
- if (mine.every((rule) => rule.nopasswd)) return DONE;
19531
+ if (mine.every((rule2) => rule2.nopasswd)) return DONE;
19305
19532
  if (!parsed3.reset && this.timestamps.current(s.owner, s.policy)) {
19306
19533
  this.timestamps.stamp(s.owner, s.policy);
19307
19534
  return DONE;
@@ -19360,7 +19587,7 @@ var Sudo = class {
19360
19587
  return failed2("EPERM", `User ${self.name} is not allowed to run sudo on ${host}.`);
19361
19588
  }
19362
19589
  const shown2 = [];
19363
- for (const rule of rules) shown2.push(described(rule, await this.writable(rule)));
19590
+ for (const rule2 of rules) shown2.push(described(rule2, await this.writable(rule2)));
19364
19591
  const lines3 = shown2.join("\n");
19365
19592
  const params = defaults2.flatMap((d) => d.params).join(", ");
19366
19593
  const matching = params === "" ? "" : `Matching Defaults entries for ${self.name} on ${host}:
@@ -20793,8 +21020,8 @@ function sameCert(a, b) {
20793
21020
  if (!a || !b) return a === b;
20794
21021
  return a.cert.length === b.cert.length && a.cert.every((byte, i) => byte === b.cert[i]);
20795
21022
  }
20796
- function winner(current, expected, record3) {
20797
- return sameCert(current, expected) ? record3 : current;
21023
+ function winner(current, expected, record4) {
21024
+ return sameCert(current, expected) ? record4 : current;
20798
21025
  }
20799
21026
  var DAY = 24 * 60 * 60 * 1e3;
20800
21027
  var CA_LIFETIME = 3650 * DAY;
@@ -20811,14 +21038,14 @@ function validLeafName(host) {
20811
21038
  }
20812
21039
  var RealmCa = class _RealmCa {
20813
21040
  record;
20814
- constructor(record3) {
20815
- this.record = record3;
21041
+ constructor(record4) {
21042
+ this.record = record4;
20816
21043
  }
20817
21044
  static async open(owner, store, now = Date.now()) {
20818
21045
  const stored = await store.get(owner).catch(() => void 0);
20819
21046
  if (stored && stored.notAfter - now > CA_RENEW_BEFORE) return new _RealmCa(stored);
20820
- const record3 = await _RealmCa.create(owner, now);
20821
- return new _RealmCa(await store.swap(owner, stored, record3));
21047
+ const record4 = await _RealmCa.create(owner, now);
21048
+ return new _RealmCa(await store.swap(owner, stored, record4));
20822
21049
  }
20823
21050
  static async create(owner, now) {
20824
21051
  const pair = await crypto.subtle.generateKey(ECDSA, false, ["sign", "verify"]);
@@ -21044,8 +21271,8 @@ function memoryCaStore() {
21044
21271
  const records = /* @__PURE__ */ new Map();
21045
21272
  return {
21046
21273
  get: async (owner) => records.get(owner),
21047
- swap: async (owner, expected, record3) => {
21048
- const kept = winner(records.get(owner), expected, record3);
21274
+ swap: async (owner, expected, record4) => {
21275
+ const kept = winner(records.get(owner), expected, record4);
21049
21276
  records.set(owner, kept);
21050
21277
  return kept;
21051
21278
  }
@@ -21423,14 +21650,14 @@ var HttpHandles = class {
21423
21650
  const port = this.local?.port(req.url);
21424
21651
  try {
21425
21652
  const target = port === void 0 ? toHostLoopback(req.url) : req.url;
21426
- const request = {
21653
+ const request2 = {
21427
21654
  url: target,
21428
21655
  method: req.method,
21429
21656
  headers: req.headers,
21430
21657
  ...entry.upload ? { bodyStream: entry.upload } : req.body ? { body: req.body } : {},
21431
21658
  signal: entry.abort.signal
21432
21659
  };
21433
- const response = port === void 0 ? await this.transport.fetch(request, this.owner, await this.stamp?.()) : await this.local.fetch(request, port);
21660
+ const response = port === void 0 ? await this.transport.fetch(request2, this.owner, await this.stamp?.()) : await this.local.fetch(request2, port);
21434
21661
  entry.body = response.body[Symbol.asyncIterator]();
21435
21662
  entry.cancel = () => response.cancel();
21436
21663
  if (!this.open.has(handle)) await entry.cancel().catch(() => void 0);
@@ -21622,7 +21849,7 @@ function header2(id2, flags2, counts) {
21622
21849
  function opt() {
21623
21850
  return [0, 0, TYPE_OPT, UDP_EDNS >> 8, UDP_EDNS & 255, 0, 0, 0, 0, 0, 0];
21624
21851
  }
21625
- function record2(type, rdata) {
21852
+ function record3(type, rdata) {
21626
21853
  const ttl = DNS_STUB_TTL;
21627
21854
  return [
21628
21855
  192,
@@ -21643,11 +21870,11 @@ function record2(type, rdata) {
21643
21870
  function replyFlags(query, rcode, aa) {
21644
21871
  return QR | query & 30720 | (aa ? AA : 0) | query & RD | RA | query & CD | rcode;
21645
21872
  }
21646
- function answers(reply, q) {
21647
- if (reply.length < 12 || !(u16(reply, 2) & QR) || u16(reply, 4) !== 1) return false;
21648
- const read = readName(reply, 12);
21649
- if (!read || read.end + 4 > reply.length) return false;
21650
- return read.name === q.name && u16(reply, read.end) === q.type && u16(reply, read.end + 2) === q.klass;
21873
+ function answers(reply2, q) {
21874
+ if (reply2.length < 12 || !(u16(reply2, 2) & QR) || u16(reply2, 4) !== 1) return false;
21875
+ const read = readName(reply2, 12);
21876
+ if (!read || read.end + 4 > reply2.length) return false;
21877
+ return read.name === q.name && u16(reply2, read.end) === q.type && u16(reply2, read.end + 2) === q.klass;
21651
21878
  }
21652
21879
  function errorReply2(id2, flags2, rcode) {
21653
21880
  return new Uint8Array(header2(id2, replyFlags(flags2, rcode, false), [0, 0, 0, 0]));
@@ -21661,10 +21888,10 @@ function answerReply(query, q, rcode, answers2, aa) {
21661
21888
  ...extra.flat()
21662
21889
  ]);
21663
21890
  }
21664
- function truncated(reply, q, query) {
21891
+ function truncated(reply2, q, query) {
21665
21892
  const limit = q.edns !== void 0 ? Math.min(q.edns, UDP_MAX) : UDP_PLAIN;
21666
- if (reply.length <= limit) return reply;
21667
- const flags2 = u16(reply, 2) | TC;
21893
+ if (reply2.length <= limit) return reply2;
21894
+ const flags2 = u16(reply2, 2) | TC;
21668
21895
  const extra = q.edns !== void 0 ? [opt()] : [];
21669
21896
  return new Uint8Array([
21670
21897
  ...header2(q.id, flags2, [1, 0, 0, extra.length]),
@@ -21719,10 +21946,10 @@ var DnsStub = class {
21719
21946
  if (!parsed3) return void 0;
21720
21947
  if (!parsed3.ok) return errorReply2(parsed3.id, parsed3.flags, parsed3.rcode);
21721
21948
  const q = parsed3.question;
21722
- const reply = await this.reply(query, q).catch(
21949
+ const reply2 = await this.reply(query, q).catch(
21723
21950
  () => answerReply(query, q, SERVFAIL, [], false)
21724
21951
  );
21725
- return udp ? truncated(reply, q, query) : reply;
21952
+ return udp ? truncated(reply2, q, query) : reply2;
21726
21953
  }
21727
21954
  async reply(query, q) {
21728
21955
  if (q.klass !== CLASS_IN || literal2(q.name)) return this.forward(query, q);
@@ -21730,14 +21957,14 @@ var DnsStub = class {
21730
21957
  const address2 = reverseAddress(q.name);
21731
21958
  const name2 = address2 !== void 0 ? await this.reverse(address2) : void 0;
21732
21959
  if (name2 !== void 0)
21733
- return answerReply(query, q, NOERROR, [record2(TYPE_PTR, encodeName(name2))], true);
21960
+ return answerReply(query, q, NOERROR, [record3(TYPE_PTR, encodeName(name2))], true);
21734
21961
  return this.forward(query, q);
21735
21962
  }
21736
21963
  if (q.type === TYPE_A || q.type === TYPE_AAAA) {
21737
21964
  const addresses = q.name === "" ? [] : await this.lookup(q.name);
21738
21965
  const answers2 = addresses.flatMap((a) => {
21739
21966
  const data = addressData(a, q.type);
21740
- return data ? [record2(q.type, data)] : [];
21967
+ return data ? [record3(q.type, data)] : [];
21741
21968
  });
21742
21969
  if (answers2.length > 0 || local(q.name) || await this.known(q.name)) {
21743
21970
  const rcode = addresses.length > 0 ? NOERROR : NXDOMAIN;
@@ -21770,10 +21997,10 @@ var DnsStub = class {
21770
21997
  () => void 0
21771
21998
  );
21772
21999
  if (!got || !answers(got, q)) return answerReply(query, q, SERVFAIL, [], false);
21773
- const reply = got.slice();
21774
- reply[0] = q.id >> 8;
21775
- reply[1] = q.id & 255;
21776
- return reply;
22000
+ const reply2 = got.slice();
22001
+ reply2[0] = q.id >> 8;
22002
+ reply2[1] = q.id & 255;
22003
+ return reply2;
21777
22004
  }
21778
22005
  };
21779
22006
  async function collect(body, max) {
@@ -21848,28 +22075,28 @@ function addressText(type, rdata) {
21848
22075
  if (type !== TYPE_AAAA || rdata.length !== 16) return void 0;
21849
22076
  return ipv6Text(Array.from({ length: 8 }, (_, i) => u16(rdata, i * 2)));
21850
22077
  }
21851
- function addressesOf(reply, type) {
21852
- if (reply.length < 12 || !(u16(reply, 2) & QR)) return void 0;
21853
- const rcode = u16(reply, 2) & 15;
22078
+ function addressesOf(reply2, type) {
22079
+ if (reply2.length < 12 || !(u16(reply2, 2) & QR)) return void 0;
22080
+ const rcode = u16(reply2, 2) & 15;
21854
22081
  if (rcode === NXDOMAIN) return { addresses: [] };
21855
22082
  if (rcode !== NOERROR) return void 0;
21856
22083
  let at = 12;
21857
- for (let n = u16(reply, 4); n > 0; n--) {
21858
- const after = skipName(reply, at);
22084
+ for (let n = u16(reply2, 4); n > 0; n--) {
22085
+ const after = skipName(reply2, at);
21859
22086
  if (after === void 0) return void 0;
21860
22087
  at = after + 4;
21861
22088
  }
21862
22089
  const addresses = [];
21863
22090
  let ttl;
21864
- for (let n = u16(reply, 6); n > 0; n--) {
21865
- const after = skipName(reply, at);
21866
- if (after === void 0 || after + 10 > reply.length) return void 0;
21867
- const end = after + 10 + u16(reply, after + 8);
21868
- if (end > reply.length) return void 0;
21869
- const text = u16(reply, after) === type && u16(reply, after + 2) === CLASS_IN ? addressText(type, reply.subarray(after + 10, end)) : void 0;
22091
+ for (let n = u16(reply2, 6); n > 0; n--) {
22092
+ const after = skipName(reply2, at);
22093
+ if (after === void 0 || after + 10 > reply2.length) return void 0;
22094
+ const end = after + 10 + u16(reply2, after + 8);
22095
+ if (end > reply2.length) return void 0;
22096
+ const text = u16(reply2, after) === type && u16(reply2, after + 2) === CLASS_IN ? addressText(type, reply2.subarray(after + 10, end)) : void 0;
21870
22097
  if (text !== void 0) {
21871
22098
  addresses.push(text);
21872
- ttl = Math.min(ttl ?? Number.POSITIVE_INFINITY, u32(reply, after + 4));
22099
+ ttl = Math.min(ttl ?? Number.POSITIVE_INFINITY, u32(reply2, after + 4));
21873
22100
  }
21874
22101
  at = end;
21875
22102
  }
@@ -21889,8 +22116,8 @@ async function forwardedLookup(forward, name2, family, signal) {
21889
22116
  const types = family === 4 ? [TYPE_A] : family === 6 ? [TYPE_AAAA] : [TYPE_A, TYPE_AAAA];
21890
22117
  const answers2 = await Promise.all(
21891
22118
  types.map(async (type) => {
21892
- const reply = await forward(addressQuery(name2, type), signal);
21893
- const answer2 = reply ? addressesOf(reply, type) : void 0;
22119
+ const reply2 = await forward(addressQuery(name2, type), signal);
22120
+ const answer2 = reply2 ? addressesOf(reply2, type) : void 0;
21894
22121
  if (!answer2) throw new Error(`the DNS forwarder gave no answer for ${name2}`);
21895
22122
  return answer2;
21896
22123
  })
@@ -21926,9 +22153,9 @@ async function serveTcp(stub, conn) {
21926
22153
  if (!size) return;
21927
22154
  const query = await readExactly(conn, u16(size, 0), idle2);
21928
22155
  if (!query) return;
21929
- const reply = await stub.answer(query, false);
21930
- if (!reply) return;
21931
- const framed = new Uint8Array([reply.length >> 8, reply.length & 255, ...reply]);
22156
+ const reply2 = await stub.answer(query, false);
22157
+ if (!reply2) return;
22158
+ const framed = new Uint8Array([reply2.length >> 8, reply2.length & 255, ...reply2]);
21932
22159
  const sent = await conn.write(framed, AbortSignal.timeout(DNS_TCP_IDLE_MS));
21933
22160
  if (sent < framed.length) return;
21934
22161
  }
@@ -21963,10 +22190,10 @@ function enableDnsStub(net, stub) {
21963
22190
  if (inflight >= DNS_UDP_INFLIGHT) return;
21964
22191
  inflight++;
21965
22192
  void stub.answer(datagram2.bytes, true).then(
21966
- (reply) => {
21967
- if (!reply) return;
22193
+ (reply2) => {
22194
+ if (!reply2) return;
21968
22195
  const from = { family: "inet", host: to.host, port: DNS_PORT };
21969
- net.deliverDgram(datagram2.from.port, { bytes: reply, from });
22196
+ net.deliverDgram(datagram2.from.port, { bytes: reply2, from });
21970
22197
  },
21971
22198
  () => void 0
21972
22199
  ).finally(() => inflight--);
@@ -23197,15 +23424,15 @@ async function substituteHead(head, ask) {
23197
23424
  if (!head.endsWith("\r\n\r\n")) return void 0;
23198
23425
  const lines3 = head.slice(0, -4).split("\r\n");
23199
23426
  if (lines3.some((l) => l.includes("\n") || l.includes("\r"))) return void 0;
23200
- const request = REQUEST_LINE2.exec(lines3[0]);
23201
- const found = request ? scan(lines3) : void 0;
23202
- if (!request || !found || found.length !== 1) return void 0;
23427
+ const request2 = REQUEST_LINE2.exec(lines3[0]);
23428
+ const found = request2 ? scan(lines3) : void 0;
23429
+ if (!request2 || !found || found.length !== 1) return void 0;
23203
23430
  const at = found[0];
23204
23431
  if (at.placeholders.length > SESSION_PLACEHOLDERS) return void 0;
23205
23432
  const values = usable2(
23206
23433
  await ask(`header:${at.name}`, at.placeholders, {
23207
- method: request[1],
23208
- path: request[2]
23434
+ method: request2[1],
23435
+ path: request2[2]
23209
23436
  })
23210
23437
  );
23211
23438
  if (Object.keys(values).length === 0) return void 0;
@@ -23632,9 +23859,9 @@ async function swapped(text, position, ask) {
23632
23859
  }
23633
23860
  async function plain2(b642, ask) {
23634
23861
  const text = decoded(b642);
23635
- const fields = text?.split("\0");
23636
- if (fields?.length !== 3) return { line: b642 };
23637
- const [authz, user, pass2] = fields;
23862
+ const fields2 = text?.split("\0");
23863
+ if (fields2?.length !== 3) return { line: b642 };
23864
+ const [authz, user, pass2] = fields2;
23638
23865
  if (placeholdersIn(authz + user).length > 0) return { line: b642 };
23639
23866
  const done4 = await swapped(pass2, "auth-plain", ask);
23640
23867
  if (!done4) return { line: b642 };
@@ -26753,8 +26980,8 @@ var WasmProcess = class {
26753
26980
  return "deliver";
26754
26981
  }
26755
26982
  if (!(this.caught & bit)) {
26756
- const action = defaultAction(sig);
26757
- return action === "stop" ? this.stop(sig) : action;
26983
+ const action2 = defaultAction(sig);
26984
+ return action2 === "stop" ? this.stop(sig) : action2;
26758
26985
  }
26759
26986
  if (((this.options.pendingBits?.() ?? 0) & bit) !== 0) {
26760
26987
  if (STUCK_ESCAPES.has(sig) && this.pendingAt.get(sig) === this.calls) return "terminate";
@@ -28435,7 +28662,7 @@ var JsThreads = class {
28435
28662
  control.close();
28436
28663
  };
28437
28664
  const ops = /* @__PURE__ */ new Map();
28438
- const dispatch2 = async (req, block) => {
28665
+ const dispatch3 = async (req, block) => {
28439
28666
  if (isWasmSyscall(req) && req.op === "proc-exit") {
28440
28667
  queueMicrotask(() => end(req.status & 255));
28441
28668
  return ENDING;
@@ -28445,8 +28672,8 @@ var JsThreads = class {
28445
28672
  if (!ended) track(ops, req, result);
28446
28673
  return result;
28447
28674
  };
28448
- const responder = this.deps.attach(worker, sab, this.deps.clocks.timed(clock, dispatch2));
28449
- const lane = this.deps.openLane(dispatch2);
28675
+ const responder = this.deps.attach(worker, sab, this.deps.clocks.timed(clock, dispatch3));
28676
+ const lane = this.deps.openLane(dispatch3);
28450
28677
  const onMessage = (event) => {
28451
28678
  const data = event.data;
28452
28679
  if (data?.type === JS_THREAD_EXIT) end(codeOf4(data.code));
@@ -28630,10 +28857,10 @@ function transferOf(opts, lane) {
28630
28857
  const transfer = opts.fork ? [opts.fork.memory.buffer] : [];
28631
28858
  return lane ? [...transfer, lane.port] : transfer;
28632
28859
  }
28633
- function openLane(token, dispatch2) {
28860
+ function openLane(token, dispatch3) {
28634
28861
  const sab = new SharedArrayBuffer(SAB_HEADER_BYTES + SAB_DEFAULT_WINDOW_BYTES);
28635
28862
  const { port1, port2 } = new MessageChannel();
28636
- const responder = attachSyncSabResponder(port1, sab, token, { dispatch: dispatch2 });
28863
+ const responder = attachSyncSabResponder(port1, sab, token, { dispatch: dispatch3 });
28637
28864
  port1.start();
28638
28865
  return {
28639
28866
  lane: { sab, port: port2 },
@@ -28888,16 +29115,16 @@ function spawnWasmProcess(opts) {
28888
29115
  heldBy(process, holds3, opts.replacements);
28889
29116
  const worker = opts.createWorker();
28890
29117
  const dying = new Dying();
28891
- const dispatch2 = (req, block) => dying.serve(
29118
+ const dispatch3 = (req, block) => dying.serve(
28892
29119
  req,
28893
29120
  () => isWasmSyscall(req) ? process.syscall(req, callAbort(req), block) : dispatchSyncFs(req)
28894
29121
  );
28895
29122
  const clocks = new ProcessClocks(sab, opts.program.abi !== "js", process);
28896
29123
  const responder = attachSyncSabResponder(worker, sab, token, {
28897
- dispatch: clocks.timed(void 0, dispatch2)
29124
+ dispatch: clocks.timed(void 0, dispatch3)
28898
29125
  });
28899
- const lane = opts.program.abi === "js" ? openLane(token, dispatch2) : void 0;
28900
- const jsThreads = jsThreadsOf(opts, process, token, dispatch2, clocks, header5);
29126
+ const lane = opts.program.abi === "js" ? openLane(token, dispatch3) : void 0;
29127
+ const jsThreads = jsThreadsOf(opts, process, token, dispatch3, clocks, header5);
28901
29128
  const { promise: exited, resolve: settle } = Promise.withResolvers();
28902
29129
  let done4 = false;
28903
29130
  const crash = new CrashSlot((message3) => crashReport(process, opts.onError, message3));
@@ -29017,7 +29244,7 @@ function spawnWasmProcess(opts) {
29017
29244
  ...clockViews(clocks)
29018
29245
  };
29019
29246
  }
29020
- function jsThreadsOf(opts, process, token, dispatch2, clocks, header5) {
29247
+ function jsThreadsOf(opts, process, token, dispatch3, clocks, header5) {
29021
29248
  if (opts.program.abi !== "js") return void 0;
29022
29249
  const wakes = /* @__PURE__ */ new Set();
29023
29250
  asyncFanout.set(header5, wakes);
@@ -29028,7 +29255,7 @@ function jsThreadsOf(opts, process, token, dispatch2, clocks, header5) {
29028
29255
  init: (sab, lane) => processInit(opts, sab, process.umask, copyCred(process.cred), lane),
29029
29256
  openLane: (laneDispatch) => openLane(token, laneDispatch),
29030
29257
  attach: (worker, sab, threadDispatch) => attachSyncSabResponder(worker, sab, token, { dispatch: threadDispatch }),
29031
- dispatch: dispatch2,
29258
+ dispatch: dispatch3,
29032
29259
  clocks,
29033
29260
  admission: opts.admission
29034
29261
  });
@@ -29787,15 +30014,15 @@ var LockService = class {
29787
30014
  const known = this.granted.get(id2);
29788
30015
  if (known) return void this.channel.postMessage({ id: id2, to: from, ...known });
29789
30016
  await this.settled;
29790
- let reply;
30017
+ let reply2;
29791
30018
  try {
29792
- reply = { ok: await this.serve(ask, from, id2) ?? null };
30019
+ reply2 = { ok: await this.serve(ask, from, id2) ?? null };
29793
30020
  } catch (err) {
29794
- reply = { errno: err.code ?? "EIO" };
30021
+ reply2 = { errno: err.code ?? "EIO" };
29795
30022
  }
29796
- this.granted.set(id2, reply);
30023
+ this.granted.set(id2, reply2);
29797
30024
  if (this.granted.size > 4096) this.granted.delete(this.granted.keys().next().value);
29798
- this.channel.postMessage({ id: id2, to: from, ...reply });
30025
+ this.channel.postMessage({ id: id2, to: from, ...reply2 });
29799
30026
  }
29800
30027
  ownerFor(kernel, owner) {
29801
30028
  if (kernel === this.kernel) return owner;
@@ -30070,26 +30297,26 @@ var RemoteTransport = class {
30070
30297
  this.port = port;
30071
30298
  this.traits = traits;
30072
30299
  }
30073
- receive(reply) {
30074
- if (reply.net === "body-pull") {
30075
- void this.pull(reply.nid);
30300
+ receive(reply2) {
30301
+ if (reply2.net === "body-pull") {
30302
+ void this.pull(reply2.nid);
30076
30303
  return;
30077
30304
  }
30078
- const socket = this.sockets.get(reply.nid);
30079
- if (socket && this.toSocket(reply, socket)) return;
30080
- const waiter = this.waiting.get(reply.nid);
30305
+ const socket = this.sockets.get(reply2.nid);
30306
+ if (socket && this.toSocket(reply2, socket)) return;
30307
+ const waiter = this.waiting.get(reply2.nid);
30081
30308
  if (!waiter) return;
30082
- this.waiting.delete(reply.nid);
30083
- if (reply.net === "error") {
30084
- waiter.reject(new TransportError(reply.message, reply.status, reply.code, reply.detail));
30085
- } else waiter.resolve(reply);
30086
- }
30087
- toSocket(reply, socket) {
30088
- if (reply.net === "ws-message") socket.queue.push(reply.data);
30089
- else if (reply.net === "ws-acked") socket.acked(reply.n);
30090
- else if (reply.net === "ws-closed") {
30091
- this.sockets.delete(reply.nid);
30092
- socket.queue.end({ code: reply.code, reason: reply.reason });
30309
+ this.waiting.delete(reply2.nid);
30310
+ if (reply2.net === "error") {
30311
+ waiter.reject(new TransportError(reply2.message, reply2.status, reply2.code, reply2.detail));
30312
+ } else waiter.resolve(reply2);
30313
+ }
30314
+ toSocket(reply2, socket) {
30315
+ if (reply2.net === "ws-message") socket.queue.push(reply2.data);
30316
+ else if (reply2.net === "ws-acked") socket.acked(reply2.n);
30317
+ else if (reply2.net === "ws-closed") {
30318
+ this.sockets.delete(reply2.nid);
30319
+ socket.queue.end({ code: reply2.code, reason: reply2.reason });
30093
30320
  } else return false;
30094
30321
  return true;
30095
30322
  }
@@ -30141,9 +30368,9 @@ var RemoteTransport = class {
30141
30368
  waiter?.reject(new TransportError("the request was cancelled"));
30142
30369
  this.port.postMessage({ net: "cancel", nid });
30143
30370
  }
30144
- async fetch(request, owner, stamp) {
30371
+ async fetch(request2, owner, stamp) {
30145
30372
  const nid = ++this.nextId;
30146
- const { signal, redirect } = request;
30373
+ const { signal, redirect } = request2;
30147
30374
  signal.throwIfAborted();
30148
30375
  if (unfollowed2(redirect) && !honors(this.traits, redirect)) {
30149
30376
  throw refused4(`this transport cannot honor redirect: ${redirect}`);
@@ -30161,16 +30388,16 @@ var RemoteTransport = class {
30161
30388
  finished = true;
30162
30389
  signal.removeEventListener("abort", abort);
30163
30390
  };
30164
- if (request.bodyStream) this.uploads.set(nid, request.bodyStream[Symbol.asyncIterator]());
30391
+ if (request2.bodyStream) this.uploads.set(nid, request2.bodyStream[Symbol.asyncIterator]());
30165
30392
  let head;
30166
30393
  try {
30167
30394
  head = await this.ask({
30168
30395
  net: "fetch",
30169
30396
  nid,
30170
- url: request.url,
30171
- method: request.method,
30172
- headers: request.headers,
30173
- ...request.bodyStream ? { streamed: true } : request.body ? { body: request.body } : {},
30397
+ url: request2.url,
30398
+ method: request2.method,
30399
+ headers: request2.headers,
30400
+ ...request2.bodyStream ? { streamed: true } : request2.body ? { body: request2.body } : {},
30174
30401
  ...redirect !== void 0 ? { redirect } : {},
30175
30402
  ...owner !== void 0 ? { owner } : {},
30176
30403
  ...stamp ? { stamp } : {}
@@ -30182,11 +30409,11 @@ var RemoteTransport = class {
30182
30409
  const { status, statusText, headers, url, redirected: redirected2, redirects, opaqueRedirect } = head;
30183
30410
  const read = async () => {
30184
30411
  if (finished) return void 0;
30185
- const reply = await this.ask({ net: "read", nid }).catch((e) => {
30412
+ const reply2 = await this.ask({ net: "read", nid }).catch((e) => {
30186
30413
  finish();
30187
30414
  throw e;
30188
30415
  });
30189
- if (reply.net === "chunk") return reply.bytes;
30416
+ if (reply2.net === "chunk") return reply2.bytes;
30190
30417
  finish();
30191
30418
  return void 0;
30192
30419
  };
@@ -30222,9 +30449,9 @@ var RemoteTransport = class {
30222
30449
  }
30223
30450
  };
30224
30451
  }
30225
- async websocket(request) {
30452
+ async websocket(request2) {
30226
30453
  const nid = ++this.nextId;
30227
- const { signal } = request;
30454
+ const { signal } = request2;
30228
30455
  signal.throwIfAborted();
30229
30456
  const abort = () => this.cancel(nid);
30230
30457
  signal.addEventListener("abort", abort, { once: true });
@@ -30233,9 +30460,9 @@ var RemoteTransport = class {
30233
30460
  opened2 = await this.ask({
30234
30461
  net: "ws-open",
30235
30462
  nid,
30236
- url: request.url,
30237
- protocols: request.protocols,
30238
- headers: request.headers
30463
+ url: request2.url,
30464
+ protocols: request2.protocols,
30465
+ headers: request2.headers
30239
30466
  });
30240
30467
  } finally {
30241
30468
  signal.removeEventListener("abort", abort);
@@ -30275,8 +30502,8 @@ function header3(headers, name2) {
30275
30502
  return values.length > 0 ? values.join(", ") : void 0;
30276
30503
  }
30277
30504
  function fingerprint(headers) {
30278
- const fields = MATCHED.map((name2) => header3(headers, name2) ?? "");
30279
- return JSON.stringify([...fields, header3(headers, "authorization") !== void 0]);
30505
+ const fields2 = MATCHED.map((name2) => header3(headers, name2) ?? "");
30506
+ return JSON.stringify([...fields2, header3(headers, "authorization") !== void 0]);
30280
30507
  }
30281
30508
  function unauthorized(print) {
30282
30509
  return JSON.stringify([...JSON.parse(print).slice(0, -1), false]);
@@ -30339,24 +30566,24 @@ function replayingHops(inner, heldMs = HELD_MS) {
30339
30566
  return { ...inner.traits, manualRedirects: true };
30340
30567
  },
30341
30568
  ...inner.websocket ? { websocket: inner.websocket.bind(inner) } : {},
30342
- async fetch(request, ...rest2) {
30343
- if (unfollowed2(request.redirect)) return inner.fetch(request, ...rest2);
30569
+ async fetch(request2, ...rest2) {
30570
+ if (unfollowed2(request2.redirect)) return inner.fetch(request2, ...rest2);
30344
30571
  const [caller] = rest2;
30345
30572
  const owner = caller ?? KERNEL;
30346
- const key = keyOf4(owner, request.method, request.url);
30573
+ const key = keyOf4(owner, request2.method, request2.url);
30347
30574
  const waiting2 = held2.get(key);
30348
- if (waiting2 && waiting2.fingerprint === fingerprint(request.headers)) {
30575
+ if (waiting2 && waiting2.fingerprint === fingerprint(request2.headers)) {
30349
30576
  held2.delete(key);
30350
30577
  clearTimeout(waiting2.timer);
30351
30578
  return replay(waiting2);
30352
30579
  }
30353
30580
  if (waiting2) drop(key);
30354
- const response = await inner.fetch(request, ...rest2);
30581
+ const response = await inner.fetch(request2, ...rest2);
30355
30582
  if (!response.redirects?.length) return response;
30356
30583
  return replay({
30357
30584
  owner,
30358
- method: request.method,
30359
- fingerprint: fingerprint(request.headers),
30585
+ method: request2.method,
30586
+ fingerprint: fingerprint(request2.headers),
30360
30587
  hops: response.redirects,
30361
30588
  final: response
30362
30589
  });
@@ -30389,26 +30616,26 @@ var UNSAFE_FIELD = /[\r\n\0]/;
30389
30616
  function sealedHooks(option) {
30390
30617
  if (!option) return {};
30391
30618
  if (typeof option === "function") return { request: option };
30392
- const { request, fetch: fetch2 } = option;
30393
- if (typeof request !== "function" || fetch2 !== void 0 && typeof fetch2 !== "function") {
30619
+ const { request: request2, fetch: fetch2 } = option;
30620
+ if (typeof request2 !== "function" || fetch2 !== void 0 && typeof fetch2 !== "function") {
30394
30621
  throw new TypeError("sealed takes a function or { request, fetch? }");
30395
30622
  }
30396
- return { request, ...fetch2 ? { fetch: fetch2 } : {} };
30623
+ return { request: request2, ...fetch2 ? { fetch: fetch2 } : {} };
30397
30624
  }
30398
30625
  function headerList(headers) {
30399
30626
  return Array.isArray(headers) && headers.every(
30400
30627
  (field4) => Array.isArray(field4) && field4.length === 2 && field4.every((text) => typeof text === "string" && !UNSAFE_FIELD.test(text))
30401
30628
  );
30402
30629
  }
30403
- function sealedReplyValid(reply) {
30404
- if (typeof reply !== "object" || reply === null) return false;
30405
- const { redirects, redirected: redirected2, status, statusText, headers, url, body, cancel } = reply;
30630
+ function sealedReplyValid(reply2) {
30631
+ if (typeof reply2 !== "object" || reply2 === null) return false;
30632
+ const { redirects, redirected: redirected2, status, statusText, headers, url, body, cancel } = reply2;
30406
30633
  return redirects === void 0 && redirected2 !== true && Number.isInteger(status) && status >= 100 && status <= 599 && typeof statusText === "string" && !UNSAFE_FIELD.test(statusText) && headerList(headers) && (url === void 0 || typeof url === "string") && typeof body?.[Symbol.asyncIterator] === "function" && typeof cancel === "function";
30407
30634
  }
30408
- function dropSealedReply(reply) {
30409
- const { cancel } = reply ?? {};
30635
+ function dropSealedReply(reply2) {
30636
+ const { cancel } = reply2 ?? {};
30410
30637
  if (typeof cancel !== "function") return;
30411
- void Promise.resolve().then(() => cancel.call(reply)).catch(() => void 0);
30638
+ void Promise.resolve().then(() => cancel.call(reply2)).catch(() => void 0);
30412
30639
  }
30413
30640
  function failed3(reason) {
30414
30641
  const text = reason instanceof Error ? reason.message : String(reason);
@@ -30455,8 +30682,8 @@ async function* ticking(stream2, stall) {
30455
30682
  yield chunk2;
30456
30683
  }
30457
30684
  }
30458
- function sealedRequest(request, stamp, stall) {
30459
- const { method, url, headers, body, bodyStream: bodyStream2 } = request;
30685
+ function sealedRequest(request2, stamp, stall) {
30686
+ const { method, url, headers, body, bodyStream: bodyStream2 } = request2;
30460
30687
  return {
30461
30688
  v: 1,
30462
30689
  caller: structuredClone(stamp),
@@ -30467,18 +30694,18 @@ function sealedRequest(request, stamp, stall) {
30467
30694
  ...bodyStream2 ? { bodyStream: ticking(bodyStream2, stall) } : body ? { body } : {}
30468
30695
  };
30469
30696
  }
30470
- function guarded2(reply, stall) {
30697
+ function guarded2(reply2, stall) {
30471
30698
  let finished = false;
30472
30699
  const cancel = async () => {
30473
30700
  stall.signal.removeEventListener("abort", dropped2);
30474
30701
  stall.rest();
30475
30702
  if (finished) return;
30476
30703
  finished = true;
30477
- await reply.cancel().catch(() => void 0);
30704
+ await reply2.cancel().catch(() => void 0);
30478
30705
  };
30479
30706
  const dropped2 = () => void cancel();
30480
30707
  stall.signal.addEventListener("abort", dropped2, { once: true });
30481
- const source = reply.body[Symbol.asyncIterator]();
30708
+ const source = reply2.body[Symbol.asyncIterator]();
30482
30709
  const body = (async function* () {
30483
30710
  try {
30484
30711
  for (; ; ) {
@@ -30497,35 +30724,35 @@ function guarded2(reply, stall) {
30497
30724
  }
30498
30725
  })();
30499
30726
  return {
30500
- ...reply.url !== void 0 ? { url: reply.url } : {},
30501
- status: reply.status,
30502
- statusText: reply.statusText,
30503
- headers: reply.headers,
30727
+ ...reply2.url !== void 0 ? { url: reply2.url } : {},
30728
+ status: reply2.status,
30729
+ statusText: reply2.statusText,
30730
+ headers: reply2.headers,
30504
30731
  body,
30505
30732
  cancel
30506
30733
  };
30507
30734
  }
30508
30735
  function sealedFetcher(hook, stop, idleMs = BODY_IDLE_MS) {
30509
- return async (request, stamp) => {
30510
- const stall = new Stall([request.signal, stop], idleMs);
30736
+ return async (request2, stamp) => {
30737
+ const stall = new Stall([request2.signal, stop], idleMs);
30511
30738
  const { signal } = stall;
30512
30739
  if (signal.aborted) throw failed3(signal.reason);
30513
30740
  stall.arm();
30514
30741
  const asked = Promise.resolve().then(() => {
30515
30742
  signal.throwIfAborted();
30516
- return hook(sealedRequest(request, stamp, stall), { signal });
30743
+ return hook(sealedRequest(request2, stamp, stall), { signal });
30517
30744
  });
30518
- let reply;
30745
+ let reply2;
30519
30746
  try {
30520
- reply = await until(asked, signal);
30747
+ reply2 = await until(asked, signal);
30521
30748
  } catch (e) {
30522
30749
  void asked.then(dropSealedReply, () => void 0);
30523
30750
  throw failed3(e);
30524
30751
  } finally {
30525
30752
  stall.rest();
30526
30753
  }
30527
- if (sealedReplyValid(reply)) return guarded2(reply, stall);
30528
- dropSealedReply(reply);
30754
+ if (sealedReplyValid(reply2)) return guarded2(reply2, stall);
30755
+ dropSealedReply(reply2);
30529
30756
  throw failed3("the reply is not a scrubbed response");
30530
30757
  };
30531
30758
  }
@@ -30690,7 +30917,7 @@ var PackageLocks = class {
30690
30917
  metadata;
30691
30918
  constructor(metadata, locks = replacingLocks()) {
30692
30919
  this.metadata = metadata;
30693
- this.locks = locks;
30920
+ this.locks = locks ?? void 0;
30694
30921
  }
30695
30922
  loading(roots, run2) {
30696
30923
  if (!this.locks || roots.length === 0) return run2(false);
@@ -30899,7 +31126,7 @@ function setAttrOf(req) {
30899
31126
  for (const key of SET_ATTRS) if (req[key] !== void 0) attr2[key] = req[key];
30900
31127
  return attr2;
30901
31128
  }
30902
- async function dispatch(h, req) {
31129
+ async function dispatch2(h, req) {
30903
31130
  switch (req.op) {
30904
31131
  case "getattr":
30905
31132
  return h.getattr(req.path);
@@ -30955,22 +31182,22 @@ async function dispatch(h, req) {
30955
31182
  }
30956
31183
  function serveFilesystem(port, handlers, capabilities = {}, options = {}) {
30957
31184
  let open = false;
30958
- const reply = (message3, transfer = []) => port.postMessage(message3, transfer);
31185
+ const reply2 = (message3, transfer = []) => port.postMessage(message3, transfer);
30959
31186
  async function hello(message3) {
30960
31187
  const refused5 = driverVersionError(message3.protocol);
30961
31188
  if (refused5) {
30962
- reply({ hello: { protocol: DRIVER_PROTOCOL, error: refused5, errno: "EPROTO" } });
31189
+ reply2({ hello: { protocol: DRIVER_PROTOCOL, error: refused5, errno: "EPROTO" } });
30963
31190
  return;
30964
31191
  }
30965
31192
  try {
30966
31193
  const refined = await handlers.mount?.(message3.mount);
30967
31194
  open = true;
30968
- reply({
31195
+ reply2({
30969
31196
  hello: { protocol: DRIVER_PROTOCOL, capabilities: { ...capabilities, ...refined } }
30970
31197
  });
30971
31198
  } catch (err) {
30972
31199
  const code = err?.code;
30973
- reply({
31200
+ reply2({
30974
31201
  hello: {
30975
31202
  protocol: DRIVER_PROTOCOL,
30976
31203
  error: err instanceof Error ? err.message : String(err),
@@ -30986,17 +31213,17 @@ function serveFilesystem(port, handlers, capabilities = {}, options = {}) {
30986
31213
  return;
30987
31214
  }
30988
31215
  if (!open) return;
30989
- dispatch(handlers, data).then(
31216
+ dispatch2(handlers, data).then(
30990
31217
  (result) => {
30991
31218
  if (result instanceof Uint8Array) {
30992
31219
  const whole = result.byteOffset === 0 && result.byteLength === result.buffer.byteLength;
30993
31220
  const bytes = options.owned && whole ? result : fresh(result);
30994
- reply({ id: data.id, result: bytes }, [bytes.buffer]);
30995
- } else reply({ id: data.id, result: result ?? null });
31221
+ reply2({ id: data.id, result: bytes }, [bytes.buffer]);
31222
+ } else reply2({ id: data.id, result: result ?? null });
30996
31223
  },
30997
31224
  (err) => {
30998
31225
  const code = err?.code;
30999
- reply({
31226
+ reply2({
31000
31227
  id: data.id,
31001
31228
  errno: typeof code === "string" ? code : "EIO",
31002
31229
  message: err instanceof Error ? err.message : String(err)
@@ -31005,7 +31232,7 @@ function serveFilesystem(port, handlers, capabilities = {}, options = {}) {
31005
31232
  );
31006
31233
  });
31007
31234
  port.start?.();
31008
- return { invalidate: (paths) => reply({ invalidate: paths }) };
31235
+ return { invalidate: (paths) => reply2({ invalidate: paths }) };
31009
31236
  }
31010
31237
 
31011
31238
  // src/fs/notice.ts
@@ -31510,21 +31737,21 @@ var OpfsFs = class {
31510
31737
  const want2 = { uid: owner.uid, gid: setgid ? parentGid : owner.gid };
31511
31738
  let mode = owner.mode === void 0 ? void 0 : owner.mode & PERM_MASK;
31512
31739
  if (directory2 && setgid) mode = (mode ?? 493) | S_ISGID4;
31513
- const fields = {};
31740
+ const fields2 = {};
31514
31741
  if (mode !== void 0 && mode !== (this.mode(path, directory2, void 0) & PERM_MASK)) {
31515
- fields.mode = mode;
31742
+ fields2.mode = mode;
31516
31743
  }
31517
- if (self) fields.heir = void 0;
31518
- if (ownOf(self) || !sameOwner(want2, inherit(entries))) Object.assign(fields, want2);
31519
- return Object.keys(fields).length > 0 ? fields : void 0;
31744
+ if (self) fields2.heir = void 0;
31745
+ if (ownOf(self) || !sameOwner(want2, inherit(entries))) Object.assign(fields2, want2);
31746
+ return Object.keys(fields2).length > 0 ? fields2 : void 0;
31520
31747
  }
31521
31748
  async stampNew(path, owner, directory2) {
31522
31749
  const owned4 = await this.newFields(path, owner, directory2);
31523
31750
  if (owner?.socket && owner.fifo) throw new Error("a new node is a socket or a FIFO, not both");
31524
31751
  const kind = directory2 ? void 0 : owner?.socket ? "socket" : owner?.fifo ? "fifo" : void 0;
31525
31752
  const unique = kind === "fifo" ? { ino: inodeOf(`${path}\0${crypto.randomUUID()}`) } : {};
31526
- const fields = kind ? { ...owned4, ...unique, [kind]: true } : owned4;
31527
- if (fields) await this.meta.update(path, (entry) => ({ ...occupied(entry), path, ...fields }));
31753
+ const fields2 = kind ? { ...owned4, ...unique, [kind]: true } : owned4;
31754
+ if (fields2) await this.meta.update(path, (entry) => ({ ...occupied(entry), path, ...fields2 }));
31528
31755
  }
31529
31756
  guarded = [];
31530
31757
  protect(prefixes2, versions = false) {
@@ -31676,9 +31903,9 @@ var OpfsFs = class {
31676
31903
  metaTransactions() {
31677
31904
  return this.meta.transactions?.();
31678
31905
  }
31679
- io(request) {
31906
+ io(request2) {
31680
31907
  this.others++;
31681
- return request;
31908
+ return request2;
31682
31909
  }
31683
31910
  fresh() {
31684
31911
  this.changes++;
@@ -32985,8 +33212,8 @@ var OpfsFs = class {
32985
33212
  renamingDirs = /* @__PURE__ */ new Set();
32986
33213
  intents = 0;
32987
33214
  async intend(rename, at = `${RENAMES2}/${crypto.randomUUID()}`) {
32988
- const record3 = { ...rename, at: Date.now() * 1e3 + this.intents++ % 1e3 };
32989
- await this.meta.update(at, () => ({ path: at, rename: record3 }));
33215
+ const record4 = { ...rename, at: Date.now() * 1e3 + this.intents++ % 1e3 };
33216
+ await this.meta.update(at, () => ({ path: at, rename: record4 }));
32990
33217
  return at;
32991
33218
  }
32992
33219
  async rollBack(from, to, intents) {
@@ -33262,7 +33489,7 @@ var OpfsFs = class {
33262
33489
  throw fsError("EEXIST", path);
33263
33490
  }
33264
33491
  const now = Date.now();
33265
- const fields = await this.newFields(at, owner && { uid: owner.uid, gid: owner.gid }, false);
33492
+ const fields2 = await this.newFields(at, owner && { uid: owner.uid, gid: owner.gid }, false);
33266
33493
  await this.entering(
33267
33494
  at,
33268
33495
  () => this.meta.update(at, (entry) => ({
@@ -33272,7 +33499,7 @@ var OpfsFs = class {
33272
33499
  ino: entry?.vacated && entry.ino !== void 0 ? entry.ino : inodeOf(at),
33273
33500
  mtimeMs: now,
33274
33501
  ctimeMs: now,
33275
- ...fields
33502
+ ...fields2
33276
33503
  }))
33277
33504
  );
33278
33505
  this.touch(Date.now(), parent.path);
@@ -34337,11 +34564,11 @@ var PortTransport = class {
34337
34564
  this.requestMs + Math.ceil(bytes / 1048576) * PORT_MS_PER_MIB
34338
34565
  );
34339
34566
  this.watchBeat();
34340
- this.waiting.set(id2, (reply) => {
34567
+ this.waiting.set(id2, (reply2) => {
34341
34568
  clearTimeout(timer);
34342
34569
  this.waiting.delete(id2);
34343
- if (reply.error) reject(fsError2(reply.error.code ?? "EIO", reply.error.message ?? ""));
34344
- else resolve2(reply);
34570
+ if (reply2.error) reject(fsError2(reply2.error.code ?? "EIO", reply2.error.message ?? ""));
34571
+ else resolve2(reply2);
34345
34572
  });
34346
34573
  try {
34347
34574
  this.port.postMessage({ id: id2, ...message3 }, transfer);
@@ -34354,11 +34581,11 @@ var PortTransport = class {
34354
34581
  return (await this.ask({ op: "call", name: op, body })).result;
34355
34582
  }
34356
34583
  async read(fh, offset, size, ifMatch) {
34357
- const reply = await this.ask(
34584
+ const reply2 = await this.ask(
34358
34585
  { op: "read", fh, offset, size, ...ifMatch ? { ifMatch } : {} },
34359
34586
  size
34360
34587
  );
34361
- return reply.bytes ?? new Uint8Array(0);
34588
+ return reply2.bytes ?? new Uint8Array(0);
34362
34589
  }
34363
34590
  async write(fh, offset, bytes) {
34364
34591
  await this.ask({ op: "write", fh, offset, bytes }, bytes.length);
@@ -34384,11 +34611,11 @@ var PortTransport = class {
34384
34611
  resolve2();
34385
34612
  };
34386
34613
  this.watchBeat();
34387
- this.waiting.set(id2, (reply) => {
34388
- if (reply.open) return onOpen();
34389
- if (reply.event) return onEvent(reply.event);
34614
+ this.waiting.set(id2, (reply2) => {
34615
+ if (reply2.open) return onOpen();
34616
+ if (reply2.event) return onEvent(reply2.event);
34390
34617
  finish();
34391
- if (reply.error) reject(fsError2(reply.error.code ?? "ENOTCONN", reply.error.message ?? ""));
34618
+ if (reply2.error) reject(fsError2(reply2.error.code ?? "ENOTCONN", reply2.error.message ?? ""));
34392
34619
  else resolve2();
34393
34620
  });
34394
34621
  signal.addEventListener("abort", stop, { once: true });
@@ -35529,6 +35756,9 @@ function addTimes(into, pid, t) {
35529
35756
  const at = into.get(pid) ?? { utime: 0, stime: 0 };
35530
35757
  into.set(pid, { utime: at.utime + t.utime, stime: at.stime + t.stime });
35531
35758
  }
35759
+ function locksForPackages(options) {
35760
+ return new PackageLocks(options.packageLocks ?? META_DB, options.leaseImage ? null : void 0);
35761
+ }
35532
35762
  var Launcher = class {
35533
35763
  emscripten;
35534
35764
  admit;
@@ -35544,6 +35774,8 @@ var Launcher = class {
35544
35774
  unlinkOwnerOption;
35545
35775
  durable;
35546
35776
  base;
35777
+ leaseImage;
35778
+ disposing = false;
35547
35779
  createWorker;
35548
35780
  compile;
35549
35781
  moduleUrl;
@@ -35676,7 +35908,8 @@ var Launcher = class {
35676
35908
  this.memories = memoriesOf(options.wasmMemories);
35677
35909
  this.rootFs = options.fs;
35678
35910
  this.locks = kernelLocks(options.fs.rootName, this.flushingPeers(options.fs));
35679
- this.packageLocks = new PackageLocks(options.packageLocks ?? META_DB);
35911
+ this.leaseImage = options.leaseImage;
35912
+ this.packageLocks = locksForPackages(options);
35680
35913
  this.dac = this.usersMode === "off" ? void 0 : new Dac(this.usersMode, options.onDenial);
35681
35914
  if (this.dac) this.wireDac(this.dac);
35682
35915
  this.clipboard = new ClipboardBroker(
@@ -35730,7 +35963,7 @@ var Launcher = class {
35730
35963
  this.pnpmChain = new Set(chain(normalizePath(this.pnpmHome)));
35731
35964
  this.modulesDir = options.modules ?? "/node_modules";
35732
35965
  this.appended = appendedRoots(options.commands);
35733
- this.cdp = new CdpHosts(options.cdp);
35966
+ this.cdp = new CdpHosts(options.cdp, options.leaseTag, (pid) => this.sessionOf(pid).client);
35734
35967
  this.facades = new FacadeHosts(options.facades);
35735
35968
  const hostname = options.hostname ?? DEFAULT_HOSTNAME;
35736
35969
  if (!isHostname(hostname)) throw new Error(`not a host name: ${String(hostname)}`);
@@ -35740,7 +35973,7 @@ var Launcher = class {
35740
35973
  ...networkEnv(hostname),
35741
35974
  HOSTNAME: hostname,
35742
35975
  TZ: this.timeZone,
35743
- SLICC_CDP_URL: this.cdp.url,
35976
+ ...this.cdp.env(),
35744
35977
  ...this.facades.env(),
35745
35978
  ...options.env
35746
35979
  };
@@ -35784,7 +36017,7 @@ var Launcher = class {
35784
36017
  { [Symbol.iterator]: () => holders2.flatMap((set3) => [...set3]).values() },
35785
36018
  (path) => this.mountRoot(path),
35786
36019
  {
35787
- locks: webLocks(),
36020
+ locks: this.leaseImage ? void 0 : webLocks(),
35788
36021
  busy: (path) => [...this.openFiles].some((nodes) => nodes.holds(path)),
35789
36022
  owner: options.unlinkOwner,
35790
36023
  marks: this.pathMarks,
@@ -35834,6 +36067,9 @@ var Launcher = class {
35834
36067
  now: sudoClock ? () => sudoClock.now() : void 0
35835
36068
  });
35836
36069
  this.cron = this.cronService(options.cron);
36070
+ this.watchCatalogs();
36071
+ }
36072
+ watchCatalogs() {
35837
36073
  void this.unlinked.sweep("/");
35838
36074
  this.watchers.watch(
35839
36075
  [this.modulesDir, this.pnpmHome, ...this.appended],
@@ -36279,9 +36515,13 @@ var Launcher = class {
36279
36515
  };
36280
36516
  }
36281
36517
  async plan(file, argv, cwd, scope, argv0, catalogOnly = false) {
36518
+ if (this.leaseImage && file !== "playwright-cli" && file !== "/usr/bin/playwright-cli" && file !== CLI_FILE)
36519
+ throw fsError("EACCES", "only the installed lease CLI can execute");
36282
36520
  const found = await this.resolve(file, argv[0] ?? file, cwd, scope);
36283
36521
  const named = typeof argv0 === "string" && found && !found.fixed;
36284
36522
  const direct = named ? { ...found, argv0 } : found;
36523
+ if (this.leaseImage && (!direct || direct.wasm !== CLI_FILE || direct.shim || direct.copy))
36524
+ throw fsError("EACCES", "lease CLI path mismatch");
36285
36525
  if (direct) {
36286
36526
  const shim = direct.shim ? { sources: [direct.shim], asked: direct.asked ? { [direct.shim]: direct.asked } : {} } : {};
36287
36527
  return { target: direct, args: [...direct.prefix ?? [], ...argv.slice(1)], ...shim };
@@ -36576,8 +36816,9 @@ var Launcher = class {
36576
36816
  const pin = await this.pinOf(path, caller);
36577
36817
  const sum = Object.values(pin)[0];
36578
36818
  const key = sum === void 0 ? await this.cacheKey(path, asked) : `${path}:sha256:${sum}`;
36819
+ const checked = this.leaseImage ? await this.leaseImage.bytes(path) : void 0;
36579
36820
  const loaded = this.cached(this.compiled, key, async () => {
36580
- const { bytes: read, key: readKey } = await this.keyed(path, caller, asked);
36821
+ const { bytes: read, key: readKey } = checked ? { bytes: checked, key } : await this.keyed(path, caller, asked);
36581
36822
  const bytes = sum === void 0 ? read : await this.pinnedBytes(pin, read);
36582
36823
  const memory = importedMemory(bytes);
36583
36824
  const foreign = foreignImports(bytes);
@@ -36797,7 +37038,16 @@ var Launcher = class {
36797
37038
  const base = { abi: "emscripten", emscripten: "kernel", glue: "", module };
36798
37039
  return { ...base, ...memory ? { memory } : {}, path: target.glue };
36799
37040
  }
37041
+ checkLeaseProgram(target) {
37042
+ if (this.cdp.leaseOnly && (target.abi !== "wasi" || target.imports !== void 0)) {
37043
+ throw fsError(
37044
+ "EACCES",
37045
+ "a lease-only kernel runs only WASI modules without JavaScript imports"
37046
+ );
37047
+ }
37048
+ }
36800
37049
  async program(target, env, caller) {
37050
+ this.checkLeaseProgram(target);
36801
37051
  if (target.abi === "js" && target.wasm === SUDO_PATH) {
36802
37052
  return { abi: "js", glue: SUDO_SOURCE, path: SUDO_PATH };
36803
37053
  }
@@ -37056,11 +37306,16 @@ var Launcher = class {
37056
37306
  });
37057
37307
  }
37058
37308
  }
37309
+ mayStart(req) {
37310
+ if (this.leaseImage && req.cred.euid === 0)
37311
+ throw fsError("EACCES", "lease CLI may not run as root");
37312
+ if (this.disposing) throw fsError("EACCES", "lease job ended");
37313
+ if (req.pgid !== void 0 && this.jobs.sessionOf(req.pgid) === void 0)
37314
+ throw new SpawnError("ESRCH");
37315
+ }
37059
37316
  start(req) {
37317
+ this.mayStart(req);
37060
37318
  this.sampling();
37061
- if (req.pgid !== void 0 && this.jobs.sessionOf(req.pgid) === void 0) {
37062
- throw new SpawnError("ESRCH");
37063
- }
37064
37319
  const pid = req.pid ?? this.nextPid++;
37065
37320
  const cwdSlot = this.cwds.share(req.cwdSlot);
37066
37321
  this.cwdSlots.set(pid, cwdSlot);
@@ -37892,8 +38147,12 @@ var Launcher = class {
37892
38147
  attest(path, options = {}) {
37893
38148
  return attest(this.rootFs, path, {
37894
38149
  ...options,
38150
+ ...this.leaseImage && path === CLI_FILE ? { maxBytes: CLI_MAX } : {},
37895
38151
  users: this.usersMode,
37896
38152
  mounts: this.mounts.list().map((entry) => entry.target).filter((target) => this.mounts.mounted(target) !== void 0)
38153
+ }).then((record4) => {
38154
+ this.leaseImage?.attest(record4);
38155
+ return record4;
37897
38156
  });
37898
38157
  }
37899
38158
  watchSource(pid) {
@@ -37923,6 +38182,8 @@ var Launcher = class {
37923
38182
  return this.fileWatches.watch(paths, notify);
37924
38183
  }
37925
38184
  async mount(spec) {
38185
+ if (this.cdp.leaseOnly)
38186
+ throw fsError("EACCES", "a lease-only kernel cannot mount host services");
37926
38187
  this.guardMount(spec.target);
37927
38188
  const fsa = spec.type === "fsa" && !spec.source.startsWith("fsa:");
37928
38189
  const entry = await this.mounts.mount(
@@ -37935,7 +38196,8 @@ var Launcher = class {
37935
38196
  }
37936
38197
  async mountShm() {
37937
38198
  await this.base.mkdir(SHM, { recursive: true });
37938
- await this.mounts.mountSystem({ type: "tmpfs", source: "shm", target: SHM }, this.fs);
38199
+ if (!this.leaseImage)
38200
+ await this.mounts.mountSystem({ type: "tmpfs", source: "shm", target: SHM }, this.fs);
37939
38201
  await this.fs.chmod(SHM, 1023);
37940
38202
  }
37941
38203
  async ownTmp() {
@@ -38046,6 +38308,12 @@ var Launcher = class {
38046
38308
  for (const nodes of this.openFiles) nodes.revoke(at);
38047
38309
  for (const holds3 of this.held) holds3.revoke(at);
38048
38310
  }
38311
+ endLeaseProcesses() {
38312
+ this.disposing = true;
38313
+ this.leaseImage?.close();
38314
+ this.cdp.close();
38315
+ for (const process of this.processes.values()) process.kill();
38316
+ }
38049
38317
  unmountAll() {
38050
38318
  this.cron.stop();
38051
38319
  this.booting.abort();
@@ -38053,7 +38321,7 @@ var Launcher = class {
38053
38321
  for (const target of targets.sort((a, b) => b.length - a.length)) this.umount(target, true);
38054
38322
  }
38055
38323
  async permit(req) {
38056
- const policy = this.processMounts;
38324
+ const policy = !this.cdp.leaseOnly && this.processMounts;
38057
38325
  const allowed = typeof policy === "function" ? await policy(req) : policy;
38058
38326
  if (!allowed) throw fsError("EPERM", `process ${req.pid} may not ${req.op} ${req.target}`);
38059
38327
  }
@@ -38117,7 +38385,7 @@ var Launcher = class {
38117
38385
  await writeCaFile(this.base, this.ca).catch(() => void 0);
38118
38386
  await this.cron.provision().catch(() => void 0);
38119
38387
  this.fstab = this.mountFstab();
38120
- void this.cron.start();
38388
+ if (!this.leaseImage) void this.cron.start();
38121
38389
  }
38122
38390
  async mountFstab() {
38123
38391
  const text = await this.base.readFile(FSTAB_PATH).catch(() => "");
@@ -38139,10 +38407,11 @@ var Launcher = class {
38139
38407
  }
38140
38408
  );
38141
38409
  }
38142
- environment(cwd, extra, account, login2 = false) {
38410
+ environment(cwd, extra, account, session, login2 = false) {
38143
38411
  const env = {
38144
38412
  ...login2 ? { ...networkEnv(this.hostname), HOSTNAME: this.hostname, TZ: this.timeZone } : this.env,
38145
38413
  ...userEnv(account, this.pnpmHome),
38414
+ ...this.cdp.leaseOnly ? this.cdp.env(session) : {},
38146
38415
  PWD: cwd,
38147
38416
  ...extra
38148
38417
  };
@@ -38500,7 +38769,8 @@ var Launcher = class {
38500
38769
  COLORTERM: "truecolor",
38501
38770
  ...options.env
38502
38771
  },
38503
- account
38772
+ account,
38773
+ options.session
38504
38774
  );
38505
38775
  const report = (message3) => options.onData(encoder10.encode(`${message3}\r
38506
38776
  `));
@@ -38539,7 +38809,7 @@ var Launcher = class {
38539
38809
  tagged.tagBase,
38540
38810
  missing6
38541
38811
  );
38542
- const env = this.environment(cwd, options.env, account, options.login);
38812
+ const env = this.environment(cwd, options.env, account, options.session, options.login);
38543
38813
  const out = [];
38544
38814
  const err = [];
38545
38815
  const keep2 = options.collect !== false;
@@ -38705,12 +38975,12 @@ function unopened(url, code) {
38705
38975
  status: 502
38706
38976
  });
38707
38977
  }
38708
- function openWebSocket(Socket, request, withHeaders) {
38709
- const { url, protocols, signal } = request;
38978
+ function openWebSocket(Socket, request2, withHeaders) {
38979
+ const { url, protocols, signal } = request2;
38710
38980
  signal.throwIfAborted();
38711
38981
  let socket;
38712
38982
  try {
38713
- socket = withHeaders ? new Socket(url, { protocols, headers: headerRecord(request.headers) }) : new Socket(url, protocols);
38983
+ socket = withHeaders ? new Socket(url, { protocols, headers: headerRecord(request2.headers) }) : new Socket(url, protocols);
38714
38984
  } catch (e) {
38715
38985
  return Promise.reject(Object.assign(new Error(blockedReason(url, e)), { status: 502 }));
38716
38986
  }
@@ -38855,11 +39125,11 @@ function streamOf(body) {
38855
39125
  { highWaterMark: 0 }
38856
39126
  );
38857
39127
  }
38858
- function requestBody(request) {
38859
- if (request.bodyStream) {
38860
- return { body: streamOf(request.bodyStream), duplex: "half" };
39128
+ function requestBody(request2) {
39129
+ if (request2.bodyStream) {
39130
+ return { body: streamOf(request2.bodyStream), duplex: "half" };
38861
39131
  }
38862
- return request.body ? { body: request.body } : {};
39132
+ return request2.body ? { body: request2.body } : {};
38863
39133
  }
38864
39134
  function fetchTransport(options = {}) {
38865
39135
  const send3 = options.fetch ?? globalThis.fetch.bind(globalThis);
@@ -38878,28 +39148,28 @@ function fetchTransport(options = {}) {
38878
39148
  ...Socket ? { websocket: true } : {},
38879
39149
  ...options.streamingBodies ? { streamingBodies: true } : {}
38880
39150
  },
38881
- ...Socket ? { websocket: (request) => openWebSocket(Socket, request, headers) } : {},
38882
- async fetch(request) {
38883
- const sent = sentHeaders(request.headers, inPage);
38884
- if (refuse2) refuseUnsendable(request.url, sent, options.hint);
39151
+ ...Socket ? { websocket: (request2) => openWebSocket(Socket, request2, headers) } : {},
39152
+ async fetch(request2) {
39153
+ const sent = sentHeaders(request2.headers, inPage);
39154
+ if (refuse2) refuseUnsendable(request2.url, sent, options.hint);
38885
39155
  let response;
38886
39156
  try {
38887
- response = await send3(request.url, {
38888
- method: request.method,
39157
+ response = await send3(request2.url, {
39158
+ method: request2.method,
38889
39159
  headers: sent,
38890
- ...requestBody(request),
38891
- signal: request.signal,
38892
- redirect: request.redirect ?? instance,
39160
+ ...requestBody(request2),
39161
+ signal: request2.signal,
39162
+ redirect: request2.redirect ?? instance,
38893
39163
  credentials: "omit",
38894
39164
  mode: "cors"
38895
39165
  });
38896
39166
  } catch (e) {
38897
- if (request.signal.aborted) throw e;
39167
+ if (request2.signal.aborted) throw e;
38898
39168
  const causeCode = e?.cause?.code;
38899
39169
  const dns = typeof causeCode === "string" && DNS_CODES.has(causeCode);
38900
39170
  throw Object.assign(
38901
39171
  new Error(
38902
- `fetch ${request.url} failed (unreachable, or not allowed by CORS)${options.hint ? `: ${options.hint}` : ""}`
39172
+ `fetch ${request2.url} failed (unreachable, or not allowed by CORS)${options.hint ? `: ${options.hint}` : ""}`
38903
39173
  ),
38904
39174
  { status: 502 },
38905
39175
  dns ? { code: causeCode } : {},
@@ -39368,7 +39638,7 @@ function cdpRegistry(send3, gone) {
39368
39638
  return {
39369
39639
  serve(l, req) {
39370
39640
  const hook = portCdpHook(
39371
- (request, cdp) => send3({ cdpOpen: { ...request, registration: req.id }, port: cdp }, [
39641
+ (request2, cdp) => send3({ cdpOpen: { ...request2, registration: req.id }, port: cdp }, [
39372
39642
  cdp
39373
39643
  ]),
39374
39644
  gone,
@@ -39392,7 +39662,7 @@ function facadeRegistry(send3, gone) {
39392
39662
  return {
39393
39663
  serve(l, req) {
39394
39664
  const hook = portFacadeHook(
39395
- (request, facade) => send3({ facadeOpen: { ...request, registration: req.id }, port: facade }, [
39665
+ (request2, facade) => send3({ facadeOpen: { ...request2, registration: req.id }, port: facade }, [
39396
39666
  facade
39397
39667
  ]),
39398
39668
  gone,
@@ -39490,8 +39760,8 @@ function requestBinding(send3, port) {
39490
39760
  const asker = embedderAsker({ postMessage: (m, t) => send3(m, t) });
39491
39761
  let unbind;
39492
39762
  port.addEventListener("message", (event) => {
39493
- const reply = embedderReplyOf(event.data);
39494
- if (reply) asker.answer(reply);
39763
+ const reply2 = embedderReplyOf(event.data);
39764
+ if (reply2) asker.answer(reply2);
39495
39765
  });
39496
39766
  return {
39497
39767
  async accept(host, hello) {
@@ -39508,7 +39778,7 @@ function requestBinding(send3, port) {
39508
39778
  close: () => unbind?.()
39509
39779
  };
39510
39780
  }
39511
- async function sudoRunAs(l, self, host, req, reply) {
39781
+ async function sudoRunAs(l, self, host, req, reply2) {
39512
39782
  if (self.uid !== 0) throw sudoFailure("EPERM", "sudo: only a root client may run a sudo request");
39513
39783
  const { stdout, stderr, tag } = req.options;
39514
39784
  const running = await l.sudoRun(req.replay, {
@@ -39518,19 +39788,19 @@ async function sudoRunAs(l, self, host, req, reply) {
39518
39788
  base: host.tag,
39519
39789
  session: host.session
39520
39790
  });
39521
- reply(req.id, { started: running.pid });
39791
+ reply2(req.id, { started: running.pid });
39522
39792
  const { status, signal } = await running.ended;
39523
39793
  return { result: status, ...signalField(signal) };
39524
39794
  }
39525
- function answered(pending, req, reply, detach) {
39795
+ function answered(pending, req, reply2, detach) {
39526
39796
  pending.then(
39527
39797
  ({ result, signal, transfer }) => {
39528
- reply(req.id, { result, ...signal ? { signal } : {} }, transfer);
39798
+ reply2(req.id, { result, ...signal ? { signal } : {} }, transfer);
39529
39799
  if (req.op === "detach") detach(req.kill === true);
39530
39800
  },
39531
39801
  (err) => {
39532
39802
  const code = err?.code;
39533
- reply(req.id, {
39803
+ reply2(req.id, {
39534
39804
  error: err instanceof Error ? err.message : String(err),
39535
39805
  ...typeof code === "string" ? { code } : {}
39536
39806
  });
@@ -39544,8 +39814,8 @@ function deviceBinding(send3, port) {
39544
39814
  const asker = devicesAsker({ postMessage: (m, t) => send3(m, t) });
39545
39815
  let unbind;
39546
39816
  port.addEventListener("message", (event) => {
39547
- const reply = devicesReplyOf(event.data);
39548
- if (reply) asker.answer(reply);
39817
+ const reply2 = devicesReplyOf(event.data);
39818
+ if (reply2) asker.answer(reply2);
39549
39819
  });
39550
39820
  return {
39551
39821
  async accept(host, hello) {
@@ -39572,7 +39842,7 @@ function serveClient(port, host) {
39572
39842
  const send3 = (message3, transfer = []) => {
39573
39843
  if (state !== "closed") port.postMessage(message3, transfer);
39574
39844
  };
39575
- const reply = (id2, body, transfer) => send3({ id: id2, ...body }, transfer);
39845
+ const reply2 = (id2, body, transfer) => send3({ id: id2, ...body }, transfer);
39576
39846
  const hosts = hostRegistries(send3, ended.promise, port);
39577
39847
  const traces = traceRegistry(send3);
39578
39848
  function detach(kill = false, bye = "the slicc-kernel detached this client") {
@@ -39618,14 +39888,14 @@ function serveClient(port, host) {
39618
39888
  const session = await l.openTerminal(req.argv, {
39619
39889
  ...req.options,
39620
39890
  ...await runTagged(l, self, req.options, host.tag, host.session),
39621
- onData: (bytes) => reply(req.id, { fd: 1, bytes: bytes.slice() })
39891
+ onData: (bytes) => reply2(req.id, { fd: 1, bytes: bytes.slice() })
39622
39892
  });
39623
39893
  if (state === "closed") {
39624
39894
  session.close();
39625
39895
  } else {
39626
39896
  terminals.set(req.id, session);
39627
39897
  sessions2.add(session.pid);
39628
- reply(req.id, { started: session.pid });
39898
+ reply2(req.id, { started: session.pid });
39629
39899
  }
39630
39900
  try {
39631
39901
  const status = await session.exited;
@@ -39635,7 +39905,7 @@ function serveClient(port, host) {
39635
39905
  }
39636
39906
  }
39637
39907
  async function spawn(req, l) {
39638
- const out = (fd) => (bytes) => reply(req.id, { fd, bytes: bytes.slice() });
39908
+ const out = (fd) => (bytes) => reply2(req.id, { fd, bytes: bytes.slice() });
39639
39909
  if (req.options.pgid !== void 0) joinable(l, req.options.pgid, (sid) => sessions2.has(sid));
39640
39910
  let leader;
39641
39911
  const result = await l.run(req.argv, {
@@ -39649,7 +39919,7 @@ function serveClient(port, host) {
39649
39919
  if (state === "closed") return;
39650
39920
  groups.add(req.options.pgid ?? pid);
39651
39921
  if (req.options.pgid === void 0) sessions2.add(pid);
39652
- reply(req.id, { started: pid });
39922
+ reply2(req.id, { started: pid });
39653
39923
  }
39654
39924
  });
39655
39925
  if (leader === void 0) throw fsError("ENOENT", `${req.argv[0] ?? ""}: command not found`);
@@ -39694,7 +39964,7 @@ function serveClient(port, host) {
39694
39964
  case "untrace":
39695
39965
  return traces.answer(l, self, req);
39696
39966
  case "sudo-run":
39697
- return sudoRunAs(l, self, host, req, reply);
39967
+ return sudoRunAs(l, self, host, req, reply2);
39698
39968
  case "detach":
39699
39969
  return { result: true };
39700
39970
  default:
@@ -39720,7 +39990,7 @@ function serveClient(port, host) {
39720
39990
  }
39721
39991
  if (traces.ack(data)) return;
39722
39992
  const req = data;
39723
- answered(handle(req), req, reply, detach);
39993
+ answered(handle(req), req, reply2, detach);
39724
39994
  });
39725
39995
  port.addEventListener("close", () => detach());
39726
39996
  port.start?.();
@@ -40246,14 +40516,14 @@ var ForkTokens = class {
40246
40516
  }
40247
40517
  watchAnswer(token, answer2) {
40248
40518
  if (token === void 0) return;
40249
- const reply = answer2;
40250
- if (!reply || reply.failed !== void 0) {
40519
+ const reply2 = answer2;
40520
+ if (!reply2 || reply2.failed !== void 0) {
40251
40521
  this.drop(token);
40252
40522
  return;
40253
40523
  }
40254
- if (typeof reply.status !== "number" || !(reply.bytes instanceof Uint8Array)) return;
40524
+ if (typeof reply2.status !== "number" || !(reply2.bytes instanceof Uint8Array)) return;
40255
40525
  try {
40256
- if (!decodeSabResult(reply.status, reply.bytes).ok) this.drop(token);
40526
+ if (!decodeSabResult(reply2.status, reply2.bytes).ok) this.drop(token);
40257
40527
  } catch {
40258
40528
  this.drop(token);
40259
40529
  }
@@ -41894,6 +42164,9 @@ function isSqliteRoot(handle) {
41894
42164
  return handle instanceof SqliteDirectoryHandle;
41895
42165
  }
41896
42166
 
42167
+ // src/fs/memory-budget.ts
42168
+ var LEASE_FS_BYTES = 64 * 1024 * 1024;
42169
+
41897
42170
  // src/node/memory-root.ts
41898
42171
  var fail3 = (name2) => {
41899
42172
  throw new DOMException(name2, name2);
@@ -41971,6 +42244,15 @@ var MemoryFile = class {
41971
42244
  name;
41972
42245
  parent;
41973
42246
  data = new Chunks();
42247
+ removed = false;
42248
+ staging = /* @__PURE__ */ new Set();
42249
+ remove() {
42250
+ this.removed = true;
42251
+ for (const done4 of this.staging) done4();
42252
+ this.parent.budget?.resize(this.data.size, 0);
42253
+ this.data = new Chunks();
42254
+ this.parent.budget?.entry(-1);
42255
+ }
41974
42256
  lastModified = Date.now();
41975
42257
  constructor(name2, parent) {
41976
42258
  this.name = name2;
@@ -41983,33 +42265,59 @@ var MemoryFile = class {
41983
42265
  async createWritable({ keepExistingData = false } = {}) {
41984
42266
  const next3 = keepExistingData ? new Chunks([...this.data.blobs], this.data.size) : new Chunks();
41985
42267
  let position = 0;
42268
+ const budget = this.parent.budget;
42269
+ let reserved2 = next3.size;
42270
+ budget?.resize(0, reserved2);
42271
+ let ended = false;
42272
+ const abort = () => {
42273
+ if (ended) return;
42274
+ ended = true;
42275
+ budget?.resize(reserved2, 0);
42276
+ this.staging.delete(abort);
42277
+ };
42278
+ if (budget) this.staging.add(abort);
42279
+ const reserve = (size) => {
42280
+ if (budget && (ended || this.removed)) fail3("NotFoundError");
42281
+ budget?.resize(reserved2, size);
42282
+ reserved2 = size;
42283
+ };
42284
+ const truncate = (size) => {
42285
+ reserve(size);
42286
+ next3.truncate(size);
42287
+ };
41986
42288
  const put = async (data) => {
41987
42289
  const bytes = await bytesOf5(data);
42290
+ reserve(Math.max(next3.size, position + bytes.length));
41988
42291
  await next3.write(position, bytes);
41989
42292
  position += bytes.length;
41990
42293
  };
41991
42294
  return {
41992
42295
  write: async (data) => {
41993
42296
  if (!isParams2(data)) return put(data);
41994
- if (data.type === "truncate") return next3.truncate(data.size ?? 0);
42297
+ if (data.type === "truncate") return truncate(data.size ?? 0);
41995
42298
  position = data.position ?? position;
41996
42299
  if (data.type === "write") await put(data.data);
41997
42300
  },
41998
42301
  seek: async (at) => {
41999
42302
  position = at;
42000
42303
  },
42001
- truncate: async (size) => next3.truncate(size),
42304
+ truncate: async (size) => truncate(size),
42002
42305
  close: async () => {
42306
+ if (budget && (ended || this.removed)) fail3("NotFoundError");
42307
+ budget?.resize(this.data.size, 0);
42308
+ ended = true;
42309
+ this.staging.delete(abort);
42003
42310
  this.data = next3;
42004
42311
  this.lastModified = Date.now();
42005
42312
  },
42006
- abort: async () => {
42007
- }
42313
+ abort: async () => abort()
42008
42314
  };
42009
42315
  }
42010
42316
  async move(parent, name2) {
42011
42317
  valid2(name2);
42012
- if (parent.children.get(name2)?.kind === "directory") fail3("InvalidModificationError");
42318
+ const old = parent.children.get(name2);
42319
+ if (old?.kind === "directory") fail3("InvalidModificationError");
42320
+ if (old && old !== this && parent.budget) old.remove();
42013
42321
  this.parent.children.delete(this.name);
42014
42322
  this.name = name2;
42015
42323
  this.parent = parent;
@@ -42022,7 +42330,9 @@ var MemoryDirectory = class _MemoryDirectory {
42022
42330
  parent;
42023
42331
  children = /* @__PURE__ */ new Map();
42024
42332
  removed = false;
42025
- constructor(name2, parent) {
42333
+ budget;
42334
+ constructor(name2, parent, budget = parent?.budget) {
42335
+ this.budget = budget;
42026
42336
  this.name = name2;
42027
42337
  this.parent = parent;
42028
42338
  }
@@ -42036,6 +42346,7 @@ var MemoryDirectory = class _MemoryDirectory {
42036
42346
  if (found?.kind === "file") fail3("TypeMismatchError");
42037
42347
  if (found) return found;
42038
42348
  if (!create) fail3("NotFoundError");
42349
+ this.budget?.entry(1);
42039
42350
  const dir = new _MemoryDirectory(name2, this);
42040
42351
  this.children.set(name2, dir);
42041
42352
  return dir;
@@ -42047,6 +42358,7 @@ var MemoryDirectory = class _MemoryDirectory {
42047
42358
  if (found?.kind === "directory") fail3("TypeMismatchError");
42048
42359
  if (found) return found;
42049
42360
  if (!create) fail3("NotFoundError");
42361
+ this.budget?.entry(1);
42050
42362
  const file = new MemoryFile(name2, this);
42051
42363
  this.children.set(name2, file);
42052
42364
  return file;
@@ -42060,7 +42372,7 @@ var MemoryDirectory = class _MemoryDirectory {
42060
42372
  fail3("InvalidModificationError");
42061
42373
  }
42062
42374
  this.children.delete(name2);
42063
- if (found.kind === "directory") found.remove();
42375
+ if (found.kind === "directory" || this.budget) found.remove();
42064
42376
  }
42065
42377
  async resolve(handle) {
42066
42378
  const names2 = [];
@@ -42072,7 +42384,12 @@ var MemoryDirectory = class _MemoryDirectory {
42072
42384
  }
42073
42385
  remove() {
42074
42386
  this.removed = true;
42075
- for (const child of this.children.values()) if (child.kind === "directory") child.remove();
42387
+ for (const child of this.children.values())
42388
+ if (child.kind === "directory" || this.budget) child.remove();
42389
+ if (this.budget) {
42390
+ this.children.clear();
42391
+ if (this.parent) this.budget.entry(-1);
42392
+ }
42076
42393
  }
42077
42394
  async *keys() {
42078
42395
  this.present();
@@ -42299,11 +42616,11 @@ function stream(chunks2, socket, signal) {
42299
42616
  }
42300
42617
  });
42301
42618
  }
42302
- async function requestBytes(request) {
42303
- const url = new URL(request.url);
42304
- const body = request.body ? new Uint8Array(await request.arrayBuffer()) : void 0;
42305
- const lines3 = [`${request.method} ${url.pathname}${url.search} HTTP/1.1`, `Host: ${url.host}`];
42306
- request.headers.forEach((value2, name2) => {
42619
+ async function requestBytes(request2) {
42620
+ const url = new URL(request2.url);
42621
+ const body = request2.body ? new Uint8Array(await request2.arrayBuffer()) : void 0;
42622
+ const lines3 = [`${request2.method} ${url.pathname}${url.search} HTTP/1.1`, `Host: ${url.host}`];
42623
+ request2.headers.forEach((value2, name2) => {
42307
42624
  if (!OWN_HEADERS2.has(name2)) lines3.push(`${name2}: ${value2}`);
42308
42625
  });
42309
42626
  if (body) lines3.push(`Content-Length: ${body.length}`);
@@ -42316,8 +42633,8 @@ async function requestBytes(request) {
42316
42633
  }
42317
42634
  async function loopbackFetch(dial, input, options) {
42318
42635
  options.signal?.throwIfAborted();
42319
- const request = input instanceof Request ? input : new Request(input);
42320
- const bytes = await requestBytes(request);
42636
+ const request2 = input instanceof Request ? input : new Request(input);
42637
+ const bytes = await requestBytes(request2);
42321
42638
  const socket = await dial({
42322
42639
  port: options.port,
42323
42640
  ...options.host ? { host: options.host } : {}
@@ -42334,7 +42651,7 @@ async function loopbackFetch(dial, input, options) {
42334
42651
  if (!raw2) throw errorWithCode("ECONNRESET: the connection closed before a response");
42335
42652
  head = parseHead2(raw2);
42336
42653
  } while (head.status >= 100 && head.status < 200);
42337
- const chunks2 = bodyOf2(source, head, request.method);
42654
+ const chunks2 = bodyOf2(source, head, request2.method);
42338
42655
  if (!chunks2) socket.close();
42339
42656
  return new Response(chunks2 ? stream(chunks2, socket, options.signal) : null, {
42340
42657
  status: head.status,
@@ -42486,21 +42803,21 @@ var Channel = class {
42486
42803
  this.remote?.receive(data);
42487
42804
  return;
42488
42805
  }
42489
- const reply = data;
42490
- const call = this.pending.get(reply.id);
42806
+ const reply2 = data;
42807
+ const call = this.pending.get(reply2.id);
42491
42808
  if (!call) return;
42492
- if (reply.fd !== void 0) {
42493
- call.output?.(reply.fd, reply.bytes);
42809
+ if (reply2.fd !== void 0) {
42810
+ call.output?.(reply2.fd, reply2.bytes);
42494
42811
  return;
42495
42812
  }
42496
- if (reply.started !== void 0) {
42497
- call.started?.(reply.started);
42813
+ if (reply2.started !== void 0) {
42814
+ call.started?.(reply2.started);
42498
42815
  return;
42499
42816
  }
42500
- this.pending.delete(reply.id);
42501
- call.ended?.(reply.signal);
42502
- if (reply.error !== void 0) call.reject(new KernelCallError(reply.error, reply.code));
42503
- else call.resolve(reply.result);
42817
+ this.pending.delete(reply2.id);
42818
+ call.ended?.(reply2.signal);
42819
+ if (reply2.error !== void 0) call.reject(new KernelCallError(reply2.error, reply2.code));
42820
+ else call.resolve(reply2.result);
42504
42821
  }
42505
42822
  traced(trace, events, dropped2) {
42506
42823
  const listener = this.tracing.get(trace);
@@ -42519,24 +42836,24 @@ var Channel = class {
42519
42836
  }
42520
42837
  }
42521
42838
  }
42522
- openCdp({ cdpOpen: { registration, ...request }, port }) {
42839
+ openCdp({ cdpOpen: { registration, ...request2 }, port }) {
42523
42840
  const hook = registration === void 0 ? void 0 : this.cdpHooks.get(registration);
42524
42841
  if (!hook || this.failure) {
42525
42842
  port.postMessage({ error: "this client no longer serves CDP" });
42526
42843
  port.close();
42527
42844
  return;
42528
42845
  }
42529
- const close = serveCdpPort(port, hook, request, () => this.cdpOpen.delete(close));
42846
+ const close = serveCdpPort(port, hook, request2, () => this.cdpOpen.delete(close));
42530
42847
  this.cdpOpen.add(close);
42531
42848
  }
42532
- openFacade({ facadeOpen: { registration, ...request }, port }) {
42849
+ openFacade({ facadeOpen: { registration, ...request2 }, port }) {
42533
42850
  const hook = registration === void 0 ? void 0 : this.facadeHooks.get(registration);
42534
42851
  if (!hook || this.failure) {
42535
42852
  port.postMessage({ error: "this client no longer serves the facade" });
42536
42853
  port.close();
42537
42854
  return;
42538
42855
  }
42539
- const close = serveFacadePort(port, hook, request, () => this.facadeOpen.delete(close));
42856
+ const close = serveFacadePort(port, hook, request2, () => this.facadeOpen.delete(close));
42540
42857
  this.facadeOpen.add(close);
42541
42858
  }
42542
42859
  };
@@ -42713,7 +43030,7 @@ async function terminalOn(channel, argv, opts) {
42713
43030
  );
42714
43031
  done4.catch(started.reject);
42715
43032
  const pid = await started.promise;
42716
- const send3 = (action) => void channel.call({ op: "terminal", terminal: id2, ...action }).catch(() => void 0);
43033
+ const send3 = (action2) => void channel.call({ op: "terminal", terminal: id2, ...action2 }).catch(() => void 0);
42717
43034
  return {
42718
43035
  pid,
42719
43036
  exited: done4,
@@ -43856,7 +44173,7 @@ function textOf(on) {
43856
44173
  }
43857
44174
  function checkedRequests(hook) {
43858
44175
  const kinds = kindsOf(hook);
43859
- return { kinds, handle: (request) => hook.handle(request) };
44176
+ return { kinds, handle: (request2) => hook.handle(request2) };
43860
44177
  }
43861
44178
  function embedderHooks({ requests, approve, cdp }) {
43862
44179
  return {
@@ -43890,6 +44207,12 @@ function rootFs(options) {
43890
44207
  const ranged2 = options.ranged ?? (sql !== void 0 || isMemoryRoot(root));
43891
44208
  return { root, fs: new OpfsFs(root, meta, void 0, { ranged: ranged2 }) };
43892
44209
  }
44210
+ function isolateGate(options) {
44211
+ return new IsolateGate(
44212
+ options.isolates?.max ?? MAX_ISOLATES,
44213
+ options.isolates?.waitMs ?? options.wasmMemories?.idleMs ?? ISOLATE_WAIT_MS
44214
+ );
44215
+ }
43893
44216
  function isolateMemory(options) {
43894
44217
  const { memory, perInstance } = options.isolates ?? {};
43895
44218
  return {
@@ -43925,12 +44248,13 @@ function settled(port, flush) {
43925
44248
  });
43926
44249
  return port;
43927
44250
  }
43928
- function client(launcher, clients, { user, tag, requests }, flush) {
44251
+ function client(launcher, clients, { user, tag, requests, devices }, flush) {
43929
44252
  tagOption(tag);
44253
+ const session = ++sessions;
44254
+ const endLease = launcher.cdp.bindClient(session, tag, requests || devices);
43930
44255
  const ports = launcher.ports();
43931
44256
  const port1 = settled(ports.port1, flush);
43932
44257
  const { port2 } = ports;
43933
- const session = ++sessions;
43934
44258
  const served2 = serveClient(port1, {
43935
44259
  launcher: async () => launcher,
43936
44260
  signal: signalNumber,
@@ -43942,6 +44266,7 @@ function client(launcher, clients, { user, tag, requests }, flush) {
43942
44266
  clients.add(served2);
43943
44267
  const unbind = requests && requests !== "attach" ? launcher.embedder.register(session, checkedRequests(requests)) : void 0;
43944
44268
  void served2.closed.then(() => {
44269
+ endLease?.();
43945
44270
  clients.delete(served2);
43946
44271
  unbind?.();
43947
44272
  });
@@ -43949,6 +44274,7 @@ function client(launcher, clients, { user, tag, requests }, flush) {
43949
44274
  }
43950
44275
  async function createCloudflareKernel(options) {
43951
44276
  if (!options?.loader) throw new TypeError("createCloudflareKernel: loader is required");
44277
+ const lease = checkedLease(options, "cloudflare");
43952
44278
  const hooks = sealedHooks(options.sealed);
43953
44279
  const { root, fs } = rootFs(options);
43954
44280
  const flush = () => {
@@ -43956,10 +44282,7 @@ async function createCloudflareKernel(options) {
43956
44282
  };
43957
44283
  await fs.reconcile();
43958
44284
  const images = new Images();
43959
- const gate = new IsolateGate(
43960
- options.isolates?.max ?? MAX_ISOLATES,
43961
- options.isolates?.waitMs ?? options.wasmMemories?.idleMs ?? ISOLATE_WAIT_MS
43962
- );
44285
+ const gate = isolateGate(options);
43963
44286
  const processes2 = cloudflareProcesses(
43964
44287
  options.loader,
43965
44288
  images,
@@ -43996,7 +44319,7 @@ async function createCloudflareKernel(options) {
43996
44319
  ...options.protect ? { protect: options.protect } : {},
43997
44320
  ...hooks.request ? { sealed: hooks.request } : {},
43998
44321
  ...hooks.fetch ? { sealedFetch: hooks.fetch } : {},
43999
- ...embedderHooks(options),
44322
+ ...lease ? { leaseTag: lease.tag, cdp: leaseHook(lease) } : embedderHooks(options),
44000
44323
  ...options.wasmMemories ? { wasmMemories: options.wasmMemories } : {},
44001
44324
  cron: { poll: false, ...options.cron }
44002
44325
  });
@@ -44110,6 +44433,7 @@ async function createCloudflareKernel(options) {
44110
44433
  }
44111
44434
  export {
44112
44435
  ASYNC_PROCESS_SOURCE,
44436
+ CDP_LEASE_VERSION,
44113
44437
  ISOLATE_WAIT_MS,
44114
44438
  Images,
44115
44439
  IsolateGate,