@rdlabo/ionic-angular-kit 21.5.6 → 21.5.8

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.
@@ -9,6 +9,7 @@ import { Capacitor } from '@capacitor/core';
9
9
  import { HttpContextToken, HttpResponse } from '@angular/common/http';
10
10
  import { defer, catchError, throwError, tap, from, concatMap, of } from 'rxjs';
11
11
 
12
+ const MAX_OFFLINE_NATURAL_KEY_TEXT_BYTES = 1024;
12
13
  const IDENTIFIER_PATTERN = /^[a-z][a-z0-9_]*$/;
13
14
  const RESERVED_COLUMN_NAMES = new Set([
14
15
  'local_id',
@@ -33,6 +34,7 @@ function defineReplicaEntity() {
33
34
  table: definition.table,
34
35
  sourceKey: definition.sourceKey,
35
36
  scope: definition.scope,
37
+ identity: definition.identity,
36
38
  fields: definition.fields,
37
39
  });
38
40
  };
@@ -78,13 +80,99 @@ function nullable(column) {
78
80
  function serverId() {
79
81
  return { kind: 'serverId' };
80
82
  }
83
+ /** Declares an ordered composite natural key without changing the immutable local UUID. */
84
+ function naturalKey(sourceKeys) {
85
+ return { kind: 'naturalKey', sourceKeys };
86
+ }
81
87
  /** Rejects a remote identity on a local-only projection before it reaches platform storage. */
82
88
  function assertOfflineReplicaServerId(schema, value) {
83
- const hasServerId = schema.fields.some((field) => field.policy === 'serverId');
84
- if (!hasServerId && value !== null) {
89
+ if (schema.identity.kind !== 'serverId' && value !== null) {
85
90
  throw new Error(`Offline replica source "${schema.sourceKey}" does not define a serverId field.`);
86
91
  }
87
92
  }
93
+ /** Extracts and validates an entity's natural key in declared component order. */
94
+ function offlineNaturalKeyFromValues(schema, values) {
95
+ if (schema.identity.kind !== 'naturalKey')
96
+ return null;
97
+ if (!isPlainObject$1(values)) {
98
+ throw new Error(`Offline replica values for "${schema.sourceKey}" must be a plain object.`);
99
+ }
100
+ return Object.fromEntries(schema.identity.sourceKeys.map((sourceKey) => {
101
+ const value = values[sourceKey];
102
+ const field = schema.fields.find((candidate) => candidate.sourceKey === sourceKey);
103
+ if ((field.storageKind === 'text' && typeof value !== 'string') ||
104
+ (field.storageKind === 'integer' && (typeof value !== 'number' || !Number.isSafeInteger(value) || !Number.isFinite(value)))) {
105
+ throw new Error(`Offline replica naturalKey field "${sourceKey}" has an invalid value.`);
106
+ }
107
+ if (typeof value === 'string')
108
+ assertNaturalKeyText(sourceKey, value);
109
+ return [sourceKey, value];
110
+ }));
111
+ }
112
+ /** Validates a supplied natural key and returns it in schema-declared order. */
113
+ function normalizeOfflineNaturalKey(schema, naturalKey) {
114
+ if (schema.identity.kind !== 'naturalKey') {
115
+ throw new Error(`Offline replica source "${schema.sourceKey}" does not define a naturalKey identity.`);
116
+ }
117
+ if (!isPlainObject$1(naturalKey)) {
118
+ throw new Error(`Offline replica naturalKey for "${schema.sourceKey}" must be a plain object.`);
119
+ }
120
+ const actualKeys = Object.keys(naturalKey);
121
+ if (actualKeys.length !== schema.identity.sourceKeys.length ||
122
+ actualKeys.some((key) => !schema.identity.sourceKeys.includes(key))) {
123
+ throw new Error(`Offline replica naturalKey for "${schema.sourceKey}" must contain exactly its declared fields.`);
124
+ }
125
+ return offlineNaturalKeyFromValues(schema, naturalKey);
126
+ }
127
+ /** Stable, type-tagged identity key used by web uniqueness and pull collapse. */
128
+ function canonicalOfflineRemoteIdentity(schema, identity) {
129
+ if (schema.identity.kind === 'serverId') {
130
+ if (!('serverId' in identity) || 'naturalKey' in identity) {
131
+ throw new Error(`Offline replica source "${schema.sourceKey}" requires serverId identity.`);
132
+ }
133
+ assertPositiveServerId(identity.serverId);
134
+ return `serverId:n:${identity.serverId}`;
135
+ }
136
+ if (schema.identity.kind === 'naturalKey') {
137
+ if (!('naturalKey' in identity) || 'serverId' in identity) {
138
+ throw new Error(`Offline replica source "${schema.sourceKey}" requires naturalKey identity.`);
139
+ }
140
+ const key = normalizeOfflineNaturalKey(schema, identity.naturalKey);
141
+ return `naturalKey:${JSON.stringify(schema.identity.sourceKeys.map((sourceKey) => {
142
+ const value = key[sourceKey];
143
+ return [sourceKey, typeof value === 'number' ? 'n' : 's', value];
144
+ }))}`;
145
+ }
146
+ throw new Error(`Offline replica source "${schema.sourceKey}" is local-only.`);
147
+ }
148
+ /** Enforces one immutable natural identity across optimistic and confirmed row values. */
149
+ function assertOfflineReplicaNaturalKeyBaseline(schema, values, confirmedValues) {
150
+ if (schema.identity.kind !== 'naturalKey' || confirmedValues === null)
151
+ return;
152
+ const current = canonicalOfflineRemoteIdentity(schema, { naturalKey: offlineNaturalKeyFromValues(schema, values) });
153
+ const confirmed = canonicalOfflineRemoteIdentity(schema, {
154
+ naturalKey: offlineNaturalKeyFromValues(schema, confirmedValues),
155
+ });
156
+ if (current !== confirmed) {
157
+ throw new Error(`Offline replica confirmedValues naturalKey must match values for "${schema.sourceKey}".`);
158
+ }
159
+ }
160
+ function assertPositiveServerId(value) {
161
+ if (!Number.isSafeInteger(value) || value <= 0) {
162
+ throw new Error('Offline replica serverId must be a positive integer.');
163
+ }
164
+ }
165
+ function assertNaturalKeyText(sourceKey, value) {
166
+ if (value.includes('\0')) {
167
+ throw new Error(`Offline replica naturalKey field "${sourceKey}" must not contain NUL.`);
168
+ }
169
+ if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(value)) {
170
+ throw new Error(`Offline replica naturalKey field "${sourceKey}" must contain well-formed Unicode.`);
171
+ }
172
+ if (new TextEncoder().encode(value).byteLength > MAX_OFFLINE_NATURAL_KEY_TEXT_BYTES) {
173
+ throw new Error(`Offline replica naturalKey field "${sourceKey}" must not exceed ${MAX_OFFLINE_NATURAL_KEY_TEXT_BYTES} UTF-8 bytes.`);
174
+ }
175
+ }
88
176
  /** Excludes a source property from SQLite while retaining it in the select shape. */
89
177
  function ignored(reason) {
90
178
  return { kind: 'ignored', reason };
@@ -96,22 +184,46 @@ function buildOfflineReplicaEntitySchema(definition) {
96
184
  const serverIdCount = sourceKeys.filter((sourceKey) => definition.fields[sourceKey]?.kind === 'serverId').length;
97
185
  if (serverIdCount > 1)
98
186
  throw new Error('Replica entity must define at most one serverId field.');
99
- const hasServerId = serverIdCount === 1;
100
187
  const fields = sourceKeys.map((sourceKey) => {
101
188
  const fieldDef = definition.fields[sourceKey];
102
189
  return materializeFieldDescriptor(sourceKey, fieldDef);
103
190
  });
104
- const createTableSql = buildCreateTableSql(definition.table, definition.scope, fields, hasServerId);
105
- const schemaFingerprintInput = buildSchemaFingerprintInput(definition.table, definition.sourceKey, definition.scope, fields, hasServerId);
191
+ const identity = materializeIdentity(definition.identity, fields);
192
+ const createTableSql = buildCreateTableSql(definition.table, definition.scope, fields, identity);
193
+ const schemaFingerprintInput = buildSchemaFingerprintInput(definition.table, definition.sourceKey, definition.scope, fields, identity);
106
194
  return {
107
195
  tableName: definition.table,
108
196
  sourceKey: definition.sourceKey,
109
197
  scope: definition.scope,
198
+ identity,
110
199
  fields,
111
200
  createTableSql,
112
201
  schemaFingerprintInput,
113
202
  };
114
203
  }
204
+ function materializeIdentity(definition, fields) {
205
+ const serverField = fields.find((field) => field.policy === 'serverId');
206
+ if (definition && serverField)
207
+ throw new Error('Replica entity cannot define both serverId and naturalKey identity.');
208
+ if (serverField)
209
+ return { kind: 'serverId', sourceKeys: [serverField.sourceKey] };
210
+ if (!definition)
211
+ return { kind: 'localOnly', sourceKeys: [] };
212
+ if (definition.sourceKeys.length === 0)
213
+ throw new Error('Replica naturalKey must contain at least one source field.');
214
+ if (new Set(definition.sourceKeys).size !== definition.sourceKeys.length) {
215
+ throw new Error('Replica naturalKey source fields must be unique.');
216
+ }
217
+ for (const sourceKey of definition.sourceKeys) {
218
+ const field = fields.find((candidate) => candidate.sourceKey === sourceKey);
219
+ if (!field)
220
+ throw new Error(`Replica naturalKey field "${sourceKey}" is not defined.`);
221
+ if (field.policy !== 'column' || field.nullable || !['text', 'integer'].includes(field.storageKind ?? '')) {
222
+ throw new Error(`Replica naturalKey field "${sourceKey}" must be a required text or integer column.`);
223
+ }
224
+ }
225
+ return { kind: 'naturalKey', sourceKeys: [...definition.sourceKeys] };
226
+ }
115
227
  function materializeFieldDescriptor(sourceKey, fieldDef) {
116
228
  if (fieldDef.kind === 'ignored') {
117
229
  if (!fieldDef.reason.trim())
@@ -152,12 +264,12 @@ function materializeFieldDescriptor(sourceKey, fieldDef) {
152
264
  ignoredReason: null,
153
265
  };
154
266
  }
155
- function buildCreateTableSql(tableName, scope, fields, hasServerId) {
267
+ function buildCreateTableSql(tableName, scope, fields, identity) {
156
268
  const columnLines = ['local_id TEXT NOT NULL', '_offline_user_id INTEGER NOT NULL'];
157
269
  if (scope === 'partition') {
158
270
  columnLines.push('_offline_scope_id TEXT NOT NULL');
159
271
  }
160
- if (hasServerId) {
272
+ if (identity.kind === 'serverId') {
161
273
  columnLines.push('server_id INTEGER');
162
274
  }
163
275
  columnLines.push('_offline_confirmed_json TEXT', '_offline_server_revision_json TEXT', '_offline_sync_state TEXT NOT NULL', '_offline_fetched_at INTEGER NOT NULL');
@@ -169,13 +281,18 @@ function buildCreateTableSql(tableName, scope, fields, hasServerId) {
169
281
  columnLines.push(`${field.sqliteColumnName} ${field.affinity}${nullability}`);
170
282
  }
171
283
  const statements = [`CREATE TABLE IF NOT EXISTS ${tableName} (\n ${columnLines.join(',\n ')},\n PRIMARY KEY (local_id)\n)`];
172
- if (hasServerId) {
284
+ if (identity.kind === 'serverId') {
173
285
  const indexColumns = scope === 'partition' ? '_offline_user_id, _offline_scope_id, server_id' : '_offline_user_id, server_id';
174
286
  statements.push(`CREATE UNIQUE INDEX IF NOT EXISTS uq_${tableName}_server_id ON ${tableName} (${indexColumns}) WHERE server_id IS NOT NULL`);
175
287
  }
288
+ else if (identity.kind === 'naturalKey') {
289
+ const naturalKeyColumns = identity.sourceKeys.map((sourceKey) => fields.find((field) => field.sourceKey === sourceKey).sqliteColumnName);
290
+ const indexColumns = ['_offline_user_id', ...(scope === 'partition' ? ['_offline_scope_id'] : []), ...naturalKeyColumns].join(', ');
291
+ statements.push(`CREATE UNIQUE INDEX IF NOT EXISTS uq_${tableName}_natural_key ON ${tableName} (${indexColumns})`);
292
+ }
176
293
  return statements;
177
294
  }
178
- function buildSchemaFingerprintInput(tableName, sourceKey, scope, fields, hasServerId) {
295
+ function buildSchemaFingerprintInput(tableName, sourceKey, scope, fields, identity) {
179
296
  const fieldParts = fields.map((field) => {
180
297
  if (field.policy === 'ignored') {
181
298
  return `${field.sourceKey}:ignored:${field.ignoredReason ?? ''}`;
@@ -189,7 +306,9 @@ function buildSchemaFingerprintInput(tableName, sourceKey, scope, fields, hasSer
189
306
  `table=${tableName}`,
190
307
  `source=${sourceKey}`,
191
308
  `scope=${scope}`,
192
- `hasServerId=${hasServerId ? '1' : '0'}`,
309
+ ...(identity.kind === 'naturalKey'
310
+ ? [`hasServerId=0`, `identity=naturalKey:${identity.sourceKeys.join(',')}`, 'identityCodec=v1']
311
+ : [`hasServerId=${identity.kind === 'serverId' ? '1' : '0'}`]),
193
312
  `fields=${fieldParts.join(';')}`,
194
313
  ].join('|');
195
314
  }
@@ -555,7 +674,7 @@ const OFFLINE_COMMAND_EXECUTOR = new InjectionToken('OFFLINE_COMMAND_EXECUTOR');
555
674
  const OFFLINE_SYNC_CONTEXT = new InjectionToken('OFFLINE_SYNC_CONTEXT');
556
675
 
557
676
  /** Current durable storage schema used by both web and native repositories. */
558
- const OFFLINE_SCHEMA_VERSION = 4;
677
+ const OFFLINE_SCHEMA_VERSION = 5;
559
678
  /** DI token for the selected platform repository. */
560
679
  const OFFLINE_REPOSITORY = new InjectionToken('OFFLINE_REPOSITORY');
561
680
  /** Selects encrypted SQLite on native platforms and Ionic Storage on web. */
@@ -609,6 +728,16 @@ class IonicOfflineRepository {
609
728
  });
610
729
  }
611
730
  async getReplicaRow(scope, sourceKey, localId) {
731
+ await this.initialize();
732
+ await this.#writes;
733
+ const schema = this.#resolveReplicaEntitySchema(sourceKey);
734
+ const rows = await this.#readRecord(ROWS_KEY);
735
+ const row = rows[this.#rowKey(scope, sourceKey, localId)];
736
+ if (!row || (row.visibility ?? 'present') === 'pending_delete')
737
+ return null;
738
+ return this.#rowForScope(row, schema, scope);
739
+ }
740
+ async getReplicaRowIncludingPendingDelete(scope, sourceKey, localId) {
612
741
  await this.initialize();
613
742
  await this.#writes;
614
743
  const schema = this.#resolveReplicaEntitySchema(sourceKey);
@@ -625,6 +754,8 @@ class IonicOfflineRepository {
625
754
  .filter((row) => {
626
755
  if (row.sourceKey !== sourceKey || row.userId !== scope.userId)
627
756
  return false;
757
+ if ((row.visibility ?? 'present') === 'pending_delete')
758
+ return false;
628
759
  return schema.scope === 'partition' ? row.scopeId === scope.scopeId : true;
629
760
  })
630
761
  .map((row) => this.#rowForScope(row, schema, scope))
@@ -644,6 +775,22 @@ class IonicOfflineRepository {
644
775
  });
645
776
  return row ? this.#rowForScope(row, schema, scope) : null;
646
777
  }
778
+ async getReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
779
+ await this.initialize();
780
+ await this.#writes;
781
+ const schema = this.#resolveReplicaEntitySchema(sourceKey);
782
+ const canonical = canonicalOfflineRemoteIdentity(schema, identity);
783
+ const rows = await this.#readRecord(ROWS_KEY);
784
+ const row = Object.values(rows).find((candidate) => {
785
+ if (candidate.sourceKey !== sourceKey || candidate.userId !== scope.userId)
786
+ return false;
787
+ if (schema.scope === 'partition' && candidate.scopeId !== scope.scopeId)
788
+ return false;
789
+ const candidateIdentity = this.#rowRemoteIdentity(schema, candidate);
790
+ return candidateIdentity !== null && canonicalOfflineRemoteIdentity(schema, candidateIdentity) === canonical;
791
+ });
792
+ return row ? this.#rowForScope(row, schema, scope) : null;
793
+ }
647
794
  async getReplicaCursor(scope) {
648
795
  await this.initialize();
649
796
  await this.#writes;
@@ -720,7 +867,18 @@ class IonicOfflineRepository {
720
867
  return write;
721
868
  }
722
869
  async #migrate() {
723
- const metadata = await this.#storage.get(METADATA_KEY);
870
+ let metadata = await this.#storage.get(METADATA_KEY);
871
+ if (metadata?.schemaVersion === 4) {
872
+ const rows = await this.#readRecord(ROWS_KEY);
873
+ const commands = await this.#readRecord(OUTBOX_KEY);
874
+ await this.#storage.set(ROWS_KEY, Object.fromEntries(Object.entries(rows).map(([key, row]) => [key, { ...row, visibility: row.visibility ?? 'present' }])));
875
+ await this.#storage.set(OUTBOX_KEY, Object.fromEntries(Object.entries(commands).map(([key, command]) => [
876
+ key,
877
+ { ...command, replicaMutation: command.replicaMutation ?? 'upsert' },
878
+ ])));
879
+ metadata = { ...metadata, schemaVersion: OFFLINE_SCHEMA_VERSION };
880
+ await this.#storage.set(METADATA_KEY, metadata);
881
+ }
724
882
  if (metadata?.schemaVersion !== undefined && metadata.schemaVersion !== OFFLINE_SCHEMA_VERSION) {
725
883
  throw new Error(`Unsupported offline storage schema version ${metadata.schemaVersion}; expected ${OFFLINE_SCHEMA_VERSION}. ` +
726
884
  'A lossless core schema migration is required before this database can be opened.');
@@ -879,7 +1037,10 @@ class IonicOfflineRepository {
879
1037
  ]);
880
1038
  const identityCheckRows = { ...rows };
881
1039
  for (const row of transaction.putRows ?? []) {
882
- this.#assertUniqueReplicaServerId(identityCheckRows, row);
1040
+ const existing = identityCheckRows[this.#rowKey(row, row.sourceKey, row.localId)];
1041
+ if (existing)
1042
+ this.#assertReplicaIdentityAssignment(existing, row);
1043
+ this.#assertUniqueReplicaIdentity(identityCheckRows, row);
883
1044
  identityCheckRows[this.#rowKey(row, row.sourceKey, row.localId)] = row;
884
1045
  }
885
1046
  if (journal)
@@ -939,13 +1100,14 @@ class IonicOfflineRepository {
939
1100
  return `${scope.userId}:${partition}:${sourceKey}:${localId}`;
940
1101
  }
941
1102
  #rowForScope(row, schema, scope) {
942
- return schema.scope === 'user' ? { ...row, scopeId: scope.scopeId } : row;
1103
+ const normalized = { ...row, visibility: row.visibility ?? 'present' };
1104
+ return schema.scope === 'user' ? { ...normalized, scopeId: scope.scopeId } : normalized;
943
1105
  }
944
1106
  #cursorKey(scope) {
945
1107
  return `${scope.userId}:${scope.scopeId}`;
946
1108
  }
947
1109
  #schemaHasServerId(schema) {
948
- return schema.fields.some((field) => field.policy === 'serverId');
1110
+ return schema.identity.kind === 'serverId';
949
1111
  }
950
1112
  #validateReplicaRow(row) {
951
1113
  const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
@@ -953,24 +1115,58 @@ class IonicOfflineRepository {
953
1115
  encodeOfflineReplicaValues(schema, row.values);
954
1116
  if (row.confirmedValues !== null)
955
1117
  encodeOfflineReplicaValues(schema, row.confirmedValues);
1118
+ assertOfflineReplicaNaturalKeyBaseline(schema, row.values, row.confirmedValues);
956
1119
  }
957
- #assertUniqueReplicaServerId(rows, incoming) {
958
- if (incoming.serverId === null)
959
- return;
1120
+ #assertUniqueReplicaIdentity(rows, incoming) {
960
1121
  const schema = this.#resolveReplicaEntitySchema(incoming.sourceKey);
1122
+ const identity = this.#rowRemoteIdentity(schema, incoming);
1123
+ if (identity === null)
1124
+ return;
1125
+ const canonical = canonicalOfflineRemoteIdentity(schema, identity);
961
1126
  const incomingKey = this.#rowKey(incoming, incoming.sourceKey, incoming.localId);
962
1127
  const collision = Object.entries(rows).find(([key, row]) => {
963
1128
  if (key === incomingKey)
964
1129
  return false;
965
- if (row.userId !== incoming.userId || row.sourceKey !== incoming.sourceKey || row.serverId !== incoming.serverId) {
1130
+ if (row.userId !== incoming.userId || row.sourceKey !== incoming.sourceKey)
966
1131
  return false;
967
- }
968
- return schema.scope === 'user' || row.scopeId === incoming.scopeId;
1132
+ if (schema.scope === 'partition' && row.scopeId !== incoming.scopeId)
1133
+ return false;
1134
+ const rowIdentity = this.#rowRemoteIdentity(schema, row);
1135
+ return rowIdentity !== null && canonicalOfflineRemoteIdentity(schema, rowIdentity) === canonical;
969
1136
  });
970
1137
  if (collision) {
971
- throw new Error(`Offline replica serverId ${String(incoming.serverId)} is already mapped to localId ${collision[1].localId}.`);
1138
+ if (schema.identity.kind === 'serverId') {
1139
+ throw new Error(`Offline replica serverId ${String(incoming.serverId)} is already mapped to localId ${collision[1].localId}.`);
1140
+ }
1141
+ throw new Error(`Offline replica remote identity is already mapped to localId ${collision[1].localId}.`);
1142
+ }
1143
+ }
1144
+ #assertReplicaIdentityAssignment(existing, incoming) {
1145
+ const schema = this.#resolveReplicaEntitySchema(incoming.sourceKey);
1146
+ if (schema.identity.kind === 'serverId') {
1147
+ if (existing.serverId !== null && existing.serverId !== incoming.serverId) {
1148
+ throw new Error(`Offline replica serverId is immutable: current=${existing.serverId}, incoming=${String(incoming.serverId)}.`);
1149
+ }
1150
+ return;
1151
+ }
1152
+ if (schema.identity.kind === 'naturalKey') {
1153
+ const current = canonicalOfflineRemoteIdentity(schema, {
1154
+ naturalKey: offlineNaturalKeyFromValues(schema, existing.values),
1155
+ });
1156
+ const next = canonicalOfflineRemoteIdentity(schema, {
1157
+ naturalKey: offlineNaturalKeyFromValues(schema, incoming.values),
1158
+ });
1159
+ if (current !== next)
1160
+ throw new Error(`Offline replica naturalKey is immutable for "${schema.sourceKey}".`);
972
1161
  }
973
1162
  }
1163
+ #rowRemoteIdentity(schema, row) {
1164
+ if (schema.identity.kind === 'serverId')
1165
+ return row.serverId === null ? null : { serverId: row.serverId };
1166
+ if (schema.identity.kind === 'naturalKey')
1167
+ return { naturalKey: offlineNaturalKeyFromValues(schema, row.values) };
1168
+ return null;
1169
+ }
974
1170
  #resolveReplicaEntitySchema(sourceKey) {
975
1171
  const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);
976
1172
  if (!schema)
@@ -1038,14 +1234,19 @@ class OfflineReplicaPullService {
1038
1234
  ? { userId: acknowledgedCommand.userId, scopeId: acknowledgedCommand.scopeId }
1039
1235
  : scope;
1040
1236
  const acknowledgedRow = acknowledgedCommand
1041
- ? await this.#repository.getReplicaRow(acknowledgedScope, change.sourceKey, acknowledgedCommand.aggregateLocalId)
1237
+ ? await (this.#repository.getReplicaRowIncludingPendingDelete?.(acknowledgedScope, change.sourceKey, acknowledgedCommand.aggregateLocalId) ??
1238
+ this.#repository.getReplicaRow(acknowledgedScope, change.sourceKey, acknowledgedCommand.aggregateLocalId))
1042
1239
  : null;
1043
1240
  if (acknowledgedCommand && !acknowledgedRow) {
1044
1241
  throw new Error(`Acknowledged command "${acknowledgedCommand.commandId}" has no local replica row.`);
1045
1242
  }
1046
- const serverRow = await this.#repository.getReplicaRowByServerId(scope, change.sourceKey, change.serverId);
1243
+ const identity = this.#identity(change);
1244
+ const serverRow = await this.#repository.getReplicaRowByRemoteIdentity(scope, change.sourceKey, identity);
1047
1245
  if (acknowledgedRow && serverRow && acknowledgedRow.localId !== serverRow.localId) {
1048
- throw new Error(`Server id ${change.serverId} is already mapped to another local replica row.`);
1246
+ if (identity.serverId !== undefined) {
1247
+ throw new Error(`Server id ${identity.serverId} is already mapped to another local replica row.`);
1248
+ }
1249
+ throw new Error(`Remote identity for "${change.sourceKey}" is already mapped to another local replica row.`);
1049
1250
  }
1050
1251
  const existing = acknowledgedRow ?? serverRow;
1051
1252
  const related = existing
@@ -1053,6 +1254,7 @@ class OfflineReplicaPullService {
1053
1254
  : [];
1054
1255
  const hasPending = related.length > 0;
1055
1256
  if (acknowledgedCommand) {
1257
+ this.#assertIdentityAssignment(schema, existing, identity);
1056
1258
  this.#applyAcknowledgement(change, existing, related, putRows, removeRows, putCommands, removeCommandIds);
1057
1259
  continue;
1058
1260
  }
@@ -1063,7 +1265,13 @@ class OfflineReplicaPullService {
1063
1265
  removeRows.push(existing);
1064
1266
  continue;
1065
1267
  }
1066
- putRows.push({ ...existing, serverRevision: change.serverRevision, syncState: 'conflict', fetchedAt: Date.now() });
1268
+ putRows.push({
1269
+ ...existing,
1270
+ confirmedValues: null,
1271
+ serverRevision: change.serverRevision,
1272
+ syncState: 'conflict',
1273
+ fetchedAt: Date.now(),
1274
+ });
1067
1275
  for (const command of related) {
1068
1276
  putCommands.set(command.commandId, { ...command, state: 'conflict', retryAt: null, lastErrorCode: 'remote_deleted' });
1069
1277
  }
@@ -1075,7 +1283,7 @@ class OfflineReplicaPullService {
1075
1283
  ...scope,
1076
1284
  sourceKey: change.sourceKey,
1077
1285
  localId: crypto.randomUUID(),
1078
- serverId: change.serverId,
1286
+ serverId: identity.serverId ?? null,
1079
1287
  values: confirmedValues,
1080
1288
  confirmedValues,
1081
1289
  serverRevision: change.serverRevision,
@@ -1141,9 +1349,21 @@ class OfflineReplicaPullService {
1141
1349
  if (typeof change['deleted'] !== 'boolean') {
1142
1350
  throw new Error(`${label}.deleted must be a boolean.`);
1143
1351
  }
1144
- const serverId = change['serverId'];
1145
- if (typeof serverId !== 'number' || !Number.isFinite(serverId) || !Number.isSafeInteger(serverId) || serverId <= 0) {
1146
- throw new Error(`${label}.serverId must be a positive integer.`);
1352
+ const schema = this.#entitySchema(change['sourceKey']);
1353
+ if (schema.identity.kind === 'serverId') {
1354
+ const serverId = change['serverId'];
1355
+ if (typeof serverId !== 'number' || !Number.isSafeInteger(serverId) || serverId <= 0) {
1356
+ throw new Error(`${label}.serverId must be a positive integer.`);
1357
+ }
1358
+ if (change['naturalKey'] !== undefined) {
1359
+ throw new Error(`${label}.naturalKey must be omitted for a serverId entity.`);
1360
+ }
1361
+ }
1362
+ try {
1363
+ canonicalOfflineRemoteIdentity(schema, change);
1364
+ }
1365
+ catch (error) {
1366
+ throw new Error(`${label} has invalid remote identity: ${error instanceof Error ? error.message : String(error)}`);
1147
1367
  }
1148
1368
  const revision = change['serverRevision'];
1149
1369
  if (typeof revision !== 'string' && (typeof revision !== 'number' || !Number.isFinite(revision))) {
@@ -1174,14 +1394,26 @@ class OfflineReplicaPullService {
1174
1394
  }
1175
1395
  #validatedValues(schema, change) {
1176
1396
  if (change.values === null) {
1177
- throw new Error(`Offline replica change "${change.sourceKey}"/${change.serverId} is missing values.`);
1397
+ throw new Error(change.serverId === undefined
1398
+ ? `Offline replica change "${change.sourceKey}" is missing values.`
1399
+ : `Offline replica change "${change.sourceKey}"/${change.serverId} is missing values.`);
1400
+ }
1401
+ const values = projectOfflineReplicaValues(schema, change.values);
1402
+ if (schema.identity.kind === 'naturalKey') {
1403
+ const expected = offlineNaturalKeyFromValues(schema, values);
1404
+ const incoming = normalizeOfflineNaturalKey(schema, change.naturalKey);
1405
+ if (canonicalOfflineRemoteIdentity(schema, { naturalKey: expected }) !==
1406
+ canonicalOfflineRemoteIdentity(schema, { naturalKey: incoming })) {
1407
+ throw new Error(`Offline replica change "${change.sourceKey}" naturalKey does not match values.`);
1408
+ }
1178
1409
  }
1179
- return projectOfflineReplicaValues(schema, change.values);
1410
+ return values;
1180
1411
  }
1181
1412
  #collapseChanges(changes) {
1182
1413
  const collapsed = new Map();
1183
1414
  for (const [ordinal, change] of changes.entries()) {
1184
- const key = `${change.sourceKey}:${change.serverId}`;
1415
+ const schema = this.#entitySchema(change.sourceKey);
1416
+ const key = `${change.sourceKey}:${canonicalOfflineRemoteIdentity(schema, this.#identity(change))}`;
1185
1417
  const previous = collapsed.get(key);
1186
1418
  const acknowledgedCommandIds = [...new Set([...(previous?.acknowledgedCommandIds ?? []), ...(change.acknowledgedCommandIds ?? [])])];
1187
1419
  const acknowledgementOrdinals = { ...(previous?.acknowledgementOrdinals ?? {}) };
@@ -1220,9 +1452,28 @@ class OfflineReplicaPullService {
1220
1452
  }
1221
1453
  if (change.deleted) {
1222
1454
  if (following.length > 0) {
1223
- putRows.push({ ...row, serverRevision: change.serverRevision, syncState: 'conflict', fetchedAt: Date.now() });
1224
- for (const command of following) {
1225
- putCommands.set(command.commandId, { ...command, state: 'conflict', lastErrorCode: 'remote_deleted' });
1455
+ if (acknowledgementSuperseded) {
1456
+ putRows.push({
1457
+ ...row,
1458
+ confirmedValues: null,
1459
+ serverRevision: change.serverRevision,
1460
+ syncState: 'conflict',
1461
+ fetchedAt: Date.now(),
1462
+ });
1463
+ for (const command of following) {
1464
+ putCommands.set(command.commandId, { ...command, state: 'conflict', lastErrorCode: 'remote_deleted' });
1465
+ }
1466
+ }
1467
+ else {
1468
+ putRows.push({
1469
+ ...row,
1470
+ values: following.at(-1).optimisticValue,
1471
+ confirmedValues: null,
1472
+ serverRevision: change.serverRevision,
1473
+ syncState: 'pending',
1474
+ visibility: following.at(-1).replicaMutation === 'delete' ? 'pending_delete' : 'present',
1475
+ fetchedAt: Date.now(),
1476
+ });
1226
1477
  }
1227
1478
  }
1228
1479
  else {
@@ -1232,20 +1483,33 @@ class OfflineReplicaPullService {
1232
1483
  }
1233
1484
  const schema = this.#entitySchema(change.sourceKey);
1234
1485
  const confirmedValues = this.#validatedValues(schema, change);
1235
- this.#assertServerIdAssignment(row.serverId, change.serverId);
1486
+ this.#assertIdentityAssignment(schema, row, this.#identity(change));
1236
1487
  putRows.push({
1237
1488
  ...row,
1238
- serverId: change.serverId,
1489
+ serverId: change.serverId ?? null,
1239
1490
  values: following.length > 0 ? following.at(-1).optimisticValue : confirmedValues,
1240
1491
  confirmedValues,
1241
1492
  serverRevision: change.serverRevision,
1242
1493
  fetchedAt: Date.now(),
1243
1494
  syncState: following.length > 0 ? (acknowledgementSuperseded ? 'conflict' : 'pending') : 'confirmed',
1495
+ visibility: following.at(-1)?.replicaMutation === 'delete' ? 'pending_delete' : 'present',
1244
1496
  });
1245
1497
  }
1246
- #assertServerIdAssignment(current, incoming) {
1247
- if (current !== null && current !== incoming) {
1248
- throw new Error(`Replica serverId is immutable: current=${current}, incoming=${incoming}.`);
1498
+ #identity(change) {
1499
+ return change.serverId !== undefined ? { serverId: change.serverId } : { naturalKey: change.naturalKey };
1500
+ }
1501
+ #assertIdentityAssignment(schema, row, incoming) {
1502
+ if (schema.identity.kind === 'serverId') {
1503
+ const serverId = incoming.serverId;
1504
+ if (row.serverId !== null && row.serverId !== serverId) {
1505
+ throw new Error(`Replica serverId is immutable: current=${row.serverId}, incoming=${serverId}.`);
1506
+ }
1507
+ return;
1508
+ }
1509
+ const current = offlineNaturalKeyFromValues(schema, row.values);
1510
+ if (current !== null &&
1511
+ canonicalOfflineRemoteIdentity(schema, { naturalKey: current }) !== canonicalOfflineRemoteIdentity(schema, incoming)) {
1512
+ throw new Error(`Replica naturalKey is immutable for "${schema.sourceKey}".`);
1249
1513
  }
1250
1514
  }
1251
1515
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineReplicaPullService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
@@ -1623,6 +1887,7 @@ class OfflineSyncService {
1623
1887
  operation: request.operation,
1624
1888
  payload: normalized.payload,
1625
1889
  optimisticValue,
1890
+ replicaMutation: request.replicaMutation ?? 'upsert',
1626
1891
  payloadHash: await this.#payloadHash(normalized.payload),
1627
1892
  baseRevision: normalized.baseRevision,
1628
1893
  state: 'pending',
@@ -1633,12 +1898,37 @@ class OfflineSyncService {
1633
1898
  };
1634
1899
  await this.#assertOutboxCapacity(userId, command);
1635
1900
  const entityType = this.#entityType(command);
1636
- const existing = await this.#repository.getReplicaRow(scope, entityType, aggregateLocalId);
1901
+ const schema = this.#entitySchema(entityType);
1902
+ if (request.replicaMutation === 'delete' && !this.#repository.getReplicaRowIncludingPendingDelete) {
1903
+ throw new Error('Offline repository does not support durable replica delete tombstones.');
1904
+ }
1905
+ const existing = await this.#getReplicaRowForSync(scope, entityType, aggregateLocalId);
1637
1906
  const initialServerId = this.#initialServerId(existing?.serverId ?? null, request.serverId);
1638
- if (initialServerId !== null) {
1639
- const mapped = await this.#repository.getReplicaRowByServerId(scope, entityType, initialServerId);
1907
+ const naturalKey = offlineNaturalKeyFromValues(schema, optimisticValue);
1908
+ const remoteIdentity = schema.identity.kind === 'serverId'
1909
+ ? initialServerId === null
1910
+ ? null
1911
+ : { serverId: initialServerId }
1912
+ : schema.identity.kind === 'naturalKey'
1913
+ ? { naturalKey: naturalKey }
1914
+ : null;
1915
+ if (schema.identity.kind === 'naturalKey' && request.serverId != null) {
1916
+ throw new Error(`Offline replica source "${entityType}" does not define a serverId field.`);
1917
+ }
1918
+ if (schema.identity.kind === 'naturalKey') {
1919
+ const canonicalValuesKey = canonicalOfflineRemoteIdentity(schema, remoteIdentity);
1920
+ if (existing &&
1921
+ canonicalOfflineRemoteIdentity(schema, { naturalKey: offlineNaturalKeyFromValues(schema, existing.values) }) !== canonicalValuesKey) {
1922
+ throw new Error(`Offline replica naturalKey is immutable and must match optimistic values for "${entityType}".`);
1923
+ }
1924
+ }
1925
+ if (remoteIdentity !== null) {
1926
+ const mapped = await this.#repository.getReplicaRowByRemoteIdentity(scope, entityType, remoteIdentity);
1640
1927
  if (mapped !== null && mapped.localId !== aggregateLocalId) {
1641
- throw new Error(`Offline replica serverId ${String(initialServerId)} is already mapped to localId ${mapped.localId}.`);
1928
+ if (remoteIdentity.serverId !== undefined) {
1929
+ throw new Error(`Offline replica serverId ${String(remoteIdentity.serverId)} is already mapped to localId ${mapped.localId}.`);
1930
+ }
1931
+ throw new Error(`Offline replica remote identity is already mapped to localId ${mapped.localId}.`);
1642
1932
  }
1643
1933
  }
1644
1934
  const optimisticRow = {
@@ -1651,6 +1941,7 @@ class OfflineSyncService {
1651
1941
  serverRevision: existing?.serverRevision ?? normalized.baseRevision,
1652
1942
  fetchedAt: Date.now(),
1653
1943
  syncState: 'pending',
1944
+ visibility: request.replicaMutation === 'delete' ? 'pending_delete' : 'present',
1654
1945
  };
1655
1946
  if (generation !== this.#generation) {
1656
1947
  throw new Error('Offline session changed before the command could be persisted');
@@ -1791,7 +2082,13 @@ class OfflineSyncService {
1791
2082
  throw new Error(`Offline replica row not found: ${sending.aggregateType}/${sending.aggregateLocalId}`);
1792
2083
  let result;
1793
2084
  try {
1794
- result = await this.#executor.execute(sending, { localId: row.localId, serverId: row.serverId });
2085
+ const schema = this.#entitySchema(row.sourceKey);
2086
+ const naturalKey = offlineNaturalKeyFromValues(schema, row.values);
2087
+ result = await this.#executor.execute(sending, {
2088
+ localId: row.localId,
2089
+ serverId: row.serverId,
2090
+ ...(naturalKey !== null ? { naturalKey } : {}),
2091
+ });
1795
2092
  }
1796
2093
  catch (error) {
1797
2094
  if (!this.#isCurrent(generation))
@@ -1816,7 +2113,7 @@ class OfflineSyncService {
1816
2113
  let baseRevision = request.baseRevision ?? null;
1817
2114
  let payload = request.payload;
1818
2115
  const aggregateLocalId = request.aggregateLocalId;
1819
- const row = await this.#repository.getReplicaRow(scope, this.#entityType(request), aggregateLocalId);
2116
+ const row = await this.#getReplicaRowForSync(scope, this.#entityType(request), aggregateLocalId);
1820
2117
  if (row?.serverRevision != null && row.serverRevision !== baseRevision) {
1821
2118
  const rebased = this.#executor.withServerRevision({ ...scope, ...request, aggregateLocalId, payload, baseRevision }, row.serverRevision);
1822
2119
  baseRevision = row.serverRevision;
@@ -1837,7 +2134,10 @@ class OfflineSyncService {
1837
2134
  throw new Error(`Offline replica row disappeared while completing command ${command.commandId}.`);
1838
2135
  }
1839
2136
  this.#assertServerRevision(result.serverRevision);
1840
- const confirmedValues = result.confirmedValues ?? command.optimisticValue;
2137
+ const removesReplica = result.removeReplica === true || command.replicaMutation === 'delete';
2138
+ const confirmedValues = removesReplica ? null : (result.confirmedValues ?? command.optimisticValue);
2139
+ const schema = this.#entitySchema(current.sourceKey);
2140
+ this.#assertCommandResultIdentity(schema, current, result);
1841
2141
  const serverId = this.#resolvedServerId(current.serverId, result.serverId);
1842
2142
  const row = {
1843
2143
  ...current,
@@ -1847,12 +2147,13 @@ class OfflineSyncService {
1847
2147
  serverRevision: revision ?? current.serverRevision,
1848
2148
  fetchedAt: Date.now(),
1849
2149
  syncState: rebased.length > 0 ? 'pending' : 'confirmed',
2150
+ visibility: rebased.at(-1)?.replicaMutation === 'delete' ? 'pending_delete' : 'present',
1850
2151
  };
1851
2152
  if (!this.#isCurrent(generation))
1852
2153
  return;
1853
2154
  await this.#repository.transactReplica({
1854
- putRows: result.removeReplica ? undefined : [row],
1855
- removeRows: result.removeReplica ? [current] : undefined,
2155
+ putRows: removesReplica && rebased.length === 0 ? undefined : [row],
2156
+ removeRows: removesReplica && rebased.length === 0 ? [current] : undefined,
1856
2157
  putCommands: rebased,
1857
2158
  removeCommandIds: [command.commandId],
1858
2159
  });
@@ -1860,7 +2161,11 @@ class OfflineSyncService {
1860
2161
  async #rowForCommand(command) {
1861
2162
  const scope = { userId: command.userId, scopeId: command.scopeId };
1862
2163
  const entityType = this.#entityType(command);
1863
- return this.#repository.getReplicaRow(scope, entityType, command.aggregateLocalId);
2164
+ return this.#getReplicaRowForSync(scope, entityType, command.aggregateLocalId);
2165
+ }
2166
+ #getReplicaRowForSync(scope, sourceKey, localId) {
2167
+ return (this.#repository.getReplicaRowIncludingPendingDelete?.(scope, sourceKey, localId) ??
2168
+ this.#repository.getReplicaRow(scope, sourceKey, localId));
1864
2169
  }
1865
2170
  #replicaState(state) {
1866
2171
  if (state === 'blocked_auth' || state === 'rejected' || state === 'conflict')
@@ -1870,6 +2175,12 @@ class OfflineSyncService {
1870
2175
  #entityType(command) {
1871
2176
  return this.#hooks.entityType(command);
1872
2177
  }
2178
+ #entitySchema(sourceKey) {
2179
+ const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);
2180
+ if (!schema)
2181
+ throw new Error(`Unknown offline replica source key "${sourceKey}".`);
2182
+ return schema;
2183
+ }
1873
2184
  async #discardCommands(discarded) {
1874
2185
  const all = await this.#readKnownCommands();
1875
2186
  const discardedIds = new Set(discarded.map((command) => command.commandId));
@@ -1891,6 +2202,7 @@ class OfflineSyncService {
1891
2202
  ...row,
1892
2203
  values: remaining.length > 0 ? remaining.at(-1).optimisticValue : row.confirmedValues,
1893
2204
  syncState: remaining.length > 0 ? 'pending' : 'confirmed',
2205
+ visibility: remaining.at(-1)?.replicaMutation === 'delete' ? 'pending_delete' : 'present',
1894
2206
  });
1895
2207
  }
1896
2208
  }
@@ -1951,6 +2263,23 @@ class OfflineSyncService {
1951
2263
  #initialServerId(current, incoming) {
1952
2264
  return incoming === null || incoming === undefined ? current : this.#resolvedServerId(current, incoming);
1953
2265
  }
2266
+ #assertCommandResultIdentity(schema, current, result) {
2267
+ if (schema.identity.kind === 'naturalKey' && result.serverId !== undefined) {
2268
+ throw new Error(`Offline command returned serverId for naturalKey source "${schema.sourceKey}".`);
2269
+ }
2270
+ if (schema.identity.kind !== 'serverId' && result.serverId !== undefined) {
2271
+ throw new Error(`Offline command returned serverId for source "${schema.sourceKey}" without serverId identity.`);
2272
+ }
2273
+ if (schema.identity.kind === 'naturalKey') {
2274
+ const confirmedValues = result.confirmedValues ?? current.values;
2275
+ const currentKey = offlineNaturalKeyFromValues(schema, current.values);
2276
+ const confirmedKey = offlineNaturalKeyFromValues(schema, confirmedValues);
2277
+ if (canonicalOfflineRemoteIdentity(schema, { naturalKey: currentKey }) !==
2278
+ canonicalOfflineRemoteIdentity(schema, { naturalKey: confirmedKey })) {
2279
+ throw new Error(`Offline replica naturalKey is immutable for "${schema.sourceKey}".`);
2280
+ }
2281
+ }
2282
+ }
1954
2283
  async #discoverScopes(generation = this.#generation) {
1955
2284
  const session = await this.#context.getSession();
1956
2285
  if (!this.#isCurrent(generation))
@@ -2392,6 +2721,7 @@ const SCHEMA = [
2392
2721
  operation TEXT NOT NULL,
2393
2722
  payload_json TEXT NOT NULL,
2394
2723
  optimistic_value_json TEXT NOT NULL,
2724
+ replica_mutation TEXT NOT NULL DEFAULT 'upsert',
2395
2725
  payload_hash TEXT NOT NULL,
2396
2726
  base_revision_json TEXT,
2397
2727
  state TEXT NOT NULL,
@@ -2452,10 +2782,22 @@ class SqliteOfflineRepository {
2452
2782
  }
2453
2783
  const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
2454
2784
  const row = rows[0];
2455
- if (!row)
2785
+ if (!row || (row['_offline_visibility'] ?? 'present') === 'pending_delete')
2456
2786
  return null;
2457
2787
  return this.#replicaRowFromSqliteRow(schema, scope, sourceKey, localId, row);
2458
2788
  }
2789
+ async getReplicaRowIncludingPendingDelete(scope, sourceKey, localId) {
2790
+ const schema = this.#resolveReplicaEntitySchema(sourceKey);
2791
+ const predicates = ['local_id = ?', '_offline_user_id = ?'];
2792
+ const values = [localId, scope.userId];
2793
+ if (schema.scope === 'partition') {
2794
+ predicates.push('_offline_scope_id = ?');
2795
+ values.push(scope.scopeId);
2796
+ }
2797
+ const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
2798
+ const row = rows[0];
2799
+ return row ? this.#replicaRowFromSqliteRow(schema, scope, sourceKey, localId, row) : null;
2800
+ }
2459
2801
  async getReplicaRows(scope, sourceKey) {
2460
2802
  const schema = this.#resolveReplicaEntitySchema(sourceKey);
2461
2803
  const predicates = ['_offline_user_id = ?'];
@@ -2465,7 +2807,9 @@ class SqliteOfflineRepository {
2465
2807
  values.push(scope.scopeId);
2466
2808
  }
2467
2809
  const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')} ORDER BY local_id ASC`, values);
2468
- return rows.map((row) => this.#replicaRowFromSqliteRow(schema, scope, sourceKey, this.#string(row['local_id']), row));
2810
+ return rows
2811
+ .filter((row) => (row['_offline_visibility'] ?? 'present') !== 'pending_delete')
2812
+ .map((row) => this.#replicaRowFromSqliteRow(schema, scope, sourceKey, this.#string(row['local_id']), row));
2469
2813
  }
2470
2814
  async getReplicaRowByServerId(scope, sourceKey, serverId) {
2471
2815
  const schema = this.#resolveReplicaEntitySchema(sourceKey);
@@ -2483,6 +2827,30 @@ class SqliteOfflineRepository {
2483
2827
  return null;
2484
2828
  return this.#replicaRowFromSqliteRow(schema, scope, sourceKey, this.#string(row['local_id']), row);
2485
2829
  }
2830
+ async getReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
2831
+ const schema = this.#resolveReplicaEntitySchema(sourceKey);
2832
+ canonicalOfflineRemoteIdentity(schema, identity);
2833
+ if (schema.identity.kind === 'serverId') {
2834
+ return this.getReplicaRowByServerId(scope, sourceKey, identity.serverId);
2835
+ }
2836
+ const naturalKey = normalizeOfflineNaturalKey(schema, identity.naturalKey);
2837
+ const predicates = ['_offline_user_id = ?'];
2838
+ const values = [scope.userId];
2839
+ if (schema.scope === 'partition') {
2840
+ predicates.push('_offline_scope_id = ?');
2841
+ values.push(scope.scopeId);
2842
+ }
2843
+ for (const sourceKeyPart of schema.identity.sourceKeys) {
2844
+ const field = schema.fields.find((candidate) => candidate.sourceKey === sourceKeyPart);
2845
+ predicates.push(`${field.sqliteColumnName} = ?`);
2846
+ values.push(naturalKey[sourceKeyPart]);
2847
+ }
2848
+ const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
2849
+ const row = rows[0];
2850
+ if (!row)
2851
+ return null;
2852
+ return this.#replicaRowFromSqliteRow(schema, scope, sourceKey, this.#string(row['local_id']), row);
2853
+ }
2486
2854
  async getReplicaCursor(scope) {
2487
2855
  const rows = await this.#query('SELECT cursor FROM offline_replica_cursors WHERE user_id = ? AND scope_id = ?', [
2488
2856
  scope.userId,
@@ -2568,12 +2936,21 @@ class SqliteOfflineRepository {
2568
2936
  if (!commandColumns.some((column) => column['name'] === 'optimistic_value_json')) {
2569
2937
  await this.#execute(databaseId, 'ALTER TABLE offline_sync_commands ADD COLUMN optimistic_value_json TEXT');
2570
2938
  }
2939
+ if (!commandColumns.some((column) => column['name'] === 'replica_mutation')) {
2940
+ await this.#execute(databaseId, "ALTER TABLE offline_sync_commands ADD COLUMN replica_mutation TEXT NOT NULL DEFAULT 'upsert'");
2941
+ }
2571
2942
  // Keep this repair outside the ADD-column branch so a process/database
2572
2943
  // failure after ALTER but before backfill is retried on every open.
2573
2944
  await this.#execute(databaseId, 'UPDATE offline_sync_commands SET optimistic_value_json = payload_json WHERE optimistic_value_json IS NULL');
2574
2945
  await this.#execute(databaseId, `INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, NULL)
2575
2946
  ON CONFLICT(id) DO UPDATE SET schema_version = excluded.schema_version`, [OFFLINE_SCHEMA_VERSION]);
2576
2947
  await this.#initializeReplicaSchema(databaseId);
2948
+ for (const entity of this.#options.replicaSchema.entities) {
2949
+ const columns = await this.#queryDatabase(databaseId, `PRAGMA table_info(${entity.tableName})`);
2950
+ if (!columns.some((column) => column['name'] === '_offline_visibility')) {
2951
+ await this.#execute(databaseId, `ALTER TABLE ${entity.tableName} ADD COLUMN _offline_visibility TEXT NOT NULL DEFAULT 'present'`);
2952
+ }
2953
+ }
2577
2954
  }
2578
2955
  async #initializeReplicaSchema(databaseId) {
2579
2956
  const bundle = this.#options.replicaSchema;
@@ -2677,6 +3054,7 @@ class SqliteOfflineRepository {
2677
3054
  operation: this.#string(row['operation']),
2678
3055
  payload: this.#parse(row['payload_json']),
2679
3056
  optimisticValue: this.#parse(row['optimistic_value_json']),
3057
+ replicaMutation: this.#string(row['replica_mutation']),
2680
3058
  payloadHash: this.#string(row['payload_hash']),
2681
3059
  baseRevision: this.#parseNullable(row['base_revision_json']),
2682
3060
  state: this.#string(row['state']),
@@ -2689,12 +3067,13 @@ class SqliteOfflineRepository {
2689
3067
  #putCommand(databaseId, command) {
2690
3068
  return this.#execute(databaseId, `INSERT INTO offline_sync_commands
2691
3069
  (command_id, user_id, scope_id, aggregate_type, aggregate_local_id, operation, payload_json, optimistic_value_json,
2692
- payload_hash, base_revision_json, state, attempts, retry_at, created_at, last_error_code)
2693
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
3070
+ replica_mutation, payload_hash, base_revision_json, state, attempts, retry_at, created_at, last_error_code)
3071
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2694
3072
  ON CONFLICT(command_id) DO UPDATE SET
2695
3073
  user_id = excluded.user_id, scope_id = excluded.scope_id, aggregate_type = excluded.aggregate_type,
2696
3074
  aggregate_local_id = excluded.aggregate_local_id, operation = excluded.operation, payload_json = excluded.payload_json,
2697
- optimistic_value_json = excluded.optimistic_value_json, payload_hash = excluded.payload_hash,
3075
+ optimistic_value_json = excluded.optimistic_value_json, replica_mutation = excluded.replica_mutation,
3076
+ payload_hash = excluded.payload_hash,
2698
3077
  base_revision_json = excluded.base_revision_json, state = excluded.state, attempts = excluded.attempts,
2699
3078
  retry_at = excluded.retry_at, created_at = excluded.created_at, last_error_code = excluded.last_error_code`, [
2700
3079
  command.commandId,
@@ -2705,6 +3084,7 @@ class SqliteOfflineRepository {
2705
3084
  command.operation,
2706
3085
  JSON.stringify(command.payload),
2707
3086
  JSON.stringify(command.optimisticValue),
3087
+ command.replicaMutation ?? 'upsert',
2708
3088
  command.payloadHash,
2709
3089
  this.#stringifyNullable(command.baseRevision),
2710
3090
  command.state,
@@ -2714,10 +3094,16 @@ class SqliteOfflineRepository {
2714
3094
  command.lastErrorCode,
2715
3095
  ]);
2716
3096
  }
2717
- #putReplicaRow(databaseId, row) {
3097
+ async #putReplicaRow(databaseId, row) {
2718
3098
  const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
2719
3099
  assertOfflineReplicaServerId(schema, row.serverId);
2720
3100
  const encoded = encodeOfflineReplicaValues(schema, row.values);
3101
+ if (row.confirmedValues !== null)
3102
+ encodeOfflineReplicaValues(schema, row.confirmedValues);
3103
+ assertOfflineReplicaNaturalKeyBaseline(schema, row.values, row.confirmedValues);
3104
+ const existing = await this.getReplicaRowIncludingPendingDelete(row, row.sourceKey, row.localId);
3105
+ if (existing)
3106
+ this.#assertReplicaIdentityAssignment(schema, existing, row);
2721
3107
  const confirmedValues = row.confirmedValues === null ? null : projectOfflineReplicaValues(schema, row.confirmedValues);
2722
3108
  const { sql, domainColumns } = this.#buildReplicaUpsertStatement(schema);
2723
3109
  const values = [
@@ -2728,10 +3114,11 @@ class SqliteOfflineRepository {
2728
3114
  confirmedValues === null ? null : JSON.stringify(confirmedValues),
2729
3115
  row.serverRevision == null ? null : JSON.stringify(row.serverRevision),
2730
3116
  row.syncState,
3117
+ row.visibility ?? 'present',
2731
3118
  row.fetchedAt,
2732
3119
  ...domainColumns.map((column) => encoded[column] ?? null),
2733
3120
  ];
2734
- return this.#execute(databaseId, sql, values);
3121
+ await this.#execute(databaseId, sql, values);
2735
3122
  }
2736
3123
  #removeReplicaRow(databaseId, key) {
2737
3124
  const schema = this.#resolveReplicaEntitySchema(key.sourceKey);
@@ -2758,8 +3145,8 @@ class SqliteOfflineRepository {
2758
3145
  insertColumns.push('server_id');
2759
3146
  updateSets.push('server_id = excluded.server_id');
2760
3147
  }
2761
- insertColumns.push('_offline_confirmed_json', '_offline_server_revision_json', '_offline_sync_state', '_offline_fetched_at');
2762
- updateSets.push('_offline_confirmed_json = excluded._offline_confirmed_json', '_offline_server_revision_json = excluded._offline_server_revision_json', '_offline_sync_state = excluded._offline_sync_state', '_offline_fetched_at = excluded._offline_fetched_at');
3148
+ insertColumns.push('_offline_confirmed_json', '_offline_server_revision_json', '_offline_sync_state', '_offline_visibility', '_offline_fetched_at');
3149
+ updateSets.push('_offline_confirmed_json = excluded._offline_confirmed_json', '_offline_server_revision_json = excluded._offline_server_revision_json', '_offline_sync_state = excluded._offline_sync_state', '_offline_visibility = excluded._offline_visibility', '_offline_fetched_at = excluded._offline_fetched_at');
2763
3150
  const domainColumns = [];
2764
3151
  for (const field of schema.fields) {
2765
3152
  if (field.policy !== 'column' || field.sqliteColumnName === null)
@@ -2787,6 +3174,7 @@ class SqliteOfflineRepository {
2787
3174
  serverRevision: this.#parseNullable(row['_offline_server_revision_json']),
2788
3175
  fetchedAt: this.#number(row['_offline_fetched_at']),
2789
3176
  syncState: this.#string(row['_offline_sync_state']),
3177
+ visibility: (row['_offline_visibility'] ?? 'present'),
2790
3178
  };
2791
3179
  }
2792
3180
  #resolveReplicaEntitySchema(sourceKey) {
@@ -2796,7 +3184,25 @@ class SqliteOfflineRepository {
2796
3184
  return schema;
2797
3185
  }
2798
3186
  #schemaHasServerId(schema) {
2799
- return schema.fields.some((field) => field.policy === 'serverId');
3187
+ return schema.identity.kind === 'serverId';
3188
+ }
3189
+ #assertReplicaIdentityAssignment(schema, existing, incoming) {
3190
+ if (schema.identity.kind === 'serverId') {
3191
+ if (existing.serverId !== null && existing.serverId !== incoming.serverId) {
3192
+ throw new Error(`Offline replica serverId is immutable: current=${existing.serverId}, incoming=${String(incoming.serverId)}.`);
3193
+ }
3194
+ return;
3195
+ }
3196
+ if (schema.identity.kind === 'naturalKey') {
3197
+ const current = canonicalOfflineRemoteIdentity(schema, {
3198
+ naturalKey: offlineNaturalKeyFromValues(schema, existing.values),
3199
+ });
3200
+ const next = canonicalOfflineRemoteIdentity(schema, {
3201
+ naturalKey: offlineNaturalKeyFromValues(schema, incoming.values),
3202
+ });
3203
+ if (current !== next)
3204
+ throw new Error(`Offline replica naturalKey is immutable for "${schema.sourceKey}".`);
3205
+ }
2800
3206
  }
2801
3207
  async #execute(databaseId, statement, values = []) {
2802
3208
  await this.#sqlite.execute({ databaseId, statement, values });
@@ -2944,5 +3350,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
2944
3350
  * Generated bundle index. Do not edit.
2945
3351
  */
2946
3352
 
2947
- export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCoordinatorService, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaPullService, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineSyncService, SqliteOfflineRepository, assertOfflineReplicaServerId, booleanColumn, createCommunitySqliteDriver, createOfflineAuthBridge, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, ignored, integer, isOfflineFallbackError, json, nullable, offlineInterceptor, projectOfflineReplicaValues, provideOffline, provideOfflineRequestPolicy, real, selectOfflineRepository, serverId, sha256OfflineReplicaSchema, text };
3353
+ export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCoordinatorService, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaPullService, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineSyncService, SqliteOfflineRepository, assertOfflineReplicaNaturalKeyBaseline, assertOfflineReplicaServerId, booleanColumn, canonicalOfflineRemoteIdentity, createCommunitySqliteDriver, createOfflineAuthBridge, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, ignored, integer, isOfflineFallbackError, json, naturalKey, normalizeOfflineNaturalKey, nullable, offlineInterceptor, offlineNaturalKeyFromValues, projectOfflineReplicaValues, provideOffline, provideOfflineRequestPolicy, real, selectOfflineRepository, serverId, sha256OfflineReplicaSchema, text };
2948
3354
  //# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map