@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 fs = require('fs');
6
6
  var module$1 = require('module');
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('login-web-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,6 +850,16 @@ function createTransport(config) {
727
850
  }
728
851
 
729
852
  // src/session-storage-capture.ts
853
+ var SESSION_STORAGE_EXCLUDED_KEYS = ["__uiBridge_tabId"];
854
+ function withoutExcludedKeys(kv) {
855
+ const excluded = SESSION_STORAGE_EXCLUDED_KEYS;
856
+ const out = {};
857
+ for (const key of Object.keys(kv)) {
858
+ if (excluded.includes(key)) continue;
859
+ out[key] = kv[key];
860
+ }
861
+ return out;
862
+ }
730
863
  function isCapturableOrigin(origin) {
731
864
  return typeof origin === "string" && origin.length > 0 && origin !== "null";
732
865
  }
@@ -744,7 +877,8 @@ function buildMultiOriginSessionStorageMap(frames) {
744
877
  if (frame.kv === null) continue;
745
878
  const origin = frameOrigin(frame.url);
746
879
  if (origin === null) continue;
747
- out[origin] = { ...out[origin] ?? {}, ...frame.kv };
880
+ const kv = withoutExcludedKeys(frame.kv);
881
+ out[origin] = { ...out[origin] ?? {}, ...kv };
748
882
  }
749
883
  return out;
750
884
  }
@@ -752,72 +886,15 @@ function mergeMultiOriginSessionStorageIntoArtifact(artifact, map) {
752
886
  const existing = artifact.__sessionStorage && typeof artifact.__sessionStorage === "object" ? artifact.__sessionStorage : {};
753
887
  const merged = { ...existing };
754
888
  for (const origin of Object.keys(map)) {
755
- merged[origin] = { ...map[origin] };
889
+ merged[origin] = withoutExcludedKeys(map[origin]);
756
890
  }
757
891
  artifact.__sessionStorage = merged;
758
892
  return artifact;
759
893
  }
760
894
 
761
895
  // src/cli-args.ts
762
- var COMMON_FLAGS = /* @__PURE__ */ new Set(["--help", "-h", "--quiet"]);
763
- function isFlagShaped(value) {
764
- return value.startsWith("--");
765
- }
766
- function consumeValue(flag, raw, error) {
767
- if (raw === void 0) return null;
768
- if (isFlagShaped(raw)) {
769
- throw error(`${flag} expects a value but got the flag '${raw}' \u2014 did you omit ${flag}'s argument?`);
770
- }
771
- return raw;
772
- }
773
- function rejectEmptyValue(flag, value, error) {
774
- if (value !== null && value.trim() === "") {
775
- throw error(
776
- `${flag} was given an empty value \u2014 omit the flag to use its default, or pass a non-empty value`
777
- );
778
- }
779
- return value;
780
- }
781
- var ArgReader = class {
782
- argv;
783
- error;
784
- /**
785
- * @param argv Already sliced past `node script`.
786
- * @param known All flags the bin recognizes (union the bin's set with {@link COMMON_FLAGS}).
787
- * @param error Factory producing the bin's domain error type.
788
- */
789
- constructor(argv, known, error) {
790
- this.argv = argv;
791
- this.error = error;
792
- for (const arg of argv) {
793
- if (isFlagShaped(arg) && !known.has(arg)) {
794
- throw error(`Unknown flag: ${arg}`);
795
- }
796
- }
797
- }
798
- /** True if `name` appears as a bare boolean flag. */
799
- has(name) {
800
- return this.argv.includes(name);
801
- }
802
- /**
803
- * Value following the value-flag `name`, or `null` when the flag is absent OR
804
- * has no following token (the caller defaults it). Throws when the following
805
- * token is flag-shaped — the swallow this kit exists to kill. Delegates to
806
- * {@link consumeValue} so the guard (and its message) live in exactly one
807
- * place for both the indexOf-style and switch-style parsers.
808
- */
809
- value(name) {
810
- const i = this.argv.indexOf(name);
811
- if (i < 0 || i + 1 >= this.argv.length) return null;
812
- return consumeValue(name, this.argv[i + 1], this.error);
813
- }
814
- };
815
- function makeLogger(prefix, quiet) {
816
- if (quiet) return () => {
817
- };
818
- return (m) => process.stderr.write(`${prefix} ${m}
819
- `) ;
820
- }
896
+ var cli_args_exports = {};
897
+ __reExport(cli_args_exports, ui_bridge_cli_args_star__namespace);
821
898
 
822
899
  // src/login-drive.ts
823
900
  var isCognito = (u) => /auth\.qontinui\.io|amazoncognito\.com|\/oauth2\//i.test(u);
@@ -1015,7 +1092,7 @@ var LoginCliArgError = class extends Error {
1015
1092
  };
1016
1093
  function parseArgs(argv) {
1017
1094
  const mkError = (m) => new LoginCliArgError(m);
1018
- const reader = new ArgReader(argv, KNOWN_FLAGS, mkError);
1095
+ const reader = new cli_args_exports.ArgReader(argv, KNOWN_FLAGS, mkError);
1019
1096
  const valueOf = (name) => reader.value(name);
1020
1097
  const has = (name) => reader.has(name);
1021
1098
  const help = has("--help") || has("-h");
@@ -1025,12 +1102,12 @@ function parseArgs(argv) {
1025
1102
  throw new LoginCliArgError(`--timeout expects a positive integer (got ${timeoutRaw})`);
1026
1103
  }
1027
1104
  const args = {
1028
- url: rejectEmptyValue("--url", valueOf("--url"), mkError) ?? "https://qontinui.io/login",
1105
+ url: (0, cli_args_exports.rejectEmptyValue)("--url", valueOf("--url"), mkError) ?? "https://qontinui.io/login",
1029
1106
  email: valueOf("--email") ?? process.env.UIB_LOGIN_EMAIL ?? "",
1030
1107
  password: valueOf("--password") ?? process.env.UIB_LOGIN_PASSWORD ?? "",
1031
1108
  // An EMPTY --success would make `landingPath.includes('')` true on any
1032
1109
  // landing — ok:true while parked on the login page. Reject it.
1033
- success: rejectEmptyValue("--success", valueOf("--success"), mkError) ?? "/dashboard",
1110
+ success: (0, cli_args_exports.rejectEmptyValue)("--success", valueOf("--success"), mkError) ?? "/dashboard",
1034
1111
  timeoutMs,
1035
1112
  headed: has("--headed"),
1036
1113
  postClick: valueOf("--post-login-click"),
@@ -1058,7 +1135,7 @@ var KNOWN_FLAGS = /* @__PURE__ */ new Set([
1058
1135
  "--screenshot",
1059
1136
  "--storage-state-out",
1060
1137
  "--keep-open",
1061
- ...COMMON_FLAGS
1138
+ ...cli_args_exports.COMMON_FLAGS
1062
1139
  ]);
1063
1140
  function validateArgs(args) {
1064
1141
  if (args.help) return;
@@ -1101,7 +1178,7 @@ ${USAGE}`);
1101
1178
  screenshotPath,
1102
1179
  storageStateOut
1103
1180
  } = args;
1104
- const log = makeLogger("[login-web]", args.quiet);
1181
+ const log = (0, cli_args_exports.makeLogger)("[login-web]", args.quiet);
1105
1182
  const transport = createTransport({
1106
1183
  kind: "injected",
1107
1184
  options: { targetUrl: url, waitForSettle: false, readyTimeoutMs: 45e3, headed }