@qontinui/ui-bridge-wrapper 0.5.0 → 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.
@@ -4,13 +4,55 @@
4
4
  var url = require('url');
5
5
  var module$1 = require('module');
6
6
  var fs = require('fs');
7
+ var ui_bridge_cli_args_star = require('@qontinui/ui-bridge-cli-args');
7
8
 
8
9
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
10
+ function _interopNamespace(e) {
11
+ if (e && e.__esModule) return e;
12
+ var n = Object.create(null);
13
+ if (e) {
14
+ Object.keys(e).forEach(function (k) {
15
+ if (k !== 'default') {
16
+ var d = Object.getOwnPropertyDescriptor(e, k);
17
+ Object.defineProperty(n, k, d.get ? d : {
18
+ enumerable: true,
19
+ get: function () { return e[k]; }
20
+ });
21
+ }
22
+ });
23
+ }
24
+ n.default = e;
25
+ return Object.freeze(n);
26
+ }
27
+
28
+ var ui_bridge_cli_args_star__namespace = /*#__PURE__*/_interopNamespace(ui_bridge_cli_args_star);
29
+
30
+ var __defProp = Object.defineProperty;
31
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
32
+ var __getOwnPropNames = Object.getOwnPropertyNames;
33
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
34
+ var __copyProps = (to, from, except, desc) => {
35
+ if (from && typeof from === "object" || typeof from === "function") {
36
+ for (let key of __getOwnPropNames(from))
37
+ if (!__hasOwnProp.call(to, key) && key !== except)
38
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
39
+ }
40
+ return to;
41
+ };
42
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget);
43
+
9
44
  // src/types.ts
10
45
  var WrapperTransportError = class extends Error {
11
46
  code;
12
47
  retryable;
13
48
  cause;
49
+ /**
50
+ * Optional structured diagnostic payload (error-code-specific shape) so
51
+ * programmatic callers can branch on data instead of parsing the message —
52
+ * e.g. `INJECTED_EXPECT_SELECTOR_UNMET` attaches
53
+ * `{ registeredElements, elementCount }`.
54
+ */
55
+ details;
14
56
  constructor(code, message, options = {}) {
15
57
  super(message);
16
58
  this.name = "WrapperTransportError";
@@ -19,6 +61,9 @@ var WrapperTransportError = class extends Error {
19
61
  if (options.cause !== void 0) {
20
62
  this.cause = options.cause;
21
63
  }
64
+ if (options.details !== void 0) {
65
+ this.details = options.details;
66
+ }
22
67
  }
23
68
  };
24
69
 
@@ -254,6 +299,7 @@ Underlying import error: ${cause}`
254
299
  );
255
300
  }
256
301
  const initScripts = await this.buildInitScripts();
302
+ const relayAuth = this.relayAuth();
257
303
  let tab;
258
304
  try {
259
305
  tab = await launchHeadlessTab({
@@ -267,7 +313,9 @@ Underlying import error: ${cause}`
267
313
  forwardConsole: this.options.forwardConsole,
268
314
  initScripts: initScripts.length > 0 ? initScripts : void 0,
269
315
  launchArgs: this.options.launchArgs && this.options.launchArgs.length > 0 ? this.options.launchArgs : void 0,
270
- storageStatePath: this.options.storageStatePath
316
+ storageStatePath: this.options.storageStatePath,
317
+ ...relayAuth.authToken ? { authToken: relayAuth.authToken } : {},
318
+ ...relayAuth.callerUserId ? { callerUserId: relayAuth.callerUserId } : {}
271
319
  });
272
320
  } catch (err) {
273
321
  const cause = err instanceof Error ? err.message : String(err);
@@ -299,6 +347,15 @@ Underlying launch error: ${cause}`
299
347
  async buildInitScripts() {
300
348
  return [];
301
349
  }
350
+ /**
351
+ * Subclass hook: credentials for the launcher's Node-side relay registration
352
+ * poll (`<uiBridgeBase>/tabs`). Default: none (anonymous poll — correct for an
353
+ * ungated relay). Injected mode overrides this with the `--auth-token` bearer
354
+ * and the `--registration-metadata` userId.
355
+ */
356
+ relayAuth() {
357
+ return {};
358
+ }
302
359
  /**
303
360
  * Subclass hook: run after launch + navigation, before `ready()` resolves.
304
361
  * Default: no-op. Injected mode overrides it to await the in-page runtime.
@@ -337,6 +394,8 @@ var HeadedTransport = class extends HeadlessTransport {
337
394
  };
338
395
  var require2 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('inject-cli.cjs', document.baseURI).href)));
339
396
  var cachedBundle = null;
397
+ var DIGEST_MAX_ELEMENTS = 10;
398
+ var DIGEST_TIMEOUT_MS = 5e3;
340
399
  function loadInjectedBundle() {
341
400
  if (cachedBundle !== null) return cachedBundle;
342
401
  let bundlePath;
@@ -392,8 +451,8 @@ var InjectedTransport = class extends HeadlessTransport {
392
451
  cfg.registrationMetadata = this.injected.registrationMetadata;
393
452
  if (this.injected.appId) cfg.appId = this.injected.appId;
394
453
  if (this.injected.appName) cfg.appName = this.injected.appName;
395
- if (this.injected.tabId) cfg.tabId = this.injected.tabId;
396
454
  }
455
+ if (this.injected.tabId) cfg.tabId = this.injected.tabId;
397
456
  if (this.injected.settleQuietMs !== void 0)
398
457
  cfg.settleQuietMs = this.injected.settleQuietMs;
399
458
  if (this.injected.settleTimeoutMs !== void 0)
@@ -402,6 +461,18 @@ var InjectedTransport = class extends HeadlessTransport {
402
461
  cfg.expectSelector = this.injected.expectSelector;
403
462
  return Object.keys(cfg).length > 0 ? cfg : null;
404
463
  }
464
+ /**
465
+ * The relay credentials the Node-side registration poll needs. Same bearer the
466
+ * page-side client gets via `__uiBridgeInjectedConfig.authToken`; without it
467
+ * the poll against a gated relay 401s and the CLI reports `tabId: null` on a
468
+ * launch that actually registered.
469
+ */
470
+ relayAuth() {
471
+ return {
472
+ ...this.injected.authToken ? { authToken: this.injected.authToken } : {},
473
+ ...this.injected.registrationMetadata?.userId ? { callerUserId: this.injected.registrationMetadata.userId } : {}
474
+ };
475
+ }
405
476
  async buildInitScripts() {
406
477
  const scripts = [];
407
478
  const cfg = this.injectedConfig();
@@ -451,14 +522,66 @@ var InjectedTransport = class extends HeadlessTransport {
451
522
  }
452
523
  if (state.settledByTimeout && !state.expectSatisfied) {
453
524
  const sel = this.injected.expectSelector;
525
+ const baseMessage = sel ? `The injected runtime settled at its cap without the expected control (selector '${sel}') appearing \u2014 ${state.elementCount} element(s) were registered, but none matched. The control may mount slower than the settle cap (raise options.settleTimeoutMs), the selector may be wrong, or the inject failed. Treat as BLOCKED/UNVERIFIED, not a clean page.` : `The injected runtime settled at its cap with an empty registry (0 elements). The page never rendered interactive content within the settle cap, or the inject failed. Raise options.settleTimeoutMs for a slow page; otherwise treat as BLOCKED/UNVERIFIED.`;
526
+ const digest = await this.registeredElementDigest(page);
527
+ if (digest === null) {
528
+ throw new WrapperTransportError("INJECTED_EXPECT_SELECTOR_UNMET", baseMessage, {
529
+ retryable: true
530
+ });
531
+ }
532
+ const summary = digest.length > 0 ? ` Registered: ${digest.map((el) => el.role ? `${el.id} (${el.role})` : el.id).join(", ")}${state.elementCount > digest.length ? ", \u2026" : ""}` : "";
454
533
  throw new WrapperTransportError(
455
534
  "INJECTED_EXPECT_SELECTOR_UNMET",
456
- sel ? `The injected runtime settled at its cap without the expected control (selector '${sel}') appearing \u2014 ${state.elementCount} element(s) were registered, but none matched. The control may mount slower than the settle cap (raise options.settleTimeoutMs), the selector may be wrong, or the inject failed. Treat as BLOCKED/UNVERIFIED, not a clean page.` : `The injected runtime settled at its cap with an empty registry (0 elements). The page never rendered interactive content within the settle cap, or the inject failed. Raise options.settleTimeoutMs for a slow page; otherwise treat as BLOCKED/UNVERIFIED.`,
457
- { retryable: true }
535
+ `${baseMessage}${summary}`,
536
+ {
537
+ retryable: true,
538
+ details: { registeredElements: digest, elementCount: state.elementCount }
539
+ }
458
540
  );
459
541
  }
460
542
  }
461
543
  }
544
+ /**
545
+ * Best-effort digest of the first {@link DIGEST_MAX_ELEMENTS} registered
546
+ * interactive elements, read through the in-page dispatcher's
547
+ * `getControlSnapshot` action (the snapshot's per-element projection is
548
+ * already redaction-safe — we never read raw DOM labels here). Returns
549
+ * `null` on ANY failure or timeout: this feeds error diagnostics only, and a
550
+ * broken page realm must never mask the error being reported.
551
+ */
552
+ async registeredElementDigest(page) {
553
+ let timer;
554
+ try {
555
+ const snapshotPromise = page.evaluate(
556
+ () => window.__uiBridgeInjected.execute("getControlSnapshot", { skipSettle: true })
557
+ );
558
+ const snapshot = await Promise.race([
559
+ snapshotPromise,
560
+ new Promise((_, reject) => {
561
+ timer = setTimeout(() => reject(new Error("digest fetch timed out")), DIGEST_TIMEOUT_MS);
562
+ })
563
+ ]);
564
+ if (!snapshot || typeof snapshot !== "object") return null;
565
+ const elements = snapshot.elements;
566
+ if (!Array.isArray(elements)) return null;
567
+ const digest = [];
568
+ for (const el of elements.slice(0, DIGEST_MAX_ELEMENTS)) {
569
+ if (!el || typeof el !== "object") continue;
570
+ const e = el;
571
+ if (typeof e.id !== "string") continue;
572
+ digest.push({
573
+ id: e.id,
574
+ ...typeof e.role === "string" ? { role: e.role } : {},
575
+ ...typeof e.label === "string" ? { label: e.label } : {}
576
+ });
577
+ }
578
+ return digest;
579
+ } catch {
580
+ return null;
581
+ } finally {
582
+ if (timer !== void 0) clearTimeout(timer);
583
+ }
584
+ }
462
585
  async buildContext() {
463
586
  if (!this.tab) {
464
587
  throw new WrapperTransportError(
@@ -727,16 +850,8 @@ function createTransport(config) {
727
850
  }
728
851
 
729
852
  // src/cli-args.ts
730
- function isFlagShaped(value) {
731
- return value.startsWith("--");
732
- }
733
- function consumeValue(flag, raw, error) {
734
- if (raw === void 0) return null;
735
- if (isFlagShaped(raw)) {
736
- throw error(`${flag} expects a value but got the flag '${raw}' \u2014 did you omit ${flag}'s argument?`);
737
- }
738
- return raw;
739
- }
853
+ var cli_args_exports = {};
854
+ __reExport(cli_args_exports, ui_bridge_cli_args_star__namespace);
740
855
 
741
856
  // src/inject-cli.ts
742
857
  var USAGE = `ui-bridge-inject \u2014 drive UI Bridge's injected transport against a UI-Bridge-free page
@@ -886,25 +1001,25 @@ function parseArgs(argv) {
886
1001
  // String value-flags: guard each consumed value against the flag-shaped
887
1002
  // swallow (`--url --headed` must error, not capture `--headed` as the url).
888
1003
  case "--url":
889
- args.url = consumeValue("--url", argv[++i], mkError) ?? "";
1004
+ args.url = (0, cli_args_exports.consumeValue)("--url", argv[++i], mkError) ?? "";
890
1005
  break;
891
1006
  case "--relay":
892
- args.relay = consumeValue("--relay", argv[++i], mkError);
1007
+ args.relay = (0, cli_args_exports.consumeValue)("--relay", argv[++i], mkError);
893
1008
  break;
894
1009
  case "--auth-token":
895
- args.authToken = consumeValue("--auth-token", argv[++i], mkError);
1010
+ args.authToken = (0, cli_args_exports.consumeValue)("--auth-token", argv[++i], mkError);
896
1011
  break;
897
1012
  case "--app-id":
898
- args.appId = consumeValue("--app-id", argv[++i], mkError);
1013
+ args.appId = (0, cli_args_exports.consumeValue)("--app-id", argv[++i], mkError);
899
1014
  break;
900
1015
  case "--app-name":
901
- args.appName = consumeValue("--app-name", argv[++i], mkError);
1016
+ args.appName = (0, cli_args_exports.consumeValue)("--app-name", argv[++i], mkError);
902
1017
  break;
903
1018
  case "--tab-id":
904
- args.tabId = consumeValue("--tab-id", argv[++i], mkError);
1019
+ args.tabId = (0, cli_args_exports.consumeValue)("--tab-id", argv[++i], mkError);
905
1020
  break;
906
1021
  case "--storage-state": {
907
- const raw = consumeValue("--storage-state", argv[++i], mkError);
1022
+ const raw = (0, cli_args_exports.consumeValue)("--storage-state", argv[++i], mkError);
908
1023
  if (raw === null || raw.length === 0) {
909
1024
  throw new InjectCliArgError(
910
1025
  `--storage-state expects a path to a storageState JSON file (got <missing>)`
@@ -922,7 +1037,7 @@ function parseArgs(argv) {
922
1037
  break;
923
1038
  }
924
1039
  case "--exec": {
925
- const raw = consumeValue("--exec", argv[++i], mkError);
1040
+ const raw = (0, cli_args_exports.consumeValue)("--exec", argv[++i], mkError);
926
1041
  if (raw === null) {
927
1042
  throw new InjectCliArgError(`--exec expects '<action> <json-payload>' (got <missing>)`);
928
1043
  }
@@ -930,7 +1045,7 @@ function parseArgs(argv) {
930
1045
  break;
931
1046
  }
932
1047
  case "--registration-metadata": {
933
- const raw = consumeValue("--registration-metadata", argv[++i], mkError);
1048
+ const raw = (0, cli_args_exports.consumeValue)("--registration-metadata", argv[++i], mkError);
934
1049
  if (raw === null) {
935
1050
  throw new InjectCliArgError(
936
1051
  `--registration-metadata expects JSON {"userId","sessionId"} (got <missing>)`
@@ -953,7 +1068,7 @@ function parseArgs(argv) {
953
1068
  break;
954
1069
  }
955
1070
  case "--ready-timeout": {
956
- const raw = consumeValue("--ready-timeout", argv[++i], mkError);
1071
+ const raw = (0, cli_args_exports.consumeValue)("--ready-timeout", argv[++i], mkError);
957
1072
  const n = raw === null ? NaN : Number.parseInt(raw, 10);
958
1073
  if (!Number.isFinite(n) || n <= 0) {
959
1074
  throw new InjectCliArgError(
@@ -967,7 +1082,7 @@ function parseArgs(argv) {
967
1082
  args.waitForSettle = false;
968
1083
  break;
969
1084
  case "--settle-quiet": {
970
- const raw = consumeValue("--settle-quiet", argv[++i], mkError);
1085
+ const raw = (0, cli_args_exports.consumeValue)("--settle-quiet", argv[++i], mkError);
971
1086
  const n = raw === null ? NaN : Number.parseInt(raw, 10);
972
1087
  if (!Number.isFinite(n) || n < 0) {
973
1088
  throw new InjectCliArgError(
@@ -978,7 +1093,7 @@ function parseArgs(argv) {
978
1093
  break;
979
1094
  }
980
1095
  case "--settle-timeout": {
981
- const raw = consumeValue("--settle-timeout", argv[++i], mkError);
1096
+ const raw = (0, cli_args_exports.consumeValue)("--settle-timeout", argv[++i], mkError);
982
1097
  const n = raw === null ? NaN : Number.parseInt(raw, 10);
983
1098
  if (!Number.isFinite(n) || n <= 0) {
984
1099
  throw new InjectCliArgError(
@@ -989,7 +1104,7 @@ function parseArgs(argv) {
989
1104
  break;
990
1105
  }
991
1106
  case "--expect-selector": {
992
- const raw = consumeValue("--expect-selector", argv[++i], mkError);
1107
+ const raw = (0, cli_args_exports.consumeValue)("--expect-selector", argv[++i], mkError);
993
1108
  if (raw === null || raw.length === 0) {
994
1109
  throw new InjectCliArgError(`--expect-selector expects a CSS selector (got <missing>)`);
995
1110
  }
@@ -997,7 +1112,7 @@ function parseArgs(argv) {
997
1112
  break;
998
1113
  }
999
1114
  case "--viewport": {
1000
- const raw = consumeValue("--viewport", argv[++i], mkError);
1115
+ const raw = (0, cli_args_exports.consumeValue)("--viewport", argv[++i], mkError);
1001
1116
  const match = raw?.match(/^(\d+)x(\d+)$/);
1002
1117
  if (!match) {
1003
1118
  throw new InjectCliArgError(`--viewport expects WxH (got ${raw ?? "<missing>"})`);