{"version":3,"sources":["/home/runner/work/kora/kora/packages/store/dist/chunk-OTLAUBFG.cjs","../src/multi-tab/version-gate.ts","../src/multi-tab/open-seq.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACWA,oCAAoC;ADTpC;AACA;AEJA,IAAM,cAAA,EAAgB,WAAA;AACtB,IAAM,WAAA,EAAa,UAAA;AAEnB,SAAS,gBAAA,CAAA,EAAyC;AACjD,EAAA,OAAO,IAAI,OAAA,CAAqB,CAAC,OAAA,EAAS,MAAA,EAAA,GAAW;AACpD,IAAA,MAAM,QAAA,EAAU,SAAA,CAAU,IAAA,CAAK,aAAA,EAAe,CAAC,CAAA;AAC/C,IAAA,OAAA,CAAQ,gBAAA,EAAkB,CAAA,EAAA,GAAM;AAC/B,MAAA,GAAA,CAAI,CAAC,OAAA,CAAQ,MAAA,CAAO,gBAAA,CAAiB,QAAA,CAAS,UAAU,CAAA,EAAG;AAC1D,QAAA,OAAA,CAAQ,MAAA,CAAO,iBAAA,CAAkB,UAAU,CAAA;AAAA,MAC5C;AAAA,IACD,CAAA;AACA,IAAA,OAAA,CAAQ,UAAA,EAAY,CAAA,EAAA,GAAM,OAAA,CAAQ,OAAA,CAAQ,MAAM,CAAA;AAChD,IAAA,OAAA,CAAQ,QAAA,EAAU,CAAA,EAAA,GACjB,MAAA;AAAA,MACC,IAAI,uCAAA;AAAA,QACH,CAAA,sDAAA,mCAAyD,OAAA,mBAAQ,KAAA,6BAAO,SAAA,UAAW,iBAAe,CAAA,CAAA;AACxE,QAAA;AAC3B,MAAA;AACD,IAAA;AACD,EAAA;AACF;AAYuE;AAChC,EAAA;AAC3B,IAAA;AACqD,MAAA;AACvB,MAAA;AACxC,IAAA;AACD,EAAA;AACkC,EAAA;AAC9B,EAAA;AACmD,IAAA;AACJ,MAAA;AACV,MAAA;AACvB,MAAA;AACa,MAAA;AACN,MAAA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AAA;AACxB,IAAA;AACmB,oBAAA;AACZ,MAAA;AACO,MAAA;AACoB,MAAA;AACxB,MAAA;AACT,IAAA;AACgF,IAAA;AACnB,MAAA;AACtC,MAAA;AACJ,MAAA;AACpB,IAAA;AAC4C,IAAA;AAC7B,IAAA;AAChB,EAAA;AAAA;AAGoD,EAAA;AACnB,IAAA;AACO,IAAA;AACT,IAAA;AAG5B,IAAA;AACM,MAAA;AACA,MAAA;AAEQ,IAAA;AACmB,MAAA;AACjC,IAAA;AACH,EAAA;AAEiC,EAAA;AACJ,oBAAA;AACP,IAAA;AAEO,oBAAA;AACP,IAAA;AACC,oBAAA;AACP,IAAA;AAChB,EAAA;AAEwC,EAAA;AACZ,IAAA;AACsC,IAAA;AAC1D,IAAA;AACR,EAAA;AAEgD,EAAA;AACrB,IAAA;AAKmD,IAAA;AAI3E,IAAA;AACD,MAAA;AACD,IAAA;AACa,IAAA;AACK,IAAA;AACnB,EAAA;AAE6B,EAAA;AACG,IAAA;AACmB,IAAA;AAC7C,MAAA;AACc,QAAA;AACF,MAAA;AACsD,QAAA;AACtE,MAAA;AACD,IAAA;AACD,EAAA;AACD;AAEoC;AAAC;AAEN;AACgD,EAAA;AACpD,IAAA;AAC1B,EAAA;AACwE,EAAA;AACzE;ADnT2G;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/kora/kora/packages/store/dist/chunk-OTLAUBFG.cjs","sourcesContent":[null,"/**\n * Version gate: one build of the app writes a database at a time\n * (`docs/design/version-gate.md`).\n *\n * Every tab of an origin that opens a database declares an identity\n * `{ build, format, openSeq, tabId }` and holds an exclusive Web Lock named after it (its\n * tab lock) for its life. The set of held tab locks is the roster: `navigator.locks.query()`\n * lists every tab, including silent followers and tabs that have not processed any message.\n *\n * - The ordering key is `(format, openSeq)`: a newer storage format always wins, and within\n *   a format the later-opened tab wins (a deployment, or the rollback of one). `openSeq`\n *   comes from an IndexedDB counter ({@link allocateOpenSeq}), never from the clock.\n * - A tab RETIRES as soon as it learns of a tab of a different build with a higher key:\n *   it refuses new writes, drains the writes it started, makes them durable, stops sync,\n *   gives up its storage roles, and releases its tab lock. Retirement's steps are\n *   registered by the layers that own them ({@link VersionGate.addRetireStep}).\n * - A tab's write gate OPENS (its storage opens) only when no tab of another build with a\n *   lower key holds a tab lock: it waits for each one's release, with no deadline.\n *\n * Runtimes without a window (Node, native adapters) do not apply the gate: one process\n * owns the database file. A browser without `BroadcastChannel` gets an exclusive single\n * tab; a browser without Web Locks refuses to open unless `allowUncoordinatedTabs` is set.\n */\n\nimport type { KoraEventEmitter, SchemaDefinition, VersionGateTabIdentity } from '@korajs/core'\nimport { KORA_STORAGE_FORMAT } from '@korajs/core'\nimport {\n\tfnv1a32Hex,\n\tgatedLeaderIdentityLockPrefix,\n\tgatedLeaderLockName,\n\tleaderLockName,\n\tstorageChannelName,\n} from '../adapters/opfs-names'\nimport {\n\tBuildSupersededError,\n\ttype BuildSupersededInfo,\n\tPersistenceError,\n\tTabCoordinationUnavailableError,\n\tVersionGateClosedError,\n} from '../errors'\nimport { allocateOpenSeq } from './open-seq'\n\n/** The identity a tab declares to the gate. */\nexport type TabIdentity = VersionGateTabIdentity\n\n/** Message a tab posts after acquiring its tab lock, and while its gate waits. */\nexport const BUILD_HELLO = 'kora-build-hello'\n/** Message a retiring tab posts just before it releases its tab lock. */\nexport const BUILD_RETIRED = 'kora-build-retired'\n/**\n * Message a retiring tab posts when its durability barrier failed (`unsaved: true`) or\n * succeeded again (`unsaved: false`), so waiting tabs can tell the user which tab needs\n * attention (`store:build-gate-waiting` reason `unsaved-writes`).\n */\nexport const BUILD_UNSAVED = 'kora-build-unsaved'\n/** The storage leader's heartbeat (multi-tab storage); carries the leader's identity. */\nconst LEADER_HEARTBEAT = 'kora-leader-heartbeat'\n\nconst DEFAULT_HEARTBEAT_MS = 1000\nconst DEFAULT_WAITING_REPORT_MS = 10_000\nconst DEFAULT_RETRY_INITIAL_MS = 1000\nconst DEFAULT_RETRY_MAX_MS = 30_000\n\n/**\n * Compare two tabs' ordering keys `(format, openSeq)`: positive when `a` wins. `openSeq` is\n * unique per database, so ties do not occur; `tabId` decides one deterministically anyway.\n */\nexport function compareTabKeys(a: TabIdentity, b: TabIdentity): number {\n\tif (a.format !== b.format) return a.format - b.format\n\tif (a.openSeq !== b.openSeq) return a.openSeq - b.openSeq\n\treturn a.tabId < b.tabId ? -1 : a.tabId > b.tabId ? 1 : 0\n}\n\n/** Prefix of every tab lock of `dbName`. */\nexport function tabLockPrefix(dbName: string): string {\n\treturn `kora-tab:${dbName}:`\n}\n\n/** The tab lock name of `identity`: the prefix followed by the identity as JSON. */\nexport function tabLockName(dbName: string, identity: TabIdentity): string {\n\treturn `${tabLockPrefix(dbName)}${JSON.stringify({\n\t\tbuild: identity.build,\n\t\tformat: identity.format,\n\t\topenSeq: identity.openSeq,\n\t\ttabId: identity.tabId,\n\t})}`\n}\n\n/** The identity in a tab lock name of `dbName`, or null for any other lock. */\nexport function parseTabLockName(dbName: string, name: string): TabIdentity | null {\n\tconst prefix = tabLockPrefix(dbName)\n\tif (!name.startsWith(prefix)) return null\n\treturn parseIdentityJson(name.slice(prefix.length))\n}\n\nfunction parseIdentityJson(text: string): TabIdentity | null {\n\ttry {\n\t\tconst value: unknown = JSON.parse(text)\n\t\treturn isTabIdentity(value) ? value : null\n\t} catch {\n\t\treturn null\n\t}\n}\n\n/** Lock a tab holds while it has writes no stored snapshot holds yet (retiring or freezing). */\nexport function unsavedLockName(dbName: string, tabId: string): string {\n\treturn `kora-tab-unsaved:${dbName}:${tabId}`\n}\n\n/** Lock a tab holds for its life when the browser has no `BroadcastChannel` (4.1.1). */\nexport function exclusiveDatabaseLockName(dbName: string): string {\n\treturn `kora-db:${dbName}`\n}\n\n/** Whether `value` is a complete {@link TabIdentity}. */\nexport function isTabIdentity(value: unknown): value is TabIdentity {\n\tif (typeof value !== 'object' || value === null) return false\n\tconst candidate = value as Record<string, unknown>\n\treturn (\n\t\ttypeof candidate.build === 'string' &&\n\t\ttypeof candidate.format === 'number' &&\n\t\tNumber.isSafeInteger(candidate.format) &&\n\t\ttypeof candidate.openSeq === 'number' &&\n\t\tNumber.isSafeInteger(candidate.openSeq) &&\n\t\ttypeof candidate.tabId === 'string'\n\t)\n}\n\n/**\n * A build id derived from the storage format and the schema (collections, fields, version),\n * used only when the app supplies none (version gate, section 3): it still tells apart two\n * deployments whose schemas differ. Never the `korajs` package version.\n */\nexport function schemaFingerprint(schema: SchemaDefinition, format = KORA_STORAGE_FORMAT): string {\n\tconst text = stableStringify({ format, version: schema.version, collections: schema.collections })\n\treturn `schema-${format}-${schema.version}-${fnv1a32Hex(text)}${fnv1a32Hex(`${text.length}:${text}`)}`\n}\n\nfunction stableStringify(value: unknown): string {\n\tif (typeof value === 'function' || value === undefined) return 'null'\n\tif (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null'\n\tif (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`\n\tconst entries = Object.entries(value as Record<string, unknown>)\n\t\t.filter(([, entry]) => typeof entry !== 'function' && entry !== undefined)\n\t\t.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n\treturn `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${stableStringify(entry)}`).join(',')}}`\n}\n\n// === Runtime seams ===\n\n/** The part of a Web Lock the gate uses. */\nexport interface GateLock {\n\tname: string\n}\n\n/** Options of a Web Locks request, as the gate uses them. */\nexport interface GateLockRequestOptions {\n\tmode?: 'exclusive' | 'shared'\n\tifAvailable?: boolean\n\tsignal?: AbortSignal\n}\n\n/** The part of `navigator.locks` the gate uses (injected in tests). */\nexport interface GateLockManager {\n\trequest(\n\t\tname: string,\n\t\toptions: GateLockRequestOptions,\n\t\tcallback: (lock: GateLock | null) => unknown,\n\t): Promise<unknown>\n\tquery(): Promise<{ held?: ReadonlyArray<{ name?: string }> }>\n}\n\n/** The part of a `BroadcastChannel` the gate uses (injected in tests). */\nexport interface GateChannel {\n\tpostMessage(message: unknown): void\n\taddEventListener(type: 'message', listener: (event: { data: unknown }) => void): void\n\tremoveEventListener(type: 'message', listener: (event: { data: unknown }) => void): void\n\tclose(): void\n}\n\n/** What the runtime offers the gate. Detected from globals unless injected. */\nexport interface VersionGateRuntime {\n\t/** A browser page (a `window` and a `document`): the gate applies. */\n\tbrowser: boolean\n\tlocks: GateLockManager | null\n\tcreateChannel: ((name: string) => GateChannel) | null\n\t/**\n\t * The page is not a secure context (plain HTTP on a non-localhost origin), where browsers\n\t * expose no Web Locks: the gate does not apply there (section 4.1.1).\n\t */\n\tinsecureContext?: boolean\n}\n\nfunction detectRuntime(): VersionGateRuntime {\n\tconst browser = typeof window !== 'undefined' && typeof document !== 'undefined'\n\tconst nav = typeof navigator !== 'undefined' ? navigator : undefined\n\tconst locks =\n\t\tnav?.locks && typeof nav.locks.request === 'function' && typeof nav.locks.query === 'function'\n\t\t\t? (nav.locks as unknown as GateLockManager)\n\t\t\t: null\n\tconst createChannel =\n\t\ttypeof BroadcastChannel !== 'undefined'\n\t\t\t? (name: string): GateChannel => new BroadcastChannel(name) as unknown as GateChannel\n\t\t\t: null\n\tconst secure = (globalThis as { isSecureContext?: unknown }).isSecureContext\n\treturn { browser, locks, createChannel, insecureContext: secure === false }\n}\n\n/** The insecure-context warning is printed once per page, not once per database. */\nlet insecureContextWarned = false\n\n// === Gate ===\n\n/** How the gate coordinates in this runtime (section 4.1.1). */\nexport type VersionGateMode =\n\t/** Not a browser: one process owns the database; nothing to coordinate. */\n\t| 'off'\n\t/** Web Locks and `BroadcastChannel`: the full protocol. */\n\t| 'full'\n\t/** Web Locks, no `BroadcastChannel`: one tab at a time. */\n\t| 'exclusive'\n\t/** No Web Locks in a secure context (an old browser): refused, unless allowed. */\n\t| 'unavailable'\n\t/**\n\t * Not a secure context (plain HTTP, not localhost): browsers expose no Web Locks there.\n\t * The gate does not apply (as before it), with one console warning.\n\t */\n\t| 'insecure-context'\n\t/** No Web Locks, `allowUncoordinatedTabs`: single-tab as before the gate. */\n\t| 'uncoordinated'\n\n/** Lifecycle of a gate. */\nexport type VersionGateState =\n\t| 'idle'\n\t| 'opening'\n\t| 'waiting'\n\t| 'open'\n\t| 'suspended'\n\t| 'retiring'\n\t| 'retired'\n\t| 'closed'\n\n/** Phases of retirement, run in this order (section 5, steps 3 to 6). */\nexport type RetirePhase = 'drain' | 'durability' | 'sync' | 'roles'\nconst RETIRE_PHASES: readonly RetirePhase[] = ['drain', 'durability', 'sync', 'roles']\n\n/** Passed to supersede listeners and retirement steps. */\nexport interface SupersededInfo {\n\t/** This tab. */\n\tcurrent: TabIdentity\n\t/** The tab of a different build whose key is higher. */\n\tnewer: TabIdentity\n}\n\n/** A change listeners of {@link VersionGate.onChange} hear about. */\nexport interface VersionGateSnapshot {\n\tstate: VersionGateState\n\tidentity: TabIdentity | null\n\t/** Set once this tab is superseded. */\n\tnewer: TabIdentity | null\n\t/** This tab's retirement is held because its latest writes are not saved yet. */\n\tunsaved: boolean\n\t/** While waiting: the tabs this one waits for, and why. */\n\twaiting: {\n\t\twaitingFor: TabIdentity[]\n\t\treason: 'live-writer' | 'unsaved-writes' | 'legacy-build'\n\t} | null\n}\n\n/** Options of {@link VersionGate}. */\nexport interface VersionGateOptions {\n\t/** The Kora database name the gate guards. */\n\tdbName: string\n\t/**\n\t * The app's build id (`createApp({ build })`, or injected by the `@korajs/cli/vite`\n\t * plugins). When absent, the adapter derives one from the schema before opening\n\t * ({@link VersionGate.useSchemaFingerprint}) and `store:build-unidentified` is reported.\n\t */\n\tbuild?: string\n\t/** Kora storage format of this code. Defaults to `KORA_STORAGE_FORMAT`. */\n\tformat?: number\n\temitter?: KoraEventEmitter\n\t/** Open single-tab in a browser without Web Locks (test environments). */\n\tallowUncoordinatedTabs?: boolean\n\t/** @internal Test seam: the runtime's coordination APIs. */\n\truntime?: Partial<VersionGateRuntime>\n\t/** @internal Test seam: the open-order counter. */\n\tallocateOpenSeq?: (dbName: string) => Promise<number>\n\t/** Interval of re-sent hellos while waiting. Default 1000 ms. */\n\theartbeatMs?: number\n\t/** Waiting time before `store:build-gate-waiting` is reported. Default 10 s. */\n\twaitingReportMs?: number\n\t/** Backoff of a failed durability barrier's retries. Default 1 s doubling to 30 s. */\n\tretryBackoffMs?: { initial: number; max: number }\n\t/** @internal Test seam: this tab's random id. */\n\ttabId?: string\n}\n\ninterface HeldLock {\n\trelease(): void\n}\n\n/**\n * The version gate of one database in one tab. See the module documentation.\n *\n * @example\n * ```typescript\n * const gate = new VersionGate({ dbName: 'my-app', build: import.meta.env.VITE_COMMIT_SHA })\n * gate.onSuperseded(({ newer }) => showReloadBanner(newer.build))\n * await gate.open() // resolves once no tab of another build writes this database\n * ```\n */\nexport class VersionGate {\n\treadonly dbName: string\n\treadonly format: number\n\tprivate build: string | null\n\tprivate buildUnidentified = false\n\tprivate readonly emitter: KoraEventEmitter | undefined\n\tprivate readonly runtime: VersionGateRuntime\n\tprivate readonly allocate: (dbName: string) => Promise<number>\n\tprivate readonly heartbeatMs: number\n\tprivate readonly waitingReportMs: number\n\tprivate readonly retryBackoff: { initial: number; max: number }\n\tprivate readonly tabId: string\n\tprivate readonly allowUncoordinatedTabs: boolean\n\tprivate currentMode: VersionGateMode\n\n\tprivate state: VersionGateState = 'idle'\n\tprivate identity: TabIdentity | null = null\n\tprivate openedAt: number | null = null\n\tprivate openPromise: Promise<void> | null = null\n\tprivate tabLock: HeldLock | null = null\n\tprivate exclusiveLock: HeldLock | null = null\n\tprivate channel: GateChannel | null = null\n\tprivate readonly onMessage = (event: { data: unknown }): void => this.handleMessage(event.data)\n\n\tprivate newer: TabIdentity | null = null\n\tprivate retirement: Promise<void> | null = null\n\tprivate retiredSignal: () => void = () => {}\n\tprivate readonly retiredPromise: Promise<void>\n\tprivate supersededSignal: () => void = () => {}\n\tprivate readonly supersededPromise: Promise<void>\n\tprivate readonly supersededListeners = new Set<(info: SupersededInfo) => void>()\n\tprivate readonly changeListeners = new Set<(snapshot: VersionGateSnapshot) => void>()\n\tprivate readonly steps = new Map<RetirePhase, Array<(info: SupersededInfo) => Promise<void>>>()\n\n\tprivate unsaved = false\n\tprivate unsavedMarker: HeldLock | null = null\n\t/** Unsaved marker locks seen at the last discovery. */\n\tprivate unsavedHeld = new Set<string>()\n\t/** Identity-named gated-leader markers found by the last discovery (other tabs only). */\n\tprivate heldLeaders: TabIdentity[] = []\n\t/** Their lock names, by tab id, exactly as held (waited on by name). */\n\tprivate heldLeaderLockNames = new Map<string, string>()\n\tprivate readonly unsavedPeers = new Set<string>()\n\tprivate waiting: VersionGateSnapshot['waiting'] = null\n\tprivate waitingReported: string | null = null\n\tprivate waitingTimers: Array<ReturnType<typeof setTimeout>> = []\n\tprivate readonly waitAborts = new Set<AbortController>()\n\tprivate legacyReported = false\n\tprivate retryWake: (() => void) | null = null\n\tprivate recoveryExporter: (() => Promise<unknown>) | null = null\n\tprivate closeCheck: (() => Promise<void>) | null = null\n\t/** Aborts lock requests still queued when the gate closes. */\n\tprivate readonly closeAbort = new AbortController()\n\n\tconstructor(options: VersionGateOptions) {\n\t\tthis.dbName = options.dbName\n\t\tthis.format = options.format ?? KORA_STORAGE_FORMAT\n\t\tthis.build = options.build ?? null\n\t\tthis.emitter = options.emitter\n\t\tthis.runtime = { ...detectRuntime(), ...options.runtime }\n\t\tthis.allocate = options.allocateOpenSeq ?? allocateOpenSeq\n\t\tthis.heartbeatMs = options.heartbeatMs ?? DEFAULT_HEARTBEAT_MS\n\t\tthis.waitingReportMs = options.waitingReportMs ?? DEFAULT_WAITING_REPORT_MS\n\t\tthis.retryBackoff = options.retryBackoffMs ?? {\n\t\t\tinitial: DEFAULT_RETRY_INITIAL_MS,\n\t\t\tmax: DEFAULT_RETRY_MAX_MS,\n\t\t}\n\t\tthis.tabId = options.tabId ?? createTabId()\n\t\tthis.allowUncoordinatedTabs = options.allowUncoordinatedTabs === true\n\t\tthis.currentMode = !this.runtime.browser\n\t\t\t? 'off'\n\t\t\t: this.runtime.locks === null\n\t\t\t\t? this.runtime.insecureContext\n\t\t\t\t\t? 'insecure-context'\n\t\t\t\t\t: 'unavailable'\n\t\t\t\t: this.runtime.createChannel === null\n\t\t\t\t\t? 'exclusive'\n\t\t\t\t\t: 'full'\n\t\tthis.retiredPromise = new Promise<void>((resolve) => {\n\t\t\tthis.retiredSignal = resolve\n\t\t})\n\t\tthis.supersededPromise = new Promise<void>((resolve) => {\n\t\t\tthis.supersededSignal = resolve\n\t\t})\n\t}\n\n\t/** How the gate coordinates in this runtime. */\n\tget mode(): VersionGateMode {\n\t\treturn this.currentMode\n\t}\n\n\t/** Whether tabs are coordinated at all (`full` or `exclusive`). */\n\tisCoordinating(): boolean {\n\t\treturn this.currentMode === 'full' || this.currentMode === 'exclusive'\n\t}\n\n\t/** This tab's identity, once the gate allocated its `openSeq`. */\n\tgetIdentity(): TabIdentity | null {\n\t\treturn this.identity ? { ...this.identity } : null\n\t}\n\n\t/** The build this gate declares (null until set). */\n\tgetBuild(): string | null {\n\t\treturn this.build\n\t}\n\n\t/** DevTools: identity, open time (display only) and state. */\n\tgetInfo(): { identity: TabIdentity | null; openedAt: number | null; state: VersionGateState } {\n\t\treturn { identity: this.getIdentity(), openedAt: this.openedAt, state: this.state }\n\t}\n\n\tgetState(): VersionGateState {\n\t\treturn this.state\n\t}\n\n\t/**\n\t * The refusal of a close while this tab retires with writes no stored snapshot holds (its\n\t * durability barrier is failing), or null. Closing then would release the tab lock and\n\t * let the newer build open without them, so `Store.close`, the IndexedDB adapter and\n\t * `app.close()` check it first and throw it (surfaced, never silent); the prompt's Retry\n\t * and Export keep working.\n\t */\n\tunsavedCloseError(): PersistenceError | null {\n\t\tif (this.newer === null || this.state !== 'retiring' || !this.unsaved) return null\n\t\treturn this.closeRefusal()\n\t}\n\n\t/** The `UNSAVED_WRITES` refusal of a close (see {@link assertClosable}). */\n\tcloseRefusal(cause?: unknown): PersistenceError {\n\t\treturn new PersistenceError(\n\t\t\t`Database \"${this.dbName}\" was not closed: this tab is handing it to a newer version of the app and its latest changes are not saved yet. Closing now would lose them. Retry saving (or Export them) from the prompt, then close.`,\n\t\t\t{\n\t\t\t\tdbName: this.dbName,\n\t\t\t\tcode: 'UNSAVED_WRITES',\n\t\t\t\t...(cause instanceof Error ? { cause: cause.message } : {}),\n\t\t\t},\n\t\t)\n\t}\n\n\t/**\n\t * Set by the adapter that owns durability (the IndexedDB fallback): from the moment this\n\t * tab retires until it retired, a close first runs this check, which saves every committed\n\t * write and throws {@link closeRefusal} when that fails.\n\t */\n\tsetCloseCheck(check: (() => Promise<void>) | null): void {\n\t\tthis.closeCheck = check\n\t}\n\n\t/**\n\t * Before a close tears anything down: while this tab retires (from the moment retirement\n\t * starts, not only after a failed save), make every committed write durable or refuse with\n\t * `UNSAVED_WRITES`. Closing would release the tab lock and let the newer build open\n\t * without them. A no-op when not retiring.\n\t */\n\tasync assertClosable(): Promise<void> {\n\t\tif (this.newer === null || this.state !== 'retiring') return\n\t\tconst refused = this.unsavedCloseError()\n\t\tif (refused) throw refused\n\t\tif (this.closeCheck) await this.closeCheck()\n\t}\n\n\t/** True once this tab is superseded (retiring or retired). */\n\tisSuperseded(): boolean {\n\t\treturn this.newer !== null\n\t}\n\n\t/** The builds of a supersession, for {@link BuildSupersededError}. */\n\tsupersededInfo(): BuildSupersededInfo | null {\n\t\tif (!this.newer) return null\n\t\treturn { currentBuild: this.build ?? 'unknown', newerBuild: this.newer.build }\n\t}\n\n\t/**\n\t * Use a fingerprint of the storage format and the schema as the build, when the app gave\n\t * none. Reported as `store:build-unidentified` at open.\n\t */\n\tuseSchemaFingerprint(schema: SchemaDefinition): void {\n\t\tif (this.build !== null) return\n\t\tthis.build = schemaFingerprint(schema, this.format)\n\t\tthis.buildUnidentified = true\n\t}\n\n\t/**\n\t * Called synchronously when this tab is superseded, before any write is refused\n\t * (section 5, steps 1 and 2). Listeners close their write gates and show the prompt.\n\t */\n\tonSuperseded(listener: (info: SupersededInfo) => void): () => void {\n\t\tthis.supersededListeners.add(listener)\n\t\tif (this.newer && this.identity) {\n\t\t\tlistener({ current: { ...this.identity }, newer: { ...this.newer } })\n\t\t}\n\t\treturn () => {\n\t\t\tthis.supersededListeners.delete(listener)\n\t\t}\n\t}\n\n\t/** Listen to state changes (prompts: waiting, unsaved writes, retired). */\n\tonChange(listener: (snapshot: VersionGateSnapshot) => void): () => void {\n\t\tthis.changeListeners.add(listener)\n\t\treturn () => {\n\t\t\tthis.changeListeners.delete(listener)\n\t\t}\n\t}\n\n\t/** Current state, as {@link onChange} reports it. */\n\tsnapshot(): VersionGateSnapshot {\n\t\treturn {\n\t\t\tstate: this.state,\n\t\t\tidentity: this.getIdentity(),\n\t\t\tnewer: this.newer ? { ...this.newer } : null,\n\t\t\tunsaved: this.unsaved,\n\t\t\twaiting: this.waiting\n\t\t\t\t? {\n\t\t\t\t\t\twaitingFor: this.waiting.waitingFor.map((t) => ({ ...t })),\n\t\t\t\t\t\treason: this.waiting.reason,\n\t\t\t\t\t}\n\t\t\t\t: null,\n\t\t}\n\t}\n\n\t/**\n\t * Register a retirement step. Steps run once, in phase order (`drain`, `durability`,\n\t * `sync`, `roles`), each awaited; then the tab posts `kora-build-retired` and releases\n\t * its tab lock, which opens the newer tab's gate.\n\t */\n\taddRetireStep(phase: RetirePhase, step: (info: SupersededInfo) => Promise<void>): () => void {\n\t\tconst list = this.steps.get(phase) ?? []\n\t\tlist.push(step)\n\t\tthis.steps.set(phase, list)\n\t\treturn () => {\n\t\t\tconst current = this.steps.get(phase)\n\t\t\tif (current)\n\t\t\t\tthis.steps.set(\n\t\t\t\t\tphase,\n\t\t\t\t\tcurrent.filter((entry) => entry !== step),\n\t\t\t\t)\n\t\t}\n\t}\n\n\t/**\n\t * Open the write gate: allocate `openSeq`, take the tab lock, discover the other tabs and\n\t * wait until no tab of another build with a lower key holds its lock. Resolves when this\n\t * tab may open storage. Rejects with {@link BuildSupersededError} when a tab of another\n\t * build with a higher key exists (this tab retires instead), and with\n\t * {@link TabCoordinationUnavailableError} in a browser without Web Locks.\n\t */\n\topen(): Promise<void> {\n\t\tif (!this.openPromise) {\n\t\t\tconst opening = this.doOpen()\n\t\t\tthis.openPromise = opening\n\t\t\t// A failed open is not cached, so the next open() tries again, unless the gate is done:\n\t\t\t// closed or retired by a newer build, it keeps that rejection for every caller.\n\t\t\topening.catch((error: unknown) => {\n\t\t\t\tconst terminal =\n\t\t\t\t\terror instanceof BuildSupersededError || error instanceof VersionGateClosedError\n\t\t\t\tif (!terminal && this.openPromise === opening) this.openPromise = null\n\t\t\t})\n\t\t}\n\t\treturn this.openPromise\n\t}\n\n\tprivate async doOpen(): Promise<void> {\n\t\tif (this.currentMode === 'off') {\n\t\t\tthis.setState('open')\n\t\t\treturn\n\t\t}\n\t\tif (this.currentMode === 'insecure-context') {\n\t\t\tif (!insecureContextWarned) {\n\t\t\t\tinsecureContextWarned = true\n\t\t\t\tconsole.warn(\n\t\t\t\t\t'[kora] This page is served over plain HTTP, where browsers provide no Web Locks, so the version gate is off: two tabs running different deployments of the app can write the local database at the same time, and tabs share it uncoordinated. Serve the app over HTTPS (or from localhost) to turn it on.',\n\t\t\t\t)\n\t\t\t}\n\t\t\tthis.setState('open')\n\t\t\treturn\n\t\t}\n\t\tif (this.currentMode === 'unavailable') {\n\t\t\tif (!this.allowUncoordinatedTabs) {\n\t\t\t\tconst error = new TabCoordinationUnavailableError(this.dbName)\n\t\t\t\tthis.emitter?.emit({\n\t\t\t\t\ttype: 'store:tab-coordination-unavailable',\n\t\t\t\t\tdbName: this.dbName,\n\t\t\t\t\tmessage: error.message,\n\t\t\t\t})\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\tthis.currentMode = 'uncoordinated'\n\t\t\tconsole.warn(\n\t\t\t\t`[kora] store.allowUncoordinatedTabs: database \"${this.dbName}\" opens without tab coordination (no Web Locks). Two tabs of the app can overwrite each other's writes; use this only in test environments.`,\n\t\t\t)\n\t\t\tthis.setState('open')\n\t\t\treturn\n\t\t}\n\t\tthis.setState('opening')\n\t\tif (this.build === null) {\n\t\t\t// The adapter derives a fingerprint before opening; reaching here without one is a\n\t\t\t// direct gate user that set neither.\n\t\t\tthis.build = 'unidentified'\n\t\t\tthis.buildUnidentified = true\n\t\t}\n\t\tif (this.buildUnidentified) this.reportUnidentified()\n\t\tconst openSeq = await this.allocate(this.dbName)\n\t\tthis.throwIfClosed()\n\t\tthis.identity = { build: this.build, format: this.format, openSeq, tabId: this.tabId }\n\t\tthis.openedAt = Date.now()\n\t\tthis.tabLock = await this.acquire(tabLockName(this.dbName, this.identity))\n\t\ttry {\n\t\t\tthis.throwIfStopped()\n\t\t\tif (this.currentMode === 'exclusive') {\n\t\t\t\tawait this.acquireExclusive()\n\t\t\t\tthis.throwIfStopped()\n\t\t\t\tthis.setState('open')\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthis.startChannel()\n\t\t\tthis.postHello()\n\t\t\tawait this.settle()\n\t\t\t// Never `open` over a gate that closed or started retiring during the last await.\n\t\t\tthis.throwIfStopped()\n\t\t} catch (error) {\n\t\t\t// Closed or superseded: those paths release their own locks.\n\t\t\tif (!(error instanceof BuildSupersededError || error instanceof VersionGateClosedError)) {\n\t\t\t\t// Any other failure (a lock query rejected): never hold the tab lock without a\n\t\t\t\t// storage worker, or a newer build waits on a tab that never opened. As resume().\n\t\t\t\tthis.stopWaitingTimers()\n\t\t\t\tthis.stopChannel()\n\t\t\t\tthis.releaseHeldLocks()\n\t\t\t\tif (this.getState() !== 'closed') this.setState('idle')\n\t\t\t}\n\t\t\tthrow error\n\t\t}\n\t\tthis.setState('open')\n\t}\n\n\t/**\n\t * A gate closed while it opened or resumed never reaches `open`: its tab lock and channel\n\t * are gone, so storage must not open behind it.\n\t */\n\tprivate throwIfClosed(): void {\n\t\tif (this.state === 'closed') throw new VersionGateClosedError(this.dbName)\n\t}\n\n\t/**\n\t * After every await of an open or a resume, before any state change: closed\n\t * ({@link VersionGateClosedError}) or superseded ({@link BuildSupersededError}) stops it.\n\t */\n\tprivate throwIfStopped(): void {\n\t\tthis.throwIfClosed()\n\t\tthis.throwIfSuperseded()\n\t}\n\n\t/**\n\t * Called by a tab granted the storage leader lock (first open or promotion) before it\n\t * opens a worker (rule 4). False when a tab of another build with a higher key is listed\n\t * (this tab retires) or this tab is already retiring: the caller releases the leader lock\n\t * unopened.\n\t */\n\tasync mayLead(): Promise<boolean> {\n\t\tif (this.currentMode !== 'full') return true\n\t\tif (this.newer !== null || this.state === 'closed') return false\n\t\tconst me = this.identity\n\t\tif (!me) return true\n\t\tconst newer = (await this.discover()).find((tab) => this.supersedes(tab, me))\n\t\t// Closed or superseded while discovery ran: never lead.\n\t\t// (getState(): the await may have changed what TypeScript narrowed above.)\n\t\tif (this.getState() === 'closed' || this.newer !== null) return false\n\t\tif (newer) {\n\t\t\tvoid this.retire(newer)\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t}\n\n\t/**\n\t * Page lifecycle (`freeze`, bfcache `pagehide`): release the tab lock. The caller has\n\t * already made every committed write durable and released the storage leader lock (the\n\t * lifecycle rule of section 4.1). No-op unless the gate is open.\n\t */\n\tsuspend(): void {\n\t\tif (this.state !== 'open' || !this.isCoordinating()) return\n\t\tthis.releaseHeldLocks()\n\t\tthis.setState('suspended')\n\t}\n\n\t/**\n\t * Page lifecycle (`resume`, `pageshow`): re-acquire the tab lock and run discovery before\n\t * anything else (rule 5). False when this tab must not use storage again: it is retired,\n\t * retiring, or a newer build appeared meanwhile (it retires now).\n\t */\n\tasync resume(): Promise<boolean> {\n\t\tif (this.state === 'open') return true\n\t\tif (this.state !== 'suspended') return false\n\t\tconst me = this.identity\n\t\tif (!me) return false\n\t\tthis.setState('opening')\n\t\ttry {\n\t\t\tthis.tabLock = await this.acquire(tabLockName(this.dbName, me))\n\t\t\tthis.throwIfStopped()\n\t\t\tif (this.currentMode === 'exclusive') {\n\t\t\t\tawait this.acquireExclusive()\n\t\t\t} else {\n\t\t\t\tthis.postHello()\n\t\t\t\tawait this.settle()\n\t\t\t}\n\t\t\tthis.throwIfStopped()\n\t\t} catch (error) {\n\t\t\tif (error instanceof BuildSupersededError || error instanceof VersionGateClosedError) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\t// Any other failure (a lock query rejected): never hold the tab lock without a\n\t\t\t// storage worker. Release it and go back to suspended; the caller retries.\n\t\t\tconst now = this.getState()\n\t\t\tif (now === 'opening' || now === 'waiting') {\n\t\t\t\tthis.stopWaitingTimers()\n\t\t\t\tthis.releaseHeldLocks()\n\t\t\t\tthis.setState('suspended')\n\t\t\t}\n\t\t\tthrow error\n\t\t}\n\t\tthis.setState('open')\n\t\treturn true\n\t}\n\n\t/**\n\t * {@link resume}, retried with backoff (or the user's Retry, `visibilitychange`) while it\n\t * fails for another reason than supersession or closure (a lock query rejected). Between\n\t * attempts the gate is suspended and holds no lock, so no tab waits on a tab without a\n\t * storage worker. False once this tab must not use storage (superseded, closed).\n\t */\n\tasync resumeWithRetry(): Promise<boolean> {\n\t\tfor (let attempt = 0; ; attempt += 1) {\n\t\t\ttry {\n\t\t\t\treturn await this.resume()\n\t\t\t} catch (error) {\n\t\t\t\tif (this.state !== 'suspended') return false\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`[kora] Resuming the version gate of \"${this.dbName}\" failed; retrying:`,\n\t\t\t\t\terror,\n\t\t\t\t)\n\t\t\t\tawait this.waitForRetry(attempt)\n\t\t\t\tif (this.state !== 'suspended') return this.state === 'open'\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Report whether this retiring tab's durability barrier is failing, so waiting tabs can\n\t * name it (`unsaved-writes`) and this tab's prompt can offer Retry and Export.\n\t */\n\treportUnsavedWrites(unsaved: boolean): void {\n\t\tif (this.unsaved === unsaved) return\n\t\tthis.unsaved = unsaved\n\t\tthis.updateUnsavedMarker()\n\t\tthis.notifyChange()\n\t}\n\n\t/**\n\t * Wait before the next durability retry: the backoff for `attempt`, or until\n\t * {@link retryNow} (the user's Retry, `visibilitychange`), whichever is first.\n\t */\n\twaitForRetry(attempt: number): Promise<void> {\n\t\tconst delay = Math.min(this.retryBackoff.max, this.retryBackoff.initial * 2 ** attempt)\n\t\treturn new Promise<void>((resolve) => {\n\t\t\tconst timer = setTimeout(done, delay)\n\t\t\tconst wake = (): void => done()\n\t\t\tfunction done(): void {\n\t\t\t\tclearTimeout(timer)\n\t\t\t\tresolve()\n\t\t\t}\n\t\t\tthis.retryWake = wake\n\t\t}).finally(() => {\n\t\t\tthis.retryWake = null\n\t\t})\n\t}\n\n\t/** Retry a failed durability barrier now (the prompt's Retry button). */\n\tretryNow(): void {\n\t\tthis.retryWake?.()\n\t}\n\n\t/** Set by the IndexedDB adapter: a download of the in-memory database (Export button). */\n\tsetRecoveryExporter(exporter: (() => Promise<unknown>) | null): void {\n\t\tthis.recoveryExporter = exporter\n\t}\n\n\t/**\n\t * The explicit recovery path while a failed barrier holds retirement: the in-memory\n\t * database as a dump. Null when no adapter offers one (OPFS: committed is durable).\n\t */\n\tasync exportRecoveryDump(): Promise<unknown> {\n\t\treturn this.recoveryExporter ? this.recoveryExporter() : null\n\t}\n\n\t/** Resolves once this tab has retired (its tab lock released). */\n\twhenRetired(): Promise<void> {\n\t\treturn this.retiredPromise\n\t}\n\n\t/**\n\t * Leader, retiring: wait until every other tab that is itself superseded (a tab of a\n\t * different build with a higher key is present) has released its tab lock, so their\n\t * retirement, which may still need this worker to finish a write or save a snapshot,\n\t * completes before the worker stops. Tabs that will not retire (the winning build's)\n\t * are never waited for, so this cannot wait on the tab that waits for this one.\n\t */\n\tasync waitForPeersToRetire(): Promise<void> {\n\t\tconst me = this.identity\n\t\tif (!me || !this.newer || this.currentMode !== 'full') return\n\t\tfor (;;) {\n\t\t\tconst others = await this.discover()\n\t\t\tconst everyone = [me, ...others]\n\t\t\tconst retiring = others.filter((tab) =>\n\t\t\t\teveryone.some((other) => other.build !== tab.build && compareTabKeys(other, tab) > 0),\n\t\t\t)\n\t\t\tif (retiring.length === 0) return\n\t\t\tawait Promise.all(retiring.map((tab) => this.waitForRelease(tabLockName(this.dbName, tab))))\n\t\t}\n\t}\n\n\t/**\n\t * While this tab holds writes not yet in a stored snapshot (a failed barrier while it\n\t * retires), it holds an unsaved marker lock and tells the channel. The lock is\n\t * what a tab that opens later finds (`query()`): it may never see the message.\n\t */\n\tprivate updateUnsavedMarker(): void {\n\t\tconst me = this.identity\n\t\tif (!me) return\n\t\tconst unsaved = this.unsaved\n\t\tif (unsaved && !this.unsavedMarker && this.runtime.locks) {\n\t\t\tlet release: () => void = () => {}\n\t\t\tconst held = new Promise<void>((resolve) => {\n\t\t\t\trelease = resolve\n\t\t\t})\n\t\t\tvoid this.runtime.locks\n\t\t\t\t.request(unsavedLockName(this.dbName, me.tabId), { mode: 'exclusive' }, () => held)\n\t\t\t\t.catch(() => undefined)\n\t\t\tthis.unsavedMarker = { release }\n\t\t} else if (!unsaved && this.unsavedMarker) {\n\t\t\tthis.unsavedMarker.release()\n\t\t\tthis.unsavedMarker = null\n\t\t}\n\t\tthis.post({ type: BUILD_UNSAVED, identity: me, unsaved })\n\t}\n\n\t/** Normal close: release the locks and leave the channel. A pending open fails. */\n\tclose(): void {\n\t\tif (this.state === 'closed') return\n\t\tconst retired = this.state === 'retired'\n\t\tif (!retired) this.setState('closed')\n\t\tthis.closeAbort.abort()\n\t\tthis.stopWaitingTimers()\n\t\tfor (const controller of this.waitAborts) controller.abort()\n\t\tthis.waitAborts.clear()\n\t\tthis.releaseHeldLocks()\n\t\tthis.stopChannel()\n\t}\n\n\t// === Protocol ===\n\n\tprivate supersedes(tab: TabIdentity, me: TabIdentity): boolean {\n\t\treturn tab.tabId !== me.tabId && tab.build !== me.build && compareTabKeys(tab, me) > 0\n\t}\n\n\t/**\n\t * Wait until no tab of another build with a lower key holds its tab lock (rule 2), or\n\t * throw {@link BuildSupersededError} when one with a higher key exists (rule 1).\n\t */\n\tprivate async settle(): Promise<void> {\n\t\tfor (;;) {\n\t\t\tthis.throwIfClosed()\n\t\t\tthis.throwIfSuperseded()\n\t\t\tconst me = this.identity\n\t\t\tif (!me) return\n\t\t\tconst others = await this.discover()\n\t\t\tconst leaders = this.heldLeaders\n\t\t\tthis.throwIfClosed()\n\t\t\tthis.throwIfSuperseded()\n\t\t\tconst newer = [...others, ...leaders].find((tab) => this.supersedes(tab, me))\n\t\t\tif (newer) {\n\t\t\t\tvoid this.retire(newer)\n\t\t\t\tthis.throwIfSuperseded()\n\t\t\t}\n\t\t\tconst isOlder = (tab: TabIdentity): boolean =>\n\t\t\t\ttab.build !== me.build && compareTabKeys(tab, me) < 0 && tab.tabId !== me.tabId\n\t\t\tconst older = others.filter(isOlder)\n\t\t\t// A storage leader of another build whose tab lock is not held (a tab frozen while it\n\t\t\t// was being promoted, or opening) still holds the leader lock and its worker: this\n\t\t\t// build must neither open through it nor lead before it lets go (rule 4).\n\t\t\tconst olderLeaders = leaders.filter(\n\t\t\t\t(leader) => isOlder(leader) && !older.some((tab) => tab.tabId === leader.tabId),\n\t\t\t)\n\t\t\tconst legacy = await this.legacyLeaderPresent()\n\t\t\t// The probe awaited (lock query, heartbeat): a hello may have retired this tab, or the\n\t\t\t// gate closed. Neither returns as settled nor becomes `waiting`.\n\t\t\tthis.throwIfClosed()\n\t\t\tthis.throwIfSuperseded()\n\t\t\tif (older.length === 0 && olderLeaders.length === 0 && !legacy) {\n\t\t\t\tthis.waiting = null\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (legacy) this.reportLegacy()\n\t\t\tthis.waiting = {\n\t\t\t\twaitingFor: [...older, ...olderLeaders],\n\t\t\t\treason: legacy ? 'legacy-build' : this.waitingReason(older),\n\t\t\t}\n\t\t\tthis.setState('waiting')\n\t\t\tthis.postHello()\n\t\t\tthis.startWaitingTimers()\n\t\t\ttry {\n\t\t\t\tconst releases = older.map((tab) => this.waitForRelease(tabLockName(this.dbName, tab)))\n\t\t\t\tfor (const leader of olderLeaders) {\n\t\t\t\t\tconst name = this.heldLeaderLockNames.get(leader.tabId)\n\t\t\t\t\tif (name) releases.push(this.waitForRelease(name))\n\t\t\t\t}\n\t\t\t\tif (legacy) {\n\t\t\t\t\treleases.push(this.waitForRelease(leaderLockName(this.dbName)))\n\t\t\t\t}\n\t\t\t\tawait Promise.race([Promise.all(releases), this.supersededPromise])\n\t\t\t} finally {\n\t\t\t\tthis.stopWaitingTimers()\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * A pre-gate build is the storage leader when the leader lock is held without the gated\n\t * leader marker (every gated leader takes {@link gatedLeaderLockName} right after it is\n\t * granted the leader lock, and releases it after the leader lock). The marker is checked\n\t * twice, one heartbeat apart, so a gated leader between its two grants is not mistaken\n\t * for a pre-gate one.\n\t */\n\tprivate async legacyLeaderPresent(): Promise<boolean> {\n\t\tconst locks = this.runtime.locks\n\t\tif (!locks) return false\n\t\tfor (let check = 0; check < 2; check += 1) {\n\t\t\tconst held = new Set((await locks.query()).held?.map((lock) => lock.name) ?? [])\n\t\t\tif (!held.has(leaderLockName(this.dbName))) return false\n\t\t\tif (held.has(gatedLeaderLockName(this.dbName))) return false\n\t\t\tif (check === 0) {\n\t\t\t\tawait new Promise<void>((resolve) => setTimeout(resolve, this.heartbeatMs))\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\n\tprivate waitingReason(older: TabIdentity[]): 'live-writer' | 'unsaved-writes' {\n\t\treturn older.some((tab) => this.unsavedPeers.has(tab.tabId) || this.unsavedHeld.has(tab.tabId))\n\t\t\t? 'unsaved-writes'\n\t\t\t: 'live-writer'\n\t}\n\n\tprivate async discover(): Promise<TabIdentity[]> {\n\t\tconst locks = this.runtime.locks\n\t\tif (!locks) return []\n\t\tconst snapshot = await locks.query()\n\t\tconst tabs: TabIdentity[] = []\n\t\tconst seen = new Set<string>()\n\t\tconst unsavedPrefix = unsavedLockName(this.dbName, '')\n\t\tconst leaderPrefix = gatedLeaderIdentityLockPrefix(this.dbName)\n\t\tthis.unsavedHeld = new Set()\n\t\tconst leaders: TabIdentity[] = []\n\t\tconst leaderLockNames = new Map<string, string>()\n\t\tfor (const lock of snapshot.held ?? []) {\n\t\t\tif (typeof lock.name !== 'string') continue\n\t\t\tif (lock.name.startsWith(unsavedPrefix)) {\n\t\t\t\tthis.unsavedHeld.add(lock.name.slice(unsavedPrefix.length))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (lock.name.startsWith(leaderPrefix)) {\n\t\t\t\tconst leader = parseIdentityJson(lock.name.slice(leaderPrefix.length))\n\t\t\t\tif (leader && leader.tabId !== this.tabId) {\n\t\t\t\t\tleaders.push(leader)\n\t\t\t\t\tleaderLockNames.set(leader.tabId, lock.name)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst identity = parseTabLockName(this.dbName, lock.name)\n\t\t\tif (!identity || identity.tabId === this.tabId || seen.has(identity.tabId)) continue\n\t\t\tseen.add(identity.tabId)\n\t\t\ttabs.push(identity)\n\t\t}\n\t\tthis.heldLeaders = leaders\n\t\tthis.heldLeaderLockNames = leaderLockNames\n\t\treturn tabs\n\t}\n\n\tprivate handleMessage(data: unknown): void {\n\t\tif (typeof data !== 'object' || data === null) return\n\t\tconst message = data as {\n\t\t\ttype?: unknown\n\t\t\tidentity?: unknown\n\t\t\tunsaved?: unknown\n\t\t\tepoch?: unknown\n\t\t}\n\t\tif (message.type === BUILD_HELLO && isTabIdentity(message.identity)) {\n\t\t\tthis.consider(message.identity)\n\t\t\treturn\n\t\t}\n\t\tif (message.type === BUILD_UNSAVED && isTabIdentity(message.identity)) {\n\t\t\tif (message.unsaved === true) this.unsavedPeers.add(message.identity.tabId)\n\t\t\telse this.unsavedPeers.delete(message.identity.tabId)\n\t\t\tthis.refreshWaitingReason()\n\t\t\treturn\n\t\t}\n\t\tif (message.type === BUILD_RETIRED && isTabIdentity(message.identity)) {\n\t\t\tthis.unsavedPeers.delete(message.identity.tabId)\n\t\t\treturn\n\t\t}\n\t\tif (message.type === LEADER_HEARTBEAT && isTabIdentity(message.identity)) {\n\t\t\tthis.consider(message.identity)\n\t\t}\n\t}\n\n\t/** Rule 1: retire as soon as a tab of another build with a higher key is known. */\n\tprivate consider(other: TabIdentity): void {\n\t\tconst me = this.identity\n\t\tif (!me || this.newer !== null) return\n\t\tif (this.state === 'closed' || this.state === 'idle' || this.state === 'suspended') return\n\t\tif (this.supersedes(other, me)) void this.retire(other)\n\t}\n\n\t/** Section 5: announce, refuse writes, then run the registered steps in phase order. */\n\tprivate retire(newer: TabIdentity): Promise<void> {\n\t\tif (this.retirement) return this.retirement\n\t\tconst me = this.identity\n\t\tif (!me) return Promise.resolve()\n\t\tthis.newer = { ...newer }\n\t\tthis.waiting = null\n\t\tthis.stopWaitingTimers()\n\t\tfor (const controller of this.waitAborts) controller.abort()\n\t\tthis.waitAborts.clear()\n\t\tthis.setState('retiring')\n\t\tconst info: SupersededInfo = { current: { ...me }, newer: { ...newer } }\n\t\t// Steps 1 and 2 in this task: every listener (prompt, write gates) runs before any\n\t\t// write can be refused.\n\t\tfor (const listener of [...this.supersededListeners]) {\n\t\t\ttry {\n\t\t\t\tlistener(info)\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error('[kora] version gate: a build-superseded listener failed:', error)\n\t\t\t}\n\t\t}\n\t\tthis.supersededSignal()\n\t\tthis.retirement = this.runRetirement(info)\n\t\treturn this.retirement\n\t}\n\n\tprivate async runRetirement(info: SupersededInfo): Promise<void> {\n\t\tfor (const phase of RETIRE_PHASES) {\n\t\t\tfor (const step of [...(this.steps.get(phase) ?? [])]) {\n\t\t\t\t// A failed step keeps the tab lock: the step runs again (backoff, or the user's\n\t\t\t\t// Retry) until it completes. Releasing early would let the newer build open while\n\t\t\t\t// this tab may still hold a worker, the leader lock or unsaved writes.\n\t\t\t\tfor (let attempt = 0; ; attempt += 1) {\n\t\t\t\t\tif (this.state === 'closed') return\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait step(info)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t`[kora] version gate: retirement step \"${phase}\" failed; retrying:`,\n\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t)\n\t\t\t\t\t\tawait this.waitForRetry(attempt)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (this.state === 'closed') return\n\t\tthis.post({ type: BUILD_RETIRED, identity: info.current })\n\t\tthis.releaseHeldLocks()\n\t\tthis.stopChannel()\n\t\tthis.setState('retired')\n\t\tthis.retiredSignal()\n\t}\n\n\tprivate throwIfSuperseded(): void {\n\t\tconst info = this.supersededInfo()\n\t\tif (info) throw new BuildSupersededError({ operation: 'open' }, info)\n\t}\n\n\tprivate refreshWaitingReason(): void {\n\t\tif (!this.waiting || this.waiting.reason === 'legacy-build') return\n\t\tconst reason = this.waitingReason(this.waiting.waitingFor)\n\t\tif (reason === this.waiting.reason) return\n\t\tthis.waiting = { ...this.waiting, reason }\n\t\tif (this.waitingReported !== null) this.reportWaiting()\n\t\telse this.notifyChange()\n\t}\n\n\tprivate startWaitingTimers(): void {\n\t\tthis.stopWaitingTimers()\n\t\tthis.waitingTimers.push(setTimeout(() => this.reportWaiting(), this.waitingReportMs))\n\t\tconst rehello = (): void => {\n\t\t\tif (this.state !== 'waiting') return\n\t\t\tthis.postHello()\n\t\t\tthis.waitingTimers.push(setTimeout(rehello, this.heartbeatMs))\n\t\t}\n\t\tthis.waitingTimers.push(setTimeout(rehello, this.heartbeatMs))\n\t}\n\n\tprivate stopWaitingTimers(): void {\n\t\tfor (const timer of this.waitingTimers) clearTimeout(timer)\n\t\tthis.waitingTimers = []\n\t\tthis.waitingReported = null\n\t}\n\n\tprivate reportWaiting(): void {\n\t\tconst waiting = this.waiting\n\t\tif (!waiting || this.state !== 'waiting') return\n\t\tthis.waitingReported = waiting.reason\n\t\tconst message =\n\t\t\twaiting.reason === 'unsaved-writes'\n\t\t\t\t? 'Another tab of this app is on an older version and has changes it has not saved yet. Switch to that tab to resolve it.'\n\t\t\t\t: waiting.reason === 'legacy-build'\n\t\t\t\t\t? 'Another tab of this app is open on an older version. Close other tabs of this app, then reload.'\n\t\t\t\t\t: 'Another tab of this app is still open on an older version. Close it to continue.'\n\t\tthis.emitter?.emit({\n\t\t\ttype: 'store:build-gate-waiting',\n\t\t\tdbName: this.dbName,\n\t\t\twaitingFor: waiting.waitingFor.map((tab) => ({ ...tab })),\n\t\t\treason: waiting.reason,\n\t\t\tmessage,\n\t\t})\n\t\tthis.notifyChange()\n\t}\n\n\tprivate reportUnidentified(): void {\n\t\tconst message = `Database \"${this.dbName}\" has no build id, so tabs of two deployments are told apart only by a schema fingerprint (${this.build}); a deployment that changes only application code is not gated. Pass createApp({ build }) (a commit SHA or CI build number) or use koraBuildId() / koraServiceWorker() from @korajs/cli/vite.`\n\t\tthis.emitter?.emit({\n\t\t\ttype: 'store:build-unidentified',\n\t\t\tdbName: this.dbName,\n\t\t\tfingerprint: this.build ?? 'unidentified',\n\t\t\tmessage,\n\t\t})\n\t\tconsole.warn(`[kora] ${message}`)\n\t}\n\n\tprivate reportLegacy(): void {\n\t\tif (this.legacyReported) return\n\t\tthis.legacyReported = true\n\t\tthis.emitter?.emit({\n\t\t\ttype: 'store:legacy-build-detected',\n\t\t\tdbName: this.dbName,\n\t\t\tmessage:\n\t\t\t\t'A tab running an older version of this app (from before the version gate) is still open. Close other tabs of this app, then reload.',\n\t\t})\n\t}\n\n\tprivate postHello(): void {\n\t\tif (this.identity) this.post({ type: BUILD_HELLO, identity: this.identity })\n\t}\n\n\tprivate post(message: unknown): void {\n\t\ttry {\n\t\t\tthis.channel?.postMessage(message)\n\t\t} catch (error) {\n\t\t\tconsole.warn('[kora] version gate: could not post to the storage channel:', error)\n\t\t}\n\t}\n\n\tprivate startChannel(): void {\n\t\tif (this.channel || !this.runtime.createChannel) return\n\t\tthis.channel = this.runtime.createChannel(storageChannelName(this.dbName))\n\t\tthis.channel.addEventListener('message', this.onMessage)\n\t}\n\n\tprivate stopChannel(): void {\n\t\tif (!this.channel) return\n\t\tthis.channel.removeEventListener('message', this.onMessage)\n\t\tthis.channel.close()\n\t\tthis.channel = null\n\t}\n\n\t// === Locks ===\n\n\t/** Request an exclusive lock and hold it until released. */\n\tprivate acquire(name: string, ifAvailable = false): Promise<HeldLock> {\n\t\tconst locks = this.requireLocks()\n\t\tif (this.state === 'closed') return Promise.reject(new VersionGateClosedError(this.dbName))\n\t\treturn new Promise<HeldLock>((resolve, reject) => {\n\t\t\tlet release: () => void = () => {}\n\t\t\tconst held = new Promise<void>((done) => {\n\t\t\t\trelease = done\n\t\t\t})\n\t\t\tlocks\n\t\t\t\t.request(\n\t\t\t\t\tname,\n\t\t\t\t\tifAvailable\n\t\t\t\t\t\t? { mode: 'exclusive', ifAvailable: true }\n\t\t\t\t\t\t: { mode: 'exclusive', signal: this.closeAbort.signal },\n\t\t\t\t\t(lock) => {\n\t\t\t\t\t\tif (lock === null) {\n\t\t\t\t\t\t\treject(new LockUnavailable())\n\t\t\t\t\t\t\treturn undefined\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (this.state === 'closed') {\n\t\t\t\t\t\t\t// Granted after close: hand it straight back.\n\t\t\t\t\t\t\treject(new VersionGateClosedError(this.dbName))\n\t\t\t\t\t\t\treturn undefined\n\t\t\t\t\t\t}\n\t\t\t\t\t\tresolve({ release })\n\t\t\t\t\t\treturn held\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t\t// Aborted by close(): the gate closed. Anything else (a SecurityError in a sandboxed\n\t\t\t\t// or opaque-origin frame) is the real cause and is reported as it is.\n\t\t\t\t.catch((error: unknown) =>\n\t\t\t\t\treject(\n\t\t\t\t\t\tthis.closeAbort.signal.aborted || this.state === 'closed'\n\t\t\t\t\t\t\t? new VersionGateClosedError(this.dbName)\n\t\t\t\t\t\t\t: error,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t})\n\t}\n\n\t/** Exclusive single tab (no `BroadcastChannel`): hold `kora-db:<db>` for the tab's life. */\n\tprivate async acquireExclusive(): Promise<void> {\n\t\tconst name = exclusiveDatabaseLockName(this.dbName)\n\t\ttry {\n\t\t\tthis.exclusiveLock = await this.acquire(name, true)\n\t\t\treturn\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof LockUnavailable)) throw error\n\t\t}\n\t\tconst me = this.identity\n\t\tconst holder = me\n\t\t\t? ((await this.discover()).find((tab) => tab.tabId !== me.tabId) ?? null)\n\t\t\t: null\n\t\tthis.throwIfStopped()\n\t\tif (me && holder && this.supersedes(holder, me)) {\n\t\t\t// The database is held by a tab of another build that opened later: this tab never\n\t\t\t// opened storage, so it retires at once.\n\t\t\tvoid this.retire(holder)\n\t\t\tthis.throwIfSuperseded()\n\t\t}\n\t\tthis.emitter?.emit({\n\t\t\ttype: 'store:tab-exclusive',\n\t\t\tdbName: this.dbName,\n\t\t\theldBy: holder ? { ...holder } : null,\n\t\t\tmessage: 'This app is open in another tab. Close it to continue here.',\n\t\t})\n\t\tif (me && holder && holder.build !== me.build && compareTabKeys(holder, me) < 0) {\n\t\t\tthis.waiting = { waitingFor: [holder], reason: 'live-writer' }\n\t\t\tthis.setState('waiting')\n\t\t\tthis.reportWaiting()\n\t\t}\n\t\tthis.exclusiveLock = await this.acquire(name)\n\t\tthis.waiting = null\n\t}\n\n\t/** Resolves once no tab holds `name` (a shared request is granted only then). */\n\tprivate waitForRelease(name: string): Promise<void> {\n\t\tconst locks = this.requireLocks()\n\t\tconst controller = new AbortController()\n\t\tthis.waitAborts.add(controller)\n\t\treturn locks\n\t\t\t.request(name, { mode: 'shared', signal: controller.signal }, () => undefined)\n\t\t\t.then(\n\t\t\t\t() => undefined,\n\t\t\t\t() => undefined,\n\t\t\t)\n\t\t\t.finally(() => {\n\t\t\t\tthis.waitAborts.delete(controller)\n\t\t\t})\n\t}\n\n\tprivate releaseHeldLocks(): void {\n\t\tthis.unsavedMarker?.release()\n\t\tthis.unsavedMarker = null\n\t\t// The exclusive database lock (no-channel mode) first: it is the storage role.\n\t\tthis.exclusiveLock?.release()\n\t\tthis.exclusiveLock = null\n\t\tthis.tabLock?.release()\n\t\tthis.tabLock = null\n\t}\n\n\tprivate requireLocks(): GateLockManager {\n\t\tconst locks = this.runtime.locks\n\t\tif (!locks) throw new TabCoordinationUnavailableError(this.dbName)\n\t\treturn locks\n\t}\n\n\tprivate setState(state: VersionGateState): void {\n\t\tif (this.state === state) return\n\t\t// Invariant: a retiring, retired or closed gate never becomes opening, waiting, open or\n\t\t// suspended again (the explicit rechecks after each await throw first; this is the\n\t\t// last line). Retiring may only become retired or closed.\n\t\tconst active =\n\t\t\tstate === 'opening' || state === 'waiting' || state === 'open' || state === 'suspended'\n\t\tif (\n\t\t\tactive &&\n\t\t\t(this.state === 'retiring' || this.state === 'retired' || this.state === 'closed')\n\t\t) {\n\t\t\treturn\n\t\t}\n\t\tthis.state = state\n\t\tthis.notifyChange()\n\t}\n\n\tprivate notifyChange(): void {\n\t\tconst snapshot = this.snapshot()\n\t\tfor (const listener of [...this.changeListeners]) {\n\t\t\ttry {\n\t\t\t\tlistener(snapshot)\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error('[kora] version gate: a change listener failed:', error)\n\t\t\t}\n\t\t}\n\t}\n}\n\nclass LockUnavailable extends Error {}\n\nfunction createTabId(): string {\n\tif (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n\t\treturn crypto.randomUUID()\n\t}\n\treturn `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`\n}\n","/// <reference lib=\"dom\" />\nimport { PersistenceError } from '../errors'\n\n/**\n * The version gate's open-order counter (section 3): a small IndexedDB database of its\n * own, `kora-gate`, one counter record per Kora database name. It lives apart from the\n * IndexedDB fallback's snapshot database because OPFS apps never open that one.\n *\n * Known edge: clearing site data while tabs stay open restarts the counter at 1, so a tab\n * opened afterwards (even of the newer build) can get a lower key than a tab still open\n * from before, and retire in its favour. Clearing site data deletes the database those\n * tabs use too; reloading every tab of the app restores the order.\n */\nconst GATE_DATABASE = 'kora-gate'\nconst GATE_STORE = 'open-seq'\n\nfunction openGateDatabase(): Promise<IDBDatabase> {\n\treturn new Promise<IDBDatabase>((resolve, reject) => {\n\t\tconst request = indexedDB.open(GATE_DATABASE, 1)\n\t\trequest.onupgradeneeded = () => {\n\t\t\tif (!request.result.objectStoreNames.contains(GATE_STORE)) {\n\t\t\t\trequest.result.createObjectStore(GATE_STORE)\n\t\t\t}\n\t\t}\n\t\trequest.onsuccess = () => resolve(request.result)\n\t\trequest.onerror = () =>\n\t\t\treject(\n\t\t\t\tnew PersistenceError(\n\t\t\t\t\t`Could not open the version gate's IndexedDB database: ${request.error?.message ?? 'unknown error'}`,\n\t\t\t\t\t{ database: GATE_DATABASE },\n\t\t\t\t),\n\t\t\t)\n\t})\n}\n\n/**\n * Allocate this tab's `openSeq` for `dbName`: read `n`, write `n + 1`, take `n + 1`, in\n * ONE `readwrite` transaction. IndexedDB serializes `readwrite` transactions on a store\n * across tabs, so no two tabs get the same value and a later allocation always gets a\n * higher one, whatever the wall clock does (it can move backwards, and two tabs can open\n * in the same millisecond). The record is never reset.\n *\n * @throws PersistenceError when IndexedDB is unavailable or the transaction fails: the\n *   caller fails the open, never guesses an order\n */\nexport async function allocateOpenSeq(dbName: string): Promise<number> {\n\tif (typeof indexedDB === 'undefined') {\n\t\tthrow new PersistenceError(\n\t\t\t`Could not order this tab among the tabs of database \"${dbName}\": IndexedDB is unavailable.`,\n\t\t\t{ dbName, code: 'OPEN_SEQ_UNAVAILABLE' },\n\t\t)\n\t}\n\tconst db = await openGateDatabase()\n\ttry {\n\t\treturn await new Promise<number>((resolve, reject) => {\n\t\t\tconst tx = db.transaction(GATE_STORE, 'readwrite')\n\t\t\tconst store = tx.objectStore(GATE_STORE)\n\t\t\tlet allocated = 0\n\t\t\tconst read = store.get(dbName)\n\t\t\tread.onsuccess = () => {\n\t\t\t\tconst current = typeof read.result === 'number' ? read.result : 0\n\t\t\t\tallocated = current + 1\n\t\t\t\tstore.put(allocated, dbName)\n\t\t\t}\n\t\t\ttx.oncomplete = () => resolve(allocated)\n\t\t\tconst fail = (): void =>\n\t\t\t\treject(\n\t\t\t\t\tnew PersistenceError(\n\t\t\t\t\t\t`Could not order this tab among the tabs of database \"${dbName}\": ${tx.error?.message ?? 'transaction aborted'}`,\n\t\t\t\t\t\t{ dbName, code: 'OPEN_SEQ_FAILED' },\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\ttx.onerror = fail\n\t\t\ttx.onabort = fail\n\t\t})\n\t} finally {\n\t\tdb.close()\n\t}\n}\n"]}