@incodetech/core 0.0.0-dev-20260728-af4e1aee → 0.0.0-dev-20260729-e2dda0b0

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.
Files changed (170) hide show
  1. package/dist/BrowserDiagnosticsCryptoProvider-BZqV7sJR.esm.js +96 -0
  2. package/dist/IBrowserEnvironmentCapability-DEaRRk-R.esm.js +9 -0
  3. package/dist/{WasmUtilProvider-BrWOTaVG.esm.js → WasmUtilProvider-D13sxEmA.esm.js} +2 -406
  4. package/dist/{addressSearch-DEYnZoez.esm.js → addressSearch-D_0t2Wdn.esm.js} +2 -2
  5. package/dist/ae-signature.esm.js +1 -1
  6. package/dist/antifraud.esm.js +2 -2
  7. package/dist/{antifraudManager-CFsD4BgV.esm.js → antifraudManager-COYh4O_y.esm.js} +2 -2
  8. package/dist/{antifraudStateMachine-VB-aXHct.esm.js → antifraudStateMachine-NuzlVVte.esm.js} +2 -2
  9. package/dist/api-Bx3gKW_y.esm.js +129 -0
  10. package/dist/{apiError-B-PkYxln.esm.js → apiError-GA6MbJpI.esm.js} +12 -1
  11. package/dist/authentication.d.ts +3 -3
  12. package/dist/authentication.esm.js +2 -2
  13. package/dist/{authenticationManager-BDkpqQ-5.esm.js → authenticationManager-B7v0Jy-x.esm.js} +5 -5
  14. package/dist/{authenticationManager-B2KZQ9zw.d.ts → authenticationManager-BGM8bpD0.d.ts} +1 -1
  15. package/dist/{authenticationStateMachine-lTogTlQv.esm.js → authenticationStateMachine-DAh9ziFC.esm.js} +5 -5
  16. package/dist/camera.esm.js +1 -1
  17. package/dist/certificate-issuance.esm.js +2 -2
  18. package/dist/{certificateIssuanceStateMachine-Di_bLlkP.esm.js → certificateIssuanceStateMachine-N__sTAgu.esm.js} +2 -2
  19. package/dist/consent.d.ts +1 -1
  20. package/dist/consent.esm.js +2 -2
  21. package/dist/{consentManager-DLOyIZzt.d.ts → consentManager-BhYFeKiG.d.ts} +9 -9
  22. package/dist/{consentManager-0EiBXYtL.esm.js → consentManager-CWEAhAJ5.esm.js} +2 -2
  23. package/dist/{consentStateMachine-STURxpEc.esm.js → consentStateMachine-DWL-X0Jb.esm.js} +2 -2
  24. package/dist/cross-document-data-match.esm.js +1 -1
  25. package/dist/{crossDocumentDataMatchManager-Dw7euiiZ.esm.js → crossDocumentDataMatchManager-Bk4W2TDJ.esm.js} +3 -3
  26. package/dist/curp-validation.d.ts +1 -1
  27. package/dist/curp-validation.esm.js +2 -2
  28. package/dist/{curpValidationManager-BGj9U3E0.esm.js → curpValidationManager-B6gYKygj.esm.js} +2 -2
  29. package/dist/{curpValidationManager-BEWD-Lvo.d.ts → curpValidationManager-DVGr7Fq7.d.ts} +1 -1
  30. package/dist/{curpValidationStateMachine-Dq6l4oeZ.esm.js → curpValidationStateMachine-42RbYcam.esm.js} +2 -2
  31. package/dist/custom-fields.esm.js +3 -3
  32. package/dist/custom-watchlist.esm.js +2 -2
  33. package/dist/{customWatchlistStateMachine-BuQML-pk.esm.js → customWatchlistStateMachine-BbDtH5kk.esm.js} +2 -2
  34. package/dist/{deepsightLoader-DDu_KUyv.esm.js → deepsightLoader-CHG26pOB.esm.js} +14 -4
  35. package/dist/document-capture.d.ts +1 -1
  36. package/dist/document-capture.esm.js +2 -2
  37. package/dist/document-upload.d.ts +8 -8
  38. package/dist/document-upload.esm.js +3 -3
  39. package/dist/{documentCaptureManager-B-J1lXcH.d.ts → documentCaptureManager-BK_4RbHt.d.ts} +73 -73
  40. package/dist/{documentCaptureManager-DBRQX16v.esm.js → documentCaptureManager-FvcNYpkS.esm.js} +2 -2
  41. package/dist/{documentCaptureStateMachine-BXgH9gGq.esm.js → documentCaptureStateMachine-BlzN0-mU.esm.js} +4 -4
  42. package/dist/dynamic-forms.d.ts +2 -2
  43. package/dist/dynamic-forms.esm.js +2 -2
  44. package/dist/{dynamicFormsManager-DI0sCyVB.esm.js → dynamicFormsManager-CfJixpOW.esm.js} +8 -4
  45. package/dist/{dynamicFormsManager-BYac2uEY.d.ts → dynamicFormsManager-fhK0yINk.d.ts} +9 -1
  46. package/dist/{dynamicFormsStateMachine-BQqAwNQ-.esm.js → dynamicFormsStateMachine-DrPO1i45.esm.js} +71 -6
  47. package/dist/ekyb.d.ts +1 -1
  48. package/dist/ekyb.esm.js +3 -3
  49. package/dist/{ekybManager-BQQyRMqw.esm.js → ekybManager-DVCqaSzz.esm.js} +2 -2
  50. package/dist/{ekybStateMachine-jsiqdGjv.esm.js → ekybStateMachine-C3y-Qx1a.esm.js} +4 -4
  51. package/dist/ekyc.esm.js +2 -2
  52. package/dist/{ekycManager-Cl2e4Knv.esm.js → ekycManager-dimNksoE.esm.js} +2 -2
  53. package/dist/{ekycStateMachine-9Mm7LBea.esm.js → ekycStateMachine-Yl3sQmhm.esm.js} +3 -3
  54. package/dist/electronic-signature.esm.js +1 -1
  55. package/dist/{electronicSignatureManager-BXIpAJ5m.esm.js → electronicSignatureManager-D0X7P-de.esm.js} +4 -4
  56. package/dist/email.esm.js +2 -2
  57. package/dist/{emailManager-Dmt1YrtS.esm.js → emailManager-BqJMritP.esm.js} +2 -2
  58. package/dist/{emailStateMachine-DQS-QMgQ.esm.js → emailStateMachine-CLtrh2Ot.esm.js} +2 -2
  59. package/dist/{endpoints-CfRg7iAr.esm.js → endpoints-DOfmJylF.esm.js} +8 -1
  60. package/dist/{events-Dy8PyVO5.esm.js → events-CMFCCu1H.esm.js} +2 -9
  61. package/dist/events.esm.js +1 -1
  62. package/dist/extensibility.d.ts +13 -13
  63. package/dist/extensibility.esm.js +26 -32
  64. package/dist/face-match.esm.js +2 -2
  65. package/dist/{faceCaptureManagerFactory-B2TUje5s.d.ts → faceCaptureManagerFactory-B92LFT16.d.ts} +3 -3
  66. package/dist/{faceCaptureManagerFactory-DaYwl0Yq.esm.js → faceCaptureManagerFactory-D2pR3ZnX.esm.js} +3 -3
  67. package/dist/{faceCaptureSetup-DlmX-9nD.esm.js → faceCaptureSetup-DbhDPMjb.esm.js} +5 -5
  68. package/dist/{faceMatchManager-fPX11GnX.esm.js → faceMatchManager-XxTEAj9C.esm.js} +2 -2
  69. package/dist/{faceMatchStateMachine-D_7UX1rV.esm.js → faceMatchStateMachine-ubds4WlI.esm.js} +2 -2
  70. package/dist/field-comparison.esm.js +1 -1
  71. package/dist/{fieldComparisonManager-USUE9qDr.esm.js → fieldComparisonManager-BzaX4TvX.esm.js} +3 -3
  72. package/dist/fiscal-qr.esm.js +3 -3
  73. package/dist/flow-events.d.ts +1 -1
  74. package/dist/flow.d.ts +6 -6
  75. package/dist/flow.esm.js +4 -4
  76. package/dist/{flowCompletionService-D5oIlcza.esm.js → flowCompletionService-BdZR6HyE.esm.js} +3 -3
  77. package/dist/{flowServices-T5JoA_1N.esm.js → flowServices-CPti9am-.esm.js} +8 -6
  78. package/dist/geolocation.esm.js +2 -2
  79. package/dist/{geolocationManager-zeqAcVHC.esm.js → geolocationManager-DW27-LTL.esm.js} +2 -2
  80. package/dist/{geolocationStateMachine-DxSETS9_.esm.js → geolocationStateMachine-Cz3Q6az0.esm.js} +3 -3
  81. package/dist/government-validation.esm.js +2 -2
  82. package/dist/{governmentValidationStateMachine-loZfWcU9.esm.js → governmentValidationStateMachine-CtG3bIdM.esm.js} +2 -2
  83. package/dist/home.d.ts +1 -1
  84. package/dist/home.esm.js +1 -1
  85. package/dist/http.esm.js +1 -1
  86. package/dist/id-ocr.d.ts +1 -1
  87. package/dist/id-ocr.esm.js +2 -2
  88. package/dist/id-verification.esm.js +2 -2
  89. package/dist/id.d.ts +2 -2
  90. package/dist/id.esm.js +5 -5
  91. package/dist/{idCaptureDefaults-DCrjeNl5.esm.js → idCaptureDefaults-BDS43fFL.esm.js} +2 -2
  92. package/dist/{idCaptureManager-D6fKtXhM.d.ts → idCaptureManager-C-WjmsN4.d.ts} +2 -2
  93. package/dist/{idCaptureManager-DaqabBBZ.esm.js → idCaptureManager-CPzgzVu8.esm.js} +4 -4
  94. package/dist/{idCaptureStateMachine-CU1CsT7x.esm.js → idCaptureStateMachine-CAKztWBq.esm.js} +28 -17
  95. package/dist/{idOcrManager-dLuxey6y.d.ts → idOcrManager-DXc_xRN7.d.ts} +1 -1
  96. package/dist/{idOcrManager-CnIWzuqU.esm.js → idOcrManager-Drs6frVO.esm.js} +2 -2
  97. package/dist/{idOcrStateMachine-Cqi8173Y.esm.js → idOcrStateMachine-s08FLvEh.esm.js} +3 -3
  98. package/dist/{idVerificationManager-BTsyXjv6.esm.js → idVerificationManager-Df97Bf0n.esm.js} +2 -2
  99. package/dist/{idVerificationStateMachine-7BSciEJk.esm.js → idVerificationStateMachine-tAF7pvC8.esm.js} +2 -2
  100. package/dist/identity-reuse.d.ts +1 -1
  101. package/dist/identity-reuse.esm.js +2 -2
  102. package/dist/{identityReuseManager-BjMJHKLP.esm.js → identityReuseManager-0ZHGWr9T.esm.js} +2 -2
  103. package/dist/{identityReuseManager-D6pD4hcZ.d.ts → identityReuseManager-v2TH5g7e.d.ts} +1 -1
  104. package/dist/{identityReuseStateMachine-B0IFF3R7.esm.js → identityReuseStateMachine-DG8kbKuy.esm.js} +2 -2
  105. package/dist/{index-X9serOZT.d.ts → index-CLMF0QLQ.d.ts} +1 -1
  106. package/dist/index.d.ts +1 -1
  107. package/dist/index.esm.js +1 -1
  108. package/dist/{invokeOnCaptureCallback-B-QfsCQY.esm.js → invokeOnCaptureCallback-Cgl54qED.esm.js} +1 -1
  109. package/dist/mandatory-consent.d.ts +2 -2
  110. package/dist/mandatory-consent.esm.js +2 -2
  111. package/dist/{mandatoryConsentManager-IKpruo6V.d.ts → mandatoryConsentManager-CzsVFG33.d.ts} +6 -6
  112. package/dist/{mandatoryConsentManager-BOOjm7SU.esm.js → mandatoryConsentManager-DaKK7S4q.esm.js} +2 -2
  113. package/dist/{mandatoryConsentStateMachine-BP3npRnI.esm.js → mandatoryConsentStateMachine-CjKpOQXU.esm.js} +2 -2
  114. package/dist/{onDeviceFaceResults-bUR2uNg0.esm.js → onDeviceFaceResults-CVhk1BWp.esm.js} +13 -6
  115. package/dist/{permissionGuards-5Cu6a8iN.esm.js → permissionGuards-UMiLlPfq.esm.js} +1 -1
  116. package/dist/{permissionServices-CkHL1BjH.esm.js → permissionServices-C4qKxOl4.esm.js} +1 -1
  117. package/dist/personhood.d.ts +1 -1
  118. package/dist/personhood.esm.js +9 -22
  119. package/dist/phone.esm.js +2 -2
  120. package/dist/{phoneManager-C3aqq6jS.esm.js → phoneManager-WImoAp4i.esm.js} +2 -2
  121. package/dist/{phoneStateMachine-CLGcLA8t.esm.js → phoneStateMachine-FJ-_x1G4.esm.js} +2 -2
  122. package/dist/qe-signature.esm.js +1 -1
  123. package/dist/{recordingService-ChBo1rvx.esm.js → recordingService-BGPq5vGr.esm.js} +3 -3
  124. package/dist/redirect-to-mobile.esm.js +2 -2
  125. package/dist/{redirectToMobileManager-BO0BVfgM.esm.js → redirectToMobileManager-CxEu6KnV.esm.js} +2 -2
  126. package/dist/{redirectToMobileStateMachine-BQuhw8_L.esm.js → redirectToMobileStateMachine-jI5XPtZJ.esm.js} +2 -2
  127. package/dist/{runChildModule-Crz1nHwJ.esm.js → runChildModule-fagPe5Ct.esm.js} +6 -1
  128. package/dist/selfie.d.ts +3 -3
  129. package/dist/selfie.esm.js +9 -9
  130. package/dist/{selfieErrorUtils-BAEYvNVr.esm.js → selfieErrorUtils-DCRRRj38.esm.js} +3 -3
  131. package/dist/{selfieManager-BT7dmOHi.d.ts → selfieManager-CxeMb2tM.d.ts} +1 -1
  132. package/dist/{selfieManager-9Eci1f5e.esm.js → selfieManager-DTiBsQNn.esm.js} +5 -5
  133. package/dist/{selfieStateMachine-CKRTfYh8.esm.js → selfieStateMachine-CxabK5_3.esm.js} +3 -3
  134. package/dist/session-Ccob4IUP.esm.js +161 -0
  135. package/dist/session.d.ts +9 -2
  136. package/dist/session.esm.js +4 -152
  137. package/dist/{sessionInitializer-CgjN51b2.esm.js → sessionInitializer-DEd0CQ74.esm.js} +27 -32
  138. package/dist/{setup-BFGd-cxt.esm.js → setup-BR4G3NHV.esm.js} +78 -11
  139. package/dist/{setup-B1WTXTQV.d.ts → setup-Dj8n_YLP.d.ts} +22 -0
  140. package/dist/signature.esm.js +2 -2
  141. package/dist/{signatureStateMachine-zRLvEGTw.esm.js → signatureStateMachine-Dx92l8pR.esm.js} +2 -2
  142. package/dist/{stats-4DAk7TYl.esm.js → stats-6sK3f5pc.esm.js} +2 -2
  143. package/dist/stats.esm.js +1 -1
  144. package/dist/trueSight-4L5GCqKy.esm.js +1 -0
  145. package/dist/trueSightService-DKC-gmQC.esm.js +1891 -0
  146. package/dist/trust-graph.esm.js +1 -1
  147. package/dist/{types-BK-v1UYb.d.ts → types-BBQjIaK4.d.ts} +1 -1
  148. package/dist/{types-xIEGXWk8.d.ts → types-BSBzhHRH.d.ts} +9 -0
  149. package/dist/{types-DjHL5Wa9.d.ts → types-BX_XkMsQ.d.ts} +1 -1
  150. package/dist/{types-DznwkfTc.d.ts → types-C2n-6lCx.d.ts} +1 -1
  151. package/dist/types-CrUhpMDP.d.ts +6 -0
  152. package/dist/{types-NSJbROLr.d.ts → types-KPvmag_B.d.ts} +2 -0
  153. package/dist/video-selfie.d.ts +2 -2
  154. package/dist/video-selfie.esm.js +9 -9
  155. package/dist/wasm.d.ts +1 -1
  156. package/dist/wasm.esm.js +3 -3
  157. package/dist/{wasmDefaults-B4DUtYET.esm.js → wasmDefaults-DJiEvV7f.esm.js} +1 -1
  158. package/dist/wasmWebClient-DM8lkb0z.esm.js +407 -0
  159. package/dist/watchlist-for-business.esm.js +2 -2
  160. package/dist/watchlist.esm.js +2 -2
  161. package/dist/{watchlistForBusinessStateMachine-Rc6BAwlr.esm.js → watchlistForBusinessStateMachine-Eo-WEYha.esm.js} +2 -2
  162. package/dist/{watchlistManager-FRMpgcWW.esm.js → watchlistManager-DnVfNc1v.esm.js} +2 -2
  163. package/dist/{watchlistStateMachine-64y9XBjm.esm.js → watchlistStateMachine-DZSOauwp.esm.js} +2 -2
  164. package/dist/workflow.d.ts +17 -9
  165. package/dist/workflow.esm.js +55 -40
  166. package/package.json +3 -3
  167. package/dist/api-BDTZNnca.esm.js +0 -71
  168. package/dist/clientLifecycle-BX83zwtT.esm.js +0 -528
  169. package/dist/session-B3d0Xtee.esm.js +0 -1
  170. package/dist/types-sK-eGomM.d.ts +0 -6
@@ -0,0 +1,1891 @@
1
+ import { a as setWebApiHttpTransport, i as initializeWasmWebClient, o as setupWasmConnection, r as executeWasmRequest, t as WasmWebClientError } from "./wasmWebClient-DM8lkb0z.esm.js";
2
+ import { t as getTimestamp } from "./IBrowserEnvironmentCapability-DEaRRk-R.esm.js";
3
+ import { i as isApiConfigured, n as getApi, o as setClient, r as getToken, t as api } from "./api-Bx3gKW_y.esm.js";
4
+ import { n as eventModuleNames, v as subscribeEvent } from "./events-CMFCCu1H.esm.js";
5
+ import { t as endpoints } from "./endpoints-DOfmJylF.esm.js";
6
+ //#region ../infra/src/http/createApi.ts
7
+ var FetchHttpError = class extends Error {
8
+ constructor(status, statusText, url, method, headers, data) {
9
+ super(`HTTP ${status} ${statusText}`);
10
+ this.ok = false;
11
+ this.status = status;
12
+ this.statusText = statusText;
13
+ this.url = url;
14
+ this.method = method;
15
+ this.headers = headers;
16
+ this.data = data;
17
+ this.name = "FetchHttpError";
18
+ }
19
+ };
20
+ const buildQueryString$1 = (query) => {
21
+ if (!query) return "";
22
+ const params = new URLSearchParams();
23
+ Object.entries(query).forEach(([key, value]) => {
24
+ if (value !== void 0 && value !== null) params.append(key, String(value));
25
+ });
26
+ const str = params.toString();
27
+ return str ? `?${str}` : "";
28
+ };
29
+ const buildUrl$1 = (baseURL, url, query) => {
30
+ const queryString = buildQueryString$1(query);
31
+ if (url.startsWith("http://") || url.startsWith("https://")) return `${url}${queryString}`;
32
+ return `${baseURL.endsWith("/") ? baseURL.slice(0, -1) : baseURL}${url.startsWith("/") ? url : `/${url}`}${queryString}`;
33
+ };
34
+ const prepareBody$1 = (body) => {
35
+ if (body === null || body === void 0) return null;
36
+ if (body instanceof FormData || body instanceof Blob || body instanceof ArrayBuffer) return body;
37
+ if (typeof body === "object") return JSON.stringify(body);
38
+ return String(body);
39
+ };
40
+ const parseResponse = async (response, parseType) => {
41
+ if (parseType === "response") return response;
42
+ if (parseType === "blob") return await response.blob();
43
+ if (parseType === "arrayBuffer") return await response.arrayBuffer();
44
+ if (parseType === "text") return await response.text();
45
+ const contentType = response.headers.get("content-type") ?? "";
46
+ if (parseType === "json" || contentType.includes("application/json")) {
47
+ const raw = await response.text();
48
+ if (raw.length === 0) return "";
49
+ try {
50
+ return JSON.parse(raw);
51
+ } catch {
52
+ return raw;
53
+ }
54
+ }
55
+ return await response.text();
56
+ };
57
+ const DEFAULT_TIMEOUT$1 = 3e4;
58
+ const requestWithXHR = (fullUrl, method, mergedHeaders, requestBody, timeout, signal, onUploadProgress) => {
59
+ return new Promise((resolve, reject) => {
60
+ const xhr = new XMLHttpRequest();
61
+ xhr.open(method, fullUrl, true);
62
+ Object.entries(mergedHeaders).forEach(([key, value]) => {
63
+ xhr.setRequestHeader(key, value);
64
+ });
65
+ xhr.timeout = timeout;
66
+ xhr.upload.onprogress = (event) => {
67
+ if (event.lengthComputable) {
68
+ const percentComplete = event.loaded / event.total * 100;
69
+ onUploadProgress(Math.round(percentComplete));
70
+ }
71
+ };
72
+ xhr.onload = () => {
73
+ const responseHeaders = {};
74
+ xhr.getAllResponseHeaders().split("\r\n").forEach((line) => {
75
+ const parts = line.split(": ");
76
+ if (parts.length === 2) responseHeaders[parts[0].toLowerCase()] = parts[1];
77
+ });
78
+ let data;
79
+ try {
80
+ if ((xhr.getResponseHeader("content-type") ?? "").includes("application/json")) data = JSON.parse(xhr.responseText);
81
+ else data = xhr.responseText;
82
+ } catch {
83
+ data = xhr.responseText;
84
+ }
85
+ if (xhr.status >= 200 && xhr.status < 300) resolve({
86
+ ok: true,
87
+ status: xhr.status,
88
+ statusText: xhr.statusText,
89
+ url: fullUrl,
90
+ headers: responseHeaders,
91
+ data
92
+ });
93
+ else reject(new FetchHttpError(xhr.status, xhr.statusText, fullUrl, method, responseHeaders, data));
94
+ };
95
+ xhr.onerror = () => {
96
+ reject(new FetchHttpError(0, "Network Error", fullUrl, method, {}, null));
97
+ };
98
+ xhr.ontimeout = () => {
99
+ reject(new FetchHttpError(0, "Request timeout", fullUrl, method, {}, null));
100
+ };
101
+ if (signal) signal.addEventListener("abort", () => {
102
+ xhr.abort();
103
+ reject(new FetchHttpError(0, "Request aborted", fullUrl, method, {}, null));
104
+ });
105
+ xhr.send(requestBody);
106
+ });
107
+ };
108
+ const createApi = (config) => {
109
+ const headers = {
110
+ "Content-Type": "application/json",
111
+ Accept: "application/json",
112
+ "api-version": "1.0",
113
+ ...config.customHeaders ?? {}
114
+ };
115
+ const defaults = {
116
+ baseURL: config.apiURL,
117
+ headers
118
+ };
119
+ const client = {
120
+ defaults,
121
+ async request(requestConfig) {
122
+ const { method = "GET", url, headers = {}, query, params, body, signal, timeout = config.timeout ?? DEFAULT_TIMEOUT$1, parse, onUploadProgress, keepalive } = requestConfig;
123
+ const fullUrl = buildUrl$1(defaults.baseURL, url, params ?? query);
124
+ const mergedHeaders = {
125
+ ...defaults.headers,
126
+ ...headers
127
+ };
128
+ const requestBody = prepareBody$1(body);
129
+ let finalHeaders = mergedHeaders;
130
+ if (requestBody === null && (method === "POST" || method === "PUT" || method === "PATCH")) {
131
+ const { "Content-Type": _, ...headersWithoutContentType } = mergedHeaders;
132
+ finalHeaders = headersWithoutContentType;
133
+ }
134
+ if (onUploadProgress) {
135
+ if (requestBody !== null && typeof ReadableStream !== "undefined" && requestBody instanceof ReadableStream) throw new Error("Upload progress tracking is not supported for ReadableStream bodies");
136
+ return requestWithXHR(fullUrl, method, finalHeaders, requestBody, timeout, signal, onUploadProgress);
137
+ }
138
+ const controller = new AbortController();
139
+ const abortSignal = signal ?? controller.signal;
140
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
141
+ try {
142
+ const response = await fetch(fullUrl, {
143
+ method,
144
+ headers: finalHeaders,
145
+ body: requestBody,
146
+ signal: abortSignal,
147
+ keepalive
148
+ });
149
+ if (timeoutId) clearTimeout(timeoutId);
150
+ const responseHeaders = {};
151
+ response.headers.forEach((value, key) => {
152
+ responseHeaders[key] = value;
153
+ });
154
+ const data = await parseResponse(response, parse);
155
+ if (!response.ok) throw new FetchHttpError(response.status, response.statusText, fullUrl, method, responseHeaders, data);
156
+ return {
157
+ ok: true,
158
+ status: response.status,
159
+ statusText: response.statusText,
160
+ url: fullUrl,
161
+ headers: responseHeaders,
162
+ data
163
+ };
164
+ } catch (error) {
165
+ if (timeoutId) clearTimeout(timeoutId);
166
+ if (error instanceof FetchHttpError) throw error;
167
+ if (error instanceof Error && error.name === "AbortError") throw new FetchHttpError(0, "Request timeout", fullUrl, method, {}, null);
168
+ throw error;
169
+ }
170
+ },
171
+ get(url, config) {
172
+ return client.request({
173
+ ...config,
174
+ url,
175
+ method: "GET"
176
+ });
177
+ },
178
+ post(url, body, config) {
179
+ return client.request({
180
+ ...config,
181
+ url,
182
+ body,
183
+ method: "POST"
184
+ });
185
+ },
186
+ put(url, body, config) {
187
+ return client.request({
188
+ ...config,
189
+ url,
190
+ body,
191
+ method: "PUT"
192
+ });
193
+ },
194
+ patch(url, body, config) {
195
+ return client.request({
196
+ ...config,
197
+ url,
198
+ body,
199
+ method: "PATCH"
200
+ });
201
+ },
202
+ delete(url, config) {
203
+ return client.request({
204
+ ...config,
205
+ url,
206
+ method: "DELETE"
207
+ });
208
+ },
209
+ head(url, config) {
210
+ return client.request({
211
+ ...config,
212
+ url,
213
+ method: "HEAD"
214
+ });
215
+ },
216
+ options(url, config) {
217
+ return client.request({
218
+ ...config,
219
+ url,
220
+ method: "OPTIONS"
221
+ });
222
+ },
223
+ setHeader(name, value) {
224
+ defaults.headers[name] = value;
225
+ }
226
+ };
227
+ return client;
228
+ };
229
+ //#endregion
230
+ //#region ../infra/src/http/createWasmApi.ts
231
+ const RSA_OAEP_SHA256_SCHEME = "RSA/NONE/OAEPWITHSHA-256ANDMGF1PADDING";
232
+ /**
233
+ * Builds the base set of HTTP headers that the WASM WebClient sends on every
234
+ * request (including the internal `/e2ee/key/v2` and `/e2ee/key` handshake
235
+ * calls).
236
+ */
237
+ function buildWasmDefaultHeaders(customHeaders) {
238
+ return {
239
+ "Content-Type": "application/json",
240
+ Accept: "application/json",
241
+ "api-version": "1.0",
242
+ ...customHeaders ?? {}
243
+ };
244
+ }
245
+ var WasmHttpError = class extends Error {
246
+ constructor(status, statusText, url, method, headers, data) {
247
+ super(`HTTP ${status} ${statusText}`);
248
+ this.ok = false;
249
+ this.status = status;
250
+ this.statusText = statusText;
251
+ this.url = url;
252
+ this.method = method;
253
+ this.headers = headers;
254
+ this.data = data;
255
+ this.name = "WasmHttpError";
256
+ }
257
+ };
258
+ const DEFAULT_TIMEOUT = 3e4;
259
+ const HTTP_METHODS = /* @__PURE__ */ new Set([
260
+ "GET",
261
+ "POST",
262
+ "PUT",
263
+ "PATCH",
264
+ "DELETE"
265
+ ]);
266
+ const buildQueryString = (query) => {
267
+ if (!query) return "";
268
+ const params = new URLSearchParams();
269
+ Object.entries(query).forEach(([key, value]) => {
270
+ if (value !== void 0 && value !== null) params.append(key, String(value));
271
+ });
272
+ const str = params.toString();
273
+ return str ? `?${str}` : "";
274
+ };
275
+ const buildUrl = (baseURL, url, query) => {
276
+ const queryString = buildQueryString(query);
277
+ if (url.startsWith("http://") || url.startsWith("https://")) return `${url}${queryString}`;
278
+ return `${baseURL.endsWith("/") ? baseURL.slice(0, -1) : baseURL}${url.startsWith("/") ? url : `/${url}`}${queryString}`;
279
+ };
280
+ const prepareBody = (body) => {
281
+ if (body === null || body === void 0) return void 0;
282
+ if (body instanceof FormData || body instanceof Blob || body instanceof ArrayBuffer || body instanceof Uint8Array || typeof body === "string") return body;
283
+ if (typeof body === "object") return body;
284
+ return String(body);
285
+ };
286
+ const normalizeMethod = (method) => {
287
+ const upper = method.toUpperCase();
288
+ if (!HTTP_METHODS.has(upper)) throw new Error(`Unsupported HTTP method for WASM client: ${method}`);
289
+ return upper;
290
+ };
291
+ const getErrorStatus = (error) => {
292
+ if (error instanceof WasmWebClientError) return error.statusCode;
293
+ if (typeof error === "object" && error !== null) {
294
+ const record = error;
295
+ if (typeof record.statusCode === "number") return record.statusCode;
296
+ if (typeof record.status === "number") return record.status;
297
+ }
298
+ return 0;
299
+ };
300
+ const getErrorData = (error) => {
301
+ if (error instanceof WasmWebClientError) return error.response?.data ?? null;
302
+ return null;
303
+ };
304
+ const getErrorMessage = (error) => {
305
+ if (error instanceof Error) return error.message;
306
+ return "WasmWebClient request failed";
307
+ };
308
+ const withAbortSignal = async (promise, signal, error) => {
309
+ if (!signal) return await promise;
310
+ if (signal.aborted) throw error;
311
+ return await new Promise((resolve, reject) => {
312
+ const onAbort = () => reject(error);
313
+ signal.addEventListener("abort", onAbort, { once: true });
314
+ promise.then(resolve, reject).finally(() => {
315
+ signal.removeEventListener("abort", onAbort);
316
+ });
317
+ });
318
+ };
319
+ const createWasmApi = async (config) => {
320
+ const headers = buildWasmDefaultHeaders(config.customHeaders);
321
+ const isEncryptionEnabled = config.isEncryptionEnabled ?? (() => false);
322
+ const useSha256 = config.mgf1 === "sha256";
323
+ await initializeWasmWebClient(config.wasm.wasmPath, config.wasm.wasmSimdPath ?? config.wasm.wasmPath, config.wasm.glueCodePath, config.wasm.glueCodeSimdPath ?? "", config.wasm.useSimd ?? true);
324
+ await setupWasmConnection(config.apiURL, "", config.encryptionEnabled ?? false, headers, useSha256);
325
+ const defaults = {
326
+ baseURL: config.apiURL,
327
+ headers
328
+ };
329
+ const client = {
330
+ defaults,
331
+ async request(requestConfig) {
332
+ const { method = "GET", url, headers: requestHeaders = {}, query, params, body, signal, timeout = config.timeout ?? DEFAULT_TIMEOUT, onUploadProgress, ie = false } = requestConfig;
333
+ const upperMethod = normalizeMethod(method);
334
+ const requestParams = params ?? query;
335
+ const fullUrl = buildUrl(defaults.baseURL, url, requestParams);
336
+ const needsSchemeHeader = ie || useSha256 && isEncryptionEnabled();
337
+ const mergedHeaders = {
338
+ ...defaults.headers,
339
+ ...needsSchemeHeader ? { "X-RSA-Encryption-Scheme": RSA_OAEP_SHA256_SCHEME } : {},
340
+ ...requestHeaders
341
+ };
342
+ const requestBody = prepareBody(body);
343
+ const wasmProgress = onUploadProgress ? (progress) => {
344
+ if (progress.total > 0) onUploadProgress(Math.round(progress.loaded / progress.total * 100));
345
+ } : void 0;
346
+ const abortError = new WasmHttpError(0, "Request aborted", fullUrl, upperMethod, {}, null);
347
+ if (signal?.aborted) throw abortError;
348
+ try {
349
+ const response = await withAbortSignal(executeWasmRequest(upperMethod, url, requestBody, mergedHeaders, requestParams, timeout, wasmProgress, ie), signal, abortError);
350
+ if (response.status < 200 || response.status >= 300) throw new WasmHttpError(response.status, "", fullUrl, upperMethod, {}, response.data);
351
+ return {
352
+ ok: true,
353
+ status: response.status,
354
+ statusText: "",
355
+ url: fullUrl,
356
+ headers: {},
357
+ data: response.data
358
+ };
359
+ } catch (error) {
360
+ if (error instanceof WasmHttpError) throw error;
361
+ throw new WasmHttpError(getErrorStatus(error), getErrorMessage(error), fullUrl, upperMethod, {}, getErrorData(error));
362
+ }
363
+ },
364
+ get(url, requestConfig) {
365
+ return client.request({
366
+ ...requestConfig,
367
+ url,
368
+ method: "GET"
369
+ });
370
+ },
371
+ post(url, body, requestConfig) {
372
+ return client.request({
373
+ ...requestConfig,
374
+ url,
375
+ body,
376
+ method: "POST"
377
+ });
378
+ },
379
+ put(url, body, requestConfig) {
380
+ return client.request({
381
+ ...requestConfig,
382
+ url,
383
+ body,
384
+ method: "PUT"
385
+ });
386
+ },
387
+ patch(url, body, requestConfig) {
388
+ return client.request({
389
+ ...requestConfig,
390
+ url,
391
+ body,
392
+ method: "PATCH"
393
+ });
394
+ },
395
+ delete(url, requestConfig) {
396
+ return client.request({
397
+ ...requestConfig,
398
+ url,
399
+ method: "DELETE"
400
+ });
401
+ },
402
+ head() {
403
+ return Promise.reject(/* @__PURE__ */ new Error("HEAD is not supported by the WASM HTTP client"));
404
+ },
405
+ options() {
406
+ return Promise.reject(/* @__PURE__ */ new Error("OPTIONS is not supported by the WASM HTTP client"));
407
+ },
408
+ setHeader(name, value) {
409
+ defaults.headers[name] = value;
410
+ }
411
+ };
412
+ return client;
413
+ };
414
+ //#endregion
415
+ //#region src/internal/http/clientLifecycle.ts
416
+ /**
417
+ * Wraps the active HttpClient as a transport for the C++ `WebApi` host
418
+ * adapter. Lets the on-device face-results POST flow through the same
419
+ * `httpClient.request()` pipeline as every other endpoint — header
420
+ * injection, encryption-state handling, default headers, timeout — instead
421
+ * of bypassing it via `executeWasmRequest` directly.
422
+ */
423
+ function bindWebApiTransport(client) {
424
+ return async (url, body, config) => {
425
+ const response = await client.request({
426
+ method: "POST",
427
+ url,
428
+ body,
429
+ headers: config.headers,
430
+ params: config.params,
431
+ timeout: config.timeout,
432
+ ie: config.ie
433
+ });
434
+ return {
435
+ data: response.data,
436
+ status: response.status
437
+ };
438
+ };
439
+ }
440
+ function installClient(client) {
441
+ setClient(client);
442
+ setWebApiHttpTransport(bindWebApiTransport(client));
443
+ }
444
+ let storedHttpConfig;
445
+ /** Reads the current HTTP-client config (or `undefined` if none installed). */
446
+ function getStoredHttpConfig() {
447
+ return storedHttpConfig;
448
+ }
449
+ /** Whether encryption is currently active on the installed HTTP client. */
450
+ function isHttpEncrypted() {
451
+ return storedHttpConfig?.encryption.enabled ?? false;
452
+ }
453
+ /** Clears all HTTP-client state. Called by `reset()`. */
454
+ function resetHttpClientState() {
455
+ storedHttpConfig = void 0;
456
+ setWebApiHttpTransport(null);
457
+ }
458
+ /**
459
+ * Builds (or replaces) the HTTP client when `setup()` receives an `apiURL`.
460
+ * Picks `createWasmApi` when `effectiveWasm` is set, otherwise plain
461
+ * `createApi`. Wraps the call in handshake-failure context when encryption
462
+ * is requested.
463
+ */
464
+ async function installFreshHttpClient(apiURL, options, effectiveWasm, encryption) {
465
+ installClient(effectiveWasm ? await withHandshakeFailureContext(encryption.enabled, () => createWasmApi({
466
+ apiURL,
467
+ customHeaders: options.customHeaders,
468
+ timeout: options.timeout,
469
+ wasm: effectiveWasm,
470
+ encryptionEnabled: encryption.enabled,
471
+ mgf1: encryption.mgf1,
472
+ isEncryptionEnabled: isHttpEncrypted
473
+ })) : createApi({
474
+ apiURL,
475
+ customHeaders: options.customHeaders,
476
+ timeout: options.timeout
477
+ }));
478
+ storedHttpConfig = {
479
+ apiURL,
480
+ customHeaders: options.customHeaders,
481
+ timeout: options.timeout,
482
+ isWasm: Boolean(effectiveWasm),
483
+ encryption
484
+ };
485
+ }
486
+ /**
487
+ * Replaces the active HTTP client with the WASM-backed one. Used internally
488
+ * by lazy-loading UI components (`<incode-flow>`, `<incode-workflow>`) when
489
+ * WASM finishes warming up.
490
+ *
491
+ * No-op when no apiURL was previously configured, or when the active client
492
+ * is already WASM-backed. The encryption state (enabled + MGF1 scheme) is
493
+ * preserved across the swap — this is *not* a user-facing encryption change.
494
+ *
495
+ * @internal NOT a public API. Application code should use
496
+ * `setup({ wasm: {...} })` instead.
497
+ */
498
+ async function upgradeToWasmHttpClient(resolved) {
499
+ const stored = storedHttpConfig;
500
+ if (!stored || stored.isWasm) return;
501
+ installClient(await createWasmApi({
502
+ apiURL: stored.apiURL,
503
+ customHeaders: stored.customHeaders,
504
+ timeout: stored.timeout,
505
+ wasm: resolved,
506
+ encryptionEnabled: stored.encryption.enabled,
507
+ mgf1: stored.encryption.mgf1,
508
+ isEncryptionEnabled: isHttpEncrypted
509
+ }));
510
+ storedHttpConfig = {
511
+ ...stored,
512
+ isWasm: true
513
+ };
514
+ }
515
+ /**
516
+ * When `wantsEncryption` is true, wraps a call that triggers the in-binary
517
+ * RSA/AES handshake so its rejection surfaces as a single, descriptive error
518
+ * with the original error preserved as `cause`. Pass-through otherwise.
519
+ */
520
+ async function withHandshakeFailureContext(wantsEncryption, fn) {
521
+ if (!wantsEncryption) return fn();
522
+ try {
523
+ return await fn();
524
+ } catch (cause) {
525
+ const error = /* @__PURE__ */ new Error("Failed to establish encrypted transport. The /e2ee/key handshake did not complete. Verify the apiURL is reachable and that the environment supports E2EE.");
526
+ error.cause = cause;
527
+ throw error;
528
+ }
529
+ }
530
+ /** Dirty-timer half of the interrupted-snapshot rebuild debounce (module boundaries + timer). */
531
+ const SNAPSHOT_DIRTY_INTERVAL_MS = 15e3;
532
+ /** Hard cap per log message, UTF-8 bytes (contract). */
533
+ const MESSAGE_MAX_BYTES = 8 * 1024;
534
+ const TRUESIGHT_SDK_ID = "IncdOnboarding";
535
+ /** localStorage key prefix for persisted sealed snapshots (A3: one slot per session). */
536
+ const PENDING_STORAGE_KEY_PREFIX = "incode.truesight.pending.";
537
+ //#endregion
538
+ //#region src/internal/trueSight/sanitize.ts
539
+ /**
540
+ * Deny-by-default message scrubber — runs at INGESTION (inside the log buffer's
541
+ * `append`), so the buffer, every persisted snapshot, and every upload are
542
+ * already clean; there is no code path around it (ENG-48677 plan §1.2).
543
+ *
544
+ * Ordered pipeline. Two deliberate deviations from the plan's original rule
545
+ * order, both from the P1-A adversarial review (2026-07-23, recorded in the
546
+ * plan's Operating-decisions section):
547
+ * - Inputs are pre-clamped to 2× the message cap BEFORE any regex runs — the
548
+ * unanchored patterns are quadratic on pathological non-matching runs
549
+ * (measured ~4.5 s on a 100 KB run), so regex cost must be bounded first.
550
+ * The final 8 KB cap still runs last.
551
+ * - The base64-blob rule runs BEFORE the digit-run rule — a digit run inside a
552
+ * blob would otherwise split it into sub-64-char fragments that escape
553
+ * redaction.
554
+ *
555
+ * The regex table ships in the P1-A PR description for privacy sign-off (see
556
+ * .agents/guides/privacy.md). Known hardening backlog (D4, Phase 4): formatted
557
+ * phone numbers, unicode digits/emails, fuzz/property tests.
558
+ */
559
+ /** Three dot-joined base64url segments — JWT/JWS shape. */
560
+ const JWT_PATTERN = /\b[\w-]{8,}\.[\w-]{8,}\.[\w-]{8,}\b/g;
561
+ /**
562
+ * Credential-ish key with a `:`/`=` value (quoted, `Bearer …`, or bare token).
563
+ * The key may carry prefixes (`access_token`, `x-api-key`, `sessionToken`) —
564
+ * a plain \b boundary would miss `_token` since `_` is a word character.
565
+ */
566
+ const CREDENTIAL_KV_PATTERN = /([\w-]*(?:token|api[-_]?key|authorization|auth|secret|password|passwd))\s*[:=]\s*("[^"]*"|'[^']*'|(?:Bearer\s+)?[^\s,;&]+)/gi;
567
+ /** Userinfo credentials in an absolute URL (`https://user:pass@host/…`). */
568
+ const URL_USERINFO_PATTERN = /(\bhttps?:\/\/)[^\s/@]*(?::[^\s/@]*)?@/gi;
569
+ /** Query string / fragment of an absolute URL — kills signed URLs. */
570
+ const URL_TAIL_PATTERN = /(https?:\/\/[^\s?#]+)[?#][^\s]*/g;
571
+ const EMAIL_PATTERN = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
572
+ /** base64-ish blobs (media, keys) — 64+ chars of the base64/base64url alphabet. */
573
+ const BASE64_BLOB_PATTERN = /[-A-Za-z0-9+/_]{64,}={0,2}/g;
574
+ /** Runs of 8+ digits — phones, CURP, document numbers. */
575
+ const DIGIT_RUN_PATTERN = /\d{8,}/g;
576
+ const TRUNCATION_SUFFIX = "…[truncated]";
577
+ /** Regex-cost bound: clamp raw input before any pattern runs (see header note). */
578
+ const REGEX_INPUT_MAX_BYTES = MESSAGE_MAX_BYTES * 2;
579
+ function sanitizeMessage(message) {
580
+ return truncateUtf8(truncateUtf8(message, REGEX_INPUT_MAX_BYTES).replace(JWT_PATTERN, "[jwt]").replace(CREDENTIAL_KV_PATTERN, "$1=[redacted]").replace(URL_USERINFO_PATTERN, "$1[redacted]@").replace(URL_TAIL_PATTERN, "$1").replace(EMAIL_PATTERN, "[email]").replace(BASE64_BLOB_PATTERN, (match) => `[blob:${match.length}]`).replace(DIGIT_RUN_PATTERN, "[digits]"), MESSAGE_MAX_BYTES);
581
+ }
582
+ /**
583
+ * UTF-8 byte length without TextEncoder (banned browser global in L1 —
584
+ * see the no-browser-api-in-core lint rule). Counts by code point.
585
+ */
586
+ function utf8ByteLength(value) {
587
+ let bytes = 0;
588
+ for (const char of value) bytes += codePointByteLength(char);
589
+ return bytes;
590
+ }
591
+ function codePointByteLength(char) {
592
+ const codePoint = char.codePointAt(0) ?? 0;
593
+ if (codePoint < 128) return 1;
594
+ if (codePoint < 2048) return 2;
595
+ if (codePoint < 65536) return 3;
596
+ return 4;
597
+ }
598
+ /** Cuts on a code-point boundary so no surrogate half ever reaches the wire. */
599
+ function truncateUtf8(value, maxBytes) {
600
+ if (utf8ByteLength(value) <= maxBytes) return value;
601
+ const budget = maxBytes - utf8ByteLength(TRUNCATION_SUFFIX);
602
+ let bytes = 0;
603
+ let result = "";
604
+ for (const char of value) {
605
+ const charBytes = codePointByteLength(char);
606
+ if (bytes + charBytes > budget) break;
607
+ bytes += charBytes;
608
+ result += char;
609
+ }
610
+ return result + TRUNCATION_SUFFIX;
611
+ }
612
+ const EVICTION_ORDER = [
613
+ "verbose",
614
+ "debug",
615
+ "info"
616
+ ];
617
+ function createLogBuffer(options = {}) {
618
+ const flushThresholdBytes = options.flushThresholdBytes ?? 6e5;
619
+ const maxEntries = options.maxEntries ?? 5e3;
620
+ const { onOverflow } = options;
621
+ const entries = [];
622
+ let mode = onOverflow ? "flush" : "evict";
623
+ let nextIndex = 0;
624
+ let bytes = 0;
625
+ let dropped = 0;
626
+ let overflowPending = false;
627
+ function entryCost(entry) {
628
+ return utf8ByteLength(entry.message) + utf8ByteLength(entry.subsystem) + 120;
629
+ }
630
+ function removeAt(position) {
631
+ const [removed] = entries.splice(position, 1);
632
+ bytes -= entryCost(removed);
633
+ dropped += 1;
634
+ }
635
+ /** Lowest level first (oldest within it); warning+ only as the last resort. */
636
+ function evictOne() {
637
+ for (const level of EVICTION_ORDER) {
638
+ const position = entries.findIndex((entry) => entry.level === level);
639
+ if (position !== -1) {
640
+ removeAt(position);
641
+ return;
642
+ }
643
+ }
644
+ removeAt(0);
645
+ }
646
+ function copyOf(entry) {
647
+ return { ...entry };
648
+ }
649
+ return {
650
+ append(level, subsystem, category, message) {
651
+ const entry = {
652
+ index: nextIndex,
653
+ timestampMs: getTimestamp(),
654
+ level,
655
+ subsystem,
656
+ category,
657
+ message: sanitizeMessage(message)
658
+ };
659
+ nextIndex += 1;
660
+ entries.push(entry);
661
+ bytes += entryCost(entry);
662
+ if (mode === "flush" && onOverflow) {
663
+ if (!overflowPending && bytes >= flushThresholdBytes) {
664
+ overflowPending = true;
665
+ onOverflow(entries.map(copyOf));
666
+ }
667
+ } else while (bytes > flushThresholdBytes && entries.length > 1) evictOne();
668
+ while (entries.length > maxEntries) evictOne();
669
+ },
670
+ snapshot() {
671
+ return entries.map(copyOf);
672
+ },
673
+ sliceSince(index) {
674
+ return entries.filter((entry) => entry.index > index).map(copyOf);
675
+ },
676
+ markFlushed(uptoIndex) {
677
+ let removedBytes = 0;
678
+ let keepFrom = 0;
679
+ while (keepFrom < entries.length && entries[keepFrom].index <= uptoIndex) {
680
+ removedBytes += entryCost(entries[keepFrom]);
681
+ keepFrom += 1;
682
+ }
683
+ entries.splice(0, keepFrom);
684
+ bytes -= removedBytes;
685
+ overflowPending = false;
686
+ },
687
+ setOverflowMode(next) {
688
+ mode = next;
689
+ },
690
+ get droppedCount() {
691
+ return dropped;
692
+ },
693
+ get byteEstimate() {
694
+ return bytes;
695
+ }
696
+ };
697
+ }
698
+ //#endregion
699
+ //#region ../infra/src/crypto/randomUUID.ts
700
+ /**
701
+ * Cryptographically-strong UUID v4 (RFC 4122).
702
+ *
703
+ * Lives in infra (L0) so Core (L1) can mint secure identifiers without touching
704
+ * the `crypto` browser API directly — Core delegates here, keeping it free of
705
+ * browser globals (enforced by the `no-browser-api-in-core` lint rule). Backed
706
+ * by `crypto.randomUUID`, available in every browser the SDK targets.
707
+ */
708
+ function randomUUID() {
709
+ return crypto.randomUUID();
710
+ }
711
+ //#endregion
712
+ //#region ../infra/src/time/epochMsToIsoString.ts
713
+ /**
714
+ * Converts an epoch-milliseconds timestamp to a full ISO-8601 UTC string
715
+ * (e.g. `2026-07-23T09:41:00.000Z`).
716
+ *
717
+ * Lives in Infra (L0) so Core can format wire timestamps without touching the
718
+ * `Date` global directly — banned in Core by the `no-browser-api-in-core` lint
719
+ * rule — mirroring the `crypto/randomUUID.ts` free-function precedent.
720
+ * (`DateFormattingProvider.utcToIsoDateString` is date-only and not suitable.)
721
+ */
722
+ function epochMsToIsoString(epochMs) {
723
+ return new Date(epochMs).toISOString();
724
+ }
725
+ //#endregion
726
+ //#region src/internal/version/sdkVersion.ts
727
+ const SDK_VERSION = "0.0.0-dev-20260729-e2dda0b0";
728
+ //#endregion
729
+ //#region src/internal/trueSight/recordBuilder.ts
730
+ /**
731
+ * Assembles the exact plaintext contract record — the ONLY place a diagnostics
732
+ * payload is shaped. Pure: same function serves final records, interrupted
733
+ * snapshots, and future incremental slices (ENG-48677 plan §1.1).
734
+ *
735
+ * Deny-by-default is structural here: every field is an explicit literal —
736
+ * nothing is spread from internal state, so no unexpected field can ever leak
737
+ * into an upload.
738
+ *
739
+ * Hard gates enforced:
740
+ * - empty/missing `sessionId` or `startedAt` → returns `null` (upload skipped —
741
+ * expected for sessions that die before `/omni/start`).
742
+ * - `failureReason` present if-and-only-if `outcome === 'failure'` (defaults to
743
+ * `'unknown'` when a failure arrives without one, rather than dropping the record).
744
+ * - fresh record `id` per build; `endedAt` stamped at build time.
745
+ */
746
+ function buildDiagnosticsRecord(meta, logs, outcome, failureReason, recordId) {
747
+ if (!meta.sessionId || meta.startedAtMs === null) return null;
748
+ const flowType = meta.flowType ?? deriveFlowTypeFromSurface(meta.integrationType);
749
+ if (flowType === null) return null;
750
+ return {
751
+ schemaVersion: "1.0",
752
+ id: recordId ?? randomUUID(),
753
+ session: {
754
+ sessionId: meta.sessionId,
755
+ sdkId: TRUESIGHT_SDK_ID,
756
+ sdkVersion: SDK_VERSION,
757
+ platform: "web",
758
+ sdkMode: null,
759
+ browser: meta.browser,
760
+ osVersion: meta.osVersion,
761
+ osLanguage: meta.osLanguage,
762
+ sdkLanguage: meta.sdkLanguage,
763
+ integrationType: meta.integrationType,
764
+ flowType,
765
+ flowId: meta.flowId,
766
+ workflowId: meta.workflowId,
767
+ outcome,
768
+ ...outcome === "failure" ? { failureReason: failureReason ?? "unknown" } : {},
769
+ startedAt: epochMsToIsoString(meta.startedAtMs),
770
+ endedAt: epochMsToIsoString(getTimestamp()),
771
+ testing: meta.testing,
772
+ e2eEncryptionEnabled: meta.e2eEncryptionEnabled,
773
+ configurationId: meta.hasConfigurationId,
774
+ externalCustomerId: meta.hasExternalCustomerId,
775
+ hasProvidedSessionId: meta.hasProvidedSessionId,
776
+ token: meta.hasToken,
777
+ externalToken: meta.hasExternalToken
778
+ },
779
+ logs: logs.map(toContractEntry)
780
+ };
781
+ }
782
+ /**
783
+ * Wire `flowType` when no orchestrator was OBSERVED (an observed one — set by
784
+ * the bridge on any flow event — always wins). Stage ingest requires a
785
+ * non-null enum (probe 2026-07-23: null/omitted/off-enum all 400), so the
786
+ * entry surface decides, and the mapping is deliberately exhaustive:
787
+ *
788
+ * - `startWorkflow` → 'workflow' (Webflows engine entered, died pre-ready)
789
+ * - `startFlow` → 'flow' (flow/orchestrated manager, died pre-ready)
790
+ * - `startOnboarding`→ 'flow' (self-loading UI wraps the flow engine)
791
+ * - `startOnboardingSection` → null → the BUILD ABORTS (record withheld):
792
+ * a standalone session has no truthful flowType, and mislabeling it as a
793
+ * flow session is worse than skipping the upload. Withheld until the
794
+ * DECIDED BE ask ships (`flowType:"standalone"`, not nullable) — then this
795
+ * branch returns 'standalone' and standalone diagnostics start flowing,
796
+ * coordinated with the BE deploy since off-enum values 400 today.
797
+ */
798
+ function deriveFlowTypeFromSurface(integrationType) {
799
+ switch (integrationType) {
800
+ case "startWorkflow": return "workflow";
801
+ case "startFlow":
802
+ case "startOnboarding": return "flow";
803
+ case "startOnboardingSection": return null;
804
+ }
805
+ }
806
+ function toContractEntry(entry) {
807
+ return {
808
+ index: entry.index,
809
+ timestamp: epochMsToIsoString(entry.timestampMs),
810
+ level: entry.level,
811
+ thread: "main",
812
+ message: entry.message,
813
+ subsystem: entry.subsystem,
814
+ category: entry.category
815
+ };
816
+ }
817
+ //#endregion
818
+ //#region src/internal/trueSight/sessionMetadata.ts
819
+ /**
820
+ * Hosts that match this pattern are non-prod by heuristic. Known failure modes
821
+ * (customer CNAMEs, devMode left on in prod) are documented for the planned
822
+ * P1 team review — see plan §Operating decisions (B6).
823
+ */
824
+ const NON_PROD_HOST_PATTERN = /stage|demo|saas-dev|localhost/i;
825
+ function createInitialState() {
826
+ return {
827
+ sessionId: null,
828
+ startedAtMs: null,
829
+ browser: null,
830
+ osVersion: null,
831
+ osLanguage: null,
832
+ sdkLanguage: "en-US",
833
+ integrationType: "startOnboardingSection",
834
+ flowType: null,
835
+ flowId: null,
836
+ workflowId: null,
837
+ testing: false,
838
+ devModeSignal: void 0,
839
+ apiUrlSignal: void 0,
840
+ hasConfigurationId: false,
841
+ hasExternalCustomerId: false,
842
+ hasProvidedSessionId: false,
843
+ hasExternalToken: false
844
+ };
845
+ }
846
+ let state = createInitialState();
847
+ let sources = {};
848
+ function stampStartedAtOnce() {
849
+ if (state.startedAtMs === null) state.startedAtMs = getTimestamp();
850
+ }
851
+ /** Tap for `createSession` — sessionId comes from the returned `interviewId`. */
852
+ function noteSessionCreated(session, options = {}) {
853
+ if (session.interviewId) state.sessionId = session.interviewId;
854
+ stampStartedAtOnce();
855
+ state.sdkLanguage = options.language ?? state.sdkLanguage;
856
+ state.hasConfigurationId = state.hasConfigurationId || options.configurationId !== void 0;
857
+ state.hasExternalCustomerId = state.hasExternalCustomerId || options.externalCustomerId !== void 0;
858
+ state.hasProvidedSessionId = state.hasProvidedSessionId || options.interviewId !== void 0;
859
+ }
860
+ /**
861
+ * Fallback sessionId for host-minted-token integrations that never called
862
+ * `createSession`: `Features.sessionIdentifier` — used only when no
863
+ * `interviewId` was observed.
864
+ */
865
+ function noteFeatureConfig(features) {
866
+ if (!state.sessionId && features.sessionIdentifier) {
867
+ state.sessionId = features.sessionIdentifier;
868
+ stampStartedAtOnce();
869
+ }
870
+ }
871
+ /**
872
+ * Entry-surface discriminator. `startOnboardingSection` is the default (weakest
873
+ * signal — standalone module managers); richer surfaces upgrade it and are never
874
+ * downgraded back.
875
+ */
876
+ function noteIntegrationSurface(integrationType) {
877
+ if (integrationType === "startOnboardingSection") return;
878
+ state.integrationType = integrationType;
879
+ }
880
+ function noteEnvironment(environment) {
881
+ state.browser = environment.browser ?? state.browser;
882
+ state.osVersion = environment.osVersion ?? state.osVersion;
883
+ state.osLanguage = environment.osLanguage ?? state.osLanguage;
884
+ }
885
+ /**
886
+ * WRITE-ONCE orchestrator identity (determinism guarantee for debugging):
887
+ * a session is a flow or a workflow from its first orchestrator observation
888
+ * and can never flip mid-session — a record labeled `flow` must always point
889
+ * at a real flow. First non-null value wins for each of flowType/flowId/
890
+ * workflowId; later calls are ignored (the service logs a self-health line
891
+ * when a CONFLICTING orchestrator kind shows up).
892
+ */
893
+ function noteFlowContext(context) {
894
+ state.flowType = state.flowType ?? context.flowType;
895
+ state.flowId = state.flowId ?? context.flowId ?? null;
896
+ state.workflowId = state.workflowId ?? context.workflowId ?? null;
897
+ }
898
+ /**
899
+ * `testing` heuristic: devMode OR non-prod API host pattern. Always a boolean —
900
+ * the contract requires the field present on every record. Signals MERGE across
901
+ * calls (a later apiUrl-only call must not erase an earlier devMode signal);
902
+ * `testing` is recomputed from the merged pair.
903
+ */
904
+ function noteTestingSignals(signals) {
905
+ state.devModeSignal = signals.devMode ?? state.devModeSignal;
906
+ state.apiUrlSignal = signals.apiUrl ?? state.apiUrlSignal;
907
+ state.testing = state.devModeSignal === true || state.apiUrlSignal !== void 0 && NON_PROD_HOST_PATTERN.test(state.apiUrlSignal);
908
+ }
909
+ /**
910
+ * Live read of the merged testing signal (devMode OR non-prod host). Used to
911
+ * gate host-console self-health noise so production host pages stay quiet while
912
+ * staging/dev keeps the console signal (the record always captures it either
913
+ * way via `trueSightLog`). Same signal the overflow-flush staging gate uses.
914
+ */
915
+ function isTrueSightTesting() {
916
+ return state.testing;
917
+ }
918
+ /**
919
+ * Tap for `initializeSession({ token })` with a host-minted token — records
920
+ * only the presence fact ("this token came from outside the SDK"), never the
921
+ * token itself.
922
+ */
923
+ function noteExternalTokenProvided() {
924
+ state.hasExternalToken = true;
925
+ }
926
+ /**
927
+ * Wiring tap for every `initializeSession({ token })`: a token activated
928
+ * before any `createSession` was observed on this page is host-minted, i.e.
929
+ * external. (The exact `token`/`externalToken` web-semantics are a pending
930
+ * Phase 0 contract ask — this inference is the interim mapping.)
931
+ */
932
+ function noteTokenActivated() {
933
+ if (state.sessionId === null) noteExternalTokenProvided();
934
+ }
935
+ function configureTrueSightMetadataSources(next) {
936
+ sources = next;
937
+ }
938
+ /** Explicit literal — the metadata half handed to the record builder. */
939
+ function buildSessionMetadata() {
940
+ return {
941
+ sessionId: state.sessionId,
942
+ startedAtMs: state.startedAtMs,
943
+ browser: state.browser,
944
+ osVersion: state.osVersion,
945
+ osLanguage: state.osLanguage,
946
+ sdkLanguage: state.sdkLanguage,
947
+ integrationType: state.integrationType,
948
+ flowType: state.flowType,
949
+ flowId: state.flowId,
950
+ workflowId: state.workflowId,
951
+ testing: state.testing,
952
+ e2eEncryptionEnabled: readE2eEncryptionEnabled(),
953
+ hasConfigurationId: state.hasConfigurationId,
954
+ hasExternalCustomerId: state.hasExternalCustomerId,
955
+ hasProvidedSessionId: state.hasProvidedSessionId,
956
+ hasToken: readHasToken(),
957
+ hasExternalToken: state.hasExternalToken
958
+ };
959
+ }
960
+ /** Fail-open: diagnostics must never throw into the host flow. */
961
+ function readE2eEncryptionEnabled() {
962
+ try {
963
+ return sources.getE2eEncryptionEnabled?.() ?? false;
964
+ } catch {
965
+ return false;
966
+ }
967
+ }
968
+ /** Fail-open, like readE2eEncryptionEnabled. */
969
+ function readHasToken() {
970
+ try {
971
+ return sources.getHasToken?.() ?? false;
972
+ } catch {
973
+ return false;
974
+ }
975
+ }
976
+ function resetTrueSightMetadata() {
977
+ state = createInitialState();
978
+ sources = {};
979
+ }
980
+ //#endregion
981
+ //#region src/internal/trueSight/pendingEnvelopeStore.ts
982
+ /** Index slot listing sessionIds with pending entries (no enumeration API). */
983
+ const PENDING_INDEX_KEY = `${PENDING_STORAGE_KEY_PREFIX}index`;
984
+ function slotKey(sessionId) {
985
+ return `${PENDING_STORAGE_KEY_PREFIX}${sessionId}`;
986
+ }
987
+ /**
988
+ * Adds the session to the pending index. Called once at collection start —
989
+ * long before any page-hide — so the hide path never needs the index
990
+ * read-modify-write and stays a single synchronous-effective write.
991
+ */
992
+ async function registerPendingSlot(sessionId, deps) {
993
+ try {
994
+ const index = await readIndex(deps.storage);
995
+ if (index.includes(sessionId)) return;
996
+ await deps.storage.set(PENDING_INDEX_KEY, [...index, sessionId]);
997
+ } catch {}
998
+ }
999
+ /**
1000
+ * Writes the sealed snapshot into the session's slot. `BrowserStorageProvider`
1001
+ * executes the underlying `localStorage.setItem` synchronously in the first
1002
+ * slice of the async call, which is what makes this safe to fire (void) from
1003
+ * a page-hide handler.
1004
+ */
1005
+ async function writePendingEnvelope(sessionId, entry, deps) {
1006
+ try {
1007
+ await deps.storage.set(slotKey(sessionId), entry);
1008
+ } catch {}
1009
+ }
1010
+ /** Removes the entry and its index membership (terminal upload dispatched). */
1011
+ async function clearPending(sessionId, deps) {
1012
+ try {
1013
+ await deps.storage.remove(slotKey(sessionId));
1014
+ const index = await readIndex(deps.storage);
1015
+ if (index.includes(sessionId)) await deps.storage.set(PENDING_INDEX_KEY, index.filter((candidate) => candidate !== sessionId));
1016
+ } catch {}
1017
+ }
1018
+ /**
1019
+ * Next-load recovery, invoked from the first-token-observed hook (A1 — never
1020
+ * at `setup()`, which has no auth). For each foreign, old-enough entry: the
1021
+ * slot is cleared AT DISPATCH, then the envelope is posted fire-and-forget —
1022
+ * no 200-tracking, no retries (A2; a crash between clear and fire loses that
1023
+ * record, consistent with no-retry). Entries at/past the retention ceiling
1024
+ * are deleted unsent (A4). Never rejects; returns the A5 loss counters.
1025
+ */
1026
+ async function recoverPendingEnvelopes(options) {
1027
+ const { storage, post, currentSessionId } = options;
1028
+ const now = options.now ?? getTimestamp;
1029
+ const counters = {
1030
+ recovered: 0,
1031
+ gcExpired: 0
1032
+ };
1033
+ try {
1034
+ const index = await readIndex(storage);
1035
+ if (index.length === 0) return counters;
1036
+ const keptInIndex = [];
1037
+ for (const sessionId of index) {
1038
+ if (sessionId === currentSessionId) {
1039
+ keptInIndex.push(sessionId);
1040
+ continue;
1041
+ }
1042
+ const entry = await readEntry(storage, sessionId);
1043
+ if (entry === "missing") continue;
1044
+ if (entry === "corrupt") {
1045
+ counters.gcExpired += 1;
1046
+ continue;
1047
+ }
1048
+ const age = now() - entry.persistedAt;
1049
+ if (age >= 6048e5) {
1050
+ counters.gcExpired += 1;
1051
+ await storage.remove(slotKey(sessionId));
1052
+ continue;
1053
+ }
1054
+ if (age < 12e4) {
1055
+ keptInIndex.push(sessionId);
1056
+ continue;
1057
+ }
1058
+ await storage.remove(slotKey(sessionId));
1059
+ counters.recovered += 1;
1060
+ post(endpoints.diagnosticsData, entry.envelope, {}).catch(() => {});
1061
+ }
1062
+ await storage.set(PENDING_INDEX_KEY, keptInIndex);
1063
+ } catch {}
1064
+ return counters;
1065
+ }
1066
+ async function readIndex(storage) {
1067
+ const index = await storage.get(PENDING_INDEX_KEY);
1068
+ if (!Array.isArray(index)) return [];
1069
+ return index.filter((value) => typeof value === "string");
1070
+ }
1071
+ /** Reads one entry; malformed slots are pruned and reported as corrupt. */
1072
+ async function readEntry(storage, sessionId) {
1073
+ try {
1074
+ const value = await storage.get(slotKey(sessionId));
1075
+ if (value === null) return "missing";
1076
+ if (typeof value === "object" && value.v === 1 && typeof value.persistedAt === "number" && typeof value.envelope === "object") return value;
1077
+ await storage.remove(slotKey(sessionId));
1078
+ return "corrupt";
1079
+ } catch {
1080
+ try {
1081
+ await storage.remove(slotKey(sessionId));
1082
+ } catch {}
1083
+ return "corrupt";
1084
+ }
1085
+ }
1086
+ //#endregion
1087
+ //#region src/internal/featureConfig/featureConfigService.ts
1088
+ let cachedFeatures = null;
1089
+ /**
1090
+ * Checks if a feature is enabled in the feature config.
1091
+ */
1092
+ function isFeatureEnabled(feature, features) {
1093
+ return features?.find((f) => f.feature === feature)?.enabled ?? false;
1094
+ }
1095
+ /**
1096
+ * Fetches feature configuration from the backend.
1097
+ * Results are cached for the session lifetime.
1098
+ */
1099
+ async function fetchFeatureConfig(signal) {
1100
+ if (cachedFeatures) return cachedFeatures;
1101
+ const response = await api.get(endpoints.featureConfig, { signal });
1102
+ if (!response.ok) throw new Error(`Failed to fetch feature config: ${response.status} ${response.statusText}`);
1103
+ cachedFeatures = response.data;
1104
+ return cachedFeatures;
1105
+ }
1106
+ /**
1107
+ * Resets the cached feature config (useful for testing).
1108
+ */
1109
+ function resetFeatureConfigCache() {
1110
+ cachedFeatures = null;
1111
+ }
1112
+ //#endregion
1113
+ //#region src/internal/trueSight/eventBridge.ts
1114
+ /**
1115
+ * Canonical subsystem registry (plan §Subsystem registry): one stable
1116
+ * lowercase dotted string per SDK area. The raw `eventModuleNames` wire
1117
+ * values are inconsistent (`SELFIE`, `datasharingconsent`, `AdSign`…), four
1118
+ * keys collapse into `ID`, and `workflow` doubles as a module name — this
1119
+ * table is the single normalization point, snapshot-frozen in tests so the
1120
+ * dashboard facet stays bounded (~70 strings) forever.
1121
+ */
1122
+ const MODULE_SUBSYSTEMS = {
1123
+ [eventModuleNames.selfie]: "module.selfie",
1124
+ [eventModuleNames.faceCapture]: "module.face-capture",
1125
+ [eventModuleNames.authentication]: "module.authentication",
1126
+ [eventModuleNames.authFace]: "module.auth-face",
1127
+ [eventModuleNames.mlConsent]: "module.ml-consent",
1128
+ [eventModuleNames.combinedConsent]: "module.combined-consent",
1129
+ [eventModuleNames.curpValidation]: "module.curp",
1130
+ [eventModuleNames.faceMatch]: "module.face-match",
1131
+ [eventModuleNames.qr]: "module.qr",
1132
+ [eventModuleNames.videoSelfie]: "module.video-selfie",
1133
+ [eventModuleNames.id]: "module.id",
1134
+ [eventModuleNames.idCapture]: "module.id-capture",
1135
+ [eventModuleNames.idVerification]: "module.id-verification",
1136
+ [eventModuleNames.idOcr]: "module.id-ocr",
1137
+ [eventModuleNames.document]: "module.document-capture",
1138
+ [eventModuleNames.creditCard]: "module.credit-card-front",
1139
+ [eventModuleNames.creditCardBack]: "module.credit-card-back",
1140
+ [eventModuleNames.conference]: "module.conference",
1141
+ [eventModuleNames.otp]: "module.otp",
1142
+ [eventModuleNames.signature]: "module.e-sign",
1143
+ [eventModuleNames.ekyc]: "module.e-kyc",
1144
+ [eventModuleNames.watchlist]: "module.watchlist",
1145
+ [eventModuleNames.globalWatchList]: "module.global-watchlist",
1146
+ [eventModuleNames.customWatchList]: "module.custom-watchlist",
1147
+ [eventModuleNames.email]: "module.email",
1148
+ [eventModuleNames.phone]: "module.phone-number",
1149
+ [eventModuleNames.instantVerifyEmail]: "module.instant-verify-email",
1150
+ [eventModuleNames.instantVerifyConsent]: "module.instant-verify-consent",
1151
+ [eventModuleNames.forms]: "module.forms",
1152
+ [eventModuleNames.customModule]: "module.custom-module",
1153
+ [eventModuleNames.geolocation]: "module.geolocation",
1154
+ [eventModuleNames.ekyb]: "module.e-kyb",
1155
+ [eventModuleNames.identityReuse]: "module.identity-reuse",
1156
+ [eventModuleNames.antifraud]: "module.antifraud",
1157
+ [eventModuleNames.aeSignature]: "module.ae-signature",
1158
+ [eventModuleNames.qeSignature]: "module.qe-signature",
1159
+ [eventModuleNames.crossDocumentDataMatch]: "module.cross-document-data-match",
1160
+ [eventModuleNames.customFields]: "module.custom-fields",
1161
+ [eventModuleNames.fieldComparison]: "module.field-comparison",
1162
+ [eventModuleNames.personhood]: "module.personhood",
1163
+ [eventModuleNames.watchlistForBusiness]: "module.watchlist-for-business",
1164
+ [eventModuleNames.trustGraph]: "module.trust-graph",
1165
+ [eventModuleNames.certificateIssuance]: "module.certificate-issuance",
1166
+ [eventModuleNames.governmentValidation]: "module.government-validation",
1167
+ [eventModuleNames.documentUpload]: "module.document-upload",
1168
+ [eventModuleNames.home]: "module.home",
1169
+ [eventModuleNames.workflow]: "module.workflow",
1170
+ [eventModuleNames.fiscalQr]: "module.fiscal-qr"
1171
+ };
1172
+ const CUSTOM_SUBSYSTEM_MAX_CHARS = 40;
1173
+ /**
1174
+ * Canonical `module.<kebab>` for a raw wire module name. Unknown/integrator-
1175
+ * custom names get a sanitized lowercase fallback (capped) — custom SDK 2
1176
+ * integrations get real per-module detail, not a lumped `other`.
1177
+ */
1178
+ function normalizeSubsystem(rawModule) {
1179
+ if (rawModule === void 0) return "module.unknown";
1180
+ const canonical = MODULE_SUBSYSTEMS[rawModule];
1181
+ if (canonical !== void 0) return canonical;
1182
+ const sanitized = rawModule.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, CUSTOM_SUBSYSTEM_MAX_CHARS).replace(/-+$/g, "");
1183
+ return `module.${sanitized === "" ? "unknown" : sanitized}`;
1184
+ }
1185
+ const ID_SCAN_MODULES = /* @__PURE__ */ new Set([
1186
+ eventModuleNames.id,
1187
+ eventModuleNames.idCapture,
1188
+ eventModuleNames.idVerification,
1189
+ eventModuleNames.idOcr,
1190
+ eventModuleNames.document,
1191
+ eventModuleNames.documentUpload,
1192
+ eventModuleNames.creditCard,
1193
+ eventModuleNames.creditCardBack,
1194
+ eventModuleNames.curpValidation
1195
+ ]);
1196
+ const FACE_SCAN_MODULES = /* @__PURE__ */ new Set([
1197
+ eventModuleNames.selfie,
1198
+ eventModuleNames.faceCapture,
1199
+ eventModuleNames.authentication,
1200
+ eventModuleNames.authFace,
1201
+ eventModuleNames.faceMatch,
1202
+ eventModuleNames.videoSelfie,
1203
+ eventModuleNames.personhood
1204
+ ]);
1205
+ const ORCHESTRATION_MODULES = /* @__PURE__ */ new Set([eventModuleNames.home, eventModuleNames.workflow]);
1206
+ /**
1207
+ * Coarse category for HTTP-failure entries, from the endpoint path (event
1208
+ * map row 23: "by endpoint"). A conservative token heuristic — the category
1209
+ * is coarse by contract, so near-misses fall to `other`, never to a wrong
1210
+ * scan bucket.
1211
+ */
1212
+ function categoryForEndpoint(endpoint) {
1213
+ if (/face|selfie|video|speech|personhood|authenticate|recordings/.test(endpoint)) return "faceScan";
1214
+ if (/front-id|back-id|second-id|process\/id|images|barcode|ocr|document|curp|cfdi|address-statement/.test(endpoint)) return "idScan";
1215
+ if (/start|flow|workflow|feature-config|onboarding|finish-status/.test(endpoint)) return "orchestration";
1216
+ return "other";
1217
+ }
1218
+ /** Coarse contract category from the RAW `event.module` value (plan rule). */
1219
+ function categoryForModule(rawModule) {
1220
+ if (rawModule === void 0) return "other";
1221
+ if (ID_SCAN_MODULES.has(rawModule)) return "idScan";
1222
+ if (FACE_SCAN_MODULES.has(rawModule)) return "faceScan";
1223
+ if (ORCHESTRATION_MODULES.has(rawModule)) return "orchestration";
1224
+ return "other";
1225
+ }
1226
+ /** `verb key=value` line: undefined values drop their pair entirely. */
1227
+ function formatLine(verb, pairs = []) {
1228
+ const parts = [verb];
1229
+ for (const [key, value] of pairs) if (value !== void 0 && value !== null && value !== "") parts.push(`${key}=${String(value)}`);
1230
+ return parts.join(" ");
1231
+ }
1232
+ /**
1233
+ * Analytics event → contract log tuple, or `null` for codes the taxonomy
1234
+ * does not cover (deny-by-default: nothing rides into the record unreviewed).
1235
+ * Levels/subsystems/categories per the plan's event map rows 5–6 and 16–20.
1236
+ */
1237
+ function mapAnalyticsEventToLog(event) {
1238
+ const payload = event.payload ?? {};
1239
+ const subsystem = normalizeSubsystem(event.module);
1240
+ const category = categoryForModule(event.module);
1241
+ switch (event.code) {
1242
+ case "moduleOpened":
1243
+ case "moduleClosed": return {
1244
+ level: "info",
1245
+ subsystem,
1246
+ category,
1247
+ message: formatLine(event.code === "moduleOpened" ? "module opened" : "module closed", [["screen", event.screen]])
1248
+ };
1249
+ case "screenOpened":
1250
+ case "screenClosed": return {
1251
+ level: "debug",
1252
+ subsystem,
1253
+ category,
1254
+ message: formatLine(event.code === "screenOpened" ? "screen opened" : "screen closed", [["screen", event.screen]])
1255
+ };
1256
+ case "errorTriggered": return {
1257
+ level: "error",
1258
+ subsystem,
1259
+ category,
1260
+ message: formatLine("errorTriggered", [
1261
+ ["errorName", stringOrUndefined(payload.errorName) ?? "unknown"],
1262
+ ["errorCode", stringOrUndefined(payload.errorCode)],
1263
+ ["reason", stringOrUndefined(payload.reason)]
1264
+ ])
1265
+ };
1266
+ case "captureAttemptFinished": return {
1267
+ level: "debug",
1268
+ subsystem,
1269
+ category,
1270
+ message: formatLine("capture attempt finished", [["logs", stringOrUndefined(payload.logs)]])
1271
+ };
1272
+ case "background":
1273
+ case "foreground": return {
1274
+ level: "debug",
1275
+ subsystem,
1276
+ category,
1277
+ message: `visibility ${event.code}`
1278
+ };
1279
+ case "elementClicked": return {
1280
+ level: "debug",
1281
+ subsystem,
1282
+ category,
1283
+ message: formatLine("element clicked", [["element", stringOrUndefined(payload.element)], ["action", stringOrUndefined(payload.action)]])
1284
+ };
1285
+ case "browser": {
1286
+ const browser = nameVersion(payload.browser);
1287
+ const os = nameVersion(payload.os);
1288
+ const device = typeof payload.device === "object" && payload.device !== null ? stringOrUndefined(payload.device.type) : void 0;
1289
+ return {
1290
+ level: "info",
1291
+ subsystem: "session",
1292
+ category: "other",
1293
+ message: formatLine("browser info", [
1294
+ ["browser", browser],
1295
+ ["os", os],
1296
+ ["device", device],
1297
+ ["webrtc", typeof payload.isWebRtcSupported === "boolean" ? payload.isWebRtcSupported : void 0]
1298
+ ])
1299
+ };
1300
+ }
1301
+ default: return null;
1302
+ }
1303
+ }
1304
+ function stringOrUndefined(value) {
1305
+ return typeof value === "string" ? value : void 0;
1306
+ }
1307
+ function nameVersion(value) {
1308
+ if (typeof value !== "object" || value === null) return;
1309
+ const { name, version } = value;
1310
+ const joined = [name, version].filter((part) => typeof part === "string" && part !== "").join(" ");
1311
+ return joined === "" ? void 0 : joined;
1312
+ }
1313
+ //#endregion
1314
+ //#region src/internal/trueSight/uploader.ts
1315
+ let cryptoProviderPromise = null;
1316
+ /**
1317
+ * Loads the browser sealer as a LAZY chunk, once — crypto stays off the host
1318
+ * page's critical path until diagnostics actually need it (first upload or
1319
+ * the service's prewarm).
1320
+ */
1321
+ function loadDiagnosticsCryptoProvider() {
1322
+ cryptoProviderPromise ??= import("./BrowserDiagnosticsCryptoProvider-BZqV7sJR.esm.js").then((module) => new module.BrowserDiagnosticsCryptoProvider());
1323
+ return cryptoProviderPromise;
1324
+ }
1325
+ /**
1326
+ * Seals and posts one diagnostics record. Never rejects (fail-open). Size
1327
+ * guards per contract: warn approaching the 1 MB envelope cap; over the cap,
1328
+ * rebuild ONCE with the oldest half of the logs dropped; still over → drop
1329
+ * the upload entirely rather than send an invalid envelope.
1330
+ */
1331
+ async function uploadDiagnostics(record, options) {
1332
+ const warn = options.warn ?? defaultWarn;
1333
+ try {
1334
+ const sealer = await (options.loadCrypto ?? loadDiagnosticsCryptoProvider)();
1335
+ let envelope = await sealer.seal(JSON.stringify(record));
1336
+ let envelopeBytes = utf8ByteLength(JSON.stringify(envelope));
1337
+ if (envelopeBytes > 1e6) {
1338
+ const trimmed = {
1339
+ ...record,
1340
+ logs: record.logs.slice(Math.floor(record.logs.length / 2))
1341
+ };
1342
+ warn(`[TrueSight] envelope ${envelopeBytes}B over the 1MB cap — rebuilt with the oldest ${record.logs.length - trimmed.logs.length} logs dropped`);
1343
+ envelope = await sealer.seal(JSON.stringify(trimmed));
1344
+ envelopeBytes = utf8ByteLength(JSON.stringify(envelope));
1345
+ if (envelopeBytes > 1e6) {
1346
+ warn("[TrueSight] envelope still over the cap after trim — upload dropped");
1347
+ return;
1348
+ }
1349
+ } else if (envelopeBytes > 9e5) warn(`[TrueSight] envelope ${envelopeBytes}B is approaching the 1MB cap`);
1350
+ const keepalive = options.keepalive === true && envelopeBytes <= 6e4;
1351
+ if (isForwardedFalse((await options.post(endpoints.diagnosticsData, envelope, keepalive ? { keepalive: true } : {})).data)) warn("[TrueSight] proxy accepted the record but did not forward it (forwarded:false)");
1352
+ } catch (error) {
1353
+ warn(`[TrueSight] diagnostics upload failed (no retry): ${String(error)}`);
1354
+ }
1355
+ }
1356
+ function isForwardedFalse(data) {
1357
+ return typeof data === "object" && data !== null && "forwarded" in data && data.forwarded === false;
1358
+ }
1359
+ function defaultWarn() {}
1360
+ //#endregion
1361
+ //#region src/internal/trueSight/trueSightService.ts
1362
+ let active = false;
1363
+ let remoteKilled = false;
1364
+ let finalized = false;
1365
+ let cryptoUnsupported = false;
1366
+ let collectionStarted = false;
1367
+ let flagResolutionStarted = false;
1368
+ let lastError = null;
1369
+ let buffer = null;
1370
+ let unsubscribeEvents = null;
1371
+ let options = defaultOptions();
1372
+ /** First orchestrator kind observed — LOCKS the session identity (see stampOrchestratorIdentity). */
1373
+ let observedManagerKind = null;
1374
+ let orchestratorConflictLogged = false;
1375
+ let snapshotRecordId = null;
1376
+ let cachedPendingEnvelope = null;
1377
+ let snapshotDirty = false;
1378
+ let captureActive = false;
1379
+ let rebuildInFlight = false;
1380
+ let sealFailureLogged = false;
1381
+ let pendingSlotRegistered = false;
1382
+ let recoveryStarted = false;
1383
+ let bridgeFailureCount = 0;
1384
+ let envSnapshotLogged = false;
1385
+ let hintTransitionCount = 0;
1386
+ let hintSuppressedCount = 0;
1387
+ let lastHintStatus = null;
1388
+ let overflowBatchCount = 0;
1389
+ let lastFlushRecordId = null;
1390
+ let overflowDormant = false;
1391
+ let overflowFlushInFlightUpTo = null;
1392
+ let dirtyTimerHandle = null;
1393
+ let unsubscribePageHide = null;
1394
+ function defaultOptions() {
1395
+ return {
1396
+ fetchFeatures: fetchFeatureConfig,
1397
+ captureTransport: captureLiveTransport,
1398
+ upload: uploadDiagnostics,
1399
+ loadCrypto: loadDiagnosticsCryptoProvider
1400
+ };
1401
+ }
1402
+ /**
1403
+ * Boot-time entry, called from `setup()`. Idempotent — the first activating
1404
+ * call wins for the SDK lifecycle (like the analytics batcher and the
1405
+ * encryption lock); `reset()` → `resetTrueSight()` starts a new one.
1406
+ * `enabled:false` is a no-op by design: zero subscriptions, zero state.
1407
+ */
1408
+ function initializeTrueSightDiagnostics(serviceOptions) {
1409
+ if (!serviceOptions.enabled || active) return;
1410
+ active = true;
1411
+ options = {
1412
+ ...defaultOptions(),
1413
+ ...pickDefined(serviceOptions)
1414
+ };
1415
+ buffer = createLogBuffer({ onOverflow: handleBufferOverflow });
1416
+ configureTrueSightMetadataSources({
1417
+ getHasToken: () => getToken() !== null,
1418
+ getE2eEncryptionEnabled: isHttpEncrypted
1419
+ });
1420
+ unsubscribeEvents = subscribeEvent(handleAnalyticsEvent);
1421
+ trueSightLog("debug", "diagnostics", "other", "diagnostics initialized");
1422
+ if (options.pageLifecycle && options.storage) unsubscribePageHide = options.pageLifecycle.onPageHide(handlePageHide);
1423
+ if (options.timer && options.storage) dirtyTimerHandle = options.timer.setInterval(() => {
1424
+ maybeRebuildSnapshot();
1425
+ }, SNAPSHOT_DIRTY_INTERVAL_MS);
1426
+ }
1427
+ /**
1428
+ * Session-time entry, called from `initializeSession` once feature config is
1429
+ * known. Collection is already running by then (buffering starts at
1430
+ * initialize); this resolves the remote flag and prewarms the crypto chunk.
1431
+ * When the host's fetch failed, call with no argument — the service resolves
1432
+ * the cached `fetchFeatureConfig()` itself (a token is present at this point).
1433
+ */
1434
+ function startTrueSightCollection(features) {
1435
+ if (!active || remoteKilled || finalized) return;
1436
+ if (!collectionStarted) {
1437
+ collectionStarted = true;
1438
+ prewarmCrypto();
1439
+ }
1440
+ if (features) {
1441
+ noteFeatureConfig(features);
1442
+ if (!flagResolutionStarted) {
1443
+ flagResolutionStarted = true;
1444
+ applyFeatureResolution(features, false);
1445
+ }
1446
+ } else if (!flagResolutionStarted) {
1447
+ flagResolutionStarted = true;
1448
+ options.fetchFeatures().then((fetched) => {
1449
+ noteFeatureConfig(fetched);
1450
+ applyFeatureResolution(fetched, false);
1451
+ }, () => {
1452
+ applyFeatureResolution(null, true);
1453
+ });
1454
+ }
1455
+ kickRecoveryOnce();
1456
+ }
1457
+ /**
1458
+ * P1-E capture taps call this around detection loops (C7): while active,
1459
+ * snapshot rebuilds are suppressed — the collector must never compete with
1460
+ * 30 fps capture. Deactivation flushes the deferred rebuild.
1461
+ */
1462
+ function noteTrueSightCaptureActivity(activityActive) {
1463
+ captureActive = activityActive;
1464
+ if (!activityActive) maybeRebuildSnapshot();
1465
+ }
1466
+ /**
1467
+ * Seals and uploads the one final record per session. The upload-relevant
1468
+ * state — transport, metadata (live token/E2EE getters read NOW), buffered
1469
+ * logs — is captured SYNCHRONOUSLY before the first await, because `reset()`
1470
+ * calls `resetApi()` immediately after this returns. Finalize-once: later
1471
+ * terminals and late events are no-ops. Never rejects.
1472
+ */
1473
+ function finalizeTrueSight(outcome, failureReason) {
1474
+ if (!active || remoteKilled || finalized) return Promise.resolve();
1475
+ finalized = true;
1476
+ trueSightLog("info", "session", "orchestration", `finalizing outcome=${outcome}${failureReason !== void 0 ? ` reason=${failureReason}` : ""}`);
1477
+ const metadata = buildSessionMetadata();
1478
+ const logs = (buffer?.snapshot() ?? []).filter((entry) => overflowFlushInFlightUpTo === null || entry.index > overflowFlushInFlightUpTo);
1479
+ const transport = safeCaptureTransport();
1480
+ if (transport === null || cryptoUnsupported) return Promise.resolve();
1481
+ const record = buildDiagnosticsRecord(metadata, logs, outcome, failureReason);
1482
+ if (record === null) return Promise.resolve();
1483
+ cachedPendingEnvelope = null;
1484
+ if (options.storage && metadata.sessionId) clearPending(metadata.sessionId, { storage: options.storage });
1485
+ return options.upload(record, {
1486
+ post: transport,
1487
+ keepalive: true,
1488
+ loadCrypto: options.loadCrypto,
1489
+ warn: selfHealthWarn
1490
+ });
1491
+ }
1492
+ /**
1493
+ * Capture guidance-hint transition tap (event map 19b/19c): the moment the
1494
+ * hint the user sees CHANGES, as the status CODE — never the localized text.
1495
+ * Consecutive dedupe on top of the source dedupe, plus a per-attempt budget
1496
+ * (~60, then suppress-with-counter) so a struggling capture can never flood
1497
+ * the buffer. The budget resets when a capture attempt finishes. Level is
1498
+ * debug so the eviction fallback drops hints before warnings/errors.
1499
+ */
1500
+ function trueSightHintTransition(subsystem, category, status) {
1501
+ if (buffer === null || finalized) return;
1502
+ if (status === lastHintStatus) return;
1503
+ lastHintStatus = status;
1504
+ hintTransitionCount += 1;
1505
+ if (hintTransitionCount > 60) {
1506
+ hintSuppressedCount += 1;
1507
+ return;
1508
+ }
1509
+ if (hintTransitionCount === 60) {
1510
+ trueSightLog("debug", subsystem, category, "hint transition budget reached suppressing=true");
1511
+ return;
1512
+ }
1513
+ trueSightLog("debug", subsystem, category, `hint changed status=${status}`);
1514
+ }
1515
+ function resetHintBudget() {
1516
+ if (hintSuppressedCount > 0) trueSightLog("debug", "diagnostics", "other", `hint transitions suppressed count=${hintSuppressedCount}`);
1517
+ hintTransitionCount = 0;
1518
+ hintSuppressedCount = 0;
1519
+ lastHintStatus = null;
1520
+ }
1521
+ /** Buffer tap for wiring points and self-health lines. No-op when inactive. */
1522
+ function trueSightLog(level, subsystem, category, message) {
1523
+ if (buffer === null) return;
1524
+ buffer.append(level, subsystem, category, message);
1525
+ snapshotDirty = true;
1526
+ }
1527
+ /**
1528
+ * Minimal P1-B bridge, invoked by `attachFlowEventEmitter` for every curated
1529
+ * flow event. Terminal mapping (repo conventions): `flow.completed` →
1530
+ * success, `flow.closed` → cancelled, `flow.error` → records `lastError`
1531
+ * only — error state is recoverable, not terminal. Fail-open.
1532
+ */
1533
+ function notifyTrueSightFlowEvent(event, managerKind) {
1534
+ if (!active || remoteKilled) return;
1535
+ try {
1536
+ const identityAccepted = stampOrchestratorIdentity(managerKind);
1537
+ snapshotDirty = true;
1538
+ switch (event.type) {
1539
+ case "flow.started":
1540
+ trueSightLog("info", managerKind, "orchestration", "flow.started");
1541
+ break;
1542
+ case "flow.ready":
1543
+ if (identityAccepted) noteFlowContext({
1544
+ flowType: managerKind,
1545
+ flowId: managerKind === "flow" ? event.flowId ?? null : null,
1546
+ workflowId: managerKind === "workflow" ? event.flowId ?? null : null
1547
+ });
1548
+ trueSightLog("info", managerKind, "orchestration", `flow.ready ${managerKind === "workflow" ? "workflowId" : "flowId"}=${event.flowId ?? "unknown"}`);
1549
+ break;
1550
+ case "flow.module.started":
1551
+ case "flow.module.completed": {
1552
+ const position = modulePosition(event.payload);
1553
+ trueSightLog("info", managerKind, "orchestration", `module ${event.type === "flow.module.started" ? "started" : "completed"} module=${event.module ?? "unknown"}${position}`);
1554
+ maybeRebuildSnapshot();
1555
+ break;
1556
+ }
1557
+ case "flow.error":
1558
+ lastError = sanitizeMessage(event.error ?? "unknown");
1559
+ trueSightLog("error", managerKind, "orchestration", `flow.error message=${event.error ?? "unknown"}`);
1560
+ break;
1561
+ case "flow.completed":
1562
+ trueSightLog("info", managerKind, "orchestration", "flow.completed");
1563
+ finalizeTrueSight("success");
1564
+ break;
1565
+ case "flow.closed":
1566
+ trueSightLog("info", managerKind, "orchestration", "flow.closed");
1567
+ finalizeTrueSight("cancelled");
1568
+ break;
1569
+ default: break;
1570
+ }
1571
+ } catch {}
1572
+ }
1573
+ /**
1574
+ * `manager.stop()` while unfinalized = the session ended without a terminal —
1575
+ * the sanctioned interrupted marker until BE ships `inProgress`.
1576
+ */
1577
+ function notifyTrueSightManagerStopped(managerKind) {
1578
+ if (!active || remoteKilled || finalized) return;
1579
+ try {
1580
+ stampOrchestratorIdentity(managerKind);
1581
+ finalizeTrueSight("failure", lastError ?? "stopped_before_completion");
1582
+ } catch {}
1583
+ }
1584
+ /**
1585
+ * DETERMINISTIC session identity: the FIRST orchestrator kind observed locks
1586
+ * `flowType`/`integrationType` for the whole session — a record labeled
1587
+ * `flow` must always point at a real flow, never flip mid-session and send
1588
+ * the debugger to the wrong dashboard. A conflicting kind (host misuse: two
1589
+ * orchestrators on one session) is ignored for identity purposes and leaves
1590
+ * exactly one self-health breadcrumb; its terminals still finalize
1591
+ * (finalize-once — session closure with a caveat beats no record).
1592
+ *
1593
+ * @returns whether this kind owns the session identity (callers gate
1594
+ * identity-derived writes like flowId/workflowId on it).
1595
+ */
1596
+ function stampOrchestratorIdentity(managerKind) {
1597
+ if (observedManagerKind === null) observedManagerKind = managerKind;
1598
+ else if (observedManagerKind !== managerKind) {
1599
+ if (!orchestratorConflictLogged) {
1600
+ orchestratorConflictLogged = true;
1601
+ trueSightLog("warning", "diagnostics", "other", `orchestratorConflict ignored=${managerKind} locked=${observedManagerKind}`);
1602
+ }
1603
+ return false;
1604
+ }
1605
+ noteIntegrationSurface(managerKind === "workflow" ? "startWorkflow" : "startFlow");
1606
+ noteFlowContext({ flowType: managerKind });
1607
+ return true;
1608
+ }
1609
+ /** Full teardown, called from `reset()` AFTER finalize captured its snapshot. */
1610
+ function resetTrueSight() {
1611
+ unsubscribeEvents?.();
1612
+ unsubscribeEvents = null;
1613
+ unsubscribePageHide?.();
1614
+ unsubscribePageHide = null;
1615
+ if (dirtyTimerHandle !== null) {
1616
+ options.timer?.clearInterval(dirtyTimerHandle);
1617
+ dirtyTimerHandle = null;
1618
+ }
1619
+ buffer = null;
1620
+ active = false;
1621
+ remoteKilled = false;
1622
+ finalized = false;
1623
+ cryptoUnsupported = false;
1624
+ collectionStarted = false;
1625
+ flagResolutionStarted = false;
1626
+ lastError = null;
1627
+ observedManagerKind = null;
1628
+ orchestratorConflictLogged = false;
1629
+ snapshotRecordId = null;
1630
+ cachedPendingEnvelope = null;
1631
+ snapshotDirty = false;
1632
+ captureActive = false;
1633
+ rebuildInFlight = false;
1634
+ sealFailureLogged = false;
1635
+ pendingSlotRegistered = false;
1636
+ recoveryStarted = false;
1637
+ bridgeFailureCount = 0;
1638
+ envSnapshotLogged = false;
1639
+ hintTransitionCount = 0;
1640
+ hintSuppressedCount = 0;
1641
+ lastHintStatus = null;
1642
+ overflowBatchCount = 0;
1643
+ lastFlushRecordId = null;
1644
+ overflowDormant = false;
1645
+ overflowFlushInFlightUpTo = null;
1646
+ options = defaultOptions();
1647
+ resetTrueSightMetadata();
1648
+ }
1649
+ function handleAnalyticsEvent(event) {
1650
+ if (finalized) return;
1651
+ try {
1652
+ const mapped = mapAnalyticsEventToLog(event);
1653
+ if (mapped === null) return;
1654
+ trueSightLog(mapped.level, mapped.subsystem, mapped.category, mapped.message);
1655
+ if (mapped.level === "error" || mapped.level === "severe") logEnvironmentSnapshotOnce();
1656
+ if (event.code === "captureAttemptFinished") resetHintBudget();
1657
+ } catch {
1658
+ bridgeFailureCount += 1;
1659
+ if (bridgeFailureCount === 1) trueSightLog("warning", "diagnostics", "other", "bridge mapping failed");
1660
+ }
1661
+ }
1662
+ /**
1663
+ * Environment-snapshot-on-first-error (event map 19d): the "conditions at
1664
+ * the moment of failure" line — logged once per session, right after the
1665
+ * first error-level entry. The snapshot closure is injected (navigator
1666
+ * facts live behind the L0 environment provider).
1667
+ */
1668
+ function logEnvironmentSnapshotOnce() {
1669
+ if (envSnapshotLogged || options.getEnvironmentSnapshot === void 0) return;
1670
+ envSnapshotLogged = true;
1671
+ try {
1672
+ trueSightLog("info", "session", "other", `environment at first error ${options.getEnvironmentSnapshot()}`);
1673
+ } catch {}
1674
+ }
1675
+ function applyFeatureResolution(features, unresolvable) {
1676
+ if (!active || remoteKilled || finalized) return;
1677
+ const entry = features?.features?.find((candidate) => candidate.feature === "TRUESIGHT_DIAGNOSTICS");
1678
+ if (entry?.enabled === false) {
1679
+ remoteKill();
1680
+ return;
1681
+ }
1682
+ trueSightLog("info", "diagnostics", "other", `featureFlag resolution=${unresolvable ? "unresolvable" : entry ? "true" : "absent"}`);
1683
+ }
1684
+ function remoteKill() {
1685
+ remoteKilled = true;
1686
+ buffer = null;
1687
+ unsubscribeEvents?.();
1688
+ unsubscribeEvents = null;
1689
+ }
1690
+ /**
1691
+ * Size-limit overflow flush (plan §1.3, event map 10b): the buffer crossed
1692
+ * ~600 KB mid-session — ship the slice as its OWN contract-valid record
1693
+ * (fresh id, same sessionId, index continuity ties the records together)
1694
+ * and keep logging. **STAGING-ONLY until BE ships `inProgress`/`flushReason`
1695
+ * (hard gate B2)**: outside staging (`testing !== true`) the machinery goes
1696
+ * dormant and the buffer falls back to eviction. Interim outcome marker is
1697
+ * the sanctioned `failure/interrupted` pair; the terminal record supersedes.
1698
+ */
1699
+ function handleBufferOverflow(slice) {
1700
+ dispatchOverflowSlice(slice);
1701
+ }
1702
+ async function dispatchOverflowSlice(slice) {
1703
+ if (!active || remoteKilled || finalized || overflowDormant || slice.length === 0) return;
1704
+ const metadata = buildSessionMetadata();
1705
+ if (metadata.testing !== true) {
1706
+ goOverflowDormant("overflowFlush dormant reason=prod");
1707
+ return;
1708
+ }
1709
+ if (cryptoUnsupported) {
1710
+ goOverflowDormant("overflowFlush dormant reason=cryptoUnsupported");
1711
+ return;
1712
+ }
1713
+ const transport = safeCaptureTransport();
1714
+ if (transport === null) {
1715
+ goOverflowDormant("overflowFlush dormant reason=noTransport");
1716
+ return;
1717
+ }
1718
+ overflowBatchCount += 1;
1719
+ const record = buildDiagnosticsRecord(metadata, [{
1720
+ index: slice[0].index,
1721
+ timestampMs: getTimestamp(),
1722
+ level: "info",
1723
+ subsystem: "diagnostics",
1724
+ category: "other",
1725
+ message: `sizeLimitFlush batch=${overflowBatchCount} prevRecordId=${lastFlushRecordId ?? "none"}`
1726
+ }, ...slice], "failure", "interrupted");
1727
+ if (record === null) {
1728
+ goOverflowDormant("overflowFlush dormant reason=unbuildable");
1729
+ return;
1730
+ }
1731
+ lastFlushRecordId = record.id;
1732
+ const upToIndex = slice[slice.length - 1].index;
1733
+ overflowFlushInFlightUpTo = upToIndex;
1734
+ await options.upload(record, {
1735
+ post: transport,
1736
+ loadCrypto: options.loadCrypto,
1737
+ warn: selfHealthWarn
1738
+ });
1739
+ buffer?.markFlushed(upToIndex);
1740
+ overflowFlushInFlightUpTo = null;
1741
+ snapshotDirty = true;
1742
+ trueSightLog("info", "diagnostics", "other", `sizeLimitFlush dispatched batch=${overflowBatchCount} recordId=${record.id} entries=${slice.length}`);
1743
+ }
1744
+ /** B2 fallback: machinery dormant, eviction takes over — logged exactly once. */
1745
+ function goOverflowDormant(message) {
1746
+ if (overflowDormant) return;
1747
+ overflowDormant = true;
1748
+ trueSightLog("warning", "diagnostics", "other", message);
1749
+ buffer?.setOverflowMode("evict");
1750
+ }
1751
+ /**
1752
+ * Debounced interrupted-snapshot rebuild (plan §1.8): triggered by module
1753
+ * boundaries and the dirty-interval tick, suppressed while a capture loop is
1754
+ * active (C7). Seals the CURRENT state as a `failure/interrupted` record
1755
+ * under the session's stable snapshot id, caches the envelope (the page-hide
1756
+ * handler writes only the cache — it never builds), and persists it.
1757
+ */
1758
+ function maybeRebuildSnapshot() {
1759
+ if (!active || remoteKilled || finalized || cryptoUnsupported || captureActive || rebuildInFlight || !snapshotDirty || options.storage === void 0) return;
1760
+ const metadata = buildSessionMetadata();
1761
+ if (!metadata.sessionId) return;
1762
+ const storage = options.storage;
1763
+ const sessionId = metadata.sessionId;
1764
+ snapshotRecordId ??= randomUUID();
1765
+ const record = buildDiagnosticsRecord(metadata, buffer?.snapshot() ?? [], "failure", "interrupted", snapshotRecordId);
1766
+ if (record === null) return;
1767
+ snapshotDirty = false;
1768
+ rebuildInFlight = true;
1769
+ options.loadCrypto().then((sealer) => sealer.seal(JSON.stringify(record))).then(async (envelope) => {
1770
+ cachedPendingEnvelope = envelope;
1771
+ if (!pendingSlotRegistered) {
1772
+ pendingSlotRegistered = true;
1773
+ await registerPendingSlot(sessionId, { storage });
1774
+ }
1775
+ await writePendingEnvelope(sessionId, {
1776
+ v: 1,
1777
+ persistedAt: getTimestamp(),
1778
+ envelope
1779
+ }, { storage });
1780
+ }).catch(() => {
1781
+ snapshotDirty = true;
1782
+ if (!sealFailureLogged) {
1783
+ sealFailureLogged = true;
1784
+ trueSightLog("warning", "diagnostics", "other", "snapshot seal failed persistDisabled=false");
1785
+ }
1786
+ }).finally(() => {
1787
+ rebuildInFlight = false;
1788
+ });
1789
+ }
1790
+ /**
1791
+ * Page-hide = persist only, NEVER send (locked decision): one synchronous-
1792
+ * effective write of the freshest pre-sealed snapshot. Building or posting
1793
+ * here is forbidden — a hidden tab is frequently a user who returns.
1794
+ */
1795
+ function handlePageHide() {
1796
+ if (!active || remoteKilled || finalized || cachedPendingEnvelope === null || options.storage === void 0) return;
1797
+ const sessionId = buildSessionMetadata().sessionId;
1798
+ if (!sessionId) return;
1799
+ writePendingEnvelope(sessionId, {
1800
+ v: 1,
1801
+ persistedAt: getTimestamp(),
1802
+ envelope: cachedPendingEnvelope
1803
+ }, { storage: options.storage });
1804
+ trueSightLog("debug", "diagnostics", "other", "snapshot persisted on pagehide");
1805
+ }
1806
+ /**
1807
+ * Next-load recovery off the first-token-observed hook (A1) — runs once per
1808
+ * lifecycle, fire-and-forget, and reports the A5 loss counters as a
1809
+ * self-health line when there was anything to report.
1810
+ */
1811
+ function kickRecoveryOnce() {
1812
+ if (recoveryStarted || options.storage === void 0) return;
1813
+ recoveryStarted = true;
1814
+ const transport = safeCaptureTransport();
1815
+ if (transport === null) return;
1816
+ recoverPendingEnvelopes({
1817
+ storage: options.storage,
1818
+ post: transport,
1819
+ currentSessionId: buildSessionMetadata().sessionId
1820
+ }).then((counters) => {
1821
+ if (counters.recovered > 0 || counters.gcExpired > 0) trueSightLog("info", "diagnostics", "other", `recovery recovered=${counters.recovered} gcExpired=${counters.gcExpired}`);
1822
+ });
1823
+ }
1824
+ /**
1825
+ * Resolves crypto support ahead of finalize (and warms the lazy chunk so the
1826
+ * terminal path never pays the import). Unsupported → collect-only mode with
1827
+ * exactly one self-health warning.
1828
+ */
1829
+ function prewarmCrypto() {
1830
+ options.loadCrypto().then((provider) => {
1831
+ if (!provider.isSupported()) markCryptoUnsupported();
1832
+ }, () => {
1833
+ markCryptoUnsupported();
1834
+ });
1835
+ }
1836
+ function markCryptoUnsupported() {
1837
+ if (cryptoUnsupported) return;
1838
+ cryptoUnsupported = true;
1839
+ trueSightLog("warning", "diagnostics", "other", "crypto unsupported collectOnly=true");
1840
+ }
1841
+ /**
1842
+ * Default transport capture: a closure over the live client + token AS OF
1843
+ * NOW. `reset()` may null the singletons immediately after — the returned
1844
+ * closure keeps working against the captured references.
1845
+ */
1846
+ function captureLiveTransport() {
1847
+ try {
1848
+ if (!isApiConfigured()) return null;
1849
+ const client = getApi();
1850
+ const token = getToken();
1851
+ if (token === null) return null;
1852
+ return (url, body, config) => client.post(url, body, {
1853
+ ...config,
1854
+ headers: { "X-Incode-Hardware-Id": token }
1855
+ });
1856
+ } catch {
1857
+ return null;
1858
+ }
1859
+ }
1860
+ function safeCaptureTransport() {
1861
+ try {
1862
+ return options.captureTransport();
1863
+ } catch {
1864
+ return null;
1865
+ }
1866
+ }
1867
+ function selfHealthWarn(message) {
1868
+ if (isTrueSightTesting()) console.warn(message);
1869
+ trueSightLog("warning", "diagnostics", "other", message);
1870
+ }
1871
+ /** Spread-safe subset: injected seams only, `undefined` values dropped. */
1872
+ function pickDefined(serviceOptions) {
1873
+ const picked = {};
1874
+ if (serviceOptions.fetchFeatures) picked.fetchFeatures = serviceOptions.fetchFeatures;
1875
+ if (serviceOptions.captureTransport) picked.captureTransport = serviceOptions.captureTransport;
1876
+ if (serviceOptions.upload) picked.upload = serviceOptions.upload;
1877
+ if (serviceOptions.loadCrypto) picked.loadCrypto = serviceOptions.loadCrypto;
1878
+ if (serviceOptions.pageLifecycle) picked.pageLifecycle = serviceOptions.pageLifecycle;
1879
+ if (serviceOptions.timer) picked.timer = serviceOptions.timer;
1880
+ if (serviceOptions.storage) picked.storage = serviceOptions.storage;
1881
+ if (serviceOptions.getEnvironmentSnapshot) picked.getEnvironmentSnapshot = serviceOptions.getEnvironmentSnapshot;
1882
+ return picked;
1883
+ }
1884
+ /** ` index=i total=n` suffix when the flow event carries module positioning. */
1885
+ function modulePosition(payload) {
1886
+ if (typeof payload !== "object" || payload === null) return "";
1887
+ const { moduleIndex, totalModules } = payload;
1888
+ return `${typeof moduleIndex === "number" ? ` index=${moduleIndex}` : ""}${typeof totalModules === "number" ? ` total=${totalModules}` : ""}`;
1889
+ }
1890
+ //#endregion
1891
+ export { upgradeToWasmHttpClient as C, resetHttpClientState as S, noteTokenActivated as _, notifyTrueSightManagerStopped as a, getStoredHttpConfig as b, trueSightHintTransition as c, fetchFeatureConfig as d, isFeatureEnabled as f, noteTestingSignals as g, noteSessionCreated as h, notifyTrueSightFlowEvent as i, trueSightLog as l, noteEnvironment as m, initializeTrueSightDiagnostics as n, resetTrueSight as o, resetFeatureConfigCache as p, noteTrueSightCaptureActivity as r, startTrueSightCollection as s, finalizeTrueSight as t, categoryForEndpoint as u, SDK_VERSION as v, createApi as w, installFreshHttpClient as x, randomUUID as y };