@rdlabo/ionic-angular-kit 21.5.6 → 21.5.8

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
@@ -506,21 +506,48 @@ provideOffline({
506
506
  });
507
507
  ```
508
508
 
509
- SQLite entities use an immutable client-generated UUID as `localId` and keep the server's
510
- `AUTO_INCREMENT` id separately as nullable `serverId`. The outbox references only `aggregateLocalId`.
511
- Immediately before each send, the executor receives the latest `{ localId, serverId }` resolved from
512
- SQLite; a successful create adds `serverId` without replacing `localId`. Entity projection and outbox
513
- append/removal are committed in one local transaction.
509
+ Every SQLite entity uses an immutable client-generated UUID as `localId`; the outbox references only
510
+ `aggregateLocalId`. Remote identity is declared per entity:
511
+
512
+ | Remote identity | SQLite representation | Executor target |
513
+ | ------------------------------- | --------------------------------------------- | ----------------------------------------- |
514
+ | `serverId()` | nullable `server_id` | `{ localId, serverId }` |
515
+ | `naturalKey(['a', 'b'])` | mapped `a`/`b` columns; no `server_id` column | `{ localId, serverId: null, naturalKey }` |
516
+ | no remote identity (local-only) | mapped values only | `{ localId, serverId: null }` |
514
517
 
515
- | Identity | SQLite column | Before synchronization | After server acknowledgement |
516
- | ---------- | ------------- | ----------------------- | ----------------------------------- |
517
- | `localId` | `local_id` | client-generated UUID | unchanged UUID |
518
- | `serverId` | `server_id` | `NULL` for a new entity | positive server `AUTO_INCREMENT` id |
518
+ A successful numeric create adds `serverId` without replacing `localId`. A natural key is derived from current
519
+ mapped values in declaration order; it is not duplicated as hidden row metadata. Entity projection and outbox
520
+ append/removal are committed in one local transaction.
519
521
 
520
522
  The write lifecycle is: update the replica immediately → append an outbox command in the same transaction → render
521
523
  the optimistic value → replay in the background → validate the server revision → store the confirmed value and
522
524
  revision. The server remains authoritative; SQLite is the durable local working database, not an HTTP response cache.
523
525
 
526
+ For a DB row whose deletion is represented by absence, enqueue the same full row values with
527
+ `replicaMutation: 'delete'`. The runtime stores a library-owned durable tombstone: normal `getReplicaRow()` and
528
+ `getReplicaRows()` reads stop returning the row immediately, while synchronization retains its immutable `localId`,
529
+ remote identity, confirmed baseline, and Outbox command. A successful tombstone acknowledgement removes the row
530
+ physically; retry, authorization failure, and conflict keep it hidden; discarding restores the latest confirmed
531
+ baseline unless the server has also deleted it.
532
+
533
+ Custom `OfflineRepository` implementations must implement `getReplicaRowIncludingPendingDelete()` before they can
534
+ accept `replicaMutation: 'delete'`; the runtime rejects that enqueue otherwise. This is intentional: ordinary product
535
+ reads stay hidden, while the library's remote-identity lookup and synchronization path must still resolve the durable
536
+ tombstone for replay, lost-ACK reconciliation, conflict handling, and discard.
537
+
538
+ ```ts
539
+ await offlineSync.enqueue({
540
+ scopeId,
541
+ aggregateType: 'favorites',
542
+ aggregateLocalId: favorite.localId,
543
+ operation: 'favorite.delete',
544
+ payload: { favTo: favorite.values.favTo },
545
+ optimisticValue: favorite.values,
546
+ baseRevision: favorite.serverRevision,
547
+ replicaMutation: 'delete',
548
+ });
549
+ ```
550
+
524
551
  The runtime retains pending, rejected, and conflicted commands until synchronization or an explicit user discard;
525
552
  it never evicts an unconfirmed mutation because of age or storage pressure. To keep a device that remains offline for
526
553
  months from exhausting SQLite, enqueue applies backpressure at 1,000 commands or 10 MiB per user by default. Products
@@ -528,9 +555,10 @@ may lower these limits with `outboxLimits: { maxCommandsPerUser, maxBytesPerUser
528
555
  existing replica and Outbox remain unchanged and enqueue rejects with `OfflineOutboxCapacityError`, so the UI can ask
529
556
  the user to reconnect or resolve/discard an attention item.
530
557
 
531
- `serverId()` supports positive safe integers only. Products must expose an internal numeric primary key for a
532
- replicated entity; a human-facing string such as a public code, slip number, or SKU remains an ordinary replicated
533
- column. There is intentionally no text-server-id overload.
558
+ Use `serverId()` for a positive safe-integer `AUTO_INCREMENT` key. Use `naturalKey([...])` when the product table's
559
+ remote identity is an existing composite primary key. Natural-key components must be required mapped `text()` or
560
+ `integer()` columns; nullable, ignored, JSON, empty declarations, duplicates, and mixed `serverId()`/`naturalKey()`
561
+ declarations reject. Text components reject NUL, malformed Unicode, and values larger than 1,024 UTF-8 bytes.
534
562
 
535
563
  When the application already knows the numeric server id but the first replica pull has not materialized the row,
536
564
  pass that identity explicitly while adopting the entity. This is required for updates and especially deletes: an
@@ -549,8 +577,9 @@ await offlineSync.enqueue({
549
577
  ```
550
578
 
551
579
  The mapping is immutable and unique inside its effective replica scope. Reassigning one `localId` to another
552
- `serverId`, or assigning the same `serverId` to another `localId`, rejects before persistence. Web storage enforces
553
- the same rule transactionally as SQLite's unique indexes: partition-scoped entities are unique per
580
+ `serverId` or natural key, or assigning the same remote identity to another `localId`, rejects before persistence.
581
+ Web storage enforces the rule transactionally. SQLite uses a scoped partial unique index for `server_id` and a
582
+ scoped composite unique index over the natural-key columns: partition-scoped entities are unique per
554
583
  user/partition/source, and user-scoped entities are unique per user/source across partitions. If an adopted row has
555
584
  no confirmed baseline and
556
585
  its final command is discarded, the local row is removed; the next pull may materialize the authoritative server
@@ -560,7 +589,9 @@ Each synchronization cycle pulls authoritative server deltas before replaying th
560
589
  replica schema version/hash and advances a durable user/partition cursor in the same transaction as its rows. A schema
561
590
  mismatch, malformed row, or non-advancing cursor rejects synchronization without advancing that cursor. If a remote
562
591
  revision changed while a local command is pending, the optimistic row remains visible and both row and command move
563
- to `conflict`; the new server value is retained as the confirmed baseline.
592
+ to `conflict`; the new server value is retained as the confirmed baseline. A remote tombstone follows the same
593
+ retention rule: without pending commands it removes the row, while a pending row and its Outbox remain under
594
+ `remote_deleted` conflict so the user can resolve or discard them.
564
595
 
565
596
  The command adapter must send `commandId` as the server-side idempotency key. The server persists that key with the
566
597
  mutation and returns all keys represented by a delta row as `acknowledgedCommandIds`. This correlation is required:
@@ -577,8 +608,22 @@ shape or `null` to delete a row. Identity and sync metadata (`localId`, `serverI
577
608
  `syncState`) stay outside the callback. The bundle fingerprint hashes `version`, entity layouts, and
578
609
  migration `fromVersion`/`statements` — never function bodies.
579
610
 
611
+ Changing a natural-key component list or its order changes the schema fingerprint and SQLite unique index. For a
612
+ released schema, bump `version`; native migration SQL must `DROP INDEX` and recreate the scoped composite index, and
613
+ `migrateWebRow` must preserve every natural-key value. Keep the transaction journal and schema-migration recovery
614
+ records until the replacement rows, index, and metadata commit together. This natural-key API is currently
615
+ unreleased, so adopting it before the first release needs no compatibility helper or legacy-row migration.
616
+
580
617
  ```typescript
581
- import { defineOfflineReplicaSchema, defineReplicaEntity, provideOffline, serverId, text } from '@rdlabo/ionic-angular-kit/offline';
618
+ import {
619
+ defineOfflineReplicaSchema,
620
+ defineReplicaEntity,
621
+ integer,
622
+ naturalKey,
623
+ provideOffline,
624
+ serverId,
625
+ text,
626
+ } from '@rdlabo/ionic-angular-kit/offline';
582
627
 
583
628
  // This is the Hono package's existing `typeof items.$inferSelect` export.
584
629
  import type { Items as ItemSelect } from '@product/hono/db/schema';
@@ -594,9 +639,28 @@ const itemEntityV2 = defineReplicaEntity<ItemSelect>()({
594
639
  },
595
640
  });
596
641
 
642
+ // Mirrors a product DB TableScheme whose primary key is (favFrom, favTo).
643
+ type FavoriteSelect = {
644
+ favFrom: number;
645
+ favTo: number;
646
+ label: string;
647
+ };
648
+
649
+ const favoriteEntity = defineReplicaEntity<FavoriteSelect>()({
650
+ table: 'favorites',
651
+ sourceKey: 'favorites',
652
+ scope: 'user',
653
+ identity: naturalKey(['favFrom', 'favTo']),
654
+ fields: {
655
+ favFrom: integer(),
656
+ favTo: integer(),
657
+ label: text(),
658
+ },
659
+ });
660
+
597
661
  const replicaSchema = defineOfflineReplicaSchema({
598
662
  version: 2,
599
- entities: [itemEntityV2],
663
+ entities: [itemEntityV2, favoriteEntity],
600
664
  migrations: [
601
665
  {
602
666
  fromVersion: 1,
@@ -623,11 +687,12 @@ not a compatibility option: without strict null checking, TypeScript cannot dist
623
687
  from a required one and the schema lock cannot prove the SQLite mapping.
624
688
 
625
689
  The schema definition must import the Hono package's exported `$inferSelect` type and map every key exactly once as
626
- a SQLite column, `serverId()`, or `ignored(reason)`, with exactly one numeric `serverId()` per replicated entity.
690
+ a SQLite column, `serverId()`, or `ignored(reason)`. A remotely replicated entity declares either one numeric
691
+ `serverId()` or one ordered `naturalKey([...])`; a local-only projection declares neither.
627
692
  Nullable Hono columns require `nullable(...)`; non-null columns reject it. Therefore adding,
628
693
  removing, or changing nullability of a Drizzle column breaks the app build until its replica mapping is updated.
629
- At runtime, `values` contains only the mapped column projection; `localId` and `serverId` remain dedicated replica
630
- fields and ignored server fields are never persisted.
694
+ At runtime, `values` contains only the mapped column projection; `localId` and numeric `serverId` remain dedicated
695
+ replica fields, natural identity is always derived from `values`, and ignored server fields are never persisted.
631
696
 
632
697
  - **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.
633
698
  - **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.