leesto-connect 0.1.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -2
- package/dist/chunks/dist-BTlWkbvW.js.map +1 -1
- package/dist/chunks/rrweb-qwppqH_c.js.map +1 -1
- package/dist/leesto-connect.js +833 -415
- package/dist/leesto-connect.js.map +1 -1
- package/package.json +17 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"leesto-connect.js","names":[],"sources":["../../src/bridge.ts","../../src/diagnostics.ts","../../src/diagnostics-redact.ts","../../src/diagnostics-observers.ts","../../src/network-ring.ts","../../src/diagnostics-capture.ts","../../src/rrweb-recorder.ts","../../src/shell-origins.ts","../../src/app-client.ts","../../src/connect.ts"],"sourcesContent":["// Shared postMessage protocol between the Livery shell (parent) and the embedded\n// host app (iframe). Framework-agnostic: the shell side uses useShellBridge, the\n// app side uses connectLeestoApp (both in this package).\n\nimport type { DiagnosticsSnapshot } from \"./diagnostics\";\n\n/** Version du protocole parlée par CE code. À incrémenter quand un message est\n * retiré, renommé, ou change de sens — jamais pour un simple ajout de champ\n * optionnel, que l'autre bout ignore sans dommage. */\nexport const LEESTO_BRIDGE_VERSION = 1;\n\n/** Version minimale qu'un connecteur doit parler pour que le shell le pilote.\n * Tant qu'elle vaut LEESTO_BRIDGE_VERSION, aucun connecteur n'est rejeté. */\nexport const MIN_SUPPORTED_BRIDGE_VERSION = 1;\n\n/** Verdict de compatibilité entre le shell et le connecteur embarqué. */\nexport type BridgeCompatibility =\n | { status: \"ok\"; version: number }\n /** Le connecteur est trop vieux : les fonctions qui exigent le protocole\n * récent doivent être désactivées ET expliquées, pas laissées mortes. */\n | { status: \"connector-outdated\"; version: number; required: number }\n /** Le connecteur devance le shell. Informatif : le shell ignore les champs\n * qu'il ne connaît pas, on ne casse pas un client en avance de phase. */\n | { status: \"shell-outdated\"; version: number; supported: number };\n\n/** Compare la version annoncée par le connecteur à celle du shell.\n *\n * Pourquoi cette fonction existe : le connecteur et le shell partaient\n * toujours ensemble (le Lab sert le bundle), donc ils ne pouvaient pas\n * diverger. Dès qu'un client épingle une version npm, son connecteur se fige\n * pendant que le shell évolue — et un désaccord de protocole échoue en\n * SILENCE (le message est simplement ignoré). Annoncer sa version au\n * handshake est ce qui transforme cette panne muette en message actionnable.\n *\n * Une annonce absente vaut 1 : c'est ce que parlent les builds antérieurs à\n * la négociation. Une valeur aberrante y retombe aussi, plutôt que de\n * propager un NaN dans les comparaisons. */\nexport function bridgeCompatibility(\n reported: number | undefined,\n {\n shell = LEESTO_BRIDGE_VERSION,\n min = MIN_SUPPORTED_BRIDGE_VERSION,\n }: { shell?: number; min?: number } = {},\n): BridgeCompatibility {\n const version =\n typeof reported === \"number\" && Number.isFinite(reported) && reported >= 1\n ? Math.floor(reported)\n : 1;\n if (version < min) return { status: \"connector-outdated\", version, required: min };\n if (version > shell) return { status: \"shell-outdated\", version, supported: shell };\n return { status: \"ok\", version };\n}\n\n/** An element the tester pointed at in the host app. */\nexport type PickedElement = {\n /** Best-effort CSS selector to re-find the element. */\n selector: string;\n /** Short human label (tag + text snippet) for display. */\n label: string;\n /** Viewport-relative bounding box at pick time. */\n rect: { x: number; y: number; width: number; height: number };\n};\n\n/** Build descriptor of the embedded host app, declared by connectLeestoApp.\n * Both fields are optional/best-effort — the shell degrades to URL-only. */\nexport type AppBuild = {\n version?: string;\n environment?: string;\n};\n\n/** Messages the host app sends UP to the shell. */\nexport type AppToShell =\n // `gpc: true` ⇒ le signal Global Privacy Control est actif côté utilisateur :\n // l'enregistrement de session est légalement bloqué (cf. ECH-290).\n | {\n type: \"leesto:ready\";\n url: string;\n /** Version du protocole parlée par le connecteur. Optionnelle : absente\n * des builds antérieurs à la négociation, qui parlent la version 1. */\n bridgeVersion?: number;\n /** Favicon declared by the embedded app, resolved to an absolute URL. */\n favicon?: string;\n build?: AppBuild;\n gpc?: boolean;\n diagnosticRunId?: string;\n }\n | { type: \"leesto:location\"; url: string }\n | { type: \"leesto:pong\" }\n | ({ type: \"leesto:element-picked\" } & PickedElement)\n | { type: \"leesto:pick-cancelled\" }\n | { type: \"leesto:screenshot\"; dataUrl: string }\n | { type: \"leesto:capture-failed\"; reason?: string }\n // Session recording (rrweb) — events streamés par batchs pendant l'enregistrement.\n | { type: \"leesto:rec-batch\"; events: unknown[] }\n | { type: \"leesto:rec-stopped\"; durationMs: number }\n | { type: \"leesto:rec-error\"; reason: string }\n // Enregistrement refusé AVANT tout démarrage (aucune donnée captée). `gpc` =\n // Global Privacy Control actif : conformité, la capture ne doit pas avoir lieu.\n | { type: \"leesto:rec-blocked\"; reason: \"gpc\" }\n // Réponse à `leesto:diagnostics-request` : copie des ring buffers console +\n // réseau. Toujours envoyée, même vide (diagnostic non armé) — le shell ne doit\n // pas rester suspendu sur son timeout au moment du submit.\n | { type: \"leesto:diagnostics\"; snapshot: DiagnosticsSnapshot };\n\n/** Messages the shell sends DOWN to the host app. */\nexport type ShellToApp =\n | { type: \"leesto:ping\" }\n | { type: \"leesto:highlight\"; selector: string | null }\n | { type: \"leesto:pick-start\" }\n | { type: \"leesto:pick-stop\" }\n | { type: \"leesto:capture-request\" }\n // Session recording (rrweb).\n | { type: \"leesto:rec-start\" }\n | { type: \"leesto:rec-stop\" }\n // Demande du diagnostic technique au moment du signalement (pull, calqué sur\n // `leesto:capture-request`) : aucun trafic postMessage en régime permanent.\n | { type: \"leesto:diagnostics-request\" };\n\nexport type LeestoMessage = AppToShell | ShellToApp;\n\n/** Cheap structural guard — every message type is namespaced with `leesto:`. */\nexport function isLeestoMessage(data: unknown): data is LeestoMessage {\n return (\n typeof data === \"object\" &&\n data !== null &&\n typeof (data as { type?: unknown }).type === \"string\" &&\n (data as { type: string }).type.startsWith(\"leesto:\")\n );\n}\n","// Constantes + helpers PURS du diagnostic technique (console + réseau), sans\n// dépendance au DOM : testables et importables partout — shell, app, et vues\n// serveur de `apps/desk` qui doivent filtrer le blob par content-type.\n// L'instrumentation elle-même vit dans `diagnostics-capture.ts`.\n//\n// Miroir volontaire de `rrweb.ts` (même séparation pur/DOM) : ce module ne\n// connaît que la FORME de la donnée, jamais sa collecte.\n\nimport type { NetworkEntry } from \"./network-ring\";\n\n/** Content-type dédié : distingue un blob de diagnostic d'un média et d'une\n * session rrweb. C'est ce marqueur que lisent la galerie, l'indexation de\n * rétention et la résolution du blob côté Convex. */\nexport const DIAGNOSTICS_CONTENT_TYPE = \"application/vnd.leesto.diagnostics+json\";\n\n/** True si ce média est un blob de diagnostic (donc à NE PAS rendre comme une\n * image ou une vidéo — il n'a pas de représentation visuelle). */\nexport function isDiagnosticsContentType(contentType: string | undefined | null): boolean {\n return contentType === DIAGNOSTICS_CONTENT_TYPE;\n}\n\n// --- Armement par l'URL ------------------------------------------------------\n// `connectLeestoApp` s'exécute dans l'app du client et ne connaît pas le\n// consentement (détenu par le shell). Un armement par message bridge laisserait\n// une fenêtre de boot : les patches ne seraient posés qu'APRÈS le démarrage de\n// l'app, perdant l'échec de mount et les appels API initiaux — la classe de bug\n// la plus coûteuse en test. Le paramètre est lisible SYNCHRONEMENT à l'appel.\n//\n// Query param et non fragment : un fragment casse les apps à hash-router (échec\n// dur, l'app charge la mauvaise route) là où un paramètre inconnu est toléré\n// par à peu près tous les routeurs.\n\n/** Nom du paramètre d'armement. Ne porte aucun identifiant : c'est un booléen. */\nexport const LEESTO_DIAG_PARAM = \"leesto_diag\";\n/** Identifiant opaque d'une session de test. Il ne contient jamais un ticket ou\n * une donnée métier et sert uniquement à corréler les logs navigateur/backend. */\nexport const LEESTO_RUN_PARAM = \"leesto_run\";\nexport const LEESTO_RUN_HEADER = \"X-Leesto-Run-Id\";\n\nconst RUN_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\nexport function isDiagnosticRunId(value: unknown): value is string {\n return typeof value === \"string\" && RUN_ID_RE.test(value);\n}\n\nexport function createDiagnosticRunId(): string | undefined {\n try {\n const cryptoApi = globalThis.crypto;\n const uuid = cryptoApi?.randomUUID?.();\n if (isDiagnosticRunId(uuid)) return uuid;\n if (!cryptoApi?.getRandomValues) return undefined;\n const bytes = cryptoApi.getRandomValues(new Uint8Array(16));\n bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;\n bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;\n const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n const fallback = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n return isDiagnosticRunId(fallback) ? fallback : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Ajoute le marqueur d'armement à l'URL de l'app (côté shell, seulement quand\n * le consentement est donné). Retourne l'URL inchangée si elle est illisible —\n * on ne casse jamais le chargement de l'iframe pour du diagnostic. */\nexport function withDiagnosticsParam(appUrl: string, runId?: string): string {\n try {\n const url = new URL(appUrl);\n url.searchParams.set(LEESTO_DIAG_PARAM, \"1\");\n if (isDiagnosticRunId(runId)) url.searchParams.set(LEESTO_RUN_PARAM, runId);\n return url.href;\n } catch {\n return appUrl;\n }\n}\n\nexport function diagnosticRunIdFromSearch(search: string): string | undefined {\n try {\n const value = new URLSearchParams(search).get(LEESTO_RUN_PARAM);\n return isDiagnosticRunId(value) ? value : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** True si l'app a été chargée avec le marqueur d'armement (côté app). Accepte\n * une query string brute (`location.search`) pour rester testable sans DOM. */\nexport function hasDiagnosticsParam(search: string): boolean {\n try {\n return new URLSearchParams(search).get(LEESTO_DIAG_PARAM) === \"1\";\n } catch {\n return false;\n }\n}\n\n/** Retire le marqueur d'une URL avant de la poser sur le ticket : c'est un\n * détail d'implémentation, il n'a rien à faire dans le contexte d'un rapport. */\nexport function stripDiagnosticsParam(rawUrl: string): string {\n try {\n const url = new URL(rawUrl);\n if (!url.searchParams.has(LEESTO_DIAG_PARAM) && !url.searchParams.has(LEESTO_RUN_PARAM))\n return rawUrl;\n url.searchParams.delete(LEESTO_DIAG_PARAM);\n url.searchParams.delete(LEESTO_RUN_PARAM);\n return url.href;\n } catch {\n return rawUrl;\n }\n}\n\n// --- Forme de la donnée ------------------------------------------------------\n\n/** Erreur bufferisée : `console.error`/`warn`, erreur non gérée, promesse\n * rejetée. La stack est souvent LA donnée manquante (message = symptôme). */\nexport type ErrorRingEntry = {\n level: \"error\" | \"warn\";\n message: string;\n stack?: string;\n mechanism?:\n | \"console\"\n | \"window.error\"\n | \"unhandledrejection\"\n | \"resource\"\n | \"report\"\n | \"manual\"\n | string;\n name?: string;\n sourceUrl?: string;\n line?: number;\n column?: number;\n at: number;\n};\n\n/** Ligne `console.log`/`info` bufferisée. */\nexport type ConsoleRingEntry = {\n level: \"log\" | \"info\";\n message: string;\n at: number;\n};\n\n/** Copie des trois rings à un instant t. */\nexport type DiagnosticsSnapshot = {\n errors: ErrorRingEntry[];\n logs: ConsoleRingEntry[];\n network: NetworkEntry[];\n /** Opaque run correlation id, present only for an armed shell session. */\n runId?: string;\n};\n\n/** True si le snapshot ne contient rien — inutile de produire un blob vide. */\nexport function isEmptySnapshot(s: DiagnosticsSnapshot): boolean {\n return s.errors.length === 0 && s.logs.length === 0 && s.network.length === 0;\n}\n\n// Tags des custom events maison, lus par `lib/rrwebTrace.ts` côté Convex.\n// Partagés avec `diagnostics-capture.ts` : une seule définition, sinon le\n// contrat SDK ↔ backend se met à diverger en silence.\nexport const CONSOLE_TAG = \"leesto/console\";\nexport const NETWORK_TAG = \"leesto/network\";\nexport const NETWORK_RING_TAG = \"leesto/network-ring\";\nexport const CONSOLE_RING_TAG = \"leesto/console-ring\";\nexport const DIAGNOSTICS_META_TAG = \"leesto/diagnostics-meta\";\n\n/** Un custom event rrweb (`EventType.Custom`). */\nconst EVENT_CUSTOM = 5;\n\n/**\n * Convertit un snapshot en tableau d'events rrweb `type: 5`.\n *\n * C'est LE point de contrat : `extractConsoleEntries` / `extractNetworkEntries`\n * (`apps/convex/lib/rrwebTrace.ts`) sont des fonctions pures sur `type: 5` et\n * fonctionnent donc sur ce tableau sans modification — les onglets Console et\n * Réseau de l'admin s'alimentent du blob de diagnostic exactement comme d'une\n * session. Un test de round-trip garde ce contrat honnête.\n */\nexport function diagnosticsToRrwebEvents(snapshot: DiagnosticsSnapshot): unknown[] {\n const events: unknown[] = [];\n\n if (snapshot.runId) {\n events.push({\n type: EVENT_CUSTOM,\n timestamp: Date.now(),\n data: { tag: DIAGNOSTICS_META_TAG, payload: { runId: snapshot.runId } },\n });\n }\n\n // Une erreur = un event, horodaté par l'event lui-même (extractConsoleEntries\n // lit `e.timestamp` pour ce tag).\n for (const e of snapshot.errors) {\n events.push({\n type: EVENT_CUSTOM,\n timestamp: e.at,\n data: {\n tag: CONSOLE_TAG,\n payload: {\n level: e.level,\n message: e.message,\n ...(e.stack ? { stack: e.stack } : {}),\n ...(e.mechanism ? { mechanism: e.mechanism } : {}),\n ...(e.name ? { name: e.name } : {}),\n ...(e.sourceUrl ? { sourceUrl: e.sourceUrl } : {}),\n ...(typeof e.line === \"number\" ? { line: e.line } : {}),\n ...(typeof e.column === \"number\" ? { column: e.column } : {}),\n },\n },\n });\n }\n\n // Les rings partent en un event chacun ; leurs entrées portent leur propre\n // `at` (log/info) ou `startedAt` (réseau).\n if (snapshot.logs.length > 0) {\n events.push({\n type: EVENT_CUSTOM,\n timestamp: snapshot.logs[snapshot.logs.length - 1]?.at ?? Date.now(),\n data: { tag: CONSOLE_RING_TAG, payload: { entries: snapshot.logs } },\n });\n }\n if (snapshot.network.length > 0) {\n events.push({\n type: EVENT_CUSTOM,\n timestamp: snapshot.network[snapshot.network.length - 1]?.startedAt ?? Date.now(),\n data: { tag: NETWORK_RING_TAG, payload: { entries: snapshot.network } },\n });\n }\n\n return events;\n}\n\n/** Sérialise un snapshot en Blob typé, prêt pour `uploadMedia`. */\nexport function serializeDiagnostics(snapshot: DiagnosticsSnapshot): Blob {\n return new Blob([JSON.stringify(diagnosticsToRrwebEvents(snapshot))], {\n type: DIAGNOSTICS_CONTENT_TYPE,\n });\n}\n","// Rédaction PII pré-egress, partagée par TOUTES les sources de diagnostic.\n//\n// Ce module existe pour une raison précise : `diagnostics-capture.ts` (qui\n// patche console/fetch/XHR) et `diagnostics-observers.ts` (qui observe\n// passivement les ressources) alimentent le MÊME blob. Tant que la rédaction\n// vivait dans le seul module de capture, la source passive ne pouvait pas s'en\n// servir sans créer un cycle d'import — et elle s'en passait, laissant fuiter\n// les identifiants présents dans le chemin des URL d'images, scripts et polices.\n// La garantie doit être unique, donc le code doit l'être aussi.\n//\n// rrweb masque le DOM (inputs starrés, zones bloquées) ; ces regex couvrent ce\n// que le masquage DOM NE voit PAS : nos custom events (console, path d'URL) et\n// tout texte qui échapperait aux sélecteurs. Filet de sécurité : la vraie valeur\n// est remplacée DANS le navigateur, à l'écriture dans le ring — elle n'existe\n// donc jamais en clair en mémoire au-delà de l'appel (PCI/HIPAA).\n\nconst EMAIL_RE = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}/g;\nconst SSN_RE = /\\b\\d{3}-\\d{2}-\\d{4}\\b/g;\n// Suite de 13–19 chiffres, séparateurs espace/tiret tolérés — validée par Luhn.\nconst CARD_RE = /\\d(?:[ -]?\\d){12,18}/g;\n\n/** Validation Luhn d'une suite de chiffres (rejette les faux positifs). */\nfunction luhnValid(digits: string): boolean {\n let sum = 0;\n let alt = false;\n for (let i = digits.length - 1; i >= 0; i--) {\n let n = digits.charCodeAt(i) - 48;\n if (n < 0 || n > 9) return false;\n if (alt) {\n n *= 2;\n if (n > 9) n -= 9;\n }\n sum += n;\n alt = !alt;\n }\n return sum % 10 === 0;\n}\n\n/** Remplace emails / SSN / cartes bancaires (Luhn) par des marqueurs. Idempotent\n * et sûr sur chaîne vide. À appliquer à tout texte libre avant egress. */\nexport function redactPII(text: string): string {\n if (!text) return text;\n let out = text.replace(EMAIL_RE, \"[email masqué]\");\n out = out.replace(SSN_RE, \"[id masqué]\");\n out = out.replace(CARD_RE, (m) => {\n const digits = m.replace(/[ -]/g, \"\");\n return digits.length >= 13 && digits.length <= 19 && luhnValid(digits) ? \"[carte masquée]\" : m;\n });\n return out;\n}\n\n/** URL réduite à origin + chemin : on retire la query (peut porter des tokens). */\nexport function safeUrl(input: unknown): string {\n const raw =\n typeof input === \"string\"\n ? input\n : input instanceof URL\n ? input.href\n : input instanceof Request\n ? input.url\n : String(input);\n try {\n const u = new URL(raw, typeof location !== \"undefined\" ? location.href : undefined);\n // Query déjà retirée ; on rédige en plus les PII embarquées dans le path\n // (ex. /users/jane@corp.com/…).\n return u.origin + redactPII(u.pathname);\n } catch {\n return redactPII(raw.split(\"?\")[0] ?? raw);\n }\n}\n","// Socle PASSIF du diagnostic : ce que le navigateur expose nativement, sans\n// patcher quoi que ce soit dans l'app du client.\n//\n// Pourquoi ce module existe à côté de `diagnostics-capture.ts` (qui, lui,\n// monkey-patche) : le patch de `console.*` est incontournable — il n'existe\n// aucune API d'observation de la console. Le patch réseau, lui, ne l'est pas, et\n// il est à la fois le plus invasif et le MOINS couvrant :\n// - il ne voit que `fetch` et XHR, jamais les images, scripts, feuilles de\n// style ou polices — un chunk JS en 404 est pourtant un bug de test banal ;\n// - il entre en concurrence avec Sentry / Datadog, qui wrappent aussi `fetch`\n// chez le client ;\n// - il ne peut rien capturer avant son installation, là où\n// `PerformanceObserver` rejoue l'historique avec `buffered: true`.\n//\n// Le wrapper reste nécessaire pour le statut HTTP et la méthode (Resource\n// Timing ne les expose pas partout) : les deux sources sont complémentaires,\n// et on déduplique par `initiatorType`.\n\nimport { safeUrl } from \"./diagnostics-redact\";\nimport type { NetworkEntry } from \"./network-ring\";\n\n/** Requêtes déjà couvertes par le wrapper `fetch`/XHR, avec leur vrai statut :\n * on ignore leur double Resource Timing plutôt que de dégrader l'information. */\nconst WRAPPED_INITIATORS = new Set([\"fetch\", \"xmlhttprequest\"]);\n\n/** Rapports du navigateur qu'on juge utiles à un testeur. `crash` est exclu :\n * il n'arriverait de toute façon jamais jusqu'à l'envoi du rapport. */\nconst REPORT_TYPES = [\"deprecation\", \"intervention\"];\n\nexport type ObserverSinks = {\n /** Une requête observée passivement (jamais une entrée du wrapper). */\n onResource: (entry: NetworkEntry) => void;\n /** Un signal du navigateur : dépréciation, intervention, violation CSP. */\n onReport: (level: \"error\" | \"warn\", message: string) => void;\n};\n\nexport type ObserverHandle = { teardown: () => void };\n\nconst NOOP: ObserverHandle = { teardown: () => {} };\n\n/** Horodatage epoch d'une entrée Performance (dont `startTime` est relatif à\n * `timeOrigin`), pour rester sur la même échelle que les `Date.now()` du\n * wrapper — sinon le tri chronologique côté admin mélangerait tout. */\nfunction epochOf(startTime: number): number {\n const origin = typeof performance !== \"undefined\" ? performance.timeOrigin : 0;\n return Math.round(origin + startTime);\n}\n\n/** Statut HTTP d'une entrée Resource Timing. `responseStatus` n'existe pas\n * partout (et vaut 0 pour un cross-origin sans `Timing-Allow-Origin`) : on\n * préfère l'ABSENCE de statut à un `0` qui signifierait « échec » à tort. */\nfunction statusOf(entry: PerformanceResourceTiming): number | undefined {\n const raw = (entry as PerformanceResourceTiming & { responseStatus?: number }).responseStatus;\n return typeof raw === \"number\" && raw > 0 ? raw : undefined;\n}\n\nfunction toNetworkEntry(entry: PerformanceResourceTiming): NetworkEntry | null {\n if (WRAPPED_INITIATORS.has(entry.initiatorType)) return null;\n const status = statusOf(entry);\n // `transferSize` vaut 0 sur un hit de cache : on retombe sur la taille\n // encodée, qui reste une information utile pour l'équipe.\n const size = entry.transferSize || entry.encodedBodySize || undefined;\n return {\n method: \"GET\", // Resource Timing ne couvre que des GET (hors fetch/XHR, exclus).\n // MÊME rédaction que le wrapper fetch/XHR : retirer la query ne suffit pas,\n // un identifiant se loge tout aussi bien dans le chemin\n // (/u/jane@corp.com/avatar.png). La garantie pré-egress vaut pour les deux\n // sources, sinon elle ne vaut rien.\n url: safeUrl(entry.name),\n ...(status !== undefined ? { status } : {}),\n durationMs: Math.round(entry.duration),\n ...(size ? { responseSize: size } : {}),\n startedAt: epochOf(entry.startTime),\n ...(status !== undefined && status >= 400 ? { failed: true } : {}),\n initiatorType: entry.initiatorType,\n };\n}\n\n/**\n * Installe les observateurs passifs. Chaque bloc est indépendamment gardé :\n * `ReportingObserver` n'existe pas dans Safari, `PerformanceObserver` peut\n * refuser un type inconnu. Un observateur indisponible ne doit jamais empêcher\n * les autres de tourner, ni casser l'app hôte.\n */\nexport function installDiagnosticObservers(sinks: ObserverSinks): ObserverHandle {\n if (typeof window === \"undefined\") return NOOP;\n const teardowns: Array<() => void> = [];\n\n // --- Requêtes réseau, toutes origines confondues -------------------------\n // `buffered: true` rejoue les entrées ANTÉRIEURES à l'observateur : les\n // ressources chargées pendant le démarrage de l'app sont récupérées\n // rétroactivement, ce qu'aucun wrapper ne peut faire.\n if (typeof PerformanceObserver !== \"undefined\") {\n try {\n const obs = new PerformanceObserver((list) => {\n for (const raw of list.getEntries()) {\n try {\n const entry = toNetworkEntry(raw as PerformanceResourceTiming);\n if (entry) sinks.onResource(entry);\n } catch {\n // Observation best-effort : jamais au détriment de l'app hôte.\n }\n }\n });\n obs.observe({ type: \"resource\", buffered: true });\n teardowns.push(() => obs.disconnect());\n } catch {\n // Type non supporté : on s'en passe.\n }\n }\n\n // --- Signaux du navigateur (dépréciations, interventions) ----------------\n const ReportingObserverCtor = (\n window as unknown as { ReportingObserver?: new (...a: never[]) => ReportingObserverLike }\n ).ReportingObserver;\n if (ReportingObserverCtor) {\n try {\n const obs = new ReportingObserverCtor(\n ((reports: BrowserReport[]) => {\n for (const r of reports) {\n const detail = typeof r.body?.message === \"string\" ? r.body.message : r.type;\n sinks.onReport(\"warn\", `Navigateur (${r.type}) : ${detail}`);\n }\n }) as never,\n { types: REPORT_TYPES, buffered: true } as never,\n );\n obs.observe();\n teardowns.push(() => obs.disconnect());\n } catch {\n // Indisponible : on s'en passe.\n }\n }\n\n // --- Violations CSP ------------------------------------------------------\n // Le classique « ça marche en local, pas en prod » : une ressource bloquée\n // par la politique de sécurité échoue sans trace exploitable ailleurs.\n const onCsp = (e: Event) => {\n const v = e as SecurityPolicyViolationEvent;\n sinks.onReport(\n \"error\",\n `CSP : ${v.blockedURI || \"ressource\"} bloqué par « ${v.violatedDirective} »`,\n );\n };\n window.addEventListener(\"securitypolicyviolation\", onCsp);\n teardowns.push(() => window.removeEventListener(\"securitypolicyviolation\", onCsp));\n\n let done = false;\n return {\n teardown: () => {\n if (done) return;\n done = true;\n for (const t of teardowns) {\n try {\n t();\n } catch {\n // Déconnexion best-effort.\n }\n }\n },\n };\n}\n\n// `ReportingObserver` n'est pas dans les lib DOM de toutes les versions de TS :\n// on décrit le strict minimum qu'on utilise plutôt que d'élargir la config.\ntype BrowserReport = { type: string; body?: { message?: unknown } };\ntype ReportingObserverLike = { observe: () => void; disconnect: () => void };\n","// Ring buffer borné générique (dernières entrées, les plus anciennes évincées).\n// Pur/testable : la capture (fetch/XHR/console) et le flush rrweb vivent dans\n// rrweb-recorder.ts.\n\nexport type NetworkEntry = {\n method: string;\n url: string;\n /** Code HTTP. ABSENT quand le navigateur ne l'expose pas — une ressource\n * cross-origin sans `Timing-Allow-Origin` observée via Resource Timing. On\n * préfère l'absence à un `0` trompeur : `0` garde son sens strict, « la\n * requête n'a pas abouti ». Une donnée de diagnostic fausse est pire\n * qu'absente. */\n status?: number;\n durationMs: number;\n responseSize?: number;\n contentType?: string;\n startedAt: number;\n failed?: boolean;\n /** Origine rapportée par Resource Timing (`img`, `script`, `css`, `link`…).\n * Absent sur les entrées issues du wrapper `fetch`/XHR. */\n initiatorType?: string;\n /** Identifiant de corrélation renvoyé par l'API, si exposé par CORS. */\n requestId?: string;\n /** Trace HTTP renvoyée par le serveur, tronquée et non interprétée côté SDK. */\n traceparent?: string;\n /** Run de test opaque, utile quand le blob est extrait hors du ticket. */\n runId?: string;\n};\n\nexport type Ring<T> = {\n push: (entry: T) => void;\n /** Copie NON destructive des entrées courantes (les plus anciennes évincées\n * au-delà de `max`). Ne vide PAS le ring : les rings de diagnostic sont\n * permanents et un flush de session ne doit jamais en effacer l'historique. */\n snapshot: () => T[];\n};\n\nexport type NetworkRing = Ring<NetworkEntry>;\n\nexport function createRing<T>(max: number): Ring<T> {\n const buf: T[] = [];\n return {\n push(entry) {\n buf.push(entry);\n if (buf.length > max) buf.shift();\n },\n snapshot() {\n return buf.slice();\n },\n };\n}\n\nexport function createNetworkRing(max: number): NetworkRing {\n return createRing<NetworkEntry>(max);\n}\n","// Instrumentation du diagnostic technique. Deux sources, délibérément\n// complémentaires :\n// - ce module PATCHE ce qui n'a pas d'équivalent observable : `console.*` (il\n// n'existe aucune API d'observation de la console), et `fetch`/XHR pour le\n// statut HTTP et la méthode que Resource Timing n'expose pas partout ;\n// - `diagnostics-observers.ts` OBSERVE passivement le reste — toutes les\n// requêtes (images, scripts, polices), les signaux du navigateur et les\n// violations CSP — sans rien patcher chez le client.\n// La FORME de la donnée et les helpers purs vivent dans `diagnostics.ts` ;\n// ce module est la partie qui touche au DOM.\n//\n// Deux régimes, un seul code :\n// - ARMÉ (session Lab consentie, cf. `hasDiagnosticsParam`) : installé dès\n// `connectLeestoApp`, les rings couvrent toute la session de test et sont\n// joints à TOUT signalement — y compris un rapport texte seul.\n// - ÉPHÉMÈRE : créé par le recorder rrweb le temps d'un enregistrement quand\n// le diagnostic n'est pas armé, ce qui reproduit le comportement historique.\n//\n// Le sink (`setSink`) sert au recorder : pendant un enregistrement, les erreurs\n// sont AUSSI émises en custom events rrweb pour rester entrelacées\n// chronologiquement dans le replay.\n\nimport {\n CONSOLE_RING_TAG,\n CONSOLE_TAG,\n type ConsoleRingEntry,\n type DiagnosticsSnapshot,\n type ErrorRingEntry,\n isDiagnosticRunId,\n LEESTO_RUN_HEADER,\n NETWORK_RING_TAG,\n NETWORK_TAG,\n} from \"./diagnostics\";\nimport { installDiagnosticObservers } from \"./diagnostics-observers\";\nimport { redactPII, safeUrl } from \"./diagnostics-redact\";\nimport { createRing, type NetworkEntry } from \"./network-ring\";\n\n// Ré-export : la rédaction vit désormais dans `diagnostics-redact.ts` (partagée\n// avec la source passive), mais elle reste exposée d'ici, son point d'entrée\n// historique pour les appelants et les tests.\nexport { redactPII } from \"./diagnostics-redact\";\n\nconst NETWORK_RING_MAX = 50;\n// Ring SÉPARÉ pour les ressources observées passivement : une page en charge\n// des dizaines (images, scripts, polices), et mélangées au même ring elles\n// évinceraient les appels `fetch`/XHR, qui portent le vrai statut HTTP et sont\n// bien plus utiles à l'équipe.\nconst RESOURCE_RING_MAX = 30;\nconst CONSOLE_RING_MAX = 100;\nconst ERROR_RING_MAX = 50;\nconst MSG_CAP = 500;\nconst STACK_CAP = 8000;\n\n/** Émetteur de custom events rrweb (branché par le recorder, sinon absent). */\nexport type EmitFn = <T>(tag: string, payload: T) => void;\n\nexport type DiagnosticsHandle = {\n /** Copie non destructive des trois rings. */\n snapshot: () => DiagnosticsSnapshot;\n /** Branche/débranche l'émission temps réel vers le recorder rrweb. */\n setSink: (emit: EmitFn | null) => void;\n /** Émet les rings log/info + réseau vers le sink courant, en un event chacun\n * (trop bavards pour un event par ligne). À appeler AVANT `teardown`. */\n flushRings: () => void;\n /** Restauration idempotente de tout ce qui a été patché. */\n teardown: () => void;\n};\n\n/** Stack trace d'une valeur (Error uniquement), rédigée et bornée. La stack est\n * souvent LA donnée manquante côté équipe : message seul = symptôme, stack =\n * localisation. Best-effort : undefined si la valeur n'en porte pas. */\nfunction stackOf(value: unknown): string | undefined {\n const stack = value instanceof Error ? value.stack : undefined;\n if (!stack) return undefined;\n return redactPII(stack).slice(0, STACK_CAP);\n}\n\n/** Représentation texte courte et sûre d'un argument loggé (sans dump massif). */\nfunction stringifyArg(a: unknown): string {\n if (a instanceof Error) return `${a.name}: ${a.message}`;\n if (typeof a === \"string\") return a;\n if (typeof a === \"object\" && a !== null) {\n try {\n return JSON.stringify(a, (key, value) => {\n if (\n /^(authorization|cookie|set-cookie|token|access_token|refresh_token|password|secret|api[-_]?key)$/i.test(\n key,\n )\n ) {\n return \"[masqué]\";\n }\n return value;\n }).slice(0, 500);\n } catch {\n return \"[objet]\";\n }\n }\n return String(a);\n}\n\n/** Taille de réponse dérivée UNIQUEMENT du header content-length (jamais du body). */\nfunction sizeFromContentLength(v: string | null): number | undefined {\n if (!v) return undefined;\n const n = Number(v);\n return Number.isFinite(n) && n >= 0 ? n : undefined;\n}\n\nconst NOOP_HANDLE: DiagnosticsHandle = {\n snapshot: () => ({ errors: [], logs: [], network: [] }),\n setSink: () => {},\n flushRings: () => {},\n teardown: () => {},\n};\n\n/**\n * Installe la capture et retourne son handle. Sans `sink`, rien n'est émis :\n * la donnée s'accumule dans les rings et n'en sort qu'au `snapshot()` d'un\n * signalement.\n */\nexport function installDiagnostics(opts: {\n captureNetwork: boolean;\n runId?: string;\n /** Origines supplémentaires autorisées à recevoir X-Leesto-Run-Id. */\n runIdOrigins?: string[];\n sink?: EmitFn | null;\n}): DiagnosticsHandle {\n if (typeof window === \"undefined\") return NOOP_HANDLE;\n\n const netRing = createRing<NetworkEntry>(NETWORK_RING_MAX);\n const resourceRing = createRing<NetworkEntry>(RESOURCE_RING_MAX);\n const consoleRing = createRing<ConsoleRingEntry>(CONSOLE_RING_MAX);\n const errorRing = createRing<ErrorRingEntry>(ERROR_RING_MAX);\n const runId = isDiagnosticRunId(opts.runId) ? opts.runId : undefined;\n const isRunIdAllowed = (raw: unknown): boolean => {\n if (!runId) return false;\n try {\n const target = new URL(String(raw), location.href);\n return target.origin === location.origin || (opts.runIdOrigins ?? []).includes(target.origin);\n } catch {\n return false;\n }\n };\n\n let sink: EmitFn | null = opts.sink ?? null;\n const emit: EmitFn = (tag, payload) => {\n sink?.(tag, payload);\n };\n\n const recordNet = (e: NetworkEntry) => {\n if (opts.captureNetwork) netRing.push(e);\n };\n\n /** Erreur : bufferisée dans le ring ET streamée au sink (entrelacement dans\n * le replay). La stack du premier argument Error localise le bug. */\n const recordError = (\n level: \"error\" | \"warn\",\n message: string,\n stack?: string,\n details: Partial<ErrorRingEntry> = {},\n ) => {\n if (!message) return;\n const entry: ErrorRingEntry = {\n level,\n message,\n ...(stack ? { stack } : {}),\n ...details,\n at: Date.now(),\n };\n errorRing.push(entry);\n emit(CONSOLE_TAG, entry);\n };\n\n const logConsole = (level: \"error\" | \"warn\", args: unknown[]) => {\n try {\n const message = redactPII(args.map(stringifyArg).join(\" \")).slice(0, MSG_CAP);\n const error = args.find((a) => a instanceof Error);\n recordError(level, message, stackOf(error), {\n mechanism: \"console\",\n ...(error instanceof Error && error.name ? { name: error.name } : {}),\n });\n } catch {\n // capture best-effort : ne jamais casser le code applicatif loggé.\n }\n };\n const recordLog = (level: \"log\" | \"info\", args: unknown[]) => {\n try {\n const message = redactPII(args.map(stringifyArg).join(\" \")).slice(0, MSG_CAP);\n if (message) consoleRing.push({ level, message, at: Date.now() });\n } catch {\n // capture best-effort.\n }\n };\n\n const origError = console.error;\n const origWarn = console.warn;\n const origLog = console.log;\n const origInfo = console.info;\n console.error = (...args: unknown[]) => {\n logConsole(\"error\", args);\n return origError.apply(console, args as never);\n };\n console.warn = (...args: unknown[]) => {\n logConsole(\"warn\", args);\n return origWarn.apply(console, args as never);\n };\n console.log = (...args: unknown[]) => {\n recordLog(\"log\", args);\n return origLog.apply(console, args as never);\n };\n console.info = (...args: unknown[]) => {\n recordLog(\"info\", args);\n return origInfo.apply(console, args as never);\n };\n\n const onError = (e: Event) => {\n // Un échec de CHARGEMENT de ressource (<img>, <script>, <link>) est dispatché\n // sur l'élément et NE REMONTE PAS : seule la phase de capture le voit. D'où\n // le `true` ci-dessous — sans lui, un chunk JS en 404 nous échappait\n // totalement, alors que c'est un des bugs de test les plus fréquents.\n const target = e.target;\n if (target instanceof Element) {\n const src =\n (target as Partial<HTMLImageElement & HTMLScriptElement>).src ||\n (target as Partial<HTMLLinkElement>).href ||\n \"\";\n if (!src) return;\n recordError(\n \"error\",\n `Ressource non chargée : <${target.tagName.toLowerCase()}> ${safeUrl(src)}`.slice(\n 0,\n MSG_CAP,\n ),\n undefined,\n { mechanism: \"resource\", sourceUrl: safeUrl(src) },\n );\n return;\n }\n const err = e as ErrorEvent;\n recordError(\n \"error\",\n redactPII(`Erreur non gérée : ${err.message}`).slice(0, MSG_CAP),\n stackOf(err.error),\n {\n mechanism: \"window.error\",\n ...(typeof err.error?.name === \"string\" ? { name: err.error.name } : {}),\n ...(typeof err.filename === \"string\" && err.filename\n ? { sourceUrl: safeUrl(err.filename) }\n : {}),\n ...(typeof err.lineno === \"number\" && err.lineno > 0 ? { line: err.lineno } : {}),\n ...(typeof err.colno === \"number\" && err.colno > 0 ? { column: err.colno } : {}),\n },\n );\n };\n const onRejection = (e: PromiseRejectionEvent) => {\n recordError(\n \"error\",\n redactPII(`Promesse rejetée : ${stringifyArg(e.reason)}`).slice(0, MSG_CAP),\n stackOf(e.reason),\n {\n mechanism: \"unhandledrejection\",\n ...(e.reason instanceof Error && e.reason.name ? { name: e.reason.name } : {}),\n },\n );\n };\n window.addEventListener(\"error\", onError, true);\n window.addEventListener(\"unhandledrejection\", onRejection);\n\n // --- fetch ---------------------------------------------------------------\n const origFetch = typeof window.fetch === \"function\" ? window.fetch.bind(window) : null;\n if (origFetch) {\n window.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {\n const start = Date.now();\n const method = (\n init?.method ??\n (input instanceof Request ? input.method : \"GET\") ??\n \"GET\"\n ).toUpperCase();\n const url = safeUrl(input);\n let requestInit = init;\n if (runId && isRunIdAllowed(input)) {\n const headers = new Headers(input instanceof Request ? input.headers : undefined);\n for (const [key, value] of new Headers(init?.headers)) headers.set(key, value);\n headers.set(LEESTO_RUN_HEADER, runId);\n requestInit = { ...init, headers };\n }\n try {\n const res = await origFetch(input, requestInit);\n // Capture best-effort : ne JAMAIS convertir un succès en échec ni jeter\n // l'erreur d'instrumentation à l'appelant. `res` est toujours renvoyé.\n try {\n const requestId = res.headers.get(\"x-request-id\");\n const traceparent = res.headers.get(\"traceparent\");\n recordNet({\n method,\n url,\n status: res.status,\n durationMs: Date.now() - start,\n responseSize: sizeFromContentLength(res.headers.get(\"content-length\")),\n contentType: res.headers.get(\"content-type\") ?? undefined,\n startedAt: start,\n ...(requestId ? { requestId: requestId.slice(0, 200) } : {}),\n ...(traceparent ? { traceparent: traceparent.slice(0, 200) } : {}),\n ...(runId ? { runId } : {}),\n });\n if (!res.ok) {\n emit(NETWORK_TAG, { method, url, status: res.status, durationMs: Date.now() - start });\n }\n } catch {\n // capture best-effort : ne jamais casser l'appel fetch applicatif.\n }\n return res;\n } catch (err) {\n // status 0 = la requête n'a pas abouti (réseau coupé, CORS, abort…).\n try {\n const durationMs = Date.now() - start;\n recordNet({\n method,\n url,\n status: 0,\n durationMs,\n startedAt: start,\n failed: true,\n ...(runId ? { runId } : {}),\n });\n emit(NETWORK_TAG, { method, url, status: 0, durationMs });\n } catch {\n // capture best-effort.\n }\n throw err;\n }\n }) as typeof window.fetch;\n }\n\n // --- XMLHttpRequest ------------------------------------------------------\n const origOpen = XMLHttpRequest.prototype.open;\n const origSend = XMLHttpRequest.prototype.send;\n type XhrMeta = { method: string; url: string; start: number; propagate: boolean };\n const META = \"__echoNet\" as const;\n XMLHttpRequest.prototype.open = function (\n this: XMLHttpRequest & { [META]?: XhrMeta },\n method: string,\n url: string | URL,\n ...rest: unknown[]\n ) {\n this[META] = {\n method: (method || \"GET\").toUpperCase(),\n url: safeUrl(url),\n start: 0,\n propagate: isRunIdAllowed(url),\n };\n return origOpen.apply(this, [method, url, ...rest] as never);\n };\n XMLHttpRequest.prototype.send = function (\n this: XMLHttpRequest & { [META]?: XhrMeta },\n ...args: unknown[]\n ) {\n const meta = this[META];\n if (meta) {\n meta.start = Date.now();\n if (runId && meta.propagate) {\n try {\n this.setRequestHeader(LEESTO_RUN_HEADER, runId);\n } catch {\n // Header injection is best-effort; never break the XHR.\n }\n }\n // `{ once: true }` : sinon la réutilisation d'une même instance XHR (polling)\n // ferait re-tirer ce listener au 2e loadend → entrée corrompue.\n this.addEventListener(\n \"loadend\",\n () => {\n try {\n const durationMs = Date.now() - meta.start;\n const status = this.status;\n const failed = status === 0;\n const requestId = this.getResponseHeader(\"x-request-id\");\n const traceparent = this.getResponseHeader(\"traceparent\");\n recordNet({\n method: meta.method,\n url: meta.url,\n status,\n durationMs,\n responseSize: sizeFromContentLength(this.getResponseHeader(\"content-length\")),\n contentType: this.getResponseHeader(\"content-type\") ?? undefined,\n startedAt: meta.start,\n ...(failed ? { failed: true } : {}),\n ...(runId ? { runId } : {}),\n ...(requestId ? { requestId: requestId.slice(0, 200) } : {}),\n ...(traceparent ? { traceparent: traceparent.slice(0, 200) } : {}),\n });\n if (failed || status >= 400) {\n emit(NETWORK_TAG, { method: meta.method, url: meta.url, status, durationMs });\n }\n } catch {\n // capture best-effort : ne jamais casser la requête XHR applicative.\n }\n },\n { once: true },\n );\n }\n return origSend.apply(this, args as never);\n };\n\n // --- Socle passif --------------------------------------------------------\n // Couvre ce que le wrapper ne voit pas (images, scripts, polices, CSS) et\n // rejoue rétroactivement le démarrage via `buffered: true`.\n const observers = installDiagnosticObservers({\n onResource: (entry) => {\n if (opts.captureNetwork) resourceRing.push(runId ? { ...entry, runId } : entry);\n },\n onReport: (level, message) =>\n recordError(level, redactPII(message).slice(0, MSG_CAP), undefined, { mechanism: \"report\" }),\n });\n\n /** Les deux sources réseau fusionnées, dans l'ordre chronologique : le\n * wrapper (statut HTTP exact) et l'observation passive (couverture large). */\n const mergedNetwork = (): NetworkEntry[] =>\n opts.captureNetwork\n ? [...netRing.snapshot(), ...resourceRing.snapshot()].sort(\n (a, b) => a.startedAt - b.startedAt,\n )\n : [];\n\n let restored = false;\n return {\n snapshot: () => ({\n errors: errorRing.snapshot(),\n logs: consoleRing.snapshot(),\n network: mergedNetwork(),\n ...(runId ? { runId } : {}),\n }),\n setSink: (next) => {\n sink = next;\n },\n flushRings: () => {\n // `snapshot()` est NON destructif : le flush d'une session ne doit jamais\n // amputer les rings permanents d'un rapport ultérieur.\n const entries = mergedNetwork();\n if (entries.length > 0) emit(NETWORK_RING_TAG, { entries });\n const logs = consoleRing.snapshot();\n if (logs.length > 0) emit(CONSOLE_RING_TAG, { entries: logs });\n const errors = errorRing.snapshot();\n if (errors.length > 0) emit(CONSOLE_TAG, { entries: errors });\n },\n teardown: () => {\n if (restored) return;\n restored = true;\n sink = null;\n observers.teardown();\n console.error = origError;\n console.warn = origWarn;\n console.log = origLog;\n console.info = origInfo;\n window.removeEventListener(\"error\", onError, true);\n window.removeEventListener(\"unhandledrejection\", onRejection);\n if (origFetch) window.fetch = origFetch;\n XMLHttpRequest.prototype.open = origOpen;\n XMLHttpRequest.prototype.send = origSend;\n },\n };\n}\n","// Wrapper app-side du recorder rrweb. rrweb est importé dynamiquement (zéro poids\n// tant qu'on n'enregistre pas, comme modern-screenshot). Le recorder émet les\n// events par batchs via onBatch ; un safety cap arrête tout seul au bout de 10 min.\n//\n// Le recorder n'instrumente PLUS lui-même la console et le réseau : cette capture\n// vit dans `diagnostics-capture.ts` et lui est passée en `diagnostics`. Pendant\n// l'enregistrement il s'y branche en sink pour que les erreurs restent\n// entrelacées chronologiquement dans la session (`addCustomEvent`). Sans handle\n// fourni — diagnostic non armé — il en crée un éphémère le temps de\n// l'enregistrement, ce qui reproduit exactement le comportement historique.\n\nimport { type DiagnosticsHandle, installDiagnostics } from \"./diagnostics-capture\";\n\nconst SAFETY_CAP_MS = 10 * 60 * 1000;\nconst BATCH_INTERVAL_MS = 1000;\n\nexport type RrwebRecorderHandle = {\n /** Stoppe l'enregistrement, flush le dernier batch, et renvoie la durée. */\n stop: () => number;\n};\n\nexport type StartRecorderOptions = {\n /** Appelé ~1×/s avec les events accumulés depuis le dernier batch. */\n onBatch: (events: unknown[]) => void;\n /** Appelé quand le safety cap se déclenche (le shell doit finaliser). */\n onCap: () => void;\n /** Capture réseau (ring buffer fetch/XHR) — défaut activé. */\n captureNetwork?: boolean;\n /** Capture de diagnostic déjà installée (régime armé). Absente → le recorder\n * en crée une éphémère, détruite à l'arrêt. */\n diagnostics?: DiagnosticsHandle | null;\n};\n\n/**\n * Options de masquage passées à `record()`. Masquage AGRESSIF par défaut, opt-out\n * côté client (l'intégrateur révèle explicitement ce qui est safe) — jamais opt-in.\n * Contrat pour le dev de l'app embarquée :\n * - `.leesto-mask` / `[data-leesto-block]` → élément ENTIER jamais capturé (placeholder).\n * - `.leesto-mask-text` / `[data-private]` → structure gardée, TEXTE masqué.\n * - tous les inputs sont masqués par défaut (`maskAllInputs`).\n * S'applique au full snapshot (« scan » initial) ET aux mutations incrémentales.\n */\nexport const RECORD_MASK_OPTIONS = {\n maskAllInputs: true,\n maskInputOptions: { password: true, email: true, tel: true, text: true },\n blockClass: \"leesto-mask\",\n blockSelector: \"[data-leesto-block]\",\n maskTextClass: \"leesto-mask-text\",\n maskTextSelector: \"[data-private]\",\n} as const;\n\n/** Démarre un enregistrement rrweb du document courant. Masquage agressif par\n * défaut (RGPD/PCI/HIPAA) via `RECORD_MASK_OPTIONS` + rédaction PII des custom\n * events (console/réseau) avant egress. */\nexport async function startRrwebRecorder(\n options: StartRecorderOptions,\n): Promise<RrwebRecorderHandle> {\n const { record, addCustomEvent } = await import(\"rrweb\");\n const startedAt = Date.now();\n let buffer: unknown[] = [];\n let stopped = false;\n let durationMs = 0;\n\n const flush = () => {\n if (buffer.length === 0) return;\n const batch = buffer;\n buffer = [];\n options.onBatch(batch);\n };\n\n const stopFn = record({\n emit(event) {\n buffer.push(event);\n },\n ...RECORD_MASK_OPTIONS,\n });\n\n // Capture diagnostique (console / erreurs / réseau) → custom events rrweb.\n // Branchée seulement si l'enregistrement a bien démarré.\n const provided = options.diagnostics ?? null;\n const capture = stopFn\n ? (provided ?? installDiagnostics({ captureNetwork: options.captureNetwork !== false }))\n : null;\n // Un handle qu'on a créé ici nous appartient : c'est le seul qu'on détruira.\n const ownsCapture = capture !== null && provided === null;\n\n capture?.setSink((tag, payload) => {\n // rrweb garde un flag `recording` GLOBAL au module : un autre stop\n // (double record() via HMR/StrictMode, stop avant l'init différée de\n // rrweb) le fait retomber et addCustomEvent jette alors — y compris\n // pendant notre flushRings. Capture best-effort : on perd l'event,\n // jamais l'app hôte.\n try {\n addCustomEvent(tag, payload);\n } catch {}\n });\n\n const interval = setInterval(flush, BATCH_INTERVAL_MS);\n // Box mutable pour que doStop() puisse annuler le cap même si la const\n // capTimer n'est pas encore assignée au moment de la définition de doStop.\n const cap = { timer: null as ReturnType<typeof setTimeout> | null };\n\n // Idempotent : un second appel (ex. le shell qui stoppe après onCap) renvoie la\n // durée figée sans re-stopper.\n const doStop = (): number => {\n if (stopped) return durationMs;\n stopped = true;\n clearInterval(interval);\n clearTimeout(cap.timer ?? undefined);\n capture?.flushRings();\n // Débrancher avant de détruire : un handle permanent survit à la session et\n // continue d'alimenter ses rings pour les signalements suivants.\n capture?.setSink(null);\n if (ownsCapture) capture?.teardown();\n stopFn?.();\n flush();\n durationMs = Date.now() - startedAt;\n return durationMs;\n };\n\n // Le cap stoppe lui-même le recorder (pas de fuite si le consommateur tarde),\n // puis notifie le shell pour qu'il finalise.\n cap.timer = setTimeout(() => {\n doStop();\n options.onCap();\n }, SAFETY_CAP_MS);\n\n return { stop: doStop };\n}\n","// Allowlist des origines de shell autorisées à piloter le connecteur.\n//\n// Pourquoi ce module existe : le connecteur tourne dans l'app d'un TIERS et se\n// laissait piloter par n'importe quel parent, l'origine du shell étant devinée\n// depuis `document.referrer` (avec repli sur `\"*\"`). Un site capable d'embarquer\n// l'app cible pouvait donc lui demander une capture d'écran, démarrer un\n// enregistrement rrweb et lire le diagnostic — le referrer étant lui-même\n// contrôlable par l'attaquant (`referrerpolicy=\"no-referrer\"` forçait le repli).\n//\n// Le seul rempart restant était le `frame-ancestors` de l'app cible, hors de\n// notre contrôle et impossible à poser sur les builders no-code que le produit\n// vise (Lovable/Replit/Framer). D'où une allowlist embarquée dans le bundle.\n\n/** Origines de la surface Livery (apps/lab) en déploiement Leesto. */\nexport const DEFAULT_SHELL_ORIGINS: readonly string[] = [\n \"https://lab.leesto.app\",\n \"https://studio-dev.leesto.app\",\n];\n\n/** Origines de dev du shell (cf. NEXT_PUBLIC_LIVE_APP_URL dans .env.example).\n * Ajoutées UNIQUEMENT quand la page embarquée est elle-même en loopback. */\nexport const DEV_SHELL_ORIGINS: readonly string[] = [\n \"http://localhost:3505\",\n \"http://127.0.0.1:3505\",\n];\n\n/** Vrai pour une origine servie depuis la machine locale. */\nexport function isLoopbackOrigin(origin: string): boolean {\n try {\n const host = new URL(origin).hostname;\n return (\n host === \"localhost\" ||\n host.endsWith(\".localhost\") ||\n host === \"127.0.0.1\" ||\n host === \"[::1]\"\n );\n } catch {\n return false;\n }\n}\n\n/** Réduit une entrée déclarée à son origine ; `null` si inexploitable. */\nfunction toOrigin(raw: string): string | null {\n const trimmed = raw.trim();\n if (!trimmed) return null;\n try {\n const { origin } = new URL(trimmed);\n return origin === \"null\" ? null : origin;\n } catch {\n return null;\n }\n}\n\n/** Liste des origines de shell auxquelles ce connecteur accepte de parler.\n * Une déclaration explicite (data-shell-origin / option) REMPLACE les défauts :\n * un shell auto-hébergé n'a pas à faire confiance aux origines Leesto. */\nexport function resolveShellOrigins(input: {\n explicit?: readonly string[];\n pageOrigin: string;\n}): string[] {\n const explicit = (input.explicit ?? []).map(toOrigin).filter((o): o is string => o !== null);\n if (explicit.length > 0) return [...new Set(explicit)];\n\n const defaults = [...DEFAULT_SHELL_ORIGINS];\n if (isLoopbackOrigin(input.pageOrigin)) defaults.push(...DEV_SHELL_ORIGINS);\n return [...new Set(defaults)];\n}\n\n/** Comparaison d'origine STRICTE (schéma + hôte + port), pour couper court aux\n * sosies de domaine. `\"*\"`, `\"\"` et `\"null\"` ne sont jamais des origines\n * valides : une cible non résolue doit faire échouer la connexion, pas diffuser. */\nexport function isAllowedShellOrigin(origin: string, allowlist: readonly string[]): boolean {\n if (!origin || origin === \"*\" || origin === \"null\") return false;\n return allowlist.includes(origin);\n}\n","// App-side bridge client. A third-party host app calls connectLeestoApp() once so\n// the Livery shell can talk to it. Vanilla (no React) — works in any app, and is\n// a no-op when the page isn't embedded in a shell (window.parent === window).\n\nimport {\n type AppBuild,\n type AppToShell,\n isLeestoMessage,\n LEESTO_BRIDGE_VERSION,\n type ShellToApp,\n} from \"./bridge\";\nimport {\n createDiagnosticRunId,\n diagnosticRunIdFromSearch,\n hasDiagnosticsParam,\n} from \"./diagnostics\";\nimport { type DiagnosticsHandle, installDiagnostics } from \"./diagnostics-capture\";\nimport { type RrwebRecorderHandle, startRrwebRecorder } from \"./rrweb-recorder\";\nimport { isAllowedShellOrigin, resolveShellOrigins } from \"./shell-origins\";\n\nexport type ConnectLeestoAppOptions = {\n /** Color of the highlight outline drawn on `leesto:highlight`. */\n highlightColor?: string;\n /** Returns a screenshot of the app as a data URL. When omitted, the app\n * screenshots its own `document.body` with modern-screenshot (lazy-loaded on\n * first capture) — so the Livery shell gets a prompt-free, chrome-free shot\n * with zero extra code. Provide this to override (e.g. capture a subtree). */\n capture?: () => Promise<string>;\n /** Build descriptor of this app (version + environment) to stamp on reports.\n * Best-effort: falls back to window.__LEESTO_APP_BUILD__ then <meta> tags. */\n build?: AppBuild;\n /** Capture des requêtes réseau récentes (métadonnées, ring buffer) comme\n * diagnostic — joint à la session enregistrée. Défaut : activé. */\n captureNetwork?: boolean;\n /** Origines supplémentaires auxquelles transmettre l'identifiant de run.\n * L'origine de l'app est toujours autorisée ; vide = aucun cross-origin. */\n runIdOrigins?: string[];\n /** Origines de shell autorisées à piloter ce connecteur. Déclarer cette\n * option REMPLACE les origines Leesto par défaut (shell auto-hébergé). */\n shellOrigins?: string[];\n};\n\n/** Vrai si l'utilisateur a activé Global Privacy Control (navigator.globalPrivacyControl).\n * Signal d'opt-out légalement opposable (CCPA & co.) : quand il est présent, la\n * capture de session ne doit pas avoir lieu. Best-effort / SSR-safe. */\nexport function gpcHonored(): boolean {\n return (\n typeof navigator !== \"undefined\" &&\n (navigator as Navigator & { globalPrivacyControl?: boolean }).globalPrivacyControl === true\n );\n}\n\n/** Resolve the app build descriptor, best-effort. Order: explicit option →\n * window.__LEESTO_APP_BUILD__ → <meta name=\"app-version|app-environment\">.\n * Empty/whitespace values are dropped; returns undefined when nothing usable. */\nexport function resolveBuild(explicit: AppBuild | undefined): AppBuild | undefined {\n const clean = (v: unknown): string | undefined => {\n const s = typeof v === \"string\" ? v.trim() : \"\";\n return s.length > 0 ? s : undefined;\n };\n const metaContent = (name: string): string | undefined => {\n if (typeof document === \"undefined\") return undefined;\n return clean(document.querySelector(`meta[name=\"${name}\"]`)?.getAttribute(\"content\"));\n };\n const globalBuild =\n typeof window !== \"undefined\"\n ? (window as unknown as { __LEESTO_APP_BUILD__?: AppBuild }).__LEESTO_APP_BUILD__\n : undefined;\n\n const version =\n clean(explicit?.version) ?? clean(globalBuild?.version) ?? metaContent(\"app-version\");\n const environment =\n clean(explicit?.environment) ??\n clean(globalBuild?.environment) ??\n metaContent(\"app-environment\");\n\n if (!version && !environment) return undefined;\n return { ...(version ? { version } : {}), ...(environment ? { environment } : {}) };\n}\n\n/** Resolve the app's declared favicon while still inside its own document. */\nexport function resolveFavicon(): string | undefined {\n if (typeof document === \"undefined\") return undefined;\n const link = document.querySelector<HTMLLinkElement>(\n 'link[rel~=\"icon\"], link[rel=\"shortcut icon\"], link[rel=\"apple-touch-icon\"]',\n );\n if (!link?.href) return undefined;\n try {\n return new URL(link.href, location.href).href;\n } catch {\n return undefined;\n }\n}\n\n/** Effective page background: dark apps usually paint it on <html> (or a root\n * container), leaving <body> transparent. Forcing white here would bleed\n * through wherever body doesn't paint — the \"white band\" around the capture.\n * Resolve body → html → white so the shot matches what the user sees. */\nfunction pageBackgroundColor(): string {\n const isOpaque = (c: string) =>\n !!c && c !== \"transparent\" && !/^rgba\\(\\s*0,\\s*0,\\s*0,\\s*0\\s*\\)$/.test(c);\n const bodyBg = getComputedStyle(document.body).backgroundColor;\n if (isOpaque(bodyBg)) return bodyBg;\n const htmlBg = getComputedStyle(document.documentElement).backgroundColor;\n if (isOpaque(htmlBg)) return htmlBg;\n return \"#ffffff\";\n}\n\n/** Default self-screenshot: render the app's own DOM to a PNG data URL — the\n * VISIBLE VIEWPORT at the current scroll, i.e. what the tester actually sees.\n *\n * We capture <html> cropped to the viewport box and translate it up by the\n * scroll offset (`style.transform`). modern-screenshot clones the DOM into an\n * SVG foreignObject where `position: fixed`/`sticky` no longer resolves against\n * the viewport — and our root translate would drag those elements off-screen —\n * so we re-pin them with an opposite translate for the duration of the capture.\n * (Capturing `document.body` full-height instead left fixed sidebars/headers\n * collapsed and the main content visually offset.)\n *\n * The app runs in its own document, so this captures ONLY the app — no Livery\n * chrome (that lives in the parent shell). modern-screenshot is dynamically\n * imported so it's only pulled into the bundle on first capture. */\nasync function defaultCapture(): Promise<string> {\n const { domToPng } = await import(\"modern-screenshot\");\n const root = document.documentElement;\n const sx = window.scrollX;\n const sy = window.scrollY;\n\n // Re-pin fixed/sticky elements so they don't ride the root translate.\n const pinned: Array<[HTMLElement, string]> = [];\n for (const el of root.querySelectorAll<HTMLElement>(\"*\")) {\n const pos = getComputedStyle(el).position;\n if (pos === \"fixed\" || pos === \"sticky\") {\n const prev = el.style.transform;\n pinned.push([el, prev]);\n el.style.transform = `translate(${sx}px, ${sy}px)${prev ? ` ${prev}` : \"\"}`;\n }\n }\n\n try {\n return await domToPng(root, {\n quality: 0.92,\n backgroundColor: pageBackgroundColor(),\n width: root.clientWidth,\n height: root.clientHeight,\n style: { transform: `translate(${-sx}px, ${-sy}px)`, transformOrigin: \"top left\" },\n });\n } finally {\n for (const [el, prev] of pinned) el.style.transform = prev;\n }\n}\n\n/** Best-effort, reasonably-stable CSS selector for an element. */\nfunction buildSelector(el: Element): string {\n if (el.id) return `#${CSS.escape(el.id)}`;\n const parts: string[] = [];\n let node: Element | null = el;\n while (node && node.nodeType === 1 && node !== document.body && parts.length < 4) {\n if (node.id) {\n parts.unshift(`#${CSS.escape(node.id)}`);\n break;\n }\n let part = node.tagName.toLowerCase();\n const cls =\n typeof node.className === \"string\"\n ? node.className.trim().split(/\\s+/).filter(Boolean)[0]\n : null;\n if (cls) part += `.${CSS.escape(cls)}`;\n const parent: Element | null = node.parentElement;\n if (parent) {\n const sameTag = Array.from(parent.children).filter((c) => c.tagName === node?.tagName);\n if (sameTag.length > 1) part += `:nth-of-type(${sameTag.indexOf(node) + 1})`;\n }\n parts.unshift(part);\n node = parent;\n }\n return parts.join(\" > \");\n}\n\n/** Short label: tag + a trimmed text snippet. */\nfunction labelOf(el: Element): string {\n const tag = el.tagName.toLowerCase();\n const text = (el.textContent ?? \"\").replace(/\\s+/g, \" \").trim().slice(0, 40);\n return text ? `${tag} · ${text}` : tag;\n}\n\nexport function connectLeestoApp(options: ConnectLeestoAppOptions = {}): () => void {\n if (typeof window === \"undefined\" || window.parent === window) return () => {};\n const parent = window.parent;\n const color = options.highlightColor ?? \"#6B8E23\";\n\n // Allowlist des origines de shell (cf. shell-origins.ts). Le connecteur tourne\n // dans l'app d'un TIERS : il ne se laisse piloter que par un shell connu, et\n // n'adresse ses messages qu'à une origine explicite — jamais de wildcard.\n const allowedOrigins = resolveShellOrigins({\n explicit: options.shellOrigins,\n pageOrigin: location.origin,\n });\n\n // Le referrer n'est qu'un INDICE pour épingler l'origine tout de suite, jamais\n // une preuve : après une navigation interne il vaut l'origine de l'app\n // elle-même, donc une valeur hors allowlist ne prouve rien. C'est le premier\n // message entrant valide qui tranche — `event.origin` est posé par le\n // navigateur, lui n'est pas falsifiable.\n let shellOrigin: string | null = null;\n try {\n const fromReferrer = document.referrer ? new URL(document.referrer).origin : \"\";\n if (isAllowedShellOrigin(fromReferrer, allowedOrigins)) shellOrigin = fromReferrer;\n } catch {\n /* pas d'indice exploitable */\n }\n\n // Avant l'épinglage, le message est adressé à CHAQUE origine allowlistée :\n // postMessage ne délivre qu'à celle qui correspond réellement au parent, donc\n // rien ne fuit vers les autres.\n const post = (msg: AppToShell) => {\n if (shellOrigin) {\n parent.postMessage(msg, shellOrigin);\n return;\n }\n for (const origin of allowedOrigins) parent.postMessage(msg, origin);\n };\n\n let highlighted: HTMLElement | null = null;\n let prevOutline = \"\";\n const clearHighlight = () => {\n if (highlighted) highlighted.style.outline = prevOutline;\n highlighted = null;\n };\n\n // --- Element picker -------------------------------------------------------\n let stopPick: (() => void) | null = null;\n const startPick = () => {\n if (stopPick) return;\n let hovered: HTMLElement | null = null;\n let hoverPrev = \"\";\n const setHover = (el: HTMLElement | null) => {\n if (hovered === el) return;\n if (hovered) hovered.style.outline = hoverPrev;\n hovered = el;\n if (el) {\n hoverPrev = el.style.outline;\n el.style.outline = `2px dashed ${color}`;\n el.style.outlineOffset = \"1px\";\n }\n };\n const onMove = (e: MouseEvent) => setHover(e.target instanceof HTMLElement ? e.target : null);\n const onClick = (e: MouseEvent) => {\n e.preventDefault();\n e.stopPropagation();\n const el = e.target;\n const target = el instanceof HTMLElement ? el : null;\n stopPick?.();\n if (target) {\n const r = target.getBoundingClientRect();\n post({\n type: \"leesto:element-picked\",\n selector: buildSelector(target),\n label: labelOf(target),\n rect: { x: r.x, y: r.y, width: r.width, height: r.height },\n });\n }\n };\n const onKey = (e: KeyboardEvent) => {\n if (e.key === \"Escape\") {\n stopPick?.();\n post({ type: \"leesto:pick-cancelled\" });\n }\n };\n stopPick = () => {\n if (hovered) hovered.style.outline = hoverPrev;\n hovered = null;\n document.removeEventListener(\"mousemove\", onMove, true);\n document.removeEventListener(\"click\", onClick, true);\n document.removeEventListener(\"keydown\", onKey, true);\n document.body.style.cursor = \"\";\n stopPick = null;\n };\n document.body.style.cursor = \"crosshair\";\n document.addEventListener(\"mousemove\", onMove, true);\n document.addEventListener(\"click\", onClick, true);\n document.addEventListener(\"keydown\", onKey, true);\n };\n\n // --- Diagnostic technique (console + réseau) ------------------------------\n // Armé par l'URL et lu SYNCHRONEMENT ici. Un armement par message bridge\n // laisserait passer tout le démarrage de l'app — échec de mount, appels API\n // initiaux en erreur, écran blanc — soit la classe de bug la plus coûteuse en\n // test. Sans le marqueur, RIEN n'est patché : le SDK reste inerte hors d'une\n // session Lab consentie. Double garde GPC (le shell n'arme déjà pas).\n const diagnosticsArmed = hasDiagnosticsParam(location.search) && !gpcHonored();\n const diagnosticRunId = diagnosticsArmed\n ? (diagnosticRunIdFromSearch(location.search) ?? createDiagnosticRunId())\n : undefined;\n const diagnostics: DiagnosticsHandle | null = diagnosticsArmed\n ? installDiagnostics({\n captureNetwork: options.captureNetwork !== false,\n runId: diagnosticRunId,\n runIdOrigins: options.runIdOrigins,\n })\n : null;\n\n let recorder: RrwebRecorderHandle | null = null;\n let recorderStarting = false;\n let stopRequested = false;\n const stopRecording = () => {\n if (recorder) {\n const durationMs = recorder.stop();\n recorder = null;\n post({ type: \"leesto:rec-stopped\", durationMs });\n } else if (recorderStarting) {\n // rec-stop arrivé pendant l'init async : finaliser dès que le handle résout.\n stopRequested = true;\n }\n };\n\n const onMessage = (event: MessageEvent) => {\n if (event.source !== parent) return;\n if (!isAllowedShellOrigin(event.origin, allowedOrigins)) return;\n if (!isLeestoMessage(event.data)) return;\n // Première origine valide → épinglée : les messages suivants ne partent\n // plus qu'à elle.\n if (!shellOrigin) shellOrigin = event.origin;\n const msg = event.data as ShellToApp;\n if (msg.type === \"leesto:ping\") {\n post({ type: \"leesto:pong\" });\n } else if (msg.type === \"leesto:highlight\") {\n clearHighlight();\n if (msg.selector) {\n // Le sélecteur vient du pont : `querySelector` lève une SyntaxError s'il\n // est malformé, et elle s'échapperait de ce listener en erreur NON\n // capturée dans l'app du tiers. Un surlignage raté n'est pas une panne.\n let el: HTMLElement | null = null;\n try {\n el = document.querySelector<HTMLElement>(msg.selector);\n } catch {\n el = null;\n }\n if (el) {\n highlighted = el;\n prevOutline = el.style.outline;\n el.style.outline = `2px solid ${color}`;\n el.style.outlineOffset = \"2px\";\n el.scrollIntoView({ block: \"center\", behavior: \"smooth\" });\n }\n }\n } else if (msg.type === \"leesto:pick-start\") {\n startPick();\n } else if (msg.type === \"leesto:pick-stop\") {\n stopPick?.();\n } else if (msg.type === \"leesto:capture-request\") {\n const capture = options.capture ?? defaultCapture;\n capture()\n .then((dataUrl) => post({ type: \"leesto:screenshot\", dataUrl }))\n .catch((err) =>\n post({\n type: \"leesto:capture-failed\",\n reason: err instanceof Error ? err.message : \"capture_error\",\n }),\n );\n } else if (msg.type === \"leesto:rec-start\") {\n if (recorder || recorderStarting) return; // déjà en cours / en démarrage\n // Gate conformité : si Global Privacy Control est actif, la capture de\n // session est légalement interdite — on la refuse AVANT tout démarrage,\n // sans jamais instancier le recorder (aucune donnée n'est captée). ECH-290.\n if (gpcHonored()) {\n post({ type: \"leesto:rec-blocked\", reason: \"gpc\" });\n return;\n }\n recorderStarting = true;\n stopRequested = false;\n startRrwebRecorder({\n onBatch: (events) => post({ type: \"leesto:rec-batch\", events }),\n onCap: () => stopRecording(),\n captureNetwork: options.captureNetwork,\n // Armé → le recorder se branche sur la capture permanente (les erreurs\n // restent entrelacées dans le replay) sans la détruire à l'arrêt.\n // Sinon il en crée une éphémère, comme avant.\n diagnostics,\n })\n .then((h) => {\n recorderStarting = false;\n recorder = h;\n if (stopRequested) stopRecording(); // stop demandé pendant l'init\n })\n .catch((err) => {\n recorderStarting = false;\n post({\n type: \"leesto:rec-error\",\n reason: err instanceof Error ? err.message : \"rec_error\",\n });\n });\n } else if (msg.type === \"leesto:rec-stop\") {\n stopRecording();\n } else if (msg.type === \"leesto:diagnostics-request\") {\n // Toujours répondre, même sans capture armée : sinon le shell attend son\n // timeout pour rien à chaque signalement.\n post({\n type: \"leesto:diagnostics\",\n snapshot: diagnostics?.snapshot() ?? { errors: [], logs: [], network: [] },\n });\n }\n };\n\n window.addEventListener(\"message\", onMessage);\n\n // Announce readiness + current location, and report SPA navigations.\n // `gpc` prévient le shell dès la connexion que l'enregistrement est bloqué\n // (conformité Global Privacy Control), pour qu'il n'offre pas la capture.\n const build = resolveBuild(options.build);\n const favicon = resolveFavicon();\n post({\n type: \"leesto:ready\",\n url: location.href,\n // Annonce la version du protocole : un connecteur épinglé sur npm se fige\n // pendant que le shell évolue, et un désaccord échoue en SILENCE sans ça.\n bridgeVersion: LEESTO_BRIDGE_VERSION,\n ...(favicon ? { favicon } : {}),\n ...(build ? { build } : {}),\n ...(diagnosticRunId ? { diagnosticRunId } : {}),\n ...(gpcHonored() ? { gpc: true } : {}),\n });\n // Les navigations d'un routeur client (React Router, TanStack, Next App Router)\n // passent par history.pushState/replaceState, qui NE déclenchent PAS `popstate`.\n // Sans ce patch le shell restait sur l'URL d'entrée : le testeur signalait un\n // bug depuis /facturation et le ticket portait /dashboard. On patche donc ces\n // deux méthodes — uniquement dans une page EMBARQUÉE (connectLeestoApp a déjà\n // rendu la main autrement), et on les restaure à la déconnexion.\n let lastReported = location.href;\n const reportLocation = () => {\n if (location.href === lastReported) return; // pas de doublon sur le pont\n lastReported = location.href;\n post({ type: \"leesto:location\", url: location.href });\n };\n\n const nativePushState = history.pushState;\n const nativeReplaceState = history.replaceState;\n const patchedPushState: History[\"pushState\"] = (...args) => {\n nativePushState.apply(history, args);\n reportLocation();\n };\n const patchedReplaceState: History[\"replaceState\"] = (...args) => {\n nativeReplaceState.apply(history, args);\n reportLocation();\n };\n history.pushState = patchedPushState;\n history.replaceState = patchedReplaceState;\n\n window.addEventListener(\"popstate\", reportLocation);\n window.addEventListener(\"hashchange\", reportLocation);\n\n return () => {\n stopRecording();\n diagnostics?.teardown();\n clearHighlight();\n stopPick?.();\n window.removeEventListener(\"message\", onMessage);\n window.removeEventListener(\"popstate\", reportLocation);\n window.removeEventListener(\"hashchange\", reportLocation);\n // Ne restaure que SI personne n'a patché par-dessus nous entre-temps :\n // écraser le patch d'une autre lib serait pire que de laisser le nôtre.\n if (history.pushState === patchedPushState) history.pushState = nativePushState;\n if (history.replaceState === patchedReplaceState) history.replaceState = nativeReplaceState;\n };\n}\n","// Standalone auto-init entry for the Livery connector, built as a CDN ES module:\n//\n// <script type=\"module\" src=\"https://…/leesto-connect.js\" data-leesto-connect></script>\n//\n// Calls connectLeestoApp() on load so the embedding Livery shell can screenshot the\n// page and record rrweb. No-op when the page isn't framed by Livery (connectLeestoApp\n// bails when window.parent === window). rrweb + modern-screenshot stay in lazy\n// chunks — fetched only on the first record/capture, so a normal page load of the\n// host app downloads just this tiny entry.\n//\n// Self-hosted shell (replaces the built-in Leesto origins):\n// <script type=\"module\" src=\"…/leesto-connect.js\" data-leesto-connect\n// data-shell-origin=\"https://qa.acme.test\"></script>\n//\n// Manual control (skip auto-init with data-leesto-manual):\n// <script type=\"module\" src=\"…/leesto-connect.js\" data-leesto-connect data-leesto-manual></script>\n// <script>window.LeestoConnect.connect({ highlightColor: \"#6B8E23\" })</script>\n\nimport { type ConnectLeestoAppOptions, connectLeestoApp } from \"./app-client\";\n\ndeclare global {\n interface Window {\n LeestoConnect?: {\n /** Manually wire the connector (returns a disconnect fn). */\n connect: (options?: ConnectLeestoAppOptions) => () => void;\n };\n }\n}\n\n/** The connector's own <script> tag. In classic scripts this is\n * document.currentScript; in module scripts that's null, so fall back to the\n * element tagged with data-leesto-connect. */\nfunction ownScript(): HTMLScriptElement | null {\n if (typeof document === \"undefined\") return null;\n return (\n (document.currentScript as HTMLScriptElement | null) ??\n document.querySelector<HTMLScriptElement>(\"script[data-leesto-connect]\")\n );\n}\n\nfunction optionsFromScript(el: HTMLScriptElement | null): ConnectLeestoAppOptions {\n const options: ConnectLeestoAppOptions = {};\n const highlightColor = el?.dataset.highlightColor;\n if (highlightColor) options.highlightColor = highlightColor;\n // Shell auto-hébergé : `data-shell-origin=\"https://a, https://b\"` remplace les\n // origines Leesto par défaut. Sans cet attribut, seules celles-ci sont admises.\n const shellOrigins = (el?.dataset.shellOrigin ?? \"\")\n .split(\",\")\n .map((o) => o.trim())\n .filter(Boolean);\n if (shellOrigins.length > 0) options.shellOrigins = shellOrigins;\n return options;\n}\n\nif (typeof window !== \"undefined\") {\n window.LeestoConnect = { connect: (options) => connectLeestoApp(options) };\n const el = ownScript();\n // Auto-connect unless the host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AY,CAAc,GAClD,OAAO,iBAAiB,cAAc,CAAc,GAEpD,MAAa;AACX,IAAA,EAAc,GACd,GAAa,SAAS,GACtB,EAAe,GACf,IAAW,GACX,OAAO,oBAAoB,WAAW,CAAS,GAC/C,OAAO,oBAAoB,YAAY,CAAc,GACrD,OAAO,oBAAoB,cAAc,CAAc,GAGnD,QAAQ,cAAc,MAAkB,QAAQ,YAAY,IAC5D,QAAQ,iBAAiB,MAAqB,QAAQ,eAAe;AAAA,EAC3E;AACF;AChbA,SAAS,KAAsC;AAC7C,SAAI,OAAO,WAAa,MAAoB,OAEzC,SAAS,iBACV,SAAS,cAAiC,6BAA6B;AAE3E;AAEA,SAAS,GAAkB,GAAuD;AAChF,QAAM,IAAmC,CAAC,GACpC,IAAiB,GAAI,QAAQ;AACnC,EAAI,MAAgB,EAAQ,iBAAiB;AAG7C,QAAM,KAAgB,GAAI,QAAQ,eAAe,IAC9C,MAAM,GAAG,EACT,IAAA,CAAK,MAAM,EAAE,KAAK,CAAC,EACnB,OAAO,OAAO;AACjB,SAAI,EAAa,SAAS,MAAG,EAAQ,eAAe,IAC7C;AACT;AAEA,IAAI,OAAO,SAAW,KAAa;AACjC,SAAO,gBAAgB,EAAE,SAAA,CAAU,MAAY,EAAiB,CAAO,EAAE;AACzE,QAAM,IAAK,GAAU;AAErB,GAAI,CAAC,KAAM,EAAG,QAAQ,iBAAiB,WACrC,EAAiB,GAAkB,CAAE,CAAC;AAE1C"}
|
|
1
|
+
{"version":3,"file":"leesto-connect.js","names":[],"sources":["../../shared/src/bridge.ts","../../shared/src/diagnostics.ts","../../ui/src/theme/brand.json","../../shared/src/networkRing.ts","../src/diagnostics-redact.ts","../src/diagnostics-observers.ts","../src/diagnostics-capture.ts","../src/login-fill.ts","../src/rrweb-recorder.ts","../src/shell-origins.ts","../src/app-client.ts","../src/connect.ts"],"sourcesContent":["// Shared postMessage protocol between the Livery shell (parent) and the embedded\n// host app (iframe). Framework-agnostic: the shell side uses useShellBridge, the\n// app side uses connectLeestoApp (both in this package).\n\nimport type { DiagnosticsSnapshot } from \"./diagnostics\";\n\n/** Version du protocole parlée par CE code. À incrémenter quand un message est\n * retiré, renommé, ou change de sens — jamais pour un simple ajout de champ\n * optionnel, que l'autre bout ignore sans dommage. */\nexport const LEESTO_BRIDGE_VERSION = 1;\n\n/** Version minimale qu'un connecteur doit parler pour que le shell le pilote.\n * Tant qu'elle vaut LEESTO_BRIDGE_VERSION, aucun connecteur n'est rejeté. */\nexport const MIN_SUPPORTED_BRIDGE_VERSION = 1;\n\n/** Capacité annoncée par un connecteur qui sait détecter et remplir un\n * formulaire de connexion (ECH-309). Le Lab n'arme l'auto-login que si elle\n * figure dans `leesto:ready.capabilities`. */\nexport const LOGIN_CAPABILITY = \"login\";\n\n/** Ce que le connecteur a servi lors d'un remplissage : l'identifiant seul\n * (premier écran d'un login en deux temps), le mot de passe seul (second\n * écran), ou les deux d'un coup (formulaire classique). */\nexport type LoginFillStep = \"identifier\" | \"password\" | \"both\";\n\n/** Délai après une soumission complète au bout duquel le connecteur re-vérifie\n * la présence d'un formulaire de connexion. Une app qui REJETTE la connexion\n * sans recharger (re-rendu qui garde le formulaire monté) ne fait disparaître\n * aucun nœud : sans cette vérification, le connecteur n'a rien à ré-annoncer\n * et le shell conclut « Connecté » sur un échec. Encore présent à l'échéance\n * ⇒ la soumission a échoué.\n *\n * Partagée parce que le shell DOIT attendre plus longtemps que ça avant de\n * conclure (cf. CONNECTED_AFTER_MS côté Lab) : l'annonce doit lui parvenir\n * avant sa propre échéance, sinon il affiche un succès puis se dédit. */\nexport const LOGIN_SETTLE_MS = 6_000;\n\n/** Verdict de compatibilité entre le shell et le connecteur embarqué. */\nexport type BridgeCompatibility =\n | { status: \"ok\"; version: number }\n /** Le connecteur est trop vieux : les fonctions qui exigent le protocole\n * récent doivent être désactivées ET expliquées, pas laissées mortes. */\n | { status: \"connector-outdated\"; version: number; required: number }\n /** Le connecteur devance le shell. Informatif : le shell ignore les champs\n * qu'il ne connaît pas, on ne casse pas un client en avance de phase. */\n | { status: \"shell-outdated\"; version: number; supported: number };\n\n/** Compare la version annoncée par le connecteur à celle du shell.\n *\n * Pourquoi cette fonction existe : le connecteur et le shell partaient\n * toujours ensemble (le Lab sert le bundle), donc ils ne pouvaient pas\n * diverger. Dès qu'un client épingle une version npm, son connecteur se fige\n * pendant que le shell évolue — et un désaccord de protocole échoue en\n * SILENCE (le message est simplement ignoré). Annoncer sa version au\n * handshake est ce qui transforme cette panne muette en message actionnable.\n *\n * Une annonce absente vaut 1 : c'est ce que parlent les builds antérieurs à\n * la négociation. Une valeur aberrante y retombe aussi, plutôt que de\n * propager un NaN dans les comparaisons. */\nexport function bridgeCompatibility(\n reported: number | undefined,\n {\n shell = LEESTO_BRIDGE_VERSION,\n min = MIN_SUPPORTED_BRIDGE_VERSION,\n }: { shell?: number; min?: number } = {},\n): BridgeCompatibility {\n const version =\n typeof reported === \"number\" && Number.isFinite(reported) && reported >= 1\n ? Math.floor(reported)\n : 1;\n if (version < min) return { status: \"connector-outdated\", version, required: min };\n if (version > shell) return { status: \"shell-outdated\", version, supported: shell };\n return { status: \"ok\", version };\n}\n\n/** An element the tester pointed at in the host app. */\nexport type PickedElement = {\n /** Best-effort CSS selector to re-find the element. */\n selector: string;\n /** Short human label (tag + text snippet) for display. */\n label: string;\n /** Viewport-relative bounding box at pick time. */\n rect: { x: number; y: number; width: number; height: number };\n};\n\n/** Build descriptor of the embedded host app, declared by connectLeestoApp.\n * Both fields are optional/best-effort — the shell degrades to URL-only. */\nexport type AppBuild = {\n version?: string;\n environment?: string;\n};\n\n/** Messages the host app sends UP to the shell. */\nexport type AppToShell =\n // `gpc: true` ⇒ le signal Global Privacy Control est actif côté utilisateur :\n // l'enregistrement de session est légalement bloqué (cf. ECH-290).\n | {\n type: \"leesto:ready\";\n url: string;\n /** Version du protocole parlée par le connecteur. Optionnelle : absente\n * des builds antérieurs à la négociation, qui parlent la version 1. */\n bridgeVersion?: number;\n /** Favicon declared by the embedded app, resolved to an absolute URL. */\n favicon?: string;\n build?: AppBuild;\n gpc?: boolean;\n diagnosticRunId?: string;\n /** Capacités du connecteur (ex. [\"login\"]). Absent des builds antérieurs. */\n capabilities?: string[];\n /** Retour disponible dans l’historique propre à l’iframe. */\n canGoBack?: boolean;\n }\n | { type: \"leesto:location\"; url: string; canGoBack?: boolean }\n | { type: \"leesto:pong\" }\n | ({ type: \"leesto:element-picked\" } & PickedElement)\n | { type: \"leesto:pick-cancelled\" }\n | { type: \"leesto:screenshot\"; dataUrl: string; selector?: string }\n | { type: \"leesto:capture-failed\"; reason?: string }\n // Session recording (rrweb) — events streamés par batchs pendant l'enregistrement.\n | { type: \"leesto:rec-batch\"; events: unknown[] }\n | { type: \"leesto:rec-stopped\"; durationMs: number }\n | { type: \"leesto:rec-error\"; reason: string }\n // Enregistrement refusé AVANT tout démarrage (aucune donnée captée). `gpc` =\n // Global Privacy Control actif : conformité, la capture ne doit pas avoir lieu.\n | { type: \"leesto:rec-blocked\"; reason: \"gpc\" }\n // Réponse à `leesto:diagnostics-request` : copie des ring buffers console +\n // réseau. Toujours envoyée, même vide (diagnostic non armé) — le shell ne doit\n // pas rester suspendu sur son timeout au moment du submit.\n | { type: \"leesto:diagnostics\"; snapshot: DiagnosticsSnapshot }\n // Auto-login (ECH-309) : un formulaire de connexion est présent — le shell\n // répond `leesto:login-fill` s'il a un rôle courant, sinon ouvre le panneau.\n | { type: \"leesto:login-form-detected\" }\n | { type: \"leesto:login-filled\"; step: LoginFillStep }\n | { type: \"leesto:login-error\"; reason: string };\n\n/** Messages the shell sends DOWN to the host app. */\nexport type ShellToApp =\n | { type: \"leesto:navigate-back\" }\n // Émis par le shell dès qu'il écoute. Le connecteur répond `leesto:pong` ET\n // rejoue `leesto:ready` : l'iframe SSR peut avoir annoncé son état avant que\n // le shell hydrate, sans ça le handshake initial est perdu.\n | { type: \"leesto:ping\" }\n | { type: \"leesto:highlight\"; selector: string | null }\n | { type: \"leesto:pick-start\" }\n | { type: \"leesto:pick-stop\" }\n | { type: \"leesto:capture-request\"; selector?: string }\n // Session recording (rrweb).\n | { type: \"leesto:rec-start\" }\n | { type: \"leesto:rec-stop\" }\n // Demande du diagnostic technique au moment du signalement (pull, calqué sur\n // `leesto:capture-request`) : aucun trafic postMessage en régime permanent.\n | { type: \"leesto:diagnostics-request\" }\n // Auto-login (ECH-309). `login-watch` arme la détection (renvoyé à chaque\n // `leesto:ready`), `login-fill` porte les identifiants du rôle courant,\n // `login-cancel` les fait oublier.\n | { type: \"leesto:login-watch\" }\n | { type: \"leesto:login-fill\"; login: string; password: string }\n | { type: \"leesto:login-cancel\" };\n\nexport type LeestoMessage = AppToShell | ShellToApp;\n\n/** Cheap structural guard — every message type is namespaced with `leesto:`. */\nexport function isLeestoMessage(data: unknown): data is LeestoMessage {\n return (\n typeof data === \"object\" &&\n data !== null &&\n typeof (data as { type?: unknown }).type === \"string\" &&\n (data as { type: string }).type.startsWith(\"leesto:\")\n );\n}\n","// Constantes + helpers PURS du diagnostic technique (console + réseau), sans\n// dépendance au DOM : testables et importables partout — shell, app, et vues\n// serveur de `apps/desk` qui doivent filtrer le blob par content-type.\n// L'instrumentation elle-même vit dans `diagnostics-capture.ts`.\n//\n// Miroir volontaire de `rrweb.ts` (même séparation pur/DOM) : ce module ne\n// connaît que la FORME de la donnée, jamais sa collecte.\n\nimport type { NetworkEntry } from \"./networkRing\";\n\n/** Content-type dédié : distingue un blob de diagnostic d'un média et d'une\n * session rrweb. C'est ce marqueur que lisent la galerie, l'indexation de\n * rétention et la résolution du blob côté Convex. */\nexport const DIAGNOSTICS_CONTENT_TYPE = \"application/vnd.leesto.diagnostics+json\";\n\n/** True si ce média est un blob de diagnostic (donc à NE PAS rendre comme une\n * image ou une vidéo — il n'a pas de représentation visuelle). */\nexport function isDiagnosticsContentType(contentType: string | undefined | null): boolean {\n return contentType === DIAGNOSTICS_CONTENT_TYPE;\n}\n\n// --- Armement par l'URL ------------------------------------------------------\n// `connectLeestoApp` s'exécute dans l'app du client et ne connaît pas le\n// consentement (détenu par le shell). Un armement par message bridge laisserait\n// une fenêtre de boot : les patches ne seraient posés qu'APRÈS le démarrage de\n// l'app, perdant l'échec de mount et les appels API initiaux — la classe de bug\n// la plus coûteuse en test. Le paramètre est lisible SYNCHRONEMENT à l'appel.\n//\n// Query param et non fragment : un fragment casse les apps à hash-router (échec\n// dur, l'app charge la mauvaise route) là où un paramètre inconnu est toléré\n// par à peu près tous les routeurs.\n\n/** Nom du paramètre d'armement. Ne porte aucun identifiant : c'est un booléen. */\nexport const LEESTO_DIAG_PARAM = \"leesto_diag\";\n/** Identifiant opaque d'une session de test. Il ne contient jamais un ticket ou\n * une donnée métier et sert uniquement à corréler les logs navigateur/backend. */\nexport const LEESTO_RUN_PARAM = \"leesto_run\";\nexport const LEESTO_RUN_HEADER = \"X-Leesto-Run-Id\";\n\nconst RUN_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\nexport function isDiagnosticRunId(value: unknown): value is string {\n return typeof value === \"string\" && RUN_ID_RE.test(value);\n}\n\nexport function createDiagnosticRunId(): string | undefined {\n try {\n const cryptoApi = globalThis.crypto;\n const uuid = cryptoApi?.randomUUID?.();\n if (isDiagnosticRunId(uuid)) return uuid;\n if (!cryptoApi?.getRandomValues) return undefined;\n const bytes = cryptoApi.getRandomValues(new Uint8Array(16));\n bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;\n bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;\n const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n const fallback = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n return isDiagnosticRunId(fallback) ? fallback : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Ajoute le marqueur d'armement à l'URL de l'app (côté shell, seulement quand\n * le consentement est donné). Retourne l'URL inchangée si elle est illisible —\n * on ne casse jamais le chargement de l'iframe pour du diagnostic. */\nexport function withDiagnosticsParam(appUrl: string, runId?: string): string {\n try {\n const url = new URL(appUrl);\n url.searchParams.set(LEESTO_DIAG_PARAM, \"1\");\n if (isDiagnosticRunId(runId)) url.searchParams.set(LEESTO_RUN_PARAM, runId);\n return url.href;\n } catch {\n return appUrl;\n }\n}\n\nexport function diagnosticRunIdFromSearch(search: string): string | undefined {\n try {\n const value = new URLSearchParams(search).get(LEESTO_RUN_PARAM);\n return isDiagnosticRunId(value) ? value : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** True si l'app a été chargée avec le marqueur d'armement (côté app). Accepte\n * une query string brute (`location.search`) pour rester testable sans DOM. */\nexport function hasDiagnosticsParam(search: string): boolean {\n try {\n return new URLSearchParams(search).get(LEESTO_DIAG_PARAM) === \"1\";\n } catch {\n return false;\n }\n}\n\n/** Retire le marqueur d'une URL avant de la poser sur le ticket : c'est un\n * détail d'implémentation, il n'a rien à faire dans le contexte d'un rapport. */\nexport function stripDiagnosticsParam(rawUrl: string): string {\n try {\n const url = new URL(rawUrl);\n if (!url.searchParams.has(LEESTO_DIAG_PARAM) && !url.searchParams.has(LEESTO_RUN_PARAM))\n return rawUrl;\n url.searchParams.delete(LEESTO_DIAG_PARAM);\n url.searchParams.delete(LEESTO_RUN_PARAM);\n return url.href;\n } catch {\n return rawUrl;\n }\n}\n\n// --- Forme de la donnée ------------------------------------------------------\n\n/** Erreur bufferisée : `console.error`/`warn`, erreur non gérée, promesse\n * rejetée. La stack est souvent LA donnée manquante (message = symptôme). */\nexport type ErrorRingEntry = {\n level: \"error\" | \"warn\";\n message: string;\n stack?: string;\n mechanism?:\n | \"console\"\n | \"window.error\"\n | \"unhandledrejection\"\n | \"resource\"\n | \"report\"\n | \"manual\"\n | string;\n name?: string;\n sourceUrl?: string;\n line?: number;\n column?: number;\n at: number;\n};\n\n/** Ligne `console.log`/`info` bufferisée. */\nexport type ConsoleRingEntry = {\n level: \"log\" | \"info\";\n message: string;\n at: number;\n};\n\n/** Copie des trois rings à un instant t. */\nexport type DiagnosticsSnapshot = {\n errors: ErrorRingEntry[];\n logs: ConsoleRingEntry[];\n network: NetworkEntry[];\n /** Opaque run correlation id, present only for an armed shell session. */\n runId?: string;\n};\n\n/** True si le snapshot ne contient rien — inutile de produire un blob vide. */\nexport function isEmptySnapshot(s: DiagnosticsSnapshot): boolean {\n return s.errors.length === 0 && s.logs.length === 0 && s.network.length === 0;\n}\n\n// Tags des custom events maison, lus par `lib/rrwebTrace.ts` côté Convex.\n// Partagés avec `diagnostics-capture.ts` : une seule définition, sinon le\n// contrat SDK ↔ backend se met à diverger en silence.\nexport const CONSOLE_TAG = \"leesto/console\";\nexport const NETWORK_TAG = \"leesto/network\";\nexport const NETWORK_RING_TAG = \"leesto/network-ring\";\nexport const CONSOLE_RING_TAG = \"leesto/console-ring\";\nexport const DIAGNOSTICS_META_TAG = \"leesto/diagnostics-meta\";\n\n/** Un custom event rrweb (`EventType.Custom`). */\nconst EVENT_CUSTOM = 5;\n\n/**\n * Convertit un snapshot en tableau d'events rrweb `type: 5`.\n *\n * C'est LE point de contrat : `extractConsoleEntries` / `extractNetworkEntries`\n * (`apps/convex/lib/rrwebTrace.ts`) sont des fonctions pures sur `type: 5` et\n * fonctionnent donc sur ce tableau sans modification — les onglets Console et\n * Réseau de l'admin s'alimentent du blob de diagnostic exactement comme d'une\n * session. Un test de round-trip garde ce contrat honnête.\n */\nexport function diagnosticsToRrwebEvents(snapshot: DiagnosticsSnapshot): unknown[] {\n const events: unknown[] = [];\n\n if (snapshot.runId) {\n events.push({\n type: EVENT_CUSTOM,\n timestamp: Date.now(),\n data: { tag: DIAGNOSTICS_META_TAG, payload: { runId: snapshot.runId } },\n });\n }\n\n // Une erreur = un event, horodaté par l'event lui-même (extractConsoleEntries\n // lit `e.timestamp` pour ce tag).\n for (const e of snapshot.errors) {\n events.push({\n type: EVENT_CUSTOM,\n timestamp: e.at,\n data: {\n tag: CONSOLE_TAG,\n payload: {\n level: e.level,\n message: e.message,\n ...(e.stack ? { stack: e.stack } : {}),\n ...(e.mechanism ? { mechanism: e.mechanism } : {}),\n ...(e.name ? { name: e.name } : {}),\n ...(e.sourceUrl ? { sourceUrl: e.sourceUrl } : {}),\n ...(typeof e.line === \"number\" ? { line: e.line } : {}),\n ...(typeof e.column === \"number\" ? { column: e.column } : {}),\n },\n },\n });\n }\n\n // Les rings partent en un event chacun ; leurs entrées portent leur propre\n // `at` (log/info) ou `startedAt` (réseau).\n if (snapshot.logs.length > 0) {\n events.push({\n type: EVENT_CUSTOM,\n timestamp: snapshot.logs[snapshot.logs.length - 1]?.at ?? Date.now(),\n data: { tag: CONSOLE_RING_TAG, payload: { entries: snapshot.logs } },\n });\n }\n if (snapshot.network.length > 0) {\n events.push({\n type: EVENT_CUSTOM,\n timestamp: snapshot.network[snapshot.network.length - 1]?.startedAt ?? Date.now(),\n data: { tag: NETWORK_RING_TAG, payload: { entries: snapshot.network } },\n });\n }\n\n return events;\n}\n\n/** Sérialise un snapshot en Blob typé, prêt pour `uploadMedia`. */\nexport function serializeDiagnostics(snapshot: DiagnosticsSnapshot): Blob {\n return new Blob([JSON.stringify(diagnosticsToRrwebEvents(snapshot))], {\n type: DIAGNOSTICS_CONTENT_TYPE,\n });\n}\n","{\n \"light\": {\n \"primary\": \"#08783f\",\n \"hover\": \"#066633\",\n \"foreground\": \"#f3fff7\"\n },\n \"dark\": {\n \"primary\": \"#46c383\",\n \"hover\": \"#65d49b\",\n \"foreground\": \"#082315\"\n }\n}\n","// Ring buffer borné générique (dernières entrées, les plus anciennes évincées).\n// Pur/testable : la capture (fetch/XHR/console) et le flush rrweb vivent dans\n// rrweb-recorder.ts.\n\nexport type NetworkEntry = {\n method: string;\n url: string;\n /** Code HTTP. ABSENT quand le navigateur ne l'expose pas — une ressource\n * cross-origin sans `Timing-Allow-Origin` observée via Resource Timing. On\n * préfère l'absence à un `0` trompeur : `0` garde son sens strict, « la\n * requête n'a pas abouti ». Une donnée de diagnostic fausse est pire\n * qu'absente. */\n status?: number;\n durationMs: number;\n responseSize?: number;\n contentType?: string;\n startedAt: number;\n failed?: boolean;\n /** Origine rapportée par Resource Timing (`img`, `script`, `css`, `link`…).\n * Absent sur les entrées issues du wrapper `fetch`/XHR. */\n initiatorType?: string;\n /** Identifiant de corrélation renvoyé par l'API, si exposé par CORS. */\n requestId?: string;\n /** Trace HTTP renvoyée par le serveur, tronquée et non interprétée côté SDK. */\n traceparent?: string;\n /** Run de test opaque, utile quand le blob est extrait hors du ticket. */\n runId?: string;\n};\n\nexport type Ring<T> = {\n push: (entry: T) => void;\n /** Copie NON destructive des entrées courantes (les plus anciennes évincées\n * au-delà de `max`). Ne vide PAS le ring : les rings de diagnostic sont\n * permanents et un flush de session ne doit jamais en effacer l'historique. */\n snapshot: () => T[];\n};\n\nexport type NetworkRing = Ring<NetworkEntry>;\n\nexport function createRing<T>(max: number): Ring<T> {\n const buf: T[] = [];\n return {\n push(entry) {\n buf.push(entry);\n if (buf.length > max) buf.shift();\n },\n snapshot() {\n return buf.slice();\n },\n };\n}\n\nexport function createNetworkRing(max: number): NetworkRing {\n return createRing<NetworkEntry>(max);\n}\n","// Rédaction PII pré-egress, partagée par TOUTES les sources de diagnostic.\n//\n// Ce module existe pour une raison précise : `diagnostics-capture.ts` (qui\n// patche console/fetch/XHR) et `diagnostics-observers.ts` (qui observe\n// passivement les ressources) alimentent le MÊME blob. Tant que la rédaction\n// vivait dans le seul module de capture, la source passive ne pouvait pas s'en\n// servir sans créer un cycle d'import — et elle s'en passait, laissant fuiter\n// les identifiants présents dans le chemin des URL d'images, scripts et polices.\n// La garantie doit être unique, donc le code doit l'être aussi.\n//\n// rrweb masque le DOM (inputs starrés, zones bloquées) ; ces regex couvrent ce\n// que le masquage DOM NE voit PAS : nos custom events (console, path d'URL) et\n// tout texte qui échapperait aux sélecteurs. Filet de sécurité : la vraie valeur\n// est remplacée DANS le navigateur, à l'écriture dans le ring — elle n'existe\n// donc jamais en clair en mémoire au-delà de l'appel (PCI/HIPAA).\n\nconst EMAIL_RE = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}/g;\nconst SSN_RE = /\\b\\d{3}-\\d{2}-\\d{4}\\b/g;\n// Suite de 13–19 chiffres, séparateurs espace/tiret tolérés — validée par Luhn.\nconst CARD_RE = /\\d(?:[ -]?\\d){12,18}/g;\n\n/** Validation Luhn d'une suite de chiffres (rejette les faux positifs). */\nfunction luhnValid(digits: string): boolean {\n let sum = 0;\n let alt = false;\n for (let i = digits.length - 1; i >= 0; i--) {\n let n = digits.charCodeAt(i) - 48;\n if (n < 0 || n > 9) return false;\n if (alt) {\n n *= 2;\n if (n > 9) n -= 9;\n }\n sum += n;\n alt = !alt;\n }\n return sum % 10 === 0;\n}\n\n/** Remplace emails / SSN / cartes bancaires (Luhn) par des marqueurs. Idempotent\n * et sûr sur chaîne vide. À appliquer à tout texte libre avant egress. */\nexport function redactPII(text: string): string {\n if (!text) return text;\n let out = text.replace(EMAIL_RE, \"[email masqué]\");\n out = out.replace(SSN_RE, \"[id masqué]\");\n out = out.replace(CARD_RE, (m) => {\n const digits = m.replace(/[ -]/g, \"\");\n return digits.length >= 13 && digits.length <= 19 && luhnValid(digits) ? \"[carte masquée]\" : m;\n });\n return out;\n}\n\n/** URL réduite à origin + chemin : on retire la query (peut porter des tokens). */\nexport function safeUrl(input: unknown): string {\n const raw =\n typeof input === \"string\"\n ? input\n : input instanceof URL\n ? input.href\n : input instanceof Request\n ? input.url\n : String(input);\n try {\n const u = new URL(raw, typeof location !== \"undefined\" ? location.href : undefined);\n // Query déjà retirée ; on rédige en plus les PII embarquées dans le path\n // (ex. /users/jane@corp.com/…).\n return u.origin + redactPII(u.pathname);\n } catch {\n return redactPII(raw.split(\"?\")[0] ?? raw);\n }\n}\n","// Socle PASSIF du diagnostic : ce que le navigateur expose nativement, sans\n// patcher quoi que ce soit dans l'app du client.\n//\n// Pourquoi ce module existe à côté de `diagnostics-capture.ts` (qui, lui,\n// monkey-patche) : le patch de `console.*` est incontournable — il n'existe\n// aucune API d'observation de la console. Le patch réseau, lui, ne l'est pas, et\n// il est à la fois le plus invasif et le MOINS couvrant :\n// - il ne voit que `fetch` et XHR, jamais les images, scripts, feuilles de\n// style ou polices — un chunk JS en 404 est pourtant un bug de test banal ;\n// - il entre en concurrence avec Sentry / Datadog, qui wrappent aussi `fetch`\n// chez le client ;\n// - il ne peut rien capturer avant son installation, là où\n// `PerformanceObserver` rejoue l'historique avec `buffered: true`.\n//\n// Le wrapper reste nécessaire pour le statut HTTP et la méthode (Resource\n// Timing ne les expose pas partout) : les deux sources sont complémentaires,\n// et on déduplique par `initiatorType`.\n\nimport type { NetworkEntry } from \"@leesto/shared/networkRing\";\nimport { safeUrl } from \"./diagnostics-redact\";\n\n/** Requêtes déjà couvertes par le wrapper `fetch`/XHR, avec leur vrai statut :\n * on ignore leur double Resource Timing plutôt que de dégrader l'information. */\nconst WRAPPED_INITIATORS = new Set([\"fetch\", \"xmlhttprequest\"]);\n\n/** Rapports du navigateur qu'on juge utiles à un testeur. `crash` est exclu :\n * il n'arriverait de toute façon jamais jusqu'à l'envoi du rapport. */\nconst REPORT_TYPES = [\"deprecation\", \"intervention\"];\n\nexport type ObserverSinks = {\n /** Une requête observée passivement (jamais une entrée du wrapper). */\n onResource: (entry: NetworkEntry) => void;\n /** Un signal du navigateur : dépréciation, intervention, violation CSP. */\n onReport: (level: \"error\" | \"warn\", message: string) => void;\n};\n\nexport type ObserverHandle = { teardown: () => void };\n\nconst NOOP: ObserverHandle = { teardown: () => {} };\n\n/** Horodatage epoch d'une entrée Performance (dont `startTime` est relatif à\n * `timeOrigin`), pour rester sur la même échelle que les `Date.now()` du\n * wrapper — sinon le tri chronologique côté admin mélangerait tout. */\nfunction epochOf(startTime: number): number {\n const origin = typeof performance !== \"undefined\" ? performance.timeOrigin : 0;\n return Math.round(origin + startTime);\n}\n\n/** Statut HTTP d'une entrée Resource Timing. `responseStatus` n'existe pas\n * partout (et vaut 0 pour un cross-origin sans `Timing-Allow-Origin`) : on\n * préfère l'ABSENCE de statut à un `0` qui signifierait « échec » à tort. */\nfunction statusOf(entry: PerformanceResourceTiming): number | undefined {\n const raw = (entry as PerformanceResourceTiming & { responseStatus?: number }).responseStatus;\n return typeof raw === \"number\" && raw > 0 ? raw : undefined;\n}\n\nfunction toNetworkEntry(entry: PerformanceResourceTiming): NetworkEntry | null {\n if (WRAPPED_INITIATORS.has(entry.initiatorType)) return null;\n const status = statusOf(entry);\n // `transferSize` vaut 0 sur un hit de cache : on retombe sur la taille\n // encodée, qui reste une information utile pour l'équipe.\n const size = entry.transferSize || entry.encodedBodySize || undefined;\n return {\n method: \"GET\", // Resource Timing ne couvre que des GET (hors fetch/XHR, exclus).\n // MÊME rédaction que le wrapper fetch/XHR : retirer la query ne suffit pas,\n // un identifiant se loge tout aussi bien dans le chemin\n // (/u/jane@corp.com/avatar.png). La garantie pré-egress vaut pour les deux\n // sources, sinon elle ne vaut rien.\n url: safeUrl(entry.name),\n ...(status !== undefined ? { status } : {}),\n durationMs: Math.round(entry.duration),\n ...(size ? { responseSize: size } : {}),\n startedAt: epochOf(entry.startTime),\n ...(status !== undefined && status >= 400 ? { failed: true } : {}),\n initiatorType: entry.initiatorType,\n };\n}\n\n/**\n * Installe les observateurs passifs. Chaque bloc est indépendamment gardé :\n * `ReportingObserver` n'existe pas dans Safari, `PerformanceObserver` peut\n * refuser un type inconnu. Un observateur indisponible ne doit jamais empêcher\n * les autres de tourner, ni casser l'app hôte.\n */\nexport function installDiagnosticObservers(sinks: ObserverSinks): ObserverHandle {\n if (typeof window === \"undefined\") return NOOP;\n const teardowns: Array<() => void> = [];\n\n // --- Requêtes réseau, toutes origines confondues -------------------------\n // `buffered: true` rejoue les entrées ANTÉRIEURES à l'observateur : les\n // ressources chargées pendant le démarrage de l'app sont récupérées\n // rétroactivement, ce qu'aucun wrapper ne peut faire.\n if (typeof PerformanceObserver !== \"undefined\") {\n try {\n const obs = new PerformanceObserver((list) => {\n for (const raw of list.getEntries()) {\n try {\n const entry = toNetworkEntry(raw as PerformanceResourceTiming);\n if (entry) sinks.onResource(entry);\n } catch {\n // Observation best-effort : jamais au détriment de l'app hôte.\n }\n }\n });\n obs.observe({ type: \"resource\", buffered: true });\n teardowns.push(() => obs.disconnect());\n } catch {\n // Type non supporté : on s'en passe.\n }\n }\n\n // --- Signaux du navigateur (dépréciations, interventions) ----------------\n const ReportingObserverCtor = (\n window as unknown as { ReportingObserver?: new (...a: never[]) => ReportingObserverLike }\n ).ReportingObserver;\n if (ReportingObserverCtor) {\n try {\n const obs = new ReportingObserverCtor(\n ((reports: BrowserReport[]) => {\n for (const r of reports) {\n const detail = typeof r.body?.message === \"string\" ? r.body.message : r.type;\n sinks.onReport(\"warn\", `Navigateur (${r.type}) : ${detail}`);\n }\n }) as never,\n { types: REPORT_TYPES, buffered: true } as never,\n );\n obs.observe();\n teardowns.push(() => obs.disconnect());\n } catch {\n // Indisponible : on s'en passe.\n }\n }\n\n // --- Violations CSP ------------------------------------------------------\n // Le classique « ça marche en local, pas en prod » : une ressource bloquée\n // par la politique de sécurité échoue sans trace exploitable ailleurs.\n const onCsp = (e: Event) => {\n const v = e as SecurityPolicyViolationEvent;\n sinks.onReport(\n \"error\",\n `CSP : ${v.blockedURI || \"ressource\"} bloqué par « ${v.violatedDirective} »`,\n );\n };\n window.addEventListener(\"securitypolicyviolation\", onCsp);\n teardowns.push(() => window.removeEventListener(\"securitypolicyviolation\", onCsp));\n\n let done = false;\n return {\n teardown: () => {\n if (done) return;\n done = true;\n for (const t of teardowns) {\n try {\n t();\n } catch {\n // Déconnexion best-effort.\n }\n }\n },\n };\n}\n\n// `ReportingObserver` n'est pas dans les lib DOM de toutes les versions de TS :\n// on décrit le strict minimum qu'on utilise plutôt que d'élargir la config.\ntype BrowserReport = { type: string; body?: { message?: unknown } };\ntype ReportingObserverLike = { observe: () => void; disconnect: () => void };\n","// Instrumentation du diagnostic technique. Deux sources, délibérément\n// complémentaires :\n// - ce module PATCHE ce qui n'a pas d'équivalent observable : `console.*` (il\n// n'existe aucune API d'observation de la console), et `fetch`/XHR pour le\n// statut HTTP et la méthode que Resource Timing n'expose pas partout ;\n// - `diagnostics-observers.ts` OBSERVE passivement le reste — toutes les\n// requêtes (images, scripts, polices), les signaux du navigateur et les\n// violations CSP — sans rien patcher chez le client.\n// La FORME de la donnée et les helpers purs vivent dans `diagnostics.ts` ;\n// ce module est la partie qui touche au DOM.\n//\n// Deux régimes, un seul code :\n// - ARMÉ (session Lab consentie, cf. `hasDiagnosticsParam`) : installé dès\n// `connectLeestoApp`, les rings couvrent toute la session de test et sont\n// joints à TOUT signalement — y compris un rapport texte seul.\n// - ÉPHÉMÈRE : créé par le recorder rrweb le temps d'un enregistrement quand\n// le diagnostic n'est pas armé, ce qui reproduit le comportement historique.\n//\n// Le sink (`setSink`) sert au recorder : pendant un enregistrement, les erreurs\n// sont AUSSI émises en custom events rrweb pour rester entrelacées\n// chronologiquement dans le replay.\n\nimport {\n CONSOLE_RING_TAG,\n CONSOLE_TAG,\n type ConsoleRingEntry,\n type DiagnosticsSnapshot,\n type ErrorRingEntry,\n isDiagnosticRunId,\n LEESTO_RUN_HEADER,\n NETWORK_RING_TAG,\n NETWORK_TAG,\n} from \"@leesto/shared/diagnostics\";\nimport { createRing, type NetworkEntry } from \"@leesto/shared/networkRing\";\nimport { installDiagnosticObservers } from \"./diagnostics-observers\";\nimport { redactPII, safeUrl } from \"./diagnostics-redact\";\n\n// Ré-export : la rédaction vit désormais dans `diagnostics-redact.ts` (partagée\n// avec la source passive), mais elle reste exposée d'ici, son point d'entrée\n// historique pour les appelants et les tests.\nexport { redactPII } from \"./diagnostics-redact\";\n\nconst NETWORK_RING_MAX = 50;\n// Ring SÉPARÉ pour les ressources observées passivement : une page en charge\n// des dizaines (images, scripts, polices), et mélangées au même ring elles\n// évinceraient les appels `fetch`/XHR, qui portent le vrai statut HTTP et sont\n// bien plus utiles à l'équipe.\nconst RESOURCE_RING_MAX = 30;\nconst CONSOLE_RING_MAX = 100;\nconst ERROR_RING_MAX = 50;\nconst MSG_CAP = 500;\nconst STACK_CAP = 8000;\n\n/** Émetteur de custom events rrweb (branché par le recorder, sinon absent). */\nexport type EmitFn = <T>(tag: string, payload: T) => void;\n\nexport type DiagnosticsHandle = {\n /** Copie non destructive des trois rings. */\n snapshot: () => DiagnosticsSnapshot;\n /** Branche/débranche l'émission temps réel vers le recorder rrweb. */\n setSink: (emit: EmitFn | null) => void;\n /** Émet les rings log/info + réseau vers le sink courant, en un event chacun\n * (trop bavards pour un event par ligne). À appeler AVANT `teardown`. */\n flushRings: () => void;\n /** Restauration idempotente de tout ce qui a été patché. */\n teardown: () => void;\n};\n\n/** Stack trace d'une valeur (Error uniquement), rédigée et bornée. La stack est\n * souvent LA donnée manquante côté équipe : message seul = symptôme, stack =\n * localisation. Best-effort : undefined si la valeur n'en porte pas. */\nfunction stackOf(value: unknown): string | undefined {\n const stack = value instanceof Error ? value.stack : undefined;\n if (!stack) return undefined;\n return redactPII(stack).slice(0, STACK_CAP);\n}\n\n/** Représentation texte courte et sûre d'un argument loggé (sans dump massif). */\nfunction stringifyArg(a: unknown): string {\n if (a instanceof Error) return `${a.name}: ${a.message}`;\n if (typeof a === \"string\") return a;\n if (typeof a === \"object\" && a !== null) {\n try {\n return JSON.stringify(a, (key, value) => {\n if (\n /^(authorization|cookie|set-cookie|token|access_token|refresh_token|password|secret|api[-_]?key)$/i.test(\n key,\n )\n ) {\n return \"[masqué]\";\n }\n return value;\n }).slice(0, 500);\n } catch {\n return \"[objet]\";\n }\n }\n return String(a);\n}\n\n/** Taille de réponse dérivée UNIQUEMENT du header content-length (jamais du body). */\nfunction sizeFromContentLength(v: string | null): number | undefined {\n if (!v) return undefined;\n const n = Number(v);\n return Number.isFinite(n) && n >= 0 ? n : undefined;\n}\n\nconst NOOP_HANDLE: DiagnosticsHandle = {\n snapshot: () => ({ errors: [], logs: [], network: [] }),\n setSink: () => {},\n flushRings: () => {},\n teardown: () => {},\n};\n\n/**\n * Installe la capture et retourne son handle. Sans `sink`, rien n'est émis :\n * la donnée s'accumule dans les rings et n'en sort qu'au `snapshot()` d'un\n * signalement.\n */\nexport function installDiagnostics(opts: {\n captureNetwork: boolean;\n runId?: string;\n /** Origines supplémentaires autorisées à recevoir X-Leesto-Run-Id. */\n runIdOrigins?: string[];\n sink?: EmitFn | null;\n}): DiagnosticsHandle {\n if (typeof window === \"undefined\") return NOOP_HANDLE;\n\n const netRing = createRing<NetworkEntry>(NETWORK_RING_MAX);\n const resourceRing = createRing<NetworkEntry>(RESOURCE_RING_MAX);\n const consoleRing = createRing<ConsoleRingEntry>(CONSOLE_RING_MAX);\n const errorRing = createRing<ErrorRingEntry>(ERROR_RING_MAX);\n const runId = isDiagnosticRunId(opts.runId) ? opts.runId : undefined;\n const isRunIdAllowed = (raw: unknown): boolean => {\n if (!runId) return false;\n try {\n const target = new URL(String(raw), location.href);\n return target.origin === location.origin || (opts.runIdOrigins ?? []).includes(target.origin);\n } catch {\n return false;\n }\n };\n\n let sink: EmitFn | null = opts.sink ?? null;\n const emit: EmitFn = (tag, payload) => {\n sink?.(tag, payload);\n };\n\n const recordNet = (e: NetworkEntry) => {\n if (opts.captureNetwork) netRing.push(e);\n };\n\n /** Erreur : bufferisée dans le ring ET streamée au sink (entrelacement dans\n * le replay). La stack du premier argument Error localise le bug. */\n const recordError = (\n level: \"error\" | \"warn\",\n message: string,\n stack?: string,\n details: Partial<ErrorRingEntry> = {},\n ) => {\n if (!message) return;\n const entry: ErrorRingEntry = {\n level,\n message,\n ...(stack ? { stack } : {}),\n ...details,\n at: Date.now(),\n };\n errorRing.push(entry);\n emit(CONSOLE_TAG, entry);\n };\n\n const logConsole = (level: \"error\" | \"warn\", args: unknown[]) => {\n try {\n const message = redactPII(args.map(stringifyArg).join(\" \")).slice(0, MSG_CAP);\n const error = args.find((a) => a instanceof Error);\n recordError(level, message, stackOf(error), {\n mechanism: \"console\",\n ...(error instanceof Error && error.name ? { name: error.name } : {}),\n });\n } catch {\n // capture best-effort : ne jamais casser le code applicatif loggé.\n }\n };\n const recordLog = (level: \"log\" | \"info\", args: unknown[]) => {\n try {\n const message = redactPII(args.map(stringifyArg).join(\" \")).slice(0, MSG_CAP);\n if (message) consoleRing.push({ level, message, at: Date.now() });\n } catch {\n // capture best-effort.\n }\n };\n\n const origError = console.error;\n const origWarn = console.warn;\n const origLog = console.log;\n const origInfo = console.info;\n console.error = (...args: unknown[]) => {\n logConsole(\"error\", args);\n return origError.apply(console, args as never);\n };\n console.warn = (...args: unknown[]) => {\n logConsole(\"warn\", args);\n return origWarn.apply(console, args as never);\n };\n console.log = (...args: unknown[]) => {\n recordLog(\"log\", args);\n return origLog.apply(console, args as never);\n };\n console.info = (...args: unknown[]) => {\n recordLog(\"info\", args);\n return origInfo.apply(console, args as never);\n };\n\n const onError = (e: Event) => {\n // Un échec de CHARGEMENT de ressource (<img>, <script>, <link>) est dispatché\n // sur l'élément et NE REMONTE PAS : seule la phase de capture le voit. D'où\n // le `true` ci-dessous — sans lui, un chunk JS en 404 nous échappait\n // totalement, alors que c'est un des bugs de test les plus fréquents.\n const target = e.target;\n if (target instanceof Element) {\n const src =\n (target as Partial<HTMLImageElement & HTMLScriptElement>).src ||\n (target as Partial<HTMLLinkElement>).href ||\n \"\";\n if (!src) return;\n recordError(\n \"error\",\n `Ressource non chargée : <${target.tagName.toLowerCase()}> ${safeUrl(src)}`.slice(\n 0,\n MSG_CAP,\n ),\n undefined,\n { mechanism: \"resource\", sourceUrl: safeUrl(src) },\n );\n return;\n }\n const err = e as ErrorEvent;\n recordError(\n \"error\",\n redactPII(`Erreur non gérée : ${err.message}`).slice(0, MSG_CAP),\n stackOf(err.error),\n {\n mechanism: \"window.error\",\n ...(typeof err.error?.name === \"string\" ? { name: err.error.name } : {}),\n ...(typeof err.filename === \"string\" && err.filename\n ? { sourceUrl: safeUrl(err.filename) }\n : {}),\n ...(typeof err.lineno === \"number\" && err.lineno > 0 ? { line: err.lineno } : {}),\n ...(typeof err.colno === \"number\" && err.colno > 0 ? { column: err.colno } : {}),\n },\n );\n };\n const onRejection = (e: PromiseRejectionEvent) => {\n recordError(\n \"error\",\n redactPII(`Promesse rejetée : ${stringifyArg(e.reason)}`).slice(0, MSG_CAP),\n stackOf(e.reason),\n {\n mechanism: \"unhandledrejection\",\n ...(e.reason instanceof Error && e.reason.name ? { name: e.reason.name } : {}),\n },\n );\n };\n window.addEventListener(\"error\", onError, true);\n window.addEventListener(\"unhandledrejection\", onRejection);\n\n // --- fetch ---------------------------------------------------------------\n const origFetch = typeof window.fetch === \"function\" ? window.fetch.bind(window) : null;\n if (origFetch) {\n window.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {\n const start = Date.now();\n const method = (\n init?.method ??\n (input instanceof Request ? input.method : \"GET\") ??\n \"GET\"\n ).toUpperCase();\n const url = safeUrl(input);\n let requestInit = init;\n if (runId && isRunIdAllowed(input)) {\n const headers = new Headers(input instanceof Request ? input.headers : undefined);\n for (const [key, value] of new Headers(init?.headers)) headers.set(key, value);\n headers.set(LEESTO_RUN_HEADER, runId);\n requestInit = { ...init, headers };\n }\n try {\n const res = await origFetch(input, requestInit);\n // Capture best-effort : ne JAMAIS convertir un succès en échec ni jeter\n // l'erreur d'instrumentation à l'appelant. `res` est toujours renvoyé.\n try {\n const requestId = res.headers.get(\"x-request-id\");\n const traceparent = res.headers.get(\"traceparent\");\n recordNet({\n method,\n url,\n status: res.status,\n durationMs: Date.now() - start,\n responseSize: sizeFromContentLength(res.headers.get(\"content-length\")),\n contentType: res.headers.get(\"content-type\") ?? undefined,\n startedAt: start,\n ...(requestId ? { requestId: requestId.slice(0, 200) } : {}),\n ...(traceparent ? { traceparent: traceparent.slice(0, 200) } : {}),\n ...(runId ? { runId } : {}),\n });\n if (!res.ok) {\n emit(NETWORK_TAG, { method, url, status: res.status, durationMs: Date.now() - start });\n }\n } catch {\n // capture best-effort : ne jamais casser l'appel fetch applicatif.\n }\n return res;\n } catch (err) {\n // status 0 = la requête n'a pas abouti (réseau coupé, CORS, abort…).\n try {\n const durationMs = Date.now() - start;\n recordNet({\n method,\n url,\n status: 0,\n durationMs,\n startedAt: start,\n failed: true,\n ...(runId ? { runId } : {}),\n });\n emit(NETWORK_TAG, { method, url, status: 0, durationMs });\n } catch {\n // capture best-effort.\n }\n throw err;\n }\n }) as typeof window.fetch;\n }\n\n // --- XMLHttpRequest ------------------------------------------------------\n const origOpen = XMLHttpRequest.prototype.open;\n const origSend = XMLHttpRequest.prototype.send;\n type XhrMeta = { method: string; url: string; start: number; propagate: boolean };\n const META = \"__echoNet\" as const;\n XMLHttpRequest.prototype.open = function (\n this: XMLHttpRequest & { [META]?: XhrMeta },\n method: string,\n url: string | URL,\n ...rest: unknown[]\n ) {\n this[META] = {\n method: (method || \"GET\").toUpperCase(),\n url: safeUrl(url),\n start: 0,\n propagate: isRunIdAllowed(url),\n };\n return origOpen.apply(this, [method, url, ...rest] as never);\n };\n XMLHttpRequest.prototype.send = function (\n this: XMLHttpRequest & { [META]?: XhrMeta },\n ...args: unknown[]\n ) {\n const meta = this[META];\n if (meta) {\n meta.start = Date.now();\n if (runId && meta.propagate) {\n try {\n this.setRequestHeader(LEESTO_RUN_HEADER, runId);\n } catch {\n // Header injection is best-effort; never break the XHR.\n }\n }\n // `{ once: true }` : sinon la réutilisation d'une même instance XHR (polling)\n // ferait re-tirer ce listener au 2e loadend → entrée corrompue.\n this.addEventListener(\n \"loadend\",\n () => {\n try {\n const durationMs = Date.now() - meta.start;\n const status = this.status;\n const failed = status === 0;\n const requestId = this.getResponseHeader(\"x-request-id\");\n const traceparent = this.getResponseHeader(\"traceparent\");\n recordNet({\n method: meta.method,\n url: meta.url,\n status,\n durationMs,\n responseSize: sizeFromContentLength(this.getResponseHeader(\"content-length\")),\n contentType: this.getResponseHeader(\"content-type\") ?? undefined,\n startedAt: meta.start,\n ...(failed ? { failed: true } : {}),\n ...(runId ? { runId } : {}),\n ...(requestId ? { requestId: requestId.slice(0, 200) } : {}),\n ...(traceparent ? { traceparent: traceparent.slice(0, 200) } : {}),\n });\n if (failed || status >= 400) {\n emit(NETWORK_TAG, { method: meta.method, url: meta.url, status, durationMs });\n }\n } catch {\n // capture best-effort : ne jamais casser la requête XHR applicative.\n }\n },\n { once: true },\n );\n }\n return origSend.apply(this, args as never);\n };\n\n // --- Socle passif --------------------------------------------------------\n // Couvre ce que le wrapper ne voit pas (images, scripts, polices, CSS) et\n // rejoue rétroactivement le démarrage via `buffered: true`.\n const observers = installDiagnosticObservers({\n onResource: (entry) => {\n if (opts.captureNetwork) resourceRing.push(runId ? { ...entry, runId } : entry);\n },\n onReport: (level, message) =>\n recordError(level, redactPII(message).slice(0, MSG_CAP), undefined, { mechanism: \"report\" }),\n });\n\n /** Les deux sources réseau fusionnées, dans l'ordre chronologique : le\n * wrapper (statut HTTP exact) et l'observation passive (couverture large). */\n const mergedNetwork = (): NetworkEntry[] =>\n opts.captureNetwork\n ? [...netRing.snapshot(), ...resourceRing.snapshot()].sort(\n (a, b) => a.startedAt - b.startedAt,\n )\n : [];\n\n let restored = false;\n return {\n snapshot: () => ({\n errors: errorRing.snapshot(),\n logs: consoleRing.snapshot(),\n network: mergedNetwork(),\n ...(runId ? { runId } : {}),\n }),\n setSink: (next) => {\n sink = next;\n },\n flushRings: () => {\n // `snapshot()` est NON destructif : le flush d'une session ne doit jamais\n // amputer les rings permanents d'un rapport ultérieur.\n const entries = mergedNetwork();\n if (entries.length > 0) emit(NETWORK_RING_TAG, { entries });\n const logs = consoleRing.snapshot();\n if (logs.length > 0) emit(CONSOLE_RING_TAG, { entries: logs });\n const errors = errorRing.snapshot();\n if (errors.length > 0) emit(CONSOLE_TAG, { entries: errors });\n },\n teardown: () => {\n if (restored) return;\n restored = true;\n sink = null;\n observers.teardown();\n console.error = origError;\n console.warn = origWarn;\n console.log = origLog;\n console.info = origInfo;\n window.removeEventListener(\"error\", onError, true);\n window.removeEventListener(\"unhandledrejection\", onRejection);\n if (origFetch) window.fetch = origFetch;\n XMLHttpRequest.prototype.open = origOpen;\n XMLHttpRequest.prototype.send = origSend;\n },\n };\n}\n","// Auto-login (ECH-309) — détection et remplissage d'un formulaire de CONNEXION\n// dans l'app embarquée. Module vanilla, aucun état global : `installLoginFill`\n// renvoie un handle que app-client.ts pilote depuis les messages du shell.\n//\n// Deux invariants, dans l'ordre :\n// 1. Ne JAMAIS soumettre autre chose qu'une connexion. Un champ mot de passe\n// ne suffit pas (inscription, changement de mot de passe) et un champ email\n// non plus (magic link, mot de passe oublié, newsletter). Il faut un signal\n// positif ET aucun signal négatif — cf. spec « Bridge et connecteur ».\n// 2. Chaque champ est servi AU PLUS UNE FOIS par chargement de page, et un\n// champ déjà rempli n'est JAMAIS écrasé. Une fois le mot de passe servi,\n// les identifiants sont oubliés mais l'observation CONTINUE : si l'app\n// rejette la connexion et re-rend son formulaire, on le ré-annonce (une\n// fois qu'il a réellement disparu de la page), et c'est le shell — seul\n// porteur de l'anti-boucle à travers les navigations — qui décide.\nimport { LOGIN_SETTLE_MS, type LoginFillStep } from \"@leesto/shared/bridge\";\n\nexport type LoginCredentials = { login: string; password: string };\n\nexport type LoginFormMatch = {\n /** `password` : formulaire complet ou second écran ; `identifier` : premier\n * écran d'un login en deux temps (identifiant seul). */\n kind: \"password\" | \"identifier\";\n form: HTMLFormElement | null;\n identifier: HTMLInputElement | null;\n password: HTMLInputElement | null;\n submit: HTMLElement | null;\n};\n\nexport type FillOutcome = { step: LoginFillStep } | { error: string };\n\n/** Ce qui a déjà été servi sur cette page. */\nexport type FilledState = { identifier: boolean; password: boolean };\n\nexport type LoginFillSinks = {\n onDetected: () => void;\n onFilled: (step: LoginFillStep) => void;\n onError: (reason: string) => void;\n};\n\nexport type LoginFillHandle = {\n /** Arme la détection (idempotent : renvoyé à chaque `leesto:ready`). */\n watch: () => void;\n /** Identifiants du rôle courant : remplit ce qui est présent, puis ce qui apparaît. */\n fill: (creds: LoginCredentials) => void;\n /** Oublie les identifiants et arrête d'observer. */\n cancel: () => void;\n teardown: () => void;\n};\n\nconst DEBOUNCE_MS = 100;\nconst OBSERVED_ATTRIBUTES = [\"hidden\", \"class\", \"style\", \"type\", \"disabled\", \"aria-hidden\"];\n\n// Sélecteurs partagés — une seule définition de ce qu'est un champ mot de\n// passe / identifiant, réutilisée partout où la question se pose (détection,\n// fallback sans <form>, comptage des surfaces candidates pour l'ambiguïté\n// d'un titre hors formulaire).\nconst PASSWORD_SELECTOR = 'input[type=\"password\"]';\nconst IDENTIFIER_SELECTOR =\n 'input[autocomplete=\"username\"], input[autocomplete=\"email\"], input[type=\"email\"]';\n\nconst CREDENTIAL_SELECTOR = `${PASSWORD_SELECTOR}, ${IDENTIFIER_SELECTOR}`;\n\n// Vocabulaire comparé après normalisation (minuscules, sans accents).\nconst POSITIVE =\n /\\b(connexion|se connecter|connectez[- ]vous|s'identifier|identifiez[- ]vous|login|log ?in|sign ?in)\\b/;\n// Vocabulaire complet : appliqué au texte du bouton et à l'en-tête, deux\n// canaux écrits par un humain pour un lecteur humain — un faux positif y est\n// rare et le contexte y est fiable.\n//\n// Il inclut le vocabulaire d'ENREGISTREMENT / CONFIRMATION / TRANSACTION\n// (enregistrer, mettre à jour, confirmer, supprimer mon compte, payer…) : ces\n// écrans vivent DERRIÈRE la connexion, là où le testeur passe toute sa\n// session, et `autocomplete=\"current-password\"` y est la valeur RECOMMANDÉE\n// par le W3C pour une ré-authentification (profil, paiement, suppression de\n// compte). Sans ces tokens, le seul `current-password` suffisait à les faire\n// passer pour une connexion : on écrasait la vraie adresse du client et on\n// cliquait « Confirmer la suppression ». Ils ne vont PAS dans\n// `NEGATIVE_IDENTITY` : sur le canal `id`/`name`/`class`/`action`, `save` ou\n// `update` sont des mots de route trop courants.\nconst NEGATIVE =\n /\\b(inscription|s'inscrire|inscrivez|creer (un|votre|mon) compte|sign ?up|register|create (an |your )?account|mot de passe oublie|oublie|reinitialiser|forgot|reset|lien de connexion|magic link|envoyer (un|le) lien|send (me )?(a |the )?link|code|newsletter|abonner|subscribe|enregistrer|sauvegarder|mettre a jour|save|update|confirmer|confirm|supprimer mon compte|delete account|payer|pay)\\b/;\n// Sous-ensemble appliqué à `id`/`name`/`class`/au CHEMIN de `action` : ces\n// canaux sont écrits par un développeur pour une machine (routes, slugs\n// OAuth…), où un token court et générique (`code`, `reset`, `register`,\n// `oublie` isolé) déclenche trop de faux positifs — `response_type=code`\n// dans une URL OAuth en est l'exemple réel. On n'y garde que les phrases\n// longues, sans ambiguïté.\nconst NEGATIVE_IDENTITY =\n /\\b(inscription|s'inscrire|inscrivez|creer (un|votre|mon) compte|sign ?up|create (an |your )?account|mot de passe oublie|reinitialiser|forgot|lien de connexion|magic link|envoyer (un|le) lien|send (me )?(a |the )?link|newsletter|abonner|subscribe)\\b/;\n\n// Un bouton qui DIT afficher/masquer le mot de passe est une commande de champ,\n// jamais une soumission — même posé au milieu des champs.\nconst SHOW_HIDE = /\\b(afficher|masquer|voir|show|hide|toggle)\\b/;\n// Idem pour une commande qui VIDE le champ : l'élire effaçait le mot de passe\n// qu'on venait d'écrire, et annonçait une connexion.\nconst CLEAR = /\\b(effacer|vider|supprimer|clear|reset)\\b/;\nconst EYE = /[\\u{1F441}\\u{1F576}\\u{1F440}]/u;\n\nfunction normalize(text: string | null | undefined): string {\n return (\n (text ?? \"\")\n .normalize(\"NFD\")\n .replace(/[̀-ͯ]/g, \"\")\n // Apostrophes typographiques → apostrophe droite : les UI françaises\n // écrivent « S’inscrire », « S’identifier ». Sans ce pli, les tokens\n // `s'inscrire` / `s'identifier` du vocabulaire sont morts.\n .replace(/[’‘]/g, \"'\")\n .replace(/\\s+/g, \" \")\n .trim()\n .toLowerCase()\n );\n}\n\n/** Visible au sens strict : ni l'élément ni un de ses ANCÊTRES n'est masqué\n * (`hidden`, `aria-hidden`, `type=hidden`, `display:none`/`visibility:hidden`\n * calculé). On remonte l'arbre à la main plutôt que de s'en remettre à\n * `getClientRects()` : `display` ne s'hérite pas — `getComputedStyle` d'un\n * descendant ne reflète JAMAIS un ancêtre masqué, dans aucun navigateur —\n * et jsdom ne fait aucune mise en page réelle : `getClientRects()` y\n * renvoie une liste TOUJOURS vide, y compris pour un élément parfaitement\n * visible (vérifié empiriquement), ce qui casserait toute la détection en\n * test. Cette marche d'ancêtres donne le même résultat qu'un navigateur réel\n * sans dépendre d'une mise en page que jsdom ne calcule pas. */\nfunction isVisible(el: HTMLElement): boolean {\n let node: HTMLElement | null = el;\n while (node) {\n if (node.hasAttribute(\"hidden\") || node.getAttribute(\"aria-hidden\") === \"true\") return false;\n if (node instanceof HTMLInputElement && node.type === \"hidden\") return false;\n const style = node.ownerDocument.defaultView?.getComputedStyle(node);\n if (style && (style.display === \"none\" || style.visibility === \"hidden\")) return false;\n node = node.parentElement;\n }\n return true;\n}\n\nfunction visibleInputs(scope: ParentNode, selector: string): HTMLInputElement[] {\n return Array.from(scope.querySelectorAll<HTMLInputElement>(selector)).filter(isVisible);\n}\n\nfunction buttonLabel(el: HTMLElement | null): string {\n if (!el) return \"\";\n if (el instanceof HTMLInputElement) return el.value;\n return el.textContent ?? \"\";\n}\n\n/** Région dans laquelle on cherche les éléments SATELLITES d'un candidat\n * (l'identifiant, le bouton de soumission) — jamais le document entier.\n * Pour un `<form>`, c'est le formulaire lui-même : il borne naturellement.\n * Pour un candidat SANS `<form>`, c'est l'ancêtre le plus haut qu'on puisse\n * atteindre depuis le champ retenu sans avaler un candidat ÉTRANGER\n * (cf. `regionAround`), et `outsideForms` interdit en plus d'y retenir quoi\n * que ce soit qui appartienne à un `<form>` : une surface de connexion sans\n * `<form>` n'emprunte JAMAIS le champ ni le bouton d'un voisin — sinon on\n * saisit des identifiants de test dans le formulaire de contact du client,\n * puis on le soumet. */\ntype Region = { scope: ParentNode; outsideForms: boolean };\n\nfunction inRegion(region: Region, el: Element): boolean {\n return !region.outsideForms || !el.closest(\"form\");\n}\n\nfunction regionInputs(region: Region, selector: string): HTMLInputElement[] {\n return Array.from(region.scope.querySelectorAll<HTMLInputElement>(selector)).filter(\n (el) => isVisible(el) && inRegion(region, el),\n );\n}\n\n/** Nom accessible d'une commande : ce qu'un lecteur (humain ou d'écran) en\n * comprend. */\nfunction controlName(el: HTMLElement): string {\n return normalize(el.getAttribute(\"aria-label\") ?? el.getAttribute(\"title\") ?? el.textContent);\n}\n\n/** Commande « afficher / masquer le mot de passe » : jamais un bouton de\n * soumission, où qu'elle soit posée. L'élire cliquait l'œil et annonçait une\n * connexion qui n'avait pas eu lieu. */\nfunction isShowHideControl(el: HTMLElement): boolean {\n const name = controlName(el);\n return SHOW_HIDE.test(name) || EYE.test(name);\n}\n\n/** Commande DE CHAMP : un `<button>` sans `type=\"submit\"` dont le conteneur\n * immédiat renferme un champ d'identification mais PAS l'identifiant retenu\n * par ce candidat. Le vrai bouton d'une connexion est posé avec l'ensemble\n * des champs, donc avec l'identifiant ; une croix « effacer » ou un œil vit\n * dans le conteneur d'UN champ. Sans identifiant retenu (écran mot de passe\n * seul), rien n'est écarté : le bouton partage alors légitimement le\n * conteneur du seul champ de l'écran (InputGroup). */\nfunction isFieldAffordance(button: HTMLElement, identifier: HTMLInputElement | null): boolean {\n if (button.getAttribute(\"type\") === \"submit\") return false;\n if (!identifier) return false;\n const parent = button.parentElement;\n if (!parent) return false;\n if (visibleInputs(parent, CREDENTIAL_SELECTOR).length === 0) return false;\n return !parent.contains(identifier);\n}\n\n/** Toutes les commandes interactives visibles d'un conteneur. */\nconst CONTROL_SELECTOR =\n 'button, input[type=\"submit\"], input[type=\"button\"], input[type=\"image\"], a[href]';\n\nfunction hasControl(container: Element): boolean {\n return Array.from(container.querySelectorAll<HTMLElement>(CONTROL_SELECTOR)).some(isVisible);\n}\n\n/** Ce champ d'identification appartient-il à une AUTRE surface que la nôtre ?\n * Test de CONTENANCE : on remonte depuis le candidat tant que l'ancêtre ne\n * contient pas notre champ retenu, et s'il porte une commande interactive\n * c'est une surface autonome (widget promo, newsletter, composeur de chat,\n * en-tête de recherche) — elle a de quoi se soumettre seule, donc elle ne\n * nous appartient pas.\n *\n * Remplace un test de POSITION (« une commande sépare-t-elle les deux champs\n * dans l'ordre du document ? ») qui se trompait des deux côtés : il manquait\n * le leurre dont la commande PRÉCÈDE son propre champ, et il prenait pour un\n * leurre la carte de connexion la plus banale, où un lien « Mot de passe\n * oublié ? » se glisse entre les deux rangées de champs. La contenance ne\n * regarde que ce qui est RANGÉ AVEC le candidat, jamais ce qui passe entre. */\nfunction fromAnotherSurface(candidate: Element, field: Element): boolean {\n let node: Element | null = candidate.parentElement;\n while (node && !node.contains(field)) {\n if (hasControl(node)) return true;\n node = node.parentElement;\n }\n return false;\n}\n\n/** Contexte accessible d'un champ : ce qui le nomme pour un humain comme pour\n * une machine. Sert à reconnaître un champ de leurre qui n'a AUCUNE commande\n * à lui (`<label>Newsletter <input type=\"email\"></label>`) — structurellement\n * indiscernable d'un wrapper de champ, mais qui le dit en toutes lettres. */\nfunction fieldContext(input: HTMLInputElement): string {\n const parts: Array<string | null> = [\n input.getAttribute(\"name\"),\n input.getAttribute(\"id\"),\n input.getAttribute(\"placeholder\"),\n input.getAttribute(\"aria-label\"),\n input.closest(\"label\")?.textContent ?? null,\n ];\n const id = input.getAttribute(\"id\");\n if (id) {\n const associated = input.ownerDocument.querySelector(`label[for=\"${CSS.escape(id)}\"]`);\n if (associated) parts.push(associated.textContent);\n }\n return normalize(parts.filter(Boolean).join(\" \"));\n}\n\n/** Région d'un candidat sans `<form>`, par ASCENSION depuis le champ retenu\n * (le mot de passe choisi, ou l'identifiant sur un premier écran\n * identifiant-seul) — jamais depuis l'ensemble des champs libres de la page,\n * qui ferait remonter la région jusqu'à un leurre lointain.\n *\n * On part du parent de ce champ et on monte tant que la région NE SUFFIT PAS\n * — elle suffit quand elle porte À LA FOIS l'identifiant que ce candidat doit\n * encore trouver et un bouton de soumission. Monter est nécessaire : le\n * bouton, ou l'identifiant, vit souvent hors du conteneur du mot de passe\n * (pied de modale, `<label>` ou `.field` par champ). Deux garde-fous :\n *\n * 1. On s'arrête avant un ancêtre qui avalerait un candidat ÉTRANGER : un\n * `<form>`, un SECOND mot de passe, un SECOND identifiant alors qu'on en\n * retient déjà un, un identifiant dont le CONTEXTE parle d'autre chose\n * (newsletter, inscription… cf. `fieldContext`), ou un identifiant RANGÉ\n * AVEC une commande interactive (`fromAnotherSurface`). Ce dernier test\n * est la frontière exacte entre un leurre — une surface autonome, qui a de\n * quoi se soumettre seule — et un identifiant simplement rangé dans un\n * conteneur frère (un wrapper par champ, le balisage React le plus\n * courant), qu'il faut au contraire aller chercher.\n *\n * 2. Si aucune région visitée ne suffit, on ne garde PAS la plus haute : on\n * retient la plus basse dont le bouton DIT la connexion, et à défaut le\n * wrapper du champ lui-même — donc, en pratique, aucun bouton du tout\n * (faux négatif assumé) plutôt que celui d'un voisin élu faute de mieux.\n * Sans ça, un écran mot-de-passe-seul — qui ne peut par construction\n * jamais suffire — montait jusqu'à `<body>` et y élisait le bouton du\n * premier widget venu (barre de recherche, bandeau cookies), qu'on\n * cliquait. Un leurre sans\n * champ d'identification est invisible aux tests ci-dessus : seule\n * l'étendue de la région peut l'écarter. */\nfunction regionAround(field: HTMLInputElement, password: HTMLInputElement | null): Region | null {\n const start = field.parentElement;\n if (!start) return null;\n const body = field.ownerDocument.body;\n\n // Ce que la région porte, évalué avec les fonctions de la détection\n // elle-même : on teste exactement ce que le candidat retiendra.\n const identifierIn = (scope: HTMLElement): HTMLInputElement | null =>\n password ? identifierFor({ scope, outsideForms: true }, password) : field;\n const submitIn = (scope: HTMLElement): HTMLElement | null =>\n findSubmit({ scope, outsideForms: true }, field, identifierIn(scope));\n const suffices = (scope: HTMLElement): boolean => !!identifierIn(scope) && !!submitIn(scope);\n\n let region: HTMLElement = start;\n // La plus basse région visitée dont le bouton DIT la connexion : un bouton\n // étranger logé dans le conteneur du mot de passe ferait sinon gagner sa\n // région à lui.\n let withPositiveSubmit: HTMLElement | null = null;\n const noteSubmit = (scope: HTMLElement) => {\n const submit = submitIn(scope);\n if (!submit) return;\n if (!withPositiveSubmit && POSITIVE.test(controlName(submit))) withPositiveSubmit = scope;\n };\n noteSubmit(start);\n while (region !== body && !suffices(region)) {\n const next: HTMLElement | null = region.parentElement;\n if (!next) break;\n if (next.querySelector(\"form\")) break;\n const own: Element[] = [field];\n const retained = identifierIn(region);\n if (retained && retained !== field) own.push(retained);\n const identifierRetained = !!retained;\n const foreign = visibleInputs(next, CREDENTIAL_SELECTOR)\n .filter((input) => !input.closest(\"form\") && !own.includes(input))\n .some((input) => {\n if (input.matches(PASSWORD_SELECTOR)) return true;\n if (identifierRetained) return true;\n if (NEGATIVE.test(fieldContext(input))) return true;\n return fromAnotherSurface(input, field);\n });\n if (foreign) break;\n region = next;\n noteSubmit(next);\n }\n // Aucune région visitée ne suffit et aucune ne porte un bouton qui DIT la\n // connexion : on redescend au wrapper du champ lui-même. `findSubmit` n'y\n // trouvera rien, `canSubmit` sera faux et `fillLoginForm` n'écrira rien —\n // un faux négatif propre. C'est la dernière commande ÉTRANGÈRE qu'on\n // pouvait encore cliquer : le bouton d'un widget voisin, élu faute de\n // mieux parce que le login n'a pas de bouton à lui.\n const scope = suffices(region) ? region : (withPositiveSubmit ?? start);\n return { scope, outsideForms: true };\n}\n\n/** Région du candidat : le `<form>` lui-même, ou l'ascension bornée ci-dessus.\n * `password` est le mot de passe retenu par ce candidat (null sur un premier\n * écran identifiant-seul) : l'ascension en a besoin pour savoir si la région\n * doit encore fournir un identifiant. */\nfunction regionFor(\n form: HTMLFormElement | null,\n field: HTMLInputElement,\n password: HTMLInputElement | null,\n): Region | null {\n return form ? { scope: form, outsideForms: false } : regionAround(field, password);\n}\n\n/** Ce bouton est-il rangé dans le conteneur d'UN champ, sous la région ?\n * Le vrai bouton d'une connexion est posé avec l'ensemble des champs ; une\n * commande logée dans le conteneur d'un seul champ est une commande de ce\n * champ (ou celle d'un widget qui s'y est invité). */\nfunction insideFieldWrapper(button: HTMLElement, region: Region): boolean {\n let node: Element | null = button.parentElement;\n while (node && node !== region.scope) {\n if (visibleInputs(node, CREDENTIAL_SELECTOR).length === 1) return true;\n node = node.parentElement;\n }\n return false;\n}\n\n/** Bouton de soumission de ce candidat dans sa région, choisi par PRÉFÉRENCE\n * et non par premier venu. `identifier` est l'identifiant retenu (null sur un\n * écran mot-de-passe-seul).\n *\n * Exclusions dures : une commande qui dit afficher/masquer ou effacer n'est\n * jamais une soumission, et une commande de champ non plus (cf.\n * `isFieldAffordance`).\n *\n * PLANCHER, avant toute préférence : un bouton sans `type=\"submit\"` n'est\n * électable que s'il SUIT le champ d'ancrage. Sans ce plancher, dès que la\n * région du login n'offre aucun bouton, la commande quelconque la plus proche\n * qui précède l'emporte — et le chrome d'une page en contient toujours une\n * (« Fermer » d'une promo, « Tout accepter » d'un bandeau, « Menu » d'un\n * en-tête) : on la cliquait. Un `type=\"submit\"` explicite reste électable des\n * deux côtés : il est déjà borné par la région, et une connexion réelle place\n * parfois son bouton avant le champ.\n *\n * Préférences ensuite, dans l'ordre : hors du conteneur d'un champ ; nom qui\n * dit la connexion ; `type=\"submit\"` explicite ; placé APRÈS le champ\n * d'ancrage ; enfin le plus proche de celui-ci. */\nfunction findSubmit(\n region: Region,\n anchor: HTMLElement,\n identifier: HTMLInputElement | null,\n): HTMLElement | null {\n const follows = (b: HTMLElement): boolean =>\n !!(anchor.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING);\n const candidates = Array.from(\n region.scope.querySelectorAll<HTMLElement>('button, input[type=\"submit\"]'),\n ).filter(\n (b) =>\n isVisible(b) &&\n inRegion(region, b) &&\n (b.getAttribute(\"type\") === \"submit\" || follows(b)) &&\n !isShowHideControl(b) &&\n !CLEAR.test(controlName(b)) &&\n !isFieldAffordance(b, identifier),\n );\n if (candidates.length === 0) return null;\n const rank = (b: HTMLElement, index: number): number[] => {\n const after = follows(b);\n return [\n insideFieldWrapper(b, region) ? 1 : 0,\n POSITIVE.test(controlName(b)) ? 0 : 1,\n b.getAttribute(\"type\") === \"submit\" ? 0 : 1,\n after ? 0 : 1,\n // Le plus proche du champ : le premier de ceux qui suivent, le dernier\n // de ceux qui précèdent.\n after ? index : -index,\n ];\n };\n let best = candidates[0] as HTMLElement;\n let bestRank = rank(best, 0);\n candidates.forEach((candidate, index) => {\n const candidateRank = rank(candidate, index);\n for (let i = 0; i < candidateRank.length; i++) {\n const a = candidateRank[i] as number;\n const b = bestRank[i] as number;\n if (a === b) continue;\n if (a < b) {\n best = candidate;\n bestRank = candidateRank;\n }\n return;\n }\n });\n return best;\n}\n\n/** Un ancêtre qui contient PLUSIEURS surfaces de connexion candidates ne peut\n * pas prêter son titre à UNE SEULE d'entre elles sans ambiguïté : un `<h1>`\n * de page dit quelque chose de la page, rien d'une surface précise parmi\n * plusieurs. Compter uniquement les `<form>` sous-estime les concurrents :\n * ce module traite délibérément une région SANS `<form>` comme une surface\n * de login à part entière (apps React/Lovable/Supabase) — un `<form>` leurre\n * + un login sans `<form>` sous le même ancêtre sont DEUX surfaces, pas une.\n * On compte donc : le nombre de `<form>` + 1 si un champ identifiant/mot de\n * passe visible existe hors de TOUT `<form>` dans cet ancêtre (même champs\n * que la détection utilise partout ailleurs — pas une seconde notion). */\nfunction unambiguousHeadingContainer(container: Element): boolean {\n const forms = container.querySelectorAll(\"form\").length;\n const looseCredential = visibleInputs(container, CREDENTIAL_SELECTOR).some(\n (input) => !input.closest(\"form\"),\n );\n return forms + (looseCredential ? 1 : 0) === 1;\n}\n\n/** En-tête du formulaire : aria-label / aria-labelledby, sinon le premier\n * titre DANS le formulaire — toujours une évidence valide, sans ambiguïté\n * possible. Sinon un titre HORS du formulaire ne compte que s'il est\n * attaché sans ambiguïté à CE formulaire : on remonte jusqu'au plus proche\n * ancêtre qui le contient (un frère qui précède, sinon le plus proche\n * ancêtre « section-like »), et on exige que cet ancêtre ne contienne QUE\n * ce `<form>` — sinon l'évidence est jetée entièrement, jamais prêtée à un\n * autre formulaire du même ancêtre. */\nfunction headingText(form: HTMLFormElement | null, scope: ParentNode): string {\n if (form) {\n const label = form.getAttribute(\"aria-label\");\n if (label) return label;\n const by = form.getAttribute(\"aria-labelledby\");\n if (by) {\n const el = form.ownerDocument.getElementById(by);\n if (el) return el.textContent ?? \"\";\n }\n const inside = form.querySelector(\"h1, h2, h3, legend\");\n if (inside) return inside.textContent ?? \"\";\n let sibling = form.previousElementSibling;\n while (sibling) {\n const heading = /^(h1|h2|h3|legend)$/i.test(sibling.tagName)\n ? sibling\n : sibling.querySelector(\"h1, h2, h3, legend\");\n if (heading) {\n const container = form.parentElement;\n if (container && unambiguousHeadingContainer(container)) {\n return heading.textContent ?? \"\";\n }\n return \"\";\n }\n sibling = sibling.previousElementSibling;\n }\n const container = form.closest(\n \"section, article, aside, dialog, fieldset, [role='dialog'], [role='region']\",\n );\n if (container && container !== form) {\n const heading = container.querySelector(\"h1, h2, h3, legend\");\n if (heading) {\n if (unambiguousHeadingContainer(container)) return heading.textContent ?? \"\";\n return \"\";\n }\n }\n return \"\";\n }\n const root = scope instanceof Document ? scope.body : (scope as HTMLElement);\n return root?.querySelector(\"h1, h2, h3\")?.textContent ?? \"\";\n}\n\nfunction signals(form: HTMLFormElement | null, scope: ParentNode, submit: HTMLElement | null) {\n const submitText = normalize(buttonLabel(submit));\n const heading = normalize(headingText(form, scope));\n // `action` sur son CHEMIN seul : la query string d'une URL OAuth réelle\n // (`?client_id=…&response_type=code&…`) contient des tokens courts qui\n // n'ont rien à voir avec la nature du formulaire.\n const actionPath = (form?.getAttribute(\"action\") ?? \"\").split(\"?\")[0];\n const identity = normalize(\n [form?.id, form?.getAttribute(\"name\"), form?.className, actionPath].filter(Boolean).join(\" \"),\n );\n return {\n positive: POSITIVE.test(submitText) || POSITIVE.test(heading),\n negative:\n NEGATIVE.test(submitText) || NEGATIVE.test(heading) || NEGATIVE_IDENTITY.test(identity),\n };\n}\n\nfunction identifierFor(region: Region, password: HTMLInputElement | null): HTMLInputElement | null {\n const preferred =\n regionInputs(region, 'input[autocomplete=\"username\"]')[0] ??\n regionInputs(region, 'input[autocomplete=\"email\"]')[0] ??\n regionInputs(region, 'input[type=\"email\"]')[0];\n if (preferred) return preferred;\n if (!password) return null;\n // Le dernier champ texte visible AVANT le mot de passe.\n const texts = regionInputs(region, 'input[type=\"text\"], input:not([type])').filter(\n (t) => t.compareDocumentPosition(password) & Node.DOCUMENT_POSITION_FOLLOWING,\n );\n return texts[texts.length - 1] ?? null;\n}\n\nfunction matchScope(form: HTMLFormElement | null, scope: ParentNode): LoginFormMatch | null {\n // Aucun `new-password` toléré, même caché : c'est une inscription ou un\n // changement de mot de passe.\n if (scope.querySelector('input[autocomplete=\"new-password\"]')) return null;\n const passwords = visibleInputs(scope, PASSWORD_SELECTOR);\n if (passwords.length > 1) return null;\n\n if (passwords.length === 1) {\n const password = passwords[0] as HTMLInputElement;\n // Région bornée dans laquelle chercher les satellites (cf. `Region`),\n // amorcée sur le champ RETENU par ce candidat.\n const region = regionFor(form, password, password);\n if (!region) return null;\n // L'identifiant d'abord : le choix du bouton en dépend (une commande de\n // champ se reconnaît à ce qu'elle ne partage PAS son conteneur avec lui).\n const identifier = identifierFor(region, password);\n const submit = findSubmit(region, password, identifier);\n const s = signals(form, scope, submit);\n const positive = password.autocomplete === \"current-password\" || s.positive;\n if (!positive || s.negative) return null;\n return { kind: \"password\", form, identifier, password, submit };\n }\n\n const identifiers = visibleInputs(scope, IDENTIFIER_SELECTOR);\n if (identifiers.length !== 1) return null;\n const identifier = identifiers[0] as HTMLInputElement;\n const region = regionFor(form, identifier, null);\n if (!region) return null;\n const submit = findSubmit(region, identifier, identifier);\n const s = signals(form, scope, submit);\n const positive = identifier.autocomplete === \"username\" || s.positive;\n if (!positive || s.negative) return null;\n return { kind: \"identifier\", form, identifier, password: null, submit };\n}\n\n/** Premier formulaire de connexion accepté dans `root` (les `<form>` d'abord).\n *\n * Si le document ne contient AUCUN `<form>`, on regarde directement le\n * document entier, sans condition — c'est le cas courant chez nos clients\n * React/Lovable/Supabase, qui construisent typiquement leur login (souvent\n * un premier écran identifiant-seul, sans mot de passe encore à l'écran)\n * sans `<form>` du tout ; il n'y a alors rien à « regarder au-delà de ».\n *\n * Si des `<form>` existent mais qu'aucun ne matche (ex. une simple barre de\n * recherche dans l'en-tête), on essaie AUSSI le document entier — sinon ce\n * `<form>` sans rapport suffirait à rendre invisible un login construit à\n * côté sans `<form>` — mais SEULEMENT s'il existe un mot de passe visible\n * qui n'appartient à AUCUN `<form>` : sinon on ré-évaluerait, hors de tout\n * contexte, un mot de passe déjà examiné (et à raison rejeté) via son\n * `<form>` — ex. un champ `new-password` d'inscription. */\nexport function findLoginForm(root: ParentNode = document): LoginFormMatch | null {\n const forms = Array.from(root.querySelectorAll(\"form\"));\n for (const form of forms) {\n const m = matchScope(form, form);\n if (m) return m;\n }\n if (forms.length === 0) return matchScope(null, root);\n const loosePassword = visibleInputs(root, PASSWORD_SELECTOR).find(\n (input) => !input.closest(\"form\"),\n );\n if (!loosePassword) return null;\n return matchScope(null, root);\n}\n\nfunction setNativeValue(input: HTMLInputElement, value: string) {\n const proto = Object.getPrototypeOf(input) as object;\n const setter =\n Object.getOwnPropertyDescriptor(proto, \"value\")?.set ??\n Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, \"value\")?.set;\n if (setter) setter.call(input, value);\n else input.value = value;\n input.dispatchEvent(new Event(\"input\", { bubbles: true }));\n input.dispatchEvent(new Event(\"change\", { bubbles: true }));\n}\n\n/** Ce candidat offre-t-il un moyen de soumettre ? Question posée AVANT\n * d'écrire quoi que ce soit : écrire des identifiants qu'on ne pourra pas\n * soumettre n'obtient rien et les dépose dans le champ d'un client (une barre\n * de recherche adoptée à tort, par exemple), où l'utilisateur les voit\n * apparaître. */\nfunction canSubmit(match: LoginFormMatch): boolean {\n return !!match.form || !!match.submit;\n}\n\nfunction submitMatch(match: LoginFormMatch): boolean {\n const form = match.form;\n // On soumet ce qu'on vient d'écrire, point final : la validation HTML native\n // (`type=email`, `pattern`, `required`…) de la page cible ne doit jamais\n // avaler silencieusement `requestSubmit()`/le clic — un identifiant de test\n // n'a aucune raison de respecter le format attendu par l'app hôte.\n const previousNoValidate = form?.noValidate;\n if (form) form.noValidate = true;\n try {\n if (form && typeof form.requestSubmit === \"function\") {\n form.requestSubmit();\n return true;\n }\n if (match.submit) {\n match.submit.click();\n return true;\n }\n if (form) {\n form.submit();\n return true;\n }\n return false;\n } finally {\n if (form) form.noValidate = previousNoValidate ?? false;\n }\n}\n\n/** Ce que NOUS avons écrit dans cette page, champ par champ. Sert à distinguer\n * « le champ est occupé » de « le champ est occupé PAR NOUS » : seul le second\n * cas est réécrasable. Remis à zéro quand le formulaire disparaît — la page a\n * changé, ces valeurs ne sont plus à l'écran. */\nexport type OwnValues = { identifier: string | null; password: string | null };\n\nconst NOTHING_OWNED: OwnValues = { identifier: null, password: null };\n\n/** Un champ est remplissable s'il est VIDE — on n'écrase jamais une valeur que\n * la page ou l'utilisateur y a mise — ou s'il porte EXACTEMENT ce que nous y\n * avons écrit. Bretelle de la ceinture qu'est le vocabulaire négatif : si un\n * écran de ré-authentification passait malgré tout, la vraie adresse du\n * client, pré-remplie, resterait intacte.\n *\n * L'exception « c'est notre valeur » existe pour le réessai : après un refus,\n * les champs portent les identifiants périmés que nous venons de servir, et\n * sans elle une relance ne pouvait plus rien écrire (`already-filled`) — le\n * testeur restait bloqué alors même que l'admin avait corrigé le compte. */\nfunction fillable(input: HTMLInputElement | null, own: string | null): boolean {\n if (!input || input.disabled || input.readOnly) return false;\n return input.value === \"\" || (own !== null && input.value === own);\n}\n\n/** Ce qui serait effectivement écrit dans le DOM à cet instant : un champ\n * désactivé ou en lecture seule ne l'est pas tant qu'il le reste — l'app\n * active souvent le mot de passe à l'étape 2 (`disabled` fait partie des\n * attributs observés) ; il sera reconsidéré dès que l'attribut change. Seule\n * source de vérité pour « qu'est-ce qui a été écrit », partagée par\n * `fillLoginForm` (qui écrit) et `installLoginFill` (qui enregistre) — pour\n * que les deux restent d'accord même quand la soumission échoue ensuite. */\nfunction writable(match: LoginFormMatch, filled: FilledState, own: OwnValues): FilledState {\n return {\n identifier: fillable(match.identifier, own.identifier) && !filled.identifier,\n password: fillable(match.password, own.password) && !filled.password,\n };\n}\n\n/** L'identifiant à l'écran contredit-il celui qu'on s'apprête à soumettre ?\n * Cas réel : un login en deux écrans dont l'étape 2 passe l'e-mail en\n * `readOnly`. Après un refus, l'admin corrige le compte et le testeur\n * relance : le champ porte encore l'ANCIENNE adresse, intouchable, et nous\n * allions soumettre l'ancien identifiant avec le nouveau mot de passe — un\n * échec garanti, qui consomme au passage une tentative du limiteur de l'app.\n * Mieux vaut le dire que le tenter : `identifier-mismatch` rend la main. */\nfunction identifierConflicts(\n match: LoginFormMatch,\n creds: LoginCredentials,\n toWrite: FilledState,\n): boolean {\n const input = match.identifier;\n if (!input || toWrite.identifier) return false;\n return input.value !== \"\" && input.value !== creds.login;\n}\n\n/** Remplit ce qui est présent, pas encore servi et remplissable, puis soumet.\n * Pure vis-à-vis du handle : `filled` dit ce qui a déjà été servi sur cette\n * page. L'ordre compte : on résout le moyen de soumission AVANT d'écrire, et\n * on n'écrit RIEN s'il n'y en a pas. Une écriture n'a donc lieu que sur le\n * chemin qui réussit — `{ step }` implique « écrit », une erreur implique\n * « rien écrit ». */\nexport function fillLoginForm(\n match: LoginFormMatch,\n creds: LoginCredentials,\n filled: FilledState,\n own: OwnValues = NOTHING_OWNED,\n): FillOutcome {\n const toWrite = writable(match, filled, own);\n if (!toWrite.identifier && !toWrite.password) return { error: \"nothing-to-fill\" };\n if (identifierConflicts(match, creds, toWrite)) return { error: \"identifier-mismatch\" };\n if (!canSubmit(match)) return { error: \"no-submit\" };\n if (toWrite.identifier) setNativeValue(match.identifier as HTMLInputElement, creds.login);\n if (toWrite.password) setNativeValue(match.password as HTMLInputElement, creds.password);\n if (!submitMatch(match)) return { error: \"no-submit\" };\n return {\n step:\n toWrite.identifier && toWrite.password\n ? \"both\"\n : toWrite.password\n ? \"password\"\n : \"identifier\",\n };\n}\n\nexport function installLoginFill(sinks: LoginFillSinks): LoginFillHandle {\n if (typeof window === \"undefined\" || typeof MutationObserver === \"undefined\") {\n return { watch() {}, fill() {}, cancel() {}, teardown() {} };\n }\n let creds: LoginCredentials | null = null;\n let filled: FilledState = { identifier: false, password: false };\n let own: OwnValues = { identifier: null, password: null };\n let announced = false;\n let observer: MutationObserver | null = null;\n let timer: ReturnType<typeof setTimeout> | null = null;\n let settleTimer: ReturnType<typeof setTimeout> | null = null;\n\n const clearSettle = () => {\n if (settleTimer) clearTimeout(settleTimer);\n settleTimer = null;\n };\n\n const stopObserving = () => {\n observer?.disconnect();\n observer = null;\n clearSettle();\n if (timer) clearTimeout(timer);\n timer = null;\n };\n\n const pass = () => {\n const match = findLoginForm(document);\n if (!match) {\n // Le formulaire a DISPARU : la page a changé d'écran. On réarme\n // l'annonce, de sorte qu'une réapparition (l'app a rejeté la connexion\n // et re-rend son formulaire) soit signalée au shell. Exiger la\n // disparition évite de ré-annoncer 100 ms après la soumission le\n // formulaire encore présent dans le DOM.\n announced = false;\n // La page a changé d'écran : ce que nous avions écrit n'est plus à\n // l'écran, donc plus rien ne nous appartient. Sans cette remise à zéro,\n // un champ d'un AUTRE formulaire portant par coïncidence la même valeur\n // deviendrait écrasable.\n own = { identifier: null, password: null };\n clearSettle();\n return;\n }\n if (!creds) {\n if (!announced) {\n announced = true;\n sinks.onDetected();\n }\n } else {\n // `fillLoginForm` n'écrit QUE sur le chemin qui réussit : on n'note\n // donc comme servi que ce qu'elle a réellement écrit, calculé avec la\n // même fonction qu'elle. Sur erreur, rien n'a été écrit et rien n'est\n // noté — l'anti-boucle est porté par l'arrêt de l'observation, qui\n // rend l'erreur définitive.\n const toWrite = writable(match, filled, own);\n const outcome = fillLoginForm(match, creds, filled, own);\n if (!(\"error\" in outcome)) {\n if (toWrite.identifier) {\n filled = { ...filled, identifier: true };\n own = { ...own, identifier: creds.login };\n }\n if (toWrite.password) {\n filled = { ...filled, password: true };\n own = { ...own, password: creds.password };\n }\n }\n if (\"error\" in outcome) {\n // `nothing-to-fill` reste un no-op silencieux tant que QUELQUE CHOSE a\n // déjà été servi sur cette page : c'est le cas légitime pour lequel\n // l'avalement existe (une passe de plus sur un formulaire déjà\n // rempli). Mais si RIEN n'a jamais été servi ici, c'est que la page\n // présentait les deux champs déjà peuplés — `fillable()` exige un\n // champ vide. L'avaler laissait le shell bloqué en « filling » pour\n // toujours : pas de `filled`, pas d'`error`, donc ni sortie du\n // spinner, ni bouton de réessai, ni ligne d'audit. On le remonte.\n const fatal =\n outcome.error !== \"nothing-to-fill\"\n ? outcome.error\n : !filled.identifier && !filled.password\n ? \"already-filled\"\n : null;\n if (fatal) {\n // Erreur définitive (ex. aucun mécanisme de soumission trouvé) :\n // aucune mutation ultérieure ne pourra la corriger, on arrête.\n sinks.onError(fatal);\n creds = null;\n stopObserving();\n }\n } else {\n sinks.onFilled(outcome.step);\n if (filled.password) {\n // Tout est servi : on OUBLIE les identifiants — plus rien ne peut\n // être resoumis d'ici — mais on CONTINUE d'observer. Si l'app\n // rejette la connexion et re-rend son formulaire SANS recharger,\n // la disparition puis la réapparition du formulaire produiront un\n // second `detected` ; sans ça le shell concluait « Connecté » au\n // bout de son minuteur et journalisait un succès pour un échec.\n creds = null;\n // …mais beaucoup d'apps ne démontent RIEN en cas de refus : elles\n // insèrent un message d'erreur sous un formulaire qui reste monté.\n // Aucune disparition, donc aucune réapparition à observer. D'où ce\n // contrôle unique à l'échéance : encore un formulaire de connexion\n // à l'écran = la soumission a échoué, et on le dit.\n clearSettle();\n settleTimer = setTimeout(() => {\n settleTimer = null;\n if (!findLoginForm(document)) return; // parti : connexion réussie.\n announced = true;\n sinks.onDetected();\n }, LOGIN_SETTLE_MS);\n }\n }\n }\n // Pas de replanification inconditionnelle ici : on ne fait tourner AUCUN\n // minuteur dans l'app d'un client tant que le MutationObserver n'a rien\n // signalé. La détection après coup dépend entièrement de son callback\n // (via `schedule`, débouncé DEBOUNCE_MS) — cf. rapport de tâche.\n };\n\n const schedule = () => {\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => {\n timer = null;\n pass();\n }, DEBOUNCE_MS);\n };\n\n const startObserving = () => {\n if (observer) return;\n observer = new MutationObserver(schedule);\n observer.observe(document.body, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: OBSERVED_ATTRIBUTES,\n });\n };\n\n return {\n watch() {\n if (!observer) {\n announced = false;\n startObserving();\n }\n pass();\n },\n fill(next) {\n creds = next;\n startObserving();\n pass();\n },\n cancel() {\n creds = null;\n filled = { identifier: false, password: false };\n announced = false;\n stopObserving();\n },\n teardown() {\n creds = null;\n stopObserving();\n },\n };\n}\n","// Wrapper app-side du recorder rrweb. rrweb est importé dynamiquement (zéro poids\n// tant qu'on n'enregistre pas, comme modern-screenshot). Le recorder émet les\n// events par batchs via onBatch ; un safety cap arrête tout seul au bout de 10 min.\n//\n// Le recorder n'instrumente PLUS lui-même la console et le réseau : cette capture\n// vit dans `diagnostics-capture.ts` et lui est passée en `diagnostics`. Pendant\n// l'enregistrement il s'y branche en sink pour que les erreurs restent\n// entrelacées chronologiquement dans la session (`addCustomEvent`). Sans handle\n// fourni — diagnostic non armé — il en crée un éphémère le temps de\n// l'enregistrement, ce qui reproduit exactement le comportement historique.\n\nimport { type DiagnosticsHandle, installDiagnostics } from \"./diagnostics-capture\";\n\nconst SAFETY_CAP_MS = 10 * 60 * 1000;\nconst BATCH_INTERVAL_MS = 1000;\n\nexport type RrwebRecorderHandle = {\n /** Stoppe l'enregistrement, flush le dernier batch, et renvoie la durée. */\n stop: () => number;\n};\n\nexport type StartRecorderOptions = {\n /** Appelé ~1×/s avec les events accumulés depuis le dernier batch. */\n onBatch: (events: unknown[]) => void;\n /** Appelé quand le safety cap se déclenche (le shell doit finaliser). */\n onCap: () => void;\n /** Capture réseau (ring buffer fetch/XHR) — défaut activé. */\n captureNetwork?: boolean;\n /** Capture de diagnostic déjà installée (régime armé). Absente → le recorder\n * en crée une éphémère, détruite à l'arrêt. */\n diagnostics?: DiagnosticsHandle | null;\n};\n\n/**\n * Options de masquage passées à `record()`. Masquage AGRESSIF par défaut, opt-out\n * côté client (l'intégrateur révèle explicitement ce qui est safe) — jamais opt-in.\n * Contrat pour le dev de l'app embarquée :\n * - `.leesto-mask` / `[data-leesto-block]` → élément ENTIER jamais capturé (placeholder).\n * - `.leesto-mask-text` / `[data-private]` → structure gardée, TEXTE masqué.\n * - tous les inputs sont masqués par défaut (`maskAllInputs`).\n * S'applique au full snapshot (« scan » initial) ET aux mutations incrémentales.\n */\nexport const RECORD_MASK_OPTIONS = {\n maskAllInputs: true,\n maskInputOptions: { password: true, email: true, tel: true, text: true },\n blockClass: \"leesto-mask\",\n blockSelector: \"[data-leesto-block]\",\n maskTextClass: \"leesto-mask-text\",\n maskTextSelector: \"[data-private]\",\n} as const;\n\n/** Démarre un enregistrement rrweb du document courant. Masquage agressif par\n * défaut (RGPD/PCI/HIPAA) via `RECORD_MASK_OPTIONS` + rédaction PII des custom\n * events (console/réseau) avant egress. */\nexport async function startRrwebRecorder(\n options: StartRecorderOptions,\n): Promise<RrwebRecorderHandle> {\n const { record, addCustomEvent } = await import(\"rrweb\");\n const startedAt = Date.now();\n let buffer: unknown[] = [];\n let stopped = false;\n let durationMs = 0;\n\n const flush = () => {\n if (buffer.length === 0) return;\n const batch = buffer;\n buffer = [];\n options.onBatch(batch);\n };\n\n const stopFn = record({\n emit(event) {\n buffer.push(event);\n },\n ...RECORD_MASK_OPTIONS,\n });\n\n // Capture diagnostique (console / erreurs / réseau) → custom events rrweb.\n // Branchée seulement si l'enregistrement a bien démarré.\n const provided = options.diagnostics ?? null;\n const capture = stopFn\n ? (provided ?? installDiagnostics({ captureNetwork: options.captureNetwork !== false }))\n : null;\n // Un handle qu'on a créé ici nous appartient : c'est le seul qu'on détruira.\n const ownsCapture = capture !== null && provided === null;\n\n capture?.setSink((tag, payload) => {\n // rrweb garde un flag `recording` GLOBAL au module : un autre stop\n // (double record() via HMR/StrictMode, stop avant l'init différée de\n // rrweb) le fait retomber et addCustomEvent jette alors — y compris\n // pendant notre flushRings. Capture best-effort : on perd l'event,\n // jamais l'app hôte.\n try {\n addCustomEvent(tag, payload);\n } catch {}\n });\n\n const interval = setInterval(flush, BATCH_INTERVAL_MS);\n // Box mutable pour que doStop() puisse annuler le cap même si la const\n // capTimer n'est pas encore assignée au moment de la définition de doStop.\n const cap = { timer: null as ReturnType<typeof setTimeout> | null };\n\n // Idempotent : un second appel (ex. le shell qui stoppe après onCap) renvoie la\n // durée figée sans re-stopper.\n const doStop = (): number => {\n if (stopped) return durationMs;\n stopped = true;\n clearInterval(interval);\n clearTimeout(cap.timer ?? undefined);\n capture?.flushRings();\n // Débrancher avant de détruire : un handle permanent survit à la session et\n // continue d'alimenter ses rings pour les signalements suivants.\n capture?.setSink(null);\n if (ownsCapture) capture?.teardown();\n stopFn?.();\n flush();\n durationMs = Date.now() - startedAt;\n return durationMs;\n };\n\n // Le cap stoppe lui-même le recorder (pas de fuite si le consommateur tarde),\n // puis notifie le shell pour qu'il finalise.\n cap.timer = setTimeout(() => {\n doStop();\n options.onCap();\n }, SAFETY_CAP_MS);\n\n return { stop: doStop };\n}\n","// Allowlist des origines de shell autorisées à piloter le connecteur.\n//\n// Pourquoi ce module existe : le connecteur tourne dans l'app d'un TIERS et se\n// laissait piloter par n'importe quel parent, l'origine du shell étant devinée\n// depuis `document.referrer` (avec repli sur `\"*\"`). Un site capable d'embarquer\n// l'app cible pouvait donc lui demander une capture d'écran, démarrer un\n// enregistrement rrweb et lire le diagnostic — le referrer étant lui-même\n// contrôlable par l'attaquant (`referrerpolicy=\"no-referrer\"` forçait le repli).\n//\n// Le seul rempart restant était le `frame-ancestors` de l'app cible, hors de\n// notre contrôle et impossible à poser sur les builders no-code que le produit\n// vise (Lovable/Replit/Framer). D'où une allowlist embarquée dans le bundle.\n\n/** Origines de la surface Livery (apps/lab) en déploiement Leesto. */\nexport const DEFAULT_SHELL_ORIGINS: readonly string[] = [\n \"https://lab.leesto.app\",\n \"https://lab-dev.leesto.app\",\n];\n\n/** Origines de dev du shell (cf. NEXT_PUBLIC_LIVE_APP_URL dans .env.example).\n * Ajoutées UNIQUEMENT quand la page embarquée est elle-même en loopback. */\nexport const DEV_SHELL_ORIGINS: readonly string[] = [\n \"http://localhost:3505\",\n \"http://127.0.0.1:3505\",\n];\n\n/** Vrai pour une origine servie depuis la machine locale. */\nexport function isLoopbackOrigin(origin: string): boolean {\n try {\n const host = new URL(origin).hostname;\n return (\n host === \"localhost\" ||\n host.endsWith(\".localhost\") ||\n host === \"127.0.0.1\" ||\n host === \"[::1]\"\n );\n } catch {\n return false;\n }\n}\n\n/** Réduit une entrée déclarée à son origine ; `null` si inexploitable. */\nfunction toOrigin(raw: string): string | null {\n const trimmed = raw.trim();\n if (!trimmed) return null;\n try {\n const { origin } = new URL(trimmed);\n return origin === \"null\" ? null : origin;\n } catch {\n return null;\n }\n}\n\n/** Liste des origines de shell auxquelles ce connecteur accepte de parler.\n * Une déclaration explicite (data-shell-origin / option) REMPLACE les défauts :\n * un shell auto-hébergé n'a pas à faire confiance aux origines Leesto. */\nexport function resolveShellOrigins(input: {\n explicit?: readonly string[];\n pageOrigin: string;\n}): string[] {\n const explicit = (input.explicit ?? []).map(toOrigin).filter((o): o is string => o !== null);\n if (explicit.length > 0) return [...new Set(explicit)];\n\n const defaults = [...DEFAULT_SHELL_ORIGINS];\n if (isLoopbackOrigin(input.pageOrigin)) defaults.push(...DEV_SHELL_ORIGINS);\n return [...new Set(defaults)];\n}\n\n/** Comparaison d'origine STRICTE (schéma + hôte + port), pour couper court aux\n * sosies de domaine. `\"*\"`, `\"\"` et `\"null\"` ne sont jamais des origines\n * valides : une cible non résolue doit faire échouer la connexion, pas diffuser. */\nexport function isAllowedShellOrigin(origin: string, allowlist: readonly string[]): boolean {\n if (!origin || origin === \"*\" || origin === \"null\") return false;\n return allowlist.includes(origin);\n}\n","// App-side bridge client. A third-party host app calls connectLeestoApp() once so\n// the Livery shell can talk to it. Vanilla (no React) — works in any app, and is\n// a no-op when the page isn't embedded in a shell (window.parent === window).\n\nimport {\n type AppBuild,\n type AppToShell,\n isLeestoMessage,\n LEESTO_BRIDGE_VERSION,\n LOGIN_CAPABILITY,\n type ShellToApp,\n} from \"@leesto/shared/bridge\";\nimport {\n createDiagnosticRunId,\n diagnosticRunIdFromSearch,\n hasDiagnosticsParam,\n} from \"@leesto/shared/diagnostics\";\nimport brand from \"@leesto/ui/theme/brand\";\nimport { type DiagnosticsHandle, installDiagnostics } from \"./diagnostics-capture\";\nimport { installLoginFill, type LoginFillHandle } from \"./login-fill\";\nimport { type RrwebRecorderHandle, startRrwebRecorder } from \"./rrweb-recorder\";\nimport { isAllowedShellOrigin, resolveShellOrigins } from \"./shell-origins\";\n\nexport type ConnectLeestoAppOptions = {\n /** Color of the highlight outline drawn on `leesto:highlight`. */\n highlightColor?: string;\n /** Returns a screenshot of the app as a data URL. When omitted, the app\n * screenshots its own `document.body` with modern-screenshot (lazy-loaded on\n * first capture) — so the Livery shell gets a prompt-free, chrome-free shot\n * with zero extra code. Provide this to override (e.g. capture a subtree). */\n capture?: () => Promise<string>;\n /** Build descriptor of this app (version + environment) to stamp on reports.\n * Best-effort: falls back to window.__LEESTO_APP_BUILD__ then <meta> tags. */\n build?: AppBuild;\n /** Capture des requêtes réseau récentes (métadonnées, ring buffer) comme\n * diagnostic — joint à la session enregistrée. Défaut : activé. */\n captureNetwork?: boolean;\n /** Origines supplémentaires auxquelles transmettre l'identifiant de run.\n * L'origine de l'app est toujours autorisée ; vide = aucun cross-origin. */\n runIdOrigins?: string[];\n /** Origines de shell autorisées à piloter ce connecteur. Déclarer cette\n * option REMPLACE les origines Leesto par défaut (shell auto-hébergé). */\n shellOrigins?: string[];\n};\n\n/** Vrai si l'utilisateur a activé Global Privacy Control (navigator.globalPrivacyControl).\n * Signal d'opt-out légalement opposable (CCPA & co.) : quand il est présent, la\n * capture de session ne doit pas avoir lieu. Best-effort / SSR-safe. */\nexport function gpcHonored(): boolean {\n return (\n typeof navigator !== \"undefined\" &&\n (navigator as Navigator & { globalPrivacyControl?: boolean }).globalPrivacyControl === true\n );\n}\n\n/** Resolve the app build descriptor, best-effort. Order: explicit option →\n * window.__LEESTO_APP_BUILD__ → <meta name=\"app-version|app-environment\">.\n * Empty/whitespace values are dropped; returns undefined when nothing usable. */\nexport function resolveBuild(explicit: AppBuild | undefined): AppBuild | undefined {\n const clean = (v: unknown): string | undefined => {\n const s = typeof v === \"string\" ? v.trim() : \"\";\n return s.length > 0 ? s : undefined;\n };\n const metaContent = (name: string): string | undefined => {\n if (typeof document === \"undefined\") return undefined;\n return clean(document.querySelector(`meta[name=\"${name}\"]`)?.getAttribute(\"content\"));\n };\n const globalBuild =\n typeof window !== \"undefined\"\n ? (window as unknown as { __LEESTO_APP_BUILD__?: AppBuild }).__LEESTO_APP_BUILD__\n : undefined;\n\n const version =\n clean(explicit?.version) ?? clean(globalBuild?.version) ?? metaContent(\"app-version\");\n const environment =\n clean(explicit?.environment) ??\n clean(globalBuild?.environment) ??\n metaContent(\"app-environment\");\n\n if (!version && !environment) return undefined;\n return { ...(version ? { version } : {}), ...(environment ? { environment } : {}) };\n}\n\n/** Resolve the app's declared favicon while still inside its own document. */\nexport function resolveFavicon(): string | undefined {\n if (typeof document === \"undefined\") return undefined;\n const link = document.querySelector<HTMLLinkElement>(\n 'link[rel~=\"icon\"], link[rel=\"shortcut icon\"], link[rel=\"apple-touch-icon\"]',\n );\n if (!link?.href) return undefined;\n try {\n return new URL(link.href, location.href).href;\n } catch {\n return undefined;\n }\n}\n\n/** Effective page background: dark apps usually paint it on <html> (or a root\n * container), leaving <body> transparent. Forcing white here would bleed\n * through wherever body doesn't paint — the \"white band\" around the capture.\n * Resolve body → html → white so the shot matches what the user sees. */\nfunction pageBackgroundColor(): string {\n const isOpaque = (c: string) =>\n !!c && c !== \"transparent\" && !/^rgba\\(\\s*0,\\s*0,\\s*0,\\s*0\\s*\\)$/.test(c);\n const bodyBg = getComputedStyle(document.body).backgroundColor;\n if (isOpaque(bodyBg)) return bodyBg;\n const htmlBg = getComputedStyle(document.documentElement).backgroundColor;\n if (isOpaque(htmlBg)) return htmlBg;\n return \"#ffffff\";\n}\n\n/** Default self-screenshot: render the app's own DOM to a PNG data URL — the\n * VISIBLE VIEWPORT at the current scroll, i.e. what the tester actually sees.\n *\n * We capture <html> cropped to the viewport box and translate it up by the\n * scroll offset (`style.transform`). modern-screenshot clones the DOM into an\n * SVG foreignObject where `position: fixed`/`sticky` no longer resolves against\n * the viewport — and our root translate would drag those elements off-screen —\n * so we re-pin them with an opposite translate for the duration of the capture.\n * (Capturing `document.body` full-height instead left fixed sidebars/headers\n * collapsed and the main content visually offset.)\n *\n * The app runs in its own document, so this captures ONLY the app — no Livery\n * chrome (that lives in the parent shell). modern-screenshot is dynamically\n * imported so it's only pulled into the bundle on first capture. */\nasync function defaultCapture(selector?: string): Promise<string> {\n const { domToPng } = await import(\"modern-screenshot\");\n if (selector) {\n const element = document.querySelector(selector);\n if (!element) throw new Error(\"element_not_found\");\n return domToPng(element, { quality: 0.92 });\n }\n const root = document.documentElement;\n const sx = window.scrollX;\n const sy = window.scrollY;\n\n // Re-pin fixed/sticky elements so they don't ride the root translate.\n const pinned: Array<[HTMLElement, string]> = [];\n for (const el of root.querySelectorAll<HTMLElement>(\"*\")) {\n const pos = getComputedStyle(el).position;\n if (pos === \"fixed\" || pos === \"sticky\") {\n const prev = el.style.transform;\n pinned.push([el, prev]);\n el.style.transform = `translate(${sx}px, ${sy}px)${prev ? ` ${prev}` : \"\"}`;\n }\n }\n\n try {\n return await domToPng(root, {\n quality: 0.92,\n backgroundColor: pageBackgroundColor(),\n width: root.clientWidth,\n height: root.clientHeight,\n style: { transform: `translate(${-sx}px, ${-sy}px)`, transformOrigin: \"top left\" },\n });\n } finally {\n for (const [el, prev] of pinned) el.style.transform = prev;\n }\n}\n\n/** Best-effort, reasonably-stable CSS selector for an element. */\nfunction buildSelector(el: Element): string {\n if (el.id) return `#${CSS.escape(el.id)}`;\n const parts: string[] = [];\n let node: Element | null = el;\n while (node && node.nodeType === 1 && node !== document.body && parts.length < 4) {\n if (node.id) {\n parts.unshift(`#${CSS.escape(node.id)}`);\n break;\n }\n let part = node.tagName.toLowerCase();\n const cls =\n typeof node.className === \"string\"\n ? node.className.trim().split(/\\s+/).filter(Boolean)[0]\n : null;\n if (cls) part += `.${CSS.escape(cls)}`;\n const parent: Element | null = node.parentElement;\n if (parent) {\n const sameTag = Array.from(parent.children).filter((c) => c.tagName === node?.tagName);\n if (sameTag.length > 1) part += `:nth-of-type(${sameTag.indexOf(node) + 1})`;\n }\n parts.unshift(part);\n node = parent;\n }\n return parts.join(\" > \");\n}\n\n/** Short label: tag + a trimmed text snippet. */\nfunction labelOf(el: Element): string {\n const tag = el.tagName.toLowerCase();\n const text = (el.textContent ?? \"\").replace(/\\s+/g, \" \").trim().slice(0, 40);\n return text ? `${tag} · ${text}` : tag;\n}\n\nexport function connectLeestoApp(options: ConnectLeestoAppOptions = {}): () => void {\n if (typeof window === \"undefined\" || window.parent === window) return () => {};\n const parent = window.parent;\n const color = options.highlightColor ?? brand.light.primary;\n\n // Allowlist des origines de shell (cf. shell-origins.ts). Le connecteur tourne\n // dans l'app d'un TIERS : il ne se laisse piloter que par un shell connu, et\n // n'adresse ses messages qu'à une origine explicite — jamais de wildcard.\n const allowedOrigins = resolveShellOrigins({\n explicit: options.shellOrigins,\n pageOrigin: location.origin,\n });\n\n // Le referrer n'est qu'un INDICE pour épingler l'origine tout de suite, jamais\n // une preuve : après une navigation interne il vaut l'origine de l'app\n // elle-même, donc une valeur hors allowlist ne prouve rien. C'est le premier\n // message entrant valide qui tranche — `event.origin` est posé par le\n // navigateur, lui n'est pas falsifiable.\n let shellOrigin: string | null = null;\n try {\n const fromReferrer = document.referrer ? new URL(document.referrer).origin : \"\";\n if (isAllowedShellOrigin(fromReferrer, allowedOrigins)) shellOrigin = fromReferrer;\n } catch {\n /* pas d'indice exploitable */\n }\n\n // Avant l'épinglage, le message est adressé à CHAQUE origine allowlistée :\n // postMessage ne délivre qu'à celle qui correspond réellement au parent, donc\n // rien ne fuit vers les autres.\n const post = (msg: AppToShell) => {\n if (shellOrigin) {\n parent.postMessage(msg, shellOrigin);\n return;\n }\n for (const origin of allowedOrigins) parent.postMessage(msg, origin);\n };\n\n let highlighted: HTMLElement | null = null;\n let prevOutline = \"\";\n const clearHighlight = () => {\n if (highlighted) highlighted.style.outline = prevOutline;\n highlighted = null;\n };\n\n // --- Element picker -------------------------------------------------------\n let stopPick: (() => void) | null = null;\n const startPick = () => {\n stopPick?.();\n clearHighlight();\n // A separate frame never modifies the host's styles. Removing an older\n // frame also makes duplicate connector installations visually harmless.\n document.querySelector(\"[data-leesto-picker-outline]\")?.remove();\n const outline = document.createElement(\"div\");\n outline.dataset.leestoPickerOutline = \"\";\n outline.setAttribute(\"aria-hidden\", \"true\");\n Object.assign(outline.style, {\n position: \"fixed\",\n pointerEvents: \"none\",\n zIndex: \"2147483647\",\n boxSizing: \"border-box\",\n border: `2px solid ${color}`,\n borderRadius: \"4px\",\n display: \"none\",\n });\n document.documentElement.append(outline);\n let hovered: Element | null = null;\n let selected: Element | null = null;\n const previousCursor = document.body.style.cursor;\n const update = () => {\n const target = selected ?? hovered;\n if (!target) return;\n const r = target.getBoundingClientRect();\n if (selected) {\n post({\n type: \"leesto:element-picked\",\n selector: buildSelector(target),\n label: labelOf(target),\n rect: { x: r.x, y: r.y, width: r.width, height: r.height },\n });\n } else {\n Object.assign(outline.style, {\n display: \"block\",\n left: `${r.x}px`,\n top: `${r.y}px`,\n width: `${r.width}px`,\n height: `${r.height}px`,\n });\n }\n };\n const onMove = (e: MouseEvent) => {\n hovered = e.target instanceof Element ? e.target : null;\n update();\n };\n const stopHover = () => {\n outline.remove();\n document.removeEventListener(\"mousemove\", onMove, true);\n document.removeEventListener(\"click\", onClick, true);\n document.body.style.cursor = previousCursor;\n };\n const onClick = (e: MouseEvent) => {\n e.preventDefault();\n e.stopPropagation();\n selected = e.target instanceof Element ? e.target : null;\n stopHover();\n update();\n };\n const onKey = (e: KeyboardEvent) => {\n if (e.key === \"Escape\") {\n stopPick?.();\n post({ type: \"leesto:pick-cancelled\" });\n }\n };\n stopPick = () => {\n stopHover();\n document.removeEventListener(\"keydown\", onKey, true);\n document.removeEventListener(\"scroll\", update, true);\n window.removeEventListener(\"resize\", update);\n stopPick = null;\n };\n document.body.style.cursor = \"crosshair\";\n document.addEventListener(\"mousemove\", onMove, true);\n document.addEventListener(\"click\", onClick, true);\n document.addEventListener(\"keydown\", onKey, true);\n // Keep the selected rectangle in sync while the shell's comment popover\n // is open, including scrolling inside a nested app container.\n document.addEventListener(\"scroll\", update, true);\n window.addEventListener(\"resize\", update);\n };\n\n // --- Diagnostic technique (console + réseau) ------------------------------\n // Armé par l'URL et lu SYNCHRONEMENT ici. Un armement par message bridge\n // laisserait passer tout le démarrage de l'app — échec de mount, appels API\n // initiaux en erreur, écran blanc — soit la classe de bug la plus coûteuse en\n // test. Sans le marqueur, RIEN n'est patché : le SDK reste inerte hors d'une\n // session Lab consentie. Double garde GPC (le shell n'arme déjà pas).\n const diagnosticsArmed = hasDiagnosticsParam(location.search) && !gpcHonored();\n const diagnosticRunId = diagnosticsArmed\n ? (diagnosticRunIdFromSearch(location.search) ?? createDiagnosticRunId())\n : undefined;\n const diagnostics: DiagnosticsHandle | null = diagnosticsArmed\n ? installDiagnostics({\n captureNetwork: options.captureNetwork !== false,\n runId: diagnosticRunId,\n runIdOrigins: options.runIdOrigins,\n })\n : null;\n\n let recorder: RrwebRecorderHandle | null = null;\n let recorderStarting = false;\n let stopRequested = false;\n const stopRecording = () => {\n if (recorder) {\n const durationMs = recorder.stop();\n recorder = null;\n post({ type: \"leesto:rec-stopped\", durationMs });\n } else if (recorderStarting) {\n // rec-stop arrivé pendant l'init async : finaliser dès que le handle résout.\n stopRequested = true;\n }\n };\n\n // Annonce l'état complet du connecteur (URL courante, favicon, build, GPC…).\n // Appelée à la connexion ET sur chaque `leesto:ping` : le shell (Lab) rend\n // l'iframe en SSR, donc cette page peut avoir chargé et annoncé son `ready`\n // AVANT que le shell hydrate et écoute — l'annonce partait alors dans le vide\n // et le shell restait « connexion en cours » jusqu'à un refresh. Le ping,\n // émis par le shell dès qu'il écoute, fait rejouer l'annonce.\n // --- Auto-login (ECH-309) --------------------------------------------------\n // Inerte tant que le shell n'envoie pas `leesto:login-watch` : aucun observer,\n // aucune lecture du DOM. Les identifiants ne vivent qu'en mémoire du handle et\n // sont oubliés dès que tout est servi, sur `login-cancel` ou au déchargement.\n const loginFill: LoginFillHandle = installLoginFill({\n onDetected: () => post({ type: \"leesto:login-form-detected\" }),\n onFilled: (step) => post({ type: \"leesto:login-filled\", step }),\n onError: (reason) => post({ type: \"leesto:login-error\", reason }),\n });\n const forgetLogin = () => loginFill.cancel();\n window.addEventListener(\"pagehide\", forgetLogin);\n\n const build = resolveBuild(options.build);\n const navigation = window.navigation;\n let navigatingBack = false;\n let disconnected = false;\n const canGoBack = () => !navigatingBack && navigation?.canGoBack === true;\n let lastCanGoBack = canGoBack();\n let lastReported = location.href;\n const announceReady = () => {\n lastReported = location.href;\n lastCanGoBack = canGoBack();\n const favicon = resolveFavicon();\n post({\n type: \"leesto:ready\",\n url: location.href,\n // Annonce la version du protocole : un connecteur épinglé sur npm se fige\n // pendant que le shell évolue, et un désaccord échoue en SILENCE sans ça.\n bridgeVersion: LEESTO_BRIDGE_VERSION,\n // Capacités du connecteur : le shell n'offre l'auto-login que si l'app\n // embarquée sait le servir (connecteur épinglé plus ancien = absent).\n capabilities: [LOGIN_CAPABILITY, ...(navigation ? [\"navigation\"] : [])],\n canGoBack: lastCanGoBack,\n ...(favicon ? { favicon } : {}),\n ...(build ? { build } : {}),\n ...(diagnosticRunId ? { diagnosticRunId } : {}),\n // `gpc` prévient le shell dès la connexion que l'enregistrement est bloqué\n // (conformité Global Privacy Control), pour qu'il n'offre pas la capture.\n ...(gpcHonored() ? { gpc: true } : {}),\n });\n };\n\n const onMessage = (event: MessageEvent) => {\n if (event.source !== parent) return;\n if (!isAllowedShellOrigin(event.origin, allowedOrigins)) return;\n if (!isLeestoMessage(event.data)) return;\n // Première origine valide → épinglée : les messages suivants ne partent\n // plus qu'à elle.\n if (!shellOrigin) shellOrigin = event.origin;\n const msg = event.data as ShellToApp;\n if (msg.type === \"leesto:ping\") {\n post({ type: \"leesto:pong\" });\n announceReady();\n } else if (msg.type === \"leesto:navigate-back\") {\n if (!navigation || !canGoBack()) return;\n navigatingBack = true;\n reportLocation();\n // Navigation is scoped to this frame and same-origin entries, unlike\n // history.back(), which can traverse the parent’s joint session history.\n void Promise.resolve(navigation.back().finished)\n .catch(() => {})\n .finally(() => {\n navigatingBack = false;\n if (!disconnected) reportLocation();\n });\n } else if (msg.type === \"leesto:highlight\") {\n clearHighlight();\n if (msg.selector) {\n // Le sélecteur vient du pont : `querySelector` lève une SyntaxError s'il\n // est malformé, et elle s'échapperait de ce listener en erreur NON\n // capturée dans l'app du tiers. Un surlignage raté n'est pas une panne.\n let el: HTMLElement | null = null;\n try {\n el = document.querySelector<HTMLElement>(msg.selector);\n } catch {\n el = null;\n }\n if (el) {\n highlighted = el;\n prevOutline = el.style.outline;\n el.style.outline = `2px solid ${color}`;\n el.style.outlineOffset = \"2px\";\n el.scrollIntoView({ block: \"center\", behavior: \"smooth\" });\n }\n }\n } else if (msg.type === \"leesto:pick-start\") {\n startPick();\n } else if (msg.type === \"leesto:pick-stop\") {\n stopPick?.();\n } else if (msg.type === \"leesto:capture-request\") {\n // Targeted captures always use the selected node; a custom full-page\n // capture override cannot guarantee the requested region.\n const capture = msg.selector\n ? defaultCapture(msg.selector)\n : (options.capture ?? defaultCapture)();\n capture\n .then((dataUrl) =>\n post({\n type: \"leesto:screenshot\",\n dataUrl,\n ...(msg.selector ? { selector: msg.selector } : {}),\n }),\n )\n .catch((err) =>\n post({\n type: \"leesto:capture-failed\",\n reason: err instanceof Error ? err.message : \"capture_error\",\n }),\n );\n } else if (msg.type === \"leesto:rec-start\") {\n if (recorder || recorderStarting) return; // déjà en cours / en démarrage\n // Gate conformité : si Global Privacy Control est actif, la capture de\n // session est légalement interdite — on la refuse AVANT tout démarrage,\n // sans jamais instancier le recorder (aucune donnée n'est captée). ECH-290.\n if (gpcHonored()) {\n post({ type: \"leesto:rec-blocked\", reason: \"gpc\" });\n return;\n }\n recorderStarting = true;\n stopRequested = false;\n startRrwebRecorder({\n onBatch: (events) => post({ type: \"leesto:rec-batch\", events }),\n onCap: () => stopRecording(),\n captureNetwork: options.captureNetwork,\n // Armé → le recorder se branche sur la capture permanente (les erreurs\n // restent entrelacées dans le replay) sans la détruire à l'arrêt.\n // Sinon il en crée une éphémère, comme avant.\n diagnostics,\n })\n .then((h) => {\n recorderStarting = false;\n recorder = h;\n if (stopRequested) stopRecording(); // stop demandé pendant l'init\n })\n .catch((err) => {\n recorderStarting = false;\n post({\n type: \"leesto:rec-error\",\n reason: err instanceof Error ? err.message : \"rec_error\",\n });\n });\n } else if (msg.type === \"leesto:rec-stop\") {\n stopRecording();\n } else if (msg.type === \"leesto:diagnostics-request\") {\n // Toujours répondre, même sans capture armée : sinon le shell attend son\n // timeout pour rien à chaque signalement.\n post({\n type: \"leesto:diagnostics\",\n snapshot: diagnostics?.snapshot() ?? { errors: [], logs: [], network: [] },\n });\n } else if (msg.type === \"leesto:login-watch\") {\n loginFill.watch();\n } else if (msg.type === \"leesto:login-fill\") {\n loginFill.fill({ login: msg.login, password: msg.password });\n } else if (msg.type === \"leesto:login-cancel\") {\n loginFill.cancel();\n }\n };\n\n window.addEventListener(\"message\", onMessage);\n\n // Announce readiness + current location, and report SPA navigations.\n announceReady();\n // Les navigations d'un routeur client (React Router, TanStack, Next App Router)\n // passent par history.pushState/replaceState, qui NE déclenchent PAS `popstate`.\n // Sans ce patch le shell restait sur l'URL d'entrée : le testeur signalait un\n // bug depuis /facturation et le ticket portait /dashboard. On patche donc ces\n // deux méthodes — uniquement dans une page EMBARQUÉE (connectLeestoApp a déjà\n // rendu la main autrement), et on les restaure à la déconnexion.\n const reportLocation = () => {\n if (location.href === lastReported && canGoBack() === lastCanGoBack) return;\n lastReported = location.href;\n lastCanGoBack = canGoBack();\n post({ type: \"leesto:location\", url: location.href, canGoBack: lastCanGoBack });\n };\n\n const nativePushState = history.pushState;\n const nativeReplaceState = history.replaceState;\n const patchedPushState: History[\"pushState\"] = (...args) => {\n nativePushState.apply(history, args);\n reportLocation();\n };\n const patchedReplaceState: History[\"replaceState\"] = (...args) => {\n nativeReplaceState.apply(history, args);\n reportLocation();\n };\n history.pushState = patchedPushState;\n history.replaceState = patchedReplaceState;\n\n navigation?.addEventListener(\"currententrychange\", reportLocation);\n window.addEventListener(\"popstate\", reportLocation);\n window.addEventListener(\"hashchange\", reportLocation);\n\n return () => {\n disconnected = true;\n navigation?.removeEventListener(\"currententrychange\", reportLocation);\n stopRecording();\n diagnostics?.teardown();\n clearHighlight();\n stopPick?.();\n loginFill.teardown();\n window.removeEventListener(\"pagehide\", forgetLogin);\n window.removeEventListener(\"message\", onMessage);\n window.removeEventListener(\"popstate\", reportLocation);\n window.removeEventListener(\"hashchange\", reportLocation);\n // Ne restaure que SI personne n'a patché par-dessus nous entre-temps :\n // écraser le patch d'une autre lib serait pire que de laisser le nôtre.\n if (history.pushState === patchedPushState) history.pushState = nativePushState;\n if (history.replaceState === patchedReplaceState) history.replaceState = nativeReplaceState;\n };\n}\n","// Standalone auto-init entry for the Livery connector, built as a CDN ES module:\n//\n// <script type=\"module\" src=\"https://…/leesto-connect.js\" data-leesto-connect></script>\n//\n// Calls connectLeestoApp() on load so the embedding Livery shell can screenshot the\n// page and record rrweb. No-op when the page isn't framed by Livery (connectLeestoApp\n// bails when window.parent === window). rrweb + modern-screenshot stay in lazy\n// chunks — fetched only on the first record/capture, so a normal page load of the\n// host app downloads just this tiny entry.\n//\n// Self-hosted shell (replaces the built-in Leesto origins):\n// <script type=\"module\" src=\"…/leesto-connect.js\" data-leesto-connect\n// data-shell-origin=\"https://qa.acme.test\"></script>\n//\n// Manual control (skip auto-init with data-leesto-manual):\n// <script type=\"module\" src=\"…/leesto-connect.js\" data-leesto-connect data-leesto-manual></script>\n// <script>window.LeestoConnect.connect({ highlightColor: \"#6B8E23\" })</script>\n\nimport { type ConnectLeestoAppOptions, connectLeestoApp } from \"./app-client\";\n\ndeclare global {\n interface Window {\n LeestoConnect?: {\n /** Manually wire the connector (returns a disconnect fn). */\n connect: (options?: ConnectLeestoAppOptions) => () => void;\n };\n }\n}\n\n/** The connector's own <script> tag. In classic scripts this is\n * document.currentScript; in module scripts that's null, so fall back to the\n * element tagged with data-leesto-connect. */\nfunction ownScript(): HTMLScriptElement | null {\n if (typeof document === \"undefined\") return null;\n return (\n (document.currentScript as HTMLScriptElement | null) ??\n document.querySelector<HTMLScriptElement>(\"script[data-leesto-connect]\")\n );\n}\n\nfunction optionsFromScript(el: HTMLScriptElement | null): ConnectLeestoAppOptions {\n const options: ConnectLeestoAppOptions = {};\n const highlightColor = el?.dataset.highlightColor;\n if (highlightColor) options.highlightColor = highlightColor;\n // Shell auto-hébergé : `data-shell-origin=\"https://a, https://b\"` remplace les\n // origines Leesto par défaut. Sans cet attribut, seules celles-ci sont admises.\n const shellOrigins = (el?.dataset.shellOrigin ?? \"\")\n .split(\",\")\n .map((o) => o.trim())\n .filter(Boolean);\n if (shellOrigins.length > 0) options.shellOrigins = shellOrigins;\n return options;\n}\n\nif (typeof window !== \"undefined\") {\n window.LeestoConnect = { connect: (options) => connectLeestoApp(options) };\n const el = ownScript();\n // Auto-connect unless the host opted into manual init (data-leesto-manual).\n if (!el || el.dataset.leestoManual === undefined) {\n connectLeestoApp(optionsFromScript(el));\n }\n}\n"],"mappings":"AAkBA,IAAa,KAAmB,SAiBnB,KAAkB;AA+H/B,SAAgB,GAAgB,GAAsC;AACpE,SACE,OAAO,KAAS,YAChB,MAAS,QACT,OAAQ,EAA4B,QAAS,YAC5C,EAA0B,KAAK,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