@prometheus-ags/entity-graph-core 3.2.0 → 4.0.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.
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/devtools/protocol.ts","../src/merge/lww.ts","../src/merge/registry.ts","../src/view/evaluator.ts","../src/graph.ts","../src/devtools/projection.ts","../src/devtools/inspection.ts","../src/engine.ts","../src/crud/relations.ts","../src/devtools/relationships.ts","../src/devtools-compatibility-bridge.ts","../src/devtools/time-travel.ts","../src/devtools/views.ts","../src/devtools/previews.ts","../src/devtools/controller.ts","../src/devtools/client.ts"],"names":["createStore","subscribeWithSelector","immer","notify","reference","encodedBytes","base","event"],"mappings":";;;;;;;AAGO,IAAM,uBAAA,GAA0B;AAGhC,IAAM,+BAAA,GAAkC;;;ACQxC,IAAM,WAAA,GAA6B,CAAC,IAAA,EAAM,IAAA,KAAS;AACxD,EAAA,OAAO,IAAA,GAAO,EAAE,GAAG,IAAA,EAAM,GAAG,IAAA,EAAK,GAAI,EAAE,GAAG,IAAA,EAAK;AACjD,CAAA;;;ACDA,IAAM,MAAA,uBAAa,GAAA,EAA2B;AAC9C,IAAI,aAAA,GAAsC,IAAA;AAsBnC,SAAS,iBAAiB,IAAA,EAA6B;AAC5D,EAAA,OAAO,MAAA,CAAO,GAAA,CAAI,IAAI,CAAA,IAAK,aAAA,IAAiB,WAAA;AAC9C;;;AClCO,SAAS,aAAA,CAAc,QAAiC,MAAA,EAA6B;AAC1F,EAAA,IAAI,KAAA,CAAM,OAAA,CAAQ,MAAM,CAAA,EAAG,OAAO,MAAA,CAAO,KAAA,CAAM,CAAC,MAAA,KAAW,aAAA,CAAc,MAAA,EAAQ,MAAM,CAAC,CAAA;AACxF,EAAA,OAAO,YAAA,CAAa,QAAQ,MAAM,CAAA;AACpC;AACA,SAAS,YAAA,CAAa,QAAiC,KAAA,EAA6B;AAClF,EAAA,MAAM,EAAE,KAAA,EAAO,OAAA,E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,GAAa,oBAAoB,KAAK,CAAA;AAC5C,EAAA,OAAO,MAAM,WAAW,MAAA,EAAO;AACjC,CAAC,CAAA;;;ACjgCD,IAAI,WAAA,GAAc,CAAA;AAGX,SAAS,yBAAA,CACd,SACA,SAAA,EACqB;AACrB,EAAA,IAAI,YAAA,GAAe,KAAA;AACnB,EAAA,OAAO;AAAA,IACL,OAAA;AAAA,IACA,OAAA,CAAQ,SAAS,OAAA,EAAS;AACxB,MAAA,MAAM,SAAA,GAAY,WAAW,WAAA,EAAa,CAAA,CAAA;AAC1C,MAAA,OAAO,UAAU,OAAA,CAAQ;AAAA,QACvB,QAAA,EAAU,uBAAA;AAAA,QACV,OAAA,EAAS,+BAAA;AAAA,QACT,SAAA;AAAA,QACA,OAAA;AAAA,QACA,OAAA;AAAA,QACA,GAAI,OAAA,KAAY,MAAA,GAAY,EAAE,OAAA,KAAY;AAAC,OAC5C,CAAA;AAAA,IACH,CAAA;AAAA,IACA,UAAU,QAAA,EAAU;AAClB,MAAA,IAAI,YAAA,SAAqB,MAAM;AAAA,MAAC,CAAA;AAChC,MAAA,OAAO,SAAA,CAAU,UAAU,QAAQ,CAAA;AAAA,IACrC,CAAA;AAAA,IACA,UAAA,GAAa;AACX,MAAA,IAAI,YAAA,EAAc;AAClB,MAAA,YAAA,GAAe,IAAA;AACf,MAAA,SAAA,CAAU,KAAA,EAAM;AAAA,IAClB;AAAA,GACF;AACF","file":"devtools.cjs","sourcesContent":["import type { GraphState } from \"../graph\";\n\n/** Stable wire protocol identifier for every DevTools envelope. */\nexport const GRAPH_DEVTOOLS_PROTOCOL = \"prometheus.entity-graph.devtools\" as const;\n\n/** Current wire protocol major. Incompatible envelopes must be rejected. */\nexport const GRAPH_DEVTOOLS_PROTOCOL_VERSION = 1 as const;\n\nexport type GraphDevtoolsChangeCategory =\n | \"entity\"\n | \"patch\"\n | \"entity-state\"\n | \"sync\"\n | \"list\"\n | \"store\";\n\nexport type GraphDevtoolsChangeAction = \"added\" | \"updated\" | \"removed\" | \"replaced\";\n\nexport interface GraphDevtoolsCounts {\n entityTypes: number;\n entities: number;\n patchedEntities: number;\n entityStates: number;\n syncMetadata: number;\n lists: number;\n listMemberships: number;\n fetching: number;\n stale: number;\n errors: number;\n}\n\nexport interface GraphDevtoolsChange {\n category: GraphDevtoolsChangeCategory;\n action: GraphDevtoolsChangeAction;\n /** Entity type, entity-state key, or list query key. */\n key: string;\n /** Entity id when the change targets one normalized entity. */\n id?: string;\n beforeCount?: number;\n afterCount?: number;\n valueState:\n | \"hidden-by-policy\"\n | \"included\"\n | \"redacted\"\n | \"redaction-error\"\n | \"truncated\";\n /** Omitted under the default metadata-only policy. */\n before?: unknown;\n /** Omitted under the default metadata-only policy. */\n after?: unknown;\n}\n\nexport interface GraphDevtoolsCapabilities {\n protocolVersion: typeof GRAPH_DEVTOOLS_PROTOCOL_VERSION;\n metadataOnlyByDefault: true;\n commands: ReadonlyArray<GraphDevtoolsCommandName>;\n features: ReadonlyArray<\n | \"semantic-events\"\n | \"diagnostic-events\"\n | \"bounded-history\"\n | \"multi-client\"\n | \"multi-store\"\n | \"entity-inspection\"\n | \"view-inspection\"\n | \"relationship-inspection\"\n | \"local-preview\"\n | \"snapshot-history\"\n | \"time-travel\"\n | \"history-import\"\n >;\n limits: {\n historyEvents: number;\n historyBytes: number;\n eventBytes: number;\n snapshots: number;\n snapshotBytes: number;\n };\n}\n\nexport type GraphDevtoolsSnapshotReference =\n | {\n cursor: number;\n capturedAt: string;\n eventSequence: number | null;\n label?: string;\n status: \"retained\";\n bytes: number;\n }\n | {\n cursor: number;\n capturedAt: string;\n eventSequence: number | null;\n label?: string;\n status: \"unavailable\";\n reason: \"retention-disabled\" | \"capture-failed\" | \"oversize\";\n };\n\nexport interface GraphDevtoolsSnapshotHistoryStatus {\n mode: \"live\" | \"rewound\";\n cursor: number | null;\n source: \"retained\" | \"import\" | null;\n retainedSnapshots: number;\n retainedBytes: number;\n snapshotLimit: number;\n byteLimit: number;\n baselineCursor: number | null;\n oldestCursor: number | null;\n newestCursor: number | null;\n latestCursor: number | null;\n lastUnavailable: Extract<GraphDevtoolsSnapshotReference, { status: \"unavailable\" }> | null;\n importCandidate: {\n candidateId: string;\n snapshots: number;\n bytes: number;\n } | null;\n}\n\nexport interface GraphDevtoolsEventBase {\n protocol: typeof GRAPH_DEVTOOLS_PROTOCOL;\n version: typeof GRAPH_DEVTOOLS_PROTOCOL_VERSION;\n storeId: string;\n sequence: number;\n eventId: string;\n /** For v1 mutation events one event represents one Zustand publication. */\n correlationId: string;\n observedAt: string;\n}\n\nexport interface GraphDevtoolsMutationEvent extends GraphDevtoolsEventBase {\n type: \"mutation\";\n payload: {\n /** Capture outcome at this publication; later eviction does not rewrite the event. */\n snapshot: GraphDevtoolsSnapshotReference;\n changes: GraphDevtoolsChange[];\n /** Entity identities touched by this exact publication. */\n affectedEntities?: GraphDevtoolsViewMembership[];\n /** Registered views affected at this publication boundary. */\n affectedViewIds?: string[];\n before: GraphDevtoolsCounts;\n after: GraphDevtoolsCounts;\n /** Time spent projecting the already-completed store publication. */\n projectionDurationMs: number;\n valuesTruncated: boolean;\n /** Semantic changes omitted only when metadata itself exceeds the event byte limit. */\n changesOmitted: number;\n };\n}\n\nexport interface GraphDevtoolsLifecycleEvent extends GraphDevtoolsEventBase {\n type: \"lifecycle\";\n payload: {\n state: \"attached\" | \"client-connected\" | \"client-disconnected\" | \"disposed\";\n clientId?: string;\n activeClients: number;\n };\n}\n\nexport interface GraphDevtoolsDiagnosticEvent extends GraphDevtoolsEventBase {\n type: \"diagnostic\";\n payload: {\n code: \"projection-failed\";\n message: string;\n /** The graph publication is still captured even when semantic projection fails. */\n snapshot: GraphDevtoolsSnapshotReference;\n };\n}\n\nexport interface GraphDevtoolsViewEvent extends GraphDevtoolsEventBase {\n type: \"view\";\n payload: {\n state: \"registered\" | \"membership-changed\" | \"unregistered\";\n viewId: string;\n membershipCount: number;\n };\n}\n\nexport interface GraphDevtoolsTimeTravelEvent extends GraphDevtoolsEventBase {\n type: \"time-travel\";\n payload: {\n state: \"rewound\" | \"live\";\n cursor: number | null;\n previousCursor: number | null;\n source: \"retained\" | \"import\" | null;\n previousSource: \"retained\" | \"import\" | null;\n reason: \"command\" | \"import\" | \"mutation\";\n };\n}\n\nexport type GraphDevtoolsEvent =\n | GraphDevtoolsMutationEvent\n | GraphDevtoolsLifecycleEvent\n | GraphDevtoolsDiagnosticEvent\n | GraphDevtoolsViewEvent\n | GraphDevtoolsTimeTravelEvent;\n\nexport interface GraphDevtoolsSnapshot {\n protocol: typeof GRAPH_DEVTOOLS_PROTOCOL;\n version: typeof GRAPH_DEVTOOLS_PROTOCOL_VERSION;\n storeId: string;\n capturedAt: string;\n counts: GraphDevtoolsCounts;\n history: GraphDevtoolsHistoryStatus;\n snapshots: GraphDevtoolsSnapshotHistoryStatus;\n}\n\nexport interface GraphDevtoolsHistoryStatus {\n retainedEvents: number;\n retainedBytes: number;\n eventLimit: number;\n byteLimit: number;\n oldestSequence: number | null;\n newestSequence: number | null;\n}\n\nexport interface GraphDevtoolsEntityError {\n kind: \"entity-fetch\";\n message: string;\n /** `null` when the graph only retained the compatibility error string. */\n retryable: boolean | null;\n}\n\nexport interface GraphDevtoolsEntityDirtyReason {\n kind: \"local-patch\" | \"sync-state\";\n field: string | null;\n change: \"added\" | \"changed\" | \"unsynced\";\n}\n\nexport interface GraphDevtoolsEntityRecord {\n key: string;\n type: string;\n id: string;\n presence: \"present\" | \"missing-canonical\";\n canonical: unknown | null;\n patch: unknown | null;\n merged: unknown | null;\n dirty: boolean;\n dirtyReasons: GraphDevtoolsEntityDirtyReason[];\n entityState: {\n isFetching: boolean;\n lastFetchedAt: string | null;\n stale: boolean;\n error: GraphDevtoolsEntityError | null;\n };\n sync: {\n synced: boolean;\n origin: \"server\" | \"client\" | \"optimistic\";\n updatedAt: string | null;\n };\n /** Store-local revision; increments once per publication that touches this entity. */\n revision: number;\n /** Stable IDs of registered views currently displaying this entity. */\n viewIds: string[];\n}\n\nexport interface GraphDevtoolsEntityRecordsSnapshot {\n protocol: typeof GRAPH_DEVTOOLS_PROTOCOL;\n version: typeof GRAPH_DEVTOOLS_PROTOCOL_VERSION;\n storeId: string;\n capturedAt: string;\n entityRecords: GraphDevtoolsEntityRecord[];\n}\n\nexport interface GraphDevtoolsViewDefinition {\n viewId: string;\n label: string;\n kind: \"entity\" | \"list\";\n entityType: string;\n queryKey?: string | null;\n}\n\nexport interface GraphDevtoolsViewMembership {\n type: string;\n id: string;\n}\n\nexport interface GraphDevtoolsViewListStats {\n visibleCount: number;\n graphCount: number;\n total: number | null;\n isFetching: boolean;\n isFetchingMore: boolean;\n stale: boolean;\n hasNextPage: boolean;\n hasPreviousPage: boolean;\n}\n\nexport interface GraphDevtoolsViewRecord extends GraphDevtoolsViewDefinition {\n queryKey: string | null;\n registeredAt: string;\n lastRenderedAt: string | null;\n renderCount: number;\n /** Active rendered registrations contributing to this view record. */\n subscriberCount: number;\n membership: GraphDevtoolsViewMembership[];\n list: GraphDevtoolsViewListStats | null;\n}\n\nexport interface GraphDevtoolsEntityViewMembership extends GraphDevtoolsViewMembership {\n viewIds: string[];\n}\n\nexport interface GraphDevtoolsViewsSnapshot {\n protocol: typeof GRAPH_DEVTOOLS_PROTOCOL;\n version: typeof GRAPH_DEVTOOLS_PROTOCOL_VERSION;\n storeId: string;\n capturedAt: string;\n views: GraphDevtoolsViewRecord[];\n entityViewMembership: GraphDevtoolsEntityViewMembership[];\n}\n\nexport interface GraphDevtoolsRelationshipEndpoint {\n type: string;\n id: string;\n field?: string | null;\n}\n\nexport interface GraphDevtoolsRelationship {\n relation: string;\n cardinality: \"belongsTo\" | \"hasMany\" | \"manyToMany\";\n direction: \"outgoing\" | \"reverse\";\n source: GraphDevtoolsRelationshipEndpoint;\n target: GraphDevtoolsRelationshipEndpoint;\n status: \"resolved\" | \"missing-target\";\n}\n\nexport interface GraphDevtoolsRelationshipsSnapshot {\n protocol: typeof GRAPH_DEVTOOLS_PROTOCOL;\n version: typeof GRAPH_DEVTOOLS_PROTOCOL_VERSION;\n storeId: string;\n capturedAt: string;\n relationships: GraphDevtoolsRelationship[];\n}\n\nexport interface GraphDevtoolsPreviewEntityPatchPayload {\n type: string;\n id: string;\n patch: Record<string, unknown>;\n}\n\nexport interface GraphDevtoolsRestoreEntityPreviewPayload {\n previewId: string;\n}\n\nexport interface GraphDevtoolsRewindPayload {\n cursor: number;\n}\n\nexport interface GraphDevtoolsRewindReceipt {\n status: \"rewound\";\n cursor: number;\n source: \"retained\";\n previousCursor: number | null;\n previousSource: \"retained\" | \"import\" | null;\n changedAt: string;\n}\n\nexport interface GraphDevtoolsExpiredHistoryReceipt {\n status: \"expired-history\";\n cursor: number;\n reason: \"evicted\" | \"cleared\" | \"unavailable\";\n unavailableReason?: Extract<GraphDevtoolsSnapshotReference, { status: \"unavailable\" }>[\"reason\"];\n oldestCursor: number | null;\n newestCursor: number | null;\n latestCursor: number | null;\n}\n\nexport type GraphDevtoolsRewindResult =\n | GraphDevtoolsRewindReceipt\n | GraphDevtoolsExpiredHistoryReceipt;\n\nexport interface GraphDevtoolsReturnToLiveReceipt {\n status: \"live\";\n cursor: null;\n previousCursor: number;\n previousSource: \"retained\" | \"import\";\n reason: \"command\";\n changedAt: string;\n}\n\nexport type GraphDevtoolsGraphData = Pick<\n GraphState,\n \"entities\" | \"patches\" | \"entityStates\" | \"syncMetadata\" | \"lists\"\n>;\n\nexport interface GraphDevtoolsHistoryImportSnapshot {\n cursor: number;\n capturedAt: string;\n eventSequence: number | null;\n data: GraphDevtoolsGraphData;\n}\n\nexport interface GraphDevtoolsHistoryImportEnvelope {\n protocol: typeof GRAPH_DEVTOOLS_PROTOCOL;\n version: typeof GRAPH_DEVTOOLS_PROTOCOL_VERSION;\n storeId: string;\n exportedAt: string;\n snapshots: ReadonlyArray<GraphDevtoolsHistoryImportSnapshot>;\n}\n\nexport interface GraphDevtoolsInspectHistoryImportPayload {\n candidate: unknown;\n}\n\nexport interface GraphDevtoolsHistoryImportInspectionReceipt {\n status: \"awaiting-confirmation\";\n candidateId: string;\n storeId: string;\n protocolVersion: typeof GRAPH_DEVTOOLS_PROTOCOL_VERSION;\n inspectedAt: string;\n bytes: number;\n snapshots: ReadonlyArray<{\n cursor: number;\n capturedAt: string;\n eventSequence: number | null;\n bytes: number;\n }>;\n}\n\nexport interface GraphDevtoolsHistoryImportRejectedReceipt {\n status: \"rejected\";\n reason:\n | \"invalid-envelope\"\n | \"wrong-store\"\n | \"unsupported-version\"\n | \"snapshot-limit-exceeded\"\n | \"byte-limit-exceeded\"\n | \"time-travel-unavailable\"\n | \"disposed\";\n message: string;\n}\n\nexport type GraphDevtoolsHistoryImportInspectionResult =\n | GraphDevtoolsHistoryImportInspectionReceipt\n | GraphDevtoolsHistoryImportRejectedReceipt;\n\nexport interface GraphDevtoolsConfirmHistoryImportPayload {\n candidateId: string;\n cursor: number;\n confirm: true;\n}\n\nexport interface GraphDevtoolsHistoryImportRestoreReceipt {\n status: \"rewound\";\n source: \"import\";\n candidateId: string;\n cursor: number;\n previousCursor: number | null;\n previousSource: \"retained\" | \"import\" | null;\n changedAt: string;\n}\n\nexport interface GraphDevtoolsHistoryImportRestoreRejectedReceipt {\n status: \"rejected\";\n reason:\n | \"candidate-not-found\"\n | \"snapshot-not-found\"\n | \"restore-failed\"\n | \"time-travel-unavailable\"\n | \"disposed\";\n message: string;\n}\n\nexport type GraphDevtoolsHistoryImportRestoreResult =\n | GraphDevtoolsHistoryImportRestoreReceipt\n | GraphDevtoolsHistoryImportRestoreRejectedReceipt;\n\nexport interface GraphDevtoolsPreviewAppliedReceipt {\n previewId: string;\n entity: { type: string; id: string };\n priorPatch: unknown | null;\n previewPatch: unknown;\n appliedPatch: unknown;\n baselineRevision: number;\n previewRevision: number;\n appliedAt: string;\n}\n\nexport interface GraphDevtoolsPreviewRestoredReceipt {\n previewId: string;\n status: \"restored\";\n restoredPatch: unknown | null;\n observedRevision: number;\n restoredAt: string;\n}\n\nexport interface GraphDevtoolsPreviewConflictReceipt {\n previewId: string;\n status: \"conflict\";\n reason: \"entity-changed-since-preview\";\n expectedRevision: number;\n observedRevision: number;\n currentPatch: unknown | null;\n priorPatch: unknown | null;\n}\n\nexport type GraphDevtoolsPreviewRestoreReceipt =\n | GraphDevtoolsPreviewRestoredReceipt\n | GraphDevtoolsPreviewConflictReceipt;\n\nexport type GraphDevtoolsCommandName =\n | \"get-capabilities\"\n | \"get-snapshot\"\n | \"get-history\"\n | \"get-history-status\"\n | \"get-entity-records\"\n | \"get-views\"\n | \"get-relationships\"\n | \"preview-entity-patch\"\n | \"restore-entity-preview\"\n | \"get-time-travel-status\"\n | \"rewind\"\n | \"return-to-live\"\n | \"inspect-history-import\"\n | \"confirm-history-import\"\n | \"clear-history\";\n\nexport interface GraphDevtoolsCommand {\n protocol: typeof GRAPH_DEVTOOLS_PROTOCOL;\n version: typeof GRAPH_DEVTOOLS_PROTOCOL_VERSION;\n requestId: string;\n storeId: string;\n command: GraphDevtoolsCommandName;\n payload?: unknown;\n}\n\nexport type GraphDevtoolsResultPayload =\n | GraphDevtoolsCapabilities\n | GraphDevtoolsSnapshot\n | GraphDevtoolsHistoryStatus\n | GraphDevtoolsEntityRecordsSnapshot\n | GraphDevtoolsViewsSnapshot\n | GraphDevtoolsRelationshipsSnapshot\n | GraphDevtoolsPreviewAppliedReceipt\n | GraphDevtoolsPreviewRestoreReceipt\n | GraphDevtoolsSnapshotHistoryStatus\n | GraphDevtoolsRewindResult\n | GraphDevtoolsReturnToLiveReceipt\n | GraphDevtoolsHistoryImportInspectionResult\n | GraphDevtoolsHistoryImportRestoreResult\n | ReadonlyArray<GraphDevtoolsEvent>\n | { cleared: true };\n\nexport type GraphDevtoolsResult =\n | {\n protocol: typeof GRAPH_DEVTOOLS_PROTOCOL;\n version: typeof GRAPH_DEVTOOLS_PROTOCOL_VERSION;\n requestId: string;\n storeId: string;\n ok: true;\n result: GraphDevtoolsResultPayload;\n }\n | {\n protocol: typeof GRAPH_DEVTOOLS_PROTOCOL;\n version: typeof GRAPH_DEVTOOLS_PROTOCOL_VERSION;\n requestId: string;\n storeId: string;\n ok: false;\n error: {\n code:\n | \"invalid-envelope\"\n | \"invalid-payload\"\n | \"unsupported-version\"\n | \"wrong-store\"\n | \"unsupported-command\"\n | \"entity-not-found\"\n | \"preview-not-found\"\n | \"snapshot-not-found\"\n | \"time-travel-unavailable\"\n | \"not-rewound\"\n | \"confirmation-required\"\n | \"disposed\";\n message: string;\n };\n };\n\nexport interface GraphDevtoolsValueContext {\n storeId: string;\n category: GraphDevtoolsChangeCategory;\n key: string;\n id?: string;\n /** Empty means the redactor is receiving the whole current change value. */\n fieldPath: ReadonlyArray<string | number>;\n side: \"before\" | \"after\";\n destination: \"history\" | \"inspection\";\n}\n\n/** Values never leave the graph under the default metadata-only policy. */\nexport type GraphDevtoolsValuePolicy =\n | { mode?: \"metadata-only\" }\n | {\n mode: \"include\";\n redact?: (value: unknown, context: GraphDevtoolsValueContext) => unknown;\n };\n\nexport interface GraphDevtoolsTransport {\n request(command: unknown): Promise<GraphDevtoolsResult>;\n subscribe(listener: (event: GraphDevtoolsEvent) => void): () => void;\n close(): void;\n}\n","/**\n * merge/lww.ts — Last-write-wins default strategy.\n *\n * Semantics match the historical `upsertEntity` behavior exactly: shallow-merge\n * the incoming write over the previous value. This is the fallback when no\n * other strategy is registered, so registering nothing is a no-op change.\n */\n\nimport type { MergeStrategy } from \"./types\";\n\n/**\n * Shallow-merge `next` over `prev` (incoming keys win). Returns a new object.\n * On first write (`prev` undefined) returns a shallow copy of `next`.\n */\nexport const lwwStrategy: MergeStrategy = (prev, next) => {\n return prev ? { ...prev, ...next } : { ...next };\n};\n","/**\n * merge/registry.ts — One MergeStrategy per entity type (+ optional global default).\n *\n * Lookup order at write time:\n * 1. strategy registered for the exact `type`\n * 2. global default strategy (if one was set)\n * 3. built-in LWW (`lwwStrategy`)\n *\n * Step 3 guarantees that with zero registrations the graph behaves exactly as\n * it did before this seam existed.\n */\n\nimport type { MergeStrategy } from \"./types\";\nimport { lwwStrategy } from \"./lww\";\n\nconst byType = new Map<string, MergeStrategy>();\nlet globalDefault: MergeStrategy | null = null;\n\n/**\n * Register a {@link MergeStrategy} for one entity type. Overwrites any prior\n * registration for that type.\n */\nexport function registerMergeStrategy(type: string, strategy: MergeStrategy): void {\n byType.set(type, strategy);\n}\n\n/**\n * Set the fallback strategy used for any type without its own registration.\n * Pass `null` to clear it (reverting the fallback to built-in LWW).\n */\nexport function setDefaultMergeStrategy(strategy: MergeStrategy | null): void {\n globalDefault = strategy;\n}\n\n/**\n * Resolve the effective strategy for a type: per-type → global default → LWW.\n * Always returns a usable strategy (never null).\n */\nexport function getMergeStrategy(type: string): MergeStrategy {\n return byType.get(type) ?? globalDefault ?? lwwStrategy;\n}\n\n/** True if `type` (or a global default) has a non-LWW strategy registered. */\nexport function hasMergeStrategy(type: string): boolean {\n return byType.has(type) || globalDefault !== null;\n}\n\n/** @internal Test-only. NOT re-exported from index.ts. */\nexport function __resetMergeStrategies(): void {\n byType.clear();\n globalDefault = null;\n}\n","import type { FilterSpec, FilterClause, FilterGroup, SortSpec, SortClause } from \"./types\";\n\n/**\n * Evaluate `FilterSpec` against one in-memory entity — mirrors remote semantics as closely as plain JS allows.\n * Use for **local** and **hybrid** `useEntityView` paths so UI filtering matches what users expect from the declarative spec.\n */\nexport function matchesFilter(entity: Record<string, unknown>, filter: FilterSpec): boolean {\n if (Array.isArray(filter)) return filter.every((clause) => matchesClause(entity, clause));\n return matchesGroup(entity, filter);\n}\nfunction matchesGroup(entity: Record<string, unknown>, group: FilterGroup): boolean {\n const { logic, clauses } = group;\n if (logic === \"and\") return clauses.every((c) => \"logic\" in c ? matchesGroup(entity, c) : matchesClause(entity, c));\n return clauses.some((c) => \"logic\" in c ? matchesGroup(entity, c) : matchesClause(entity, c));\n}\nfunction matchesClause(entity: Record<string, unknown>, clause: FilterClause): boolean {\n const { field, op, value, predicate } = clause;\n const fv = getNestedValue(entity, field);\n switch (op) {\n case \"eq\": return fv === value;\n case \"neq\": return fv !== value;\n case \"gt\": return (fv as number) > (value as number);\n case \"gte\": return (fv as number) >= (value as number);\n case \"lt\": return (fv as number) < (value as number);\n case \"lte\": return (fv as number) <= (value as number);\n case \"in\": return Array.isArray(value) && value.includes(fv);\n case \"nin\": return Array.isArray(value) && !value.includes(fv);\n case \"isNull\": return fv == null;\n case \"isNotNull\": return fv != null;\n case \"contains\": return typeof fv === \"string\" && typeof value === \"string\" && fv.toLowerCase().includes(value.toLowerCase());\n case \"startsWith\": return typeof fv === \"string\" && typeof value === \"string\" && fv.toLowerCase().startsWith(value.toLowerCase());\n case \"endsWith\": return typeof fv === \"string\" && typeof value === \"string\" && fv.toLowerCase().endsWith(value.toLowerCase());\n case \"between\": { const [lo, hi] = value as [number, number]; return (fv as number) >= lo && (fv as number) <= hi; }\n case \"arrayContains\": return Array.isArray(fv) && fv.includes(value);\n case \"arrayOverlaps\": return Array.isArray(fv) && Array.isArray(value) && value.some((v) => fv.includes(v));\n case \"matches\": return typeof fv === \"string\" && new RegExp(value as string).test(fv);\n case \"custom\": return predicate ? predicate(fv, entity) : true;\n default: return true;\n }\n}\n/**\n * Case-insensitive substring match across configured string fields; empty query is a no-op pass.\n * Keeps quick search consistent between client-only and debounced remote `q` params.\n */\nexport function matchesSearch(entity: Record<string, unknown>, query: string, fields: string[]): boolean {\n if (!query.trim()) return true;\n const lq = query.toLowerCase();\n return fields.some((field) => { const v = getNestedValue(entity, field); return typeof v === \"string\" && v.toLowerCase().includes(lq); });\n}\n/**\n * Multi-key comparator implementing `SortSpec` (null ordering, optional custom comparators, locale-aware string fallback).\n * Shared by local sorting and binary insertion for realtime updates.\n */\nexport function compareEntities(a: Record<string, unknown>, b: Record<string, unknown>, sort: SortSpec): number {\n for (const clause of sort) { const r = compareByClause(a, b, clause); if (r !== 0) return r; } return 0;\n}\nfunction compareByClause(a: Record<string, unknown>, b: Record<string, unknown>, clause: SortClause): number {\n const { field, direction, nulls = \"last\", comparator } = clause;\n const av = getNestedValue(a, field); const bv = getNestedValue(b, field);\n const aNull = av == null; const bNull = bv == null;\n if (aNull && bNull) return 0;\n if (aNull) return nulls === \"first\" ? -1 : 1;\n if (bNull) return nulls === \"first\" ? 1 : -1;\n let cmp: number;\n if (comparator) cmp = comparator(av, bv);\n else if (typeof av === \"string\" && typeof bv === \"string\") cmp = av.localeCompare(bv, undefined, { sensitivity: \"base\", numeric: true });\n else if (typeof av === \"number\" && typeof bv === \"number\") cmp = av - bv;\n else cmp = String(av).localeCompare(String(bv));\n return direction === \"desc\" ? -cmp : cmp;\n}\n/**\n * Binary-search insertion index so realtime inserts land in sorted order without resorting the full id list (O(log n) per insert).\n * Skips missing `getEntity` rows by advancing low — callers should ensure entities exist or tolerate append-like behavior.\n */\nexport function findInsertionIndex(entity: Record<string, unknown>, sortedIds: string[], getEntity: (id: string) => Record<string, unknown> | null, sort: SortSpec): number {\n let lo = 0; let hi = sortedIds.length;\n while (lo < hi) { const mid = (lo + hi) >>> 1; const me = getEntity(sortedIds[mid]); if (!me) { lo = mid + 1; continue; } if (compareEntities(entity, me, sort) <= 0) hi = mid; else lo = mid + 1; }\n return lo;\n}\n/**\n * Pure list projection: map ids → entities, drop missing, filter/sort/search, return **ids** in display order.\n * Bridges stored id lists with on-the-fly view descriptors without duplicating entity payloads.\n */\nexport function applyView(ids: string[], getEntity: (id: string) => Record<string, unknown> | null, filter?: FilterSpec | null, sort?: SortSpec | null, search?: { query: string; fields: string[] } | null): string[] {\n let entries: Array<{ id: string; entity: Record<string, unknown> }> = [];\n for (const id of ids) { const entity = getEntity(id); if (!entity) continue; entries.push({ id, entity }); }\n if (filter && entries.length > 0) entries = entries.filter(({ entity }) => matchesFilter(entity, filter));\n if (search?.query) entries = entries.filter(({ entity }) => matchesSearch(entity, search.query, search.fields));\n if (sort && sort.length > 0) entries.sort((a, b) => compareEntities(a.entity, b.entity, sort));\n return entries.map((e) => e.id);\n}\n/**\n * Heuristic for whether the graph likely holds **all** rows for a list key (enables local-only filtering/sorting in `useEntityView`).\n * `total` and `hasNextPage` come from list metadata written by fetchers.\n */\nexport function checkCompleteness(loadedCount: number, total: number | null, hasNextPage: boolean): { isComplete: boolean; reason: string } {\n if (!hasNextPage && total !== null && loadedCount >= total) return { isComplete: true, reason: \"all-loaded\" };\n if (hasNextPage) return { isComplete: false, reason: \"has-more-pages\" };\n return { isComplete: true, reason: \"no-more-pages\" };\n}\nfunction getNestedValue(obj: Record<string, unknown>, path: string): unknown {\n const parts = path.replace(/\\[(\\d+)\\]/g, \".$1\").split(\".\");\n let current: unknown = obj;\n for (const part of parts) { if (current == null || typeof current !== \"object\") return undefined; current = (current as Record<string, unknown>)[part]; }\n return current;\n}\n","import { createStore } from \"zustand/vanilla\";\nimport { subscribeWithSelector } from \"zustand/middleware\";\nimport { immer } from \"zustand/middleware/immer\";\nimport type { EntityError } from \"./errors\";\nimport { getMergeStrategy } from \"./merge/registry\";\nimport type { MergeContext } from \"./merge/types\";\nimport { findInsertionIndex, matchesFilter, matchesSearch } from \"./view/evaluator\";\nimport type { ViewDescriptor } from \"./view/types\";\n\n/** Logical entity kind (e.g. `\"Post\"`). Used to partition the normalized graph. */\nexport type EntityType = string;\n/** Primary key for an entity within its `type`. Lists and relations reference this, not row copies. */\nexport type EntityId = string;\n/** Stable string key for a list query (often `JSON.stringify`-shaped). Lists store IDs only under this key. */\nexport type QueryKey = string;\n/** Provenance of the latest known entity state. */\nexport type SyncOrigin = \"server\" | \"client\" | \"optimistic\";\n\n/** Optional sync-facing metadata kept outside canonical entity payloads. */\nexport interface EntitySyncMetadata {\n synced: boolean;\n origin: SyncOrigin;\n updatedAt: number | null;\n}\n\n/** Snapshot shape returned by sync-aware reads and graph-native query helpers. */\nexport type EntitySnapshot<T extends object> = T & {\n $synced: boolean;\n $origin: SyncOrigin;\n $updatedAt: number | null;\n};\n\n/**\n * Fetch/cache metadata for a single entity instance (`type:id`).\n * Separates transport concerns from canonical `entities` data so hooks can show spinners and stale-while-revalidate without mutating server-shaped fields.\n */\nexport interface EntityState {\n isFetching: boolean;\n lastFetched: number | null;\n error: string | null;\n stale: boolean;\n}\n\n/**\n * Ordered **IDs** for a list query plus pagination metadata — never embedded entity payloads.\n * Cross-view reactivity depends on this: when `entities[type][id]` updates, every list containing that id re-resolves rows from the graph.\n */\nexport interface ListState {\n ids: EntityId[];\n total: number | null;\n nextCursor: string | null;\n prevCursor: string | null;\n hasNextPage: boolean;\n hasPrevPage: boolean;\n isFetching: boolean;\n isFetchingMore: boolean;\n error: string | null;\n /**\n * Typed error instance for 2.0 hooks (`useEntities`, `useEntityQuery`).\n * Carries `TerminalError` / `TransientError` so consumers can\n * `instanceof`-check the failure mode without parsing the string in\n * `error`. Both fields are written together by `setListError`; the\n * string `error` field remains for back-compat with 1.x consumers.\n */\n lastError: EntityError | null;\n lastFetched: number | null;\n stale: boolean;\n currentPage: number | null;\n pageSize: number | null;\n}\n\n/** Pagination and lifecycle metadata accepted by successful list writes. */\nexport type ListResultMeta = Partial<Omit<\n ListState,\n \"ids\" | \"isFetching\" | \"isFetchingMore\" | \"error\" | \"stale\"\n>>;\n\n/** One list projection updated as part of an atomic fetched-list ingestion. */\nexport interface FetchedListTarget {\n key: QueryKey;\n mode?: \"replace\" | \"append\";\n meta?: ListResultMeta;\n /** Override list membership when the transport derives ids separately. */\n ids?: EntityId[];\n}\n\n/** Additional normalized entity rows committed with the primary fetched list. */\nexport interface FetchedEntityBatch {\n type: EntityType;\n entries: Array<{ id: EntityId; data: Record<string, unknown> }>;\n}\n\n/** Incrementally project fetched rows into an existing view-backed list. */\nexport interface FetchedListProjection {\n key: QueryKey;\n view: ViewDescriptor;\n /** Complete the projection's fetch lifecycle without replacing its ids. */\n completeFetch?: boolean;\n}\n\n/** Additional graph projections completed by one fetched-list response. */\nexport interface IngestFetchedListOptions {\n lists?: FetchedListTarget[];\n /** Side-descriptor rows that must commit or fail with the primary batch. */\n sideBatches?: FetchedEntityBatch[];\n /** View-backed lists that receive matching fetched ids in the same publication. */\n projections?: FetchedListProjection[];\n /** List fetch flags to clear without replacing their existing ids or metadata. */\n finishListFetches?: QueryKey[];\n}\n\n/**\n * Stable fallbacks for missing `lists[key]` / `entityStates[key]` slots.\n * Inline `?? { ... }` defaults allocate new objects every `getSnapshot` call and trigger React 19\n * “getSnapshot should be cached” / maximum update depth errors with `useSyncExternalStore`.\n */\nexport const EMPTY_IDS: EntityId[] = [];\n\nexport const EMPTY_ENTITY_STATE: EntityState = {\n isFetching: false,\n lastFetched: null,\n error: null,\n stale: false,\n};\n\nexport const EMPTY_SYNC_METADATA: EntitySyncMetadata = {\n synced: true,\n origin: \"server\",\n updatedAt: null,\n};\n\nexport const EMPTY_LIST_STATE: ListState = {\n ids: EMPTY_IDS,\n total: null,\n nextCursor: null,\n prevCursor: null,\n hasNextPage: false,\n hasPrevPage: false,\n isFetching: false,\n isFetchingMore: false,\n error: null,\n lastError: null,\n lastFetched: null,\n stale: false,\n currentPage: null,\n pageSize: null,\n};\n\n/**\n * Canonical Zustand store: **entities** (server truth), **patches** (UI-only overlay), **lists** (id order + list meta), and **entityStates** (per-entity fetch state).\n * Framework bindings subscribe to the vanilla store; stores, adapters, and\n * engines can read it synchronously through `graphStore.getState()`.\n */\nexport interface GraphState {\n /** Normalized server-confirmed records. Mutate only via upsert/replace/remove — not from components. */\n entities: Record<EntityType, Record<EntityId, Record<string, unknown>>>;\n /** Local-only fields merged at read time (`readEntity` / hooks). Never send patches to the server. */\n patches: Record<EntityType, Record<EntityId, Record<string, unknown>>>;\n /** Per-entity fetch lifecycle keyed as `${type}:${id}`. */\n entityStates: Record<string, EntityState>;\n /** Optional sync/provenance state layered beside the canonical entity payload. */\n syncMetadata: Record<string, EntitySyncMetadata>;\n /** List slots keyed by serialized query keys. Values hold id arrays and pagination — not entity clones. */\n lists: Record<QueryKey, ListState>;\n /**\n * Shallow-merge `data` into the canonical entity. Use when the API returns partial updates or normalized fragments.\n * @param type - Entity kind\n * @param id - Entity id\n * @param data - Fields to merge into existing canonical data\n */\n upsertEntity: (type: EntityType, id: EntityId, data: Record<string, unknown>) => void;\n /**\n * Batch upsert for list endpoints — avoids N separate writes when hydrating many rows at once.\n * @param type - Entity kind\n * @param entries - Pairs of id + partial/full payloads to merge\n */\n upsertEntities: (type: EntityType, entries: Array<{ id: EntityId; data: Record<string, unknown> }>) => void;\n /**\n * Merge one fetched page, mark every row fetched, and update its list\n * projections in one Zustand publication.\n */\n ingestFetchedList: (\n type: EntityType,\n entries: Array<{ id: EntityId; data: Record<string, unknown> }>,\n options?: IngestFetchedListOptions,\n ) => void;\n /**\n * Replace the canonical entity entirely (no merge). Use when the server returns a full snapshot and partial merge would leave stale keys behind.\n */\n replaceEntity: (type: EntityType, id: EntityId, data: Record<string, unknown>) => void;\n /** Remove canonical entity, its patches, and its entityState. Does not remove the id from lists — use `removeIdFromAllLists` if needed. */\n removeEntity: (type: EntityType, id: EntityId) => void;\n /**\n * Merge UI-only fields into `patches` so every subscriber sees selection, expansion, optimistic toggles, etc., without forking canonical data.\n */\n patchEntity: (type: EntityType, id: EntityId, patch: Record<string, unknown>) => void;\n /** Remove specific patch keys; other patch keys remain. */\n unpatchEntity: (type: EntityType, id: EntityId, keys: string[]) => void;\n /** Drop all patches for an entity (e.g. after successful mutation when server data is authoritative). */\n clearPatch: (type: EntityType, id: EntityId) => void;\n /** Reflect in-flight GET for a single entity (deduped fetches in the engine still flip this once per logical request). */\n setEntityFetching: (type: EntityType, id: EntityId, fetching: boolean) => void;\n /** Persist terminal fetch failure message and clear fetching — hooks surface `error` while leaving prior data if any. */\n setEntityError: (type: EntityType, id: EntityId, error: string | null) => void;\n /** Mark entity successfully loaded; clears error, fetching, stale, and updates `lastFetched`. */\n setEntityFetched: (type: EntityType, id: EntityId) => void;\n /** Drive background revalidation: when true, hooks refetch while still showing cached `readEntity` data. */\n setEntityStale: (type: EntityType, id: EntityId, stale: boolean) => void;\n /** Merge sync metadata for one entity without polluting canonical server fields. */\n setEntitySyncMetadata: (type: EntityType, id: EntityId, metadata: Partial<EntitySyncMetadata>) => void;\n /** Clear sync metadata for one entity. */\n clearEntitySyncMetadata: (type: EntityType, id: EntityId) => void;\n /**\n * Replace list ids and merge pagination meta after a primary list fetch (not load-more).\n * Resets fetching flags and clears list error on success path (engine calls this after normalize).\n */\n setListResult: (key: QueryKey, ids: EntityId[], meta: Partial<Omit<ListState, \"ids\" | \"isFetching\" | \"isFetchingMore\" | \"error\" | \"stale\">>) => void;\n /** Append unique ids (e.g. infinite scroll) while merging meta; dedupes id order. */\n appendListResult: (key: QueryKey, ids: EntityId[], meta: Partial<Omit<ListState, \"ids\" | \"isFetching\" | \"isFetchingMore\" | \"error\" | \"stale\">>) => void;\n /** Prepend ids (e.g. “new item at top”) with optional meta merge. */\n prependListResult: (key: QueryKey, ids: EntityId[], meta?: Partial<ListState>) => void;\n /** After deletes, keep every list consistent by removing an id everywhere it appears and decrementing `total` when tracked. */\n removeIdFromAllLists: (type: EntityType, id: EntityId) => void;\n /**\n * Insert or move an id in one list. If the id already exists, it is removed first then re-inserted at `position`.\n * @param position - `\"start\"`, `\"end\"`, or numeric index\n */\n insertIdInList: (key: QueryKey, id: EntityId, position: \"start\" | \"end\" | number) => void;\n /** Initial or full list fetch in progress (not page-2+). */\n setListFetching: (key: QueryKey, fetching: boolean) => void;\n /** Pagination / “load more” in progress for the same list key. */\n setListFetchingMore: (key: QueryKey, fetchingMore: boolean) => void;\n /**\n * Record list fetch failure; clears both fetching flags.\n * The optional `typed` argument is the typed `EntityError` instance\n * (used by 2.0 hooks); when omitted only the string `error` field is\n * populated (back-compat with 1.x callers).\n */\n setListError: (key: QueryKey, error: string | null, typed?: EntityError | null) => void;\n /** Mark a list query stale so hooks can refetch without discarding current ids (stale-while-revalidate). */\n setListStale: (key: QueryKey, stale: boolean) => void;\n /**\n * Mark one or all entities of a type stale for subscriber-driven refetch. Does not delete data.\n * @param id - Omit to stale every entity of `type`\n */\n invalidateEntity: (type: EntityType, id?: EntityId) => void;\n /**\n * Mark lists stale by key prefix or custom predicate so the next access triggers background refresh without dropping ids immediately.\n */\n invalidateLists: (matcher: string | ((key: QueryKey) => boolean)) => void;\n /** Convenience: stale all entities of a type and lists whose keys start with `type`. */\n invalidateType: (type: EntityType) => void;\n /**\n * Single read path: `{ ...entities[type][id], ...patches[type][id] }` or null if no canonical row exists.\n * @returns Merged view suitable for rendering; not a deep clone\n */\n readEntity: <T = Record<string, unknown>>(type: EntityType, id: EntityId) => T | null;\n /**\n * Sync-aware read path: canonical entity + patches + virtual sync metadata (`$synced`, `$origin`, `$updatedAt`).\n */\n readEntitySnapshot: <T = Record<string, unknown>>(type: EntityType, id: EntityId) => EntitySnapshot<T & Record<string, unknown>> | null;\n}\n\nfunction defaultEntityState(): EntityState {\n return { ...EMPTY_ENTITY_STATE };\n}\n\nfunction defaultSyncMetadata(): EntitySyncMetadata {\n return { ...EMPTY_SYNC_METADATA };\n}\n\nfunction defaultListState(): ListState {\n return { ...EMPTY_LIST_STATE, ids: [] };\n}\n\nfunction ek(type: EntityType, id: EntityId) { return `${type}:${id}`; }\n\ninterface SnapshotCacheEntry {\n base: Record<string, unknown>;\n patch: Record<string, unknown> | undefined;\n metadata: EntitySyncMetadata;\n snapshot: EntitySnapshot<Record<string, unknown>>;\n}\n\nconst snapshotCache = new Map<string, SnapshotCacheEntry>();\n\nfunction readCachedEntitySnapshot<T extends Record<string, unknown>>(\n type: EntityType,\n id: EntityId,\n base: Record<string, unknown>,\n patch: Record<string, unknown> | undefined,\n metadata: EntitySyncMetadata,\n): EntitySnapshot<T> {\n const key = ek(type, id);\n const cached = snapshotCache.get(key);\n if (\n cached &&\n cached.base === base &&\n cached.patch === patch &&\n cached.metadata === metadata\n ) {\n return cached.snapshot as EntitySnapshot<T>;\n }\n\n const snapshot = {\n ...(patch ? { ...base, ...patch } : base),\n $synced: metadata.synced,\n $origin: metadata.origin,\n $updatedAt: metadata.updatedAt,\n } as EntitySnapshot<T>;\n\n snapshotCache.set(key, { base, patch, metadata, snapshot });\n return snapshot;\n}\n\n/** Creates an isolated, framework-neutral entity graph store. */\nexport function createGraphStore() {\n return createStore<GraphState>()(\n subscribeWithSelector(\n immer((set, get) => ({\n entities: {}, patches: {}, entityStates: {}, syncMetadata: {}, lists: {},\n\n upsertEntity: (type, id, data) => set((s) => {\n if (!s.entities[type]) s.entities[type] = {};\n const key = ek(type, id);\n // Route through the registered MergeStrategy (default = LWW shallow merge,\n // identical to the historical `{ ...prev, ...data }` behavior).\n const strategy = getMergeStrategy(type);\n const ctx: MergeContext = { type, id, origin: s.syncMetadata[key]?.origin ?? \"server\", updatedAt: Date.now() };\n s.entities[type][id] = strategy(s.entities[type][id], data, ctx);\n if (!s.syncMetadata[key]) s.syncMetadata[key] = defaultSyncMetadata();\n }),\n upsertEntities: (type, entries) => set((s) => {\n if (!s.entities[type]) s.entities[type] = {};\n const strategy = getMergeStrategy(type);\n for (const { id, data } of entries) {\n const key = ek(type, id);\n const ctx: MergeContext = { type, id, origin: s.syncMetadata[key]?.origin ?? \"server\", updatedAt: Date.now() };\n s.entities[type][id] = strategy(s.entities[type][id], data, ctx);\n if (!s.syncMetadata[key]) s.syncMetadata[key] = defaultSyncMetadata();\n }\n }),\n ingestFetchedList: (type, entries, options = {}) => set((s) => {\n const fetchedAt = Date.now();\n const ids = entries.map(({ id }) => id);\n const batches: FetchedEntityBatch[] = [\n { type, entries },\n ...(options.sideBatches ?? []),\n ];\n const origins = new Map<string, SyncOrigin>();\n\n for (const batch of batches) {\n if (!s.entities[batch.type]) s.entities[batch.type] = {};\n for (const { id } of batch.entries) {\n const key = ek(batch.type, id);\n if (!origins.has(key)) {\n origins.set(key, s.syncMetadata[key]?.origin ?? \"server\");\n }\n }\n }\n\n for (const batch of batches) {\n const strategy = getMergeStrategy(batch.type);\n for (const { id, data } of batch.entries) {\n const key = ek(batch.type, id);\n const ctx: MergeContext = {\n type: batch.type,\n id,\n origin: origins.get(key) ?? \"server\",\n updatedAt: fetchedAt,\n };\n s.entities[batch.type][id] = strategy(s.entities[batch.type][id], data, ctx);\n }\n }\n\n const completed = new Set<string>();\n for (const batch of batches) {\n for (const { id } of batch.entries) {\n const key = ek(batch.type, id);\n if (completed.has(key)) continue;\n completed.add(key);\n if (!s.entityStates[key]) s.entityStates[key] = defaultEntityState();\n s.entityStates[key].lastFetched = fetchedAt;\n s.entityStates[key].isFetching = false;\n s.entityStates[key].error = null;\n s.entityStates[key].stale = false;\n s.syncMetadata[key] = {\n ...(s.syncMetadata[key] ?? defaultSyncMetadata()),\n synced: true,\n origin: \"server\",\n updatedAt: fetchedAt,\n };\n }\n }\n\n const readDraftEntity = (id: EntityId): Record<string, unknown> | null => {\n const base = s.entities[type]?.[id];\n if (!base) return null;\n const patch = s.patches[type]?.[id];\n const metadata = s.syncMetadata[ek(type, id)] ?? defaultSyncMetadata();\n return {\n ...base,\n ...(patch ?? {}),\n $synced: metadata.synced,\n $origin: metadata.origin,\n $updatedAt: metadata.updatedAt,\n };\n };\n\n for (const target of options.lists ?? []) {\n const existing = s.lists[target.key] ?? defaultListState();\n const targetIds = target.ids ?? ids;\n const nextIds = target.mode === \"append\"\n ? Array.from(new Set([...existing.ids, ...targetIds]))\n : targetIds;\n s.lists[target.key] = {\n ...existing,\n ...(target.meta ?? {}),\n ids: nextIds,\n isFetching: false,\n isFetchingMore: false,\n error: null,\n lastError: null,\n stale: false,\n lastFetched: fetchedAt,\n };\n }\n\n for (const projection of options.projections ?? []) {\n const existing = s.lists[projection.key] ?? defaultListState();\n const nextIds = [...existing.ids];\n const { filter, sort, search } = projection.view;\n\n for (const id of new Set(ids)) {\n if (nextIds.includes(id)) continue;\n const entity = readDraftEntity(id);\n if (!entity) continue;\n const matches =\n (!filter || matchesFilter(entity, filter)) &&\n (!search?.query || matchesSearch(entity, search.query, search.fields));\n if (!matches) continue;\n\n if (sort && sort.length > 0) {\n const index = findInsertionIndex(entity, nextIds, readDraftEntity, sort);\n nextIds.splice(index, 0, id);\n } else {\n nextIds.unshift(id);\n }\n }\n\n s.lists[projection.key] = projection.completeFetch\n ? {\n ...existing,\n ids: nextIds,\n isFetching: false,\n isFetchingMore: false,\n error: null,\n lastError: null,\n stale: false,\n lastFetched: fetchedAt,\n }\n : { ...existing, ids: nextIds };\n }\n\n for (const key of options.finishListFetches ?? []) {\n if (!s.lists[key]) s.lists[key] = defaultListState();\n s.lists[key].isFetching = false;\n }\n }),\n replaceEntity: (type, id, data) => set((s) => {\n if (!s.entities[type]) s.entities[type] = {};\n s.entities[type][id] = data;\n const key = ek(type, id);\n if (!s.syncMetadata[key]) s.syncMetadata[key] = defaultSyncMetadata();\n }),\n removeEntity: (type, id) => set((s) => {\n delete s.entities[type]?.[id];\n delete s.patches[type]?.[id];\n delete s.entityStates[ek(type, id)];\n delete s.syncMetadata[ek(type, id)];\n }),\n patchEntity: (type, id, patch) => set((s) => {\n if (!s.patches[type]) s.patches[type] = {};\n s.patches[type][id] = { ...(s.patches[type][id] ?? {}), ...patch };\n }),\n unpatchEntity: (type, id, keys) => set((s) => {\n const p = s.patches[type]?.[id]; if (!p) return;\n for (const k of keys) delete p[k];\n }),\n clearPatch: (type, id) => set((s) => { delete s.patches[type]?.[id]; }),\n setEntityFetching: (type, id, fetching) => set((s) => {\n const k = ek(type, id);\n if (!s.entityStates[k]) s.entityStates[k] = defaultEntityState();\n s.entityStates[k].isFetching = fetching;\n }),\n setEntityError: (type, id, error) => set((s) => {\n const k = ek(type, id);\n if (!s.entityStates[k]) s.entityStates[k] = defaultEntityState();\n s.entityStates[k].error = error; s.entityStates[k].isFetching = false;\n }),\n setEntityFetched: (type, id) => set((s) => {\n const k = ek(type, id);\n if (!s.entityStates[k]) s.entityStates[k] = defaultEntityState();\n s.entityStates[k].lastFetched = Date.now();\n s.entityStates[k].isFetching = false;\n s.entityStates[k].error = null; s.entityStates[k].stale = false;\n s.syncMetadata[k] = { ...(s.syncMetadata[k] ?? defaultSyncMetadata()), synced: true, origin: \"server\", updatedAt: Date.now() };\n }),\n setEntityStale: (type, id, stale) => set((s) => {\n const k = ek(type, id);\n if (!s.entityStates[k]) s.entityStates[k] = defaultEntityState();\n s.entityStates[k].stale = stale;\n }),\n setEntitySyncMetadata: (type, id, metadata) => set((s) => {\n const k = ek(type, id);\n s.syncMetadata[k] = { ...(s.syncMetadata[k] ?? defaultSyncMetadata()), ...metadata };\n }),\n clearEntitySyncMetadata: (type, id) => set((s) => {\n delete s.syncMetadata[ek(type, id)];\n }),\n setListResult: (key, ids, meta) => set((s) => {\n const ex = s.lists[key] ?? defaultListState();\n s.lists[key] = { ...ex, ...meta, ids, isFetching: false, isFetchingMore: false, error: null, lastError: null, stale: false, lastFetched: Date.now() };\n }),\n appendListResult: (key, ids, meta) => set((s) => {\n const ex = s.lists[key] ?? defaultListState();\n s.lists[key] = { ...ex, ...meta, ids: Array.from(new Set([...ex.ids, ...ids])), isFetching: false, isFetchingMore: false, error: null, lastError: null, stale: false, lastFetched: Date.now() };\n }),\n prependListResult: (key, ids, meta) => set((s) => {\n const ex = s.lists[key] ?? defaultListState();\n s.lists[key] = { ...ex, ...(meta ?? {}), ids: Array.from(new Set([...ids, ...ex.ids])), isFetching: false, isFetchingMore: false, error: null, lastError: null, stale: false, lastFetched: Date.now() };\n }),\n removeIdFromAllLists: (_type, id) => set((s) => {\n for (const key of Object.keys(s.lists)) {\n const list = s.lists[key]; const idx = list.ids.indexOf(id);\n if (idx !== -1) { list.ids.splice(idx, 1); if (list.total !== null) list.total -= 1; }\n }\n }),\n insertIdInList: (key, id, position) => set((s) => {\n if (!s.lists[key]) s.lists[key] = defaultListState();\n const ids = s.lists[key].ids;\n const ex = ids.indexOf(id); if (ex !== -1) ids.splice(ex, 1);\n if (position === \"start\") ids.unshift(id);\n else if (position === \"end\") ids.push(id);\n else ids.splice(position, 0, id);\n }),\n setListFetching: (key, fetching) => set((s) => {\n if (!s.lists[key]) s.lists[key] = defaultListState();\n s.lists[key].isFetching = fetching;\n }),\n setListFetchingMore: (key, fetchingMore) => set((s) => {\n if (!s.lists[key]) s.lists[key] = defaultListState();\n s.lists[key].isFetchingMore = fetchingMore;\n }),\n setListError: (key, error, typed) => set((s) => {\n if (!s.lists[key]) s.lists[key] = defaultListState();\n s.lists[key].error = error;\n s.lists[key].lastError = typed ?? (error === null ? null : s.lists[key].lastError);\n s.lists[key].isFetching = false;\n s.lists[key].isFetchingMore = false;\n // Stamp lastFetched on failure too. Without this, the SWR\n // staleness check (`Date.now() - (lastFetched ?? 0) > staleTime`)\n // would return true on the next render and refire the fetcher\n // immediately — a 404/permanent error becomes an infinite\n // retry loop. With lastFetched stamped, the failure is treated\n // as a complete attempt and consumers see a stable `error` +\n // `isFetching: false`. They can manually `refetch()` if they\n // want to retry. Clearing `stale` also makes invalidateLists\n // the explicit retry mechanism, which is the contract we want.\n s.lists[key].lastFetched = Date.now();\n s.lists[key].stale = false;\n }),\n setListStale: (key, stale) => set((s) => {\n if (!s.lists[key]) s.lists[key] = defaultListState();\n s.lists[key].stale = stale;\n }),\n invalidateEntity: (type, id) => set((s) => {\n if (id) { const k = ek(type, id); if (s.entityStates[k]) s.entityStates[k].stale = true; }\n else { for (const k of Object.keys(s.entityStates)) if (k.startsWith(`${type}:`)) s.entityStates[k].stale = true; }\n }),\n invalidateLists: (matcher) => set((s) => {\n const pred = typeof matcher === \"string\" ? (k: string) => k.startsWith(matcher) : matcher;\n for (const key of Object.keys(s.lists)) if (pred(key)) s.lists[key].stale = true;\n }),\n invalidateType: (type) => { get().invalidateEntity(type); get().invalidateLists(type); },\n readEntity: <T>(type: EntityType, id: EntityId): T | null => {\n const s = get(); const base = s.entities[type]?.[id]; if (!base) return null;\n const patch = s.patches[type]?.[id];\n return (patch ? { ...base, ...patch } : base) as T;\n },\n readEntitySnapshot: <T>(type: EntityType, id: EntityId): EntitySnapshot<T & Record<string, unknown>> | null => {\n const s = get();\n const base = s.entities[type]?.[id];\n if (!base) {\n snapshotCache.delete(ek(type, id));\n return null;\n }\n const patch = s.patches[type]?.[id];\n const metadata = s.syncMetadata[ek(type, id)] ?? EMPTY_SYNC_METADATA;\n return readCachedEntitySnapshot<T & Record<string, unknown>>(\n type,\n id,\n base,\n patch,\n metadata,\n );\n },\n }))\n )\n );\n}\n\n/**\n * Default process-wide entity graph store. Framework bindings subscribe to\n * this vanilla store; non-React consumers use its `getState`, `setState`, and\n * `subscribe` methods directly.\n */\nexport const graphStore = createGraphStore();\n\nexport type GraphStore = ReturnType<typeof createGraphStore>;\n\n/**\n * @deprecated Import `graphStore` from core, or `useGraphStore` from the React\n * binding. This StoreApi-shaped alias remains for non-React 2.x migrations.\n */\nexport const useGraphStore = graphStore;\n","import type { GraphState } from \"../graph\";\nimport type {\n GraphDevtoolsChange,\n GraphDevtoolsCounts,\n GraphDevtoolsValueContext,\n GraphDevtoolsValuePolicy,\n} from \"./protocol\";\n\ntype GraphDataState = Pick<\n GraphState,\n \"entities\" | \"patches\" | \"entityStates\" | \"syncMetadata\" | \"lists\"\n>;\n\nfunction countRecordEntries(record: Record<string, unknown>): number {\n return Object.keys(record).length;\n}\n\nexport function collectGraphDevtoolsCounts(state: GraphDataState): GraphDevtoolsCounts {\n let entities = 0;\n let entityTypes = 0;\n for (const bucket of Object.values(state.entities)) {\n const count = Object.keys(bucket).length;\n if (count > 0) entityTypes += 1;\n entities += count;\n }\n\n let patchedEntities = 0;\n for (const bucket of Object.values(state.patches)) {\n for (const patch of Object.values(bucket)) {\n if (Object.keys(patch).length > 0) patchedEntities += 1;\n }\n }\n\n let listMemberships = 0;\n let fetching = 0;\n let stale = 0;\n let errors = 0;\n for (const list of Object.values(state.lists)) {\n listMemberships += list.ids.length;\n if (list.isFetching || list.isFetchingMore) fetching += 1;\n if (list.stale) stale += 1;\n if (list.error !== null || list.lastError !== null) errors += 1;\n }\n for (const entityState of Object.values(state.entityStates)) {\n if (entityState.isFetching) fetching += 1;\n if (entityState.stale) stale += 1;\n if (entityState.error !== null) errors += 1;\n }\n\n return {\n entityTypes,\n entities,\n patchedEntities,\n entityStates: countRecordEntries(state.entityStates),\n syncMetadata: countRecordEntries(state.syncMetadata),\n lists: countRecordEntries(state.lists),\n listMemberships,\n fetching,\n stale,\n errors,\n };\n}\n\nfunction withValues(\n change: Omit<GraphDevtoolsChange, \"valueState\" | \"before\" | \"after\">,\n before: unknown,\n after: unknown,\n policy: GraphDevtoolsValuePolicy,\n storeId: string,\n): GraphDevtoolsChange {\n if (policy.mode !== \"include\") return { ...change, valueState: \"hidden-by-policy\" };\n const redact = policy.redact ?? ((value: unknown) => value);\n const baseContext: Omit<GraphDevtoolsValueContext, \"side\"> = {\n storeId,\n category: change.category,\n key: change.key,\n ...(change.id !== undefined ? { id: change.id } : {}),\n fieldPath: [],\n destination: \"history\",\n };\n const projectValue = (value: unknown, side: GraphDevtoolsValueContext[\"side\"]) => {\n try {\n return { value: toGraphDevtoolsTransportValue(redact(value, { ...baseContext, side })), failed: false };\n } catch {\n return { value: { $type: \"redaction-error\" }, failed: true };\n }\n };\n const projectedBefore = before !== undefined ? projectValue(before, \"before\") : undefined;\n const projectedAfter = after !== undefined ? projectValue(after, \"after\") : undefined;\n return {\n ...change,\n valueState:\n projectedBefore?.failed || projectedAfter?.failed\n ? \"redaction-error\"\n : policy.redact\n ? \"redacted\"\n : \"included\",\n ...(projectedBefore ? { before: projectedBefore.value } : {}),\n ...(projectedAfter ? { after: projectedAfter.value } : {}),\n };\n}\n\n/** Convert graph values into deterministic JSON-safe DevTools payloads. */\nexport function toGraphDevtoolsTransportValue(value: unknown, seen = new WeakSet<object>()): unknown {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return value;\n if (typeof value === \"number\") return Number.isFinite(value) ? value : String(value);\n if (typeof value === \"bigint\") return { $type: \"bigint\", value: value.toString() };\n if (typeof value === \"undefined\") return { $type: \"undefined\" };\n if (typeof value === \"function\" || typeof value === \"symbol\") return { $type: typeof value };\n if (value instanceof Date) return { $type: \"date\", value: value.toISOString() };\n if (value instanceof Error) return { $type: \"error\", name: value.name, message: value.message };\n if (typeof value !== \"object\") return String(value);\n if (seen.has(value)) return { $type: \"circular\" };\n seen.add(value);\n try {\n if (Array.isArray(value)) return value.map((item) => toGraphDevtoolsTransportValue(item, seen));\n const normalized: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n normalized[key] = toGraphDevtoolsTransportValue(item, seen);\n }\n return normalized;\n } finally {\n seen.delete(value);\n }\n}\n\nfunction actionFor(before: unknown, after: unknown): GraphDevtoolsChange[\"action\"] {\n if (before === undefined) return \"added\";\n if (after === undefined) return \"removed\";\n return \"updated\";\n}\n\nfunction diffNestedRecords(\n category: \"entity\" | \"patch\",\n before: Record<string, Record<string, Record<string, unknown>>>,\n after: Record<string, Record<string, Record<string, unknown>>>,\n policy: GraphDevtoolsValuePolicy,\n storeId: string,\n): GraphDevtoolsChange[] {\n const changes: GraphDevtoolsChange[] = [];\n for (const type of new Set([...Object.keys(before), ...Object.keys(after)])) {\n const beforeBucket = before[type] ?? {};\n const afterBucket = after[type] ?? {};\n if (beforeBucket === afterBucket) continue;\n for (const id of new Set([...Object.keys(beforeBucket), ...Object.keys(afterBucket)])) {\n const previous = beforeBucket[id];\n const current = afterBucket[id];\n if (previous === current) continue;\n changes.push(withValues({\n category,\n action: actionFor(previous, current),\n key: type,\n id,\n }, previous, current, policy, storeId));\n }\n }\n return changes;\n}\n\nfunction diffFlatRecords(\n category: \"entity-state\" | \"sync\",\n before: Record<string, unknown>,\n after: Record<string, unknown>,\n policy: GraphDevtoolsValuePolicy,\n storeId: string,\n): GraphDevtoolsChange[] {\n const changes: GraphDevtoolsChange[] = [];\n if (before === after) return changes;\n for (const key of new Set([...Object.keys(before), ...Object.keys(after)])) {\n const previous = before[key];\n const current = after[key];\n if (previous === current) continue;\n changes.push(withValues({\n category,\n action: actionFor(previous, current),\n key,\n }, previous, current, policy, storeId));\n }\n return changes;\n}\n\nfunction diffLists(\n before: GraphState[\"lists\"],\n after: GraphState[\"lists\"],\n policy: GraphDevtoolsValuePolicy,\n storeId: string,\n): GraphDevtoolsChange[] {\n const changes: GraphDevtoolsChange[] = [];\n if (before === after) return changes;\n for (const key of new Set([...Object.keys(before), ...Object.keys(after)])) {\n const previous = before[key];\n const current = after[key];\n if (previous === current) continue;\n changes.push(withValues({\n category: \"list\",\n action: actionFor(previous, current),\n key,\n beforeCount: previous?.ids.length ?? 0,\n afterCount: current?.ids.length ?? 0,\n }, previous, current, policy, storeId));\n }\n return changes;\n}\n\n/**\n * Project one Zustand publication into semantic graph effects. This is the\n * authoritative boundary because it also observes direct `store.setState`\n * hydration, rollback, restore, and external adapter writes.\n */\nexport function projectGraphDevtoolsChanges(\n before: GraphDataState,\n after: GraphDataState,\n policy: GraphDevtoolsValuePolicy,\n storeId: string,\n): GraphDevtoolsChange[] {\n return [\n ...diffNestedRecords(\"entity\", before.entities, after.entities, policy, storeId),\n ...diffNestedRecords(\"patch\", before.patches, after.patches, policy, storeId),\n ...diffFlatRecords(\"entity-state\", before.entityStates, after.entityStates, policy, storeId),\n ...diffFlatRecords(\"sync\", before.syncMetadata, after.syncMetadata, policy, storeId),\n ...diffLists(before.lists, after.lists, policy, storeId),\n ];\n}\n","import {\n EMPTY_ENTITY_STATE,\n EMPTY_SYNC_METADATA,\n type GraphState,\n} from \"../graph\";\nimport type {\n GraphDevtoolsChange,\n GraphDevtoolsEntityDirtyReason,\n GraphDevtoolsEntityRecord,\n GraphDevtoolsEntityRecordsSnapshot,\n GraphDevtoolsValueContext,\n GraphDevtoolsValuePolicy,\n} from \"./protocol\";\nimport {\n GRAPH_DEVTOOLS_PROTOCOL,\n GRAPH_DEVTOOLS_PROTOCOL_VERSION,\n} from \"./protocol\";\nimport { toGraphDevtoolsTransportValue } from \"./projection\";\n\ntype GraphInspectionState = Pick<\n GraphState,\n \"entities\" | \"patches\" | \"entityStates\" | \"syncMetadata\"\n>;\n\ntype GraphEntityIdentityState = Pick<GraphState, \"entities\" | \"patches\">;\n\nfunction wireEntityKey(type: string, id: string): string {\n return `${type}:${id}`;\n}\n\n/** Collision-free key for controller-owned maps; never exposed as a wire identity. */\nexport function graphDevtoolsEntityIdentityKey(type: string, id: string): string {\n return JSON.stringify([type, id]);\n}\n\nexport function parseGraphDevtoolsEntityIdentityKey(\n key: string,\n): { type: string; id: string } | null {\n try {\n const value: unknown = JSON.parse(key);\n if (\n Array.isArray(value) && value.length === 2 &&\n typeof value[0] === \"string\" && typeof value[1] === \"string\"\n ) return { type: value[0], id: value[1] };\n } catch {\n // Internal map keys may be absent or stale; never surface parser failures.\n }\n return null;\n}\n\nfunction splitEntityKey(key: string): { type: string; id: string } | null {\n const separator = key.indexOf(\":\");\n if (separator < 1 || separator === key.length - 1) return null;\n return { type: key.slice(0, separator), id: key.slice(separator + 1) };\n}\n\n/** Resolve legacy `type:id` metadata keys against actual graph buckets first. */\nexport function graphDevtoolsEntityIdentitiesForStateKey(\n state: GraphEntityIdentityState,\n key: string,\n): Array<{ type: string; id: string }> {\n const matches: Array<{ type: string; id: string }> = [];\n const types = new Set([...Object.keys(state.entities), ...Object.keys(state.patches)]);\n for (const type of types) {\n const ids = new Set([\n ...Object.keys(state.entities[type] ?? {}),\n ...Object.keys(state.patches[type] ?? {}),\n ]);\n for (const id of ids) {\n if (wireEntityKey(type, id) === key) matches.push({ type, id });\n }\n }\n if (matches.length > 0) return matches;\n const fallback = splitEntityKey(key);\n return fallback ? [fallback] : [];\n}\n\nfunction toIsoTimestamp(value: number | null): string | null {\n return value === null ? null : new Date(value).toISOString();\n}\n\nfunction compareEntityIdentity(\n left: { type: string; id: string },\n right: { type: string; id: string },\n): number {\n if (left.type !== right.type) return left.type < right.type ? -1 : 1;\n if (left.id === right.id) return 0;\n return left.id < right.id ? -1 : 1;\n}\n\nfunction collectEntityIdentities(state: GraphInspectionState): Array<{ type: string; id: string }> {\n const identities = new Map<string, { type: string; id: string }>();\n for (const [type, bucket] of Object.entries(state.entities)) {\n for (const id of Object.keys(bucket)) {\n identities.set(graphDevtoolsEntityIdentityKey(type, id), { type, id });\n }\n }\n for (const [type, bucket] of Object.entries(state.patches)) {\n for (const id of Object.keys(bucket)) {\n identities.set(graphDevtoolsEntityIdentityKey(type, id), { type, id });\n }\n }\n for (const key of [...Object.keys(state.entityStates), ...Object.keys(state.syncMetadata)]) {\n for (const identity of graphDevtoolsEntityIdentitiesForStateKey(state, key)) {\n identities.set(graphDevtoolsEntityIdentityKey(identity.type, identity.id), identity);\n }\n }\n return [...identities.values()].sort(compareEntityIdentity);\n}\n\nfunction dirtyReasonsFor(\n canonical: Record<string, unknown> | undefined,\n patch: Record<string, unknown> | undefined,\n synced: boolean,\n): GraphDevtoolsEntityDirtyReason[] {\n const reasons: GraphDevtoolsEntityDirtyReason[] = [];\n for (const field of Object.keys(patch ?? {}).sort()) {\n reasons.push({\n kind: \"local-patch\",\n field,\n change: canonical && Object.hasOwn(canonical, field) ? \"changed\" : \"added\",\n });\n }\n if (!synced) {\n reasons.push({ kind: \"sync-state\", field: null, change: \"unsynced\" });\n }\n return reasons;\n}\n\nexport function projectGraphDevtoolsInspectionValue(\n value: unknown,\n policy: GraphDevtoolsValuePolicy,\n context: Omit<GraphDevtoolsValueContext, \"fieldPath\" | \"side\" | \"destination\">,\n): unknown {\n if (policy.mode !== \"include\") return { $type: \"hidden-by-policy\" };\n try {\n const projected = policy.redact\n ? policy.redact(value, {\n ...context,\n fieldPath: [],\n side: \"after\",\n destination: \"inspection\",\n })\n : value;\n return toGraphDevtoolsTransportValue(projected);\n } catch {\n return { $type: \"redaction-error\" };\n }\n}\n\nfunction recordFor(\n state: GraphInspectionState,\n storeId: string,\n type: string,\n id: string,\n revisions: ReadonlyMap<string, number>,\n valuePolicy: GraphDevtoolsValuePolicy,\n): GraphDevtoolsEntityRecord {\n const key = wireEntityKey(type, id);\n const identityKey = graphDevtoolsEntityIdentityKey(type, id);\n const canonical = state.entities[type]?.[id];\n const storedPatch = state.patches[type]?.[id];\n const patch = storedPatch && Object.keys(storedPatch).length > 0 ? storedPatch : undefined;\n const entityState = state.entityStates[key] ?? EMPTY_ENTITY_STATE;\n const sync = state.syncMetadata[key] ?? EMPTY_SYNC_METADATA;\n const dirtyReasons = dirtyReasonsFor(canonical, patch, sync.synced);\n\n return {\n key,\n type,\n id,\n presence: canonical ? \"present\" : \"missing-canonical\",\n canonical: canonical\n ? projectGraphDevtoolsInspectionValue(canonical, valuePolicy, { storeId, category: \"entity\", key: type, id })\n : null,\n patch: patch\n ? projectGraphDevtoolsInspectionValue(patch, valuePolicy, { storeId, category: \"patch\", key: type, id })\n : null,\n merged: canonical\n ? projectGraphDevtoolsInspectionValue(\n { ...canonical, ...(patch ?? {}) },\n valuePolicy,\n { storeId, category: \"entity\", key: type, id },\n )\n : null,\n dirty: dirtyReasons.length > 0,\n dirtyReasons,\n entityState: {\n isFetching: entityState.isFetching,\n lastFetchedAt: toIsoTimestamp(entityState.lastFetched),\n stale: entityState.stale,\n error: entityState.error === null\n ? null\n : {\n kind: \"entity-fetch\",\n message: entityState.error,\n retryable: null,\n },\n },\n sync: {\n synced: sync.synced,\n origin: sync.origin,\n updatedAt: toIsoTimestamp(sync.updatedAt),\n },\n revision: revisions.get(identityKey) ?? 0,\n viewIds: [],\n };\n}\n\n/** Project the current entity inspection model without retaining graph values. */\nexport function projectGraphDevtoolsEntityRecords(\n state: GraphInspectionState,\n storeId: string,\n revisions: ReadonlyMap<string, number>,\n valuePolicy: GraphDevtoolsValuePolicy = { mode: \"metadata-only\" },\n viewIdsByEntity: ReadonlyMap<string, readonly string[]> = new Map(),\n): GraphDevtoolsEntityRecordsSnapshot {\n return {\n protocol: GRAPH_DEVTOOLS_PROTOCOL,\n version: GRAPH_DEVTOOLS_PROTOCOL_VERSION,\n storeId,\n capturedAt: new Date().toISOString(),\n entityRecords: collectEntityIdentities(state).map(({ type, id }) => {\n const record = recordFor(state, storeId, type, id, revisions, valuePolicy);\n return {\n ...record,\n viewIds: [...(viewIdsByEntity.get(graphDevtoolsEntityIdentityKey(type, id)) ?? [])],\n };\n }),\n };\n}\n\n/** Advance each touched entity exactly once for one completed store publication. */\nexport function advanceGraphDevtoolsEntityRevisions(\n changes: ReadonlyArray<GraphDevtoolsChange>,\n revisions: Map<string, number>,\n state: GraphEntityIdentityState,\n valueRevisions?: Map<string, number>,\n): void {\n const touched = new Set<string>();\n const valueTouched = new Set<string>();\n for (const change of changes) {\n if ((change.category === \"entity\" || change.category === \"patch\") && change.id !== undefined) {\n const key = graphDevtoolsEntityIdentityKey(change.key, change.id);\n touched.add(key);\n valueTouched.add(key);\n continue;\n }\n if (change.category === \"entity-state\" || change.category === \"sync\") {\n for (const identity of graphDevtoolsEntityIdentitiesForStateKey(state, change.key)) {\n touched.add(graphDevtoolsEntityIdentityKey(identity.type, identity.id));\n }\n }\n }\n for (const key of touched) revisions.set(key, (revisions.get(key) ?? 0) + 1);\n if (valueRevisions) {\n for (const key of valueTouched) valueRevisions.set(key, (valueRevisions.get(key) ?? 0) + 1);\n }\n}\n","import { graphStore } from \"./graph\";\nimport type { EntityType, EntityId, GraphStore } from \"./graph\";\nimport {\n emitLegacyDevtoolsEvent,\n subscribeLegacyDevtoolsEvent,\n type LegacyDevtoolsEvent,\n} from \"./legacy-devtools\";\n\n/**\n * Process-wide defaults for stale times, retries, and background revalidation.\n * Keeps hook signatures small: `useEntity` / `useEntityList` merge these with per-query overrides.\n */\nexport interface EngineOptions {\n defaultStaleTime?: number;\n /** Max age (`Date.now() - lastFetched`) for evicting entities with zero subscribers during GC. */\n defaultGcTime?: number;\n /** Interval between GC passes when the collector is active (default 60s). */\n gcInterval?: number;\n maxRetries?: number;\n retryBaseDelay?: number;\n revalidateOnFocus?: boolean;\n revalidateOnReconnect?: boolean;\n}\n\n/**\n * Declarative **instruction** for loading one entity: wire transport (`fetch`), normalization, and graph writes.\n * Hooks pass this to `fetchEntity`; the graph remains source of truth after success.\n */\nexport interface EntityQueryOptions<TRaw, TEntity extends object> {\n type: EntityType;\n id: EntityId | null | undefined;\n fetch: (id: EntityId) => Promise<TRaw>;\n normalize: (raw: TRaw) => TEntity;\n idField?: string;\n sideEffects?: (raw: TRaw, store: GraphStore) => void;\n staleTime?: number;\n enabled?: boolean;\n onSuccess?: (entity: TEntity) => void;\n onError?: (error: Error) => void;\n}\n\n/** Cursor/page knobs passed through to list `fetch` implementations (REST, GraphQL, etc.). */\nexport interface ListFetchParams {\n cursor?: string;\n page?: number;\n pageSize?: number;\n params?: Record<string, unknown>;\n}\n\n/**\n * Normalized list page shape from any backend. Items are mapped through `normalize` into `{ id, data }` upserts — the list stores ids only.\n */\nexport interface ListResponse<T> {\n items: T[];\n total?: number | null;\n nextCursor?: string | null;\n prevCursor?: string;\n hasNextPage?: boolean;\n hasPrevPage?: boolean;\n page?: number;\n pageSize?: number;\n}\n\n/**\n * Declarative **instruction** for a collection query: stable `queryKey`, fetcher, and per-row normalization into the graph.\n * `mode` controls whether a fetch replaces ids or appends (infinite scroll) when used with load-more.\n */\nexport interface ListQueryOptions<TRaw, TEntity extends object> {\n type: EntityType;\n queryKey: unknown[];\n /**\n * Inline fetcher (deprecated 1.x REST form). Optional in 2.0: pure graph\n * subscriptions for Tier-A PGlite/Electric entities pass no fetcher — the\n * graph is hydrated out-of-band and the hook only joins ids → entities.\n * When omitted, `fetchList` is a no-op and the hook is read-only.\n */\n fetch?: (params: ListFetchParams) => Promise<ListResponse<TRaw>>;\n /** Row normalizer. Optional alongside `fetch` (graph-only callers omit both). */\n normalize?: (raw: TRaw) => { id: EntityId; data: TEntity };\n sideEffects?: (items: TRaw[], store: GraphStore) => void;\n mode?: \"replace\" | \"append\";\n staleTime?: number;\n enabled?: boolean;\n onSuccess?: (result: ListResponse<TRaw>) => void;\n onError?: (error: Error) => void;\n}\n\n/**\n * Deterministic string key for list queries so object order in nested keys does not create duplicate cache entries.\n * @param key - Hook-provided query key array (serializable values)\n */\nexport function serializeKey(key: unknown[]): string {\n return JSON.stringify(key, (_, v) =>\n v && typeof v === \"object\" && !Array.isArray(v)\n ? Object.fromEntries(Object.entries(v as Record<string, unknown>).sort()) : v);\n}\n\nfunction sleep(ms: number) { return new Promise((r) => setTimeout(r, ms)); }\n\nconst inflightByStore = new WeakMap<GraphStore, Map<string, Promise<unknown>>>();\n\nfunction inflightFor(store: GraphStore) {\n let inflight = inflightByStore.get(store);\n if (!inflight) {\n inflight = new Map();\n inflightByStore.set(store, inflight);\n }\n return inflight;\n}\n/**\n * Collapse concurrent identical requests into one Promise (prevents stampedes when many components mount the same entity/list).\n * @param key - Logical dedupe key (e.g. `type:id` or serialized list key)\n * @param fn - Async work that performs the fetch + graph writes\n */\nexport function dedupe<T>(key: string, fn: () => Promise<T>, store: GraphStore = graphStore): Promise<T> {\n const inflight = inflightFor(store);\n if (inflight.has(key)) return inflight.get(key) as Promise<T>;\n const p = fn().finally(() => inflight.delete(key));\n inflight.set(key, p); return p;\n}\n\nconst globalSubscriberStatsListeners = new Set<() => void>();\nconst subscriberStatsListenersByStore = new WeakMap<GraphStore, Set<() => void>>();\nfunction subscriberStatsListenersFor(store: GraphStore) {\n let listeners = subscriberStatsListenersByStore.get(store);\n if (!listeners) {\n listeners = new Set();\n subscriberStatsListenersByStore.set(store, listeners);\n }\n return listeners;\n}\nfunction emitSubscriberStatsChange(store: GraphStore) {\n for (const cb of new Set([\n ...globalSubscriberStatsListeners,\n ...subscriberStatsListenersFor(store),\n ])) cb();\n}\n\nconst subscribersByStore = new WeakMap<GraphStore, Map<string, Set<symbol>>>();\n\nfunction subscribersFor(store: GraphStore) {\n let subscribers = subscribersByStore.get(store);\n if (!subscribers) {\n subscribers = new Map();\n subscribersByStore.set(store, subscribers);\n }\n return subscribers;\n}\n/**\n * Ref-count graph interest for a subscriber key (`${type}:${id}`). Background revalidation skips keys with zero subscribers.\n * @returns Opaque token required for `unregisterSubscriber`\n */\nexport function registerSubscriber(key: string, store: GraphStore = graphStore): symbol {\n const subscribers = subscribersFor(store);\n const token = Symbol(key);\n if (!subscribers.has(key)) subscribers.set(key, new Set());\n subscribers.get(key)!.add(token);\n emitSubscriberStatsChange(store);\n return token;\n}\n/** Pair with `registerSubscriber` on unmount so idle entities stop refetching. */\nexport function unregisterSubscriber(key: string, token: symbol, store: GraphStore = graphStore) {\n const subscribers = subscribersFor(store);\n const set = subscribers.get(key);\n if (!set) return;\n set.delete(token);\n if (set.size === 0) subscribers.delete(key);\n emitSubscriberStatsChange(store);\n}\n/** Used by the engine to avoid background work for keys nothing in the tree is observing. */\nexport function hasSubscribers(key: string, store: GraphStore = graphStore) {\n return (subscribersFor(store).get(key)?.size ?? 0) > 0;\n}\n\nconst DEFAULT_OPTIONS: Required<EngineOptions> = {\n defaultStaleTime: 30_000,\n defaultGcTime: 300_000,\n gcInterval: 60_000,\n maxRetries: 3,\n retryBaseDelay: 1_000,\n revalidateOnFocus: true,\n revalidateOnReconnect: true,\n};\nlet engineOptions: Required<EngineOptions> = { ...DEFAULT_OPTIONS };\n\n/**\n * Subscribe to ref-count changes for `registerSubscriber` / `unregisterSubscriber`.\n * Used by `useGraphDevTools` so subscriber totals update without graph mutations.\n */\nexport function subscribeSubscriberStats(onChange: () => void, store?: GraphStore) {\n const listeners = store ? subscriberStatsListenersFor(store) : globalSubscriberStatsListeners;\n listeners.add(onChange);\n return () => listeners.delete(onChange);\n}\n\n/** Total active entity subscriber tokens across all keys (sum of ref-counts). */\nexport function getActiveSubscriberCount(store: GraphStore = graphStore): number {\n let n = 0;\n for (const set of subscribersFor(store).values()) n += set.size;\n return n;\n}\n\n// ── DevtoolsEvent + tap (W3 — entity-engine-devtools-tap capability) ────────\n//\n// In-process push stream of mutating graph events for dev tooling. The\n// Entity Explorer (W5+) subscribes here for its Events tab and to keep the\n// Tree tab live without polling.\n//\n// This deprecated stream preserves the original graph-transaction op-site\n// contract without loading the optional v1 controller into the root bundle.\n// It retains no independent history or cursor.\n\n/**\n * Discriminated union of devtools events.\n *\n * New inspection surfaces should use the versioned `./devtools` subpath.\n */\nexport type DevtoolsEvent = LegacyDevtoolsEvent;\n\ntype DevtoolsListener = (event: DevtoolsEvent) => void;\n\n/**\n * Subscribe to the devtools event stream.\n *\n * - Returns an `UnsubscribeFn` that removes this listener.\n * - Idempotent: subscribing the same function reference twice tracks it once\n * (Set semantics).\n * - Throwing listeners do NOT block delivery to other listeners; the error is\n * logged via `console.warn` and dispatch continues.\n * - Re-entrancy safe: listeners that subscribe/unsubscribe during dispatch\n * affect future events only, not the in-flight one.\n */\nexport function subscribeDevtoolsEvent(cb: DevtoolsListener): () => void {\n return subscribeLegacyDevtoolsEvent(cb);\n}\n\n/**\n * Internal deprecated synthetic-injection seam retained for compatibility.\n *\n * NOT re-exported from `src/index.ts` — the public surface is\n * `subscribeDevtoolsEvent` only.\n */\nexport function notifyDevtools(event: DevtoolsEvent): void {\n emitLegacyDevtoolsEvent(event);\n}\n\nconst gcIntervalsByStore = new Map<GraphStore, ReturnType<typeof setInterval>>();\n\n/**\n * One GC pass: removes entities that are unobserved, older than `defaultGcTime`, not fetching,\n * and have no non-empty local patches; then strips their ids from all lists.\n */\nfunction runGarbageCollection(storeApi: GraphStore = graphStore): void {\n const store = storeApi.getState();\n const { defaultGcTime: gcTime } = getEngineOptions();\n const now = Date.now();\n const toRemove: Array<{ type: EntityType; id: EntityId }> = [];\n\n for (const type of Object.keys(store.entities)) {\n const bucket = store.entities[type];\n if (!bucket) continue;\n for (const id of Object.keys(bucket)) {\n const key = `${type}:${id}`;\n if (hasSubscribers(key, storeApi)) continue;\n const patch = store.patches[type]?.[id];\n if (patch !== undefined && Object.keys(patch).length > 0) continue;\n const entityState = store.entityStates[key];\n if (entityState?.isFetching) continue;\n const lastFetched = entityState?.lastFetched;\n if (lastFetched == null) continue;\n if (now - lastFetched <= gcTime) continue;\n toRemove.push({ type, id });\n }\n }\n\n for (const { type, id } of toRemove) {\n store.removeEntity(type, id);\n store.removeIdFromAllLists(type, id);\n }\n}\n\n/**\n * Stops the periodic garbage-collection timer for the selected graph.\n */\nexport function stopGarbageCollector(storeApi: GraphStore = graphStore): void {\n const intervalId = gcIntervalsByStore.get(storeApi);\n if (intervalId != null && typeof clearInterval !== \"undefined\") {\n clearInterval(intervalId);\n gcIntervalsByStore.delete(storeApi);\n }\n}\n\n/**\n * Starts periodic garbage collection using current `getEngineOptions().gcInterval`.\n * Stops any previous interval first. No-ops during SSR (`window` is undefined) or without `setInterval`.\n * @returns Disposer that stops this graph's collector.\n */\nexport function startGarbageCollector(storeApi: GraphStore = graphStore): () => void {\n stopGarbageCollector(storeApi);\n if (typeof window === \"undefined\" || typeof setInterval === \"undefined\") return () => {};\n const intervalId = setInterval(\n () => runGarbageCollection(storeApi),\n getEngineOptions().gcInterval,\n );\n gcIntervalsByStore.set(storeApi, intervalId);\n return () => stopGarbageCollector(storeApi);\n}\n\nfunction restartGarbageCollector(storeApi: GraphStore = graphStore) {\n startGarbageCollector(storeApi);\n}\n\n/** Override global engine behavior (typically once at app bootstrap). Restarts GC with merged options. */\nexport function configureEngine(opts: EngineOptions) {\n engineOptions = { ...DEFAULT_OPTIONS, ...opts };\n const activeStores = [...gcIntervalsByStore.keys()];\n if (activeStores.length === 0) restartGarbageCollector();\n else for (const storeApi of activeStores) restartGarbageCollector(storeApi);\n}\n/** Read merged engine options; hooks use this for default `staleTime` and retry behavior. */\nexport function getEngineOptions() { return engineOptions; }\n\n/**\n * Run a single-entity fetch with dedupe, retries, normalization, and graph updates.\n * Call from hooks/adapters — not from presentational components.\n */\nexport async function fetchEntity<TRaw, TEntity extends object>(\n opts: EntityQueryOptions<TRaw, TEntity>, engineOpts: Required<EngineOptions>, storeApi: GraphStore = graphStore\n) {\n const { type, id, fetch, normalize, sideEffects, idField = \"id\" } = opts;\n if (!id) return;\n storeApi.getState().setEntityFetching(type, id, true);\n const attempt = async (retries: number): Promise<void> => {\n try {\n const raw = await fetch(id);\n const normalized = normalize(raw);\n const resolvedId = (normalized as Record<string, unknown>)[idField] as EntityId ?? id;\n storeApi.getState().upsertEntity(type, resolvedId, normalized as Record<string, unknown>);\n storeApi.getState().setEntityFetched(type, resolvedId);\n if (sideEffects) sideEffects(raw, storeApi);\n opts.onSuccess?.(normalized);\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n if (retries < engineOpts.maxRetries) { await sleep(engineOpts.retryBaseDelay * Math.pow(2, retries)); return attempt(retries + 1); }\n storeApi.getState().setEntityError(type, id, error.message);\n opts.onError?.(error);\n }\n };\n await dedupe(`${type}:${id}`, () => attempt(0), storeApi);\n}\n\n/**\n * Fetch a list page: upserts all rows, writes ids to the list key, supports append mode for pagination.\n * @param isLoadMore - When true, uses a separate dedupe key and `appendListResult` / `setListFetchingMore`.\n */\nexport async function fetchList<TRaw, TEntity extends object>(\n opts: ListQueryOptions<TRaw, TEntity>, params: ListFetchParams, engineOpts: Required<EngineOptions>, isLoadMore = false, storeApi: GraphStore = graphStore\n) {\n const { type, queryKey, fetch, normalize, sideEffects, mode = \"replace\" } = opts;\n const key = serializeKey(queryKey);\n const store = storeApi.getState();\n // Graph-only subscription (Tier-A PGlite/Electric): no inline fetcher. The\n // graph is hydrated out-of-band, so there is nothing to fetch here.\n if (!fetch || !normalize) return;\n if (isLoadMore) store.setListFetchingMore(key, true);\n else store.setListFetching(key, true);\n const attempt = async (retries: number): Promise<void> => {\n try {\n const response = await fetch(params);\n const normalized = response.items.map(normalize);\n const meta = { total: response.total ?? null, nextCursor: response.nextCursor ?? null, prevCursor: response.prevCursor ?? null, hasNextPage: response.hasNextPage ?? !!response.nextCursor, hasPrevPage: response.hasPrevPage ?? !!response.prevCursor, currentPage: response.page ?? null, pageSize: response.pageSize ?? null };\n storeApi.getState().ingestFetchedList(\n type,\n normalized.map(({ id, data }) => ({ id, data: data as Record<string, unknown> })),\n { lists: [{ key, mode: mode === \"append\" && isLoadMore ? \"append\" : \"replace\", meta }] },\n );\n if (sideEffects) sideEffects(response.items, storeApi);\n opts.onSuccess?.(response);\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n if (retries < engineOpts.maxRetries) { await sleep(engineOpts.retryBaseDelay * Math.pow(2, retries)); return attempt(retries + 1); }\n storeApi.getState().setListError(key, error.message);\n opts.onError?.(error);\n }\n };\n await dedupe(isLoadMore ? `${key}:more` : key, () => attempt(0), storeApi);\n}\n\ninterface GlobalListenerAttachment {\n references: number;\n dispose: () => void;\n}\n\nconst globalListenerAttachments = new WeakMap<GraphStore, GlobalListenerAttachment>();\n\nfunction releaseGlobalListenerAttachment(\n storeApi: GraphStore,\n attachment: GlobalListenerAttachment,\n): () => void {\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const current = globalListenerAttachments.get(storeApi);\n if (current !== attachment) return;\n current.references -= 1;\n if (current.references > 0) return;\n current.dispose();\n globalListenerAttachments.delete(storeApi);\n };\n}\n\n/**\n * Opt-in window listeners that mark **subscribed** entities stale on focus/reconnect so hooks can SWR-refetch.\n * Reference-counted per graph and safe for SSR (no-ops without `window`).\n * @returns Disposer that releases this attachment and removes listeners plus GC when the last owner releases it.\n */\nexport function attachGlobalListeners(storeApi: GraphStore = graphStore): () => void {\n if (typeof window === \"undefined\") return () => {};\n const existing = globalListenerAttachments.get(storeApi);\n if (existing) {\n existing.references += 1;\n return releaseGlobalListenerAttachment(storeApi, existing);\n }\n\n const stopGc = startGarbageCollector(storeApi);\n const revalidateAll = () => {\n const state = storeApi.getState();\n for (const key of subscribersFor(storeApi).keys()) {\n if (!hasSubscribers(key, storeApi)) continue;\n const colonIdx = key.indexOf(\":\");\n if (colonIdx === -1) continue;\n const type = key.slice(0, colonIdx);\n const id = key.slice(colonIdx + 1);\n state.setEntityStale(type, id, true);\n }\n };\n const revalidateWhenVisible = () => {\n if (document.visibilityState === \"visible\") revalidateAll();\n };\n const revalidateOnFocus = engineOptions.revalidateOnFocus;\n const revalidateOnReconnect = engineOptions.revalidateOnReconnect;\n if (revalidateOnFocus) {\n window.addEventListener(\"visibilitychange\", revalidateWhenVisible);\n window.addEventListener(\"focus\", revalidateAll);\n }\n if (revalidateOnReconnect) window.addEventListener(\"online\", revalidateAll);\n\n const attachment: GlobalListenerAttachment = {\n references: 1,\n dispose: () => {\n if (revalidateOnFocus) {\n window.removeEventListener(\"visibilitychange\", revalidateWhenVisible);\n window.removeEventListener(\"focus\", revalidateAll);\n }\n if (revalidateOnReconnect) {\n window.removeEventListener(\"online\", revalidateAll);\n }\n stopGc();\n },\n };\n globalListenerAttachments.set(storeApi, attachment);\n return releaseGlobalListenerAttachment(storeApi, attachment);\n}\n","import { graphStore } from \"../graph\";\nimport { serializeKey } from \"../engine\";\nimport type { EntityType, EntityId, GraphStore } from \"../graph\";\n\nexport type RelationCardinality = \"belongsTo\" | \"hasMany\" | \"manyToMany\";\n/**\n * FK edge: this entity points at one parent row. Used to invalidate parent aggregates and optional list keys when the FK changes.\n */\nexport interface BelongsToRelation { cardinality: \"belongsTo\"; foreignKey: string; targetType: EntityType; invalidateTargetLists?: string[]; }\n/**\n * Inverse collection: children carry `foreignKey` pointing here; `listKeyPrefix` builds the child list query key for a given parent id.\n */\nexport interface HasManyRelation { cardinality: \"hasMany\"; targetType: EntityType; foreignKey: string; listKeyPrefix: (parentId: EntityId) => unknown[]; }\n/**\n * Join-style relation stored as an id array on this entity; invalidates partner lists derived via `listKeyPrefix` for each touched id.\n */\nexport interface ManyToManyRelation { cardinality: \"manyToMany\"; targetType: EntityType; localArrayField?: string; listKeyPrefix: (thisId: EntityId) => unknown[]; }\nexport type RelationDescriptor = BelongsToRelation | HasManyRelation | ManyToManyRelation;\n/**\n * Declarative relation metadata for one `EntityType`: optional named relations and list key prefixes to invalidate on any mutation.\n */\nexport interface EntitySchema { type: EntityType; relations?: Record<string, RelationDescriptor>; globalListKeys?: string[]; }\n/**\n * Snapshot diff passed to cascade rules after CRUD: compare `previous` vs `next` to find FK moves, array membership changes, etc.\n */\nexport interface CascadeContext { type: EntityType; id: EntityId; previous: Record<string, unknown> | null; next: Record<string, unknown> | null; op: \"create\" | \"update\" | \"delete\"; }\n\nconst schemaRegistry = new Map<EntityType, EntitySchema>();\n/** Register or replace schema for `schema.type` (typically at app init). */\nexport function registerSchema(schema: EntitySchema) { schemaRegistry.set(schema.type, schema); }\n/** Lookup schema for cascade/join reads; returns null if unregistered. */\nexport function getSchema(type: EntityType) { return schemaRegistry.get(type) ?? null; }\n/** Read the existing registry for derived tooling projections without creating a second schema source. */\nexport function getRegisteredSchemas(): readonly EntitySchema[] { return [...schemaRegistry.values()]; }\n\n/**\n * After a successful mutation, mark related entities/lists stale so hooks refetch without manually hunting query keys.\n * Traverses registered schemas (including reverse `hasMany`) so denormalized UIs stay eventually consistent with the graph.\n */\nexport function cascadeInvalidation(ctx: CascadeContext, storeApi: GraphStore = graphStore) {\n const schema = schemaRegistry.get(ctx.type); if (!schema) return;\n const store = storeApi.getState();\n if (schema.globalListKeys) for (const key of schema.globalListKeys) store.invalidateLists(key);\n if (!schema.relations) return;\n for (const [, relation] of Object.entries(schema.relations)) {\n switch (relation.cardinality) {\n case \"belongsTo\": {\n const prevFk = ctx.previous?.[relation.foreignKey] as EntityId | null;\n const nextFk = ctx.next?.[relation.foreignKey] as EntityId | null;\n if (prevFk && prevFk !== nextFk && relation.invalidateTargetLists) for (const kp of relation.invalidateTargetLists) store.invalidateLists((k) => k.startsWith(kp) && k.includes(prevFk));\n if (nextFk && relation.invalidateTargetLists) for (const kp of relation.invalidateTargetLists) store.invalidateLists((k) => k.startsWith(kp) && k.includes(nextFk));\n if (prevFk) store.invalidateEntity(relation.targetType, prevFk);\n if (nextFk) store.invalidateEntity(relation.targetType, nextFk);\n break;\n }\n case \"hasMany\": store.invalidateLists(serializeKey(relation.listKeyPrefix(ctx.id) as unknown[])); break;\n case \"manyToMany\": {\n const prevIds = ctx.previous?.[relation.localArrayField ?? \"\"] as EntityId[] | null;\n const nextIds = ctx.next?.[relation.localArrayField ?? \"\"] as EntityId[] | null;\n for (const relatedId of new Set([...(prevIds ?? []), ...(nextIds ?? [])])) store.invalidateLists(serializeKey(relation.listKeyPrefix(relatedId) as unknown[]));\n break;\n }\n }\n }\n for (const [, otherSchema] of schemaRegistry) {\n if (!otherSchema.relations) continue;\n for (const [, rel] of Object.entries(otherSchema.relations)) {\n if (rel.targetType !== ctx.type) continue;\n if (rel.cardinality === \"hasMany\") store.invalidateLists(serializeKey(rel.listKeyPrefix(ctx.id) as unknown[]));\n }\n }\n}\n\n/**\n * Resolve relation **placeholders** for detail panels: joins graph reads for belongs-to targets, has-many id lists, or many-to-many id arrays.\n * Returns plain objects suitable for rendering; does not mutate the graph.\n */\nexport function readRelations(type: EntityType, entity: Record<string, unknown>, storeApi: GraphStore = graphStore): Record<string, unknown> {\n const schema = schemaRegistry.get(type); if (!schema?.relations) return {};\n const store = storeApi.getState(); const result: Record<string, unknown> = {};\n for (const [name, relation] of Object.entries(schema.relations)) {\n switch (relation.cardinality) {\n case \"belongsTo\": { const fkValue = entity[relation.foreignKey] as EntityId | null; result[name] = fkValue ? store.readEntity(relation.targetType, fkValue) : null; break; }\n case \"hasMany\": { const listKey = serializeKey(relation.listKeyPrefix(entity.id as EntityId) as unknown[]); const listState = store.lists[listKey]; result[name] = listState ? listState.ids.map((id) => store.readEntity(relation.targetType, id)).filter(Boolean) : []; break; }\n case \"manyToMany\": { const ids = entity[relation.localArrayField ?? \"\"] as EntityId[] | null; result[name] = ids ? ids.map((id) => store.readEntity(relation.targetType, id)).filter(Boolean) : []; break; }\n }\n }\n return result;\n}\n","import { getRegisteredSchemas, type RelationDescriptor } from \"../crud/relations\";\nimport { serializeKey } from \"../engine\";\nimport type { GraphState } from \"../graph\";\nimport {\n GRAPH_DEVTOOLS_PROTOCOL,\n GRAPH_DEVTOOLS_PROTOCOL_VERSION,\n type GraphDevtoolsRelationship,\n type GraphDevtoolsRelationshipsSnapshot,\n} from \"./protocol\";\n\nfunction mergedEntity(\n state: GraphState,\n type: string,\n id: string,\n): Record<string, unknown> | null {\n const canonical = state.entities[type]?.[id];\n if (!canonical) return null;\n return { ...canonical, ...(state.patches[type]?.[id] ?? {}) };\n}\n\nfunction statusFor(state: GraphState, type: string, id: string): GraphDevtoolsRelationship[\"status\"] {\n return state.entities[type]?.[id] ? \"resolved\" : \"missing-target\";\n}\n\nfunction edge(\n relation: string,\n descriptor: RelationDescriptor,\n direction: GraphDevtoolsRelationship[\"direction\"],\n sourceType: string,\n sourceId: string,\n sourceField: string | null,\n targetType: string,\n targetId: string,\n state: GraphState,\n): GraphDevtoolsRelationship {\n return {\n relation,\n cardinality: descriptor.cardinality,\n direction,\n source: { type: sourceType, id: sourceId, field: sourceField },\n target: { type: targetType, id: targetId },\n status: statusFor(state, targetType, targetId),\n };\n}\n\nfunction belongsToEdges(\n state: GraphState,\n schemaType: string,\n relation: string,\n descriptor: Extract<RelationDescriptor, { cardinality: \"belongsTo\" }>,\n): GraphDevtoolsRelationship[] {\n const edges: GraphDevtoolsRelationship[] = [];\n for (const id of Object.keys(state.entities[schemaType] ?? {})) {\n const entity = mergedEntity(state, schemaType, id);\n const targetId = entity?.[descriptor.foreignKey];\n if (typeof targetId !== \"string\" || targetId.length === 0) continue;\n edges.push(edge(\n relation,\n descriptor,\n \"outgoing\",\n schemaType,\n id,\n descriptor.foreignKey,\n descriptor.targetType,\n targetId,\n state,\n ));\n }\n return edges;\n}\n\nfunction hasManyEdges(\n state: GraphState,\n schemaType: string,\n relation: string,\n descriptor: Extract<RelationDescriptor, { cardinality: \"hasMany\" }>,\n): GraphDevtoolsRelationship[] {\n const edges: GraphDevtoolsRelationship[] = [];\n for (const parentId of Object.keys(state.entities[schemaType] ?? {})) {\n const childIds = new Set<string>();\n for (const childId of Object.keys(state.entities[descriptor.targetType] ?? {})) {\n const child = mergedEntity(state, descriptor.targetType, childId);\n if (child?.[descriptor.foreignKey] === parentId) childIds.add(childId);\n }\n const listKey = serializeKey(descriptor.listKeyPrefix(parentId) as unknown[]);\n for (const childId of state.lists[listKey]?.ids ?? []) {\n if (!state.entities[descriptor.targetType]?.[childId]) childIds.add(childId);\n }\n for (const childId of childIds) {\n edges.push(edge(\n relation,\n descriptor,\n \"reverse\",\n schemaType,\n parentId,\n null,\n descriptor.targetType,\n childId,\n state,\n ));\n }\n }\n return edges;\n}\n\nfunction manyToManyEdges(\n state: GraphState,\n schemaType: string,\n relation: string,\n descriptor: Extract<RelationDescriptor, { cardinality: \"manyToMany\" }>,\n): GraphDevtoolsRelationship[] {\n const field = descriptor.localArrayField;\n if (!field) return [];\n const edges: GraphDevtoolsRelationship[] = [];\n for (const id of Object.keys(state.entities[schemaType] ?? {})) {\n const entity = mergedEntity(state, schemaType, id);\n const targetIds = entity?.[field];\n if (!Array.isArray(targetIds)) continue;\n for (const targetId of new Set(targetIds)) {\n if (typeof targetId !== \"string\" || targetId.length === 0) continue;\n edges.push(edge(\n relation,\n descriptor,\n \"outgoing\",\n schemaType,\n id,\n field,\n descriptor.targetType,\n targetId,\n state,\n ));\n }\n }\n return edges;\n}\n\nfunction compareRelationships(\n left: GraphDevtoolsRelationship,\n right: GraphDevtoolsRelationship,\n): number {\n const leftKey = [\n left.source.type,\n left.source.id,\n left.relation,\n left.direction,\n left.target.type,\n left.target.id,\n ].join(\"\\u0000\");\n const rightKey = [\n right.source.type,\n right.source.id,\n right.relation,\n right.direction,\n right.target.type,\n right.target.id,\n ].join(\"\\u0000\");\n if (leftKey === rightKey) return 0;\n return leftKey < rightKey ? -1 : 1;\n}\n\n/** Project relationships exclusively from the existing CRUD schema registry and graph state. */\nexport function projectGraphDevtoolsRelationships(\n state: GraphState,\n storeId: string,\n): GraphDevtoolsRelationshipsSnapshot {\n const relationships: GraphDevtoolsRelationship[] = [];\n for (const schema of getRegisteredSchemas()) {\n for (const [name, descriptor] of Object.entries(schema.relations ?? {})) {\n switch (descriptor.cardinality) {\n case \"belongsTo\":\n relationships.push(...belongsToEdges(state, schema.type, name, descriptor));\n break;\n case \"hasMany\":\n relationships.push(...hasManyEdges(state, schema.type, name, descriptor));\n break;\n case \"manyToMany\":\n relationships.push(...manyToManyEdges(state, schema.type, name, descriptor));\n break;\n }\n }\n }\n relationships.sort(compareRelationships);\n return {\n protocol: GRAPH_DEVTOOLS_PROTOCOL,\n version: GRAPH_DEVTOOLS_PROTOCOL_VERSION,\n storeId,\n capturedAt: new Date().toISOString(),\n relationships,\n };\n}\n","import type { GraphStore } from \"./graph\";\n\nexport interface LegacyTimeTravelSnapshotMetadata {\n seq: number;\n at: number;\n label?: string;\n}\n\nexport interface LegacyTimeTravelState {\n snapshots: ReadonlyArray<LegacyTimeTravelSnapshotMetadata>;\n cursor: number | null;\n capacity: number;\n}\n\n/**\n * Thin root-safe facade supplied by an attached optional DevTools controller.\n * It owns no graph data, cursor, or snapshot history.\n */\nexport interface GraphDevtoolsCompatibilityDelegate {\n configure(capacity: number): void;\n capture(label?: string): number;\n restoreByIndex(index: number): boolean;\n restoreByCursor(cursor: number): boolean;\n step(delta: number): boolean;\n getState(): LegacyTimeTravelState;\n subscribe(listener: () => void): () => void;\n clear(): void;\n}\n\ninterface CompatibilityEntry {\n delegate: GraphDevtoolsCompatibilityDelegate | null;\n listeners: Set<() => void>;\n unsubscribeDelegate: (() => void) | null;\n compatibilityDetach: (() => void) | null;\n}\n\ninterface CompatibilityBridgeState {\n version: 1;\n entries: WeakMap<GraphStore, CompatibilityEntry>;\n factory: ((store: GraphStore) => () => void) | null;\n}\n\nconst BRIDGE_KEY = Symbol.for(\"prometheus.entity-graph.devtools.compatibility.v1\");\nconst bridgeHost = globalThis as typeof globalThis & { [key: symbol]: unknown };\nconst existingBridge = bridgeHost[BRIDGE_KEY] as CompatibilityBridgeState | undefined;\nconst bridgeState: CompatibilityBridgeState = existingBridge?.version === 1\n ? existingBridge\n : { version: 1, entries: new WeakMap(), factory: null };\nbridgeHost[BRIDGE_KEY] = bridgeState;\n\nfunction getOrCreateEntry(store: GraphStore): CompatibilityEntry {\n let entry = bridgeState.entries.get(store);\n if (!entry) {\n entry = {\n delegate: null,\n listeners: new Set(),\n unsubscribeDelegate: null,\n compatibilityDetach: null,\n };\n bridgeState.entries.set(store, entry);\n }\n return entry;\n}\n\nfunction ensureDelegate(store: GraphStore, entry: CompatibilityEntry): void {\n const factory = bridgeState.factory;\n if (entry.delegate || entry.compatibilityDetach || !factory) return;\n entry.compatibilityDetach = factory(store);\n}\n\n/** Registered only when the explicit optional DevTools module is loaded. */\nexport function registerGraphDevtoolsCompatibilityFactory(\n factory: (store: GraphStore) => () => void,\n): void {\n bridgeState.factory = factory;\n}\n\nfunction notify(entry: CompatibilityEntry): void {\n for (const listener of [...entry.listeners]) {\n try {\n listener();\n } catch {\n // Deprecated tooling listeners never interrupt the graph or controller.\n }\n }\n}\n\nexport function registerGraphDevtoolsCompatibilityDelegate(\n store: GraphStore,\n delegate: GraphDevtoolsCompatibilityDelegate,\n): () => void {\n const entry = getOrCreateEntry(store);\n entry.unsubscribeDelegate?.();\n entry.delegate = delegate;\n entry.unsubscribeDelegate = delegate.subscribe(() => notify(entry));\n notify(entry);\n\n let unregistered = false;\n return () => {\n if (unregistered || entry.delegate !== delegate) return;\n unregistered = true;\n entry.unsubscribeDelegate?.();\n entry.unsubscribeDelegate = null;\n entry.delegate = null;\n notify(entry);\n if (entry.listeners.size === 0) bridgeState.entries.delete(store);\n };\n}\n\nexport function getGraphDevtoolsCompatibilityDelegate(\n store: GraphStore,\n): GraphDevtoolsCompatibilityDelegate | null {\n const entry = getOrCreateEntry(store);\n ensureDelegate(store, entry);\n return entry.delegate;\n}\n\nexport function peekGraphDevtoolsCompatibilityDelegate(\n store: GraphStore,\n): GraphDevtoolsCompatibilityDelegate | null {\n return bridgeState.entries.get(store)?.delegate ?? null;\n}\n\nexport function subscribeGraphDevtoolsCompatibility(\n store: GraphStore,\n listener: () => void,\n): () => void {\n const entry = getOrCreateEntry(store);\n entry.listeners.add(listener);\n ensureDelegate(store, entry);\n return () => {\n entry.listeners.delete(listener);\n if (entry.listeners.size === 0 && entry.delegate === null) bridgeState.entries.delete(store);\n };\n}\n\nexport function resetGraphDevtoolsCompatibility(store?: GraphStore): void {\n if (store) {\n const entry = bridgeState.entries.get(store);\n entry?.delegate?.clear();\n if (entry?.compatibilityDetach) {\n const detach = entry.compatibilityDetach;\n entry.compatibilityDetach = null;\n detach();\n }\n if (entry && entry.delegate === null && entry.listeners.size === 0) bridgeState.entries.delete(store);\n return;\n }\n bridgeState.entries = new WeakMap<GraphStore, CompatibilityEntry>();\n}\n","import type { GraphState } from \"../graph\";\nimport {\n GRAPH_DEVTOOLS_PROTOCOL,\n GRAPH_DEVTOOLS_PROTOCOL_VERSION,\n type GraphDevtoolsExpiredHistoryReceipt,\n type GraphDevtoolsGraphData,\n type GraphDevtoolsHistoryImportInspectionResult,\n type GraphDevtoolsHistoryImportInspectionReceipt,\n type GraphDevtoolsSnapshotHistoryStatus,\n type GraphDevtoolsSnapshotReference,\n} from \"./protocol\";\n\nexport interface GraphDevtoolsRetainedSnapshot {\n readonly reference: Extract<GraphDevtoolsSnapshotReference, { status: \"retained\" }>;\n readonly data: GraphDevtoolsGraphData;\n}\n\nexport type GraphDevtoolsSnapshotRewindAttempt =\n | {\n status: \"rewound\";\n previousCursor: number | null;\n previousSource: \"retained\" | \"import\" | null;\n }\n | GraphDevtoolsExpiredHistoryReceipt\n | null;\n\nexport type GraphDevtoolsImportRestoreAttempt =\n | {\n status: \"rewound\";\n previousCursor: number | null;\n previousSource: \"retained\" | \"import\" | null;\n }\n | { status: \"candidate-not-found\" }\n | { status: \"snapshot-not-found\" }\n | { status: \"restore-failed\" };\n\nexport interface GraphDevtoolsReturnToLiveAttempt {\n previousCursor: number;\n previousSource: \"retained\" | \"import\";\n}\n\nexport interface GraphDevtoolsSnapshotHistory {\n capture(state: GraphState, eventSequence: number | null, label?: string): GraphDevtoolsSnapshotReference;\n captureCompatibility(state: GraphState, label?: string): GraphDevtoolsSnapshotReference;\n getStatus(): GraphDevtoolsSnapshotHistoryStatus;\n getReferences(): ReadonlyArray<Extract<GraphDevtoolsSnapshotReference, { status: \"retained\" }>>;\n getCompatibilityReferences(): ReadonlyArray<Extract<GraphDevtoolsSnapshotReference, { status: \"retained\" }>>;\n read(cursor: number): GraphDevtoolsGraphData | null;\n rewind(\n cursor: number,\n liveState: GraphState,\n restore: (data: GraphDevtoolsGraphData) => void,\n ): GraphDevtoolsSnapshotRewindAttempt;\n inspectImport(candidate: unknown, storeId: string): GraphDevtoolsHistoryImportInspectionResult;\n restoreImport(\n candidateId: string,\n cursor: number,\n liveState: GraphState,\n restore: (data: GraphDevtoolsGraphData) => void,\n ): GraphDevtoolsImportRestoreAttempt;\n returnToLive(restore: (data: GraphDevtoolsGraphData) => void): GraphDevtoolsReturnToLiveAttempt | null;\n leaveRewindForMutation(): GraphDevtoolsReturnToLiveAttempt | null;\n configureLimit(snapshotLimit: number): void;\n subscribe(listener: () => void): () => void;\n clear(): void;\n dispose(): void;\n}\n\nexport interface GraphDevtoolsSnapshotHistoryOptions {\n snapshotLimit: number;\n snapshotBytesLimit: number;\n}\n\nfunction cloneGraphData(data: GraphDevtoolsGraphData): GraphDevtoolsGraphData {\n return structuredClone({\n entities: data.entities,\n patches: data.patches,\n entityStates: data.entityStates,\n syncMetadata: data.syncMetadata,\n lists: data.lists,\n });\n}\n\nfunction encodedBytes(value: unknown): number {\n return new TextEncoder().encode(JSON.stringify(value)).byteLength;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction isJsonValue(value: unknown, ancestors = new Set<object>()): boolean {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return true;\n if (typeof value === \"number\") return Number.isFinite(value);\n if (typeof value !== \"object\") return false;\n if (ancestors.has(value)) return false;\n\n ancestors.add(value);\n const valid = Array.isArray(value)\n ? value.every((item) => isJsonValue(item, ancestors))\n : isRecord(value) && Object.values(value).every((item) => isJsonValue(item, ancestors));\n ancestors.delete(value);\n return valid;\n}\n\nfunction isNullableString(value: unknown): boolean {\n return value === null || typeof value === \"string\";\n}\n\nfunction isNullableFiniteNumber(value: unknown): boolean {\n return value === null || (typeof value === \"number\" && Number.isFinite(value));\n}\n\nfunction isTimestamp(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0 && Number.isFinite(Date.parse(value));\n}\n\nfunction isEntityTable(value: unknown): boolean {\n return isRecord(value) && Object.values(value).every(\n (entities) => isRecord(entities) && Object.values(entities).every(isRecord),\n );\n}\n\nfunction isEntityStates(value: unknown): boolean {\n return isRecord(value) && Object.values(value).every((state) => (\n isRecord(state) &&\n typeof state.isFetching === \"boolean\" &&\n isNullableFiniteNumber(state.lastFetched) &&\n isNullableString(state.error) &&\n typeof state.stale === \"boolean\"\n ));\n}\n\nfunction isSyncMetadata(value: unknown): boolean {\n return isRecord(value) && Object.values(value).every((metadata) => (\n isRecord(metadata) &&\n typeof metadata.synced === \"boolean\" &&\n (metadata.origin === \"server\" || metadata.origin === \"client\" || metadata.origin === \"optimistic\") &&\n isNullableFiniteNumber(metadata.updatedAt)\n ));\n}\n\nfunction isLists(value: unknown): boolean {\n return isRecord(value) && Object.values(value).every((list) => (\n isRecord(list) &&\n Array.isArray(list.ids) && list.ids.every((id) => typeof id === \"string\") &&\n isNullableFiniteNumber(list.total) &&\n isNullableString(list.nextCursor) &&\n isNullableString(list.prevCursor) &&\n typeof list.hasNextPage === \"boolean\" &&\n typeof list.hasPrevPage === \"boolean\" &&\n typeof list.isFetching === \"boolean\" &&\n typeof list.isFetchingMore === \"boolean\" &&\n isNullableString(list.error) &&\n (list.lastError === null || isRecord(list.lastError)) &&\n isNullableFiniteNumber(list.lastFetched) &&\n typeof list.stale === \"boolean\" &&\n isNullableFiniteNumber(list.currentPage) &&\n isNullableFiniteNumber(list.pageSize)\n ));\n}\n\nfunction isGraphData(value: unknown): value is GraphDevtoolsGraphData {\n return isRecord(value) &&\n isEntityTable(value.entities) &&\n isEntityTable(value.patches) &&\n isEntityStates(value.entityStates) &&\n isSyncMetadata(value.syncMetadata) &&\n isLists(value.lists);\n}\n\ninterface ImportedSnapshot {\n cursor: number;\n capturedAt: string;\n eventSequence: number | null;\n bytes: number;\n data: GraphDevtoolsGraphData;\n}\n\ninterface ImportedCandidate {\n candidateId: string;\n bytes: number;\n snapshots: ImportedSnapshot[];\n}\n\n/** Controller-local snapshot storage. It never subscribes to or owns a graph. */\nexport function createGraphDevtoolsSnapshotHistory(\n options: GraphDevtoolsSnapshotHistoryOptions,\n): GraphDevtoolsSnapshotHistory {\n const retained: GraphDevtoolsRetainedSnapshot[] = [];\n const compatibilityLabels = new Map<number, string | undefined>();\n const listeners = new Set<() => void>();\n let snapshotLimit = options.snapshotLimit;\n let retainedBytes = 0;\n let latestCursor = 0;\n let baselineCursor: number | null = null;\n let lastUnavailable: Extract<GraphDevtoolsSnapshotReference, { status: \"unavailable\" }> | null = null;\n const unavailableReferences = new Map<\n number,\n Extract<GraphDevtoolsSnapshotReference, { status: \"unavailable\" }>\n >();\n let clearedThroughCursor = 0;\n let mode: GraphDevtoolsSnapshotHistoryStatus[\"mode\"] = \"live\";\n let activeCursor: number | null = null;\n let activeSource: GraphDevtoolsSnapshotHistoryStatus[\"source\"] = null;\n let protectedLiveHead: GraphDevtoolsGraphData | null = null;\n let importedCandidate: ImportedCandidate | null = null;\n let nextImportCandidate = 1;\n let disposed = false;\n\n const notify = () => {\n for (const listener of [...listeners]) {\n try {\n listener();\n } catch {\n // Compatibility observers are isolated from the snapshot owner.\n }\n }\n };\n\n const unavailable = (\n cursor: number,\n capturedAt: string,\n eventSequence: number | null,\n reason: Extract<GraphDevtoolsSnapshotReference, { status: \"unavailable\" }>[\"reason\"],\n label?: string,\n ): GraphDevtoolsSnapshotReference => {\n const reference: Extract<GraphDevtoolsSnapshotReference, { status: \"unavailable\" }> = {\n cursor,\n capturedAt,\n eventSequence,\n ...(label !== undefined ? { label } : {}),\n status: \"unavailable\",\n reason,\n };\n lastUnavailable = reference;\n unavailableReferences.set(cursor, reference);\n while (unavailableReferences.size > Math.max(1, snapshotLimit)) {\n const oldest = unavailableReferences.keys().next().value as number | undefined;\n if (oldest === undefined) break;\n unavailableReferences.delete(oldest);\n }\n return reference;\n };\n\n const expired = (cursor: number): GraphDevtoolsExpiredHistoryReceipt | null => {\n if (cursor > latestCursor) return null;\n const status = history.getStatus();\n const unavailableReference = unavailableReferences.get(cursor);\n if (unavailableReference) {\n return {\n status: \"expired-history\",\n cursor,\n reason: \"unavailable\",\n unavailableReason: unavailableReference.reason,\n oldestCursor: status.oldestCursor,\n newestCursor: status.newestCursor,\n latestCursor: status.latestCursor,\n };\n }\n return {\n status: \"expired-history\",\n cursor,\n reason: cursor <= clearedThroughCursor ? \"cleared\" : \"evicted\",\n oldestCursor: status.oldestCursor,\n newestCursor: status.newestCursor,\n latestCursor: status.latestCursor,\n };\n };\n\n const enterRewind = (\n cursor: number,\n source: \"retained\" | \"import\",\n data: GraphDevtoolsGraphData,\n liveState: GraphState,\n restore: (data: GraphDevtoolsGraphData) => void,\n ): Extract<GraphDevtoolsSnapshotRewindAttempt, { status: \"rewound\" }> | null => {\n if (disposed || (mode === \"rewound\" && protectedLiveHead === null)) return null;\n const previousCursor = activeCursor;\n const previousSource = activeSource;\n let target: GraphDevtoolsGraphData;\n let nextLiveHead = protectedLiveHead;\n try {\n target = cloneGraphData(data);\n if (mode === \"live\") nextLiveHead = cloneGraphData(liveState);\n restore(target);\n } catch {\n return null;\n }\n protectedLiveHead = nextLiveHead;\n mode = \"rewound\";\n activeCursor = cursor;\n activeSource = source;\n return { status: \"rewound\", previousCursor, previousSource };\n };\n\n const history: GraphDevtoolsSnapshotHistory = {\n capture(state, eventSequence, label) {\n // Live graph activity invalidates an inspected-but-unrestored candidate\n // and releases its portion of the one controller-local memory budget.\n importedCandidate = null;\n const cursor = ++latestCursor;\n const capturedAt = new Date().toISOString();\n if (baselineCursor === null) baselineCursor = cursor;\n if (disposed || snapshotLimit === 0 || options.snapshotBytesLimit === 0) {\n const reference = unavailable(cursor, capturedAt, eventSequence, \"retention-disabled\", label);\n notify();\n return reference;\n }\n\n let data: GraphDevtoolsGraphData;\n let bytes: number;\n try {\n data = cloneGraphData(state);\n bytes = encodedBytes(data);\n } catch {\n const reference = unavailable(cursor, capturedAt, eventSequence, \"capture-failed\", label);\n notify();\n return reference;\n }\n if (bytes > options.snapshotBytesLimit) {\n const unavailableReference = unavailable(cursor, capturedAt, eventSequence, \"oversize\", label);\n notify();\n return unavailableReference;\n }\n\n const reference: Extract<GraphDevtoolsSnapshotReference, { status: \"retained\" }> = {\n cursor,\n capturedAt,\n eventSequence,\n ...(label !== undefined ? { label } : {}),\n status: \"retained\",\n bytes,\n };\n retained.push({ reference, data });\n retainedBytes += bytes;\n while (\n retained.length > snapshotLimit ||\n retainedBytes > options.snapshotBytesLimit\n ) {\n const removed = retained.shift();\n if (removed) compatibilityLabels.delete(removed.reference.cursor);\n retainedBytes -= removed?.reference.bytes ?? 0;\n }\n notify();\n return reference;\n },\n captureCompatibility(state, label) {\n const candidateCursor = mode === \"live\"\n ? latestCursor\n : activeSource === \"retained\"\n ? activeCursor\n : null;\n const current = candidateCursor === null\n ? undefined\n : retained.find(({ reference }) => reference.cursor === candidateCursor);\n if (current && !compatibilityLabels.has(current.reference.cursor)) {\n compatibilityLabels.set(current.reference.cursor, label);\n notify();\n return {\n ...current.reference,\n ...(label !== undefined ? { label } : {}),\n };\n }\n const reference = history.capture(state, null, label);\n if (reference.status === \"retained\") {\n compatibilityLabels.set(reference.cursor, label);\n }\n return reference;\n },\n getStatus() {\n return {\n mode,\n cursor: activeCursor,\n source: activeSource,\n retainedSnapshots: retained.length,\n retainedBytes,\n snapshotLimit,\n byteLimit: options.snapshotBytesLimit,\n baselineCursor,\n oldestCursor: retained[0]?.reference.cursor ?? null,\n newestCursor: retained.length > 0\n ? retained[retained.length - 1]!.reference.cursor\n : null,\n latestCursor: latestCursor === 0 ? null : latestCursor,\n lastUnavailable,\n importCandidate: importedCandidate\n ? {\n candidateId: importedCandidate.candidateId,\n snapshots: importedCandidate.snapshots.length,\n bytes: importedCandidate.bytes,\n }\n : null,\n };\n },\n getReferences() {\n return retained.map(({ reference }) => ({ ...reference }));\n },\n getCompatibilityReferences() {\n return retained\n .filter(({ reference }) => compatibilityLabels.has(reference.cursor))\n .map(({ reference }) => {\n const label = compatibilityLabels.get(reference.cursor);\n return { ...reference, ...(label !== undefined ? { label } : {}) };\n });\n },\n read(cursor) {\n const snapshot = retained.find((candidate) => candidate.reference.cursor === cursor);\n return snapshot ? cloneGraphData(snapshot.data) : null;\n },\n rewind(cursor, liveState, restore) {\n if (disposed) return null;\n const snapshot = retained.find((candidate) => candidate.reference.cursor === cursor);\n if (!snapshot) return expired(cursor);\n const result = enterRewind(cursor, \"retained\", snapshot.data, liveState, restore);\n if (result) notify();\n return result;\n },\n inspectImport(candidate, storeId) {\n // Every inspection attempt replaces the prior inert candidate, including\n // a rejected attempt, so confirmation can never target stale UI state.\n importedCandidate = null;\n const rejected = (\n reason: Extract<GraphDevtoolsHistoryImportInspectionResult, { status: \"rejected\" }>[\"reason\"],\n message: string,\n ): GraphDevtoolsHistoryImportInspectionResult => {\n notify();\n return { status: \"rejected\", reason, message };\n };\n try {\n if (!isRecord(candidate) || !isJsonValue(candidate) || candidate.protocol !== GRAPH_DEVTOOLS_PROTOCOL) {\n return rejected(\"invalid-envelope\", \"Import must use the Prometheus entity-graph DevTools protocol\");\n }\n if (candidate.version !== GRAPH_DEVTOOLS_PROTOCOL_VERSION) {\n return rejected(\"unsupported-version\", `Import protocol version ${String(candidate.version)} is unsupported`);\n }\n if (candidate.storeId !== storeId) {\n return rejected(\"wrong-store\", `Import targets ${String(candidate.storeId)}, not ${storeId}`);\n }\n if (!isTimestamp(candidate.exportedAt) || !Array.isArray(candidate.snapshots) || candidate.snapshots.length === 0) {\n return rejected(\"invalid-envelope\", \"Import metadata and at least one snapshot are required\");\n }\n if (candidate.snapshots.length > snapshotLimit) {\n return rejected(\"snapshot-limit-exceeded\", `Import contains ${candidate.snapshots.length} snapshots; limit is ${snapshotLimit}`);\n }\n const importBytes = encodedBytes(candidate);\n if (importBytes > options.snapshotBytesLimit) {\n return rejected(\"byte-limit-exceeded\", `Import contains ${importBytes} bytes; limit is ${options.snapshotBytesLimit}`);\n }\n\n const snapshots: ImportedSnapshot[] = [];\n let previousCursor = 0;\n for (const value of candidate.snapshots) {\n if (!isRecord(value)) return rejected(\"invalid-envelope\", \"Every imported snapshot must be an object\");\n const cursor = value.cursor;\n const eventSequence = value.eventSequence;\n if (\n typeof cursor !== \"number\" || !Number.isSafeInteger(cursor) || cursor <= previousCursor ||\n !isTimestamp(value.capturedAt) ||\n !(eventSequence === null || (typeof eventSequence === \"number\" && Number.isSafeInteger(eventSequence) && eventSequence > 0)) ||\n !isGraphData(value.data)\n ) {\n return rejected(\"invalid-envelope\", \"Imported snapshots must have ordered stable cursors and valid graph data\");\n }\n const data = cloneGraphData(value.data);\n snapshots.push({\n cursor,\n capturedAt: value.capturedAt,\n eventSequence,\n bytes: encodedBytes(data),\n data,\n });\n previousCursor = cursor;\n }\n\n const candidateBytes = snapshots.reduce((total, snapshot) => total + snapshot.bytes, 0);\n while (\n retained.length + snapshots.length > snapshotLimit ||\n retainedBytes + candidateBytes > options.snapshotBytesLimit\n ) {\n const removed = retained.shift();\n if (!removed) break;\n compatibilityLabels.delete(removed.reference.cursor);\n retainedBytes -= removed.reference.bytes;\n }\n\n const candidateId = `import-${nextImportCandidate++}`;\n importedCandidate = { candidateId, bytes: candidateBytes, snapshots };\n notify();\n const receipt: GraphDevtoolsHistoryImportInspectionReceipt = {\n status: \"awaiting-confirmation\",\n candidateId,\n storeId,\n protocolVersion: GRAPH_DEVTOOLS_PROTOCOL_VERSION,\n inspectedAt: new Date().toISOString(),\n bytes: importBytes,\n snapshots: snapshots.map(({ data: _data, ...metadata }) => metadata),\n };\n return receipt;\n } catch {\n return rejected(\"invalid-envelope\", \"Import could not be safely inspected or cloned\");\n }\n },\n restoreImport(candidateId, cursor, liveState, restore) {\n if (!importedCandidate || importedCandidate.candidateId !== candidateId) {\n return { status: \"candidate-not-found\" };\n }\n const snapshot = importedCandidate.snapshots.find((candidate) => candidate.cursor === cursor);\n if (!snapshot) return { status: \"snapshot-not-found\" };\n const restored = enterRewind(cursor, \"import\", snapshot.data, liveState, restore);\n if (!restored) return { status: \"restore-failed\" };\n // Confirmation is one-shot. Reusing imported data requires a fresh,\n // visible inspection and confirmation cycle.\n importedCandidate = null;\n notify();\n return restored;\n },\n returnToLive(restore) {\n if (disposed || mode !== \"rewound\" || protectedLiveHead === null) return null;\n const previousCursor = activeCursor;\n const previousSource = activeSource;\n if (previousCursor === null || previousSource === null) return null;\n try {\n restore(cloneGraphData(protectedLiveHead));\n } catch {\n return null;\n }\n mode = \"live\";\n activeCursor = null;\n activeSource = null;\n protectedLiveHead = null;\n notify();\n return { previousCursor, previousSource };\n },\n leaveRewindForMutation() {\n if (mode !== \"rewound\") return null;\n const previousCursor = activeCursor;\n const previousSource = activeSource;\n if (previousCursor === null || previousSource === null) return null;\n mode = \"live\";\n activeCursor = null;\n activeSource = null;\n protectedLiveHead = null;\n notify();\n return { previousCursor, previousSource };\n },\n configureLimit(nextLimit) {\n if (!Number.isFinite(nextLimit) || nextLimit <= 0) return;\n snapshotLimit = Math.max(1, Math.floor(nextLimit));\n while (retained.length > snapshotLimit) {\n const removed = retained.shift();\n if (removed) compatibilityLabels.delete(removed.reference.cursor);\n retainedBytes -= removed?.reference.bytes ?? 0;\n }\n while (unavailableReferences.size > Math.max(1, snapshotLimit)) {\n const oldest = unavailableReferences.keys().next().value as number | undefined;\n if (oldest === undefined) break;\n unavailableReferences.delete(oldest);\n }\n if (importedCandidate && retained.length + importedCandidate.snapshots.length > snapshotLimit) {\n importedCandidate = null;\n }\n notify();\n },\n subscribe(listener) {\n if (disposed) return () => {};\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n clear() {\n retained.length = 0;\n compatibilityLabels.clear();\n retainedBytes = 0;\n clearedThroughCursor = latestCursor;\n importedCandidate = null;\n notify();\n },\n dispose() {\n disposed = true;\n retained.length = 0;\n compatibilityLabels.clear();\n retainedBytes = 0;\n lastUnavailable = null;\n unavailableReferences.clear();\n mode = \"live\";\n activeCursor = null;\n activeSource = null;\n protectedLiveHead = null;\n importedCandidate = null;\n listeners.clear();\n },\n };\n\n return history;\n}\n","import { EMPTY_LIST_STATE, type GraphState } from \"../graph\";\nimport {\n GRAPH_DEVTOOLS_PROTOCOL,\n GRAPH_DEVTOOLS_PROTOCOL_VERSION,\n type GraphDevtoolsViewDefinition,\n type GraphDevtoolsViewEvent,\n type GraphDevtoolsViewMembership,\n type GraphDevtoolsViewRecord,\n type GraphDevtoolsViewsSnapshot,\n} from \"./protocol\";\nimport {\n graphDevtoolsEntityIdentitiesForStateKey,\n graphDevtoolsEntityIdentityKey,\n parseGraphDevtoolsEntityIdentityKey,\n} from \"./inspection\";\n\nexport interface GraphDevtoolsViewRegistration {\n readonly viewId: string;\n updateMembership(entityIds: readonly string[]): void;\n unregister(): void;\n}\n\nexport interface GraphDevtoolsViewRegistry {\n register(definition: GraphDevtoolsViewDefinition): GraphDevtoolsViewRegistration;\n getSnapshot(): GraphDevtoolsViewsSnapshot;\n getViewIdsByEntity(): ReadonlyMap<string, readonly string[]>;\n dispose(): void;\n}\n\ninterface ViewRegistrationState {\n entityIds: string[];\n renderCount: number;\n lastRenderedAt: string | null;\n}\n\ninterface ViewEntry {\n definition: GraphDevtoolsViewDefinition;\n registeredAt: string;\n registrations: Map<symbol, ViewRegistrationState>;\n}\n\nfunction orderedUnique(values: readonly string[]): string[] {\n return [...new Set(values)];\n}\n\nfunction sameValues(left: readonly string[], right: readonly string[]): boolean {\n return left.length === right.length && left.every((value, index) => value === right[index]);\n}\n\nfunction membershipFor(entry: ViewEntry): GraphDevtoolsViewMembership[] {\n const entityIds = new Set<string>();\n for (const registration of entry.registrations.values()) {\n for (const id of registration.entityIds) entityIds.add(id);\n }\n return [...entityIds].map((id) => ({ type: entry.definition.entityType, id }));\n}\n\nfunction viewRecord(entry: ViewEntry, state: GraphState): GraphDevtoolsViewRecord {\n const membership = membershipFor(entry);\n const registrations = [...entry.registrations.values()];\n const lastRenderedAt = registrations\n .map((registration) => registration.lastRenderedAt)\n .filter((value): value is string => value !== null)\n .sort()\n .at(-1) ?? null;\n const queryKey = entry.definition.queryKey ?? null;\n const listState = queryKey === null ? EMPTY_LIST_STATE : (state.lists[queryKey] ?? EMPTY_LIST_STATE);\n\n return {\n ...entry.definition,\n queryKey,\n registeredAt: entry.registeredAt,\n lastRenderedAt,\n renderCount: registrations.reduce((total, registration) => total + registration.renderCount, 0),\n subscriberCount: registrations.length,\n membership,\n list: entry.definition.kind === \"list\"\n ? {\n visibleCount: membership.length,\n graphCount: listState.ids.length,\n total: listState.total,\n isFetching: listState.isFetching,\n isFetchingMore: listState.isFetchingMore,\n stale: listState.stale,\n hasNextPage: listState.hasNextPage,\n hasPreviousPage: listState.hasPrevPage,\n }\n : null,\n };\n}\n\nfunction allEntityIdentities(\n state: GraphState,\n memberships: ReadonlyMap<string, readonly string[]>,\n): Array<{ type: string; id: string }> {\n const identities = new Map<string, { type: string; id: string }>();\n for (const [type, bucket] of Object.entries(state.entities)) {\n for (const id of Object.keys(bucket)) {\n identities.set(graphDevtoolsEntityIdentityKey(type, id), { type, id });\n }\n }\n for (const [type, bucket] of Object.entries(state.patches)) {\n for (const id of Object.keys(bucket)) {\n identities.set(graphDevtoolsEntityIdentityKey(type, id), { type, id });\n }\n }\n for (const key of [\n ...Object.keys(state.entityStates),\n ...Object.keys(state.syncMetadata),\n ]) {\n for (const identity of graphDevtoolsEntityIdentitiesForStateKey(state, key)) {\n identities.set(graphDevtoolsEntityIdentityKey(identity.type, identity.id), identity);\n }\n }\n for (const key of memberships.keys()) {\n const identity = parseGraphDevtoolsEntityIdentityKey(key);\n if (identity) identities.set(key, identity);\n }\n return [...identities.values()].sort((left, right) => {\n if (left.type !== right.type) return left.type < right.type ? -1 : 1;\n if (left.id === right.id) return 0;\n return left.id < right.id ? -1 : 1;\n });\n}\n\nexport function createGraphDevtoolsViewRegistry(\n storeId: string,\n getState: () => GraphState,\n onViewChange: (change: GraphDevtoolsViewEvent[\"payload\"]) => void,\n): GraphDevtoolsViewRegistry {\n const entries = new Map<string, ViewEntry>();\n let disposed = false;\n\n const viewIdsByEntity = (): Map<string, string[]> => {\n const result = new Map<string, string[]>();\n for (const [viewId, entry] of entries) {\n for (const membership of membershipFor(entry)) {\n const key = graphDevtoolsEntityIdentityKey(membership.type, membership.id);\n const viewIds = result.get(key) ?? [];\n viewIds.push(viewId);\n result.set(key, viewIds);\n }\n }\n for (const viewIds of result.values()) viewIds.sort();\n return result;\n };\n\n return {\n register(definition) {\n if (disposed) return { viewId: definition.viewId, updateMembership() {}, unregister() {} };\n const token = Symbol(definition.viewId);\n let entry = entries.get(definition.viewId);\n const isNew = entry === undefined;\n if (!entry) {\n entry = {\n definition: { ...definition, queryKey: definition.queryKey ?? null },\n registeredAt: new Date().toISOString(),\n registrations: new Map(),\n };\n entries.set(definition.viewId, entry);\n }\n entry.registrations.set(token, { entityIds: [], renderCount: 0, lastRenderedAt: null });\n if (isNew) onViewChange({ state: \"registered\", viewId: definition.viewId, membershipCount: 0 });\n\n let unregistered = false;\n return {\n viewId: definition.viewId,\n updateMembership(entityIds) {\n if (disposed || unregistered) return;\n const currentEntry = entries.get(definition.viewId);\n const registration = currentEntry?.registrations.get(token);\n if (!currentEntry || !registration) return;\n const before = membershipFor(currentEntry);\n registration.entityIds = orderedUnique(entityIds);\n registration.renderCount += 1;\n registration.lastRenderedAt = new Date().toISOString();\n const after = membershipFor(currentEntry);\n const beforeKeys = before.map(({ type, id }) => graphDevtoolsEntityIdentityKey(type, id));\n const afterKeys = after.map(({ type, id }) => graphDevtoolsEntityIdentityKey(type, id));\n if (!sameValues(beforeKeys, afterKeys)) {\n onViewChange({\n state: \"membership-changed\",\n viewId: definition.viewId,\n membershipCount: after.length,\n });\n }\n },\n unregister() {\n if (disposed || unregistered) return;\n unregistered = true;\n const currentEntry = entries.get(definition.viewId);\n if (!currentEntry) return;\n const before = membershipFor(currentEntry);\n currentEntry.registrations.delete(token);\n if (currentEntry.registrations.size === 0) {\n entries.delete(definition.viewId);\n onViewChange({ state: \"unregistered\", viewId: definition.viewId, membershipCount: 0 });\n return;\n }\n const after = membershipFor(currentEntry);\n const beforeKeys = before.map(({ type, id }) => graphDevtoolsEntityIdentityKey(type, id));\n const afterKeys = after.map(({ type, id }) => graphDevtoolsEntityIdentityKey(type, id));\n if (!sameValues(beforeKeys, afterKeys)) {\n onViewChange({\n state: \"membership-changed\",\n viewId: definition.viewId,\n membershipCount: after.length,\n });\n }\n },\n };\n },\n getSnapshot() {\n const state = getState();\n const memberships = viewIdsByEntity();\n return {\n protocol: GRAPH_DEVTOOLS_PROTOCOL,\n version: GRAPH_DEVTOOLS_PROTOCOL_VERSION,\n storeId,\n capturedAt: new Date().toISOString(),\n views: [...entries.values()]\n .map((entry) => viewRecord(entry, state))\n .sort((left, right) => left.viewId < right.viewId ? -1 : left.viewId > right.viewId ? 1 : 0),\n entityViewMembership: allEntityIdentities(state, memberships).map(({ type, id }) => ({\n type,\n id,\n viewIds: [...(memberships.get(graphDevtoolsEntityIdentityKey(type, id)) ?? [])],\n })),\n };\n },\n getViewIdsByEntity() {\n return viewIdsByEntity();\n },\n dispose() {\n disposed = true;\n entries.clear();\n },\n };\n}\n","import type { GraphStore } from \"../graph\";\nimport {\n graphDevtoolsEntityIdentityKey,\n projectGraphDevtoolsInspectionValue,\n} from \"./inspection\";\nimport type {\n GraphDevtoolsPreviewAppliedReceipt,\n GraphDevtoolsPreviewConflictReceipt,\n GraphDevtoolsPreviewRestoreReceipt,\n GraphDevtoolsValuePolicy,\n} from \"./protocol\";\n\ninterface RawPreviewReceipt {\n previewId: string;\n type: string;\n id: string;\n priorPatch: Record<string, unknown> | undefined;\n previewPatch: Record<string, unknown>;\n appliedPatch: Record<string, unknown>;\n baselineRevision: number;\n previewRevision: number;\n appliedAt: string;\n}\n\nexport interface GraphDevtoolsPreviewController {\n apply(type: string, id: string, patch: Record<string, unknown>): GraphDevtoolsPreviewAppliedReceipt | null;\n restore(previewId: string): GraphDevtoolsPreviewRestoreReceipt | null;\n dispose(): void;\n}\n\nfunction replaceEntityPatch(\n store: GraphStore,\n type: string,\n id: string,\n patch: Record<string, unknown> | undefined,\n): void {\n store.setState((state) => {\n const patches = { ...state.patches };\n const bucket = { ...(patches[type] ?? {}) };\n if (patch === undefined) delete bucket[id];\n else bucket[id] = { ...patch };\n if (Object.keys(bucket).length === 0) delete patches[type];\n else patches[type] = bucket;\n return { patches };\n });\n}\n\nexport function createGraphDevtoolsPreviewController(\n store: GraphStore,\n storeId: string,\n valuePolicy: GraphDevtoolsValuePolicy,\n valueRevisionFor: (type: string, id: string) => number,\n): GraphDevtoolsPreviewController {\n const receipts = new Map<string, RawPreviewReceipt>();\n const activeByEntity = new Map<string, string>();\n let nextPreview = 1;\n let disposed = false;\n\n const projectPatch = (type: string, id: string, value: unknown): unknown => (\n projectGraphDevtoolsInspectionValue(\n value,\n valuePolicy,\n { storeId, category: \"patch\", key: type, id },\n )\n );\n\n const removeReceipt = (receipt: RawPreviewReceipt) => {\n receipts.delete(receipt.previewId);\n const key = graphDevtoolsEntityIdentityKey(receipt.type, receipt.id);\n if (activeByEntity.get(key) === receipt.previewId) activeByEntity.delete(key);\n };\n\n return {\n apply(type, id, patch) {\n if (disposed || !store.getState().entities[type]?.[id]) return null;\n const key = graphDevtoolsEntityIdentityKey(type, id);\n const previousPreviewId = activeByEntity.get(key);\n if (previousPreviewId) receipts.delete(previousPreviewId);\n\n const storedPriorPatch = store.getState().patches[type]?.[id];\n const priorPatch = storedPriorPatch === undefined ? undefined : { ...storedPriorPatch };\n const previewPatch = { ...patch };\n const baselineRevision = valueRevisionFor(type, id);\n store.getState().patchEntity(type, id, previewPatch);\n const appliedPatch = { ...(store.getState().patches[type]?.[id] ?? {}) };\n const previewRevision = valueRevisionFor(type, id);\n const receipt: RawPreviewReceipt = {\n previewId: `preview-${storeId}-${nextPreview++}`,\n type,\n id,\n priorPatch,\n previewPatch,\n appliedPatch,\n baselineRevision,\n previewRevision,\n appliedAt: new Date().toISOString(),\n };\n receipts.set(receipt.previewId, receipt);\n activeByEntity.set(key, receipt.previewId);\n return {\n previewId: receipt.previewId,\n entity: { type, id },\n priorPatch: priorPatch === undefined ? null : projectPatch(type, id, priorPatch),\n previewPatch: projectPatch(type, id, previewPatch),\n appliedPatch: projectPatch(type, id, appliedPatch),\n baselineRevision,\n previewRevision,\n appliedAt: receipt.appliedAt,\n };\n },\n restore(previewId) {\n if (disposed) return null;\n const receipt = receipts.get(previewId);\n if (!receipt) return null;\n const observedRevision = valueRevisionFor(receipt.type, receipt.id);\n if (observedRevision !== receipt.previewRevision) {\n const currentPatch = store.getState().patches[receipt.type]?.[receipt.id];\n const conflict: GraphDevtoolsPreviewConflictReceipt = {\n previewId,\n status: \"conflict\",\n reason: \"entity-changed-since-preview\",\n expectedRevision: receipt.previewRevision,\n observedRevision,\n currentPatch: currentPatch === undefined\n ? null\n : projectPatch(receipt.type, receipt.id, currentPatch),\n priorPatch: receipt.priorPatch === undefined\n ? null\n : projectPatch(receipt.type, receipt.id, receipt.priorPatch),\n };\n removeReceipt(receipt);\n return conflict;\n }\n\n replaceEntityPatch(store, receipt.type, receipt.id, receipt.priorPatch);\n removeReceipt(receipt);\n return {\n previewId,\n status: \"restored\",\n restoredPatch: receipt.priorPatch === undefined\n ? null\n : projectPatch(receipt.type, receipt.id, receipt.priorPatch),\n observedRevision,\n restoredAt: new Date().toISOString(),\n };\n },\n dispose() {\n disposed = true;\n receipts.clear();\n activeByEntity.clear();\n },\n };\n}\n","import type { GraphState, GraphStore } from \"../graph\";\nimport {\n registerGraphDevtoolsCompatibilityDelegate,\n registerGraphDevtoolsCompatibilityFactory,\n} from \"../devtools-compatibility-bridge\";\nimport {\n advanceGraphDevtoolsEntityRevisions,\n graphDevtoolsEntityIdentitiesForStateKey,\n graphDevtoolsEntityIdentityKey,\n projectGraphDevtoolsEntityRecords,\n} from \"./inspection\";\nimport { collectGraphDevtoolsCounts, projectGraphDevtoolsChanges } from \"./projection\";\nimport {\n GRAPH_DEVTOOLS_PROTOCOL,\n GRAPH_DEVTOOLS_PROTOCOL_VERSION,\n type GraphDevtoolsCapabilities,\n type GraphDevtoolsCommand,\n type GraphDevtoolsCommandName,\n type GraphDevtoolsDiagnosticEvent,\n type GraphDevtoolsEvent,\n type GraphDevtoolsEntityRecordsSnapshot,\n type GraphDevtoolsGraphData,\n type GraphDevtoolsHistoryImportInspectionResult,\n type GraphDevtoolsHistoryImportRestoreReceipt,\n type GraphDevtoolsHistoryImportRestoreResult,\n type GraphDevtoolsHistoryStatus,\n type GraphDevtoolsInspectHistoryImportPayload,\n type GraphDevtoolsLifecycleEvent,\n type GraphDevtoolsMutationEvent,\n type GraphDevtoolsPreviewEntityPatchPayload,\n type GraphDevtoolsRewindPayload,\n type GraphDevtoolsRewindResult,\n type GraphDevtoolsRelationshipsSnapshot,\n type GraphDevtoolsRestoreEntityPreviewPayload,\n type GraphDevtoolsReturnToLiveReceipt,\n type GraphDevtoolsResult,\n type GraphDevtoolsSnapshot,\n type GraphDevtoolsSnapshotHistoryStatus,\n type GraphDevtoolsSnapshotReference,\n type GraphDevtoolsTimeTravelEvent,\n type GraphDevtoolsTransport,\n type GraphDevtoolsValuePolicy,\n type GraphDevtoolsViewDefinition,\n type GraphDevtoolsViewEvent,\n type GraphDevtoolsViewMembership,\n type GraphDevtoolsViewsSnapshot,\n} from \"./protocol\";\nimport { createGraphDevtoolsSnapshotHistory } from \"./time-travel\";\nimport {\n createGraphDevtoolsViewRegistry,\n type GraphDevtoolsViewRegistration,\n} from \"./views\";\nimport { projectGraphDevtoolsRelationships } from \"./relationships\";\nimport { createGraphDevtoolsPreviewController } from \"./previews\";\n\nexport interface AttachGraphDevtoolsOptions {\n /**\n * `false` makes only this attachment a no-op. It never tears down references\n * already held by other attachments to the same store.\n */\n enabled?: boolean;\n storeId?: string;\n historyLimit?: number;\n historyBytesLimit?: number;\n eventBytesLimit?: number;\n snapshotLimit?: number;\n snapshotBytesLimit?: number;\n values?: GraphDevtoolsValuePolicy;\n}\n\nexport interface GraphDevtoolsController {\n readonly storeId: string;\n readonly capabilities: GraphDevtoolsCapabilities;\n getSnapshot(): GraphDevtoolsSnapshot;\n getHistory(): ReadonlyArray<GraphDevtoolsEvent>;\n getHistoryStatus(): GraphDevtoolsHistoryStatus;\n getSnapshotHistoryStatus(): GraphDevtoolsSnapshotHistoryStatus;\n getSnapshotReferences(): ReadonlyArray<Extract<GraphDevtoolsSnapshotReference, { status: \"retained\" }>>;\n getCompatibilitySnapshotReferences(): ReadonlyArray<Extract<GraphDevtoolsSnapshotReference, { status: \"retained\" }>>;\n captureCompatibilitySnapshot(label?: string): number;\n configureSnapshotLimit(snapshotLimit: number): void;\n subscribeSnapshotHistory(listener: () => void): () => void;\n clearSnapshotHistory(): void;\n getEntityRecords(): GraphDevtoolsEntityRecordsSnapshot;\n getViews(): GraphDevtoolsViewsSnapshot;\n getRelationships(): GraphDevtoolsRelationshipsSnapshot;\n registerView(definition: GraphDevtoolsViewDefinition): GraphDevtoolsViewRegistration;\n rewind(cursor: number): GraphDevtoolsRewindResult | null;\n returnToLive(): GraphDevtoolsReturnToLiveReceipt | null;\n inspectHistoryImport(candidate: unknown): GraphDevtoolsHistoryImportInspectionResult;\n confirmHistoryImport(candidateId: string, cursor: number): GraphDevtoolsHistoryImportRestoreResult;\n clearHistory(): void;\n subscribe(listener: (event: GraphDevtoolsEvent) => void, replay?: boolean): () => void;\n connect(clientId?: string): GraphDevtoolsTransport;\n handleCommand(command: unknown): GraphDevtoolsResult;\n isDisposed(): boolean;\n}\n\nexport interface GraphDevtoolsAttachment {\n readonly enabled: boolean;\n readonly controller: GraphDevtoolsController | null;\n detach(): void;\n}\n\ninterface ControllerEntry {\n controller: GraphDevtoolsController;\n dispose(): void;\n references: number;\n}\n\ninterface CreatedController {\n controller: GraphDevtoolsController;\n dispose(): void;\n}\n\nconst controllers = new WeakMap<GraphStore, ControllerEntry>();\nconst storeNumbers = new WeakMap<GraphStore, number>();\nlet nextStoreNumber = 1;\n\nfunction nowDuration(): number {\n return globalThis.performance?.now() ?? Date.now();\n}\n\nfunction boundedLimit(value: number | undefined, fallback: number, minimum = 0): number {\n const candidate = value ?? fallback;\n return Number.isFinite(candidate) ? Math.max(minimum, Math.floor(candidate)) : fallback;\n}\n\nfunction storeIdFor(store: GraphStore): string {\n let number = storeNumbers.get(store);\n if (number === undefined) {\n number = nextStoreNumber++;\n storeNumbers.set(store, number);\n }\n return `graph-${number}`;\n}\n\nfunction resultError(\n storeId: string,\n requestId: string,\n code: Extract<GraphDevtoolsResult, { ok: false }>[\"error\"][\"code\"],\n message: string,\n): GraphDevtoolsResult {\n return {\n protocol: GRAPH_DEVTOOLS_PROTOCOL,\n version: GRAPH_DEVTOOLS_PROTOCOL_VERSION,\n requestId,\n storeId,\n ok: false,\n error: { code, message },\n };\n}\n\nfunction parseCommand(command: unknown): GraphDevtoolsCommand | null {\n if (typeof command !== \"object\" || command === null) return null;\n const candidate = command as Partial<GraphDevtoolsCommand>;\n if (\n candidate.protocol !== GRAPH_DEVTOOLS_PROTOCOL ||\n typeof candidate.version !== \"number\" ||\n typeof candidate.requestId !== \"string\" ||\n typeof candidate.storeId !== \"string\" ||\n typeof candidate.command !== \"string\"\n ) return null;\n return candidate as GraphDevtoolsCommand;\n}\n\nfunction parsePreviewPayload(payload: unknown): GraphDevtoolsPreviewEntityPatchPayload | null {\n if (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) return null;\n const candidate = payload as Partial<GraphDevtoolsPreviewEntityPatchPayload>;\n if (\n typeof candidate.type !== \"string\" || candidate.type.length === 0 ||\n typeof candidate.id !== \"string\" || candidate.id.length === 0 ||\n typeof candidate.patch !== \"object\" || candidate.patch === null || Array.isArray(candidate.patch) ||\n Object.keys(candidate.patch).length === 0\n ) return null;\n return candidate as GraphDevtoolsPreviewEntityPatchPayload;\n}\n\nfunction parseRestorePreviewPayload(payload: unknown): GraphDevtoolsRestoreEntityPreviewPayload | null {\n if (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) return null;\n const previewId = (payload as Partial<GraphDevtoolsRestoreEntityPreviewPayload>).previewId;\n return typeof previewId === \"string\" && previewId.length > 0 ? { previewId } : null;\n}\n\nfunction parseRewindPayload(payload: unknown): GraphDevtoolsRewindPayload | null {\n if (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) return null;\n const cursor = (payload as Partial<GraphDevtoolsRewindPayload>).cursor;\n return typeof cursor === \"number\" && Number.isSafeInteger(cursor) && cursor > 0\n ? { cursor }\n : null;\n}\n\nfunction parseInspectHistoryImportPayload(\n payload: unknown,\n): GraphDevtoolsInspectHistoryImportPayload | null {\n if (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) return null;\n if (!Object.prototype.hasOwnProperty.call(payload, \"candidate\")) return null;\n return { candidate: (payload as GraphDevtoolsInspectHistoryImportPayload).candidate };\n}\n\ninterface ParsedConfirmHistoryImportPayload {\n candidateId: string;\n cursor: number;\n confirm: boolean;\n}\n\nfunction parseConfirmHistoryImportPayload(\n payload: unknown,\n): ParsedConfirmHistoryImportPayload | null {\n if (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) return null;\n const candidate = payload as Partial<ParsedConfirmHistoryImportPayload>;\n if (\n typeof candidate.candidateId !== \"string\" || candidate.candidateId.length === 0 ||\n typeof candidate.cursor !== \"number\" || !Number.isSafeInteger(candidate.cursor) || candidate.cursor <= 0 ||\n typeof candidate.confirm !== \"boolean\"\n ) return null;\n return candidate as ParsedConfirmHistoryImportPayload;\n}\n\nfunction createController(\n store: GraphStore,\n options: AttachGraphDevtoolsOptions,\n): CreatedController {\n const storeId = options.storeId ?? storeIdFor(store);\n const historyLimit = boundedLimit(options.historyLimit, 500);\n const historyBytesLimit = boundedLimit(options.historyBytesLimit, 5 * 1024 * 1024);\n const eventBytesLimit = boundedLimit(options.eventBytesLimit, 256 * 1024, 1024);\n const snapshotLimit = boundedLimit(options.snapshotLimit, 50);\n const snapshotBytesLimit = boundedLimit(options.snapshotBytesLimit, 10 * 1024 * 1024);\n const timeTravelEnabled = snapshotLimit > 0 && snapshotBytesLimit > 0;\n const timeTravelCommands: GraphDevtoolsCommandName[] = timeTravelEnabled\n ? [\n \"get-time-travel-status\",\n \"rewind\",\n \"return-to-live\",\n \"inspect-history-import\",\n \"confirm-history-import\",\n ]\n : [];\n const timeTravelFeatures: Array<GraphDevtoolsCapabilities[\"features\"][number]> = timeTravelEnabled\n ? [\"snapshot-history\", \"time-travel\", \"history-import\"]\n : [];\n const valuePolicy = options.values ?? { mode: \"metadata-only\" };\n const capabilities: GraphDevtoolsCapabilities = {\n protocolVersion: GRAPH_DEVTOOLS_PROTOCOL_VERSION,\n metadataOnlyByDefault: true,\n commands: [\n \"get-capabilities\",\n \"get-snapshot\",\n \"get-history\",\n \"get-history-status\",\n \"get-entity-records\",\n \"get-views\",\n \"get-relationships\",\n \"preview-entity-patch\",\n \"restore-entity-preview\",\n ...timeTravelCommands,\n \"clear-history\",\n ],\n features: [\n \"semantic-events\",\n \"diagnostic-events\",\n \"bounded-history\",\n \"multi-client\",\n \"multi-store\",\n \"entity-inspection\",\n \"view-inspection\",\n \"relationship-inspection\",\n \"local-preview\",\n ...timeTravelFeatures,\n ],\n limits: {\n historyEvents: historyLimit,\n historyBytes: historyBytesLimit,\n eventBytes: eventBytesLimit,\n snapshots: snapshotLimit,\n snapshotBytes: snapshotBytesLimit,\n },\n };\n const listeners = new Set<(event: GraphDevtoolsEvent) => void>();\n const history: GraphDevtoolsEvent[] = [];\n const historySizes: number[] = [];\n const entityRevisions = new Map<string, number>();\n const entityValueRevisions = new Map<string, number>();\n let retainedBytes = 0;\n let sequence = 0;\n let activeClients = 0;\n let nextClientNumber = 1;\n let disposed = false;\n let projectionFailureRevision = 0;\n let internalReplayDepth = 0;\n const snapshotHistory = createGraphDevtoolsSnapshotHistory({\n snapshotLimit,\n snapshotBytesLimit,\n });\n snapshotHistory.capture(store.getState(), null);\n\n const nextBase = () => {\n const current = ++sequence;\n const eventId = `${storeId}:${current}`;\n return {\n protocol: GRAPH_DEVTOOLS_PROTOCOL,\n version: GRAPH_DEVTOOLS_PROTOCOL_VERSION,\n storeId,\n sequence: current,\n eventId,\n correlationId: eventId,\n observedAt: new Date().toISOString(),\n } as const;\n };\n\n const encodedBytes = (value: unknown) => new TextEncoder().encode(JSON.stringify(value)).byteLength;\n\n const boundEvent = (event: GraphDevtoolsEvent): GraphDevtoolsEvent => {\n if (event.type !== \"mutation\") return event;\n if (encodedBytes(event) <= eventBytesLimit) return event;\n const valuesTruncated = event.payload.changes.some(\n (change) => \"before\" in change || \"after\" in change,\n );\n const withoutValues: GraphDevtoolsMutationEvent = {\n ...event,\n payload: {\n ...event.payload,\n valuesTruncated,\n changes: event.payload.changes.map(({ before: _before, after: _after, ...change }) => ({\n ...change,\n valueState:\n change.valueState === \"hidden-by-policy\" || change.valueState === \"redaction-error\"\n ? change.valueState\n : \"truncated\",\n })),\n },\n };\n if (encodedBytes(withoutValues) <= eventBytesLimit) return withoutValues;\n\n const emptyWithAffectedMetadata: GraphDevtoolsMutationEvent = {\n ...withoutValues,\n payload: {\n ...withoutValues.payload,\n changes: [],\n changesOmitted: withoutValues.payload.changes.length,\n },\n };\n const { affectedEntities: _affectedEntities, affectedViewIds: _affectedViewIds, ...compactPayload } =\n withoutValues.payload;\n const boundedBase = encodedBytes(emptyWithAffectedMetadata) <= eventBytesLimit\n ? withoutValues\n : { ...withoutValues, payload: compactPayload };\n let lower = 0;\n let upper = withoutValues.payload.changes.length;\n let bounded: GraphDevtoolsMutationEvent = {\n ...boundedBase,\n payload: {\n ...boundedBase.payload,\n changes: [],\n changesOmitted: withoutValues.payload.changes.length,\n },\n };\n while (lower <= upper) {\n const count = Math.floor((lower + upper) / 2);\n const candidate: GraphDevtoolsMutationEvent = {\n ...boundedBase,\n payload: {\n ...boundedBase.payload,\n changes: withoutValues.payload.changes.slice(0, count),\n changesOmitted: withoutValues.payload.changes.length - count,\n },\n };\n if (encodedBytes(candidate) <= eventBytesLimit) {\n bounded = candidate;\n lower = count + 1;\n } else {\n upper = count - 1;\n }\n }\n return bounded;\n };\n\n const publish = (candidate: GraphDevtoolsEvent) => {\n if (disposed) return;\n const event = boundEvent(candidate);\n if (historyLimit > 0 && historyBytesLimit > 0) {\n const size = encodedBytes(event);\n history.push(event);\n historySizes.push(size);\n retainedBytes += size;\n while (history.length > historyLimit || retainedBytes > historyBytesLimit) {\n history.shift();\n retainedBytes -= historySizes.shift() ?? 0;\n }\n }\n for (const listener of [...listeners]) {\n try {\n listener(event);\n } catch {\n // Tooling listeners are isolated from the production graph boundary.\n }\n }\n };\n\n const publishLifecycle = (\n state: GraphDevtoolsLifecycleEvent[\"payload\"][\"state\"],\n clientId?: string,\n ) => {\n publish({\n ...nextBase(),\n type: \"lifecycle\",\n payload: {\n state,\n ...(clientId !== undefined ? { clientId } : {}),\n activeClients,\n },\n });\n };\n\n const publishTimeTravel = (\n state: GraphDevtoolsTimeTravelEvent[\"payload\"][\"state\"],\n cursor: number | null,\n previousCursor: number | null,\n source: GraphDevtoolsTimeTravelEvent[\"payload\"][\"source\"],\n previousSource: GraphDevtoolsTimeTravelEvent[\"payload\"][\"previousSource\"],\n reason: GraphDevtoolsTimeTravelEvent[\"payload\"][\"reason\"],\n ): GraphDevtoolsTimeTravelEvent => {\n const event: GraphDevtoolsTimeTravelEvent = {\n ...nextBase(),\n type: \"time-travel\",\n payload: { state, cursor, previousCursor, source, previousSource, reason },\n };\n publish(event);\n return event;\n };\n\n const restoreGraphData = (data: GraphDevtoolsGraphData) => {\n internalReplayDepth += 1;\n try {\n store.setState(data as Partial<GraphState>);\n } finally {\n internalReplayDepth -= 1;\n }\n };\n\n const leaveRewindForMutation = () => {\n const previous = snapshotHistory.leaveRewindForMutation();\n if (previous === null) return;\n projectionFailureRevision += 1;\n publishTimeTravel(\n \"live\",\n null,\n previous.previousCursor,\n null,\n previous.previousSource,\n \"mutation\",\n );\n };\n\n const viewRegistry = createGraphDevtoolsViewRegistry(storeId, () => store.getState(), (payload) => {\n const event: GraphDevtoolsViewEvent = { ...nextBase(), type: \"view\", payload };\n publish(event);\n });\n\n const affectedProjection = (\n changes: GraphDevtoolsMutationEvent[\"payload\"][\"changes\"],\n previous: GraphState,\n current: GraphState,\n ): { affectedEntities: GraphDevtoolsViewMembership[]; affectedViewIds: string[] } => {\n const identities = new Map<string, GraphDevtoolsViewMembership>();\n const changedListKeys = new Set<string>();\n for (const change of changes) {\n if ((change.category === \"entity\" || change.category === \"patch\") && change.id !== undefined) {\n identities.set(graphDevtoolsEntityIdentityKey(change.key, change.id), {\n type: change.key,\n id: change.id,\n });\n } else if (change.category === \"entity-state\" || change.category === \"sync\") {\n const stateIdentities = [\n ...graphDevtoolsEntityIdentitiesForStateKey(previous, change.key),\n ...graphDevtoolsEntityIdentitiesForStateKey(current, change.key),\n ];\n for (const identity of stateIdentities) {\n identities.set(graphDevtoolsEntityIdentityKey(identity.type, identity.id), identity);\n }\n } else if (change.category === \"list\") {\n changedListKeys.add(change.key);\n }\n }\n\n const views = viewRegistry.getSnapshot().views;\n const affectedViewIds = new Set<string>();\n for (const view of views) {\n if (view.queryKey !== null && changedListKeys.has(view.queryKey)) {\n affectedViewIds.add(view.viewId);\n const previousIds = previous.lists[view.queryKey]?.ids ?? [];\n const currentIds = current.lists[view.queryKey]?.ids ?? [];\n const previousPositions = new Map(previousIds.map((id, index) => [id, index]));\n const currentPositions = new Map(currentIds.map((id, index) => [id, index]));\n const ids = new Set([...previousIds, ...currentIds]);\n for (const id of ids) {\n if (previousPositions.get(id) === currentPositions.get(id)) continue;\n identities.set(graphDevtoolsEntityIdentityKey(view.entityType, id), {\n type: view.entityType,\n id,\n });\n }\n }\n if (view.membership.some((member) => (\n identities.has(graphDevtoolsEntityIdentityKey(member.type, member.id))\n ))) {\n affectedViewIds.add(view.viewId);\n }\n }\n\n return {\n affectedEntities: [...identities.values()],\n affectedViewIds: [...affectedViewIds].sort(),\n };\n };\n\n const unsubscribeStore = store.subscribe((current: GraphState, previous: GraphState) => {\n if (disposed || internalReplayDepth > 0) return;\n const startedAt = nowDuration();\n let changes: GraphDevtoolsMutationEvent[\"payload\"][\"changes\"];\n try {\n changes = projectGraphDevtoolsChanges(previous, current, valuePolicy, storeId);\n } catch {\n // The failed projection cannot prove which values changed. Advance a\n // controller-wide epoch so every active preview refuses a possibly\n // destructive restore rather than treating an unknown publication as safe.\n leaveRewindForMutation();\n projectionFailureRevision += 1;\n const base = nextBase();\n const event: GraphDevtoolsDiagnosticEvent = {\n ...base,\n type: \"diagnostic\",\n payload: {\n code: \"projection-failed\",\n message: \"A graph publication could not be projected for DevTools.\",\n snapshot: snapshotHistory.capture(current, base.sequence),\n },\n };\n publish(event);\n return;\n }\n if (changes.length === 0) return;\n leaveRewindForMutation();\n advanceGraphDevtoolsEntityRevisions(changes, entityRevisions, current, entityValueRevisions);\n const affected = affectedProjection(changes, previous, current);\n const base = nextBase();\n const event: GraphDevtoolsMutationEvent = {\n ...base,\n type: \"mutation\",\n payload: {\n snapshot: snapshotHistory.capture(current, base.sequence),\n valuesTruncated: false,\n changesOmitted: 0,\n changes,\n ...affected,\n before: collectGraphDevtoolsCounts(previous),\n after: collectGraphDevtoolsCounts(current),\n projectionDurationMs: Math.max(0, nowDuration() - startedAt),\n },\n };\n publish(event);\n });\n\n const previewController = createGraphDevtoolsPreviewController(\n store,\n storeId,\n valuePolicy,\n (type, id) => (\n (entityValueRevisions.get(graphDevtoolsEntityIdentityKey(type, id)) ?? 0) +\n projectionFailureRevision\n ),\n );\n\n const controller: GraphDevtoolsController = {\n storeId,\n capabilities,\n getSnapshot() {\n return {\n protocol: GRAPH_DEVTOOLS_PROTOCOL,\n version: GRAPH_DEVTOOLS_PROTOCOL_VERSION,\n storeId,\n capturedAt: new Date().toISOString(),\n counts: collectGraphDevtoolsCounts(store.getState()),\n history: controller.getHistoryStatus(),\n snapshots: controller.getSnapshotHistoryStatus(),\n };\n },\n getHistory() {\n return [...history];\n },\n getHistoryStatus() {\n return {\n retainedEvents: history.length,\n retainedBytes,\n eventLimit: historyLimit,\n byteLimit: historyBytesLimit,\n oldestSequence: history[0]?.sequence ?? null,\n newestSequence: history.length > 0 ? history[history.length - 1]!.sequence : null,\n };\n },\n getSnapshotHistoryStatus() {\n return snapshotHistory.getStatus();\n },\n getSnapshotReferences() {\n return snapshotHistory.getReferences();\n },\n getCompatibilitySnapshotReferences() {\n return snapshotHistory.getCompatibilityReferences();\n },\n captureCompatibilitySnapshot(label) {\n const reference = snapshotHistory.captureCompatibility(store.getState(), label);\n return reference.status === \"retained\" ? reference.cursor : -1;\n },\n configureSnapshotLimit(nextSnapshotLimit) {\n snapshotHistory.configureLimit(nextSnapshotLimit);\n capabilities.limits.snapshots = snapshotHistory.getStatus().snapshotLimit;\n },\n subscribeSnapshotHistory(listener) {\n return snapshotHistory.subscribe(listener);\n },\n clearSnapshotHistory() {\n snapshotHistory.clear();\n },\n getEntityRecords() {\n return projectGraphDevtoolsEntityRecords(\n store.getState(),\n storeId,\n entityRevisions,\n valuePolicy,\n viewRegistry.getViewIdsByEntity(),\n );\n },\n getViews() {\n return viewRegistry.getSnapshot();\n },\n getRelationships() {\n return projectGraphDevtoolsRelationships(store.getState(), storeId);\n },\n registerView(definition) {\n return viewRegistry.register(definition);\n },\n rewind(cursor) {\n if (!timeTravelEnabled) return null;\n const attempt = snapshotHistory.rewind(cursor, store.getState(), restoreGraphData);\n if (attempt === null || attempt.status === \"expired-history\") return attempt;\n projectionFailureRevision += 1;\n const event = publishTimeTravel(\n \"rewound\",\n cursor,\n attempt.previousCursor,\n \"retained\",\n attempt.previousSource,\n \"command\",\n );\n return {\n status: \"rewound\",\n cursor,\n source: \"retained\",\n previousCursor: attempt.previousCursor,\n previousSource: attempt.previousSource,\n changedAt: event.observedAt,\n };\n },\n returnToLive() {\n if (!timeTravelEnabled) return null;\n const previous = snapshotHistory.returnToLive(restoreGraphData);\n if (previous === null) return null;\n projectionFailureRevision += 1;\n const event = publishTimeTravel(\n \"live\",\n null,\n previous.previousCursor,\n null,\n previous.previousSource,\n \"command\",\n );\n return {\n status: \"live\",\n cursor: null,\n previousCursor: previous.previousCursor,\n previousSource: previous.previousSource,\n reason: \"command\",\n changedAt: event.observedAt,\n };\n },\n inspectHistoryImport(candidate) {\n if (disposed) {\n return { status: \"rejected\", reason: \"disposed\", message: \"DevTools controller is disposed\" };\n }\n if (!timeTravelEnabled) {\n return {\n status: \"rejected\",\n reason: \"time-travel-unavailable\",\n message: \"Time travel is disabled for this controller\",\n };\n }\n return snapshotHistory.inspectImport(candidate, storeId);\n },\n confirmHistoryImport(candidateId, cursor) {\n if (disposed) {\n return { status: \"rejected\", reason: \"disposed\", message: \"DevTools controller is disposed\" };\n }\n if (!timeTravelEnabled) {\n return {\n status: \"rejected\",\n reason: \"time-travel-unavailable\",\n message: \"Time travel is disabled for this controller\",\n };\n }\n const attempt = snapshotHistory.restoreImport(\n candidateId,\n cursor,\n store.getState(),\n restoreGraphData,\n );\n if (attempt.status === \"candidate-not-found\") {\n return {\n status: \"rejected\",\n reason: \"candidate-not-found\",\n message: `Import candidate ${candidateId} is no longer awaiting confirmation`,\n };\n }\n if (attempt.status === \"snapshot-not-found\") {\n return {\n status: \"rejected\",\n reason: \"snapshot-not-found\",\n message: `Import candidate ${candidateId} does not contain cursor ${cursor}`,\n };\n }\n if (attempt.status === \"restore-failed\") {\n return {\n status: \"rejected\",\n reason: \"restore-failed\",\n message: `Import candidate ${candidateId} could not be restored through the graph boundary`,\n };\n }\n projectionFailureRevision += 1;\n const event = publishTimeTravel(\n \"rewound\",\n cursor,\n attempt.previousCursor,\n \"import\",\n attempt.previousSource,\n \"import\",\n );\n const receipt: GraphDevtoolsHistoryImportRestoreReceipt = {\n status: \"rewound\",\n source: \"import\",\n candidateId,\n cursor,\n previousCursor: attempt.previousCursor,\n previousSource: attempt.previousSource,\n changedAt: event.observedAt,\n };\n return receipt;\n },\n clearHistory() {\n history.length = 0;\n historySizes.length = 0;\n retainedBytes = 0;\n snapshotHistory.clear();\n },\n subscribe(listener, replay = false) {\n if (disposed) return () => {};\n if (replay) {\n for (const event of [...history]) {\n try {\n listener(event);\n } catch {\n // Replay delivery has the same listener isolation as live delivery.\n }\n }\n }\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n connect(clientId = `client-${nextClientNumber++}`) {\n if (disposed) return createDisposedTransport(storeId, clientId);\n activeClients += 1;\n publishLifecycle(\"client-connected\", clientId);\n let closed = false;\n const connectionSubscriptions = new Set<() => void>();\n return {\n request(command) {\n if (closed) {\n const parsed = parseCommand(command);\n return Promise.resolve(resultError(\n storeId,\n parsed?.requestId ?? \"closed\",\n \"disposed\",\n \"DevTools client is disconnected\",\n ));\n }\n return Promise.resolve(controller.handleCommand(command));\n },\n subscribe(listener) {\n if (closed) return () => {};\n const unsubscribe = controller.subscribe(listener);\n connectionSubscriptions.add(unsubscribe);\n return () => {\n connectionSubscriptions.delete(unsubscribe);\n unsubscribe();\n };\n },\n close() {\n if (closed) return;\n closed = true;\n for (const unsubscribe of connectionSubscriptions) unsubscribe();\n connectionSubscriptions.clear();\n activeClients = Math.max(0, activeClients - 1);\n publishLifecycle(\"client-disconnected\", clientId);\n },\n };\n },\n handleCommand(command) {\n const parsed = parseCommand(command);\n const requestId = parsed?.requestId ?? \"invalid\";\n if (disposed) return resultError(storeId, requestId, \"disposed\", \"DevTools controller is disposed\");\n if (!parsed) return resultError(storeId, requestId, \"invalid-envelope\", \"Invalid DevTools command envelope\");\n if (parsed.version !== GRAPH_DEVTOOLS_PROTOCOL_VERSION) {\n return resultError(storeId, parsed.requestId, \"unsupported-version\", `Unsupported DevTools protocol version ${parsed.version}`);\n }\n if (parsed.storeId !== storeId) {\n return resultError(storeId, parsed.requestId, \"wrong-store\", `Command targets ${parsed.storeId}, not ${storeId}`);\n }\n\n let result: Extract<GraphDevtoolsResult, { ok: true }>[\"result\"];\n switch (parsed.command) {\n case \"get-capabilities\": result = capabilities; break;\n case \"get-snapshot\": result = controller.getSnapshot(); break;\n case \"get-history\": result = controller.getHistory(); break;\n case \"get-history-status\": result = controller.getHistoryStatus(); break;\n case \"get-entity-records\": result = controller.getEntityRecords(); break;\n case \"get-views\": result = controller.getViews(); break;\n case \"get-relationships\": result = controller.getRelationships(); break;\n case \"get-time-travel-status\": {\n if (!timeTravelEnabled) return resultError(storeId, parsed.requestId, \"time-travel-unavailable\", \"Time travel is disabled for this controller\");\n result = controller.getSnapshotHistoryStatus();\n break;\n }\n case \"rewind\": {\n if (!timeTravelEnabled) return resultError(storeId, parsed.requestId, \"time-travel-unavailable\", \"Time travel is disabled for this controller\");\n const payload = parseRewindPayload(parsed.payload);\n if (!payload) return resultError(storeId, parsed.requestId, \"invalid-payload\", \"Invalid rewind payload\");\n const receipt = controller.rewind(payload.cursor);\n if (!receipt) return resultError(storeId, parsed.requestId, \"snapshot-not-found\", `Snapshot cursor ${payload.cursor} is not retained`);\n result = receipt;\n break;\n }\n case \"return-to-live\": {\n if (!timeTravelEnabled) return resultError(storeId, parsed.requestId, \"time-travel-unavailable\", \"Time travel is disabled for this controller\");\n const receipt = controller.returnToLive();\n if (!receipt) return resultError(storeId, parsed.requestId, \"not-rewound\", \"The graph is already live\");\n result = receipt;\n break;\n }\n case \"inspect-history-import\": {\n if (!timeTravelEnabled) return resultError(storeId, parsed.requestId, \"time-travel-unavailable\", \"Time travel is disabled for this controller\");\n const payload = parseInspectHistoryImportPayload(parsed.payload);\n if (!payload) return resultError(storeId, parsed.requestId, \"invalid-payload\", \"Invalid history import inspection payload\");\n result = controller.inspectHistoryImport(payload.candidate);\n break;\n }\n case \"confirm-history-import\": {\n if (!timeTravelEnabled) return resultError(storeId, parsed.requestId, \"time-travel-unavailable\", \"Time travel is disabled for this controller\");\n const payload = parseConfirmHistoryImportPayload(parsed.payload);\n if (!payload) return resultError(storeId, parsed.requestId, \"invalid-payload\", \"Invalid history import confirmation payload\");\n if (!payload.confirm) return resultError(storeId, parsed.requestId, \"confirmation-required\", \"History import restore requires confirm: true\");\n result = controller.confirmHistoryImport(payload.candidateId, payload.cursor);\n break;\n }\n case \"preview-entity-patch\": {\n const payload = parsePreviewPayload(parsed.payload);\n if (!payload) return resultError(storeId, parsed.requestId, \"invalid-payload\", \"Invalid entity preview payload\");\n const receipt = previewController.apply(payload.type, payload.id, payload.patch);\n if (!receipt) return resultError(storeId, parsed.requestId, \"entity-not-found\", `Entity ${payload.type}:${payload.id} was not found`);\n result = receipt;\n break;\n }\n case \"restore-entity-preview\": {\n const payload = parseRestorePreviewPayload(parsed.payload);\n if (!payload) return resultError(storeId, parsed.requestId, \"invalid-payload\", \"Invalid preview restore payload\");\n const receipt = previewController.restore(payload.previewId);\n if (!receipt) return resultError(storeId, parsed.requestId, \"preview-not-found\", `Preview ${payload.previewId} was not found`);\n result = receipt;\n break;\n }\n case \"clear-history\": controller.clearHistory(); result = { cleared: true }; break;\n default:\n return resultError(storeId, parsed.requestId, \"unsupported-command\", `Unsupported DevTools command ${parsed.command}`);\n }\n return {\n protocol: GRAPH_DEVTOOLS_PROTOCOL,\n version: GRAPH_DEVTOOLS_PROTOCOL_VERSION,\n requestId: parsed.requestId,\n storeId,\n ok: true,\n result,\n };\n },\n isDisposed() {\n return disposed;\n },\n };\n\n const unregisterCompatibility = registerGraphDevtoolsCompatibilityDelegate(store, {\n configure(capacity) {\n controller.configureSnapshotLimit(capacity);\n },\n capture(label) {\n return controller.captureCompatibilitySnapshot(label);\n },\n restoreByIndex(index) {\n if (!Number.isInteger(index)) return false;\n const reference = controller.getCompatibilitySnapshotReferences()[index];\n if (!reference) return false;\n return controller.rewind(reference.cursor)?.status === \"rewound\";\n },\n restoreByCursor(cursor) {\n return controller.rewind(cursor)?.status === \"rewound\";\n },\n step(delta) {\n if (!Number.isInteger(delta)) return false;\n const references = controller.getCompatibilitySnapshotReferences();\n if (references.length === 0) return false;\n const status = controller.getSnapshotHistoryStatus();\n const activeIndex = status.source === \"retained\" && status.cursor !== null\n ? references.findIndex((reference) => reference.cursor === status.cursor)\n : -1;\n const base = activeIndex === -1 ? references.length - 1 : activeIndex;\n const target = Math.max(0, Math.min(references.length - 1, base + delta));\n return controller.rewind(references[target]!.cursor)?.status === \"rewound\";\n },\n getState() {\n const references = controller.getCompatibilitySnapshotReferences();\n const status = controller.getSnapshotHistoryStatus();\n const cursor = status.source === \"retained\" && status.cursor !== null\n ? references.findIndex((reference) => reference.cursor === status.cursor)\n : -1;\n return {\n snapshots: references.map((reference) => ({\n seq: reference.cursor,\n at: Date.parse(reference.capturedAt),\n ...(reference.label !== undefined ? { label: reference.label } : {}),\n })),\n cursor: cursor === -1 ? null : cursor,\n capacity: status.snapshotLimit,\n };\n },\n subscribe(listener) {\n return controller.subscribeSnapshotHistory(listener);\n },\n clear() {\n controller.clearSnapshotHistory();\n },\n });\n\n const dispose = () => {\n if (disposed) return;\n activeClients = 0;\n publishLifecycle(\"disposed\");\n disposed = true;\n unregisterCompatibility();\n unsubscribeStore();\n listeners.clear();\n history.length = 0;\n historySizes.length = 0;\n retainedBytes = 0;\n entityRevisions.clear();\n entityValueRevisions.clear();\n viewRegistry.dispose();\n previewController.dispose();\n snapshotHistory.dispose();\n };\n\n publishLifecycle(\"attached\");\n return { controller, dispose };\n}\n\nfunction createDisposedTransport(storeId: string, clientId: string): GraphDevtoolsTransport {\n return {\n request(command) {\n const parsed = parseCommand(command);\n return Promise.resolve(resultError(\n storeId,\n parsed?.requestId ?? clientId,\n \"disposed\",\n \"DevTools controller is disposed\",\n ));\n },\n subscribe() {\n return () => {};\n },\n close() {},\n };\n}\n\n/** Attach or reference the one DevTools controller owned by `store`. */\nexport function attachGraphDevtools(\n store: GraphStore,\n options: AttachGraphDevtoolsOptions = {},\n): GraphDevtoolsAttachment {\n if (options.enabled === false) {\n return { enabled: false, controller: null, detach() {} };\n }\n\n let entry = controllers.get(store);\n if (!entry || entry.controller.isDisposed()) {\n entry = { ...createController(store, options), references: 0 };\n controllers.set(store, entry);\n }\n entry.references += 1;\n let detached = false;\n\n return {\n enabled: true,\n controller: entry.controller,\n detach() {\n if (detached) return;\n detached = true;\n const current = controllers.get(store);\n if (!current || current.controller !== entry?.controller) return;\n current.references = Math.max(0, current.references - 1);\n if (current.references === 0) {\n current.dispose();\n controllers.delete(store);\n }\n },\n };\n}\n\n/** Return the currently attached controller without changing its lifetime. */\nexport function getGraphDevtoolsController(store: GraphStore): GraphDevtoolsController | null {\n const entry = controllers.get(store);\n return entry && !entry.controller.isDisposed() ? entry.controller : null;\n}\n\nregisterGraphDevtoolsCompatibilityFactory((store) => {\n const attachment = attachGraphDevtools(store);\n return () => attachment.detach();\n});\n","import {\n GRAPH_DEVTOOLS_PROTOCOL,\n GRAPH_DEVTOOLS_PROTOCOL_VERSION,\n type GraphDevtoolsCommandName,\n type GraphDevtoolsEvent,\n type GraphDevtoolsResult,\n type GraphDevtoolsTransport,\n} from \"./protocol\";\n\nexport interface GraphDevtoolsClient {\n readonly storeId: string;\n request(command: GraphDevtoolsCommandName, payload?: unknown): Promise<GraphDevtoolsResult>;\n subscribe(listener: (event: GraphDevtoolsEvent) => void): () => void;\n disconnect(): void;\n}\n\nlet nextRequest = 1;\n\n/** Protocol client that depends only on a transport, not Zustand or a UI runtime. */\nexport function createGraphDevtoolsClient(\n storeId: string,\n transport: GraphDevtoolsTransport,\n): GraphDevtoolsClient {\n let disconnected = false;\n return {\n storeId,\n request(command, payload) {\n const requestId = `request-${nextRequest++}`;\n return transport.request({\n protocol: GRAPH_DEVTOOLS_PROTOCOL,\n version: GRAPH_DEVTOOLS_PROTOCOL_VERSION,\n requestId,\n storeId,\n command,\n ...(payload !== undefined ? { payload } : {}),\n });\n },\n subscribe(listener) {\n if (disconnected) return () => {};\n return transport.subscribe(listener);\n },\n disconnect() {\n if (disconnected) return;\n disconnected = true;\n transport.close();\n },\n };\n}\n"]}