@ekrooh/bare 0.6.1 → 0.7.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.
@@ -1,60 +1,73 @@
1
+ import { a as isCanonicalErrorCode, c as MAX_HEADER_BYTES, i as CoreError, l as MessageType, n as err, o as ErrorCode, s as MAX_FRAME_BYTES } from "./errors-Bl5w-m62.mjs";
1
2
  import { TextDecoder as TextDecoder$1, TextEncoder as TextEncoder$1 } from "bare-encoding";
2
- // core/messages/constants.ts
3
- const VERSION = 1;
4
- const MessageType = { ENVELOPE: 1 };
5
- /** Canonical error codes. Everything the framework throws uses these; peers
6
- * may carry arbitrary codes over the wire, and consumers may return app-scoped
7
- * codes (e.g. `app.photos/not-found`) which are preserved verbatim. Keep
8
- * `android/src/main/.../ErrorCodes.kt` in sync with the canonical union. */
9
- const ErrorCode = {
10
- UNSUPPORTED_CAPABILITY: "UNSUPPORTED_CAPABILITY",
11
- UNSUPPORTED_EVENT: "UNSUPPORTED_EVENT",
12
- HOST_ERROR: "HOST_ERROR",
13
- TRANSPORT_ERROR: "TRANSPORT_ERROR",
14
- PLUGIN_ERROR: "PLUGIN_ERROR",
15
- INVALID_RESPONSE: "INVALID_RESPONSE",
16
- FRAME_TOO_LARGE: "FRAME_TOO_LARGE",
17
- FRAME_INVALID: "FRAME_INVALID",
18
- TIMEOUT: "TIMEOUT"
19
- };
20
- /** A JSON header must fit a 16-bit big-endian length field. */
21
- const MAX_HEADER_BYTES = 65535;
22
- /** Upper bound on one encoded frame. Large binary transfers are a plugin-level
23
- * concern (out-of-band handles), not an in-band payload. */
24
- const MAX_FRAME_BYTES = 16777216;
25
- // core/messages/types.ts
26
- var CoreError = class extends Error {
27
- code;
28
- constructor(code, message) {
29
- super(message);
30
- this.name = "CoreError";
31
- this.code = code;
3
+ /** UTF-8 byte length of `str`, without a `TextEncoder` (Bare has no global
4
+ * one). A lone surrogate counts as the 3-byte U+FFFD an encoder writes. */
5
+ function utf8ByteLength(str) {
6
+ let bytes = 0;
7
+ for (let i = 0; i < str.length; i++) {
8
+ const unit = str.charCodeAt(i);
9
+ if (unit < 128) bytes += 1;
10
+ else if (unit < 2048) bytes += 2;
11
+ else if (unit >= 55296 && unit <= 56319 && i + 1 < str.length) {
12
+ const next = str.charCodeAt(i + 1);
13
+ if (next >= 56320 && next <= 57343) {
14
+ bytes += 4;
15
+ i++;
16
+ } else bytes += 3;
17
+ } else bytes += 3;
18
+ }
19
+ return bytes;
20
+ }
21
+ /** Whether `value` is a string within {@link MAX_ID_LENGTH} UTF-8 bytes. */
22
+ function isShortId(value) {
23
+ if (typeof value !== "string") return false;
24
+ if (value.length * 3 <= 256) return true;
25
+ return value.length <= 256 && utf8ByteLength(value) <= 256;
26
+ }
27
+ /** A correctly delimited frame whose content is invalid (not UTF-8, not JSON,
28
+ * an unknown header type, an over-long id, an over-deep value). The stream is
29
+ * still in sync after it, so only this frame is dropped. */
30
+ var FrameContentError = class extends CoreError {
31
+ recovered;
32
+ constructor(message, recovered) {
33
+ super(ErrorCode.FRAME_INVALID, message);
34
+ this.name = "FrameContentError";
35
+ this.recovered = recovered;
32
36
  }
33
37
  };
34
- // core/messages/errors.ts
35
- /** Success half of an `Either` tuple. */
36
- function ok(result) {
37
- return [null, result];
38
- }
39
- /** Failure half of an `Either` tuple. Accepts a canonical error code or any
40
- * app-scoped code (`app.photos/not-found`) — the code is preserved verbatim. */
41
- function err(code, message) {
42
- return [new CoreError(code, message), null];
43
- }
44
- /** Convenience for constructing a `CoreError` from a possibly-non-canonical
45
- * wire code: preserves known codes, maps anything else to `PLUGIN_ERROR`.
46
- * Framework callers that want app codes preserved construct the error
47
- * directly instead. */
48
- function coerceErrorCode(code) {
49
- if (code && code in ErrorCode) return code;
50
- return ErrorCode.PLUGIN_ERROR;
38
+ // core/messages/timers.ts
39
+ /** Largest delay `setTimeout` honours. A larger one overflows its 32-bit
40
+ * signed field and fires almost at once, turning a long deadline into an
41
+ * immediate timeout. */
42
+ const MAX_TIMER_MS = 2 ** 31 - 1;
43
+ /** A usable timer delay: `value` when it is a finite number above 0 (capped
44
+ * at {@link MAX_TIMER_MS}), otherwise `fallback`. */
45
+ function timerMs(value, fallback) {
46
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return Math.min(fallback, MAX_TIMER_MS);
47
+ return Math.min(value, MAX_TIMER_MS);
51
48
  }
52
49
  // core/messages/plugin-kernel.ts
50
+ /** A plugin id is two or more dot-separated segments of letters, digits, `-`
51
+ * and `_` (`app.photos`), at most {@link MAX_ID_LENGTH} bytes. */
52
+ const PLUGIN_ID_PATTERN = /^[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)+$/;
53
+ /** Namespaces the framework owns. A consumer plugin there could shadow a
54
+ * framework plugin, or collide with one a later release adds. */
55
+ const RESERVED_PLUGIN_NAMESPACES = ["core.", "vendor."];
56
+ /** The framework's own plugins: the only ids allowed in a reserved namespace. */
57
+ const FRAMEWORK_PLUGIN_IDS = /* @__PURE__ */ new Set([
58
+ "core.health",
59
+ "core.discovery",
60
+ "core.permissions",
61
+ "core.logs",
62
+ "vendor.media"
63
+ ]);
53
64
  function createPluginRegistry() {
54
65
  const plugins = /* @__PURE__ */ new Map();
55
66
  return {
56
67
  register(plugin) {
57
- if (!plugin.id.includes(".")) throw new Error(`plugin id must be namespaced (example: "vendor.plugin"), got "${plugin.id}"`);
68
+ const id = plugin.id;
69
+ if (typeof id !== "string" || !isShortId(id) || !PLUGIN_ID_PATTERN.test(id)) throw new Error(`plugin id must be namespaced (example: "app.photos": dot-separated letters, digits, "-" or "_"), got "${String(id).slice(0, 256)}"`);
70
+ if (RESERVED_PLUGIN_NAMESPACES.some((ns) => id.startsWith(ns)) && !FRAMEWORK_PLUGIN_IDS.has(id)) throw new Error(`plugin id "${id}" is in a namespace reserved for framework plugins (core.*, vendor.*); use your own namespace, e.g. "app.${id.slice(id.indexOf(".") + 1)}"`);
58
71
  if (plugins.has(plugin.id)) throw new Error(`plugin id "${plugin.id}" is already registered`);
59
72
  plugins.set(plugin.id, plugin);
60
73
  },
@@ -98,9 +111,29 @@ function declaresEvent(plugin, event) {
98
111
  function createPluginRouter(registry, runtime, options) {
99
112
  const logger = options?.logger ?? console;
100
113
  const maxInflight = options?.maxInflight ?? DEFAULT_MAX_INFLIGHT;
114
+ const maxPerChannel = options?.maxInflightPerChannel ?? Math.max(1, Math.floor(maxInflight * 3 / 4));
115
+ const maxPerPlugin = options?.maxInflightPerPlugin ?? maxInflight;
101
116
  const serialPlugins = new Set(options?.serialPlugins);
102
117
  const serialTails = /* @__PURE__ */ new Map();
103
118
  let inflight = 0;
119
+ const inflightByChannel = /* @__PURE__ */ new Map();
120
+ const inflightByPlugin = /* @__PURE__ */ new Map();
121
+ const bump = (map, key, by) => {
122
+ const next = (map.get(key) ?? 0) + by;
123
+ if (next <= 0) map.delete(key);
124
+ else map.set(key, next);
125
+ };
126
+ /** Logs the detail of a thrown error and returns what the peer may see: the
127
+ * code of a canonical `CoreError`, otherwise `fallback`, and a fixed
128
+ * message. Raw exception text (paths, internals) never reaches the page. */
129
+ function thrownError(e, fallback, what) {
130
+ const detail = e instanceof Error ? e.message : String(e);
131
+ logger.error(`${what} failed: ${detail}`);
132
+ const code = e instanceof CoreError && isCanonicalErrorCode(e.code) ? e.code : fallback;
133
+ if (code === ErrorCode.TIMEOUT) return new CoreError(code, `${what} timed out`);
134
+ if (code === ErrorCode.UNSUPPORTED_EVENT) return new CoreError(code, `Unsupported event ${what} on ${runtime}`);
135
+ return new CoreError(code, `${what} failed`);
136
+ }
104
137
  const capsTtlMs = options?.hostCapabilitiesTtlMs ?? DEFAULT_HOST_CAPABILITIES_TTL_MS;
105
138
  let capsCache = null;
106
139
  let capsInflight = null;
@@ -175,9 +208,7 @@ function createPluginRouter(registry, runtime, options) {
175
208
  });
176
209
  return null;
177
210
  } catch (e) {
178
- const error = new CoreError(ErrorCode.PLUGIN_ERROR, e instanceof Error ? e.message : String(e));
179
- logger.error(`dispatch ${header.pluginId}.${header.event} failed: ${error.message}`);
180
- return invokeErrorResponse(header, error);
211
+ return invokeErrorResponse(header, thrownError(e, ErrorCode.PLUGIN_ERROR, `${header.pluginId}.${header.event}`));
181
212
  }
182
213
  }
183
214
  if (isPluginInvokeRequestHeader(header)) {
@@ -200,13 +231,11 @@ function createPluginRouter(registry, runtime, options) {
200
231
  } : void 0
201
232
  };
202
233
  } catch (e) {
203
- const error = new CoreError(ErrorCode.PLUGIN_ERROR, e instanceof Error ? e.message : String(e));
204
- logger.error(`invoke ${header.pluginId}.${header.event} failed: ${error.message}`);
205
- return invokeErrorResponse(header, error);
234
+ return invokeErrorResponse(header, thrownError(e, ErrorCode.PLUGIN_ERROR, `${header.pluginId}.${header.event}`));
206
235
  }
207
236
  if (header.requestId && options?.delegateToHost) try {
208
237
  if (await hostAnnounces(header.pluginId, header.event)) {
209
- const delegated = await options.delegateToHost(header, payload);
238
+ const delegated = await options.delegateToHost(header, payload, hostTimeoutFor(plugin, header.event));
210
239
  if (delegated) {
211
240
  const code = delegated.error?.code;
212
241
  if (code === ErrorCode.UNSUPPORTED_CAPABILITY || code === ErrorCode.UNSUPPORTED_EVENT) capsCache = null;
@@ -216,24 +245,33 @@ function createPluginRouter(registry, runtime, options) {
216
245
  }
217
246
  } catch (e) {
218
247
  capsCache = null;
219
- return invokeErrorResponse(header, new CoreError(ErrorCode.HOST_ERROR, e instanceof Error ? e.message : String(e)));
248
+ return invokeErrorResponse(header, thrownError(e, ErrorCode.HOST_ERROR, `${header.pluginId}.${header.event}`));
220
249
  }
221
250
  return invokeErrorResponse(header, new CoreError(ErrorCode.UNSUPPORTED_CAPABILITY, `Unsupported capability ${header.pluginId}.${header.event} on ${runtime}`));
222
251
  }
223
252
  return null;
224
253
  }
225
- return { async route(header, payload) {
254
+ return { async route(header, payload, context) {
226
255
  if (!isPluginEnvelopeHeader(header)) return routeNow(header, payload);
227
- if (inflight >= maxInflight) {
228
- const error = new CoreError(ErrorCode.TRANSPORT_ERROR, `too many calls in flight (limit ${maxInflight}); retry later`);
256
+ const busy = (limit, scope) => {
257
+ const error = new CoreError(ErrorCode.TRANSPORT_ERROR, `too many calls in flight${scope} (limit ${limit}); retry later`);
229
258
  logger.warn(`${header.pluginId}.${header.event}: ${error.message}`);
230
259
  return invokeErrorResponse(header, error);
231
- }
260
+ };
261
+ if (inflight >= maxInflight) return busy(maxInflight, "");
262
+ const channel = context?.channel;
263
+ if (channel !== void 0 && (inflightByChannel.get(channel) ?? 0) >= maxPerChannel) return busy(maxPerChannel, " on this channel");
264
+ const pluginKey = registry.get(header.pluginId) ? header.pluginId : void 0;
265
+ if (pluginKey !== void 0 && (inflightByPlugin.get(pluginKey) ?? 0) >= maxPerPlugin) return busy(maxPerPlugin, " for this plugin");
232
266
  inflight++;
267
+ if (channel !== void 0) bump(inflightByChannel, channel, 1);
268
+ if (pluginKey !== void 0) bump(inflightByPlugin, pluginKey, 1);
233
269
  try {
234
270
  return serialPlugins.has(header.pluginId) ? await runSerial(header.pluginId, () => routeNow(header, payload)) : await routeNow(header, payload);
235
271
  } finally {
236
272
  inflight--;
273
+ if (channel !== void 0) bump(inflightByChannel, channel, -1);
274
+ if (pluginKey !== void 0) bump(inflightByPlugin, pluginKey, -1);
237
275
  }
238
276
  } };
239
277
  }
@@ -268,6 +306,13 @@ function createPluginBus(messenger) {
268
306
  }
269
307
  };
270
308
  }
309
+ /** The manifest's host deadline for `event`, read as an own property. */
310
+ function hostTimeoutFor(plugin, event) {
311
+ const timeouts = plugin?.hostTimeoutsMs;
312
+ if (!timeouts || !Object.prototype.hasOwnProperty.call(timeouts, event)) return;
313
+ const value = timeouts[event];
314
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.min(value, MAX_TIMER_MS) : void 0;
315
+ }
271
316
  function invokeErrorResponse(header, error) {
272
317
  return {
273
318
  type: "INVOKE_RESPONSE",
@@ -332,6 +377,7 @@ function webRandomBytes() {
332
377
  const MAX_CONCURRENT_INVOKES = 1024;
333
378
  function createProtocolMessenger(send, options = {}) {
334
379
  const platform = resolvePlatform(options.platform);
380
+ const diagnostics = options.diagnostics === true;
335
381
  const withRequestId = (request) => ({
336
382
  ...request,
337
383
  requestId: createRequestId(platform)
@@ -350,20 +396,24 @@ function createProtocolMessenger(send, options = {}) {
350
396
  return new Promise((resolvePromise, rejectPromise) => {
351
397
  const fail = async (reason) => {
352
398
  console.error(`[invoke] ${reason}`);
399
+ if (!diagnostics) {
400
+ rejectPromise(new Error(reason));
401
+ return;
402
+ }
353
403
  const tail = await sharedLogTail();
354
404
  rejectPromise(new Error(tail ? `${reason}; recent logs: ${tail}` : reason));
355
405
  };
356
406
  const timer = setTimeout(() => {
357
407
  pending.delete(requestId);
358
408
  fail(`invoke timeout for ${request.type} (${requestId})`);
359
- }, timeoutMs);
409
+ }, timerMs(timeoutMs, 5e3));
360
410
  if (pending.size >= MAX_CONCURRENT_INVOKES) {
361
411
  const oldest = pending.keys().next().value;
362
412
  if (oldest !== void 0) {
363
413
  const dropped = pending.get(oldest);
364
414
  if (dropped) {
365
415
  clearTimeout(dropped.timer);
366
- dropped.reject(/* @__PURE__ */ new Error(`invoke dropped: too many concurrent invokes (${requestId})`));
416
+ dropped.reject(/* @__PURE__ */ new Error(`invoke dropped: too many concurrent invokes (${oldest})`));
367
417
  }
368
418
  pending.delete(oldest);
369
419
  }
@@ -457,7 +507,7 @@ async function serverLogTail() {
457
507
  * frame cap. The frame prefix is `[version][type][headerLenHi][headerLenLo]
458
508
  * [payloadLenHi][payloadLenMid][payloadLenLo]`, so the floor is
459
509
  * 7 + MAX_HEADER_BYTES. */
460
- const MIN_FRAME_BYTES = 65542;
510
+ const MIN_FRAME_BYTES = MAX_HEADER_BYTES + 7;
461
511
  function clampFrameBytes(value) {
462
512
  return Math.min(Math.max(Number.isFinite(value) ? Math.floor(value) : MAX_FRAME_BYTES, MIN_FRAME_BYTES), MAX_FRAME_BYTES);
463
513
  }
@@ -534,7 +584,7 @@ var MessageProtocol = class {
534
584
  try {
535
585
  console.debug("[wire] header frame is not valid UTF-8");
536
586
  } catch {}
537
- throw new CoreError(ErrorCode.FRAME_INVALID, "FRAME_INVALID: header frame is not valid UTF-8");
587
+ throw new FrameContentError("FRAME_INVALID: header frame is not valid UTF-8");
538
588
  }
539
589
  return {
540
590
  type,
@@ -547,10 +597,41 @@ const KNOWN_MESSAGE_TYPES = new Set(Object.values(MessageType));
547
597
  function isKnownMessageType(type) {
548
598
  return KNOWN_MESSAGE_TYPES.has(type);
549
599
  }
600
+ function shortString(value) {
601
+ return isShortId(value) ? value : void 0;
602
+ }
603
+ function recoverHeader(header) {
604
+ return {
605
+ type: shortString(header.type),
606
+ requestId: shortString(header.requestId),
607
+ pluginId: shortString(header.pluginId),
608
+ event: shortString(header.event)
609
+ };
610
+ }
550
611
  function parseAndValidateHeader(headerJson) {
551
- const parsed = JSON.parse(headerJson);
552
- if (!parsed || typeof parsed !== "object") throw new Error("Invalid header: expected object");
612
+ let parsed;
613
+ try {
614
+ parsed = JSON.parse(headerJson);
615
+ } catch {
616
+ throw new FrameContentError("FRAME_INVALID: header is not valid JSON");
617
+ }
618
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new FrameContentError("Invalid header: expected object");
553
619
  const header = parsed;
620
+ try {
621
+ return validateHeader(header);
622
+ } catch (err) {
623
+ throw new FrameContentError(err instanceof Error ? err.message : String(err), recoverHeader(header));
624
+ }
625
+ }
626
+ function validateHeader(header) {
627
+ for (const field of [
628
+ "requestId",
629
+ "pluginId",
630
+ "event"
631
+ ]) {
632
+ const value = header[field];
633
+ if (typeof value === "string" && !isShortId(value)) throw new Error(`FRAME_INVALID: ${field} longer than 256 UTF-8 bytes`);
634
+ }
554
635
  switch (header.type) {
555
636
  case "DISPATCH":
556
637
  if (isValidPluginHeaderFields(header)) return mergeHeader(header, {
@@ -590,7 +671,8 @@ function parseAndValidateHeader(headerJson) {
590
671
  if (typeof header.requestId === "string") return mergeHeader(header, {
591
672
  type: "HOST_CAPABILITIES_RESPONSE",
592
673
  requestId: header.requestId,
593
- capabilities: parseCapabilityDescriptors(header.capabilities)
674
+ capabilities: parseCapabilityDescriptors(header.capabilities),
675
+ error: parseCoreErrorWire(header.error)
594
676
  });
595
677
  break;
596
678
  case "HOST_INVOKE_REQUEST":
@@ -611,7 +693,7 @@ function parseAndValidateHeader(headerJson) {
611
693
  error: parseCoreErrorWire(header.error)
612
694
  });
613
695
  }
614
- throw new Error(`Unsupported header type: ${String(header.type)}`);
696
+ throw new Error(`Unsupported header type: ${String(header.type).slice(0, 64)}`);
615
697
  }
616
698
  /** Only allowlisted, schema-known fields are carried forward. Unknown wire
617
699
  * fields are dropped so attacker-controlled keys (e.g. `__proto__` or an
@@ -708,35 +790,49 @@ function parseCapabilityDescriptors(value) {
708
790
  function definePlugin(id, specs, options = {}) {
709
791
  const invokeByEvent = /* @__PURE__ */ new Map();
710
792
  const dispatchByEvent = /* @__PURE__ */ new Map();
793
+ const validators = /* @__PURE__ */ new Map();
794
+ const hostTimeoutsMs = Object.create(null);
711
795
  const events = [];
712
796
  for (const key of Object.keys(specs)) {
713
797
  const spec = specs[key];
714
798
  if (spec.pluginId !== id) throw new Error(`event spec ${spec.name} belongs to ${spec.pluginId}, not ${id}`);
715
799
  events.push(spec.name);
800
+ if (spec.validate) validators.set(spec.name, spec.validate);
801
+ if (typeof spec.hostTimeoutMs === "number" && Number.isFinite(spec.hostTimeoutMs) && spec.hostTimeoutMs > 0) hostTimeoutsMs[spec.name] = Math.min(spec.hostTimeoutMs, MAX_TIMER_MS);
716
802
  const invoker = options.invoke?.[key];
717
803
  if (invoker) invokeByEvent.set(spec.name, invoker);
718
804
  const dispatcher = options.dispatch?.[key];
719
805
  if (dispatcher) dispatchByEvent.set(spec.name, dispatcher);
720
806
  }
807
+ /** False when the event's spec has a validator and `args` fails it. */
808
+ const argsValid = (event, args) => {
809
+ const validate = validators.get(event);
810
+ return validate ? validate(args) === true : true;
811
+ };
812
+ const invalidArgs = (event) => `Invalid arguments for ${id}.${event}`;
721
813
  const adapter = {};
722
814
  if (invokeByEvent.size > 0) adapter.invoke = (event, args, context) => {
723
815
  const handler = invokeByEvent.get(event);
724
- if (!handler) throw new Error(`Unhandled invoke event ${event}`);
816
+ if (!handler) return err(ErrorCode.UNSUPPORTED_EVENT, `Unsupported event ${id}.${event} on ${context.runtime}`);
817
+ if (!argsValid(event, args)) return err(ErrorCode.PLUGIN_ERROR, invalidArgs(event));
725
818
  return handler(args, context);
726
819
  };
727
820
  if (dispatchByEvent.size > 0) adapter.dispatch = (event, args, context) => {
728
821
  const handler = dispatchByEvent.get(event);
729
- if (!handler) throw new Error(`Unhandled dispatch event ${event}`);
822
+ if (!handler) throw new CoreError(ErrorCode.UNSUPPORTED_EVENT, `Unsupported event ${id}.${event} on ${context.runtime}`);
823
+ if (!argsValid(event, args)) throw new CoreError(ErrorCode.PLUGIN_ERROR, invalidArgs(event));
730
824
  return handler(args, context);
731
825
  };
732
826
  const runtimes = {};
733
827
  if (invokeByEvent.size > 0 || dispatchByEvent.size > 0) runtimes.bare = adapter;
734
- return {
828
+ const manifest = {
735
829
  id,
736
830
  capabilities: options.capabilities,
737
831
  events,
738
832
  runtimes
739
833
  };
834
+ if (Object.keys(hostTimeoutsMs).length > 0) manifest.hostTimeoutsMs = hostTimeoutsMs;
835
+ return manifest;
740
836
  }
741
837
  /** Typed builder: an invoke envelope for a spec's event. */
742
838
  function invokeEvent(spec, args, payload, timeoutMs) {
@@ -766,7 +862,7 @@ function createBareRuntimeContext(plugins = [], routerOptions) {
766
862
  const textDecoder = new TextDecoder$1();
767
863
  const protocol = new MessageProtocol({
768
864
  encode: (str) => textEncoder.encode(str),
769
- decode: (bytes) => textDecoder.decode(bytes)
865
+ decode: (bytes) => strictUtf8(bytes, textDecoder.decode(bytes), textEncoder)
770
866
  });
771
867
  const pluginRegistry = createPluginRegistry();
772
868
  for (const plugin of plugins) pluginRegistry.register(plugin);
@@ -776,6 +872,19 @@ function createBareRuntimeContext(plugins = [], routerOptions) {
776
872
  pluginRouter: createPluginRouter(pluginRegistry, runtime, routerOptions)
777
873
  };
778
874
  }
875
+ /** Bare's `TextDecoder` has no `fatal` mode: it substitutes U+FFFD for invalid
876
+ * UTF-8. Decoding is strict on every other runtime, so a header that only
877
+ * decodes by substitution is refused here too (the codec turns the throw into
878
+ * `FRAME_INVALID`). A decoded string holds U+FFFD either because the bytes
879
+ * held one (EF BF BD) or because the decoder substituted it; re-encoding tells
880
+ * them apart, and only strings that contain one pay for it. */
881
+ function strictUtf8(bytes, decoded, encoder) {
882
+ if (!decoded.includes("�")) return decoded;
883
+ const roundTrip = encoder.encode(decoded);
884
+ if (roundTrip.byteLength !== bytes.byteLength) throw new TypeError("invalid UTF-8");
885
+ for (let i = 0; i < bytes.byteLength; i++) if (roundTrip[i] !== bytes[i]) throw new TypeError("invalid UTF-8");
886
+ return decoded;
887
+ }
779
888
  // core/logs/capture-web.ts
780
889
  function safeStringify(value) {
781
890
  if (typeof value === "string") return value;
@@ -863,4 +972,4 @@ function installWebConsoleCapture(options = {}) {
863
972
  }
864
973
  };
865
974
  }
866
- export { MAX_FRAME_BYTES as _, invokeEvent as a, VERSION as b, createRequestId as c, createPluginRouter as d, coerceErrorCode as f, ErrorCode as g, CoreError as h, dispatchEvent as i, createPluginBus as l, ok as m, createBareRuntimeContext as n, MessageProtocol as o, err as p, definePlugin as r, createProtocolMessenger as s, installWebConsoleCapture as t, createPluginRegistry as u, MAX_HEADER_BYTES as v, MessageType as y };
975
+ export { invokeEvent as a, createRequestId as c, createPluginRouter as d, timerMs as f, dispatchEvent as i, createPluginBus as l, isShortId as m, createBareRuntimeContext as n, MessageProtocol as o, FrameContentError as p, definePlugin as r, createProtocolMessenger as s, installWebConsoleCapture as t, createPluginRegistry as u };
@@ -0,0 +1,111 @@
1
+ import { n as err, o as ErrorCode, r as ok } from "./errors-Bl5w-m62.mjs";
2
+ import { r as definePlugin } from "./messages-BxviiFuh.mjs";
3
+ import { discoverySpecs } from "./plugins-discovery-events.mjs";
4
+ import { healthSpecs } from "./plugins-health-events.mjs";
5
+ import { logsSpecs } from "./plugins-logs-events.mjs";
6
+ import { permissionSpecs } from "./plugins-permissions-events.mjs";
7
+ // plugins/discovery/plugin.ts
8
+ function mergeCapabilityRows(a, b) {
9
+ const map = /* @__PURE__ */ new Map();
10
+ for (const row of [...a, ...b]) {
11
+ const existing = map.get(row.pluginId);
12
+ if (!existing) map.set(row.pluginId, {
13
+ pluginId: row.pluginId,
14
+ capabilities: [...row.capabilities],
15
+ events: [...row.events],
16
+ runtimes: [...row.runtimes]
17
+ });
18
+ else {
19
+ const ev = /* @__PURE__ */ new Set([...existing.events, ...row.events]);
20
+ const rt = /* @__PURE__ */ new Set([...existing.runtimes, ...row.runtimes]);
21
+ const caps = /* @__PURE__ */ new Set([...existing.capabilities, ...row.capabilities]);
22
+ map.set(row.pluginId, {
23
+ pluginId: row.pluginId,
24
+ capabilities: [...caps],
25
+ events: [...ev],
26
+ runtimes: [...rt]
27
+ });
28
+ }
29
+ }
30
+ return [...map.values()];
31
+ }
32
+ function createDiscoveryPlugin(deps) {
33
+ return definePlugin("core.discovery", discoverySpecs, {
34
+ capabilities: ["discovery"],
35
+ invoke: { list: async () => {
36
+ const merged = mergeCapabilityRows(deps.listBareCapabilities(), await deps.queryHostCapabilities());
37
+ return ok({
38
+ schemaVersion: 1,
39
+ capabilities: merged
40
+ });
41
+ } }
42
+ });
43
+ }
44
+ // plugins/health/plugin.ts
45
+ function createHealthPlugin() {
46
+ return definePlugin("core.health", healthSpecs, {
47
+ capabilities: ["health"],
48
+ invoke: {
49
+ ping: (args) => ok({
50
+ message: args?.message ?? "pong",
51
+ ts: Date.now()
52
+ }),
53
+ payloadEcho: (args, context) => ok({
54
+ label: args?.label ?? "payload",
55
+ payloadSize: context.payload.byteLength
56
+ }),
57
+ roundtrip: () => ok({
58
+ pong: true,
59
+ ts: Date.now()
60
+ })
61
+ }
62
+ });
63
+ }
64
+ // plugins/logs/args.ts
65
+ /** Internal (not an `exports` entry): runtime checks for `logs.view` args.
66
+ * Event specs are types only, so the page can send any JSON value. */
67
+ const LOG_LEVELS = [
68
+ "debug",
69
+ "info",
70
+ "warn",
71
+ "error"
72
+ ];
73
+ const LOG_SOURCES = ["backend", "web"];
74
+ function isLogLevel(value) {
75
+ return LOG_LEVELS.includes(value);
76
+ }
77
+ function isLogSource(value) {
78
+ return LOG_SOURCES.includes(value);
79
+ }
80
+ const LOGS_VIEW_DEFAULT_TAIL = 20;
81
+ function createLogsPlugin(deps) {
82
+ return definePlugin("core.logs", logsSpecs, {
83
+ capabilities: ["logs"],
84
+ invoke: {
85
+ view: (args) => {
86
+ const rawTail = args?.tail;
87
+ if (rawTail !== void 0 && (typeof rawTail !== "number" || !Number.isFinite(rawTail))) return err(ErrorCode.PLUGIN_ERROR, "logs.view: tail must be a number");
88
+ const level = args?.level;
89
+ if (level !== void 0 && !isLogLevel(level)) return err(ErrorCode.PLUGIN_ERROR, "logs.view: unknown level");
90
+ const source = args?.source;
91
+ if (source !== void 0 && !isLogSource(source)) return err(ErrorCode.PLUGIN_ERROR, "logs.view: unknown source");
92
+ const tail = rawTail === void 0 ? LOGS_VIEW_DEFAULT_TAIL : Math.max(0, Math.min(Math.trunc(rawTail), 100));
93
+ return ok({ entries: deps.store.view({
94
+ tail,
95
+ level,
96
+ source
97
+ }) });
98
+ },
99
+ clear: () => ok({ cleared: deps.store.clear() })
100
+ }
101
+ });
102
+ }
103
+ // plugins/permissions/plugin.ts
104
+ /**
105
+ * Declares host-only permission events. Handlers are registered on the Android host
106
+ * via {@code HostPluginRegistry}; the worklet delegates invokes here over IPC.
107
+ */
108
+ function createPermissionsPluginStub() {
109
+ return definePlugin("core.permissions", permissionSpecs, { capabilities: ["permissions"] });
110
+ }
111
+ export { createDiscoveryPlugin as i, createLogsPlugin as n, createHealthPlugin as r, createPermissionsPluginStub as t };
@@ -1,4 +1,4 @@
1
- import { I as CapabilityDescriptor, K as InvokeEnvelope } from "./index-Do-kTNXw.mjs";
1
+ import { d as InvokeEnvelope, t as CapabilityDescriptor } from "./types-BC39OoZB.mjs";
2
2
  export type DiscoveryListResult = {
3
3
  schemaVersion: 1;
4
4
  capabilities: CapabilityDescriptor[];
@@ -1,4 +1,4 @@
1
- import { a as invokeEvent } from "./messages-CMNIFMFY.mjs";
1
+ import { a as invokeEvent } from "./messages-BxviiFuh.mjs";
2
2
  // plugins/discovery/events.ts
3
3
  const discoverySpecs = { list: {
4
4
  pluginId: "core.discovery",
@@ -1,4 +1,4 @@
1
- import { K as InvokeEnvelope } from "./index-Do-kTNXw.mjs";
1
+ import { d as InvokeEnvelope } from "./types-BC39OoZB.mjs";
2
2
  export declare const healthSpecs: {
3
3
  readonly ping: {
4
4
  readonly pluginId: 'core.health';
@@ -1,4 +1,4 @@
1
- import { a as invokeEvent } from "./messages-CMNIFMFY.mjs";
1
+ import { a as invokeEvent } from "./messages-BxviiFuh.mjs";
2
2
  // plugins/health/events.ts
3
3
  const healthSpecs = {
4
4
  ping: {
@@ -1,4 +1,5 @@
1
- import { K as InvokeEnvelope, i as LogSource, n as LogEntry, r as LogLevel } from "./index-Do-kTNXw.mjs";
1
+ import { d as InvokeEnvelope } from "./types-BC39OoZB.mjs";
2
+ import { i as LogSource, n as LogEntry, r as LogLevel } from "./index-B3AmX7mC.mjs";
2
3
  export type LogsViewArgs = {
3
4
  /** Most-recent N matching entries. Defaults to a small window. */
4
5
  tail?: number;
@@ -1,4 +1,4 @@
1
- import { a as invokeEvent } from "./messages-CMNIFMFY.mjs";
1
+ import { a as invokeEvent } from "./messages-BxviiFuh.mjs";
2
2
  // plugins/logs/events.ts
3
3
  const logsSpecs = {
4
4
  view: {
@@ -1,4 +1,4 @@
1
- import { K as InvokeEnvelope } from "./index-Do-kTNXw.mjs";
1
+ import { d as InvokeEnvelope } from "./types-BC39OoZB.mjs";
2
2
  export type MediaKind = 'image' | 'video';
3
3
  export type MediaResult = {
4
4
  /** URL served by the worklet's loopback HTTP server (no bytes on the wire). */
@@ -1,26 +1 @@
1
- import { a as invokeEvent } from "./messages-CMNIFMFY.mjs";
2
- // plugins/media/events.ts
3
- const MEDIA_INVOKE_TIMEOUT_MS = 3e5;
4
- const mediaSpecs = {
5
- pick: {
6
- pluginId: "vendor.media",
7
- name: "media.pick",
8
- args: {},
9
- result: {}
10
- },
11
- capture: {
12
- pluginId: "vendor.media",
13
- name: "media.capture",
14
- args: {},
15
- result: {}
16
- }
17
- };
18
- const mediaEvents = { media: {
19
- pick(kind = "image") {
20
- return invokeEvent(mediaSpecs.pick, { kind }, null, MEDIA_INVOKE_TIMEOUT_MS);
21
- },
22
- capture(kind = "image") {
23
- return invokeEvent(mediaSpecs.capture, { kind }, null, MEDIA_INVOKE_TIMEOUT_MS);
24
- }
25
- } };
26
- export { mediaEvents, mediaSpecs };
1
+ export { t as mediaEvents, n as mediaSpecs } from "./events-DUGMT3B9.mjs";
@@ -1,4 +1,4 @@
1
- import { K as InvokeEnvelope } from "./index-Do-kTNXw.mjs";
1
+ import { d as InvokeEnvelope } from "./types-BC39OoZB.mjs";
2
2
  /** Canonical permission ids. Hosts map each to their platform equivalent. */
3
3
  export type PermissionId = 'storage' | 'camera';
4
4
  export type PermissionStatus = 'granted' | 'denied' | 'notDetermined' | 'unsupported';
@@ -14,6 +14,7 @@ export declare const permissionSpecs: {
14
14
  permission: PermissionId;
15
15
  };
16
16
  readonly result: PermissionResult;
17
+ readonly hostTimeoutMs: number;
17
18
  };
18
19
  readonly status: {
19
20
  readonly pluginId: 'core.permissions';