@g9tm/syncdata 1.5.18 → 1.5.20

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.
@@ -306,6 +306,11 @@ export declare const G9ERevocationReason: {
306
306
  readonly Unsubscribed: 1;
307
307
  readonly Expired: 2;
308
308
  readonly AccessRevoked: 3;
309
+ /**
310
+ * A row the device adopted from its own table that no subscription holds and the server never confirmed, released by the
311
+ * application (`G9SyncEngine.releaseUnclaimedRows`, 1.5.19).
312
+ */
313
+ readonly Unclaimed: 4;
309
314
  };
310
315
  export type G9ERevocationReason = (typeof G9ERevocationReason)[keyof typeof G9ERevocationReason];
311
316
  /** `G9ERevocationDisposition`. */
@@ -463,6 +468,10 @@ export interface G9SyncClientStore {
463
468
  /** Gives up the local change of rejected rows and takes the server's copy (LES-0070); run a forced reconcile after it. */
464
469
  revertRejected(localTable: string | null, key: string | null, signal?: AbortSignal): Promise<number>;
465
470
  markDirty(localTable: string, keys: readonly string[], signal?: AbortSignal): Promise<number>;
471
+ /** `RefetchRowsAsync` (1.5.19): clean held rows get `server_ver = -1` and their subscriptions NeedsReconcile. Returns the rows marked. */
472
+ refetchRows(localTable: string, keys: readonly string[] | null, signal?: AbortSignal): Promise<number>;
473
+ /** `ReleaseUnclaimedRowsAsync` (1.5.19): disposes adopted rows nothing holds and the server never claimed, capture off. */
474
+ releaseUnclaimedRows(localTable: string, keys: readonly string[] | null, includePending: boolean, signal?: AbortSignal): Promise<G9ApplyReport>;
466
475
  adoptExistingRows(signal?: AbortSignal): Promise<number>;
467
476
  saveRunReport(report: G9SyncRunReport, keep: number, signal?: AbortSignal): Promise<void>;
468
477
  getRecentRunReports(count: number, signal?: AbortSignal): Promise<G9SyncRunReport[]>;
@@ -215,6 +215,11 @@ export const G9ERevocationReason = {
215
215
  Unsubscribed: 1,
216
216
  Expired: 2,
217
217
  AccessRevoked: 3,
218
+ /**
219
+ * A row the device adopted from its own table that no subscription holds and the server never confirmed, released by the
220
+ * application (`G9SyncEngine.releaseUnclaimedRows`, 1.5.19).
221
+ */
222
+ Unclaimed: 4,
218
223
  };
219
224
  /** `G9ERevocationDisposition`. */
220
225
  export const G9ERevocationDisposition = {
@@ -1 +1 @@
1
- {"version":3,"file":"storeTypes.js","sourceRoot":"","sources":["../../src/client/storeTypes.ts"],"names":[],"mappings":"AAkCA,8BAA8B;AAC9B,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,MAAM,EAAE,CAAC;IACT,cAAc,EAAE,CAAC;IACjB,MAAM,EAAE,CAAC;CACD,CAAC;AAyBX,iDAAiD;AACjD,MAAM,UAAU,iBAAiB,CAAC,MAAgC;IAChE,OAAO;QACL,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,UAAU,EAAE,MAAM,CAAC,UAAU,CAAC,MAAM;QACpC,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,cAAc,EAAE,MAAM,CAAC,cAAc;QACrC,QAAQ,EAAE,MAAM,CAAC,QAAQ;KAC1B,CAAC;AACJ,CAAC;AAiED,2EAA2E;AAE3E,yEAAyE;AACzE,MAAM,CAAC,MAAM,sBAAsB,GAAG,iBAAiB,CAAC;AACxD,MAAM,yBAAyB,GAAG,EAAE,CAAC;AAErC,yFAAyF;AACzF,oHAAoH;AACpH,MAAM,CAAC,MAAM,cAAc,GAAG,MAAM,CAAC;AACrC,8DAA8D;AAC9D,MAAM,CAAC,MAAM,iBAAiB,GAAG,SAAS,CAAC;AAC3C,4FAA4F;AAC5F,MAAM,CAAC,MAAM,eAAe,GAAG,OAAO,CAAC;AACvC,kIAAkI;AAClI,MAAM,CAAC,MAAM,gBAAgB,GAAG,QAAQ,CAAC;AAEzC,MAAM,OAAO,kBAAkB;IAA/B;QACE,iBAAY,GAAG,CAAC,CAAC;QACjB,oCAA+B,GAAG,CAAC,CAAC;QAC3B,oBAAe,GAAa,EAAE,CAAC;QAC/B,oBAAe,GAAgC,EAAE,CAAC;QAClD,qBAAgB,GAAgC,EAAE,CAAC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,EAAE,IAAI,CAAC,CAAC;IACjC,CAAC;IAEO,IAAI,CACV,MAAmF,EACnF,WAAoD;QAEpD,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,KAAK,EAAE,SAAS,EAAE,IAAI,CAAC,UAAU,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC,CAAC;QAC9F,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;CACF;AAuBD,4EAA4E;AAE5E,0GAA0G;AAC1G,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,KAAK,EAAE,CAAC;IACR,OAAO,EAAE,CAAC;IACV,QAAQ,EAAE,CAAC;IACX,IAAI,EAAE,CAAC;CACC,CAAC;AAQX,MAAM,UAAU,mBAAmB,CAAC,KAAc;IAChD,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,OAAQ,KAAyC,CAAC,iBAAiB,KAAK,QAAQ,CAAC;AACzI,CAAC","sourcesContent":["// Twins of G9SyncData.Client/Storage/*.cs: the client store contract, its records, local commands, revocation rules\r\n// and apply diagnostics. The engine is store-agnostic; `@g9tm/syncdata/sqlite` is the implementation.\r\nimport type { G9EMoveOutPolicy } from '../abstractions/enums.js';\r\nimport type { G9Long } from '../abstractions/long.js';\r\nimport type { G9SyncParameters } from '../abstractions/parameters.js';\r\nimport type {\r\n G9DtBackfillRequest,\r\n G9DtCommand,\r\n G9DtHelloResult,\r\n G9DtNegotiatedTable,\r\n G9DtPullContinuation,\r\n G9DtPullPlan,\r\n G9DtPushResult,\r\n G9DtSnapshotFileRequest,\r\n G9DtSubscriptionDefinition,\r\n G9DtSubscriptionRef,\r\n G9DtSyncChunk,\r\n G9DtTableColumns,\r\n G9DtTableDigest,\r\n} from '../protocol/dtos.js';\r\nimport type { G9SyncClientModel } from './model.js';\r\n\r\n// ---------------------------------------------------------------- server state and subscriptions\r\n\r\n/** What the client last learned from the server (`G9CClientServerState`). */\r\nexport interface G9ClientServerState {\r\n epoch: string | null;\r\n lastHelloUtcMs: number | null;\r\n /** Server clock minus device clock, ms. */\r\n serverClockOffsetMs: number;\r\n tables: G9DtNegotiatedTable[];\r\n definitions: G9DtSubscriptionDefinition[];\r\n}\r\n\r\n/** `G9ESubscriptionState`. */\r\nexport const G9ESubscriptionState = {\r\n Active: 0,\r\n NeedsReconcile: 1,\r\n Failed: 2,\r\n} as const;\r\nexport type G9ESubscriptionState = (typeof G9ESubscriptionState)[keyof typeof G9ESubscriptionState];\r\n\r\n/** A local subscription (`G9CSyncSubscriptionRecord`). Times are epoch milliseconds UTC. */\r\nexport interface G9SyncSubscriptionRecord {\r\n key: string;\r\n name: string;\r\n parameters: G9SyncParameters;\r\n /** Membership slot (bit) for persistent subscriptions; the shared ephemeral slot otherwise. */\r\n slot: number;\r\n ephemeral: boolean;\r\n ttlMs: number | null;\r\n cursor: string | null;\r\n /** The move-out policy the server last announced; kept so it still applies once access is gone. */\r\n moveOutPolicy: G9EMoveOutPolicy | null;\r\n definitionHash: string | null;\r\n authHash: string | null;\r\n state: G9ESubscriptionState;\r\n lastErrorCode: string | null;\r\n createdUtcMs: number;\r\n lastSuccessUtcMs: number | null;\r\n lastReconcileUtcMs: number | null;\r\n lastAccessUtcMs: number | null;\r\n}\r\n\r\n/** `G9CSyncSubscriptionRecord.ToReference()`. */\r\nexport function toSubscriptionRef(record: G9SyncSubscriptionRecord): G9DtSubscriptionRef {\r\n return {\r\n name: record.name,\r\n parameters: record.parameters.values,\r\n cursor: record.cursor,\r\n definitionHash: record.definitionHash,\r\n authHash: record.authHash,\r\n };\r\n}\r\n\r\n/** A partial update of a subscription record; absent members are left unchanged (`G9CSubscriptionUpdate`). */\r\nexport interface G9SubscriptionUpdate {\r\n cursor?: string | null;\r\n definitionHash?: string | null;\r\n authHash?: string | null;\r\n state?: G9ESubscriptionState | null;\r\n errorCode?: string | null;\r\n clearError?: boolean;\r\n succeeded?: boolean;\r\n reconciled?: boolean;\r\n accessed?: boolean;\r\n clearCursor?: boolean;\r\n}\r\n\r\n// ---------------------------------------------------------------- push and pull\r\n\r\n/** A push batch built from dirty rows (`G9CPushBatch`). */\r\nexport interface G9PushBatch {\r\n batchId: number;\r\n /** Highest local change sequence included; rows changed after it stay dirty after the acknowledgement. */\r\n maxSequence: number;\r\n frames: Uint8Array[];\r\n tables: G9DtTableColumns[];\r\n rowCount: number;\r\n /** True when the byte budget ended the batch early: more pending rows follow. */\r\n truncated: boolean;\r\n /** Rows rejected on the device while building the batch (G9S-REJ-TOO-LARGE). */\r\n rejectedLocally: number;\r\n /** Commands carried by this batch, in device order. */\r\n commands: G9DtCommand[];\r\n}\r\n\r\n/** A pull being staged, persisted across restarts (`G9CStagedPull`). */\r\nexport interface G9StagedPull {\r\n runId: string;\r\n plan: G9DtPullPlan;\r\n createdUtcMs: number;\r\n backfills: G9DtBackfillRequest[];\r\n /** What the world looked like when the plan was made (ADR-0046); a run only resumes a stage whose generation matches. */\r\n generation: string | null;\r\n /** The cursor each planned subscription had when the plan was made, by subscription key (ADR-0060). */\r\n plannedFromCursors: { [subscriptionKey: string]: string | null };\r\n /** The device clock when the stage began, assigned by the store. */\r\n stageSequence: number;\r\n}\r\n\r\n/** One committed slice of a staged pull (`G9CApplySlice`). */\r\nexport interface G9ApplySlice {\r\n report: G9ApplyReport;\r\n rowsApplied: number;\r\n rowsAppliedTotal: number;\r\n rowsPlanned: number;\r\n isFinal: boolean;\r\n}\r\n\r\n/** `G9CResumePoint`. */\r\nexport interface G9ResumePoint {\r\n continuation: G9DtPullContinuation | null;\r\n stagedRows: number;\r\n stagedBytes: number;\r\n complete: boolean;\r\n}\r\n\r\n// ---------------------------------------------------------------- reports\r\n\r\n/** Why a table large enough for index deferral kept its indexes live. */\r\nexport const REASON_TABLE_NOT_EMPTY = 'table-not-empty';\r\nconst MAX_FOREIGN_TRIGGER_NAMES = 10;\r\n\r\n/** How an apply ran, as opposed to what it changed (`G9CApplyDiagnostics`, ADR-0058). */\r\n/** A file table copied record for record into an empty table with identical columns (the transfer optimisation). */\r\nexport const FILE_MODE_COPY = 'copy';\r\n/** A file table copied into an empty table by column name. */\r\nexport const FILE_MODE_COLUMNS = 'columns';\r\n/** A file table merged into a table that held rows or protected rows: changed rows only. */\r\nexport const FILE_MODE_MERGE = 'merge';\r\n/** A file table inserted into a table holding only OTHER rows (a second site's first load): every row is new, no per-row diff. */\r\nexport const FILE_MODE_APPEND = 'append';\r\n\r\nexport class G9ApplyDiagnostics {\r\n transactions = 0;\r\n transactionsWithTriggersSkipped = 0;\r\n readonly foreignTriggers: string[] = [];\r\n readonly deferredIndexes: { [table: string]: number } = {};\r\n readonly liveIndexReasons: { [table: string]: string } = {};\r\n readonly rowsByTable: { [table: string]: number } = {};\r\n readonly msByTable: { [table: string]: number } = {};\r\n indexRebuildMs = 0;\r\n elapsedMs = 0;\r\n /** Snapshot files copied in (ADR-0072). */\r\n snapshotFiles = 0;\r\n /** Rows that arrived through snapshot files. */\r\n fileRows = 0;\r\n /** Milliseconds spent copying snapshot files, metadata included. */\r\n fileCopyMs = 0;\r\n /** How each table came out of a snapshot file: `copy`, `columns` or `merge` (see FILE_MODE_*). */\r\n readonly fileTables: { [table: string]: string } = {};\r\n\r\n /** True when every transaction ran with trigger execution off, false when any ran with it on, null when nothing was applied. */\r\n get triggersSkipped(): boolean | null {\r\n return this.transactions === 0 ? null : this.transactionsWithTriggersSkipped === this.transactions;\r\n }\r\n\r\n get deferredIndexCount(): number {\r\n let total = 0;\r\n for (const key of Object.keys(this.deferredIndexes)) total += this.deferredIndexes[key] as number;\r\n return total;\r\n }\r\n\r\n merge(other: G9ApplyDiagnostics): void {\r\n this.transactions += other.transactions;\r\n this.transactionsWithTriggersSkipped += other.transactionsWithTriggersSkipped;\r\n this.indexRebuildMs += other.indexRebuildMs;\r\n this.elapsedMs += other.elapsedMs;\r\n this.snapshotFiles += other.snapshotFiles;\r\n this.fileRows += other.fileRows;\r\n this.fileCopyMs += other.fileCopyMs;\r\n for (const key of Object.keys(other.fileTables)) this.fileTables[key] = other.fileTables[key] as string;\r\n for (const name of other.foreignTriggers) {\r\n if (this.foreignTriggers.length >= MAX_FOREIGN_TRIGGER_NAMES) break;\r\n if (!this.foreignTriggers.some((n) => n.toLowerCase() === name.toLowerCase())) this.foreignTriggers.push(name);\r\n }\r\n addAll(this.deferredIndexes, other.deferredIndexes);\r\n for (const key of Object.keys(other.liveIndexReasons)) this.liveIndexReasons[key] = other.liveIndexReasons[key] as string;\r\n addAll(this.rowsByTable, other.rowsByTable);\r\n addAll(this.msByTable, other.msByTable);\r\n }\r\n\r\n /** One line for a log: what engaged, what did not and why, and the tables that took the time. */\r\n toString(): string {\r\n if (this.transactions === 0) return 'nothing applied';\r\n let text = `${this.transactions} transaction(s) in ${this.elapsedMs} ms; triggers `;\r\n text +=\r\n this.triggersSkipped === true\r\n ? 'skipped'\r\n : this.transactionsWithTriggersSkipped === 0\r\n ? 'LIVE'\r\n : `skipped in ${this.transactionsWithTriggersSkipped} of ${this.transactions}`;\r\n if (this.foreignTriggers.length > 0) text += ' (foreign: ' + this.foreignTriggers.join(', ') + ')';\r\n const deferred = Object.keys(this.deferredIndexes);\r\n if (deferred.length > 0) {\r\n text += `; ${this.deferredIndexCount} index(es) rebuilt after the load in ${this.indexRebuildMs} ms (` + deferred.map((t) => t + ':' + this.deferredIndexes[t]).join(', ') + ')';\r\n }\r\n const live = Object.keys(this.liveIndexReasons);\r\n if (live.length > 0) text += '; live indexes on ' + live.map((t) => t + ' (' + this.liveIndexReasons[t] + ')').join(', ');\r\n if (this.snapshotFiles > 0) {\r\n text +=\r\n `; ${this.snapshotFiles} snapshot file(s), ${this.fileRows} rows copied in ${this.fileCopyMs} ms (` +\r\n Object.keys(this.fileTables)\r\n .map((t) => t + ':' + this.fileTables[t])\r\n .join(', ') +\r\n ')';\r\n }\r\n const slowest = Object.keys(this.msByTable)\r\n .sort((a, b) => (this.msByTable[b] as number) - (this.msByTable[a] as number))\r\n .slice(0, 4);\r\n if (slowest.length > 0) {\r\n text +=\r\n '; ' +\r\n slowest\r\n .map((t) => {\r\n const ms = this.msByTable[t] as number;\r\n const rows = this.rowsByTable[t] ?? 0;\r\n const rate = ms > 0 ? Math.floor((rows * 1000) / ms) : rows;\r\n return `${t} ${rows} rows in ${ms} ms (${rate}/s)`;\r\n })\r\n .join(', ');\r\n }\r\n return text;\r\n }\r\n}\r\n\r\nfunction addAll(target: { [key: string]: number }, source: { [key: string]: number }): void {\r\n for (const key of Object.keys(source)) target[key] = (target[key] ?? 0) + (source[key] as number);\r\n}\r\n\r\n/** What an apply changed (`G9CApplyReport`). */\r\nexport class G9ApplyReport {\r\n upserts = 0;\r\n deletes = 0;\r\n moveOuts = 0;\r\n membershipAdded = 0;\r\n /** Rows skipped because they carry a pending local change. */\r\n skippedDirty = 0;\r\n accepted = 0;\r\n rejected = 0;\r\n conflicts = 0;\r\n /** Conflicts the device lost that were kept on it as rejections (LES-0072). */\r\n conflictsKept = 0;\r\n /** Conflicts the device lost on paper only: the server already held its values for every lost column (LES-0085). */\r\n conflictsSameValue = 0;\r\n commandsCompleted = 0;\r\n revokedDeleted = 0;\r\n revokedQuarantined = 0;\r\n revokedRetained = 0;\r\n /** Changed keys per local table (capped per table). */\r\n readonly changedKeys: { [localTable: string]: string[] } = {};\r\n /** Upserts whose row already held exactly the incoming values (ADR-0058). */\r\n unchangedRows = 0;\r\n readonly diagnostics = new G9ApplyDiagnostics();\r\n\r\n get total(): number {\r\n return this.upserts + this.deletes + this.moveOuts;\r\n }\r\n\r\n merge(other: G9ApplyReport): void {\r\n this.unchangedRows += other.unchangedRows;\r\n this.diagnostics.merge(other.diagnostics);\r\n this.upserts += other.upserts;\r\n this.deletes += other.deletes;\r\n this.moveOuts += other.moveOuts;\r\n this.membershipAdded += other.membershipAdded;\r\n this.skippedDirty += other.skippedDirty;\r\n this.accepted += other.accepted;\r\n this.rejected += other.rejected;\r\n this.conflicts += other.conflicts;\r\n this.conflictsKept += other.conflictsKept;\r\n this.conflictsSameValue += other.conflictsSameValue;\r\n this.commandsCompleted += other.commandsCompleted;\r\n this.revokedDeleted += other.revokedDeleted;\r\n this.revokedQuarantined += other.revokedQuarantined;\r\n this.revokedRetained += other.revokedRetained;\r\n for (const table of Object.keys(other.changedKeys)) {\r\n const list = this.changedKeys[table] ?? (this.changedKeys[table] = []);\r\n for (const key of other.changedKeys[table] as string[]) list.push(key);\r\n }\r\n }\r\n}\r\n\r\n/** A local row as seen by reconciliation (`G9CLocalRowEntry`). */\r\nexport interface G9LocalRowEntry {\r\n key: string;\r\n bucket: number;\r\n version: number;\r\n hash: G9Long;\r\n member: boolean;\r\n dirty: boolean;\r\n}\r\n\r\nexport interface G9PendingTable {\r\n localTable: string;\r\n upserts: number;\r\n deletes: number;\r\n rejected: number;\r\n}\r\n\r\nexport interface G9PendingSummary {\r\n totalRows: number;\r\n rejectedRows: number;\r\n /** Commands recorded on the device and not yet executed by the server. */\r\n pendingCommands: number;\r\n tables: G9PendingTable[];\r\n}\r\n\r\n/** One entry of the local change feed (`G9CChangeFeedEntry`). */\r\nexport interface G9ChangeFeedEntry {\r\n sequence: number;\r\n key: string;\r\n deleted: boolean;\r\n localPending: boolean;\r\n}\r\n\r\n/**\r\n * Narrows a change-feed read to the keys a query of the app's own tables selects (`G9CChangeFeedKeyFilter`): a projection of one\r\n * site no longer walks the entries of every other site. Deletions are always returned - their rows are gone, so no query can place\r\n * them. `keySql` is one SELECT of one column, embedded as `pk IN (...)`; parameters are bound by name (`$name`, `@name`, `:name`)\r\n * and `$g9t`, `$g9a`, `$g9l` belong to the read.\r\n */\r\nexport interface G9ChangeFeedKeyFilter {\r\n keySql: string;\r\n parameters?: { [name: string]: string | number | null };\r\n}\r\n\r\nconst RESERVED_FEED_PARAMETERS = ['$g9t', '$g9a', '$g9l'];\r\n\r\n/** Throws when the filter cannot be embedded safely (`G9CChangeFeedKeyFilter.Validate`). */\r\nexport function validateChangeFeedKeyFilter(filter: G9ChangeFeedKeyFilter): void {\r\n const sql = (filter.keySql ?? '').trim();\r\n if (sql.slice(0, 6).toUpperCase() !== 'SELECT' || sql.indexOf(';') >= 0) {\r\n throw new Error('A change-feed key filter is a single SELECT statement of one column.');\r\n }\r\n for (const name of Object.keys(filter.parameters ?? {})) {\r\n if (name.length < 2 || '$@:'.indexOf(name[0] as string) < 0) throw new Error(`Change-feed key filter parameter '${name}' must be named ($name, @name or :name).`);\r\n if (RESERVED_FEED_PARAMETERS.indexOf(name.toLowerCase()) >= 0) throw new Error(`Change-feed key filter parameter '${name}' is reserved by the read.`);\r\n }\r\n}\r\n\r\nexport interface G9SyncRejection {\r\n localTable: string;\r\n key: string;\r\n code: string;\r\n message: string | null;\r\n sqlState: string | null;\r\n constraint: string | null;\r\n column: string | null;\r\n details: string | null;\r\n atUtcMs: number;\r\n}\r\n\r\n/** A persisted summary of one run (`G9CSyncRunReport`); serialized with the .NET JSON names into g9_runs. */\r\nexport interface G9SyncRunReport {\r\n runId: string;\r\n startedUtcMs: number;\r\n durationMs: number;\r\n outcome: string;\r\n priority: string;\r\n errorCode: string | null;\r\n errorMessage: string | null;\r\n pushed: number;\r\n rejected: number;\r\n conflicts: number;\r\n downloaded: number;\r\n applied: number;\r\n downloadedBytes: number;\r\n subscriptions: string[];\r\n phaseMs: { [phase: string]: number };\r\n triggersSkipped: boolean | null;\r\n foreignTriggers: string[];\r\n applyTransactions: number;\r\n indexesDeferred: number;\r\n indexRebuildMs: number;\r\n liveIndexReasons: { [table: string]: string };\r\n unchangedRows: number;\r\n}\r\n\r\n// ---------------------------------------------------------------- local commands (ADR-0025)\r\n\r\n/** `G9ELocalCommandState`. */\r\nexport const G9ELocalCommandState = {\r\n Pending: 0,\r\n Ok: 1,\r\n Rejected: 2,\r\n Superseded: 3,\r\n} as const;\r\nexport type G9ELocalCommandState = (typeof G9ELocalCommandState)[keyof typeof G9ELocalCommandState];\r\n\r\n/** A command recorded on this device (`G9CLocalCommand`). */\r\nexport interface G9LocalCommand {\r\n commandId: string;\r\n sequence: number;\r\n name: string;\r\n version: number;\r\n payload: string;\r\n createdUtcMs: number;\r\n state: G9ELocalCommandState;\r\n code: string | null;\r\n message: string | null;\r\n result: string | null;\r\n completedUtcMs: number | null;\r\n}\r\n\r\n/** What to record (`G9CCommandRequest`). */\r\nexport interface G9CommandRequest {\r\n name: string;\r\n version?: number;\r\n /** JSON payload for the server's handler. */\r\n payload: string;\r\n}\r\n\r\n/** A value an app binds through {@link G9LocalCommandWriter}: the SQLite driver's value forms, plus booleans. */\r\nexport type G9LocalSqlArgument = null | number | string | boolean | ArrayBuffer | Uint8Array | { int64: string } | G9Long;\r\n\r\n/**\r\n * Writes a command's local effects in the transaction that records it (`IG9LocalCommandWriter`). Rows written here are\r\n * not uploaded as row changes; they are protected from pulls until the server's result arrives.\r\n */\r\nexport interface G9LocalCommandWriter {\r\n /** Executes SQL; parameters bind positionally as `$p0`, `$p1`, … */\r\n execute(sql: string, ...args: G9LocalSqlArgument[]): Promise<number>;\r\n scalar(sql: string, ...args: G9LocalSqlArgument[]): Promise<unknown>;\r\n}\r\n\r\n// ---------------------------------------------------------------- revocation (ADR-0026)\r\n\r\n/** `G9ERevocationReason`. */\r\nexport const G9ERevocationReason = {\r\n LeftScope: 0,\r\n Unsubscribed: 1,\r\n Expired: 2,\r\n AccessRevoked: 3,\r\n} as const;\r\nexport type G9ERevocationReason = (typeof G9ERevocationReason)[keyof typeof G9ERevocationReason];\r\n\r\n/** `G9ERevocationDisposition`. */\r\nexport const G9ERevocationDisposition = {\r\n Delete: 0,\r\n MarkRevoked: 1,\r\n Quarantine: 2,\r\n Retain: 3,\r\n} as const;\r\nexport type G9ERevocationDisposition = (typeof G9ERevocationDisposition)[keyof typeof G9ERevocationDisposition];\r\n\r\n/** A row no subscription holds any more, as a revocation rule sees it (`G9CRevokedRow`). */\r\nexport interface G9RevokedRow {\r\n localTable: string;\r\n key: string;\r\n reason: G9ERevocationReason;\r\n subscriptionKey: string | null;\r\n hasPendingChanges: boolean;\r\n isRejected: boolean;\r\n /** Column values (key included) as stored locally; empty when the row no longer exists locally. */\r\n values: { [column: string]: unknown };\r\n}\r\n\r\n/** Lets a custom rule change the row before its disposition applies. */\r\nexport interface G9RevokedRowEditor {\r\n set(column: string, value: unknown): void;\r\n}\r\n\r\nexport interface G9RevocationRule {\r\n readonly name: string;\r\n readonly condition: (row: G9RevokedRow) => boolean;\r\n readonly decide: (row: G9RevokedRow, editor: G9RevokedRowEditor) => G9ERevocationDisposition;\r\n readonly retainWhile: ((row: G9RevokedRow) => boolean) | null;\r\n}\r\n\r\n/** Ordered revocation rules (`G9CRevocationPolicy`): the first matching rule decides. */\r\nexport class G9RevocationPolicy {\r\n readonly rules: readonly G9RevocationRule[];\r\n\r\n private constructor(rules: readonly G9RevocationRule[]) {\r\n this.rules = rules;\r\n }\r\n\r\n /** No rules: delete clean rows, quarantine rows with pending changes. */\r\n static readonly default = new G9RevocationPolicy([]);\r\n\r\n static create(configure: (builder: G9RevocationPolicyBuilder) => void): G9RevocationPolicy {\r\n const builder = new G9RevocationPolicyBuilder();\r\n configure(builder);\r\n return new G9RevocationPolicy(builder.rules.slice());\r\n }\r\n\r\n decide(row: G9RevokedRow, editor: G9RevokedRowEditor): { rule: G9RevocationRule | null; disposition: G9ERevocationDisposition } {\r\n for (const rule of this.rules) {\r\n if (rule.condition(row)) return { rule, disposition: rule.decide(row, editor) };\r\n }\r\n return { rule: null, disposition: row.hasPendingChanges ? G9ERevocationDisposition.Quarantine : G9ERevocationDisposition.Delete };\r\n }\r\n\r\n find(name: string): G9RevocationRule | null {\r\n for (const rule of this.rules) if (rule.name === name) return rule;\r\n return null;\r\n }\r\n}\r\n\r\nexport class G9RevocationPolicyBuilder {\r\n readonly rules: G9RevocationRule[] = [];\r\n\r\n when(name: string, condition: (row: G9RevokedRow) => boolean): G9RevocationActionBuilder {\r\n if (typeof name !== 'string' || name.trim() === '') throw new TypeError('A rule needs a name.');\r\n if (this.rules.some((r) => r.name === name)) throw new RangeError(`Revocation rule '${name}' is declared twice.`);\r\n return new G9RevocationActionBuilder(this, name, condition);\r\n }\r\n\r\n /** Rows of one local table. */\r\n forTable(name: string, localTable: string, condition?: (row: G9RevokedRow) => boolean): G9RevocationActionBuilder {\r\n const table = localTable.toLowerCase();\r\n return this.when(name, (row) => row.localTable.toLowerCase() === table && (condition ? condition(row) : true));\r\n }\r\n}\r\n\r\nexport class G9RevocationActionBuilder {\r\n private readonly _owner: G9RevocationPolicyBuilder;\r\n private readonly _name: string;\r\n private readonly _condition: (row: G9RevokedRow) => boolean;\r\n\r\n constructor(owner: G9RevocationPolicyBuilder, name: string, condition: (row: G9RevokedRow) => boolean) {\r\n this._owner = owner;\r\n this._name = name;\r\n this._condition = condition;\r\n }\r\n\r\n delete(): G9RevocationPolicyBuilder {\r\n return this._add(() => G9ERevocationDisposition.Delete, null);\r\n }\r\n\r\n markRevoked(): G9RevocationPolicyBuilder {\r\n return this._add(() => G9ERevocationDisposition.MarkRevoked, null);\r\n }\r\n\r\n quarantine(): G9RevocationPolicyBuilder {\r\n return this._add(() => G9ERevocationDisposition.Quarantine, null);\r\n }\r\n\r\n retainWhile(retainWhile: (row: G9RevokedRow) => boolean): G9RevocationPolicyBuilder {\r\n return this._add(() => G9ERevocationDisposition.Retain, retainWhile);\r\n }\r\n\r\n custom(decide: (row: G9RevokedRow, editor: G9RevokedRowEditor) => G9ERevocationDisposition): G9RevocationPolicyBuilder {\r\n return this._add(decide, null);\r\n }\r\n\r\n private _add(\r\n decide: (row: G9RevokedRow, editor: G9RevokedRowEditor) => G9ERevocationDisposition,\r\n retainWhile: ((row: G9RevokedRow) => boolean) | null,\r\n ): G9RevocationPolicyBuilder {\r\n this._owner.rules.push({ name: this._name, condition: this._condition, decide, retainWhile });\r\n return this._owner;\r\n }\r\n}\r\n\r\n/** A row in the holding area (`G9CQuarantinedRow`). */\r\nexport interface G9QuarantinedRow {\r\n localTable: string;\r\n key: string;\r\n reason: G9ERevocationReason;\r\n rule: string | null;\r\n hadPendingChanges: boolean;\r\n values: { [column: string]: unknown };\r\n atUtcMs: number;\r\n}\r\n\r\n/** A row kept in the app's table after revocation (`G9CRetainedRow`). */\r\nexport interface G9RetainedRow {\r\n localTable: string;\r\n key: string;\r\n disposition: G9ERevocationDisposition;\r\n reason: G9ERevocationReason;\r\n rule: string | null;\r\n atUtcMs: number;\r\n}\r\n\r\n// ---------------------------------------------------------------- failures\r\n\r\n/** What went wrong inside a client store, in terms an application can act on (`G9ELocalStoreFailure`). */\r\nexport const G9ELocalStoreFailure = {\r\n Other: 0,\r\n Corrupt: 1,\r\n DiskFull: 2,\r\n Busy: 3,\r\n} as const;\r\nexport type G9ELocalStoreFailure = (typeof G9ELocalStoreFailure)[keyof typeof G9ELocalStoreFailure];\r\n\r\n/** Implemented by a store's errors so the engine can give a run's failure a stable code (`IG9SyncLocalStoreFailure`). */\r\nexport interface G9SyncLocalStoreFailure {\r\n readonly localStoreFailure: G9ELocalStoreFailure;\r\n}\r\n\r\nexport function isLocalStoreFailure(error: unknown): error is G9SyncLocalStoreFailure {\r\n return typeof error === 'object' && error !== null && typeof (error as { localStoreFailure?: unknown }).localStoreFailure === 'number';\r\n}\r\n\r\n// ---------------------------------------------------------------- the store contract\r\n\r\n/**\r\n * The client storage provider (`IG9SyncClientStore`): local tables, change capture, subscription membership,\r\n * staging, apply and metadata. Every method takes an optional AbortSignal (the CancellationToken twin).\r\n */\r\nexport interface G9SyncClientStore {\r\n initialize(model: G9SyncClientModel, signal?: AbortSignal): Promise<void>;\r\n getClientId(signal?: AbortSignal): Promise<string>;\r\n getServerState(signal?: AbortSignal): Promise<G9ClientServerState>;\r\n /**\r\n * Stores the Hello answer. `localMidpointMs`: the local time the server's clock reading corresponds to - the midpoint of the round\r\n * trip (LES-0075); the offset is then exact up to the asymmetry of the two legs. Omitted: the time of this call.\r\n */\r\n saveHello(hello: G9DtHelloResult, signal?: AbortSignal, localMidpointMs?: number): Promise<void>;\r\n getPendingBackfills(signal?: AbortSignal): Promise<G9DtBackfillRequest[]>;\r\n\r\n getSubscriptions(signal?: AbortSignal): Promise<G9SyncSubscriptionRecord[]>;\r\n ensureSubscription(\r\n name: string,\r\n parameters: G9SyncParameters,\r\n ephemeral: boolean,\r\n ttlMs: number | null,\r\n adoptExistingRows: boolean,\r\n signal?: AbortSignal,\r\n ): Promise<G9SyncSubscriptionRecord>;\r\n removeSubscription(key: string, policy: G9EMoveOutPolicy, signal?: AbortSignal): Promise<void>;\r\n releaseSubscriptionRows(key: string, signal?: AbortSignal): Promise<G9ApplyReport>;\r\n updateSubscription(key: string, update: G9SubscriptionUpdate, signal?: AbortSignal): Promise<void>;\r\n collectExpiredEphemeral(utcNowMs: number, signal?: AbortSignal): Promise<number>;\r\n\r\n buildPushBatch(tables: readonly G9DtNegotiatedTable[], maxRows: number, maxBytes: number, signal?: AbortSignal): Promise<G9PushBatch | null>;\r\n forgetUploadedRows(localTable: string, keys: readonly string[] | null, signal?: AbortSignal): Promise<number>;\r\n applyPushResult(batch: G9PushBatch, result: G9DtPushResult, signal?: AbortSignal): Promise<G9ApplyReport>;\r\n\r\n getStagedPull(signal?: AbortSignal): Promise<G9StagedPull | null>;\r\n /** The newest staged pull planned under exactly this generation, or null (ADR-0060). */\r\n getStagedPullForGeneration(generation: string, signal?: AbortSignal): Promise<G9StagedPull | null>;\r\n beginStagedPull(pull: G9StagedPull, signal?: AbortSignal): Promise<void>;\r\n pruneStagedPulls(olderThanUtcMs: number, maxBytes: number, keepGeneration: string | null, signal?: AbortSignal): Promise<number>;\r\n discardAllStagedPulls(signal?: AbortSignal): Promise<number>;\r\n stageChunk(runId: string, chunk: G9DtSyncChunk, signal?: AbortSignal): Promise<void>;\r\n /**\r\n * The store's offer to receive large first downloads as SQLite snapshot files (ADR-0072), or null for rows only. A store that\r\n * makes an offer stages file segments (`chunk.file`) in `stageChunk` and copies the files in `applyStagedPull`.\r\n */\r\n describeSnapshotFiles?(negotiated: readonly G9DtNegotiatedTable[]): G9DtSnapshotFileRequest | null;\r\n getResumePoint(runId: string, signal?: AbortSignal): Promise<G9ResumePoint>;\r\n applyStagedPull(\r\n runId: string,\r\n rowsApplied: ((rows: number) => void) | null,\r\n slices: ((slice: G9ApplySlice) => void) | null,\r\n signal?: AbortSignal,\r\n ): Promise<G9ApplyReport>;\r\n discardStagedPull(runId: string, signal?: AbortSignal): Promise<void>;\r\n\r\n computeDigest(subscriptionKey: string, table: G9DtNegotiatedTable, signal?: AbortSignal): Promise<G9DtTableDigest>;\r\n readLocalEntries(\r\n subscriptionKey: string,\r\n table: G9DtNegotiatedTable,\r\n buckets: ReadonlySet<number>,\r\n serverKeys: ReadonlySet<string>,\r\n signal?: AbortSignal,\r\n ): Promise<G9LocalRowEntry[]>;\r\n applyReconcile(\r\n subscriptionKey: string,\r\n table: G9DtNegotiatedTable,\r\n fetchedFrames: readonly Uint8Array[],\r\n addMembership: readonly string[],\r\n moveOut: readonly string[],\r\n policy: G9EMoveOutPolicy,\r\n signal?: AbortSignal,\r\n ): Promise<G9ApplyReport>;\r\n\r\n getPendingSummary(signal?: AbortSignal): Promise<G9PendingSummary>;\r\n enqueueCommand(\r\n request: G9CommandRequest,\r\n applyLocally: ((writer: G9LocalCommandWriter, signal?: AbortSignal) => Promise<void>) | null,\r\n signal?: AbortSignal,\r\n ): Promise<G9LocalCommand>;\r\n getQuarantined(signal?: AbortSignal): Promise<G9QuarantinedRow[]>;\r\n restoreQuarantined(localTable: string, key: string, signal?: AbortSignal): Promise<number>;\r\n discardQuarantined(localTable: string | null, key: string | null, signal?: AbortSignal): Promise<number>;\r\n getRetained(signal?: AbortSignal): Promise<G9RetainedRow[]>;\r\n reevaluateRetained(signal?: AbortSignal): Promise<number>;\r\n getCommands(state: G9ELocalCommandState | null, limit: number, signal?: AbortSignal): Promise<G9LocalCommand[]>;\r\n readChangeFeed(localTable: string, afterSequence: number, limit: number, signal?: AbortSignal): Promise<G9ChangeFeedEntry[]>;\r\n /** The feed narrowed to the keys `keyFilter` selects, plus every deletion; fewer than `limit` entries means the read is complete. */\r\n readChangeFeedFiltered(localTable: string, afterSequence: number, limit: number, keyFilter: G9ChangeFeedKeyFilter, signal?: AbortSignal): Promise<G9ChangeFeedEntry[]>;\r\n getChangeSequence(signal?: AbortSignal): Promise<number>;\r\n getChangeFeedFloor(signal?: AbortSignal): Promise<number>;\r\n getRejections(signal?: AbortSignal): Promise<G9SyncRejection[]>;\r\n retryRejected(localTable: string | null, key: string | null, signal?: AbortSignal): Promise<number>;\r\n /** Gives up the local change of rejected rows and takes the server's copy (LES-0070); run a forced reconcile after it. */\r\n revertRejected(localTable: string | null, key: string | null, signal?: AbortSignal): Promise<number>;\r\n markDirty(localTable: string, keys: readonly string[], signal?: AbortSignal): Promise<number>;\r\n adoptExistingRows(signal?: AbortSignal): Promise<number>;\r\n saveRunReport(report: G9SyncRunReport, keep: number, signal?: AbortSignal): Promise<void>;\r\n getRecentRunReports(count: number, signal?: AbortSignal): Promise<G9SyncRunReport[]>;\r\n getPhaseStatistics(signal?: AbortSignal): Promise<{ [key: string]: number }>;\r\n recordPhaseStatistics(samples: { [key: string]: number }, signal?: AbortSignal): Promise<void>;\r\n purgeDeletedFeed(keep: number, signal?: AbortSignal): Promise<number>;\r\n dispose(): Promise<void>;\r\n}\r\n"]}
1
+ {"version":3,"file":"storeTypes.js","sourceRoot":"","sources":["../../src/client/storeTypes.ts"],"names":[],"mappings":"AAkCA,8BAA8B;AAC9B,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,MAAM,EAAE,CAAC;IACT,cAAc,EAAE,CAAC;IACjB,MAAM,EAAE,CAAC;CACD,CAAC;AAyBX,iDAAiD;AACjD,MAAM,UAAU,iBAAiB,CAAC,MAAgC;IAChE,OAAO;QACL,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,UAAU,EAAE,MAAM,CAAC,UAAU,CAAC,MAAM;QACpC,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,cAAc,EAAE,MAAM,CAAC,cAAc;QACrC,QAAQ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,IAAI,KAAK,KAAK,IAAI,IAAI,OAAQ,KAAyC,CAAC,iBAAiB,KAAK,QAAQ,CAAC;AACzI,CAAC","sourcesContent":["// Twins of G9SyncData.Client/Storage/*.cs: the client store contract, its records, local commands, revocation rules\r\n// and apply diagnostics. The engine is store-agnostic; `@g9tm/syncdata/sqlite` is the implementation.\r\nimport type { G9EMoveOutPolicy } from '../abstractions/enums.js';\r\nimport type { G9Long } from '../abstractions/long.js';\r\nimport type { G9SyncParameters } from '../abstractions/parameters.js';\r\nimport type {\r\n G9DtBackfillRequest,\r\n G9DtCommand,\r\n G9DtHelloResult,\r\n G9DtNegotiatedTable,\r\n G9DtPullContinuation,\r\n G9DtPullPlan,\r\n G9DtPushResult,\r\n G9DtSnapshotFileRequest,\r\n G9DtSubscriptionDefinition,\r\n G9DtSubscriptionRef,\r\n G9DtSyncChunk,\r\n G9DtTableColumns,\r\n G9DtTableDigest,\r\n} from '../protocol/dtos.js';\r\nimport type { G9SyncClientModel } from './model.js';\r\n\r\n// ---------------------------------------------------------------- server state and subscriptions\r\n\r\n/** What the client last learned from the server (`G9CClientServerState`). */\r\nexport interface G9ClientServerState {\r\n epoch: string | null;\r\n lastHelloUtcMs: number | null;\r\n /** Server clock minus device clock, ms. */\r\n serverClockOffsetMs: number;\r\n tables: G9DtNegotiatedTable[];\r\n definitions: G9DtSubscriptionDefinition[];\r\n}\r\n\r\n/** `G9ESubscriptionState`. */\r\nexport const G9ESubscriptionState = {\r\n Active: 0,\r\n NeedsReconcile: 1,\r\n Failed: 2,\r\n} as const;\r\nexport type G9ESubscriptionState = (typeof G9ESubscriptionState)[keyof typeof G9ESubscriptionState];\r\n\r\n/** A local subscription (`G9CSyncSubscriptionRecord`). Times are epoch milliseconds UTC. */\r\nexport interface G9SyncSubscriptionRecord {\r\n key: string;\r\n name: string;\r\n parameters: G9SyncParameters;\r\n /** Membership slot (bit) for persistent subscriptions; the shared ephemeral slot otherwise. */\r\n slot: number;\r\n ephemeral: boolean;\r\n ttlMs: number | null;\r\n cursor: string | null;\r\n /** The move-out policy the server last announced; kept so it still applies once access is gone. */\r\n moveOutPolicy: G9EMoveOutPolicy | null;\r\n definitionHash: string | null;\r\n authHash: string | null;\r\n state: G9ESubscriptionState;\r\n lastErrorCode: string | null;\r\n createdUtcMs: number;\r\n lastSuccessUtcMs: number | null;\r\n lastReconcileUtcMs: number | null;\r\n lastAccessUtcMs: number | null;\r\n}\r\n\r\n/** `G9CSyncSubscriptionRecord.ToReference()`. */\r\nexport function toSubscriptionRef(record: G9SyncSubscriptionRecord): G9DtSubscriptionRef {\r\n return {\r\n name: record.name,\r\n parameters: record.parameters.values,\r\n cursor: record.cursor,\r\n definitionHash: record.definitionHash,\r\n authHash: record.authHash,\r\n };\r\n}\r\n\r\n/** A partial update of a subscription record; absent members are left unchanged (`G9CSubscriptionUpdate`). */\r\nexport interface G9SubscriptionUpdate {\r\n cursor?: string | null;\r\n definitionHash?: string | null;\r\n authHash?: string | null;\r\n state?: G9ESubscriptionState | null;\r\n errorCode?: string | null;\r\n clearError?: boolean;\r\n succeeded?: boolean;\r\n reconciled?: boolean;\r\n accessed?: boolean;\r\n clearCursor?: boolean;\r\n}\r\n\r\n// ---------------------------------------------------------------- push and pull\r\n\r\n/** A push batch built from dirty rows (`G9CPushBatch`). */\r\nexport interface G9PushBatch {\r\n batchId: number;\r\n /** Highest local change sequence included; rows changed after it stay dirty after the acknowledgement. */\r\n maxSequence: number;\r\n frames: Uint8Array[];\r\n tables: G9DtTableColumns[];\r\n rowCount: number;\r\n /** True when the byte budget ended the batch early: more pending rows follow. */\r\n truncated: boolean;\r\n /** Rows rejected on the device while building the batch (G9S-REJ-TOO-LARGE). */\r\n rejectedLocally: number;\r\n /** Commands carried by this batch, in device order. */\r\n commands: G9DtCommand[];\r\n}\r\n\r\n/** A pull being staged, persisted across restarts (`G9CStagedPull`). */\r\nexport interface G9StagedPull {\r\n runId: string;\r\n plan: G9DtPullPlan;\r\n createdUtcMs: number;\r\n backfills: G9DtBackfillRequest[];\r\n /** What the world looked like when the plan was made (ADR-0046); a run only resumes a stage whose generation matches. */\r\n generation: string | null;\r\n /** The cursor each planned subscription had when the plan was made, by subscription key (ADR-0060). */\r\n plannedFromCursors: { [subscriptionKey: string]: string | null };\r\n /** The device clock when the stage began, assigned by the store. */\r\n stageSequence: number;\r\n}\r\n\r\n/** One committed slice of a staged pull (`G9CApplySlice`). */\r\nexport interface G9ApplySlice {\r\n report: G9ApplyReport;\r\n rowsApplied: number;\r\n rowsAppliedTotal: number;\r\n rowsPlanned: number;\r\n isFinal: boolean;\r\n}\r\n\r\n/** `G9CResumePoint`. */\r\nexport interface G9ResumePoint {\r\n continuation: G9DtPullContinuation | null;\r\n stagedRows: number;\r\n stagedBytes: number;\r\n complete: boolean;\r\n}\r\n\r\n// ---------------------------------------------------------------- reports\r\n\r\n/** Why a table large enough for index deferral kept its indexes live. */\r\nexport const REASON_TABLE_NOT_EMPTY = 'table-not-empty';\r\nconst MAX_FOREIGN_TRIGGER_NAMES = 10;\r\n\r\n/** How an apply ran, as opposed to what it changed (`G9CApplyDiagnostics`, ADR-0058). */\r\n/** A file table copied record for record into an empty table with identical columns (the transfer optimisation). */\r\nexport const FILE_MODE_COPY = 'copy';\r\n/** A file table copied into an empty table by column name. */\r\nexport const FILE_MODE_COLUMNS = 'columns';\r\n/** A file table merged into a table that held rows or protected rows: changed rows only. */\r\nexport const FILE_MODE_MERGE = 'merge';\r\n/** A file table inserted into a table holding only OTHER rows (a second site's first load): every row is new, no per-row diff. */\r\nexport const FILE_MODE_APPEND = 'append';\r\n\r\nexport class G9ApplyDiagnostics {\r\n transactions = 0;\r\n transactionsWithTriggersSkipped = 0;\r\n readonly foreignTriggers: string[] = [];\r\n readonly deferredIndexes: { [table: string]: number } = {};\r\n readonly liveIndexReasons: { [table: string]: string } = {};\r\n readonly rowsByTable: { [table: string]: number } = {};\r\n readonly msByTable: { [table: string]: number } = {};\r\n indexRebuildMs = 0;\r\n elapsedMs = 0;\r\n /** Snapshot files copied in (ADR-0072). */\r\n snapshotFiles = 0;\r\n /** Rows that arrived through snapshot files. */\r\n fileRows = 0;\r\n /** Milliseconds spent copying snapshot files, metadata included. */\r\n fileCopyMs = 0;\r\n /** How each table came out of a snapshot file: `copy`, `columns` or `merge` (see FILE_MODE_*). */\r\n readonly fileTables: { [table: string]: string } = {};\r\n\r\n /** True when every transaction ran with trigger execution off, false when any ran with it on, null when nothing was applied. */\r\n get triggersSkipped(): boolean | null {\r\n return this.transactions === 0 ? null : this.transactionsWithTriggersSkipped === this.transactions;\r\n }\r\n\r\n get deferredIndexCount(): number {\r\n let total = 0;\r\n for (const key of Object.keys(this.deferredIndexes)) total += this.deferredIndexes[key] as number;\r\n return total;\r\n }\r\n\r\n merge(other: G9ApplyDiagnostics): void {\r\n this.transactions += other.transactions;\r\n this.transactionsWithTriggersSkipped += other.transactionsWithTriggersSkipped;\r\n this.indexRebuildMs += other.indexRebuildMs;\r\n this.elapsedMs += other.elapsedMs;\r\n this.snapshotFiles += other.snapshotFiles;\r\n this.fileRows += other.fileRows;\r\n this.fileCopyMs += other.fileCopyMs;\r\n for (const key of Object.keys(other.fileTables)) this.fileTables[key] = other.fileTables[key] as string;\r\n for (const name of other.foreignTriggers) {\r\n if (this.foreignTriggers.length >= MAX_FOREIGN_TRIGGER_NAMES) break;\r\n if (!this.foreignTriggers.some((n) => n.toLowerCase() === name.toLowerCase())) this.foreignTriggers.push(name);\r\n }\r\n addAll(this.deferredIndexes, other.deferredIndexes);\r\n for (const key of Object.keys(other.liveIndexReasons)) this.liveIndexReasons[key] = other.liveIndexReasons[key] as string;\r\n addAll(this.rowsByTable, other.rowsByTable);\r\n addAll(this.msByTable, other.msByTable);\r\n }\r\n\r\n /** One line for a log: what engaged, what did not and why, and the tables that took the time. */\r\n toString(): string {\r\n if (this.transactions === 0) return 'nothing applied';\r\n let text = `${this.transactions} transaction(s) in ${this.elapsedMs} ms; triggers `;\r\n text +=\r\n this.triggersSkipped === true\r\n ? 'skipped'\r\n : this.transactionsWithTriggersSkipped === 0\r\n ? 'LIVE'\r\n : `skipped in ${this.transactionsWithTriggersSkipped} of ${this.transactions}`;\r\n if (this.foreignTriggers.length > 0) text += ' (foreign: ' + this.foreignTriggers.join(', ') + ')';\r\n const deferred = Object.keys(this.deferredIndexes);\r\n if (deferred.length > 0) {\r\n text += `; ${this.deferredIndexCount} index(es) rebuilt after the load in ${this.indexRebuildMs} ms (` + deferred.map((t) => t + ':' + this.deferredIndexes[t]).join(', ') + ')';\r\n }\r\n const live = Object.keys(this.liveIndexReasons);\r\n if (live.length > 0) text += '; live indexes on ' + live.map((t) => t + ' (' + this.liveIndexReasons[t] + ')').join(', ');\r\n if (this.snapshotFiles > 0) {\r\n text +=\r\n `; ${this.snapshotFiles} snapshot file(s), ${this.fileRows} rows copied in ${this.fileCopyMs} ms (` +\r\n Object.keys(this.fileTables)\r\n .map((t) => t + ':' + this.fileTables[t])\r\n .join(', ') +\r\n ')';\r\n }\r\n const slowest = Object.keys(this.msByTable)\r\n .sort((a, b) => (this.msByTable[b] as number) - (this.msByTable[a] as number))\r\n .slice(0, 4);\r\n if (slowest.length > 0) {\r\n text +=\r\n '; ' +\r\n slowest\r\n .map((t) => {\r\n const ms = this.msByTable[t] as number;\r\n const rows = this.rowsByTable[t] ?? 0;\r\n const rate = ms > 0 ? Math.floor((rows * 1000) / ms) : rows;\r\n return `${t} ${rows} rows in ${ms} ms (${rate}/s)`;\r\n })\r\n .join(', ');\r\n }\r\n return text;\r\n }\r\n}\r\n\r\nfunction addAll(target: { [key: string]: number }, source: { [key: string]: number }): void {\r\n for (const key of Object.keys(source)) target[key] = (target[key] ?? 0) + (source[key] as number);\r\n}\r\n\r\n/** What an apply changed (`G9CApplyReport`). */\r\nexport class G9ApplyReport {\r\n upserts = 0;\r\n deletes = 0;\r\n moveOuts = 0;\r\n membershipAdded = 0;\r\n /** Rows skipped because they carry a pending local change. */\r\n skippedDirty = 0;\r\n accepted = 0;\r\n rejected = 0;\r\n conflicts = 0;\r\n /** Conflicts the device lost that were kept on it as rejections (LES-0072). */\r\n conflictsKept = 0;\r\n /** Conflicts the device lost on paper only: the server already held its values for every lost column (LES-0085). */\r\n conflictsSameValue = 0;\r\n commandsCompleted = 0;\r\n revokedDeleted = 0;\r\n revokedQuarantined = 0;\r\n revokedRetained = 0;\r\n /** Changed keys per local table (capped per table). */\r\n readonly changedKeys: { [localTable: string]: string[] } = {};\r\n /** Upserts whose row already held exactly the incoming values (ADR-0058). */\r\n unchangedRows = 0;\r\n readonly diagnostics = new G9ApplyDiagnostics();\r\n\r\n get total(): number {\r\n return this.upserts + this.deletes + this.moveOuts;\r\n }\r\n\r\n merge(other: G9ApplyReport): void {\r\n this.unchangedRows += other.unchangedRows;\r\n this.diagnostics.merge(other.diagnostics);\r\n this.upserts += other.upserts;\r\n this.deletes += other.deletes;\r\n this.moveOuts += other.moveOuts;\r\n this.membershipAdded += other.membershipAdded;\r\n this.skippedDirty += other.skippedDirty;\r\n this.accepted += other.accepted;\r\n this.rejected += other.rejected;\r\n this.conflicts += other.conflicts;\r\n this.conflictsKept += other.conflictsKept;\r\n this.conflictsSameValue += other.conflictsSameValue;\r\n this.commandsCompleted += other.commandsCompleted;\r\n this.revokedDeleted += other.revokedDeleted;\r\n this.revokedQuarantined += other.revokedQuarantined;\r\n this.revokedRetained += other.revokedRetained;\r\n for (const table of Object.keys(other.changedKeys)) {\r\n const list = this.changedKeys[table] ?? (this.changedKeys[table] = []);\r\n for (const key of other.changedKeys[table] as string[]) list.push(key);\r\n }\r\n }\r\n}\r\n\r\n/** A local row as seen by reconciliation (`G9CLocalRowEntry`). */\r\nexport interface G9LocalRowEntry {\r\n key: string;\r\n bucket: number;\r\n version: number;\r\n hash: G9Long;\r\n member: boolean;\r\n dirty: boolean;\r\n}\r\n\r\nexport interface G9PendingTable {\r\n localTable: string;\r\n upserts: number;\r\n deletes: number;\r\n rejected: number;\r\n}\r\n\r\nexport interface G9PendingSummary {\r\n totalRows: number;\r\n rejectedRows: number;\r\n /** Commands recorded on the device and not yet executed by the server. */\r\n pendingCommands: number;\r\n tables: G9PendingTable[];\r\n}\r\n\r\n/** One entry of the local change feed (`G9CChangeFeedEntry`). */\r\nexport interface G9ChangeFeedEntry {\r\n sequence: number;\r\n key: string;\r\n deleted: boolean;\r\n localPending: boolean;\r\n}\r\n\r\n/**\r\n * Narrows a change-feed read to the keys a query of the app's own tables selects (`G9CChangeFeedKeyFilter`): a projection of one\r\n * site no longer walks the entries of every other site. Deletions are always returned - their rows are gone, so no query can place\r\n * them. `keySql` is one SELECT of one column, embedded as `pk IN (...)`; parameters are bound by name (`$name`, `@name`, `:name`)\r\n * and `$g9t`, `$g9a`, `$g9l` belong to the read.\r\n */\r\nexport interface G9ChangeFeedKeyFilter {\r\n keySql: string;\r\n parameters?: { [name: string]: string | number | null };\r\n}\r\n\r\nconst RESERVED_FEED_PARAMETERS = ['$g9t', '$g9a', '$g9l'];\r\n\r\n/** Throws when the filter cannot be embedded safely (`G9CChangeFeedKeyFilter.Validate`). */\r\nexport function validateChangeFeedKeyFilter(filter: G9ChangeFeedKeyFilter): void {\r\n const sql = (filter.keySql ?? '').trim();\r\n if (sql.slice(0, 6).toUpperCase() !== 'SELECT' || sql.indexOf(';') >= 0) {\r\n throw new Error('A change-feed key filter is a single SELECT statement of one column.');\r\n }\r\n for (const name of Object.keys(filter.parameters ?? {})) {\r\n if (name.length < 2 || '$@:'.indexOf(name[0] as string) < 0) throw new Error(`Change-feed key filter parameter '${name}' must be named ($name, @name or :name).`);\r\n if (RESERVED_FEED_PARAMETERS.indexOf(name.toLowerCase()) >= 0) throw new Error(`Change-feed key filter parameter '${name}' is reserved by the read.`);\r\n }\r\n}\r\n\r\nexport interface G9SyncRejection {\r\n localTable: string;\r\n key: string;\r\n code: string;\r\n message: string | null;\r\n sqlState: string | null;\r\n constraint: string | null;\r\n column: string | null;\r\n details: string | null;\r\n atUtcMs: number;\r\n}\r\n\r\n/** A persisted summary of one run (`G9CSyncRunReport`); serialized with the .NET JSON names into g9_runs. */\r\nexport interface G9SyncRunReport {\r\n runId: string;\r\n startedUtcMs: number;\r\n durationMs: number;\r\n outcome: string;\r\n priority: string;\r\n errorCode: string | null;\r\n errorMessage: string | null;\r\n pushed: number;\r\n rejected: number;\r\n conflicts: number;\r\n downloaded: number;\r\n applied: number;\r\n downloadedBytes: number;\r\n subscriptions: string[];\r\n phaseMs: { [phase: string]: number };\r\n triggersSkipped: boolean | null;\r\n foreignTriggers: string[];\r\n applyTransactions: number;\r\n indexesDeferred: number;\r\n indexRebuildMs: number;\r\n liveIndexReasons: { [table: string]: string };\r\n unchangedRows: number;\r\n}\r\n\r\n// ---------------------------------------------------------------- local commands (ADR-0025)\r\n\r\n/** `G9ELocalCommandState`. */\r\nexport const G9ELocalCommandState = {\r\n Pending: 0,\r\n Ok: 1,\r\n Rejected: 2,\r\n Superseded: 3,\r\n} as const;\r\nexport type G9ELocalCommandState = (typeof G9ELocalCommandState)[keyof typeof G9ELocalCommandState];\r\n\r\n/** A command recorded on this device (`G9CLocalCommand`). */\r\nexport interface G9LocalCommand {\r\n commandId: string;\r\n sequence: number;\r\n name: string;\r\n version: number;\r\n payload: string;\r\n createdUtcMs: number;\r\n state: G9ELocalCommandState;\r\n code: string | null;\r\n message: string | null;\r\n result: string | null;\r\n completedUtcMs: number | null;\r\n}\r\n\r\n/** What to record (`G9CCommandRequest`). */\r\nexport interface G9CommandRequest {\r\n name: string;\r\n version?: number;\r\n /** JSON payload for the server's handler. */\r\n payload: string;\r\n}\r\n\r\n/** A value an app binds through {@link G9LocalCommandWriter}: the SQLite driver's value forms, plus booleans. */\r\nexport type G9LocalSqlArgument = null | number | string | boolean | ArrayBuffer | Uint8Array | { int64: string } | G9Long;\r\n\r\n/**\r\n * Writes a command's local effects in the transaction that records it (`IG9LocalCommandWriter`). Rows written here are\r\n * not uploaded as row changes; they are protected from pulls until the server's result arrives.\r\n */\r\nexport interface G9LocalCommandWriter {\r\n /** Executes SQL; parameters bind positionally as `$p0`, `$p1`, … */\r\n execute(sql: string, ...args: G9LocalSqlArgument[]): Promise<number>;\r\n scalar(sql: string, ...args: G9LocalSqlArgument[]): Promise<unknown>;\r\n}\r\n\r\n// ---------------------------------------------------------------- revocation (ADR-0026)\r\n\r\n/** `G9ERevocationReason`. */\r\nexport const G9ERevocationReason = {\r\n LeftScope: 0,\r\n Unsubscribed: 1,\r\n Expired: 2,\r\n AccessRevoked: 3,\r\n /**\r\n * A row the device adopted from its own table that no subscription holds and the server never confirmed, released by the\r\n * application (`G9SyncEngine.releaseUnclaimedRows`, 1.5.19).\r\n */\r\n Unclaimed: 4,\r\n} as const;\r\nexport type G9ERevocationReason = (typeof G9ERevocationReason)[keyof typeof G9ERevocationReason];\r\n\r\n/** `G9ERevocationDisposition`. */\r\nexport const G9ERevocationDisposition = {\r\n Delete: 0,\r\n MarkRevoked: 1,\r\n Quarantine: 2,\r\n Retain: 3,\r\n} as const;\r\nexport type G9ERevocationDisposition = (typeof G9ERevocationDisposition)[keyof typeof G9ERevocationDisposition];\r\n\r\n/** A row no subscription holds any more, as a revocation rule sees it (`G9CRevokedRow`). */\r\nexport interface G9RevokedRow {\r\n localTable: string;\r\n key: string;\r\n reason: G9ERevocationReason;\r\n subscriptionKey: string | null;\r\n hasPendingChanges: boolean;\r\n isRejected: boolean;\r\n /** Column values (key included) as stored locally; empty when the row no longer exists locally. */\r\n values: { [column: string]: unknown };\r\n}\r\n\r\n/** Lets a custom rule change the row before its disposition applies. */\r\nexport interface G9RevokedRowEditor {\r\n set(column: string, value: unknown): void;\r\n}\r\n\r\nexport interface G9RevocationRule {\r\n readonly name: string;\r\n readonly condition: (row: G9RevokedRow) => boolean;\r\n readonly decide: (row: G9RevokedRow, editor: G9RevokedRowEditor) => G9ERevocationDisposition;\r\n readonly retainWhile: ((row: G9RevokedRow) => boolean) | null;\r\n}\r\n\r\n/** Ordered revocation rules (`G9CRevocationPolicy`): the first matching rule decides. */\r\nexport class G9RevocationPolicy {\r\n readonly rules: readonly G9RevocationRule[];\r\n\r\n private constructor(rules: readonly G9RevocationRule[]) {\r\n this.rules = rules;\r\n }\r\n\r\n /** No rules: delete clean rows, quarantine rows with pending changes. */\r\n static readonly default = new G9RevocationPolicy([]);\r\n\r\n static create(configure: (builder: G9RevocationPolicyBuilder) => void): G9RevocationPolicy {\r\n const builder = new G9RevocationPolicyBuilder();\r\n configure(builder);\r\n return new G9RevocationPolicy(builder.rules.slice());\r\n }\r\n\r\n decide(row: G9RevokedRow, editor: G9RevokedRowEditor): { rule: G9RevocationRule | null; disposition: G9ERevocationDisposition } {\r\n for (const rule of this.rules) {\r\n if (rule.condition(row)) return { rule, disposition: rule.decide(row, editor) };\r\n }\r\n return { rule: null, disposition: row.hasPendingChanges ? G9ERevocationDisposition.Quarantine : G9ERevocationDisposition.Delete };\r\n }\r\n\r\n find(name: string): G9RevocationRule | null {\r\n for (const rule of this.rules) if (rule.name === name) return rule;\r\n return null;\r\n }\r\n}\r\n\r\nexport class G9RevocationPolicyBuilder {\r\n readonly rules: G9RevocationRule[] = [];\r\n\r\n when(name: string, condition: (row: G9RevokedRow) => boolean): G9RevocationActionBuilder {\r\n if (typeof name !== 'string' || name.trim() === '') throw new TypeError('A rule needs a name.');\r\n if (this.rules.some((r) => r.name === name)) throw new RangeError(`Revocation rule '${name}' is declared twice.`);\r\n return new G9RevocationActionBuilder(this, name, condition);\r\n }\r\n\r\n /** Rows of one local table. */\r\n forTable(name: string, localTable: string, condition?: (row: G9RevokedRow) => boolean): G9RevocationActionBuilder {\r\n const table = localTable.toLowerCase();\r\n return this.when(name, (row) => row.localTable.toLowerCase() === table && (condition ? condition(row) : true));\r\n }\r\n}\r\n\r\nexport class G9RevocationActionBuilder {\r\n private readonly _owner: G9RevocationPolicyBuilder;\r\n private readonly _name: string;\r\n private readonly _condition: (row: G9RevokedRow) => boolean;\r\n\r\n constructor(owner: G9RevocationPolicyBuilder, name: string, condition: (row: G9RevokedRow) => boolean) {\r\n this._owner = owner;\r\n this._name = name;\r\n this._condition = condition;\r\n }\r\n\r\n delete(): G9RevocationPolicyBuilder {\r\n return this._add(() => G9ERevocationDisposition.Delete, null);\r\n }\r\n\r\n markRevoked(): G9RevocationPolicyBuilder {\r\n return this._add(() => G9ERevocationDisposition.MarkRevoked, null);\r\n }\r\n\r\n quarantine(): G9RevocationPolicyBuilder {\r\n return this._add(() => G9ERevocationDisposition.Quarantine, null);\r\n }\r\n\r\n retainWhile(retainWhile: (row: G9RevokedRow) => boolean): G9RevocationPolicyBuilder {\r\n return this._add(() => G9ERevocationDisposition.Retain, retainWhile);\r\n }\r\n\r\n custom(decide: (row: G9RevokedRow, editor: G9RevokedRowEditor) => G9ERevocationDisposition): G9RevocationPolicyBuilder {\r\n return this._add(decide, null);\r\n }\r\n\r\n private _add(\r\n decide: (row: G9RevokedRow, editor: G9RevokedRowEditor) => G9ERevocationDisposition,\r\n retainWhile: ((row: G9RevokedRow) => boolean) | null,\r\n ): G9RevocationPolicyBuilder {\r\n this._owner.rules.push({ name: this._name, condition: this._condition, decide, retainWhile });\r\n return this._owner;\r\n }\r\n}\r\n\r\n/** A row in the holding area (`G9CQuarantinedRow`). */\r\nexport interface G9QuarantinedRow {\r\n localTable: string;\r\n key: string;\r\n reason: G9ERevocationReason;\r\n rule: string | null;\r\n hadPendingChanges: boolean;\r\n values: { [column: string]: unknown };\r\n atUtcMs: number;\r\n}\r\n\r\n/** A row kept in the app's table after revocation (`G9CRetainedRow`). */\r\nexport interface G9RetainedRow {\r\n localTable: string;\r\n key: string;\r\n disposition: G9ERevocationDisposition;\r\n reason: G9ERevocationReason;\r\n rule: string | null;\r\n atUtcMs: number;\r\n}\r\n\r\n// ---------------------------------------------------------------- failures\r\n\r\n/** What went wrong inside a client store, in terms an application can act on (`G9ELocalStoreFailure`). */\r\nexport const G9ELocalStoreFailure = {\r\n Other: 0,\r\n Corrupt: 1,\r\n DiskFull: 2,\r\n Busy: 3,\r\n} as const;\r\nexport type G9ELocalStoreFailure = (typeof G9ELocalStoreFailure)[keyof typeof G9ELocalStoreFailure];\r\n\r\n/** Implemented by a store's errors so the engine can give a run's failure a stable code (`IG9SyncLocalStoreFailure`). */\r\nexport interface G9SyncLocalStoreFailure {\r\n readonly localStoreFailure: G9ELocalStoreFailure;\r\n}\r\n\r\nexport function isLocalStoreFailure(error: unknown): error is G9SyncLocalStoreFailure {\r\n return typeof error === 'object' && error !== null && typeof (error as { localStoreFailure?: unknown }).localStoreFailure === 'number';\r\n}\r\n\r\n// ---------------------------------------------------------------- the store contract\r\n\r\n/**\r\n * The client storage provider (`IG9SyncClientStore`): local tables, change capture, subscription membership,\r\n * staging, apply and metadata. Every method takes an optional AbortSignal (the CancellationToken twin).\r\n */\r\nexport interface G9SyncClientStore {\r\n initialize(model: G9SyncClientModel, signal?: AbortSignal): Promise<void>;\r\n getClientId(signal?: AbortSignal): Promise<string>;\r\n getServerState(signal?: AbortSignal): Promise<G9ClientServerState>;\r\n /**\r\n * Stores the Hello answer. `localMidpointMs`: the local time the server's clock reading corresponds to - the midpoint of the round\r\n * trip (LES-0075); the offset is then exact up to the asymmetry of the two legs. Omitted: the time of this call.\r\n */\r\n saveHello(hello: G9DtHelloResult, signal?: AbortSignal, localMidpointMs?: number): Promise<void>;\r\n getPendingBackfills(signal?: AbortSignal): Promise<G9DtBackfillRequest[]>;\r\n\r\n getSubscriptions(signal?: AbortSignal): Promise<G9SyncSubscriptionRecord[]>;\r\n ensureSubscription(\r\n name: string,\r\n parameters: G9SyncParameters,\r\n ephemeral: boolean,\r\n ttlMs: number | null,\r\n adoptExistingRows: boolean,\r\n signal?: AbortSignal,\r\n ): Promise<G9SyncSubscriptionRecord>;\r\n removeSubscription(key: string, policy: G9EMoveOutPolicy, signal?: AbortSignal): Promise<void>;\r\n releaseSubscriptionRows(key: string, signal?: AbortSignal): Promise<G9ApplyReport>;\r\n updateSubscription(key: string, update: G9SubscriptionUpdate, signal?: AbortSignal): Promise<void>;\r\n collectExpiredEphemeral(utcNowMs: number, signal?: AbortSignal): Promise<number>;\r\n\r\n buildPushBatch(tables: readonly G9DtNegotiatedTable[], maxRows: number, maxBytes: number, signal?: AbortSignal): Promise<G9PushBatch | null>;\r\n forgetUploadedRows(localTable: string, keys: readonly string[] | null, signal?: AbortSignal): Promise<number>;\r\n applyPushResult(batch: G9PushBatch, result: G9DtPushResult, signal?: AbortSignal): Promise<G9ApplyReport>;\r\n\r\n getStagedPull(signal?: AbortSignal): Promise<G9StagedPull | null>;\r\n /** The newest staged pull planned under exactly this generation, or null (ADR-0060). */\r\n getStagedPullForGeneration(generation: string, signal?: AbortSignal): Promise<G9StagedPull | null>;\r\n beginStagedPull(pull: G9StagedPull, signal?: AbortSignal): Promise<void>;\r\n pruneStagedPulls(olderThanUtcMs: number, maxBytes: number, keepGeneration: string | null, signal?: AbortSignal): Promise<number>;\r\n discardAllStagedPulls(signal?: AbortSignal): Promise<number>;\r\n stageChunk(runId: string, chunk: G9DtSyncChunk, signal?: AbortSignal): Promise<void>;\r\n /**\r\n * The store's offer to receive large first downloads as SQLite snapshot files (ADR-0072), or null for rows only. A store that\r\n * makes an offer stages file segments (`chunk.file`) in `stageChunk` and copies the files in `applyStagedPull`.\r\n */\r\n describeSnapshotFiles?(negotiated: readonly G9DtNegotiatedTable[]): G9DtSnapshotFileRequest | null;\r\n getResumePoint(runId: string, signal?: AbortSignal): Promise<G9ResumePoint>;\r\n applyStagedPull(\r\n runId: string,\r\n rowsApplied: ((rows: number) => void) | null,\r\n slices: ((slice: G9ApplySlice) => void) | null,\r\n signal?: AbortSignal,\r\n ): Promise<G9ApplyReport>;\r\n discardStagedPull(runId: string, signal?: AbortSignal): Promise<void>;\r\n\r\n computeDigest(subscriptionKey: string, table: G9DtNegotiatedTable, signal?: AbortSignal): Promise<G9DtTableDigest>;\r\n readLocalEntries(\r\n subscriptionKey: string,\r\n table: G9DtNegotiatedTable,\r\n buckets: ReadonlySet<number>,\r\n serverKeys: ReadonlySet<string>,\r\n signal?: AbortSignal,\r\n ): Promise<G9LocalRowEntry[]>;\r\n applyReconcile(\r\n subscriptionKey: string,\r\n table: G9DtNegotiatedTable,\r\n fetchedFrames: readonly Uint8Array[],\r\n addMembership: readonly string[],\r\n moveOut: readonly string[],\r\n policy: G9EMoveOutPolicy,\r\n signal?: AbortSignal,\r\n ): Promise<G9ApplyReport>;\r\n\r\n getPendingSummary(signal?: AbortSignal): Promise<G9PendingSummary>;\r\n enqueueCommand(\r\n request: G9CommandRequest,\r\n applyLocally: ((writer: G9LocalCommandWriter, signal?: AbortSignal) => Promise<void>) | null,\r\n signal?: AbortSignal,\r\n ): Promise<G9LocalCommand>;\r\n getQuarantined(signal?: AbortSignal): Promise<G9QuarantinedRow[]>;\r\n restoreQuarantined(localTable: string, key: string, signal?: AbortSignal): Promise<number>;\r\n discardQuarantined(localTable: string | null, key: string | null, signal?: AbortSignal): Promise<number>;\r\n getRetained(signal?: AbortSignal): Promise<G9RetainedRow[]>;\r\n reevaluateRetained(signal?: AbortSignal): Promise<number>;\r\n getCommands(state: G9ELocalCommandState | null, limit: number, signal?: AbortSignal): Promise<G9LocalCommand[]>;\r\n readChangeFeed(localTable: string, afterSequence: number, limit: number, signal?: AbortSignal): Promise<G9ChangeFeedEntry[]>;\r\n /** The feed narrowed to the keys `keyFilter` selects, plus every deletion; fewer than `limit` entries means the read is complete. */\r\n readChangeFeedFiltered(localTable: string, afterSequence: number, limit: number, keyFilter: G9ChangeFeedKeyFilter, signal?: AbortSignal): Promise<G9ChangeFeedEntry[]>;\r\n getChangeSequence(signal?: AbortSignal): Promise<number>;\r\n getChangeFeedFloor(signal?: AbortSignal): Promise<number>;\r\n getRejections(signal?: AbortSignal): Promise<G9SyncRejection[]>;\r\n retryRejected(localTable: string | null, key: string | null, signal?: AbortSignal): Promise<number>;\r\n /** Gives up the local change of rejected rows and takes the server's copy (LES-0070); run a forced reconcile after it. */\r\n revertRejected(localTable: string | null, key: string | null, signal?: AbortSignal): Promise<number>;\r\n markDirty(localTable: string, keys: readonly string[], signal?: AbortSignal): Promise<number>;\r\n /** `RefetchRowsAsync` (1.5.19): clean held rows get `server_ver = -1` and their subscriptions NeedsReconcile. Returns the rows marked. */\r\n refetchRows(localTable: string, keys: readonly string[] | null, signal?: AbortSignal): Promise<number>;\r\n /** `ReleaseUnclaimedRowsAsync` (1.5.19): disposes adopted rows nothing holds and the server never claimed, capture off. */\r\n releaseUnclaimedRows(localTable: string, keys: readonly string[] | null, includePending: boolean, signal?: AbortSignal): Promise<G9ApplyReport>;\r\n adoptExistingRows(signal?: AbortSignal): Promise<number>;\r\n saveRunReport(report: G9SyncRunReport, keep: number, signal?: AbortSignal): Promise<void>;\r\n getRecentRunReports(count: number, signal?: AbortSignal): Promise<G9SyncRunReport[]>;\r\n getPhaseStatistics(signal?: AbortSignal): Promise<{ [key: string]: number }>;\r\n recordPhaseStatistics(samples: { [key: string]: number }, signal?: AbortSignal): Promise<void>;\r\n purgeDeletedFeed(keep: number, signal?: AbortSignal): Promise<number>;\r\n dispose(): Promise<void>;\r\n}\r\n"]}
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /** The package version; equal to the .NET packages' (G9SyncDataVersion) — one release, both sides. */
2
- export declare const VERSION = "1.5.18";
2
+ export declare const VERSION = "1.5.20";
3
3
  export { G9EConflictPolicy, G9EMoveOutPolicy, G9ESyncColumnType, G9ESyncDirection, columnTypeName, isColumnType } from './abstractions/enums.js';
4
4
  export { G9SyncErrorCodes, G9SyncException, isRetryableCode, isSyncException, type G9SyncExceptionOptions } from './abstractions/errors.js';
5
5
  export { G9Long, parseJson, stringifyJson } from './abstractions/long.js';
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@
3
3
  // doubles `@g9tm/syncdata/testing`, the pure-JavaScript Brotli decoder `@g9tm/syncdata/brotli-js`; Lynx wiring is the
4
4
  // separate package `@g9tm/syncdata-lynx`. Every public type keeps its .NET name without the G9C prefix (PARITY.md).
5
5
  /** The package version; equal to the .NET packages' (G9SyncDataVersion) — one release, both sides. */
6
- export const VERSION = '1.5.18';
6
+ export const VERSION = '1.5.20';
7
7
  // abstractions
8
8
  export { G9EConflictPolicy, G9EMoveOutPolicy, G9ESyncColumnType, G9ESyncDirection, columnTypeName, isColumnType } from './abstractions/enums.js';
9
9
  export { G9SyncErrorCodes, G9SyncException, isRetryableCode, isSyncException } from './abstractions/errors.js';
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,wHAAwH;AACxH,uHAAuH;AACvH,sHAAsH;AACtH,oHAAoH;AAEpH,sGAAsG;AACtG,MAAM,CAAC,MAAM,OAAO,GAAG,QAAQ,CAAC;AAEhC,eAAe;AACf,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACjJ,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,eAAe,EAAE,eAAe,EAA+B,MAAM,0BAA0B,CAAC;AAC5I,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAC1E,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AACvG,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAElF,WAAW;AACX,cAAc,oBAAoB,CAAC;AACnC,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,qBAAqB,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAC5G,OAAO,EACL,UAAU,EACV,UAAU,EACV,oBAAoB,EACpB,UAAU,EACV,mBAAmB,EACnB,oBAAoB,EACpB,gBAA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W,EAAE,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC","sourcesContent":["// @g9tm/syncdata — the TypeScript twin of the G9SyncData .NET client (abstractions, protocol, engine). The SQLite store\r\n// is `@g9tm/syncdata/sqlite`, the SignalR transport `@g9tm/syncdata/signalr`, Node helpers `@g9tm/syncdata/node`, test\r\n// doubles `@g9tm/syncdata/testing`, the pure-JavaScript Brotli decoder `@g9tm/syncdata/brotli-js`; Lynx wiring is the\r\n// separate package `@g9tm/syncdata-lynx`. Every public type keeps its .NET name without the G9C prefix (PARITY.md).\r\n\r\n/** The package version; equal to the .NET packages' (G9SyncDataVersion) — one release, both sides. */\r\nexport const VERSION = '1.5.18';\r\n\r\n// abstractions\r\nexport { G9EConflictPolicy, G9EMoveOutPolicy, G9ESyncColumnType, G9ESyncDirection, columnTypeName, isColumnType } from './abstractions/enums.js';\r\nexport { G9SyncErrorCodes, G9SyncException, isRetryableCode, isSyncException, type G9SyncExceptionOptions } from './abstractions/errors.js';\r\nexport { G9Long, parseJson, stringifyJson } from './abstractions/long.js';\r\nexport { EMPTY_GUID, guidToN, newGuid, normalizeGuid, tryNormalizeGuid } from './abstractions/guid.js';\r\nexport { G9SyncKey } from './abstractions/key.js';\r\nexport { G9SyncDigest } from './abstractions/digest.js';\r\nexport { G9SyncParameters, escapeDataString } from './abstractions/parameters.js';\r\n\r\n// protocol\r\nexport * from './protocol/dtos.js';\r\nexport { G9SyncHubErrors, G9SyncProtocol, negotiateFrameVersion, tableGroup } from './protocol/protocol.js';\r\nexport {\r\n bytesField,\r\n dateTimeMs,\r\n fromMessagePackNames,\r\n G9WireGuid,\r\n GUID_EXTENSION_TYPE,\r\n readChangesAvailable,\r\n readContinuation,\r\n readHelloResult,\r\n readPullPlan,\r\n readPushResult,\r\n readReconcileSummary,\r\n readSyncChunk,\r\n toMessagePackNames,\r\n type G9WireFormat,\r\n} from './protocol/wire.js';\r\nexport { G9ECompression, G9EPushRowOp, G9ERowBatchOp, G9RowBatchFormat, G9RowBatchFormatError } from './protocol/rowBatch/format.js';\r\nexport { G9RowBatchWriter, type G9DateTimeOffsetValue, type G9DateTimeValue, type G9FrameCompressor } from './protocol/rowBatch/writer.js';\r\nexport {\r\n G9RowBatchReader,\r\n getDefaultFrameDecompressor,\r\n openRowBatch,\r\n openRowBatchSync,\r\n readFrameHeader,\r\n setDefaultFrameDecompressor,\r\n type G9FrameDecompressor,\r\n type G9FrameHeader,\r\n type G9OpenRowBatchOptions,\r\n} from './protocol/rowBatch/reader.js';\r\nexport { decimalToDouble, formatDecimal, formatDouble, parseDecimal, type DecimalParts } from './internal/dotnetFormat.js';\r\n\r\n// client\r\nexport { G9SyncClientModel, G9SyncClientModelBuilder, G9SyncClientTable, G9SyncClientTableBuilder, type G9SyncClientColumn, type G9SyncClientIndex } from './client/model.js';\r\nexport * from './client/storeTypes.js';\r\nexport type { G9SyncTransport } from './client/transport.js';\r\nexport { G9ESyncPhase, G9SyncProgressTracker, phaseName, type G9DtSyncProgress } from './client/progress.js';\r\nexport {\r\n G9ESyncOutcome,\r\n G9ESyncPriority,\r\n G9SyncPostStep,\r\n G9SyncRun,\r\n describeModelProblem,\r\n isTransientError,\r\n normalizeError,\r\n outcomeName,\r\n priorityName,\r\n resolveEngineOptions,\r\n type G9RowsAppliedEvent,\r\n type G9SubscriptionOptions,\r\n type G9SyncEngineOptions,\r\n type G9SyncHealth,\r\n type G9SyncHostHooks,\r\n type G9SyncLogger,\r\n type G9SyncLogLevel,\r\n type G9SyncModelProblem,\r\n type G9SyncPostStepContext,\r\n type G9SyncRequest,\r\n type G9SyncRunResult,\r\n} from './client/runs.js';\r\nexport { G9SyncEngine, stageGeneration } from './client/engine.js';\r\n\r\n// helpers the Lynx package and tests share\r\nexport { base64ToBytes, bytesToBase64 } from './internal/base64.js';\r\nexport { utf8Decode, utf8Encode } from './internal/utf8.js';\r\nexport { md5 } from './internal/md5.js';\r\nexport { sha256, toHex } from './internal/sha256.js';\r\nexport { cancellationError, createAbortController, delay, linkSignals, onAbort, yieldToEventLoop } from './internal/abort.js';\r\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,wHAAwH;AACxH,uHAAuH;AACvH,sHAAsH;AACtH,oHAAoH;AAEpH,sGAAsG;AACtG,MAAM,CAAC,MAAM,OAAO,GAAG,QAAQ,CAAC;AAEhC,eAAe;AACf,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACjJ,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,eAAe,EAAE,eAAe,EAA+B,MAAM,0BAA0B,CAAC;AAC5I,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAC1E,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AACvG,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAElF,WAAW;AACX,cAAc,oBAAoB,CAAC;AACnC,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,qBAAqB,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAC5G,OAAO,EACL,UAAU,EACV,UAAU,EACV,oBAAoB,EACpB,UAAU,EACV,mBAAmB,EACnB,oBAAoB,EACpB,gBAAgB,EAChB,eAAe,EACf,YAAY,EACZ,cAAc,EACd,oBAAoB,EACpB,aAAa,EACb,kBAAkB,GAEnB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,aAAa,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AACrI,OAAO,EAAE,gBAAgB,EAA4E,MAAM,+BAA+B,CAAC;AAC3I,OAAO,EACL,gBAAgB,EAChB,2BAA2B,EAC3B,YAAY,EACZ,gBAAgB,EAChB,eAAe,EACf,2BAA2B,GAI5B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,YAAY,EAAE,YAAY,EAAqB,MAAM,4BAA4B,CAAC;AAE3H,SAAS;AACT,OAAO,EAAE,iBAAiB,EAAE,wBAAwB,EAAE,iBAAiB,EAAE,wBAAwB,EAAmD,MAAM,mBAAmB,CAAC;AAC9K,cAAc,wBAAwB,CAAC;AAEvC,OAAO,EAAE,YAAY,EAAE,qBAAqB,EAAE,SAAS,EAAyB,MAAM,sBAAsB,CAAC;AAC7G,OAAO,EACL,cAAc,EACd,eAAe,EACf,cAAc,EACd,SAAS,EACT,oBAAoB,EACpB,gBAAgB,EAChB,cAAc,EACd,WAAW,EACX,YAAY,EACZ,oBAAoB,GAYrB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAEnE,2CAA2C;AAC3C,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACpE,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AACxC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC","sourcesContent":["// @g9tm/syncdata — the TypeScript twin of the G9SyncData .NET client (abstractions, protocol, engine). The SQLite store\r\n// is `@g9tm/syncdata/sqlite`, the SignalR transport `@g9tm/syncdata/signalr`, Node helpers `@g9tm/syncdata/node`, test\r\n// doubles `@g9tm/syncdata/testing`, the pure-JavaScript Brotli decoder `@g9tm/syncdata/brotli-js`; Lynx wiring is the\r\n// separate package `@g9tm/syncdata-lynx`. Every public type keeps its .NET name without the G9C prefix (PARITY.md).\r\n\r\n/** The package version; equal to the .NET packages' (G9SyncDataVersion) — one release, both sides. */\r\nexport const VERSION = '1.5.20';\r\n\r\n// abstractions\r\nexport { G9EConflictPolicy, G9EMoveOutPolicy, G9ESyncColumnType, G9ESyncDirection, columnTypeName, isColumnType } from './abstractions/enums.js';\r\nexport { G9SyncErrorCodes, G9SyncException, isRetryableCode, isSyncException, type G9SyncExceptionOptions } from './abstractions/errors.js';\r\nexport { G9Long, parseJson, stringifyJson } from './abstractions/long.js';\r\nexport { EMPTY_GUID, guidToN, newGuid, normalizeGuid, tryNormalizeGuid } from './abstractions/guid.js';\r\nexport { G9SyncKey } from './abstractions/key.js';\r\nexport { G9SyncDigest } from './abstractions/digest.js';\r\nexport { G9SyncParameters, escapeDataString } from './abstractions/parameters.js';\r\n\r\n// protocol\r\nexport * from './protocol/dtos.js';\r\nexport { G9SyncHubErrors, G9SyncProtocol, negotiateFrameVersion, tableGroup } from './protocol/protocol.js';\r\nexport {\r\n bytesField,\r\n dateTimeMs,\r\n fromMessagePackNames,\r\n G9WireGuid,\r\n GUID_EXTENSION_TYPE,\r\n readChangesAvailable,\r\n readContinuation,\r\n readHelloResult,\r\n readPullPlan,\r\n readPushResult,\r\n readReconcileSummary,\r\n readSyncChunk,\r\n toMessagePackNames,\r\n type G9WireFormat,\r\n} from './protocol/wire.js';\r\nexport { G9ECompression, G9EPushRowOp, G9ERowBatchOp, G9RowBatchFormat, G9RowBatchFormatError } from './protocol/rowBatch/format.js';\r\nexport { G9RowBatchWriter, type G9DateTimeOffsetValue, type G9DateTimeValue, type G9FrameCompressor } from './protocol/rowBatch/writer.js';\r\nexport {\r\n G9RowBatchReader,\r\n getDefaultFrameDecompressor,\r\n openRowBatch,\r\n openRowBatchSync,\r\n readFrameHeader,\r\n setDefaultFrameDecompressor,\r\n type G9FrameDecompressor,\r\n type G9FrameHeader,\r\n type G9OpenRowBatchOptions,\r\n} from './protocol/rowBatch/reader.js';\r\nexport { decimalToDouble, formatDecimal, formatDouble, parseDecimal, type DecimalParts } from './internal/dotnetFormat.js';\r\n\r\n// client\r\nexport { G9SyncClientModel, G9SyncClientModelBuilder, G9SyncClientTable, G9SyncClientTableBuilder, type G9SyncClientColumn, type G9SyncClientIndex } from './client/model.js';\r\nexport * from './client/storeTypes.js';\r\nexport type { G9SyncTransport } from './client/transport.js';\r\nexport { G9ESyncPhase, G9SyncProgressTracker, phaseName, type G9DtSyncProgress } from './client/progress.js';\r\nexport {\r\n G9ESyncOutcome,\r\n G9ESyncPriority,\r\n G9SyncPostStep,\r\n G9SyncRun,\r\n describeModelProblem,\r\n isTransientError,\r\n normalizeError,\r\n outcomeName,\r\n priorityName,\r\n resolveEngineOptions,\r\n type G9RowsAppliedEvent,\r\n type G9SubscriptionOptions,\r\n type G9SyncEngineOptions,\r\n type G9SyncHealth,\r\n type G9SyncHostHooks,\r\n type G9SyncLogger,\r\n type G9SyncLogLevel,\r\n type G9SyncModelProblem,\r\n type G9SyncPostStepContext,\r\n type G9SyncRequest,\r\n type G9SyncRunResult,\r\n} from './client/runs.js';\r\nexport { G9SyncEngine, stageGeneration } from './client/engine.js';\r\n\r\n// helpers the Lynx package and tests share\r\nexport { base64ToBytes, bytesToBase64 } from './internal/base64.js';\r\nexport { utf8Decode, utf8Encode } from './internal/utf8.js';\r\nexport { md5 } from './internal/md5.js';\r\nexport { sha256, toHex } from './internal/sha256.js';\r\nexport { cancellationError, createAbortController, delay, linkSignals, onAbort, yieldToEventLoop } from './internal/abort.js';\r\n"]}
@@ -26,6 +26,20 @@ export declare function disposeReleasedRows(store: StoreInternals, connection: G
26
26
  * NeedsReconcile, so their next sync of any kind does it (offline now is fine). A library write: capture is silent, nothing uploads.
27
27
  */
28
28
  export declare function revertRejected(store: StoreInternals, localTable: string | null, key: string | null): Promise<number>;
29
+ /**
30
+ * `RefetchRowsAsync` (1.5.19): the next sync fetches these rows again and overwrites their values. Every CLEAN row a subscription
31
+ * holds (no pending change, no rejection, not deleted) gets `server_ver = -1` - a version no server issues, so the reconcile's
32
+ * digest differs and the apply writes the server's values and real version - and the subscriptions holding them become
33
+ * NeedsReconcile. Metadata only: the app's table and the change feed are untouched, nothing uploads.
34
+ */
35
+ export declare function refetchRows(store: StoreInternals, localTable: string, keys: readonly string[] | null): Promise<number>;
36
+ /**
37
+ * `ReleaseUnclaimedRowsAsync` (1.5.19): disposes rows of one table that no subscription holds and the server never claimed
38
+ * (`server_ver = 0`), not decided before (revoked, quarantined), not an ephemeral member and not in a pending command - reason
39
+ * Unclaimed, capture off, nothing uploads. A pending change (and a refused one) only with `includePending`: then the revocation
40
+ * policy decides it like any released row (the default quarantines it, the refusal with it).
41
+ */
42
+ export declare function releaseUnclaimedRows(store: StoreInternals, localTable: string, keys: readonly string[] | null, includePending: boolean): Promise<G9ApplyReport>;
29
43
  /** `RemoveLocalRow`: the row leaves the app's table; its metadata becomes a tombstone at the clock's next value. */
30
44
  export declare function removeLocalRow(connection: G9SqliteConnection, table: LocalTable, key: string): Promise<void>;
31
45
  export declare function getQuarantined(store: StoreInternals): Promise<G9QuarantinedRow[]>;
@@ -6,6 +6,7 @@
6
6
  // clock afterwards (unconditionally, like the .NET store's `++sequence`).
7
7
  import { G9ESyncColumnType } from '../abstractions/enums.js';
8
8
  import { G9Long } from '../abstractions/long.js';
9
+ import { G9SyncKey } from '../abstractions/key.js';
9
10
  import { G9ApplyReport, G9ERevocationDisposition, G9ERevocationReason, G9ESubscriptionState, } from '../client/storeTypes.js';
10
11
  import { asLong, asNumber, asOptionalString, asString, G9StatementBatch, statementsOf } from './connection.js';
11
12
  import { byTid, deserializeValues, getLocal, keyValue, nowMs, readLocalValues, serializeValues } from './internals.js';
@@ -363,6 +364,81 @@ export async function revertRejected(store, localTable, key) {
363
364
  return rows.length;
364
365
  }));
365
366
  }
367
+ /** Canonical keys of `keys` (a GUID key in any spelling finds its row), distinct, as JSON pages of 5000; `[null]` = the whole table. */
368
+ function keyPages(table, keys) {
369
+ if (keys === null)
370
+ return [null];
371
+ const canonical = [...new Set(keys.map((k) => { var _a; return (_a = G9SyncKey.tryNormalize(table.model.keyType, k)) !== null && _a !== void 0 ? _a : k; }))];
372
+ const pages = [];
373
+ for (let i = 0; i < canonical.length; i += 5000)
374
+ pages.push(JSON.stringify(canonical.slice(i, i + 5000)));
375
+ return pages;
376
+ }
377
+ /**
378
+ * `RefetchRowsAsync` (1.5.19): the next sync fetches these rows again and overwrites their values. Every CLEAN row a subscription
379
+ * holds (no pending change, no rejection, not deleted) gets `server_ver = -1` - a version no server issues, so the reconcile's
380
+ * digest differs and the apply writes the server's values and real version - and the subscriptions holding them become
381
+ * NeedsReconcile. Metadata only: the app's table and the change feed are untouched, nothing uploads.
382
+ */
383
+ export async function refetchRows(store, localTable, keys) {
384
+ store.ensureInitialized();
385
+ const table = getLocal(store, localTable);
386
+ const pages = keyPages(table, keys);
387
+ return store.writeLock.run(() => store.writer().transaction('immediate', async () => {
388
+ const connection = store.writer();
389
+ const clean = 'tid = $t AND dirty = 0 AND rejected = 0 AND deleted = 0 AND subs <> 0';
390
+ let marked = 0;
391
+ for (const page of pages) {
392
+ const where = clean + (page === null ? '' : ' AND pk IN (SELECT value FROM json_each($keys))');
393
+ const params = page === null ? { $t: table.tid } : { $t: table.tid, $keys: page };
394
+ // The holders first: every subscription with its bit in one of these rows.
395
+ await connection.exec(`UPDATE g9_subscriptions SET state = $needs WHERE EXISTS (SELECT 1 FROM g9_rows WHERE ${where} AND ((subs >> g9_subscriptions.slot) & 1) = 1)`, { ...params, $needs: G9ESubscriptionState.NeedsReconcile });
396
+ marked += await connection.exec('UPDATE g9_rows SET server_ver = -1 WHERE ' + where, params);
397
+ }
398
+ return marked;
399
+ }));
400
+ }
401
+ /**
402
+ * `ReleaseUnclaimedRowsAsync` (1.5.19): disposes rows of one table that no subscription holds and the server never claimed
403
+ * (`server_ver = 0`), not decided before (revoked, quarantined), not an ephemeral member and not in a pending command - reason
404
+ * Unclaimed, capture off, nothing uploads. A pending change (and a refused one) only with `includePending`: then the revocation
405
+ * policy decides it like any released row (the default quarantines it, the refusal with it).
406
+ */
407
+ export async function releaseUnclaimedRows(store, localTable, keys, includePending) {
408
+ store.ensureInitialized();
409
+ const table = getLocal(store, localTable);
410
+ const pages = keyPages(table, keys);
411
+ const report = new G9ApplyReport();
412
+ const where = 'r.tid = $t AND r.subs = 0 AND r.deleted = 0 AND r.server_ver = 0' +
413
+ (includePending ? '' : ' AND r.dirty = 0 AND r.rejected = 0') +
414
+ ' AND NOT EXISTS (SELECT 1 FROM g9_revoked v WHERE v.tid = r.tid AND v.pk = r.pk)' +
415
+ ' AND NOT EXISTS (SELECT 1 FROM g9_quarantine q WHERE q.tid = r.tid AND q.pk = r.pk)' +
416
+ ' AND NOT EXISTS (SELECT 1 FROM g9_ephemeral_rows e WHERE e.tid = r.tid AND e.pk = r.pk)' +
417
+ ' AND NOT EXISTS (SELECT 1 FROM g9_command_rows cr JOIN g9_commands c ON c.command_id = cr.command_id WHERE c.state = 0 AND cr.tid = r.tid AND cr.pk = r.pk)';
418
+ await store.writeLock.run(() => store.writer().transaction('immediate', async () => {
419
+ const connection = store.writer();
420
+ // Every page is read BEFORE anything is disposed (.NET collects the whole list first), each in key order.
421
+ await connection.exec('DROP TABLE IF EXISTS temp.g9_unclaimed; CREATE TEMP TABLE g9_unclaimed (n INTEGER PRIMARY KEY, tid INTEGER NOT NULL, pk TEXT NOT NULL)');
422
+ for (const page of pages) {
423
+ const byKeys = page === null ? '' : ' AND r.pk IN (SELECT value FROM json_each($keys))';
424
+ await connection.exec(`INSERT INTO temp.g9_unclaimed (tid, pk) SELECT r.tid, r.pk FROM g9_rows r WHERE ${where}${byKeys} ORDER BY r.pk`, page === null ? { $t: table.tid } : { $t: table.tid, $keys: page });
425
+ }
426
+ if (asNumber(await connection.scalar('SELECT count(*) FROM temp.g9_unclaimed')) > 0) {
427
+ // Capture OFF: a release is local housekeeping and must never reach the server as a delete.
428
+ await connection.exec('UPDATE g9_ctx SET applying = 1 WHERE id = 1');
429
+ const max = store.options.maxChangedKeysPerTable;
430
+ await disposeReleasedRows(store, connection, 'SELECT tid, pk FROM temp.g9_unclaimed ORDER BY n', {}, G9ERevocationReason.Unclaimed, null, report, (_tid, key) => {
431
+ var _a;
432
+ const changed = (_a = report.changedKeys[table.model.localName]) !== null && _a !== void 0 ? _a : (report.changedKeys[table.model.localName] = []);
433
+ if (changed.length < max)
434
+ changed.push(key);
435
+ });
436
+ await connection.exec('UPDATE g9_ctx SET applying = 0 WHERE id = 1');
437
+ }
438
+ await connection.exec('DROP TABLE temp.g9_unclaimed');
439
+ }));
440
+ return report;
441
+ }
366
442
  /** `RemoveLocalRow`: the row leaves the app's table; its metadata becomes a tombstone at the clock's next value. */
367
443
  export async function removeLocalRow(connection, table, key) {
368
444
  for (const statement of removeLocalRowStatements(table, key, NEXT_SEQ, {}))