@qontinui/ui-bridge-wrapper 0.2.0 → 0.4.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.
package/dist/index.js CHANGED
@@ -1,3 +1,6 @@
1
+ import { createRequire } from 'module';
2
+ import { readFileSync } from 'fs';
3
+
1
4
  // src/types.ts
2
5
  var WrapperTransportError = class extends Error {
3
6
  code;
@@ -221,6 +224,7 @@ var HeadlessTransport = class extends BaseTransport {
221
224
  }
222
225
  async onReady() {
223
226
  const { launchHeadlessTab } = await import('@qontinui/ui-bridge-headless');
227
+ const initScripts = await this.buildInitScripts();
224
228
  const tab = await launchHeadlessTab({
225
229
  url: this.options.targetUrl,
226
230
  headless: this.headless,
@@ -229,7 +233,8 @@ var HeadlessTransport = class extends BaseTransport {
229
233
  viewportWidth: this.options.viewportWidth,
230
234
  viewportHeight: this.options.viewportHeight,
231
235
  userAgent: this.options.userAgent,
232
- forwardConsole: this.options.forwardConsole
236
+ forwardConsole: this.options.forwardConsole,
237
+ initScripts: initScripts.length > 0 ? initScripts : void 0
233
238
  });
234
239
  this.tab = {
235
240
  browser: tab.browser,
@@ -239,6 +244,21 @@ var HeadlessTransport = class extends BaseTransport {
239
244
  tabId: tab.tabId,
240
245
  close: tab.close
241
246
  };
247
+ await this.afterLaunch(tab.page);
248
+ }
249
+ /**
250
+ * Subclass hook: init-scripts to register on the browser context before the
251
+ * first navigation (via `context.addInitScript`). Default: none. Injected
252
+ * mode overrides this to inject the config + runtime bundle pre-paint.
253
+ */
254
+ async buildInitScripts() {
255
+ return [];
256
+ }
257
+ /**
258
+ * Subclass hook: run after launch + navigation, before `ready()` resolves.
259
+ * Default: no-op. Injected mode overrides it to await the in-page runtime.
260
+ */
261
+ async afterLaunch(_page) {
242
262
  }
243
263
  async onClose() {
244
264
  if (!this.tab) return;
@@ -270,6 +290,187 @@ var HeadedTransport = class extends HeadlessTransport {
270
290
  super(config, registry, { kind: "headed", headless: false });
271
291
  }
272
292
  };
293
+ var require2 = createRequire(import.meta.url);
294
+ var cachedBundle = null;
295
+ function loadInjectedBundle() {
296
+ if (cachedBundle !== null) return cachedBundle;
297
+ let bundlePath;
298
+ try {
299
+ bundlePath = require2.resolve("@qontinui/ui-bridge/injected/bundle.global.js");
300
+ } catch {
301
+ const pkgJson = require2.resolve("@qontinui/ui-bridge/package.json");
302
+ bundlePath = pkgJson.replace(/package\.json$/, "dist/injected/bundle.global.js");
303
+ }
304
+ try {
305
+ cachedBundle = readFileSync(bundlePath, "utf8");
306
+ } catch (cause) {
307
+ throw new WrapperTransportError(
308
+ "INJECTED_BUNDLE_MISSING",
309
+ `Could not read the UI Bridge injected runtime bundle at '${bundlePath}'. Ensure @qontinui/ui-bridge is built (the IIFE is emitted by its tsup build).`,
310
+ { cause }
311
+ );
312
+ }
313
+ return cachedBundle;
314
+ }
315
+ var InjectedTransport = class extends HeadlessTransport {
316
+ injected;
317
+ constructor(config, registry) {
318
+ const raw = config.options ?? {};
319
+ const headed = raw["headed"] === true;
320
+ super(config, registry, { kind: "injected", headless: !headed });
321
+ this.injected = {
322
+ headed,
323
+ readyTimeoutMs: typeof raw["readyTimeoutMs"] === "number" ? raw["readyTimeoutMs"] : 3e4,
324
+ waitForSettle: raw["waitForSettle"] !== false,
325
+ settleQuietMs: typeof raw["settleQuietMs"] === "number" ? raw["settleQuietMs"] : void 0,
326
+ settleTimeoutMs: typeof raw["settleTimeoutMs"] === "number" ? raw["settleTimeoutMs"] : void 0,
327
+ expectSelector: typeof raw["expectSelector"] === "string" && raw["expectSelector"].length > 0 ? raw["expectSelector"] : void 0,
328
+ authToken: typeof raw["authToken"] === "string" ? raw["authToken"] : void 0,
329
+ registrationMetadata: isRegistrationMetadata(raw["registrationMetadata"]) ? raw["registrationMetadata"] : void 0,
330
+ appId: typeof raw["appId"] === "string" ? raw["appId"] : void 0,
331
+ appName: typeof raw["appName"] === "string" ? raw["appName"] : void 0,
332
+ tabId: typeof raw["tabId"] === "string" ? raw["tabId"] : void 0
333
+ };
334
+ }
335
+ /**
336
+ * Build the `__uiBridgeInjectedConfig` injected ahead of the bundle, or null
337
+ * if there's nothing to configure. Carries the relay fields (Variant B only,
338
+ * when `uiBridgeBase` is set) AND the settle-tuning fields (both variants).
339
+ */
340
+ injectedConfig() {
341
+ const cfg = {};
342
+ const base = this.options.uiBridgeBase;
343
+ if (base) {
344
+ cfg.uiBridgeBase = base;
345
+ if (this.injected.authToken) cfg.authToken = this.injected.authToken;
346
+ if (this.injected.registrationMetadata)
347
+ cfg.registrationMetadata = this.injected.registrationMetadata;
348
+ if (this.injected.appId) cfg.appId = this.injected.appId;
349
+ if (this.injected.appName) cfg.appName = this.injected.appName;
350
+ if (this.injected.tabId) cfg.tabId = this.injected.tabId;
351
+ }
352
+ if (this.injected.settleQuietMs !== void 0)
353
+ cfg.settleQuietMs = this.injected.settleQuietMs;
354
+ if (this.injected.settleTimeoutMs !== void 0)
355
+ cfg.settleTimeoutMs = this.injected.settleTimeoutMs;
356
+ if (this.injected.expectSelector !== void 0)
357
+ cfg.expectSelector = this.injected.expectSelector;
358
+ return Object.keys(cfg).length > 0 ? cfg : null;
359
+ }
360
+ async buildInitScripts() {
361
+ const scripts = [];
362
+ const cfg = this.injectedConfig();
363
+ if (cfg) {
364
+ scripts.push(`window.__uiBridgeInjectedConfig = ${JSON.stringify(cfg)};`);
365
+ }
366
+ scripts.push(loadInjectedBundle());
367
+ return scripts;
368
+ }
369
+ async afterLaunch(page) {
370
+ try {
371
+ await page.waitForFunction(
372
+ () => window.__uiBridgeInjected?.ready === true,
373
+ void 0,
374
+ { timeout: this.injected.readyTimeoutMs }
375
+ );
376
+ } catch (cause) {
377
+ throw new WrapperTransportError(
378
+ "INJECTED_RUNTIME_NOT_READY",
379
+ `The injected UI Bridge runtime did not report ready within ${this.injected.readyTimeoutMs}ms. The bundle may have failed to evaluate (check page console / CSP) or the page never reached DOMContentLoaded.`,
380
+ { cause, retryable: true }
381
+ );
382
+ }
383
+ if (this.injected.waitForSettle) {
384
+ let state;
385
+ try {
386
+ await page.waitForFunction(
387
+ () => window.__uiBridgeInjected?.settled === true,
388
+ void 0,
389
+ { timeout: this.injected.readyTimeoutMs }
390
+ );
391
+ state = await page.evaluate(() => {
392
+ const api = window.__uiBridgeInjected;
393
+ return {
394
+ settled: api?.settled === true,
395
+ settledByTimeout: api?.settledByTimeout === true,
396
+ expectSatisfied: api?.expectSatisfied === true,
397
+ elementCount: api?.elementCount ?? 0
398
+ };
399
+ });
400
+ } catch (cause) {
401
+ throw new WrapperTransportError(
402
+ "INJECTED_RUNTIME_NOT_SETTLED",
403
+ `The injected UI Bridge runtime did not report settled within ${this.injected.readyTimeoutMs}ms. The page kept mutating past its settle cap, or the realm was torn down. Pass options.waitForSettle=false to gate on ready only, or raise options.settleTimeoutMs / readyTimeoutMs.`,
404
+ { cause, retryable: true }
405
+ );
406
+ }
407
+ if (state.settledByTimeout && !state.expectSatisfied) {
408
+ const sel = this.injected.expectSelector;
409
+ throw new WrapperTransportError(
410
+ "INJECTED_EXPECT_SELECTOR_UNMET",
411
+ 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.`,
412
+ { retryable: true }
413
+ );
414
+ }
415
+ }
416
+ }
417
+ async buildContext() {
418
+ if (!this.tab) {
419
+ throw new WrapperTransportError(
420
+ "NOT_READY",
421
+ `Transport 'injected' is not ready; call ready() before dispatch`
422
+ );
423
+ }
424
+ const { page, context: browserContext, browser, uiBridgeRegistered, tabId } = this.tab;
425
+ const execute = (action, payload) => page.evaluate(
426
+ (args) => window.__uiBridgeInjected.execute(args[0], args[1]),
427
+ [action, payload]
428
+ );
429
+ const settleState = () => page.evaluate(() => {
430
+ const api = window.__uiBridgeInjected;
431
+ return {
432
+ settled: api?.settled === true,
433
+ elementCount: api?.elementCount ?? 0,
434
+ settledByTimeout: api?.settledByTimeout === true,
435
+ expectSatisfied: api?.expectSatisfied === true
436
+ };
437
+ });
438
+ const whenSettled = (timeoutMs) => page.evaluate(
439
+ (ms) => {
440
+ const api = window.__uiBridgeInjected;
441
+ if (api?.whenSettled) return api.whenSettled(ms ?? void 0);
442
+ return Promise.resolve({
443
+ settled: api?.settled === true,
444
+ elementCount: api?.elementCount ?? 0,
445
+ settledByTimeout: api?.settledByTimeout === true,
446
+ expectSatisfied: api?.expectSatisfied === true
447
+ });
448
+ },
449
+ timeoutMs ?? null
450
+ );
451
+ return {
452
+ kind: "injected",
453
+ page,
454
+ browserContext,
455
+ browser,
456
+ uiBridgeRegistered,
457
+ ready: true,
458
+ tabId,
459
+ settleState,
460
+ whenSettled,
461
+ execute,
462
+ find: (criteria) => execute("find", criteria ?? {}),
463
+ act: (id, request) => execute("executeElementAction", { id, request }),
464
+ snapshot: (options) => execute("getControlSnapshot", options ?? {}),
465
+ assert: (spec) => execute("aiAssert", spec)
466
+ };
467
+ }
468
+ };
469
+ function isRegistrationMetadata(value) {
470
+ if (!value || typeof value !== "object") return false;
471
+ const v = value;
472
+ return typeof v.userId === "string" && typeof v.sessionId === "string";
473
+ }
273
474
 
274
475
  // src/transports/live.ts
275
476
  var LiveSessionTransport = class extends BaseTransport {
@@ -466,6 +667,8 @@ function createTransport(config) {
466
667
  return new HeadlessTransport(config);
467
668
  case "headed":
468
669
  return new HeadedTransport(config);
670
+ case "injected":
671
+ return new InjectedTransport(config);
469
672
  case "live": {
470
673
  const opts = config.options ?? {};
471
674
  const injected = typeof opts.webSocketCtor === "function" ? { webSocketCtor: opts.webSocketCtor } : void 0;
@@ -704,6 +907,6 @@ async function startDispatchServer(transport, port, logName) {
704
907
  });
705
908
  }
706
909
 
707
- export { ApiTransport, BaseTransport, HandlerRegistry, HeadedTransport, HeadlessTransport, LiveSessionTransport, WrapperTransportError, createTransport, emitManifestOnly, paramSchemaOf, runWrapperEntrypoint, withAuthRefresh, withRetry };
910
+ export { ApiTransport, BaseTransport, HandlerRegistry, HeadedTransport, HeadlessTransport, InjectedTransport, LiveSessionTransport, WrapperTransportError, createTransport, emitManifestOnly, paramSchemaOf, runWrapperEntrypoint, withAuthRefresh, withRetry };
708
911
  //# sourceMappingURL=index.js.map
709
912
  //# sourceMappingURL=index.js.map