@rdlabo/ionic-angular-kit 21.5.8 → 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
|
|
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
|
-
|
|
80
|
-
|
|
81
|
-
return { kind: 'serverId' };
|
|
79
|
+
function generatedId(kind) {
|
|
80
|
+
return { kind: 'remoteId', affinity: kind === 'integer' ? 'INTEGER' : 'TEXT' };
|
|
82
81
|
}
|
|
83
|
-
/** Declares an ordered
|
|
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
|
-
/**
|
|
88
|
-
function
|
|
89
|
-
|
|
90
|
-
|
|
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$
|
|
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$
|
|
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 === '
|
|
130
|
-
if (!('
|
|
131
|
-
throw new Error(`Offline replica source "${schema.sourceKey}" requires
|
|
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
|
-
|
|
134
|
-
return `
|
|
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) || '
|
|
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
|
|
161
|
-
if (
|
|
162
|
-
throw new Error(
|
|
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.`);
|
|
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;
|
|
163
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
|
|
185
|
-
if (
|
|
186
|
-
throw new Error('Replica entity must define at most one
|
|
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 === '
|
|
221
|
+
const serverField = fields.find((field) => field.policy === 'remoteId');
|
|
206
222
|
if (definition && serverField)
|
|
207
|
-
throw new Error('Replica entity cannot
|
|
223
|
+
throw new Error('Replica entity cannot combine a generated id field with another identity.');
|
|
208
224
|
if (serverField)
|
|
209
|
-
return { kind: '
|
|
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 === '
|
|
259
|
+
if (fieldDef.kind === 'remoteId') {
|
|
242
260
|
return {
|
|
243
261
|
sourceKey,
|
|
244
|
-
policy: '
|
|
262
|
+
policy: 'remoteId',
|
|
245
263
|
sqliteColumnName: 'server_id',
|
|
246
|
-
affinity:
|
|
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 = ['
|
|
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 === '
|
|
273
|
-
columnLines.push('server_id
|
|
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
|
|
284
|
-
|
|
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 === '
|
|
301
|
-
return `${field.sourceKey}:
|
|
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
|
-
? [`
|
|
311
|
-
:
|
|
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 `
|
|
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$
|
|
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$
|
|
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 `
|
|
414
|
-
* identical; the server identifier remains available through the replica row's dedicated `
|
|
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$
|
|
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 =
|
|
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[
|
|
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[
|
|
895
|
+
manifests[canonicalOfflinePrincipalId(userId)] = value;
|
|
727
896
|
return manifests;
|
|
728
897
|
});
|
|
729
898
|
}
|
|
730
|
-
async getReplicaRow(scope, sourceKey,
|
|
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 =
|
|
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,
|
|
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 =
|
|
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.
|
|
931
|
+
.sort((left, right) => this.#compareReplicaIdentity(schema, left.identity, right.identity));
|
|
763
932
|
}
|
|
764
|
-
async
|
|
765
|
-
|
|
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
|
-
|
|
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 =
|
|
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[
|
|
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) =>
|
|
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
|
-
|
|
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
|
|
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
|
}
|
|
@@ -1036,18 +1188,38 @@ class IonicOfflineRepository {
|
|
|
1036
1188
|
this.#readRecord(CURSORS_KEY),
|
|
1037
1189
|
]);
|
|
1038
1190
|
const identityCheckRows = { ...rows };
|
|
1191
|
+
const releases = new Map();
|
|
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)}.`);
|
|
1197
|
+
}
|
|
1198
|
+
releases.set(key, release);
|
|
1199
|
+
}
|
|
1200
|
+
const consumedReleases = new Set();
|
|
1039
1201
|
for (const row of transaction.putRows ?? []) {
|
|
1040
|
-
const
|
|
1202
|
+
const key = this.#rowKey(row);
|
|
1203
|
+
const existing = identityCheckRows[key];
|
|
1204
|
+
const release = releases.get(key);
|
|
1205
|
+
if (!existing && release) {
|
|
1206
|
+
throw new Error(`Offline replica remoteId release requires an existing row for ${row.sourceKey}/${canonicalOfflineReplicaIdentity(row.identity)}.`);
|
|
1207
|
+
}
|
|
1041
1208
|
if (existing)
|
|
1042
|
-
this.#assertReplicaIdentityAssignment(existing, row);
|
|
1209
|
+
this.#assertReplicaIdentityAssignment(existing, row, release);
|
|
1210
|
+
if (release)
|
|
1211
|
+
consumedReleases.add(key);
|
|
1043
1212
|
this.#assertUniqueReplicaIdentity(identityCheckRows, row);
|
|
1044
|
-
identityCheckRows[
|
|
1213
|
+
identityCheckRows[key] = row;
|
|
1214
|
+
}
|
|
1215
|
+
if (consumedReleases.size !== releases.size) {
|
|
1216
|
+
throw new Error('Offline replica remoteId release must match an existing row in putRows.');
|
|
1045
1217
|
}
|
|
1046
1218
|
if (journal)
|
|
1047
1219
|
await this.#storage.set(REPLICA_TRANSACTION_KEY, transaction);
|
|
1048
1220
|
for (const row of transaction.putRows ?? []) {
|
|
1049
1221
|
const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
|
|
1050
|
-
rows[this.#rowKey(row
|
|
1222
|
+
rows[this.#rowKey(row)] = {
|
|
1051
1223
|
...row,
|
|
1052
1224
|
scopeId: schema.scope === 'user' ? '' : row.scopeId,
|
|
1053
1225
|
values: projectOfflineReplicaValues(schema, row.values),
|
|
@@ -1055,7 +1227,7 @@ class IonicOfflineRepository {
|
|
|
1055
1227
|
};
|
|
1056
1228
|
}
|
|
1057
1229
|
for (const row of transaction.removeRows ?? []) {
|
|
1058
|
-
delete rows[this.#rowKey(row
|
|
1230
|
+
delete rows[this.#rowKey(row)];
|
|
1059
1231
|
}
|
|
1060
1232
|
for (const command of transaction.putCommands ?? [])
|
|
1061
1233
|
commands[command.commandId] = command;
|
|
@@ -1094,36 +1266,96 @@ class IonicOfflineRepository {
|
|
|
1094
1266
|
this.#writes = write.catch(() => undefined);
|
|
1095
1267
|
return write;
|
|
1096
1268
|
}
|
|
1097
|
-
#rowKey(
|
|
1098
|
-
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
1099
|
-
const partition = schema.scope === 'user' ? 'user' : String(
|
|
1100
|
-
return `${
|
|
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
|
+
});
|
|
1101
1291
|
}
|
|
1102
1292
|
#rowForScope(row, schema, scope) {
|
|
1103
1293
|
const normalized = { ...row, visibility: row.visibility ?? 'present' };
|
|
1104
1294
|
return schema.scope === 'user' ? { ...normalized, scopeId: scope.scopeId } : normalized;
|
|
1105
1295
|
}
|
|
1106
1296
|
#cursorKey(scope) {
|
|
1107
|
-
return `${scope.userId}:${scope.scopeId}`;
|
|
1108
|
-
}
|
|
1109
|
-
#
|
|
1110
|
-
|
|
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);
|
|
1111
1318
|
}
|
|
1112
1319
|
#validateReplicaRow(row) {
|
|
1113
1320
|
const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
|
|
1114
|
-
|
|
1321
|
+
this.#validateRowIdentity(schema, row);
|
|
1115
1322
|
encodeOfflineReplicaValues(schema, row.values);
|
|
1116
1323
|
if (row.confirmedValues !== null)
|
|
1117
1324
|
encodeOfflineReplicaValues(schema, row.confirmedValues);
|
|
1118
1325
|
assertOfflineReplicaNaturalKeyBaseline(schema, row.values, row.confirmedValues);
|
|
1119
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
|
+
}
|
|
1120
1352
|
#assertUniqueReplicaIdentity(rows, incoming) {
|
|
1121
1353
|
const schema = this.#resolveReplicaEntitySchema(incoming.sourceKey);
|
|
1122
|
-
const identity =
|
|
1354
|
+
const identity = offlineReplicaRemoteIdentity(schema, incoming.identity);
|
|
1123
1355
|
if (identity === null)
|
|
1124
1356
|
return;
|
|
1125
1357
|
const canonical = canonicalOfflineRemoteIdentity(schema, identity);
|
|
1126
|
-
const incomingKey = this.#rowKey(incoming
|
|
1358
|
+
const incomingKey = this.#rowKey(incoming);
|
|
1127
1359
|
const collision = Object.entries(rows).find(([key, row]) => {
|
|
1128
1360
|
if (key === incomingKey)
|
|
1129
1361
|
return false;
|
|
@@ -1131,41 +1363,72 @@ class IonicOfflineRepository {
|
|
|
1131
1363
|
return false;
|
|
1132
1364
|
if (schema.scope === 'partition' && row.scopeId !== incoming.scopeId)
|
|
1133
1365
|
return false;
|
|
1134
|
-
const rowIdentity =
|
|
1366
|
+
const rowIdentity = offlineReplicaRemoteIdentity(schema, row.identity);
|
|
1135
1367
|
return rowIdentity !== null && canonicalOfflineRemoteIdentity(schema, rowIdentity) === canonical;
|
|
1136
1368
|
});
|
|
1137
1369
|
if (collision) {
|
|
1138
|
-
if (schema.identity.kind === '
|
|
1139
|
-
|
|
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}.`);
|
|
1140
1376
|
}
|
|
1141
|
-
throw new Error(`Offline replica remote identity is already mapped to
|
|
1377
|
+
throw new Error(`Offline replica remote identity is already mapped to another row.`);
|
|
1142
1378
|
}
|
|
1143
1379
|
}
|
|
1144
|
-
#assertReplicaIdentityAssignment(existing, incoming) {
|
|
1380
|
+
#assertReplicaIdentityAssignment(existing, incoming, release) {
|
|
1145
1381
|
const schema = this.#resolveReplicaEntitySchema(incoming.sourceKey);
|
|
1146
|
-
if (schema.identity.kind
|
|
1147
|
-
|
|
1148
|
-
|
|
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;
|
|
1393
|
+
}
|
|
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
|
+
}
|
|
1398
|
+
if (release) {
|
|
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}.`);
|
|
1401
|
+
}
|
|
1402
|
+
return;
|
|
1403
|
+
}
|
|
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)}.`);
|
|
1149
1409
|
}
|
|
1150
1410
|
return;
|
|
1151
1411
|
}
|
|
1152
1412
|
if (schema.identity.kind === 'naturalKey') {
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
}
|
|
1156
|
-
const
|
|
1157
|
-
|
|
1158
|
-
});
|
|
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 });
|
|
1159
1418
|
if (current !== next)
|
|
1160
1419
|
throw new Error(`Offline replica naturalKey is immutable for "${schema.sourceKey}".`);
|
|
1161
1420
|
}
|
|
1162
1421
|
}
|
|
1163
|
-
#
|
|
1164
|
-
if (
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
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
|
+
}
|
|
1169
1432
|
}
|
|
1170
1433
|
#resolveReplicaEntitySchema(sourceKey) {
|
|
1171
1434
|
const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);
|
|
@@ -1180,13 +1443,22 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
|
|
|
1180
1443
|
type: Injectable,
|
|
1181
1444
|
args: [{ providedIn: 'root' }]
|
|
1182
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
|
+
}
|
|
1183
1456
|
|
|
1184
1457
|
/** Pulls authoritative server deltas into one durable local replica partition. */
|
|
1185
1458
|
class OfflineReplicaPullService {
|
|
1186
1459
|
#repository = inject(OFFLINE_REPOSITORY);
|
|
1187
1460
|
#options = inject(OFFLINE_KIT_OPTIONS);
|
|
1188
1461
|
#puller = inject(OFFLINE_REPLICA_PULLER);
|
|
1189
|
-
#hooks = inject(OFFLINE_COMMAND_HOOKS);
|
|
1190
1462
|
#executor = inject(OFFLINE_COMMAND_EXECUTOR);
|
|
1191
1463
|
#schemaHash = null;
|
|
1192
1464
|
async pull(scope) {
|
|
@@ -1219,38 +1491,39 @@ class OfflineReplicaPullService {
|
|
|
1219
1491
|
const command = commands.find((candidate) => candidate.commandId === commandId);
|
|
1220
1492
|
if (!command)
|
|
1221
1493
|
return null;
|
|
1222
|
-
if (
|
|
1494
|
+
if (command.sourceKey !== change.sourceKey) {
|
|
1223
1495
|
throw new Error(`Acknowledged command "${commandId}" does not target "${change.sourceKey}".`);
|
|
1224
1496
|
}
|
|
1225
1497
|
return command;
|
|
1226
1498
|
})
|
|
1227
1499
|
.filter((command) => command !== null);
|
|
1228
|
-
const
|
|
1229
|
-
if (
|
|
1230
|
-
throw new Error(`Acknowledged commands for "${change.sourceKey}" target multiple
|
|
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.`);
|
|
1231
1503
|
}
|
|
1232
1504
|
const acknowledgedCommand = acknowledged[0];
|
|
1233
1505
|
const acknowledgedScope = acknowledgedCommand
|
|
1234
1506
|
? { userId: acknowledgedCommand.userId, scopeId: acknowledgedCommand.scopeId }
|
|
1235
1507
|
: scope;
|
|
1236
1508
|
const acknowledgedRow = acknowledgedCommand
|
|
1237
|
-
? await (this.#repository.getReplicaRowIncludingPendingDelete?.(acknowledgedScope, change.sourceKey, acknowledgedCommand.
|
|
1238
|
-
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))
|
|
1239
1510
|
: null;
|
|
1240
1511
|
if (acknowledgedCommand && !acknowledgedRow) {
|
|
1241
1512
|
throw new Error(`Acknowledged command "${acknowledgedCommand.commandId}" has no local replica row.`);
|
|
1242
1513
|
}
|
|
1243
1514
|
const identity = this.#identity(change);
|
|
1244
1515
|
const serverRow = await this.#repository.getReplicaRowByRemoteIdentity(scope, change.sourceKey, identity);
|
|
1245
|
-
if (acknowledgedRow &&
|
|
1246
|
-
|
|
1247
|
-
|
|
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.`);
|
|
1248
1521
|
}
|
|
1249
1522
|
throw new Error(`Remote identity for "${change.sourceKey}" is already mapped to another local replica row.`);
|
|
1250
1523
|
}
|
|
1251
1524
|
const existing = acknowledgedRow ?? serverRow;
|
|
1252
1525
|
const related = existing
|
|
1253
|
-
? commands.filter((command) =>
|
|
1526
|
+
? commands.filter((command) => command.sourceKey === change.sourceKey && commandIdentityMatchesReplicaRow(schema, existing, command.identity))
|
|
1254
1527
|
: [];
|
|
1255
1528
|
const hasPending = related.length > 0;
|
|
1256
1529
|
if (acknowledgedCommand) {
|
|
@@ -1262,7 +1535,7 @@ class OfflineReplicaPullService {
|
|
|
1262
1535
|
if (!existing)
|
|
1263
1536
|
continue;
|
|
1264
1537
|
if (!hasPending) {
|
|
1265
|
-
removeRows.push(existing);
|
|
1538
|
+
removeRows.push({ ...existing, identity: existing.identity });
|
|
1266
1539
|
continue;
|
|
1267
1540
|
}
|
|
1268
1541
|
putRows.push({
|
|
@@ -1282,8 +1555,9 @@ class OfflineReplicaPullService {
|
|
|
1282
1555
|
putRows.push({
|
|
1283
1556
|
...scope,
|
|
1284
1557
|
sourceKey: change.sourceKey,
|
|
1285
|
-
|
|
1286
|
-
|
|
1558
|
+
identity: schema.identity.kind === 'naturalKey'
|
|
1559
|
+
? offlineNaturalReplicaIdentity(schema, confirmedValues)
|
|
1560
|
+
: offlineGeneratedReplicaIdentity(crypto.randomUUID(), identity.remoteId ?? null),
|
|
1287
1561
|
values: confirmedValues,
|
|
1288
1562
|
confirmedValues,
|
|
1289
1563
|
serverRevision: change.serverRevision,
|
|
@@ -1350,13 +1624,15 @@ class OfflineReplicaPullService {
|
|
|
1350
1624
|
throw new Error(`${label}.deleted must be a boolean.`);
|
|
1351
1625
|
}
|
|
1352
1626
|
const schema = this.#entitySchema(change['sourceKey']);
|
|
1353
|
-
if (schema.identity.kind === '
|
|
1354
|
-
const
|
|
1355
|
-
|
|
1356
|
-
|
|
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.`);
|
|
1357
1633
|
}
|
|
1358
1634
|
if (change['naturalKey'] !== undefined) {
|
|
1359
|
-
throw new Error(`${label}.naturalKey must be omitted for a
|
|
1635
|
+
throw new Error(`${label}.naturalKey must be omitted for a generated entity.`);
|
|
1360
1636
|
}
|
|
1361
1637
|
}
|
|
1362
1638
|
try {
|
|
@@ -1394,9 +1670,9 @@ class OfflineReplicaPullService {
|
|
|
1394
1670
|
}
|
|
1395
1671
|
#validatedValues(schema, change) {
|
|
1396
1672
|
if (change.values === null) {
|
|
1397
|
-
throw new Error(change.
|
|
1673
|
+
throw new Error(change.remoteId === undefined
|
|
1398
1674
|
? `Offline replica change "${change.sourceKey}" is missing values.`
|
|
1399
|
-
: `Offline replica change "${change.sourceKey}"/${change.
|
|
1675
|
+
: `Offline replica change "${change.sourceKey}"/${String(change.remoteId)} is missing values.`);
|
|
1400
1676
|
}
|
|
1401
1677
|
const values = projectOfflineReplicaValues(schema, change.values);
|
|
1402
1678
|
if (schema.identity.kind === 'naturalKey') {
|
|
@@ -1477,7 +1753,7 @@ class OfflineReplicaPullService {
|
|
|
1477
1753
|
}
|
|
1478
1754
|
}
|
|
1479
1755
|
else {
|
|
1480
|
-
removeRows.push(row);
|
|
1756
|
+
removeRows.push({ ...row, identity: row.identity });
|
|
1481
1757
|
}
|
|
1482
1758
|
return;
|
|
1483
1759
|
}
|
|
@@ -1486,7 +1762,7 @@ class OfflineReplicaPullService {
|
|
|
1486
1762
|
this.#assertIdentityAssignment(schema, row, this.#identity(change));
|
|
1487
1763
|
putRows.push({
|
|
1488
1764
|
...row,
|
|
1489
|
-
|
|
1765
|
+
identity: row.identity.kind === 'generated' ? { ...row.identity, remoteId: change.remoteId ?? row.identity.remoteId } : row.identity,
|
|
1490
1766
|
values: following.length > 0 ? following.at(-1).optimisticValue : confirmedValues,
|
|
1491
1767
|
confirmedValues,
|
|
1492
1768
|
serverRevision: change.serverRevision,
|
|
@@ -1496,17 +1772,20 @@ class OfflineReplicaPullService {
|
|
|
1496
1772
|
});
|
|
1497
1773
|
}
|
|
1498
1774
|
#identity(change) {
|
|
1499
|
-
return change.
|
|
1775
|
+
return change.remoteId !== undefined ? { remoteId: change.remoteId } : { naturalKey: change.naturalKey };
|
|
1500
1776
|
}
|
|
1501
1777
|
#assertIdentityAssignment(schema, row, incoming) {
|
|
1502
|
-
if (schema.identity.kind === '
|
|
1503
|
-
const
|
|
1504
|
-
if (row.
|
|
1505
|
-
throw new Error(`Replica
|
|
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)}.`);
|
|
1506
1785
|
}
|
|
1507
1786
|
return;
|
|
1508
1787
|
}
|
|
1509
|
-
const current = offlineNaturalKeyFromValues(schema, row.values);
|
|
1788
|
+
const current = row.identity.kind === 'natural' ? row.identity.naturalKey : offlineNaturalKeyFromValues(schema, row.values);
|
|
1510
1789
|
if (current !== null &&
|
|
1511
1790
|
canonicalOfflineRemoteIdentity(schema, { naturalKey: current }) !== canonicalOfflineRemoteIdentity(schema, incoming)) {
|
|
1512
1791
|
throw new Error(`Replica naturalKey is immutable for "${schema.sourceKey}".`);
|
|
@@ -1527,6 +1806,15 @@ function isPlainObject(value) {
|
|
|
1527
1806
|
return prototype === Object.prototype || prototype === null;
|
|
1528
1807
|
}
|
|
1529
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
|
+
|
|
1530
1818
|
/** transport不能(status=0)だけをlocal replica fallback対象にし、HTTPエラーは隠さない。 */
|
|
1531
1819
|
function isOfflineFallbackError(error) {
|
|
1532
1820
|
return typeof error === 'object' && error !== null && error.status === 0;
|
|
@@ -1769,7 +2057,8 @@ class OfflineSyncService {
|
|
|
1769
2057
|
#flushTransitions;
|
|
1770
2058
|
#generation;
|
|
1771
2059
|
#sendingTransitions;
|
|
1772
|
-
|
|
2060
|
+
/** Serializes enqueue and acknowledgement projection over the same local replica. */
|
|
2061
|
+
#replicaMutationTail;
|
|
1773
2062
|
#retryTimer;
|
|
1774
2063
|
#initialized;
|
|
1775
2064
|
#lastCommandCreatedAt;
|
|
@@ -1789,7 +2078,8 @@ class OfflineSyncService {
|
|
|
1789
2078
|
this.#flushTransitions = new Set();
|
|
1790
2079
|
this.#generation = 0;
|
|
1791
2080
|
this.#sendingTransitions = new Set();
|
|
1792
|
-
|
|
2081
|
+
/** Serializes enqueue and acknowledgement projection over the same local replica. */
|
|
2082
|
+
this.#replicaMutationTail = Promise.resolve();
|
|
1793
2083
|
this.#retryTimer = null;
|
|
1794
2084
|
this.#initialized = false;
|
|
1795
2085
|
this.#lastCommandCreatedAt = 0;
|
|
@@ -1848,7 +2138,7 @@ class OfflineSyncService {
|
|
|
1848
2138
|
}
|
|
1849
2139
|
async resetSession() {
|
|
1850
2140
|
this.revokeSession();
|
|
1851
|
-
await Promise.allSettled([this.#
|
|
2141
|
+
await Promise.allSettled([this.#replicaMutationTail, ...this.#flushTransitions]);
|
|
1852
2142
|
await this.#waitForSendingTransitions();
|
|
1853
2143
|
await this.#restoreInterruptedCommands();
|
|
1854
2144
|
this.#activeUserId = null;
|
|
@@ -1862,28 +2152,64 @@ class OfflineSyncService {
|
|
|
1862
2152
|
}
|
|
1863
2153
|
enqueue(request, options = {}) {
|
|
1864
2154
|
const generation = this.#generation;
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
2155
|
+
return this.#serializeReplicaMutation(() => this.#enqueue(request, options, generation));
|
|
2156
|
+
}
|
|
2157
|
+
/**
|
|
2158
|
+
* Serializes a product-owned replica projection with enqueue and command ACK
|
|
2159
|
+
* reconciliation. For read/derive/write cache updates, prefer
|
|
2160
|
+
* `runSerializedReplicaMutation` so the read is serialized as well.
|
|
2161
|
+
*/
|
|
2162
|
+
async transactReplica(transaction) {
|
|
2163
|
+
await this.runSerializedReplicaMutation(async (repository) => {
|
|
2164
|
+
await repository.transactReplica(transaction);
|
|
2165
|
+
});
|
|
2166
|
+
}
|
|
2167
|
+
/**
|
|
2168
|
+
* Runs a product cache's replica read/derive/write sequence atomically with
|
|
2169
|
+
* enqueue and ACK projection. Use this for any repository reads that inform
|
|
2170
|
+
* a later transaction; `transactReplica` alone only serializes the write.
|
|
2171
|
+
*/
|
|
2172
|
+
runSerializedReplicaMutation(operation) {
|
|
2173
|
+
const generation = this.#generation;
|
|
2174
|
+
return this.#serializeReplicaMutation(async () => {
|
|
2175
|
+
await this.initialize();
|
|
2176
|
+
if (!this.#isCurrent(generation))
|
|
2177
|
+
throw new Error('Offline session changed before serialized replica mutation.');
|
|
2178
|
+
const result = await operation(this.#repository);
|
|
2179
|
+
if (this.#isCurrent(generation))
|
|
2180
|
+
await this.#refreshState(generation);
|
|
2181
|
+
return result;
|
|
2182
|
+
});
|
|
2183
|
+
}
|
|
2184
|
+
#serializeReplicaMutation(operation) {
|
|
2185
|
+
const mutation = this.#replicaMutationTail.then(operation);
|
|
2186
|
+
this.#replicaMutationTail = mutation.then(() => undefined, () => undefined);
|
|
2187
|
+
return mutation;
|
|
1868
2188
|
}
|
|
1869
2189
|
async #enqueue(request, options, generation) {
|
|
1870
2190
|
await this.initialize();
|
|
1871
2191
|
const session = await this.#getLocalSession();
|
|
1872
2192
|
if (!session)
|
|
1873
2193
|
throw new Error('Cannot enqueue an offline command without an authenticated user');
|
|
2194
|
+
this.#assertSessionPrincipalBoundary(session);
|
|
1874
2195
|
const userId = session.userId;
|
|
1875
2196
|
this.#setActiveUser(userId);
|
|
1876
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
|
+
}
|
|
1877
2201
|
this.noteScope(scope);
|
|
1878
|
-
const
|
|
1879
|
-
const normalized = await this.#normalizeEnqueueRequest(scope, request);
|
|
2202
|
+
const commandIdentity = offlineCommandLookupIdentity(request.identity);
|
|
2203
|
+
const normalized = await this.#normalizeEnqueueRequest(scope, request, commandIdentity);
|
|
1880
2204
|
const optimisticValue = request.optimisticValue;
|
|
1881
2205
|
const commandId = crypto.randomUUID();
|
|
2206
|
+
const sourceKey = this.#hooks.entityType(request);
|
|
1882
2207
|
const command = {
|
|
1883
2208
|
...scope,
|
|
1884
2209
|
commandId,
|
|
1885
2210
|
aggregateType: request.aggregateType,
|
|
1886
|
-
|
|
2211
|
+
sourceKey,
|
|
2212
|
+
identity: commandIdentity,
|
|
1887
2213
|
operation: request.operation,
|
|
1888
2214
|
payload: normalized.payload,
|
|
1889
2215
|
optimisticValue,
|
|
@@ -1897,45 +2223,62 @@ class OfflineSyncService {
|
|
|
1897
2223
|
lastErrorCode: null,
|
|
1898
2224
|
};
|
|
1899
2225
|
await this.#assertOutboxCapacity(userId, command);
|
|
1900
|
-
const entityType =
|
|
2226
|
+
const entityType = command.sourceKey;
|
|
1901
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
|
+
}
|
|
1902
2237
|
if (request.replicaMutation === 'delete' && !this.#repository.getReplicaRowIncludingPendingDelete) {
|
|
1903
2238
|
throw new Error('Offline repository does not support durable replica delete tombstones.');
|
|
1904
2239
|
}
|
|
1905
|
-
const existing = await this.#getReplicaRowForSync(scope, entityType,
|
|
1906
|
-
const
|
|
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);
|
|
1907
2244
|
const naturalKey = offlineNaturalKeyFromValues(schema, optimisticValue);
|
|
1908
|
-
|
|
1909
|
-
|
|
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
|
|
1910
2252
|
? null
|
|
1911
|
-
: {
|
|
2253
|
+
: { remoteId: initialRemoteId }
|
|
1912
2254
|
: schema.identity.kind === 'naturalKey'
|
|
1913
2255
|
? { naturalKey: naturalKey }
|
|
1914
2256
|
: null;
|
|
1915
|
-
if (schema.identity.kind === 'naturalKey' && request.serverId != null) {
|
|
1916
|
-
throw new Error(`Offline replica source "${entityType}" does not define a serverId field.`);
|
|
1917
|
-
}
|
|
1918
2257
|
if (schema.identity.kind === 'naturalKey') {
|
|
1919
2258
|
const canonicalValuesKey = canonicalOfflineRemoteIdentity(schema, remoteIdentity);
|
|
1920
2259
|
if (existing &&
|
|
1921
|
-
canonicalOfflineRemoteIdentity(schema, {
|
|
2260
|
+
canonicalOfflineRemoteIdentity(schema, {
|
|
2261
|
+
naturalKey: existing.identity.kind === 'natural' ? existing.identity.naturalKey : offlineNaturalKeyFromValues(schema, existing.values),
|
|
2262
|
+
}) !== canonicalValuesKey) {
|
|
1922
2263
|
throw new Error(`Offline replica naturalKey is immutable and must match optimistic values for "${entityType}".`);
|
|
1923
2264
|
}
|
|
1924
2265
|
}
|
|
1925
2266
|
if (remoteIdentity !== null) {
|
|
1926
2267
|
const mapped = await this.#repository.getReplicaRowByRemoteIdentity(scope, entityType, remoteIdentity);
|
|
1927
|
-
if (mapped !== null && mapped
|
|
1928
|
-
if (
|
|
1929
|
-
throw new Error(`Offline replica
|
|
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.`);
|
|
1930
2271
|
}
|
|
1931
|
-
throw new Error(`Offline replica remote identity is already mapped to
|
|
2272
|
+
throw new Error(`Offline replica remote identity is already mapped to another row.`);
|
|
1932
2273
|
}
|
|
1933
2274
|
}
|
|
2275
|
+
const rowIdentity = schema.identity.kind === 'naturalKey'
|
|
2276
|
+
? offlineNaturalReplicaIdentity(schema, optimisticValue)
|
|
2277
|
+
: offlineGeneratedReplicaIdentity(generatedIdentity.localId, initialRemoteId);
|
|
1934
2278
|
const optimisticRow = {
|
|
1935
2279
|
...scope,
|
|
1936
2280
|
sourceKey: entityType,
|
|
1937
|
-
|
|
1938
|
-
serverId: initialServerId,
|
|
2281
|
+
identity: rowIdentity,
|
|
1939
2282
|
values: optimisticValue,
|
|
1940
2283
|
confirmedValues: existing?.confirmedValues ?? existing?.values ?? null,
|
|
1941
2284
|
serverRevision: existing?.serverRevision ?? normalized.baseRevision,
|
|
@@ -2056,10 +2399,9 @@ class OfflineSyncService {
|
|
|
2056
2399
|
});
|
|
2057
2400
|
}
|
|
2058
2401
|
async #sendAggregate(commands, generation) {
|
|
2059
|
-
for (
|
|
2402
|
+
for (const command of commands) {
|
|
2060
2403
|
if (!this.#isCurrent(generation))
|
|
2061
2404
|
return;
|
|
2062
|
-
const command = commands[index];
|
|
2063
2405
|
if (command.state === 'retry_wait' && (command.retryAt ?? 0) > Date.now())
|
|
2064
2406
|
break;
|
|
2065
2407
|
if (!['pending', 'retry_wait'].includes(command.state))
|
|
@@ -2079,16 +2421,10 @@ class OfflineSyncService {
|
|
|
2079
2421
|
return;
|
|
2080
2422
|
const row = await this.#rowForCommand(sending);
|
|
2081
2423
|
if (!row)
|
|
2082
|
-
throw new Error(`Offline replica row not found: ${sending.aggregateType}/${sending.
|
|
2424
|
+
throw new Error(`Offline replica row not found: ${sending.aggregateType}/${canonicalOfflineCommandIdentity(sending.identity)}`);
|
|
2083
2425
|
let result;
|
|
2084
2426
|
try {
|
|
2085
|
-
|
|
2086
|
-
const naturalKey = offlineNaturalKeyFromValues(schema, row.values);
|
|
2087
|
-
result = await this.#executor.execute(sending, {
|
|
2088
|
-
localId: row.localId,
|
|
2089
|
-
serverId: row.serverId,
|
|
2090
|
-
...(naturalKey !== null ? { naturalKey } : {}),
|
|
2091
|
-
});
|
|
2427
|
+
result = await this.#executor.execute(sending, offlineCommandTargetFromReplicaRow(row));
|
|
2092
2428
|
}
|
|
2093
2429
|
catch (error) {
|
|
2094
2430
|
if (!this.#isCurrent(generation))
|
|
@@ -2106,27 +2442,51 @@ class OfflineSyncService {
|
|
|
2106
2442
|
}
|
|
2107
2443
|
if (!this.#isCurrent(generation))
|
|
2108
2444
|
return;
|
|
2109
|
-
await this.#completeCommand(commands,
|
|
2445
|
+
await this.#completeCommand(commands, sending, result, generation);
|
|
2110
2446
|
}
|
|
2111
2447
|
}
|
|
2112
|
-
async #normalizeEnqueueRequest(scope, request) {
|
|
2448
|
+
async #normalizeEnqueueRequest(scope, request, commandIdentity) {
|
|
2113
2449
|
let baseRevision = request.baseRevision ?? null;
|
|
2114
2450
|
let payload = request.payload;
|
|
2115
|
-
const
|
|
2116
|
-
const row = await this.#getReplicaRowForSync(scope,
|
|
2451
|
+
const sourceKey = this.#hooks.entityType(request);
|
|
2452
|
+
const row = await this.#getReplicaRowForSync(scope, sourceKey, commandIdentity);
|
|
2117
2453
|
if (row?.serverRevision != null && row.serverRevision !== baseRevision) {
|
|
2118
|
-
const rebased = this.#executor.withServerRevision({ ...scope, ...request,
|
|
2454
|
+
const rebased = this.#executor.withServerRevision({ ...scope, ...request, sourceKey, identity: commandIdentity, payload, baseRevision }, row.serverRevision);
|
|
2119
2455
|
baseRevision = row.serverRevision;
|
|
2120
2456
|
payload = rebased.payload;
|
|
2121
2457
|
}
|
|
2122
2458
|
return { payload, baseRevision };
|
|
2123
2459
|
}
|
|
2124
|
-
async #completeCommand(commands,
|
|
2460
|
+
async #completeCommand(commands, command, result, generation) {
|
|
2461
|
+
return this.#serializeReplicaMutation(() => this.#completeCommandLocked(commands, command, result, generation));
|
|
2462
|
+
}
|
|
2463
|
+
async #completeCommandLocked(commands, command, result, generation) {
|
|
2464
|
+
if (result.clearRemoteId === true && result.remoteId !== undefined) {
|
|
2465
|
+
throw new Error('Offline command cannot return remoteId and clearRemoteId together.');
|
|
2466
|
+
}
|
|
2467
|
+
if (result.clearRemoteId === true && result.serverRevision !== undefined) {
|
|
2468
|
+
throw new Error('Offline command cannot return serverRevision and clearRemoteId together.');
|
|
2469
|
+
}
|
|
2470
|
+
// An enqueue may have completed while transport was in flight. Re-read the
|
|
2471
|
+
// aggregate immediately before the atomic acknowledgement transaction so a
|
|
2472
|
+
// delete ACK cannot remove a row that has already been re-added locally.
|
|
2473
|
+
const latestCommands = (await this.#readKnownCommands()).filter((candidate) => this.#aggregateKey(candidate) === this.#aggregateKey(command));
|
|
2474
|
+
const latestIndex = latestCommands.findIndex((candidate) => candidate.commandId === command.commandId);
|
|
2475
|
+
if (latestIndex < 0)
|
|
2476
|
+
return;
|
|
2125
2477
|
const revision = result.serverRevision;
|
|
2126
|
-
const following =
|
|
2127
|
-
const rebased =
|
|
2128
|
-
|
|
2129
|
-
|
|
2478
|
+
const following = latestCommands.slice(latestIndex + 1);
|
|
2479
|
+
const rebased = result.clearRemoteId === true
|
|
2480
|
+
? following.map((item) => {
|
|
2481
|
+
if (!this.#executor.withoutServerRevision) {
|
|
2482
|
+
throw new Error('Offline command executor must implement withoutServerRevision to recreate a deleted remoteId row.');
|
|
2483
|
+
}
|
|
2484
|
+
return this.#executor.withoutServerRevision(item);
|
|
2485
|
+
})
|
|
2486
|
+
: revision === undefined
|
|
2487
|
+
? following
|
|
2488
|
+
: following.map((item) => this.#executor.withServerRevision(item, revision));
|
|
2489
|
+
latestCommands.splice(latestIndex + 1, rebased.length, ...rebased);
|
|
2130
2490
|
const current = await this.#rowForCommand(command);
|
|
2131
2491
|
if (!this.#isCurrent(generation))
|
|
2132
2492
|
return;
|
|
@@ -2135,16 +2495,24 @@ class OfflineSyncService {
|
|
|
2135
2495
|
}
|
|
2136
2496
|
this.#assertServerRevision(result.serverRevision);
|
|
2137
2497
|
const removesReplica = result.removeReplica === true || command.replicaMutation === 'delete';
|
|
2498
|
+
if (result.clearRemoteId === true && !removesReplica) {
|
|
2499
|
+
throw new Error('Offline command can clear remoteId only for a confirmed replica removal.');
|
|
2500
|
+
}
|
|
2138
2501
|
const confirmedValues = removesReplica ? null : (result.confirmedValues ?? command.optimisticValue);
|
|
2139
2502
|
const schema = this.#entitySchema(current.sourceKey);
|
|
2140
2503
|
this.#assertCommandResultIdentity(schema, current, result);
|
|
2141
|
-
const
|
|
2504
|
+
const resolvedRemoteId = this.#resolvedRemoteId(current, result);
|
|
2142
2505
|
const row = {
|
|
2143
2506
|
...current,
|
|
2144
|
-
values: rebased.length > 0 ?
|
|
2507
|
+
values: rebased.length > 0 ? current.values : confirmedValues,
|
|
2145
2508
|
confirmedValues,
|
|
2146
|
-
|
|
2147
|
-
|
|
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),
|
|
2148
2516
|
fetchedAt: Date.now(),
|
|
2149
2517
|
syncState: rebased.length > 0 ? 'pending' : 'confirmed',
|
|
2150
2518
|
visibility: rebased.at(-1)?.replicaMutation === 'delete' ? 'pending_delete' : 'present',
|
|
@@ -2153,19 +2521,34 @@ class OfflineSyncService {
|
|
|
2153
2521
|
return;
|
|
2154
2522
|
await this.#repository.transactReplica({
|
|
2155
2523
|
putRows: removesReplica && rebased.length === 0 ? undefined : [row],
|
|
2524
|
+
releaseRemoteIds: result.clearRemoteId === true &&
|
|
2525
|
+
current.identity.kind === 'generated' &&
|
|
2526
|
+
current.identity.remoteId !== null &&
|
|
2527
|
+
!(removesReplica && rebased.length === 0)
|
|
2528
|
+
? [
|
|
2529
|
+
{
|
|
2530
|
+
userId: current.userId,
|
|
2531
|
+
scopeId: current.scopeId,
|
|
2532
|
+
sourceKey: current.sourceKey,
|
|
2533
|
+
identity: current.identity,
|
|
2534
|
+
remoteId: current.identity.remoteId,
|
|
2535
|
+
},
|
|
2536
|
+
]
|
|
2537
|
+
: undefined,
|
|
2156
2538
|
removeRows: removesReplica && rebased.length === 0 ? [current] : undefined,
|
|
2157
2539
|
putCommands: rebased,
|
|
2158
2540
|
removeCommandIds: [command.commandId],
|
|
2159
2541
|
});
|
|
2542
|
+
commands.splice(0, commands.length, ...latestCommands);
|
|
2160
2543
|
}
|
|
2161
2544
|
async #rowForCommand(command) {
|
|
2162
2545
|
const scope = { userId: command.userId, scopeId: command.scopeId };
|
|
2163
2546
|
const entityType = this.#entityType(command);
|
|
2164
|
-
return this.#getReplicaRowForSync(scope, entityType, command.
|
|
2547
|
+
return this.#getReplicaRowForSync(scope, entityType, command.identity);
|
|
2165
2548
|
}
|
|
2166
|
-
#getReplicaRowForSync(scope, sourceKey,
|
|
2167
|
-
return (this.#repository.getReplicaRowIncludingPendingDelete?.(scope, sourceKey,
|
|
2168
|
-
this.#repository.getReplicaRow(scope, sourceKey,
|
|
2549
|
+
#getReplicaRowForSync(scope, sourceKey, identity) {
|
|
2550
|
+
return (this.#repository.getReplicaRowIncludingPendingDelete?.(scope, sourceKey, identity) ??
|
|
2551
|
+
this.#repository.getReplicaRow(scope, sourceKey, identity));
|
|
2169
2552
|
}
|
|
2170
2553
|
#replicaState(state) {
|
|
2171
2554
|
if (state === 'blocked_auth' || state === 'rejected' || state === 'conflict')
|
|
@@ -2173,7 +2556,7 @@ class OfflineSyncService {
|
|
|
2173
2556
|
return 'pending';
|
|
2174
2557
|
}
|
|
2175
2558
|
#entityType(command) {
|
|
2176
|
-
return
|
|
2559
|
+
return command.sourceKey;
|
|
2177
2560
|
}
|
|
2178
2561
|
#entitySchema(sourceKey) {
|
|
2179
2562
|
const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);
|
|
@@ -2218,7 +2601,7 @@ class OfflineSyncService {
|
|
|
2218
2601
|
if (!schema)
|
|
2219
2602
|
throw new Error(`Unknown offline replica source key "${sourceKey}".`);
|
|
2220
2603
|
const partition = schema.scope === 'user' ? 'user' : `partition:${command.scopeId}`;
|
|
2221
|
-
return `${command.userId}:${partition}:${sourceKey}:${command.
|
|
2604
|
+
return `${canonicalOfflinePrincipalId(command.userId)}:${partition}:${sourceKey}:${canonicalOfflineCommandIdentity(command.identity)}`;
|
|
2222
2605
|
}
|
|
2223
2606
|
#failedCommand(command, error) {
|
|
2224
2607
|
const status = this.#errorStatus(error);
|
|
@@ -2249,30 +2632,49 @@ class OfflineSyncService {
|
|
|
2249
2632
|
throw new Error(`Offline command returned invalid serverRevision ${String(revision)}.`);
|
|
2250
2633
|
}
|
|
2251
2634
|
}
|
|
2252
|
-
#
|
|
2635
|
+
#resolvedRemoteId(current, result) {
|
|
2636
|
+
if (current.identity.kind !== 'generated')
|
|
2637
|
+
return null;
|
|
2638
|
+
const incoming = result.remoteId;
|
|
2253
2639
|
if (incoming === undefined)
|
|
2254
|
-
return current;
|
|
2255
|
-
|
|
2256
|
-
|
|
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)}.`);
|
|
2257
2645
|
}
|
|
2646
|
+
return incoming;
|
|
2647
|
+
}
|
|
2648
|
+
#initialRemoteId(schema, current, incoming) {
|
|
2649
|
+
if (incoming === null || incoming === undefined)
|
|
2650
|
+
return current;
|
|
2651
|
+
assertOfflineReplicaGeneratedRemoteId(schema, incoming);
|
|
2258
2652
|
if (current !== null && current !== incoming) {
|
|
2259
|
-
throw new Error(`Offline replica
|
|
2653
|
+
throw new Error(`Offline replica remote id is immutable: current=${String(current)}, incoming=${String(incoming)}.`);
|
|
2260
2654
|
}
|
|
2261
2655
|
return incoming;
|
|
2262
2656
|
}
|
|
2263
|
-
#
|
|
2264
|
-
|
|
2657
|
+
#assertRemoteIdHint(schema, current, hint) {
|
|
2658
|
+
if (hint === null || hint === undefined)
|
|
2659
|
+
return;
|
|
2660
|
+
assertOfflineReplicaGeneratedRemoteId(schema, hint);
|
|
2661
|
+
if (current !== null && current !== hint) {
|
|
2662
|
+
throw new Error(`Offline replica remoteId hint does not match current=${String(current)}: incoming=${String(hint)}.`);
|
|
2663
|
+
}
|
|
2265
2664
|
}
|
|
2266
2665
|
#assertCommandResultIdentity(schema, current, result) {
|
|
2267
|
-
if (
|
|
2268
|
-
throw new Error(`Offline command
|
|
2666
|
+
if (result.clearRemoteId === true && schema.identity.kind !== 'generated') {
|
|
2667
|
+
throw new Error(`Offline command cannot clear remoteId for source "${schema.sourceKey}".`);
|
|
2269
2668
|
}
|
|
2270
|
-
if (schema.identity.kind
|
|
2271
|
-
throw new Error(`Offline command returned
|
|
2669
|
+
if (schema.identity.kind === 'naturalKey' && result.remoteId !== undefined) {
|
|
2670
|
+
throw new Error(`Offline command returned generated remote id for naturalKey source "${schema.sourceKey}".`);
|
|
2671
|
+
}
|
|
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.`);
|
|
2272
2674
|
}
|
|
2273
2675
|
if (schema.identity.kind === 'naturalKey') {
|
|
2274
2676
|
const confirmedValues = result.confirmedValues ?? current.values;
|
|
2275
|
-
const currentKey = offlineNaturalKeyFromValues(schema, current.values);
|
|
2677
|
+
const currentKey = current.identity.kind === 'natural' ? current.identity.naturalKey : offlineNaturalKeyFromValues(schema, current.values);
|
|
2276
2678
|
const confirmedKey = offlineNaturalKeyFromValues(schema, confirmedValues);
|
|
2277
2679
|
if (canonicalOfflineRemoteIdentity(schema, { naturalKey: currentKey }) !==
|
|
2278
2680
|
canonicalOfflineRemoteIdentity(schema, { naturalKey: confirmedKey })) {
|
|
@@ -2287,6 +2689,7 @@ class OfflineSyncService {
|
|
|
2287
2689
|
if (!session) {
|
|
2288
2690
|
return false;
|
|
2289
2691
|
}
|
|
2692
|
+
this.#assertSessionPrincipalBoundary(session);
|
|
2290
2693
|
this.#setActiveUser(session.userId);
|
|
2291
2694
|
this.#knownScopes.clear();
|
|
2292
2695
|
for (const scope of session.scopes)
|
|
@@ -2302,6 +2705,7 @@ class OfflineSyncService {
|
|
|
2302
2705
|
this.#knownScopes.clear();
|
|
2303
2706
|
return true;
|
|
2304
2707
|
}
|
|
2708
|
+
this.#assertSessionPrincipalBoundary(session);
|
|
2305
2709
|
this.#setActiveUser(session.userId);
|
|
2306
2710
|
this.#knownScopes.clear();
|
|
2307
2711
|
for (const scope of session.scopes)
|
|
@@ -2318,6 +2722,14 @@ class OfflineSyncService {
|
|
|
2318
2722
|
this.#activeUserId = userId;
|
|
2319
2723
|
this.#lastCommandCreatedAt = 0;
|
|
2320
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
|
+
}
|
|
2321
2733
|
async #readKnownCommands() {
|
|
2322
2734
|
const commands = (await Promise.all([...this.#knownScopes.values()].map((scope) => this.#repository.getCommands(scope))))
|
|
2323
2735
|
.flat()
|
|
@@ -2409,7 +2821,7 @@ class OfflineSyncService {
|
|
|
2409
2821
|
return serialized;
|
|
2410
2822
|
}
|
|
2411
2823
|
#scopeKey(scope) {
|
|
2412
|
-
return `${scope.userId}:${scope.scopeId}`;
|
|
2824
|
+
return `${canonicalOfflinePrincipalId(scope.userId)}:${scope.scopeId}`;
|
|
2413
2825
|
}
|
|
2414
2826
|
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineSyncService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
2415
2827
|
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineSyncService, providedIn: 'root' }); }
|
|
@@ -2615,9 +3027,7 @@ function createOfflineAuthBridge(options) {
|
|
|
2615
3027
|
};
|
|
2616
3028
|
}
|
|
2617
3029
|
function assertOfflineRemoteIdentity(identity) {
|
|
2618
|
-
|
|
2619
|
-
throw new Error('Offline remote identity userId must be a positive safe integer.');
|
|
2620
|
-
}
|
|
3030
|
+
canonicalOfflinePrincipalId(identity.userId);
|
|
2621
3031
|
if (!Array.isArray(identity.scopeIds) || identity.scopeIds.some((scopeId) => typeof scopeId !== 'string' || scopeId.length === 0)) {
|
|
2622
3032
|
throw new Error('Offline remote identity scopeIds must contain only non-empty strings.');
|
|
2623
3033
|
}
|
|
@@ -2706,18 +3116,19 @@ const SCHEMA = [
|
|
|
2706
3116
|
`CREATE TABLE IF NOT EXISTS offline_metadata (
|
|
2707
3117
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
2708
3118
|
schema_version INTEGER NOT NULL,
|
|
2709
|
-
last_user_id
|
|
3119
|
+
last_user_id TEXT
|
|
2710
3120
|
)`,
|
|
2711
3121
|
`CREATE TABLE IF NOT EXISTS offline_session_manifests (
|
|
2712
|
-
user_id
|
|
3122
|
+
user_id TEXT PRIMARY KEY,
|
|
2713
3123
|
value_json TEXT NOT NULL
|
|
2714
3124
|
)`,
|
|
2715
3125
|
`CREATE TABLE IF NOT EXISTS offline_sync_commands (
|
|
2716
3126
|
command_id TEXT PRIMARY KEY,
|
|
2717
|
-
user_id
|
|
3127
|
+
user_id TEXT NOT NULL,
|
|
2718
3128
|
scope_id TEXT NOT NULL,
|
|
2719
3129
|
aggregate_type TEXT NOT NULL,
|
|
2720
|
-
|
|
3130
|
+
source_key TEXT NOT NULL,
|
|
3131
|
+
identity_json TEXT NOT NULL,
|
|
2721
3132
|
operation TEXT NOT NULL,
|
|
2722
3133
|
payload_json TEXT NOT NULL,
|
|
2723
3134
|
optimistic_value_json TEXT NOT NULL,
|
|
@@ -2738,7 +3149,7 @@ const SCHEMA = [
|
|
|
2738
3149
|
schema_hash TEXT NOT NULL CHECK (length(schema_hash) = 64)
|
|
2739
3150
|
)`,
|
|
2740
3151
|
`CREATE TABLE IF NOT EXISTS offline_replica_cursors (
|
|
2741
|
-
user_id
|
|
3152
|
+
user_id TEXT NOT NULL,
|
|
2742
3153
|
scope_id TEXT NOT NULL,
|
|
2743
3154
|
cursor TEXT NOT NULL,
|
|
2744
3155
|
PRIMARY KEY (user_id, scope_id)
|
|
@@ -2757,85 +3168,70 @@ class SqliteOfflineRepository {
|
|
|
2757
3168
|
}
|
|
2758
3169
|
async getLastUserId() {
|
|
2759
3170
|
const rows = await this.#query('SELECT last_user_id FROM offline_metadata WHERE id = 1');
|
|
2760
|
-
|
|
3171
|
+
const value = this.#stringOrNull(rows[0]?.['last_user_id']);
|
|
3172
|
+
return value === null ? null : parseOfflinePrincipalId(value);
|
|
2761
3173
|
}
|
|
2762
3174
|
async setLastUserId(userId) {
|
|
2763
3175
|
await this.#write(`INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, ?)
|
|
2764
|
-
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)]);
|
|
2765
3177
|
}
|
|
2766
3178
|
async getSessionManifest(userId) {
|
|
2767
|
-
const rows = await this.#query('SELECT value_json FROM offline_session_manifests WHERE user_id = ?', [
|
|
3179
|
+
const rows = await this.#query('SELECT value_json FROM offline_session_manifests WHERE user_id = ?', [
|
|
3180
|
+
canonicalOfflinePrincipalId(userId),
|
|
3181
|
+
]);
|
|
2768
3182
|
const row = rows[0];
|
|
2769
3183
|
return row ? this.#parse(row['value_json']) : null;
|
|
2770
3184
|
}
|
|
2771
3185
|
async putSessionManifest(userId, value) {
|
|
2772
3186
|
await this.#write(`INSERT INTO offline_session_manifests (user_id, value_json) VALUES (?, ?)
|
|
2773
|
-
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)]);
|
|
2774
3188
|
}
|
|
2775
|
-
async getReplicaRow(scope, sourceKey,
|
|
2776
|
-
const
|
|
2777
|
-
|
|
2778
|
-
const values = [localId, scope.userId];
|
|
2779
|
-
if (schema.scope === 'partition') {
|
|
2780
|
-
predicates.push('_offline_scope_id = ?');
|
|
2781
|
-
values.push(scope.scopeId);
|
|
2782
|
-
}
|
|
2783
|
-
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
|
|
2784
|
-
const row = rows[0];
|
|
2785
|
-
if (!row || (row['_offline_visibility'] ?? 'present') === 'pending_delete')
|
|
2786
|
-
return null;
|
|
2787
|
-
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;
|
|
2788
3192
|
}
|
|
2789
|
-
async getReplicaRowIncludingPendingDelete(scope, sourceKey,
|
|
2790
|
-
const
|
|
2791
|
-
|
|
2792
|
-
const values = [localId, scope.userId];
|
|
2793
|
-
if (schema.scope === 'partition') {
|
|
2794
|
-
predicates.push('_offline_scope_id = ?');
|
|
2795
|
-
values.push(scope.scopeId);
|
|
2796
|
-
}
|
|
2797
|
-
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
|
|
2798
|
-
const row = rows[0];
|
|
2799
|
-
return row ? this.#replicaRowFromSqliteRow(schema, scope, sourceKey, localId, row) : null;
|
|
3193
|
+
async getReplicaRowIncludingPendingDelete(scope, sourceKey, identity) {
|
|
3194
|
+
const row = await this.#queryReplicaRow(scope, sourceKey, identity, true);
|
|
3195
|
+
return row;
|
|
2800
3196
|
}
|
|
2801
3197
|
async getReplicaRows(scope, sourceKey) {
|
|
2802
3198
|
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
2803
3199
|
const predicates = ['_offline_user_id = ?'];
|
|
2804
|
-
const values = [scope.userId];
|
|
3200
|
+
const values = [canonicalOfflinePrincipalId(scope.userId)];
|
|
2805
3201
|
if (schema.scope === 'partition') {
|
|
2806
3202
|
predicates.push('_offline_scope_id = ?');
|
|
2807
3203
|
values.push(scope.scopeId);
|
|
2808
3204
|
}
|
|
2809
|
-
const
|
|
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);
|
|
2810
3209
|
return rows
|
|
2811
3210
|
.filter((row) => (row['_offline_visibility'] ?? 'present') !== 'pending_delete')
|
|
2812
|
-
.map((row) => this.#replicaRowFromSqliteRow(schema, scope, sourceKey,
|
|
3211
|
+
.map((row) => this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row));
|
|
2813
3212
|
}
|
|
2814
|
-
async
|
|
2815
|
-
|
|
2816
|
-
if (!this.#schemaHasServerId(schema))
|
|
2817
|
-
return null;
|
|
2818
|
-
const predicates = ['server_id = ?', '_offline_user_id = ?'];
|
|
2819
|
-
const values = [serverId, scope.userId];
|
|
2820
|
-
if (schema.scope === 'partition') {
|
|
2821
|
-
predicates.push('_offline_scope_id = ?');
|
|
2822
|
-
values.push(scope.scopeId);
|
|
2823
|
-
}
|
|
2824
|
-
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
|
|
2825
|
-
const row = rows[0];
|
|
2826
|
-
if (!row)
|
|
3213
|
+
async getReplicaRowByRemoteId(scope, sourceKey, remoteId) {
|
|
3214
|
+
if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
|
|
2827
3215
|
return null;
|
|
2828
|
-
return this
|
|
3216
|
+
return this.getReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });
|
|
2829
3217
|
}
|
|
2830
3218
|
async getReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
|
|
2831
3219
|
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
2832
3220
|
canonicalOfflineRemoteIdentity(schema, identity);
|
|
2833
|
-
if (schema.identity.kind === '
|
|
2834
|
-
|
|
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;
|
|
2835
3231
|
}
|
|
2836
3232
|
const naturalKey = normalizeOfflineNaturalKey(schema, identity.naturalKey);
|
|
2837
3233
|
const predicates = ['_offline_user_id = ?'];
|
|
2838
|
-
const values = [scope.userId];
|
|
3234
|
+
const values = [canonicalOfflinePrincipalId(scope.userId)];
|
|
2839
3235
|
if (schema.scope === 'partition') {
|
|
2840
3236
|
predicates.push('_offline_scope_id = ?');
|
|
2841
3237
|
values.push(scope.scopeId);
|
|
@@ -2847,13 +3243,11 @@ class SqliteOfflineRepository {
|
|
|
2847
3243
|
}
|
|
2848
3244
|
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
|
|
2849
3245
|
const row = rows[0];
|
|
2850
|
-
|
|
2851
|
-
return null;
|
|
2852
|
-
return this.#replicaRowFromSqliteRow(schema, scope, sourceKey, this.#string(row['local_id']), row);
|
|
3246
|
+
return row ? this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row) : null;
|
|
2853
3247
|
}
|
|
2854
3248
|
async getReplicaCursor(scope) {
|
|
2855
3249
|
const rows = await this.#query('SELECT cursor FROM offline_replica_cursors WHERE user_id = ? AND scope_id = ?', [
|
|
2856
|
-
scope.userId,
|
|
3250
|
+
canonicalOfflinePrincipalId(scope.userId),
|
|
2857
3251
|
scope.scopeId,
|
|
2858
3252
|
]);
|
|
2859
3253
|
const row = rows[0];
|
|
@@ -2862,12 +3256,12 @@ class SqliteOfflineRepository {
|
|
|
2862
3256
|
return { ...scope, cursor: this.#string(row['cursor']) };
|
|
2863
3257
|
}
|
|
2864
3258
|
async getCommands(scope) {
|
|
2865
|
-
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]);
|
|
2866
3260
|
return rows.map((row) => this.#command(row));
|
|
2867
3261
|
}
|
|
2868
3262
|
async getCommandsForUser(userId) {
|
|
2869
3263
|
const rows = await this.#query('SELECT * FROM offline_sync_commands WHERE user_id = ? ORDER BY created_at ASC, command_id ASC', [
|
|
2870
|
-
userId,
|
|
3264
|
+
canonicalOfflinePrincipalId(userId),
|
|
2871
3265
|
]);
|
|
2872
3266
|
return rows.map((row) => this.#command(row));
|
|
2873
3267
|
}
|
|
@@ -2882,19 +3276,26 @@ class SqliteOfflineRepository {
|
|
|
2882
3276
|
}
|
|
2883
3277
|
async clearUser(userId) {
|
|
2884
3278
|
await this.#transaction(async (database) => {
|
|
2885
|
-
|
|
2886
|
-
await this.#execute(database, 'DELETE FROM
|
|
2887
|
-
await this.#execute(database, 'DELETE FROM
|
|
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]);
|
|
2888
3283
|
for (const entity of this.#options.replicaSchema.entities) {
|
|
2889
|
-
await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ?`, [
|
|
3284
|
+
await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ?`, [principal]);
|
|
2890
3285
|
}
|
|
2891
|
-
await this.#execute(database, 'UPDATE offline_metadata SET last_user_id = NULL WHERE id = 1 AND last_user_id = ?', [
|
|
3286
|
+
await this.#execute(database, 'UPDATE offline_metadata SET last_user_id = NULL WHERE id = 1 AND last_user_id = ?', [principal]);
|
|
2892
3287
|
});
|
|
2893
3288
|
}
|
|
2894
3289
|
async clearScope(scope) {
|
|
2895
3290
|
await this.#transaction(async (database) => {
|
|
2896
|
-
const values = [scope.userId, scope.scopeId];
|
|
2897
|
-
|
|
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
|
+
}
|
|
2898
3299
|
await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ? AND scope_id = ?', values);
|
|
2899
3300
|
for (const entity of this.#options.replicaSchema.entities) {
|
|
2900
3301
|
if (entity.scope !== 'partition')
|
|
@@ -2904,9 +3305,29 @@ class SqliteOfflineRepository {
|
|
|
2904
3305
|
});
|
|
2905
3306
|
}
|
|
2906
3307
|
async transactReplica(transaction) {
|
|
3308
|
+
for (const row of transaction.putRows ?? [])
|
|
3309
|
+
this.#validateReplicaRow(row);
|
|
2907
3310
|
await this.#transaction(async (databaseId) => {
|
|
2908
|
-
|
|
2909
|
-
|
|
3311
|
+
const releases = new Map();
|
|
3312
|
+
for (const release of transaction.releaseRemoteIds ?? []) {
|
|
3313
|
+
this.#assertValidReleaseRemoteId(release.remoteId);
|
|
3314
|
+
const key = this.#replicaRowKey(release);
|
|
3315
|
+
if (releases.has(key)) {
|
|
3316
|
+
throw new Error(`Offline replica remoteId release is duplicated for ${release.sourceKey}/${canonicalOfflineReplicaIdentity(release.identity)}.`);
|
|
3317
|
+
}
|
|
3318
|
+
releases.set(key, release);
|
|
3319
|
+
}
|
|
3320
|
+
const consumedReleases = new Set();
|
|
3321
|
+
for (const row of transaction.putRows ?? []) {
|
|
3322
|
+
const key = this.#replicaRowKey(row);
|
|
3323
|
+
const release = releases.get(key);
|
|
3324
|
+
await this.#putReplicaRow(databaseId, row, release);
|
|
3325
|
+
if (release)
|
|
3326
|
+
consumedReleases.add(key);
|
|
3327
|
+
}
|
|
3328
|
+
if (consumedReleases.size !== releases.size) {
|
|
3329
|
+
throw new Error('Offline replica remoteId release must match an existing row in putRows.');
|
|
3330
|
+
}
|
|
2910
3331
|
for (const row of transaction.removeRows ?? [])
|
|
2911
3332
|
await this.#removeReplicaRow(databaseId, row);
|
|
2912
3333
|
for (const command of transaction.putCommands ?? [])
|
|
@@ -2928,29 +3349,20 @@ class SqliteOfflineRepository {
|
|
|
2928
3349
|
this.#databaseId = databaseId;
|
|
2929
3350
|
for (const statement of SCHEMA)
|
|
2930
3351
|
await this.#execute(databaseId, statement);
|
|
2931
|
-
|
|
2932
|
-
if (
|
|
2933
|
-
await this.#execute(databaseId, '
|
|
2934
|
-
|
|
2935
|
-
|
|
2936
|
-
|
|
2937
|
-
|
|
2938
|
-
|
|
2939
|
-
|
|
2940
|
-
|
|
2941
|
-
|
|
2942
|
-
// Keep this repair outside the ADD-column branch so a process/database
|
|
2943
|
-
// failure after ALTER but before backfill is retried on every open.
|
|
2944
|
-
await this.#execute(databaseId, 'UPDATE offline_sync_commands SET optimistic_value_json = payload_json WHERE optimistic_value_json IS NULL');
|
|
2945
|
-
await this.#execute(databaseId, `INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, NULL)
|
|
2946
|
-
ON CONFLICT(id) DO UPDATE SET schema_version = excluded.schema_version`, [OFFLINE_SCHEMA_VERSION]);
|
|
2947
|
-
await this.#initializeReplicaSchema(databaseId);
|
|
2948
|
-
for (const entity of this.#options.replicaSchema.entities) {
|
|
2949
|
-
const columns = await this.#queryDatabase(databaseId, `PRAGMA table_info(${entity.tableName})`);
|
|
2950
|
-
if (!columns.some((column) => column['name'] === '_offline_visibility')) {
|
|
2951
|
-
await this.#execute(databaseId, `ALTER TABLE ${entity.tableName} ADD COLUMN _offline_visibility TEXT NOT NULL DEFAULT 'present'`);
|
|
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.');
|
|
2952
3363
|
}
|
|
2953
3364
|
}
|
|
3365
|
+
await this.#initializeReplicaSchema(databaseId);
|
|
2954
3366
|
}
|
|
2955
3367
|
async #initializeReplicaSchema(databaseId) {
|
|
2956
3368
|
const bundle = this.#options.replicaSchema;
|
|
@@ -3047,10 +3459,11 @@ class SqliteOfflineRepository {
|
|
|
3047
3459
|
#command(row) {
|
|
3048
3460
|
return {
|
|
3049
3461
|
commandId: this.#string(row['command_id']),
|
|
3050
|
-
userId: this.#
|
|
3462
|
+
userId: parseOfflinePrincipalId(this.#string(row['user_id'])),
|
|
3051
3463
|
scopeId: this.#string(row['scope_id']),
|
|
3052
3464
|
aggregateType: this.#string(row['aggregate_type']),
|
|
3053
|
-
|
|
3465
|
+
sourceKey: this.#string(row['source_key']),
|
|
3466
|
+
identity: parseOfflineCommandIdentity(this.#parse(row['identity_json'])),
|
|
3054
3467
|
operation: this.#string(row['operation']),
|
|
3055
3468
|
payload: this.#parse(row['payload_json']),
|
|
3056
3469
|
optimisticValue: this.#parse(row['optimistic_value_json']),
|
|
@@ -3066,21 +3479,23 @@ class SqliteOfflineRepository {
|
|
|
3066
3479
|
}
|
|
3067
3480
|
#putCommand(databaseId, command) {
|
|
3068
3481
|
return this.#execute(databaseId, `INSERT INTO offline_sync_commands
|
|
3069
|
-
(command_id, user_id, scope_id, aggregate_type,
|
|
3482
|
+
(command_id, user_id, scope_id, aggregate_type, source_key, identity_json, operation, payload_json, optimistic_value_json,
|
|
3070
3483
|
replica_mutation, payload_hash, base_revision_json, state, attempts, retry_at, created_at, last_error_code)
|
|
3071
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
3484
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
3072
3485
|
ON CONFLICT(command_id) DO UPDATE SET
|
|
3073
3486
|
user_id = excluded.user_id, scope_id = excluded.scope_id, aggregate_type = excluded.aggregate_type,
|
|
3074
|
-
|
|
3487
|
+
source_key = excluded.source_key,
|
|
3488
|
+
identity_json = excluded.identity_json, operation = excluded.operation, payload_json = excluded.payload_json,
|
|
3075
3489
|
optimistic_value_json = excluded.optimistic_value_json, replica_mutation = excluded.replica_mutation,
|
|
3076
3490
|
payload_hash = excluded.payload_hash,
|
|
3077
3491
|
base_revision_json = excluded.base_revision_json, state = excluded.state, attempts = excluded.attempts,
|
|
3078
3492
|
retry_at = excluded.retry_at, created_at = excluded.created_at, last_error_code = excluded.last_error_code`, [
|
|
3079
3493
|
command.commandId,
|
|
3080
|
-
command.userId,
|
|
3494
|
+
canonicalOfflinePrincipalId(command.userId),
|
|
3081
3495
|
command.scopeId,
|
|
3082
3496
|
command.aggregateType,
|
|
3083
|
-
command.
|
|
3497
|
+
command.sourceKey,
|
|
3498
|
+
serializeOfflineCommandIdentity(command.identity),
|
|
3084
3499
|
command.operation,
|
|
3085
3500
|
JSON.stringify(command.payload),
|
|
3086
3501
|
JSON.stringify(command.optimisticValue),
|
|
@@ -3094,56 +3509,132 @@ class SqliteOfflineRepository {
|
|
|
3094
3509
|
command.lastErrorCode,
|
|
3095
3510
|
]);
|
|
3096
3511
|
}
|
|
3097
|
-
async #
|
|
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
|
+
}
|
|
3542
|
+
async #putReplicaRow(databaseId, row, release) {
|
|
3098
3543
|
const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
|
|
3099
|
-
|
|
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
|
+
}
|
|
3100
3557
|
const encoded = encodeOfflineReplicaValues(schema, row.values);
|
|
3101
3558
|
if (row.confirmedValues !== null)
|
|
3102
3559
|
encodeOfflineReplicaValues(schema, row.confirmedValues);
|
|
3103
3560
|
assertOfflineReplicaNaturalKeyBaseline(schema, row.values, row.confirmedValues);
|
|
3104
|
-
const existing = await this
|
|
3561
|
+
const existing = await this.#queryReplicaRow(row, row.sourceKey, replicaAddressFromIdentity(row.identity), true);
|
|
3562
|
+
if (!existing && release) {
|
|
3563
|
+
throw new Error(`Offline replica remoteId release requires an existing row for ${row.sourceKey}/${canonicalOfflineReplicaIdentity(row.identity)}.`);
|
|
3564
|
+
}
|
|
3105
3565
|
if (existing)
|
|
3106
|
-
this.#assertReplicaIdentityAssignment(schema, existing, row);
|
|
3566
|
+
this.#assertReplicaIdentityAssignment(schema, existing, row, release);
|
|
3107
3567
|
const confirmedValues = row.confirmedValues === null ? null : projectOfflineReplicaValues(schema, row.confirmedValues);
|
|
3108
3568
|
const { sql, domainColumns } = this.#buildReplicaUpsertStatement(schema);
|
|
3109
|
-
const values = [
|
|
3110
|
-
|
|
3111
|
-
|
|
3112
|
-
|
|
3113
|
-
|
|
3114
|
-
|
|
3115
|
-
|
|
3116
|
-
|
|
3117
|
-
|
|
3118
|
-
|
|
3119
|
-
|
|
3120
|
-
|
|
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));
|
|
3121
3587
|
await this.#execute(databaseId, sql, values);
|
|
3122
3588
|
}
|
|
3123
3589
|
#removeReplicaRow(databaseId, key) {
|
|
3124
3590
|
const schema = this.#resolveReplicaEntitySchema(key.sourceKey);
|
|
3125
|
-
const predicates = ['
|
|
3126
|
-
const values = [key.
|
|
3591
|
+
const predicates = ['_offline_user_id = ?'];
|
|
3592
|
+
const values = [canonicalOfflinePrincipalId(key.userId)];
|
|
3127
3593
|
if (schema.scope === 'partition') {
|
|
3128
3594
|
predicates.push('_offline_scope_id = ?');
|
|
3129
3595
|
values.push(key.scopeId);
|
|
3130
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
|
+
}
|
|
3131
3608
|
return this.#execute(databaseId, `DELETE FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
|
|
3132
3609
|
}
|
|
3133
3610
|
#putReplicaCursor(databaseId, cursor) {
|
|
3134
3611
|
return this.#execute(databaseId, `INSERT INTO offline_replica_cursors (user_id, scope_id, cursor) VALUES (?, ?, ?)
|
|
3135
|
-
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]);
|
|
3136
3613
|
}
|
|
3137
3614
|
#buildReplicaUpsertStatement(schema) {
|
|
3138
|
-
const insertColumns = ['
|
|
3615
|
+
const insertColumns = ['_offline_user_id'];
|
|
3139
3616
|
const updateSets = ['_offline_user_id = excluded._offline_user_id'];
|
|
3617
|
+
const conflictTarget = ['_offline_user_id'];
|
|
3140
3618
|
if (schema.scope === 'partition') {
|
|
3141
3619
|
insertColumns.push('_offline_scope_id');
|
|
3142
3620
|
updateSets.push('_offline_scope_id = excluded._offline_scope_id');
|
|
3621
|
+
conflictTarget.push('_offline_scope_id');
|
|
3143
3622
|
}
|
|
3144
|
-
if (
|
|
3623
|
+
if (schema.identity.kind === 'generated') {
|
|
3624
|
+
insertColumns.unshift('local_id');
|
|
3145
3625
|
insertColumns.push('server_id');
|
|
3146
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');
|
|
3147
3638
|
}
|
|
3148
3639
|
insertColumns.push('_offline_confirmed_json', '_offline_server_revision_json', '_offline_sync_state', '_offline_visibility', '_offline_fetched_at');
|
|
3149
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');
|
|
@@ -3159,16 +3650,16 @@ class SqliteOfflineRepository {
|
|
|
3159
3650
|
return {
|
|
3160
3651
|
sql: `INSERT INTO ${schema.tableName} (${insertColumns.join(', ')})
|
|
3161
3652
|
VALUES (${placeholders})
|
|
3162
|
-
ON CONFLICT(
|
|
3653
|
+
ON CONFLICT(${conflictTarget.join(', ')}) DO UPDATE SET ${updateSets.join(', ')}`,
|
|
3163
3654
|
domainColumns,
|
|
3164
3655
|
};
|
|
3165
3656
|
}
|
|
3166
|
-
#replicaRowFromSqliteRow(schema, scope, sourceKey,
|
|
3657
|
+
#replicaRowFromSqliteRow(schema, scope, sourceKey, row) {
|
|
3658
|
+
const identity = this.#identityFromSqliteRow(schema, row);
|
|
3167
3659
|
return {
|
|
3168
3660
|
...scope,
|
|
3169
3661
|
sourceKey,
|
|
3170
|
-
|
|
3171
|
-
serverId: this.#schemaHasServerId(schema) ? this.#numberOrNull(row['server_id']) : null,
|
|
3662
|
+
identity,
|
|
3172
3663
|
values: decodeOfflineReplicaValues(schema, row),
|
|
3173
3664
|
confirmedValues: this.#parseNullable(row['_offline_confirmed_json']),
|
|
3174
3665
|
serverRevision: this.#parseNullable(row['_offline_server_revision_json']),
|
|
@@ -3177,33 +3668,111 @@ class SqliteOfflineRepository {
|
|
|
3177
3668
|
visibility: (row['_offline_visibility'] ?? 'present'),
|
|
3178
3669
|
};
|
|
3179
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
|
+
}
|
|
3180
3686
|
#resolveReplicaEntitySchema(sourceKey) {
|
|
3181
3687
|
const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);
|
|
3182
3688
|
if (!schema)
|
|
3183
3689
|
throw new Error(`Unknown offline replica source key "${sourceKey}".`);
|
|
3184
3690
|
return schema;
|
|
3185
3691
|
}
|
|
3186
|
-
#
|
|
3187
|
-
|
|
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);
|
|
3719
|
+
}
|
|
3720
|
+
#replicaRowKey(row) {
|
|
3721
|
+
const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
|
|
3722
|
+
return `${canonicalOfflinePrincipalId(row.userId)}:${schema.scope === 'user' ? 'user' : row.scopeId}:${row.sourceKey}:${canonicalOfflineReplicaIdentity(row.identity)}`;
|
|
3188
3723
|
}
|
|
3189
|
-
#assertReplicaIdentityAssignment(schema, existing, incoming) {
|
|
3190
|
-
if (schema.identity.kind
|
|
3191
|
-
|
|
3192
|
-
|
|
3724
|
+
#assertReplicaIdentityAssignment(schema, existing, incoming, release) {
|
|
3725
|
+
if (release && schema.identity.kind !== 'generated') {
|
|
3726
|
+
throw new Error(`Offline replica remoteId release is unsupported for source "${incoming.sourceKey}".`);
|
|
3727
|
+
}
|
|
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
|
+
}
|
|
3741
|
+
if (release) {
|
|
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}.`);
|
|
3744
|
+
}
|
|
3745
|
+
return;
|
|
3746
|
+
}
|
|
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)}.`);
|
|
3193
3752
|
}
|
|
3194
3753
|
return;
|
|
3195
3754
|
}
|
|
3196
3755
|
if (schema.identity.kind === 'naturalKey') {
|
|
3197
|
-
|
|
3198
|
-
|
|
3199
|
-
}
|
|
3200
|
-
const
|
|
3201
|
-
|
|
3202
|
-
});
|
|
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 });
|
|
3203
3761
|
if (current !== next)
|
|
3204
3762
|
throw new Error(`Offline replica naturalKey is immutable for "${schema.sourceKey}".`);
|
|
3205
3763
|
}
|
|
3206
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
|
+
}
|
|
3207
3776
|
async #execute(databaseId, statement, values = []) {
|
|
3208
3777
|
await this.#sqlite.execute({ databaseId, statement, values });
|
|
3209
3778
|
}
|
|
@@ -3350,5 +3919,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
|
|
|
3350
3919
|
* Generated bundle index. Do not edit.
|
|
3351
3920
|
*/
|
|
3352
3921
|
|
|
3353
|
-
export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCoordinatorService, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaPullService, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineSyncService, SqliteOfflineRepository,
|
|
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 };
|
|
3354
3923
|
//# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map
|