@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.
@@ -1,75 +1,13 @@
1
1
  /**
2
- * Shared CLI argument primitives for the package bins (`ui-bridge-login-web`,
3
- * `ui-bridge-capture-specs`, `ui-bridge-inject`). Each bin used to re-implement
4
- * its own `valueOf`/`has`/unknown-flag kit, and those copies drifted — most
5
- * importantly, every one of them silently SWALLOWED a flag-shaped value: a
6
- * value-flag followed by another `--flag` (e.g. `--success --headed`) captured
7
- * the flag as the value, so a *successful* login could report `ok:false` because
8
- * its `--success` target was literally `"--headed"`. The kit below is the single
9
- * home for argument reading and rejects that swallow uniformly.
2
+ * Shared CLI argument primitives for the wrapper bins (`ui-bridge-login-web`,
3
+ * `ui-bridge-capture-specs`, `ui-bridge-inject`).
10
4
  *
11
- * The bins keep their own typed `parseArgs` (the arg SHAPE differs per bin); this
12
- * module only owns the low-level reading + the cross-bin invariants (flag-shaped
13
- * value rejection, unknown-flag rejection, the shared `--quiet`/`--help` flags,
14
- * and a `--quiet`-aware stderr logger).
15
- */
16
- /**
17
- * Construct a bin's own domain error from a message. Passing the factory keeps
18
- * thrown errors the bin's specific type (`LoginCliArgError` / `CaptureCliArgError`
19
- * / `InjectCliArgError`) so each bin's `main()` `instanceof` catch still fires.
20
- */
21
- export type ArgErrorFactory = (message: string) => Error;
22
- /**
23
- * Flags shared by every bin. A bin unions these into its own KNOWN set so the
24
- * common surface (`--help`, `-h`, `--quiet`) is defined in exactly one place.
25
- */
26
- export declare const COMMON_FLAGS: ReadonlySet<string>;
27
- /**
28
- * Guard a single value consumed by a *switch-style* parser (`argv[++i]`) against
29
- * the flag-shaped swallow. Returns the value, `null` when it's simply absent
30
- * (end of argv — the caller applies its own required/default handling), and
31
- * THROWS (via `error`) when the value is flag-shaped — that is never an intended
32
- * value, it's an omitted argument.
33
- */
34
- export declare function consumeValue(flag: string, raw: string | undefined, error: ArgErrorFactory): string | null;
35
- /**
36
- * Reject a present-but-empty value (`--success ''`). An empty value on a
37
- * matching/target flag is never intended — e.g. an empty `--success` makes
38
- * `landingPath.includes('')` true on ANY landing page, turning a stuck login
39
- * into a false success (the exact exit-code-trust failure #83 exists to
40
- * prevent). `null` (flag absent — caller defaults it) passes through.
41
- */
42
- export declare function rejectEmptyValue(flag: string, value: string | null, error: ArgErrorFactory): string | null;
43
- /**
44
- * An `indexOf`-based reader for the browser bins' flat arg lists. Rejects unknown
45
- * `--flags` up front (matching each bin's prior behavior) and rejects flag-shaped
46
- * values for value-flags (the swallow fix).
47
- */
48
- export declare class ArgReader {
49
- private readonly argv;
50
- private readonly error;
51
- /**
52
- * @param argv Already sliced past `node script`.
53
- * @param known All flags the bin recognizes (union the bin's set with {@link COMMON_FLAGS}).
54
- * @param error Factory producing the bin's domain error type.
55
- */
56
- constructor(argv: readonly string[], known: ReadonlySet<string>, error: ArgErrorFactory);
57
- /** True if `name` appears as a bare boolean flag. */
58
- has(name: string): boolean;
59
- /**
60
- * Value following the value-flag `name`, or `null` when the flag is absent OR
61
- * has no following token (the caller defaults it). Throws when the following
62
- * token is flag-shaped — the swallow this kit exists to kill. Delegates to
63
- * {@link consumeValue} so the guard (and its message) live in exactly one
64
- * place for both the indexOf-style and switch-style parsers.
65
- */
66
- value(name: string): string | null;
67
- }
68
- /**
69
- * Build a `--quiet`-aware stderr logger. When `quiet` is true it drops every
70
- * line; otherwise it writes `<prefix> <message>` (or just `<message>` when
71
- * `prefix` is empty) to stderr. Shared so all three bins honor `--quiet`
72
- * identically.
73
- */
74
- export declare function makeLogger(prefix: string, quiet: boolean): (message: string) => void;
5
+ * The primitives themselves now live in the zero-dependency leaf package
6
+ * `@qontinui/ui-bridge-cli-args`, so the sibling `@qontinui/ui-bridge-headless`
7
+ * bin (`ui-bridge-tab`) can import the same swallow guard without a dependency
8
+ * cycle (the wrapper AND the engine both depend *down* onto headless, so neither
9
+ * could host code headless imports). This file stays as a stable re-export so the
10
+ * three bins' `import … from './cli-args.js'` keep working — no bin churn.
11
+ */
12
+ export * from '@qontinui/ui-bridge-cli-args';
75
13
  //# sourceMappingURL=cli-args.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"cli-args.d.ts","sourceRoot":"","sources":["../src/cli-args.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH;;;;GAIG;AACH,MAAM,MAAM,eAAe,GAAG,CAAC,OAAO,EAAE,MAAM,KAAK,KAAK,CAAC;AAEzD;;;GAGG;AACH,eAAO,MAAM,YAAY,EAAE,WAAW,CAAC,MAAM,CAAwC,CAAC;AAWtF;;;;;;GAMG;AACH,wBAAgB,YAAY,CAC1B,IAAI,EAAE,MAAM,EACZ,GAAG,EAAE,MAAM,GAAG,SAAS,EACvB,KAAK,EAAE,eAAe,GACrB,MAAM,GAAG,IAAI,CAMf;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAC9B,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,MAAM,GAAG,IAAI,EACpB,KAAK,EAAE,eAAe,GACrB,MAAM,GAAG,IAAI,CAOf;AAED;;;;GAIG;AACH,qBAAa,SAAS;IACpB,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAoB;IACzC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAkB;IAExC;;;;OAIG;gBACS,IAAI,EAAE,SAAS,MAAM,EAAE,EAAE,KAAK,EAAE,WAAW,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,eAAe;IAUvF,qDAAqD;IACrD,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAI1B;;;;;;OAMG;IACH,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI;CAKnC;AAED;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAKpF"}
1
+ {"version":3,"file":"cli-args.d.ts","sourceRoot":"","sources":["../src/cli-args.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,cAAc,8BAA8B,CAAC"}
package/dist/index.cjs CHANGED
@@ -9,6 +9,13 @@ var WrapperTransportError = class extends Error {
9
9
  code;
10
10
  retryable;
11
11
  cause;
12
+ /**
13
+ * Optional structured diagnostic payload (error-code-specific shape) so
14
+ * programmatic callers can branch on data instead of parsing the message —
15
+ * e.g. `INJECTED_EXPECT_SELECTOR_UNMET` attaches
16
+ * `{ registeredElements, elementCount }`.
17
+ */
18
+ details;
12
19
  constructor(code, message, options = {}) {
13
20
  super(message);
14
21
  this.name = "WrapperTransportError";
@@ -17,6 +24,9 @@ var WrapperTransportError = class extends Error {
17
24
  if (options.cause !== void 0) {
18
25
  this.cause = options.cause;
19
26
  }
27
+ if (options.details !== void 0) {
28
+ this.details = options.details;
29
+ }
20
30
  }
21
31
  };
22
32
 
@@ -252,6 +262,7 @@ Underlying import error: ${cause}`
252
262
  );
253
263
  }
254
264
  const initScripts = await this.buildInitScripts();
265
+ const relayAuth = this.relayAuth();
255
266
  let tab;
256
267
  try {
257
268
  tab = await launchHeadlessTab({
@@ -265,7 +276,9 @@ Underlying import error: ${cause}`
265
276
  forwardConsole: this.options.forwardConsole,
266
277
  initScripts: initScripts.length > 0 ? initScripts : void 0,
267
278
  launchArgs: this.options.launchArgs && this.options.launchArgs.length > 0 ? this.options.launchArgs : void 0,
268
- storageStatePath: this.options.storageStatePath
279
+ storageStatePath: this.options.storageStatePath,
280
+ ...relayAuth.authToken ? { authToken: relayAuth.authToken } : {},
281
+ ...relayAuth.callerUserId ? { callerUserId: relayAuth.callerUserId } : {}
269
282
  });
270
283
  } catch (err) {
271
284
  const cause = err instanceof Error ? err.message : String(err);
@@ -297,6 +310,15 @@ Underlying launch error: ${cause}`
297
310
  async buildInitScripts() {
298
311
  return [];
299
312
  }
313
+ /**
314
+ * Subclass hook: credentials for the launcher's Node-side relay registration
315
+ * poll (`<uiBridgeBase>/tabs`). Default: none (anonymous poll — correct for an
316
+ * ungated relay). Injected mode overrides this with the `--auth-token` bearer
317
+ * and the `--registration-metadata` userId.
318
+ */
319
+ relayAuth() {
320
+ return {};
321
+ }
300
322
  /**
301
323
  * Subclass hook: run after launch + navigation, before `ready()` resolves.
302
324
  * Default: no-op. Injected mode overrides it to await the in-page runtime.
@@ -335,6 +357,8 @@ var HeadedTransport = class extends HeadlessTransport {
335
357
  };
336
358
  var require2 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
337
359
  var cachedBundle = null;
360
+ var DIGEST_MAX_ELEMENTS = 10;
361
+ var DIGEST_TIMEOUT_MS = 5e3;
338
362
  function loadInjectedBundle() {
339
363
  if (cachedBundle !== null) return cachedBundle;
340
364
  let bundlePath;
@@ -390,8 +414,8 @@ var InjectedTransport = class extends HeadlessTransport {
390
414
  cfg.registrationMetadata = this.injected.registrationMetadata;
391
415
  if (this.injected.appId) cfg.appId = this.injected.appId;
392
416
  if (this.injected.appName) cfg.appName = this.injected.appName;
393
- if (this.injected.tabId) cfg.tabId = this.injected.tabId;
394
417
  }
418
+ if (this.injected.tabId) cfg.tabId = this.injected.tabId;
395
419
  if (this.injected.settleQuietMs !== void 0)
396
420
  cfg.settleQuietMs = this.injected.settleQuietMs;
397
421
  if (this.injected.settleTimeoutMs !== void 0)
@@ -400,6 +424,18 @@ var InjectedTransport = class extends HeadlessTransport {
400
424
  cfg.expectSelector = this.injected.expectSelector;
401
425
  return Object.keys(cfg).length > 0 ? cfg : null;
402
426
  }
427
+ /**
428
+ * The relay credentials the Node-side registration poll needs. Same bearer the
429
+ * page-side client gets via `__uiBridgeInjectedConfig.authToken`; without it
430
+ * the poll against a gated relay 401s and the CLI reports `tabId: null` on a
431
+ * launch that actually registered.
432
+ */
433
+ relayAuth() {
434
+ return {
435
+ ...this.injected.authToken ? { authToken: this.injected.authToken } : {},
436
+ ...this.injected.registrationMetadata?.userId ? { callerUserId: this.injected.registrationMetadata.userId } : {}
437
+ };
438
+ }
403
439
  async buildInitScripts() {
404
440
  const scripts = [];
405
441
  const cfg = this.injectedConfig();
@@ -449,14 +485,66 @@ var InjectedTransport = class extends HeadlessTransport {
449
485
  }
450
486
  if (state.settledByTimeout && !state.expectSatisfied) {
451
487
  const sel = this.injected.expectSelector;
488
+ 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.`;
489
+ const digest = await this.registeredElementDigest(page);
490
+ if (digest === null) {
491
+ throw new WrapperTransportError("INJECTED_EXPECT_SELECTOR_UNMET", baseMessage, {
492
+ retryable: true
493
+ });
494
+ }
495
+ const summary = digest.length > 0 ? ` Registered: ${digest.map((el) => el.role ? `${el.id} (${el.role})` : el.id).join(", ")}${state.elementCount > digest.length ? ", \u2026" : ""}` : "";
452
496
  throw new WrapperTransportError(
453
497
  "INJECTED_EXPECT_SELECTOR_UNMET",
454
- 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.`,
455
- { retryable: true }
498
+ `${baseMessage}${summary}`,
499
+ {
500
+ retryable: true,
501
+ details: { registeredElements: digest, elementCount: state.elementCount }
502
+ }
456
503
  );
457
504
  }
458
505
  }
459
506
  }
507
+ /**
508
+ * Best-effort digest of the first {@link DIGEST_MAX_ELEMENTS} registered
509
+ * interactive elements, read through the in-page dispatcher's
510
+ * `getControlSnapshot` action (the snapshot's per-element projection is
511
+ * already redaction-safe — we never read raw DOM labels here). Returns
512
+ * `null` on ANY failure or timeout: this feeds error diagnostics only, and a
513
+ * broken page realm must never mask the error being reported.
514
+ */
515
+ async registeredElementDigest(page) {
516
+ let timer;
517
+ try {
518
+ const snapshotPromise = page.evaluate(
519
+ () => window.__uiBridgeInjected.execute("getControlSnapshot", { skipSettle: true })
520
+ );
521
+ const snapshot = await Promise.race([
522
+ snapshotPromise,
523
+ new Promise((_, reject) => {
524
+ timer = setTimeout(() => reject(new Error("digest fetch timed out")), DIGEST_TIMEOUT_MS);
525
+ })
526
+ ]);
527
+ if (!snapshot || typeof snapshot !== "object") return null;
528
+ const elements = snapshot.elements;
529
+ if (!Array.isArray(elements)) return null;
530
+ const digest = [];
531
+ for (const el of elements.slice(0, DIGEST_MAX_ELEMENTS)) {
532
+ if (!el || typeof el !== "object") continue;
533
+ const e = el;
534
+ if (typeof e.id !== "string") continue;
535
+ digest.push({
536
+ id: e.id,
537
+ ...typeof e.role === "string" ? { role: e.role } : {},
538
+ ...typeof e.label === "string" ? { label: e.label } : {}
539
+ });
540
+ }
541
+ return digest;
542
+ } catch {
543
+ return null;
544
+ } finally {
545
+ if (timer !== void 0) clearTimeout(timer);
546
+ }
547
+ }
460
548
  async buildContext() {
461
549
  if (!this.tab) {
462
550
  throw new WrapperTransportError(