@kehto/paja 0.21.4 → 0.24.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.
@@ -7734,7 +7734,7 @@ function createRelayPoolService(options) {
7734
7734
  subId,
7735
7735
  result: createRelayEventResultWithHints(item, observedRelayUrls ?? relayUrls2)
7736
7736
  });
7737
- }, relayUrls2);
7737
+ }, relayUrls2, relayHint !== void 0);
7738
7738
  tracked.set(subKey, { handle, eoseTimer });
7739
7739
  return;
7740
7740
  }
@@ -10066,9 +10066,10 @@ function discoveredReadRelays(ctx, authors, lists) {
10066
10066
  }
10067
10067
  return { relays: [...relays], missingAuthors };
10068
10068
  }
10069
- function immediateReadRelays(ctx, relayHints) {
10069
+ function immediateReadPlan(ctx, relayHints) {
10070
10070
  const hints = allowed(ctx, relayHints ?? []);
10071
- return hints.length > 0 ? hints : allowed(ctx, ctx.fallbackRelays);
10071
+ if (hints.length > 0) return { relays: hints, origin: "hint" };
10072
+ return { relays: allowed(ctx, ctx.fallbackRelays), origin: "fallback" };
10072
10073
  }
10073
10074
  function recordRelay(collector, id, relayUrl2) {
10074
10075
  let set = collector.relayMap.get(id);
@@ -10111,8 +10112,8 @@ function buildQueryResult(collector, options, incomplete, subscribedAny) {
10111
10112
  if (!subscribedAny) result2.error = "relay list unavailable";
10112
10113
  return result2;
10113
10114
  }
10114
- function relayPoolSubscribe(ctx, filters, relayUrl2, cb) {
10115
- return ctx.relayPool.subscribe(filters, [relayUrl2], cb);
10115
+ function relayPoolSubscribe(ctx, filters, relayUrl2, cb, origin) {
10116
+ return ctx.relayPool.subscribe(filters, [relayUrl2], cb, origin);
10116
10117
  }
10117
10118
  function startQueryImpl(ctx, filters, options, sink) {
10118
10119
  if (!ctx.relayPool.isAvailable()) {
@@ -10162,7 +10163,7 @@ function startQueryImpl(ctx, filters, options, sink) {
10162
10163
  if (finished || discoveryPending || collector.pendingVerifications > 0) return;
10163
10164
  if (activeRelays.size === 0 || eoseRelays.size >= activeRelays.size) finalize();
10164
10165
  }
10165
- function attachRelay(relayUrl2) {
10166
+ function attachRelay(relayUrl2, origin) {
10166
10167
  if (finished || activeRelays.has(relayUrl2)) return;
10167
10168
  activeRelays.add(relayUrl2);
10168
10169
  try {
@@ -10175,7 +10176,7 @@ function startQueryImpl(ctx, filters, options, sink) {
10175
10176
  }
10176
10177
  recordRelay(collector, item.id, relayUrl2);
10177
10178
  admitEvent(ctx, collector, item, sink, () => !finished, maybeFinalize);
10178
- });
10179
+ }, origin);
10179
10180
  subscribedAny = true;
10180
10181
  if (finished) {
10181
10182
  try {
@@ -10190,13 +10191,21 @@ function startQueryImpl(ctx, filters, options, sink) {
10190
10191
  incomplete = true;
10191
10192
  }
10192
10193
  }
10193
- function attachMany(relayUrls2) {
10194
- for (const relayUrl2 of relayUrls2) attachRelay(relayUrl2);
10194
+ function attachMany(relayUrls2, origin) {
10195
+ for (const relayUrl2 of relayUrls2) attachRelay(relayUrl2, origin);
10196
+ }
10197
+ function attachHintedAndDiscovered(hintRelays, discoveredRelays) {
10198
+ attachMany(hintRelays, "hint");
10199
+ attachMany(discoveredRelays, "nip65");
10200
+ if (hintRelays.length === 0 && discoveredRelays.length === 0) {
10201
+ attachMany(allowed(ctx, ctx.fallbackRelays), "fallback");
10202
+ }
10195
10203
  }
10196
10204
  timer = setTimeout(() => finalize(true), options?.timeoutMs ?? ctx.defaultTimeoutMs);
10197
10205
  if (authors.length === 0) {
10198
10206
  discoveryPending = false;
10199
- attachMany(allowed(ctx, [...ctx.fallbackRelays, ...options?.relays ?? []]));
10207
+ attachMany(allowed(ctx, options?.relays ?? []), "hint");
10208
+ attachMany(allowed(ctx, ctx.fallbackRelays), "fallback");
10200
10209
  maybeFinalize();
10201
10210
  } else {
10202
10211
  let loaded;
@@ -10205,7 +10214,8 @@ function startQueryImpl(ctx, filters, options, sink) {
10205
10214
  } catch {
10206
10215
  discoveryPending = false;
10207
10216
  incomplete = true;
10208
- attachMany(immediateReadRelays(ctx, options?.relays));
10217
+ const immediate = immediateReadPlan(ctx, options?.relays);
10218
+ attachMany(immediate.relays, immediate.origin);
10209
10219
  maybeFinalize();
10210
10220
  return { result: result2, close: () => finalize(true) };
10211
10221
  }
@@ -10213,17 +10223,17 @@ function startQueryImpl(ctx, filters, options, sink) {
10213
10223
  const discovery = discoveredReadRelays(ctx, authors, loaded);
10214
10224
  discoveryPending = false;
10215
10225
  incomplete ||= discovery.missingAuthors.length > 0;
10216
- const initial = allowed(ctx, [...options?.relays ?? [], ...discovery.relays]);
10217
- attachMany(initial.length > 0 ? initial : allowed(ctx, ctx.fallbackRelays));
10226
+ attachHintedAndDiscovered(allowed(ctx, options?.relays ?? []), discovery.relays);
10218
10227
  maybeFinalize();
10219
10228
  } else {
10220
- attachMany(immediateReadRelays(ctx, options?.relays));
10229
+ const immediate = immediateReadPlan(ctx, options?.relays);
10230
+ attachMany(immediate.relays, immediate.origin);
10221
10231
  void Promise.resolve(loaded).then((lists) => {
10222
10232
  if (finished) return;
10223
10233
  const discovery = discoveredReadRelays(ctx, authors, lists);
10224
10234
  discoveryPending = false;
10225
10235
  incomplete ||= discovery.missingAuthors.length > 0;
10226
- attachMany(discovery.relays);
10236
+ attachMany(discovery.relays, "nip65");
10227
10237
  maybeFinalize();
10228
10238
  }).catch(() => {
10229
10239
  if (finished) return;
@@ -10269,7 +10279,7 @@ function closeLiveSub(sub) {
10269
10279
  }
10270
10280
  sub.handles.clear();
10271
10281
  }
10272
- function attachLiveRelay(ctx, sub, filters, relayUrl2, sink) {
10282
+ function attachLiveRelay(ctx, sub, filters, relayUrl2, sink, origin) {
10273
10283
  if (sub.closed || sub.relays.has(relayUrl2)) return false;
10274
10284
  sub.relays.add(relayUrl2);
10275
10285
  try {
@@ -10281,7 +10291,7 @@ function attachLiveRelay(ctx, sub, filters, relayUrl2, sink) {
10281
10291
  sub.seen.add(item.id);
10282
10292
  sink.event(createRelayEventResultWithHints(item, [relayUrl2]));
10283
10293
  });
10284
- });
10294
+ }, origin);
10285
10295
  if (sub.closed) {
10286
10296
  try {
10287
10297
  handle.unsubscribe();
@@ -10307,8 +10317,15 @@ function startSubscription(ctx, filters, options, sink) {
10307
10317
  };
10308
10318
  let discoveryOpen = authors.length > 0;
10309
10319
  let discoveryTimer;
10310
- function attachMany(relayUrls2) {
10311
- for (const relayUrl2 of relayUrls2) attachLiveRelay(ctx, sub, filters, relayUrl2, sink);
10320
+ function attachMany(relayUrls2, origin) {
10321
+ for (const relayUrl2 of relayUrls2) attachLiveRelay(ctx, sub, filters, relayUrl2, sink, origin);
10322
+ }
10323
+ function attachHintedAndDiscovered(hintRelays, discoveredRelays) {
10324
+ attachMany(hintRelays, "hint");
10325
+ attachMany(discoveredRelays, "nip65");
10326
+ if (hintRelays.length === 0 && discoveredRelays.length === 0) {
10327
+ attachMany(allowed(ctx, ctx.fallbackRelays), "fallback");
10328
+ }
10312
10329
  }
10313
10330
  function closeUnavailable() {
10314
10331
  if (sub.closed || sub.handles.size > 0) return;
@@ -10319,7 +10336,8 @@ function startSubscription(ctx, filters, options, sink) {
10319
10336
  closeUnavailable();
10320
10337
  } else if (authors.length === 0) {
10321
10338
  discoveryOpen = false;
10322
- attachMany(immediateReadRelays(ctx, options?.relays));
10339
+ const immediate = immediateReadPlan(ctx, options?.relays);
10340
+ attachMany(immediate.relays, immediate.origin);
10323
10341
  closeUnavailable();
10324
10342
  } else {
10325
10343
  let loaded;
@@ -10327,18 +10345,19 @@ function startSubscription(ctx, filters, options, sink) {
10327
10345
  loaded = ctx.loadRelayLists(authors);
10328
10346
  } catch {
10329
10347
  discoveryOpen = false;
10330
- attachMany(immediateReadRelays(ctx, options?.relays));
10348
+ const immediate = immediateReadPlan(ctx, options?.relays);
10349
+ attachMany(immediate.relays, immediate.origin);
10331
10350
  closeUnavailable();
10332
10351
  loaded = /* @__PURE__ */ new Map();
10333
10352
  }
10334
10353
  if (discoveryOpen && loaded instanceof Map) {
10335
10354
  const discovery = discoveredReadRelays(ctx, authors, loaded);
10336
10355
  discoveryOpen = false;
10337
- const initial = allowed(ctx, [...options?.relays ?? [], ...discovery.relays]);
10338
- attachMany(initial.length > 0 ? initial : allowed(ctx, ctx.fallbackRelays));
10356
+ attachHintedAndDiscovered(allowed(ctx, options?.relays ?? []), discovery.relays);
10339
10357
  closeUnavailable();
10340
10358
  } else if (discoveryOpen) {
10341
- attachMany(immediateReadRelays(ctx, options?.relays));
10359
+ const immediate = immediateReadPlan(ctx, options?.relays);
10360
+ attachMany(immediate.relays, immediate.origin);
10342
10361
  discoveryTimer = setTimeout(() => {
10343
10362
  discoveryOpen = false;
10344
10363
  closeUnavailable();
@@ -10347,7 +10366,7 @@ function startSubscription(ctx, filters, options, sink) {
10347
10366
  if (!discoveryOpen || sub.closed) return;
10348
10367
  discoveryOpen = false;
10349
10368
  clearTimeout(discoveryTimer);
10350
- attachMany(discoveredReadRelays(ctx, authors, lists).relays);
10369
+ attachMany(discoveredReadRelays(ctx, authors, lists).relays, "nip65");
10351
10370
  closeUnavailable();
10352
10371
  }).catch(() => {
10353
10372
  if (!discoveryOpen || sub.closed) return;
@@ -13322,10 +13341,7 @@ function createCryptoAdapter(shellHooks) {
13322
13341
  function createAclPersistence() {
13323
13342
  return {
13324
13343
  persist(data) {
13325
- try {
13326
- localStorage.setItem("napplet:acl", data);
13327
- } catch {
13328
- }
13344
+ localStorage.setItem("napplet:acl", data);
13329
13345
  },
13330
13346
  load() {
13331
13347
  try {
@@ -16301,7 +16317,8 @@ var SECTION_IDS = {
16301
16317
  acl: "paja-section-acl",
16302
16318
  signer: "paja-section-signer",
16303
16319
  "resource-servers": "paja-section-resource-servers",
16304
- messages: "paja-section-messages"
16320
+ messages: "paja-section-messages",
16321
+ events: "paja-section-events"
16305
16322
  };
16306
16323
  function installPajaSidebarSections() {
16307
16324
  const collapsed = {};
@@ -16338,6 +16355,93 @@ function installPajaSidebarSections() {
16338
16355
  return () => disposers.forEach((dispose) => dispose());
16339
16356
  }
16340
16357
 
16358
+ // src/browser-gamepad-indicators.ts
16359
+ var ICON = '<svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="1.7" aria-hidden="true"><path d="M7 6h10c3 0 5 10 3 12-2 2-5-3-6-3h-4c-1 0-4 5-6 3C2 16 4 6 7 6Z"/><path d="M7 9v6m-3-3h6"/><circle cx="16" cy="10" r="1" fill="currentColor"/><circle cx="19" cy="13" r="1" fill="currentColor"/></svg>';
16360
+ function installPajaGamepadIndicators() {
16361
+ const container = document.getElementById("paja-gamepads");
16362
+ if (!container || typeof navigator.getGamepads !== "function") return () => {
16363
+ };
16364
+ const icons = /* @__PURE__ */ new Map();
16365
+ const activeUntil = /* @__PURE__ */ new Map();
16366
+ let frame;
16367
+ let disposed = false;
16368
+ const makeIcon = (pad3) => {
16369
+ const icon = document.createElement("span");
16370
+ icon.className = "gamepad-indicator";
16371
+ icon.dataset.gamepadIndex = String(pad3.index);
16372
+ icon.setAttribute("role", "img");
16373
+ icon.style.setProperty("--pad-color", `hsl(${(pad3.index * 137.508 + 155) % 360} 75% 70%)`);
16374
+ icon.style.setProperty("--pad-turn", `${(pad3.index % 2 ? -1 : 1) * (6 + pad3.index * 2)}deg`);
16375
+ icon.style.setProperty("--pad-lift", `${-2 - pad3.index % 4}px`);
16376
+ icon.style.setProperty("--pad-duration", `${480 + pad3.index * 85}ms`);
16377
+ icon.style.setProperty("--pad-animation", ["gamepad-bounce", "gamepad-rock", "gamepad-pulse", "gamepad-nudge"][pad3.index % 4]);
16378
+ icon.innerHTML = ICON;
16379
+ const number = document.createElement("small");
16380
+ number.textContent = String(pad3.index + 1);
16381
+ icon.append(number);
16382
+ container.append(icon);
16383
+ icons.set(pad3.index, icon);
16384
+ return icon;
16385
+ };
16386
+ const sample = () => {
16387
+ let pads;
16388
+ try {
16389
+ pads = Array.from(navigator.getGamepads());
16390
+ } catch {
16391
+ pads = [];
16392
+ }
16393
+ const connected = /* @__PURE__ */ new Set();
16394
+ const focused = document.visibilityState !== "hidden" && document.hasFocus();
16395
+ const now2 = performance.now();
16396
+ for (const pad3 of pads) {
16397
+ if (!pad3?.connected) continue;
16398
+ connected.add(pad3.index);
16399
+ const icon = icons.get(pad3.index) ?? makeIcon(pad3);
16400
+ const input = focused && (pad3.axes.some((axis) => Math.abs(axis) > 0.12) || pad3.buttons.some((button2) => button2.pressed || button2.value > 0.05));
16401
+ if (input) activeUntil.set(pad3.index, now2 + 420);
16402
+ if (!focused) activeUntil.delete(pad3.index);
16403
+ const active = now2 < (activeUntil.get(pad3.index) ?? 0);
16404
+ const activity = active ? "active" : "idle";
16405
+ if (icon.dataset.activity !== activity || icon.dataset.model !== pad3.id) {
16406
+ icon.dataset.activity = activity;
16407
+ icon.dataset.model = pad3.id;
16408
+ const label = `Controller ${pad3.index + 1}: ${pad3.id} \u2014 ${activity}`;
16409
+ icon.setAttribute("aria-label", label);
16410
+ icon.title = label;
16411
+ }
16412
+ }
16413
+ for (const [index, icon] of icons) {
16414
+ if (connected.has(index)) continue;
16415
+ icon.remove();
16416
+ icons.delete(index);
16417
+ activeUntil.delete(index);
16418
+ }
16419
+ };
16420
+ const tick = () => {
16421
+ frame = void 0;
16422
+ if (disposed) return;
16423
+ sample();
16424
+ if (document.visibilityState !== "hidden") frame = requestAnimationFrame(tick);
16425
+ };
16426
+ const refresh = () => {
16427
+ if (frame !== void 0) cancelAnimationFrame(frame);
16428
+ tick();
16429
+ };
16430
+ const events = ["gamepadconnected", "gamepaddisconnected", "focus", "blur"];
16431
+ for (const event of events) window.addEventListener(event, refresh);
16432
+ document.addEventListener("visibilitychange", refresh);
16433
+ tick();
16434
+ return () => {
16435
+ disposed = true;
16436
+ if (frame !== void 0) cancelAnimationFrame(frame);
16437
+ for (const event of events) window.removeEventListener(event, refresh);
16438
+ document.removeEventListener("visibilitychange", refresh);
16439
+ container.replaceChildren();
16440
+ icons.clear();
16441
+ activeUntil.clear();
16442
+ };
16443
+ }
16444
+
16341
16445
  // ../../node_modules/.pnpm/nostr-tools@2.23.3_typescript@5.9.3/node_modules/nostr-tools/lib/esm/pool.js
16342
16446
  var verifiedSymbol3 = /* @__PURE__ */ Symbol("verified");
16343
16447
  var isRecord4 = (obj) => obj instanceof Object;
@@ -18314,208 +18418,39 @@ function createBrowserBleController(activation, api = browserBluetoothApi()) {
18314
18418
  };
18315
18419
  }
18316
18420
 
18317
- // src/browser-intent-controller.ts
18318
- var MAX_INTENT_DELIVERY_ATTEMPTS = 10;
18319
- var BrowserIntentController = class {
18320
- constructor(options) {
18321
- this.options = options;
18322
- this.maxAttempts = normalizeAttempts(options.maxAttempts);
18323
- }
18324
- options;
18325
- maxAttempts;
18326
- /** Retain delivery work immediately; completion remains host-observable only. */
18327
- accept(params) {
18328
- const acceptance = Object.freeze({ completion: this.dispatch(params) });
18329
- this.options.onAccepted?.(params, acceptance);
18330
- return acceptance;
18331
- }
18332
- /** Complete an already accepted delivery. Kept public for host diagnostics and tests. */
18333
- async dispatch(params) {
18334
- const dispatch2 = freezeDispatch(params);
18335
- let reason = "no-current-target";
18336
- for (let attempt = 1; attempt <= this.maxAttempts; attempt += 1) {
18337
- let generation;
18338
- try {
18339
- generation = await this.options.openOrReuse(dispatch2, attempt);
18340
- } catch {
18341
- reason = "open-failed";
18342
- continue;
18343
- }
18344
- if (!generation) {
18345
- reason = "open-failed";
18346
- continue;
18347
- }
18348
- try {
18349
- await this.options.waitForReady(generation);
18350
- } catch {
18351
- reason = "ready-failed";
18352
- continue;
18353
- }
18354
- if (!await this.options.isCurrent(generation)) {
18355
- reason = "no-current-target";
18356
- continue;
18357
- }
18358
- try {
18359
- await this.options.send(generation, dispatch2);
18360
- this.options.onDelivered?.(dispatch2);
18361
- return;
18362
- } catch {
18363
- this.options.onTerminal?.(dispatch2, "send-failed");
18364
- throw new Error("intent target send failed");
18365
- }
18366
- }
18367
- this.options.onTerminal?.(dispatch2, reason);
18368
- throw new Error(`intent target ${reason}`);
18369
- }
18370
- };
18371
- function normalizeAttempts(value) {
18372
- if (value === void 0) return 2;
18373
- if (!Number.isFinite(value)) throw new TypeError("maxAttempts must be finite");
18374
- return Math.min(MAX_INTENT_DELIVERY_ATTEMPTS, Math.max(1, Math.floor(value)));
18375
- }
18376
- function freezeDispatch(params) {
18377
- if (!params || typeof params.handler !== "string" || params.handler.length === 0) {
18378
- throw new TypeError("Intent dispatch requires a handler");
18379
- }
18380
- if (typeof params.sender !== "string" || params.sender.length === 0 || typeof params.archetype !== "string" || params.archetype.length === 0 || typeof params.action !== "string" || params.action.length === 0 || typeof params.convention !== "string" || params.convention.length === 0) {
18381
- throw new TypeError("Intent dispatch requires canonical routing fields");
18382
- }
18383
- const payload = freezeValue(params.payload);
18384
- const behavior = params.behavior === void 0 ? void 0 : freezeValue({ ...params.behavior });
18385
- return Object.freeze({
18386
- handler: params.handler,
18387
- sender: params.sender,
18388
- archetype: params.archetype,
18389
- action: params.action,
18390
- convention: params.convention,
18391
- ...params.payload === void 0 ? {} : { payload },
18392
- ...behavior === void 0 ? {} : { behavior },
18393
- ...params.sourceWindowId === void 0 ? {} : { sourceWindowId: params.sourceWindowId }
18394
- });
18395
- }
18396
- function freezeValue(value, seen = /* @__PURE__ */ new WeakMap()) {
18397
- if (typeof value !== "object" || value === null) return value;
18398
- const existing = seen.get(value);
18399
- if (existing !== void 0) return existing;
18400
- if (Array.isArray(value)) {
18401
- const copy2 = [];
18402
- seen.set(value, copy2);
18403
- for (const item of value) copy2.push(freezeValue(item, seen));
18404
- return Object.freeze(copy2);
18405
- }
18406
- const copy = {};
18407
- seen.set(value, copy);
18408
- for (const [key, item] of Object.entries(value)) copy[key] = freezeValue(item, seen);
18409
- return Object.freeze(copy);
18410
- }
18411
-
18412
- // src/installed-napplet-catalog.ts
18413
- function matchesInstalledNappletRecord(record2, target) {
18414
- return target.id === record2.id && target.aggregateHash === record2.aggregateHash;
18415
- }
18416
- var InstalledNappletCatalog = class {
18417
- records = /* @__PURE__ */ new Map();
18418
- listeners = /* @__PURE__ */ new Set();
18419
- /** Insert or replace a record from an already resolver-verified pointer. */
18420
- install(resolved) {
18421
- const record2 = freezeRecord({
18422
- id: resolved.manifest.catalogId,
18423
- dTag: resolved.dTag,
18424
- aggregateHash: resolved.aggregateHash,
18425
- pointer: copyPointer(resolved.pointer),
18426
- ...resolved.manifest.title === void 0 ? {} : { title: resolved.manifest.title },
18427
- requires: [...resolved.manifest.requires],
18428
- optional: [...resolved.manifest.optional ?? []],
18429
- archetypes: resolved.manifest.archetypes.map((archetype) => ({
18430
- slug: archetype.slug,
18431
- convention: archetype.convention,
18432
- params: [...archetype.params]
18433
- }))
18434
- });
18435
- this.records.set(record2.id, record2);
18436
- this.notify(record2.id);
18437
- return record2;
18438
- }
18439
- /** Remove an artifact explicitly; frame teardown never calls this method. */
18440
- remove(id) {
18441
- const removed = this.records.delete(id);
18442
- if (removed) this.notify(id);
18443
- return removed;
18444
- }
18445
- /** Return whether a verified installation exists for a catalog ID. */
18446
- has(id) {
18447
- return this.records.has(id);
18448
- }
18449
- /** Return immutable serializable installed-artifact facts. */
18450
- installed() {
18451
- return [...this.records.values()];
18452
- }
18453
- /** Return a verified record by catalog ID. */
18454
- get(id) {
18455
- return this.records.get(id);
18456
- }
18457
- /**
18458
- * Atomically confirm that a resolved target still belongs to the exact record
18459
- * selected before an async operation. The record object is the catalog version
18460
- * token, so even a same-identity replacement cannot pass this check.
18461
- */
18462
- validateCurrent(selected, target) {
18463
- if (this.records.get(selected.id) !== selected) return null;
18464
- return matchesInstalledNappletRecord(selected, target) ? selected : null;
18465
- }
18466
- /**
18467
- * Return declared handlers whose host environment can receive intent delivery.
18468
- * @param canReceiveIntent - Resolve intent availability for each verified identity;
18469
- * without host policy, return declared candidates for the host to filter.
18470
- * @returns Named intent candidates usable under the supplied host policy.
18471
- */
18472
- intentCatalog(canReceiveIntent = () => true) {
18473
- return this.installed().filter(canReceiveIntent).map((record2) => manifestToIntentCatalogEntry({
18474
- catalogId: record2.id,
18475
- ...record2.title === void 0 ? {} : { title: record2.title },
18476
- archetypes: record2.archetypes.map((archetype) => ({
18477
- slug: archetype.slug,
18478
- convention: archetype.convention,
18479
- params: [...archetype.params]
18480
- }))
18481
- }));
18482
- }
18483
- /** Subscribe to explicit install and artifact-removal changes. */
18484
- onChanged(listener) {
18485
- this.listeners.add(listener);
18486
- return () => this.listeners.delete(listener);
18487
- }
18488
- notify(id) {
18489
- for (const listener of this.listeners) listener(id);
18490
- }
18491
- };
18492
- function copyPointer(pointer) {
18493
- if (pointer.type === "naddr") {
18494
- return Object.freeze({
18495
- type: "naddr",
18496
- value: pointer.value,
18497
- identifier: pointer.identifier,
18498
- pubkey: pointer.pubkey,
18499
- kind: pointer.kind,
18500
- relays: Object.freeze([...pointer.relays])
18501
- });
18502
- }
18503
- return Object.freeze({
18504
- type: "nevent",
18505
- value: pointer.value,
18506
- id: pointer.id,
18507
- ...pointer.author === void 0 ? {} : { author: pointer.author },
18508
- ...pointer.kind === void 0 ? {} : { kind: pointer.kind },
18509
- relays: Object.freeze([...pointer.relays])
18421
+ // src/browser-catalog-intent-service.ts
18422
+ function createPajaCatalogIntentService(adapter, host) {
18423
+ const resolver = createCatalogIntentResolver({
18424
+ loadCatalog: () => host.catalog.intentCatalog(
18425
+ (record2) => resolveShellEnvironment(adapter, record2).capabilities.domains.includes("intent")
18426
+ ),
18427
+ targets: host.controller,
18428
+ getDefaultHandler: host.getDefaultHandler,
18429
+ chooseHandler: host.chooseHandler,
18430
+ authorizeExplicitHandler: host.authorizeExplicitHandler,
18431
+ resolveHandlerHint: host.resolveHandlerHint
18510
18432
  });
18511
- }
18512
- function freezeRecord(record2) {
18513
- return Object.freeze({
18514
- ...record2,
18515
- requires: Object.freeze([...record2.requires]),
18516
- optional: Object.freeze([...record2.optional ?? []]),
18517
- archetypes: Object.freeze(record2.archetypes.map((archetype) => Object.freeze({ ...archetype, params: Object.freeze([...archetype.params]) })))
18433
+ const intentService = createIntentService({
18434
+ resolver,
18435
+ resolveSender: host.resolveSender
18518
18436
  });
18437
+ let stopCatalogChanges;
18438
+ const service = {
18439
+ ...intentService,
18440
+ onRegistered(context) {
18441
+ stopCatalogChanges?.();
18442
+ intentService.onRegistered?.(context);
18443
+ stopCatalogChanges = host.catalog.onChanged((_id, archetypes) => {
18444
+ for (const archetype of archetypes) resolver.notifyChanged(archetype);
18445
+ });
18446
+ },
18447
+ onUnregistered() {
18448
+ stopCatalogChanges?.();
18449
+ stopCatalogChanges = void 0;
18450
+ intentService.onUnregistered?.();
18451
+ }
18452
+ };
18453
+ return { service, notifyChanged: (archetype) => resolver.notifyChanged(archetype) };
18519
18454
  }
18520
18455
 
18521
18456
  // src/browser-upload.ts
@@ -19043,38 +18978,191 @@ function dedupe(urls) {
19043
18978
  return out;
19044
18979
  }
19045
18980
 
19046
- // src/browser-relay-runtime.ts
19047
- var PAJA_NIP65_RELAY_LIST_KIND = 10002;
19048
- var PAJA_CONTACT_LIST_KIND = 3;
19049
- var PAJA_WEBRTC_SIGNAL_KIND = 25050;
19050
- var NIP17_GIFT_WRAP_KIND2 = 1059;
19051
- var PAJA_CONTACT_LIST_CANDIDATE_LIMIT = 64;
19052
- var PAJA_LIVE_QUERY_WAIT_MS = 4e3;
19053
- var contactListCandidateQueries = /* @__PURE__ */ new WeakMap();
19054
- function matchesFilter2(event, filter) {
19055
- const ids = filter.ids;
19056
- if (ids && !ids.some((id) => event.id === id || event.id.startsWith(id))) return false;
19057
- const authors = filter.authors;
19058
- if (authors && !authors.some((author) => event.pubkey === author || event.pubkey.startsWith(author))) return false;
19059
- const kinds = filter.kinds;
19060
- if (kinds && !kinds.includes(event.kind)) return false;
19061
- if (typeof filter.since === "number" && event.created_at < filter.since) return false;
19062
- if (typeof filter.until === "number" && event.created_at > filter.until) return false;
19063
- for (const [key, value] of Object.entries(filter)) {
19064
- if (!key.startsWith("#") || !Array.isArray(value)) continue;
19065
- const tagName = key.slice(1);
19066
- const allowed2 = value.filter((item) => typeof item === "string");
19067
- if (allowed2.length === 0) continue;
19068
- if (!event.tags.some((tag) => tag[0] === tagName && typeof tag[1] === "string" && allowed2.includes(tag[1]))) return false;
19069
- }
19070
- return true;
19071
- }
19072
- function matchesAnyFilter2(event, filters) {
19073
- return filters.length === 0 || filters.some((filter) => matchesFilter2(event, filter));
19074
- }
19075
- function normalizedFilters(filters) {
19076
- return Array.isArray(filters) ? filters : [filters];
19077
- }
18981
+ // ../../node_modules/.pnpm/nostr-tools@2.23.3_typescript@5.9.3/node_modules/nostr-tools/lib/esm/utils.js
18982
+ var utf8Decoder6 = new TextDecoder("utf-8");
18983
+ var utf8Encoder6 = new TextEncoder();
18984
+ function normalizeURL2(url) {
18985
+ try {
18986
+ if (url.indexOf("://") === -1)
18987
+ url = "wss://" + url;
18988
+ let p = new URL(url);
18989
+ if (p.protocol === "http:")
18990
+ p.protocol = "ws:";
18991
+ else if (p.protocol === "https:")
18992
+ p.protocol = "wss:";
18993
+ p.pathname = p.pathname.replace(/\/+/g, "/");
18994
+ if (p.pathname.endsWith("/"))
18995
+ p.pathname = p.pathname.slice(0, -1);
18996
+ if (p.port === "80" && p.protocol === "ws:" || p.port === "443" && p.protocol === "wss:")
18997
+ p.port = "";
18998
+ p.searchParams.sort();
18999
+ p.hash = "";
19000
+ return p.toString();
19001
+ } catch (e) {
19002
+ throw new Error(`Invalid URL: ${url}`);
19003
+ }
19004
+ }
19005
+
19006
+ // src/browser-relay-transport.ts
19007
+ function relaySources(urls) {
19008
+ const sources2 = /* @__PURE__ */ new Map();
19009
+ for (const source of urls) {
19010
+ const url = normalizeURL2(source);
19011
+ if (!sources2.has(url)) sources2.set(url, source);
19012
+ }
19013
+ return [...sources2].map(([url, source]) => ({ url, source }));
19014
+ }
19015
+ function subscribePajaLive(pool, relayUrls2, filters, next, observe, maxWait, label = "kehto-paja-runtime") {
19016
+ const sources2 = relaySources(relayUrls2);
19017
+ const activeFilters = filters.length ? filters : [{}];
19018
+ const seen = /* @__PURE__ */ new Set();
19019
+ const ended = /* @__PURE__ */ new Set();
19020
+ const subscriptions = /* @__PURE__ */ new Set();
19021
+ const controller = new AbortController();
19022
+ let closed = false;
19023
+ let eosed = false;
19024
+ const finishRelay = (url) => {
19025
+ if (closed || eosed) return;
19026
+ ended.add(url);
19027
+ if (ended.size === sources2.length) {
19028
+ eosed = true;
19029
+ next("EOSE");
19030
+ }
19031
+ };
19032
+ if (!sources2.length) queueMicrotask(() => {
19033
+ if (!closed) next("EOSE");
19034
+ });
19035
+ for (const { url, source } of sources2) {
19036
+ if (pool.allowConnectingToRelay?.(url, ["read", activeFilters]) === false) {
19037
+ queueMicrotask(() => finishRelay(url));
19038
+ continue;
19039
+ }
19040
+ void pool.ensureRelay(url, {
19041
+ connectionTimeout: Math.min(pool.maxWaitForConnection ?? maxWait, maxWait),
19042
+ abort: controller.signal
19043
+ }).then((relay) => {
19044
+ if (closed) return;
19045
+ pool.onRelayConnectionSuccess?.(url);
19046
+ const subscribe = (retry) => {
19047
+ if (closed) return;
19048
+ const subscription = relay.subscribe(activeFilters, {
19049
+ label,
19050
+ eoseTimeout: maxWait,
19051
+ onevent(event) {
19052
+ if (closed) return;
19053
+ if (pool.trackRelays) {
19054
+ const history = pool.seenOn.get(event.id) ?? /* @__PURE__ */ new Set();
19055
+ history.add(relay);
19056
+ pool.seenOn.set(event.id, history);
19057
+ }
19058
+ try {
19059
+ observe(event, source);
19060
+ } catch {
19061
+ }
19062
+ if (seen.has(event.id)) return;
19063
+ seen.add(event.id);
19064
+ next(event);
19065
+ },
19066
+ oneose: () => finishRelay(url),
19067
+ onclose(reason) {
19068
+ const signer = pool.automaticallyAuth?.(url);
19069
+ if (!closed && !retry && signer && reason.startsWith("auth-required: ")) {
19070
+ void relay.auth(signer).then(() => subscribe(true)).catch(() => finishRelay(url));
19071
+ } else finishRelay(url);
19072
+ }
19073
+ });
19074
+ if (closed && !subscription.closed) subscription.close("paja query closed");
19075
+ else if (!subscription.closed) subscriptions.add(subscription);
19076
+ };
19077
+ subscribe(false);
19078
+ }).catch(() => {
19079
+ if (!closed) pool.onRelayConnectionFailure?.(url);
19080
+ finishRelay(url);
19081
+ });
19082
+ }
19083
+ return {
19084
+ unsubscribe(reason = "paja unsubscribe") {
19085
+ if (closed) return;
19086
+ closed = true;
19087
+ controller.abort();
19088
+ for (const subscription of subscriptions) {
19089
+ if (subscription.closed) continue;
19090
+ try {
19091
+ void Promise.resolve(subscription.close(reason)).catch(() => {
19092
+ });
19093
+ } catch {
19094
+ }
19095
+ }
19096
+ subscriptions.clear();
19097
+ }
19098
+ };
19099
+ }
19100
+ async function queryPajaLive(pool, relayUrls2, filters, maxWait, observe, collectUntilLimit = false, signal) {
19101
+ const batches = await Promise.all((filters.length ? filters : [{}]).map((filter) => {
19102
+ const limit = collectUntilLimit && typeof filter.limit === "number" && filter.limit >= 0 ? filter.limit : Infinity;
19103
+ if (limit === 0 || signal?.aborted) return Promise.resolve([]);
19104
+ return new Promise((resolve) => {
19105
+ const events2 = [];
19106
+ let subscription;
19107
+ let finished = false;
19108
+ const finish = (reason) => {
19109
+ if (finished) return;
19110
+ finished = true;
19111
+ clearTimeout(timer);
19112
+ signal?.removeEventListener("abort", abort);
19113
+ subscription?.unsubscribe(reason);
19114
+ resolve(events2);
19115
+ };
19116
+ const abort = () => finish("paja query aborted");
19117
+ const timer = setTimeout(() => finish("paja query timeout"), maxWait);
19118
+ signal?.addEventListener("abort", abort, { once: true });
19119
+ subscription = subscribePajaLive(pool, relayUrls2, [filter], (item) => {
19120
+ if (finished) return;
19121
+ if (item === "EOSE") return finish("closed automatically on eose");
19122
+ events2.push(item);
19123
+ if (events2.length >= limit) finish("paja query limit reached");
19124
+ }, observe, maxWait, collectUntilLimit ? "kehto-paja-candidates" : "kehto-paja-query");
19125
+ if (finished) subscription.unsubscribe();
19126
+ if (signal?.aborted) abort();
19127
+ });
19128
+ }));
19129
+ const events = /* @__PURE__ */ new Map();
19130
+ for (const event of batches.flat()) events.set(event.id, event);
19131
+ return [...events.values()].sort((a, b) => b.created_at - a.created_at);
19132
+ }
19133
+
19134
+ // src/browser-relay-runtime.ts
19135
+ var PAJA_NIP65_RELAY_LIST_KIND = 10002;
19136
+ var PAJA_CONTACT_LIST_KIND = 3;
19137
+ var PAJA_WEBRTC_SIGNAL_KIND = 25050;
19138
+ var NIP17_GIFT_WRAP_KIND2 = 1059;
19139
+ var PAJA_CONTACT_LIST_CANDIDATE_LIMIT = 64;
19140
+ var PAJA_LIVE_QUERY_WAIT_MS = 4e3;
19141
+ var contactListCandidateQueries = /* @__PURE__ */ new WeakMap();
19142
+ function matchesFilter2(event, filter) {
19143
+ const ids = filter.ids;
19144
+ if (ids && !ids.some((id) => event.id === id || event.id.startsWith(id))) return false;
19145
+ const authors = filter.authors;
19146
+ if (authors && !authors.some((author) => event.pubkey === author || event.pubkey.startsWith(author))) return false;
19147
+ const kinds = filter.kinds;
19148
+ if (kinds && !kinds.includes(event.kind)) return false;
19149
+ if (typeof filter.since === "number" && event.created_at < filter.since) return false;
19150
+ if (typeof filter.until === "number" && event.created_at > filter.until) return false;
19151
+ for (const [key, value] of Object.entries(filter)) {
19152
+ if (!key.startsWith("#") || !Array.isArray(value)) continue;
19153
+ const tagName = key.slice(1);
19154
+ const allowed2 = value.filter((item) => typeof item === "string");
19155
+ if (allowed2.length === 0) continue;
19156
+ if (!event.tags.some((tag) => tag[0] === tagName && typeof tag[1] === "string" && allowed2.includes(tag[1]))) return false;
19157
+ }
19158
+ return true;
19159
+ }
19160
+ function matchesAnyFilter2(event, filters) {
19161
+ return filters.length === 0 || filters.some((filter) => matchesFilter2(event, filter));
19162
+ }
19163
+ function normalizedFilters(filters) {
19164
+ return Array.isArray(filters) ? filters : [filters];
19165
+ }
19078
19166
  function applyFilterLimit(events, filter) {
19079
19167
  const limit = typeof filter.limit === "number" && filter.limit >= 0 ? filter.limit : void 0;
19080
19168
  if (limit === void 0) return events;
@@ -19090,78 +19178,6 @@ function collectMemoryEvents(events, filters) {
19090
19178
  }
19091
19179
  return [...out.values()].sort((a, b) => b.created_at - a.created_at);
19092
19180
  }
19093
- function subscribeLive(pool, relayUrls2, filters, next) {
19094
- const activeFilters = filters.length > 0 ? filters : [{}];
19095
- const requests = relayUrls2.flatMap((url) => activeFilters.map((filter) => ({ url, filter })));
19096
- if (requests.length === 0) {
19097
- queueMicrotask(() => next("EOSE"));
19098
- return { unsubscribe() {
19099
- } };
19100
- }
19101
- const sub = pool.subscribeMap(requests, {
19102
- label: "kehto-paja-runtime",
19103
- maxWait: PAJA_LIVE_QUERY_WAIT_MS,
19104
- onevent: (event) => next(event),
19105
- oneose: () => next("EOSE")
19106
- });
19107
- return {
19108
- unsubscribe() {
19109
- void sub.close("paja unsubscribe");
19110
- }
19111
- };
19112
- }
19113
- function queryLiveBounded(pool, relayUrls2, filter, maxWaitMs, limit, signal) {
19114
- if (limit === 0 || signal?.aborted) return Promise.resolve([]);
19115
- return new Promise((resolve) => {
19116
- const events = [];
19117
- let settled = false;
19118
- let closeRequested = false;
19119
- let closeReason = "paja query limit reached";
19120
- let subscription;
19121
- let abort;
19122
- const finish = () => {
19123
- if (settled) return;
19124
- settled = true;
19125
- if (abort) signal?.removeEventListener("abort", abort);
19126
- resolve(events);
19127
- };
19128
- const close = (reason = closeReason) => {
19129
- closeRequested = true;
19130
- closeReason = reason;
19131
- if (!subscription) return;
19132
- void Promise.resolve(subscription.close(reason)).catch(() => {
19133
- });
19134
- finish();
19135
- };
19136
- abort = () => close("paja query aborted");
19137
- signal?.addEventListener("abort", abort, { once: true });
19138
- subscription = pool.subscribeEose(relayUrls2, filter, {
19139
- label: "kehto-paja-runtime",
19140
- maxWait: maxWaitMs,
19141
- onevent(event) {
19142
- if (events.length >= limit) return;
19143
- events.push(event);
19144
- if (events.length === limit) close();
19145
- },
19146
- onclose: finish
19147
- });
19148
- if (closeRequested) close();
19149
- });
19150
- }
19151
- async function queryLive(pool, relayUrls2, filters, maxWaitMs = PAJA_LIVE_QUERY_WAIT_MS, collectUntilLimit = false, signal) {
19152
- const activeFilters = filters.length > 0 ? filters : [{}];
19153
- const batches = await Promise.all(activeFilters.map((filter) => {
19154
- const limit = typeof filter.limit === "number" && filter.limit >= 0 ? filter.limit : void 0;
19155
- if (collectUntilLimit && limit !== void 0) return queryLiveBounded(pool, relayUrls2, filter, maxWaitMs, limit, signal);
19156
- return pool.querySync(relayUrls2, filter, {
19157
- label: "kehto-paja-runtime",
19158
- maxWait: maxWaitMs
19159
- });
19160
- }));
19161
- const out = /* @__PURE__ */ new Map();
19162
- for (const event of batches.flat()) out.set(event.id, event);
19163
- return [...out.values()].sort((a, b) => b.created_at - a.created_at);
19164
- }
19165
19181
  async function publishLive(pool, relayUrls2, event) {
19166
19182
  const results = await Promise.allSettled(pool.publish(relayUrls2, event));
19167
19183
  return Object.fromEntries(relayUrls2.map((relayUrl2, index) => [relayUrl2, results[index]?.status === "fulfilled"]));
@@ -19204,12 +19220,33 @@ function createPajaRelayBackend(getSimulation, confirmRequest, livePool = new Si
19204
19220
  const fixtureEvents = getSimulation().relay.fixtures.flatMap(toNostrEvent);
19205
19221
  const acceptedMemoryEvents = [];
19206
19222
  const subscribers = /* @__PURE__ */ new Set();
19223
+ let relayEventObserver;
19224
+ let relayRequestObserver;
19225
+ const observeRelayRequest = (context, relayUrls2) => {
19226
+ if (relayUrls2.length === 0) return;
19227
+ relayRequestObserver?.({ ...context, relayUrls: [...relayUrls2] });
19228
+ };
19229
+ const observeRelayEvent = (context, relayUrls2, event, source) => {
19230
+ relayEventObserver?.({
19231
+ ...context,
19232
+ relayUrls: [...relayUrls2],
19233
+ event,
19234
+ sightedOn: [source]
19235
+ });
19236
+ };
19207
19237
  const isAvailable = () => getSimulation().relay.mode !== "disabled" && getPajaRelayUrls(getSimulation()).length > 0;
19208
19238
  const cachedEvents = () => getSimulation().relay.mode === "memory" ? [...fixtureEvents, ...acceptedMemoryEvents] : [];
19209
- const query = async (relayUrls2, filters, maxWaitMs) => {
19239
+ const query = async (relayUrls2, filters, maxWaitMs, context = { reason: "host" }) => {
19210
19240
  const cached = collectMemoryEvents(cachedEvents(), filters);
19211
19241
  if (getSimulation().relay.mode !== "live" || relayUrls2.length === 0) return cached;
19212
- const liveEvents = await queryLive(livePool, relayUrls2, filters, maxWaitMs);
19242
+ observeRelayRequest(context, relayUrls2);
19243
+ const liveEvents = await queryPajaLive(
19244
+ livePool,
19245
+ relayUrls2,
19246
+ filters,
19247
+ maxWaitMs ?? PAJA_LIVE_QUERY_WAIT_MS,
19248
+ (event, source) => observeRelayEvent(context, relayUrls2, event, source)
19249
+ );
19213
19250
  const out = /* @__PURE__ */ new Map();
19214
19251
  for (const event of [...cached, ...liveEvents]) out.set(event.id, event);
19215
19252
  return [...out.values()].sort((a, b) => b.created_at - a.created_at);
@@ -19217,7 +19254,16 @@ function createPajaRelayBackend(getSimulation, confirmRequest, livePool = new Si
19217
19254
  const queryContactListCandidates = async (relayUrls2, filters, maxWaitMs, signal) => {
19218
19255
  const cached = collectMemoryEvents(cachedEvents(), filters);
19219
19256
  if (signal?.aborted || getSimulation().relay.mode !== "live" || relayUrls2.length === 0) return cached;
19220
- const liveEvents = await queryLive(livePool, relayUrls2, filters, maxWaitMs, true, signal);
19257
+ observeRelayRequest({ reason: "host" }, relayUrls2);
19258
+ const liveEvents = await queryPajaLive(
19259
+ livePool,
19260
+ relayUrls2,
19261
+ filters,
19262
+ maxWaitMs ?? PAJA_LIVE_QUERY_WAIT_MS,
19263
+ (event, source) => observeRelayEvent({ reason: "host" }, relayUrls2, event, source),
19264
+ true,
19265
+ signal
19266
+ );
19221
19267
  const out = /* @__PURE__ */ new Map();
19222
19268
  for (const event of [...cached, ...liveEvents]) out.set(event.id, event);
19223
19269
  return [...out.values()].sort((a, b) => b.created_at - a.created_at);
@@ -19246,7 +19292,7 @@ function createPajaRelayBackend(getSimulation, confirmRequest, livePool = new Si
19246
19292
  return { outcomes };
19247
19293
  }
19248
19294
  const backend = {
19249
- subscription(relayUrls2, filtersInput) {
19295
+ subscription(relayUrls2, filtersInput, context = { reason: "host" }) {
19250
19296
  return {
19251
19297
  subscribe(next) {
19252
19298
  const filters = normalizedFilters(filtersInput);
@@ -19256,7 +19302,15 @@ function createPajaRelayBackend(getSimulation, confirmRequest, livePool = new Si
19256
19302
  };
19257
19303
  subscribers.add(subscriber);
19258
19304
  for (const event of collectMemoryEvents(cachedEvents(), filters)) next(event);
19259
- const liveSub = getSimulation().relay.mode === "live" ? subscribeLive(livePool, relayUrls2, filters, subscriber.next) : null;
19305
+ if (getSimulation().relay.mode === "live") observeRelayRequest(context, relayUrls2);
19306
+ const liveSub = getSimulation().relay.mode === "live" ? subscribePajaLive(
19307
+ livePool,
19308
+ relayUrls2,
19309
+ filters,
19310
+ subscriber.next,
19311
+ (event, source) => observeRelayEvent(context, relayUrls2, event, source),
19312
+ PAJA_LIVE_QUERY_WAIT_MS
19313
+ ) : null;
19260
19314
  queueMicrotask(() => {
19261
19315
  if (subscribers.has(subscriber) && !liveSub) next("EOSE");
19262
19316
  });
@@ -19273,12 +19327,12 @@ function createPajaRelayBackend(getSimulation, confirmRequest, livePool = new Si
19273
19327
  const attempt = await attemptPublish(relayUrls2, event);
19274
19328
  if (attempt.error) throw new Error(attempt.error);
19275
19329
  },
19276
- request(relayUrls2, filtersInput) {
19330
+ request(relayUrls2, filtersInput, context = { reason: "host" }) {
19277
19331
  return {
19278
19332
  subscribe(observer) {
19279
19333
  const filters = normalizedFilters(filtersInput);
19280
19334
  let active = true;
19281
- query(relayUrls2, filters).then((matched) => {
19335
+ query(relayUrls2, filters, void 0, context).then((matched) => {
19282
19336
  if (!active) return;
19283
19337
  for (const event of matched) observer.next(event);
19284
19338
  observer.complete();
@@ -19297,11 +19351,18 @@ function createPajaRelayBackend(getSimulation, confirmRequest, livePool = new Si
19297
19351
  },
19298
19352
  async countWithRelay(relayUrls2, filters) {
19299
19353
  if (getSimulation().relay.mode !== "live") throw new Error("count unavailable");
19354
+ observeRelayRequest({ reason: "host" }, relayUrls2);
19300
19355
  return countLive(livePool, relayUrls2, normalizedFilters(filters));
19301
19356
  },
19302
19357
  observedRelayUrls(eventId) {
19303
19358
  return [...livePool.seenOn?.get(eventId) ?? []].map((relay) => relay.url);
19304
19359
  },
19360
+ setRelayEventObserver(observer) {
19361
+ relayEventObserver = observer;
19362
+ },
19363
+ setRelayRequestObserver(observer) {
19364
+ relayRequestObserver = observer;
19365
+ },
19305
19366
  query,
19306
19367
  async publishToRelays(relayUrls2, event) {
19307
19368
  return (await attemptPublish(relayUrls2, event)).outcomes;
@@ -19421,8 +19482,8 @@ function createPajaRelayListLoader(backend, getSimulation, signerProvider, getHo
19421
19482
  }
19422
19483
  function createPajaOutboxRelayPool(backend) {
19423
19484
  return {
19424
- subscribe(filters, relayUrls2, callback) {
19425
- return backend.subscription(relayUrls2, filters).subscribe((item) => callback(item));
19485
+ subscribe(filters, relayUrls2, callback, origin) {
19486
+ return backend.subscription(relayUrls2, filters, { reason: "outbox", origin }).subscribe((item) => callback(item));
19426
19487
  },
19427
19488
  publish(event, relayUrls2) {
19428
19489
  return backend.publishToRelays(relayUrls2, event);
@@ -21574,9 +21635,10 @@ function createDevServices(backend, getSimulation, relayConfig, onThemeService,
21574
21635
  }
21575
21636
  if (getSimulation().relay.mode === "live") {
21576
21637
  services.relay = createRelayPoolService({
21577
- subscribe: (filters, callback, relayUrls2) => backend.subscription(
21638
+ subscribe: (filters, callback, relayUrls2, fromHint) => backend.subscription(
21578
21639
  (relayUrls2 ?? getReadRelays()).filter((url) => isPajaRelayAllowed(url, getAllRelays)),
21579
- filters
21640
+ filters,
21641
+ { reason: fromHint ? "hint" : "host" }
21580
21642
  ).subscribe((item) => {
21581
21643
  if (item === "EOSE" || typeof item === "object" && item !== null) {
21582
21644
  callback(
@@ -21800,6 +21862,8 @@ function createPajaAdapter(config, getSimulation, onThemeService, onThemeBroadca
21800
21862
  });
21801
21863
  const adapter = {
21802
21864
  ready,
21865
+ notifyIntentChanged: () => {
21866
+ },
21803
21867
  setWindowBlossomServers: serviceBundle.setWindowBlossomServers,
21804
21868
  relayPool: createPajaRelayHooks(relayBackend, getSimulation, relayConfig),
21805
21869
  relayConfig,
@@ -21839,20 +21903,9 @@ function createPajaAdapter(config, getSimulation, onThemeService, onThemeBroadca
21839
21903
  }
21840
21904
  };
21841
21905
  if (getSimulation().intent.enabled && intentHost) {
21842
- const resolver = createCatalogIntentResolver({
21843
- loadCatalog: () => intentHost.catalog.intentCatalog(
21844
- (record2) => resolveShellEnvironment(adapter, record2).capabilities.domains.includes("intent")
21845
- ),
21846
- targets: intentHost.controller,
21847
- getDefaultHandler: intentHost.getDefaultHandler,
21848
- chooseHandler: intentHost.chooseHandler,
21849
- authorizeExplicitHandler: intentHost.authorizeExplicitHandler,
21850
- resolveHandlerHint: intentHost.resolveHandlerHint
21851
- });
21852
- services.intent = createIntentService({
21853
- resolver,
21854
- resolveSender: intentHost.resolveSender
21855
- });
21906
+ const intent = createPajaCatalogIntentService(adapter, intentHost);
21907
+ services.intent = intent.service;
21908
+ adapter.notifyIntentChanged = intent.notifyChanged;
21856
21909
  }
21857
21910
  return adapter;
21858
21911
  }
@@ -21873,6 +21926,241 @@ function forwardPajaHotkey(event) {
21873
21926
  }));
21874
21927
  }
21875
21928
 
21929
+ // src/browser-relay-panel.ts
21930
+ var PAJA_EVENT_COUNTER_RESET_ID = "event-counter-reset";
21931
+ var RELAY_BOXES = [
21932
+ {
21933
+ kind: "nip65",
21934
+ label: "outbox relays (NIP-65)",
21935
+ reason: "outbox",
21936
+ origin: "nip65",
21937
+ configured: false,
21938
+ emptyNote: "no author-routed reads"
21939
+ },
21940
+ { kind: "hint", label: "relay hints", reason: "outbox", origin: "hint", configured: false },
21941
+ { kind: "fallback", label: "fallback relays", reason: "outbox", origin: "fallback", configured: true },
21942
+ { kind: "unattributed", label: "outbox relays (unattributed)", reason: "outbox", configured: false },
21943
+ { kind: "scoped", label: "scoped relay", reason: "hint", configured: false },
21944
+ { kind: "host", label: "host pool", reason: "host", configured: false }
21945
+ ];
21946
+ function boxKindFor(reason, origin) {
21947
+ if (reason === "outbox") return origin ?? "unattributed";
21948
+ return reason === "hint" ? "scoped" : "host";
21949
+ }
21950
+ function emptyBox() {
21951
+ return { count: 0, reads: /* @__PURE__ */ new Map(), relays: /* @__PURE__ */ new Map() };
21952
+ }
21953
+ function distinctRelayUrls(urls) {
21954
+ const unique = /* @__PURE__ */ new Map();
21955
+ for (const url of urls) {
21956
+ if (url.length === 0) continue;
21957
+ const key = normalizeURL2(url);
21958
+ if (!unique.has(key)) unique.set(key, url);
21959
+ }
21960
+ return [...unique.values()];
21961
+ }
21962
+ function createPajaRelayEventCounter(onChange) {
21963
+ const boxes = /* @__PURE__ */ new Map();
21964
+ const eventIds = /* @__PURE__ */ new Set();
21965
+ let total = 0;
21966
+ const boxFor = (kind) => {
21967
+ let box = boxes.get(kind);
21968
+ if (!box) {
21969
+ box = emptyBox();
21970
+ boxes.set(kind, box);
21971
+ }
21972
+ return box;
21973
+ };
21974
+ const relayFor = (kind, relayUrl2) => {
21975
+ const box = boxFor(kind);
21976
+ const key = normalizeURL2(relayUrl2);
21977
+ let relay = box.relays.get(key);
21978
+ if (!relay) {
21979
+ relay = { relayUrl: relayUrl2, count: 0, kinds: /* @__PURE__ */ new Map() };
21980
+ box.relays.set(key, relay);
21981
+ }
21982
+ return relay;
21983
+ };
21984
+ return {
21985
+ get total() {
21986
+ return total;
21987
+ },
21988
+ get uniqueEvents() {
21989
+ return eventIds.size;
21990
+ },
21991
+ snapshot(inventory) {
21992
+ const out = [];
21993
+ for (const spec of RELAY_BOXES) {
21994
+ const box = boxes.get(spec.kind);
21995
+ const configured = spec.configured ? inventory?.[spec.kind] ?? [] : [];
21996
+ const seen = /* @__PURE__ */ new Set();
21997
+ const relays = [];
21998
+ const push = (relayUrl2, isConfigured) => {
21999
+ const key = normalizeURL2(relayUrl2);
22000
+ if (seen.has(key)) return;
22001
+ seen.add(key);
22002
+ const relay = box?.relays.get(key);
22003
+ relays.push({
22004
+ relayUrl: relayUrl2,
22005
+ count: relay?.count ?? 0,
22006
+ readCount: box?.reads.get(key) ?? 0,
22007
+ configured: isConfigured,
22008
+ kinds: [...relay?.kinds.entries() ?? []].sort(([left], [right]) => left - right).map(([kind, count]) => ({ kind, count }))
22009
+ });
22010
+ };
22011
+ for (const url of configured) push(url, true);
22012
+ for (const relay of box?.relays.values() ?? []) push(relay.relayUrl, false);
22013
+ if (relays.length === 0 && !(spec.emptyNote && total > 0)) continue;
22014
+ relays.sort((left, right) => right.count - left.count);
22015
+ out.push({
22016
+ kind: spec.kind,
22017
+ label: spec.label,
22018
+ reason: spec.reason,
22019
+ ...spec.origin ? { origin: spec.origin } : {},
22020
+ count: box?.count ?? 0,
22021
+ relays,
22022
+ ...relays.length === 0 && spec.emptyNote ? { emptyNote: spec.emptyNote } : {}
22023
+ });
22024
+ }
22025
+ return out;
22026
+ },
22027
+ recordRead(reason, relayUrls2, origin) {
22028
+ const kind = boxKindFor(reason, origin);
22029
+ const box = boxFor(kind);
22030
+ let changed = false;
22031
+ for (const relayUrl2 of distinctRelayUrls(relayUrls2)) {
22032
+ const key = normalizeURL2(relayUrl2);
22033
+ box.reads.set(key, (box.reads.get(key) ?? 0) + 1);
22034
+ relayFor(kind, relayUrl2);
22035
+ changed = true;
22036
+ }
22037
+ if (changed) onChange?.();
22038
+ },
22039
+ recordEvent(reason, event, sightedOn, origin) {
22040
+ if (typeof event !== "object" || event === null) return;
22041
+ const kind = event.kind;
22042
+ if (typeof kind !== "number" || !Number.isSafeInteger(kind) || kind < 0) return;
22043
+ const relays = distinctRelayUrls(sightedOn);
22044
+ if (relays.length === 0) return;
22045
+ const box = boxFor(boxKindFor(reason, origin));
22046
+ for (const relayUrl2 of relays) {
22047
+ const relay = relayFor(boxKindFor(reason, origin), relayUrl2);
22048
+ relay.count += 1;
22049
+ relay.kinds.set(kind, (relay.kinds.get(kind) ?? 0) + 1);
22050
+ box.count += 1;
22051
+ total += 1;
22052
+ }
22053
+ const id = event.id;
22054
+ if (typeof id === "string" && id.length > 0) eventIds.add(id);
22055
+ onChange?.();
22056
+ },
22057
+ reset() {
22058
+ boxes.clear();
22059
+ eventIds.clear();
22060
+ total = 0;
22061
+ onChange?.();
22062
+ }
22063
+ };
22064
+ }
22065
+ function installPajaEventCounterReset(counter) {
22066
+ const button2 = document.getElementById(PAJA_EVENT_COUNTER_RESET_ID);
22067
+ const onClick = (event) => {
22068
+ event.stopPropagation();
22069
+ counter.reset();
22070
+ };
22071
+ button2?.addEventListener("click", onClick);
22072
+ return () => button2?.removeEventListener("click", onClick);
22073
+ }
22074
+ function renderPajaEventKindCounts(counter, inventory) {
22075
+ const container = document.getElementById("event-kind-counts");
22076
+ const total = document.getElementById("event-kind-total");
22077
+ const boxes = counter.snapshot(inventory);
22078
+ if (total) {
22079
+ total.textContent = boxes.length === 0 ? "" : `${counter.total}`;
22080
+ total.title = `${counter.total} relay receipt${counter.total === 1 ? "" : "s"} \xB7 ${counter.uniqueEvents} unique event${counter.uniqueEvents === 1 ? "" : "s"}`;
22081
+ }
22082
+ if (!container) return;
22083
+ if (boxes.length === 0) {
22084
+ const empty = document.createElement("div");
22085
+ empty.className = "event-empty";
22086
+ empty.textContent = "no relay events yet";
22087
+ container.replaceChildren(empty);
22088
+ return;
22089
+ }
22090
+ const busiest = Math.max(1, ...boxes.flatMap((box) => box.relays.map((relay) => relay.count)));
22091
+ container.replaceChildren(...boxes.map((box) => {
22092
+ const section = document.createElement("div");
22093
+ section.className = "event-box";
22094
+ section.dataset.relayBox = box.kind;
22095
+ section.dataset.relayReason = box.reason;
22096
+ const head = document.createElement("div");
22097
+ head.className = "event-box-head";
22098
+ const name = document.createElement("span");
22099
+ name.className = "event-box-name";
22100
+ name.textContent = box.label;
22101
+ const boxCount = document.createElement("span");
22102
+ boxCount.className = box.relays.length === 0 ? "event-box-note" : "event-box-count";
22103
+ boxCount.textContent = box.relays.length === 0 ? box.emptyNote ?? "0" : String(box.count);
22104
+ head.append(name, boxCount);
22105
+ section.append(head);
22106
+ for (const relay of box.relays) {
22107
+ const row = document.createElement("div");
22108
+ row.className = "event-relay";
22109
+ row.dataset.relayUrl = relay.relayUrl;
22110
+ row.dataset.relayCount = String(relay.count);
22111
+ row.dataset.relayReads = String(relay.readCount);
22112
+ if (relay.configured) row.dataset.relayConfigured = "true";
22113
+ const rowHead = document.createElement("div");
22114
+ rowHead.className = "event-relay-head";
22115
+ const url = document.createElement("span");
22116
+ url.className = "event-relay-url";
22117
+ url.textContent = relay.relayUrl;
22118
+ url.title = relay.relayUrl;
22119
+ const bar = document.createElement("span");
22120
+ bar.className = "event-bar";
22121
+ const fill = document.createElement("span");
22122
+ fill.className = "event-bar-fill";
22123
+ fill.style.width = `${Math.round(relay.count / busiest * 100)}%`;
22124
+ bar.append(fill);
22125
+ const relayCount = document.createElement("span");
22126
+ relayCount.className = "event-relay-count";
22127
+ relayCount.textContent = String(relay.count);
22128
+ rowHead.append(url, bar, relayCount);
22129
+ if (relay.count === 0) {
22130
+ const idle = document.createElement("span");
22131
+ idle.className = "event-relay-idle";
22132
+ idle.textContent = relay.readCount > 0 ? "silent" : "unused";
22133
+ idle.title = relay.readCount > 0 ? `Paja read from this relay ${relay.readCount} time${relay.readCount === 1 ? "" : "s"} and received no events` : "configured for this box and not used yet this session";
22134
+ rowHead.append(idle);
22135
+ }
22136
+ row.append(rowHead);
22137
+ if (relay.kinds.length > 0) {
22138
+ const kinds = document.createElement("div");
22139
+ kinds.className = "event-kinds";
22140
+ kinds.replaceChildren(...relay.kinds.map(({ kind, count }) => {
22141
+ const kindRow = document.createElement("div");
22142
+ kindRow.className = "event-row";
22143
+ kindRow.dataset.eventKind = String(kind);
22144
+ const kindCell = document.createElement("span");
22145
+ kindCell.className = "event-kind";
22146
+ kindCell.textContent = String(kind);
22147
+ const separator = document.createElement("span");
22148
+ separator.className = "event-separator";
22149
+ separator.textContent = "-";
22150
+ const countCell = document.createElement("span");
22151
+ countCell.className = "event-count";
22152
+ countCell.textContent = String(count);
22153
+ kindRow.append(kindCell, separator, countCell);
22154
+ return kindRow;
22155
+ }));
22156
+ row.append(kinds);
22157
+ }
22158
+ section.append(row);
22159
+ }
22160
+ return section;
22161
+ }));
22162
+ }
22163
+
21876
22164
  // src/local-target.ts
21877
22165
  var PAJA_LOCAL_SINGLE_FILE_HINT = "Paja opens self-contained single-file index.html only; relative scripts, styles, and images do not load.";
21878
22166
  var MAX_DTAG_LENGTH = 128;
@@ -22067,6 +22355,12 @@ function escapeHtml(value) {
22067
22355
 
22068
22356
  // src/browser-devtools.ts
22069
22357
  var PAJA_LOG_LIMIT = 500;
22358
+ var FS_PICKER_METHODS = {
22359
+ "fs.pickFile.result": "showOpenFilePicker",
22360
+ "fs.pickFiles.result": "showOpenFilePicker",
22361
+ "fs.pickDirectory.result": "showDirectoryPicker",
22362
+ "fs.pickSaveFile.result": "showSaveFilePicker"
22363
+ };
22070
22364
  var proxyToReal = /* @__PURE__ */ new WeakMap();
22071
22365
  var realToProxy = /* @__PURE__ */ new WeakMap();
22072
22366
  var proxyContexts = /* @__PURE__ */ new WeakMap();
@@ -22102,7 +22396,15 @@ function describeMessageDetail(raw) {
22102
22396
  const value = raw;
22103
22397
  for (const key of ["error", "message", "reason"]) {
22104
22398
  const detail = value[key];
22105
- if (typeof detail === "string" && detail.length > 0) return detail;
22399
+ if (typeof detail === "string" && detail.length > 0) {
22400
+ if (detail === "unsupported") {
22401
+ const picker = FS_PICKER_METHODS[raw.type];
22402
+ if (picker && !browserPickers()[picker]) {
22403
+ return `unsupported: this browser does not provide ${picker}. Workspace FS may still be available; ACL permission does not add browser APIs.`;
22404
+ }
22405
+ }
22406
+ return detail;
22407
+ }
22106
22408
  }
22107
22409
  return raw.type.endsWith(".error") ? compactMessageDetail(value) : "";
22108
22410
  }
@@ -22201,8 +22503,10 @@ function installPajaOriginRegistryProxy(originRegistry2, stateRef) {
22201
22503
  }
22202
22504
  function renderPajaDevtools(state, options) {
22203
22505
  renderInterfaceControls(state);
22506
+ renderFsSupport(state);
22204
22507
  renderAclControls(state, options.bridge);
22205
22508
  renderSignerStatus(state, options.devSignerPubkey);
22509
+ renderPajaEventKindCounts(state.relayEventCounts, state.relayInventory?.());
22206
22510
  }
22207
22511
  function renderPajaMessageLog(state) {
22208
22512
  const container = document.getElementById("message-log");
@@ -22254,6 +22558,21 @@ function renderInterfaceControls(state) {
22254
22558
  return button2;
22255
22559
  }));
22256
22560
  }
22561
+ function renderFsSupport(state) {
22562
+ const status = document.getElementById("paja-fs-support");
22563
+ if (!status) return;
22564
+ if (!domainEnabled(state.simulation, "fs")) {
22565
+ status.textContent = "FS disabled by host.";
22566
+ return;
22567
+ }
22568
+ if (!state.services?.includes("fs")) {
22569
+ status.textContent = "FS unavailable: browser workspace storage could not be opened.";
22570
+ return;
22571
+ }
22572
+ const pickers = browserPickers();
22573
+ const availability = (available) => available ? "available" : "unavailable";
22574
+ status.textContent = `FS: Workspace available. Native pickers: open ${availability(pickers.showOpenFilePicker)}, save ${availability(pickers.showSaveFilePicker)}, directory ${availability(pickers.showDirectoryPicker)}.`;
22575
+ }
22257
22576
  function renderAclControls(state, bridge) {
22258
22577
  const container = document.getElementById("acl-controls");
22259
22578
  if (!container) return;
@@ -22271,7 +22590,7 @@ function renderAclControls(state, bridge) {
22271
22590
  button2.dataset.aclCapability = capability;
22272
22591
  button2.dataset.enabled = String(allowed2);
22273
22592
  button2.textContent = capability;
22274
- button2.title = `${capability} ${allowed2 ? "allowed" : "blocked"}`;
22593
+ button2.title = `${capability} permission ${allowed2 ? "allowed" : "blocked"}; browser support is separate`;
22275
22594
  button2.addEventListener("click", () => state.setAclCapability(capability, !allowed2));
22276
22595
  return button2;
22277
22596
  }));
@@ -23257,6 +23576,7 @@ function parseRuntimeTabsSnapshot(value) {
23257
23576
  };
23258
23577
  }
23259
23578
  function renderRuntimeTabs(state) {
23579
+ document.title = getActiveTab(state)?.title || "@kehto/paja";
23260
23580
  const tabsEl = document.getElementById("napplet-tabs");
23261
23581
  if (!(tabsEl instanceof HTMLElement)) return;
23262
23582
  tabsEl.replaceChildren(...state.tabs.map((tab) => renderTab(state, tab)));
@@ -23701,6 +24021,216 @@ function installLocalFileControls(load) {
23701
24021
  function disposeNothing() {
23702
24022
  }
23703
24023
 
24024
+ // src/browser-intent-controller.ts
24025
+ var MAX_INTENT_DELIVERY_ATTEMPTS = 10;
24026
+ var BrowserIntentController = class {
24027
+ constructor(options) {
24028
+ this.options = options;
24029
+ this.maxAttempts = normalizeAttempts(options.maxAttempts);
24030
+ }
24031
+ options;
24032
+ maxAttempts;
24033
+ /** Retain delivery work immediately; completion remains host-observable only. */
24034
+ accept(params) {
24035
+ const acceptance = Object.freeze({ completion: this.dispatch(params) });
24036
+ this.options.onAccepted?.(params, acceptance);
24037
+ return acceptance;
24038
+ }
24039
+ /** Complete an already accepted delivery. Kept public for host diagnostics and tests. */
24040
+ async dispatch(params) {
24041
+ const dispatch2 = freezeDispatch(params);
24042
+ let reason = "no-current-target";
24043
+ for (let attempt = 1; attempt <= this.maxAttempts; attempt += 1) {
24044
+ let generation;
24045
+ try {
24046
+ generation = await this.options.openOrReuse(dispatch2, attempt);
24047
+ } catch {
24048
+ reason = "open-failed";
24049
+ continue;
24050
+ }
24051
+ if (!generation) {
24052
+ reason = "open-failed";
24053
+ continue;
24054
+ }
24055
+ try {
24056
+ await this.options.waitForReady(generation);
24057
+ } catch {
24058
+ reason = "ready-failed";
24059
+ continue;
24060
+ }
24061
+ if (!await this.options.isCurrent(generation)) {
24062
+ reason = "no-current-target";
24063
+ continue;
24064
+ }
24065
+ try {
24066
+ await this.options.send(generation, dispatch2);
24067
+ this.options.onDelivered?.(dispatch2);
24068
+ return;
24069
+ } catch {
24070
+ this.options.onTerminal?.(dispatch2, "send-failed");
24071
+ throw new Error("intent target send failed");
24072
+ }
24073
+ }
24074
+ this.options.onTerminal?.(dispatch2, reason);
24075
+ throw new Error(`intent target ${reason}`);
24076
+ }
24077
+ };
24078
+ function normalizeAttempts(value) {
24079
+ if (value === void 0) return 2;
24080
+ if (!Number.isFinite(value)) throw new TypeError("maxAttempts must be finite");
24081
+ return Math.min(MAX_INTENT_DELIVERY_ATTEMPTS, Math.max(1, Math.floor(value)));
24082
+ }
24083
+ function freezeDispatch(params) {
24084
+ if (!params || typeof params.handler !== "string" || params.handler.length === 0) {
24085
+ throw new TypeError("Intent dispatch requires a handler");
24086
+ }
24087
+ if (typeof params.sender !== "string" || params.sender.length === 0 || typeof params.archetype !== "string" || params.archetype.length === 0 || typeof params.action !== "string" || params.action.length === 0 || typeof params.convention !== "string" || params.convention.length === 0) {
24088
+ throw new TypeError("Intent dispatch requires canonical routing fields");
24089
+ }
24090
+ const payload = freezeValue(params.payload);
24091
+ const behavior = params.behavior === void 0 ? void 0 : freezeValue({ ...params.behavior });
24092
+ return Object.freeze({
24093
+ handler: params.handler,
24094
+ sender: params.sender,
24095
+ archetype: params.archetype,
24096
+ action: params.action,
24097
+ convention: params.convention,
24098
+ ...params.payload === void 0 ? {} : { payload },
24099
+ ...behavior === void 0 ? {} : { behavior },
24100
+ ...params.sourceWindowId === void 0 ? {} : { sourceWindowId: params.sourceWindowId }
24101
+ });
24102
+ }
24103
+ function freezeValue(value, seen = /* @__PURE__ */ new WeakMap()) {
24104
+ if (typeof value !== "object" || value === null) return value;
24105
+ const existing = seen.get(value);
24106
+ if (existing !== void 0) return existing;
24107
+ if (Array.isArray(value)) {
24108
+ const copy2 = [];
24109
+ seen.set(value, copy2);
24110
+ for (const item of value) copy2.push(freezeValue(item, seen));
24111
+ return Object.freeze(copy2);
24112
+ }
24113
+ const copy = {};
24114
+ seen.set(value, copy);
24115
+ for (const [key, item] of Object.entries(value)) copy[key] = freezeValue(item, seen);
24116
+ return Object.freeze(copy);
24117
+ }
24118
+
24119
+ // src/installed-napplet-catalog.ts
24120
+ function matchesInstalledNappletRecord(record2, target) {
24121
+ return target.id === record2.id && target.aggregateHash === record2.aggregateHash;
24122
+ }
24123
+ var InstalledNappletCatalog = class {
24124
+ records = /* @__PURE__ */ new Map();
24125
+ listeners = /* @__PURE__ */ new Set();
24126
+ /** Insert or replace a record from an already resolver-verified pointer. */
24127
+ install(resolved) {
24128
+ const record2 = freezeRecord({
24129
+ id: resolved.manifest.catalogId,
24130
+ dTag: resolved.dTag,
24131
+ aggregateHash: resolved.aggregateHash,
24132
+ pointer: copyPointer(resolved.pointer),
24133
+ ...resolved.manifest.title === void 0 ? {} : { title: resolved.manifest.title },
24134
+ requires: [...resolved.manifest.requires],
24135
+ optional: [...resolved.manifest.optional ?? []],
24136
+ archetypes: resolved.manifest.archetypes.map((archetype) => ({
24137
+ slug: archetype.slug,
24138
+ convention: archetype.convention,
24139
+ params: [...archetype.params]
24140
+ }))
24141
+ });
24142
+ const previous = this.records.get(record2.id);
24143
+ this.records.set(record2.id, record2);
24144
+ this.notify(record2.id, previous, record2);
24145
+ return record2;
24146
+ }
24147
+ /** Remove an artifact explicitly; frame teardown never calls this method. */
24148
+ remove(id) {
24149
+ const previous = this.records.get(id);
24150
+ const removed = this.records.delete(id);
24151
+ if (removed) this.notify(id, previous);
24152
+ return removed;
24153
+ }
24154
+ /** Return whether a verified installation exists for a catalog ID. */
24155
+ has(id) {
24156
+ return this.records.has(id);
24157
+ }
24158
+ /** Return immutable serializable installed-artifact facts. */
24159
+ installed() {
24160
+ return [...this.records.values()];
24161
+ }
24162
+ /** Return a verified record by catalog ID. */
24163
+ get(id) {
24164
+ return this.records.get(id);
24165
+ }
24166
+ /**
24167
+ * Atomically confirm that a resolved target still belongs to the exact record
24168
+ * selected before an async operation. The record object is the catalog version
24169
+ * token, so even a same-identity replacement cannot pass this check.
24170
+ */
24171
+ validateCurrent(selected, target) {
24172
+ if (this.records.get(selected.id) !== selected) return null;
24173
+ return matchesInstalledNappletRecord(selected, target) ? selected : null;
24174
+ }
24175
+ /**
24176
+ * Return declared handlers whose host environment can receive intent delivery.
24177
+ * @param canReceiveIntent - Resolve intent availability for each verified identity;
24178
+ * without host policy, return declared candidates for the host to filter.
24179
+ * @returns Named intent candidates usable under the supplied host policy.
24180
+ */
24181
+ intentCatalog(canReceiveIntent = () => true) {
24182
+ return this.installed().filter(canReceiveIntent).map((record2) => manifestToIntentCatalogEntry({
24183
+ catalogId: record2.id,
24184
+ ...record2.title === void 0 ? {} : { title: record2.title },
24185
+ archetypes: record2.archetypes.map((archetype) => ({
24186
+ slug: archetype.slug,
24187
+ convention: archetype.convention,
24188
+ params: [...archetype.params]
24189
+ }))
24190
+ }));
24191
+ }
24192
+ /** Subscribe to explicit install and artifact-removal changes. */
24193
+ onChanged(listener) {
24194
+ this.listeners.add(listener);
24195
+ return () => this.listeners.delete(listener);
24196
+ }
24197
+ notify(id, previous, current) {
24198
+ const archetypes = Object.freeze([.../* @__PURE__ */ new Set([
24199
+ ...(previous?.archetypes ?? []).map(({ slug }) => slug),
24200
+ ...(current?.archetypes ?? []).map(({ slug }) => slug)
24201
+ ])]);
24202
+ for (const listener of this.listeners) listener(id, archetypes);
24203
+ }
24204
+ };
24205
+ function copyPointer(pointer) {
24206
+ if (pointer.type === "naddr") {
24207
+ return Object.freeze({
24208
+ type: "naddr",
24209
+ value: pointer.value,
24210
+ identifier: pointer.identifier,
24211
+ pubkey: pointer.pubkey,
24212
+ kind: pointer.kind,
24213
+ relays: Object.freeze([...pointer.relays])
24214
+ });
24215
+ }
24216
+ return Object.freeze({
24217
+ type: "nevent",
24218
+ value: pointer.value,
24219
+ id: pointer.id,
24220
+ ...pointer.author === void 0 ? {} : { author: pointer.author },
24221
+ ...pointer.kind === void 0 ? {} : { kind: pointer.kind },
24222
+ relays: Object.freeze([...pointer.relays])
24223
+ });
24224
+ }
24225
+ function freezeRecord(record2) {
24226
+ return Object.freeze({
24227
+ ...record2,
24228
+ requires: Object.freeze([...record2.requires]),
24229
+ optional: Object.freeze([...record2.optional ?? []]),
24230
+ archetypes: Object.freeze(record2.archetypes.map((archetype) => Object.freeze({ ...archetype, params: Object.freeze([...archetype.params]) })))
24231
+ });
24232
+ }
24233
+
23704
24234
  // src/runtime-resolver.ts
23705
24235
  var PAJA_NAPPLET_MANIFEST_KINDS = NAPPLET_KINDS;
23706
24236
  function decodePajaPointer(value) {
@@ -25779,10 +26309,12 @@ function snapshotPajaBrowserState(state, runtime) {
25779
26309
  status: tab.status,
25780
26310
  initSent: tab.windowId ? runtime.readyWindowIds.has(tab.windowId) : false
25781
26311
  })),
25782
- messageLog: [...state.messageLog]
26312
+ messageLog: [...state.messageLog],
26313
+ relayEventCounts: state.relayEventCounts.snapshot(state.relayInventory()),
26314
+ relayInventory: state.relayInventory()
25783
26315
  };
25784
26316
  }
25785
- function createPajaBrowserState(context) {
26317
+ function createPajaBrowserState(context, relayEventCounts, relayInventory) {
25786
26318
  const {
25787
26319
  config,
25788
26320
  bridge,
@@ -25808,6 +26340,8 @@ function createPajaBrowserState(context) {
25808
26340
  status: "booting",
25809
26341
  messageFilter: "",
25810
26342
  messageLog: [],
26343
+ relayEventCounts,
26344
+ relayInventory,
25811
26345
  reload() {
25812
26346
  reloadPajaTarget(this, context);
25813
26347
  },
@@ -25877,6 +26411,8 @@ function createPajaBrowserState(context) {
25877
26411
  };
25878
26412
  }
25879
26413
  async function installPajaHost() {
26414
+ const disposeGamepadIndicators = installPajaGamepadIndicators();
26415
+ window.addEventListener("pagehide", disposeGamepadIndicators, { once: true });
25880
26416
  const disposeConsolePanel = installPajaConsolePanel();
25881
26417
  const disposeSidebarSections = installPajaSidebarSections();
25882
26418
  window.addEventListener("pagehide", disposeSidebarSections, { once: true });
@@ -25949,6 +26485,13 @@ async function installPajaHost() {
25949
26485
  getIdentity: getWindowIdentity,
25950
26486
  getInitialValues: () => ({ ...getSimulation().config.values })
25951
26487
  });
26488
+ const relayEventCounts = createPajaRelayEventCounter(() => {
26489
+ if (stateRef) renderPajaEventKindCounts(stateRef.relayEventCounts, stateRef.relayInventory());
26490
+ });
26491
+ const disposeEventCounterReset = installPajaEventCounterReset(relayEventCounts);
26492
+ const relayInventory = () => ({
26493
+ fallback: adapter.relayConfig.getRelayConfig().outbox
26494
+ });
25952
26495
  const adapter = createPajaAdapter(config, getSimulation, (theme) => {
25953
26496
  runtime.themeService = theme;
25954
26497
  }, themeBroadcast.onBroadcast, confirmationController.confirm, signerController, getWindowIdentity, () => stateRef?.reload(), {
@@ -25975,6 +26518,13 @@ async function installPajaHost() {
25975
26518
  return candidates.some((candidate) => candidate.id === id) ? id : void 0;
25976
26519
  }
25977
26520
  }, confirmationController.activation, notifyController?.serviceOptions, configController?.serviceOptions, resourceSettings.getServers);
26521
+ const relayBackend = adapter.relayPool.getRelayPool();
26522
+ relayBackend?.setRelayEventObserver((sighting) => {
26523
+ relayEventCounts.recordEvent(sighting.reason, sighting.event, sighting.sightedOn, sighting.origin);
26524
+ });
26525
+ relayBackend?.setRelayRequestObserver((request) => {
26526
+ relayEventCounts.recordRead(request.reason, request.relayUrls, request.origin);
26527
+ });
25978
26528
  await adapter.ready;
25979
26529
  const bridge = createShellBridge(adapter);
25980
26530
  const stopIdentityChanges = signerController.subscribe(() => {
@@ -26001,7 +26551,7 @@ async function installPajaHost() {
26001
26551
  setStatus: (state2, status) => setStatus(state2, status)
26002
26552
  };
26003
26553
  contextRef = context;
26004
- const state = createPajaBrowserState(context);
26554
+ const state = createPajaBrowserState(context, relayEventCounts, relayInventory);
26005
26555
  stateRef = state;
26006
26556
  const stopIntentCatalogChanges = subscribePajaIntentCatalogChanges(state, context);
26007
26557
  window.addEventListener("pagehide", stopIntentCatalogChanges, { once: true });
@@ -26023,6 +26573,7 @@ async function installPajaHost() {
26023
26573
  window.addEventListener("pagehide", () => notifyController?.dispose(), { once: true });
26024
26574
  window.addEventListener("pagehide", () => configController?.dispose(), { once: true });
26025
26575
  window.addEventListener("pagehide", disposeConsolePanel, { once: true });
26576
+ window.addEventListener("pagehide", disposeEventCounterReset, { once: true });
26026
26577
  window.addEventListener("pagehide", resourceSettings.dispose, { once: true });
26027
26578
  window.__KEHTO_PAJA__ = state;
26028
26579
  window.addEventListener("message", (event) => {
@@ -26075,6 +26626,7 @@ async function installPajaHost() {
26075
26626
  setDefault(archetype, id) {
26076
26627
  runtime.intentDefaults.set(archetype, id);
26077
26628
  writePajaIntentDefaults(runtime.intentDefaults);
26629
+ adapter.notifyIntentChanged(archetype);
26078
26630
  },
26079
26631
  onAccepted() {
26080
26632
  const url = new URL(window.location.href);