@rdlabo/ionic-angular-kit 21.5.9 → 21.5.10

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.
@@ -26,7 +26,7 @@ const RESERVED_COLUMN_NAMES = new Set([
26
26
  *
27
27
  * Every key in `TSelect` must appear exactly once in `fields`, and column nullability
28
28
  * must match the select property nullability. An entity may map at most one field with
29
- * {@link serverId}; omit it for local-only projections that have no remote row identity.
29
+ * {@link generatedId}; omit it for local-only projections that have no remote row identity.
30
30
  */
31
31
  function defineReplicaEntity() {
32
32
  return function defineReplicaEntityConfig(definition) {
@@ -76,25 +76,31 @@ function nullable(column) {
76
76
  ...(column.columnName !== undefined ? { columnName: column.columnName } : {}),
77
77
  };
78
78
  }
79
- /** Maps a source property to the shared nullable `server_id` column. */
80
- function serverId() {
81
- return { kind: 'serverId' };
79
+ function generatedId(kind) {
80
+ return { kind: 'remoteId', affinity: kind === 'integer' ? 'INTEGER' : 'TEXT' };
82
81
  }
83
- /** Declares an ordered composite natural key without changing the immutable local UUID. */
82
+ /** Declares an ordered remote natural key used directly as the scoped SQLite primary key. */
84
83
  function naturalKey(sourceKeys) {
85
84
  return { kind: 'naturalKey', sourceKeys };
86
85
  }
87
- /** Rejects a remote identity on a local-only projection before it reaches platform storage. */
88
- function assertOfflineReplicaServerId(schema, value) {
89
- if (schema.identity.kind !== 'serverId' && value !== null) {
90
- throw new Error(`Offline replica source "${schema.sourceKey}" does not define a serverId field.`);
86
+ /** Declares a projection with a local UUID address and no Outbox identity. */
87
+ function localOnly() {
88
+ return { kind: 'localOnly' };
89
+ }
90
+ /** Rejects a generated remote id on a local-only or natural-key projection before it reaches platform storage. */
91
+ function assertOfflineReplicaGeneratedRemoteId(schema, value) {
92
+ if (schema.identity.kind !== 'generated' && value !== null) {
93
+ throw new Error(`Offline replica source "${schema.sourceKey}" does not define a generated remote id field.`);
91
94
  }
95
+ if (value === null)
96
+ return;
97
+ assertValidGeneratedRemoteId(schema, value);
92
98
  }
93
99
  /** Extracts and validates an entity's natural key in declared component order. */
94
100
  function offlineNaturalKeyFromValues(schema, values) {
95
101
  if (schema.identity.kind !== 'naturalKey')
96
102
  return null;
97
- if (!isPlainObject$1(values)) {
103
+ if (!isPlainObject$2(values)) {
98
104
  throw new Error(`Offline replica values for "${schema.sourceKey}" must be a plain object.`);
99
105
  }
100
106
  return Object.fromEntries(schema.identity.sourceKeys.map((sourceKey) => {
@@ -114,7 +120,7 @@ function normalizeOfflineNaturalKey(schema, naturalKey) {
114
120
  if (schema.identity.kind !== 'naturalKey') {
115
121
  throw new Error(`Offline replica source "${schema.sourceKey}" does not define a naturalKey identity.`);
116
122
  }
117
- if (!isPlainObject$1(naturalKey)) {
123
+ if (!isPlainObject$2(naturalKey)) {
118
124
  throw new Error(`Offline replica naturalKey for "${schema.sourceKey}" must be a plain object.`);
119
125
  }
120
126
  const actualKeys = Object.keys(naturalKey);
@@ -126,15 +132,15 @@ function normalizeOfflineNaturalKey(schema, naturalKey) {
126
132
  }
127
133
  /** Stable, type-tagged identity key used by web uniqueness and pull collapse. */
128
134
  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.`);
135
+ if (schema.identity.kind === 'generated') {
136
+ if (!('remoteId' in identity) || 'naturalKey' in identity) {
137
+ throw new Error(`Offline replica source "${schema.sourceKey}" requires generated remote id identity.`);
132
138
  }
133
- assertPositiveServerId(identity.serverId);
134
- return `serverId:n:${identity.serverId}`;
139
+ assertValidGeneratedRemoteId(schema, identity.remoteId);
140
+ return typeof identity.remoteId === 'string' ? `remoteId:s:${identity.remoteId}` : `remoteId:n:${identity.remoteId}`;
135
141
  }
136
142
  if (schema.identity.kind === 'naturalKey') {
137
- if (!('naturalKey' in identity) || 'serverId' in identity) {
143
+ if (!('naturalKey' in identity) || 'remoteId' in identity) {
138
144
  throw new Error(`Offline replica source "${schema.sourceKey}" requires naturalKey identity.`);
139
145
  }
140
146
  const key = normalizeOfflineNaturalKey(schema, identity.naturalKey);
@@ -157,10 +163,20 @@ function assertOfflineReplicaNaturalKeyBaseline(schema, values, confirmedValues)
157
163
  throw new Error(`Offline replica confirmedValues naturalKey must match values for "${schema.sourceKey}".`);
158
164
  }
159
165
  }
160
- function assertPositiveServerId(value) {
161
- if (!Number.isSafeInteger(value) || value <= 0) {
162
- throw new Error('Offline replica serverId must be a positive integer.');
166
+ function assertValidGeneratedRemoteId(schema, value) {
167
+ if (schema.identity.kind !== 'generated') {
168
+ throw new Error(`Offline replica source "${schema.sourceKey}" does not define a generated remote id field.`);
163
169
  }
170
+ if (schema.identity.affinity === 'INTEGER') {
171
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) {
172
+ throw new Error('Offline replica generated remote id must be a positive integer.');
173
+ }
174
+ return;
175
+ }
176
+ if (typeof value !== 'string' || value.length === 0) {
177
+ throw new Error('Offline replica generated remote id must be a non-empty string.');
178
+ }
179
+ assertNaturalKeyText('remoteId', value);
164
180
  }
165
181
  function assertNaturalKeyText(sourceKey, value) {
166
182
  if (value.includes('\0')) {
@@ -181,9 +197,9 @@ function buildOfflineReplicaEntitySchema(definition) {
181
197
  validateIdentifier(definition.table, 'table');
182
198
  validateIdentifier(definition.sourceKey, 'source key');
183
199
  const sourceKeys = Object.keys(definition.fields).sort();
184
- const serverIdCount = sourceKeys.filter((sourceKey) => definition.fields[sourceKey]?.kind === 'serverId').length;
185
- if (serverIdCount > 1)
186
- throw new Error('Replica entity must define at most one serverId field.');
200
+ const remoteIdCount = sourceKeys.filter((sourceKey) => definition.fields[sourceKey]?.kind === 'remoteId').length;
201
+ if (remoteIdCount > 1)
202
+ throw new Error('Replica entity must define at most one remoteId field.');
187
203
  const fields = sourceKeys.map((sourceKey) => {
188
204
  const fieldDef = definition.fields[sourceKey];
189
205
  return materializeFieldDescriptor(sourceKey, fieldDef);
@@ -202,12 +218,14 @@ function buildOfflineReplicaEntitySchema(definition) {
202
218
  };
203
219
  }
204
220
  function materializeIdentity(definition, fields) {
205
- const serverField = fields.find((field) => field.policy === 'serverId');
221
+ const serverField = fields.find((field) => field.policy === 'remoteId');
206
222
  if (definition && serverField)
207
- throw new Error('Replica entity cannot define both serverId and naturalKey identity.');
223
+ throw new Error('Replica entity cannot combine a generated id field with another identity.');
208
224
  if (serverField)
209
- return { kind: 'serverId', sourceKeys: [serverField.sourceKey] };
225
+ return { kind: 'generated', sourceKeys: [serverField.sourceKey], affinity: serverField.affinity };
210
226
  if (!definition)
227
+ throw new Error('Replica entity without a generated id field must declare identity explicitly.');
228
+ if (definition.kind === 'localOnly')
211
229
  return { kind: 'localOnly', sourceKeys: [] };
212
230
  if (definition.sourceKeys.length === 0)
213
231
  throw new Error('Replica naturalKey must contain at least one source field.');
@@ -238,12 +256,12 @@ function materializeFieldDescriptor(sourceKey, fieldDef) {
238
256
  ignoredReason: fieldDef.reason,
239
257
  };
240
258
  }
241
- if (fieldDef.kind === 'serverId') {
259
+ if (fieldDef.kind === 'remoteId') {
242
260
  return {
243
261
  sourceKey,
244
- policy: 'serverId',
262
+ policy: 'remoteId',
245
263
  sqliteColumnName: 'server_id',
246
- affinity: 'INTEGER',
264
+ affinity: fieldDef.affinity,
247
265
  storageKind: null,
248
266
  nullable: true,
249
267
  ignoredReason: null,
@@ -265,14 +283,17 @@ function materializeFieldDescriptor(sourceKey, fieldDef) {
265
283
  };
266
284
  }
267
285
  function buildCreateTableSql(tableName, scope, fields, identity) {
268
- const columnLines = ['local_id TEXT NOT NULL', '_offline_user_id INTEGER NOT NULL'];
286
+ const columnLines = ['_offline_user_id TEXT NOT NULL'];
269
287
  if (scope === 'partition') {
270
288
  columnLines.push('_offline_scope_id TEXT NOT NULL');
271
289
  }
272
- if (identity.kind === 'serverId') {
273
- columnLines.push('server_id INTEGER');
290
+ if (identity.kind === 'generated') {
291
+ columnLines.push('local_id TEXT NOT NULL', `server_id ${identity.affinity}`);
292
+ }
293
+ else if (identity.kind === 'localOnly') {
294
+ columnLines.push('local_id TEXT NOT NULL');
274
295
  }
275
- columnLines.push('_offline_confirmed_json TEXT', '_offline_server_revision_json TEXT', '_offline_sync_state TEXT NOT NULL', '_offline_fetched_at INTEGER NOT NULL');
296
+ columnLines.push('_offline_confirmed_json TEXT', '_offline_server_revision_json TEXT', '_offline_sync_state TEXT NOT NULL', "_offline_visibility TEXT NOT NULL DEFAULT 'present'", '_offline_fetched_at INTEGER NOT NULL');
276
297
  for (const field of fields) {
277
298
  if (field.policy !== 'column') {
278
299
  continue;
@@ -280,16 +301,20 @@ function buildCreateTableSql(tableName, scope, fields, identity) {
280
301
  const nullability = field.nullable ? '' : ' NOT NULL';
281
302
  columnLines.push(`${field.sqliteColumnName} ${field.affinity}${nullability}`);
282
303
  }
283
- const statements = [`CREATE TABLE IF NOT EXISTS ${tableName} (\n ${columnLines.join(',\n ')},\n PRIMARY KEY (local_id)\n)`];
284
- if (identity.kind === 'serverId') {
304
+ const pkColumns = [
305
+ '_offline_user_id',
306
+ ...(scope === 'partition' ? ['_offline_scope_id'] : []),
307
+ ...(identity.kind === 'naturalKey'
308
+ ? identity.sourceKeys.map((sourceKey) => fields.find((field) => field.sourceKey === sourceKey).sqliteColumnName)
309
+ : ['local_id']),
310
+ ];
311
+ const statements = [
312
+ `CREATE TABLE IF NOT EXISTS ${tableName} (\n ${columnLines.join(',\n ')},\n PRIMARY KEY (${pkColumns.join(', ')})\n)`,
313
+ ];
314
+ if (identity.kind === 'generated') {
285
315
  const indexColumns = scope === 'partition' ? '_offline_user_id, _offline_scope_id, server_id' : '_offline_user_id, server_id';
286
316
  statements.push(`CREATE UNIQUE INDEX IF NOT EXISTS uq_${tableName}_server_id ON ${tableName} (${indexColumns}) WHERE server_id IS NOT NULL`);
287
317
  }
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
- }
293
318
  return statements;
294
319
  }
295
320
  function buildSchemaFingerprintInput(tableName, sourceKey, scope, fields, identity) {
@@ -297,8 +322,8 @@ function buildSchemaFingerprintInput(tableName, sourceKey, scope, fields, identi
297
322
  if (field.policy === 'ignored') {
298
323
  return `${field.sourceKey}:ignored:${field.ignoredReason ?? ''}`;
299
324
  }
300
- if (field.policy === 'serverId') {
301
- return `${field.sourceKey}:serverId:server_id:INTEGER:nullable`;
325
+ if (field.policy === 'remoteId') {
326
+ return `${field.sourceKey}:remoteId:server_id:${field.affinity}:nullable`;
302
327
  }
303
328
  return `${field.sourceKey}:column:${field.sqliteColumnName}:${field.affinity}:${field.storageKind}:${field.nullable ? 'nullable' : 'required'}`;
304
329
  });
@@ -307,8 +332,10 @@ function buildSchemaFingerprintInput(tableName, sourceKey, scope, fields, identi
307
332
  `source=${sourceKey}`,
308
333
  `scope=${scope}`,
309
334
  ...(identity.kind === 'naturalKey'
310
- ? [`hasServerId=0`, `identity=naturalKey:${identity.sourceKeys.join(',')}`, 'identityCodec=v1']
311
- : [`hasServerId=${identity.kind === 'serverId' ? '1' : '0'}`]),
335
+ ? [`identity=naturalKey:${identity.sourceKeys.join(',')}`, 'identityCodec=v2']
336
+ : identity.kind === 'generated'
337
+ ? [`identity=generated:${identity.sourceKeys[0]}:${identity.affinity}`, 'identityCodec=v2']
338
+ : ['identity=localOnly', 'identityCodec=v2']),
312
339
  `fields=${fieldParts.join(';')}`,
313
340
  ].join('|');
314
341
  }
@@ -328,10 +355,10 @@ function toSnakeCase(value) {
328
355
  *
329
356
  * Only {@link OfflineReplicaFieldPolicy} `column` fields are emitted, keyed by
330
357
  * {@link OfflineReplicaFieldDescriptor.sqliteColumnName} in descriptor order.
331
- * Source properties mapped as `serverId` or `ignored` may be present but are not encoded.
358
+ * Source properties mapped as `remoteId` or `ignored` may be present but are not encoded.
332
359
  */
333
360
  function encodeOfflineReplicaValues(schema, values) {
334
- if (!isPlainObject$1(values)) {
361
+ if (!isPlainObject$2(values)) {
335
362
  throw new Error('Replica row values must be a plain object.');
336
363
  }
337
364
  const sourceValues = values;
@@ -377,7 +404,7 @@ function encodeOfflineReplicaValues(schema, values) {
377
404
  * present in `row` but are not decoded.
378
405
  */
379
406
  function decodeOfflineReplicaValues(schema, row) {
380
- if (!isPlainObject$1(row)) {
407
+ if (!isPlainObject$2(row)) {
381
408
  throw new Error('Replica SQLite row must be a plain object.');
382
409
  }
383
410
  const decoded = {};
@@ -410,13 +437,13 @@ function decodeOfflineReplicaValues(schema, row) {
410
437
  /**
411
438
  * Validates a source-model row and returns the canonical domain projection persisted by every repository.
412
439
  *
413
- * Fields mapped as `serverId` or `ignored` are intentionally omitted. This keeps web and native row shapes
414
- * identical; the server identifier remains available through the replica row's dedicated `serverId` field.
440
+ * Fields mapped as `remoteId` or `ignored` are intentionally omitted. This keeps web and native row shapes
441
+ * identical; the server identifier remains available through the replica row's dedicated `remoteId` field.
415
442
  */
416
443
  function projectOfflineReplicaValues(schema, values) {
417
444
  return decodeOfflineReplicaValues(schema, encodeOfflineReplicaValues(schema, values));
418
445
  }
419
- function isPlainObject$1(value) {
446
+ function isPlainObject$2(value) {
420
447
  if (value === null || typeof value !== 'object') {
421
448
  return false;
422
449
  }
@@ -653,28 +680,170 @@ function assertPositiveInteger(value, label) {
653
680
  }
654
681
  }
655
682
 
683
+ /** Type-tagged SQLite/web key; numeric 7 and text "7" never share a boundary. */
684
+ function canonicalOfflinePrincipalId(value) {
685
+ if (typeof value === 'number') {
686
+ if (!Number.isSafeInteger(value) || !Number.isFinite(value)) {
687
+ throw new Error('Offline principal id number must be a finite safe integer.');
688
+ }
689
+ return `n:${value}`;
690
+ }
691
+ if (value.length === 0)
692
+ throw new Error('Offline principal id string must not be empty.');
693
+ return `s:${JSON.stringify(value)}`;
694
+ }
695
+ /** Decodes a principal previously persisted by {@link canonicalOfflinePrincipalId}. */
696
+ function parseOfflinePrincipalId(value) {
697
+ if (value.startsWith('n:')) {
698
+ const numberValue = Number(value.slice(2));
699
+ if (!Number.isSafeInteger(numberValue))
700
+ throw new Error('Stored offline principal id is invalid.');
701
+ return numberValue;
702
+ }
703
+ if (value.startsWith('s:')) {
704
+ const stringValue = JSON.parse(value.slice(2));
705
+ if (typeof stringValue !== 'string' || stringValue.length === 0)
706
+ throw new Error('Stored offline principal id is invalid.');
707
+ return stringValue;
708
+ }
709
+ throw new Error('Stored offline principal id has an unknown codec.');
710
+ }
711
+ /** Stable storage key for one outbox or replica row identity. */
712
+ function canonicalOfflineCommandIdentity(identity) {
713
+ if (identity.kind === 'generated') {
714
+ assertOfflineLocalId(identity.localId);
715
+ return `generated:${identity.localId}`;
716
+ }
717
+ return `natural:${canonicalOfflineNaturalKeyIdentity(identity.naturalKey)}`;
718
+ }
719
+ /** Stable storage key for one materialized replica row identity. */
720
+ function canonicalOfflineReplicaIdentity(identity) {
721
+ if (identity.kind === 'generated') {
722
+ assertOfflineLocalId(identity.localId);
723
+ return `generated:${identity.localId}`;
724
+ }
725
+ if (identity.kind === 'local') {
726
+ assertOfflineLocalId(identity.localId);
727
+ return `local:${identity.localId}`;
728
+ }
729
+ return `natural:${canonicalOfflineNaturalKeyIdentity(identity.naturalKey)}`;
730
+ }
731
+ /** JSON persisted in SQLite/web outbox rows. */
732
+ function serializeOfflineCommandIdentity(identity) {
733
+ canonicalOfflineCommandIdentity(identity);
734
+ return JSON.stringify(identity);
735
+ }
736
+ /** Parses durable outbox identity JSON. */
737
+ function parseOfflineCommandIdentity(value) {
738
+ if (!isPlainObject$1(value))
739
+ throw new Error('Offline command identity must be a plain object.');
740
+ if (value['kind'] === 'generated') {
741
+ assertOfflineLocalId(value['localId']);
742
+ return { kind: 'generated', localId: value['localId'] };
743
+ }
744
+ if (value['kind'] === 'natural') {
745
+ if (!isPlainObject$1(value['naturalKey']))
746
+ throw new Error('Offline natural command identity requires naturalKey.');
747
+ return { kind: 'natural', naturalKey: value['naturalKey'] };
748
+ }
749
+ throw new Error('Offline command identity must be generated or natural.');
750
+ }
751
+ /** Builds a generated replica identity. */
752
+ function offlineGeneratedReplicaIdentity(localId, remoteId) {
753
+ assertOfflineLocalId(localId);
754
+ return { kind: 'generated', localId, remoteId };
755
+ }
756
+ /** Validates a durable local row id before it can enter either storage backend. */
757
+ function assertOfflineLocalId(value) {
758
+ if (typeof value !== 'string' ||
759
+ value.length === 0 ||
760
+ value.includes('\0') ||
761
+ value !== value.normalize('NFC') ||
762
+ new TextEncoder().encode(value).byteLength > 255) {
763
+ throw new Error('Offline localId must be a non-empty normalized string of at most 255 UTF-8 bytes without NUL.');
764
+ }
765
+ }
766
+ /** Builds a natural replica identity from current domain values. */
767
+ function offlineNaturalReplicaIdentity(schema, values) {
768
+ return { kind: 'natural', naturalKey: offlineNaturalKeyFromValues(schema, values) };
769
+ }
770
+ /** Converts a materialized replica identity into an outbox address. */
771
+ function commandIdentityFromReplicaIdentity(identity) {
772
+ if (identity.kind === 'generated')
773
+ return { kind: 'generated', localId: identity.localId };
774
+ if (identity.kind === 'local') {
775
+ throw new Error('Local-only replica rows cannot be added to the Outbox.');
776
+ }
777
+ return { kind: 'natural', naturalKey: identity.naturalKey };
778
+ }
779
+ /** Converts a materialized row identity into its immutable repository address. */
780
+ function replicaAddressFromIdentity(identity) {
781
+ if (identity.kind === 'natural')
782
+ return { kind: 'natural', naturalKey: identity.naturalKey };
783
+ return { kind: identity.kind, localId: identity.localId };
784
+ }
785
+ /** Whether a command identity addresses the given replica row. */
786
+ function commandIdentityMatchesReplicaRow(schema, row, commandIdentity) {
787
+ if (commandIdentity.kind === 'generated') {
788
+ return row.identity.kind === 'generated' && row.identity.localId === commandIdentity.localId;
789
+ }
790
+ if (row.identity.kind !== 'natural')
791
+ return false;
792
+ return (canonicalOfflineRemoteIdentity(schema, { naturalKey: row.identity.naturalKey }) ===
793
+ canonicalOfflineRemoteIdentity(schema, { naturalKey: normalizeOfflineNaturalKey(schema, commandIdentity.naturalKey) }));
794
+ }
795
+ /** Remote identity used by pull reconciliation and uniqueness checks. */
796
+ function offlineReplicaRemoteIdentity(schema, identity) {
797
+ if (schema.identity.kind === 'generated') {
798
+ return identity.kind === 'generated' && identity.remoteId !== null ? { remoteId: identity.remoteId } : null;
799
+ }
800
+ if (schema.identity.kind === 'naturalKey') {
801
+ return identity.kind === 'natural' ? { naturalKey: identity.naturalKey } : null;
802
+ }
803
+ return null;
804
+ }
805
+ function canonicalOfflineNaturalKeyIdentity(naturalKey) {
806
+ return JSON.stringify(Object.keys(naturalKey)
807
+ .sort()
808
+ .map((key) => {
809
+ const value = naturalKey[key];
810
+ return [key, typeof value === 'number' ? 'n' : 's', value];
811
+ }));
812
+ }
813
+ function isPlainObject$1(value) {
814
+ if (value === null || typeof value !== 'object')
815
+ return false;
816
+ const prototype = Object.getPrototypeOf(value);
817
+ return prototype === Object.prototype || prototype === null;
818
+ }
819
+
656
820
  /** DI token for the application-provided explicit replica pull transport. */
657
821
  const OFFLINE_REPLICA_PULLER = new InjectionToken('OFFLINE_REPLICA_PULLER');
658
822
 
659
823
  /** DI token for product-independent offline persistence settings. */
660
824
  const OFFLINE_KIT_OPTIONS = new InjectionToken('OFFLINE_KIT_OPTIONS');
661
825
 
662
- const DEFAULT_OFFLINE_COMMAND_HOOKS = {
663
- entityType: (command) => command.aggregateType,
664
- };
665
- /** DI token for optional product-specific synchronization hooks. */
666
- const OFFLINE_COMMAND_HOOKS = new InjectionToken('OFFLINE_COMMAND_HOOKS', {
667
- providedIn: 'root',
668
- factory: () => DEFAULT_OFFLINE_COMMAND_HOOKS,
669
- });
670
-
671
826
  /** DI token for the product-specific command transport adapter. */
672
827
  const OFFLINE_COMMAND_EXECUTOR = new InjectionToken('OFFLINE_COMMAND_EXECUTOR');
673
828
  /** DI token for authenticated synchronization context. */
674
829
  const OFFLINE_SYNC_CONTEXT = new InjectionToken('OFFLINE_SYNC_CONTEXT');
830
+ /** Resolves the transport target from a replica row. */
831
+ function offlineCommandTargetFromReplicaRow(row) {
832
+ if (row.identity.kind === 'natural')
833
+ return { kind: 'natural', naturalKey: row.identity.naturalKey };
834
+ if (row.identity.kind === 'local')
835
+ throw new Error('Local-only replica rows cannot be synchronized.');
836
+ return { kind: 'generated', localId: row.identity.localId, remoteId: row.identity.remoteId };
837
+ }
838
+ /** Resolves a command lookup identity from an enqueue request identity. */
839
+ function offlineCommandLookupIdentity(identity) {
840
+ if (identity.kind === 'generated')
841
+ return { kind: 'generated', localId: identity.localId };
842
+ return { kind: 'natural', naturalKey: identity.naturalKey };
843
+ }
675
844
 
676
845
  /** Current durable storage schema used by both web and native repositories. */
677
- const OFFLINE_SCHEMA_VERSION = 5;
846
+ const OFFLINE_SCHEMA_VERSION = 1;
678
847
  /** DI token for the selected platform repository. */
679
848
  const OFFLINE_REPOSITORY = new InjectionToken('OFFLINE_REPOSITORY');
680
849
  /** Selects encrypted SQLite on native platforms and Ionic Storage on web. */
@@ -718,31 +887,31 @@ class IonicOfflineRepository {
718
887
  await this.initialize();
719
888
  await this.#writes;
720
889
  const manifests = await this.#readRecord(SESSION_MANIFESTS_KEY);
721
- return manifests[String(userId)] ?? null;
890
+ return manifests[canonicalOfflinePrincipalId(userId)] ?? null;
722
891
  }
723
892
  async putSessionManifest(userId, value) {
724
893
  await this.initialize();
725
894
  await this.#mutateRecord(SESSION_MANIFESTS_KEY, (manifests) => {
726
- manifests[String(userId)] = value;
895
+ manifests[canonicalOfflinePrincipalId(userId)] = value;
727
896
  return manifests;
728
897
  });
729
898
  }
730
- async getReplicaRow(scope, sourceKey, localId) {
899
+ async getReplicaRow(scope, sourceKey, identity) {
731
900
  await this.initialize();
732
901
  await this.#writes;
733
902
  const schema = this.#resolveReplicaEntitySchema(sourceKey);
734
903
  const rows = await this.#readRecord(ROWS_KEY);
735
- const row = rows[this.#rowKey(scope, sourceKey, localId)];
904
+ const row = this.#findRowByAddress(rows, scope, sourceKey, schema, identity);
736
905
  if (!row || (row.visibility ?? 'present') === 'pending_delete')
737
906
  return null;
738
907
  return this.#rowForScope(row, schema, scope);
739
908
  }
740
- async getReplicaRowIncludingPendingDelete(scope, sourceKey, localId) {
909
+ async getReplicaRowIncludingPendingDelete(scope, sourceKey, identity) {
741
910
  await this.initialize();
742
911
  await this.#writes;
743
912
  const schema = this.#resolveReplicaEntitySchema(sourceKey);
744
913
  const rows = await this.#readRecord(ROWS_KEY);
745
- const row = rows[this.#rowKey(scope, sourceKey, localId)];
914
+ const row = this.#findRowByAddress(rows, scope, sourceKey, schema, identity);
746
915
  return row ? this.#rowForScope(row, schema, scope) : null;
747
916
  }
748
917
  async getReplicaRows(scope, sourceKey) {
@@ -759,21 +928,12 @@ class IonicOfflineRepository {
759
928
  return schema.scope === 'partition' ? row.scopeId === scope.scopeId : true;
760
929
  })
761
930
  .map((row) => this.#rowForScope(row, schema, scope))
762
- .sort((left, right) => left.localId.localeCompare(right.localId));
931
+ .sort((left, right) => this.#compareReplicaIdentity(schema, left.identity, right.identity));
763
932
  }
764
- async getReplicaRowByServerId(scope, sourceKey, serverId) {
765
- await this.initialize();
766
- await this.#writes;
767
- const schema = this.#resolveReplicaEntitySchema(sourceKey);
768
- if (!this.#schemaHasServerId(schema))
933
+ async getReplicaRowByRemoteId(scope, sourceKey, remoteId) {
934
+ if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
769
935
  return null;
770
- const rows = await this.#readRecord(ROWS_KEY);
771
- const row = Object.values(rows).find((row) => {
772
- if (row.sourceKey !== sourceKey || row.userId !== scope.userId || row.serverId !== serverId)
773
- return false;
774
- return schema.scope === 'partition' ? row.scopeId === scope.scopeId : true;
775
- });
776
- return row ? this.#rowForScope(row, schema, scope) : null;
936
+ return this.getReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });
777
937
  }
778
938
  async getReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
779
939
  await this.initialize();
@@ -786,7 +946,7 @@ class IonicOfflineRepository {
786
946
  return false;
787
947
  if (schema.scope === 'partition' && candidate.scopeId !== scope.scopeId)
788
948
  return false;
789
- const candidateIdentity = this.#rowRemoteIdentity(schema, candidate);
949
+ const candidateIdentity = offlineReplicaRemoteIdentity(schema, candidate.identity);
790
950
  return candidateIdentity !== null && canonicalOfflineRemoteIdentity(schema, candidateIdentity) === canonical;
791
951
  });
792
952
  return row ? this.#rowForScope(row, schema, scope) : null;
@@ -836,12 +996,12 @@ class IonicOfflineRepository {
836
996
  await this.initialize();
837
997
  await Promise.all([
838
998
  this.#mutateRecord(SESSION_MANIFESTS_KEY, (manifests) => {
839
- delete manifests[String(userId)];
999
+ delete manifests[canonicalOfflinePrincipalId(userId)];
840
1000
  return manifests;
841
1001
  }),
842
1002
  this.#filterRecord(ROWS_KEY, (value) => value.userId !== userId),
843
1003
  this.#filterRecord(OUTBOX_KEY, (value) => value.userId !== userId),
844
- this.#filterRecord(CURSORS_KEY, (_value, key) => !key.startsWith(`${userId}:`)),
1004
+ this.#filterRecord(CURSORS_KEY, (_value, key) => !key.startsWith(`${canonicalOfflinePrincipalId(userId)}:`)),
845
1005
  ]);
846
1006
  const metadata = await this.#metadata();
847
1007
  if (metadata.lastUserId === userId) {
@@ -856,7 +1016,10 @@ class IonicOfflineRepository {
856
1016
  const schema = this.#resolveReplicaEntitySchema(value.sourceKey);
857
1017
  return schema.scope === 'user' || !belongsToGroup(value);
858
1018
  }),
859
- this.#filterRecord(OUTBOX_KEY, (value) => !belongsToGroup(value)),
1019
+ this.#filterRecord(OUTBOX_KEY, (value) => {
1020
+ const schema = this.#resolveReplicaEntitySchema(value.sourceKey);
1021
+ return schema.scope === 'user' || !belongsToGroup(value);
1022
+ }),
860
1023
  this.#filterRecord(CURSORS_KEY, (_value, key) => key !== this.#cursorKey(scope)),
861
1024
  ]);
862
1025
  }
@@ -867,18 +1030,7 @@ class IonicOfflineRepository {
867
1030
  return write;
868
1031
  }
869
1032
  async #migrate() {
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
- }
1033
+ const metadata = await this.#storage.get(METADATA_KEY);
882
1034
  if (metadata?.schemaVersion !== undefined && metadata.schemaVersion !== OFFLINE_SCHEMA_VERSION) {
883
1035
  throw new Error(`Unsupported offline storage schema version ${metadata.schemaVersion}; expected ${OFFLINE_SCHEMA_VERSION}. ` +
884
1036
  'A lossless core schema migration is required before this database can be opened.');
@@ -976,7 +1128,7 @@ class IonicOfflineRepository {
976
1128
  values: projectOfflineReplicaValues(entitySchema, current.values),
977
1129
  confirmedValues: current.confirmedValues === null ? null : projectOfflineReplicaValues(entitySchema, current.confirmedValues),
978
1130
  };
979
- const transformedKey = this.#rowKey(transformedRow, transformedRow.sourceKey, transformedRow.localId);
1131
+ const transformedKey = this.#rowKey(transformedRow);
980
1132
  if (transformedRows[transformedKey]) {
981
1133
  throw new Error(`Replica schema migration produced duplicate row key "${transformedKey}".`);
982
1134
  }
@@ -1037,22 +1189,21 @@ class IonicOfflineRepository {
1037
1189
  ]);
1038
1190
  const identityCheckRows = { ...rows };
1039
1191
  const releases = new Map();
1040
- for (const release of transaction.releaseServerIds ?? []) {
1041
- if (!Number.isSafeInteger(release.serverId) || release.serverId <= 0) {
1042
- throw new Error(`Offline replica release has invalid serverId ${String(release.serverId)}.`);
1192
+ for (const release of transaction.releaseRemoteIds ?? []) {
1193
+ this.#assertValidReleaseRemoteId(release.remoteId);
1194
+ const key = this.#rowKey(release);
1195
+ if (releases.has(key)) {
1196
+ throw new Error(`Offline replica remoteId release is duplicated for ${release.sourceKey}/${canonicalOfflineReplicaIdentity(release.identity)}.`);
1043
1197
  }
1044
- const key = this.#rowKey(release, release.sourceKey, release.localId);
1045
- if (releases.has(key))
1046
- throw new Error(`Offline replica serverId release is duplicated for ${release.sourceKey}/${release.localId}.`);
1047
1198
  releases.set(key, release);
1048
1199
  }
1049
1200
  const consumedReleases = new Set();
1050
1201
  for (const row of transaction.putRows ?? []) {
1051
- const key = this.#rowKey(row, row.sourceKey, row.localId);
1202
+ const key = this.#rowKey(row);
1052
1203
  const existing = identityCheckRows[key];
1053
1204
  const release = releases.get(key);
1054
1205
  if (!existing && release) {
1055
- throw new Error(`Offline replica serverId release requires an existing row for ${row.sourceKey}/${row.localId}.`);
1206
+ throw new Error(`Offline replica remoteId release requires an existing row for ${row.sourceKey}/${canonicalOfflineReplicaIdentity(row.identity)}.`);
1056
1207
  }
1057
1208
  if (existing)
1058
1209
  this.#assertReplicaIdentityAssignment(existing, row, release);
@@ -1062,13 +1213,13 @@ class IonicOfflineRepository {
1062
1213
  identityCheckRows[key] = row;
1063
1214
  }
1064
1215
  if (consumedReleases.size !== releases.size) {
1065
- throw new Error('Offline replica serverId release must match an existing row in putRows.');
1216
+ throw new Error('Offline replica remoteId release must match an existing row in putRows.');
1066
1217
  }
1067
1218
  if (journal)
1068
1219
  await this.#storage.set(REPLICA_TRANSACTION_KEY, transaction);
1069
1220
  for (const row of transaction.putRows ?? []) {
1070
1221
  const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
1071
- rows[this.#rowKey(row, row.sourceKey, row.localId)] = {
1222
+ rows[this.#rowKey(row)] = {
1072
1223
  ...row,
1073
1224
  scopeId: schema.scope === 'user' ? '' : row.scopeId,
1074
1225
  values: projectOfflineReplicaValues(schema, row.values),
@@ -1076,7 +1227,7 @@ class IonicOfflineRepository {
1076
1227
  };
1077
1228
  }
1078
1229
  for (const row of transaction.removeRows ?? []) {
1079
- delete rows[this.#rowKey(row, row.sourceKey, row.localId)];
1230
+ delete rows[this.#rowKey(row)];
1080
1231
  }
1081
1232
  for (const command of transaction.putCommands ?? [])
1082
1233
  commands[command.commandId] = command;
@@ -1115,36 +1266,96 @@ class IonicOfflineRepository {
1115
1266
  this.#writes = write.catch(() => undefined);
1116
1267
  return write;
1117
1268
  }
1118
- #rowKey(scope, sourceKey, localId) {
1119
- const schema = this.#resolveReplicaEntitySchema(sourceKey);
1120
- const partition = schema.scope === 'user' ? 'user' : String(scope.scopeId);
1121
- return `${scope.userId}:${partition}:${sourceKey}:${localId}`;
1269
+ #rowKey(row) {
1270
+ const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
1271
+ const partition = schema.scope === 'user' ? 'user' : String(row.scopeId);
1272
+ return `${canonicalOfflinePrincipalId(row.userId)}:${partition}:${row.sourceKey}:${canonicalOfflineReplicaIdentity(row.identity)}`;
1273
+ }
1274
+ #findRowByAddress(rows, scope, sourceKey, schema, identity) {
1275
+ return Object.values(rows).find((row) => {
1276
+ if (row.sourceKey !== sourceKey || row.userId !== scope.userId)
1277
+ return false;
1278
+ if (schema.scope === 'partition' && row.scopeId !== scope.scopeId)
1279
+ return false;
1280
+ if (identity.kind === 'generated') {
1281
+ return row.identity.kind === 'generated' && row.identity.localId === identity.localId;
1282
+ }
1283
+ if (identity.kind === 'local') {
1284
+ return row.identity.kind === 'local' && row.identity.localId === identity.localId;
1285
+ }
1286
+ if (row.identity.kind !== 'natural')
1287
+ return false;
1288
+ return (canonicalOfflineRemoteIdentity(schema, { naturalKey: row.identity.naturalKey }) ===
1289
+ canonicalOfflineRemoteIdentity(schema, { naturalKey: normalizeOfflineNaturalKey(schema, identity.naturalKey) }));
1290
+ });
1122
1291
  }
1123
1292
  #rowForScope(row, schema, scope) {
1124
1293
  const normalized = { ...row, visibility: row.visibility ?? 'present' };
1125
1294
  return schema.scope === 'user' ? { ...normalized, scopeId: scope.scopeId } : normalized;
1126
1295
  }
1127
1296
  #cursorKey(scope) {
1128
- return `${scope.userId}:${scope.scopeId}`;
1129
- }
1130
- #schemaHasServerId(schema) {
1131
- return schema.identity.kind === 'serverId';
1297
+ return `${canonicalOfflinePrincipalId(scope.userId)}:${scope.scopeId}`;
1298
+ }
1299
+ #compareReplicaIdentity(schema, left, right) {
1300
+ if (left.kind === 'natural' && right.kind === 'natural' && schema.identity.kind === 'naturalKey') {
1301
+ const leftKey = normalizeOfflineNaturalKey(schema, left.naturalKey);
1302
+ const rightKey = normalizeOfflineNaturalKey(schema, right.naturalKey);
1303
+ for (const sourceKey of schema.identity.sourceKeys) {
1304
+ const leftValue = leftKey[sourceKey];
1305
+ const rightValue = rightKey[sourceKey];
1306
+ if (leftValue === rightValue)
1307
+ continue;
1308
+ if (typeof leftValue === 'number' && typeof rightValue === 'number') {
1309
+ return leftValue < rightValue ? -1 : 1;
1310
+ }
1311
+ return compareUtf8Binary(String(leftValue), String(rightValue));
1312
+ }
1313
+ return 0;
1314
+ }
1315
+ const leftId = left.kind === 'natural' ? canonicalOfflineReplicaIdentity(left) : left.localId;
1316
+ const rightId = right.kind === 'natural' ? canonicalOfflineReplicaIdentity(right) : right.localId;
1317
+ return compareUtf8Binary(leftId, rightId);
1132
1318
  }
1133
1319
  #validateReplicaRow(row) {
1134
1320
  const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
1135
- assertOfflineReplicaServerId(schema, row.serverId);
1321
+ this.#validateRowIdentity(schema, row);
1136
1322
  encodeOfflineReplicaValues(schema, row.values);
1137
1323
  if (row.confirmedValues !== null)
1138
1324
  encodeOfflineReplicaValues(schema, row.confirmedValues);
1139
1325
  assertOfflineReplicaNaturalKeyBaseline(schema, row.values, row.confirmedValues);
1140
1326
  }
1327
+ #validateRowIdentity(schema, row) {
1328
+ if (schema.identity.kind === 'localOnly') {
1329
+ if (row.identity.kind !== 'local') {
1330
+ throw new Error(`Offline replica source "${schema.sourceKey}" requires local identity.`);
1331
+ }
1332
+ return;
1333
+ }
1334
+ if (schema.identity.kind === 'generated') {
1335
+ if (row.identity.kind !== 'generated') {
1336
+ throw new Error(`Offline replica source "${schema.sourceKey}" requires generated identity.`);
1337
+ }
1338
+ assertOfflineReplicaGeneratedRemoteId(schema, row.identity.remoteId);
1339
+ return;
1340
+ }
1341
+ if (schema.identity.kind === 'naturalKey') {
1342
+ if (row.identity.kind !== 'natural') {
1343
+ throw new Error(`Offline replica source "${schema.sourceKey}" requires natural identity.`);
1344
+ }
1345
+ const fromValues = offlineNaturalKeyFromValues(schema, row.values);
1346
+ if (canonicalOfflineRemoteIdentity(schema, { naturalKey: row.identity.naturalKey }) !==
1347
+ canonicalOfflineRemoteIdentity(schema, { naturalKey: fromValues })) {
1348
+ throw new Error(`Offline replica identity naturalKey must match values for "${schema.sourceKey}".`);
1349
+ }
1350
+ }
1351
+ }
1141
1352
  #assertUniqueReplicaIdentity(rows, incoming) {
1142
1353
  const schema = this.#resolveReplicaEntitySchema(incoming.sourceKey);
1143
- const identity = this.#rowRemoteIdentity(schema, incoming);
1354
+ const identity = offlineReplicaRemoteIdentity(schema, incoming.identity);
1144
1355
  if (identity === null)
1145
1356
  return;
1146
1357
  const canonical = canonicalOfflineRemoteIdentity(schema, identity);
1147
- const incomingKey = this.#rowKey(incoming, incoming.sourceKey, incoming.localId);
1358
+ const incomingKey = this.#rowKey(incoming);
1148
1359
  const collision = Object.entries(rows).find(([key, row]) => {
1149
1360
  if (key === incomingKey)
1150
1361
  return false;
@@ -1152,50 +1363,72 @@ class IonicOfflineRepository {
1152
1363
  return false;
1153
1364
  if (schema.scope === 'partition' && row.scopeId !== incoming.scopeId)
1154
1365
  return false;
1155
- const rowIdentity = this.#rowRemoteIdentity(schema, row);
1366
+ const rowIdentity = offlineReplicaRemoteIdentity(schema, row.identity);
1156
1367
  return rowIdentity !== null && canonicalOfflineRemoteIdentity(schema, rowIdentity) === canonical;
1157
1368
  });
1158
1369
  if (collision) {
1159
- if (schema.identity.kind === 'serverId') {
1160
- throw new Error(`Offline replica serverId ${String(incoming.serverId)} is already mapped to localId ${collision[1].localId}.`);
1370
+ if (schema.identity.kind === 'generated') {
1371
+ const remoteId = incoming.identity.kind === 'generated' ? incoming.identity.remoteId : null;
1372
+ const mapped = collision[1].identity.kind === 'generated'
1373
+ ? collision[1].identity.localId
1374
+ : canonicalOfflineReplicaIdentity(collision[1].identity);
1375
+ throw new Error(`Offline replica remote id ${String(remoteId)} is already mapped to ${mapped}.`);
1161
1376
  }
1162
- throw new Error(`Offline replica remote identity is already mapped to localId ${collision[1].localId}.`);
1377
+ throw new Error(`Offline replica remote identity is already mapped to another row.`);
1163
1378
  }
1164
1379
  }
1165
1380
  #assertReplicaIdentityAssignment(existing, incoming, release) {
1166
1381
  const schema = this.#resolveReplicaEntitySchema(incoming.sourceKey);
1167
- if (release && schema.identity.kind !== 'serverId') {
1168
- throw new Error(`Offline replica serverId release is unsupported for source "${incoming.sourceKey}".`);
1382
+ if (release && schema.identity.kind !== 'generated') {
1383
+ throw new Error(`Offline replica remoteId release is unsupported for source "${incoming.sourceKey}".`);
1384
+ }
1385
+ if (schema.identity.kind === 'localOnly') {
1386
+ if (existing.identity.kind !== 'local' || incoming.identity.kind !== 'local') {
1387
+ throw new Error(`Offline replica local identity is required for "${incoming.sourceKey}".`);
1388
+ }
1389
+ if (existing.identity.localId !== incoming.identity.localId) {
1390
+ throw new Error(`Offline replica localId is immutable for "${schema.sourceKey}".`);
1391
+ }
1392
+ return;
1169
1393
  }
1170
- if (schema.identity.kind === 'serverId') {
1394
+ if (schema.identity.kind === 'generated') {
1395
+ if (existing.identity.kind !== 'generated' || incoming.identity.kind !== 'generated') {
1396
+ throw new Error(`Offline replica generated identity is required for "${incoming.sourceKey}".`);
1397
+ }
1171
1398
  if (release) {
1172
- if (existing.serverId !== release.serverId || incoming.serverId !== null) {
1173
- throw new Error(`Offline replica serverId release must transition current=${existing.serverId} to incoming=null for ${incoming.sourceKey}/${incoming.localId}.`);
1399
+ if (existing.identity.remoteId !== release.remoteId || incoming.identity.remoteId !== null) {
1400
+ throw new Error(`Offline replica remoteId release must transition current=${String(existing.identity.remoteId)} to incoming=null for ${incoming.sourceKey}/${incoming.identity.localId}.`);
1174
1401
  }
1175
1402
  return;
1176
1403
  }
1177
- if (existing.serverId !== null && existing.serverId !== incoming.serverId) {
1178
- throw new Error(`Offline replica serverId is immutable: current=${existing.serverId}, incoming=${String(incoming.serverId)}.`);
1404
+ if (existing.identity.localId !== incoming.identity.localId) {
1405
+ throw new Error(`Offline replica localId is immutable for "${schema.sourceKey}".`);
1406
+ }
1407
+ if (existing.identity.remoteId !== null && existing.identity.remoteId !== incoming.identity.remoteId) {
1408
+ throw new Error(`Offline replica remoteId is immutable: current=${String(existing.identity.remoteId)}, incoming=${String(incoming.identity.remoteId)}.`);
1179
1409
  }
1180
1410
  return;
1181
1411
  }
1182
1412
  if (schema.identity.kind === 'naturalKey') {
1183
- const current = canonicalOfflineRemoteIdentity(schema, {
1184
- naturalKey: offlineNaturalKeyFromValues(schema, existing.values),
1185
- });
1186
- const next = canonicalOfflineRemoteIdentity(schema, {
1187
- naturalKey: offlineNaturalKeyFromValues(schema, incoming.values),
1188
- });
1413
+ if (existing.identity.kind !== 'natural' || incoming.identity.kind !== 'natural') {
1414
+ throw new Error(`Offline replica natural identity is required for "${schema.sourceKey}".`);
1415
+ }
1416
+ const current = canonicalOfflineRemoteIdentity(schema, { naturalKey: existing.identity.naturalKey });
1417
+ const next = canonicalOfflineRemoteIdentity(schema, { naturalKey: incoming.identity.naturalKey });
1189
1418
  if (current !== next)
1190
1419
  throw new Error(`Offline replica naturalKey is immutable for "${schema.sourceKey}".`);
1191
1420
  }
1192
1421
  }
1193
- #rowRemoteIdentity(schema, row) {
1194
- if (schema.identity.kind === 'serverId')
1195
- return row.serverId === null ? null : { serverId: row.serverId };
1196
- if (schema.identity.kind === 'naturalKey')
1197
- return { naturalKey: offlineNaturalKeyFromValues(schema, row.values) };
1198
- return null;
1422
+ #assertValidReleaseRemoteId(remoteId) {
1423
+ if (typeof remoteId === 'number') {
1424
+ if (!Number.isSafeInteger(remoteId) || remoteId <= 0) {
1425
+ throw new Error(`Offline replica release has invalid remoteId ${String(remoteId)}.`);
1426
+ }
1427
+ return;
1428
+ }
1429
+ if (typeof remoteId !== 'string' || remoteId.length === 0) {
1430
+ throw new Error(`Offline replica release has invalid remoteId ${String(remoteId)}.`);
1431
+ }
1199
1432
  }
1200
1433
  #resolveReplicaEntitySchema(sourceKey) {
1201
1434
  const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);
@@ -1210,13 +1443,22 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
1210
1443
  type: Injectable,
1211
1444
  args: [{ providedIn: 'root' }]
1212
1445
  }] });
1446
+ function compareUtf8Binary(left, right) {
1447
+ const leftBytes = new TextEncoder().encode(left);
1448
+ const rightBytes = new TextEncoder().encode(right);
1449
+ const length = Math.min(leftBytes.length, rightBytes.length);
1450
+ for (let index = 0; index < length; index += 1) {
1451
+ if (leftBytes[index] !== rightBytes[index])
1452
+ return leftBytes[index] < rightBytes[index] ? -1 : 1;
1453
+ }
1454
+ return leftBytes.length < rightBytes.length ? -1 : leftBytes.length > rightBytes.length ? 1 : 0;
1455
+ }
1213
1456
 
1214
1457
  /** Pulls authoritative server deltas into one durable local replica partition. */
1215
1458
  class OfflineReplicaPullService {
1216
1459
  #repository = inject(OFFLINE_REPOSITORY);
1217
1460
  #options = inject(OFFLINE_KIT_OPTIONS);
1218
1461
  #puller = inject(OFFLINE_REPLICA_PULLER);
1219
- #hooks = inject(OFFLINE_COMMAND_HOOKS);
1220
1462
  #executor = inject(OFFLINE_COMMAND_EXECUTOR);
1221
1463
  #schemaHash = null;
1222
1464
  async pull(scope) {
@@ -1249,38 +1491,39 @@ class OfflineReplicaPullService {
1249
1491
  const command = commands.find((candidate) => candidate.commandId === commandId);
1250
1492
  if (!command)
1251
1493
  return null;
1252
- if (this.#hooks.entityType(command) !== change.sourceKey) {
1494
+ if (command.sourceKey !== change.sourceKey) {
1253
1495
  throw new Error(`Acknowledged command "${commandId}" does not target "${change.sourceKey}".`);
1254
1496
  }
1255
1497
  return command;
1256
1498
  })
1257
1499
  .filter((command) => command !== null);
1258
- const acknowledgedLocalIds = new Set(acknowledged.map((command) => command.aggregateLocalId));
1259
- if (acknowledgedLocalIds.size > 1) {
1260
- throw new Error(`Acknowledged commands for "${change.sourceKey}" target multiple local rows.`);
1500
+ const acknowledgedIdentities = new Set(acknowledged.map((command) => canonicalOfflineCommandIdentity(command.identity)));
1501
+ if (acknowledgedIdentities.size > 1) {
1502
+ throw new Error(`Acknowledged commands for "${change.sourceKey}" target multiple replica identities.`);
1261
1503
  }
1262
1504
  const acknowledgedCommand = acknowledged[0];
1263
1505
  const acknowledgedScope = acknowledgedCommand
1264
1506
  ? { userId: acknowledgedCommand.userId, scopeId: acknowledgedCommand.scopeId }
1265
1507
  : scope;
1266
1508
  const acknowledgedRow = acknowledgedCommand
1267
- ? await (this.#repository.getReplicaRowIncludingPendingDelete?.(acknowledgedScope, change.sourceKey, acknowledgedCommand.aggregateLocalId) ??
1268
- this.#repository.getReplicaRow(acknowledgedScope, change.sourceKey, acknowledgedCommand.aggregateLocalId))
1509
+ ? await (this.#repository.getReplicaRowIncludingPendingDelete?.(acknowledgedScope, change.sourceKey, acknowledgedCommand.identity) ?? this.#repository.getReplicaRow(acknowledgedScope, change.sourceKey, acknowledgedCommand.identity))
1269
1510
  : null;
1270
1511
  if (acknowledgedCommand && !acknowledgedRow) {
1271
1512
  throw new Error(`Acknowledged command "${acknowledgedCommand.commandId}" has no local replica row.`);
1272
1513
  }
1273
1514
  const identity = this.#identity(change);
1274
1515
  const serverRow = await this.#repository.getReplicaRowByRemoteIdentity(scope, change.sourceKey, identity);
1275
- if (acknowledgedRow && serverRow && acknowledgedRow.localId !== serverRow.localId) {
1276
- if (identity.serverId !== undefined) {
1277
- throw new Error(`Server id ${identity.serverId} is already mapped to another local replica row.`);
1516
+ if (acknowledgedRow &&
1517
+ serverRow &&
1518
+ !commandIdentityMatchesReplicaRow(schema, acknowledgedRow, commandIdentityFromReplicaIdentity(serverRow.identity))) {
1519
+ if (identity.remoteId !== undefined) {
1520
+ throw new Error(`Server id ${String(identity.remoteId)} is already mapped to another local replica row.`);
1278
1521
  }
1279
1522
  throw new Error(`Remote identity for "${change.sourceKey}" is already mapped to another local replica row.`);
1280
1523
  }
1281
1524
  const existing = acknowledgedRow ?? serverRow;
1282
1525
  const related = existing
1283
- ? commands.filter((command) => this.#hooks.entityType(command) === change.sourceKey && command.aggregateLocalId === existing.localId)
1526
+ ? commands.filter((command) => command.sourceKey === change.sourceKey && commandIdentityMatchesReplicaRow(schema, existing, command.identity))
1284
1527
  : [];
1285
1528
  const hasPending = related.length > 0;
1286
1529
  if (acknowledgedCommand) {
@@ -1292,7 +1535,7 @@ class OfflineReplicaPullService {
1292
1535
  if (!existing)
1293
1536
  continue;
1294
1537
  if (!hasPending) {
1295
- removeRows.push(existing);
1538
+ removeRows.push({ ...existing, identity: existing.identity });
1296
1539
  continue;
1297
1540
  }
1298
1541
  putRows.push({
@@ -1312,8 +1555,9 @@ class OfflineReplicaPullService {
1312
1555
  putRows.push({
1313
1556
  ...scope,
1314
1557
  sourceKey: change.sourceKey,
1315
- localId: crypto.randomUUID(),
1316
- serverId: identity.serverId ?? null,
1558
+ identity: schema.identity.kind === 'naturalKey'
1559
+ ? offlineNaturalReplicaIdentity(schema, confirmedValues)
1560
+ : offlineGeneratedReplicaIdentity(crypto.randomUUID(), identity.remoteId ?? null),
1317
1561
  values: confirmedValues,
1318
1562
  confirmedValues,
1319
1563
  serverRevision: change.serverRevision,
@@ -1380,13 +1624,15 @@ class OfflineReplicaPullService {
1380
1624
  throw new Error(`${label}.deleted must be a boolean.`);
1381
1625
  }
1382
1626
  const schema = this.#entitySchema(change['sourceKey']);
1383
- if (schema.identity.kind === 'serverId') {
1384
- const serverId = change['serverId'];
1385
- if (typeof serverId !== 'number' || !Number.isSafeInteger(serverId) || serverId <= 0) {
1386
- throw new Error(`${label}.serverId must be a positive integer.`);
1627
+ if (schema.identity.kind === 'generated') {
1628
+ const remoteId = change['remoteId'];
1629
+ const validInteger = typeof remoteId === 'number' && Number.isSafeInteger(remoteId) && remoteId > 0;
1630
+ const validText = typeof remoteId === 'string' && remoteId.length > 0;
1631
+ if (schema.identity.affinity === 'INTEGER' ? !validInteger : !validText) {
1632
+ throw new Error(`${label}.remoteId must be a valid generated remote id.`);
1387
1633
  }
1388
1634
  if (change['naturalKey'] !== undefined) {
1389
- throw new Error(`${label}.naturalKey must be omitted for a serverId entity.`);
1635
+ throw new Error(`${label}.naturalKey must be omitted for a generated entity.`);
1390
1636
  }
1391
1637
  }
1392
1638
  try {
@@ -1424,9 +1670,9 @@ class OfflineReplicaPullService {
1424
1670
  }
1425
1671
  #validatedValues(schema, change) {
1426
1672
  if (change.values === null) {
1427
- throw new Error(change.serverId === undefined
1673
+ throw new Error(change.remoteId === undefined
1428
1674
  ? `Offline replica change "${change.sourceKey}" is missing values.`
1429
- : `Offline replica change "${change.sourceKey}"/${change.serverId} is missing values.`);
1675
+ : `Offline replica change "${change.sourceKey}"/${String(change.remoteId)} is missing values.`);
1430
1676
  }
1431
1677
  const values = projectOfflineReplicaValues(schema, change.values);
1432
1678
  if (schema.identity.kind === 'naturalKey') {
@@ -1507,7 +1753,7 @@ class OfflineReplicaPullService {
1507
1753
  }
1508
1754
  }
1509
1755
  else {
1510
- removeRows.push(row);
1756
+ removeRows.push({ ...row, identity: row.identity });
1511
1757
  }
1512
1758
  return;
1513
1759
  }
@@ -1516,7 +1762,7 @@ class OfflineReplicaPullService {
1516
1762
  this.#assertIdentityAssignment(schema, row, this.#identity(change));
1517
1763
  putRows.push({
1518
1764
  ...row,
1519
- serverId: change.serverId ?? null,
1765
+ identity: row.identity.kind === 'generated' ? { ...row.identity, remoteId: change.remoteId ?? row.identity.remoteId } : row.identity,
1520
1766
  values: following.length > 0 ? following.at(-1).optimisticValue : confirmedValues,
1521
1767
  confirmedValues,
1522
1768
  serverRevision: change.serverRevision,
@@ -1526,17 +1772,20 @@ class OfflineReplicaPullService {
1526
1772
  });
1527
1773
  }
1528
1774
  #identity(change) {
1529
- return change.serverId !== undefined ? { serverId: change.serverId } : { naturalKey: change.naturalKey };
1775
+ return change.remoteId !== undefined ? { remoteId: change.remoteId } : { naturalKey: change.naturalKey };
1530
1776
  }
1531
1777
  #assertIdentityAssignment(schema, row, incoming) {
1532
- if (schema.identity.kind === 'serverId') {
1533
- const serverId = incoming.serverId;
1534
- if (row.serverId !== null && row.serverId !== serverId) {
1535
- throw new Error(`Replica serverId is immutable: current=${row.serverId}, incoming=${serverId}.`);
1778
+ if (schema.identity.kind === 'generated') {
1779
+ const remoteId = incoming.remoteId;
1780
+ if (row.identity.kind !== 'generated') {
1781
+ throw new Error(`Replica generated identity is required for "${schema.sourceKey}".`);
1782
+ }
1783
+ if (row.identity.remoteId !== null && row.identity.remoteId !== remoteId) {
1784
+ throw new Error(`Replica remote id is immutable: current=${String(row.identity.remoteId)}, incoming=${String(remoteId)}.`);
1536
1785
  }
1537
1786
  return;
1538
1787
  }
1539
- const current = offlineNaturalKeyFromValues(schema, row.values);
1788
+ const current = row.identity.kind === 'natural' ? row.identity.naturalKey : offlineNaturalKeyFromValues(schema, row.values);
1540
1789
  if (current !== null &&
1541
1790
  canonicalOfflineRemoteIdentity(schema, { naturalKey: current }) !== canonicalOfflineRemoteIdentity(schema, incoming)) {
1542
1791
  throw new Error(`Replica naturalKey is immutable for "${schema.sourceKey}".`);
@@ -1557,6 +1806,15 @@ function isPlainObject(value) {
1557
1806
  return prototype === Object.prototype || prototype === null;
1558
1807
  }
1559
1808
 
1809
+ const DEFAULT_OFFLINE_COMMAND_HOOKS = {
1810
+ entityType: (command) => command.aggregateType,
1811
+ };
1812
+ /** DI token for optional product-specific synchronization hooks. */
1813
+ const OFFLINE_COMMAND_HOOKS = new InjectionToken('OFFLINE_COMMAND_HOOKS', {
1814
+ providedIn: 'root',
1815
+ factory: () => DEFAULT_OFFLINE_COMMAND_HOOKS,
1816
+ });
1817
+
1560
1818
  /** transport不能(status=0)だけをlocal replica fallback対象にし、HTTPエラーは隠さない。 */
1561
1819
  function isOfflineFallbackError(error) {
1562
1820
  return typeof error === 'object' && error !== null && error.status === 0;
@@ -1933,19 +2191,25 @@ class OfflineSyncService {
1933
2191
  const session = await this.#getLocalSession();
1934
2192
  if (!session)
1935
2193
  throw new Error('Cannot enqueue an offline command without an authenticated user');
2194
+ this.#assertSessionPrincipalBoundary(session);
1936
2195
  const userId = session.userId;
1937
2196
  this.#setActiveUser(userId);
1938
2197
  const scope = { userId, scopeId: request.scopeId };
2198
+ if (!session.scopes.some((candidate) => candidate.userId === userId && candidate.scopeId === request.scopeId)) {
2199
+ throw new Error(`Offline sync session does not include scope "${request.scopeId}".`);
2200
+ }
1939
2201
  this.noteScope(scope);
1940
- const aggregateLocalId = request.aggregateLocalId;
1941
- const normalized = await this.#normalizeEnqueueRequest(scope, request);
2202
+ const commandIdentity = offlineCommandLookupIdentity(request.identity);
2203
+ const normalized = await this.#normalizeEnqueueRequest(scope, request, commandIdentity);
1942
2204
  const optimisticValue = request.optimisticValue;
1943
2205
  const commandId = crypto.randomUUID();
2206
+ const sourceKey = this.#hooks.entityType(request);
1944
2207
  const command = {
1945
2208
  ...scope,
1946
2209
  commandId,
1947
2210
  aggregateType: request.aggregateType,
1948
- aggregateLocalId,
2211
+ sourceKey,
2212
+ identity: commandIdentity,
1949
2213
  operation: request.operation,
1950
2214
  payload: normalized.payload,
1951
2215
  optimisticValue,
@@ -1959,46 +2223,62 @@ class OfflineSyncService {
1959
2223
  lastErrorCode: null,
1960
2224
  };
1961
2225
  await this.#assertOutboxCapacity(userId, command);
1962
- const entityType = this.#entityType(command);
2226
+ const entityType = command.sourceKey;
1963
2227
  const schema = this.#entitySchema(entityType);
2228
+ if (schema.identity.kind === 'localOnly') {
2229
+ throw new Error(`Offline replica source "${entityType}" is local-only and cannot be added to the Outbox.`);
2230
+ }
2231
+ if (schema.identity.kind === 'generated' && request.identity.kind !== 'generated') {
2232
+ throw new Error(`Offline replica source "${entityType}" requires generated identity.`);
2233
+ }
2234
+ if (schema.identity.kind === 'naturalKey' && request.identity.kind !== 'natural') {
2235
+ throw new Error(`Offline replica source "${entityType}" requires natural identity.`);
2236
+ }
1964
2237
  if (request.replicaMutation === 'delete' && !this.#repository.getReplicaRowIncludingPendingDelete) {
1965
2238
  throw new Error('Offline repository does not support durable replica delete tombstones.');
1966
2239
  }
1967
- const existing = await this.#getReplicaRowForSync(scope, entityType, aggregateLocalId);
1968
- const initialServerId = this.#initialServerId(existing?.serverId ?? null, request.serverId);
1969
- this.#assertServerIdHint(existing?.serverId ?? null, request.serverIdHint);
2240
+ const existing = await this.#getReplicaRowForSync(scope, entityType, commandIdentity);
2241
+ const generatedIdentity = request.identity.kind === 'generated' ? request.identity : null;
2242
+ const initialRemoteId = this.#initialRemoteId(schema, existing?.identity.kind === 'generated' ? existing.identity.remoteId : null, generatedIdentity?.remoteId);
2243
+ this.#assertRemoteIdHint(schema, existing?.identity.kind === 'generated' ? existing.identity.remoteId : null, generatedIdentity?.remoteIdHint);
1970
2244
  const naturalKey = offlineNaturalKeyFromValues(schema, optimisticValue);
1971
- const remoteIdentity = schema.identity.kind === 'serverId'
1972
- ? initialServerId === null
2245
+ if (schema.identity.kind === 'naturalKey' &&
2246
+ canonicalOfflineRemoteIdentity(schema, { naturalKey: request.identity.kind === 'natural' ? request.identity.naturalKey : {} }) !==
2247
+ canonicalOfflineRemoteIdentity(schema, { naturalKey: naturalKey })) {
2248
+ throw new Error(`Offline command naturalKey must match optimistic values for "${entityType}".`);
2249
+ }
2250
+ const remoteIdentity = schema.identity.kind === 'generated'
2251
+ ? initialRemoteId === null
1973
2252
  ? null
1974
- : { serverId: initialServerId }
2253
+ : { remoteId: initialRemoteId }
1975
2254
  : schema.identity.kind === 'naturalKey'
1976
2255
  ? { naturalKey: naturalKey }
1977
2256
  : null;
1978
- if (schema.identity.kind === 'naturalKey' && (request.serverId != null || request.serverIdHint != null)) {
1979
- throw new Error(`Offline replica source "${entityType}" does not define a serverId field.`);
1980
- }
1981
2257
  if (schema.identity.kind === 'naturalKey') {
1982
2258
  const canonicalValuesKey = canonicalOfflineRemoteIdentity(schema, remoteIdentity);
1983
2259
  if (existing &&
1984
- canonicalOfflineRemoteIdentity(schema, { naturalKey: offlineNaturalKeyFromValues(schema, existing.values) }) !== canonicalValuesKey) {
2260
+ canonicalOfflineRemoteIdentity(schema, {
2261
+ naturalKey: existing.identity.kind === 'natural' ? existing.identity.naturalKey : offlineNaturalKeyFromValues(schema, existing.values),
2262
+ }) !== canonicalValuesKey) {
1985
2263
  throw new Error(`Offline replica naturalKey is immutable and must match optimistic values for "${entityType}".`);
1986
2264
  }
1987
2265
  }
1988
2266
  if (remoteIdentity !== null) {
1989
2267
  const mapped = await this.#repository.getReplicaRowByRemoteIdentity(scope, entityType, remoteIdentity);
1990
- if (mapped !== null && mapped.localId !== aggregateLocalId) {
1991
- if (remoteIdentity.serverId !== undefined) {
1992
- throw new Error(`Offline replica serverId ${String(remoteIdentity.serverId)} is already mapped to localId ${mapped.localId}.`);
2268
+ if (mapped !== null && !commandIdentityMatchesReplicaRow(schema, mapped, commandIdentity)) {
2269
+ if ('remoteId' in remoteIdentity) {
2270
+ throw new Error(`Offline replica remote id ${String(remoteIdentity.remoteId)} is already mapped to another row.`);
1993
2271
  }
1994
- throw new Error(`Offline replica remote identity is already mapped to localId ${mapped.localId}.`);
2272
+ throw new Error(`Offline replica remote identity is already mapped to another row.`);
1995
2273
  }
1996
2274
  }
2275
+ const rowIdentity = schema.identity.kind === 'naturalKey'
2276
+ ? offlineNaturalReplicaIdentity(schema, optimisticValue)
2277
+ : offlineGeneratedReplicaIdentity(generatedIdentity.localId, initialRemoteId);
1997
2278
  const optimisticRow = {
1998
2279
  ...scope,
1999
2280
  sourceKey: entityType,
2000
- localId: aggregateLocalId,
2001
- serverId: initialServerId,
2281
+ identity: rowIdentity,
2002
2282
  values: optimisticValue,
2003
2283
  confirmedValues: existing?.confirmedValues ?? existing?.values ?? null,
2004
2284
  serverRevision: existing?.serverRevision ?? normalized.baseRevision,
@@ -2141,16 +2421,10 @@ class OfflineSyncService {
2141
2421
  return;
2142
2422
  const row = await this.#rowForCommand(sending);
2143
2423
  if (!row)
2144
- throw new Error(`Offline replica row not found: ${sending.aggregateType}/${sending.aggregateLocalId}`);
2424
+ throw new Error(`Offline replica row not found: ${sending.aggregateType}/${canonicalOfflineCommandIdentity(sending.identity)}`);
2145
2425
  let result;
2146
2426
  try {
2147
- const schema = this.#entitySchema(row.sourceKey);
2148
- const naturalKey = offlineNaturalKeyFromValues(schema, row.values);
2149
- result = await this.#executor.execute(sending, {
2150
- localId: row.localId,
2151
- serverId: row.serverId,
2152
- ...(naturalKey !== null ? { naturalKey } : {}),
2153
- });
2427
+ result = await this.#executor.execute(sending, offlineCommandTargetFromReplicaRow(row));
2154
2428
  }
2155
2429
  catch (error) {
2156
2430
  if (!this.#isCurrent(generation))
@@ -2171,13 +2445,13 @@ class OfflineSyncService {
2171
2445
  await this.#completeCommand(commands, sending, result, generation);
2172
2446
  }
2173
2447
  }
2174
- async #normalizeEnqueueRequest(scope, request) {
2448
+ async #normalizeEnqueueRequest(scope, request, commandIdentity) {
2175
2449
  let baseRevision = request.baseRevision ?? null;
2176
2450
  let payload = request.payload;
2177
- const aggregateLocalId = request.aggregateLocalId;
2178
- const row = await this.#getReplicaRowForSync(scope, this.#entityType(request), aggregateLocalId);
2451
+ const sourceKey = this.#hooks.entityType(request);
2452
+ const row = await this.#getReplicaRowForSync(scope, sourceKey, commandIdentity);
2179
2453
  if (row?.serverRevision != null && row.serverRevision !== baseRevision) {
2180
- const rebased = this.#executor.withServerRevision({ ...scope, ...request, aggregateLocalId, payload, baseRevision }, row.serverRevision);
2454
+ const rebased = this.#executor.withServerRevision({ ...scope, ...request, sourceKey, identity: commandIdentity, payload, baseRevision }, row.serverRevision);
2181
2455
  baseRevision = row.serverRevision;
2182
2456
  payload = rebased.payload;
2183
2457
  }
@@ -2187,11 +2461,11 @@ class OfflineSyncService {
2187
2461
  return this.#serializeReplicaMutation(() => this.#completeCommandLocked(commands, command, result, generation));
2188
2462
  }
2189
2463
  async #completeCommandLocked(commands, command, result, generation) {
2190
- if (result.clearServerId === true && result.serverId !== undefined) {
2191
- throw new Error('Offline command cannot return serverId and clearServerId together.');
2464
+ if (result.clearRemoteId === true && result.remoteId !== undefined) {
2465
+ throw new Error('Offline command cannot return remoteId and clearRemoteId together.');
2192
2466
  }
2193
- if (result.clearServerId === true && result.serverRevision !== undefined) {
2194
- throw new Error('Offline command cannot return serverRevision and clearServerId together.');
2467
+ if (result.clearRemoteId === true && result.serverRevision !== undefined) {
2468
+ throw new Error('Offline command cannot return serverRevision and clearRemoteId together.');
2195
2469
  }
2196
2470
  // An enqueue may have completed while transport was in flight. Re-read the
2197
2471
  // aggregate immediately before the atomic acknowledgement transaction so a
@@ -2202,10 +2476,10 @@ class OfflineSyncService {
2202
2476
  return;
2203
2477
  const revision = result.serverRevision;
2204
2478
  const following = latestCommands.slice(latestIndex + 1);
2205
- const rebased = result.clearServerId === true
2479
+ const rebased = result.clearRemoteId === true
2206
2480
  ? following.map((item) => {
2207
2481
  if (!this.#executor.withoutServerRevision) {
2208
- throw new Error('Offline command executor must implement withoutServerRevision to recreate a deleted serverId row.');
2482
+ throw new Error('Offline command executor must implement withoutServerRevision to recreate a deleted remoteId row.');
2209
2483
  }
2210
2484
  return this.#executor.withoutServerRevision(item);
2211
2485
  })
@@ -2221,23 +2495,24 @@ class OfflineSyncService {
2221
2495
  }
2222
2496
  this.#assertServerRevision(result.serverRevision);
2223
2497
  const removesReplica = result.removeReplica === true || command.replicaMutation === 'delete';
2224
- if (result.clearServerId === true && !removesReplica) {
2225
- throw new Error('Offline command can clear serverId only for a confirmed replica removal.');
2498
+ if (result.clearRemoteId === true && !removesReplica) {
2499
+ throw new Error('Offline command can clear remoteId only for a confirmed replica removal.');
2226
2500
  }
2227
2501
  const confirmedValues = removesReplica ? null : (result.confirmedValues ?? command.optimisticValue);
2228
2502
  const schema = this.#entitySchema(current.sourceKey);
2229
2503
  this.#assertCommandResultIdentity(schema, current, result);
2230
- const serverId = result.clearServerId === true ? null : this.#resolvedServerId(current.serverId, result.serverId);
2504
+ const resolvedRemoteId = this.#resolvedRemoteId(current, result);
2231
2505
  const row = {
2232
2506
  ...current,
2233
- // The row may have received a local-only patch (for example, a UI
2234
- // projection was integrated) while this command was in flight. Keep the
2235
- // current durable optimistic state instead of restoring the stale
2236
- // command snapshot when later commands remain queued.
2237
2507
  values: rebased.length > 0 ? current.values : confirmedValues,
2238
2508
  confirmedValues,
2239
- serverId,
2240
- serverRevision: result.clearServerId === true ? null : (revision ?? current.serverRevision),
2509
+ identity: current.identity.kind === 'generated'
2510
+ ? {
2511
+ ...current.identity,
2512
+ remoteId: result.clearRemoteId === true ? null : resolvedRemoteId,
2513
+ }
2514
+ : current.identity,
2515
+ serverRevision: result.clearRemoteId === true ? null : (revision ?? current.serverRevision),
2241
2516
  fetchedAt: Date.now(),
2242
2517
  syncState: rebased.length > 0 ? 'pending' : 'confirmed',
2243
2518
  visibility: rebased.at(-1)?.replicaMutation === 'delete' ? 'pending_delete' : 'present',
@@ -2246,14 +2521,17 @@ class OfflineSyncService {
2246
2521
  return;
2247
2522
  await this.#repository.transactReplica({
2248
2523
  putRows: removesReplica && rebased.length === 0 ? undefined : [row],
2249
- releaseServerIds: result.clearServerId === true && current.serverId !== null && !(removesReplica && rebased.length === 0)
2524
+ releaseRemoteIds: result.clearRemoteId === true &&
2525
+ current.identity.kind === 'generated' &&
2526
+ current.identity.remoteId !== null &&
2527
+ !(removesReplica && rebased.length === 0)
2250
2528
  ? [
2251
2529
  {
2252
2530
  userId: current.userId,
2253
2531
  scopeId: current.scopeId,
2254
2532
  sourceKey: current.sourceKey,
2255
- localId: current.localId,
2256
- serverId: current.serverId,
2533
+ identity: current.identity,
2534
+ remoteId: current.identity.remoteId,
2257
2535
  },
2258
2536
  ]
2259
2537
  : undefined,
@@ -2266,11 +2544,11 @@ class OfflineSyncService {
2266
2544
  async #rowForCommand(command) {
2267
2545
  const scope = { userId: command.userId, scopeId: command.scopeId };
2268
2546
  const entityType = this.#entityType(command);
2269
- return this.#getReplicaRowForSync(scope, entityType, command.aggregateLocalId);
2547
+ return this.#getReplicaRowForSync(scope, entityType, command.identity);
2270
2548
  }
2271
- #getReplicaRowForSync(scope, sourceKey, localId) {
2272
- return (this.#repository.getReplicaRowIncludingPendingDelete?.(scope, sourceKey, localId) ??
2273
- this.#repository.getReplicaRow(scope, sourceKey, localId));
2549
+ #getReplicaRowForSync(scope, sourceKey, identity) {
2550
+ return (this.#repository.getReplicaRowIncludingPendingDelete?.(scope, sourceKey, identity) ??
2551
+ this.#repository.getReplicaRow(scope, sourceKey, identity));
2274
2552
  }
2275
2553
  #replicaState(state) {
2276
2554
  if (state === 'blocked_auth' || state === 'rejected' || state === 'conflict')
@@ -2278,7 +2556,7 @@ class OfflineSyncService {
2278
2556
  return 'pending';
2279
2557
  }
2280
2558
  #entityType(command) {
2281
- return this.#hooks.entityType(command);
2559
+ return command.sourceKey;
2282
2560
  }
2283
2561
  #entitySchema(sourceKey) {
2284
2562
  const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);
@@ -2323,7 +2601,7 @@ class OfflineSyncService {
2323
2601
  if (!schema)
2324
2602
  throw new Error(`Unknown offline replica source key "${sourceKey}".`);
2325
2603
  const partition = schema.scope === 'user' ? 'user' : `partition:${command.scopeId}`;
2326
- return `${command.userId}:${partition}:${sourceKey}:${command.aggregateLocalId}`;
2604
+ return `${canonicalOfflinePrincipalId(command.userId)}:${partition}:${sourceKey}:${canonicalOfflineCommandIdentity(command.identity)}`;
2327
2605
  }
2328
2606
  #failedCommand(command, error) {
2329
2607
  const status = this.#errorStatus(error);
@@ -2354,43 +2632,49 @@ class OfflineSyncService {
2354
2632
  throw new Error(`Offline command returned invalid serverRevision ${String(revision)}.`);
2355
2633
  }
2356
2634
  }
2357
- #resolvedServerId(current, incoming) {
2635
+ #resolvedRemoteId(current, result) {
2636
+ if (current.identity.kind !== 'generated')
2637
+ return null;
2638
+ const incoming = result.remoteId;
2358
2639
  if (incoming === undefined)
2359
- return current;
2360
- if (!Number.isSafeInteger(incoming) || incoming <= 0) {
2361
- throw new Error(`Offline command returned invalid serverId ${String(incoming)}.`);
2640
+ return current.identity.remoteId;
2641
+ const schema = this.#entitySchema(current.sourceKey);
2642
+ assertOfflineReplicaGeneratedRemoteId(schema, incoming);
2643
+ if (current.identity.remoteId !== null && current.identity.remoteId !== incoming) {
2644
+ throw new Error(`Offline replica remote id is immutable: current=${String(current.identity.remoteId)}, incoming=${String(incoming)}.`);
2362
2645
  }
2646
+ return incoming;
2647
+ }
2648
+ #initialRemoteId(schema, current, incoming) {
2649
+ if (incoming === null || incoming === undefined)
2650
+ return current;
2651
+ assertOfflineReplicaGeneratedRemoteId(schema, incoming);
2363
2652
  if (current !== null && current !== incoming) {
2364
- throw new Error(`Offline replica serverId is immutable: current=${current}, incoming=${incoming}.`);
2653
+ throw new Error(`Offline replica remote id is immutable: current=${String(current)}, incoming=${String(incoming)}.`);
2365
2654
  }
2366
2655
  return incoming;
2367
2656
  }
2368
- #initialServerId(current, incoming) {
2369
- return incoming === null || incoming === undefined ? current : this.#resolvedServerId(current, incoming);
2370
- }
2371
- #assertServerIdHint(current, hint) {
2657
+ #assertRemoteIdHint(schema, current, hint) {
2372
2658
  if (hint === null || hint === undefined)
2373
2659
  return;
2374
- if (!Number.isSafeInteger(hint) || hint <= 0) {
2375
- throw new Error(`Offline command returned invalid serverId hint ${String(hint)}.`);
2376
- }
2660
+ assertOfflineReplicaGeneratedRemoteId(schema, hint);
2377
2661
  if (current !== null && current !== hint) {
2378
- throw new Error(`Offline replica serverId hint does not match current=${current}: incoming=${hint}.`);
2662
+ throw new Error(`Offline replica remoteId hint does not match current=${String(current)}: incoming=${String(hint)}.`);
2379
2663
  }
2380
2664
  }
2381
2665
  #assertCommandResultIdentity(schema, current, result) {
2382
- if (result.clearServerId === true && schema.identity.kind !== 'serverId') {
2383
- throw new Error(`Offline command cannot clear serverId for source "${schema.sourceKey}".`);
2666
+ if (result.clearRemoteId === true && schema.identity.kind !== 'generated') {
2667
+ throw new Error(`Offline command cannot clear remoteId for source "${schema.sourceKey}".`);
2384
2668
  }
2385
- if (schema.identity.kind === 'naturalKey' && result.serverId !== undefined) {
2386
- throw new Error(`Offline command returned serverId for naturalKey source "${schema.sourceKey}".`);
2669
+ if (schema.identity.kind === 'naturalKey' && result.remoteId !== undefined) {
2670
+ throw new Error(`Offline command returned generated remote id for naturalKey source "${schema.sourceKey}".`);
2387
2671
  }
2388
- if (schema.identity.kind !== 'serverId' && result.serverId !== undefined) {
2389
- throw new Error(`Offline command returned serverId for source "${schema.sourceKey}" without serverId identity.`);
2672
+ if (schema.identity.kind !== 'generated' && result.remoteId !== undefined) {
2673
+ throw new Error(`Offline command returned generated remote id for source "${schema.sourceKey}" without generated identity.`);
2390
2674
  }
2391
2675
  if (schema.identity.kind === 'naturalKey') {
2392
2676
  const confirmedValues = result.confirmedValues ?? current.values;
2393
- const currentKey = offlineNaturalKeyFromValues(schema, current.values);
2677
+ const currentKey = current.identity.kind === 'natural' ? current.identity.naturalKey : offlineNaturalKeyFromValues(schema, current.values);
2394
2678
  const confirmedKey = offlineNaturalKeyFromValues(schema, confirmedValues);
2395
2679
  if (canonicalOfflineRemoteIdentity(schema, { naturalKey: currentKey }) !==
2396
2680
  canonicalOfflineRemoteIdentity(schema, { naturalKey: confirmedKey })) {
@@ -2405,6 +2689,7 @@ class OfflineSyncService {
2405
2689
  if (!session) {
2406
2690
  return false;
2407
2691
  }
2692
+ this.#assertSessionPrincipalBoundary(session);
2408
2693
  this.#setActiveUser(session.userId);
2409
2694
  this.#knownScopes.clear();
2410
2695
  for (const scope of session.scopes)
@@ -2420,6 +2705,7 @@ class OfflineSyncService {
2420
2705
  this.#knownScopes.clear();
2421
2706
  return true;
2422
2707
  }
2708
+ this.#assertSessionPrincipalBoundary(session);
2423
2709
  this.#setActiveUser(session.userId);
2424
2710
  this.#knownScopes.clear();
2425
2711
  for (const scope of session.scopes)
@@ -2436,6 +2722,14 @@ class OfflineSyncService {
2436
2722
  this.#activeUserId = userId;
2437
2723
  this.#lastCommandCreatedAt = 0;
2438
2724
  }
2725
+ #assertSessionPrincipalBoundary(session) {
2726
+ canonicalOfflinePrincipalId(session.userId);
2727
+ for (const scope of session.scopes) {
2728
+ if (scope.userId !== session.userId) {
2729
+ throw new Error('Offline sync session scope belongs to a different principal.');
2730
+ }
2731
+ }
2732
+ }
2439
2733
  async #readKnownCommands() {
2440
2734
  const commands = (await Promise.all([...this.#knownScopes.values()].map((scope) => this.#repository.getCommands(scope))))
2441
2735
  .flat()
@@ -2527,7 +2821,7 @@ class OfflineSyncService {
2527
2821
  return serialized;
2528
2822
  }
2529
2823
  #scopeKey(scope) {
2530
- return `${scope.userId}:${scope.scopeId}`;
2824
+ return `${canonicalOfflinePrincipalId(scope.userId)}:${scope.scopeId}`;
2531
2825
  }
2532
2826
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineSyncService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
2533
2827
  static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineSyncService, providedIn: 'root' }); }
@@ -2733,9 +3027,7 @@ function createOfflineAuthBridge(options) {
2733
3027
  };
2734
3028
  }
2735
3029
  function assertOfflineRemoteIdentity(identity) {
2736
- if (!Number.isSafeInteger(identity.userId) || identity.userId <= 0) {
2737
- throw new Error('Offline remote identity userId must be a positive safe integer.');
2738
- }
3030
+ canonicalOfflinePrincipalId(identity.userId);
2739
3031
  if (!Array.isArray(identity.scopeIds) || identity.scopeIds.some((scopeId) => typeof scopeId !== 'string' || scopeId.length === 0)) {
2740
3032
  throw new Error('Offline remote identity scopeIds must contain only non-empty strings.');
2741
3033
  }
@@ -2824,18 +3116,19 @@ const SCHEMA = [
2824
3116
  `CREATE TABLE IF NOT EXISTS offline_metadata (
2825
3117
  id INTEGER PRIMARY KEY CHECK (id = 1),
2826
3118
  schema_version INTEGER NOT NULL,
2827
- last_user_id INTEGER
3119
+ last_user_id TEXT
2828
3120
  )`,
2829
3121
  `CREATE TABLE IF NOT EXISTS offline_session_manifests (
2830
- user_id INTEGER PRIMARY KEY,
3122
+ user_id TEXT PRIMARY KEY,
2831
3123
  value_json TEXT NOT NULL
2832
3124
  )`,
2833
3125
  `CREATE TABLE IF NOT EXISTS offline_sync_commands (
2834
3126
  command_id TEXT PRIMARY KEY,
2835
- user_id INTEGER NOT NULL,
3127
+ user_id TEXT NOT NULL,
2836
3128
  scope_id TEXT NOT NULL,
2837
3129
  aggregate_type TEXT NOT NULL,
2838
- aggregate_local_id TEXT NOT NULL,
3130
+ source_key TEXT NOT NULL,
3131
+ identity_json TEXT NOT NULL,
2839
3132
  operation TEXT NOT NULL,
2840
3133
  payload_json TEXT NOT NULL,
2841
3134
  optimistic_value_json TEXT NOT NULL,
@@ -2856,7 +3149,7 @@ const SCHEMA = [
2856
3149
  schema_hash TEXT NOT NULL CHECK (length(schema_hash) = 64)
2857
3150
  )`,
2858
3151
  `CREATE TABLE IF NOT EXISTS offline_replica_cursors (
2859
- user_id INTEGER NOT NULL,
3152
+ user_id TEXT NOT NULL,
2860
3153
  scope_id TEXT NOT NULL,
2861
3154
  cursor TEXT NOT NULL,
2862
3155
  PRIMARY KEY (user_id, scope_id)
@@ -2875,85 +3168,70 @@ class SqliteOfflineRepository {
2875
3168
  }
2876
3169
  async getLastUserId() {
2877
3170
  const rows = await this.#query('SELECT last_user_id FROM offline_metadata WHERE id = 1');
2878
- return this.#numberOrNull(rows[0]?.['last_user_id']);
3171
+ const value = this.#stringOrNull(rows[0]?.['last_user_id']);
3172
+ return value === null ? null : parseOfflinePrincipalId(value);
2879
3173
  }
2880
3174
  async setLastUserId(userId) {
2881
3175
  await this.#write(`INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, ?)
2882
- ON CONFLICT(id) DO UPDATE SET schema_version = excluded.schema_version, last_user_id = excluded.last_user_id`, [OFFLINE_SCHEMA_VERSION, userId]);
3176
+ ON CONFLICT(id) DO UPDATE SET schema_version = excluded.schema_version, last_user_id = excluded.last_user_id`, [OFFLINE_SCHEMA_VERSION, canonicalOfflinePrincipalId(userId)]);
2883
3177
  }
2884
3178
  async getSessionManifest(userId) {
2885
- const rows = await this.#query('SELECT value_json FROM offline_session_manifests WHERE user_id = ?', [userId]);
3179
+ const rows = await this.#query('SELECT value_json FROM offline_session_manifests WHERE user_id = ?', [
3180
+ canonicalOfflinePrincipalId(userId),
3181
+ ]);
2886
3182
  const row = rows[0];
2887
3183
  return row ? this.#parse(row['value_json']) : null;
2888
3184
  }
2889
3185
  async putSessionManifest(userId, value) {
2890
3186
  await this.#write(`INSERT INTO offline_session_manifests (user_id, value_json) VALUES (?, ?)
2891
- ON CONFLICT(user_id) DO UPDATE SET value_json = excluded.value_json`, [userId, JSON.stringify(value)]);
3187
+ ON CONFLICT(user_id) DO UPDATE SET value_json = excluded.value_json`, [canonicalOfflinePrincipalId(userId), JSON.stringify(value)]);
2892
3188
  }
2893
- async getReplicaRow(scope, sourceKey, localId) {
2894
- const schema = this.#resolveReplicaEntitySchema(sourceKey);
2895
- const predicates = ['local_id = ?', '_offline_user_id = ?'];
2896
- const values = [localId, scope.userId];
2897
- if (schema.scope === 'partition') {
2898
- predicates.push('_offline_scope_id = ?');
2899
- values.push(scope.scopeId);
2900
- }
2901
- const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
2902
- const row = rows[0];
2903
- if (!row || (row['_offline_visibility'] ?? 'present') === 'pending_delete')
2904
- return null;
2905
- return this.#replicaRowFromSqliteRow(schema, scope, sourceKey, localId, row);
3189
+ async getReplicaRow(scope, sourceKey, identity) {
3190
+ const row = await this.#queryReplicaRow(scope, sourceKey, identity, false);
3191
+ return row;
2906
3192
  }
2907
- async getReplicaRowIncludingPendingDelete(scope, sourceKey, localId) {
2908
- const schema = this.#resolveReplicaEntitySchema(sourceKey);
2909
- const predicates = ['local_id = ?', '_offline_user_id = ?'];
2910
- const values = [localId, scope.userId];
2911
- if (schema.scope === 'partition') {
2912
- predicates.push('_offline_scope_id = ?');
2913
- values.push(scope.scopeId);
2914
- }
2915
- const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
2916
- const row = rows[0];
2917
- return row ? this.#replicaRowFromSqliteRow(schema, scope, sourceKey, localId, row) : null;
3193
+ async getReplicaRowIncludingPendingDelete(scope, sourceKey, identity) {
3194
+ const row = await this.#queryReplicaRow(scope, sourceKey, identity, true);
3195
+ return row;
2918
3196
  }
2919
3197
  async getReplicaRows(scope, sourceKey) {
2920
3198
  const schema = this.#resolveReplicaEntitySchema(sourceKey);
2921
3199
  const predicates = ['_offline_user_id = ?'];
2922
- const values = [scope.userId];
3200
+ const values = [canonicalOfflinePrincipalId(scope.userId)];
2923
3201
  if (schema.scope === 'partition') {
2924
3202
  predicates.push('_offline_scope_id = ?');
2925
3203
  values.push(scope.scopeId);
2926
3204
  }
2927
- const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')} ORDER BY local_id ASC`, values);
3205
+ const orderBy = schema.identity.kind === 'naturalKey'
3206
+ ? schema.identity.sourceKeys.map((key) => schema.fields.find((field) => field.sourceKey === key).sqliteColumnName).join(', ')
3207
+ : 'local_id ASC';
3208
+ const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')} ORDER BY ${orderBy}`, values);
2928
3209
  return rows
2929
3210
  .filter((row) => (row['_offline_visibility'] ?? 'present') !== 'pending_delete')
2930
- .map((row) => this.#replicaRowFromSqliteRow(schema, scope, sourceKey, this.#string(row['local_id']), row));
3211
+ .map((row) => this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row));
2931
3212
  }
2932
- async getReplicaRowByServerId(scope, sourceKey, serverId) {
2933
- const schema = this.#resolveReplicaEntitySchema(sourceKey);
2934
- if (!this.#schemaHasServerId(schema))
2935
- return null;
2936
- const predicates = ['server_id = ?', '_offline_user_id = ?'];
2937
- const values = [serverId, scope.userId];
2938
- if (schema.scope === 'partition') {
2939
- predicates.push('_offline_scope_id = ?');
2940
- values.push(scope.scopeId);
2941
- }
2942
- const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
2943
- const row = rows[0];
2944
- if (!row)
3213
+ async getReplicaRowByRemoteId(scope, sourceKey, remoteId) {
3214
+ if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
2945
3215
  return null;
2946
- return this.#replicaRowFromSqliteRow(schema, scope, sourceKey, this.#string(row['local_id']), row);
3216
+ return this.getReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });
2947
3217
  }
2948
3218
  async getReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
2949
3219
  const schema = this.#resolveReplicaEntitySchema(sourceKey);
2950
3220
  canonicalOfflineRemoteIdentity(schema, identity);
2951
- if (schema.identity.kind === 'serverId') {
2952
- return this.getReplicaRowByServerId(scope, sourceKey, identity.serverId);
3221
+ if (schema.identity.kind === 'generated') {
3222
+ const predicates = ['server_id = ?', '_offline_user_id = ?'];
3223
+ const values = [identity.remoteId, canonicalOfflinePrincipalId(scope.userId)];
3224
+ if (schema.scope === 'partition') {
3225
+ predicates.push('_offline_scope_id = ?');
3226
+ values.push(scope.scopeId);
3227
+ }
3228
+ const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
3229
+ const row = rows[0];
3230
+ return row ? this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row) : null;
2953
3231
  }
2954
3232
  const naturalKey = normalizeOfflineNaturalKey(schema, identity.naturalKey);
2955
3233
  const predicates = ['_offline_user_id = ?'];
2956
- const values = [scope.userId];
3234
+ const values = [canonicalOfflinePrincipalId(scope.userId)];
2957
3235
  if (schema.scope === 'partition') {
2958
3236
  predicates.push('_offline_scope_id = ?');
2959
3237
  values.push(scope.scopeId);
@@ -2965,13 +3243,11 @@ class SqliteOfflineRepository {
2965
3243
  }
2966
3244
  const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
2967
3245
  const row = rows[0];
2968
- if (!row)
2969
- return null;
2970
- return this.#replicaRowFromSqliteRow(schema, scope, sourceKey, this.#string(row['local_id']), row);
3246
+ return row ? this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row) : null;
2971
3247
  }
2972
3248
  async getReplicaCursor(scope) {
2973
3249
  const rows = await this.#query('SELECT cursor FROM offline_replica_cursors WHERE user_id = ? AND scope_id = ?', [
2974
- scope.userId,
3250
+ canonicalOfflinePrincipalId(scope.userId),
2975
3251
  scope.scopeId,
2976
3252
  ]);
2977
3253
  const row = rows[0];
@@ -2980,12 +3256,12 @@ class SqliteOfflineRepository {
2980
3256
  return { ...scope, cursor: this.#string(row['cursor']) };
2981
3257
  }
2982
3258
  async getCommands(scope) {
2983
- const rows = await this.#query('SELECT * FROM offline_sync_commands WHERE user_id = ? AND scope_id = ? ORDER BY created_at ASC, command_id ASC', [scope.userId, scope.scopeId]);
3259
+ const rows = await this.#query('SELECT * FROM offline_sync_commands WHERE user_id = ? AND scope_id = ? ORDER BY created_at ASC, command_id ASC', [canonicalOfflinePrincipalId(scope.userId), scope.scopeId]);
2984
3260
  return rows.map((row) => this.#command(row));
2985
3261
  }
2986
3262
  async getCommandsForUser(userId) {
2987
3263
  const rows = await this.#query('SELECT * FROM offline_sync_commands WHERE user_id = ? ORDER BY created_at ASC, command_id ASC', [
2988
- userId,
3264
+ canonicalOfflinePrincipalId(userId),
2989
3265
  ]);
2990
3266
  return rows.map((row) => this.#command(row));
2991
3267
  }
@@ -3000,19 +3276,26 @@ class SqliteOfflineRepository {
3000
3276
  }
3001
3277
  async clearUser(userId) {
3002
3278
  await this.#transaction(async (database) => {
3003
- await this.#execute(database, 'DELETE FROM offline_session_manifests WHERE user_id = ?', [userId]);
3004
- await this.#execute(database, 'DELETE FROM offline_sync_commands WHERE user_id = ?', [userId]);
3005
- await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ?', [userId]);
3279
+ const principal = canonicalOfflinePrincipalId(userId);
3280
+ await this.#execute(database, 'DELETE FROM offline_session_manifests WHERE user_id = ?', [principal]);
3281
+ await this.#execute(database, 'DELETE FROM offline_sync_commands WHERE user_id = ?', [principal]);
3282
+ await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ?', [principal]);
3006
3283
  for (const entity of this.#options.replicaSchema.entities) {
3007
- await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ?`, [userId]);
3284
+ await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ?`, [principal]);
3008
3285
  }
3009
- await this.#execute(database, 'UPDATE offline_metadata SET last_user_id = NULL WHERE id = 1 AND last_user_id = ?', [userId]);
3286
+ await this.#execute(database, 'UPDATE offline_metadata SET last_user_id = NULL WHERE id = 1 AND last_user_id = ?', [principal]);
3010
3287
  });
3011
3288
  }
3012
3289
  async clearScope(scope) {
3013
3290
  await this.#transaction(async (database) => {
3014
- const values = [scope.userId, scope.scopeId];
3015
- await this.#execute(database, 'DELETE FROM offline_sync_commands WHERE user_id = ? AND scope_id = ?', values);
3291
+ const values = [canonicalOfflinePrincipalId(scope.userId), scope.scopeId];
3292
+ const partitionSourceKeys = this.#options.replicaSchema.entities
3293
+ .filter((entity) => entity.scope === 'partition')
3294
+ .map((entity) => entity.sourceKey);
3295
+ if (partitionSourceKeys.length > 0) {
3296
+ await this.#execute(database, `DELETE FROM offline_sync_commands
3297
+ WHERE user_id = ? AND scope_id = ? AND source_key IN (${partitionSourceKeys.map(() => '?').join(', ')})`, [...values, ...partitionSourceKeys]);
3298
+ }
3016
3299
  await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ? AND scope_id = ?', values);
3017
3300
  for (const entity of this.#options.replicaSchema.entities) {
3018
3301
  if (entity.scope !== 'partition')
@@ -3022,15 +3305,16 @@ class SqliteOfflineRepository {
3022
3305
  });
3023
3306
  }
3024
3307
  async transactReplica(transaction) {
3308
+ for (const row of transaction.putRows ?? [])
3309
+ this.#validateReplicaRow(row);
3025
3310
  await this.#transaction(async (databaseId) => {
3026
3311
  const releases = new Map();
3027
- for (const release of transaction.releaseServerIds ?? []) {
3028
- if (!Number.isSafeInteger(release.serverId) || release.serverId <= 0) {
3029
- throw new Error(`Offline replica release has invalid serverId ${String(release.serverId)}.`);
3030
- }
3312
+ for (const release of transaction.releaseRemoteIds ?? []) {
3313
+ this.#assertValidReleaseRemoteId(release.remoteId);
3031
3314
  const key = this.#replicaRowKey(release);
3032
- if (releases.has(key))
3033
- throw new Error(`Offline replica serverId release is duplicated for ${release.sourceKey}/${release.localId}.`);
3315
+ if (releases.has(key)) {
3316
+ throw new Error(`Offline replica remoteId release is duplicated for ${release.sourceKey}/${canonicalOfflineReplicaIdentity(release.identity)}.`);
3317
+ }
3034
3318
  releases.set(key, release);
3035
3319
  }
3036
3320
  const consumedReleases = new Set();
@@ -3042,7 +3326,7 @@ class SqliteOfflineRepository {
3042
3326
  consumedReleases.add(key);
3043
3327
  }
3044
3328
  if (consumedReleases.size !== releases.size) {
3045
- throw new Error('Offline replica serverId release must match an existing row in putRows.');
3329
+ throw new Error('Offline replica remoteId release must match an existing row in putRows.');
3046
3330
  }
3047
3331
  for (const row of transaction.removeRows ?? [])
3048
3332
  await this.#removeReplicaRow(databaseId, row);
@@ -3065,29 +3349,20 @@ class SqliteOfflineRepository {
3065
3349
  this.#databaseId = databaseId;
3066
3350
  for (const statement of SCHEMA)
3067
3351
  await this.#execute(databaseId, statement);
3068
- let commandColumns = await this.#queryDatabase(databaseId, 'PRAGMA table_info(offline_sync_commands)');
3069
- if (commandColumns.some((column) => column['name'] === 'aggregate_id')) {
3070
- await this.#execute(databaseId, 'ALTER TABLE offline_sync_commands RENAME COLUMN aggregate_id TO aggregate_local_id');
3071
- commandColumns = await this.#queryDatabase(databaseId, 'PRAGMA table_info(offline_sync_commands)');
3072
- }
3073
- if (!commandColumns.some((column) => column['name'] === 'optimistic_value_json')) {
3074
- await this.#execute(databaseId, 'ALTER TABLE offline_sync_commands ADD COLUMN optimistic_value_json TEXT');
3075
- }
3076
- if (!commandColumns.some((column) => column['name'] === 'replica_mutation')) {
3077
- await this.#execute(databaseId, "ALTER TABLE offline_sync_commands ADD COLUMN replica_mutation TEXT NOT NULL DEFAULT 'upsert'");
3078
- }
3079
- // Keep this repair outside the ADD-column branch so a process/database
3080
- // failure after ALTER but before backfill is retried on every open.
3081
- await this.#execute(databaseId, 'UPDATE offline_sync_commands SET optimistic_value_json = payload_json WHERE optimistic_value_json IS NULL');
3082
- await this.#execute(databaseId, `INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, NULL)
3083
- ON CONFLICT(id) DO UPDATE SET schema_version = excluded.schema_version`, [OFFLINE_SCHEMA_VERSION]);
3084
- await this.#initializeReplicaSchema(databaseId);
3085
- for (const entity of this.#options.replicaSchema.entities) {
3086
- const columns = await this.#queryDatabase(databaseId, `PRAGMA table_info(${entity.tableName})`);
3087
- if (!columns.some((column) => column['name'] === '_offline_visibility')) {
3088
- await this.#execute(databaseId, `ALTER TABLE ${entity.tableName} ADD COLUMN _offline_visibility TEXT NOT NULL DEFAULT 'present'`);
3352
+ const metadata = await this.#queryDatabase(databaseId, 'SELECT schema_version FROM offline_metadata WHERE id = 1');
3353
+ if (metadata.length === 0) {
3354
+ await this.#execute(databaseId, 'INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, NULL)', [
3355
+ OFFLINE_SCHEMA_VERSION,
3356
+ ]);
3357
+ }
3358
+ else {
3359
+ const storedVersion = this.#number(metadata[0]['schema_version']);
3360
+ if (storedVersion !== OFFLINE_SCHEMA_VERSION) {
3361
+ throw new Error(`Unsupported offline storage schema version ${storedVersion}; expected ${OFFLINE_SCHEMA_VERSION}. ` +
3362
+ 'A lossless core schema migration is required before this database can be opened.');
3089
3363
  }
3090
3364
  }
3365
+ await this.#initializeReplicaSchema(databaseId);
3091
3366
  }
3092
3367
  async #initializeReplicaSchema(databaseId) {
3093
3368
  const bundle = this.#options.replicaSchema;
@@ -3184,10 +3459,11 @@ class SqliteOfflineRepository {
3184
3459
  #command(row) {
3185
3460
  return {
3186
3461
  commandId: this.#string(row['command_id']),
3187
- userId: this.#number(row['user_id']),
3462
+ userId: parseOfflinePrincipalId(this.#string(row['user_id'])),
3188
3463
  scopeId: this.#string(row['scope_id']),
3189
3464
  aggregateType: this.#string(row['aggregate_type']),
3190
- aggregateLocalId: this.#string(row['aggregate_local_id']),
3465
+ sourceKey: this.#string(row['source_key']),
3466
+ identity: parseOfflineCommandIdentity(this.#parse(row['identity_json'])),
3191
3467
  operation: this.#string(row['operation']),
3192
3468
  payload: this.#parse(row['payload_json']),
3193
3469
  optimisticValue: this.#parse(row['optimistic_value_json']),
@@ -3203,21 +3479,23 @@ class SqliteOfflineRepository {
3203
3479
  }
3204
3480
  #putCommand(databaseId, command) {
3205
3481
  return this.#execute(databaseId, `INSERT INTO offline_sync_commands
3206
- (command_id, user_id, scope_id, aggregate_type, aggregate_local_id, operation, payload_json, optimistic_value_json,
3482
+ (command_id, user_id, scope_id, aggregate_type, source_key, identity_json, operation, payload_json, optimistic_value_json,
3207
3483
  replica_mutation, payload_hash, base_revision_json, state, attempts, retry_at, created_at, last_error_code)
3208
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
3484
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
3209
3485
  ON CONFLICT(command_id) DO UPDATE SET
3210
3486
  user_id = excluded.user_id, scope_id = excluded.scope_id, aggregate_type = excluded.aggregate_type,
3211
- aggregate_local_id = excluded.aggregate_local_id, operation = excluded.operation, payload_json = excluded.payload_json,
3487
+ source_key = excluded.source_key,
3488
+ identity_json = excluded.identity_json, operation = excluded.operation, payload_json = excluded.payload_json,
3212
3489
  optimistic_value_json = excluded.optimistic_value_json, replica_mutation = excluded.replica_mutation,
3213
3490
  payload_hash = excluded.payload_hash,
3214
3491
  base_revision_json = excluded.base_revision_json, state = excluded.state, attempts = excluded.attempts,
3215
3492
  retry_at = excluded.retry_at, created_at = excluded.created_at, last_error_code = excluded.last_error_code`, [
3216
3493
  command.commandId,
3217
- command.userId,
3494
+ canonicalOfflinePrincipalId(command.userId),
3218
3495
  command.scopeId,
3219
3496
  command.aggregateType,
3220
- command.aggregateLocalId,
3497
+ command.sourceKey,
3498
+ serializeOfflineCommandIdentity(command.identity),
3221
3499
  command.operation,
3222
3500
  JSON.stringify(command.payload),
3223
3501
  JSON.stringify(command.optimisticValue),
@@ -3231,59 +3509,132 @@ class SqliteOfflineRepository {
3231
3509
  command.lastErrorCode,
3232
3510
  ]);
3233
3511
  }
3512
+ async #queryReplicaRow(scope, sourceKey, identity, includePendingDelete) {
3513
+ const schema = this.#resolveReplicaEntitySchema(sourceKey);
3514
+ const predicates = ['_offline_user_id = ?'];
3515
+ const values = [canonicalOfflinePrincipalId(scope.userId)];
3516
+ if (schema.scope === 'partition') {
3517
+ predicates.push('_offline_scope_id = ?');
3518
+ values.push(scope.scopeId);
3519
+ }
3520
+ if (identity.kind === 'generated' || identity.kind === 'local') {
3521
+ if ((identity.kind === 'generated' && schema.identity.kind !== 'generated') ||
3522
+ (identity.kind === 'local' && schema.identity.kind !== 'localOnly')) {
3523
+ return null;
3524
+ }
3525
+ predicates.push('local_id = ?');
3526
+ values.push(identity.localId);
3527
+ }
3528
+ else {
3529
+ const naturalKey = normalizeOfflineNaturalKey(schema, identity.naturalKey);
3530
+ for (const sourceKeyPart of schema.identity.sourceKeys) {
3531
+ const field = schema.fields.find((candidate) => candidate.sourceKey === sourceKeyPart);
3532
+ predicates.push(`${field.sqliteColumnName} = ?`);
3533
+ values.push(naturalKey[sourceKeyPart]);
3534
+ }
3535
+ }
3536
+ const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
3537
+ const row = rows[0];
3538
+ if (!row || (!includePendingDelete && (row['_offline_visibility'] ?? 'present') === 'pending_delete'))
3539
+ return null;
3540
+ return this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row);
3541
+ }
3234
3542
  async #putReplicaRow(databaseId, row, release) {
3235
3543
  const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
3236
- assertOfflineReplicaServerId(schema, row.serverId);
3544
+ if (row.identity.kind === 'generated') {
3545
+ assertOfflineReplicaGeneratedRemoteId(schema, row.identity.remoteId);
3546
+ }
3547
+ if (schema.identity.kind === 'naturalKey') {
3548
+ if (row.identity.kind !== 'natural') {
3549
+ throw new Error(`Offline replica source "${row.sourceKey}" requires natural identity.`);
3550
+ }
3551
+ const valuesIdentity = offlineNaturalKeyFromValues(schema, row.values);
3552
+ if (canonicalOfflineRemoteIdentity(schema, { naturalKey: row.identity.naturalKey }) !==
3553
+ canonicalOfflineRemoteIdentity(schema, { naturalKey: valuesIdentity })) {
3554
+ throw new Error(`Offline replica identity naturalKey must match values for "${schema.sourceKey}".`);
3555
+ }
3556
+ }
3237
3557
  const encoded = encodeOfflineReplicaValues(schema, row.values);
3238
3558
  if (row.confirmedValues !== null)
3239
3559
  encodeOfflineReplicaValues(schema, row.confirmedValues);
3240
3560
  assertOfflineReplicaNaturalKeyBaseline(schema, row.values, row.confirmedValues);
3241
- const existing = await this.getReplicaRowIncludingPendingDelete(row, row.sourceKey, row.localId);
3561
+ const existing = await this.#queryReplicaRow(row, row.sourceKey, replicaAddressFromIdentity(row.identity), true);
3242
3562
  if (!existing && release) {
3243
- throw new Error(`Offline replica serverId release requires an existing row for ${row.sourceKey}/${row.localId}.`);
3563
+ throw new Error(`Offline replica remoteId release requires an existing row for ${row.sourceKey}/${canonicalOfflineReplicaIdentity(row.identity)}.`);
3244
3564
  }
3245
3565
  if (existing)
3246
3566
  this.#assertReplicaIdentityAssignment(schema, existing, row, release);
3247
3567
  const confirmedValues = row.confirmedValues === null ? null : projectOfflineReplicaValues(schema, row.confirmedValues);
3248
3568
  const { sql, domainColumns } = this.#buildReplicaUpsertStatement(schema);
3249
- const values = [
3250
- row.localId,
3251
- row.userId,
3252
- ...(schema.scope === 'partition' ? [row.scopeId] : []),
3253
- ...(this.#schemaHasServerId(schema) ? [row.serverId] : []),
3254
- confirmedValues === null ? null : JSON.stringify(confirmedValues),
3255
- row.serverRevision == null ? null : JSON.stringify(row.serverRevision),
3256
- row.syncState,
3257
- row.visibility ?? 'present',
3258
- row.fetchedAt,
3259
- ...domainColumns.map((column) => encoded[column] ?? null),
3260
- ];
3569
+ const values = [];
3570
+ if (schema.identity.kind === 'generated' || schema.identity.kind === 'localOnly') {
3571
+ const expectedKind = schema.identity.kind === 'generated' ? 'generated' : 'local';
3572
+ if (row.identity.kind !== expectedKind) {
3573
+ throw new Error(`Offline replica source "${row.sourceKey}" requires ${expectedKind} identity.`);
3574
+ }
3575
+ values.push(row.identity.localId);
3576
+ }
3577
+ values.push(canonicalOfflinePrincipalId(row.userId));
3578
+ if (schema.scope === 'partition')
3579
+ values.push(row.scopeId);
3580
+ if (schema.identity.kind === 'generated') {
3581
+ if (row.identity.kind !== 'generated') {
3582
+ throw new Error(`Offline replica source "${row.sourceKey}" requires generated identity.`);
3583
+ }
3584
+ values.push(row.identity.remoteId);
3585
+ }
3586
+ values.push(confirmedValues === null ? null : JSON.stringify(confirmedValues), row.serverRevision == null ? null : JSON.stringify(row.serverRevision), row.syncState, row.visibility ?? 'present', row.fetchedAt, ...domainColumns.map((column) => encoded[column] ?? null));
3261
3587
  await this.#execute(databaseId, sql, values);
3262
3588
  }
3263
3589
  #removeReplicaRow(databaseId, key) {
3264
3590
  const schema = this.#resolveReplicaEntitySchema(key.sourceKey);
3265
- const predicates = ['local_id = ?', '_offline_user_id = ?'];
3266
- const values = [key.localId, key.userId];
3591
+ const predicates = ['_offline_user_id = ?'];
3592
+ const values = [canonicalOfflinePrincipalId(key.userId)];
3267
3593
  if (schema.scope === 'partition') {
3268
3594
  predicates.push('_offline_scope_id = ?');
3269
3595
  values.push(key.scopeId);
3270
3596
  }
3597
+ if (key.identity.kind === 'generated' || key.identity.kind === 'local') {
3598
+ predicates.push('local_id = ?');
3599
+ values.push(key.identity.localId);
3600
+ }
3601
+ else {
3602
+ for (const sourceKeyPart of schema.identity.sourceKeys) {
3603
+ const field = schema.fields.find((candidate) => candidate.sourceKey === sourceKeyPart);
3604
+ predicates.push(`${field.sqliteColumnName} = ?`);
3605
+ values.push(key.identity.naturalKey[sourceKeyPart]);
3606
+ }
3607
+ }
3271
3608
  return this.#execute(databaseId, `DELETE FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
3272
3609
  }
3273
3610
  #putReplicaCursor(databaseId, cursor) {
3274
3611
  return this.#execute(databaseId, `INSERT INTO offline_replica_cursors (user_id, scope_id, cursor) VALUES (?, ?, ?)
3275
- ON CONFLICT(user_id, scope_id) DO UPDATE SET cursor = excluded.cursor`, [cursor.userId, cursor.scopeId, cursor.cursor]);
3612
+ ON CONFLICT(user_id, scope_id) DO UPDATE SET cursor = excluded.cursor`, [canonicalOfflinePrincipalId(cursor.userId), cursor.scopeId, cursor.cursor]);
3276
3613
  }
3277
3614
  #buildReplicaUpsertStatement(schema) {
3278
- const insertColumns = ['local_id', '_offline_user_id'];
3615
+ const insertColumns = ['_offline_user_id'];
3279
3616
  const updateSets = ['_offline_user_id = excluded._offline_user_id'];
3617
+ const conflictTarget = ['_offline_user_id'];
3280
3618
  if (schema.scope === 'partition') {
3281
3619
  insertColumns.push('_offline_scope_id');
3282
3620
  updateSets.push('_offline_scope_id = excluded._offline_scope_id');
3621
+ conflictTarget.push('_offline_scope_id');
3283
3622
  }
3284
- if (this.#schemaHasServerId(schema)) {
3623
+ if (schema.identity.kind === 'generated') {
3624
+ insertColumns.unshift('local_id');
3285
3625
  insertColumns.push('server_id');
3286
3626
  updateSets.push('server_id = excluded.server_id');
3627
+ conflictTarget.push('local_id');
3628
+ }
3629
+ else if (schema.identity.kind === 'naturalKey') {
3630
+ for (const sourceKey of schema.identity.sourceKeys) {
3631
+ const field = schema.fields.find((candidate) => candidate.sourceKey === sourceKey);
3632
+ conflictTarget.push(field.sqliteColumnName);
3633
+ }
3634
+ }
3635
+ else {
3636
+ insertColumns.unshift('local_id');
3637
+ conflictTarget.push('local_id');
3287
3638
  }
3288
3639
  insertColumns.push('_offline_confirmed_json', '_offline_server_revision_json', '_offline_sync_state', '_offline_visibility', '_offline_fetched_at');
3289
3640
  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');
@@ -3299,16 +3650,16 @@ class SqliteOfflineRepository {
3299
3650
  return {
3300
3651
  sql: `INSERT INTO ${schema.tableName} (${insertColumns.join(', ')})
3301
3652
  VALUES (${placeholders})
3302
- ON CONFLICT(local_id) DO UPDATE SET ${updateSets.join(', ')}`,
3653
+ ON CONFLICT(${conflictTarget.join(', ')}) DO UPDATE SET ${updateSets.join(', ')}`,
3303
3654
  domainColumns,
3304
3655
  };
3305
3656
  }
3306
- #replicaRowFromSqliteRow(schema, scope, sourceKey, localId, row) {
3657
+ #replicaRowFromSqliteRow(schema, scope, sourceKey, row) {
3658
+ const identity = this.#identityFromSqliteRow(schema, row);
3307
3659
  return {
3308
3660
  ...scope,
3309
3661
  sourceKey,
3310
- localId,
3311
- serverId: this.#schemaHasServerId(schema) ? this.#numberOrNull(row['server_id']) : null,
3662
+ identity,
3312
3663
  values: decodeOfflineReplicaValues(schema, row),
3313
3664
  confirmedValues: this.#parseNullable(row['_offline_confirmed_json']),
3314
3665
  serverRevision: this.#parseNullable(row['_offline_server_revision_json']),
@@ -3317,46 +3668,111 @@ class SqliteOfflineRepository {
3317
3668
  visibility: (row['_offline_visibility'] ?? 'present'),
3318
3669
  };
3319
3670
  }
3671
+ #identityFromSqliteRow(schema, row) {
3672
+ if (schema.identity.kind === 'naturalKey') {
3673
+ return offlineNaturalReplicaIdentity(schema, decodeOfflineReplicaValues(schema, row));
3674
+ }
3675
+ const localId = this.#string(row['local_id']);
3676
+ if (schema.identity.kind === 'localOnly')
3677
+ return { kind: 'local', localId };
3678
+ const remoteId = row['server_id'];
3679
+ if (remoteId == null)
3680
+ return offlineGeneratedReplicaIdentity(localId, null);
3681
+ if (schema.identity.kind === 'generated' && schema.identity.affinity === 'TEXT') {
3682
+ return offlineGeneratedReplicaIdentity(localId, this.#string(remoteId));
3683
+ }
3684
+ return offlineGeneratedReplicaIdentity(localId, this.#number(remoteId));
3685
+ }
3320
3686
  #resolveReplicaEntitySchema(sourceKey) {
3321
3687
  const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);
3322
3688
  if (!schema)
3323
3689
  throw new Error(`Unknown offline replica source key "${sourceKey}".`);
3324
3690
  return schema;
3325
3691
  }
3326
- #schemaHasServerId(schema) {
3327
- return schema.identity.kind === 'serverId';
3692
+ #validateReplicaRow(row) {
3693
+ const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
3694
+ if (schema.identity.kind === 'localOnly') {
3695
+ if (row.identity.kind !== 'local') {
3696
+ throw new Error(`Offline replica source "${schema.sourceKey}" requires local identity.`);
3697
+ }
3698
+ }
3699
+ else if (schema.identity.kind === 'generated') {
3700
+ if (row.identity.kind !== 'generated') {
3701
+ throw new Error(`Offline replica source "${schema.sourceKey}" requires generated identity.`);
3702
+ }
3703
+ assertOfflineReplicaGeneratedRemoteId(schema, row.identity.remoteId);
3704
+ }
3705
+ else {
3706
+ if (row.identity.kind !== 'natural') {
3707
+ throw new Error(`Offline replica source "${schema.sourceKey}" requires natural identity.`);
3708
+ }
3709
+ const fromValues = offlineNaturalKeyFromValues(schema, row.values);
3710
+ if (canonicalOfflineRemoteIdentity(schema, { naturalKey: row.identity.naturalKey }) !==
3711
+ canonicalOfflineRemoteIdentity(schema, { naturalKey: fromValues })) {
3712
+ throw new Error(`Offline replica identity naturalKey must match values for "${schema.sourceKey}".`);
3713
+ }
3714
+ }
3715
+ encodeOfflineReplicaValues(schema, row.values);
3716
+ if (row.confirmedValues !== null)
3717
+ encodeOfflineReplicaValues(schema, row.confirmedValues);
3718
+ assertOfflineReplicaNaturalKeyBaseline(schema, row.values, row.confirmedValues);
3328
3719
  }
3329
3720
  #replicaRowKey(row) {
3330
3721
  const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
3331
- return `${row.userId}:${schema.scope === 'user' ? 'user' : row.scopeId}:${row.sourceKey}:${row.localId}`;
3722
+ return `${canonicalOfflinePrincipalId(row.userId)}:${schema.scope === 'user' ? 'user' : row.scopeId}:${row.sourceKey}:${canonicalOfflineReplicaIdentity(row.identity)}`;
3332
3723
  }
3333
3724
  #assertReplicaIdentityAssignment(schema, existing, incoming, release) {
3334
- if (release && schema.identity.kind !== 'serverId') {
3335
- throw new Error(`Offline replica serverId release is unsupported for source "${incoming.sourceKey}".`);
3725
+ if (release && schema.identity.kind !== 'generated') {
3726
+ throw new Error(`Offline replica remoteId release is unsupported for source "${incoming.sourceKey}".`);
3336
3727
  }
3337
- if (schema.identity.kind === 'serverId') {
3728
+ if (schema.identity.kind === 'localOnly') {
3729
+ if (existing.identity.kind !== 'local' || incoming.identity.kind !== 'local') {
3730
+ throw new Error(`Offline replica local identity is required for "${incoming.sourceKey}".`);
3731
+ }
3732
+ if (existing.identity.localId !== incoming.identity.localId) {
3733
+ throw new Error(`Offline replica localId is immutable for "${schema.sourceKey}".`);
3734
+ }
3735
+ return;
3736
+ }
3737
+ if (schema.identity.kind === 'generated') {
3738
+ if (existing.identity.kind !== 'generated' || incoming.identity.kind !== 'generated') {
3739
+ throw new Error(`Offline replica generated identity is required for "${incoming.sourceKey}".`);
3740
+ }
3338
3741
  if (release) {
3339
- if (existing.serverId !== release.serverId || incoming.serverId !== null) {
3340
- throw new Error(`Offline replica serverId release must transition current=${existing.serverId} to incoming=null for ${incoming.sourceKey}/${incoming.localId}.`);
3742
+ if (existing.identity.remoteId !== release.remoteId || incoming.identity.remoteId !== null) {
3743
+ throw new Error(`Offline replica remoteId release must transition current=${String(existing.identity.remoteId)} to incoming=null for ${incoming.sourceKey}/${incoming.identity.localId}.`);
3341
3744
  }
3342
3745
  return;
3343
3746
  }
3344
- if (existing.serverId !== null && existing.serverId !== incoming.serverId) {
3345
- throw new Error(`Offline replica serverId is immutable: current=${existing.serverId}, incoming=${String(incoming.serverId)}.`);
3747
+ if (existing.identity.localId !== incoming.identity.localId) {
3748
+ throw new Error(`Offline replica localId is immutable for "${schema.sourceKey}".`);
3749
+ }
3750
+ if (existing.identity.remoteId !== null && existing.identity.remoteId !== incoming.identity.remoteId) {
3751
+ throw new Error(`Offline replica remoteId is immutable: current=${String(existing.identity.remoteId)}, incoming=${String(incoming.identity.remoteId)}.`);
3346
3752
  }
3347
3753
  return;
3348
3754
  }
3349
3755
  if (schema.identity.kind === 'naturalKey') {
3350
- const current = canonicalOfflineRemoteIdentity(schema, {
3351
- naturalKey: offlineNaturalKeyFromValues(schema, existing.values),
3352
- });
3353
- const next = canonicalOfflineRemoteIdentity(schema, {
3354
- naturalKey: offlineNaturalKeyFromValues(schema, incoming.values),
3355
- });
3756
+ if (existing.identity.kind !== 'natural' || incoming.identity.kind !== 'natural') {
3757
+ throw new Error(`Offline replica natural identity is required for "${schema.sourceKey}".`);
3758
+ }
3759
+ const current = canonicalOfflineRemoteIdentity(schema, { naturalKey: existing.identity.naturalKey });
3760
+ const next = canonicalOfflineRemoteIdentity(schema, { naturalKey: incoming.identity.naturalKey });
3356
3761
  if (current !== next)
3357
3762
  throw new Error(`Offline replica naturalKey is immutable for "${schema.sourceKey}".`);
3358
3763
  }
3359
3764
  }
3765
+ #assertValidReleaseRemoteId(remoteId) {
3766
+ if (typeof remoteId === 'number') {
3767
+ if (!Number.isSafeInteger(remoteId) || remoteId <= 0) {
3768
+ throw new Error(`Offline replica release has invalid remoteId ${String(remoteId)}.`);
3769
+ }
3770
+ return;
3771
+ }
3772
+ if (typeof remoteId !== 'string' || remoteId.length === 0) {
3773
+ throw new Error(`Offline replica release has invalid remoteId ${String(remoteId)}.`);
3774
+ }
3775
+ }
3360
3776
  async #execute(databaseId, statement, values = []) {
3361
3777
  await this.#sqlite.execute({ databaseId, statement, values });
3362
3778
  }
@@ -3503,5 +3919,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
3503
3919
  * Generated bundle index. Do not edit.
3504
3920
  */
3505
3921
 
3506
- 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 };
3922
+ 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, assertOfflineLocalId, assertOfflineReplicaGeneratedRemoteId, assertOfflineReplicaNaturalKeyBaseline, booleanColumn, canonicalOfflineCommandIdentity, canonicalOfflinePrincipalId, canonicalOfflineRemoteIdentity, canonicalOfflineReplicaIdentity, commandIdentityFromReplicaIdentity, commandIdentityMatchesReplicaRow, createCommunitySqliteDriver, createOfflineAuthBridge, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, generatedId, ignored, integer, isOfflineFallbackError, json, localOnly, naturalKey, normalizeOfflineNaturalKey, nullable, offlineCommandLookupIdentity, offlineCommandTargetFromReplicaRow, offlineGeneratedReplicaIdentity, offlineInterceptor, offlineNaturalKeyFromValues, offlineNaturalReplicaIdentity, offlineReplicaRemoteIdentity, parseOfflineCommandIdentity, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineRequestPolicy, real, replicaAddressFromIdentity, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, text };
3507
3923
  //# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map