@rdlabo/ionic-angular-kit 21.3.4 → 21.4.1
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.
- package/README.md +123 -0
- package/fesm2022/rdlabo-ionic-angular-kit-offline.mjs +2569 -0
- package/fesm2022/rdlabo-ionic-angular-kit-offline.mjs.map +1 -0
- package/fesm2022/rdlabo-ionic-angular-kit.mjs +23 -0
- package/fesm2022/rdlabo-ionic-angular-kit.mjs.map +1 -1
- package/package.json +9 -1
- package/types/rdlabo-ionic-angular-kit-offline.d.ts +641 -0
- package/types/rdlabo-ionic-angular-kit.d.ts +6 -0
|
@@ -0,0 +1,2569 @@
|
|
|
1
|
+
import * as i0 from '@angular/core';
|
|
2
|
+
import { InjectionToken, inject, Injectable, signal, computed, ErrorHandler, effect, makeEnvironmentProviders, provideAppInitializer } from '@angular/core';
|
|
3
|
+
import { KitStorageService } from '@rdlabo/ionic-angular-kit';
|
|
4
|
+
import { App } from '@capacitor/app';
|
|
5
|
+
import { Network } from '@capacitor/network';
|
|
6
|
+
import { Capacitor } from '@capacitor/core';
|
|
7
|
+
import { HttpContextToken, HttpResponse } from '@angular/common/http';
|
|
8
|
+
import { defer, catchError, throwError, tap, from, concatMap, of } from 'rxjs';
|
|
9
|
+
|
|
10
|
+
const IDENTIFIER_PATTERN = /^[a-z][a-z0-9_]*$/;
|
|
11
|
+
const RESERVED_COLUMN_NAMES = new Set([
|
|
12
|
+
'local_id',
|
|
13
|
+
'_offline_user_id',
|
|
14
|
+
'_offline_group_id',
|
|
15
|
+
'server_id',
|
|
16
|
+
'_offline_confirmed_json',
|
|
17
|
+
'_offline_server_revision_json',
|
|
18
|
+
'_offline_sync_state',
|
|
19
|
+
'_offline_fetched_at',
|
|
20
|
+
]);
|
|
21
|
+
/**
|
|
22
|
+
* Begins a type-safe replica entity schema definition for the given select shape.
|
|
23
|
+
*
|
|
24
|
+
* Every key in `TSelect` must appear exactly once in `fields`, and column nullability
|
|
25
|
+
* must match the select property nullability.
|
|
26
|
+
*/
|
|
27
|
+
function defineReplicaEntity() {
|
|
28
|
+
return function defineReplicaEntityConfig(definition) {
|
|
29
|
+
return buildOfflineReplicaEntitySchema({
|
|
30
|
+
table: definition.table,
|
|
31
|
+
sourceKey: definition.sourceKey,
|
|
32
|
+
scope: definition.scope,
|
|
33
|
+
fields: definition.fields,
|
|
34
|
+
});
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
function requiredColumn(affinity, storageKind) {
|
|
38
|
+
return { kind: 'column', affinity, storageKind, nullable: false };
|
|
39
|
+
}
|
|
40
|
+
/** Maps a non-null string source property to a TEXT column. */
|
|
41
|
+
function text() {
|
|
42
|
+
return requiredColumn('TEXT', 'text');
|
|
43
|
+
}
|
|
44
|
+
/** Maps a non-null integer source property to an INTEGER column. */
|
|
45
|
+
function integer() {
|
|
46
|
+
return requiredColumn('INTEGER', 'integer');
|
|
47
|
+
}
|
|
48
|
+
/** Maps a non-null floating-point source property to a REAL column. */
|
|
49
|
+
function real() {
|
|
50
|
+
return requiredColumn('REAL', 'real');
|
|
51
|
+
}
|
|
52
|
+
/** Maps a non-null boolean source property to an INTEGER column. */
|
|
53
|
+
function booleanColumn() {
|
|
54
|
+
return requiredColumn('INTEGER', 'booleanColumn');
|
|
55
|
+
}
|
|
56
|
+
/** Maps a non-null JSON-serializable source property to a TEXT column. */
|
|
57
|
+
function json() {
|
|
58
|
+
return requiredColumn('TEXT', 'json');
|
|
59
|
+
}
|
|
60
|
+
/** Maps a non-null datetime source property to a canonical ISO-8601 TEXT column. */
|
|
61
|
+
function datetime() {
|
|
62
|
+
return requiredColumn('TEXT', 'datetime');
|
|
63
|
+
}
|
|
64
|
+
/** Marks a column builder as nullable for nullable select properties. */
|
|
65
|
+
function nullable(column) {
|
|
66
|
+
return {
|
|
67
|
+
kind: 'column',
|
|
68
|
+
affinity: column.affinity,
|
|
69
|
+
storageKind: column.storageKind,
|
|
70
|
+
nullable: true,
|
|
71
|
+
...(column.columnName !== undefined ? { columnName: column.columnName } : {}),
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
/** Maps a source property to the shared nullable `server_id` column. */
|
|
75
|
+
function serverId() {
|
|
76
|
+
return { kind: 'serverId' };
|
|
77
|
+
}
|
|
78
|
+
/** Excludes a source property from SQLite while retaining it in the select shape. */
|
|
79
|
+
function ignored(reason) {
|
|
80
|
+
return { kind: 'ignored', reason };
|
|
81
|
+
}
|
|
82
|
+
function buildOfflineReplicaEntitySchema(definition) {
|
|
83
|
+
validateIdentifier(definition.table, 'table');
|
|
84
|
+
validateIdentifier(definition.sourceKey, 'source key');
|
|
85
|
+
const sourceKeys = Object.keys(definition.fields).sort();
|
|
86
|
+
const serverIdCount = sourceKeys.filter((sourceKey) => definition.fields[sourceKey]?.kind === 'serverId').length;
|
|
87
|
+
if (serverIdCount !== 1)
|
|
88
|
+
throw new Error('Replica entity must define exactly one serverId field.');
|
|
89
|
+
const hasServerId = true;
|
|
90
|
+
const fields = sourceKeys.map((sourceKey) => {
|
|
91
|
+
const fieldDef = definition.fields[sourceKey];
|
|
92
|
+
return materializeFieldDescriptor(sourceKey, fieldDef);
|
|
93
|
+
});
|
|
94
|
+
const createTableSql = buildCreateTableSql(definition.table, definition.scope, fields, hasServerId);
|
|
95
|
+
const schemaFingerprintInput = buildSchemaFingerprintInput(definition.table, definition.sourceKey, definition.scope, fields, hasServerId);
|
|
96
|
+
return {
|
|
97
|
+
tableName: definition.table,
|
|
98
|
+
sourceKey: definition.sourceKey,
|
|
99
|
+
scope: definition.scope,
|
|
100
|
+
fields,
|
|
101
|
+
createTableSql,
|
|
102
|
+
schemaFingerprintInput,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
function materializeFieldDescriptor(sourceKey, fieldDef) {
|
|
106
|
+
if (fieldDef.kind === 'ignored') {
|
|
107
|
+
if (!fieldDef.reason.trim())
|
|
108
|
+
throw new Error(`Replica ignored field "${sourceKey}" requires a reason.`);
|
|
109
|
+
return {
|
|
110
|
+
sourceKey,
|
|
111
|
+
policy: 'ignored',
|
|
112
|
+
sqliteColumnName: null,
|
|
113
|
+
affinity: null,
|
|
114
|
+
storageKind: null,
|
|
115
|
+
nullable: false,
|
|
116
|
+
ignoredReason: fieldDef.reason,
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
if (fieldDef.kind === 'serverId') {
|
|
120
|
+
return {
|
|
121
|
+
sourceKey,
|
|
122
|
+
policy: 'serverId',
|
|
123
|
+
sqliteColumnName: 'server_id',
|
|
124
|
+
affinity: 'INTEGER',
|
|
125
|
+
storageKind: null,
|
|
126
|
+
nullable: true,
|
|
127
|
+
ignoredReason: null,
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
const sqliteColumnName = fieldDef.columnName ?? toSnakeCase(sourceKey);
|
|
131
|
+
validateIdentifier(sqliteColumnName, 'column');
|
|
132
|
+
if (RESERVED_COLUMN_NAMES.has(sqliteColumnName)) {
|
|
133
|
+
throw new Error(`Replica column "${sqliteColumnName}" is reserved.`);
|
|
134
|
+
}
|
|
135
|
+
return {
|
|
136
|
+
sourceKey,
|
|
137
|
+
policy: 'column',
|
|
138
|
+
sqliteColumnName,
|
|
139
|
+
affinity: fieldDef.affinity,
|
|
140
|
+
storageKind: fieldDef.storageKind,
|
|
141
|
+
nullable: fieldDef.nullable === true,
|
|
142
|
+
ignoredReason: null,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
function buildCreateTableSql(tableName, scope, fields, hasServerId) {
|
|
146
|
+
const columnLines = ['local_id TEXT NOT NULL', '_offline_user_id INTEGER NOT NULL'];
|
|
147
|
+
if (scope === 'group') {
|
|
148
|
+
columnLines.push('_offline_group_id INTEGER NOT NULL');
|
|
149
|
+
}
|
|
150
|
+
if (hasServerId) {
|
|
151
|
+
columnLines.push('server_id INTEGER');
|
|
152
|
+
}
|
|
153
|
+
columnLines.push('_offline_confirmed_json TEXT', '_offline_server_revision_json TEXT', '_offline_sync_state TEXT NOT NULL', '_offline_fetched_at INTEGER NOT NULL');
|
|
154
|
+
for (const field of fields) {
|
|
155
|
+
if (field.policy !== 'column') {
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
const nullability = field.nullable ? '' : ' NOT NULL';
|
|
159
|
+
columnLines.push(`${field.sqliteColumnName} ${field.affinity}${nullability}`);
|
|
160
|
+
}
|
|
161
|
+
const statements = [`CREATE TABLE IF NOT EXISTS ${tableName} (\n ${columnLines.join(',\n ')},\n PRIMARY KEY (local_id)\n)`];
|
|
162
|
+
if (hasServerId) {
|
|
163
|
+
const indexColumns = scope === 'group' ? '_offline_user_id, _offline_group_id, server_id' : '_offline_user_id, server_id';
|
|
164
|
+
statements.push(`CREATE UNIQUE INDEX IF NOT EXISTS uq_${tableName}_server_id ON ${tableName} (${indexColumns}) WHERE server_id IS NOT NULL`);
|
|
165
|
+
}
|
|
166
|
+
return statements;
|
|
167
|
+
}
|
|
168
|
+
function buildSchemaFingerprintInput(tableName, sourceKey, scope, fields, hasServerId) {
|
|
169
|
+
const fieldParts = fields.map((field) => {
|
|
170
|
+
if (field.policy === 'ignored') {
|
|
171
|
+
return `${field.sourceKey}:ignored:${field.ignoredReason ?? ''}`;
|
|
172
|
+
}
|
|
173
|
+
if (field.policy === 'serverId') {
|
|
174
|
+
return `${field.sourceKey}:serverId:server_id:INTEGER:nullable`;
|
|
175
|
+
}
|
|
176
|
+
return `${field.sourceKey}:column:${field.sqliteColumnName}:${field.affinity}:${field.storageKind}:${field.nullable ? 'nullable' : 'required'}`;
|
|
177
|
+
});
|
|
178
|
+
return [
|
|
179
|
+
`table=${tableName}`,
|
|
180
|
+
`source=${sourceKey}`,
|
|
181
|
+
`scope=${scope}`,
|
|
182
|
+
`hasServerId=${hasServerId ? '1' : '0'}`,
|
|
183
|
+
`fields=${fieldParts.join(';')}`,
|
|
184
|
+
].join('|');
|
|
185
|
+
}
|
|
186
|
+
function validateIdentifier(value, kind) {
|
|
187
|
+
if (!IDENTIFIER_PATTERN.test(value)) {
|
|
188
|
+
throw new Error(`Replica ${kind} "${value}" must match ${IDENTIFIER_PATTERN.source}.`);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
function toSnakeCase(value) {
|
|
192
|
+
return value
|
|
193
|
+
.replace(/([A-Z])/g, '_$1')
|
|
194
|
+
.replace(/^_/, '')
|
|
195
|
+
.toLowerCase();
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Validates and encodes a source-model row into SQLite-bound column values.
|
|
199
|
+
*
|
|
200
|
+
* Only {@link OfflineReplicaFieldPolicy} `column` fields are emitted, keyed by
|
|
201
|
+
* {@link OfflineReplicaFieldDescriptor.sqliteColumnName} in descriptor order.
|
|
202
|
+
* Source properties mapped as `serverId` or `ignored` may be present but are not encoded.
|
|
203
|
+
*/
|
|
204
|
+
function encodeOfflineReplicaValues(schema, values) {
|
|
205
|
+
if (!isPlainObject$1(values)) {
|
|
206
|
+
throw new Error('Replica row values must be a plain object.');
|
|
207
|
+
}
|
|
208
|
+
const sourceValues = values;
|
|
209
|
+
const allowedSourceKeys = new Set(schema.fields.map((field) => field.sourceKey));
|
|
210
|
+
for (const sourceKey of Object.keys(sourceValues)) {
|
|
211
|
+
if (!allowedSourceKeys.has(sourceKey)) {
|
|
212
|
+
throw new Error(`Replica row contains unknown source key "${sourceKey}".`);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
const encoded = {};
|
|
216
|
+
for (const field of schema.fields) {
|
|
217
|
+
if (field.policy !== 'column') {
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
const sqliteColumnName = field.sqliteColumnName;
|
|
221
|
+
if (sqliteColumnName === null) {
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
if (!Object.prototype.hasOwnProperty.call(sourceValues, field.sourceKey)) {
|
|
225
|
+
throw new Error(`Replica row is missing required source key "${field.sourceKey}".`);
|
|
226
|
+
}
|
|
227
|
+
const rawValue = sourceValues[field.sourceKey];
|
|
228
|
+
if (rawValue === null) {
|
|
229
|
+
if (!field.nullable) {
|
|
230
|
+
throw new Error(`Replica row source key "${field.sourceKey}" must not be null.`);
|
|
231
|
+
}
|
|
232
|
+
encoded[sqliteColumnName] = null;
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
if (rawValue === undefined) {
|
|
236
|
+
throw new Error(`Replica row source key "${field.sourceKey}" must not be undefined.`);
|
|
237
|
+
}
|
|
238
|
+
encoded[sqliteColumnName] = encodeReplicaColumnValue(field, rawValue);
|
|
239
|
+
}
|
|
240
|
+
return encoded;
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Validates and decodes SQLite column values into a source-model row.
|
|
244
|
+
*
|
|
245
|
+
* Only {@link OfflineReplicaFieldPolicy} `column` fields are emitted, keyed by
|
|
246
|
+
* {@link OfflineReplicaFieldDescriptor.sourceKey} in descriptor order.
|
|
247
|
+
* Physical columns such as `server_id`, sync metadata, and scope keys may be
|
|
248
|
+
* present in `row` but are not decoded.
|
|
249
|
+
*/
|
|
250
|
+
function decodeOfflineReplicaValues(schema, row) {
|
|
251
|
+
if (!isPlainObject$1(row)) {
|
|
252
|
+
throw new Error('Replica SQLite row must be a plain object.');
|
|
253
|
+
}
|
|
254
|
+
const decoded = {};
|
|
255
|
+
for (const field of schema.fields) {
|
|
256
|
+
if (field.policy !== 'column') {
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
const sqliteColumnName = field.sqliteColumnName;
|
|
260
|
+
if (sqliteColumnName === null) {
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
if (!Object.prototype.hasOwnProperty.call(row, sqliteColumnName)) {
|
|
264
|
+
throw new Error(`Replica SQLite row is missing required column "${sqliteColumnName}".`);
|
|
265
|
+
}
|
|
266
|
+
const rawValue = row[sqliteColumnName];
|
|
267
|
+
if (rawValue === null) {
|
|
268
|
+
if (!field.nullable) {
|
|
269
|
+
throw new Error(`Replica SQLite column "${sqliteColumnName}" must not be null.`);
|
|
270
|
+
}
|
|
271
|
+
decoded[field.sourceKey] = null;
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
if (rawValue === undefined) {
|
|
275
|
+
throw new Error(`Replica SQLite column "${sqliteColumnName}" must not be undefined.`);
|
|
276
|
+
}
|
|
277
|
+
decoded[field.sourceKey] = decodeReplicaColumnValue(field, rawValue);
|
|
278
|
+
}
|
|
279
|
+
return decoded;
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Validates a source-model row and returns the canonical domain projection persisted by every repository.
|
|
283
|
+
*
|
|
284
|
+
* Fields mapped as `serverId` or `ignored` are intentionally omitted. This keeps web and native row shapes
|
|
285
|
+
* identical; the server identifier remains available through the replica row's dedicated `serverId` field.
|
|
286
|
+
*/
|
|
287
|
+
function projectOfflineReplicaValues(schema, values) {
|
|
288
|
+
return decodeOfflineReplicaValues(schema, encodeOfflineReplicaValues(schema, values));
|
|
289
|
+
}
|
|
290
|
+
function isPlainObject$1(value) {
|
|
291
|
+
if (value === null || typeof value !== 'object') {
|
|
292
|
+
return false;
|
|
293
|
+
}
|
|
294
|
+
const prototype = Object.getPrototypeOf(value);
|
|
295
|
+
return prototype === Object.prototype || prototype === null;
|
|
296
|
+
}
|
|
297
|
+
function encodeReplicaColumnValue(field, value) {
|
|
298
|
+
switch (field.storageKind) {
|
|
299
|
+
case 'text':
|
|
300
|
+
return encodeReplicaTextValue(field.sourceKey, value);
|
|
301
|
+
case 'integer':
|
|
302
|
+
return encodeReplicaIntegerValue(field.sourceKey, value);
|
|
303
|
+
case 'real':
|
|
304
|
+
return encodeReplicaRealValue(field.sourceKey, value);
|
|
305
|
+
case 'booleanColumn':
|
|
306
|
+
return encodeReplicaBooleanValue(field.sourceKey, value);
|
|
307
|
+
case 'json':
|
|
308
|
+
return encodeReplicaJsonValue(field.sourceKey, value);
|
|
309
|
+
case 'datetime':
|
|
310
|
+
return encodeReplicaDatetimeValue(field.sourceKey, value);
|
|
311
|
+
default:
|
|
312
|
+
throw new Error(`Replica row source key "${field.sourceKey}" has no storage kind.`);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
function decodeReplicaColumnValue(field, value) {
|
|
316
|
+
switch (field.storageKind) {
|
|
317
|
+
case 'text':
|
|
318
|
+
return decodeReplicaTextValue(field.sourceKey, value);
|
|
319
|
+
case 'integer':
|
|
320
|
+
return decodeReplicaIntegerValue(field.sourceKey, value);
|
|
321
|
+
case 'real':
|
|
322
|
+
return decodeReplicaRealValue(field.sourceKey, value);
|
|
323
|
+
case 'booleanColumn':
|
|
324
|
+
return decodeReplicaBooleanValue(field.sourceKey, value);
|
|
325
|
+
case 'json':
|
|
326
|
+
return decodeReplicaJsonValue(field.sourceKey, value);
|
|
327
|
+
case 'datetime':
|
|
328
|
+
return decodeReplicaDatetimeValue(field.sourceKey, value);
|
|
329
|
+
default:
|
|
330
|
+
throw new Error(`Replica row source key "${field.sourceKey}" has no storage kind.`);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
function encodeReplicaTextValue(sourceKey, value) {
|
|
334
|
+
if (typeof value !== 'string') {
|
|
335
|
+
throw new Error(`Replica row source key "${sourceKey}" must be a string.`);
|
|
336
|
+
}
|
|
337
|
+
return value;
|
|
338
|
+
}
|
|
339
|
+
function encodeReplicaIntegerValue(sourceKey, value) {
|
|
340
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isSafeInteger(value)) {
|
|
341
|
+
throw new Error(`Replica row source key "${sourceKey}" must be a finite safe integer.`);
|
|
342
|
+
}
|
|
343
|
+
return value;
|
|
344
|
+
}
|
|
345
|
+
function encodeReplicaRealValue(sourceKey, value) {
|
|
346
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
|
347
|
+
throw new Error(`Replica row source key "${sourceKey}" must be a finite number.`);
|
|
348
|
+
}
|
|
349
|
+
return value;
|
|
350
|
+
}
|
|
351
|
+
function encodeReplicaBooleanValue(sourceKey, value) {
|
|
352
|
+
if (typeof value !== 'boolean') {
|
|
353
|
+
throw new Error(`Replica row source key "${sourceKey}" must be a boolean.`);
|
|
354
|
+
}
|
|
355
|
+
return value ? 1 : 0;
|
|
356
|
+
}
|
|
357
|
+
function encodeReplicaJsonValue(sourceKey, value) {
|
|
358
|
+
assertJsonSerializable(sourceKey, value);
|
|
359
|
+
return JSON.stringify(value);
|
|
360
|
+
}
|
|
361
|
+
function encodeReplicaDatetimeValue(sourceKey, value) {
|
|
362
|
+
if (value instanceof Date) {
|
|
363
|
+
if (Number.isNaN(value.getTime())) {
|
|
364
|
+
throw new Error(`Replica row source key "${sourceKey}" must be a valid Date.`);
|
|
365
|
+
}
|
|
366
|
+
return value.toISOString();
|
|
367
|
+
}
|
|
368
|
+
if (typeof value === 'string') {
|
|
369
|
+
return value;
|
|
370
|
+
}
|
|
371
|
+
throw new Error(`Replica row source key "${sourceKey}" must be a Date or string.`);
|
|
372
|
+
}
|
|
373
|
+
function decodeReplicaTextValue(sourceKey, value) {
|
|
374
|
+
if (typeof value !== 'string') {
|
|
375
|
+
throw new Error(`Replica row source key "${sourceKey}" must be a string.`);
|
|
376
|
+
}
|
|
377
|
+
return value;
|
|
378
|
+
}
|
|
379
|
+
function decodeReplicaIntegerValue(sourceKey, value) {
|
|
380
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isSafeInteger(value)) {
|
|
381
|
+
throw new Error(`Replica row source key "${sourceKey}" must be a finite safe integer.`);
|
|
382
|
+
}
|
|
383
|
+
return value;
|
|
384
|
+
}
|
|
385
|
+
function decodeReplicaRealValue(sourceKey, value) {
|
|
386
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
|
387
|
+
throw new Error(`Replica row source key "${sourceKey}" must be a finite number.`);
|
|
388
|
+
}
|
|
389
|
+
return value;
|
|
390
|
+
}
|
|
391
|
+
function decodeReplicaBooleanValue(sourceKey, value) {
|
|
392
|
+
if (value !== 0 && value !== 1) {
|
|
393
|
+
throw new Error(`Replica row source key "${sourceKey}" must be boolean integer 0 or 1.`);
|
|
394
|
+
}
|
|
395
|
+
return value === 1;
|
|
396
|
+
}
|
|
397
|
+
function decodeReplicaJsonValue(sourceKey, value) {
|
|
398
|
+
if (typeof value !== 'string') {
|
|
399
|
+
throw new Error(`Replica row source key "${sourceKey}" must be a JSON string.`);
|
|
400
|
+
}
|
|
401
|
+
try {
|
|
402
|
+
return JSON.parse(value);
|
|
403
|
+
}
|
|
404
|
+
catch {
|
|
405
|
+
throw new Error(`Replica row source key "${sourceKey}" must be valid JSON.`);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
function decodeReplicaDatetimeValue(sourceKey, value) {
|
|
409
|
+
if (typeof value !== 'string') {
|
|
410
|
+
throw new Error(`Replica row source key "${sourceKey}" must be a string.`);
|
|
411
|
+
}
|
|
412
|
+
return value;
|
|
413
|
+
}
|
|
414
|
+
function assertJsonSerializable(sourceKey, value, seen = new WeakSet()) {
|
|
415
|
+
if (value === null || typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string') {
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
if (typeof value === 'undefined') {
|
|
419
|
+
throw new Error(`Replica row source key "${sourceKey}" must be JSON-serializable without undefined.`);
|
|
420
|
+
}
|
|
421
|
+
if (typeof value === 'function' || typeof value === 'symbol' || typeof value === 'bigint') {
|
|
422
|
+
throw new Error(`Replica row source key "${sourceKey}" must be JSON-serializable without functions.`);
|
|
423
|
+
}
|
|
424
|
+
if (Array.isArray(value)) {
|
|
425
|
+
for (const item of value) {
|
|
426
|
+
assertJsonSerializable(sourceKey, item, seen);
|
|
427
|
+
}
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
if (typeof value === 'object') {
|
|
431
|
+
if (seen.has(value)) {
|
|
432
|
+
throw new Error(`Replica row source key "${sourceKey}" must be JSON-serializable without cycles.`);
|
|
433
|
+
}
|
|
434
|
+
seen.add(value);
|
|
435
|
+
for (const key of Object.keys(value)) {
|
|
436
|
+
assertJsonSerializable(sourceKey, value[key], seen);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
/**
|
|
441
|
+
* Validates and materializes a versioned offline replica schema bundle.
|
|
442
|
+
*
|
|
443
|
+
* Entity `tableName` and `sourceKey` values must each be unique within the bundle.
|
|
444
|
+
* Migrations must advance one version at a time without duplicates or gaps.
|
|
445
|
+
*/
|
|
446
|
+
function defineOfflineReplicaSchema(definition) {
|
|
447
|
+
assertPositiveInteger(definition.version, 'schema version');
|
|
448
|
+
const entities = [...definition.entities].sort((left, right) => left.sourceKey < right.sourceKey ? -1 : left.sourceKey > right.sourceKey ? 1 : 0);
|
|
449
|
+
const tableNames = new Set();
|
|
450
|
+
const sourceKeys = new Set();
|
|
451
|
+
for (const entity of entities) {
|
|
452
|
+
if (tableNames.has(entity.tableName)) {
|
|
453
|
+
throw new Error(`Duplicate replica entity table "${entity.tableName}".`);
|
|
454
|
+
}
|
|
455
|
+
tableNames.add(entity.tableName);
|
|
456
|
+
if (sourceKeys.has(entity.sourceKey)) {
|
|
457
|
+
throw new Error(`Duplicate replica entity source key "${entity.sourceKey}".`);
|
|
458
|
+
}
|
|
459
|
+
sourceKeys.add(entity.sourceKey);
|
|
460
|
+
}
|
|
461
|
+
const migrations = normalizeOfflineReplicaMigrations(definition.migrations, definition.version);
|
|
462
|
+
const schemaFingerprintInput = buildBundleSchemaFingerprintInput(definition.version, entities, migrations);
|
|
463
|
+
return {
|
|
464
|
+
version: definition.version,
|
|
465
|
+
entities,
|
|
466
|
+
migrations,
|
|
467
|
+
schemaFingerprintInput,
|
|
468
|
+
};
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* Computes a lowercase SHA-256 hex digest of {@link OfflineReplicaSchemaBundle.schemaFingerprintInput}.
|
|
472
|
+
*/
|
|
473
|
+
async function sha256OfflineReplicaSchema(bundle) {
|
|
474
|
+
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(bundle.schemaFingerprintInput));
|
|
475
|
+
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');
|
|
476
|
+
}
|
|
477
|
+
function normalizeOfflineReplicaMigrations(migrations, bundleVersion) {
|
|
478
|
+
const sorted = [...migrations].sort((left, right) => left.fromVersion - right.fromVersion);
|
|
479
|
+
const seenFromVersions = new Set();
|
|
480
|
+
for (const migration of sorted) {
|
|
481
|
+
assertPositiveInteger(migration.fromVersion, 'migration fromVersion');
|
|
482
|
+
const targetVersion = migration.fromVersion + 1;
|
|
483
|
+
if (targetVersion > bundleVersion) {
|
|
484
|
+
throw new Error(`Replica migration from version ${migration.fromVersion} targets version ${targetVersion}, which exceeds bundle version ${bundleVersion}.`);
|
|
485
|
+
}
|
|
486
|
+
if (seenFromVersions.has(migration.fromVersion)) {
|
|
487
|
+
throw new Error(`Duplicate replica migration from version ${migration.fromVersion}.`);
|
|
488
|
+
}
|
|
489
|
+
seenFromVersions.add(migration.fromVersion);
|
|
490
|
+
if (typeof migration.migrateWebRow !== 'function') {
|
|
491
|
+
throw new Error(`Replica migration from version ${migration.fromVersion} requires migrateWebRow.`);
|
|
492
|
+
}
|
|
493
|
+
if (migration.statements.length === 0) {
|
|
494
|
+
throw new Error(`Replica migration from version ${migration.fromVersion} requires at least one SQL statement.`);
|
|
495
|
+
}
|
|
496
|
+
for (const [index, statement] of migration.statements.entries()) {
|
|
497
|
+
if (!statement.trim()) {
|
|
498
|
+
throw new Error(`Replica migration from version ${migration.fromVersion} statement ${index + 1} must not be empty.`);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
for (let index = 1; index < sorted.length; index++) {
|
|
503
|
+
const previous = sorted[index - 1];
|
|
504
|
+
const current = sorted[index];
|
|
505
|
+
if (current.fromVersion !== previous.fromVersion + 1) {
|
|
506
|
+
throw new Error(`Replica migrations must advance consecutive schema versions; expected fromVersion ${previous.fromVersion + 1}, received ${current.fromVersion}.`);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
if (sorted.length > 0 && sorted[0].fromVersion !== 1) {
|
|
510
|
+
throw new Error(`Replica migrations must advance consecutive schema versions; expected fromVersion 1, received ${sorted[0].fromVersion}.`);
|
|
511
|
+
}
|
|
512
|
+
return sorted;
|
|
513
|
+
}
|
|
514
|
+
function buildBundleSchemaFingerprintInput(version, entities, migrations) {
|
|
515
|
+
const entityFingerprints = entities.map((entity) => entity.schemaFingerprintInput).join(';');
|
|
516
|
+
const migrationFingerprints = migrations
|
|
517
|
+
.map((migration) => `from=${migration.fromVersion}|statements=${migration.statements.join('\n')}`)
|
|
518
|
+
.join(';');
|
|
519
|
+
return `version=${version}|entities=${entityFingerprints}|migrations=${migrationFingerprints}`;
|
|
520
|
+
}
|
|
521
|
+
function assertPositiveInteger(value, label) {
|
|
522
|
+
if (!Number.isInteger(value) || value <= 0) {
|
|
523
|
+
throw new Error(`Replica ${label} must be a positive integer.`);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/** DI token for the application-provided explicit replica pull transport. */
|
|
528
|
+
const OFFLINE_REPLICA_PULLER = new InjectionToken('OFFLINE_REPLICA_PULLER');
|
|
529
|
+
|
|
530
|
+
/** DI token for product-independent offline persistence settings. */
|
|
531
|
+
const OFFLINE_KIT_OPTIONS = new InjectionToken('OFFLINE_KIT_OPTIONS');
|
|
532
|
+
|
|
533
|
+
const DEFAULT_OFFLINE_COMMAND_HOOKS = {
|
|
534
|
+
entityType: (command) => command.aggregateType,
|
|
535
|
+
};
|
|
536
|
+
/** DI token for optional product-specific synchronization hooks. */
|
|
537
|
+
const OFFLINE_COMMAND_HOOKS = new InjectionToken('OFFLINE_COMMAND_HOOKS', {
|
|
538
|
+
providedIn: 'root',
|
|
539
|
+
factory: () => DEFAULT_OFFLINE_COMMAND_HOOKS,
|
|
540
|
+
});
|
|
541
|
+
|
|
542
|
+
/** DI token for the product-specific command transport adapter. */
|
|
543
|
+
const OFFLINE_COMMAND_EXECUTOR = new InjectionToken('OFFLINE_COMMAND_EXECUTOR');
|
|
544
|
+
/** DI token for authenticated synchronization context. */
|
|
545
|
+
const OFFLINE_SYNC_CONTEXT = new InjectionToken('OFFLINE_SYNC_CONTEXT');
|
|
546
|
+
|
|
547
|
+
/** Current durable storage schema used by both web and native repositories. */
|
|
548
|
+
const OFFLINE_SCHEMA_VERSION = 4;
|
|
549
|
+
/** DI token for the selected platform repository. */
|
|
550
|
+
const OFFLINE_REPOSITORY = new InjectionToken('OFFLINE_REPOSITORY');
|
|
551
|
+
/** Selects encrypted SQLite on native platforms and Ionic Storage on web. */
|
|
552
|
+
function selectOfflineRepository(platform, webRepository, nativeRepository) {
|
|
553
|
+
return platform === 'ios' || platform === 'android' ? nativeRepository : webRepository;
|
|
554
|
+
}
|
|
555
|
+
const METADATA_KEY = 'offline:metadata';
|
|
556
|
+
const SESSION_MANIFESTS_KEY = 'offline:session:manifests';
|
|
557
|
+
const ROWS_KEY = 'offline:replica:rows';
|
|
558
|
+
const CURSORS_KEY = 'offline:replica:cursors';
|
|
559
|
+
const LEGACY_ENTITIES_KEY = 'offline:business_cache:entities';
|
|
560
|
+
const LEGACY_QUERIES_KEY = 'offline:business_cache:queries';
|
|
561
|
+
const OUTBOX_KEY = 'offline:outbox:commands';
|
|
562
|
+
const REPLICA_TRANSACTION_KEY = 'offline:replica:transaction';
|
|
563
|
+
const REPLICA_SCHEMA_MIGRATION_KEY = 'offline:replica:schema-migration';
|
|
564
|
+
function compareOfflineCommands$1(left, right) {
|
|
565
|
+
return left.createdAt - right.createdAt || (left.commandId < right.commandId ? -1 : left.commandId > right.commandId ? 1 : 0);
|
|
566
|
+
}
|
|
567
|
+
/** WebはIonic StorageのIndexedDB driverを利用する。 */
|
|
568
|
+
class IonicOfflineRepository {
|
|
569
|
+
#storage = inject(KitStorageService);
|
|
570
|
+
#options = inject(OFFLINE_KIT_OPTIONS);
|
|
571
|
+
#initialization = null;
|
|
572
|
+
#writes = Promise.resolve();
|
|
573
|
+
initialize() {
|
|
574
|
+
if (!this.#initialization) {
|
|
575
|
+
this.#initialization = this.#migrate().catch((error) => {
|
|
576
|
+
this.#initialization = null;
|
|
577
|
+
throw error;
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
return this.#initialization;
|
|
581
|
+
}
|
|
582
|
+
async getLastUserId() {
|
|
583
|
+
await this.initialize();
|
|
584
|
+
return (await this.#metadata()).lastUserId;
|
|
585
|
+
}
|
|
586
|
+
async setLastUserId(userId) {
|
|
587
|
+
await this.initialize();
|
|
588
|
+
await this.#storage.set(METADATA_KEY, { ...(await this.#metadata()), lastUserId: userId });
|
|
589
|
+
}
|
|
590
|
+
async getSessionManifest(userId) {
|
|
591
|
+
await this.initialize();
|
|
592
|
+
await this.#writes;
|
|
593
|
+
const manifests = await this.#readRecord(SESSION_MANIFESTS_KEY);
|
|
594
|
+
return manifests[String(userId)] ?? null;
|
|
595
|
+
}
|
|
596
|
+
async putSessionManifest(userId, value) {
|
|
597
|
+
await this.initialize();
|
|
598
|
+
await this.#mutateRecord(SESSION_MANIFESTS_KEY, (manifests) => {
|
|
599
|
+
manifests[String(userId)] = value;
|
|
600
|
+
return manifests;
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
async getReplicaRow(scope, sourceKey, localId) {
|
|
604
|
+
await this.initialize();
|
|
605
|
+
await this.#writes;
|
|
606
|
+
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
607
|
+
const rows = await this.#readRecord(ROWS_KEY);
|
|
608
|
+
const row = rows[this.#rowKey(scope, sourceKey, localId)];
|
|
609
|
+
return row ? this.#rowForScope(row, schema, scope) : null;
|
|
610
|
+
}
|
|
611
|
+
async getReplicaRows(scope, sourceKey) {
|
|
612
|
+
await this.initialize();
|
|
613
|
+
await this.#writes;
|
|
614
|
+
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
615
|
+
const rows = await this.#readRecord(ROWS_KEY);
|
|
616
|
+
return Object.values(rows)
|
|
617
|
+
.filter((row) => {
|
|
618
|
+
if (row.sourceKey !== sourceKey || row.userId !== scope.userId)
|
|
619
|
+
return false;
|
|
620
|
+
return schema.scope === 'group' ? row.groupId === scope.groupId : true;
|
|
621
|
+
})
|
|
622
|
+
.map((row) => this.#rowForScope(row, schema, scope))
|
|
623
|
+
.sort((left, right) => left.localId.localeCompare(right.localId));
|
|
624
|
+
}
|
|
625
|
+
async getReplicaRowByServerId(scope, sourceKey, serverId) {
|
|
626
|
+
await this.initialize();
|
|
627
|
+
await this.#writes;
|
|
628
|
+
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
629
|
+
if (!this.#schemaHasServerId(schema))
|
|
630
|
+
return null;
|
|
631
|
+
const rows = await this.#readRecord(ROWS_KEY);
|
|
632
|
+
const row = Object.values(rows).find((row) => {
|
|
633
|
+
if (row.sourceKey !== sourceKey || row.userId !== scope.userId || row.serverId !== serverId)
|
|
634
|
+
return false;
|
|
635
|
+
return schema.scope === 'group' ? row.groupId === scope.groupId : true;
|
|
636
|
+
});
|
|
637
|
+
return row ? this.#rowForScope(row, schema, scope) : null;
|
|
638
|
+
}
|
|
639
|
+
async getReplicaCursor(scope) {
|
|
640
|
+
await this.initialize();
|
|
641
|
+
await this.#writes;
|
|
642
|
+
const cursors = await this.#readRecord(CURSORS_KEY);
|
|
643
|
+
const cursor = cursors[this.#cursorKey(scope)];
|
|
644
|
+
return cursor === undefined ? null : { ...scope, cursor };
|
|
645
|
+
}
|
|
646
|
+
async getCommands(scope) {
|
|
647
|
+
await this.initialize();
|
|
648
|
+
await this.#writes;
|
|
649
|
+
const commands = await this.#readRecord(OUTBOX_KEY);
|
|
650
|
+
return Object.values(commands)
|
|
651
|
+
.filter((command) => command.userId === scope.userId && command.groupId === scope.groupId)
|
|
652
|
+
.sort(compareOfflineCommands$1);
|
|
653
|
+
}
|
|
654
|
+
async getCommandsForUser(userId) {
|
|
655
|
+
await this.initialize();
|
|
656
|
+
await this.#writes;
|
|
657
|
+
const commands = await this.#readRecord(OUTBOX_KEY);
|
|
658
|
+
return Object.values(commands)
|
|
659
|
+
.filter((command) => command.userId === userId)
|
|
660
|
+
.sort(compareOfflineCommands$1);
|
|
661
|
+
}
|
|
662
|
+
async putCommand(command) {
|
|
663
|
+
await this.initialize();
|
|
664
|
+
await this.#assertReplicaSchemaLocked();
|
|
665
|
+
await this.#mutateRecord(OUTBOX_KEY, (commands) => {
|
|
666
|
+
commands[command.commandId] = command;
|
|
667
|
+
return commands;
|
|
668
|
+
});
|
|
669
|
+
}
|
|
670
|
+
replaceCommand(command) {
|
|
671
|
+
return this.putCommand(command);
|
|
672
|
+
}
|
|
673
|
+
async removeCommand(commandId) {
|
|
674
|
+
await this.initialize();
|
|
675
|
+
await this.#mutateRecord(OUTBOX_KEY, (commands) => {
|
|
676
|
+
delete commands[commandId];
|
|
677
|
+
return commands;
|
|
678
|
+
});
|
|
679
|
+
}
|
|
680
|
+
async clearUser(userId) {
|
|
681
|
+
await this.initialize();
|
|
682
|
+
await Promise.all([
|
|
683
|
+
this.#mutateRecord(SESSION_MANIFESTS_KEY, (manifests) => {
|
|
684
|
+
delete manifests[String(userId)];
|
|
685
|
+
return manifests;
|
|
686
|
+
}),
|
|
687
|
+
this.#filterRecord(ROWS_KEY, (value) => value.userId !== userId),
|
|
688
|
+
this.#filterRecord(OUTBOX_KEY, (value) => value.userId !== userId),
|
|
689
|
+
this.#filterRecord(CURSORS_KEY, (_value, key) => !key.startsWith(`${userId}:`)),
|
|
690
|
+
]);
|
|
691
|
+
const metadata = await this.#metadata();
|
|
692
|
+
if (metadata.lastUserId === userId) {
|
|
693
|
+
await this.#storage.set(METADATA_KEY, { ...metadata, lastUserId: null });
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
async clearGroup(scope) {
|
|
697
|
+
await this.initialize();
|
|
698
|
+
const belongsToGroup = (value) => value.userId === scope.userId && value.groupId === scope.groupId;
|
|
699
|
+
await Promise.all([
|
|
700
|
+
this.#filterRecord(ROWS_KEY, (value) => {
|
|
701
|
+
const schema = this.#resolveReplicaEntitySchema(value.sourceKey);
|
|
702
|
+
return schema.scope === 'user' || !belongsToGroup(value);
|
|
703
|
+
}),
|
|
704
|
+
this.#filterRecord(OUTBOX_KEY, (value) => !belongsToGroup(value)),
|
|
705
|
+
this.#filterRecord(CURSORS_KEY, (_value, key) => key !== this.#cursorKey(scope)),
|
|
706
|
+
]);
|
|
707
|
+
}
|
|
708
|
+
async transactReplica(transaction) {
|
|
709
|
+
await this.initialize();
|
|
710
|
+
const write = this.#writes.then(() => this.#applyReplicaTransaction(transaction, true));
|
|
711
|
+
this.#writes = write.catch(() => undefined);
|
|
712
|
+
return write;
|
|
713
|
+
}
|
|
714
|
+
async #migrate() {
|
|
715
|
+
const metadata = await this.#storage.get(METADATA_KEY);
|
|
716
|
+
if (metadata?.schemaVersion !== undefined && metadata.schemaVersion !== OFFLINE_SCHEMA_VERSION) {
|
|
717
|
+
await Promise.all([
|
|
718
|
+
this.#storage.remove(SESSION_MANIFESTS_KEY),
|
|
719
|
+
this.#storage.remove(ROWS_KEY),
|
|
720
|
+
this.#storage.remove(CURSORS_KEY),
|
|
721
|
+
this.#storage.remove(LEGACY_ENTITIES_KEY),
|
|
722
|
+
this.#storage.remove(LEGACY_QUERIES_KEY),
|
|
723
|
+
this.#storage.remove(OUTBOX_KEY),
|
|
724
|
+
this.#storage.remove(REPLICA_SCHEMA_MIGRATION_KEY),
|
|
725
|
+
]);
|
|
726
|
+
await this.#storage.set(METADATA_KEY, {
|
|
727
|
+
schemaVersion: OFFLINE_SCHEMA_VERSION,
|
|
728
|
+
lastUserId: metadata.lastUserId ?? null,
|
|
729
|
+
replicaSchemaVersion: null,
|
|
730
|
+
replicaSchemaHash: null,
|
|
731
|
+
});
|
|
732
|
+
await this.#storage.remove(REPLICA_TRANSACTION_KEY);
|
|
733
|
+
await this.#initializeReplicaSchema(null, null);
|
|
734
|
+
return;
|
|
735
|
+
}
|
|
736
|
+
const interruptedSchemaMigration = await this.#storage.get(REPLICA_SCHEMA_MIGRATION_KEY);
|
|
737
|
+
if (interruptedSchemaMigration) {
|
|
738
|
+
await this.#recoverReplicaSchemaMigration(interruptedSchemaMigration);
|
|
739
|
+
}
|
|
740
|
+
const currentMetadata = await this.#metadata();
|
|
741
|
+
await this.#initializeReplicaSchema(currentMetadata.replicaSchemaVersion, currentMetadata.replicaSchemaHash);
|
|
742
|
+
const interrupted = await this.#storage.get(REPLICA_TRANSACTION_KEY);
|
|
743
|
+
if (interrupted)
|
|
744
|
+
await this.#applyReplicaTransaction(interrupted, false);
|
|
745
|
+
}
|
|
746
|
+
async #initializeReplicaSchema(storedVersion, storedHash) {
|
|
747
|
+
const bundle = this.#options.replicaSchema;
|
|
748
|
+
const targetVersion = bundle.version;
|
|
749
|
+
const targetHash = await sha256OfflineReplicaSchema(bundle);
|
|
750
|
+
if (storedVersion === null) {
|
|
751
|
+
const metadata = await this.#metadata();
|
|
752
|
+
await this.#storage.set(METADATA_KEY, {
|
|
753
|
+
...metadata,
|
|
754
|
+
replicaSchemaVersion: targetVersion,
|
|
755
|
+
replicaSchemaHash: targetHash,
|
|
756
|
+
});
|
|
757
|
+
return;
|
|
758
|
+
}
|
|
759
|
+
if (storedVersion === targetVersion && storedHash === targetHash) {
|
|
760
|
+
return;
|
|
761
|
+
}
|
|
762
|
+
if (storedVersion === targetVersion) {
|
|
763
|
+
throw new Error(`Offline replica schema hash mismatch at version ${targetVersion}. Reinstall the application or bump replicaSchema.version after intentional schema changes.`);
|
|
764
|
+
}
|
|
765
|
+
if (storedVersion > targetVersion) {
|
|
766
|
+
throw new Error(`Offline replica schema version ${storedVersion} is newer than application version ${targetVersion}. Upgrade the application before opening this database.`);
|
|
767
|
+
}
|
|
768
|
+
if (storedHash === null) {
|
|
769
|
+
throw new Error(`Offline replica schema metadata at version ${storedVersion} is missing its schema hash.`);
|
|
770
|
+
}
|
|
771
|
+
await this.#runReplicaSchemaMigration(storedVersion, storedHash, targetVersion, targetHash);
|
|
772
|
+
}
|
|
773
|
+
async #recoverReplicaSchemaMigration(journal) {
|
|
774
|
+
await this.#storage.set(ROWS_KEY, journal.originalRows);
|
|
775
|
+
const metadata = await this.#metadata();
|
|
776
|
+
await this.#storage.set(METADATA_KEY, {
|
|
777
|
+
...metadata,
|
|
778
|
+
replicaSchemaVersion: journal.fromVersion,
|
|
779
|
+
replicaSchemaHash: journal.fromHash,
|
|
780
|
+
});
|
|
781
|
+
await this.#storage.remove(REPLICA_SCHEMA_MIGRATION_KEY);
|
|
782
|
+
}
|
|
783
|
+
async #runReplicaSchemaMigration(fromVersion, fromHash, targetVersion, targetHash) {
|
|
784
|
+
const bundle = this.#options.replicaSchema;
|
|
785
|
+
for (let version = fromVersion; version < targetVersion; version++) {
|
|
786
|
+
if (!bundle.migrations.some((migration) => migration.fromVersion === version)) {
|
|
787
|
+
throw new Error(`Missing offline replica schema migration from version ${version} to ${version + 1}.`);
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
const write = this.#writes.then(async () => {
|
|
791
|
+
const rows = await this.#readRecord(ROWS_KEY);
|
|
792
|
+
const originalRows = structuredClone(rows);
|
|
793
|
+
await this.#storage.set(REPLICA_SCHEMA_MIGRATION_KEY, {
|
|
794
|
+
originalRows,
|
|
795
|
+
fromVersion,
|
|
796
|
+
fromHash,
|
|
797
|
+
targetVersion,
|
|
798
|
+
targetHash,
|
|
799
|
+
});
|
|
800
|
+
try {
|
|
801
|
+
const transformedRows = {};
|
|
802
|
+
for (const row of Object.values(rows)) {
|
|
803
|
+
let current = this.#toWebMigrationRow(row);
|
|
804
|
+
for (let version = fromVersion; version < targetVersion; version++) {
|
|
805
|
+
if (current === null)
|
|
806
|
+
break;
|
|
807
|
+
const migration = bundle.migrations.find((candidate) => candidate.fromVersion === version);
|
|
808
|
+
if (!migration) {
|
|
809
|
+
throw new Error(`Missing offline replica schema migration from version ${version} to ${version + 1}.`);
|
|
810
|
+
}
|
|
811
|
+
current = await migration.migrateWebRow(current);
|
|
812
|
+
}
|
|
813
|
+
if (current === null)
|
|
814
|
+
continue;
|
|
815
|
+
const entitySchema = bundle.entities.find((entity) => entity.sourceKey === current.sourceKey);
|
|
816
|
+
if (!entitySchema) {
|
|
817
|
+
throw new Error(`Unknown offline replica source key "${current.sourceKey}" after schema migration.`);
|
|
818
|
+
}
|
|
819
|
+
encodeOfflineReplicaValues(entitySchema, current.values);
|
|
820
|
+
if (current.confirmedValues !== null) {
|
|
821
|
+
encodeOfflineReplicaValues(entitySchema, current.confirmedValues);
|
|
822
|
+
}
|
|
823
|
+
const transformedRow = {
|
|
824
|
+
...row,
|
|
825
|
+
sourceKey: current.sourceKey,
|
|
826
|
+
values: projectOfflineReplicaValues(entitySchema, current.values),
|
|
827
|
+
confirmedValues: current.confirmedValues === null ? null : projectOfflineReplicaValues(entitySchema, current.confirmedValues),
|
|
828
|
+
};
|
|
829
|
+
const transformedKey = this.#rowKey(transformedRow, transformedRow.sourceKey, transformedRow.localId);
|
|
830
|
+
if (transformedRows[transformedKey]) {
|
|
831
|
+
throw new Error(`Replica schema migration produced duplicate row key "${transformedKey}".`);
|
|
832
|
+
}
|
|
833
|
+
transformedRows[transformedKey] = transformedRow;
|
|
834
|
+
}
|
|
835
|
+
const metadata = await this.#metadata();
|
|
836
|
+
await this.#storage.set(ROWS_KEY, transformedRows);
|
|
837
|
+
await this.#storage.set(METADATA_KEY, {
|
|
838
|
+
...metadata,
|
|
839
|
+
replicaSchemaVersion: targetVersion,
|
|
840
|
+
replicaSchemaHash: targetHash,
|
|
841
|
+
});
|
|
842
|
+
await this.#storage.remove(REPLICA_SCHEMA_MIGRATION_KEY);
|
|
843
|
+
}
|
|
844
|
+
catch (error) {
|
|
845
|
+
await this.#recoverReplicaSchemaMigration({
|
|
846
|
+
originalRows,
|
|
847
|
+
fromVersion,
|
|
848
|
+
fromHash,
|
|
849
|
+
targetVersion,
|
|
850
|
+
targetHash,
|
|
851
|
+
});
|
|
852
|
+
throw error;
|
|
853
|
+
}
|
|
854
|
+
});
|
|
855
|
+
this.#writes = write.catch(() => undefined);
|
|
856
|
+
return write;
|
|
857
|
+
}
|
|
858
|
+
#toWebMigrationRow(row) {
|
|
859
|
+
return {
|
|
860
|
+
sourceKey: row.sourceKey,
|
|
861
|
+
values: structuredClone(row.values),
|
|
862
|
+
confirmedValues: row.confirmedValues === null ? null : structuredClone(row.confirmedValues),
|
|
863
|
+
};
|
|
864
|
+
}
|
|
865
|
+
async #assertReplicaSchemaLocked() {
|
|
866
|
+
const bundle = this.#options.replicaSchema;
|
|
867
|
+
const metadata = await this.#metadata();
|
|
868
|
+
const targetHash = await sha256OfflineReplicaSchema(bundle);
|
|
869
|
+
if (metadata.replicaSchemaVersion === null) {
|
|
870
|
+
throw new Error('Offline replica schema metadata is not initialized.');
|
|
871
|
+
}
|
|
872
|
+
if (metadata.replicaSchemaVersion !== bundle.version) {
|
|
873
|
+
throw new Error(`Offline replica schema version ${metadata.replicaSchemaVersion} does not match application version ${bundle.version}.`);
|
|
874
|
+
}
|
|
875
|
+
if (metadata.replicaSchemaHash !== targetHash) {
|
|
876
|
+
throw new Error(`Offline replica schema hash mismatch at version ${bundle.version}. Reinstall the application or bump replicaSchema.version after intentional schema changes.`);
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
async #applyReplicaTransaction(transaction, journal) {
|
|
880
|
+
await this.#assertReplicaSchemaLocked();
|
|
881
|
+
for (const row of transaction.putRows ?? [])
|
|
882
|
+
this.#validateReplicaRow(row);
|
|
883
|
+
if (journal)
|
|
884
|
+
await this.#storage.set(REPLICA_TRANSACTION_KEY, transaction);
|
|
885
|
+
const [rows, commands, cursors] = await Promise.all([
|
|
886
|
+
this.#readRecord(ROWS_KEY),
|
|
887
|
+
this.#readRecord(OUTBOX_KEY),
|
|
888
|
+
this.#readRecord(CURSORS_KEY),
|
|
889
|
+
]);
|
|
890
|
+
for (const row of transaction.putRows ?? []) {
|
|
891
|
+
const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
|
|
892
|
+
rows[this.#rowKey(row, row.sourceKey, row.localId)] = {
|
|
893
|
+
...row,
|
|
894
|
+
groupId: schema.scope === 'user' ? 0 : row.groupId,
|
|
895
|
+
values: projectOfflineReplicaValues(schema, row.values),
|
|
896
|
+
confirmedValues: row.confirmedValues === null ? null : projectOfflineReplicaValues(schema, row.confirmedValues),
|
|
897
|
+
};
|
|
898
|
+
}
|
|
899
|
+
for (const row of transaction.removeRows ?? []) {
|
|
900
|
+
delete rows[this.#rowKey(row, row.sourceKey, row.localId)];
|
|
901
|
+
}
|
|
902
|
+
for (const command of transaction.putCommands ?? [])
|
|
903
|
+
commands[command.commandId] = command;
|
|
904
|
+
for (const commandId of transaction.removeCommandIds ?? [])
|
|
905
|
+
delete commands[commandId];
|
|
906
|
+
for (const cursor of transaction.putCursors ?? []) {
|
|
907
|
+
cursors[this.#cursorKey(cursor)] = cursor.cursor;
|
|
908
|
+
}
|
|
909
|
+
await Promise.all([
|
|
910
|
+
this.#storage.set(ROWS_KEY, rows),
|
|
911
|
+
this.#storage.set(OUTBOX_KEY, commands),
|
|
912
|
+
this.#storage.set(CURSORS_KEY, cursors),
|
|
913
|
+
]);
|
|
914
|
+
await this.#storage.remove(REPLICA_TRANSACTION_KEY);
|
|
915
|
+
}
|
|
916
|
+
async #metadata() {
|
|
917
|
+
const metadata = await this.#storage.get(METADATA_KEY);
|
|
918
|
+
return {
|
|
919
|
+
schemaVersion: metadata?.schemaVersion ?? OFFLINE_SCHEMA_VERSION,
|
|
920
|
+
lastUserId: metadata?.lastUserId ?? null,
|
|
921
|
+
replicaSchemaVersion: metadata?.replicaSchemaVersion ?? null,
|
|
922
|
+
replicaSchemaHash: metadata?.replicaSchemaHash ?? null,
|
|
923
|
+
};
|
|
924
|
+
}
|
|
925
|
+
async #readRecord(key) {
|
|
926
|
+
return (await this.#storage.get(key)) ?? {};
|
|
927
|
+
}
|
|
928
|
+
async #filterRecord(key, predicate) {
|
|
929
|
+
await this.#mutateRecord(key, (record) => Object.fromEntries(Object.entries(record).filter(([recordKey, value]) => predicate(value, recordKey))));
|
|
930
|
+
}
|
|
931
|
+
#mutateRecord(key, mutate) {
|
|
932
|
+
const write = this.#writes.then(async () => {
|
|
933
|
+
const record = await this.#readRecord(key);
|
|
934
|
+
await this.#storage.set(key, mutate(record));
|
|
935
|
+
});
|
|
936
|
+
this.#writes = write.catch(() => undefined);
|
|
937
|
+
return write;
|
|
938
|
+
}
|
|
939
|
+
#rowKey(scope, sourceKey, localId) {
|
|
940
|
+
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
941
|
+
const partition = schema.scope === 'user' ? 'user' : String(scope.groupId);
|
|
942
|
+
return `${scope.userId}:${partition}:${sourceKey}:${localId}`;
|
|
943
|
+
}
|
|
944
|
+
#rowForScope(row, schema, scope) {
|
|
945
|
+
return schema.scope === 'user' ? { ...row, groupId: scope.groupId } : row;
|
|
946
|
+
}
|
|
947
|
+
#cursorKey(scope) {
|
|
948
|
+
return `${scope.userId}:${scope.groupId}`;
|
|
949
|
+
}
|
|
950
|
+
#schemaHasServerId(schema) {
|
|
951
|
+
return schema.fields.some((field) => field.policy === 'serverId');
|
|
952
|
+
}
|
|
953
|
+
#validateReplicaRow(row) {
|
|
954
|
+
const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
|
|
955
|
+
encodeOfflineReplicaValues(schema, row.values);
|
|
956
|
+
if (row.confirmedValues !== null)
|
|
957
|
+
encodeOfflineReplicaValues(schema, row.confirmedValues);
|
|
958
|
+
}
|
|
959
|
+
#resolveReplicaEntitySchema(sourceKey) {
|
|
960
|
+
const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);
|
|
961
|
+
if (!schema)
|
|
962
|
+
throw new Error(`Unknown offline replica source key "${sourceKey}".`);
|
|
963
|
+
return schema;
|
|
964
|
+
}
|
|
965
|
+
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: IonicOfflineRepository, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
966
|
+
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: IonicOfflineRepository, providedIn: 'root' }); }
|
|
967
|
+
}
|
|
968
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: IonicOfflineRepository, decorators: [{
|
|
969
|
+
type: Injectable,
|
|
970
|
+
args: [{ providedIn: 'root' }]
|
|
971
|
+
}] });
|
|
972
|
+
|
|
973
|
+
/** Pulls authoritative server deltas into one durable local replica partition. */
|
|
974
|
+
class OfflineReplicaPullService {
|
|
975
|
+
#repository = inject(OFFLINE_REPOSITORY);
|
|
976
|
+
#options = inject(OFFLINE_KIT_OPTIONS);
|
|
977
|
+
#puller = inject(OFFLINE_REPLICA_PULLER);
|
|
978
|
+
#hooks = inject(OFFLINE_COMMAND_HOOKS);
|
|
979
|
+
#executor = inject(OFFLINE_COMMAND_EXECUTOR);
|
|
980
|
+
#schemaHash = null;
|
|
981
|
+
async pull(scope) {
|
|
982
|
+
const schemaHash = await (this.#schemaHash ??= sha256OfflineReplicaSchema(this.#options.replicaSchema));
|
|
983
|
+
let cursor = (await this.#repository.getReplicaCursor(scope))?.cursor ?? '';
|
|
984
|
+
for (;;) {
|
|
985
|
+
const page = await this.#puller.pull({
|
|
986
|
+
scope,
|
|
987
|
+
cursor,
|
|
988
|
+
schemaVersion: this.#options.replicaSchema.version,
|
|
989
|
+
schemaHash,
|
|
990
|
+
});
|
|
991
|
+
this.#assertPullPage(page);
|
|
992
|
+
this.#assertHandshake(page.schemaVersion, page.schemaHash, schemaHash);
|
|
993
|
+
if (page.hasMore && page.nextCursor === cursor) {
|
|
994
|
+
throw new Error(`Offline replica pull cursor did not advance for scope ${scope.userId}:${scope.groupId}.`);
|
|
995
|
+
}
|
|
996
|
+
const scopeCommands = await this.#repository.getCommands(scope);
|
|
997
|
+
const userCommands = this.#repository.getCommandsForUser ? await this.#repository.getCommandsForUser(scope.userId) : scopeCommands;
|
|
998
|
+
const changes = this.#collapseChanges(page.changes);
|
|
999
|
+
const putRows = [];
|
|
1000
|
+
const removeRows = [];
|
|
1001
|
+
const putCommands = new Map();
|
|
1002
|
+
const removeCommandIds = new Set();
|
|
1003
|
+
for (const change of changes) {
|
|
1004
|
+
const schema = this.#entitySchema(change.sourceKey);
|
|
1005
|
+
const commands = schema.scope === 'user' ? userCommands : scopeCommands;
|
|
1006
|
+
const acknowledged = (change.acknowledgedCommandIds ?? [])
|
|
1007
|
+
.map((commandId) => {
|
|
1008
|
+
const command = commands.find((candidate) => candidate.commandId === commandId);
|
|
1009
|
+
if (!command)
|
|
1010
|
+
return null;
|
|
1011
|
+
if (this.#hooks.entityType(command) !== change.sourceKey) {
|
|
1012
|
+
throw new Error(`Acknowledged command "${commandId}" does not target "${change.sourceKey}".`);
|
|
1013
|
+
}
|
|
1014
|
+
return command;
|
|
1015
|
+
})
|
|
1016
|
+
.filter((command) => command !== null);
|
|
1017
|
+
const acknowledgedLocalIds = new Set(acknowledged.map((command) => command.aggregateLocalId));
|
|
1018
|
+
if (acknowledgedLocalIds.size > 1) {
|
|
1019
|
+
throw new Error(`Acknowledged commands for "${change.sourceKey}" target multiple local rows.`);
|
|
1020
|
+
}
|
|
1021
|
+
const acknowledgedCommand = acknowledged[0];
|
|
1022
|
+
const acknowledgedScope = acknowledgedCommand
|
|
1023
|
+
? { userId: acknowledgedCommand.userId, groupId: acknowledgedCommand.groupId }
|
|
1024
|
+
: scope;
|
|
1025
|
+
const acknowledgedRow = acknowledgedCommand
|
|
1026
|
+
? await this.#repository.getReplicaRow(acknowledgedScope, change.sourceKey, acknowledgedCommand.aggregateLocalId)
|
|
1027
|
+
: null;
|
|
1028
|
+
if (acknowledgedCommand && !acknowledgedRow) {
|
|
1029
|
+
throw new Error(`Acknowledged command "${acknowledgedCommand.commandId}" has no local replica row.`);
|
|
1030
|
+
}
|
|
1031
|
+
const serverRow = await this.#repository.getReplicaRowByServerId(scope, change.sourceKey, change.serverId);
|
|
1032
|
+
if (acknowledgedRow && serverRow && acknowledgedRow.localId !== serverRow.localId) {
|
|
1033
|
+
throw new Error(`Server id ${change.serverId} is already mapped to another local replica row.`);
|
|
1034
|
+
}
|
|
1035
|
+
const existing = acknowledgedRow ?? serverRow;
|
|
1036
|
+
const related = existing
|
|
1037
|
+
? commands.filter((command) => this.#hooks.entityType(command) === change.sourceKey && command.aggregateLocalId === existing.localId)
|
|
1038
|
+
: [];
|
|
1039
|
+
const hasPending = related.length > 0;
|
|
1040
|
+
if (acknowledgedCommand) {
|
|
1041
|
+
this.#applyAcknowledgement(change, existing, related, putRows, removeRows, putCommands, removeCommandIds);
|
|
1042
|
+
continue;
|
|
1043
|
+
}
|
|
1044
|
+
if (change.deleted) {
|
|
1045
|
+
if (!existing)
|
|
1046
|
+
continue;
|
|
1047
|
+
if (!hasPending) {
|
|
1048
|
+
removeRows.push(existing);
|
|
1049
|
+
continue;
|
|
1050
|
+
}
|
|
1051
|
+
putRows.push({ ...existing, serverRevision: change.serverRevision, syncState: 'conflict', fetchedAt: Date.now() });
|
|
1052
|
+
for (const command of related) {
|
|
1053
|
+
putCommands.set(command.commandId, { ...command, state: 'conflict', retryAt: null, lastErrorCode: 'remote_deleted' });
|
|
1054
|
+
}
|
|
1055
|
+
continue;
|
|
1056
|
+
}
|
|
1057
|
+
const confirmedValues = this.#validatedValues(schema, change);
|
|
1058
|
+
if (!existing) {
|
|
1059
|
+
putRows.push({
|
|
1060
|
+
...scope,
|
|
1061
|
+
sourceKey: change.sourceKey,
|
|
1062
|
+
localId: crypto.randomUUID(),
|
|
1063
|
+
serverId: change.serverId,
|
|
1064
|
+
values: confirmedValues,
|
|
1065
|
+
confirmedValues,
|
|
1066
|
+
serverRevision: change.serverRevision,
|
|
1067
|
+
fetchedAt: Date.now(),
|
|
1068
|
+
syncState: 'confirmed',
|
|
1069
|
+
});
|
|
1070
|
+
continue;
|
|
1071
|
+
}
|
|
1072
|
+
const conflicted = related.some((command) => command.baseRevision !== change.serverRevision);
|
|
1073
|
+
putRows.push({
|
|
1074
|
+
...existing,
|
|
1075
|
+
values: hasPending ? existing.values : confirmedValues,
|
|
1076
|
+
confirmedValues,
|
|
1077
|
+
serverRevision: change.serverRevision,
|
|
1078
|
+
fetchedAt: Date.now(),
|
|
1079
|
+
syncState: conflicted ? 'conflict' : hasPending ? 'pending' : 'confirmed',
|
|
1080
|
+
});
|
|
1081
|
+
if (conflicted) {
|
|
1082
|
+
for (const command of related) {
|
|
1083
|
+
putCommands.set(command.commandId, {
|
|
1084
|
+
...command,
|
|
1085
|
+
state: 'conflict',
|
|
1086
|
+
retryAt: null,
|
|
1087
|
+
lastErrorCode: 'remote_revision',
|
|
1088
|
+
});
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
await this.#repository.transactReplica({
|
|
1093
|
+
putRows,
|
|
1094
|
+
removeRows,
|
|
1095
|
+
putCommands: [...putCommands.values()],
|
|
1096
|
+
removeCommandIds: [...removeCommandIds],
|
|
1097
|
+
putCursors: [{ ...scope, cursor: page.nextCursor }],
|
|
1098
|
+
});
|
|
1099
|
+
cursor = page.nextCursor;
|
|
1100
|
+
if (!page.hasMore)
|
|
1101
|
+
return;
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
#assertPullPage(page) {
|
|
1105
|
+
if (typeof page.nextCursor !== 'string') {
|
|
1106
|
+
throw new Error('Offline replica pull page nextCursor must be a string.');
|
|
1107
|
+
}
|
|
1108
|
+
if (typeof page.hasMore !== 'boolean') {
|
|
1109
|
+
throw new Error('Offline replica pull page hasMore must be a boolean.');
|
|
1110
|
+
}
|
|
1111
|
+
if (!Array.isArray(page.changes)) {
|
|
1112
|
+
throw new Error('Offline replica pull page changes must be an array.');
|
|
1113
|
+
}
|
|
1114
|
+
for (const [index, change] of page.changes.entries()) {
|
|
1115
|
+
this.#assertPullChange(change, index);
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
#assertPullChange(change, index) {
|
|
1119
|
+
const label = `Offline replica pull page changes[${index}]`;
|
|
1120
|
+
if (!isPlainObject(change)) {
|
|
1121
|
+
throw new Error(`${label} must be a plain object.`);
|
|
1122
|
+
}
|
|
1123
|
+
if (typeof change['sourceKey'] !== 'string') {
|
|
1124
|
+
throw new Error(`${label}.sourceKey must be a string.`);
|
|
1125
|
+
}
|
|
1126
|
+
if (typeof change['deleted'] !== 'boolean') {
|
|
1127
|
+
throw new Error(`${label}.deleted must be a boolean.`);
|
|
1128
|
+
}
|
|
1129
|
+
const serverId = change['serverId'];
|
|
1130
|
+
if (typeof serverId !== 'number' || !Number.isFinite(serverId) || !Number.isSafeInteger(serverId) || serverId <= 0) {
|
|
1131
|
+
throw new Error(`${label}.serverId must be a positive integer.`);
|
|
1132
|
+
}
|
|
1133
|
+
const revision = change['serverRevision'];
|
|
1134
|
+
if (typeof revision !== 'string' && (typeof revision !== 'number' || !Number.isFinite(revision))) {
|
|
1135
|
+
throw new Error(`${label}.serverRevision must be a string or number.`);
|
|
1136
|
+
}
|
|
1137
|
+
const acknowledgedCommandIds = change['acknowledgedCommandIds'];
|
|
1138
|
+
if ((acknowledgedCommandIds !== undefined && !Array.isArray(acknowledgedCommandIds)) ||
|
|
1139
|
+
(Array.isArray(acknowledgedCommandIds) &&
|
|
1140
|
+
acknowledgedCommandIds.some((commandId) => typeof commandId !== 'string' || commandId.length === 0))) {
|
|
1141
|
+
throw new Error(`${label}.acknowledgedCommandIds must be an array of non-empty strings.`);
|
|
1142
|
+
}
|
|
1143
|
+
if (change['deleted']) {
|
|
1144
|
+
if (change['values'] !== null) {
|
|
1145
|
+
throw new Error(`${label} with deleted=true must have null values.`);
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
#assertHandshake(version, hash, expectedHash) {
|
|
1150
|
+
if (version !== this.#options.replicaSchema.version || hash !== expectedHash) {
|
|
1151
|
+
throw new Error(`Offline replica schema mismatch: client=${this.#options.replicaSchema.version}/${expectedHash}, server=${version}/${hash}.`);
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
#entitySchema(sourceKey) {
|
|
1155
|
+
const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);
|
|
1156
|
+
if (!schema)
|
|
1157
|
+
throw new Error(`Unknown offline replica source key "${sourceKey}".`);
|
|
1158
|
+
return schema;
|
|
1159
|
+
}
|
|
1160
|
+
#validatedValues(schema, change) {
|
|
1161
|
+
if (change.values === null) {
|
|
1162
|
+
throw new Error(`Offline replica change "${change.sourceKey}"/${change.serverId} is missing values.`);
|
|
1163
|
+
}
|
|
1164
|
+
return projectOfflineReplicaValues(schema, change.values);
|
|
1165
|
+
}
|
|
1166
|
+
#collapseChanges(changes) {
|
|
1167
|
+
const collapsed = new Map();
|
|
1168
|
+
for (const change of changes) {
|
|
1169
|
+
const key = `${change.sourceKey}:${change.serverId}`;
|
|
1170
|
+
const previous = collapsed.get(key);
|
|
1171
|
+
collapsed.set(key, {
|
|
1172
|
+
...change,
|
|
1173
|
+
acknowledgedCommandIds: [...new Set([...(previous?.acknowledgedCommandIds ?? []), ...(change.acknowledgedCommandIds ?? [])])],
|
|
1174
|
+
});
|
|
1175
|
+
}
|
|
1176
|
+
return [...collapsed.values()];
|
|
1177
|
+
}
|
|
1178
|
+
#applyAcknowledgement(change, row, related, putRows, removeRows, putCommands, removeCommandIds) {
|
|
1179
|
+
const acknowledgedIds = new Set(change.acknowledgedCommandIds ?? []);
|
|
1180
|
+
const lastAcknowledgedIndex = related.reduce((last, command, index) => (acknowledgedIds.has(command.commandId) ? index : last), -1);
|
|
1181
|
+
if (lastAcknowledgedIndex < 0) {
|
|
1182
|
+
throw new Error(`Replica acknowledgement does not match the local aggregate outbox.`);
|
|
1183
|
+
}
|
|
1184
|
+
if (related.slice(0, lastAcknowledgedIndex + 1).some((command) => !acknowledgedIds.has(command.commandId))) {
|
|
1185
|
+
throw new Error(`Replica acknowledgement skipped an earlier aggregate command.`);
|
|
1186
|
+
}
|
|
1187
|
+
const following = related
|
|
1188
|
+
.slice(lastAcknowledgedIndex + 1)
|
|
1189
|
+
.map((command) => this.#executor.withServerRevision(command, change.serverRevision));
|
|
1190
|
+
for (const command of following)
|
|
1191
|
+
putCommands.set(command.commandId, command);
|
|
1192
|
+
for (const command of related.slice(0, lastAcknowledgedIndex + 1)) {
|
|
1193
|
+
removeCommandIds.add(command.commandId);
|
|
1194
|
+
}
|
|
1195
|
+
if (change.deleted) {
|
|
1196
|
+
if (following.length > 0) {
|
|
1197
|
+
putRows.push({ ...row, serverRevision: change.serverRevision, syncState: 'conflict', fetchedAt: Date.now() });
|
|
1198
|
+
for (const command of following) {
|
|
1199
|
+
putCommands.set(command.commandId, { ...command, state: 'conflict', lastErrorCode: 'remote_deleted' });
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
else {
|
|
1203
|
+
removeRows.push(row);
|
|
1204
|
+
}
|
|
1205
|
+
return;
|
|
1206
|
+
}
|
|
1207
|
+
const schema = this.#entitySchema(change.sourceKey);
|
|
1208
|
+
const confirmedValues = this.#validatedValues(schema, change);
|
|
1209
|
+
this.#assertServerIdAssignment(row.serverId, change.serverId);
|
|
1210
|
+
putRows.push({
|
|
1211
|
+
...row,
|
|
1212
|
+
serverId: change.serverId,
|
|
1213
|
+
values: following.length > 0 ? following.at(-1).optimisticValue : confirmedValues,
|
|
1214
|
+
confirmedValues,
|
|
1215
|
+
serverRevision: change.serverRevision,
|
|
1216
|
+
fetchedAt: Date.now(),
|
|
1217
|
+
syncState: following.length > 0 ? 'pending' : 'confirmed',
|
|
1218
|
+
});
|
|
1219
|
+
}
|
|
1220
|
+
#assertServerIdAssignment(current, incoming) {
|
|
1221
|
+
if (current !== null && current !== incoming) {
|
|
1222
|
+
throw new Error(`Replica serverId is immutable: current=${current}, incoming=${incoming}.`);
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineReplicaPullService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
1226
|
+
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineReplicaPullService, providedIn: 'root' }); }
|
|
1227
|
+
}
|
|
1228
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineReplicaPullService, decorators: [{
|
|
1229
|
+
type: Injectable,
|
|
1230
|
+
args: [{ providedIn: 'root' }]
|
|
1231
|
+
}] });
|
|
1232
|
+
function isPlainObject(value) {
|
|
1233
|
+
if (value === null || typeof value !== 'object') {
|
|
1234
|
+
return false;
|
|
1235
|
+
}
|
|
1236
|
+
const prototype = Object.getPrototypeOf(value);
|
|
1237
|
+
return prototype === Object.prototype || prototype === null;
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
/** transport不能(status=0)だけをlocal replica fallback対象にし、HTTPエラーは隠さない。 */
|
|
1241
|
+
function isOfflineFallbackError(error) {
|
|
1242
|
+
return typeof error === 'object' && error !== null && error.status === 0;
|
|
1243
|
+
}
|
|
1244
|
+
/** Combines operating-system connectivity with observed API reachability. */
|
|
1245
|
+
class OfflineNetworkService {
|
|
1246
|
+
constructor() {
|
|
1247
|
+
this.#osConnected = signal(null, ...(ngDevMode ? [{ debugName: "#osConnected" }] : /* istanbul ignore next */ []));
|
|
1248
|
+
this.#apiReachable = signal(null, ...(ngDevMode ? [{ debugName: "#apiReachable" }] : /* istanbul ignore next */ []));
|
|
1249
|
+
this.#listeners = [];
|
|
1250
|
+
this.#initialized = false;
|
|
1251
|
+
this.state = computed(() => {
|
|
1252
|
+
if (this.#osConnected() === false || this.#apiReachable() === false)
|
|
1253
|
+
return 'offline';
|
|
1254
|
+
if (this.#osConnected() === true && this.#apiReachable() === true)
|
|
1255
|
+
return 'online';
|
|
1256
|
+
return 'unverified';
|
|
1257
|
+
}, ...(ngDevMode ? [{ debugName: "state" }] : /* istanbul ignore next */ []));
|
|
1258
|
+
this.connected = computed(() => this.state() !== 'offline', ...(ngDevMode ? [{ debugName: "connected" }] : /* istanbul ignore next */ []));
|
|
1259
|
+
}
|
|
1260
|
+
#osConnected;
|
|
1261
|
+
#apiReachable;
|
|
1262
|
+
#listeners;
|
|
1263
|
+
#initialized;
|
|
1264
|
+
async initialize() {
|
|
1265
|
+
if (this.#initialized)
|
|
1266
|
+
return;
|
|
1267
|
+
this.#initialized = true;
|
|
1268
|
+
this.#osConnected.set((await Network.getStatus()).connected);
|
|
1269
|
+
this.#listeners.push(await Network.addListener('networkStatusChange', ({ connected }) => {
|
|
1270
|
+
this.#osConnected.set(connected);
|
|
1271
|
+
this.#apiReachable.set(connected ? null : false);
|
|
1272
|
+
}), await App.addListener('appStateChange', ({ isActive }) => {
|
|
1273
|
+
if (isActive)
|
|
1274
|
+
void this.#refreshOsStatus();
|
|
1275
|
+
}));
|
|
1276
|
+
}
|
|
1277
|
+
markApiSuccess() {
|
|
1278
|
+
this.#apiReachable.set(true);
|
|
1279
|
+
}
|
|
1280
|
+
markApiFailure() {
|
|
1281
|
+
this.#apiReachable.set(false);
|
|
1282
|
+
}
|
|
1283
|
+
async #refreshOsStatus() {
|
|
1284
|
+
this.#osConnected.set((await Network.getStatus()).connected);
|
|
1285
|
+
}
|
|
1286
|
+
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineNetworkService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
1287
|
+
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineNetworkService, providedIn: 'root' }); }
|
|
1288
|
+
}
|
|
1289
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineNetworkService, decorators: [{
|
|
1290
|
+
type: Injectable,
|
|
1291
|
+
args: [{ providedIn: 'root' }]
|
|
1292
|
+
}] });
|
|
1293
|
+
|
|
1294
|
+
/** Owns activation and cleanup of the authenticated local-replica boundary. */
|
|
1295
|
+
class OfflineSessionService {
|
|
1296
|
+
constructor() {
|
|
1297
|
+
this.#repository = inject(OFFLINE_REPOSITORY);
|
|
1298
|
+
this.#activeManifest = signal(null, ...(ngDevMode ? [{ debugName: "#activeManifest" }] : /* istanbul ignore next */ []));
|
|
1299
|
+
this.#initialized = false;
|
|
1300
|
+
this.#activatedThisRun = false;
|
|
1301
|
+
this.activeManifest = this.#activeManifest.asReadonly();
|
|
1302
|
+
}
|
|
1303
|
+
#repository;
|
|
1304
|
+
#activeManifest;
|
|
1305
|
+
#initialized;
|
|
1306
|
+
#activatedThisRun;
|
|
1307
|
+
async initialize() {
|
|
1308
|
+
if (this.#initialized)
|
|
1309
|
+
return;
|
|
1310
|
+
await this.#repository.initialize();
|
|
1311
|
+
const userId = await this.#repository.getLastUserId();
|
|
1312
|
+
if (userId !== null) {
|
|
1313
|
+
const manifest = await this.#repository.getSessionManifest(userId);
|
|
1314
|
+
this.#activeManifest.set(manifest ?? { userId, scopeIds: [], authSubject: null, updatedAt: 0 });
|
|
1315
|
+
}
|
|
1316
|
+
this.#initialized = true;
|
|
1317
|
+
}
|
|
1318
|
+
async activateSession(userId, scopeIds, authSubject) {
|
|
1319
|
+
await this.initialize();
|
|
1320
|
+
const normalizedScopeIds = [...new Set(scopeIds)].filter((id) => id !== 0).sort((a, b) => a - b);
|
|
1321
|
+
const previousUserId = await this.#repository.getLastUserId();
|
|
1322
|
+
let previous = previousUserId === userId
|
|
1323
|
+
? ((await this.#repository.getSessionManifest(userId)) ?? null)
|
|
1324
|
+
: null;
|
|
1325
|
+
// A changed provider subject is a different person even when the product reuses its numeric id.
|
|
1326
|
+
// This deliberately also clears legacy null -> known subject and known subject -> null transitions.
|
|
1327
|
+
if (previousUserId !== null && (previousUserId !== userId || previous?.authSubject !== authSubject)) {
|
|
1328
|
+
await this.#repository.clearUser(previousUserId);
|
|
1329
|
+
previous = null;
|
|
1330
|
+
}
|
|
1331
|
+
const active = new Set(normalizedScopeIds);
|
|
1332
|
+
await Promise.all((previous?.scopeIds ?? [])
|
|
1333
|
+
.filter((groupId) => !active.has(groupId))
|
|
1334
|
+
.map((groupId) => this.#repository.clearGroup({ userId, groupId })));
|
|
1335
|
+
const manifest = {
|
|
1336
|
+
userId,
|
|
1337
|
+
scopeIds: normalizedScopeIds,
|
|
1338
|
+
authSubject,
|
|
1339
|
+
updatedAt: Date.now(),
|
|
1340
|
+
};
|
|
1341
|
+
await this.#repository.setLastUserId(userId);
|
|
1342
|
+
await this.#repository.putSessionManifest(userId, manifest);
|
|
1343
|
+
this.#activeManifest.set(manifest);
|
|
1344
|
+
this.#activatedThisRun = true;
|
|
1345
|
+
}
|
|
1346
|
+
async clearActiveSession() {
|
|
1347
|
+
await this.initialize();
|
|
1348
|
+
const userId = await this.#repository.getLastUserId();
|
|
1349
|
+
if (userId !== null)
|
|
1350
|
+
await this.#repository.clearUser(userId);
|
|
1351
|
+
this.#activeManifest.set(null);
|
|
1352
|
+
this.#activatedThisRun = false;
|
|
1353
|
+
}
|
|
1354
|
+
async getSession() {
|
|
1355
|
+
await this.initialize();
|
|
1356
|
+
if (!this.#activatedThisRun)
|
|
1357
|
+
return null;
|
|
1358
|
+
const manifest = this.#activeManifest();
|
|
1359
|
+
return manifest
|
|
1360
|
+
? { userId: manifest.userId, scopes: manifest.scopeIds.map((groupId) => ({ userId: manifest.userId, groupId })) }
|
|
1361
|
+
: null;
|
|
1362
|
+
}
|
|
1363
|
+
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineSessionService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
1364
|
+
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineSessionService, providedIn: 'root' }); }
|
|
1365
|
+
}
|
|
1366
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineSessionService, decorators: [{
|
|
1367
|
+
type: Injectable,
|
|
1368
|
+
args: [{ providedIn: 'root' }]
|
|
1369
|
+
}] });
|
|
1370
|
+
|
|
1371
|
+
/** Raised before persistence when an outbox payload is not losslessly JSON serializable. */
|
|
1372
|
+
class OfflinePayloadValidationError extends Error {
|
|
1373
|
+
constructor(message = 'Offline command payload must contain only JSON values') {
|
|
1374
|
+
super(message);
|
|
1375
|
+
this.name = 'OfflinePayloadValidationError';
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
const MAX_PARALLEL_AGGREGATES = 3;
|
|
1379
|
+
const MAX_BACKOFF_MS = 60 * 60 * 1000;
|
|
1380
|
+
/** Maintains the optimistic local replica and synchronizes its durable outbox. */
|
|
1381
|
+
class OfflineSyncService {
|
|
1382
|
+
#network;
|
|
1383
|
+
#repository;
|
|
1384
|
+
#executor;
|
|
1385
|
+
#context;
|
|
1386
|
+
#hooks;
|
|
1387
|
+
#options;
|
|
1388
|
+
#pull;
|
|
1389
|
+
#errorHandler;
|
|
1390
|
+
#commands;
|
|
1391
|
+
#knownScopes;
|
|
1392
|
+
#activeUserId;
|
|
1393
|
+
#flushPromise;
|
|
1394
|
+
#generation;
|
|
1395
|
+
#sendingTransitions;
|
|
1396
|
+
#enqueueTail;
|
|
1397
|
+
#retryTimer;
|
|
1398
|
+
#initialized;
|
|
1399
|
+
#lastCommandCreatedAt;
|
|
1400
|
+
constructor() {
|
|
1401
|
+
this.#network = inject(OfflineNetworkService);
|
|
1402
|
+
this.#repository = inject(OFFLINE_REPOSITORY);
|
|
1403
|
+
this.#executor = inject(OFFLINE_COMMAND_EXECUTOR);
|
|
1404
|
+
this.#context = inject(OFFLINE_SYNC_CONTEXT);
|
|
1405
|
+
this.#hooks = inject(OFFLINE_COMMAND_HOOKS);
|
|
1406
|
+
this.#options = inject(OFFLINE_KIT_OPTIONS);
|
|
1407
|
+
this.#pull = inject(OfflineReplicaPullService);
|
|
1408
|
+
this.#errorHandler = inject(ErrorHandler);
|
|
1409
|
+
this.#commands = signal([], ...(ngDevMode ? [{ debugName: "#commands" }] : /* istanbul ignore next */ []));
|
|
1410
|
+
this.#knownScopes = new Map();
|
|
1411
|
+
this.#activeUserId = null;
|
|
1412
|
+
this.#flushPromise = null;
|
|
1413
|
+
this.#generation = 0;
|
|
1414
|
+
this.#sendingTransitions = new Set();
|
|
1415
|
+
this.#enqueueTail = Promise.resolve();
|
|
1416
|
+
this.#retryTimer = null;
|
|
1417
|
+
this.#initialized = false;
|
|
1418
|
+
this.#lastCommandCreatedAt = 0;
|
|
1419
|
+
this.pendingCommands = this.#commands.asReadonly();
|
|
1420
|
+
this.pendingCount = computed(() => this.pendingCommands().length, ...(ngDevMode ? [{ debugName: "pendingCount" }] : /* istanbul ignore next */ []));
|
|
1421
|
+
this.conflicts = computed(() => this.#commands().filter((command) => command.state === 'conflict'), ...(ngDevMode ? [{ debugName: "conflicts" }] : /* istanbul ignore next */ []));
|
|
1422
|
+
this.syncState = computed(() => {
|
|
1423
|
+
const commands = this.#commands();
|
|
1424
|
+
if (commands.some((command) => ['blocked_auth', 'rejected', 'conflict'].includes(command.state)))
|
|
1425
|
+
return 'attention';
|
|
1426
|
+
if (commands.some((command) => command.state === 'sending'))
|
|
1427
|
+
return 'syncing';
|
|
1428
|
+
return commands.length > 0 ? 'pending' : 'idle';
|
|
1429
|
+
}, ...(ngDevMode ? [{ debugName: "syncState" }] : /* istanbul ignore next */ []));
|
|
1430
|
+
effect(() => {
|
|
1431
|
+
if (this.#initialized && this.#network.connected())
|
|
1432
|
+
this.#flushInBackground();
|
|
1433
|
+
});
|
|
1434
|
+
}
|
|
1435
|
+
async initialize() {
|
|
1436
|
+
if (this.#initialized)
|
|
1437
|
+
return;
|
|
1438
|
+
await this.#repository.initialize();
|
|
1439
|
+
await this.#discoverScopes();
|
|
1440
|
+
const commands = await this.#readKnownCommands();
|
|
1441
|
+
await Promise.all(commands
|
|
1442
|
+
.filter((command) => command.state === 'sending')
|
|
1443
|
+
.map((command) => this.#repository.putCommand({ ...command, state: 'pending' })));
|
|
1444
|
+
this.#initialized = true;
|
|
1445
|
+
await this.#refreshState();
|
|
1446
|
+
if (this.#network.connected())
|
|
1447
|
+
this.#flushInBackground();
|
|
1448
|
+
}
|
|
1449
|
+
noteScope(scope) {
|
|
1450
|
+
this.#knownScopes.set(this.#scopeKey(scope), scope);
|
|
1451
|
+
}
|
|
1452
|
+
async reloadPendingCommands() {
|
|
1453
|
+
await this.initialize();
|
|
1454
|
+
await this.#refreshState();
|
|
1455
|
+
}
|
|
1456
|
+
async refreshSession() {
|
|
1457
|
+
await this.initialize();
|
|
1458
|
+
await this.#discoverScopes();
|
|
1459
|
+
await this.#restoreInterruptedCommands();
|
|
1460
|
+
await this.#refreshState();
|
|
1461
|
+
if (this.#network.connected())
|
|
1462
|
+
this.#flushInBackground();
|
|
1463
|
+
}
|
|
1464
|
+
async resetSession() {
|
|
1465
|
+
this.#invalidateFlush();
|
|
1466
|
+
await this.#waitForSendingTransitions();
|
|
1467
|
+
await this.#restoreInterruptedCommands();
|
|
1468
|
+
this.#activeUserId = null;
|
|
1469
|
+
this.#knownScopes.clear();
|
|
1470
|
+
this.#commands.set([]);
|
|
1471
|
+
this.#scheduleRetry(null);
|
|
1472
|
+
}
|
|
1473
|
+
enqueue(request, options = {}) {
|
|
1474
|
+
const enqueue = this.#enqueueTail.then(() => this.#enqueue(request, options));
|
|
1475
|
+
this.#enqueueTail = enqueue.then(() => undefined, () => undefined);
|
|
1476
|
+
return enqueue;
|
|
1477
|
+
}
|
|
1478
|
+
async #enqueue(request, options) {
|
|
1479
|
+
await this.initialize();
|
|
1480
|
+
const session = await this.#context.getSession();
|
|
1481
|
+
if (!session)
|
|
1482
|
+
throw new Error('Cannot enqueue an offline command without an authenticated user');
|
|
1483
|
+
const userId = session.userId;
|
|
1484
|
+
this.#setActiveUser(userId);
|
|
1485
|
+
const scope = { userId, groupId: request.groupId };
|
|
1486
|
+
this.noteScope(scope);
|
|
1487
|
+
const aggregateLocalId = request.aggregateLocalId;
|
|
1488
|
+
const normalized = await this.#normalizeEnqueueRequest(scope, request);
|
|
1489
|
+
const optimisticValue = request.optimisticValue;
|
|
1490
|
+
const commandId = crypto.randomUUID();
|
|
1491
|
+
const command = {
|
|
1492
|
+
...scope,
|
|
1493
|
+
commandId,
|
|
1494
|
+
aggregateType: request.aggregateType,
|
|
1495
|
+
aggregateLocalId,
|
|
1496
|
+
operation: request.operation,
|
|
1497
|
+
payload: normalized.payload,
|
|
1498
|
+
optimisticValue,
|
|
1499
|
+
payloadHash: await this.#payloadHash(normalized.payload),
|
|
1500
|
+
baseRevision: normalized.baseRevision,
|
|
1501
|
+
state: 'pending',
|
|
1502
|
+
attempts: 0,
|
|
1503
|
+
retryAt: null,
|
|
1504
|
+
createdAt: await this.#nextCommandCreatedAt(userId),
|
|
1505
|
+
lastErrorCode: null,
|
|
1506
|
+
};
|
|
1507
|
+
const entityType = this.#entityType(command);
|
|
1508
|
+
const existing = await this.#repository.getReplicaRow(scope, entityType, aggregateLocalId);
|
|
1509
|
+
const optimisticRow = {
|
|
1510
|
+
...scope,
|
|
1511
|
+
sourceKey: entityType,
|
|
1512
|
+
localId: aggregateLocalId,
|
|
1513
|
+
serverId: existing?.serverId ?? null,
|
|
1514
|
+
values: optimisticValue,
|
|
1515
|
+
confirmedValues: existing?.confirmedValues ?? existing?.values ?? null,
|
|
1516
|
+
serverRevision: existing?.serverRevision ?? normalized.baseRevision,
|
|
1517
|
+
fetchedAt: Date.now(),
|
|
1518
|
+
syncState: 'pending',
|
|
1519
|
+
};
|
|
1520
|
+
await this.#repository.transactReplica({ putRows: [optimisticRow], putCommands: [command] });
|
|
1521
|
+
await this.#refreshState();
|
|
1522
|
+
if (options.flush !== false && this.#network.connected())
|
|
1523
|
+
this.#flushInBackground();
|
|
1524
|
+
return commandId;
|
|
1525
|
+
}
|
|
1526
|
+
async discard(commandId, options = {}) {
|
|
1527
|
+
await this.initialize();
|
|
1528
|
+
const command = (await this.#readKnownCommands()).find((item) => item.commandId === commandId);
|
|
1529
|
+
if (!command)
|
|
1530
|
+
return;
|
|
1531
|
+
this.#invalidateFlush();
|
|
1532
|
+
await this.#waitForSendingTransitions();
|
|
1533
|
+
await this.#discardCommands([command]);
|
|
1534
|
+
await this.#hooks.onCommandRemoved?.(command);
|
|
1535
|
+
await this.#restoreInterruptedCommands();
|
|
1536
|
+
await this.#refreshState();
|
|
1537
|
+
if (options.flush !== false && this.#network.connected())
|
|
1538
|
+
this.#flushInBackground();
|
|
1539
|
+
}
|
|
1540
|
+
async discardAllPending() {
|
|
1541
|
+
await this.initialize();
|
|
1542
|
+
this.#invalidateFlush();
|
|
1543
|
+
await this.#waitForSendingTransitions();
|
|
1544
|
+
const commands = await this.#readKnownCommands();
|
|
1545
|
+
await this.#discardCommands(commands);
|
|
1546
|
+
await Promise.all(commands.map((command) => this.#hooks.onCommandRemoved?.(command)));
|
|
1547
|
+
await this.#refreshState();
|
|
1548
|
+
}
|
|
1549
|
+
#flushInBackground() {
|
|
1550
|
+
void this.flush().catch((error) => this.#errorHandler.handleError(error));
|
|
1551
|
+
}
|
|
1552
|
+
flush() {
|
|
1553
|
+
if (this.#flushPromise)
|
|
1554
|
+
return this.#flushPromise;
|
|
1555
|
+
const generation = this.#generation;
|
|
1556
|
+
const promise = this.#runFlush(generation).finally(() => {
|
|
1557
|
+
if (this.#flushPromise === promise)
|
|
1558
|
+
this.#flushPromise = null;
|
|
1559
|
+
});
|
|
1560
|
+
this.#flushPromise = promise;
|
|
1561
|
+
return promise;
|
|
1562
|
+
}
|
|
1563
|
+
async #runFlush(generation) {
|
|
1564
|
+
if (!this.#isCurrent(generation))
|
|
1565
|
+
return;
|
|
1566
|
+
if (!this.#network.connected()) {
|
|
1567
|
+
await this.#refreshState(generation);
|
|
1568
|
+
return;
|
|
1569
|
+
}
|
|
1570
|
+
if (!(await this.#discoverScopes(generation)))
|
|
1571
|
+
return;
|
|
1572
|
+
for (const scope of this.#knownScopes.values()) {
|
|
1573
|
+
if (!this.#isCurrent(generation) || !this.#network.connected())
|
|
1574
|
+
return;
|
|
1575
|
+
await this.#pull.pull(scope);
|
|
1576
|
+
}
|
|
1577
|
+
while (this.#network.connected() && this.#isCurrent(generation)) {
|
|
1578
|
+
const groups = this.#eligibleAggregateGroups(await this.#readKnownCommands());
|
|
1579
|
+
if (!this.#isCurrent(generation))
|
|
1580
|
+
return;
|
|
1581
|
+
if (groups.length === 0)
|
|
1582
|
+
break;
|
|
1583
|
+
let cursor = 0;
|
|
1584
|
+
const workers = Array.from({ length: Math.min(MAX_PARALLEL_AGGREGATES, groups.length) }, async () => {
|
|
1585
|
+
while (cursor < groups.length) {
|
|
1586
|
+
const group = groups[cursor++];
|
|
1587
|
+
if (group && this.#isCurrent(generation))
|
|
1588
|
+
await this.#sendAggregate(group, generation);
|
|
1589
|
+
}
|
|
1590
|
+
});
|
|
1591
|
+
await Promise.all(workers);
|
|
1592
|
+
}
|
|
1593
|
+
await this.#refreshState(generation);
|
|
1594
|
+
}
|
|
1595
|
+
#eligibleAggregateGroups(commands) {
|
|
1596
|
+
const now = Date.now();
|
|
1597
|
+
const groups = new Map();
|
|
1598
|
+
for (const command of commands) {
|
|
1599
|
+
const key = this.#aggregateKey(command);
|
|
1600
|
+
const group = groups.get(key) ?? [];
|
|
1601
|
+
group.push(command);
|
|
1602
|
+
groups.set(key, group);
|
|
1603
|
+
}
|
|
1604
|
+
return [...groups.values()].filter((group) => {
|
|
1605
|
+
const head = group[0];
|
|
1606
|
+
return head?.state === 'pending' || (head?.state === 'retry_wait' && (head.retryAt ?? 0) <= now);
|
|
1607
|
+
});
|
|
1608
|
+
}
|
|
1609
|
+
async #sendAggregate(commands, generation) {
|
|
1610
|
+
for (let index = 0; index < commands.length; index++) {
|
|
1611
|
+
if (!this.#isCurrent(generation))
|
|
1612
|
+
return;
|
|
1613
|
+
const command = commands[index];
|
|
1614
|
+
if (command.state === 'retry_wait' && (command.retryAt ?? 0) > Date.now())
|
|
1615
|
+
break;
|
|
1616
|
+
if (!['pending', 'retry_wait'].includes(command.state))
|
|
1617
|
+
break;
|
|
1618
|
+
const sending = {
|
|
1619
|
+
...command,
|
|
1620
|
+
state: 'sending',
|
|
1621
|
+
attempts: command.attempts + 1,
|
|
1622
|
+
retryAt: null,
|
|
1623
|
+
lastErrorCode: null,
|
|
1624
|
+
};
|
|
1625
|
+
await this.#putSendingCommand(sending);
|
|
1626
|
+
if (!this.#isCurrent(generation))
|
|
1627
|
+
return;
|
|
1628
|
+
await this.#refreshState(generation);
|
|
1629
|
+
if (!this.#isCurrent(generation))
|
|
1630
|
+
return;
|
|
1631
|
+
const row = await this.#rowForCommand(sending);
|
|
1632
|
+
if (!row)
|
|
1633
|
+
throw new Error(`Offline replica row not found: ${sending.aggregateType}/${sending.aggregateLocalId}`);
|
|
1634
|
+
let result;
|
|
1635
|
+
try {
|
|
1636
|
+
result = await this.#executor.execute(sending, { localId: row.localId, serverId: row.serverId });
|
|
1637
|
+
}
|
|
1638
|
+
catch (error) {
|
|
1639
|
+
if (!this.#isCurrent(generation))
|
|
1640
|
+
return;
|
|
1641
|
+
if (!this.#isClassifiableTransportError(error))
|
|
1642
|
+
throw error;
|
|
1643
|
+
const failed = this.#failedCommand(sending, error);
|
|
1644
|
+
await this.#repository.transactReplica({
|
|
1645
|
+
putRows: [{ ...row, syncState: this.#replicaState(failed.state) }],
|
|
1646
|
+
putCommands: [failed],
|
|
1647
|
+
});
|
|
1648
|
+
if (failed.state === 'retry_wait')
|
|
1649
|
+
this.#scheduleRetry(failed.retryAt);
|
|
1650
|
+
break;
|
|
1651
|
+
}
|
|
1652
|
+
if (!this.#isCurrent(generation))
|
|
1653
|
+
return;
|
|
1654
|
+
await this.#completeCommand(commands, index, sending, result, generation);
|
|
1655
|
+
}
|
|
1656
|
+
}
|
|
1657
|
+
async #normalizeEnqueueRequest(scope, request) {
|
|
1658
|
+
let baseRevision = request.baseRevision ?? null;
|
|
1659
|
+
let payload = request.payload;
|
|
1660
|
+
const aggregateLocalId = request.aggregateLocalId;
|
|
1661
|
+
const row = await this.#repository.getReplicaRow(scope, this.#entityType(request), aggregateLocalId);
|
|
1662
|
+
if (row?.serverRevision != null && row.serverRevision !== baseRevision) {
|
|
1663
|
+
const rebased = this.#executor.withServerRevision({ ...scope, ...request, aggregateLocalId, payload, baseRevision }, row.serverRevision);
|
|
1664
|
+
baseRevision = row.serverRevision;
|
|
1665
|
+
payload = rebased.payload;
|
|
1666
|
+
}
|
|
1667
|
+
return { payload, baseRevision };
|
|
1668
|
+
}
|
|
1669
|
+
async #completeCommand(commands, index, command, result, generation) {
|
|
1670
|
+
const revision = result.serverRevision;
|
|
1671
|
+
const following = commands.slice(index + 1);
|
|
1672
|
+
const rebased = revision === undefined ? following : following.map((item) => this.#executor.withServerRevision(item, revision));
|
|
1673
|
+
for (let offset = 0; offset < rebased.length; offset++)
|
|
1674
|
+
commands[index + 1 + offset] = rebased[offset];
|
|
1675
|
+
const current = await this.#rowForCommand(command);
|
|
1676
|
+
if (!this.#isCurrent(generation))
|
|
1677
|
+
return;
|
|
1678
|
+
if (!current) {
|
|
1679
|
+
throw new Error(`Offline replica row disappeared while completing command ${command.commandId}.`);
|
|
1680
|
+
}
|
|
1681
|
+
this.#assertServerRevision(result.serverRevision);
|
|
1682
|
+
const confirmedValues = result.confirmedValues ?? command.optimisticValue;
|
|
1683
|
+
const serverId = this.#resolvedServerId(current.serverId, result.serverId);
|
|
1684
|
+
const row = {
|
|
1685
|
+
...current,
|
|
1686
|
+
values: rebased.length > 0 ? rebased.at(-1).optimisticValue : confirmedValues,
|
|
1687
|
+
confirmedValues,
|
|
1688
|
+
serverId,
|
|
1689
|
+
serverRevision: revision ?? current.serverRevision,
|
|
1690
|
+
fetchedAt: Date.now(),
|
|
1691
|
+
syncState: rebased.length > 0 ? 'pending' : 'confirmed',
|
|
1692
|
+
};
|
|
1693
|
+
if (!this.#isCurrent(generation))
|
|
1694
|
+
return;
|
|
1695
|
+
await this.#repository.transactReplica({
|
|
1696
|
+
putRows: result.removeReplica ? undefined : [row],
|
|
1697
|
+
removeRows: result.removeReplica ? [current] : undefined,
|
|
1698
|
+
putCommands: rebased,
|
|
1699
|
+
removeCommandIds: [command.commandId],
|
|
1700
|
+
});
|
|
1701
|
+
}
|
|
1702
|
+
async #rowForCommand(command) {
|
|
1703
|
+
const scope = { userId: command.userId, groupId: command.groupId };
|
|
1704
|
+
const entityType = this.#entityType(command);
|
|
1705
|
+
return this.#repository.getReplicaRow(scope, entityType, command.aggregateLocalId);
|
|
1706
|
+
}
|
|
1707
|
+
#replicaState(state) {
|
|
1708
|
+
if (state === 'blocked_auth' || state === 'rejected' || state === 'conflict')
|
|
1709
|
+
return state;
|
|
1710
|
+
return 'pending';
|
|
1711
|
+
}
|
|
1712
|
+
#entityType(command) {
|
|
1713
|
+
return this.#hooks.entityType(command);
|
|
1714
|
+
}
|
|
1715
|
+
async #discardCommands(discarded) {
|
|
1716
|
+
const all = await this.#readKnownCommands();
|
|
1717
|
+
const discardedIds = new Set(discarded.map((command) => command.commandId));
|
|
1718
|
+
const affected = new Map();
|
|
1719
|
+
for (const command of discarded)
|
|
1720
|
+
affected.set(this.#aggregateKey(command), command);
|
|
1721
|
+
const putRows = [];
|
|
1722
|
+
const removeRows = [];
|
|
1723
|
+
for (const [key, command] of affected) {
|
|
1724
|
+
const row = await this.#rowForCommand(command);
|
|
1725
|
+
if (!row)
|
|
1726
|
+
continue;
|
|
1727
|
+
const remaining = all.filter((item) => !discardedIds.has(item.commandId) && this.#aggregateKey(item) === key);
|
|
1728
|
+
if (remaining.length === 0 && row.confirmedValues === null && row.serverId === null) {
|
|
1729
|
+
removeRows.push(row);
|
|
1730
|
+
}
|
|
1731
|
+
else {
|
|
1732
|
+
putRows.push({
|
|
1733
|
+
...row,
|
|
1734
|
+
values: remaining.length > 0 ? remaining.at(-1).optimisticValue : row.confirmedValues,
|
|
1735
|
+
syncState: remaining.length > 0 ? 'pending' : 'confirmed',
|
|
1736
|
+
});
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
await this.#repository.transactReplica({
|
|
1740
|
+
putRows,
|
|
1741
|
+
removeRows,
|
|
1742
|
+
removeCommandIds: [...discardedIds],
|
|
1743
|
+
});
|
|
1744
|
+
}
|
|
1745
|
+
#aggregateKey(command) {
|
|
1746
|
+
const sourceKey = this.#entityType(command);
|
|
1747
|
+
const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);
|
|
1748
|
+
if (!schema)
|
|
1749
|
+
throw new Error(`Unknown offline replica source key "${sourceKey}".`);
|
|
1750
|
+
const partition = schema.scope === 'user' ? 'user' : `group:${command.groupId}`;
|
|
1751
|
+
return `${command.userId}:${partition}:${sourceKey}:${command.aggregateLocalId}`;
|
|
1752
|
+
}
|
|
1753
|
+
#failedCommand(command, error) {
|
|
1754
|
+
const status = this.#errorStatus(error);
|
|
1755
|
+
if (status === 401 || status === 403)
|
|
1756
|
+
return { ...command, state: 'blocked_auth', lastErrorCode: String(status) };
|
|
1757
|
+
if (status === 409 || status === 412)
|
|
1758
|
+
return { ...command, state: 'conflict', lastErrorCode: String(status) };
|
|
1759
|
+
if (status >= 400 && status < 500 && status !== 429) {
|
|
1760
|
+
return { ...command, state: 'rejected', lastErrorCode: String(status) };
|
|
1761
|
+
}
|
|
1762
|
+
const retryAt = Date.now() + Math.min(MAX_BACKOFF_MS, 1000 * 2 ** Math.max(0, command.attempts - 1));
|
|
1763
|
+
return { ...command, state: 'retry_wait', retryAt, lastErrorCode: status > 0 ? String(status) : 'network' };
|
|
1764
|
+
}
|
|
1765
|
+
#errorStatus(error) {
|
|
1766
|
+
if (typeof error !== 'object' || error === null)
|
|
1767
|
+
return 0;
|
|
1768
|
+
const status = error.status;
|
|
1769
|
+
return typeof status === 'number' ? status : 0;
|
|
1770
|
+
}
|
|
1771
|
+
#isClassifiableTransportError(error) {
|
|
1772
|
+
if (typeof error !== 'object' || error === null)
|
|
1773
|
+
return false;
|
|
1774
|
+
const status = error.status;
|
|
1775
|
+
return typeof status === 'number' && Number.isInteger(status) && status >= 0;
|
|
1776
|
+
}
|
|
1777
|
+
#assertServerRevision(revision) {
|
|
1778
|
+
if (typeof revision === 'number' && !Number.isFinite(revision)) {
|
|
1779
|
+
throw new Error(`Offline command returned invalid serverRevision ${String(revision)}.`);
|
|
1780
|
+
}
|
|
1781
|
+
}
|
|
1782
|
+
#resolvedServerId(current, incoming) {
|
|
1783
|
+
if (incoming === undefined)
|
|
1784
|
+
return current;
|
|
1785
|
+
if (!Number.isSafeInteger(incoming) || incoming <= 0) {
|
|
1786
|
+
throw new Error(`Offline command returned invalid serverId ${String(incoming)}.`);
|
|
1787
|
+
}
|
|
1788
|
+
if (current !== null && current !== incoming) {
|
|
1789
|
+
throw new Error(`Offline replica serverId is immutable: current=${current}, incoming=${incoming}.`);
|
|
1790
|
+
}
|
|
1791
|
+
return incoming;
|
|
1792
|
+
}
|
|
1793
|
+
async #discoverScopes(generation = this.#generation) {
|
|
1794
|
+
const session = await this.#context.getSession();
|
|
1795
|
+
if (!this.#isCurrent(generation))
|
|
1796
|
+
return false;
|
|
1797
|
+
if (!session) {
|
|
1798
|
+
this.#activeUserId = null;
|
|
1799
|
+
this.#knownScopes.clear();
|
|
1800
|
+
return true;
|
|
1801
|
+
}
|
|
1802
|
+
this.#setActiveUser(session.userId);
|
|
1803
|
+
this.#knownScopes.clear();
|
|
1804
|
+
for (const scope of session.scopes)
|
|
1805
|
+
this.#knownScopes.set(this.#scopeKey(scope), scope);
|
|
1806
|
+
return true;
|
|
1807
|
+
}
|
|
1808
|
+
#setActiveUser(userId) {
|
|
1809
|
+
if (this.#activeUserId === userId)
|
|
1810
|
+
return;
|
|
1811
|
+
this.#knownScopes.clear();
|
|
1812
|
+
this.#activeUserId = userId;
|
|
1813
|
+
this.#lastCommandCreatedAt = 0;
|
|
1814
|
+
}
|
|
1815
|
+
async #readKnownCommands() {
|
|
1816
|
+
const commands = (await Promise.all([...this.#knownScopes.values()].map((scope) => this.#repository.getCommands(scope))))
|
|
1817
|
+
.flat()
|
|
1818
|
+
.sort(compareOfflineCommands);
|
|
1819
|
+
this.#rememberCreatedAt(commands);
|
|
1820
|
+
return commands;
|
|
1821
|
+
}
|
|
1822
|
+
async #nextCommandCreatedAt(userId) {
|
|
1823
|
+
const commands = this.#repository.getCommandsForUser
|
|
1824
|
+
? await this.#repository.getCommandsForUser(userId)
|
|
1825
|
+
: await this.#readKnownCommands();
|
|
1826
|
+
this.#rememberCreatedAt(commands);
|
|
1827
|
+
const createdAt = Math.max(Date.now(), this.#lastCommandCreatedAt + 1);
|
|
1828
|
+
this.#lastCommandCreatedAt = createdAt;
|
|
1829
|
+
return createdAt;
|
|
1830
|
+
}
|
|
1831
|
+
#rememberCreatedAt(commands) {
|
|
1832
|
+
for (const command of commands)
|
|
1833
|
+
this.#lastCommandCreatedAt = Math.max(this.#lastCommandCreatedAt, command.createdAt);
|
|
1834
|
+
}
|
|
1835
|
+
async #refreshState(generation = this.#generation) {
|
|
1836
|
+
const commands = await this.#readKnownCommands();
|
|
1837
|
+
if (!this.#isCurrent(generation))
|
|
1838
|
+
return;
|
|
1839
|
+
this.#commands.set(commands);
|
|
1840
|
+
const nextRetry = commands
|
|
1841
|
+
.filter((command) => command.state === 'retry_wait' && command.retryAt !== null)
|
|
1842
|
+
.reduce((earliest, command) => Math.min(earliest ?? command.retryAt, command.retryAt), null);
|
|
1843
|
+
this.#scheduleRetry(nextRetry);
|
|
1844
|
+
}
|
|
1845
|
+
#scheduleRetry(retryAt) {
|
|
1846
|
+
if (this.#retryTimer)
|
|
1847
|
+
clearTimeout(this.#retryTimer);
|
|
1848
|
+
this.#retryTimer = null;
|
|
1849
|
+
if (retryAt === null)
|
|
1850
|
+
return;
|
|
1851
|
+
this.#retryTimer = setTimeout(() => {
|
|
1852
|
+
this.#retryTimer = null;
|
|
1853
|
+
if (this.#network.connected())
|
|
1854
|
+
this.#flushInBackground();
|
|
1855
|
+
}, Math.max(0, retryAt - Date.now()));
|
|
1856
|
+
}
|
|
1857
|
+
#invalidateFlush() {
|
|
1858
|
+
this.#generation += 1;
|
|
1859
|
+
this.#flushPromise = null;
|
|
1860
|
+
this.#scheduleRetry(null);
|
|
1861
|
+
}
|
|
1862
|
+
#isCurrent(generation) {
|
|
1863
|
+
return generation === this.#generation;
|
|
1864
|
+
}
|
|
1865
|
+
async #restoreInterruptedCommands() {
|
|
1866
|
+
const commands = await this.#readKnownCommands();
|
|
1867
|
+
await Promise.all(commands
|
|
1868
|
+
.filter((command) => command.state === 'sending')
|
|
1869
|
+
.map((command) => this.#repository.putCommand({ ...command, state: 'pending' })));
|
|
1870
|
+
}
|
|
1871
|
+
#putSendingCommand(command) {
|
|
1872
|
+
const transition = this.#repository.putCommand(command);
|
|
1873
|
+
this.#sendingTransitions.add(transition);
|
|
1874
|
+
void transition.then(() => this.#sendingTransitions.delete(transition), () => this.#sendingTransitions.delete(transition));
|
|
1875
|
+
return transition;
|
|
1876
|
+
}
|
|
1877
|
+
async #waitForSendingTransitions() {
|
|
1878
|
+
await Promise.allSettled([...this.#sendingTransitions]);
|
|
1879
|
+
}
|
|
1880
|
+
async #payloadHash(payload) {
|
|
1881
|
+
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(this.#canonicalJson(payload)));
|
|
1882
|
+
return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('');
|
|
1883
|
+
}
|
|
1884
|
+
#canonicalJson(value) {
|
|
1885
|
+
if (Array.isArray(value))
|
|
1886
|
+
return `[${value.map((item) => this.#canonicalJson(item)).join(',')}]`;
|
|
1887
|
+
if (value !== null && typeof value === 'object') {
|
|
1888
|
+
if (Object.getPrototypeOf(value) !== Object.prototype) {
|
|
1889
|
+
throw new OfflinePayloadValidationError();
|
|
1890
|
+
}
|
|
1891
|
+
return `{${Object.entries(value)
|
|
1892
|
+
.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
|
|
1893
|
+
.map(([key, item]) => `${JSON.stringify(key)}:${this.#canonicalJson(item)}`)
|
|
1894
|
+
.join(',')}}`;
|
|
1895
|
+
}
|
|
1896
|
+
if (typeof value === 'number' && !Number.isFinite(value)) {
|
|
1897
|
+
throw new OfflinePayloadValidationError();
|
|
1898
|
+
}
|
|
1899
|
+
const serialized = JSON.stringify(value);
|
|
1900
|
+
if (typeof serialized !== 'string') {
|
|
1901
|
+
throw new OfflinePayloadValidationError();
|
|
1902
|
+
}
|
|
1903
|
+
return serialized;
|
|
1904
|
+
}
|
|
1905
|
+
#scopeKey(scope) {
|
|
1906
|
+
return `${scope.userId}:${scope.groupId}`;
|
|
1907
|
+
}
|
|
1908
|
+
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineSyncService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
1909
|
+
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineSyncService, providedIn: 'root' }); }
|
|
1910
|
+
}
|
|
1911
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineSyncService, decorators: [{
|
|
1912
|
+
type: Injectable,
|
|
1913
|
+
args: [{ providedIn: 'root' }]
|
|
1914
|
+
}], ctorParameters: () => [] });
|
|
1915
|
+
function compareOfflineCommands(left, right) {
|
|
1916
|
+
return left.createdAt - right.createdAt || (left.commandId < right.commandId ? -1 : left.commandId > right.commandId ? 1 : 0);
|
|
1917
|
+
}
|
|
1918
|
+
|
|
1919
|
+
/** Coordinates local persistence, session boundaries, network state, and outbox synchronization. */
|
|
1920
|
+
class OfflineCoordinatorService {
|
|
1921
|
+
constructor() {
|
|
1922
|
+
this.#repository = inject(OFFLINE_REPOSITORY);
|
|
1923
|
+
this.#network = inject(OfflineNetworkService);
|
|
1924
|
+
this.#sync = inject(OfflineSyncService);
|
|
1925
|
+
this.#session = inject(OfflineSessionService);
|
|
1926
|
+
this.networkState = this.#network.state;
|
|
1927
|
+
this.syncState = this.#sync.syncState;
|
|
1928
|
+
this.pendingCount = this.#sync.pendingCount;
|
|
1929
|
+
this.conflicts = this.#sync.conflicts;
|
|
1930
|
+
}
|
|
1931
|
+
#repository;
|
|
1932
|
+
#network;
|
|
1933
|
+
#sync;
|
|
1934
|
+
#session;
|
|
1935
|
+
async initialize() {
|
|
1936
|
+
await Promise.all([this.#repository.initialize(), this.#network.initialize()]);
|
|
1937
|
+
await this.#session.initialize();
|
|
1938
|
+
await this.#sync.initialize();
|
|
1939
|
+
}
|
|
1940
|
+
async activateSession(userId, scopeIds, authSubject) {
|
|
1941
|
+
await this.#sync.resetSession();
|
|
1942
|
+
await this.#session.activateSession(userId, scopeIds, authSubject);
|
|
1943
|
+
await this.#sync.refreshSession();
|
|
1944
|
+
}
|
|
1945
|
+
async clearActiveSession() {
|
|
1946
|
+
await this.#sync.resetSession();
|
|
1947
|
+
await this.#session.clearActiveSession();
|
|
1948
|
+
}
|
|
1949
|
+
async prepareLogout(action) {
|
|
1950
|
+
if (action === 'cancel')
|
|
1951
|
+
return false;
|
|
1952
|
+
if (action === 'discard') {
|
|
1953
|
+
await this.#sync.discardAllPending();
|
|
1954
|
+
return true;
|
|
1955
|
+
}
|
|
1956
|
+
await this.#sync.flush();
|
|
1957
|
+
return this.#sync.pendingCount() === 0;
|
|
1958
|
+
}
|
|
1959
|
+
flush() {
|
|
1960
|
+
return this.#sync.flush();
|
|
1961
|
+
}
|
|
1962
|
+
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineCoordinatorService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
1963
|
+
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineCoordinatorService, providedIn: 'root' }); }
|
|
1964
|
+
}
|
|
1965
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineCoordinatorService, decorators: [{
|
|
1966
|
+
type: Injectable,
|
|
1967
|
+
args: [{ providedIn: 'root' }]
|
|
1968
|
+
}] });
|
|
1969
|
+
|
|
1970
|
+
/** outbox再送時にoffline interceptorだけを迂回する。認証・retryは維持する。 */
|
|
1971
|
+
const OFFLINE_BYPASS = new HttpContextToken(() => false);
|
|
1972
|
+
/** Header attached to responses served from the local replica fallback. */
|
|
1973
|
+
const OFFLINE_RESPONSE_HEADER = 'X-Offline-Response';
|
|
1974
|
+
/** Multi-provider token containing product request policies. */
|
|
1975
|
+
const OFFLINE_REQUEST_POLICIES = new InjectionToken('OFFLINE_REQUEST_POLICIES', {
|
|
1976
|
+
factory: () => [],
|
|
1977
|
+
});
|
|
1978
|
+
/** Registers one product request policy with the offline interceptor. */
|
|
1979
|
+
function provideOfflineRequestPolicy(policy) {
|
|
1980
|
+
return [policy, { provide: OFFLINE_REQUEST_POLICIES, useExisting: policy, multi: true }];
|
|
1981
|
+
}
|
|
1982
|
+
/** Resolves the first product policy matching an HTTP request. */
|
|
1983
|
+
class OfflineRequestPolicyRegistry {
|
|
1984
|
+
#policies = inject(OFFLINE_REQUEST_POLICIES);
|
|
1985
|
+
resolve(request) {
|
|
1986
|
+
for (const policy of this.#policies) {
|
|
1987
|
+
const plan = policy.resolve(request);
|
|
1988
|
+
if (plan)
|
|
1989
|
+
return plan;
|
|
1990
|
+
}
|
|
1991
|
+
return null;
|
|
1992
|
+
}
|
|
1993
|
+
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineRequestPolicyRegistry, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
1994
|
+
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineRequestPolicyRegistry, providedIn: 'root' }); }
|
|
1995
|
+
}
|
|
1996
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineRequestPolicyRegistry, decorators: [{
|
|
1997
|
+
type: Injectable,
|
|
1998
|
+
args: [{ providedIn: 'root' }]
|
|
1999
|
+
}] });
|
|
2000
|
+
|
|
2001
|
+
/** DI token for the optional application-installed Capawesome SQLite plugin. */
|
|
2002
|
+
const CAPAWESOME_SQLITE = new InjectionToken('CAPAWESOME_SQLITE', {
|
|
2003
|
+
factory: () => null,
|
|
2004
|
+
});
|
|
2005
|
+
const SCHEMA = [
|
|
2006
|
+
`CREATE TABLE IF NOT EXISTS offline_metadata (
|
|
2007
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
2008
|
+
schema_version INTEGER NOT NULL,
|
|
2009
|
+
last_user_id INTEGER
|
|
2010
|
+
)`,
|
|
2011
|
+
`CREATE TABLE IF NOT EXISTS offline_session_manifests (
|
|
2012
|
+
user_id INTEGER PRIMARY KEY,
|
|
2013
|
+
value_json TEXT NOT NULL
|
|
2014
|
+
)`,
|
|
2015
|
+
`CREATE TABLE IF NOT EXISTS offline_sync_commands (
|
|
2016
|
+
command_id TEXT PRIMARY KEY,
|
|
2017
|
+
user_id INTEGER NOT NULL,
|
|
2018
|
+
group_id INTEGER NOT NULL,
|
|
2019
|
+
aggregate_type TEXT NOT NULL,
|
|
2020
|
+
aggregate_local_id TEXT NOT NULL,
|
|
2021
|
+
operation TEXT NOT NULL,
|
|
2022
|
+
payload_json TEXT NOT NULL,
|
|
2023
|
+
optimistic_value_json TEXT NOT NULL,
|
|
2024
|
+
payload_hash TEXT NOT NULL,
|
|
2025
|
+
base_revision_json TEXT,
|
|
2026
|
+
state TEXT NOT NULL,
|
|
2027
|
+
attempts INTEGER NOT NULL,
|
|
2028
|
+
retry_at INTEGER,
|
|
2029
|
+
created_at INTEGER NOT NULL,
|
|
2030
|
+
last_error_code TEXT
|
|
2031
|
+
)`,
|
|
2032
|
+
`CREATE INDEX IF NOT EXISTS offline_sync_commands_scope_created
|
|
2033
|
+
ON offline_sync_commands (user_id, group_id, created_at)`,
|
|
2034
|
+
`CREATE TABLE IF NOT EXISTS offline_replica_schema_metadata (
|
|
2035
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
2036
|
+
version INTEGER NOT NULL,
|
|
2037
|
+
schema_hash TEXT NOT NULL CHECK (length(schema_hash) = 64)
|
|
2038
|
+
)`,
|
|
2039
|
+
`CREATE TABLE IF NOT EXISTS offline_replica_cursors (
|
|
2040
|
+
user_id INTEGER NOT NULL,
|
|
2041
|
+
group_id INTEGER NOT NULL,
|
|
2042
|
+
cursor TEXT NOT NULL,
|
|
2043
|
+
PRIMARY KEY (user_id, group_id)
|
|
2044
|
+
)`,
|
|
2045
|
+
];
|
|
2046
|
+
/** Native iOS/Android uses the encrypted Capawesome SQLite plugin supplied by the application. */
|
|
2047
|
+
class SqliteOfflineRepository {
|
|
2048
|
+
#sqlite = inject(CAPAWESOME_SQLITE);
|
|
2049
|
+
#options = inject(OFFLINE_KIT_OPTIONS);
|
|
2050
|
+
#databaseId = null;
|
|
2051
|
+
#initialization = null;
|
|
2052
|
+
#writes = Promise.resolve();
|
|
2053
|
+
initialize() {
|
|
2054
|
+
this.#initialization ??= this.#open();
|
|
2055
|
+
return this.#initialization;
|
|
2056
|
+
}
|
|
2057
|
+
async getLastUserId() {
|
|
2058
|
+
const rows = await this.#query('SELECT last_user_id FROM offline_metadata WHERE id = 1');
|
|
2059
|
+
return this.#numberOrNull(rows[0]?.['last_user_id']);
|
|
2060
|
+
}
|
|
2061
|
+
async setLastUserId(userId) {
|
|
2062
|
+
await this.#write(`INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, ?)
|
|
2063
|
+
ON CONFLICT(id) DO UPDATE SET schema_version = excluded.schema_version, last_user_id = excluded.last_user_id`, [OFFLINE_SCHEMA_VERSION, userId]);
|
|
2064
|
+
}
|
|
2065
|
+
async getSessionManifest(userId) {
|
|
2066
|
+
const rows = await this.#query('SELECT value_json FROM offline_session_manifests WHERE user_id = ?', [userId]);
|
|
2067
|
+
const row = rows[0];
|
|
2068
|
+
return row ? this.#parse(row['value_json']) : null;
|
|
2069
|
+
}
|
|
2070
|
+
async putSessionManifest(userId, value) {
|
|
2071
|
+
await this.#write(`INSERT INTO offline_session_manifests (user_id, value_json) VALUES (?, ?)
|
|
2072
|
+
ON CONFLICT(user_id) DO UPDATE SET value_json = excluded.value_json`, [userId, JSON.stringify(value)]);
|
|
2073
|
+
}
|
|
2074
|
+
async getReplicaRow(scope, sourceKey, localId) {
|
|
2075
|
+
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
2076
|
+
const predicates = ['local_id = ?', '_offline_user_id = ?'];
|
|
2077
|
+
const values = [localId, scope.userId];
|
|
2078
|
+
if (schema.scope === 'group') {
|
|
2079
|
+
predicates.push('_offline_group_id = ?');
|
|
2080
|
+
values.push(scope.groupId);
|
|
2081
|
+
}
|
|
2082
|
+
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
|
|
2083
|
+
const row = rows[0];
|
|
2084
|
+
if (!row)
|
|
2085
|
+
return null;
|
|
2086
|
+
return this.#replicaRowFromSqliteRow(schema, scope, sourceKey, localId, row);
|
|
2087
|
+
}
|
|
2088
|
+
async getReplicaRows(scope, sourceKey) {
|
|
2089
|
+
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
2090
|
+
const predicates = ['_offline_user_id = ?'];
|
|
2091
|
+
const values = [scope.userId];
|
|
2092
|
+
if (schema.scope === 'group') {
|
|
2093
|
+
predicates.push('_offline_group_id = ?');
|
|
2094
|
+
values.push(scope.groupId);
|
|
2095
|
+
}
|
|
2096
|
+
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')} ORDER BY local_id ASC`, values);
|
|
2097
|
+
return rows.map((row) => this.#replicaRowFromSqliteRow(schema, scope, sourceKey, this.#string(row['local_id']), row));
|
|
2098
|
+
}
|
|
2099
|
+
async getReplicaRowByServerId(scope, sourceKey, serverId) {
|
|
2100
|
+
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
2101
|
+
if (!this.#schemaHasServerId(schema))
|
|
2102
|
+
return null;
|
|
2103
|
+
const predicates = ['server_id = ?', '_offline_user_id = ?'];
|
|
2104
|
+
const values = [serverId, scope.userId];
|
|
2105
|
+
if (schema.scope === 'group') {
|
|
2106
|
+
predicates.push('_offline_group_id = ?');
|
|
2107
|
+
values.push(scope.groupId);
|
|
2108
|
+
}
|
|
2109
|
+
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
|
|
2110
|
+
const row = rows[0];
|
|
2111
|
+
if (!row)
|
|
2112
|
+
return null;
|
|
2113
|
+
return this.#replicaRowFromSqliteRow(schema, scope, sourceKey, this.#string(row['local_id']), row);
|
|
2114
|
+
}
|
|
2115
|
+
async getReplicaCursor(scope) {
|
|
2116
|
+
const rows = await this.#query('SELECT cursor FROM offline_replica_cursors WHERE user_id = ? AND group_id = ?', [
|
|
2117
|
+
scope.userId,
|
|
2118
|
+
scope.groupId,
|
|
2119
|
+
]);
|
|
2120
|
+
const row = rows[0];
|
|
2121
|
+
if (!row)
|
|
2122
|
+
return null;
|
|
2123
|
+
return { ...scope, cursor: this.#string(row['cursor']) };
|
|
2124
|
+
}
|
|
2125
|
+
async getCommands(scope) {
|
|
2126
|
+
const rows = await this.#query('SELECT * FROM offline_sync_commands WHERE user_id = ? AND group_id = ? ORDER BY created_at ASC, command_id ASC', [scope.userId, scope.groupId]);
|
|
2127
|
+
return rows.map((row) => this.#command(row));
|
|
2128
|
+
}
|
|
2129
|
+
async getCommandsForUser(userId) {
|
|
2130
|
+
const rows = await this.#query('SELECT * FROM offline_sync_commands WHERE user_id = ? ORDER BY created_at ASC, command_id ASC', [
|
|
2131
|
+
userId,
|
|
2132
|
+
]);
|
|
2133
|
+
return rows.map((row) => this.#command(row));
|
|
2134
|
+
}
|
|
2135
|
+
async putCommand(command) {
|
|
2136
|
+
await this.#queueWrite((databaseId) => this.#putCommand(databaseId, command));
|
|
2137
|
+
}
|
|
2138
|
+
replaceCommand(command) {
|
|
2139
|
+
return this.putCommand(command);
|
|
2140
|
+
}
|
|
2141
|
+
async removeCommand(commandId) {
|
|
2142
|
+
await this.#write('DELETE FROM offline_sync_commands WHERE command_id = ?', [commandId]);
|
|
2143
|
+
}
|
|
2144
|
+
async clearUser(userId) {
|
|
2145
|
+
await this.#transaction(async (database) => {
|
|
2146
|
+
await this.#execute(database, 'DELETE FROM offline_session_manifests WHERE user_id = ?', [userId]);
|
|
2147
|
+
await this.#execute(database, 'DELETE FROM offline_sync_commands WHERE user_id = ?', [userId]);
|
|
2148
|
+
await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ?', [userId]);
|
|
2149
|
+
for (const entity of this.#options.replicaSchema.entities) {
|
|
2150
|
+
await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ?`, [userId]);
|
|
2151
|
+
}
|
|
2152
|
+
await this.#execute(database, 'UPDATE offline_metadata SET last_user_id = NULL WHERE id = 1 AND last_user_id = ?', [userId]);
|
|
2153
|
+
});
|
|
2154
|
+
}
|
|
2155
|
+
async clearGroup(scope) {
|
|
2156
|
+
await this.#transaction(async (database) => {
|
|
2157
|
+
const values = [scope.userId, scope.groupId];
|
|
2158
|
+
await this.#execute(database, 'DELETE FROM offline_sync_commands WHERE user_id = ? AND group_id = ?', values);
|
|
2159
|
+
await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ? AND group_id = ?', values);
|
|
2160
|
+
for (const entity of this.#options.replicaSchema.entities) {
|
|
2161
|
+
if (entity.scope !== 'group')
|
|
2162
|
+
continue;
|
|
2163
|
+
await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ? AND _offline_group_id = ?`, values);
|
|
2164
|
+
}
|
|
2165
|
+
});
|
|
2166
|
+
}
|
|
2167
|
+
async transactReplica(transaction) {
|
|
2168
|
+
await this.#transaction(async (databaseId) => {
|
|
2169
|
+
for (const row of transaction.putRows ?? [])
|
|
2170
|
+
await this.#putReplicaRow(databaseId, row);
|
|
2171
|
+
for (const row of transaction.removeRows ?? [])
|
|
2172
|
+
await this.#removeReplicaRow(databaseId, row);
|
|
2173
|
+
for (const command of transaction.putCommands ?? [])
|
|
2174
|
+
await this.#putCommand(databaseId, command);
|
|
2175
|
+
for (const commandId of transaction.removeCommandIds ?? []) {
|
|
2176
|
+
await this.#execute(databaseId, 'DELETE FROM offline_sync_commands WHERE command_id = ?', [commandId]);
|
|
2177
|
+
}
|
|
2178
|
+
for (const cursor of transaction.putCursors ?? [])
|
|
2179
|
+
await this.#putReplicaCursor(databaseId, cursor);
|
|
2180
|
+
});
|
|
2181
|
+
}
|
|
2182
|
+
async #open() {
|
|
2183
|
+
if (!this.#sqlite)
|
|
2184
|
+
throw new Error('Native offline storage requires the Capawesome SQLite plugin');
|
|
2185
|
+
const encryptionKey = await this.#options.encryptionKey?.();
|
|
2186
|
+
if (!encryptionKey)
|
|
2187
|
+
throw new Error('Native offline storage requires a non-empty encryption key');
|
|
2188
|
+
const { databaseId } = await this.#sqlite.open({
|
|
2189
|
+
path: `${this.#options.databaseName}.sqlite3`,
|
|
2190
|
+
encryptionKey,
|
|
2191
|
+
readOnly: false,
|
|
2192
|
+
});
|
|
2193
|
+
this.#databaseId = databaseId;
|
|
2194
|
+
for (const statement of SCHEMA)
|
|
2195
|
+
await this.#execute(databaseId, statement);
|
|
2196
|
+
let commandColumns = await this.#queryDatabase(databaseId, 'PRAGMA table_info(offline_sync_commands)');
|
|
2197
|
+
if (commandColumns.some((column) => column['name'] === 'aggregate_id')) {
|
|
2198
|
+
await this.#execute(databaseId, 'ALTER TABLE offline_sync_commands RENAME COLUMN aggregate_id TO aggregate_local_id');
|
|
2199
|
+
commandColumns = await this.#queryDatabase(databaseId, 'PRAGMA table_info(offline_sync_commands)');
|
|
2200
|
+
}
|
|
2201
|
+
if (!commandColumns.some((column) => column['name'] === 'optimistic_value_json')) {
|
|
2202
|
+
await this.#execute(databaseId, 'ALTER TABLE offline_sync_commands ADD COLUMN optimistic_value_json TEXT');
|
|
2203
|
+
await this.#execute(databaseId, 'UPDATE offline_sync_commands SET optimistic_value_json = payload_json');
|
|
2204
|
+
}
|
|
2205
|
+
await this.#execute(databaseId, `INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, NULL)
|
|
2206
|
+
ON CONFLICT(id) DO UPDATE SET schema_version = excluded.schema_version`, [OFFLINE_SCHEMA_VERSION]);
|
|
2207
|
+
await this.#initializeReplicaSchema(databaseId);
|
|
2208
|
+
}
|
|
2209
|
+
async #initializeReplicaSchema(databaseId) {
|
|
2210
|
+
const bundle = this.#options.replicaSchema;
|
|
2211
|
+
const targetVersion = bundle.version;
|
|
2212
|
+
const targetHash = await sha256OfflineReplicaSchema(bundle);
|
|
2213
|
+
const rows = await this.#queryDatabase(databaseId, 'SELECT version, schema_hash FROM offline_replica_schema_metadata WHERE id = 1');
|
|
2214
|
+
const storedVersion = rows[0] ? this.#number(rows[0]['version']) : null;
|
|
2215
|
+
const storedHash = rows[0] ? this.#string(rows[0]['schema_hash']) : null;
|
|
2216
|
+
if (storedVersion === null) {
|
|
2217
|
+
await this.#nativeTransaction(databaseId, async () => {
|
|
2218
|
+
await this.#executeReplicaCreateStatements(databaseId, bundle);
|
|
2219
|
+
await this.#upsertReplicaSchemaMetadata(databaseId, targetVersion, targetHash);
|
|
2220
|
+
});
|
|
2221
|
+
return;
|
|
2222
|
+
}
|
|
2223
|
+
if (storedVersion === targetVersion && storedHash === targetHash) {
|
|
2224
|
+
return;
|
|
2225
|
+
}
|
|
2226
|
+
if (storedVersion === targetVersion) {
|
|
2227
|
+
throw new Error(`Offline replica schema hash mismatch at version ${targetVersion}. Reinstall the application or bump replicaSchema.version after intentional schema changes.`);
|
|
2228
|
+
}
|
|
2229
|
+
if (storedVersion > targetVersion) {
|
|
2230
|
+
throw new Error(`Offline replica schema version ${storedVersion} is newer than application version ${targetVersion}. Upgrade the application before opening this database.`);
|
|
2231
|
+
}
|
|
2232
|
+
await this.#nativeTransaction(databaseId, async () => {
|
|
2233
|
+
for (let version = storedVersion; version < targetVersion; version++) {
|
|
2234
|
+
const migration = bundle.migrations.find((candidate) => candidate.fromVersion === version);
|
|
2235
|
+
if (!migration) {
|
|
2236
|
+
throw new Error(`Missing offline replica schema migration from version ${version} to ${version + 1}.`);
|
|
2237
|
+
}
|
|
2238
|
+
for (const statement of migration.statements) {
|
|
2239
|
+
await this.#execute(databaseId, statement);
|
|
2240
|
+
}
|
|
2241
|
+
}
|
|
2242
|
+
await this.#executeReplicaCreateStatements(databaseId, bundle);
|
|
2243
|
+
await this.#upsertReplicaSchemaMetadata(databaseId, targetVersion, targetHash);
|
|
2244
|
+
});
|
|
2245
|
+
}
|
|
2246
|
+
async #executeReplicaCreateStatements(databaseId, bundle) {
|
|
2247
|
+
for (const entity of bundle.entities) {
|
|
2248
|
+
for (const statement of entity.createTableSql) {
|
|
2249
|
+
await this.#execute(databaseId, statement);
|
|
2250
|
+
}
|
|
2251
|
+
}
|
|
2252
|
+
}
|
|
2253
|
+
async #upsertReplicaSchemaMetadata(databaseId, version, schemaHash) {
|
|
2254
|
+
await this.#execute(databaseId, `INSERT INTO offline_replica_schema_metadata (id, version, schema_hash) VALUES (1, ?, ?)
|
|
2255
|
+
ON CONFLICT(id) DO UPDATE SET version = excluded.version, schema_hash = excluded.schema_hash`, [version, schemaHash]);
|
|
2256
|
+
}
|
|
2257
|
+
async #nativeTransaction(databaseId, run) {
|
|
2258
|
+
await this.#sqlite.beginTransaction({ databaseId });
|
|
2259
|
+
try {
|
|
2260
|
+
await run();
|
|
2261
|
+
await this.#sqlite.commitTransaction({ databaseId });
|
|
2262
|
+
}
|
|
2263
|
+
catch (error) {
|
|
2264
|
+
await this.#sqlite.rollbackTransaction({ databaseId });
|
|
2265
|
+
throw error;
|
|
2266
|
+
}
|
|
2267
|
+
}
|
|
2268
|
+
async #databaseConnection() {
|
|
2269
|
+
await this.initialize();
|
|
2270
|
+
if (!this.#databaseId)
|
|
2271
|
+
throw new Error('Offline SQLite database is not initialized');
|
|
2272
|
+
return this.#databaseId;
|
|
2273
|
+
}
|
|
2274
|
+
async #query(statement, values = []) {
|
|
2275
|
+
return this.#queryDatabase(await this.#databaseConnection(), statement, values);
|
|
2276
|
+
}
|
|
2277
|
+
#write(statement, values) {
|
|
2278
|
+
return this.#queueWrite((databaseId) => this.#execute(databaseId, statement, values));
|
|
2279
|
+
}
|
|
2280
|
+
#queueWrite(run) {
|
|
2281
|
+
const write = this.#writes.then(async () => run(await this.#databaseConnection()));
|
|
2282
|
+
this.#writes = write.catch(() => undefined);
|
|
2283
|
+
return write;
|
|
2284
|
+
}
|
|
2285
|
+
#transaction(run) {
|
|
2286
|
+
const write = this.#writes.then(async () => {
|
|
2287
|
+
const databaseId = await this.#databaseConnection();
|
|
2288
|
+
await this.#sqlite.beginTransaction({ databaseId });
|
|
2289
|
+
try {
|
|
2290
|
+
await run(databaseId);
|
|
2291
|
+
await this.#sqlite.commitTransaction({ databaseId });
|
|
2292
|
+
}
|
|
2293
|
+
catch (error) {
|
|
2294
|
+
await this.#sqlite.rollbackTransaction({ databaseId });
|
|
2295
|
+
throw error;
|
|
2296
|
+
}
|
|
2297
|
+
});
|
|
2298
|
+
this.#writes = write.catch(() => undefined);
|
|
2299
|
+
return write;
|
|
2300
|
+
}
|
|
2301
|
+
#command(row) {
|
|
2302
|
+
return {
|
|
2303
|
+
commandId: this.#string(row['command_id']),
|
|
2304
|
+
userId: this.#number(row['user_id']),
|
|
2305
|
+
groupId: this.#number(row['group_id']),
|
|
2306
|
+
aggregateType: this.#string(row['aggregate_type']),
|
|
2307
|
+
aggregateLocalId: this.#string(row['aggregate_local_id']),
|
|
2308
|
+
operation: this.#string(row['operation']),
|
|
2309
|
+
payload: this.#parse(row['payload_json']),
|
|
2310
|
+
optimisticValue: this.#parse(row['optimistic_value_json']),
|
|
2311
|
+
payloadHash: this.#string(row['payload_hash']),
|
|
2312
|
+
baseRevision: this.#parseNullable(row['base_revision_json']),
|
|
2313
|
+
state: this.#string(row['state']),
|
|
2314
|
+
attempts: this.#number(row['attempts']),
|
|
2315
|
+
retryAt: this.#numberOrNull(row['retry_at']),
|
|
2316
|
+
createdAt: this.#number(row['created_at']),
|
|
2317
|
+
lastErrorCode: this.#stringOrNull(row['last_error_code']),
|
|
2318
|
+
};
|
|
2319
|
+
}
|
|
2320
|
+
#putCommand(databaseId, command) {
|
|
2321
|
+
return this.#execute(databaseId, `INSERT INTO offline_sync_commands
|
|
2322
|
+
(command_id, user_id, group_id, aggregate_type, aggregate_local_id, operation, payload_json, optimistic_value_json,
|
|
2323
|
+
payload_hash, base_revision_json, state, attempts, retry_at, created_at, last_error_code)
|
|
2324
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
2325
|
+
ON CONFLICT(command_id) DO UPDATE SET
|
|
2326
|
+
user_id = excluded.user_id, group_id = excluded.group_id, aggregate_type = excluded.aggregate_type,
|
|
2327
|
+
aggregate_local_id = excluded.aggregate_local_id, operation = excluded.operation, payload_json = excluded.payload_json,
|
|
2328
|
+
optimistic_value_json = excluded.optimistic_value_json, payload_hash = excluded.payload_hash,
|
|
2329
|
+
base_revision_json = excluded.base_revision_json, state = excluded.state, attempts = excluded.attempts,
|
|
2330
|
+
retry_at = excluded.retry_at, created_at = excluded.created_at, last_error_code = excluded.last_error_code`, [
|
|
2331
|
+
command.commandId,
|
|
2332
|
+
command.userId,
|
|
2333
|
+
command.groupId,
|
|
2334
|
+
command.aggregateType,
|
|
2335
|
+
command.aggregateLocalId,
|
|
2336
|
+
command.operation,
|
|
2337
|
+
JSON.stringify(command.payload),
|
|
2338
|
+
JSON.stringify(command.optimisticValue),
|
|
2339
|
+
command.payloadHash,
|
|
2340
|
+
this.#stringifyNullable(command.baseRevision),
|
|
2341
|
+
command.state,
|
|
2342
|
+
command.attempts,
|
|
2343
|
+
command.retryAt,
|
|
2344
|
+
command.createdAt,
|
|
2345
|
+
command.lastErrorCode,
|
|
2346
|
+
]);
|
|
2347
|
+
}
|
|
2348
|
+
#putReplicaRow(databaseId, row) {
|
|
2349
|
+
const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
|
|
2350
|
+
const encoded = encodeOfflineReplicaValues(schema, row.values);
|
|
2351
|
+
const confirmedValues = row.confirmedValues === null ? null : projectOfflineReplicaValues(schema, row.confirmedValues);
|
|
2352
|
+
const { sql, domainColumns } = this.#buildReplicaUpsertStatement(schema);
|
|
2353
|
+
const values = [
|
|
2354
|
+
row.localId,
|
|
2355
|
+
row.userId,
|
|
2356
|
+
...(schema.scope === 'group' ? [row.groupId] : []),
|
|
2357
|
+
...(this.#schemaHasServerId(schema) ? [row.serverId] : []),
|
|
2358
|
+
confirmedValues === null ? null : JSON.stringify(confirmedValues),
|
|
2359
|
+
row.serverRevision == null ? null : JSON.stringify(row.serverRevision),
|
|
2360
|
+
row.syncState,
|
|
2361
|
+
row.fetchedAt,
|
|
2362
|
+
...domainColumns.map((column) => encoded[column] ?? null),
|
|
2363
|
+
];
|
|
2364
|
+
return this.#execute(databaseId, sql, values);
|
|
2365
|
+
}
|
|
2366
|
+
#removeReplicaRow(databaseId, key) {
|
|
2367
|
+
const schema = this.#resolveReplicaEntitySchema(key.sourceKey);
|
|
2368
|
+
const predicates = ['local_id = ?', '_offline_user_id = ?'];
|
|
2369
|
+
const values = [key.localId, key.userId];
|
|
2370
|
+
if (schema.scope === 'group') {
|
|
2371
|
+
predicates.push('_offline_group_id = ?');
|
|
2372
|
+
values.push(key.groupId);
|
|
2373
|
+
}
|
|
2374
|
+
return this.#execute(databaseId, `DELETE FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
|
|
2375
|
+
}
|
|
2376
|
+
#putReplicaCursor(databaseId, cursor) {
|
|
2377
|
+
return this.#execute(databaseId, `INSERT INTO offline_replica_cursors (user_id, group_id, cursor) VALUES (?, ?, ?)
|
|
2378
|
+
ON CONFLICT(user_id, group_id) DO UPDATE SET cursor = excluded.cursor`, [cursor.userId, cursor.groupId, cursor.cursor]);
|
|
2379
|
+
}
|
|
2380
|
+
#buildReplicaUpsertStatement(schema) {
|
|
2381
|
+
const insertColumns = ['local_id', '_offline_user_id'];
|
|
2382
|
+
const updateSets = ['_offline_user_id = excluded._offline_user_id'];
|
|
2383
|
+
if (schema.scope === 'group') {
|
|
2384
|
+
insertColumns.push('_offline_group_id');
|
|
2385
|
+
updateSets.push('_offline_group_id = excluded._offline_group_id');
|
|
2386
|
+
}
|
|
2387
|
+
if (this.#schemaHasServerId(schema)) {
|
|
2388
|
+
insertColumns.push('server_id');
|
|
2389
|
+
updateSets.push('server_id = excluded.server_id');
|
|
2390
|
+
}
|
|
2391
|
+
insertColumns.push('_offline_confirmed_json', '_offline_server_revision_json', '_offline_sync_state', '_offline_fetched_at');
|
|
2392
|
+
updateSets.push('_offline_confirmed_json = excluded._offline_confirmed_json', '_offline_server_revision_json = excluded._offline_server_revision_json', '_offline_sync_state = excluded._offline_sync_state', '_offline_fetched_at = excluded._offline_fetched_at');
|
|
2393
|
+
const domainColumns = [];
|
|
2394
|
+
for (const field of schema.fields) {
|
|
2395
|
+
if (field.policy !== 'column' || field.sqliteColumnName === null)
|
|
2396
|
+
continue;
|
|
2397
|
+
insertColumns.push(field.sqliteColumnName);
|
|
2398
|
+
updateSets.push(`${field.sqliteColumnName} = excluded.${field.sqliteColumnName}`);
|
|
2399
|
+
domainColumns.push(field.sqliteColumnName);
|
|
2400
|
+
}
|
|
2401
|
+
const placeholders = insertColumns.map(() => '?').join(', ');
|
|
2402
|
+
return {
|
|
2403
|
+
sql: `INSERT INTO ${schema.tableName} (${insertColumns.join(', ')})
|
|
2404
|
+
VALUES (${placeholders})
|
|
2405
|
+
ON CONFLICT(local_id) DO UPDATE SET ${updateSets.join(', ')}`,
|
|
2406
|
+
domainColumns,
|
|
2407
|
+
};
|
|
2408
|
+
}
|
|
2409
|
+
#replicaRowFromSqliteRow(schema, scope, sourceKey, localId, row) {
|
|
2410
|
+
return {
|
|
2411
|
+
...scope,
|
|
2412
|
+
sourceKey,
|
|
2413
|
+
localId,
|
|
2414
|
+
serverId: this.#schemaHasServerId(schema) ? this.#numberOrNull(row['server_id']) : null,
|
|
2415
|
+
values: decodeOfflineReplicaValues(schema, row),
|
|
2416
|
+
confirmedValues: this.#parseNullable(row['_offline_confirmed_json']),
|
|
2417
|
+
serverRevision: this.#parseNullable(row['_offline_server_revision_json']),
|
|
2418
|
+
fetchedAt: this.#number(row['_offline_fetched_at']),
|
|
2419
|
+
syncState: this.#string(row['_offline_sync_state']),
|
|
2420
|
+
};
|
|
2421
|
+
}
|
|
2422
|
+
#resolveReplicaEntitySchema(sourceKey) {
|
|
2423
|
+
const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);
|
|
2424
|
+
if (!schema)
|
|
2425
|
+
throw new Error(`Unknown offline replica source key "${sourceKey}".`);
|
|
2426
|
+
return schema;
|
|
2427
|
+
}
|
|
2428
|
+
#schemaHasServerId(schema) {
|
|
2429
|
+
return schema.fields.some((field) => field.policy === 'serverId');
|
|
2430
|
+
}
|
|
2431
|
+
async #execute(databaseId, statement, values = []) {
|
|
2432
|
+
await this.#sqlite.execute({ databaseId, statement, values });
|
|
2433
|
+
}
|
|
2434
|
+
async #queryDatabase(databaseId, statement, values = []) {
|
|
2435
|
+
const result = await this.#sqlite.query({ databaseId, statement, values });
|
|
2436
|
+
return (result.rows ?? []).map((row) => {
|
|
2437
|
+
if (!Array.isArray(row))
|
|
2438
|
+
return row;
|
|
2439
|
+
return Object.fromEntries(row.map((value, index) => [result.columns?.[index] ?? String(index), value]));
|
|
2440
|
+
});
|
|
2441
|
+
}
|
|
2442
|
+
#parse(value) {
|
|
2443
|
+
if (typeof value !== 'string')
|
|
2444
|
+
throw new Error('Invalid JSON value in offline SQLite database');
|
|
2445
|
+
return JSON.parse(value);
|
|
2446
|
+
}
|
|
2447
|
+
#parseNullable(value) {
|
|
2448
|
+
return value == null ? null : this.#parse(value);
|
|
2449
|
+
}
|
|
2450
|
+
#stringifyNullable(value) {
|
|
2451
|
+
return value == null ? null : JSON.stringify(value);
|
|
2452
|
+
}
|
|
2453
|
+
#number(value) {
|
|
2454
|
+
if (typeof value !== 'number')
|
|
2455
|
+
throw new Error('Invalid numeric value in offline SQLite database');
|
|
2456
|
+
return value;
|
|
2457
|
+
}
|
|
2458
|
+
#numberOrNull(value) {
|
|
2459
|
+
return value == null ? null : this.#number(value);
|
|
2460
|
+
}
|
|
2461
|
+
#string(value) {
|
|
2462
|
+
if (typeof value !== 'string')
|
|
2463
|
+
throw new Error('Invalid string value in offline SQLite database');
|
|
2464
|
+
return value;
|
|
2465
|
+
}
|
|
2466
|
+
#stringOrNull(value) {
|
|
2467
|
+
return value == null ? null : this.#string(value);
|
|
2468
|
+
}
|
|
2469
|
+
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: SqliteOfflineRepository, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
2470
|
+
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: SqliteOfflineRepository, providedIn: 'root' }); }
|
|
2471
|
+
}
|
|
2472
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: SqliteOfflineRepository, decorators: [{
|
|
2473
|
+
type: Injectable,
|
|
2474
|
+
args: [{ providedIn: 'root' }]
|
|
2475
|
+
}] });
|
|
2476
|
+
|
|
2477
|
+
/**
|
|
2478
|
+
* Provide the standard scoped offline runtime.
|
|
2479
|
+
*
|
|
2480
|
+
* @remarks
|
|
2481
|
+
* Web uses Ionic Storage. Native iOS/Android uses encrypted Capawesome SQLite. The application owns
|
|
2482
|
+
* URL/DTO policy and command execution; the kit owns persistence, ordering, retries, and session
|
|
2483
|
+
* isolation.
|
|
2484
|
+
*/
|
|
2485
|
+
function provideOffline(options) {
|
|
2486
|
+
return makeEnvironmentProviders([
|
|
2487
|
+
options.commandExecutor,
|
|
2488
|
+
options.replicaPuller,
|
|
2489
|
+
{
|
|
2490
|
+
provide: OFFLINE_KIT_OPTIONS,
|
|
2491
|
+
useValue: {
|
|
2492
|
+
databaseName: options.databaseName,
|
|
2493
|
+
encryptionKey: options.encryptionKey,
|
|
2494
|
+
replicaSchema: options.replicaSchema,
|
|
2495
|
+
},
|
|
2496
|
+
},
|
|
2497
|
+
{ provide: CAPAWESOME_SQLITE, useValue: options.sqlitePlugin ?? null },
|
|
2498
|
+
{
|
|
2499
|
+
provide: OFFLINE_REPOSITORY,
|
|
2500
|
+
useFactory: () => selectOfflineRepository(Capacitor.getPlatform(), inject(IonicOfflineRepository), inject(SqliteOfflineRepository)),
|
|
2501
|
+
},
|
|
2502
|
+
{ provide: OFFLINE_SYNC_CONTEXT, useExisting: OfflineSessionService },
|
|
2503
|
+
{ provide: OFFLINE_COMMAND_EXECUTOR, useExisting: options.commandExecutor },
|
|
2504
|
+
{ provide: OFFLINE_REPLICA_PULLER, useExisting: options.replicaPuller },
|
|
2505
|
+
...(options.commandHooks ? [options.commandHooks, { provide: OFFLINE_COMMAND_HOOKS, useExisting: options.commandHooks }] : []),
|
|
2506
|
+
...options.requestPolicies.flatMap((policy) => provideOfflineRequestPolicy(policy)),
|
|
2507
|
+
...(options.providers ?? []),
|
|
2508
|
+
provideAppInitializer(() => inject(OfflineCoordinatorService).initialize()),
|
|
2509
|
+
]);
|
|
2510
|
+
}
|
|
2511
|
+
|
|
2512
|
+
/** Applies product offline read policies while observing real API reachability. */
|
|
2513
|
+
const offlineInterceptor = (request, next) => {
|
|
2514
|
+
const network = inject(OfflineNetworkService);
|
|
2515
|
+
const transport = () => observeTransport(next(request), network);
|
|
2516
|
+
if (request.context.get(OFFLINE_BYPASS))
|
|
2517
|
+
return transport();
|
|
2518
|
+
if (request.method !== 'GET')
|
|
2519
|
+
return transport();
|
|
2520
|
+
const registry = inject(OfflineRequestPolicyRegistry);
|
|
2521
|
+
const fallback = inject(OfflineRequestFallbackService);
|
|
2522
|
+
const plan = registry.resolve(request);
|
|
2523
|
+
if (!plan)
|
|
2524
|
+
return transport();
|
|
2525
|
+
return defer(transport).pipe(catchError((error) => fallback.handle(request, error, plan) ?? throwError(() => error)));
|
|
2526
|
+
};
|
|
2527
|
+
function observeTransport(source, network) {
|
|
2528
|
+
return source.pipe(tap({
|
|
2529
|
+
next: (event) => {
|
|
2530
|
+
if (event instanceof HttpResponse)
|
|
2531
|
+
network.markApiSuccess();
|
|
2532
|
+
},
|
|
2533
|
+
error: (error) => {
|
|
2534
|
+
if (isOfflineFallbackError(error))
|
|
2535
|
+
network.markApiFailure();
|
|
2536
|
+
},
|
|
2537
|
+
}));
|
|
2538
|
+
}
|
|
2539
|
+
/** Resolves transport failures from the local replica without hiding HTTP errors. */
|
|
2540
|
+
class OfflineRequestFallbackService {
|
|
2541
|
+
#registry = inject(OfflineRequestPolicyRegistry);
|
|
2542
|
+
#errorHandler = inject(ErrorHandler);
|
|
2543
|
+
handle(request, error, resolvedPlan) {
|
|
2544
|
+
if (request.context.get(OFFLINE_BYPASS) || request.method !== 'GET' || !isOfflineFallbackError(error))
|
|
2545
|
+
return null;
|
|
2546
|
+
const plan = resolvedPlan ?? this.#registry.resolve(request);
|
|
2547
|
+
if (!plan || plan.kind !== 'read')
|
|
2548
|
+
return null;
|
|
2549
|
+
return defer(() => from(plan.readLocal())).pipe(catchError((localError) => {
|
|
2550
|
+
this.#errorHandler.handleError(localError);
|
|
2551
|
+
return throwError(() => error);
|
|
2552
|
+
}), concatMap((cached) => cached ? of(cached.clone({ headers: cached.headers.set(OFFLINE_RESPONSE_HEADER, 'local') })) : throwError(() => error)));
|
|
2553
|
+
}
|
|
2554
|
+
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineRequestFallbackService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
2555
|
+
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineRequestFallbackService, providedIn: 'root' }); }
|
|
2556
|
+
}
|
|
2557
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineRequestFallbackService, decorators: [{
|
|
2558
|
+
type: Injectable,
|
|
2559
|
+
args: [{ providedIn: 'root' }]
|
|
2560
|
+
}] });
|
|
2561
|
+
|
|
2562
|
+
/** Standard scoped local replica and outbox runtime for offline-capable Ionic applications. */
|
|
2563
|
+
|
|
2564
|
+
/**
|
|
2565
|
+
* Generated bundle index. Do not edit.
|
|
2566
|
+
*/
|
|
2567
|
+
|
|
2568
|
+
export { CAPAWESOME_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, OfflinePayloadValidationError, OfflineReplicaPullService, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineSyncService, SqliteOfflineRepository, booleanColumn, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, ignored, integer, isOfflineFallbackError, json, nullable, offlineInterceptor, projectOfflineReplicaValues, provideOffline, provideOfflineRequestPolicy, real, selectOfflineRepository, serverId, sha256OfflineReplicaSchema, text };
|
|
2569
|
+
//# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map
|