@rdlabo/ionic-angular-kit 21.6.9 → 21.6.11

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.
@@ -1015,6 +1015,9 @@ class IonicOfflineRepository {
1015
1015
  async getReplicaRows(scope, sourceKey) {
1016
1016
  return this.#withCommittedRead(() => this.#readReplicaRows(scope, sourceKey));
1017
1017
  }
1018
+ async getReplicaRowsIncludingPendingDelete(scope, sourceKey) {
1019
+ return this.#withCommittedRead(() => this.#readReplicaRows(scope, sourceKey, true));
1020
+ }
1018
1021
  async getReplicaRowByRemoteId(scope, sourceKey, remoteId) {
1019
1022
  if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
1020
1023
  return null;
@@ -1061,14 +1064,14 @@ class IonicOfflineRepository {
1061
1064
  return null;
1062
1065
  return this.#rowForScope(row, schema, scope);
1063
1066
  }
1064
- async #readReplicaRows(scope, sourceKey) {
1067
+ async #readReplicaRows(scope, sourceKey, includePendingDelete = false) {
1065
1068
  const schema = this.#resolveReplicaEntitySchema(sourceKey);
1066
1069
  const rows = await this.#readRowPartition(scope, sourceKey, schema);
1067
1070
  return Object.values(rows)
1068
1071
  .filter((row) => {
1069
1072
  if (row.sourceKey !== sourceKey || row.userId !== scope.userId)
1070
1073
  return false;
1071
- if ((row.visibility ?? 'present') === 'pending_delete')
1074
+ if (!includePendingDelete && (row.visibility ?? 'present') === 'pending_delete')
1072
1075
  return false;
1073
1076
  return schema.scope === 'partition' ? row.scopeId === scope.scopeId : true;
1074
1077
  })
@@ -1121,6 +1124,7 @@ class IonicOfflineRepository {
1121
1124
  getReplicaRow: (scope, sourceKey, identity) => this.#readReplicaRow(scope, sourceKey, identity, false),
1122
1125
  getReplicaRowIncludingPendingDelete: (scope, sourceKey, identity) => this.#readReplicaRow(scope, sourceKey, identity, true),
1123
1126
  getReplicaRows: (scope, sourceKey) => this.#readReplicaRows(scope, sourceKey),
1127
+ getReplicaRowsIncludingPendingDelete: (scope, sourceKey) => this.#readReplicaRows(scope, sourceKey, true),
1124
1128
  getReplicaRowByRemoteId: async (scope, sourceKey, remoteId) => {
1125
1129
  if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
1126
1130
  return null;
@@ -1242,7 +1246,10 @@ class IonicOfflineRepository {
1242
1246
  }
1243
1247
  async #migrate() {
1244
1248
  const metadata = await this.#storage.get(METADATA_KEY);
1245
- if (metadata?.schemaVersion !== undefined && metadata.schemaVersion !== OFFLINE_SCHEMA_VERSION) {
1249
+ if (metadata?.schemaVersion === 1) {
1250
+ await this.#migrateCoreSchemaV1();
1251
+ }
1252
+ else if (metadata?.schemaVersion !== undefined && metadata.schemaVersion !== OFFLINE_SCHEMA_VERSION) {
1246
1253
  throw new Error(`Unsupported offline storage schema version ${metadata.schemaVersion}; expected ${OFFLINE_SCHEMA_VERSION}. ` +
1247
1254
  'A lossless core schema migration is required before this database can be opened.');
1248
1255
  }
@@ -1256,6 +1263,24 @@ class IonicOfflineRepository {
1256
1263
  if (interrupted)
1257
1264
  await this.#applyReplicaTransaction(interrupted, false);
1258
1265
  }
1266
+ async #migrateCoreSchemaV1() {
1267
+ const commands = await this.#readRecord(OUTBOX_KEY);
1268
+ const migratedCommands = Object.fromEntries(Object.entries(commands).map(([key, command]) => {
1269
+ const { optimisticValue, optimisticCompanions, payloadHash, ...current } = command;
1270
+ return [
1271
+ key,
1272
+ {
1273
+ ...current,
1274
+ ...(optimisticValue === undefined ? {} : { legacyOptimisticValue: structuredClone(optimisticValue) }),
1275
+ ...(optimisticCompanions === undefined ? {} : { legacyOptimisticCompanions: structuredClone(optimisticCompanions) }),
1276
+ ...(payloadHash === undefined ? {} : { legacyPayloadHash: payloadHash }),
1277
+ },
1278
+ ];
1279
+ }));
1280
+ const metadata = await this.#metadata();
1281
+ await this.#storage.set(OUTBOX_KEY, migratedCommands);
1282
+ await this.#storage.set(METADATA_KEY, { ...metadata, schemaVersion: OFFLINE_SCHEMA_VERSION });
1283
+ }
1259
1284
  async #initializeReplicaSchema(storedVersion, storedHash) {
1260
1285
  const bundle = this.#options.replicaSchema;
1261
1286
  const targetVersion = bundle.version;
@@ -2034,176 +2059,240 @@ class OfflineReplicaPullService {
2034
2059
  requestCursor = page.nextCursor;
2035
2060
  continue;
2036
2061
  }
2037
- const applied = await this.#replicaMutations.run(async (repository) => {
2038
- const currentCursor = (await repository.getReplicaCursor(scope))?.cursor ?? '';
2039
- if (currentCursor !== persistedCursor)
2040
- return currentCursor;
2041
- const scopeCommands = await repository.getCommands(scope);
2042
- const userCommands = repository.getCommandsForUser ? await repository.getCommandsForUser(scope.userId) : scopeCommands;
2043
- const changes = this.#collapseChanges(page.changes);
2044
- const projection = await this.#projector?.project({
2045
- scope,
2046
- changes,
2047
- });
2048
- this.#assertProjection(scope, projection);
2049
- const putRows = [];
2050
- const removeRows = [];
2051
- const putCommands = new Map();
2052
- const removeCommandIds = new Set();
2053
- const rematerializeAfter = [];
2054
- if (rebaselinePending || page.rebaselineRequired) {
2055
- removeRows.push(...(await this.#confirmedRowsForRebaseline(scope, userCommands)));
2056
- }
2057
- for (const change of changes) {
2058
- const schema = this.#entitySchema(change.sourceKey);
2059
- const commands = schema.scope === 'user' ? userCommands : scopeCommands;
2060
- const acknowledged = (change.acknowledgedCommandIds ?? [])
2061
- .map((commandId) => {
2062
- const command = commands.find((candidate) => candidate.commandId === commandId);
2063
- if (!command)
2064
- return null;
2065
- if (command.sourceKey !== change.sourceKey) {
2066
- throw new Error(`Acknowledged command "${commandId}" does not target "${change.sourceKey}".`);
2067
- }
2068
- const requested = reconciliationTargetsById.get(commandId);
2069
- if (command.state === 'awaiting_pull') {
2070
- if (!requested) {
2071
- throw new Error(`Acknowledged command "${commandId}" was not requested for reconciliation on this pull page.`);
2072
- }
2073
- const schema = this.#entitySchema(change.sourceKey);
2074
- if (canonicalOfflineRemoteIdentity(schema, requested.identity) !==
2075
- canonicalOfflineRemoteIdentity(schema, this.#identity(change))) {
2076
- throw new Error(`Acknowledged command "${commandId}" does not match the requested remote identity.`);
2077
- }
2078
- }
2079
- return command;
2080
- })
2081
- .filter((command) => command !== null);
2082
- const acknowledgedIdentities = new Set(acknowledged.map((command) => canonicalOfflineCommandIdentity(command.identity)));
2083
- if (acknowledgedIdentities.size > 1) {
2084
- throw new Error(`Acknowledged commands for "${change.sourceKey}" target multiple replica identities.`);
2085
- }
2086
- const acknowledgedCommand = acknowledged[0];
2087
- const acknowledgedScope = acknowledgedCommand
2088
- ? { userId: acknowledgedCommand.userId, scopeId: acknowledgedCommand.scopeId }
2089
- : scope;
2090
- const acknowledgedRow = acknowledgedCommand
2091
- ? await (this.#repository.getReplicaRowIncludingPendingDelete?.(acknowledgedScope, change.sourceKey, acknowledgedCommand.identity) ?? this.#repository.getReplicaRow(acknowledgedScope, change.sourceKey, acknowledgedCommand.identity))
2092
- : null;
2093
- if (acknowledgedCommand && !acknowledgedRow) {
2094
- throw new Error(`Acknowledged command "${acknowledgedCommand.commandId}" has no local replica row.`);
2062
+ const applied = await this.#applyAuthoritativeChanges(scope, page.changes, {
2063
+ expectedCursor: persistedCursor,
2064
+ nextCursor: page.nextCursor,
2065
+ rebaseline: rebaselinePending || page.rebaselineRequired === true,
2066
+ reconciliationTargetsById,
2067
+ });
2068
+ if (applied !== page.nextCursor) {
2069
+ persistedCursor = applied;
2070
+ requestCursor = applied;
2071
+ rebaselinePending = false;
2072
+ continue;
2073
+ }
2074
+ persistedCursor = page.nextCursor;
2075
+ requestCursor = page.nextCursor;
2076
+ rebaselinePending = false;
2077
+ if (!page.hasMore)
2078
+ return;
2079
+ }
2080
+ }
2081
+ /**
2082
+ * Applies an already-fetched authoritative server batch through the same
2083
+ * acknowledgement, conflict, and aggregate-rematerialization boundary as pull.
2084
+ */
2085
+ async applyChanges(scope, changes) {
2086
+ const reconciliationTargets = await this.#reconciliationTargets(scope);
2087
+ await this.#applyAuthoritativeChanges(scope, changes, {
2088
+ expectedCursor: null,
2089
+ nextCursor: null,
2090
+ rebaseline: false,
2091
+ reconciliationTargetsById: new Map(reconciliationTargets.map((target) => [target.commandId, target])),
2092
+ });
2093
+ }
2094
+ async #applyAuthoritativeChanges(scope, incomingChanges, options) {
2095
+ return this.#replicaMutations.run(async (repository) => {
2096
+ const currentCursor = (await repository.getReplicaCursor(scope))?.cursor ?? '';
2097
+ if (options.expectedCursor !== null && currentCursor !== options.expectedCursor)
2098
+ return currentCursor;
2099
+ const scopeCommands = await repository.getCommands(scope);
2100
+ const userCommands = repository.getCommandsForUser ? await repository.getCommandsForUser(scope.userId) : scopeCommands;
2101
+ const changes = this.#collapseChanges(typeof incomingChanges === 'function' ? await incomingChanges(repository) : incomingChanges);
2102
+ const existingRows = await this.#preloadRows(repository, scope, changes);
2103
+ const projection = await this.#projector?.project({
2104
+ scope,
2105
+ changes,
2106
+ });
2107
+ this.#assertProjection(scope, projection);
2108
+ const putRows = [];
2109
+ const removeRows = [];
2110
+ const putCommands = new Map();
2111
+ const removeCommandIds = new Set();
2112
+ const rematerializeAfter = [];
2113
+ if (options.rebaseline) {
2114
+ removeRows.push(...(await this.#confirmedRowsForRebaseline(scope, userCommands)));
2115
+ }
2116
+ for (const change of changes) {
2117
+ const schema = this.#entitySchema(change.sourceKey);
2118
+ const commands = schema.scope === 'user' ? userCommands : scopeCommands;
2119
+ const acknowledged = (change.acknowledgedCommandIds ?? [])
2120
+ .map((commandId) => {
2121
+ const command = commands.find((candidate) => candidate.commandId === commandId);
2122
+ if (!command)
2123
+ return null;
2124
+ if (command.sourceKey !== change.sourceKey) {
2125
+ throw new Error(`Acknowledged command "${commandId}" does not target "${change.sourceKey}".`);
2095
2126
  }
2096
- const identity = this.#identity(change);
2097
- const serverRow = await this.#repository.getReplicaRowByRemoteIdentity(scope, change.sourceKey, identity);
2098
- if (acknowledgedRow &&
2099
- serverRow &&
2100
- !commandIdentityMatchesReplicaRow(schema, acknowledgedRow, commandIdentityFromReplicaIdentity(serverRow.identity))) {
2101
- if (identity.remoteId !== undefined) {
2102
- throw new Error(`Server id ${String(identity.remoteId)} is already mapped to another local replica row.`);
2127
+ const requested = options.reconciliationTargetsById.get(commandId);
2128
+ if (command.state === 'awaiting_pull') {
2129
+ if (!requested) {
2130
+ throw new Error(`Acknowledged command "${commandId}" was not requested for reconciliation on this pull page.`);
2131
+ }
2132
+ const schema = this.#entitySchema(change.sourceKey);
2133
+ if (canonicalOfflineRemoteIdentity(schema, requested.identity) !==
2134
+ canonicalOfflineRemoteIdentity(schema, this.#identity(change))) {
2135
+ throw new Error(`Acknowledged command "${commandId}" does not match the requested remote identity.`);
2103
2136
  }
2104
- throw new Error(`Remote identity for "${change.sourceKey}" is already mapped to another local replica row.`);
2105
2137
  }
2106
- const existing = acknowledgedRow ?? serverRow;
2107
- const related = existing
2108
- ? commands.filter((command) => command.sourceKey === change.sourceKey && commandIdentityMatchesReplicaRow(schema, existing, command.identity))
2109
- : [];
2110
- const hasPending = related.length > 0;
2111
- if (acknowledgedCommand) {
2112
- this.#assertIdentityAssignment(schema, existing, identity);
2113
- this.#applyAcknowledgement(change, existing, related, putRows, removeRows, putCommands, removeCommandIds, rematerializeAfter);
2114
- continue;
2138
+ return command;
2139
+ })
2140
+ .filter((command) => command !== null);
2141
+ const acknowledgedIdentities = new Set(acknowledged.map((command) => canonicalOfflineCommandIdentity(command.identity)));
2142
+ if (acknowledgedIdentities.size > 1) {
2143
+ throw new Error(`Acknowledged commands for "${change.sourceKey}" target multiple replica identities.`);
2144
+ }
2145
+ const acknowledgedCommand = acknowledged[0];
2146
+ const acknowledgedScope = acknowledgedCommand
2147
+ ? { userId: acknowledgedCommand.userId, scopeId: acknowledgedCommand.scopeId }
2148
+ : scope;
2149
+ const acknowledgedRow = acknowledgedCommand
2150
+ ? (existingRows.byCommand.get(this.#commandRowKey(change.sourceKey, acknowledgedScope, acknowledgedCommand.identity)) ?? null)
2151
+ : null;
2152
+ if (acknowledgedCommand && !acknowledgedRow) {
2153
+ throw new Error(`Acknowledged command "${acknowledgedCommand.commandId}" has no local replica row.`);
2154
+ }
2155
+ const identity = this.#identity(change);
2156
+ const serverRow = existingRows.byRemote.get(this.#remoteRowKey(change.sourceKey, scope, identity)) ?? null;
2157
+ if (acknowledgedRow &&
2158
+ serverRow &&
2159
+ !commandIdentityMatchesReplicaRow(schema, acknowledgedRow, commandIdentityFromReplicaIdentity(serverRow.identity))) {
2160
+ if (identity.remoteId !== undefined) {
2161
+ throw new Error(`Server id ${String(identity.remoteId)} is already mapped to another local replica row.`);
2115
2162
  }
2116
- if (change.deleted) {
2117
- if (!existing)
2118
- continue;
2119
- if (!hasPending) {
2120
- removeRows.push({ ...existing, identity: existing.identity });
2121
- continue;
2122
- }
2123
- putRows.push({
2124
- ...existing,
2125
- confirmedValues: null,
2126
- serverRevision: change.serverRevision,
2127
- syncState: 'conflict',
2128
- fetchedAt: Date.now(),
2129
- });
2130
- for (const command of related) {
2131
- putCommands.set(command.commandId, { ...command, state: 'conflict', retryAt: null, lastErrorCode: 'remote_deleted' });
2132
- }
2133
- rematerializeAfter.push(related[0]);
2163
+ throw new Error(`Remote identity for "${change.sourceKey}" is already mapped to another local replica row.`);
2164
+ }
2165
+ const existing = acknowledgedRow ?? serverRow;
2166
+ const related = existing
2167
+ ? commands.filter((command) => command.sourceKey === change.sourceKey && commandIdentityMatchesReplicaRow(schema, existing, command.identity))
2168
+ : [];
2169
+ const hasPending = related.length > 0;
2170
+ if (acknowledgedCommand) {
2171
+ this.#assertIdentityAssignment(schema, existing, identity);
2172
+ this.#applyAcknowledgement(change, existing, related, putRows, removeRows, putCommands, removeCommandIds, rematerializeAfter);
2173
+ continue;
2174
+ }
2175
+ if (change.deleted) {
2176
+ if (!existing)
2134
2177
  continue;
2135
- }
2136
- const confirmedValues = this.#validatedValues(schema, change);
2137
- if (!existing) {
2138
- putRows.push({
2139
- ...scope,
2140
- sourceKey: change.sourceKey,
2141
- identity: schema.identity.kind === 'naturalKey'
2142
- ? offlineNaturalReplicaIdentity(schema, confirmedValues)
2143
- : offlineGeneratedReplicaIdentity(crypto.randomUUID(), identity.remoteId ?? null),
2144
- values: confirmedValues,
2145
- confirmedValues,
2146
- serverRevision: change.serverRevision,
2147
- fetchedAt: Date.now(),
2148
- syncState: 'confirmed',
2149
- });
2178
+ if (!hasPending) {
2179
+ removeRows.push({ ...existing, identity: existing.identity });
2150
2180
  continue;
2151
2181
  }
2152
- const remaining = related.filter((command) => !removeCommandIds.has(command.commandId));
2153
- const confirmedRow = {
2182
+ putRows.push({
2154
2183
  ...existing,
2155
- confirmedValues,
2184
+ confirmedValues: null,
2156
2185
  serverRevision: change.serverRevision,
2186
+ syncState: 'conflict',
2157
2187
  fetchedAt: Date.now(),
2158
- values: remaining.length > 0 ? existing.values : confirmedValues,
2159
- syncState: remaining.length > 0 ? 'pending' : 'confirmed',
2160
- };
2161
- putRows.push(confirmedRow);
2162
- if (remaining.length > 0)
2163
- rematerializeAfter.push(remaining[0]);
2164
- for (const command of remaining) {
2165
- putCommands.set(command.commandId, offlineCommandWithBaseRevision(command, change.serverRevision));
2188
+ });
2189
+ for (const command of related) {
2190
+ putCommands.set(command.commandId, { ...command, state: 'conflict', retryAt: null, lastErrorCode: 'remote_deleted' });
2166
2191
  }
2192
+ rematerializeAfter.push(related[0]);
2193
+ continue;
2167
2194
  }
2168
- const confirmedAndProjected = this.#mergeRowMutations([
2169
- { putRows, removeRows },
2170
- { putRows: projection?.putRows ?? [], removeRows: projection?.removeRows ?? [] },
2171
- ]);
2172
- const rematerialized = await this.#rematerializePendingAggregates(scope, userCommands, scopeCommands, confirmedAndProjected, putCommands, removeCommandIds, rematerializeAfter);
2173
- const finalRows = this.#mergeRowMutations([confirmedAndProjected, rematerialized]);
2174
- const removedCommands = [...removeCommandIds]
2175
- .map((commandId) => userCommands.find((command) => command.commandId === commandId) ??
2176
- scopeCommands.find((command) => command.commandId === commandId))
2177
- .filter((command) => command != null);
2178
- await repository.transactReplica({
2179
- putRows: finalRows.putRows,
2180
- removeRows: finalRows.removeRows,
2181
- putCommands: [...putCommands.values()],
2182
- removeCommandIds: [...removeCommandIds],
2183
- putCursors: [{ ...scope, cursor: page.nextCursor }],
2184
- });
2185
- await Promise.all(removedCommands.map((command) => this.#hooks.onCommandRemoved?.(command).catch(() => undefined)));
2186
- return page.nextCursor;
2195
+ const confirmedValues = this.#validatedValues(schema, change);
2196
+ if (!existing) {
2197
+ putRows.push({
2198
+ ...scope,
2199
+ sourceKey: change.sourceKey,
2200
+ identity: schema.identity.kind === 'naturalKey'
2201
+ ? offlineNaturalReplicaIdentity(schema, confirmedValues)
2202
+ : offlineGeneratedReplicaIdentity(crypto.randomUUID(), identity.remoteId ?? null),
2203
+ values: confirmedValues,
2204
+ confirmedValues,
2205
+ serverRevision: change.serverRevision,
2206
+ fetchedAt: Date.now(),
2207
+ syncState: 'confirmed',
2208
+ });
2209
+ continue;
2210
+ }
2211
+ const remaining = related.filter((command) => !removeCommandIds.has(command.commandId));
2212
+ const confirmedRow = {
2213
+ ...existing,
2214
+ confirmedValues,
2215
+ serverRevision: change.serverRevision,
2216
+ fetchedAt: Date.now(),
2217
+ values: remaining.length > 0 ? existing.values : confirmedValues,
2218
+ syncState: remaining.length > 0 ? 'pending' : 'confirmed',
2219
+ };
2220
+ putRows.push(confirmedRow);
2221
+ if (remaining.length > 0)
2222
+ rematerializeAfter.push(remaining[0]);
2223
+ for (const command of remaining) {
2224
+ putCommands.set(command.commandId, offlineCommandWithBaseRevision(command, change.serverRevision));
2225
+ }
2226
+ }
2227
+ const confirmedAndProjected = this.#mergeRowMutations([
2228
+ { putRows, removeRows },
2229
+ { putRows: projection?.putRows ?? [], removeRows: projection?.removeRows ?? [] },
2230
+ ]);
2231
+ const rematerialized = await this.#rematerializePendingAggregates(scope, userCommands, scopeCommands, confirmedAndProjected, putCommands, removeCommandIds, rematerializeAfter);
2232
+ const finalRows = this.#mergeRowMutations([confirmedAndProjected, rematerialized]);
2233
+ const removedCommands = [...removeCommandIds]
2234
+ .map((commandId) => userCommands.find((command) => command.commandId === commandId) ??
2235
+ scopeCommands.find((command) => command.commandId === commandId))
2236
+ .filter((command) => command != null);
2237
+ await repository.transactReplica({
2238
+ putRows: finalRows.putRows,
2239
+ removeRows: finalRows.removeRows,
2240
+ putCommands: [...putCommands.values()],
2241
+ removeCommandIds: [...removeCommandIds],
2242
+ ...(options.nextCursor === null ? {} : { putCursors: [{ ...scope, cursor: options.nextCursor }] }),
2187
2243
  });
2188
- if (applied !== page.nextCursor) {
2189
- persistedCursor = applied;
2190
- requestCursor = applied;
2191
- rebaselinePending = false;
2192
- continue;
2244
+ await Promise.all(removedCommands.map((command) => this.#hooks.onCommandRemoved?.(command).catch(() => undefined)));
2245
+ return options.nextCursor ?? currentCursor;
2246
+ });
2247
+ }
2248
+ async #preloadRows(repository, scope, changes) {
2249
+ const sourceKeys = [...new Set(changes.map((change) => change.sourceKey))];
2250
+ const partitions = await Promise.all(sourceKeys.map(async (sourceKey) => ({
2251
+ sourceKey,
2252
+ rows: await (repository.getReplicaRowsIncludingPendingDelete?.(scope, sourceKey) ?? repository.getReplicaRows(scope, sourceKey)),
2253
+ })));
2254
+ const byCommand = new Map();
2255
+ const byRemote = new Map();
2256
+ for (const { sourceKey, rows } of partitions) {
2257
+ const schema = this.#entitySchema(sourceKey);
2258
+ for (const row of rows) {
2259
+ if (row.identity.kind !== 'local') {
2260
+ byCommand.set(this.#commandRowKey(sourceKey, row, commandIdentityFromReplicaIdentity(row.identity)), row);
2261
+ }
2262
+ if (row.identity.kind === 'generated' && row.identity.remoteId !== null) {
2263
+ byRemote.set(this.#remoteRowKey(sourceKey, row, { remoteId: row.identity.remoteId }), row);
2264
+ }
2265
+ else if (row.identity.kind === 'natural') {
2266
+ byRemote.set(this.#remoteRowKey(sourceKey, row, { naturalKey: row.identity.naturalKey }), row);
2267
+ }
2193
2268
  }
2194
- persistedCursor = page.nextCursor;
2195
- requestCursor = page.nextCursor;
2196
- rebaselinePending = false;
2197
- if (!page.hasMore)
2198
- return;
2199
2269
  }
2270
+ return { byCommand, byRemote };
2271
+ }
2272
+ #commandRowKey(sourceKey, scope, identity) {
2273
+ const partition = this.#entitySchema(sourceKey).scope === 'user' ? '' : scope.scopeId;
2274
+ return `${sourceKey}:${scope.userId}:${partition}:${canonicalOfflineCommandIdentity(identity)}`;
2275
+ }
2276
+ #remoteRowKey(sourceKey, scope, identity) {
2277
+ const schema = this.#entitySchema(sourceKey);
2278
+ const partition = schema.scope === 'user' ? '' : scope.scopeId;
2279
+ return `${sourceKey}:${scope.userId}:${partition}:${canonicalOfflineRemoteIdentity(schema, identity)}`;
2200
2280
  }
2201
2281
  async #reconciliationTargets(scope) {
2202
2282
  const commands = (await this.#repository.getCommands(scope)).filter((command) => command.state === 'awaiting_pull');
2283
+ const rowsByCommand = new Map();
2284
+ await Promise.all([...new Set(commands.map((command) => command.sourceKey))].map(async (sourceKey) => {
2285
+ const rows = await (this.#repository.getReplicaRowsIncludingPendingDelete?.(scope, sourceKey) ??
2286
+ this.#repository.getReplicaRows(scope, sourceKey));
2287
+ for (const row of rows) {
2288
+ if (row.identity.kind !== 'local') {
2289
+ rowsByCommand.set(this.#commandRowKey(sourceKey, row, commandIdentityFromReplicaIdentity(row.identity)), row);
2290
+ }
2291
+ }
2292
+ }));
2203
2293
  const targets = [];
2204
2294
  for (const command of commands) {
2205
- const row = (await this.#repository.getReplicaRowIncludingPendingDelete?.(scope, command.sourceKey, command.identity)) ??
2206
- (await this.#repository.getReplicaRow(scope, command.sourceKey, command.identity));
2295
+ const row = rowsByCommand.get(this.#commandRowKey(command.sourceKey, command, command.identity));
2207
2296
  if (!row)
2208
2297
  throw new Error(`Awaiting-pull command "${command.commandId}" has no replica row.`);
2209
2298
  const identity = command.reconciliationIdentity ??
@@ -2612,12 +2701,12 @@ class OfflineNetworkService {
2612
2701
  return;
2613
2702
  this.#initialized = true;
2614
2703
  const [networkListener, appListener] = await Promise.all([
2615
- Network.addListener('networkStatusChange', ({ connected }) => {
2704
+ this.addNetworkStatusListener(({ connected }) => {
2616
2705
  this.#networkRevision += 1;
2617
2706
  this.#osConnected.set(connected);
2618
2707
  this.#apiReachable.set(connected ? null : false);
2619
2708
  }),
2620
- App.addListener('appStateChange', ({ isActive }) => {
2709
+ this.addAppStateListener(({ isActive }) => {
2621
2710
  this.#lifecycleRevision.update((revision) => revision + 1);
2622
2711
  this.#appActive.set(isActive);
2623
2712
  if (isActive)
@@ -2627,7 +2716,7 @@ class OfflineNetworkService {
2627
2716
  this.#listeners.push(networkListener, appListener);
2628
2717
  const networkRevision = this.#networkRevision;
2629
2718
  const lifecycleRevision = this.#lifecycleRevision();
2630
- const [network, app] = await Promise.all([Network.getStatus(), App.getState()]);
2719
+ const [network, app] = await Promise.all([this.getNetworkStatus(), this.getAppState()]);
2631
2720
  if (this.#networkRevision === networkRevision)
2632
2721
  this.#osConnected.set(network.connected);
2633
2722
  if (this.#lifecycleRevision() === lifecycleRevision)
@@ -2639,9 +2728,25 @@ class OfflineNetworkService {
2639
2728
  markApiFailure() {
2640
2729
  this.#apiReachable.set(false);
2641
2730
  }
2731
+ /** Factory seam for Capacitor app-state discovery and deterministic tests. */
2732
+ getAppState() {
2733
+ return App.getState();
2734
+ }
2735
+ /** Factory seam for Capacitor app-state listeners and deterministic tests. */
2736
+ addAppStateListener(listener) {
2737
+ return App.addListener('appStateChange', listener);
2738
+ }
2739
+ /** Factory seam for Capacitor network discovery and deterministic tests. */
2740
+ getNetworkStatus() {
2741
+ return Network.getStatus();
2742
+ }
2743
+ /** Factory seam for Capacitor network listeners and deterministic tests. */
2744
+ addNetworkStatusListener(listener) {
2745
+ return Network.addListener('networkStatusChange', listener);
2746
+ }
2642
2747
  async #refreshOsStatus() {
2643
2748
  const revision = this.#networkRevision;
2644
- const status = await Network.getStatus();
2749
+ const status = await this.getNetworkStatus();
2645
2750
  if (this.#networkRevision === revision)
2646
2751
  this.#osConnected.set(status.connected);
2647
2752
  }
@@ -5354,6 +5459,9 @@ const SCHEMA = [
5354
5459
  identity_json TEXT NOT NULL,
5355
5460
  operation TEXT NOT NULL,
5356
5461
  payload_json TEXT NOT NULL,
5462
+ optimistic_value_json TEXT NOT NULL DEFAULT 'null',
5463
+ optimistic_companions_json TEXT,
5464
+ legacy_optimistic_value_json TEXT,
5357
5465
  local_only_footprint_json TEXT,
5358
5466
  replica_mutation TEXT NOT NULL DEFAULT 'upsert',
5359
5467
  payload_hash TEXT NOT NULL,
@@ -5441,6 +5549,9 @@ class SqliteOfflineRepository {
5441
5549
  async getReplicaRows(scope, sourceKey) {
5442
5550
  return this.#withCommittedRead(() => this.#readReplicaRows(scope, sourceKey));
5443
5551
  }
5552
+ async getReplicaRowsIncludingPendingDelete(scope, sourceKey) {
5553
+ return this.#withCommittedRead(() => this.#readReplicaRows(scope, sourceKey, true));
5554
+ }
5444
5555
  async getReplicaRowByRemoteId(scope, sourceKey, remoteId) {
5445
5556
  if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
5446
5557
  return null;
@@ -5578,10 +5689,26 @@ class SqliteOfflineRepository {
5578
5689
  releases.set(key, release);
5579
5690
  }
5580
5691
  const consumedReleases = new Set();
5692
+ const existingRows = new Map();
5693
+ const partitions = new Map();
5694
+ for (const row of transaction.putRows ?? []) {
5695
+ const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
5696
+ const partitionScopeId = schema.scope === 'partition' ? row.scopeId : '';
5697
+ partitions.set(`${canonicalOfflinePrincipalId(row.userId)}:${partitionScopeId}:${row.sourceKey}`, {
5698
+ scope: row,
5699
+ sourceKey: row.sourceKey,
5700
+ });
5701
+ }
5702
+ await Promise.all([...partitions.values()].map(async ({ scope, sourceKey }) => {
5703
+ for (const row of await this.#readReplicaRows(scope, sourceKey, true)) {
5704
+ existingRows.set(this.#replicaRowKey(row), row);
5705
+ }
5706
+ }));
5581
5707
  for (const row of transaction.putRows ?? []) {
5582
5708
  const key = this.#replicaRowKey(row);
5583
5709
  const release = releases.get(key);
5584
- await this.#putReplicaRow(databaseId, row, release);
5710
+ await this.#putReplicaRow(databaseId, row, release, existingRows.get(key) ?? null);
5711
+ existingRows.set(key, row);
5585
5712
  if (release)
5586
5713
  consumedReleases.add(key);
5587
5714
  }
@@ -5637,13 +5764,35 @@ class SqliteOfflineRepository {
5637
5764
  }
5638
5765
  else {
5639
5766
  const storedVersion = this.#number(metadata[0]['schema_version']);
5640
- if (storedVersion !== OFFLINE_SCHEMA_VERSION) {
5767
+ if (storedVersion === 1) {
5768
+ await this.#migrateCoreSchemaV1(databaseId);
5769
+ }
5770
+ else if (storedVersion !== OFFLINE_SCHEMA_VERSION) {
5641
5771
  throw new OfflineStorageUnavailableError('core_schema_incompatible', `Unsupported offline storage schema version ${storedVersion}; expected ${OFFLINE_SCHEMA_VERSION}. ` +
5642
5772
  'A lossless core schema migration is required before this database can be opened.');
5643
5773
  }
5644
5774
  }
5645
5775
  await this.#initializeReplicaSchema(databaseId);
5646
5776
  }
5777
+ async #migrateCoreSchemaV1(databaseId) {
5778
+ const columns = await this.#queryDatabase(databaseId, 'PRAGMA table_info(offline_sync_commands)');
5779
+ const names = new Set(columns.map((row) => this.#string(row['name'])));
5780
+ await this.#nativeTransaction(databaseId, async () => {
5781
+ if (!names.has('legacy_optimistic_value_json')) {
5782
+ await this.#execute(databaseId, 'ALTER TABLE offline_sync_commands ADD COLUMN legacy_optimistic_value_json TEXT');
5783
+ }
5784
+ if (!names.has('local_only_footprint_json')) {
5785
+ await this.#execute(databaseId, 'ALTER TABLE offline_sync_commands ADD COLUMN local_only_footprint_json TEXT');
5786
+ }
5787
+ if (!names.has('reconciliation_identity_json')) {
5788
+ await this.#execute(databaseId, 'ALTER TABLE offline_sync_commands ADD COLUMN reconciliation_identity_json TEXT');
5789
+ }
5790
+ if (names.has('optimistic_value_json')) {
5791
+ await this.#execute(databaseId, 'UPDATE offline_sync_commands SET legacy_optimistic_value_json = optimistic_value_json WHERE legacy_optimistic_value_json IS NULL');
5792
+ }
5793
+ await this.#execute(databaseId, 'UPDATE offline_metadata SET schema_version = ? WHERE id = 1', [OFFLINE_SCHEMA_VERSION]);
5794
+ });
5795
+ }
5647
5796
  async #initializeReplicaSchema(databaseId) {
5648
5797
  const bundle = this.#options.replicaSchema;
5649
5798
  const targetVersion = bundle.version;
@@ -5757,7 +5906,7 @@ class SqliteOfflineRepository {
5757
5906
  const row = rows[0];
5758
5907
  return row ? this.#parse(row['value_json']) : null;
5759
5908
  }
5760
- async #readReplicaRows(scope, sourceKey) {
5909
+ async #readReplicaRows(scope, sourceKey, includePendingDelete = false) {
5761
5910
  const schema = this.#resolveReplicaEntitySchema(sourceKey);
5762
5911
  const predicates = ['_offline_user_id = ?'];
5763
5912
  const values = [canonicalOfflinePrincipalId(scope.userId)];
@@ -5770,7 +5919,7 @@ class SqliteOfflineRepository {
5770
5919
  : 'local_id ASC';
5771
5920
  const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')} ORDER BY ${orderBy}`, values);
5772
5921
  return rows
5773
- .filter((row) => (row['_offline_visibility'] ?? 'present') !== 'pending_delete')
5922
+ .filter((row) => includePendingDelete || (row['_offline_visibility'] ?? 'present') !== 'pending_delete')
5774
5923
  .map((row) => this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row));
5775
5924
  }
5776
5925
  async #readReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
@@ -5846,6 +5995,7 @@ class SqliteOfflineRepository {
5846
5995
  getReplicaRow: async (scope, sourceKey, identity) => (await this.#queryReplicaRow(scope, sourceKey, identity, false)),
5847
5996
  getReplicaRowIncludingPendingDelete: async (scope, sourceKey, identity) => (await this.#queryReplicaRow(scope, sourceKey, identity, true)),
5848
5997
  getReplicaRows: (scope, sourceKey) => this.#readReplicaRows(scope, sourceKey),
5998
+ getReplicaRowsIncludingPendingDelete: (scope, sourceKey) => this.#readReplicaRows(scope, sourceKey, true),
5849
5999
  getReplicaRowByRemoteId: async (scope, sourceKey, remoteId) => {
5850
6000
  if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
5851
6001
  return null;
@@ -5985,6 +6135,15 @@ class SqliteOfflineRepository {
5985
6135
  identity: parseOfflineCommandIdentity(this.#parse(row['identity_json'])),
5986
6136
  operation: this.#string(row['operation']),
5987
6137
  payload: this.#parse(row['payload_json']),
6138
+ ...(row['legacy_optimistic_value_json'] === null || row['legacy_optimistic_value_json'] === undefined
6139
+ ? {}
6140
+ : { legacyOptimisticValue: this.#parse(row['legacy_optimistic_value_json']) }),
6141
+ ...(row['optimistic_companions_json'] === null || row['optimistic_companions_json'] === undefined
6142
+ ? {}
6143
+ : { legacyOptimisticCompanions: this.#parse(row['optimistic_companions_json']) }),
6144
+ ...(row['payload_hash'] === null || row['payload_hash'] === undefined || row['payload_hash'] === ''
6145
+ ? {}
6146
+ : { legacyPayloadHash: this.#string(row['payload_hash']) }),
5988
6147
  ...(row['local_only_footprint_json'] === null || row['local_only_footprint_json'] === undefined
5989
6148
  ? {}
5990
6149
  : { localOnlyFootprint: this.#parse(row['local_only_footprint_json']) }),
@@ -6004,13 +6163,16 @@ class SqliteOfflineRepository {
6004
6163
  #putCommand(databaseId, command) {
6005
6164
  return this.#execute(databaseId, `INSERT INTO offline_sync_commands
6006
6165
  (command_id, user_id, scope_id, aggregate_type, source_key, identity_json, operation, payload_json,
6007
- local_only_footprint_json, replica_mutation, payload_hash, base_revision_json, state, attempts, retry_at, created_at, last_error_code,
6166
+ optimistic_value_json, optimistic_companions_json, legacy_optimistic_value_json, local_only_footprint_json, replica_mutation, payload_hash, base_revision_json, state, attempts, retry_at, created_at, last_error_code,
6008
6167
  server_commit_unknown, reconciliation_identity_json)
6009
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
6168
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
6010
6169
  ON CONFLICT(command_id) DO UPDATE SET
6011
6170
  user_id = excluded.user_id, scope_id = excluded.scope_id, aggregate_type = excluded.aggregate_type,
6012
6171
  source_key = excluded.source_key,
6013
6172
  identity_json = excluded.identity_json, operation = excluded.operation, payload_json = excluded.payload_json,
6173
+ optimistic_value_json = excluded.optimistic_value_json,
6174
+ optimistic_companions_json = excluded.optimistic_companions_json,
6175
+ legacy_optimistic_value_json = excluded.legacy_optimistic_value_json,
6014
6176
  local_only_footprint_json = excluded.local_only_footprint_json,
6015
6177
  replica_mutation = excluded.replica_mutation,
6016
6178
  payload_hash = excluded.payload_hash,
@@ -6026,9 +6188,12 @@ class SqliteOfflineRepository {
6026
6188
  serializeOfflineCommandIdentity(command.identity),
6027
6189
  command.operation,
6028
6190
  JSON.stringify(command.payload),
6191
+ JSON.stringify(command.legacyOptimisticValue ?? null),
6192
+ command.legacyOptimisticCompanions === undefined ? null : JSON.stringify(command.legacyOptimisticCompanions),
6193
+ command.legacyOptimisticValue === undefined ? null : JSON.stringify(command.legacyOptimisticValue),
6029
6194
  command.localOnlyFootprint === undefined ? null : JSON.stringify(command.localOnlyFootprint),
6030
6195
  command.replicaMutation ?? 'upsert',
6031
- '',
6196
+ command.legacyPayloadHash ?? '',
6032
6197
  this.#stringifyNullable(command.baseRevision),
6033
6198
  command.state,
6034
6199
  command.attempts,
@@ -6069,7 +6234,7 @@ class SqliteOfflineRepository {
6069
6234
  return null;
6070
6235
  return this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row);
6071
6236
  }
6072
- async #putReplicaRow(databaseId, row, release) {
6237
+ async #putReplicaRow(databaseId, row, release, existing) {
6073
6238
  const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
6074
6239
  if (row.identity.kind === 'generated') {
6075
6240
  assertOfflineReplicaGeneratedRemoteId(schema, row.identity.remoteId);
@@ -6088,7 +6253,6 @@ class SqliteOfflineRepository {
6088
6253
  if (row.confirmedValues !== null)
6089
6254
  encodeOfflineReplicaValues(schema, row.confirmedValues);
6090
6255
  assertOfflineReplicaNaturalKeyBaseline(schema, row.values, row.confirmedValues);
6091
- const existing = await this.#queryReplicaRow(row, row.sourceKey, replicaAddressFromIdentity(row.identity), true);
6092
6256
  if (!existing && release) {
6093
6257
  throw new Error(`Offline replica remoteId release requires an existing row for ${row.sourceKey}/${canonicalOfflineReplicaIdentity(row.identity)}.`);
6094
6258
  }