@rdlabo/ionic-angular-kit 21.5.6 → 21.5.7

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
  }
@@ -644,6 +763,22 @@ class IonicOfflineRepository {
644
763
  });
645
764
  return row ? this.#rowForScope(row, schema, scope) : null;
646
765
  }
766
+ async getReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
767
+ await this.initialize();
768
+ await this.#writes;
769
+ const schema = this.#resolveReplicaEntitySchema(sourceKey);
770
+ const canonical = canonicalOfflineRemoteIdentity(schema, identity);
771
+ const rows = await this.#readRecord(ROWS_KEY);
772
+ const row = Object.values(rows).find((candidate) => {
773
+ if (candidate.sourceKey !== sourceKey || candidate.userId !== scope.userId)
774
+ return false;
775
+ if (schema.scope === 'partition' && candidate.scopeId !== scope.scopeId)
776
+ return false;
777
+ const candidateIdentity = this.#rowRemoteIdentity(schema, candidate);
778
+ return candidateIdentity !== null && canonicalOfflineRemoteIdentity(schema, candidateIdentity) === canonical;
779
+ });
780
+ return row ? this.#rowForScope(row, schema, scope) : null;
781
+ }
647
782
  async getReplicaCursor(scope) {
648
783
  await this.initialize();
649
784
  await this.#writes;
@@ -879,7 +1014,10 @@ class IonicOfflineRepository {
879
1014
  ]);
880
1015
  const identityCheckRows = { ...rows };
881
1016
  for (const row of transaction.putRows ?? []) {
882
- this.#assertUniqueReplicaServerId(identityCheckRows, row);
1017
+ const existing = identityCheckRows[this.#rowKey(row, row.sourceKey, row.localId)];
1018
+ if (existing)
1019
+ this.#assertReplicaIdentityAssignment(existing, row);
1020
+ this.#assertUniqueReplicaIdentity(identityCheckRows, row);
883
1021
  identityCheckRows[this.#rowKey(row, row.sourceKey, row.localId)] = row;
884
1022
  }
885
1023
  if (journal)
@@ -945,7 +1083,7 @@ class IonicOfflineRepository {
945
1083
  return `${scope.userId}:${scope.scopeId}`;
946
1084
  }
947
1085
  #schemaHasServerId(schema) {
948
- return schema.fields.some((field) => field.policy === 'serverId');
1086
+ return schema.identity.kind === 'serverId';
949
1087
  }
950
1088
  #validateReplicaRow(row) {
951
1089
  const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
@@ -953,24 +1091,58 @@ class IonicOfflineRepository {
953
1091
  encodeOfflineReplicaValues(schema, row.values);
954
1092
  if (row.confirmedValues !== null)
955
1093
  encodeOfflineReplicaValues(schema, row.confirmedValues);
1094
+ assertOfflineReplicaNaturalKeyBaseline(schema, row.values, row.confirmedValues);
956
1095
  }
957
- #assertUniqueReplicaServerId(rows, incoming) {
958
- if (incoming.serverId === null)
959
- return;
1096
+ #assertUniqueReplicaIdentity(rows, incoming) {
960
1097
  const schema = this.#resolveReplicaEntitySchema(incoming.sourceKey);
1098
+ const identity = this.#rowRemoteIdentity(schema, incoming);
1099
+ if (identity === null)
1100
+ return;
1101
+ const canonical = canonicalOfflineRemoteIdentity(schema, identity);
961
1102
  const incomingKey = this.#rowKey(incoming, incoming.sourceKey, incoming.localId);
962
1103
  const collision = Object.entries(rows).find(([key, row]) => {
963
1104
  if (key === incomingKey)
964
1105
  return false;
965
- if (row.userId !== incoming.userId || row.sourceKey !== incoming.sourceKey || row.serverId !== incoming.serverId) {
1106
+ if (row.userId !== incoming.userId || row.sourceKey !== incoming.sourceKey)
966
1107
  return false;
967
- }
968
- return schema.scope === 'user' || row.scopeId === incoming.scopeId;
1108
+ if (schema.scope === 'partition' && row.scopeId !== incoming.scopeId)
1109
+ return false;
1110
+ const rowIdentity = this.#rowRemoteIdentity(schema, row);
1111
+ return rowIdentity !== null && canonicalOfflineRemoteIdentity(schema, rowIdentity) === canonical;
969
1112
  });
970
1113
  if (collision) {
971
- throw new Error(`Offline replica serverId ${String(incoming.serverId)} is already mapped to localId ${collision[1].localId}.`);
1114
+ if (schema.identity.kind === 'serverId') {
1115
+ throw new Error(`Offline replica serverId ${String(incoming.serverId)} is already mapped to localId ${collision[1].localId}.`);
1116
+ }
1117
+ throw new Error(`Offline replica remote identity is already mapped to localId ${collision[1].localId}.`);
1118
+ }
1119
+ }
1120
+ #assertReplicaIdentityAssignment(existing, incoming) {
1121
+ const schema = this.#resolveReplicaEntitySchema(incoming.sourceKey);
1122
+ if (schema.identity.kind === 'serverId') {
1123
+ if (existing.serverId !== null && existing.serverId !== incoming.serverId) {
1124
+ throw new Error(`Offline replica serverId is immutable: current=${existing.serverId}, incoming=${String(incoming.serverId)}.`);
1125
+ }
1126
+ return;
1127
+ }
1128
+ if (schema.identity.kind === 'naturalKey') {
1129
+ const current = canonicalOfflineRemoteIdentity(schema, {
1130
+ naturalKey: offlineNaturalKeyFromValues(schema, existing.values),
1131
+ });
1132
+ const next = canonicalOfflineRemoteIdentity(schema, {
1133
+ naturalKey: offlineNaturalKeyFromValues(schema, incoming.values),
1134
+ });
1135
+ if (current !== next)
1136
+ throw new Error(`Offline replica naturalKey is immutable for "${schema.sourceKey}".`);
972
1137
  }
973
1138
  }
1139
+ #rowRemoteIdentity(schema, row) {
1140
+ if (schema.identity.kind === 'serverId')
1141
+ return row.serverId === null ? null : { serverId: row.serverId };
1142
+ if (schema.identity.kind === 'naturalKey')
1143
+ return { naturalKey: offlineNaturalKeyFromValues(schema, row.values) };
1144
+ return null;
1145
+ }
974
1146
  #resolveReplicaEntitySchema(sourceKey) {
975
1147
  const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);
976
1148
  if (!schema)
@@ -1043,9 +1215,13 @@ class OfflineReplicaPullService {
1043
1215
  if (acknowledgedCommand && !acknowledgedRow) {
1044
1216
  throw new Error(`Acknowledged command "${acknowledgedCommand.commandId}" has no local replica row.`);
1045
1217
  }
1046
- const serverRow = await this.#repository.getReplicaRowByServerId(scope, change.sourceKey, change.serverId);
1218
+ const identity = this.#identity(change);
1219
+ const serverRow = await this.#repository.getReplicaRowByRemoteIdentity(scope, change.sourceKey, identity);
1047
1220
  if (acknowledgedRow && serverRow && acknowledgedRow.localId !== serverRow.localId) {
1048
- throw new Error(`Server id ${change.serverId} is already mapped to another local replica row.`);
1221
+ if (identity.serverId !== undefined) {
1222
+ throw new Error(`Server id ${identity.serverId} is already mapped to another local replica row.`);
1223
+ }
1224
+ throw new Error(`Remote identity for "${change.sourceKey}" is already mapped to another local replica row.`);
1049
1225
  }
1050
1226
  const existing = acknowledgedRow ?? serverRow;
1051
1227
  const related = existing
@@ -1075,7 +1251,7 @@ class OfflineReplicaPullService {
1075
1251
  ...scope,
1076
1252
  sourceKey: change.sourceKey,
1077
1253
  localId: crypto.randomUUID(),
1078
- serverId: change.serverId,
1254
+ serverId: identity.serverId ?? null,
1079
1255
  values: confirmedValues,
1080
1256
  confirmedValues,
1081
1257
  serverRevision: change.serverRevision,
@@ -1141,9 +1317,21 @@ class OfflineReplicaPullService {
1141
1317
  if (typeof change['deleted'] !== 'boolean') {
1142
1318
  throw new Error(`${label}.deleted must be a boolean.`);
1143
1319
  }
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.`);
1320
+ const schema = this.#entitySchema(change['sourceKey']);
1321
+ if (schema.identity.kind === 'serverId') {
1322
+ const serverId = change['serverId'];
1323
+ if (typeof serverId !== 'number' || !Number.isSafeInteger(serverId) || serverId <= 0) {
1324
+ throw new Error(`${label}.serverId must be a positive integer.`);
1325
+ }
1326
+ if (change['naturalKey'] !== undefined) {
1327
+ throw new Error(`${label}.naturalKey must be omitted for a serverId entity.`);
1328
+ }
1329
+ }
1330
+ try {
1331
+ canonicalOfflineRemoteIdentity(schema, change);
1332
+ }
1333
+ catch (error) {
1334
+ throw new Error(`${label} has invalid remote identity: ${error instanceof Error ? error.message : String(error)}`);
1147
1335
  }
1148
1336
  const revision = change['serverRevision'];
1149
1337
  if (typeof revision !== 'string' && (typeof revision !== 'number' || !Number.isFinite(revision))) {
@@ -1174,14 +1362,26 @@ class OfflineReplicaPullService {
1174
1362
  }
1175
1363
  #validatedValues(schema, change) {
1176
1364
  if (change.values === null) {
1177
- throw new Error(`Offline replica change "${change.sourceKey}"/${change.serverId} is missing values.`);
1365
+ throw new Error(change.serverId === undefined
1366
+ ? `Offline replica change "${change.sourceKey}" is missing values.`
1367
+ : `Offline replica change "${change.sourceKey}"/${change.serverId} is missing values.`);
1368
+ }
1369
+ const values = projectOfflineReplicaValues(schema, change.values);
1370
+ if (schema.identity.kind === 'naturalKey') {
1371
+ const expected = offlineNaturalKeyFromValues(schema, values);
1372
+ const incoming = normalizeOfflineNaturalKey(schema, change.naturalKey);
1373
+ if (canonicalOfflineRemoteIdentity(schema, { naturalKey: expected }) !==
1374
+ canonicalOfflineRemoteIdentity(schema, { naturalKey: incoming })) {
1375
+ throw new Error(`Offline replica change "${change.sourceKey}" naturalKey does not match values.`);
1376
+ }
1178
1377
  }
1179
- return projectOfflineReplicaValues(schema, change.values);
1378
+ return values;
1180
1379
  }
1181
1380
  #collapseChanges(changes) {
1182
1381
  const collapsed = new Map();
1183
1382
  for (const [ordinal, change] of changes.entries()) {
1184
- const key = `${change.sourceKey}:${change.serverId}`;
1383
+ const schema = this.#entitySchema(change.sourceKey);
1384
+ const key = `${change.sourceKey}:${canonicalOfflineRemoteIdentity(schema, this.#identity(change))}`;
1185
1385
  const previous = collapsed.get(key);
1186
1386
  const acknowledgedCommandIds = [...new Set([...(previous?.acknowledgedCommandIds ?? []), ...(change.acknowledgedCommandIds ?? [])])];
1187
1387
  const acknowledgementOrdinals = { ...(previous?.acknowledgementOrdinals ?? {}) };
@@ -1232,10 +1432,10 @@ class OfflineReplicaPullService {
1232
1432
  }
1233
1433
  const schema = this.#entitySchema(change.sourceKey);
1234
1434
  const confirmedValues = this.#validatedValues(schema, change);
1235
- this.#assertServerIdAssignment(row.serverId, change.serverId);
1435
+ this.#assertIdentityAssignment(schema, row, this.#identity(change));
1236
1436
  putRows.push({
1237
1437
  ...row,
1238
- serverId: change.serverId,
1438
+ serverId: change.serverId ?? null,
1239
1439
  values: following.length > 0 ? following.at(-1).optimisticValue : confirmedValues,
1240
1440
  confirmedValues,
1241
1441
  serverRevision: change.serverRevision,
@@ -1243,9 +1443,21 @@ class OfflineReplicaPullService {
1243
1443
  syncState: following.length > 0 ? (acknowledgementSuperseded ? 'conflict' : 'pending') : 'confirmed',
1244
1444
  });
1245
1445
  }
1246
- #assertServerIdAssignment(current, incoming) {
1247
- if (current !== null && current !== incoming) {
1248
- throw new Error(`Replica serverId is immutable: current=${current}, incoming=${incoming}.`);
1446
+ #identity(change) {
1447
+ return change.serverId !== undefined ? { serverId: change.serverId } : { naturalKey: change.naturalKey };
1448
+ }
1449
+ #assertIdentityAssignment(schema, row, incoming) {
1450
+ if (schema.identity.kind === 'serverId') {
1451
+ const serverId = incoming.serverId;
1452
+ if (row.serverId !== null && row.serverId !== serverId) {
1453
+ throw new Error(`Replica serverId is immutable: current=${row.serverId}, incoming=${serverId}.`);
1454
+ }
1455
+ return;
1456
+ }
1457
+ const current = offlineNaturalKeyFromValues(schema, row.values);
1458
+ if (current !== null &&
1459
+ canonicalOfflineRemoteIdentity(schema, { naturalKey: current }) !== canonicalOfflineRemoteIdentity(schema, incoming)) {
1460
+ throw new Error(`Replica naturalKey is immutable for "${schema.sourceKey}".`);
1249
1461
  }
1250
1462
  }
1251
1463
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineReplicaPullService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
@@ -1633,12 +1845,34 @@ class OfflineSyncService {
1633
1845
  };
1634
1846
  await this.#assertOutboxCapacity(userId, command);
1635
1847
  const entityType = this.#entityType(command);
1848
+ const schema = this.#entitySchema(entityType);
1636
1849
  const existing = await this.#repository.getReplicaRow(scope, entityType, aggregateLocalId);
1637
1850
  const initialServerId = this.#initialServerId(existing?.serverId ?? null, request.serverId);
1638
- if (initialServerId !== null) {
1639
- const mapped = await this.#repository.getReplicaRowByServerId(scope, entityType, initialServerId);
1851
+ const naturalKey = offlineNaturalKeyFromValues(schema, optimisticValue);
1852
+ const remoteIdentity = schema.identity.kind === 'serverId'
1853
+ ? initialServerId === null
1854
+ ? null
1855
+ : { serverId: initialServerId }
1856
+ : schema.identity.kind === 'naturalKey'
1857
+ ? { naturalKey: naturalKey }
1858
+ : null;
1859
+ if (schema.identity.kind === 'naturalKey' && request.serverId != null) {
1860
+ throw new Error(`Offline replica source "${entityType}" does not define a serverId field.`);
1861
+ }
1862
+ if (schema.identity.kind === 'naturalKey') {
1863
+ const canonicalValuesKey = canonicalOfflineRemoteIdentity(schema, remoteIdentity);
1864
+ if (existing &&
1865
+ canonicalOfflineRemoteIdentity(schema, { naturalKey: offlineNaturalKeyFromValues(schema, existing.values) }) !== canonicalValuesKey) {
1866
+ throw new Error(`Offline replica naturalKey is immutable and must match optimistic values for "${entityType}".`);
1867
+ }
1868
+ }
1869
+ if (remoteIdentity !== null) {
1870
+ const mapped = await this.#repository.getReplicaRowByRemoteIdentity(scope, entityType, remoteIdentity);
1640
1871
  if (mapped !== null && mapped.localId !== aggregateLocalId) {
1641
- throw new Error(`Offline replica serverId ${String(initialServerId)} is already mapped to localId ${mapped.localId}.`);
1872
+ if (remoteIdentity.serverId !== undefined) {
1873
+ throw new Error(`Offline replica serverId ${String(remoteIdentity.serverId)} is already mapped to localId ${mapped.localId}.`);
1874
+ }
1875
+ throw new Error(`Offline replica remote identity is already mapped to localId ${mapped.localId}.`);
1642
1876
  }
1643
1877
  }
1644
1878
  const optimisticRow = {
@@ -1791,7 +2025,13 @@ class OfflineSyncService {
1791
2025
  throw new Error(`Offline replica row not found: ${sending.aggregateType}/${sending.aggregateLocalId}`);
1792
2026
  let result;
1793
2027
  try {
1794
- result = await this.#executor.execute(sending, { localId: row.localId, serverId: row.serverId });
2028
+ const schema = this.#entitySchema(row.sourceKey);
2029
+ const naturalKey = offlineNaturalKeyFromValues(schema, row.values);
2030
+ result = await this.#executor.execute(sending, {
2031
+ localId: row.localId,
2032
+ serverId: row.serverId,
2033
+ ...(naturalKey !== null ? { naturalKey } : {}),
2034
+ });
1795
2035
  }
1796
2036
  catch (error) {
1797
2037
  if (!this.#isCurrent(generation))
@@ -1838,6 +2078,8 @@ class OfflineSyncService {
1838
2078
  }
1839
2079
  this.#assertServerRevision(result.serverRevision);
1840
2080
  const confirmedValues = result.confirmedValues ?? command.optimisticValue;
2081
+ const schema = this.#entitySchema(current.sourceKey);
2082
+ this.#assertCommandResultIdentity(schema, current, result);
1841
2083
  const serverId = this.#resolvedServerId(current.serverId, result.serverId);
1842
2084
  const row = {
1843
2085
  ...current,
@@ -1870,6 +2112,12 @@ class OfflineSyncService {
1870
2112
  #entityType(command) {
1871
2113
  return this.#hooks.entityType(command);
1872
2114
  }
2115
+ #entitySchema(sourceKey) {
2116
+ const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);
2117
+ if (!schema)
2118
+ throw new Error(`Unknown offline replica source key "${sourceKey}".`);
2119
+ return schema;
2120
+ }
1873
2121
  async #discardCommands(discarded) {
1874
2122
  const all = await this.#readKnownCommands();
1875
2123
  const discardedIds = new Set(discarded.map((command) => command.commandId));
@@ -1951,6 +2199,23 @@ class OfflineSyncService {
1951
2199
  #initialServerId(current, incoming) {
1952
2200
  return incoming === null || incoming === undefined ? current : this.#resolvedServerId(current, incoming);
1953
2201
  }
2202
+ #assertCommandResultIdentity(schema, current, result) {
2203
+ if (schema.identity.kind === 'naturalKey' && result.serverId !== undefined) {
2204
+ throw new Error(`Offline command returned serverId for naturalKey source "${schema.sourceKey}".`);
2205
+ }
2206
+ if (schema.identity.kind !== 'serverId' && result.serverId !== undefined) {
2207
+ throw new Error(`Offline command returned serverId for source "${schema.sourceKey}" without serverId identity.`);
2208
+ }
2209
+ if (schema.identity.kind === 'naturalKey') {
2210
+ const confirmedValues = result.confirmedValues ?? current.values;
2211
+ const currentKey = offlineNaturalKeyFromValues(schema, current.values);
2212
+ const confirmedKey = offlineNaturalKeyFromValues(schema, confirmedValues);
2213
+ if (canonicalOfflineRemoteIdentity(schema, { naturalKey: currentKey }) !==
2214
+ canonicalOfflineRemoteIdentity(schema, { naturalKey: confirmedKey })) {
2215
+ throw new Error(`Offline replica naturalKey is immutable for "${schema.sourceKey}".`);
2216
+ }
2217
+ }
2218
+ }
1954
2219
  async #discoverScopes(generation = this.#generation) {
1955
2220
  const session = await this.#context.getSession();
1956
2221
  if (!this.#isCurrent(generation))
@@ -2483,6 +2748,30 @@ class SqliteOfflineRepository {
2483
2748
  return null;
2484
2749
  return this.#replicaRowFromSqliteRow(schema, scope, sourceKey, this.#string(row['local_id']), row);
2485
2750
  }
2751
+ async getReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
2752
+ const schema = this.#resolveReplicaEntitySchema(sourceKey);
2753
+ canonicalOfflineRemoteIdentity(schema, identity);
2754
+ if (schema.identity.kind === 'serverId') {
2755
+ return this.getReplicaRowByServerId(scope, sourceKey, identity.serverId);
2756
+ }
2757
+ const naturalKey = normalizeOfflineNaturalKey(schema, identity.naturalKey);
2758
+ const predicates = ['_offline_user_id = ?'];
2759
+ const values = [scope.userId];
2760
+ if (schema.scope === 'partition') {
2761
+ predicates.push('_offline_scope_id = ?');
2762
+ values.push(scope.scopeId);
2763
+ }
2764
+ for (const sourceKeyPart of schema.identity.sourceKeys) {
2765
+ const field = schema.fields.find((candidate) => candidate.sourceKey === sourceKeyPart);
2766
+ predicates.push(`${field.sqliteColumnName} = ?`);
2767
+ values.push(naturalKey[sourceKeyPart]);
2768
+ }
2769
+ const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
2770
+ const row = rows[0];
2771
+ if (!row)
2772
+ return null;
2773
+ return this.#replicaRowFromSqliteRow(schema, scope, sourceKey, this.#string(row['local_id']), row);
2774
+ }
2486
2775
  async getReplicaCursor(scope) {
2487
2776
  const rows = await this.#query('SELECT cursor FROM offline_replica_cursors WHERE user_id = ? AND scope_id = ?', [
2488
2777
  scope.userId,
@@ -2714,10 +3003,16 @@ class SqliteOfflineRepository {
2714
3003
  command.lastErrorCode,
2715
3004
  ]);
2716
3005
  }
2717
- #putReplicaRow(databaseId, row) {
3006
+ async #putReplicaRow(databaseId, row) {
2718
3007
  const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
2719
3008
  assertOfflineReplicaServerId(schema, row.serverId);
2720
3009
  const encoded = encodeOfflineReplicaValues(schema, row.values);
3010
+ if (row.confirmedValues !== null)
3011
+ encodeOfflineReplicaValues(schema, row.confirmedValues);
3012
+ assertOfflineReplicaNaturalKeyBaseline(schema, row.values, row.confirmedValues);
3013
+ const existing = await this.getReplicaRow(row, row.sourceKey, row.localId);
3014
+ if (existing)
3015
+ this.#assertReplicaIdentityAssignment(schema, existing, row);
2721
3016
  const confirmedValues = row.confirmedValues === null ? null : projectOfflineReplicaValues(schema, row.confirmedValues);
2722
3017
  const { sql, domainColumns } = this.#buildReplicaUpsertStatement(schema);
2723
3018
  const values = [
@@ -2731,7 +3026,7 @@ class SqliteOfflineRepository {
2731
3026
  row.fetchedAt,
2732
3027
  ...domainColumns.map((column) => encoded[column] ?? null),
2733
3028
  ];
2734
- return this.#execute(databaseId, sql, values);
3029
+ await this.#execute(databaseId, sql, values);
2735
3030
  }
2736
3031
  #removeReplicaRow(databaseId, key) {
2737
3032
  const schema = this.#resolveReplicaEntitySchema(key.sourceKey);
@@ -2796,7 +3091,25 @@ class SqliteOfflineRepository {
2796
3091
  return schema;
2797
3092
  }
2798
3093
  #schemaHasServerId(schema) {
2799
- return schema.fields.some((field) => field.policy === 'serverId');
3094
+ return schema.identity.kind === 'serverId';
3095
+ }
3096
+ #assertReplicaIdentityAssignment(schema, existing, incoming) {
3097
+ if (schema.identity.kind === 'serverId') {
3098
+ if (existing.serverId !== null && existing.serverId !== incoming.serverId) {
3099
+ throw new Error(`Offline replica serverId is immutable: current=${existing.serverId}, incoming=${String(incoming.serverId)}.`);
3100
+ }
3101
+ return;
3102
+ }
3103
+ if (schema.identity.kind === 'naturalKey') {
3104
+ const current = canonicalOfflineRemoteIdentity(schema, {
3105
+ naturalKey: offlineNaturalKeyFromValues(schema, existing.values),
3106
+ });
3107
+ const next = canonicalOfflineRemoteIdentity(schema, {
3108
+ naturalKey: offlineNaturalKeyFromValues(schema, incoming.values),
3109
+ });
3110
+ if (current !== next)
3111
+ throw new Error(`Offline replica naturalKey is immutable for "${schema.sourceKey}".`);
3112
+ }
2800
3113
  }
2801
3114
  async #execute(databaseId, statement, values = []) {
2802
3115
  await this.#sqlite.execute({ databaseId, statement, values });
@@ -2944,5 +3257,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
2944
3257
  * Generated bundle index. Do not edit.
2945
3258
  */
2946
3259
 
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 };
3260
+ 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
3261
  //# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map