@spotpatch/runtime 1.12.0 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/{chunk-BXRMVHNT.js → chunk-ASRUAKA5.js} +1 -1
  2. package/dist/chunk-ASRUAKA5.js.map +1 -0
  3. package/dist/chunk-KIDHJQRG.js +14 -0
  4. package/dist/chunk-KIDHJQRG.js.map +1 -0
  5. package/dist/{chunk-7ES63LA7.js → chunk-P6X75LO5.js} +11 -1
  6. package/dist/chunk-P6X75LO5.js.map +1 -0
  7. package/dist/chunk-P7W3F4UA.js +115 -0
  8. package/dist/chunk-P7W3F4UA.js.map +1 -0
  9. package/dist/contextual-ask-panel.cjs +1637 -0
  10. package/dist/contextual-ask-panel.cjs.map +1 -0
  11. package/dist/contextual-ask-panel.d.cts +163 -0
  12. package/dist/contextual-ask-panel.d.ts +163 -0
  13. package/dist/contextual-ask-panel.js +1593 -0
  14. package/dist/contextual-ask-panel.js.map +1 -0
  15. package/dist/data-flow-panel.cjs +9 -0
  16. package/dist/data-flow-panel.cjs.map +1 -1
  17. package/dist/data-flow-panel.js +1 -1
  18. package/dist/external-handoff-panel.cjs +29 -9
  19. package/dist/external-handoff-panel.cjs.map +1 -1
  20. package/dist/external-handoff-panel.d.cts +3 -3
  21. package/dist/external-handoff-panel.d.ts +3 -3
  22. package/dist/external-handoff-panel.js +22 -11
  23. package/dist/external-handoff-panel.js.map +1 -1
  24. package/dist/index.cjs +1285 -279
  25. package/dist/index.cjs.map +1 -1
  26. package/dist/index.js +1250 -356
  27. package/dist/index.js.map +1 -1
  28. package/dist/motion-extension-contract-B3m26CML.d.cts +72 -0
  29. package/dist/motion-extension-contract-B3m26CML.d.ts +72 -0
  30. package/dist/motion.cjs +1251 -0
  31. package/dist/motion.cjs.map +1 -0
  32. package/dist/motion.d.cts +11 -0
  33. package/dist/motion.d.ts +11 -0
  34. package/dist/motion.js +1092 -0
  35. package/dist/motion.js.map +1 -0
  36. package/package.json +31 -3
  37. package/dist/chunk-7ES63LA7.js.map +0 -1
  38. package/dist/chunk-BXRMVHNT.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/data-flow-panel-entry.ts","../src/ui/ui-constants.ts","../src/ui/dom.ts","../src/ui/data-flow-panel.ts","../src/ui/data-flow-panel-contract.ts","../src/data-flow/data-flow-runtime.ts","../src/data-flow/report-merger.ts"],"sourcesContent":["export { createDataFlowPanel } from \"./ui/data-flow-panel.js\";\nexport {\n getDataFlowExtension,\n registerDataFlowExtension,\n type DataFlowExtension,\n type DataFlowPanel,\n type DataFlowPanelFactory,\n type DataFlowPanelSnapshot,\n type DataFlowPanelStatus,\n type DataFlowViewState,\n} from \"./ui/data-flow-panel-contract.js\";\n\nimport {\n getDataFlowRuntime,\n mergeComponentDataFlowReport,\n mergePageDataFlowReport,\n} from \"./data-flow-entry.js\";\nimport { createDataFlowPanel } from \"./ui/data-flow-panel.js\";\nimport { registerDataFlowExtension } from \"./ui/data-flow-panel-contract.js\";\n\nexport function installDataFlowPanelExtension(): void {\n registerDataFlowExtension(\n Object.freeze({\n createPanel: createDataFlowPanel,\n getComponentRegistration(component: object) {\n return getDataFlowRuntime()?.getComponentRegistration(component);\n },\n observations(routeKey: string) {\n const runtime = getDataFlowRuntime();\n runtime?.updateRoute(routeKey);\n return runtime?.observations() ?? Object.freeze([]);\n },\n mergeComponentReport: mergeComponentDataFlowReport,\n mergePageReport: mergePageDataFlowReport,\n }),\n );\n}\n","export const UI_MARKER_ATTRIBUTE = \"data-spotpatch-ui\" as const;\n\nexport const UI_Z_INDEX = Object.freeze({\n highlight: 2_147_483_646,\n controls: 2_147_483_647,\n});\n","import { UI_MARKER_ATTRIBUTE } from \"./ui-constants.js\";\n\nexport function createMarkedElement<K extends keyof HTMLElementTagNameMap>(\n document: Document,\n tagName: K,\n): HTMLElementTagNameMap[K] {\n const element = document.createElement(tagName);\n element.setAttribute(UI_MARKER_ATTRIBUTE, \"\");\n return element;\n}\n\nexport function createButton(\n document: Document,\n label: string,\n className = \"\",\n): HTMLButtonElement {\n const button = createMarkedElement(document, \"button\");\n button.type = \"button\";\n button.className = className;\n button.textContent = label;\n return button;\n}\n","import type { DataDependency, SpotPatchLocale } from \"@spotpatch/shared\";\n\nimport { createButton, createMarkedElement } from \"./dom.js\";\nimport type {\n DataFlowPanel,\n DataFlowPanelSnapshot,\n DataFlowViewState,\n} from \"./data-flow-panel-contract.js\";\n\ninterface Labels {\n readonly bindings: string;\n readonly changes: string;\n readonly componentEmpty: string;\n readonly componentTab: string;\n readonly componentTitle: string;\n readonly consumed: string;\n readonly declared: string;\n readonly diagnostics: string;\n readonly disabled: string;\n readonly error: string;\n readonly evidence: string;\n readonly loading: string;\n readonly logicalObserved: string;\n readonly noParameters: string;\n readonly observed: string;\n readonly pageEmpty: string;\n readonly pageTab: string;\n readonly pageTitle: string;\n readonly parameters: string;\n readonly refresh: string;\n readonly unknown: string;\n}\n\nconst LABELS = Object.freeze({\n \"zh-CN\": Object.freeze({\n bindings: \"数据去向\",\n changes: \"修改说明\",\n componentEmpty: \"当前组件没有找到可证明的接口。未找到不等于没有请求。\",\n componentTab: \"数据链路\",\n componentTitle: \"组件数据链路\",\n consumed: \"读取字段\",\n declared: \"代码声明,尚未在本次页面会话中观测\",\n diagnostics: \"诊断\",\n disabled: \"数据链路能力未启用,请在插件配置中设置 dataFlow: {}。\",\n error: \"数据链路报告加载失败\",\n evidence: \"证据\",\n loading: \"正在分析源码并合并运行时证据…\",\n logicalObserved: \"本次会话已进入 tRPC 调用链\",\n noParameters: \"未提取到可证明的参数键\",\n observed: \"本次会话已实际请求\",\n pageEmpty: \"当前已选页面范围内没有静态接口或运行时网络记录。\",\n pageTab: \"页面接口\",\n pageTitle: \"页面接口\",\n parameters: \"请求参数\",\n refresh: \"刷新证据\",\n unknown: \"未知\",\n }),\n \"en-US\": Object.freeze({\n bindings: \"Data destinations\",\n changes: \"Changes\",\n componentEmpty:\n \"No proven interface was found for this component. This does not prove that no request exists.\",\n componentTab: \"Data flow\",\n componentTitle: \"Component data flow\",\n consumed: \"Consumed fields\",\n declared: \"Declared in code, not observed in this page session\",\n diagnostics: \"Diagnostics\",\n disabled: \"Data flow is disabled. Set dataFlow: {} in the plugin options.\",\n error: \"Failed to load the data-flow report\",\n evidence: \"Evidence\",\n loading: \"Analyzing source and merging runtime evidence…\",\n logicalObserved: \"Dispatched through the tRPC link in this session\",\n noParameters: \"No proven parameter keys were extracted\",\n observed: \"Actually requested in this session\",\n pageEmpty:\n \"No static interface or runtime traffic is available for the selected page scope.\",\n pageTab: \"Page APIs\",\n pageTitle: \"Page interfaces\",\n parameters: \"Request parameters\",\n refresh: \"Refresh evidence\",\n unknown: \"Unknown\",\n }),\n}) satisfies Readonly<Record<SpotPatchLocale, Labels>>;\n\nfunction badge(document: Document, text: string, tone: string): HTMLElement {\n const element = createMarkedElement(document, \"span\");\n element.className = \"spotpatch-data-flow-badge\";\n element.dataset.tone = tone;\n element.textContent = text;\n return element;\n}\n\nfunction detailRow(document: Document, label: string, value: string): HTMLElement {\n const row = createMarkedElement(document, \"div\");\n row.className = \"spotpatch-data-flow-detail\";\n const key = createMarkedElement(document, \"span\");\n key.textContent = label;\n const content = createMarkedElement(document, \"code\");\n content.textContent = value;\n row.append(key, content);\n return row;\n}\n\nfunction renderDependency(\n document: Document,\n dependency: DataDependency,\n labels: Labels,\n): HTMLElement {\n const card = createMarkedElement(document, \"article\");\n card.className = \"spotpatch-data-flow-card\";\n const header = createMarkedElement(document, \"div\");\n header.className = \"spotpatch-data-flow-card-head\";\n const endpoint = createMarkedElement(document, \"div\");\n endpoint.className = \"spotpatch-data-flow-endpoint\";\n const method = createMarkedElement(document, \"strong\");\n method.textContent = dependency.method ?? labels.unknown;\n const path = createMarkedElement(document, \"code\");\n path.textContent =\n dependency.url === undefined\n ? (dependency.operation ?? labels.unknown)\n : `${dependency.url.origin ?? \"\"}${dependency.url.pathname}`;\n endpoint.append(method, path);\n const states = createMarkedElement(document, \"div\");\n states.className = \"spotpatch-data-flow-badges\";\n states.append(\n badge(\n document,\n dependency.execution === \"observed\"\n ? dependency.kind === \"rpc\"\n ? labels.logicalObserved\n : labels.observed\n : labels.declared,\n dependency.execution === \"observed\" ? \"success\" : \"neutral\",\n ),\n badge(\n document,\n dependency.proof,\n dependency.proof === \"proven\" ? \"proof\" : \"warning\",\n ),\n badge(document, dependency.association, \"neutral\"),\n );\n header.append(endpoint, states);\n\n const parameters =\n dependency.parameters.length === 0\n ? labels.noParameters\n : dependency.parameters\n .map(\n (parameter) =>\n `${parameter.position}.${parameter.path}${parameter.type === undefined ? \"\" : `: ${parameter.type}`}${parameter.sensitive ? \" [sensitive]\" : \"\"}${parameter.condition === undefined ? \"\" : ` [when ${parameter.condition}]`}`,\n )\n .join(\"\\n\");\n const consumed =\n dependency.response.consumedFields.length === 0\n ? labels.unknown\n : dependency.response.consumedFields.join(\", \");\n const bindings =\n dependency.suppliedBindings.length === 0\n ? labels.unknown\n : dependency.suppliedBindings.join(\", \");\n const body = createMarkedElement(document, \"div\");\n body.className = \"spotpatch-data-flow-card-body\";\n const observationIds = new Set(dependency.observationIds);\n const staticEvidenceCount = dependency.evidenceIds.filter(\n (id) => !observationIds.has(id),\n ).length;\n body.append(\n detailRow(document, labels.parameters, parameters),\n detailRow(document, labels.consumed, consumed),\n detailRow(document, labels.bindings, bindings),\n detailRow(\n document,\n labels.evidence,\n `${String(staticEvidenceCount)} static · ${String(dependency.observationIds.length)} runtime`,\n ),\n );\n card.append(header, body);\n return card;\n}\n\nfunction createReportRoot(\n document: Document,\n titleText: string,\n): Readonly<{ root: HTMLElement; status: HTMLElement; list: HTMLElement }> {\n const root = createMarkedElement(document, \"section\");\n root.className = \"spotpatch-data-flow-panel\";\n const title = createMarkedElement(document, \"h3\");\n title.textContent = titleText;\n const status = createMarkedElement(document, \"p\");\n status.className = \"spotpatch-data-flow-status\";\n const list = createMarkedElement(document, \"div\");\n list.className = \"spotpatch-data-flow-list\";\n root.append(title, status, list);\n return Object.freeze({ root, status, list });\n}\n\nexport function createDataFlowPanel(\n document: Document,\n enabled: boolean,\n locale: () => SpotPatchLocale,\n changesRoot: HTMLElement,\n diagnosticsRoot: HTMLElement,\n onViewChange: () => void,\n): DataFlowPanel {\n let labels = LABELS[locale()];\n const component = createReportRoot(document, labels.componentTitle);\n const page = createReportRoot(document, labels.pageTitle);\n const refreshButton = createButton(document, labels.refresh);\n const styles = document.createElement(\"style\");\n styles.textContent = DATA_FLOW_PANEL_STYLES;\n refreshButton.classList.add(\"spotpatch-data-flow-refresh\");\n component.root.prepend(refreshButton);\n const root = createMarkedElement(document, \"div\");\n const tabs = createMarkedElement(document, \"nav\");\n tabs.className = \"spotpatch-view-tabs\";\n tabs.setAttribute(\"aria-label\", \"SpotPatch views\");\n tabs.setAttribute(\"role\", \"tablist\");\n const views = new Map([\n [\"changes\", changesRoot],\n [\"component-data\", component.root],\n [\"page-data\", page.root],\n [\"diagnostics\", diagnosticsRoot],\n ]);\n const tabButtons = new Map<string, HTMLButtonElement>();\n let activeView = \"changes\";\n for (const id of views.keys()) {\n const button = createButton(document, \"\");\n button.dataset.viewId = id;\n button.id = `spotpatch-view-${id}-tab`;\n button.setAttribute(\"role\", \"tab\");\n button.setAttribute(\"aria-selected\", String(id === activeView));\n const view = views.get(id);\n view?.setAttribute(\"aria-labelledby\", button.id);\n view?.setAttribute(\"role\", \"tabpanel\");\n if (!enabled && (id === \"component-data\" || id === \"page-data\")) {\n button.hidden = true;\n }\n tabButtons.set(id, button);\n tabs.append(button);\n }\n root.append(tabs, ...views.values());\n\n function selectView(viewId: string): void {\n if (!views.has(viewId)) return;\n activeView = viewId;\n for (const [id, view] of views) {\n view.hidden = id !== viewId;\n const button = tabButtons.get(id);\n button?.setAttribute(\"aria-selected\", String(id === viewId));\n if (button !== undefined) button.tabIndex = id === viewId ? 0 : -1;\n }\n onViewChange();\n }\n\n function handleTabClick(event: Event): void {\n if (!(event.target instanceof HTMLButtonElement)) return;\n const viewId = event.target.dataset.viewId;\n if (viewId !== undefined) selectView(viewId);\n }\n\n tabs.addEventListener(\"click\", handleTabClick);\n selectView(activeView);\n\n function renderSnapshot(\n target: ReturnType<typeof createReportRoot>,\n snapshot: DataFlowPanelSnapshot,\n empty: string,\n ): void {\n target.list.replaceChildren();\n target.status.dataset.state = snapshot.status;\n if (!enabled || snapshot.status === \"disabled\") {\n target.status.textContent = labels.disabled;\n return;\n }\n if (snapshot.status === \"loading\") {\n target.status.textContent = labels.loading;\n return;\n }\n if (snapshot.status === \"error\") {\n target.status.textContent = snapshot.message ?? labels.error;\n return;\n }\n const report = snapshot.report;\n const diagnosticCodes =\n report === undefined\n ? \"\"\n : [...new Set(report.diagnostics.map(({ code }) => code))].join(\", \");\n const diagnosticSuffix =\n diagnosticCodes.length === 0\n ? \"\"\n : ` · ${labels.diagnostics}: ${diagnosticCodes}`;\n if (report === undefined || report.dependencies.length === 0) {\n target.status.textContent = `${empty}${diagnosticSuffix}`;\n return;\n }\n target.status.textContent = `${String(report.dependencies.length)} · ${report.completeness.complete ? \"complete\" : \"partial\"}${diagnosticSuffix}`;\n target.list.append(\n ...report.dependencies.map((dependency) =>\n renderDependency(document, dependency, labels),\n ),\n );\n }\n\n return Object.freeze({\n root,\n refreshButton,\n styles,\n dispose(): void {\n tabs.removeEventListener(\"click\", handleTabClick);\n },\n render(state: DataFlowViewState): void {\n labels = LABELS[locale()];\n const tabLabels = [\n labels.changes,\n labels.componentTab,\n labels.pageTab,\n labels.diagnostics,\n ];\n [...tabButtons.values()].forEach((button, index) => {\n button.textContent = tabLabels[index] ?? \"\";\n });\n refreshButton.textContent = `${labels.refresh} · ${String(state.observationCount)}`;\n refreshButton.disabled = !enabled || state.component.status === \"loading\";\n renderSnapshot(component, state.component, labels.componentEmpty);\n renderSnapshot(page, state.page, labels.pageEmpty);\n },\n resetView(): void {\n selectView(\"changes\");\n },\n });\n}\n\nconst DATA_FLOW_PANEL_STYLES = `\n .spotpatch-view-tabs { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 4px; margin-bottom: 12px; padding: 3px; border: 1px solid rgb(255 255 255 / 7%); border-radius: 9px; background: rgb(3 7 18 / 42%); }\n .spotpatch-view-tabs button { min-width: 0; border: 0; border-radius: 7px; padding: 7px 5px; color: var(--spotpatch-text-muted); background: transparent; cursor: pointer; font-size: 10.5px; }\n .spotpatch-view-tabs button[aria-selected=\"true\"] { color: #f8fafc; background: rgb(139 124 247 / 18%); }\n .spotpatch-data-flow-panel { position: relative; }\n .spotpatch-data-flow-panel > h3 { margin: 0 0 3px; color: #f3f4f6; font-size: 13px; }\n .spotpatch-data-flow-refresh { position: absolute; top: -4px; right: 0; border: 1px solid rgb(139 124 247 / 30%); border-radius: 7px; padding: 4px 8px; color: #c4baff; background: rgb(139 124 247 / 8%); cursor: pointer; font-size: 10.5px; }\n .spotpatch-data-flow-refresh:disabled { cursor: not-allowed; opacity: .45; }\n .spotpatch-data-flow-status { margin: 0 0 10px; color: var(--spotpatch-text-muted); font-size: 10.5px; line-height: 1.5; }\n .spotpatch-data-flow-list { display: grid; gap: 8px; }\n .spotpatch-data-flow-card { overflow: hidden; border: 1px solid rgb(255 255 255 / 8%); border-radius: 9px; background: rgb(255 255 255 / 2.5%); }\n .spotpatch-data-flow-card-head { display: grid; gap: 7px; padding: 10px; border-bottom: 1px solid rgb(255 255 255 / 7%); }\n .spotpatch-data-flow-endpoint { display: flex; min-width: 0; align-items: center; gap: 8px; }\n .spotpatch-data-flow-endpoint strong { color: #79d9e7; font: 700 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace; }\n .spotpatch-data-flow-endpoint code { min-width: 0; overflow: hidden; color: #f8fafc; font: 11px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace; text-overflow: ellipsis; white-space: nowrap; }\n .spotpatch-data-flow-badges { display: flex; flex-wrap: wrap; gap: 4px; }\n .spotpatch-data-flow-badge { border-radius: 999px; padding: 2px 6px; color: #9ca3af; background: rgb(255 255 255 / 5%); font-size: 9px; }\n .spotpatch-data-flow-badge[data-tone=\"success\"] { color: #6ee7b7; background: rgb(16 185 129 / 10%); }\n .spotpatch-data-flow-badge[data-tone=\"proof\"] { color: #c4b5fd; background: rgb(139 92 246 / 11%); }\n .spotpatch-data-flow-badge[data-tone=\"warning\"] { color: #fcd34d; background: rgb(245 158 11 / 10%); }\n .spotpatch-data-flow-card-body { display: grid; gap: 7px; padding: 10px; }\n .spotpatch-data-flow-detail { display: grid; grid-template-columns: 82px minmax(0, 1fr); gap: 8px; align-items: start; }\n .spotpatch-data-flow-detail > span { color: var(--spotpatch-text-muted); font-size: 10px; }\n .spotpatch-data-flow-detail > code { overflow-wrap: anywhere; color: #cbd5e1; font: 10px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; white-space: pre-wrap; }\n`;\n","import type {\n ComponentDataFlowReport,\n NetworkObservation,\n PageDataFlowReport,\n SpotPatchLocale,\n} from \"@spotpatch/shared\";\n\nimport type { DataFlowComponentRegistration } from \"../data-flow/data-flow-runtime.js\";\n\nexport type DataFlowPanelStatus = \"disabled\" | \"idle\" | \"loading\" | \"ready\" | \"error\";\n\nexport interface DataFlowPanelSnapshot {\n readonly status: DataFlowPanelStatus;\n readonly report?: ComponentDataFlowReport | PageDataFlowReport;\n readonly message?: string;\n}\n\nexport interface DataFlowViewState {\n readonly component: DataFlowPanelSnapshot;\n readonly page: DataFlowPanelSnapshot;\n readonly observationCount: number;\n}\n\nexport interface DataFlowPanel {\n readonly root: HTMLElement;\n readonly refreshButton: HTMLButtonElement;\n readonly styles: HTMLStyleElement;\n readonly dispose: () => void;\n readonly render: (state: DataFlowViewState) => void;\n readonly resetView: () => void;\n}\n\nexport type DataFlowPanelFactory = (\n document: Document,\n enabled: boolean,\n locale: () => SpotPatchLocale,\n changesRoot: HTMLElement,\n diagnosticsRoot: HTMLElement,\n onViewChange: () => void,\n) => DataFlowPanel;\n\nexport interface DataFlowExtension {\n readonly createPanel: DataFlowPanelFactory;\n readonly getComponentRegistration: (\n component: object,\n ) => DataFlowComponentRegistration | undefined;\n readonly observations: (routeKey: string) => readonly NetworkObservation[];\n readonly mergeComponentReport: (\n report: ComponentDataFlowReport,\n observations: readonly NetworkObservation[],\n ) => ComponentDataFlowReport;\n readonly mergePageReport: (\n report: PageDataFlowReport,\n observations: readonly NetworkObservation[],\n ) => PageDataFlowReport;\n}\n\nconst DATA_FLOW_EXTENSION_KEY = Symbol.for(\"spotpatch.data-flow.extension.v1\");\ntype ExtensionStore = Partial<Record<symbol, DataFlowExtension>>;\n\nexport function registerDataFlowExtension(\n extension: DataFlowExtension,\n target: ExtensionStore = globalThis,\n): void {\n target[DATA_FLOW_EXTENSION_KEY] = extension;\n}\n\nexport function getDataFlowExtension(\n target: ExtensionStore = globalThis,\n): DataFlowExtension | undefined {\n return target[DATA_FLOW_EXTENSION_KEY];\n}\n","import {\n DATA_FLOW_SCHEMA_VERSION,\n DATA_FLOW_URL_QUERY_KEY_LIMIT,\n SPOTPATCH_API_BASE,\n type NetworkObservation,\n type RuntimeDataFlowConfig,\n type RuntimeDataFlowLimits,\n type SanitizedObservedUrl,\n} from \"@spotpatch/shared/data-flow-runtime\";\n\nexport interface DataFlowComponentRegistration {\n readonly componentSourceId: string;\n readonly sourceVersion: string;\n}\n\nexport interface DataFlowInvocationToken {\n readonly invocationId: string;\n readonly componentSourceId: string;\n readonly triggerCallsiteId: string;\n readonly sourceVersion: string;\n}\n\nexport interface DataFlowRequestFrame {\n readonly requestCallsiteId: string;\n readonly sourceVersion: string;\n readonly invocationToken?: DataFlowInvocationToken;\n}\n\nexport interface DataFlowTriggerMetadata {\n readonly componentSourceId: string;\n readonly triggerCallsiteId: string;\n readonly sourceVersion: string;\n}\n\nexport interface DataFlowRequestMetadata {\n readonly requestCallsiteId: string;\n readonly sourceVersion: string;\n}\n\nexport interface DataFlowRuntime {\n readonly beginInvocation: (\n metadata: DataFlowTriggerMetadata,\n ) => DataFlowInvocationToken;\n readonly bindInvocation: <Arguments extends readonly unknown[], Result>(\n token: DataFlowInvocationToken | undefined,\n callback: (...args: Arguments) => Result,\n ) => (...args: Arguments) => Result;\n readonly bindTrigger: <Callback>(\n metadata: DataFlowTriggerMetadata,\n callback: Callback,\n ) => Callback;\n readonly captureInvocation: () => DataFlowInvocationToken | undefined;\n readonly clear: () => void;\n readonly createTrpcLink: () => DataFlowTrpcLink;\n readonly dispose: () => void;\n readonly getComponentRegistration: (\n component: object,\n ) => DataFlowComponentRegistration | undefined;\n readonly getCurrentRequestFrame: () => DataFlowRequestFrame | undefined;\n readonly observations: () => readonly NetworkObservation[];\n readonly updateRoute: (routeKey: string) => void;\n readonly registerComponent: (\n component: object,\n componentSourceId: string,\n sourceVersion: string,\n ) => void;\n readonly withInvocation: <Result>(\n token: DataFlowInvocationToken | undefined,\n callback: () => Result,\n ) => Result;\n readonly withRequestFrame: <Result>(\n token: DataFlowInvocationToken | undefined,\n metadata: DataFlowRequestMetadata,\n callback: () => Result,\n ) => Result;\n}\n\nexport interface DataFlowObservationPolicy {\n readonly shouldObserveFetch?: (\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n baseUrl: string,\n ) => boolean;\n readonly shouldObserveXhr?: (url: string, baseUrl: string) => boolean;\n}\n\nexport interface DataFlowTrpcOperation {\n readonly path: unknown;\n readonly type: unknown;\n}\n\nexport interface DataFlowTrpcLinkOptions<\n Operation extends DataFlowTrpcOperation,\n Result,\n> {\n readonly next: (operation: Operation) => Result;\n readonly op: Operation;\n}\n\nexport type DataFlowTrpcLink = (\n runtime: unknown,\n) => <Operation extends DataFlowTrpcOperation, Result>(\n options: DataFlowTrpcLinkOptions<Operation, Result>,\n) => Result;\n\ninterface DataFlowGlobal {\n readonly fetch?: typeof globalThis.fetch;\n readonly location?: Location;\n readonly performance?: Performance;\n readonly XMLHttpRequest?: typeof globalThis.XMLHttpRequest;\n}\n\ninterface MutableDataFlowGlobal extends DataFlowGlobal {\n fetch?: typeof globalThis.fetch;\n}\n\ninterface XhrMetadata {\n readonly method: string;\n readonly url: string;\n}\n\ninterface RingEntry {\n readonly bytes: number;\n readonly observation: NetworkObservation;\n readonly recordedAt: number;\n}\n\nconst RUNTIME_KEY: unique symbol = Symbol.for(\n \"spotpatch.data-flow.runtime.v1\",\n) as never;\nconst REACT_MEMO_TYPE = Symbol.for(\"react.memo\");\nconst REACT_FORWARD_REF_TYPE = Symbol.for(\"react.forward_ref\");\n\ntype DataFlowRuntimeStore = Partial<Record<symbol, DataFlowRuntime>>;\ntype GlobalWithDataFlow = MutableDataFlowGlobal & DataFlowRuntimeStore;\n\nfunction positiveNow(target: DataFlowGlobal): number {\n return target.performance?.now() ?? Date.now();\n}\n\nfunction createOpaqueSequence(prefix: string): () => string {\n let sequence = 0;\n const randomPrefix = (() => {\n try {\n const bytes = new Uint8Array(8);\n globalThis.crypto.getRandomValues(bytes);\n return Array.from(bytes, (value) => value.toString(36).padStart(2, \"0\")).join(\"\");\n } catch {\n return \"local\";\n }\n })();\n\n return () => {\n sequence += 1;\n return `${prefix}_${randomPrefix}_${sequence.toString(36)}`;\n };\n}\n\nfunction freezeUrl(value: string, baseUrl: string): SanitizedObservedUrl {\n try {\n const url = new URL(value, baseUrl);\n return Object.freeze({\n origin: url.origin,\n pathname: url.pathname,\n queryKeys: Object.freeze(\n [...new Set(url.searchParams.keys())]\n .sort()\n .slice(0, DATA_FLOW_URL_QUERY_KEY_LIMIT),\n ),\n });\n } catch {\n return Object.freeze({\n pathname: value.split(/[?#]/u, 1)[0] ?? \"{invalid}\",\n queryKeys: Object.freeze([]),\n });\n }\n}\n\nfunction readFetchUrl(input: RequestInfo | URL): string {\n if (typeof input === \"string\") return input;\n if (input instanceof URL) return input.toString();\n return input.url;\n}\n\nfunction readFetchMethod(input: RequestInfo | URL, init?: RequestInit): string {\n if (init?.method !== undefined) return init.method.toUpperCase();\n return typeof Request !== \"undefined\" && input instanceof Request\n ? input.method.toUpperCase()\n : \"GET\";\n}\n\nfunction isSpotPatchInternalUrl(value: string, baseUrl: string): boolean {\n try {\n const pathname = new URL(value, baseUrl).pathname;\n return (\n pathname === SPOTPATCH_API_BASE || pathname.startsWith(`${SPOTPATCH_API_BASE}/`)\n );\n } catch {\n return false;\n }\n}\n\nfunction approximateBytes(value: unknown): number {\n return new TextEncoder().encode(JSON.stringify(value)).byteLength;\n}\n\nfunction createRingStore(\n limits: RuntimeDataFlowLimits,\n target: DataFlowGlobal,\n): Readonly<{\n add: (observation: NetworkObservation) => void;\n clear: () => void;\n values: () => readonly NetworkObservation[];\n}> {\n const entries: RingEntry[] = [];\n let totalBytes = 0;\n\n function removeExpired(now: number): void {\n while (\n entries[0] !== undefined &&\n now - entries[0].recordedAt > limits.observationTtlMs\n ) {\n const removed = entries.shift();\n if (removed !== undefined) totalBytes -= removed.bytes;\n }\n }\n\n return Object.freeze({\n add(observation): void {\n const now = positiveNow(target);\n removeExpired(now);\n const bytes = approximateBytes(observation);\n if (bytes > limits.observationMaxBytes) return;\n entries.push(Object.freeze({ bytes, observation, recordedAt: now }));\n totalBytes += bytes;\n\n while (\n entries.length > limits.observationMaxEntries ||\n totalBytes > limits.observationMaxBytes\n ) {\n const removed = entries.shift();\n if (removed !== undefined) totalBytes -= removed.bytes;\n }\n },\n clear(): void {\n entries.length = 0;\n totalBytes = 0;\n },\n values(): readonly NetworkObservation[] {\n removeExpired(positiveNow(target));\n return Object.freeze(entries.map(({ observation }) => observation));\n },\n });\n}\n\nfunction ownPropertyDescriptor(\n target: object,\n key: PropertyKey,\n): PropertyDescriptor | undefined {\n try {\n return Object.getOwnPropertyDescriptor(target, key);\n } catch {\n return undefined;\n }\n}\n\nfunction nestedReactWrapperComponent(candidate: object): object | undefined {\n const marker: unknown = ownPropertyDescriptor(candidate, \"$$typeof\")?.value;\n const key =\n marker === REACT_MEMO_TYPE\n ? \"type\"\n : marker === REACT_FORWARD_REF_TYPE\n ? \"render\"\n : undefined;\n if (key === undefined) return undefined;\n const nested: unknown = ownPropertyDescriptor(candidate, key)?.value;\n return (typeof nested === \"object\" && nested !== null) || typeof nested === \"function\"\n ? nested\n : undefined;\n}\n\nfunction installWritableDataProperty(\n target: object,\n key: PropertyKey,\n replacement: object,\n original: PropertyDescriptor | undefined = ownPropertyDescriptor(target, key),\n): (() => void) | undefined {\n if (original === undefined || !(\"value\" in original) || !original.writable) {\n return undefined;\n }\n\n try {\n Object.defineProperty(target, key, { ...original, value: replacement });\n } catch {\n return undefined;\n }\n\n return (): void => {\n try {\n if (ownPropertyDescriptor(target, key)?.value === replacement) {\n Object.defineProperty(target, key, original);\n }\n } catch {\n // A host or later wrapper can make the property non-configurable.\n }\n };\n}\n\nfunction recordWithoutAffectingHost(record: () => void): void {\n try {\n record();\n } catch {\n // Observation is optional; the host transport result is authoritative.\n }\n}\n\nexport function createDataFlowRuntime(\n config: RuntimeDataFlowConfig,\n target: MutableDataFlowGlobal = globalThis,\n policy: DataFlowObservationPolicy = {},\n): DataFlowRuntime {\n const componentRegistry = new WeakMap<object, DataFlowComponentRegistration>();\n const xhrMetadata = new WeakMap<object, XhrMetadata>();\n const store = createRingStore(config.limits, target);\n const nextInvocationId = createOpaqueSequence(\"invocation\");\n const nextObservationId = createOpaqueSequence(\"observation\");\n const pageEpoch = createOpaqueSequence(\"page\")();\n const nextRouteEpoch = createOpaqueSequence(\"route\");\n let routeEpoch = nextRouteEpoch();\n let routeKey: string | undefined;\n let currentInvocation: DataFlowInvocationToken | undefined;\n let currentRequestFrame: DataFlowRequestFrame | undefined;\n let disposed = false;\n\n const originalFetch = (() => {\n try {\n return target.fetch;\n } catch {\n return undefined;\n }\n })();\n function spotPatchFetch(\n this: typeof globalThis,\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> {\n if (originalFetch === undefined) {\n throw new TypeError(\"Fetch is unavailable.\");\n }\n const result = Reflect.apply(originalFetch, this, [input, init]);\n recordWithoutAffectingHost(() => {\n const frame = currentRequestFrame;\n const token = frame?.invocationToken;\n const rawUrl = readFetchUrl(input);\n if (\n isSpotPatchInternalUrl(\n rawUrl,\n target.location?.href ?? \"http://spotpatch.invalid/\",\n ) ||\n policy.shouldObserveFetch?.(\n input,\n init,\n target.location?.href ?? \"http://spotpatch.invalid/\",\n ) === false\n ) {\n return;\n }\n store.add(\n Object.freeze({\n schemaVersion: DATA_FLOW_SCHEMA_VERSION,\n id: nextObservationId(),\n pageEpoch,\n routeEpoch,\n ...(frame === undefined\n ? {}\n : {\n requestCallsiteId: frame.requestCallsiteId,\n sourceVersion: frame.sourceVersion,\n }),\n ...(token === undefined\n ? {}\n : {\n invocationId: token.invocationId,\n componentSourceId: token.componentSourceId,\n triggerCallsiteId: token.triggerCallsiteId,\n }),\n transport: \"fetch\",\n method: readFetchMethod(input, init),\n url: freezeUrl(rawUrl, target.location?.href ?? \"http://spotpatch.invalid/\"),\n outcome: \"dispatched\",\n freshness: \"current\",\n diagnosticIds: Object.freeze([]),\n }),\n );\n });\n return result;\n }\n\n const restoreFetch =\n originalFetch === undefined\n ? undefined\n : installWritableDataProperty(target, \"fetch\", spotPatchFetch);\n\n const xhrPrototype = (() => {\n try {\n return target.XMLHttpRequest?.prototype;\n } catch {\n return undefined;\n }\n })();\n const originalOpenDescriptor =\n xhrPrototype === undefined\n ? undefined\n : ownPropertyDescriptor(xhrPrototype, \"open\");\n const originalSendDescriptor =\n xhrPrototype === undefined\n ? undefined\n : ownPropertyDescriptor(xhrPrototype, \"send\");\n\n function spotPatchOpen(\n this: XMLHttpRequest,\n method: string,\n url: string | URL,\n ...rest: readonly unknown[]\n ): void {\n const original: unknown = originalOpenDescriptor?.value;\n if (typeof original === \"function\") {\n Reflect.apply(original, this, [method, url, ...rest]);\n }\n recordWithoutAffectingHost(() => {\n xhrMetadata.set(this, Object.freeze({ method, url: String(url) }));\n });\n }\n\n function spotPatchSend(\n this: XMLHttpRequest,\n body?: Document | XMLHttpRequestBodyInit | null,\n ): void {\n const original: unknown = originalSendDescriptor?.value;\n if (typeof original === \"function\") Reflect.apply(original, this, [body]);\n recordWithoutAffectingHost(() => {\n const metadata = xhrMetadata.get(this);\n if (\n metadata === undefined ||\n isSpotPatchInternalUrl(\n metadata.url,\n target.location?.href ?? \"http://spotpatch.invalid/\",\n ) ||\n policy.shouldObserveXhr?.(\n metadata.url,\n target.location?.href ?? \"http://spotpatch.invalid/\",\n ) === false\n ) {\n return;\n }\n const frame = currentRequestFrame;\n const token = frame?.invocationToken;\n store.add(\n Object.freeze({\n schemaVersion: DATA_FLOW_SCHEMA_VERSION,\n id: nextObservationId(),\n pageEpoch,\n routeEpoch,\n ...(frame === undefined\n ? {}\n : {\n requestCallsiteId: frame.requestCallsiteId,\n sourceVersion: frame.sourceVersion,\n }),\n ...(token === undefined\n ? {}\n : {\n invocationId: token.invocationId,\n componentSourceId: token.componentSourceId,\n triggerCallsiteId: token.triggerCallsiteId,\n }),\n transport: \"xhr\",\n method: metadata.method.toUpperCase(),\n url: freezeUrl(\n metadata.url,\n target.location?.href ?? \"http://spotpatch.invalid/\",\n ),\n outcome: \"dispatched\",\n freshness: \"current\",\n diagnosticIds: Object.freeze([]),\n }),\n );\n });\n }\n\n const restoreXhrOpen =\n xhrPrototype === undefined || typeof originalOpenDescriptor?.value !== \"function\"\n ? undefined\n : installWritableDataProperty(\n xhrPrototype,\n \"open\",\n spotPatchOpen,\n originalOpenDescriptor,\n );\n const restoreXhrSend =\n xhrPrototype === undefined || typeof originalSendDescriptor?.value !== \"function\"\n ? undefined\n : installWritableDataProperty(\n xhrPrototype,\n \"send\",\n spotPatchSend,\n originalSendDescriptor,\n );\n\n const runtime: DataFlowRuntime = Object.freeze({\n beginInvocation(metadata: DataFlowTriggerMetadata): DataFlowInvocationToken {\n return Object.freeze({\n invocationId: nextInvocationId(),\n componentSourceId: metadata.componentSourceId,\n triggerCallsiteId: metadata.triggerCallsiteId,\n sourceVersion: metadata.sourceVersion,\n });\n },\n bindInvocation<Arguments extends readonly unknown[], Result>(\n token: DataFlowInvocationToken | undefined,\n callback: (...args: Arguments) => Result,\n ): (...args: Arguments) => Result {\n return function boundInvocation(this: unknown, ...args: Arguments): Result {\n return runtime.withInvocation(token, () => Reflect.apply(callback, this, args));\n };\n },\n bindTrigger<Callback>(\n metadata: DataFlowTriggerMetadata,\n callback: Callback,\n ): Callback {\n if (typeof callback !== \"function\") return callback;\n const callable = callback as (...args: readonly unknown[]) => unknown;\n return function boundTrigger(this: unknown, ...args: readonly unknown[]) {\n const token = runtime.beginInvocation(metadata);\n return runtime.withInvocation(token, () => Reflect.apply(callable, this, args));\n } as Callback;\n },\n captureInvocation: () => currentInvocation,\n clear: store.clear,\n createTrpcLink(): DataFlowTrpcLink {\n return () =>\n <Operation extends DataFlowTrpcOperation, Result>(\n options: DataFlowTrpcLinkOptions<Operation, Result>,\n ): Result => {\n recordWithoutAffectingHost(() => {\n const operation = options.op.path;\n const operationType = options.op.type;\n if (\n typeof operation !== \"string\" ||\n operation.length === 0 ||\n operation.length > 512 ||\n (operationType !== \"query\" &&\n operationType !== \"mutation\" &&\n operationType !== \"subscription\")\n ) {\n return;\n }\n const frame = currentRequestFrame;\n const token = frame?.invocationToken;\n store.add(\n Object.freeze({\n schemaVersion: DATA_FLOW_SCHEMA_VERSION,\n id: nextObservationId(),\n pageEpoch,\n routeEpoch,\n ...(frame === undefined\n ? {}\n : {\n requestCallsiteId: frame.requestCallsiteId,\n sourceVersion: frame.sourceVersion,\n }),\n ...(token === undefined\n ? {}\n : {\n invocationId: token.invocationId,\n componentSourceId: token.componentSourceId,\n triggerCallsiteId: token.triggerCallsiteId,\n }),\n transport: \"trpc\",\n method: operationType.toUpperCase(),\n operation,\n url: Object.freeze({\n pathname: operation,\n queryKeys: Object.freeze([]),\n }),\n outcome: \"dispatched\",\n freshness: \"current\",\n diagnosticIds: Object.freeze([]),\n }),\n );\n });\n return options.next(options.op);\n };\n },\n dispose(): void {\n if (disposed) return;\n disposed = true;\n store.clear();\n restoreFetch?.();\n restoreXhrOpen?.();\n restoreXhrSend?.();\n },\n getComponentRegistration: (component: object) => componentRegistry.get(component),\n getCurrentRequestFrame: () => currentRequestFrame,\n observations: () =>\n Object.freeze(\n store\n .values()\n .map((observation) =>\n observation.routeEpoch === routeEpoch\n ? observation\n : Object.freeze({ ...observation, freshness: \"stale-route\" as const }),\n ),\n ),\n registerComponent(\n component: object,\n componentSourceId: string,\n registeredSourceVersion: string,\n ): void {\n const registration = Object.freeze({\n componentSourceId,\n sourceVersion: registeredSourceVersion,\n });\n const pending = [component];\n const registered = new Set<object>();\n while (pending.length > 0) {\n const candidate = pending.pop();\n if (candidate === undefined || registered.has(candidate)) continue;\n registered.add(candidate);\n componentRegistry.set(candidate, registration);\n\n const nested = nestedReactWrapperComponent(candidate);\n if (nested !== undefined) pending.push(nested);\n }\n },\n updateRoute(nextRouteKey: string): void {\n if (routeKey === undefined) {\n routeKey = nextRouteKey;\n } else if (routeKey !== nextRouteKey) {\n routeKey = nextRouteKey;\n routeEpoch = nextRouteEpoch();\n }\n },\n withInvocation<Result>(\n token: DataFlowInvocationToken | undefined,\n callback: () => Result,\n ): Result {\n const parent = currentInvocation;\n currentInvocation = token;\n try {\n return callback();\n } finally {\n currentInvocation = parent;\n }\n },\n withRequestFrame<Result>(\n token: DataFlowInvocationToken | undefined,\n metadata: DataFlowRequestMetadata,\n callback: () => Result,\n ): Result {\n const parent = currentRequestFrame;\n currentRequestFrame = Object.freeze({\n requestCallsiteId: metadata.requestCallsiteId,\n sourceVersion: metadata.sourceVersion,\n ...(token === undefined ? {} : { invocationToken: token }),\n });\n try {\n return callback();\n } finally {\n currentRequestFrame = parent;\n }\n },\n });\n\n return runtime;\n}\n\nexport function installDataFlowPrelude(\n config: RuntimeDataFlowConfig,\n target: GlobalWithDataFlow = globalThis,\n policy: DataFlowObservationPolicy = {},\n): DataFlowRuntime | undefined {\n if (!config.enabled) return undefined;\n const runtime = target[RUNTIME_KEY] ?? createDataFlowRuntime(config, target, policy);\n target[RUNTIME_KEY] = runtime;\n return runtime;\n}\n\nexport function getDataFlowRuntime(\n target: GlobalWithDataFlow = globalThis,\n): DataFlowRuntime | undefined {\n return target[RUNTIME_KEY];\n}\n","import {\n isSensitiveName,\n limitDataFlowReportCollections,\n type ComponentDataFlowReport,\n type DataDependency,\n type EvidenceRef,\n type NetworkObservation,\n type PageDataFlowReport,\n} from \"@spotpatch/shared\";\n\nfunction observationMatchesDependency(\n observation: NetworkObservation,\n dependency: DataDependency,\n): boolean {\n const origin = dependency.origin;\n const transportMatches =\n dependency.kind === \"rpc\"\n ? observation.transport === \"trpc\" &&\n dependency.operation !== undefined &&\n observation.operation === dependency.operation\n : dependency.kind === \"http\"\n ? observation.transport === \"fetch\" || observation.transport === \"xhr\"\n : false;\n if (\n !transportMatches ||\n observation.freshness !== \"current\" ||\n origin === undefined ||\n observation.requestCallsiteId !== origin.requestCallsiteId ||\n observation.sourceVersion !== origin.sourceVersion ||\n (dependency.method !== undefined &&\n observation.method.toUpperCase() !== dependency.method.toUpperCase()) ||\n (dependency.url !== undefined &&\n observation.url.pathname !== dependency.url.pathname) ||\n (dependency.url?.origin !== undefined &&\n observation.url.origin !== dependency.url.origin) ||\n (origin.componentSourceId !== undefined &&\n observation.componentSourceId !== undefined &&\n observation.componentSourceId !== origin.componentSourceId) ||\n (origin.triggerCallsiteId !== undefined &&\n observation.triggerCallsiteId !== undefined &&\n observation.triggerCallsiteId !== origin.triggerCallsiteId)\n ) {\n return false;\n }\n\n return (\n dependency.association !== \"transitive\" ||\n (observation.componentSourceId === origin.componentSourceId &&\n observation.triggerCallsiteId === origin.triggerCallsiteId)\n );\n}\n\nfunction runtimeEvidence(observation: NetworkObservation): EvidenceRef {\n return Object.freeze({\n id: observation.id,\n kind: \"runtime-observation\",\n summaryKey: \"dataFlow.evidence.runtimeDispatch\",\n });\n}\n\nfunction mergeDependencies(\n dependencies: readonly DataDependency[],\n observations: readonly NetworkObservation[],\n): Readonly<{\n dependencies: readonly DataDependency[];\n matchedObservationIds: ReadonlySet<string>;\n}> {\n const matchedObservationIds = new Set<string>();\n const merged = dependencies.map((dependency) => {\n const matches = observations.filter((observation) =>\n observationMatchesDependency(observation, dependency),\n );\n for (const observation of matches) matchedObservationIds.add(observation.id);\n if (matches.length === 0) return dependency;\n const observedOrigins = [\n ...new Set(\n matches.flatMap(({ url }) => (url.origin === undefined ? [] : [url.origin])),\n ),\n ];\n const observedOrigin =\n observedOrigins.length === 1 ? observedOrigins[0] : undefined;\n return Object.freeze({\n ...dependency,\n ...(dependency.url === undefined ||\n dependency.url.origin !== undefined ||\n observedOrigin === undefined\n ? {}\n : {\n url: Object.freeze({\n ...dependency.url,\n origin: observedOrigin,\n }),\n }),\n execution: \"observed\" as const,\n observationIds: Object.freeze([\n ...new Set([...dependency.observationIds, ...matches.map(({ id }) => id)]),\n ]),\n evidenceIds: Object.freeze([\n ...new Set([...dependency.evidenceIds, ...matches.map(({ id }) => id)]),\n ]),\n });\n });\n return Object.freeze({\n dependencies: Object.freeze(merged),\n matchedObservationIds,\n });\n}\n\nfunction appendRuntimeEvidence(\n evidence: readonly EvidenceRef[],\n observations: readonly NetworkObservation[],\n matchedIds: ReadonlySet<string>,\n): readonly EvidenceRef[] {\n const existing = new Set(evidence.map(({ id }) => id));\n return Object.freeze([\n ...evidence,\n ...observations.flatMap((observation) =>\n matchedIds.has(observation.id) && !existing.has(observation.id)\n ? [runtimeEvidence(observation)]\n : [],\n ),\n ]);\n}\n\nexport function mergeComponentDataFlowReport(\n report: ComponentDataFlowReport,\n observations: readonly NetworkObservation[],\n): ComponentDataFlowReport {\n const componentObservations = observations.filter(\n (observation) =>\n observation.componentSourceId === undefined ||\n observation.componentSourceId === report.component.componentSourceId,\n );\n const merged = mergeDependencies(report.dependencies, componentObservations);\n return limitDataFlowReportCollections(\n Object.freeze({\n ...report,\n dependencies: merged.dependencies,\n evidence: appendRuntimeEvidence(\n report.evidence,\n componentObservations,\n merged.matchedObservationIds,\n ),\n }),\n { mode: \"observation\" },\n );\n}\n\nfunction unassignedDependency(observation: NetworkObservation): DataDependency {\n const isRpc = observation.transport === \"trpc\";\n return Object.freeze({\n id: observation.id,\n kind: isRpc ? \"rpc\" : \"http\",\n direction:\n observation.method === \"GET\" ||\n observation.method === \"HEAD\" ||\n observation.method === \"QUERY\" ||\n observation.method === \"SUBSCRIPTION\"\n ? \"read\"\n : \"write\",\n execution: \"observed\",\n proof: \"unavailable\",\n association: \"unassigned\",\n method: observation.method,\n ...(isRpc\n ? observation.operation === undefined\n ? {}\n : { operation: observation.operation }\n : { url: observation.url }),\n parameters: Object.freeze(\n (isRpc ? [] : observation.url.queryKeys).map((path) =>\n Object.freeze({\n path,\n position: \"query\" as const,\n sensitive: isSensitiveName(path),\n valueState: \"not-collected\" as const,\n evidenceIds: Object.freeze([observation.id]),\n }),\n ),\n ),\n response: Object.freeze({\n consumedFields: Object.freeze([]),\n }),\n suppliedBindings: Object.freeze([]),\n locationIds: Object.freeze([]),\n evidenceIds: Object.freeze([observation.id]),\n observationIds: Object.freeze([observation.id]),\n });\n}\n\nexport function mergePageDataFlowReport(\n report: PageDataFlowReport,\n observations: readonly NetworkObservation[],\n): PageDataFlowReport {\n const currentObservations = observations.filter(\n ({ freshness }) => freshness === \"current\",\n );\n const merged = mergeDependencies(report.dependencies, currentObservations);\n const unassigned = currentObservations\n .filter(({ id }) => !merged.matchedObservationIds.has(id))\n .map(unassignedDependency);\n const allObservationIds = new Set(currentObservations.map(({ id }) => id));\n return limitDataFlowReportCollections(\n Object.freeze({\n ...report,\n dependencies: Object.freeze([...merged.dependencies, ...unassigned]),\n evidence: appendRuntimeEvidence(\n report.evidence,\n currentObservations,\n allObservationIds,\n ),\n }),\n { mode: \"observation\" },\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAM,sBAAsB;AAE5B,IAAM,aAAa,OAAO,OAAO;AAAA,EACtC,WAAW;AAAA,EACX,UAAU;AACZ,CAAC;;;ACHM,SAAS,oBACd,UACA,SAC0B;AAC1B,QAAM,UAA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AO,CAAC,CAAC;AAAA,MACpD;AAAA,MACA,sBAAsB;AAAA,MACtB,iBAAiB;AAAA,IACnB,CAAC;AAAA,EACH;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/data-flow-panel-entry.ts","../src/ui/ui-constants.ts","../src/ui/dom.ts","../src/ui/data-flow-panel.ts","../src/ui/data-flow-panel-contract.ts","../src/data-flow/data-flow-runtime.ts","../src/data-flow/report-merger.ts"],"sourcesContent":["export { createDataFlowPanel } from \"./ui/data-flow-panel.js\";\nexport {\n getDataFlowExtension,\n registerDataFlowExtension,\n type DataFlowExtension,\n type DataFlowPanel,\n type DataFlowPanelFactory,\n type DataFlowPanelSnapshot,\n type DataFlowPanelStatus,\n type DataFlowViewState,\n} from \"./ui/data-flow-panel-contract.js\";\n\nimport {\n getDataFlowRuntime,\n mergeComponentDataFlowReport,\n mergePageDataFlowReport,\n} from \"./data-flow-entry.js\";\nimport { createDataFlowPanel } from \"./ui/data-flow-panel.js\";\nimport { registerDataFlowExtension } from \"./ui/data-flow-panel-contract.js\";\n\nexport function installDataFlowPanelExtension(): void {\n registerDataFlowExtension(\n Object.freeze({\n createPanel: createDataFlowPanel,\n getComponentRegistration(component: object) {\n return getDataFlowRuntime()?.getComponentRegistration(component);\n },\n observations(routeKey: string) {\n const runtime = getDataFlowRuntime();\n runtime?.updateRoute(routeKey);\n return runtime?.observations() ?? Object.freeze([]);\n },\n mergeComponentReport: mergeComponentDataFlowReport,\n mergePageReport: mergePageDataFlowReport,\n }),\n );\n}\n","export const UI_MARKER_ATTRIBUTE = \"data-spotpatch-ui\" as const;\n\nexport const UI_Z_INDEX = Object.freeze({\n highlight: 2_147_483_646,\n controls: 2_147_483_647,\n});\n\nexport const FLOATING_SURFACE_LAYOUT = Object.freeze({\n compactInset: 8,\n compactViewportWidth: 520,\n desktopInset: 24,\n dragActivationDistance: 6,\n edgeSnapDistance: 20,\n workbenchMaxHeight: 620,\n workbenchMaxWidth: 460,\n});\n","import { UI_MARKER_ATTRIBUTE } from \"./ui-constants.js\";\n\nexport function createMarkedElement<K extends keyof HTMLElementTagNameMap>(\n document: Document,\n tagName: K,\n): HTMLElementTagNameMap[K] {\n const element = document.createElement(tagName);\n element.setAttribute(UI_MARKER_ATTRIBUTE, \"\");\n return element;\n}\n\nexport function createButton(\n document: Document,\n label: string,\n className = \"\",\n): HTMLButtonElement {\n const button = createMarkedElement(document, \"button\");\n button.type = \"button\";\n button.className = className;\n button.textContent = label;\n return button;\n}\n","import type { DataDependency, SpotPatchLocale } from \"@spotpatch/shared\";\n\nimport { createButton, createMarkedElement } from \"./dom.js\";\nimport type {\n DataFlowPanel,\n DataFlowPanelSnapshot,\n DataFlowViewState,\n} from \"./data-flow-panel-contract.js\";\n\ninterface Labels {\n readonly bindings: string;\n readonly changes: string;\n readonly componentEmpty: string;\n readonly componentTab: string;\n readonly componentTitle: string;\n readonly consumed: string;\n readonly declared: string;\n readonly diagnostics: string;\n readonly disabled: string;\n readonly error: string;\n readonly evidence: string;\n readonly loading: string;\n readonly logicalObserved: string;\n readonly noParameters: string;\n readonly observed: string;\n readonly pageEmpty: string;\n readonly pageTab: string;\n readonly pageTitle: string;\n readonly parameters: string;\n readonly refresh: string;\n readonly unknown: string;\n}\n\nconst LABELS = Object.freeze({\n \"zh-CN\": Object.freeze({\n bindings: \"数据去向\",\n changes: \"修改说明\",\n componentEmpty: \"当前组件没有找到可证明的接口。未找到不等于没有请求。\",\n componentTab: \"数据链路\",\n componentTitle: \"组件数据链路\",\n consumed: \"读取字段\",\n declared: \"代码声明,尚未在本次页面会话中观测\",\n diagnostics: \"诊断\",\n disabled: \"数据链路能力未启用,请在插件配置中设置 dataFlow: {}。\",\n error: \"数据链路报告加载失败\",\n evidence: \"证据\",\n loading: \"正在分析源码并合并运行时证据…\",\n logicalObserved: \"本次会话已进入 tRPC 调用链\",\n noParameters: \"未提取到可证明的参数键\",\n observed: \"本次会话已实际请求\",\n pageEmpty: \"当前已选页面范围内没有静态接口或运行时网络记录。\",\n pageTab: \"页面接口\",\n pageTitle: \"页面接口\",\n parameters: \"请求参数\",\n refresh: \"刷新证据\",\n unknown: \"未知\",\n }),\n \"en-US\": Object.freeze({\n bindings: \"Data destinations\",\n changes: \"Changes\",\n componentEmpty:\n \"No proven interface was found for this component. This does not prove that no request exists.\",\n componentTab: \"Data flow\",\n componentTitle: \"Component data flow\",\n consumed: \"Consumed fields\",\n declared: \"Declared in code, not observed in this page session\",\n diagnostics: \"Diagnostics\",\n disabled: \"Data flow is disabled. Set dataFlow: {} in the plugin options.\",\n error: \"Failed to load the data-flow report\",\n evidence: \"Evidence\",\n loading: \"Analyzing source and merging runtime evidence…\",\n logicalObserved: \"Dispatched through the tRPC link in this session\",\n noParameters: \"No proven parameter keys were extracted\",\n observed: \"Actually requested in this session\",\n pageEmpty:\n \"No static interface or runtime traffic is available for the selected page scope.\",\n pageTab: \"Page APIs\",\n pageTitle: \"Page interfaces\",\n parameters: \"Request parameters\",\n refresh: \"Refresh evidence\",\n unknown: \"Unknown\",\n }),\n}) satisfies Readonly<Record<SpotPatchLocale, Labels>>;\n\nfunction badge(document: Document, text: string, tone: string): HTMLElement {\n const element = createMarkedElement(document, \"span\");\n element.className = \"spotpatch-data-flow-badge\";\n element.dataset.tone = tone;\n element.textContent = text;\n return element;\n}\n\nfunction detailRow(document: Document, label: string, value: string): HTMLElement {\n const row = createMarkedElement(document, \"div\");\n row.className = \"spotpatch-data-flow-detail\";\n const key = createMarkedElement(document, \"span\");\n key.textContent = label;\n const content = createMarkedElement(document, \"code\");\n content.textContent = value;\n row.append(key, content);\n return row;\n}\n\nfunction renderDependency(\n document: Document,\n dependency: DataDependency,\n labels: Labels,\n): HTMLElement {\n const card = createMarkedElement(document, \"article\");\n card.className = \"spotpatch-data-flow-card\";\n const header = createMarkedElement(document, \"div\");\n header.className = \"spotpatch-data-flow-card-head\";\n const endpoint = createMarkedElement(document, \"div\");\n endpoint.className = \"spotpatch-data-flow-endpoint\";\n const method = createMarkedElement(document, \"strong\");\n method.textContent = dependency.method ?? labels.unknown;\n const path = createMarkedElement(document, \"code\");\n path.textContent =\n dependency.url === undefined\n ? (dependency.operation ?? labels.unknown)\n : `${dependency.url.origin ?? \"\"}${dependency.url.pathname}`;\n endpoint.append(method, path);\n const states = createMarkedElement(document, \"div\");\n states.className = \"spotpatch-data-flow-badges\";\n states.append(\n badge(\n document,\n dependency.execution === \"observed\"\n ? dependency.kind === \"rpc\"\n ? labels.logicalObserved\n : labels.observed\n : labels.declared,\n dependency.execution === \"observed\" ? \"success\" : \"neutral\",\n ),\n badge(\n document,\n dependency.proof,\n dependency.proof === \"proven\" ? \"proof\" : \"warning\",\n ),\n badge(document, dependency.association, \"neutral\"),\n );\n header.append(endpoint, states);\n\n const parameters =\n dependency.parameters.length === 0\n ? labels.noParameters\n : dependency.parameters\n .map(\n (parameter) =>\n `${parameter.position}.${parameter.path}${parameter.type === undefined ? \"\" : `: ${parameter.type}`}${parameter.sensitive ? \" [sensitive]\" : \"\"}${parameter.condition === undefined ? \"\" : ` [when ${parameter.condition}]`}`,\n )\n .join(\"\\n\");\n const consumed =\n dependency.response.consumedFields.length === 0\n ? labels.unknown\n : dependency.response.consumedFields.join(\", \");\n const bindings =\n dependency.suppliedBindings.length === 0\n ? labels.unknown\n : dependency.suppliedBindings.join(\", \");\n const body = createMarkedElement(document, \"div\");\n body.className = \"spotpatch-data-flow-card-body\";\n const observationIds = new Set(dependency.observationIds);\n const staticEvidenceCount = dependency.evidenceIds.filter(\n (id) => !observationIds.has(id),\n ).length;\n body.append(\n detailRow(document, labels.parameters, parameters),\n detailRow(document, labels.consumed, consumed),\n detailRow(document, labels.bindings, bindings),\n detailRow(\n document,\n labels.evidence,\n `${String(staticEvidenceCount)} static · ${String(dependency.observationIds.length)} runtime`,\n ),\n );\n card.append(header, body);\n return card;\n}\n\nfunction createReportRoot(\n document: Document,\n titleText: string,\n): Readonly<{ root: HTMLElement; status: HTMLElement; list: HTMLElement }> {\n const root = createMarkedElement(document, \"section\");\n root.className = \"spotpatch-data-flow-panel\";\n const title = createMarkedElement(document, \"h3\");\n title.textContent = titleText;\n const status = createMarkedElement(document, \"p\");\n status.className = \"spotpatch-data-flow-status\";\n const list = createMarkedElement(document, \"div\");\n list.className = \"spotpatch-data-flow-list\";\n root.append(title, status, list);\n return Object.freeze({ root, status, list });\n}\n\nexport function createDataFlowPanel(\n document: Document,\n enabled: boolean,\n locale: () => SpotPatchLocale,\n changesRoot: HTMLElement,\n diagnosticsRoot: HTMLElement,\n onViewChange: () => void,\n): DataFlowPanel {\n let labels = LABELS[locale()];\n const component = createReportRoot(document, labels.componentTitle);\n const page = createReportRoot(document, labels.pageTitle);\n const refreshButton = createButton(document, labels.refresh);\n const styles = document.createElement(\"style\");\n styles.textContent = DATA_FLOW_PANEL_STYLES;\n refreshButton.classList.add(\"spotpatch-data-flow-refresh\");\n component.root.prepend(refreshButton);\n const root = createMarkedElement(document, \"div\");\n const tabs = createMarkedElement(document, \"nav\");\n tabs.className = \"spotpatch-view-tabs\";\n tabs.setAttribute(\"aria-label\", \"SpotPatch views\");\n tabs.setAttribute(\"role\", \"tablist\");\n const views = new Map([\n [\"changes\", changesRoot],\n [\"component-data\", component.root],\n [\"page-data\", page.root],\n [\"diagnostics\", diagnosticsRoot],\n ]);\n const tabButtons = new Map<string, HTMLButtonElement>();\n let activeView = \"changes\";\n for (const id of views.keys()) {\n const button = createButton(document, \"\");\n button.dataset.viewId = id;\n button.id = `spotpatch-view-${id}-tab`;\n button.setAttribute(\"role\", \"tab\");\n button.setAttribute(\"aria-selected\", String(id === activeView));\n const view = views.get(id);\n view?.setAttribute(\"aria-labelledby\", button.id);\n view?.setAttribute(\"role\", \"tabpanel\");\n if (!enabled && (id === \"component-data\" || id === \"page-data\")) {\n button.hidden = true;\n }\n tabButtons.set(id, button);\n tabs.append(button);\n }\n root.append(tabs, ...views.values());\n\n function selectView(viewId: string): void {\n if (!views.has(viewId)) return;\n activeView = viewId;\n for (const [id, view] of views) {\n view.hidden = id !== viewId;\n const button = tabButtons.get(id);\n button?.setAttribute(\"aria-selected\", String(id === viewId));\n if (button !== undefined) button.tabIndex = id === viewId ? 0 : -1;\n }\n onViewChange();\n }\n\n function handleTabClick(event: Event): void {\n if (!(event.target instanceof HTMLButtonElement)) return;\n const viewId = event.target.dataset.viewId;\n if (viewId !== undefined) selectView(viewId);\n }\n\n tabs.addEventListener(\"click\", handleTabClick);\n selectView(activeView);\n\n function renderSnapshot(\n target: ReturnType<typeof createReportRoot>,\n snapshot: DataFlowPanelSnapshot,\n empty: string,\n ): void {\n target.list.replaceChildren();\n target.status.dataset.state = snapshot.status;\n if (!enabled || snapshot.status === \"disabled\") {\n target.status.textContent = labels.disabled;\n return;\n }\n if (snapshot.status === \"loading\") {\n target.status.textContent = labels.loading;\n return;\n }\n if (snapshot.status === \"error\") {\n target.status.textContent = snapshot.message ?? labels.error;\n return;\n }\n const report = snapshot.report;\n const diagnosticCodes =\n report === undefined\n ? \"\"\n : [...new Set(report.diagnostics.map(({ code }) => code))].join(\", \");\n const diagnosticSuffix =\n diagnosticCodes.length === 0\n ? \"\"\n : ` · ${labels.diagnostics}: ${diagnosticCodes}`;\n if (report === undefined || report.dependencies.length === 0) {\n target.status.textContent = `${empty}${diagnosticSuffix}`;\n return;\n }\n target.status.textContent = `${String(report.dependencies.length)} · ${report.completeness.complete ? \"complete\" : \"partial\"}${diagnosticSuffix}`;\n target.list.append(\n ...report.dependencies.map((dependency) =>\n renderDependency(document, dependency, labels),\n ),\n );\n }\n\n return Object.freeze({\n root,\n refreshButton,\n styles,\n dispose(): void {\n tabs.removeEventListener(\"click\", handleTabClick);\n },\n render(state: DataFlowViewState): void {\n labels = LABELS[locale()];\n const tabLabels = [\n labels.changes,\n labels.componentTab,\n labels.pageTab,\n labels.diagnostics,\n ];\n [...tabButtons.values()].forEach((button, index) => {\n button.textContent = tabLabels[index] ?? \"\";\n });\n refreshButton.textContent = `${labels.refresh} · ${String(state.observationCount)}`;\n refreshButton.disabled = !enabled || state.component.status === \"loading\";\n renderSnapshot(component, state.component, labels.componentEmpty);\n renderSnapshot(page, state.page, labels.pageEmpty);\n },\n resetView(): void {\n selectView(\"changes\");\n },\n });\n}\n\nconst DATA_FLOW_PANEL_STYLES = `\n .spotpatch-view-tabs { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 4px; margin-bottom: 12px; padding: 3px; border: 1px solid rgb(255 255 255 / 7%); border-radius: 9px; background: rgb(3 7 18 / 42%); }\n .spotpatch-view-tabs button { min-width: 0; border: 0; border-radius: 7px; padding: 7px 5px; color: var(--spotpatch-text-muted); background: transparent; cursor: pointer; font-size: 10.5px; }\n .spotpatch-view-tabs button[aria-selected=\"true\"] { color: #f8fafc; background: rgb(139 124 247 / 18%); }\n .spotpatch-data-flow-panel { position: relative; }\n .spotpatch-data-flow-panel > h3 { margin: 0 0 3px; color: #f3f4f6; font-size: 13px; }\n .spotpatch-data-flow-refresh { position: absolute; top: -4px; right: 0; border: 1px solid rgb(139 124 247 / 30%); border-radius: 7px; padding: 4px 8px; color: #c4baff; background: rgb(139 124 247 / 8%); cursor: pointer; font-size: 10.5px; }\n .spotpatch-data-flow-refresh:disabled { cursor: not-allowed; opacity: .45; }\n .spotpatch-data-flow-status { margin: 0 0 10px; color: var(--spotpatch-text-muted); font-size: 10.5px; line-height: 1.5; }\n .spotpatch-data-flow-list { display: grid; gap: 8px; }\n .spotpatch-data-flow-card { overflow: hidden; border: 1px solid rgb(255 255 255 / 8%); border-radius: 9px; background: rgb(255 255 255 / 2.5%); }\n .spotpatch-data-flow-card-head { display: grid; gap: 7px; padding: 10px; border-bottom: 1px solid rgb(255 255 255 / 7%); }\n .spotpatch-data-flow-endpoint { display: flex; min-width: 0; align-items: center; gap: 8px; }\n .spotpatch-data-flow-endpoint strong { color: #79d9e7; font: 700 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace; }\n .spotpatch-data-flow-endpoint code { min-width: 0; overflow: hidden; color: #f8fafc; font: 11px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace; text-overflow: ellipsis; white-space: nowrap; }\n .spotpatch-data-flow-badges { display: flex; flex-wrap: wrap; gap: 4px; }\n .spotpatch-data-flow-badge { border-radius: 999px; padding: 2px 6px; color: #9ca3af; background: rgb(255 255 255 / 5%); font-size: 9px; }\n .spotpatch-data-flow-badge[data-tone=\"success\"] { color: #6ee7b7; background: rgb(16 185 129 / 10%); }\n .spotpatch-data-flow-badge[data-tone=\"proof\"] { color: #c4b5fd; background: rgb(139 92 246 / 11%); }\n .spotpatch-data-flow-badge[data-tone=\"warning\"] { color: #fcd34d; background: rgb(245 158 11 / 10%); }\n .spotpatch-data-flow-card-body { display: grid; gap: 7px; padding: 10px; }\n .spotpatch-data-flow-detail { display: grid; grid-template-columns: 82px minmax(0, 1fr); gap: 8px; align-items: start; }\n .spotpatch-data-flow-detail > span { color: var(--spotpatch-text-muted); font-size: 10px; }\n .spotpatch-data-flow-detail > code { overflow-wrap: anywhere; color: #cbd5e1; font: 10px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; white-space: pre-wrap; }\n`;\n","import type {\n ComponentDataFlowReport,\n NetworkObservation,\n PageDataFlowReport,\n SpotPatchLocale,\n} from \"@spotpatch/shared\";\n\nimport type { DataFlowComponentRegistration } from \"../data-flow/data-flow-runtime.js\";\n\nexport type DataFlowPanelStatus = \"disabled\" | \"idle\" | \"loading\" | \"ready\" | \"error\";\n\nexport interface DataFlowPanelSnapshot {\n readonly status: DataFlowPanelStatus;\n readonly report?: ComponentDataFlowReport | PageDataFlowReport;\n readonly message?: string;\n}\n\nexport interface DataFlowViewState {\n readonly component: DataFlowPanelSnapshot;\n readonly page: DataFlowPanelSnapshot;\n readonly observationCount: number;\n}\n\nexport interface DataFlowPanel {\n readonly root: HTMLElement;\n readonly refreshButton: HTMLButtonElement;\n readonly styles: HTMLStyleElement;\n readonly dispose: () => void;\n readonly render: (state: DataFlowViewState) => void;\n readonly resetView: () => void;\n}\n\nexport type DataFlowPanelFactory = (\n document: Document,\n enabled: boolean,\n locale: () => SpotPatchLocale,\n changesRoot: HTMLElement,\n diagnosticsRoot: HTMLElement,\n onViewChange: () => void,\n) => DataFlowPanel;\n\nexport interface DataFlowExtension {\n readonly createPanel: DataFlowPanelFactory;\n readonly getComponentRegistration: (\n component: object,\n ) => DataFlowComponentRegistration | undefined;\n readonly observations: (routeKey: string) => readonly NetworkObservation[];\n readonly mergeComponentReport: (\n report: ComponentDataFlowReport,\n observations: readonly NetworkObservation[],\n ) => ComponentDataFlowReport;\n readonly mergePageReport: (\n report: PageDataFlowReport,\n observations: readonly NetworkObservation[],\n ) => PageDataFlowReport;\n}\n\nconst DATA_FLOW_EXTENSION_KEY = Symbol.for(\"spotpatch.data-flow.extension.v1\");\ntype ExtensionStore = Partial<Record<symbol, DataFlowExtension>>;\n\nexport function registerDataFlowExtension(\n extension: DataFlowExtension,\n target: ExtensionStore = globalThis,\n): void {\n target[DATA_FLOW_EXTENSION_KEY] = extension;\n}\n\nexport function getDataFlowExtension(\n target: ExtensionStore = globalThis,\n): DataFlowExtension | undefined {\n return target[DATA_FLOW_EXTENSION_KEY];\n}\n","import {\n DATA_FLOW_SCHEMA_VERSION,\n DATA_FLOW_URL_QUERY_KEY_LIMIT,\n SPOTPATCH_API_BASE,\n type NetworkObservation,\n type RuntimeDataFlowConfig,\n type RuntimeDataFlowLimits,\n type SanitizedObservedUrl,\n} from \"@spotpatch/shared/data-flow-runtime\";\n\nexport interface DataFlowComponentRegistration {\n readonly componentSourceId: string;\n readonly sourceVersion: string;\n}\n\nexport interface DataFlowInvocationToken {\n readonly invocationId: string;\n readonly componentSourceId: string;\n readonly triggerCallsiteId: string;\n readonly sourceVersion: string;\n}\n\nexport interface DataFlowRequestFrame {\n readonly requestCallsiteId: string;\n readonly sourceVersion: string;\n readonly invocationToken?: DataFlowInvocationToken;\n}\n\nexport interface DataFlowTriggerMetadata {\n readonly componentSourceId: string;\n readonly triggerCallsiteId: string;\n readonly sourceVersion: string;\n}\n\nexport interface DataFlowRequestMetadata {\n readonly requestCallsiteId: string;\n readonly sourceVersion: string;\n}\n\nexport interface DataFlowRuntime {\n readonly beginInvocation: (\n metadata: DataFlowTriggerMetadata,\n ) => DataFlowInvocationToken;\n readonly bindInvocation: <Arguments extends readonly unknown[], Result>(\n token: DataFlowInvocationToken | undefined,\n callback: (...args: Arguments) => Result,\n ) => (...args: Arguments) => Result;\n readonly bindTrigger: <Callback>(\n metadata: DataFlowTriggerMetadata,\n callback: Callback,\n ) => Callback;\n readonly captureInvocation: () => DataFlowInvocationToken | undefined;\n readonly clear: () => void;\n readonly createTrpcLink: () => DataFlowTrpcLink;\n readonly dispose: () => void;\n readonly getComponentRegistration: (\n component: object,\n ) => DataFlowComponentRegistration | undefined;\n readonly getCurrentRequestFrame: () => DataFlowRequestFrame | undefined;\n readonly observations: () => readonly NetworkObservation[];\n readonly updateRoute: (routeKey: string) => void;\n readonly registerComponent: (\n component: object,\n componentSourceId: string,\n sourceVersion: string,\n ) => void;\n readonly withInvocation: <Result>(\n token: DataFlowInvocationToken | undefined,\n callback: () => Result,\n ) => Result;\n readonly withRequestFrame: <Result>(\n token: DataFlowInvocationToken | undefined,\n metadata: DataFlowRequestMetadata,\n callback: () => Result,\n ) => Result;\n}\n\nexport interface DataFlowObservationPolicy {\n readonly shouldObserveFetch?: (\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n baseUrl: string,\n ) => boolean;\n readonly shouldObserveXhr?: (url: string, baseUrl: string) => boolean;\n}\n\nexport interface DataFlowTrpcOperation {\n readonly path: unknown;\n readonly type: unknown;\n}\n\nexport interface DataFlowTrpcLinkOptions<\n Operation extends DataFlowTrpcOperation,\n Result,\n> {\n readonly next: (operation: Operation) => Result;\n readonly op: Operation;\n}\n\nexport type DataFlowTrpcLink = (\n runtime: unknown,\n) => <Operation extends DataFlowTrpcOperation, Result>(\n options: DataFlowTrpcLinkOptions<Operation, Result>,\n) => Result;\n\ninterface DataFlowGlobal {\n readonly fetch?: typeof globalThis.fetch;\n readonly location?: Location;\n readonly performance?: Performance;\n readonly XMLHttpRequest?: typeof globalThis.XMLHttpRequest;\n}\n\ninterface MutableDataFlowGlobal extends DataFlowGlobal {\n fetch?: typeof globalThis.fetch;\n}\n\ninterface XhrMetadata {\n readonly method: string;\n readonly url: string;\n}\n\ninterface RingEntry {\n readonly bytes: number;\n readonly observation: NetworkObservation;\n readonly recordedAt: number;\n}\n\nconst RUNTIME_KEY: unique symbol = Symbol.for(\n \"spotpatch.data-flow.runtime.v1\",\n) as never;\nconst REACT_MEMO_TYPE = Symbol.for(\"react.memo\");\nconst REACT_FORWARD_REF_TYPE = Symbol.for(\"react.forward_ref\");\n\ntype DataFlowRuntimeStore = Partial<Record<symbol, DataFlowRuntime>>;\ntype GlobalWithDataFlow = MutableDataFlowGlobal & DataFlowRuntimeStore;\n\nfunction positiveNow(target: DataFlowGlobal): number {\n return target.performance?.now() ?? Date.now();\n}\n\nfunction createOpaqueSequence(prefix: string): () => string {\n let sequence = 0;\n const randomPrefix = (() => {\n try {\n const bytes = new Uint8Array(8);\n globalThis.crypto.getRandomValues(bytes);\n return Array.from(bytes, (value) => value.toString(36).padStart(2, \"0\")).join(\"\");\n } catch {\n return \"local\";\n }\n })();\n\n return () => {\n sequence += 1;\n return `${prefix}_${randomPrefix}_${sequence.toString(36)}`;\n };\n}\n\nfunction freezeUrl(value: string, baseUrl: string): SanitizedObservedUrl {\n try {\n const url = new URL(value, baseUrl);\n return Object.freeze({\n origin: url.origin,\n pathname: url.pathname,\n queryKeys: Object.freeze(\n [...new Set(url.searchParams.keys())]\n .sort()\n .slice(0, DATA_FLOW_URL_QUERY_KEY_LIMIT),\n ),\n });\n } catch {\n return Object.freeze({\n pathname: value.split(/[?#]/u, 1)[0] ?? \"{invalid}\",\n queryKeys: Object.freeze([]),\n });\n }\n}\n\nfunction readFetchUrl(input: RequestInfo | URL): string {\n if (typeof input === \"string\") return input;\n if (input instanceof URL) return input.toString();\n return input.url;\n}\n\nfunction readFetchMethod(input: RequestInfo | URL, init?: RequestInit): string {\n if (init?.method !== undefined) return init.method.toUpperCase();\n return typeof Request !== \"undefined\" && input instanceof Request\n ? input.method.toUpperCase()\n : \"GET\";\n}\n\nfunction isSpotPatchInternalUrl(value: string, baseUrl: string): boolean {\n try {\n const pathname = new URL(value, baseUrl).pathname;\n return (\n pathname === SPOTPATCH_API_BASE || pathname.startsWith(`${SPOTPATCH_API_BASE}/`)\n );\n } catch {\n return false;\n }\n}\n\nfunction approximateBytes(value: unknown): number {\n return new TextEncoder().encode(JSON.stringify(value)).byteLength;\n}\n\nfunction createRingStore(\n limits: RuntimeDataFlowLimits,\n target: DataFlowGlobal,\n): Readonly<{\n add: (observation: NetworkObservation) => void;\n clear: () => void;\n values: () => readonly NetworkObservation[];\n}> {\n const entries: RingEntry[] = [];\n let totalBytes = 0;\n\n function removeExpired(now: number): void {\n while (\n entries[0] !== undefined &&\n now - entries[0].recordedAt > limits.observationTtlMs\n ) {\n const removed = entries.shift();\n if (removed !== undefined) totalBytes -= removed.bytes;\n }\n }\n\n return Object.freeze({\n add(observation): void {\n const now = positiveNow(target);\n removeExpired(now);\n const bytes = approximateBytes(observation);\n if (bytes > limits.observationMaxBytes) return;\n entries.push(Object.freeze({ bytes, observation, recordedAt: now }));\n totalBytes += bytes;\n\n while (\n entries.length > limits.observationMaxEntries ||\n totalBytes > limits.observationMaxBytes\n ) {\n const removed = entries.shift();\n if (removed !== undefined) totalBytes -= removed.bytes;\n }\n },\n clear(): void {\n entries.length = 0;\n totalBytes = 0;\n },\n values(): readonly NetworkObservation[] {\n removeExpired(positiveNow(target));\n return Object.freeze(entries.map(({ observation }) => observation));\n },\n });\n}\n\nfunction ownPropertyDescriptor(\n target: object,\n key: PropertyKey,\n): PropertyDescriptor | undefined {\n try {\n return Object.getOwnPropertyDescriptor(target, key);\n } catch {\n return undefined;\n }\n}\n\nfunction nestedReactWrapperComponent(candidate: object): object | undefined {\n const marker: unknown = ownPropertyDescriptor(candidate, \"$$typeof\")?.value;\n const key =\n marker === REACT_MEMO_TYPE\n ? \"type\"\n : marker === REACT_FORWARD_REF_TYPE\n ? \"render\"\n : undefined;\n if (key === undefined) return undefined;\n const nested: unknown = ownPropertyDescriptor(candidate, key)?.value;\n return (typeof nested === \"object\" && nested !== null) || typeof nested === \"function\"\n ? nested\n : undefined;\n}\n\nfunction installWritableDataProperty(\n target: object,\n key: PropertyKey,\n replacement: object,\n original: PropertyDescriptor | undefined = ownPropertyDescriptor(target, key),\n): (() => void) | undefined {\n if (original === undefined || !(\"value\" in original) || !original.writable) {\n return undefined;\n }\n\n try {\n Object.defineProperty(target, key, { ...original, value: replacement });\n } catch {\n return undefined;\n }\n\n return (): void => {\n try {\n if (ownPropertyDescriptor(target, key)?.value === replacement) {\n Object.defineProperty(target, key, original);\n }\n } catch {\n // A host or later wrapper can make the property non-configurable.\n }\n };\n}\n\nfunction recordWithoutAffectingHost(record: () => void): void {\n try {\n record();\n } catch {\n // Observation is optional; the host transport result is authoritative.\n }\n}\n\nexport function createDataFlowRuntime(\n config: RuntimeDataFlowConfig,\n target: MutableDataFlowGlobal = globalThis,\n policy: DataFlowObservationPolicy = {},\n): DataFlowRuntime {\n const componentRegistry = new WeakMap<object, DataFlowComponentRegistration>();\n const xhrMetadata = new WeakMap<object, XhrMetadata>();\n const store = createRingStore(config.limits, target);\n const nextInvocationId = createOpaqueSequence(\"invocation\");\n const nextObservationId = createOpaqueSequence(\"observation\");\n const pageEpoch = createOpaqueSequence(\"page\")();\n const nextRouteEpoch = createOpaqueSequence(\"route\");\n let routeEpoch = nextRouteEpoch();\n let routeKey: string | undefined;\n let currentInvocation: DataFlowInvocationToken | undefined;\n let currentRequestFrame: DataFlowRequestFrame | undefined;\n let disposed = false;\n\n const originalFetch = (() => {\n try {\n return target.fetch;\n } catch {\n return undefined;\n }\n })();\n function spotPatchFetch(\n this: typeof globalThis,\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> {\n if (originalFetch === undefined) {\n throw new TypeError(\"Fetch is unavailable.\");\n }\n const result = Reflect.apply(originalFetch, this, [input, init]);\n recordWithoutAffectingHost(() => {\n const frame = currentRequestFrame;\n const token = frame?.invocationToken;\n const rawUrl = readFetchUrl(input);\n if (\n isSpotPatchInternalUrl(\n rawUrl,\n target.location?.href ?? \"http://spotpatch.invalid/\",\n ) ||\n policy.shouldObserveFetch?.(\n input,\n init,\n target.location?.href ?? \"http://spotpatch.invalid/\",\n ) === false\n ) {\n return;\n }\n store.add(\n Object.freeze({\n schemaVersion: DATA_FLOW_SCHEMA_VERSION,\n id: nextObservationId(),\n pageEpoch,\n routeEpoch,\n ...(frame === undefined\n ? {}\n : {\n requestCallsiteId: frame.requestCallsiteId,\n sourceVersion: frame.sourceVersion,\n }),\n ...(token === undefined\n ? {}\n : {\n invocationId: token.invocationId,\n componentSourceId: token.componentSourceId,\n triggerCallsiteId: token.triggerCallsiteId,\n }),\n transport: \"fetch\",\n method: readFetchMethod(input, init),\n url: freezeUrl(rawUrl, target.location?.href ?? \"http://spotpatch.invalid/\"),\n outcome: \"dispatched\",\n freshness: \"current\",\n diagnosticIds: Object.freeze([]),\n }),\n );\n });\n return result;\n }\n\n const restoreFetch =\n originalFetch === undefined\n ? undefined\n : installWritableDataProperty(target, \"fetch\", spotPatchFetch);\n\n const xhrPrototype = (() => {\n try {\n return target.XMLHttpRequest?.prototype;\n } catch {\n return undefined;\n }\n })();\n const originalOpenDescriptor =\n xhrPrototype === undefined\n ? undefined\n : ownPropertyDescriptor(xhrPrototype, \"open\");\n const originalSendDescriptor =\n xhrPrototype === undefined\n ? undefined\n : ownPropertyDescriptor(xhrPrototype, \"send\");\n\n function spotPatchOpen(\n this: XMLHttpRequest,\n method: string,\n url: string | URL,\n ...rest: readonly unknown[]\n ): void {\n const original: unknown = originalOpenDescriptor?.value;\n if (typeof original === \"function\") {\n Reflect.apply(original, this, [method, url, ...rest]);\n }\n recordWithoutAffectingHost(() => {\n xhrMetadata.set(this, Object.freeze({ method, url: String(url) }));\n });\n }\n\n function spotPatchSend(\n this: XMLHttpRequest,\n body?: Document | XMLHttpRequestBodyInit | null,\n ): void {\n const original: unknown = originalSendDescriptor?.value;\n if (typeof original === \"function\") Reflect.apply(original, this, [body]);\n recordWithoutAffectingHost(() => {\n const metadata = xhrMetadata.get(this);\n if (\n metadata === undefined ||\n isSpotPatchInternalUrl(\n metadata.url,\n target.location?.href ?? \"http://spotpatch.invalid/\",\n ) ||\n policy.shouldObserveXhr?.(\n metadata.url,\n target.location?.href ?? \"http://spotpatch.invalid/\",\n ) === false\n ) {\n return;\n }\n const frame = currentRequestFrame;\n const token = frame?.invocationToken;\n store.add(\n Object.freeze({\n schemaVersion: DATA_FLOW_SCHEMA_VERSION,\n id: nextObservationId(),\n pageEpoch,\n routeEpoch,\n ...(frame === undefined\n ? {}\n : {\n requestCallsiteId: frame.requestCallsiteId,\n sourceVersion: frame.sourceVersion,\n }),\n ...(token === undefined\n ? {}\n : {\n invocationId: token.invocationId,\n componentSourceId: token.componentSourceId,\n triggerCallsiteId: token.triggerCallsiteId,\n }),\n transport: \"xhr\",\n method: metadata.method.toUpperCase(),\n url: freezeUrl(\n metadata.url,\n target.location?.href ?? \"http://spotpatch.invalid/\",\n ),\n outcome: \"dispatched\",\n freshness: \"current\",\n diagnosticIds: Object.freeze([]),\n }),\n );\n });\n }\n\n const restoreXhrOpen =\n xhrPrototype === undefined || typeof originalOpenDescriptor?.value !== \"function\"\n ? undefined\n : installWritableDataProperty(\n xhrPrototype,\n \"open\",\n spotPatchOpen,\n originalOpenDescriptor,\n );\n const restoreXhrSend =\n xhrPrototype === undefined || typeof originalSendDescriptor?.value !== \"function\"\n ? undefined\n : installWritableDataProperty(\n xhrPrototype,\n \"send\",\n spotPatchSend,\n originalSendDescriptor,\n );\n\n const runtime: DataFlowRuntime = Object.freeze({\n beginInvocation(metadata: DataFlowTriggerMetadata): DataFlowInvocationToken {\n return Object.freeze({\n invocationId: nextInvocationId(),\n componentSourceId: metadata.componentSourceId,\n triggerCallsiteId: metadata.triggerCallsiteId,\n sourceVersion: metadata.sourceVersion,\n });\n },\n bindInvocation<Arguments extends readonly unknown[], Result>(\n token: DataFlowInvocationToken | undefined,\n callback: (...args: Arguments) => Result,\n ): (...args: Arguments) => Result {\n return function boundInvocation(this: unknown, ...args: Arguments): Result {\n return runtime.withInvocation(token, () => Reflect.apply(callback, this, args));\n };\n },\n bindTrigger<Callback>(\n metadata: DataFlowTriggerMetadata,\n callback: Callback,\n ): Callback {\n if (typeof callback !== \"function\") return callback;\n const callable = callback as (...args: readonly unknown[]) => unknown;\n return function boundTrigger(this: unknown, ...args: readonly unknown[]) {\n const token = runtime.beginInvocation(metadata);\n return runtime.withInvocation(token, () => Reflect.apply(callable, this, args));\n } as Callback;\n },\n captureInvocation: () => currentInvocation,\n clear: store.clear,\n createTrpcLink(): DataFlowTrpcLink {\n return () =>\n <Operation extends DataFlowTrpcOperation, Result>(\n options: DataFlowTrpcLinkOptions<Operation, Result>,\n ): Result => {\n recordWithoutAffectingHost(() => {\n const operation = options.op.path;\n const operationType = options.op.type;\n if (\n typeof operation !== \"string\" ||\n operation.length === 0 ||\n operation.length > 512 ||\n (operationType !== \"query\" &&\n operationType !== \"mutation\" &&\n operationType !== \"subscription\")\n ) {\n return;\n }\n const frame = currentRequestFrame;\n const token = frame?.invocationToken;\n store.add(\n Object.freeze({\n schemaVersion: DATA_FLOW_SCHEMA_VERSION,\n id: nextObservationId(),\n pageEpoch,\n routeEpoch,\n ...(frame === undefined\n ? {}\n : {\n requestCallsiteId: frame.requestCallsiteId,\n sourceVersion: frame.sourceVersion,\n }),\n ...(token === undefined\n ? {}\n : {\n invocationId: token.invocationId,\n componentSourceId: token.componentSourceId,\n triggerCallsiteId: token.triggerCallsiteId,\n }),\n transport: \"trpc\",\n method: operationType.toUpperCase(),\n operation,\n url: Object.freeze({\n pathname: operation,\n queryKeys: Object.freeze([]),\n }),\n outcome: \"dispatched\",\n freshness: \"current\",\n diagnosticIds: Object.freeze([]),\n }),\n );\n });\n return options.next(options.op);\n };\n },\n dispose(): void {\n if (disposed) return;\n disposed = true;\n store.clear();\n restoreFetch?.();\n restoreXhrOpen?.();\n restoreXhrSend?.();\n },\n getComponentRegistration: (component: object) => componentRegistry.get(component),\n getCurrentRequestFrame: () => currentRequestFrame,\n observations: () =>\n Object.freeze(\n store\n .values()\n .map((observation) =>\n observation.routeEpoch === routeEpoch\n ? observation\n : Object.freeze({ ...observation, freshness: \"stale-route\" as const }),\n ),\n ),\n registerComponent(\n component: object,\n componentSourceId: string,\n registeredSourceVersion: string,\n ): void {\n const registration = Object.freeze({\n componentSourceId,\n sourceVersion: registeredSourceVersion,\n });\n const pending = [component];\n const registered = new Set<object>();\n while (pending.length > 0) {\n const candidate = pending.pop();\n if (candidate === undefined || registered.has(candidate)) continue;\n registered.add(candidate);\n componentRegistry.set(candidate, registration);\n\n const nested = nestedReactWrapperComponent(candidate);\n if (nested !== undefined) pending.push(nested);\n }\n },\n updateRoute(nextRouteKey: string): void {\n if (routeKey === undefined) {\n routeKey = nextRouteKey;\n } else if (routeKey !== nextRouteKey) {\n routeKey = nextRouteKey;\n routeEpoch = nextRouteEpoch();\n }\n },\n withInvocation<Result>(\n token: DataFlowInvocationToken | undefined,\n callback: () => Result,\n ): Result {\n const parent = currentInvocation;\n currentInvocation = token;\n try {\n return callback();\n } finally {\n currentInvocation = parent;\n }\n },\n withRequestFrame<Result>(\n token: DataFlowInvocationToken | undefined,\n metadata: DataFlowRequestMetadata,\n callback: () => Result,\n ): Result {\n const parent = currentRequestFrame;\n currentRequestFrame = Object.freeze({\n requestCallsiteId: metadata.requestCallsiteId,\n sourceVersion: metadata.sourceVersion,\n ...(token === undefined ? {} : { invocationToken: token }),\n });\n try {\n return callback();\n } finally {\n currentRequestFrame = parent;\n }\n },\n });\n\n return runtime;\n}\n\nexport function installDataFlowPrelude(\n config: RuntimeDataFlowConfig,\n target: GlobalWithDataFlow = globalThis,\n policy: DataFlowObservationPolicy = {},\n): DataFlowRuntime | undefined {\n if (!config.enabled) return undefined;\n const runtime = target[RUNTIME_KEY] ?? createDataFlowRuntime(config, target, policy);\n target[RUNTIME_KEY] = runtime;\n return runtime;\n}\n\nexport function getDataFlowRuntime(\n target: GlobalWithDataFlow = globalThis,\n): DataFlowRuntime | undefined {\n return target[RUNTIME_KEY];\n}\n","import {\n isSensitiveName,\n limitDataFlowReportCollections,\n type ComponentDataFlowReport,\n type DataDependency,\n type EvidenceRef,\n type NetworkObservation,\n type PageDataFlowReport,\n} from \"@spotpatch/shared\";\n\nfunction observationMatchesDependency(\n observation: NetworkObservation,\n dependency: DataDependency,\n): boolean {\n const origin = dependency.origin;\n const transportMatches =\n dependency.kind === \"rpc\"\n ? observation.transport === \"trpc\" &&\n dependency.operation !== undefined &&\n observation.operation === dependency.operation\n : dependency.kind === \"http\"\n ? observation.transport === \"fetch\" || observation.transport === \"xhr\"\n : false;\n if (\n !transportMatches ||\n observation.freshness !== \"current\" ||\n origin === undefined ||\n observation.requestCallsiteId !== origin.requestCallsiteId ||\n observation.sourceVersion !== origin.sourceVersion ||\n (dependency.method !== undefined &&\n observation.method.toUpperCase() !== dependency.method.toUpperCase()) ||\n (dependency.url !== undefined &&\n observation.url.pathname !== dependency.url.pathname) ||\n (dependency.url?.origin !== undefined &&\n observation.url.origin !== dependency.url.origin) ||\n (origin.componentSourceId !== undefined &&\n observation.componentSourceId !== undefined &&\n observation.componentSourceId !== origin.componentSourceId) ||\n (origin.triggerCallsiteId !== undefined &&\n observation.triggerCallsiteId !== undefined &&\n observation.triggerCallsiteId !== origin.triggerCallsiteId)\n ) {\n return false;\n }\n\n return (\n dependency.association !== \"transitive\" ||\n (observation.componentSourceId === origin.componentSourceId &&\n observation.triggerCallsiteId === origin.triggerCallsiteId)\n );\n}\n\nfunction runtimeEvidence(observation: NetworkObservation): EvidenceRef {\n return Object.freeze({\n id: observation.id,\n kind: \"runtime-observation\",\n summaryKey: \"dataFlow.evidence.runtimeDispatch\",\n });\n}\n\nfunction mergeDependencies(\n dependencies: readonly DataDependency[],\n observations: readonly NetworkObservation[],\n): Readonly<{\n dependencies: readonly DataDependency[];\n matchedObservationIds: ReadonlySet<string>;\n}> {\n const matchedObservationIds = new Set<string>();\n const merged = dependencies.map((dependency) => {\n const matches = observations.filter((observation) =>\n observationMatchesDependency(observation, dependency),\n );\n for (const observation of matches) matchedObservationIds.add(observation.id);\n if (matches.length === 0) return dependency;\n const observedOrigins = [\n ...new Set(\n matches.flatMap(({ url }) => (url.origin === undefined ? [] : [url.origin])),\n ),\n ];\n const observedOrigin =\n observedOrigins.length === 1 ? observedOrigins[0] : undefined;\n return Object.freeze({\n ...dependency,\n ...(dependency.url === undefined ||\n dependency.url.origin !== undefined ||\n observedOrigin === undefined\n ? {}\n : {\n url: Object.freeze({\n ...dependency.url,\n origin: observedOrigin,\n }),\n }),\n execution: \"observed\" as const,\n observationIds: Object.freeze([\n ...new Set([...dependency.observationIds, ...matches.map(({ id }) => id)]),\n ]),\n evidenceIds: Object.freeze([\n ...new Set([...dependency.evidenceIds, ...matches.map(({ id }) => id)]),\n ]),\n });\n });\n return Object.freeze({\n dependencies: Object.freeze(merged),\n matchedObservationIds,\n });\n}\n\nfunction appendRuntimeEvidence(\n evidence: readonly EvidenceRef[],\n observations: readonly NetworkObservation[],\n matchedIds: ReadonlySet<string>,\n): readonly EvidenceRef[] {\n const existing = new Set(evidence.map(({ id }) => id));\n return Object.freeze([\n ...evidence,\n ...observations.flatMap((observation) =>\n matchedIds.has(observation.id) && !existing.has(observation.id)\n ? [runtimeEvidence(observation)]\n : [],\n ),\n ]);\n}\n\nexport function mergeComponentDataFlowReport(\n report: ComponentDataFlowReport,\n observations: readonly NetworkObservation[],\n): ComponentDataFlowReport {\n const componentObservations = observations.filter(\n (observation) =>\n observation.componentSourceId === undefined ||\n observation.componentSourceId === report.component.componentSourceId,\n );\n const merged = mergeDependencies(report.dependencies, componentObservations);\n return limitDataFlowReportCollections(\n Object.freeze({\n ...report,\n dependencies: merged.dependencies,\n evidence: appendRuntimeEvidence(\n report.evidence,\n componentObservations,\n merged.matchedObservationIds,\n ),\n }),\n { mode: \"observation\" },\n );\n}\n\nfunction unassignedDependency(observation: NetworkObservation): DataDependency {\n const isRpc = observation.transport === \"trpc\";\n return Object.freeze({\n id: observation.id,\n kind: isRpc ? \"rpc\" : \"http\",\n direction:\n observation.method === \"GET\" ||\n observation.method === \"HEAD\" ||\n observation.method === \"QUERY\" ||\n observation.method === \"SUBSCRIPTION\"\n ? \"read\"\n : \"write\",\n execution: \"observed\",\n proof: \"unavailable\",\n association: \"unassigned\",\n method: observation.method,\n ...(isRpc\n ? observation.operation === undefined\n ? {}\n : { operation: observation.operation }\n : { url: observation.url }),\n parameters: Object.freeze(\n (isRpc ? [] : observation.url.queryKeys).map((path) =>\n Object.freeze({\n path,\n position: \"query\" as const,\n sensitive: isSensitiveName(path),\n valueState: \"not-collected\" as const,\n evidenceIds: Object.freeze([observation.id]),\n }),\n ),\n ),\n response: Object.freeze({\n consumedFields: Object.freeze([]),\n }),\n suppliedBindings: Object.freeze([]),\n locationIds: Object.freeze([]),\n evidenceIds: Object.freeze([observation.id]),\n observationIds: Object.freeze([observation.id]),\n });\n}\n\nexport function mergePageDataFlowReport(\n report: PageDataFlowReport,\n observations: readonly NetworkObservation[],\n): PageDataFlowReport {\n const currentObservations = observations.filter(\n ({ freshness }) => freshness === \"current\",\n );\n const merged = mergeDependencies(report.dependencies, currentObservations);\n const unassigned = currentObservations\n .filter(({ id }) => !merged.matchedObservationIds.has(id))\n .map(unassignedDependency);\n const allObservationIds = new Set(currentObservations.map(({ id }) => id));\n return limitDataFlowReportCollections(\n Object.freeze({\n ...report,\n dependencies: Object.freeze([...merged.dependencies, ...unassigned]),\n evidence: appendRuntimeEvidence(\n report.evidence,\n currentObservations,\n allObservationIds,\n ),\n }),\n { mode: \"observation\" },\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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AAAA,IACF,CAAC;AAAA,IACD,EAAE,MAAM,cAAc;AAAA,EACxB;AACF;;;ANlMO,SAAS,gCAAsC;AACpD;AAAA,IACE,OAAO,OAAO;AAAA,MACZ,aAAa;AAAA,MACb,yBAAyB,WAAmB;AAC1C,eAAO,mBAAmB,GAAG,yBAAyB,SAAS;AAAA,MACjE;AAAA,MACA,aAAa,UAAkB;AAC7B,cAAM,UAAU,mBAAmB;AACnC,iBAAS,YAAY,QAAQ;AAC7B,eAAO,SAAS,aAAa,KAAK,OAAO,OAAO,CAAC,CAAC;AAAA,MACpD;AAAA,MACA,sBAAsB;AAAA,MACtB,iBAAiB;AAAA,IACnB,CAAC;AAAA,EACH;AACF;","names":[]}
@@ -11,7 +11,7 @@ import {
11
11
  import {
12
12
  createButton,
13
13
  createMarkedElement
14
- } from "./chunk-7ES63LA7.js";
14
+ } from "./chunk-P6X75LO5.js";
15
15
 
16
16
  // src/ui/data-flow-panel.ts
17
17
  var LABELS = Object.freeze({
@@ -999,6 +999,15 @@ var UI_Z_INDEX = Object.freeze({
999
999
  highlight: 2147483646,
1000
1000
  controls: 2147483647
1001
1001
  });
1002
+ var FLOATING_SURFACE_LAYOUT = Object.freeze({
1003
+ compactInset: 8,
1004
+ compactViewportWidth: 520,
1005
+ desktopInset: 24,
1006
+ dragActivationDistance: 6,
1007
+ edgeSnapDistance: 20,
1008
+ workbenchMaxHeight: 620,
1009
+ workbenchMaxWidth: 460
1010
+ });
1002
1011
 
1003
1012
  // src/ui/dom.ts
1004
1013
  function createMarkedElement(document, tagName) {
@@ -1027,6 +1036,7 @@ var MESSAGES = Object.freeze({
1027
1036
  resultTitle: "Managed result",
1028
1037
  controlConnection: (state, mode) => `Connection: ${state} \xB7 Mode: ${mode}`,
1029
1038
  controlAuth: (auth, grant) => `Auth: ${auth} \xB7 Grant: ${grant}`,
1039
+ controlConsentRequired: 'Grant required: type "yes" in the terminal that started `pnpm dev`. If no prompt is visible, restart `pnpm dev` in an interactive terminal and connect again.',
1030
1040
  controlModel: (model) => `Model: ${model}`,
1031
1041
  controlRevision: (task) => `Revision ${String(task.revision)}: ${task.deliveryStatus} / ${task.executionStatus} / ${task.managedPhase}`,
1032
1042
  controlValidation: (outcome) => `Validation: ${outcome}`,
@@ -1035,11 +1045,11 @@ var MESSAGES = Object.freeze({
1035
1045
  controlErrorText: Object.freeze({
1036
1046
  AGENT_BINARY_NOT_FOUND: "Codex is not installed or is not on PATH.",
1037
1047
  AGENT_BINARY_UNTRUSTED: "The resolved Codex executable is not trusted.",
1038
- AGENT_VERSION_UNSUPPORTED: "The installed Codex version is unsupported.",
1048
+ AGENT_VERSION_UNSUPPORTED: "The installed Codex version is below SpotPatch's compatibility baseline.",
1039
1049
  APP_SERVER_HANDSHAKE_FAILED: "Codex App Server did not complete startup.",
1040
1050
  AGENT_AUTH_REQUIRED: "Codex requires an authenticated account.",
1041
1051
  AGENT_MODEL_UNAVAILABLE: "The configured Codex model is unavailable.",
1042
- AGENT_PROTOCOL_INCOMPATIBLE: "The Codex App Server protocol is incompatible.",
1052
+ AGENT_PROTOCOL_INCOMPATIBLE: "The generated Codex App Server schema is incompatible with SpotPatch's required protocol subset.",
1043
1053
  CODEX_CONFIG_ISOLATION_UNSUPPORTED: "This Codex version cannot prove managed configuration isolation.",
1044
1054
  MANAGED_GRANT_INVALID: "The saved project grant failed validation.",
1045
1055
  MANAGED_PLATFORM_UNSUPPORTED: "Managed execution is not proven safe on this platform.",
@@ -1047,14 +1057,14 @@ var MESSAGES = Object.freeze({
1047
1057
  MANAGED_SNAPSHOT_FAILED: "The independent workspace snapshot could not be created.",
1048
1058
  MANAGED_SCOPE_VIOLATION: "The candidate change exceeded its authorized paths.",
1049
1059
  MANAGED_CHANGE_LIMIT_EXCEEDED: "The candidate change exceeded safety limits.",
1050
- MANAGED_VALIDATION_FAILED: "A required check failed or changed the candidate diff.",
1060
+ MANAGED_VALIDATION_FAILED: "The candidate change did not pass audit or validation.",
1051
1061
  MANAGED_WORKSPACE_CONFLICT: "An authorized source file changed during execution.",
1052
1062
  MANAGED_APPLY_FAILED: "The audited change could not be applied safely.",
1053
1063
  MANAGED_CLEANUP_INCOMPLETE: "Managed thread or workspace cleanup is incomplete."
1054
1064
  }),
1055
1065
  controlActionText: Object.freeze({
1056
1066
  "install-agent": "Install Codex and retry.",
1057
- "use-supported-version": "Use a supported Codex version.",
1067
+ "use-supported-version": "Use a schema-compatible Codex version.",
1058
1068
  "sign-in": "Sign in with Codex, then retry.",
1059
1069
  "choose-available-model": "Choose an available model in Codex configuration.",
1060
1070
  "use-inbox": "Continue with the Agent inbox fallback.",
@@ -1113,6 +1123,7 @@ var MESSAGES = Object.freeze({
1113
1123
  resultTitle: "\u53D7\u7BA1\u6267\u884C\u7ED3\u679C",
1114
1124
  controlConnection: (state, mode) => `\u8FDE\u63A5\uFF1A${state} \xB7 \u6A21\u5F0F\uFF1A${mode}`,
1115
1125
  controlAuth: (auth, grant) => `\u8BA4\u8BC1\uFF1A${auth} \xB7 \u6388\u6743\uFF1A${grant}`,
1126
+ controlConsentRequired: "\u9700\u8981\u9879\u76EE\u6388\u6743\uFF1A\u8BF7\u5728\u542F\u52A8 `pnpm dev` \u7684\u7EC8\u7AEF\u8F93\u5165\u201Cyes\u201D\u3002\u82E5\u7EC8\u7AEF\u6CA1\u6709\u51FA\u73B0\u786E\u8BA4\u63D0\u793A\uFF0C\u8BF7\u5728\u53EF\u4EA4\u4E92\u7EC8\u7AEF\u91CD\u65B0\u542F\u52A8 `pnpm dev` \u540E\u518D\u8FDE\u63A5\u3002",
1116
1127
  controlModel: (model) => `\u6A21\u578B\uFF1A${model}`,
1117
1128
  controlRevision: (task) => `revision ${String(task.revision)}\uFF1A${task.deliveryStatus} / ${task.executionStatus} / ${task.managedPhase}`,
1118
1129
  controlValidation: (outcome) => `\u9A8C\u8BC1\uFF1A${outcome}`,
@@ -1121,11 +1132,11 @@ var MESSAGES = Object.freeze({
1121
1132
  controlErrorText: Object.freeze({
1122
1133
  AGENT_BINARY_NOT_FOUND: "\u672A\u5B89\u88C5 Codex\uFF0C\u6216 Codex \u4E0D\u5728 PATH \u4E2D\u3002",
1123
1134
  AGENT_BINARY_UNTRUSTED: "\u89E3\u6790\u5230\u7684 Codex \u53EF\u6267\u884C\u6587\u4EF6\u4E0D\u53EF\u4FE1\u3002",
1124
- AGENT_VERSION_UNSUPPORTED: "\u5DF2\u5B89\u88C5\u7684 Codex \u7248\u672C\u4E0D\u53D7\u652F\u6301\u3002",
1135
+ AGENT_VERSION_UNSUPPORTED: "\u5DF2\u5B89\u88C5\u7684 Codex \u7248\u672C\u4F4E\u4E8E SpotPatch \u517C\u5BB9\u57FA\u7EBF\u3002",
1125
1136
  APP_SERVER_HANDSHAKE_FAILED: "Codex App Server \u672A\u5B8C\u6210\u542F\u52A8\u63E1\u624B\u3002",
1126
1137
  AGENT_AUTH_REQUIRED: "Codex \u9700\u8981\u5DF2\u767B\u5F55\u7684\u8D26\u6237\u3002",
1127
1138
  AGENT_MODEL_UNAVAILABLE: "Codex \u914D\u7F6E\u7684\u6A21\u578B\u5F53\u524D\u4E0D\u53EF\u7528\u3002",
1128
- AGENT_PROTOCOL_INCOMPATIBLE: "Codex App Server \u534F\u8BAE\u4E0D\u517C\u5BB9\u3002",
1139
+ AGENT_PROTOCOL_INCOMPATIBLE: "Codex \u751F\u6210\u7684 App Server Schema \u4E0D\u6EE1\u8DB3 SpotPatch \u6240\u9700\u534F\u8BAE\u5B50\u96C6\u3002",
1129
1140
  CODEX_CONFIG_ISOLATION_UNSUPPORTED: "\u5F53\u524D Codex \u7248\u672C\u65E0\u6CD5\u8BC1\u660E\u53D7\u7BA1\u914D\u7F6E\u9694\u79BB\u3002",
1130
1141
  MANAGED_GRANT_INVALID: "\u4FDD\u5B58\u7684\u9879\u76EE\u6388\u6743\u672A\u901A\u8FC7\u6821\u9A8C\u3002",
1131
1142
  MANAGED_PLATFORM_UNSUPPORTED: "\u5F53\u524D\u5E73\u53F0\u5C1A\u672A\u8BC1\u660E\u53EF\u5B89\u5168\u8FD0\u884C\u53D7\u7BA1\u6267\u884C\u3002",
@@ -1133,14 +1144,14 @@ var MESSAGES = Object.freeze({
1133
1144
  MANAGED_SNAPSHOT_FAILED: "\u65E0\u6CD5\u521B\u5EFA\u72EC\u7ACB\u5DE5\u4F5C\u533A\u5FEB\u7167\u3002",
1134
1145
  MANAGED_SCOPE_VIOLATION: "\u5019\u9009\u4FEE\u6539\u8D85\u51FA\u6388\u6743\u8DEF\u5F84\u3002",
1135
1146
  MANAGED_CHANGE_LIMIT_EXCEEDED: "\u5019\u9009\u4FEE\u6539\u8D85\u8FC7\u5B89\u5168\u4E0A\u9650\u3002",
1136
- MANAGED_VALIDATION_FAILED: "required check \u5931\u8D25\u6216\u6539\u53D8\u4E86\u5019\u9009 diff\u3002",
1147
+ MANAGED_VALIDATION_FAILED: "\u5019\u9009\u4FEE\u6539\u672A\u901A\u8FC7\u5BA1\u8BA1\u6216\u9A8C\u8BC1\u3002",
1137
1148
  MANAGED_WORKSPACE_CONFLICT: "\u6267\u884C\u671F\u95F4\u6388\u6743\u6E90\u7801\u53D1\u751F\u4E86\u53D8\u5316\u3002",
1138
1149
  MANAGED_APPLY_FAILED: "\u5DF2\u5BA1\u8BA1\u4FEE\u6539\u65E0\u6CD5\u5B89\u5168\u5199\u5165\u3002",
1139
1150
  MANAGED_CLEANUP_INCOMPLETE: "\u53D7\u7BA1 thread \u6216\u5DE5\u4F5C\u533A\u6E05\u7406\u4E0D\u5B8C\u6574\u3002"
1140
1151
  }),
1141
1152
  controlActionText: Object.freeze({
1142
1153
  "install-agent": "\u5B89\u88C5 Codex \u540E\u91CD\u8BD5\u3002",
1143
- "use-supported-version": "\u6539\u7528\u53D7\u652F\u6301\u7684 Codex \u7248\u672C\u3002",
1154
+ "use-supported-version": "\u6539\u7528 Schema \u517C\u5BB9\u7684 Codex \u7248\u672C\u3002",
1144
1155
  "sign-in": "\u767B\u5F55 Codex \u540E\u91CD\u8BD5\u3002",
1145
1156
  "choose-available-model": "\u5728 Codex \u914D\u7F6E\u4E2D\u9009\u62E9\u53EF\u7528\u6A21\u578B\u3002",
1146
1157
  "use-inbox": "\u7EE7\u7EED\u4F7F\u7528 Agent \u6536\u4EF6\u7BB1\u964D\u7EA7\u8DEF\u5F84\u3002",
@@ -1277,6 +1288,7 @@ function controlStatusText(value, messages) {
1277
1288
  const parts = [
1278
1289
  messages.controlConnection(value.connectionState, value.mode),
1279
1290
  messages.controlAuth(value.authReadiness, value.grantState),
1291
+ ...value.connectionState === "awaiting-consent" && value.grantState === "missing" ? [messages.controlConsentRequired] : [],
1280
1292
  ...model === void 0 ? [] : [messages.controlModel(model)],
1281
1293
  ...task === void 0 ? [] : [
1282
1294
  messages.controlRevision(task),
@@ -1309,11 +1321,13 @@ function managedResultText(result, messages) {
1309
1321
  ...timings
1310
1322
  ].join("\n");
1311
1323
  }
1312
- function createExternalHandoffPanel(document, framework, locale, sessionId, subscribeLocale, onViewChange) {
1324
+ function createExternalHandoffPanel(document, framework, locale, sessionId, subscribeLocale, onViewChange, onDispatchChange, onControlChange) {
1313
1325
  const options = {
1314
1326
  document,
1315
1327
  framework,
1316
1328
  locale,
1329
+ ...onDispatchChange === void 0 ? {} : { onDispatchChange },
1330
+ ...onControlChange === void 0 ? {} : { onControlChange },
1317
1331
  onViewChange,
1318
1332
  sessionId,
1319
1333
  subscribeLocale
@@ -1338,6 +1352,7 @@ function createExternalHandoffPanel(document, framework, locale, sessionId, subs
1338
1352
  root.hidden = true;
1339
1353
  const heading = createMarkedElement(document, "div");
1340
1354
  heading.className = "spotpatch-external-heading";
1355
+ heading.setAttribute("data-spotpatch-agent-identity", "");
1341
1356
  const title = createMarkedElement(document, "strong");
1342
1357
  const refreshButton = createButton(document, "", "spotpatch-external-refresh");
1343
1358
  heading.append(title, refreshButton);
@@ -1566,6 +1581,7 @@ function createExternalHandoffPanel(document, framework, locale, sessionId, subs
1566
1581
  status.textContent = summaryMessage(result.handoff);
1567
1582
  }
1568
1583
  refreshActions();
1584
+ options.onDispatchChange?.(result.dispatch);
1569
1585
  options.onViewChange();
1570
1586
  };
1571
1587
  return Object.freeze({
@@ -1607,6 +1623,7 @@ function createExternalHandoffPanel(document, framework, locale, sessionId, subs
1607
1623
  status.dataset.state = capability.brokerReady ? "ready" : "error";
1608
1624
  status.textContent = capability.brokerReady ? capability.activeAdapter?.canDispatch === true ? messages.activeReady(agentName(capability.activeAdapter.kind)) : capability.dispatch !== null && capability.activeAdapter !== null ? dispatchMessage(messages, capability.dispatch) : capability.activeWaitCount > 0 ? messages.readyWaiting(capability.activeWaitCount) : messages.ready : messages.error("EXTERNAL_HANDOFF_UNAVAILABLE");
1609
1625
  refreshActions();
1626
+ options.onDispatchChange?.(capability.dispatch);
1610
1627
  options.onViewChange();
1611
1628
  },
1612
1629
  renderPublishing() {
@@ -1635,6 +1652,7 @@ function createExternalHandoffPanel(document, framework, locale, sessionId, subs
1635
1652
  controlStatus.dataset.state = value.connectionState;
1636
1653
  disclosureNoGuarantee.textContent = value.mode === "managed" ? messages.disclosureManagedGuarantee : messages.disclosureNoGuarantee;
1637
1654
  refreshControlActions();
1655
+ options.onControlChange?.(value);
1638
1656
  options.onViewChange();
1639
1657
  },
1640
1658
  renderControlUnavailable() {
@@ -1643,6 +1661,7 @@ function createExternalHandoffPanel(document, framework, locale, sessionId, subs
1643
1661
  controlStatus.textContent = messages.controlUnavailable;
1644
1662
  disclosureNoGuarantee.textContent = messages.disclosureNoGuarantee;
1645
1663
  refreshControlActions();
1664
+ options.onControlChange?.(void 0);
1646
1665
  options.onViewChange();
1647
1666
  },
1648
1667
  renderManagedResult(result) {
@@ -1660,6 +1679,7 @@ function createExternalHandoffPanel(document, framework, locale, sessionId, subs
1660
1679
  status.dataset.state = "error";
1661
1680
  status.textContent = canRetry ? `${messages.error(code)} ${messages.retry}.` : messages.error(code);
1662
1681
  refreshActions();
1682
+ options.onDispatchChange?.(null);
1663
1683
  options.onViewChange();
1664
1684
  },
1665
1685
  setBusy(nextBusy) {