@qontinui/ui-bridge-wrapper 0.4.1 → 0.5.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.
@@ -21,7 +21,7 @@
21
21
  * pure functions so they can be unit-tested without spawning a browser or
22
22
  * calling `main()`.
23
23
  */
24
- export declare const USAGE = "ui-bridge-inject \u2014 drive UI Bridge's injected transport against a UI-Bridge-free page\n\nRequired:\n --url <pageUrl> Page to open. Must start with http:// or https://\n (maps to the transport's options.targetUrl)\n\nRelay (Variant B \u2014 the default mode; --relay is REQUIRED in this mode):\n --relay <uiBridgeBase> UI Bridge relay base; the injected runtime registers\n as a relay tab. Example: http://localhost:3001/api/ui-bridge\n --auth-token <T> Bearer token for an auth-gated relay\n --registration-metadata <json>\n JSON {\"userId\":\"...\",\"sessionId\":\"...\"} for per-user\n tab-scoping on relay heartbeats\n --app-id <id> App id reported to the relay registry\n --app-name <name> Display name reported to the relay registry\n --tab-id <id> Stable per-tab id override\n\nExec (Variant A \u2014 one-shot; presence of any --exec/--exec-stdin selects this mode):\n --exec '<action> <json>' Run one action (repeatable). The value is an action\n id, a space, then a JSON payload (payload optional \u2192\n defaults {}). Example: --exec 'find {\"text\":\"Sign in\"}'\n --exec-stdin Read NDJSON lines from stdin; each line is\n {\"action\":\"...\",\"payload\":{...}}\n\nOptional:\n --headed Launch with a visible window (default: headless)\n --ready-timeout <ms> Max wait for the injected runtime ready/settle gate (default 30000)\n --no-settle Gate ready on the runtime being live only, NOT on the DOM\n settling. By default the launcher waits for the page to paint\n + go quiet (so a client-rendered SPA is drivable immediately),\n which is almost always what you want.\n --settle-quiet <ms> Quiet window with no DOM re-seed before settled (default 500)\n --settle-timeout <ms> Hard cap before settling regardless of mutations (default 10000)\n --expect-selector <css> Don't settle until an element matching this CSS selector\n exists \u2014 use when the target control (e.g. a login form)\n mounts lazily after unrelated chrome. If it never appears\n before --settle-timeout, ready() fails with a BLOCKED error\n instead of returning a control-less page.\n --viewport <WxH> Viewport size, e.g. 1280x720\n --quiet Suppress human-readable logs (JSON results still print)\n --help, -h Print this help and exit\n\nExamples:\n # Variant B: register an injected tab against a relay and stay alive\n ui-bridge-inject --url https://example.com/login \\\n --relay http://localhost:3001/api/ui-bridge --app-name \"example login\"\n\n # Variant A: snapshot the controls on a page, then exit\n ui-bridge-inject --url https://example.com/login \\\n --exec 'getControlSnapshot {}'\n\n # Variant A: find a control and act on it\n ui-bridge-inject --url https://example.com/login \\\n --exec 'find {\"text\":\"Sign in\"}'\n";
24
+ export declare const USAGE = "ui-bridge-inject \u2014 drive UI Bridge's injected transport against a UI-Bridge-free page\n\nRequired:\n --url <pageUrl> Page to open. Must start with http:// or https://\n (maps to the transport's options.targetUrl)\n\nRelay (Variant B \u2014 the default mode; --relay is REQUIRED in this mode):\n --relay <uiBridgeBase> UI Bridge relay base; the injected runtime registers\n as a relay tab. Example: http://localhost:3001/api/ui-bridge\n --auth-token <T> Bearer token for an auth-gated relay\n --registration-metadata <json>\n JSON {\"userId\":\"...\",\"sessionId\":\"...\"} for per-user\n tab-scoping on relay heartbeats\n --app-id <id> App id reported to the relay registry\n --app-name <name> Display name reported to the relay registry\n --tab-id <id> Stable per-tab id override\n\nExec (Variant A \u2014 one-shot; presence of any --exec/--exec-stdin selects this mode):\n --exec '<action> <json>' Run one action (repeatable). The value is an action\n id, a space, then a JSON payload (payload optional \u2192\n defaults {}). Example: --exec 'find {\"text\":\"Sign in\"}'\n --exec-stdin Read NDJSON lines from stdin; each line is\n {\"action\":\"...\",\"payload\":{...}}\n\nOptional:\n --storage-state <path> Seed the browser context from a Playwright storageState\n JSON file (cookies + localStorage) produced by\n 'ui-bridge-login-web --storage-state-out <path>'. This\n carries a saved authenticated session past a login wall,\n so you can drive a login-walled page (e.g. an /admin\n wizard) WITHOUT re-driving the hosted-UI login each run.\n --headed Launch with a visible window (default: headless)\n --ready-timeout <ms> Max wait for the injected runtime ready/settle gate (default 30000)\n --no-settle Gate ready on the runtime being live only, NOT on the DOM\n settling. By default the launcher waits for the page to paint\n + go quiet (so a client-rendered SPA is drivable immediately),\n which is almost always what you want.\n --settle-quiet <ms> Quiet window with no DOM re-seed before settled (default 500)\n --settle-timeout <ms> Hard cap before settling regardless of mutations (default 10000)\n --expect-selector <css> Don't settle until an element matching this CSS selector\n exists \u2014 use when the target control (e.g. a login form)\n mounts lazily after unrelated chrome. If it never appears\n before --settle-timeout, ready() fails with a BLOCKED error\n instead of returning a control-less page.\n --viewport <WxH> Viewport size, e.g. 1280x720\n --launch-arg <arg> Extra Chromium command-line argument (repeatable),\n passed through to chromium.launch({ args }).\n NOTE: when --url is https and --relay resolves to a\n loopback host, the LNA-disable flags\n (--disable-features=LocalNetworkAccessChecks,...) are\n auto-appended \u2014 Chromium otherwise blocks the\n https-page \u2192 loopback-relay fetch (Local Network Access).\n --quiet Suppress human-readable logs (JSON results still print)\n --help, -h Print this help and exit\n\nExamples:\n # Variant B: register an injected tab against a relay and stay alive\n ui-bridge-inject --url https://example.com/login \\\n --relay http://localhost:3001/api/ui-bridge --app-name \"example login\"\n\n # Variant A: snapshot the controls on a page, then exit\n ui-bridge-inject --url https://example.com/login \\\n --exec 'getControlSnapshot {}'\n\n # Variant A: find a control and act on it\n ui-bridge-inject --url https://example.com/login \\\n --exec 'find {\"text\":\"Sign in\"}'\n\n # Reuse a saved login: drive a login-walled page with a captured auth artifact\n ui-bridge-login-web --url \"https://qontinui.io/login?next=%2Fadmin\" \\\n --success /admin --storage-state-out auth.json\n ui-bridge-inject --url https://qontinui.io/admin \\\n --storage-state auth.json --exec 'getControlSnapshot {}'\n";
25
25
  /** A single Variant-A action to execute. */
26
26
  export interface ExecAction {
27
27
  action: string;
@@ -48,6 +48,10 @@ export interface InjectCliArgs {
48
48
  tabId: string | null;
49
49
  viewportWidth: number | null;
50
50
  viewportHeight: number | null;
51
+ /** Path to a Playwright storageState JSON file to seed the context (from --storage-state). */
52
+ storageState: string | null;
53
+ /** Extra Chromium launch args collected from --launch-arg flags (in order). */
54
+ launchArgs: string[];
51
55
  /** Variant-A actions collected from --exec flags (in order). */
52
56
  execActions: ExecAction[];
53
57
  /** True if --exec-stdin was given (read NDJSON from stdin in Variant A). */
@@ -77,6 +81,30 @@ export declare function validateArgs(args: InjectCliArgs): void;
77
81
  * otherwise relay registration (Variant B, the default).
78
82
  */
79
83
  export declare function selectMode(args: InjectCliArgs): 'exec' | 'relay';
84
+ /**
85
+ * Chromium feature flags that must be DISABLED for an https page to fetch a
86
+ * loopback (local-network) relay. Chromium's Local Network Access checks
87
+ * otherwise block `https://example.com` → `http://127.0.0.1:<port>` with
88
+ * "Permission was denied for this request to access the 'loopback' address
89
+ * space" (plan 2026-06-12 item 2).
90
+ */
91
+ export declare const LNA_DISABLE_FEATURES: readonly ["LocalNetworkAccessChecks", "PrivateNetworkAccessSendPreflights", "PrivateNetworkAccessRespectPreflightResults"];
92
+ /** True when a URL hostname is a loopback address (localhost / 127/8 / ::1). */
93
+ export declare function isLoopbackHost(hostname: string): boolean;
94
+ /**
95
+ * Compute the effective Chromium launch args: the user's `--launch-arg`
96
+ * values, plus the LNA-disable features auto-appended when the target page
97
+ * is https AND the relay resolves to a loopback host (the combination
98
+ * Chromium's Local Network Access checks block). If the user already passed
99
+ * a `--disable-features=` arg, the missing LNA features are merged into it
100
+ * (Chromium does not union repeated `--disable-features` flags).
101
+ *
102
+ * Pure — exported for unit tests.
103
+ */
104
+ export declare function buildLaunchArgs(args: Pick<InjectCliArgs, 'url' | 'relay' | 'launchArgs'>): {
105
+ launchArgs: string[];
106
+ lnaAutoAppended: boolean;
107
+ };
80
108
  /**
81
109
  * Build the `options` object for `createTransport({ kind: 'injected', options })`.
82
110
  * Only includes keys the user provided; `targetUrl` is always present.
@@ -1 +1 @@
1
- {"version":3,"file":"inject-cli.d.ts","sourceRoot":"","sources":["../src/inject-cli.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAOH,eAAO,MAAM,KAAK,4zGAsDjB,CA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,GAAG,MAAM,KAAG,MAMlC,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,aAAa,GAAI,GAAG,MAAM,EAAE,SAAS,MAAM,KAAG,OAC9B,CAAC;AAE9B;;;;GAIG;AACH,eAAO,MAAM,cAAc,GAAI,GAAG,MAAM,KAAG,OACU,CAAC;AAEtD,6EAA6E;AAC7E,MAAM,WAAW,gBAAgB;IAC/B,EAAE,EAAE,OAAO,CAAC;IACZ,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;CAC1B;AAED,sCAAsC;AACtC,MAAM,WAAW,iBAAiB;IAChC,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,yCAAyC;IACzC,SAAS,EAAE,MAAM,CAAC;IAClB,wEAAwE;IACxE,GAAG,CAAC,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,IAAI,CAAC;CAC3B;AAED;;;;;GAKG;AACH,wBAAsB,eAAe,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAiBxE;AAED;;;;;;;;;GASG;AACH,wBAAsB,UAAU,CAC9B,IAAI,EAAE,IAAI,EACV,EAAE,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,GAAc,EAAE,EAAE,iBAAiB,GAChE,OAAO,CAAC,gBAAgB,CAAC,CAoI3B"}
@@ -2,8 +2,8 @@
2
2
  'use strict';
3
3
 
4
4
  var url = require('url');
5
- var module$1 = require('module');
6
5
  var fs = require('fs');
6
+ var module$1 = require('module');
7
7
 
8
8
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
9
9
  // src/types.ts
@@ -224,36 +224,63 @@ var HeadlessTransport = class extends BaseTransport {
224
224
  uiBridgeBase: typeof raw["uiBridgeBase"] === "string" ? raw["uiBridgeBase"] : void 0,
225
225
  waitForUiBridgeMs: typeof raw["waitForUiBridgeMs"] === "number" ? raw["waitForUiBridgeMs"] : void 0,
226
226
  userAgent: typeof raw["userAgent"] === "string" ? raw["userAgent"] : void 0,
227
- forwardConsole: typeof raw["forwardConsole"] === "boolean" ? raw["forwardConsole"] : void 0
227
+ forwardConsole: typeof raw["forwardConsole"] === "boolean" ? raw["forwardConsole"] : void 0,
228
+ launchArgs: Array.isArray(raw["launchArgs"]) && raw["launchArgs"].every((a) => typeof a === "string") ? raw["launchArgs"] : void 0,
229
+ storageStatePath: typeof raw["storageStatePath"] === "string" ? raw["storageStatePath"] : void 0
228
230
  };
229
231
  }
230
232
  async onReady() {
231
233
  let launchHeadlessTab;
234
+ const headlessSpecifier = "@qontinui/ui-bridge-headless";
232
235
  try {
233
- ({ launchHeadlessTab } = await import('@qontinui/ui-bridge-headless'));
236
+ const mod = await import(headlessSpecifier);
237
+ ({ launchHeadlessTab } = mod);
234
238
  } catch (err) {
235
239
  const cause = err instanceof Error ? err.message : String(err);
236
- throw new WrapperTransportError(
237
- "INVALID_CONFIG",
238
- `Transport kind '${this.kind}' needs the optional '@qontinui/ui-bridge-headless' peer, which is not installed. Install it and the Chromium browser:
240
+ const code = err?.code;
241
+ if (code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND") {
242
+ throw new WrapperTransportError(
243
+ "INVALID_CONFIG",
244
+ `Transport kind '${this.kind}' needs the optional '@qontinui/ui-bridge-headless' peer, which is not installed. Install it and the Chromium browser:
239
245
  npm i @qontinui/ui-bridge-headless && npx playwright install chromium
240
246
  (bare \`npx @qontinui/ui-bridge-wrapper \u2026\` does NOT install peers \u2014 pass each peer with \`-p\`, e.g.
241
247
  npx -y -p @qontinui/ui-bridge-wrapper -p @qontinui/ui-bridge -p @qontinui/ui-bridge-headless -p playwright ui-bridge-login-web \u2026)
242
248
  Underlying import error: ${cause}`
249
+ );
250
+ }
251
+ throw new WrapperTransportError(
252
+ "INVALID_CONFIG",
253
+ `'@qontinui/ui-bridge-headless' is installed but failed to load \u2014 this is a broken install (missing transitive dependency or version skew), not a missing peer. Try reinstalling it. Underlying error: ${cause}`
243
254
  );
244
255
  }
245
256
  const initScripts = await this.buildInitScripts();
246
- const tab = await launchHeadlessTab({
247
- url: this.options.targetUrl,
248
- headless: this.headless,
249
- uiBridgeBase: this.options.uiBridgeBase,
250
- waitForUiBridgeMs: this.options.waitForUiBridgeMs,
251
- viewportWidth: this.options.viewportWidth,
252
- viewportHeight: this.options.viewportHeight,
253
- userAgent: this.options.userAgent,
254
- forwardConsole: this.options.forwardConsole,
255
- initScripts: initScripts.length > 0 ? initScripts : void 0
256
- });
257
+ let tab;
258
+ try {
259
+ tab = await launchHeadlessTab({
260
+ url: this.options.targetUrl,
261
+ headless: this.headless,
262
+ uiBridgeBase: this.options.uiBridgeBase,
263
+ waitForUiBridgeMs: this.options.waitForUiBridgeMs,
264
+ viewportWidth: this.options.viewportWidth,
265
+ viewportHeight: this.options.viewportHeight,
266
+ userAgent: this.options.userAgent,
267
+ forwardConsole: this.options.forwardConsole,
268
+ initScripts: initScripts.length > 0 ? initScripts : void 0,
269
+ launchArgs: this.options.launchArgs && this.options.launchArgs.length > 0 ? this.options.launchArgs : void 0,
270
+ storageStatePath: this.options.storageStatePath
271
+ });
272
+ } catch (err) {
273
+ const cause = err instanceof Error ? err.message : String(err);
274
+ if (/Executable doesn't exist|browserType\.launch/i.test(cause)) {
275
+ throw new WrapperTransportError(
276
+ "INVALID_CONFIG",
277
+ `Playwright's Chromium browser is not installed (the '@qontinui/ui-bridge-headless' peer itself loaded fine). Run:
278
+ npx playwright install chromium
279
+ Underlying launch error: ${cause}`
280
+ );
281
+ }
282
+ throw err;
283
+ }
257
284
  this.tab = {
258
285
  browser: tab.browser,
259
286
  context: tab.context,
@@ -699,11 +726,58 @@ function createTransport(config) {
699
726
  }
700
727
  }
701
728
 
729
+ // src/session-storage-capture.ts
730
+ function isCapturableOrigin(origin) {
731
+ return typeof origin === "string" && origin.length > 0 && origin !== "null";
732
+ }
733
+ function frameOrigin(frameUrl) {
734
+ try {
735
+ const origin = new URL(frameUrl).origin;
736
+ return isCapturableOrigin(origin) ? origin : null;
737
+ } catch {
738
+ return null;
739
+ }
740
+ }
741
+ function buildMultiOriginSessionStorageMap(frames) {
742
+ const out = {};
743
+ for (const frame of frames) {
744
+ if (frame.kv === null) continue;
745
+ const origin = frameOrigin(frame.url);
746
+ if (origin === null) continue;
747
+ out[origin] = { ...out[origin] ?? {}, ...frame.kv };
748
+ }
749
+ return out;
750
+ }
751
+ function mergeMultiOriginSessionStorageIntoArtifact(artifact, map) {
752
+ const existing = artifact.__sessionStorage && typeof artifact.__sessionStorage === "object" ? artifact.__sessionStorage : {};
753
+ const merged = { ...existing };
754
+ for (const origin of Object.keys(map)) {
755
+ merged[origin] = { ...map[origin] };
756
+ }
757
+ artifact.__sessionStorage = merged;
758
+ return artifact;
759
+ }
760
+
702
761
  // src/cli-args.ts
703
762
  var COMMON_FLAGS = /* @__PURE__ */ new Set(["--help", "-h", "--quiet"]);
704
763
  function isFlagShaped(value) {
705
764
  return value.startsWith("--");
706
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
+ }
707
781
  var ArgReader = class {
708
782
  argv;
709
783
  error;
@@ -728,18 +802,14 @@ var ArgReader = class {
728
802
  /**
729
803
  * Value following the value-flag `name`, or `null` when the flag is absent OR
730
804
  * has no following token (the caller defaults it). Throws when the following
731
- * token is flag-shaped — the swallow this kit exists to kill.
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.
732
808
  */
733
809
  value(name) {
734
810
  const i = this.argv.indexOf(name);
735
811
  if (i < 0 || i + 1 >= this.argv.length) return null;
736
- const raw = this.argv[i + 1];
737
- if (isFlagShaped(raw)) {
738
- throw this.error(
739
- `${name} expects a value but got the flag '${raw}' \u2014 did you omit ${name}'s argument?`
740
- );
741
- }
742
- return raw;
812
+ return consumeValue(name, this.argv[i + 1], this.error);
743
813
  }
744
814
  };
745
815
  function makeLogger(prefix, quiet) {
@@ -857,7 +927,7 @@ async function loginDrive(page, { email, password, timeoutMs, log = () => {
857
927
  } catch {
858
928
  const errorText2 = await scrapeErrorCard(page);
859
929
  const finalUrl2 = page.url();
860
- log(`final ${finalUrl2} (stalled)`);
930
+ log(`stalled ${finalUrl2}`);
861
931
  return { ok: false, finalUrl: finalUrl2, landingPath: pathOf(finalUrl2), errorText: errorText2 };
862
932
  }
863
933
  }
@@ -869,9 +939,9 @@ async function loginDrive(page, { email, password, timeoutMs, log = () => {
869
939
  ).catch(() => {
870
940
  });
871
941
  const finalUrl = page.url();
872
- log(`final ${finalUrl}`);
873
942
  const landingPath = await page.evaluate(() => location.pathname).catch(() => pathOf(finalUrl));
874
943
  const ok = !isAppLoginPath(finalUrl) && !isCognito(finalUrl) && !/\/auth\/callback/.test(pathOf(finalUrl));
944
+ log(ok ? `authed ${finalUrl}` : `stalled ${finalUrl}`);
875
945
  const errorText = ok ? null : await scrapeErrorCard(page);
876
946
  return { ok, finalUrl, landingPath, errorText };
877
947
  }
@@ -904,6 +974,14 @@ Options:
904
974
  --screenshot <path> Write a full-page PNG of the authed landing to
905
975
  <path> (captured BEFORE the --expect-text check, so
906
976
  a failing assertion still leaves a diagnostic image).
977
+ --storage-state-out <path> On a confirmed-authed landing, write a Playwright
978
+ storageState JSON (cookies + localStorage) to <path>,
979
+ PLUS a custom __sessionStorage key (origin \u2192 kv) so
980
+ cold replays land authed on apps that keep their
981
+ token in sessionStorage (e.g. qontinui-web).
982
+ Feed it to 'ui-bridge-inject --storage-state <path>'
983
+ to drive a login-walled page MANY times without
984
+ re-driving the hosted-UI login each run.
907
985
  --keep-open On success, park the authed session until SIGINT/
908
986
  SIGTERM instead of closing the browser.
909
987
  --quiet Suppress human-readable stderr logs (the JSON
@@ -923,6 +1001,11 @@ Examples:
923
1001
  ui-bridge-login-web --url "https://qontinui.io/login?next=%2Foperations" \\
924
1002
  --success /operations --expect-text "option2-actions-outage-drill,metric_threshold" \\
925
1003
  --screenshot out.png
1004
+ # Capture a reusable auth artifact, then drive a login-walled page with it:
1005
+ ui-bridge-login-web --url "https://qontinui.io/login?next=%2Fadmin%2Fcoord%2Fonboarding" \\
1006
+ --success /admin/coord/onboarding --storage-state-out auth.json
1007
+ ui-bridge-inject --url https://qontinui.io/admin/coord/onboarding \\
1008
+ --storage-state auth.json --exec 'getControlSnapshot {}'
926
1009
  `;
927
1010
  var LoginCliArgError = class extends Error {
928
1011
  constructor(message) {
@@ -942,16 +1025,19 @@ function parseArgs(argv) {
942
1025
  throw new LoginCliArgError(`--timeout expects a positive integer (got ${timeoutRaw})`);
943
1026
  }
944
1027
  const args = {
945
- url: valueOf("--url") ?? "https://qontinui.io/login",
1028
+ url: rejectEmptyValue("--url", valueOf("--url"), mkError) ?? "https://qontinui.io/login",
946
1029
  email: valueOf("--email") ?? process.env.UIB_LOGIN_EMAIL ?? "",
947
1030
  password: valueOf("--password") ?? process.env.UIB_LOGIN_PASSWORD ?? "",
948
- success: valueOf("--success") ?? "/dashboard",
1031
+ // An EMPTY --success would make `landingPath.includes('')` true on any
1032
+ // landing — ok:true while parked on the login page. Reject it.
1033
+ success: rejectEmptyValue("--success", valueOf("--success"), mkError) ?? "/dashboard",
949
1034
  timeoutMs,
950
1035
  headed: has("--headed"),
951
1036
  postClick: valueOf("--post-login-click"),
952
1037
  expectText: (valueOf("--expect-text") ?? "").split(",").map((s) => s.trim()).filter((s) => s.length > 0),
953
1038
  scrollToText: valueOf("--scroll-to"),
954
1039
  screenshotPath: valueOf("--screenshot"),
1040
+ storageStateOut: valueOf("--storage-state-out"),
955
1041
  keepOpen: has("--keep-open"),
956
1042
  quiet: has("--quiet"),
957
1043
  help
@@ -970,6 +1056,7 @@ var KNOWN_FLAGS = /* @__PURE__ */ new Set([
970
1056
  "--expect-text",
971
1057
  "--scroll-to",
972
1058
  "--screenshot",
1059
+ "--storage-state-out",
973
1060
  "--keep-open",
974
1061
  ...COMMON_FLAGS
975
1062
  ]);
@@ -1001,7 +1088,19 @@ ${USAGE}`);
1001
1088
  process.stdout.write(USAGE);
1002
1089
  process.exit(0);
1003
1090
  }
1004
- const { url, email, password, success, timeoutMs, headed, postClick, expectText, scrollToText, screenshotPath } = args;
1091
+ const {
1092
+ url,
1093
+ email,
1094
+ password,
1095
+ success,
1096
+ timeoutMs,
1097
+ headed,
1098
+ postClick,
1099
+ expectText,
1100
+ scrollToText,
1101
+ screenshotPath,
1102
+ storageStateOut
1103
+ } = args;
1005
1104
  const log = makeLogger("[login-web]", args.quiet);
1006
1105
  const transport = createTransport({
1007
1106
  kind: "injected",
@@ -1016,9 +1115,12 @@ ${USAGE}`);
1016
1115
  }
1017
1116
  const finalUrl = page.url();
1018
1117
  log(`final ${finalUrl}`);
1019
- await page.waitForFunction(() => window.__uiBridgeInjected?.ready === true, {
1020
- timeout: 15e3
1021
- }).catch(() => {
1118
+ await page.waitForFunction(
1119
+ () => window.__uiBridgeInjected?.ready === true,
1120
+ {
1121
+ timeout: 15e3
1122
+ }
1123
+ ).catch(() => {
1022
1124
  });
1023
1125
  let snap = null;
1024
1126
  try {
@@ -1043,6 +1145,9 @@ ${USAGE}`);
1043
1145
  await target.click();
1044
1146
  postLoginClicked = true;
1045
1147
  log(`post-login click: ${postClick}`);
1148
+ await target.waitFor({ state: "hidden", timeout: 2e3 }).catch(
1149
+ () => log(`post-login click target still visible after 2s (non-fatal): ${postClick}`)
1150
+ );
1046
1151
  } catch {
1047
1152
  log(`post-login click target never visible (non-fatal): ${postClick}`);
1048
1153
  }
@@ -1060,6 +1165,50 @@ ${USAGE}`);
1060
1165
  log(`screenshot failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`);
1061
1166
  }
1062
1167
  }
1168
+ let storageStateWritten = null;
1169
+ if (ok && storageStateOut) {
1170
+ try {
1171
+ await ctx.browserContext.storageState({ path: storageStateOut });
1172
+ storageStateWritten = storageStateOut;
1173
+ log(`storage-state written: ${storageStateOut}`);
1174
+ try {
1175
+ const frames = [];
1176
+ for (const frame of page.frames()) {
1177
+ let kv = null;
1178
+ try {
1179
+ kv = await frame.evaluate(() => {
1180
+ const o = {};
1181
+ for (let i = 0; i < sessionStorage.length; i++) {
1182
+ const k = sessionStorage.key(i);
1183
+ if (k !== null) o[k] = sessionStorage.getItem(k) ?? "";
1184
+ }
1185
+ return o;
1186
+ });
1187
+ } catch {
1188
+ kv = null;
1189
+ }
1190
+ frames.push({ url: frame.url(), kv });
1191
+ }
1192
+ const map = buildMultiOriginSessionStorageMap(frames);
1193
+ const artifact = JSON.parse(fs.readFileSync(storageStateOut, "utf8"));
1194
+ mergeMultiOriginSessionStorageIntoArtifact(artifact, map);
1195
+ fs.writeFileSync(storageStateOut, JSON.stringify(artifact));
1196
+ const origins = Object.keys(map);
1197
+ const keyCount = origins.reduce((n, o) => n + Object.keys(map[o]).length, 0);
1198
+ log(
1199
+ `sessionStorage captured across ${origins.length} origin(s) [${origins.join(", ")}]: ${keyCount} key(s) total`
1200
+ );
1201
+ } catch (err) {
1202
+ log(
1203
+ `sessionStorage capture failed (non-fatal, storageState still written): ${err instanceof Error ? err.message : String(err)}`
1204
+ );
1205
+ }
1206
+ } catch (err) {
1207
+ log(
1208
+ `storage-state export failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`
1209
+ );
1210
+ }
1211
+ }
1063
1212
  let expectFound;
1064
1213
  let expectMissing;
1065
1214
  if (ok && expectText.length > 0) {
@@ -1081,7 +1230,8 @@ ${USAGE}`);
1081
1230
  postLoginClicked,
1082
1231
  expectFound,
1083
1232
  expectMissing,
1084
- screenshotPath: screenshotPath ? screenshotWritten : void 0
1233
+ screenshotPath: screenshotPath ? screenshotWritten : void 0,
1234
+ storageStatePath: storageStateOut ? storageStateWritten : void 0
1085
1235
  };
1086
1236
  });
1087
1237
  let result;