@captello/ulc-webview-sdk 1.1.0 → 1.3.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.
@@ -202,7 +202,14 @@ declare enum OutboundMessageType {
202
202
  /** Connexions: the host should perform the profile redirect (embed mode). */
203
203
  ConnexionsProfileRedirect = "connexions_profile_redirect",
204
204
  /** Connexions: the host should trigger the vCard download (embed mode). */
205
- ConnexionsDownloadVcard = "connexions_download_vcard"
205
+ ConnexionsDownloadVcard = "connexions_download_vcard",
206
+ /**
207
+ * The user pressed the transcribe button (shown only when the embed URL enables
208
+ * it via `show_transcribe_button`): the host should transcribe the request's
209
+ * scan images and answer with an inbound
210
+ * {@link InboundMessageType.TranscribeScannerResult}.
211
+ */
212
+ TranscribeScannerRequest = "transcribe_scanner_request"
206
213
  }
207
214
  /**
208
215
  * Opaque submission payload carried by {@link OutboundMessageType.SubmissionBody}.
@@ -306,8 +313,29 @@ interface ConnexionsProfileRedirectMessage {
306
313
  interface ConnexionsDownloadVcardMessage {
307
314
  type: OutboundMessageType.ConnexionsDownloadVcard;
308
315
  }
316
+ /**
317
+ * Webview → host: the user pressed the transcribe button. Answer with a
318
+ * {@link TranscribeScannerResultMessage} (see
319
+ * {@link CaptelloWebview.onTranscribeScannerRequest} for the handler that does this
320
+ * for you). The webview shows a pending state on the button and gives up with a
321
+ * user-facing error if no result arrives in time.
322
+ *
323
+ * Host processing is a convention, not a one-off: future operations get their own
324
+ * `*_request` / `*_result` message pairs shaped like this one.
325
+ */
326
+ interface TranscribeScannerRequestMessage {
327
+ type: OutboundMessageType.TranscribeScannerRequest;
328
+ /** Correlation id — echo it back verbatim in the result. */
329
+ request_id: string;
330
+ /** The scanner (badge/barcode) element whose scan should be transcribed (e.g. `"element_6"`). */
331
+ element_id: string;
332
+ /** Public URLs of the uploaded scan images (the scanner element's image value). */
333
+ image_urls: string[];
334
+ /** The draft submission token the webview was loaded with, when it has one. */
335
+ draft_submission_token?: string;
336
+ }
309
337
  /** Discriminated union of every message the webview can emit to its host. */
310
- type OutboundMessage = FormLoadCompleteMessage | FormSubmitSuccessMessage | FormErrorMessageMessage | SubmissionBodyMessage | ConnexionsProfileRedirectMessage | ConnexionsDownloadVcardMessage;
338
+ type OutboundMessage = FormLoadCompleteMessage | FormSubmitSuccessMessage | FormErrorMessageMessage | SubmissionBodyMessage | ConnexionsProfileRedirectMessage | ConnexionsDownloadVcardMessage | TranscribeScannerRequestMessage;
311
339
  /** Maps each outbound `type` to its full message shape (used by the client's `.on`). */
312
340
  type OutboundMessageMap = {
313
341
  [M in OutboundMessage as M["type"]]: M;
@@ -323,9 +351,18 @@ declare enum InboundMessageType {
323
351
  /** Switch the current submission into draft-update mode. */
324
352
  UpdateDraft = "update_draft",
325
353
  /** Run validation against a target field (or the whole form). */
326
- TriggerValidation = "trigger_validation"
354
+ TriggerValidation = "trigger_validation",
355
+ /** Answer to an outbound {@link OutboundMessageType.TranscribeScannerRequest}. */
356
+ TranscribeScannerResult = "transcribe_scanner_result"
327
357
  }
328
- /** Shape selector for {@link InboundMessageType.FormPrefill} payloads. */
358
+ /**
359
+ * Shape selector for {@link InboundMessageType.FormPrefill} payloads.
360
+ *
361
+ * Vestigial: the webview keys only off the message `type` and reads `data` directly —
362
+ * it never inspects `data_type`. Confirmed by mutation-testing the integration spec (a
363
+ * deliberately wrong value changed nothing). Kept because it is part of the shipped wire
364
+ * shape and older webview builds may still read it; `prefill()` sets it for you.
365
+ */
329
366
  declare enum PrefillDataType {
330
367
  UlcSubmissionAndInfo = "ulc_submission_and_info"
331
368
  }
@@ -365,8 +402,48 @@ interface PrefillMessage {
365
402
  info?: PrefillInfoItem[];
366
403
  };
367
404
  }
405
+ /**
406
+ * One transcribed field in {@link TranscribeScannerResultData.fields}.
407
+ *
408
+ * Semantically the same thing as a {@link PrefillInfoItem} but in the transcription
409
+ * service's camelCase wire casing — `llFieldIdentifier` carries the same values as
410
+ * `ll_field_unique_identifier` (e.g. `"FirstName"`, `"Email"`), and it is what the
411
+ * webview matches form elements by. The webview ignores fields with an empty `value`
412
+ * rather than blanking already-filled inputs.
413
+ */
414
+ interface TranscribedScannerField {
415
+ /** Catalog field identifier the webview matches on, e.g. `"FirstName"`. */
416
+ llFieldIdentifier: string;
417
+ /** Catalog field id — metadata, not used for matching. */
418
+ llFieldId?: number;
419
+ /** Display name as the transcription service reports it. */
420
+ llFieldNameName?: string;
421
+ value: string;
422
+ }
423
+ /** Success payload of a {@link TranscribeScannerResultMessage}. */
424
+ interface TranscribeScannerResultData {
425
+ fields: TranscribedScannerField[];
426
+ /** How the transcription was produced, e.g. `"ocr_transcription"`. */
427
+ submissionType?: string;
428
+ }
429
+ /**
430
+ * Host → webview: the answer to a {@link TranscribeScannerRequestMessage}. Send
431
+ * `data` with the transcribed fields on success, or `error` (display-ready text) on
432
+ * failure. `request_id` should echo the request's; the webview also accepts a result
433
+ * without one while exactly one request is pending, for hosts that answer strictly
434
+ * one at a time.
435
+ */
436
+ interface TranscribeScannerResultMessage {
437
+ type: InboundMessageType.TranscribeScannerResult;
438
+ /** The `request_id` of the request being answered, verbatim. */
439
+ request_id?: string;
440
+ /** Transcribed fields (success). */
441
+ data?: TranscribeScannerResultData;
442
+ /** Display-ready error text (failure) — leave `data` unset. */
443
+ error?: string;
444
+ }
368
445
  /** Discriminated union of every message the host can send into the webview. */
369
- type InboundMessage = SubmitMessage | ResetMessage | UpdateDraftMessage | TriggerValidationMessage | PrefillMessage;
446
+ type InboundMessage = SubmitMessage | ResetMessage | UpdateDraftMessage | TriggerValidationMessage | PrefillMessage | TranscribeScannerResultMessage;
370
447
  /**
371
448
  * Parses a raw `MessageEvent.data` value into a typed {@link OutboundMessage}, or
372
449
  * returns `null` if it is not a recognized Captello webview message.
@@ -380,8 +457,84 @@ declare function parseOutboundMessage(data: unknown): OutboundMessage | null;
380
457
  type OutboundListener<T extends OutboundMessageType> = (message: OutboundMessageMap[T]) => void;
381
458
  /** Listener for every outbound message (used by {@link CaptelloWebview.onAny}). */
382
459
  type AnyOutboundListener = (message: OutboundMessage) => void;
383
- /** Unsubscribe handle returned by every `on*` method. Calling it removes the listener. */
384
- type Unsubscribe = () => void;
460
+ /**
461
+ * Handler for {@link CaptelloWebview.onTranscribeScannerRequest}. Receives the full
462
+ * request (`element_id`, `image_urls`, `draft_submission_token`) plus a
463
+ * {@link TranscribeScannerReply}, and answers in either style:
464
+ *
465
+ * - **return** the transcribed fields (a promise is fine) — the promise-based style, or
466
+ * - **call `reply.resolve(...)` / `reply.reject(...)`** whenever the work finishes —
467
+ * for callback-style code that can't hand back a promise.
468
+ *
469
+ * Returning nothing hands ownership to `reply`, leaving the request open until it
470
+ * answers. A thrown error / rejection becomes an error result; if it's an `Error`, its
471
+ * `message` is shown to the user by the webview, so throw display-ready messages.
472
+ */
473
+ type TranscribeScannerRequestHandler = (request: TranscribeScannerRequestMessage, reply: TranscribeScannerReply) => TranscribeScannerResultData | void | Promise<TranscribeScannerResultData | void>;
474
+ /**
475
+ * The second argument handed to a {@link TranscribeScannerRequestHandler} — everything
476
+ * needed to answer one request, so the handler never has to reach back out to the
477
+ * client or touch `postMessage` itself.
478
+ *
479
+ * Use it when the transcription can't hand back a promise: a callback-style AJAX
480
+ * wrapper, an event bus, a method that returns `void` and finishes whenever it
481
+ * finishes. Pass it along to whatever does the work and let that code answer:
482
+ *
483
+ * ```js
484
+ * webview.onTranscribeScannerRequest((request, reply) => {
485
+ * transcribeService(request.image_urls,
486
+ * (fields) => reply.resolve({ fields, submissionType: "ocr_transcription" }),
487
+ * () => reply.reject("Transcription failed."),
488
+ * );
489
+ * });
490
+ * ```
491
+ *
492
+ * A handler that returns a value (or a promise of one) is answered from that return
493
+ * value and can ignore this entirely — the promise style is unchanged.
494
+ *
495
+ * The first answer wins: once `resolve`, `reject`, or the handler's own return value
496
+ * has answered, later calls are ignored rather than posting a second result.
497
+ */
498
+ interface TranscribeScannerReply {
499
+ /** Answer with the transcribed fields. */
500
+ resolve(data: TranscribeScannerResultData): void;
501
+ /**
502
+ * Fail the request. `error` is shown to the user by the webview verbatim, so pass
503
+ * display-ready text.
504
+ */
505
+ reject(error: string): void;
506
+ /** `true` once this request has been answered, by either path. */
507
+ readonly answered: boolean;
508
+ }
509
+ /**
510
+ * Identifies the transcribe request being answered by
511
+ * {@link CaptelloWebview.resolveTranscribeScannerRequest} /
512
+ * {@link CaptelloWebview.rejectTranscribeScannerRequest} — the request message itself,
513
+ * or its bare `request_id`.
514
+ *
515
+ * `null`/`undefined` sends an un-correlated result, which the webview accepts only
516
+ * while exactly one request is pending. Pass the request whenever you have it.
517
+ */
518
+ type TranscribeScannerRequestRef = TranscribeScannerRequestMessage | string | null | undefined;
519
+ /** The `unsubscribe()` side of a subscription handle. */
520
+ interface Subscription {
521
+ /** Remove the listener. Safe to call more than once. */
522
+ unsubscribe(): void;
523
+ }
524
+ /**
525
+ * Handle returned by every `on*` method. It is an object carrying
526
+ * {@link Subscription.unsubscribe}, and is also directly callable:
527
+ *
528
+ * ```ts
529
+ * const sub = webview.on(OutboundMessageType.SubmissionBody, save);
530
+ * sub.unsubscribe(); // preferred — reads clearly at the call site
531
+ * sub(); // equivalent
532
+ * ```
533
+ *
534
+ * Both do the same thing; the callable form keeps older `const off = ...; off()`
535
+ * code working.
536
+ */
537
+ type Unsubscribe = (() => void) & Subscription;
385
538
  /**
386
539
  * Rejection reason from {@link CaptelloWebview.submitAndWait} when the webview reports
387
540
  * a `form_error_message`. `message` is the translated, display-ready text.
@@ -401,7 +554,11 @@ interface CaptelloWebviewOptions {
401
554
  /**
402
555
  * Origin to validate incoming messages against and to target outgoing messages.
403
556
  * Strongly recommended — set it to the webview's origin (e.g.
404
- * `"https://capture.captello.com"`), e.g. `new URL(embedUrl).origin`.
557
+ * `"https://capture.captello.com"`).
558
+ *
559
+ * A full URL is accepted and reduced to its origin, so you can pass the embed URL
560
+ * or the webview base URL you already have on hand rather than deriving the origin
561
+ * yourself.
405
562
  *
406
563
  * Defaults to `"*"`, which accepts messages from any origin and posts without an
407
564
  * origin check. Only acceptable for trusted/local development.
@@ -429,8 +586,90 @@ interface CaptelloWebviewOptions {
429
586
  * so its queued messages won't flush — create the client with the iframe.
430
587
  */
431
588
  queueUntilReady?: boolean;
589
+ /**
590
+ * If `true` (default), the client calls {@link CaptelloWebview.destroy} on itself
591
+ * once the bound iframe is removed from the document — so a host that tears down a
592
+ * panel, modal, or route doesn't leak the `message` listener or have to remember a
593
+ * matching `destroy()`.
594
+ *
595
+ * Removal is detected with a `MutationObserver`, and an ancestor being removed
596
+ * counts: what matters is that the iframe is no longer connected to the document.
597
+ * Only ever fires after the iframe has been seen connected, so constructing against
598
+ * a not-yet-inserted element is not mistaken for a teardown.
599
+ *
600
+ * Requires a real DOM element and `MutationObserver`; with a `{ contentWindow }`
601
+ * stand-in, or in a non-DOM environment, there is nothing to observe and this is
602
+ * inert. Set `false` to manage the lifetime entirely yourself — e.g. when you
603
+ * deliberately detach and re-insert the same iframe element.
604
+ */
605
+ autoDestroy?: boolean;
606
+ /**
607
+ * If `true`, the client may learn its webview window from the **first** inbound
608
+ * message instead of being handed an iframe — see {@link attach}, which is the
609
+ * supported way to switch this on.
610
+ *
611
+ * Only ever adopts a sender that has already cleared the origin check and parsed as
612
+ * a well-formed Captello message, so with `targetOrigin` set to the webview's origin
613
+ * only the webview can be adopted. Every later message is source-matched against
614
+ * whatever was adopted, so this is as strict as an explicit iframe after the first
615
+ * message. Under the default `targetOrigin: "*"` that gate is absent — one more
616
+ * reason to set it in production.
617
+ *
618
+ * An explicitly passed iframe always wins; nothing is adopted while one resolves.
619
+ *
620
+ * @default false
621
+ */
622
+ adoptSource?: boolean;
432
623
  }
433
- type ElementOrFrame = HTMLIFrameElement | {
624
+ /** Options for {@link attach}. Same as the client's, minus the ones it manages itself. */
625
+ type AttachOptions = Omit<CaptelloWebviewOptions, "adoptSource">;
626
+ /**
627
+ * Attaches to the embedded Captello webview **without an iframe reference**.
628
+ *
629
+ * This is the drop-in replacement for a hand-rolled global
630
+ * `window.addEventListener("message", …)` dispatcher. Call it once, register your
631
+ * handlers, and you are done — there is nothing to query from the DOM, no ordering to
632
+ * get right relative to when the iframe is created, and no teardown to remember.
633
+ *
634
+ * ```js
635
+ * const webview = CaptelloSdk.attach({ targetOrigin: CAPTURE_PORTAL_WEB_VIEW_BASE });
636
+ *
637
+ * webview.on(CaptelloSdk.OutboundMessageType.FormErrorMessage, (m) => showError(m.data));
638
+ * webview.on(CaptelloSdk.OutboundMessageType.SubmissionBody, (m) => save(m.data));
639
+ * webview.onTranscribeScannerRequest((request, reply) => transcribe(request, reply));
640
+ * ```
641
+ *
642
+ * How it finds the form: the first inbound message that clears the origin check **and**
643
+ * parses as a well-formed Captello message identifies the webview. That sender becomes
644
+ * the target for sends and the window every later message is source-matched against —
645
+ * so after the first message this is as strict as passing the iframe. Set
646
+ * `targetOrigin` to the webview's origin and only the webview can ever be adopted.
647
+ *
648
+ * Teardown is still automatic: a removed iframe's window reports `closed`, which is
649
+ * readable cross-origin, so the client notices its form going away and destroys itself.
650
+ * Pass `autoDestroy: false` to own the lifetime yourself.
651
+ *
652
+ * The trade-off versus {@link CaptelloWebview}: until the form speaks once there is no
653
+ * window to post to, so an unprompted `submit()` / `prefill()` before then has nowhere
654
+ * to go. With the default `queueUntilReady` those sends are buffered and flushed on
655
+ * `form_load_complete`, which covers the normal case. If you drive the form
656
+ * unprompted from page load and can hold the element, prefer
657
+ * `new CaptelloWebview(iframe, …)`.
658
+ */
659
+ declare function attach(options?: AttachOptions): CaptelloWebview;
660
+ /**
661
+ * The webview's iframe — the element itself, or any object exposing its
662
+ * `contentWindow` (useful for test doubles).
663
+ *
664
+ * The caller is responsible for the iframe being mounted before constructing the
665
+ * client: messages are source-matched against its `contentWindow` from the very first
666
+ * one, and sends post to it directly.
667
+ *
668
+ * When a real DOM element is passed, the client also tears itself down automatically
669
+ * once that element leaves the document — see
670
+ * {@link CaptelloWebviewOptions.autoDestroy}.
671
+ */
672
+ type FrameLike = HTMLIFrameElement | {
434
673
  contentWindow: Window | null;
435
674
  };
436
675
  /**
@@ -464,6 +703,14 @@ type ElementOrFrame = HTMLIFrameElement | {
464
703
  */
465
704
  declare class CaptelloWebview {
466
705
  private readonly frame;
706
+ /** Watches for the iframe leaving the document — see `autoDestroy`. */
707
+ private frameObserver?;
708
+ /** The webview window learned from an inbound message — see `adoptSource`. */
709
+ private adoptedWindow;
710
+ private readonly adoptSource;
711
+ private readonly autoDestroy;
712
+ /** Watches an adopted window for `closed` — see `watchAdoptedWindow`. */
713
+ private adoptedPoll?;
467
714
  private readonly targetOrigin;
468
715
  private readonly hostWindow;
469
716
  private readonly matchSource;
@@ -476,7 +723,26 @@ declare class CaptelloWebview {
476
723
  private ready;
477
724
  /** Messages sent before ready, flushed in order on load. */
478
725
  private readonly outbox;
479
- constructor(frame: ElementOrFrame, options?: CaptelloWebviewOptions);
726
+ constructor(frame: FrameLike, options?: CaptelloWebviewOptions);
727
+ /**
728
+ * Tears the client down once the bound iframe leaves the document.
729
+ *
730
+ * Observes the whole document subtree because the iframe usually goes away with an
731
+ * ancestor (a panel or modal being emptied), which produces no mutation on the
732
+ * iframe's own parent. `isConnected` is the actual test, so removal at any depth
733
+ * counts; the observer only bothers checking when a mutation actually removed
734
+ * something.
735
+ */
736
+ /**
737
+ * Tears the client down once an adopted webview window goes away.
738
+ *
739
+ * With no iframe element there is nothing to observe in the DOM, but a removed
740
+ * iframe's `contentWindow` reports `closed === true` — and `closed` is readable
741
+ * cross-origin — so a cheap periodic check is enough. Verified in Chromium against a
742
+ * genuinely cross-origin iframe.
743
+ */
744
+ private watchAdoptedWindow;
745
+ private watchForFrameRemoval;
480
746
  /** `true` once the webview has reported `form_load_complete`. */
481
747
  get isReady(): boolean;
482
748
  /**
@@ -542,9 +808,91 @@ declare class CaptelloWebview {
542
808
  submission?: SubmissionPrefill;
543
809
  info?: PrefillInfoItem[];
544
810
  }): void;
811
+ /**
812
+ * Answer the webview's transcribe requests (its transcribe button — shown when the
813
+ * embed URL sets `showTranscribeButton` — sends `transcribe_scanner_request` when
814
+ * pressed).
815
+ *
816
+ * The handler receives the request (`element_id`, `image_urls`,
817
+ * `draft_submission_token`) and a {@link TranscribeScannerReply}, and answers in
818
+ * whichever style suits the transcription code. Either way the result is posted for
819
+ * you — the host never builds or stringifies a `transcribe_scanner_result`.
820
+ *
821
+ * **Return the fields** when the work is promise-based:
822
+ *
823
+ * ```js
824
+ * webview.onTranscribeScannerRequest(async ({ image_urls }) => {
825
+ * const fields = await transcribe(image_urls);
826
+ * return { fields, submissionType: "ocr_transcription" };
827
+ * });
828
+ * ```
829
+ *
830
+ * **Or answer through `reply`** when it isn't — a callback-style AJAX wrapper, an
831
+ * event bus, a method that returns `void`. Hand `reply` to whatever does the work:
832
+ *
833
+ * ```js
834
+ * webview.onTranscribeScannerRequest((request, reply) => {
835
+ * transcribeService(request.image_urls,
836
+ * (fields) => reply.resolve({ fields, submissionType: "ocr_transcription" }),
837
+ * () => reply.reject("Transcription failed."),
838
+ * );
839
+ * });
840
+ * ```
841
+ *
842
+ * A handler that returns nothing is taken to own the reply, so the request stays
843
+ * open until `reply` answers it. A thrown error / rejected promise is sent as an
844
+ * error result; an `Error`'s `message` is shown to the user by the webview, so throw
845
+ * display-ready messages. The first answer wins — a second is ignored.
846
+ *
847
+ * Returns an unsubscribe function.
848
+ */
849
+ onTranscribeScannerRequest(handler: TranscribeScannerRequestHandler): Unsubscribe;
850
+ /**
851
+ * Answer a transcribe request **later**, from code that can't hand back a promise
852
+ * — a callback-style AJAX wrapper, an event bus, a method that returns `void`.
853
+ *
854
+ * Pair it with a plain `on(OutboundMessageType.TranscribeScannerRequest, ...)`
855
+ * subscription: hold on to the request (or just its `request_id`), and call this
856
+ * once the transcription lands. Prefer {@link onTranscribeScannerRequest} when
857
+ * your transcription code is already promise-based — it does this for you.
858
+ *
859
+ * Accepts the request message itself or its bare `request_id`. The reply is
860
+ * `JSON.stringify`'d and posted immediately, bypassing the ready-queue: a received
861
+ * request already proves the webview is live and listening. Replying after
862
+ * {@link destroy}, or after the iframe is detached, is a silent no-op — by then
863
+ * there is nobody left to answer, and the webview times its own button out.
864
+ *
865
+ * @example
866
+ * webview.on(OutboundMessageType.TranscribeScannerRequest, (request) => {
867
+ * ajax.send("Scanner", "transcribe", { image_urls: request.image_urls },
868
+ * (res) => webview.resolveTranscribeScannerRequest(request, {
869
+ * fields: res.fields,
870
+ * submissionType: "ocr_transcription",
871
+ * }),
872
+ * () => webview.rejectTranscribeScannerRequest(request, "Transcription failed."),
873
+ * );
874
+ * });
875
+ */
876
+ resolveTranscribeScannerRequest(request: TranscribeScannerRequestRef, data: TranscribeScannerResultData): void;
877
+ /**
878
+ * Fail a transcribe request answered via
879
+ * {@link resolveTranscribeScannerRequest}'s deferred flow. `error` is shown to the
880
+ * user verbatim by the webview, so pass display-ready text.
881
+ *
882
+ * Same delivery semantics as {@link resolveTranscribeScannerRequest}: posted
883
+ * immediately, and a no-op once the client is destroyed or the iframe detached.
884
+ */
885
+ rejectTranscribeScannerRequest(request: TranscribeScannerRequestRef, error: string): void;
886
+ /**
887
+ * Posts a `transcribe_scanner_result`, bypassing the ready-queue. A received
888
+ * request proves the webview is live and listening, even if this client attached
889
+ * after form load and never saw `form_load_complete`; queuing here could stall the
890
+ * reply forever while the webview's button sits in its pending state until timeout.
891
+ */
892
+ private sendTranscribeScannerResult;
545
893
  /** Remove the `message` listener and drop all subscriptions. Idempotent. */
546
894
  destroy(): void;
547
895
  private handleMessage;
548
896
  }
549
897
 
550
- export { type AddressSubmissionValue as A, type BusinessCardValue as B, type CaptelloWebviewOptions as C, type DraftSubmissionData as D, FormElementType as F, type InboundMessage as I, type NameSubmissionValue as N, OutboundMessageType as O, type PrefillInfoItem as P, type SubmissionBody as S, type Unsubscribe as U, type ValidationTarget as V, type OutboundMessageMap as a, SubmissionError as b, SubmissionTimeoutError as c, type OutboundMessage as d, type SubmissionPrefill as e, CaptelloWebview as f, type AnyOutboundListener as g, type AttachmentValue as h, InboundMessageType as i, type OrderCheckboxSubmissionData as j, type OrderRadioSubmissionData as k, type OutboundListener as l, type SubmissionPrefillDataItem as m, type SubmissionQuestionData as n, type VisibleSubmissionDataItem as o, type VisibleSubmissionElementType as p, type VisibleSubmissionElementValueMap as q, parseOutboundMessage as r };
898
+ export { type AddressSubmissionValue as A, type BusinessCardValue as B, type CaptelloWebviewOptions as C, type DraftSubmissionData as D, parseOutboundMessage as E, type FrameLike as F, type InboundMessage as I, type NameSubmissionValue as N, OutboundMessageType as O, type PrefillInfoItem as P, type SubmissionBody as S, type TranscribeScannerRequestHandler as T, type Unsubscribe as U, type ValidationTarget as V, type OutboundMessageMap as a, SubmissionError as b, SubmissionTimeoutError as c, type OutboundMessage as d, type SubmissionPrefill as e, CaptelloWebview as f, type AnyOutboundListener as g, type AttachOptions as h, type AttachmentValue as i, FormElementType as j, InboundMessageType as k, type OrderCheckboxSubmissionData as l, type OrderRadioSubmissionData as m, type OutboundListener as n, type SubmissionPrefillDataItem as o, type SubmissionQuestionData as p, type TranscribeScannerReply as q, type TranscribeScannerRequestMessage as r, type TranscribeScannerRequestRef as s, type TranscribeScannerResultData as t, type TranscribeScannerResultMessage as u, type TranscribedScannerField as v, type VisibleSubmissionDataItem as w, type VisibleSubmissionElementType as x, type VisibleSubmissionElementValueMap as y, attach as z };
@@ -0,0 +1,93 @@
1
+ import { F as FrameLike, U as Unsubscribe } from './client-CAMlFA8s.js';
2
+ import { M as MobileHostRequest, a as MobileHostRequestType, b as MobileHostRequestMap, c as MobileHostResponse, S as ScannedPerson } from './mobile-app-protocol-Bt-UDbu5.js';
3
+ export { A as AuthTokenMessage, d as MobileHostResponseMap, e as MobileHostResponseType, f as ScannerClosedMessage, g as ScannerResultMessage, p as parseMobileHostRequest, h as parseMobileHostResponse } from './mobile-app-protocol-Bt-UDbu5.js';
4
+
5
+ /**
6
+ * `@captello/ulc-webview-sdk/embedded-app` — for the **Captello mobile app** (or any
7
+ * host playing its role) that embeds an application in an iframe and serves it native
8
+ * services over `postMessage`.
9
+ *
10
+ * {@link EmbeddedAppClient} wraps the iframe: it delivers the embedded application's
11
+ * requests to typed handlers and posts the app's responses back. The embedded
12
+ * application's own side is `MobileHostClient` (`@captello/ulc-webview-sdk/mobile-host`).
13
+ *
14
+ * Not to be confused with `CaptelloWebview`, which wraps an iframe of the *capture
15
+ * webview* — a different protocol (JSON strings, snake_case types).
16
+ *
17
+ * @example
18
+ * import { EmbeddedAppClient, MobileHostRequestType } from "@captello/ulc-webview-sdk/embedded-app";
19
+ *
20
+ * const embedded = new EmbeddedAppClient(iframe, { targetOrigin: new URL(iframe.src).origin });
21
+ * embedded.onRequest(MobileHostRequestType.RequestAuthToken, async () => {
22
+ * embedded.sendAuthToken(await mintMagicToken());
23
+ * });
24
+ * embedded.onRequest(MobileHostRequestType.OpenScanner, async () => {
25
+ * for (const person of await scan()) embedded.sendScannerResult(person);
26
+ * embedded.sendScannerClosed();
27
+ * });
28
+ */
29
+
30
+ /** Listener for a specific request type from the embedded application. */
31
+ type MobileHostRequestListener<T extends MobileHostRequestType> = (request: MobileHostRequestMap[T]) => void;
32
+ /** Listener for every request from the embedded application (used by {@link EmbeddedAppClient.onAnyRequest}). */
33
+ type AnyMobileHostRequestListener = (request: MobileHostRequest) => void;
34
+ interface EmbeddedAppClientOptions {
35
+ /**
36
+ * Origin to validate incoming requests against and to target outgoing responses.
37
+ * A full URL is accepted and reduced to its origin.
38
+ *
39
+ * Defaults to the iframe's `src` origin, read fresh on every send so a `src` bound
40
+ * after construction still works. When neither is available the client refuses to
41
+ * send rather than fall back to `"*"` — a response can carry an auth token, and
42
+ * `"*"` would hand it to whatever the frame navigated to.
43
+ */
44
+ targetOrigin?: string;
45
+ /** Window to listen on. Defaults to the global `window`. */
46
+ hostWindow?: Window;
47
+ /**
48
+ * Only accept requests whose `event.source` is the bound iframe's window. Defaults
49
+ * to `true`. Set `false` if the application relays through another window.
50
+ */
51
+ matchSource?: boolean;
52
+ }
53
+ /**
54
+ * Mobile-app-side client for an application embedded in an iframe.
55
+ *
56
+ * Attaches a single `message` listener on construction; call {@link destroy} when the
57
+ * iframe goes away.
58
+ */
59
+ declare class EmbeddedAppClient {
60
+ private readonly frame;
61
+ private readonly hostWindow;
62
+ private readonly explicitOrigin;
63
+ private readonly matchSource;
64
+ private readonly listeners;
65
+ private readonly anyListeners;
66
+ private readonly boundHandler;
67
+ private destroyed;
68
+ constructor(frame: FrameLike, options?: EmbeddedAppClientOptions);
69
+ /** Subscribe to one request type. Returns a handle with `unsubscribe()` (also callable). */
70
+ onRequest<T extends MobileHostRequestType>(type: T, listener: MobileHostRequestListener<T>): Unsubscribe;
71
+ /** Subscribe to every request. */
72
+ onAnyRequest(listener: AnyMobileHostRequestListener): Unsubscribe;
73
+ /**
74
+ * Post a response into the embedded application. Returns `false` when nothing was
75
+ * sent: the client is destroyed, the iframe has no window, or no target origin could
76
+ * be resolved (see {@link EmbeddedAppClientOptions.targetOrigin}).
77
+ */
78
+ send(response: MobileHostResponse): boolean;
79
+ /** Answer a {@link MobileHostRequestType.RequestAuthToken} request. */
80
+ sendAuthToken(token: string): boolean;
81
+ /** Post one scanned person of the current scanner session. */
82
+ sendScannerResult(person: ScannedPerson): boolean;
83
+ /** Fail the current scanner session with a display-ready message. */
84
+ sendScannerError(message: string): boolean;
85
+ /** End the current scanner session; send after the last result, or on cancel. */
86
+ sendScannerClosed(): boolean;
87
+ /** Remove the `message` listener and drop every subscription. Safe to call more than once. */
88
+ destroy(): void;
89
+ private resolveOrigin;
90
+ private handleMessage;
91
+ }
92
+
93
+ export { type AnyMobileHostRequestListener, EmbeddedAppClient, type EmbeddedAppClientOptions, FrameLike, MobileHostRequest, type MobileHostRequestListener, MobileHostRequestMap, MobileHostRequestType, MobileHostResponse, ScannedPerson };
@@ -0,0 +1,119 @@
1
+ import { makeSubscription, parseMobileHostRequest } from './chunk-XI5MIDBA.js';
2
+ export { MobileHostRequestType, MobileHostResponseType, parseMobileHostRequest, parseMobileHostResponse } from './chunk-XI5MIDBA.js';
3
+
4
+ // src/embedded-app.ts
5
+ function toOrigin(value) {
6
+ if (!value) return void 0;
7
+ if (value === "*") return value;
8
+ try {
9
+ return new URL(value).origin;
10
+ } catch {
11
+ return void 0;
12
+ }
13
+ }
14
+ var EmbeddedAppClient = class {
15
+ constructor(frame, options = {}) {
16
+ this.listeners = /* @__PURE__ */ new Map();
17
+ this.anyListeners = /* @__PURE__ */ new Set();
18
+ this.boundHandler = (event) => this.handleMessage(event);
19
+ this.destroyed = false;
20
+ if (!frame) {
21
+ throw new Error("EmbeddedAppClient: a mounted iframe element (or { contentWindow }) is required.");
22
+ }
23
+ const hostWindow = options.hostWindow ?? (typeof window !== "undefined" ? window : void 0);
24
+ if (!hostWindow) {
25
+ throw new Error(
26
+ "EmbeddedAppClient: no host window available. Pass `hostWindow` when constructing outside a browser."
27
+ );
28
+ }
29
+ this.frame = frame;
30
+ this.hostWindow = hostWindow;
31
+ this.explicitOrigin = toOrigin(options.targetOrigin);
32
+ this.matchSource = options.matchSource ?? true;
33
+ this.hostWindow.addEventListener("message", this.boundHandler);
34
+ }
35
+ /** Subscribe to one request type. Returns a handle with `unsubscribe()` (also callable). */
36
+ onRequest(type, listener) {
37
+ let set = this.listeners.get(type);
38
+ if (!set) {
39
+ set = /* @__PURE__ */ new Set();
40
+ this.listeners.set(type, set);
41
+ }
42
+ set.add(listener);
43
+ return makeSubscription(() => {
44
+ set?.delete(listener);
45
+ });
46
+ }
47
+ /** Subscribe to every request. */
48
+ onAnyRequest(listener) {
49
+ this.anyListeners.add(listener);
50
+ return makeSubscription(() => {
51
+ this.anyListeners.delete(listener);
52
+ });
53
+ }
54
+ /**
55
+ * Post a response into the embedded application. Returns `false` when nothing was
56
+ * sent: the client is destroyed, the iframe has no window, or no target origin could
57
+ * be resolved (see {@link EmbeddedAppClientOptions.targetOrigin}).
58
+ */
59
+ send(response) {
60
+ if (this.destroyed) return false;
61
+ const target = this.frame.contentWindow;
62
+ const origin = this.resolveOrigin();
63
+ if (!target || !origin) return false;
64
+ target.postMessage(response, origin);
65
+ return true;
66
+ }
67
+ /** Answer a {@link MobileHostRequestType.RequestAuthToken} request. */
68
+ sendAuthToken(token) {
69
+ return this.send({ type: "AUTH_TOKEN" /* AuthToken */, token });
70
+ }
71
+ /** Post one scanned person of the current scanner session. */
72
+ sendScannerResult(person) {
73
+ return this.send({
74
+ type: "ULC_FORM_SCANNER_RESULT" /* ScannerResult */,
75
+ badgeId: person.badgeId,
76
+ result: person.fields
77
+ });
78
+ }
79
+ /** Fail the current scanner session with a display-ready message. */
80
+ sendScannerError(message) {
81
+ return this.send({ type: "ULC_FORM_SCANNER_RESULT" /* ScannerResult */, message });
82
+ }
83
+ /** End the current scanner session; send after the last result, or on cancel. */
84
+ sendScannerClosed() {
85
+ return this.send({ type: "ULC_FORM_SCANNER_CLOSED" /* ScannerClosed */ });
86
+ }
87
+ /** Remove the `message` listener and drop every subscription. Safe to call more than once. */
88
+ destroy() {
89
+ if (this.destroyed) return;
90
+ this.destroyed = true;
91
+ this.hostWindow.removeEventListener("message", this.boundHandler);
92
+ this.listeners.clear();
93
+ this.anyListeners.clear();
94
+ }
95
+ resolveOrigin() {
96
+ if (this.explicitOrigin) return this.explicitOrigin;
97
+ const src = "src" in this.frame ? this.frame.src : void 0;
98
+ return toOrigin(src);
99
+ }
100
+ handleMessage(event) {
101
+ if (this.matchSource && event.source !== this.frame.contentWindow) return;
102
+ const origin = this.resolveOrigin();
103
+ if (origin && origin !== "*" && event.origin !== origin) return;
104
+ const request = parseMobileHostRequest(event.data);
105
+ if (!request) return;
106
+ for (const listener of Array.from(this.anyListeners)) {
107
+ listener(request);
108
+ }
109
+ const set = this.listeners.get(request.type);
110
+ if (!set) return;
111
+ for (const listener of Array.from(set)) {
112
+ listener(request);
113
+ }
114
+ }
115
+ };
116
+
117
+ export { EmbeddedAppClient };
118
+ //# sourceMappingURL=embedded-app.js.map
119
+ //# sourceMappingURL=embedded-app.js.map