@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.
@@ -5,18 +5,59 @@ var fs = require('fs');
5
5
  var path = require('path');
6
6
  var url = require('url');
7
7
  var module$1 = require('module');
8
+ var ui_bridge_cli_args_star = require('@qontinui/ui-bridge-cli-args');
8
9
 
9
10
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
10
11
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
11
12
 
13
+ function _interopNamespace(e) {
14
+ if (e && e.__esModule) return e;
15
+ var n = Object.create(null);
16
+ if (e) {
17
+ Object.keys(e).forEach(function (k) {
18
+ if (k !== 'default') {
19
+ var d = Object.getOwnPropertyDescriptor(e, k);
20
+ Object.defineProperty(n, k, d.get ? d : {
21
+ enumerable: true,
22
+ get: function () { return e[k]; }
23
+ });
24
+ }
25
+ });
26
+ }
27
+ n.default = e;
28
+ return Object.freeze(n);
29
+ }
30
+
12
31
  var fs__default = /*#__PURE__*/_interopDefault(fs);
13
32
  var path__default = /*#__PURE__*/_interopDefault(path);
33
+ var ui_bridge_cli_args_star__namespace = /*#__PURE__*/_interopNamespace(ui_bridge_cli_args_star);
34
+
35
+ var __defProp = Object.defineProperty;
36
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
37
+ var __getOwnPropNames = Object.getOwnPropertyNames;
38
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
39
+ var __copyProps = (to, from, except, desc) => {
40
+ if (from && typeof from === "object" || typeof from === "function") {
41
+ for (let key of __getOwnPropNames(from))
42
+ if (!__hasOwnProp.call(to, key) && key !== except)
43
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
44
+ }
45
+ return to;
46
+ };
47
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget);
14
48
 
15
49
  // src/types.ts
16
50
  var WrapperTransportError = class extends Error {
17
51
  code;
18
52
  retryable;
19
53
  cause;
54
+ /**
55
+ * Optional structured diagnostic payload (error-code-specific shape) so
56
+ * programmatic callers can branch on data instead of parsing the message —
57
+ * e.g. `INJECTED_EXPECT_SELECTOR_UNMET` attaches
58
+ * `{ registeredElements, elementCount }`.
59
+ */
60
+ details;
20
61
  constructor(code, message, options = {}) {
21
62
  super(message);
22
63
  this.name = "WrapperTransportError";
@@ -25,6 +66,9 @@ var WrapperTransportError = class extends Error {
25
66
  if (options.cause !== void 0) {
26
67
  this.cause = options.cause;
27
68
  }
69
+ if (options.details !== void 0) {
70
+ this.details = options.details;
71
+ }
28
72
  }
29
73
  };
30
74
 
@@ -260,6 +304,7 @@ Underlying import error: ${cause}`
260
304
  );
261
305
  }
262
306
  const initScripts = await this.buildInitScripts();
307
+ const relayAuth = this.relayAuth();
263
308
  let tab;
264
309
  try {
265
310
  tab = await launchHeadlessTab({
@@ -273,7 +318,9 @@ Underlying import error: ${cause}`
273
318
  forwardConsole: this.options.forwardConsole,
274
319
  initScripts: initScripts.length > 0 ? initScripts : void 0,
275
320
  launchArgs: this.options.launchArgs && this.options.launchArgs.length > 0 ? this.options.launchArgs : void 0,
276
- storageStatePath: this.options.storageStatePath
321
+ storageStatePath: this.options.storageStatePath,
322
+ ...relayAuth.authToken ? { authToken: relayAuth.authToken } : {},
323
+ ...relayAuth.callerUserId ? { callerUserId: relayAuth.callerUserId } : {}
277
324
  });
278
325
  } catch (err) {
279
326
  const cause = err instanceof Error ? err.message : String(err);
@@ -305,6 +352,15 @@ Underlying launch error: ${cause}`
305
352
  async buildInitScripts() {
306
353
  return [];
307
354
  }
355
+ /**
356
+ * Subclass hook: credentials for the launcher's Node-side relay registration
357
+ * poll (`<uiBridgeBase>/tabs`). Default: none (anonymous poll — correct for an
358
+ * ungated relay). Injected mode overrides this with the `--auth-token` bearer
359
+ * and the `--registration-metadata` userId.
360
+ */
361
+ relayAuth() {
362
+ return {};
363
+ }
308
364
  /**
309
365
  * Subclass hook: run after launch + navigation, before `ready()` resolves.
310
366
  * Default: no-op. Injected mode overrides it to await the in-page runtime.
@@ -343,6 +399,8 @@ var HeadedTransport = class extends HeadlessTransport {
343
399
  };
344
400
  var require2 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('capture-specs-cli.cjs', document.baseURI).href)));
345
401
  var cachedBundle = null;
402
+ var DIGEST_MAX_ELEMENTS = 10;
403
+ var DIGEST_TIMEOUT_MS = 5e3;
346
404
  function loadInjectedBundle() {
347
405
  if (cachedBundle !== null) return cachedBundle;
348
406
  let bundlePath;
@@ -398,8 +456,8 @@ var InjectedTransport = class extends HeadlessTransport {
398
456
  cfg.registrationMetadata = this.injected.registrationMetadata;
399
457
  if (this.injected.appId) cfg.appId = this.injected.appId;
400
458
  if (this.injected.appName) cfg.appName = this.injected.appName;
401
- if (this.injected.tabId) cfg.tabId = this.injected.tabId;
402
459
  }
460
+ if (this.injected.tabId) cfg.tabId = this.injected.tabId;
403
461
  if (this.injected.settleQuietMs !== void 0)
404
462
  cfg.settleQuietMs = this.injected.settleQuietMs;
405
463
  if (this.injected.settleTimeoutMs !== void 0)
@@ -408,6 +466,18 @@ var InjectedTransport = class extends HeadlessTransport {
408
466
  cfg.expectSelector = this.injected.expectSelector;
409
467
  return Object.keys(cfg).length > 0 ? cfg : null;
410
468
  }
469
+ /**
470
+ * The relay credentials the Node-side registration poll needs. Same bearer the
471
+ * page-side client gets via `__uiBridgeInjectedConfig.authToken`; without it
472
+ * the poll against a gated relay 401s and the CLI reports `tabId: null` on a
473
+ * launch that actually registered.
474
+ */
475
+ relayAuth() {
476
+ return {
477
+ ...this.injected.authToken ? { authToken: this.injected.authToken } : {},
478
+ ...this.injected.registrationMetadata?.userId ? { callerUserId: this.injected.registrationMetadata.userId } : {}
479
+ };
480
+ }
411
481
  async buildInitScripts() {
412
482
  const scripts = [];
413
483
  const cfg = this.injectedConfig();
@@ -457,14 +527,66 @@ var InjectedTransport = class extends HeadlessTransport {
457
527
  }
458
528
  if (state.settledByTimeout && !state.expectSatisfied) {
459
529
  const sel = this.injected.expectSelector;
530
+ 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.`;
531
+ const digest = await this.registeredElementDigest(page);
532
+ if (digest === null) {
533
+ throw new WrapperTransportError("INJECTED_EXPECT_SELECTOR_UNMET", baseMessage, {
534
+ retryable: true
535
+ });
536
+ }
537
+ const summary = digest.length > 0 ? ` Registered: ${digest.map((el) => el.role ? `${el.id} (${el.role})` : el.id).join(", ")}${state.elementCount > digest.length ? ", \u2026" : ""}` : "";
460
538
  throw new WrapperTransportError(
461
539
  "INJECTED_EXPECT_SELECTOR_UNMET",
462
- 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.`,
463
- { retryable: true }
540
+ `${baseMessage}${summary}`,
541
+ {
542
+ retryable: true,
543
+ details: { registeredElements: digest, elementCount: state.elementCount }
544
+ }
464
545
  );
465
546
  }
466
547
  }
467
548
  }
549
+ /**
550
+ * Best-effort digest of the first {@link DIGEST_MAX_ELEMENTS} registered
551
+ * interactive elements, read through the in-page dispatcher's
552
+ * `getControlSnapshot` action (the snapshot's per-element projection is
553
+ * already redaction-safe — we never read raw DOM labels here). Returns
554
+ * `null` on ANY failure or timeout: this feeds error diagnostics only, and a
555
+ * broken page realm must never mask the error being reported.
556
+ */
557
+ async registeredElementDigest(page) {
558
+ let timer;
559
+ try {
560
+ const snapshotPromise = page.evaluate(
561
+ () => window.__uiBridgeInjected.execute("getControlSnapshot", { skipSettle: true })
562
+ );
563
+ const snapshot = await Promise.race([
564
+ snapshotPromise,
565
+ new Promise((_, reject) => {
566
+ timer = setTimeout(() => reject(new Error("digest fetch timed out")), DIGEST_TIMEOUT_MS);
567
+ })
568
+ ]);
569
+ if (!snapshot || typeof snapshot !== "object") return null;
570
+ const elements = snapshot.elements;
571
+ if (!Array.isArray(elements)) return null;
572
+ const digest = [];
573
+ for (const el of elements.slice(0, DIGEST_MAX_ELEMENTS)) {
574
+ if (!el || typeof el !== "object") continue;
575
+ const e = el;
576
+ if (typeof e.id !== "string") continue;
577
+ digest.push({
578
+ id: e.id,
579
+ ...typeof e.role === "string" ? { role: e.role } : {},
580
+ ...typeof e.label === "string" ? { label: e.label } : {}
581
+ });
582
+ }
583
+ return digest;
584
+ } catch {
585
+ return null;
586
+ } finally {
587
+ if (timer !== void 0) clearTimeout(timer);
588
+ }
589
+ }
468
590
  async buildContext() {
469
591
  if (!this.tab) {
470
592
  throw new WrapperTransportError(
@@ -733,57 +855,8 @@ function createTransport(config) {
733
855
  }
734
856
 
735
857
  // src/cli-args.ts
736
- var COMMON_FLAGS = /* @__PURE__ */ new Set(["--help", "-h", "--quiet"]);
737
- function isFlagShaped(value) {
738
- return value.startsWith("--");
739
- }
740
- function consumeValue(flag, raw, error) {
741
- if (raw === void 0) return null;
742
- if (isFlagShaped(raw)) {
743
- throw error(`${flag} expects a value but got the flag '${raw}' \u2014 did you omit ${flag}'s argument?`);
744
- }
745
- return raw;
746
- }
747
- var ArgReader = class {
748
- argv;
749
- error;
750
- /**
751
- * @param argv Already sliced past `node script`.
752
- * @param known All flags the bin recognizes (union the bin's set with {@link COMMON_FLAGS}).
753
- * @param error Factory producing the bin's domain error type.
754
- */
755
- constructor(argv, known, error) {
756
- this.argv = argv;
757
- this.error = error;
758
- for (const arg of argv) {
759
- if (isFlagShaped(arg) && !known.has(arg)) {
760
- throw error(`Unknown flag: ${arg}`);
761
- }
762
- }
763
- }
764
- /** True if `name` appears as a bare boolean flag. */
765
- has(name) {
766
- return this.argv.includes(name);
767
- }
768
- /**
769
- * Value following the value-flag `name`, or `null` when the flag is absent OR
770
- * has no following token (the caller defaults it). Throws when the following
771
- * token is flag-shaped — the swallow this kit exists to kill. Delegates to
772
- * {@link consumeValue} so the guard (and its message) live in exactly one
773
- * place for both the indexOf-style and switch-style parsers.
774
- */
775
- value(name) {
776
- const i = this.argv.indexOf(name);
777
- if (i < 0 || i + 1 >= this.argv.length) return null;
778
- return consumeValue(name, this.argv[i + 1], this.error);
779
- }
780
- };
781
- function makeLogger(prefix, quiet) {
782
- if (quiet) return () => {
783
- };
784
- return (m) => process.stderr.write(`${prefix} ${m}
785
- `) ;
786
- }
858
+ var cli_args_exports = {};
859
+ __reExport(cli_args_exports, ui_bridge_cli_args_star__namespace);
787
860
 
788
861
  // src/login-drive.ts
789
862
  var isCognito = (u) => /auth\.qontinui\.io|amazoncognito\.com|\/oauth2\//i.test(u);
@@ -979,7 +1052,7 @@ function computeLoginUrl(targets, origin) {
979
1052
  }
980
1053
  function parseArgs(argv) {
981
1054
  const mkError = (m) => new CaptureCliArgError(m);
982
- const reader = new ArgReader(argv, KNOWN_FLAGS, mkError);
1055
+ const reader = new cli_args_exports.ArgReader(argv, KNOWN_FLAGS, mkError);
983
1056
  const valueOf = (name) => reader.value(name);
984
1057
  const has = (name) => reader.has(name);
985
1058
  const help = has("--help") || has("-h");
@@ -1022,7 +1095,7 @@ var KNOWN_FLAGS = /* @__PURE__ */ new Set([
1022
1095
  "--pages",
1023
1096
  "--device",
1024
1097
  "--timeout",
1025
- ...COMMON_FLAGS
1098
+ ...cli_args_exports.COMMON_FLAGS
1026
1099
  ]);
1027
1100
  function validateArgs(args) {
1028
1101
  if (args.help) return;
@@ -1048,7 +1121,7 @@ ${USAGE}`);
1048
1121
  process.exit(0);
1049
1122
  }
1050
1123
  const { email, password, out, origin, device, timeoutMs } = args;
1051
- const log = makeLogger("[capture]", args.quiet);
1124
+ const log = (0, cli_args_exports.makeLogger)("[capture]", args.quiet);
1052
1125
  const targets = args.pages ?? defaultTargets(origin, device);
1053
1126
  const { loginUrl } = computeLoginUrl(targets, origin);
1054
1127
  const transport = createTransport({