@rdlabo/ionic-angular-kit 21.4.0 → 21.4.2
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
CHANGED
|
@@ -330,6 +330,197 @@ A fleet-canonical HTTP interceptor with:
|
|
|
330
330
|
- Configurable bypass (CDN, S3, external URLs)
|
|
331
331
|
- **Safe retry**: only idempotent methods (`GET`/`HEAD`/`OPTIONS`, or a request with an `Idempotency-Key`) are retried, and only on a transient status `[0, 408, 429, 502, 503, 504]`, up to 2 times with a short jittered backoff (honoring `Retry-After`). **Writes are never auto-retried** (no duplicate saves).
|
|
332
332
|
- **Offline fast-fail**: when the device is offline the interceptor stops retrying immediately and hands off to `offlineFallback` instead of waiting out the backoff.
|
|
333
|
+
|
|
334
|
+
### Scoped local replica and outbox (`@rdlabo/ionic-angular-kit/offline`)
|
|
335
|
+
|
|
336
|
+
The optional `offline` entry point provides a user/group-scoped local replica, durable outbox, authenticated
|
|
337
|
+
session boundary, cursor-based delta pull, aggregate-ordered replay, optimistic updates, retry classification, and a
|
|
338
|
+
read-only request-policy interceptor. Applications provide URL/DTO read policies, a replica puller, and a command
|
|
339
|
+
executor through `provideOffline(...)`.
|
|
340
|
+
Mutations are queued explicitly with `OfflineSyncService.enqueue`, not through HTTP interceptor policy.
|
|
341
|
+
Web storage uses Ionic Storage; iOS and Android use encrypted Capawesome SQLite. Importing either the
|
|
342
|
+
primary entry point or `/offline` does not pull the private plugin into existing applications.
|
|
343
|
+
|
|
344
|
+
The offline interceptor observes real transport responses to update API reachability. For matched `GET`
|
|
345
|
+
requests only, a transport failure with `status=0` may return a local replica response tagged
|
|
346
|
+
`X-Offline-Response: local`. `POST` and other write methods always go to transport unchanged; outbox replay
|
|
347
|
+
requests bypass policy with `OFFLINE_BYPASS` while still using the same transport observation.
|
|
348
|
+
|
|
349
|
+
The native offline runtime currently requires Capacitor 8, `@capawesome-team/capacitor-sqlite` 0.3.x, and
|
|
350
|
+
`@capawesome-team/capacitor-secure-preferences` 0.2.x. Configure the private Insiders registry with the license key
|
|
351
|
+
before installing the SQLite and Secure Preferences packages plus the SQLite WASM runtime. Supply the license key
|
|
352
|
+
through a local/CI secret; never commit it to `.npmrc`.
|
|
353
|
+
|
|
354
|
+
```bash
|
|
355
|
+
npm config set @capawesome-team:registry https://npm.registry.capawesome.io
|
|
356
|
+
npm config set //npm.registry.capawesome.io/:_authToken "$CAPAWESOME_LICENSE_KEY"
|
|
357
|
+
npm install @capawesome-team/capacitor-sqlite@^0.3.0 \
|
|
358
|
+
@capawesome-team/capacitor-secure-preferences@^0.2.0 \
|
|
359
|
+
@sqlite.org/sqlite-wasm
|
|
360
|
+
npx cap sync
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
Applications on an older Capacitor major must not install those versions; upgrade to Capacitor 8 before enabling
|
|
364
|
+
the standard native offline runtime. After installation, follow both plugins' platform steps. In particular, exclude
|
|
365
|
+
`CAPAWESOME_SECURE_PREFERENCES.xml` from Android 11-and-lower `fullBackupContent` and Android 12+ cloud backup rules,
|
|
366
|
+
so the database key is not restored independently of its device keystore material.
|
|
367
|
+
|
|
368
|
+
Pass the `Sqlite` export and a database key loaded from secure device storage to the kit. Never hard-code or derive
|
|
369
|
+
the database key from a user identifier or access token.
|
|
370
|
+
|
|
371
|
+
```ts
|
|
372
|
+
import { SecurePreferences } from '@capawesome-team/capacitor-secure-preferences';
|
|
373
|
+
import { Sqlite } from '@capawesome-team/capacitor-sqlite';
|
|
374
|
+
|
|
375
|
+
const OFFLINE_DATABASE_KEY = 'product-offline-database-key';
|
|
376
|
+
|
|
377
|
+
async function offlineDatabaseKey(): Promise<string> {
|
|
378
|
+
const { value } = await SecurePreferences.get({ key: OFFLINE_DATABASE_KEY });
|
|
379
|
+
if (value) return value;
|
|
380
|
+
|
|
381
|
+
const bytes = crypto.getRandomValues(new Uint8Array(32));
|
|
382
|
+
const generated = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
|
|
383
|
+
await SecurePreferences.set({ key: OFFLINE_DATABASE_KEY, value: generated });
|
|
384
|
+
return generated;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
provideOffline({
|
|
388
|
+
// ...product policies, puller, and executor
|
|
389
|
+
sqlitePlugin: Sqlite,
|
|
390
|
+
encryptionKey: offlineDatabaseKey,
|
|
391
|
+
});
|
|
392
|
+
```
|
|
393
|
+
|
|
394
|
+
SQLite entities use an immutable client-generated UUID as `localId` and keep the server's
|
|
395
|
+
`AUTO_INCREMENT` id separately as nullable `serverId`. The outbox references only `aggregateLocalId`.
|
|
396
|
+
Immediately before each send, the executor receives the latest `{ localId, serverId }` resolved from
|
|
397
|
+
SQLite; a successful create adds `serverId` without replacing `localId`. Entity projection and outbox
|
|
398
|
+
append/removal are committed in one local transaction.
|
|
399
|
+
|
|
400
|
+
| Identity | SQLite column | Before synchronization | After server acknowledgement |
|
|
401
|
+
| --- | --- | --- | --- |
|
|
402
|
+
| `localId` | `local_id` | client-generated UUID | unchanged UUID |
|
|
403
|
+
| `serverId` | `server_id` | `NULL` for a new entity | positive server `AUTO_INCREMENT` id |
|
|
404
|
+
|
|
405
|
+
The write lifecycle is: update the replica immediately → append an outbox command in the same transaction → render
|
|
406
|
+
the optimistic value → replay in the background → validate the server revision → store the confirmed value and
|
|
407
|
+
revision. The server remains authoritative; SQLite is the durable local working database, not an HTTP response cache.
|
|
408
|
+
|
|
409
|
+
`serverId()` supports positive safe integers only. Products must expose an internal numeric primary key for a
|
|
410
|
+
replicated entity; a human-facing string such as a public code, slip number, or SKU remains an ordinary replicated
|
|
411
|
+
column. There is intentionally no text-server-id overload.
|
|
412
|
+
|
|
413
|
+
When the application already knows the numeric server id but the first replica pull has not materialized the row,
|
|
414
|
+
pass that identity explicitly while adopting the entity. This is required for updates and especially deletes: an
|
|
415
|
+
omitted id would otherwise make the executor interpret the row as a not-yet-created local entity.
|
|
416
|
+
|
|
417
|
+
```ts
|
|
418
|
+
await offlineSync.enqueue({
|
|
419
|
+
groupId,
|
|
420
|
+
aggregateType: 'items',
|
|
421
|
+
aggregateLocalId: localId,
|
|
422
|
+
serverId: existingApiItem.id,
|
|
423
|
+
operation: 'items.delete',
|
|
424
|
+
payload: { method: 'DELETE' },
|
|
425
|
+
optimisticValue: existingApiItem,
|
|
426
|
+
});
|
|
427
|
+
```
|
|
428
|
+
|
|
429
|
+
The mapping is immutable and unique inside its effective replica scope. Reassigning one `localId` to another
|
|
430
|
+
`serverId`, or assigning the same `serverId` to another `localId`, rejects before persistence. Web storage enforces
|
|
431
|
+
the same rule transactionally as SQLite's unique indexes: group-scoped entities are unique per user/group/source,
|
|
432
|
+
and user-scoped entities are unique per user/source across groups. If an adopted row has no confirmed baseline and
|
|
433
|
+
its final command is discarded, the local row is removed; the next pull may materialize the authoritative server
|
|
434
|
+
row again. A row with a confirmed baseline rolls back to that baseline instead.
|
|
435
|
+
|
|
436
|
+
Each synchronization cycle pulls authoritative server deltas before replaying the outbox. Every page carries the
|
|
437
|
+
replica schema version/hash and advances a durable user/group cursor in the same transaction as its rows. A schema
|
|
438
|
+
mismatch, malformed row, or non-advancing cursor rejects synchronization without advancing that cursor. If a remote
|
|
439
|
+
revision changed while a local command is pending, the optimistic row remains visible and both row and command move
|
|
440
|
+
to `conflict`; the new server value is retained as the confirmed baseline.
|
|
441
|
+
|
|
442
|
+
The command adapter must send `commandId` as the server-side idempotency key. The server persists that key with the
|
|
443
|
+
mutation and returns all keys represented by a delta row as `acknowledgedCommandIds`. This correlation is required:
|
|
444
|
+
if the server commits a create/update/delete but its HTTP acknowledgement is lost, the next pull reconciles the
|
|
445
|
+
server result into the original `localId`, removes the acknowledged outbox prefix, and rebases later commands without
|
|
446
|
+
creating a second local identity.
|
|
447
|
+
|
|
448
|
+
Versioned replica schemas lock web and native storage. Web metadata stores
|
|
449
|
+
`replicaSchemaVersion` and `replicaSchemaHash`; native stores the same pair in
|
|
450
|
+
`offline_replica_schema_metadata`. Bump `version` for every intentional shape change and supply a
|
|
451
|
+
complete one-step migration chain. Native runs each step's SQL `statements`; web runs
|
|
452
|
+
`migrateWebRow`, which receives only `{ sourceKey, values, confirmedValues }` and may return the same
|
|
453
|
+
shape or `null` to delete a row. Identity and sync metadata (`localId`, `serverId`, scope, revision,
|
|
454
|
+
`syncState`) stay outside the callback. The bundle fingerprint hashes `version`, entity layouts, and
|
|
455
|
+
migration `fromVersion`/`statements` — never function bodies.
|
|
456
|
+
|
|
457
|
+
```typescript
|
|
458
|
+
import {
|
|
459
|
+
defineOfflineReplicaSchema,
|
|
460
|
+
defineReplicaEntity,
|
|
461
|
+
provideOffline,
|
|
462
|
+
serverId,
|
|
463
|
+
text,
|
|
464
|
+
} from '@rdlabo/ionic-angular-kit/offline';
|
|
465
|
+
|
|
466
|
+
// This is the Hono package's existing `typeof items.$inferSelect` export.
|
|
467
|
+
import type { Items as ItemSelect } from '@product/hono/db/schema';
|
|
468
|
+
|
|
469
|
+
const itemEntityV2 = defineReplicaEntity<ItemSelect>()({
|
|
470
|
+
table: 'items',
|
|
471
|
+
sourceKey: 'items',
|
|
472
|
+
scope: 'group',
|
|
473
|
+
fields: {
|
|
474
|
+
id: serverId(),
|
|
475
|
+
title: text(),
|
|
476
|
+
subtitle: text(),
|
|
477
|
+
},
|
|
478
|
+
});
|
|
479
|
+
|
|
480
|
+
const replicaSchema = defineOfflineReplicaSchema({
|
|
481
|
+
version: 2,
|
|
482
|
+
entities: [itemEntityV2],
|
|
483
|
+
migrations: [
|
|
484
|
+
{
|
|
485
|
+
fromVersion: 1,
|
|
486
|
+
statements: ['ALTER TABLE items ADD COLUMN subtitle TEXT NOT NULL DEFAULT ""'],
|
|
487
|
+
migrateWebRow: (row) => ({
|
|
488
|
+
sourceKey: row.sourceKey,
|
|
489
|
+
values: { ...row.values, subtitle: '' },
|
|
490
|
+
confirmedValues:
|
|
491
|
+
row.confirmedValues === null ? null : { ...row.confirmedValues, subtitle: '' },
|
|
492
|
+
}),
|
|
493
|
+
},
|
|
494
|
+
],
|
|
495
|
+
});
|
|
496
|
+
|
|
497
|
+
provideOffline({
|
|
498
|
+
replicaSchema,
|
|
499
|
+
replicaPuller: ProductReplicaPuller,
|
|
500
|
+
commandExecutor: ProductCommandExecutor,
|
|
501
|
+
// ...request policies, sqlitePlugin, encryptionKey
|
|
502
|
+
});
|
|
503
|
+
```
|
|
504
|
+
|
|
505
|
+
Offline replica schema consumers must compile with TypeScript `strictNullChecks: true`. This is part of the standard,
|
|
506
|
+
not a compatibility option: without strict null checking, TypeScript cannot distinguish a nullable Hono property
|
|
507
|
+
from a required one and the schema lock cannot prove the SQLite mapping.
|
|
508
|
+
|
|
509
|
+
The schema definition must import the Hono package's exported `$inferSelect` type and map every key exactly once as
|
|
510
|
+
a SQLite column, `serverId()`, or `ignored(reason)`, with exactly one numeric `serverId()` per replicated entity.
|
|
511
|
+
Nullable Hono columns require `nullable(...)`; non-null columns reject it. Therefore adding,
|
|
512
|
+
removing, or changing nullability of a Drizzle column breaks the app build until its replica mapping is updated.
|
|
513
|
+
At runtime, `values` contains only the mapped column projection; `localId` and `serverId` remain dedicated replica
|
|
514
|
+
fields and ignored server fields are never persisted.
|
|
515
|
+
|
|
516
|
+
Encrypted native builds also require the plugin's SQLCipher platform setup: enable
|
|
517
|
+
`capawesomeCapacitorSqliteIncludeSqlcipher = true` on Android; select the `SQLCipher` pod when using
|
|
518
|
+
CocoaPods, or enable the `SQLCipher` package trait when using Swift Package Manager on iOS. Follow
|
|
519
|
+
the [Capawesome SQLite installation guide](https://capawesome.io/docs/plugins/sqlite/#installation)
|
|
520
|
+
for the exact native configuration and export-compliance notes.
|
|
521
|
+
Also follow the [Capawesome Secure Preferences installation guide](https://capawesome.io/docs/plugins/secure-preferences/#installation),
|
|
522
|
+
including its Android backup exclusion rules.
|
|
523
|
+
|
|
333
524
|
- **Status classification**: `0`→`onNetworkError` (connected only), `429`→`onRateLimited`, `502/503/504`→`onServerBusy`, `400/422/500`+message→`onServerError`, `401`→`onUnauthorized`, `403`→`onForbidden`. Other statuses (e.g. `404`) are left to the caller.
|
|
334
525
|
- **Universal 60s timeout** — every request fails with a synthetic (retryable) `408` if it hangs for 60s. Deliberately generous (catches a dead server without cutting off a large upload / AI generation; `timeout({ each })` resets per emission, so streaming is unaffected). Not configurable — one fleet-wide behavior.
|
|
335
526
|
- **Optional `treatAsError(response)`** — reject a 2xx (e.g. `204`/`206`) as an error when a backend uses it to signal a condition. The one genuinely app-specific bit (some apps receive a normal `204`), kept optional so class interceptors with a 2xx-as-error convention can migrate to `provideKitHttp`.
|