@tearleads/client-sdk 0.1.238 → 0.1.240

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.
Files changed (31) hide show
  1. package/data/documents/shared/types.d.ts +5 -1
  2. package/data/documents/shared/types.js.map +1 -1
  3. package/data/persistence/documents/documentAttachmentPresence.js +44 -0
  4. package/data/persistence/documents/documentAttachmentPresence.js.map +1 -0
  5. package/data/persistence/documents/records/documentSyncFailurePersistence.d.ts +0 -2
  6. package/data/persistence/documents/records/documentSyncFailurePersistence.js +0 -2
  7. package/data/persistence/documents/records/documentSyncFailurePersistence.js.map +1 -1
  8. package/data/sqlite/migrations/localSchemaMigrations.js +14 -0
  9. package/data/sqlite/migrations/localSchemaMigrations.js.map +1 -1
  10. package/data/sqlite/schema/documentRecordSchema.js +4 -6
  11. package/data/sqlite/schema/documentRecordSchema.js.map +1 -1
  12. package/data/sqlite/schema/index.d.ts +0 -17
  13. package/internal/validators/operation/containerMutations.d.ts +16 -16
  14. package/internal/validators/operation/documentMutations.d.ts +20 -20
  15. package/internal/validators/response/containerMutationError.d.ts +2 -2
  16. package/internal/validators/response/documentMutationError.d.ts +3 -2
  17. package/internal/validators/response/documentMutationError.js +5 -0
  18. package/internal/validators/response/documentMutationError.js.map +1 -1
  19. package/package.json +1 -1
  20. package/stores/documents/documentStore/sync/attachmentUploadFailure.js +0 -1
  21. package/stores/documents/documentStore/sync/attachmentUploadFailure.js.map +1 -1
  22. package/stores/documents/documentStore/sync/syncShared.js +0 -1
  23. package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
  24. package/workflows/documents/linkSet/linkSetBlobRewraps.d.ts +10 -4
  25. package/workflows/documents/linkSet/linkSetBlobRewraps.js +23 -11
  26. package/workflows/documents/linkSet/linkSetBlobRewraps.js.map +1 -1
  27. package/workflows/documents/linkSet/linkSetLegMachine.js +74 -0
  28. package/workflows/documents/linkSet/linkSetLegMachine.js.map +1 -0
  29. package/workflows/documents/linkSet/linkSetRemote.d.ts +4 -4
  30. package/workflows/documents/linkSet/linkSetRemote.js +96 -52
  31. package/workflows/documents/linkSet/linkSetRemote.js.map +1 -1
@@ -658,11 +658,11 @@ export declare const createDocumentOperation: Omit<{
658
658
  error: string;
659
659
  }>>;
660
660
  readonly 404: z.ZodObject<{
661
- code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
661
+ code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_link_attachments_changed">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
662
662
  error: z.ZodString;
663
663
  }, z.core.$loose>;
664
664
  readonly 409: z.ZodObject<{
665
- code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
665
+ code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_link_attachments_changed">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
666
666
  error: z.ZodString;
667
667
  }, z.core.$loose>;
668
668
  readonly 500: z.ZodType<{
@@ -821,11 +821,11 @@ export declare const createDocumentOperation: Omit<{
821
821
  error: string;
822
822
  }>>;
823
823
  readonly 404: z.ZodObject<{
824
- code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
824
+ code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_link_attachments_changed">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
825
825
  error: z.ZodString;
826
826
  }, z.core.$loose>;
827
827
  readonly 409: z.ZodObject<{
828
- code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
828
+ code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_link_attachments_changed">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
829
829
  error: z.ZodString;
830
830
  }, z.core.$loose>;
831
831
  readonly 500: z.ZodType<{
@@ -1220,11 +1220,11 @@ export declare const linkDocumentOperation: Omit<{
1220
1220
  error: string;
1221
1221
  }>>;
1222
1222
  readonly 404: z.ZodObject<{
1223
- code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
1223
+ code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_link_attachments_changed">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
1224
1224
  error: z.ZodString;
1225
1225
  }, z.core.$loose>;
1226
1226
  readonly 409: z.ZodObject<{
1227
- code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
1227
+ code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_link_attachments_changed">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
1228
1228
  error: z.ZodString;
1229
1229
  }, z.core.$loose>;
1230
1230
  readonly 500: z.ZodType<{
@@ -1340,11 +1340,11 @@ export declare const linkDocumentOperation: Omit<{
1340
1340
  error: string;
1341
1341
  }>>;
1342
1342
  readonly 404: z.ZodObject<{
1343
- code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
1343
+ code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_link_attachments_changed">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
1344
1344
  error: z.ZodString;
1345
1345
  }, z.core.$loose>;
1346
1346
  readonly 409: z.ZodObject<{
1347
- code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
1347
+ code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_link_attachments_changed">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
1348
1348
  error: z.ZodString;
1349
1349
  }, z.core.$loose>;
1350
1350
  readonly 500: z.ZodType<{
@@ -1739,11 +1739,11 @@ export declare const unlinkDocumentOperation: Omit<{
1739
1739
  error: string;
1740
1740
  }>>;
1741
1741
  readonly 404: z.ZodObject<{
1742
- code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
1742
+ code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_link_attachments_changed">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
1743
1743
  error: z.ZodString;
1744
1744
  }, z.core.$loose>;
1745
1745
  readonly 409: z.ZodObject<{
1746
- code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
1746
+ code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_link_attachments_changed">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
1747
1747
  error: z.ZodString;
1748
1748
  }, z.core.$loose>;
1749
1749
  readonly 500: z.ZodType<{
@@ -1859,11 +1859,11 @@ export declare const unlinkDocumentOperation: Omit<{
1859
1859
  error: string;
1860
1860
  }>>;
1861
1861
  readonly 404: z.ZodObject<{
1862
- code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
1862
+ code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_link_attachments_changed">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
1863
1863
  error: z.ZodString;
1864
1864
  }, z.core.$loose>;
1865
1865
  readonly 409: z.ZodObject<{
1866
- code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
1866
+ code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_link_attachments_changed">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
1867
1867
  error: z.ZodString;
1868
1868
  }, z.core.$loose>;
1869
1869
  readonly 500: z.ZodType<{
@@ -1987,11 +1987,11 @@ export declare const purgeDocumentOperation: Omit<{
1987
1987
  error: string;
1988
1988
  }>>;
1989
1989
  readonly 404: z.ZodObject<{
1990
- code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
1990
+ code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_link_attachments_changed">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
1991
1991
  error: z.ZodString;
1992
1992
  }, z.core.$loose>;
1993
1993
  readonly 409: z.ZodObject<{
1994
- code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
1994
+ code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_link_attachments_changed">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
1995
1995
  error: z.ZodString;
1996
1996
  }, z.core.$loose>;
1997
1997
  readonly 500: z.ZodType<{
@@ -2504,11 +2504,11 @@ export declare const purgeDocumentOperation: Omit<{
2504
2504
  error: string;
2505
2505
  }>>;
2506
2506
  readonly 404: z.ZodObject<{
2507
- code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
2507
+ code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_link_attachments_changed">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
2508
2508
  error: z.ZodString;
2509
2509
  }, z.core.$loose>;
2510
2510
  readonly 409: z.ZodObject<{
2511
- code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
2511
+ code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_link_attachments_changed">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
2512
2512
  error: z.ZodString;
2513
2513
  }, z.core.$loose>;
2514
2514
  readonly 500: z.ZodType<{
@@ -2594,11 +2594,11 @@ export declare const getDocumentPurgeProofOperation: Omit<{
2594
2594
  error: string;
2595
2595
  }>>;
2596
2596
  readonly 404: z.ZodObject<{
2597
- code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
2597
+ code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_link_attachments_changed">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
2598
2598
  error: z.ZodString;
2599
2599
  }, z.core.$loose>;
2600
2600
  readonly 409: z.ZodObject<{
2601
- code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
2601
+ code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_link_attachments_changed">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
2602
2602
  error: z.ZodString;
2603
2603
  }, z.core.$loose>;
2604
2604
  readonly 500: z.ZodType<{
@@ -3110,11 +3110,11 @@ export declare const getDocumentPurgeProofOperation: Omit<{
3110
3110
  error: string;
3111
3111
  }>>;
3112
3112
  readonly 404: z.ZodObject<{
3113
- code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
3113
+ code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_link_attachments_changed">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
3114
3114
  error: z.ZodString;
3115
3115
  }, z.core.$loose>;
3116
3116
  readonly 409: z.ZodObject<{
3117
- code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
3117
+ code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_link_attachments_changed">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
3118
3118
  error: z.ZodString;
3119
3119
  }, z.core.$loose>;
3120
3120
  readonly 500: z.ZodType<{
@@ -9,10 +9,10 @@ export declare const CONTAINER_MUTATION_ERROR_CODES: {
9
9
  readonly stateStale: "container_mutation_state_stale";
10
10
  };
11
11
  export declare const ContainerMutationBehaviorErrorCodeSchema: z.ZodLiteral<"container_mutation_state_stale" | "container_descendant_rekeys_required" | "container_ancestor_rekeys_required" | "container_descendant_rekeys_inaccessible" | "container_manifest_already_exists" | "container_path_too_deep">;
12
- export declare const ContainerMutationErrorCodeSchema: z.ZodUnion<readonly [z.ZodLiteral<"container_mutation_state_stale" | "container_descendant_rekeys_required" | "container_ancestor_rekeys_required" | "container_descendant_rekeys_inaccessible" | "container_manifest_already_exists" | "container_path_too_deep">, z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>]>;
12
+ export declare const ContainerMutationErrorCodeSchema: z.ZodUnion<readonly [z.ZodLiteral<"container_mutation_state_stale" | "container_descendant_rekeys_required" | "container_ancestor_rekeys_required" | "container_descendant_rekeys_inaccessible" | "container_manifest_already_exists" | "container_path_too_deep">, z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_link_attachments_changed">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>]>;
13
13
  export type ContainerMutationErrorCode = z.infer<typeof ContainerMutationErrorCodeSchema>;
14
14
  export declare const ContainerMutationFailureResponseSchema: z.ZodUnion<readonly [z.ZodObject<{
15
- code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"container_mutation_state_stale" | "container_descendant_rekeys_required" | "container_ancestor_rekeys_required" | "container_descendant_rekeys_inaccessible" | "container_manifest_already_exists" | "container_path_too_deep">, z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>]>>;
15
+ code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"container_mutation_state_stale" | "container_descendant_rekeys_required" | "container_ancestor_rekeys_required" | "container_descendant_rekeys_inaccessible" | "container_manifest_already_exists" | "container_path_too_deep">, z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_link_attachments_changed">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>]>>;
16
16
  error: z.ZodString;
17
17
  requiredContainerIds: z.ZodOptional<z.ZodCustom<string[], string[]>>;
18
18
  }, z.core.$loose>, z.ZodType<{
@@ -1,18 +1,19 @@
1
1
  import { z } from "zod";
2
2
  export declare const DOCUMENT_MUTATION_ERROR_CODES: {
3
3
  readonly containerUnavailable: "container_unavailable";
4
+ readonly linkAttachmentsChanged: "document_link_attachments_changed";
4
5
  readonly manifestAlreadyExists: "document_manifest_already_exists";
5
6
  readonly unlinkRotationBaselineStale: "document_unlink_rotation_baseline_stale";
6
7
  };
7
8
  export declare const DocumentMutationBehaviorErrorCodeSchema: z.ZodLiteral<"document_manifest_already_exists">;
8
- export declare const DocumentMutationErrorCodeSchema: z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>;
9
+ export declare const DocumentMutationErrorCodeSchema: z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_link_attachments_changed">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>;
9
10
  export type DocumentMutationErrorCode = z.infer<typeof DocumentMutationErrorCodeSchema>;
10
11
  /**
11
12
  * Document mutations retain uncoded terminal diagnostics while constraining
12
13
  * every behavior-bearing code to the shared registry above.
13
14
  */
14
15
  export declare const DocumentMutationFailureResponseSchema: z.ZodObject<{
15
- code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
16
+ code: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"document_manifest_already_exists">, z.ZodLiteral<"document_sync_checkpoint_coverage_conflict" | "document_sync_conflict" | "document_sync_descendant_rekeys_required" | "document_sync_state_stale" | "document_sync_update_id_conflict">, z.ZodLiteral<"document_not_found">, z.ZodLiteral<"container_unavailable">, z.ZodLiteral<"document_link_attachments_changed">, z.ZodLiteral<"document_unlink_rotation_baseline_stale">]>>;
16
17
  error: z.ZodString;
17
18
  }, z.core.$loose>;
18
19
  export type DocumentMutationFailureResponse = z.infer<typeof DocumentMutationFailureResponseSchema>;
@@ -6,6 +6,10 @@ export const DOCUMENT_MUTATION_ERROR_CODES = {
6
6
  // live row. Registered once here because the container envelope unions this
7
7
  // schema (see ContainerMutationErrorCodeSchema).
8
8
  containerUnavailable: CONTAINER_UNAVAILABLE_ERROR_CODE,
9
+ // A link or unlink's blob rewraps do not name exactly the document's active
10
+ // bindings. The client lists the attachments and retries; the binding check
11
+ // at commit stays authoritative on the server.
12
+ linkAttachmentsChanged: "document_link_attachments_changed",
9
13
  manifestAlreadyExists: "document_manifest_already_exists",
10
14
  // An unlink's rotation baseline does not cover a committed update. The
11
15
  // client proves the full history again and retries; the rotation and its
@@ -20,6 +24,7 @@ export const DocumentMutationErrorCodeSchema = z.union([
20
24
  DocumentSyncErrorCodeSchema,
21
25
  z.literal(DOCUMENT_NOT_FOUND_ERROR_CODE),
22
26
  z.literal(DOCUMENT_MUTATION_ERROR_CODES.containerUnavailable),
27
+ z.literal(DOCUMENT_MUTATION_ERROR_CODES.linkAttachmentsChanged),
23
28
  z.literal(DOCUMENT_MUTATION_ERROR_CODES.unlinkRotationBaselineStale),
24
29
  ]);
25
30
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"documentMutationError.js","sourceRoot":"","sources":["documentMutationError.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,gCAAgC,EAAE,MAAM,6BAA6B,CAAC;AAC/E,OAAO,EACL,6BAA6B,EAC7B,2BAA2B,GAC5B,MAAM,qBAAqB,CAAC;AAE7B,MAAM,CAAC,MAAM,6BAA6B,GAAG;IAC3C,2EAA2E;IAC3E,4EAA4E;IAC5E,iDAAiD;IACjD,oBAAoB,EAAE,gCAAgC;IACtD,qBAAqB,EAAE,kCAAkC;IACzD,uEAAuE;IACvE,yEAAyE;IACzE,mDAAmD;IACnD,2BAA2B,EAAE,yCAAyC;CAC9D,CAAC;AAEX,MAAM,CAAC,MAAM,uCAAuC,GAAG,CAAC,CAAC,OAAO,CAAC;IAC/D,6BAA6B,CAAC,qBAAqB;CACpD,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,+BAA+B,GAAG,CAAC,CAAC,KAAK,CAAC;IACrD,uCAAuC;IACvC,2BAA2B;IAC3B,CAAC,CAAC,OAAO,CAAC,6BAA6B,CAAC;IACxC,CAAC,CAAC,OAAO,CAAC,6BAA6B,CAAC,oBAAoB,CAAC;IAC7D,CAAC,CAAC,OAAO,CAAC,6BAA6B,CAAC,2BAA2B,CAAC;CACrE,CAAC,CAAC;AAMH;;;GAGG;AACH,MAAM,CAAC,MAAM,qCAAqC,GAAG,CAAC,CAAC,WAAW,CAAC;IACjE,IAAI,EAAE,+BAA+B,CAAC,QAAQ,EAAE;IAChD,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;CACzB,CAAC,CAAC","sourcesContent":["import { z } from \"zod\";\nimport { CONTAINER_UNAVAILABLE_ERROR_CODE } from \"./containerUnavailableError\";\nimport {\n DOCUMENT_NOT_FOUND_ERROR_CODE,\n DocumentSyncErrorCodeSchema,\n} from \"./documentSyncError\";\n\nexport const DOCUMENT_MUTATION_ERROR_CODES = {\n // Shared with container mutations: the cited container path element has no\n // live row. Registered once here because the container envelope unions this\n // schema (see ContainerMutationErrorCodeSchema).\n containerUnavailable: CONTAINER_UNAVAILABLE_ERROR_CODE,\n manifestAlreadyExists: \"document_manifest_already_exists\",\n // An unlink's rotation baseline does not cover a committed update. The\n // client proves the full history again and retries; the rotation and its\n // frontier check stay authoritative on the server.\n unlinkRotationBaselineStale: \"document_unlink_rotation_baseline_stale\",\n} as const;\n\nexport const DocumentMutationBehaviorErrorCodeSchema = z.literal([\n DOCUMENT_MUTATION_ERROR_CODES.manifestAlreadyExists,\n]);\n\nexport const DocumentMutationErrorCodeSchema = z.union([\n DocumentMutationBehaviorErrorCodeSchema,\n DocumentSyncErrorCodeSchema,\n z.literal(DOCUMENT_NOT_FOUND_ERROR_CODE),\n z.literal(DOCUMENT_MUTATION_ERROR_CODES.containerUnavailable),\n z.literal(DOCUMENT_MUTATION_ERROR_CODES.unlinkRotationBaselineStale),\n]);\n\nexport type DocumentMutationErrorCode = z.infer<\n typeof DocumentMutationErrorCodeSchema\n>;\n\n/**\n * Document mutations retain uncoded terminal diagnostics while constraining\n * every behavior-bearing code to the shared registry above.\n */\nexport const DocumentMutationFailureResponseSchema = z.looseObject({\n code: DocumentMutationErrorCodeSchema.optional(),\n error: z.string().min(1),\n});\n\nexport type DocumentMutationFailureResponse = z.infer<\n typeof DocumentMutationFailureResponseSchema\n>;\n"]}
1
+ {"version":3,"file":"documentMutationError.js","sourceRoot":"","sources":["documentMutationError.ts"],"names":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CUMENT_NOT_FOUND_ERROR_CODE,\n DocumentSyncErrorCodeSchema,\n} from \"./documentSyncError\";\n\nexport const DOCUMENT_MUTATION_ERROR_CODES = {\n // Shared with container mutations: the cited container path element has no\n // live row. Registered once here because the container envelope unions this\n // schema (see ContainerMutationErrorCodeSchema).\n containerUnavailable: CONTAINER_UNAVAILABLE_ERROR_CODE,\n // A link or unlink's blob rewraps do not name exactly the document's active\n // bindings. The client lists the attachments and retries; the binding check\n // at commit stays authoritative on the server.\n linkAttachmentsChanged: \"document_link_attachments_changed\",\n manifestAlreadyExists: \"document_manifest_already_exists\",\n // An unlink's rotation baseline does not cover a committed update. The\n // client proves the full history again and retries; the rotation and its\n // frontier check stay authoritative on the server.\n unlinkRotationBaselineStale: \"document_unlink_rotation_baseline_stale\",\n} as const;\n\nexport const DocumentMutationBehaviorErrorCodeSchema = z.literal([\n DOCUMENT_MUTATION_ERROR_CODES.manifestAlreadyExists,\n]);\n\nexport const DocumentMutationErrorCodeSchema = z.union([\n DocumentMutationBehaviorErrorCodeSchema,\n DocumentSyncErrorCodeSchema,\n z.literal(DOCUMENT_NOT_FOUND_ERROR_CODE),\n z.literal(DOCUMENT_MUTATION_ERROR_CODES.containerUnavailable),\n z.literal(DOCUMENT_MUTATION_ERROR_CODES.linkAttachmentsChanged),\n z.literal(DOCUMENT_MUTATION_ERROR_CODES.unlinkRotationBaselineStale),\n]);\n\nexport type DocumentMutationErrorCode = z.infer<\n typeof DocumentMutationErrorCodeSchema\n>;\n\n/**\n * Document mutations retain uncoded terminal diagnostics while constraining\n * every behavior-bearing code to the shared registry above.\n */\nexport const DocumentMutationFailureResponseSchema = z.looseObject({\n code: DocumentMutationErrorCodeSchema.optional(),\n error: z.string().min(1),\n});\n\nexport type DocumentMutationFailureResponse = z.infer<\n typeof DocumentMutationFailureResponseSchema\n>;\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/client-sdk",
3
- "version": "0.1.238",
3
+ "version": "0.1.240",
4
4
  "description": "React-free Tearleads client runtime: local SQLite persistence, keys, sync, encrypted blobs, and domain workflows.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -17,7 +17,6 @@ export function reportAttachmentUploadFailure(input) {
17
17
  await new DocumentRecordRepository(lockedExecSql).recordDocumentSyncFailure({ appKind: DOCUMENTS_APP_KIND, localId: input.state.localId }, {
18
18
  attemptedAt: new Date().toISOString(),
19
19
  message: error.message,
20
- status: null,
21
20
  });
22
21
  }).catch(() => undefined);
23
22
  }
@@ -1 +1 @@
1
- {"version":3,"file":"attachmentUploadFailure.js","sourceRoot":"","sources":["attachmentUploadFailure.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,wBAAwB,EAExB,wBAAwB,GACzB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAEL,iCAAiC,GAClC,MAAM,0CAA0C,CAAC;AAElD,OAAO,EAEL,oCAAoC,GACrC,MAAM,kBAAkB,CAAC;AAE1B,MAAM,UAAU,6BAA6B,CAAC,KAM7C;IACC,MAAM,KAAK,GAAG,iCAAiC,CAC7C,KAAK,CAAC,iBAAiB,EACvB,KAAK,CAAC,KAAK,CACZ,CAAC;IACF,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC7B,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,cAAc,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;IAC5D,4EAA4E;IAC5E,sEAAsE;IACtE,yEAAyE;IACzE,yEAAyE;IACzE,kCAAkC;IAClC,KAAK,wBAAwB,CAC3B,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,EACjC,KAAK,EAAE,aAAa,EAAE,EAAE;QACtB,IACE,CAAC,oCAAoC,CACnC,KAAK,CAAC,KAAK,EACX,KAAK,CAAC,oBAAoB,CAC3B,EACD,CAAC;YACD,OAAO;QACT,CAAC;QACD,MAAM,IAAI,wBAAwB,CAChC,aAAa,CACd,CAAC,yBAAyB,CACzB,EAAE,OAAO,EAAE,kBAAkB,EAAE,OAAO,EAAE,KAAK,CAAC,KAAK,CAAC,OAAO,EAAE,EAC7D;YACE,WAAW,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACrC,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,MAAM,EAAE,IAAI;SACb,CACF,CAAC;IACJ,CAAC,CACF,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;AAC3B,CAAC","sourcesContent":["import {\n DOCUMENTS_APP_KIND,\n DocumentRecordRepository,\n type PendingAttachmentRecord,\n runSerializedSqlMutation,\n} from \"../../../../workflows/documents\";\nimport {\n type AttachmentUploadLaneReporter,\n createAttachmentUploadFailedError,\n} from \"../attachmentUpload/attachmentUploadLane\";\nimport type { DocumentStoreState } from \"../state\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\n\nexport function reportAttachmentUploadFailure(input: {\n attachmentGeneration: DocumentStoreSyncGeneration;\n error: unknown;\n pendingAttachment: PendingAttachmentRecord;\n state: DocumentStoreState;\n uploadLane: AttachmentUploadLaneReporter;\n}): void {\n const error = createAttachmentUploadFailedError(\n input.pendingAttachment,\n input.error,\n );\n input.uploadLane.fail(error);\n input.state.runtime.util.log(`Documents: ${error.message}`);\n // Surface the stuck upload in the write queue; a later successful sync pass\n // for the document clears the record. Validated inside the serialized\n // mutation: a teardown (reset/discard) racing this pass just cleared the\n // failure row, and re-recording it would resurrect a phantom queue entry\n // for work that no longer exists.\n void runSerializedSqlMutation(\n input.state.runtime.infra.execSql,\n async (lockedExecSql) => {\n if (\n !isDocumentStoreSyncGenerationCurrent(\n input.state,\n input.attachmentGeneration,\n )\n ) {\n return;\n }\n await new DocumentRecordRepository(\n lockedExecSql,\n ).recordDocumentSyncFailure(\n { appKind: DOCUMENTS_APP_KIND, localId: input.state.localId },\n {\n attemptedAt: new Date().toISOString(),\n message: error.message,\n status: null,\n },\n );\n },\n ).catch(() => undefined);\n}\n"]}
1
+ {"version":3,"file":"attachmentUploadFailure.js","sourceRoot":"","sources":["attachmentUploadFailure.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,wBAAwB,EAExB,wBAAwB,GACzB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAEL,iCAAiC,GAClC,MAAM,0CAA0C,CAAC;AAElD,OAAO,EAEL,oCAAoC,GACrC,MAAM,kBAAkB,CAAC;AAE1B,MAAM,UAAU,6BAA6B,CAAC,KAM7C;IACC,MAAM,KAAK,GAAG,iCAAiC,CAC7C,KAAK,CAAC,iBAAiB,EACvB,KAAK,CAAC,KAAK,CACZ,CAAC;IACF,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC7B,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,cAAc,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;IAC5D,4EAA4E;IAC5E,sEAAsE;IACtE,yEAAyE;IACzE,yEAAyE;IACzE,kCAAkC;IAClC,KAAK,wBAAwB,CAC3B,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,EACjC,KAAK,EAAE,aAAa,EAAE,EAAE;QACtB,IACE,CAAC,oCAAoC,CACnC,KAAK,CAAC,KAAK,EACX,KAAK,CAAC,oBAAoB,CAC3B,EACD,CAAC;YACD,OAAO;QACT,CAAC;QACD,MAAM,IAAI,wBAAwB,CAChC,aAAa,CACd,CAAC,yBAAyB,CACzB,EAAE,OAAO,EAAE,kBAAkB,EAAE,OAAO,EAAE,KAAK,CAAC,KAAK,CAAC,OAAO,EAAE,EAC7D;YACE,WAAW,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACrC,OAAO,EAAE,KAAK,CAAC,OAAO;SACvB,CACF,CAAC;IACJ,CAAC,CACF,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;AAC3B,CAAC","sourcesContent":["import {\n DOCUMENTS_APP_KIND,\n DocumentRecordRepository,\n type PendingAttachmentRecord,\n runSerializedSqlMutation,\n} from \"../../../../workflows/documents\";\nimport {\n type AttachmentUploadLaneReporter,\n createAttachmentUploadFailedError,\n} from \"../attachmentUpload/attachmentUploadLane\";\nimport type { DocumentStoreState } from \"../state\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\n\nexport function reportAttachmentUploadFailure(input: {\n attachmentGeneration: DocumentStoreSyncGeneration;\n error: unknown;\n pendingAttachment: PendingAttachmentRecord;\n state: DocumentStoreState;\n uploadLane: AttachmentUploadLaneReporter;\n}): void {\n const error = createAttachmentUploadFailedError(\n input.pendingAttachment,\n input.error,\n );\n input.uploadLane.fail(error);\n input.state.runtime.util.log(`Documents: ${error.message}`);\n // Surface the stuck upload in the write queue; a later successful sync pass\n // for the document clears the record. Validated inside the serialized\n // mutation: a teardown (reset/discard) racing this pass just cleared the\n // failure row, and re-recording it would resurrect a phantom queue entry\n // for work that no longer exists.\n void runSerializedSqlMutation(\n input.state.runtime.infra.execSql,\n async (lockedExecSql) => {\n if (\n !isDocumentStoreSyncGenerationCurrent(\n input.state,\n input.attachmentGeneration,\n )\n ) {\n return;\n }\n await new DocumentRecordRepository(\n lockedExecSql,\n ).recordDocumentSyncFailure(\n { appKind: DOCUMENTS_APP_KIND, localId: input.state.localId },\n {\n attemptedAt: new Date().toISOString(),\n message: error.message,\n },\n );\n },\n ).catch(() => undefined);\n}\n"]}
@@ -70,7 +70,6 @@ function documentSyncFailureHandler(input) {
70
70
  await new DocumentRecordRepository(lockedExecSql).recordDocumentSyncFailure({ appKind: DOCUMENTS_APP_KIND, localId: state.localId }, {
71
71
  attemptedAt: new Date().toISOString(),
72
72
  message: input.describeFailure(failure),
73
- status: failure.status,
74
73
  });
75
74
  });
76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CAAC,CAAC;QAC/C,CAAC;QACD,OAAO,SAAS,EAAE,MAAM,IAAI,KAAK,CAAC,MAAM,IAAI,UAAU,CAAC;IACzD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { deriveStableDocumentId } from \"../../../../data/documents/shared/stableDocumentId\";\nimport {\n DOCUMENTS_APP_KIND,\n type DocumentRecord,\n DocumentRecordRepository,\n type DocumentSyncUpdateIsolationError,\n describeDocumentRevalidationFailure,\n describeDocumentSyncSubmitFailure,\n type PendingUpdateRecord,\n RemoteDocumentService,\n resolveDocumentCreateAuthor,\n runSerializedSqlMutation,\n} from \"../../../../workflows/documents\";\nimport { reportDocumentSyncQuarantine } from \"../../../../workflows/documents/sync/reportDocumentSyncQuarantine\";\nimport type { PrincipalPolicyOperation } from \"../../../../workflows/principals/principalPolicyService\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n type EncapsulationKeyPair,\n markDocumentStoreRemoved,\n} from \"../state\";\nimport { installDocumentWriterProjection } from \"../writerProjectionGeneration\";\nimport {\n type CreateSeed,\n type DeferredBindSeed,\n persistCreatedRemoteDocument,\n} from \"./createdDocumentPersistence\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\nimport { recordPlannedRemoteDocumentId } from \"./syncRemoteSignals\";\n\n/**\n * Record a refused read-only revalidation on this document's failure row, so\n * a document that can never refresh stops failing silently (edge-case row\n * 13). 403s stay suppressed on purpose — a read-only 403 must never flag\n * unattempted local edits (row 9) — and the row clears on the next clean\n * pass like every other sync failure.\n */\nexport function documentRevalidationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentRevalidationFailure,\n generation,\n state,\n suppressForbidden: true,\n });\n}\n\n/**\n * Record a terminal submit failure on this document's write-queue row. Shared\n * by every store pass that can submit queued writes (create and sync), so\n * re-key exhaustion and denial failures surface no matter which pass hits\n * them first.\n */\nexport function documentTerminalSubmitFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentSyncSubmitFailure,\n generation,\n state,\n });\n}\n\n/** Persist quarantine and report its Error through the host's diagnostics. */\nexport function documentIncomingUpdateIsolationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n const recordFailure = documentSyncFailureHandler({\n describeFailure: (failure) => failure.message,\n generation,\n state,\n });\n return async (failure: DocumentSyncUpdateIsolationError) => {\n await recordFailure({ message: failure.message, status: null });\n if (generation && !isDocumentStoreSyncGenerationCurrent(state, generation))\n return;\n reportDocumentSyncQuarantine(\n generation?.currentDoc ?? state.doc ?? state,\n state.runtime.util.logError,\n failure,\n );\n };\n}\n\n/**\n * The generation recheck runs INSIDE the serialized mutation (like the\n * attachment failure path): a teardown (discard/reset) that wins the ordering\n * deletes this document's rows first and invalidates the generation, so a\n * stale handler can never resurrect a deleted or orphan failure row\n * afterwards.\n */\nfunction documentSyncFailureHandler(input: {\n describeFailure: (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => string;\n generation: DocumentStoreSyncGeneration | undefined;\n state: DocumentStoreState;\n suppressForbidden?: boolean;\n}) {\n const { generation, state } = input;\n return async (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => {\n if (input.suppressForbidden && failure.status === 403) {\n return;\n }\n\n await runSerializedSqlMutation(\n generation?.execSql ?? state.runtime.infra.execSql,\n async (lockedExecSql) => {\n if (\n generation &&\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n return;\n }\n await new DocumentRecordRepository(\n lockedExecSql,\n ).recordDocumentSyncFailure(\n { appKind: DOCUMENTS_APP_KIND, localId: state.localId },\n {\n attemptedAt: new Date().toISOString(),\n message: input.describeFailure(failure),\n status: failure.status,\n },\n );\n },\n );\n };\n}\n\nfunction hasPersistedRemoteDocumentSyncState(record: DocumentRecord): boolean {\n return (\n record.lastCommitLsn !== null &&\n record.contentKeyBundle !== null &&\n record.documentKekTargets !== null &&\n record.documentManifestBundle !== null\n );\n}\n\nexport function shouldSkipCleanScheduledDocumentSync(input: {\n currentRecord: DocumentRecord;\n pendingUpdates: readonly PendingUpdateRecord[];\n state: DocumentStoreState;\n}): boolean {\n return (\n input.pendingUpdates.length === 0 &&\n input.state.pendingAttachments.length === 0 &&\n input.state.pullContinuation === null &&\n !input.currentRecord.pullContinuationRecoveryRequired &&\n !input.state.remoteUpdatePending &&\n hasPersistedRemoteDocumentSyncState(input.currentRecord)\n );\n}\n\n/**\n * True when the store's container exists locally but has not been created on\n * the server yet (its own create intent is still pending). Creating a document\n * inside it would 404 on the container writer projection and surface a\n * spurious sync error; the container-contents lane re-arms document sync once\n * the container lands. An unknown or unqueryable container resolves false so\n * store-level consumers without container persistence keep creating eagerly.\n */\nexport async function isContainerAwaitingRemoteCreate(\n state: DocumentStoreState,\n): Promise<boolean> {\n const containerId = state.runtime.state.containerId;\n if (!containerId) {\n return false;\n }\n\n try {\n const rows = await state.runtime.infra.execSql(\n \"SELECT server_created_at FROM containers WHERE id = :containerId\",\n { \":containerId\": containerId },\n );\n const row = rows[0];\n return row !== undefined && Reflect.get(row, \"server_created_at\") == null;\n } catch {\n return false;\n }\n}\n\nasync function hasDurableDocumentForCreate(\n state: DocumentStoreState,\n isCurrent: () => boolean,\n): Promise<boolean> {\n // A bulk import can leave this store queued long after trash purged its\n // durable row. The persistence guard runs too late to prevent an orphaned\n // remote create, so check existence before beginning the network work.\n const record = await state.persistence.loadDocument(\n state.runtime.infra.execSql,\n state.localId,\n );\n if (!isCurrent()) return false;\n if (record) return true;\n markDocumentStoreRemoved(state);\n return false;\n}\n\nexport async function ensureRemoteDocument(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n nextRecord: DocumentRecord | null,\n encapsulationKeyPair: EncapsulationKeyPair,\n policyOperation: PrincipalPolicyOperation,\n generation?: DocumentStoreSyncGeneration,\n seed?: CreateSeed,\n deferredSeed?: DeferredBindSeed,\n): Promise<DocumentRecord | null> {\n const generationIsCurrent = () =>\n !generation || isDocumentStoreSyncGenerationCurrent(state, generation);\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n if (nextRecord?.documentId) {\n return nextRecord;\n }\n\n const runtime = state.runtime;\n if (!runtime.state.containerId) {\n runtime.util.log(\n \"Documents: cannot create a remote document without a container.\",\n );\n // A local-only document with no container scope (e.g. a last-link orphan\n // from a tombstone cascade, docs/sync-edge-cases.md row 3) can never\n // create; record the stuck state durably so the write queue surfaces it\n // instead of this lane going silent on every trigger.\n await documentTerminalSubmitFailureHandler(\n state,\n generation,\n )({\n message: \"Local document has no container for its remote create\",\n status: null,\n });\n return nextRecord;\n }\n\n const author = resolveDocumentCreateAuthor(runtime);\n if (!author) {\n runtime.util.log(\n \"Documents: skipped remote create because the writer context is unavailable.\",\n );\n return nextRecord;\n }\n\n const documentId =\n nextRecord?.recoveryDocumentId ??\n (await deriveStableDocumentId(state.localId));\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n // Hints for the document can arrive before the create's response installs\n // its id; see recordPlannedRemoteDocumentId.\n recordPlannedRemoteDocumentId(state, documentId);\n\n if (!(await hasDurableDocumentForCreate(state, generationIsCurrent)))\n return state.record;\n\n const writerProjectionGeneration = state.writerProjectionGeneration;\n // The runtime this create read before its awaits, with the pass's key.\n const remoteDocuments = new RemoteDocumentService({\n api: runtime.apiClient,\n encapsulationSecretKey: encapsulationKeyPair.secretKey,\n execSql: runtime.infra.execSql,\n isRemoteSyncBlocked: runtime.util.isRemoteSyncBlocked,\n });\n const created = await remoteDocuments.createRemoteDocument({\n author,\n containerId: runtime.state.containerId,\n deferredSeedUpdate: seed ? undefined : deferredSeed?.update,\n // Derive the remote id from the stable local id so a retry after a lost\n // create response re-sends the same id and adopts the existing remote\n // document instead of creating a duplicate.\n documentId,\n onTerminalSubmitFailure: documentTerminalSubmitFailureHandler(\n state,\n generation,\n ),\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n seedUpdate: seed?.update,\n stillCurrent: generationIsCurrent,\n warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer({\n operation: policyOperation,\n }),\n });\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n if (!created) {\n return nextRecord;\n }\n\n return chainIdentityWrite(state, async () => {\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n // A concurrent relink (e.g. live duplicate-facade resolution) may have\n // assigned this store a different remote identity while the create round\n // trip was in flight. That identity wins: persisting the created one here\n // would clobber the relink. The just-created remote document is left an\n // orphan, the same benign outcome as a lost create response.\n const liveDocumentId = state.record?.documentId;\n if (liveDocumentId && liveDocumentId !== created.documentId) {\n return state.record;\n }\n\n runtime.util.log(`Created document: ${created.documentId}`);\n installDocumentWriterProjection(\n state,\n created.writerProjection,\n writerProjectionGeneration,\n );\n\n // This persist is a remote-identity write (documentId + content keys), not a\n // content change. It runs after a network round trip, during which the user\n // may have kept typing into a brand-new note. The Loro doc is mutated\n // asynchronously on the write chain, so it can lag the optimistic snapshot;\n // re-deriving text/structured fields from the doc here would republish that\n // stale read over the live editor value and drop the just-typed characters\n // (the new-note \"type immediately\" race). Preserve the optimistic snapshot —\n // documentId/keys still propagate via state.record, independent of the\n // snapshot text — matching finalizeDocumentSync and the keystroke writes.\n // A committed seed settles its row in this persist, so the pass needs no\n // sync request.\n const persisted = await persistCreatedRemoteDocument({\n created,\n currentDoc,\n generation,\n seed,\n state,\n });\n if (persisted && created.deferredSeed) {\n deferredSeed?.onSigned(created.deferredSeed);\n }\n return persisted?.record ?? state.record ?? nextRecord;\n });\n}\n"]}
1
+ {"version":3,"file":"syncShared.js","sourceRoot":"","sources":["syncShared.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,oDAAoD,CAAC;AAC5F,OAAO,EACL,kBAAkB,EAElB,wBAAwB,EAExB,mCAAmC,EACnC,iCAAiC,EAEjC,qBAAqB,EACrB,2BAA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AAC;IACpB,CAAC;IAED,OAAO,kBAAkB,CAAC,KAAK,EAAE,KAAK,IAAI,EAAE;QAC1C,IAAI,CAAC,mBAAmB,EAAE;YAAE,OAAO,KAAK,CAAC,MAAM,IAAI,UAAU,CAAC;QAE9D,uEAAuE;QACvE,yEAAyE;QACzE,0EAA0E;QAC1E,wEAAwE;QACxE,6DAA6D;QAC7D,MAAM,cAAc,GAAG,KAAK,CAAC,MAAM,EAAE,UAAU,CAAC;QAChD,IAAI,cAAc,IAAI,cAAc,KAAK,OAAO,CAAC,UAAU,EAAE,CAAC;YAC5D,OAAO,KAAK,CAAC,MAAM,CAAC;QACtB,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,qBAAqB,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC;QAC5D,+BAA+B,CAC7B,KAAK,EACL,OAAO,CAAC,gBAAgB,EACxB,0BAA0B,CAC3B,CAAC;QAEF,6EAA6E;QAC7E,4EAA4E;QAC5E,sEAAsE;QACtE,4EAA4E;QAC5E,4EAA4E;QAC5E,2EAA2E;QAC3E,6EAA6E;QAC7E,uEAAuE;QACvE,0EAA0E;QAC1E,yEAAyE;QACzE,gBAAgB;QAChB,MAAM,SAAS,GAAG,MAAM,4BAA4B,CAAC;YACnD,OAAO;YACP,UAAU;YACV,UAAU;YACV,IAAI;YACJ,KAAK;SACN,CAAC,CAAC;QACH,IAAI,SAAS,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;YACtC,YAAY,EAAE,QAAQ,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;QAC/C,CAAC;QACD,OAAO,SAAS,EAAE,MAAM,IAAI,KAAK,CAAC,MAAM,IAAI,UAAU,CAAC;IACzD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { deriveStableDocumentId } from \"../../../../data/documents/shared/stableDocumentId\";\nimport {\n DOCUMENTS_APP_KIND,\n type DocumentRecord,\n DocumentRecordRepository,\n type DocumentSyncUpdateIsolationError,\n describeDocumentRevalidationFailure,\n describeDocumentSyncSubmitFailure,\n type PendingUpdateRecord,\n RemoteDocumentService,\n resolveDocumentCreateAuthor,\n runSerializedSqlMutation,\n} from \"../../../../workflows/documents\";\nimport { reportDocumentSyncQuarantine } from \"../../../../workflows/documents/sync/reportDocumentSyncQuarantine\";\nimport type { PrincipalPolicyOperation } from \"../../../../workflows/principals/principalPolicyService\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n type EncapsulationKeyPair,\n markDocumentStoreRemoved,\n} from \"../state\";\nimport { installDocumentWriterProjection } from \"../writerProjectionGeneration\";\nimport {\n type CreateSeed,\n type DeferredBindSeed,\n persistCreatedRemoteDocument,\n} from \"./createdDocumentPersistence\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\nimport { recordPlannedRemoteDocumentId } from \"./syncRemoteSignals\";\n\n/**\n * Record a refused read-only revalidation on this document's failure row, so\n * a document that can never refresh stops failing silently (edge-case row\n * 13). 403s stay suppressed on purpose — a read-only 403 must never flag\n * unattempted local edits (row 9) — and the row clears on the next clean\n * pass like every other sync failure.\n */\nexport function documentRevalidationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentRevalidationFailure,\n generation,\n state,\n suppressForbidden: true,\n });\n}\n\n/**\n * Record a terminal submit failure on this document's write-queue row. Shared\n * by every store pass that can submit queued writes (create and sync), so\n * re-key exhaustion and denial failures surface no matter which pass hits\n * them first.\n */\nexport function documentTerminalSubmitFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentSyncSubmitFailure,\n generation,\n state,\n });\n}\n\n/** Persist quarantine and report its Error through the host's diagnostics. */\nexport function documentIncomingUpdateIsolationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n const recordFailure = documentSyncFailureHandler({\n describeFailure: (failure) => failure.message,\n generation,\n state,\n });\n return async (failure: DocumentSyncUpdateIsolationError) => {\n await recordFailure({ message: failure.message, status: null });\n if (generation && !isDocumentStoreSyncGenerationCurrent(state, generation))\n return;\n reportDocumentSyncQuarantine(\n generation?.currentDoc ?? state.doc ?? state,\n state.runtime.util.logError,\n failure,\n );\n };\n}\n\n/**\n * The generation recheck runs INSIDE the serialized mutation (like the\n * attachment failure path): a teardown (discard/reset) that wins the ordering\n * deletes this document's rows first and invalidates the generation, so a\n * stale handler can never resurrect a deleted or orphan failure row\n * afterwards.\n */\nfunction documentSyncFailureHandler(input: {\n describeFailure: (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => string;\n generation: DocumentStoreSyncGeneration | undefined;\n state: DocumentStoreState;\n suppressForbidden?: boolean;\n}) {\n const { generation, state } = input;\n return async (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => {\n if (input.suppressForbidden && failure.status === 403) {\n return;\n }\n\n await runSerializedSqlMutation(\n generation?.execSql ?? state.runtime.infra.execSql,\n async (lockedExecSql) => {\n if (\n generation &&\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n return;\n }\n await new DocumentRecordRepository(\n lockedExecSql,\n ).recordDocumentSyncFailure(\n { appKind: DOCUMENTS_APP_KIND, localId: state.localId },\n {\n attemptedAt: new Date().toISOString(),\n message: input.describeFailure(failure),\n },\n );\n },\n );\n };\n}\n\nfunction hasPersistedRemoteDocumentSyncState(record: DocumentRecord): boolean {\n return (\n record.lastCommitLsn !== null &&\n record.contentKeyBundle !== null &&\n record.documentKekTargets !== null &&\n record.documentManifestBundle !== null\n );\n}\n\nexport function shouldSkipCleanScheduledDocumentSync(input: {\n currentRecord: DocumentRecord;\n pendingUpdates: readonly PendingUpdateRecord[];\n state: DocumentStoreState;\n}): boolean {\n return (\n input.pendingUpdates.length === 0 &&\n input.state.pendingAttachments.length === 0 &&\n input.state.pullContinuation === null &&\n !input.currentRecord.pullContinuationRecoveryRequired &&\n !input.state.remoteUpdatePending &&\n hasPersistedRemoteDocumentSyncState(input.currentRecord)\n );\n}\n\n/**\n * True when the store's container exists locally but has not been created on\n * the server yet (its own create intent is still pending). Creating a document\n * inside it would 404 on the container writer projection and surface a\n * spurious sync error; the container-contents lane re-arms document sync once\n * the container lands. An unknown or unqueryable container resolves false so\n * store-level consumers without container persistence keep creating eagerly.\n */\nexport async function isContainerAwaitingRemoteCreate(\n state: DocumentStoreState,\n): Promise<boolean> {\n const containerId = state.runtime.state.containerId;\n if (!containerId) {\n return false;\n }\n\n try {\n const rows = await state.runtime.infra.execSql(\n \"SELECT server_created_at FROM containers WHERE id = :containerId\",\n { \":containerId\": containerId },\n );\n const row = rows[0];\n return row !== undefined && Reflect.get(row, \"server_created_at\") == null;\n } catch {\n return false;\n }\n}\n\nasync function hasDurableDocumentForCreate(\n state: DocumentStoreState,\n isCurrent: () => boolean,\n): Promise<boolean> {\n // A bulk import can leave this store queued long after trash purged its\n // durable row. The persistence guard runs too late to prevent an orphaned\n // remote create, so check existence before beginning the network work.\n const record = await state.persistence.loadDocument(\n state.runtime.infra.execSql,\n state.localId,\n );\n if (!isCurrent()) return false;\n if (record) return true;\n markDocumentStoreRemoved(state);\n return false;\n}\n\nexport async function ensureRemoteDocument(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n nextRecord: DocumentRecord | null,\n encapsulationKeyPair: EncapsulationKeyPair,\n policyOperation: PrincipalPolicyOperation,\n generation?: DocumentStoreSyncGeneration,\n seed?: CreateSeed,\n deferredSeed?: DeferredBindSeed,\n): Promise<DocumentRecord | null> {\n const generationIsCurrent = () =>\n !generation || isDocumentStoreSyncGenerationCurrent(state, generation);\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n if (nextRecord?.documentId) {\n return nextRecord;\n }\n\n const runtime = state.runtime;\n if (!runtime.state.containerId) {\n runtime.util.log(\n \"Documents: cannot create a remote document without a container.\",\n );\n // A local-only document with no container scope (e.g. a last-link orphan\n // from a tombstone cascade, docs/sync-edge-cases.md row 3) can never\n // create; record the stuck state durably so the write queue surfaces it\n // instead of this lane going silent on every trigger.\n await documentTerminalSubmitFailureHandler(\n state,\n generation,\n )({\n message: \"Local document has no container for its remote create\",\n status: null,\n });\n return nextRecord;\n }\n\n const author = resolveDocumentCreateAuthor(runtime);\n if (!author) {\n runtime.util.log(\n \"Documents: skipped remote create because the writer context is unavailable.\",\n );\n return nextRecord;\n }\n\n const documentId =\n nextRecord?.recoveryDocumentId ??\n (await deriveStableDocumentId(state.localId));\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n // Hints for the document can arrive before the create's response installs\n // its id; see recordPlannedRemoteDocumentId.\n recordPlannedRemoteDocumentId(state, documentId);\n\n if (!(await hasDurableDocumentForCreate(state, generationIsCurrent)))\n return state.record;\n\n const writerProjectionGeneration = state.writerProjectionGeneration;\n // The runtime this create read before its awaits, with the pass's key.\n const remoteDocuments = new RemoteDocumentService({\n api: runtime.apiClient,\n encapsulationSecretKey: encapsulationKeyPair.secretKey,\n execSql: runtime.infra.execSql,\n isRemoteSyncBlocked: runtime.util.isRemoteSyncBlocked,\n });\n const created = await remoteDocuments.createRemoteDocument({\n author,\n containerId: runtime.state.containerId,\n deferredSeedUpdate: seed ? undefined : deferredSeed?.update,\n // Derive the remote id from the stable local id so a retry after a lost\n // create response re-sends the same id and adopts the existing remote\n // document instead of creating a duplicate.\n documentId,\n onTerminalSubmitFailure: documentTerminalSubmitFailureHandler(\n state,\n generation,\n ),\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n seedUpdate: seed?.update,\n stillCurrent: generationIsCurrent,\n warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer({\n operation: policyOperation,\n }),\n });\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n if (!created) {\n return nextRecord;\n }\n\n return chainIdentityWrite(state, async () => {\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n // A concurrent relink (e.g. live duplicate-facade resolution) may have\n // assigned this store a different remote identity while the create round\n // trip was in flight. That identity wins: persisting the created one here\n // would clobber the relink. The just-created remote document is left an\n // orphan, the same benign outcome as a lost create response.\n const liveDocumentId = state.record?.documentId;\n if (liveDocumentId && liveDocumentId !== created.documentId) {\n return state.record;\n }\n\n runtime.util.log(`Created document: ${created.documentId}`);\n installDocumentWriterProjection(\n state,\n created.writerProjection,\n writerProjectionGeneration,\n );\n\n // This persist is a remote-identity write (documentId + content keys), not a\n // content change. It runs after a network round trip, during which the user\n // may have kept typing into a brand-new note. The Loro doc is mutated\n // asynchronously on the write chain, so it can lag the optimistic snapshot;\n // re-deriving text/structured fields from the doc here would republish that\n // stale read over the live editor value and drop the just-typed characters\n // (the new-note \"type immediately\" race). Preserve the optimistic snapshot —\n // documentId/keys still propagate via state.record, independent of the\n // snapshot text — matching finalizeDocumentSync and the keystroke writes.\n // A committed seed settles its row in this persist, so the pass needs no\n // sync request.\n const persisted = await persistCreatedRemoteDocument({\n created,\n currentDoc,\n generation,\n seed,\n state,\n });\n if (persisted && created.deferredSeed) {\n deferredSeed?.onSigned(created.deferredSeed);\n }\n return persisted?.record ?? state.record ?? nextRecord;\n });\n}\n"]}
@@ -19,19 +19,25 @@ export declare function createLinkSetAttachmentReuse(): LinkSetAttachmentReuse;
19
19
  * was authenticated or wrapped by this device before that leg signed it, so a
20
20
  * reuse propagates no key to a new scope; any target the previous leg did not
21
21
  * wrap returns null and the leg lists and authenticates as usual. A bind or
22
- * detach in between, a content-key epoch change, or a re-entered retired
23
- * target (the API keeps its stored wrap over the fresh one) makes the API
24
- * refuse with an uncoded 409, and the caller re-lists once.
22
+ * detach in between makes the API refuse with a coded 409
23
+ * (`document_link_attachments_changed`); a content-key epoch change or a
24
+ * re-entered retired target (the API keeps its stored wrap over the fresh one)
25
+ * with an uncoded one. The caller re-lists once.
25
26
  */
26
27
  export declare function reuseCommittedBlobRewraps(input: {
27
28
  committed: BlobRewraps;
28
29
  documentId: string;
29
30
  targets: readonly DocumentContentKeyTarget[];
30
31
  }): BlobRewraps | null;
31
- /** Authenticate the existing bytes before propagating their DEK to a new scope. */
32
+ /**
33
+ * Authenticate the existing bytes before propagating their DEK to a new scope.
34
+ * `refreshListing` bypasses a cached listing, after the server refused a leg
35
+ * because its attachments changed.
36
+ */
32
37
  export declare function prepareDocumentLinkBlobRewraps(input: {
33
38
  apiClient: DocumentLinkSetMutationApi;
34
39
  execSql: ExecSql;
40
+ refreshListing?: boolean | undefined;
35
41
  targetContainerProjection: ContainerWriterProjectionResponse;
36
42
  targetSecretKey: Uint8Array;
37
43
  targets: readonly DocumentContentKeyTarget[];
@@ -18,9 +18,10 @@ export function createLinkSetAttachmentReuse() {
18
18
  * was authenticated or wrapped by this device before that leg signed it, so a
19
19
  * reuse propagates no key to a new scope; any target the previous leg did not
20
20
  * wrap returns null and the leg lists and authenticates as usual. A bind or
21
- * detach in between, a content-key epoch change, or a re-entered retired
22
- * target (the API keeps its stored wrap over the fresh one) makes the API
23
- * refuse with an uncoded 409, and the caller re-lists once.
21
+ * detach in between makes the API refuse with a coded 409
22
+ * (`document_link_attachments_changed`); a content-key epoch change or a
23
+ * re-entered retired target (the API keeps its stored wrap over the fresh one)
24
+ * with an uncoded one. The caller re-lists once.
24
25
  */
25
26
  export function reuseCommittedBlobRewraps(input) {
26
27
  const rewraps = [];
@@ -52,16 +53,14 @@ export function reuseCommittedBlobRewraps(input) {
52
53
  }
53
54
  return rewraps.sort(compareBlobIds);
54
55
  }
55
- /** Authenticate the existing bytes before propagating their DEK to a new scope. */
56
+ /**
57
+ * Authenticate the existing bytes before propagating their DEK to a new scope.
58
+ * `refreshListing` bypasses a cached listing, after the server refused a leg
59
+ * because its attachments changed.
60
+ */
56
61
  export async function prepareDocumentLinkBlobRewraps(input) {
57
62
  const documentId = input.writerProjection.documentId;
58
- const bindings = await input.apiClient.listDocumentAttachments(documentId);
59
- // The API refuses the link unless every active binding is rewrapped, so an
60
- // unavailable listing (offline, or a 409 while a bind is mid-flight) is a
61
- // retryable availability failure of this mutation, not integrity evidence.
62
- if (!bindings)
63
- throw new ProjectionDependencyUnavailableError("Document attachments are unavailable for relinking");
64
- assertProjectionVerificationCurrent(input.stillCurrent);
63
+ const bindings = await listRelinkBindings(input, documentId);
65
64
  if (bindings.length === 0)
66
65
  return [];
67
66
  const keks = await collectRelinkKeks(input);
@@ -118,6 +117,19 @@ export async function prepareDocumentLinkBlobRewraps(input) {
118
117
  }
119
118
  return [...rewrapByBlob.values()].sort(compareBlobIds);
120
119
  }
120
+ async function listRelinkBindings(input, documentId) {
121
+ // An operation that ended before or while listing cancels instead of
122
+ // failing. The shared listing still reports its own failed request.
123
+ assertProjectionVerificationCurrent(input.stillCurrent);
124
+ const bindings = await input.apiClient.listDocumentAttachments(documentId, input.refreshListing ? { refresh: true } : undefined);
125
+ assertProjectionVerificationCurrent(input.stillCurrent);
126
+ // The API refuses the link unless every active binding is rewrapped, so an
127
+ // unavailable listing (offline, or a 409 while a bind is mid-flight) is a
128
+ // retryable availability failure of this mutation, not integrity evidence.
129
+ if (!bindings)
130
+ throw new ProjectionDependencyUnavailableError("Document attachments are unavailable for relinking");
131
+ return bindings;
132
+ }
121
133
  async function wrapBlobKeyForTarget(input) {
122
134
  const { binding, target } = input;
123
135
  const wrapped = await wrapContentKey(input.contentKey, input.kek, {
@@ -1 +1 @@
1
- {"version":3,"file":"linkSetBlobRewraps.js","sourceRoot":"","sources":["linkSetBlobRewraps.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,2BAA2B,EAG3B,uBAAuB,EACvB,cAAc,GACf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAMpD,OAAO,EACL,kCAAkC,EAClC,sBAAsB,GACvB,MAAM,2CAA2C,CAAC;AAEnD,OAAO,EAAE,6BAA6B,EAAE,MAAM,yEAAyE,CAAC;AACxH,OAAO,EACL,gBAAgB,EAChB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,OA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CAAC,WAAW;gBAC7B,IAAI,EAAE,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC;gBACzC,aAAa,EAAE,UAAU,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC;aAC5D,CAAC,CAAC;YACH,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,mBAAmB,CAAC,CAAC;YACjD,+DAA+D;YAC/D,IAAI,CAAC,GAAG;gBAAE,SAAS;YACnB,MAAM,EAAE,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC;YAC7B,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;YAC9B,IAAI,QAAQ;gBACV,gBAAgB,CACd,QAAQ,EACR,GAAG,EACH,sDAAsD,CACvD,CAAC;YACJ,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC;QACpB,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,cAAc,CAAC,CAAqB,EAAE,CAAqB;IAClE,OAAO,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import {\n BLOB_CONTENT_KEY_WRAP_SUITE,\n type DocumentContentKeyTarget,\n type DocumentLinkAccessEventBody,\n readKeyingCanonicalJson,\n wrapContentKey,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n BlobAttachmentSummary,\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n deriveDocumentTargetFromProjection,\n unwrapContainerKekPath,\n} from \"../../../data/documents/shared/projection\";\nimport type { ProjectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport {\n assertEqualBytes,\n targetKey,\n} from \"../../../data/documents/shared/readers\";\nimport type { DocumentLinkSetMutationApi } from \"../../../data/documents/shared/types\";\nimport { requireProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { documentContainerProjections } from \"../../../data/keyingProjectionVerification/document/documentContainerProjections\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { createAttachmentProofReader } from \"../../blobs/verification/attachmentDecryptor\";\nimport { createAttachmentKeyAuthenticator } from \"../../blobs/verification/attachmentKeyAuthenticator\";\nimport { verifyRetainedAttachment } from \"../../blobs/verification/retainedAttachmentVerification\";\n\ninterface BlobRewrap {\n blobId: string;\n contentKeyEpoch: number;\n targets: DocumentLinkAccessEventBody[\"blobRewraps\"][number][\"targets\"][number][];\n}\n\ntype BlobRewraps = DocumentLinkAccessEventBody[\"blobRewraps\"];\n\n/**\n * One move or trash workflow lists a document's attachments once. After a leg\n * commits, `committed` holds the document-scoped envelopes it signed, which\n * are exactly what the server now stores for this document; the next leg\n * starts from them instead of listing again.\n */\nexport interface LinkSetAttachmentReuse {\n committed: BlobRewraps | null;\n}\n\nexport function createLinkSetAttachmentReuse(): LinkSetAttachmentReuse {\n return { committed: null };\n}\n\n/**\n * Re-cite the previous leg's envelopes for this leg's targets. Every envelope\n * was authenticated or wrapped by this device before that leg signed it, so a\n * reuse propagates no key to a new scope; any target the previous leg did not\n * wrap returns null and the leg lists and authenticates as usual. A bind or\n * detach in between, a content-key epoch change, or a re-entered retired\n * target (the API keeps its stored wrap over the fresh one) makes the API\n * refuse with an uncoded 409, and the caller re-lists once.\n */\nexport function reuseCommittedBlobRewraps(input: {\n committed: BlobRewraps;\n documentId: string;\n targets: readonly DocumentContentKeyTarget[];\n}): BlobRewraps | null {\n const rewraps: BlobRewrap[] = [];\n for (const rewrap of input.committed) {\n const bindingIds = [\n ...new Set(rewrap.targets.map((target) => target.bindingId)),\n ];\n const targets: BlobRewrap[\"targets\"] = [];\n for (const bindingId of bindingIds) {\n for (const target of input.targets) {\n const previous = rewrap.targets.find(\n (candidate) =>\n candidate.bindingId === bindingId &&\n candidate.documentId === input.documentId &&\n candidate.containerId === target.containerId &&\n candidate.containerKeyEpochId === target.containerKeyEpochId,\n );\n if (!previous) return null;\n targets.push({\n ...previous,\n ...target,\n wrappingMetadata: readKeyingCanonicalJson(\n previous.wrappingMetadata,\n \"Attachment wrap metadata\",\n ),\n });\n }\n }\n rewraps.push({\n blobId: rewrap.blobId,\n contentKeyEpoch: rewrap.contentKeyEpoch,\n targets,\n });\n }\n return rewraps.sort(compareBlobIds);\n}\n\n/** Authenticate the existing bytes before propagating their DEK to a new scope. */\nexport async function prepareDocumentLinkBlobRewraps(\n input: {\n apiClient: DocumentLinkSetMutationApi;\n execSql: ExecSql;\n targetContainerProjection: ContainerWriterProjectionResponse;\n targetSecretKey: Uint8Array;\n targets: readonly DocumentContentKeyTarget[];\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<DocumentLinkAccessEventBody[\"blobRewraps\"]> {\n const documentId = input.writerProjection.documentId;\n const bindings = await input.apiClient.listDocumentAttachments(documentId);\n // The API refuses the link unless every active binding is rewrapped, so an\n // unavailable listing (offline, or a 409 while a bind is mid-flight) is a\n // retryable availability failure of this mutation, not integrity evidence.\n if (!bindings)\n throw new ProjectionDependencyUnavailableError(\n \"Document attachments are unavailable for relinking\",\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (bindings.length === 0) return [];\n const keks = await collectRelinkKeks(input);\n const authenticateKey = createAttachmentKeyAuthenticator(\n input.apiClient,\n documentId,\n );\n const verifyRetained = createAttachmentProofReader(\n input.apiClient,\n documentId,\n verifyRetainedAttachment,\n );\n const rewrapByBlob = new Map<string, BlobRewrap>();\n for (const binding of bindings) {\n const verification = {\n binding,\n expectedDocumentId: documentId,\n expectedSlotId: binding.slotId,\n execSql: input.execSql,\n resolveProjectionUserKey: requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Attachment relink\",\n ),\n targetSecretKey: input.targetSecretKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n writerProjection: input.writerProjection,\n };\n const needsKey = input.targets.some(\n (target) => !retainedTarget(binding, target, documentId),\n );\n const contentKey = needsKey ? await authenticateKey(verification) : null;\n if (!needsKey) await verifyRetained(verification);\n const targets = await Promise.all(\n input.targets.map(async (target) => {\n const previous = retainedTarget(binding, target, documentId);\n if (previous)\n return {\n ...previous,\n ...target,\n wrappingMetadata: readKeyingCanonicalJson(\n previous.wrappingMetadata,\n \"Attachment wrap metadata\",\n ),\n };\n const kek = keks.get(targetKey(target));\n if (!kek)\n throw new Error(\n \"Attachment destination is not a verified current container head\",\n );\n if (!contentKey)\n throw new Error(\"Attachment content key is unavailable\");\n return wrapBlobKeyForTarget({\n binding,\n contentKey,\n documentId,\n kek,\n target,\n });\n }),\n );\n const rewrap = rewrapByBlob.get(binding.blobId) ?? {\n blobId: binding.blobId,\n contentKeyEpoch: binding.contentKeyBundle.contentKeyEpoch,\n targets: [],\n };\n if (rewrap.contentKeyEpoch !== binding.contentKeyBundle.contentKeyEpoch)\n throw new Error(\"Attachment content epoch changed during relinking\");\n rewrap.targets.push(...targets);\n rewrapByBlob.set(binding.blobId, rewrap);\n assertProjectionVerificationCurrent(input.stillCurrent);\n }\n return [...rewrapByBlob.values()].sort(compareBlobIds);\n}\n\nasync function wrapBlobKeyForTarget(input: {\n binding: BlobAttachmentSummary;\n contentKey: Uint8Array;\n documentId: string;\n kek: Uint8Array;\n target: DocumentContentKeyTarget;\n}) {\n const { binding, target } = input;\n const wrapped = await wrapContentKey(input.contentKey, input.kek, {\n kind: \"Blob\",\n objectId: binding.blobId,\n contentKeyEpoch: binding.contentKeyBundle.contentKeyEpoch,\n containerId: target.containerId,\n containerKeyEpochId: target.containerKeyEpochId,\n });\n return {\n ...target,\n bindingId: binding.bindingId,\n documentId: input.documentId,\n wrappedKey: bytesToBase64(wrapped.ciphertext),\n wrappingMetadata: {\n suite: BLOB_CONTENT_KEY_WRAP_SUITE,\n iv: bytesToBase64(wrapped.iv),\n },\n };\n}\n\nfunction retainedTarget(\n binding: BlobAttachmentSummary,\n target: DocumentContentKeyTarget,\n documentId: string,\n) {\n return binding.contentKeyBundle.targets.find(\n (candidate) =>\n candidate.bindingId === binding.bindingId &&\n candidate.documentId === documentId &&\n candidate.containerId === target.containerId &&\n candidate.containerKeyEpochId === target.containerKeyEpochId,\n );\n}\n\nasync function collectRelinkKeks(\n input: Parameters<typeof prepareDocumentLinkBlobRewraps>[0],\n): Promise<Map<string, Uint8Array>> {\n const keks = new Map<string, Uint8Array>();\n for (const projection of [\n ...documentContainerProjections(input.writerProjection),\n input.targetContainerProjection,\n ]) {\n const keys = await unwrapContainerKekPath({\n projection,\n secretKey: input.targetSecretKey,\n execSql: input.execSql,\n ...projectionVerificationOptions(input),\n });\n // Every node of this verified path has a current signed head. Historical\n // keyring entries may open source bytes, but never enter the destination map.\n for (const [index, head] of projection.containerKeks.entries()) {\n const target = deriveDocumentTargetFromProjection({\n ...projection,\n containerId: head.containerId,\n path: projection.path.slice(0, index + 1),\n containerKeks: projection.containerKeks.slice(0, index + 1),\n });\n const key = keys.get(target.containerKeyEpochId);\n // A direct child grantee need not possess any ancestor secret.\n if (!key) continue;\n const id = targetKey(target);\n const previous = keks.get(id);\n if (previous)\n assertEqualBytes(\n previous,\n key,\n \"Attachment link projections contain conflicting KEKs\",\n );\n keks.set(id, key);\n }\n }\n return keks;\n}\n\nfunction compareBlobIds(a: { blobId: string }, b: { blobId: string }): number {\n return a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CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;YAC9B,IAAI,QAAQ;gBACV,gBAAgB,CACd,QAAQ,EACR,GAAG,EACH,sDAAsD,CACvD,CAAC;YACJ,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC;QACpB,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,cAAc,CAAC,CAAqB,EAAE,CAAqB;IAClE,OAAO,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import {\n BLOB_CONTENT_KEY_WRAP_SUITE,\n type DocumentContentKeyTarget,\n type DocumentLinkAccessEventBody,\n readKeyingCanonicalJson,\n wrapContentKey,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n BlobAttachmentSummary,\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n deriveDocumentTargetFromProjection,\n unwrapContainerKekPath,\n} from \"../../../data/documents/shared/projection\";\nimport type { ProjectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport {\n assertEqualBytes,\n targetKey,\n} from \"../../../data/documents/shared/readers\";\nimport type { DocumentLinkSetMutationApi } from \"../../../data/documents/shared/types\";\nimport { requireProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { documentContainerProjections } from \"../../../data/keyingProjectionVerification/document/documentContainerProjections\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { createAttachmentProofReader } from \"../../blobs/verification/attachmentDecryptor\";\nimport { createAttachmentKeyAuthenticator } from \"../../blobs/verification/attachmentKeyAuthenticator\";\nimport { verifyRetainedAttachment } from \"../../blobs/verification/retainedAttachmentVerification\";\n\ninterface BlobRewrap {\n blobId: string;\n contentKeyEpoch: number;\n targets: DocumentLinkAccessEventBody[\"blobRewraps\"][number][\"targets\"][number][];\n}\n\ntype BlobRewraps = DocumentLinkAccessEventBody[\"blobRewraps\"];\n\n/**\n * One move or trash workflow lists a document's attachments once. After a leg\n * commits, `committed` holds the document-scoped envelopes it signed, which\n * are exactly what the server now stores for this document; the next leg\n * starts from them instead of listing again.\n */\nexport interface LinkSetAttachmentReuse {\n committed: BlobRewraps | null;\n}\n\nexport function createLinkSetAttachmentReuse(): LinkSetAttachmentReuse {\n return { committed: null };\n}\n\n/**\n * Re-cite the previous leg's envelopes for this leg's targets. Every envelope\n * was authenticated or wrapped by this device before that leg signed it, so a\n * reuse propagates no key to a new scope; any target the previous leg did not\n * wrap returns null and the leg lists and authenticates as usual. A bind or\n * detach in between makes the API refuse with a coded 409\n * (`document_link_attachments_changed`); a content-key epoch change or a\n * re-entered retired target (the API keeps its stored wrap over the fresh one)\n * with an uncoded one. The caller re-lists once.\n */\nexport function reuseCommittedBlobRewraps(input: {\n committed: BlobRewraps;\n documentId: string;\n targets: readonly DocumentContentKeyTarget[];\n}): BlobRewraps | null {\n const rewraps: BlobRewrap[] = [];\n for (const rewrap of input.committed) {\n const bindingIds = [\n ...new Set(rewrap.targets.map((target) => target.bindingId)),\n ];\n const targets: BlobRewrap[\"targets\"] = [];\n for (const bindingId of bindingIds) {\n for (const target of input.targets) {\n const previous = rewrap.targets.find(\n (candidate) =>\n candidate.bindingId === bindingId &&\n candidate.documentId === input.documentId &&\n candidate.containerId === target.containerId &&\n candidate.containerKeyEpochId === target.containerKeyEpochId,\n );\n if (!previous) return null;\n targets.push({\n ...previous,\n ...target,\n wrappingMetadata: readKeyingCanonicalJson(\n previous.wrappingMetadata,\n \"Attachment wrap metadata\",\n ),\n });\n }\n }\n rewraps.push({\n blobId: rewrap.blobId,\n contentKeyEpoch: rewrap.contentKeyEpoch,\n targets,\n });\n }\n return rewraps.sort(compareBlobIds);\n}\n\n/**\n * Authenticate the existing bytes before propagating their DEK to a new scope.\n * `refreshListing` bypasses a cached listing, after the server refused a leg\n * because its attachments changed.\n */\nexport async function prepareDocumentLinkBlobRewraps(\n input: {\n apiClient: DocumentLinkSetMutationApi;\n execSql: ExecSql;\n refreshListing?: boolean | undefined;\n targetContainerProjection: ContainerWriterProjectionResponse;\n targetSecretKey: Uint8Array;\n targets: readonly DocumentContentKeyTarget[];\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<DocumentLinkAccessEventBody[\"blobRewraps\"]> {\n const documentId = input.writerProjection.documentId;\n const bindings = await listRelinkBindings(input, documentId);\n if (bindings.length === 0) return [];\n const keks = await collectRelinkKeks(input);\n const authenticateKey = createAttachmentKeyAuthenticator(\n input.apiClient,\n documentId,\n );\n const verifyRetained = createAttachmentProofReader(\n input.apiClient,\n documentId,\n verifyRetainedAttachment,\n );\n const rewrapByBlob = new Map<string, BlobRewrap>();\n for (const binding of bindings) {\n const verification = {\n binding,\n expectedDocumentId: documentId,\n expectedSlotId: binding.slotId,\n execSql: input.execSql,\n resolveProjectionUserKey: requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Attachment relink\",\n ),\n targetSecretKey: input.targetSecretKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n writerProjection: input.writerProjection,\n };\n const needsKey = input.targets.some(\n (target) => !retainedTarget(binding, target, documentId),\n );\n const contentKey = needsKey ? await authenticateKey(verification) : null;\n if (!needsKey) await verifyRetained(verification);\n const targets = await Promise.all(\n input.targets.map(async (target) => {\n const previous = retainedTarget(binding, target, documentId);\n if (previous)\n return {\n ...previous,\n ...target,\n wrappingMetadata: readKeyingCanonicalJson(\n previous.wrappingMetadata,\n \"Attachment wrap metadata\",\n ),\n };\n const kek = keks.get(targetKey(target));\n if (!kek)\n throw new Error(\n \"Attachment destination is not a verified current container head\",\n );\n if (!contentKey)\n throw new Error(\"Attachment content key is unavailable\");\n return wrapBlobKeyForTarget({\n binding,\n contentKey,\n documentId,\n kek,\n target,\n });\n }),\n );\n const rewrap = rewrapByBlob.get(binding.blobId) ?? {\n blobId: binding.blobId,\n contentKeyEpoch: binding.contentKeyBundle.contentKeyEpoch,\n targets: [],\n };\n if (rewrap.contentKeyEpoch !== binding.contentKeyBundle.contentKeyEpoch)\n throw new Error(\"Attachment content epoch changed during relinking\");\n rewrap.targets.push(...targets);\n rewrapByBlob.set(binding.blobId, rewrap);\n assertProjectionVerificationCurrent(input.stillCurrent);\n }\n return [...rewrapByBlob.values()].sort(compareBlobIds);\n}\n\nasync function listRelinkBindings(\n input: Pick<\n Parameters<typeof prepareDocumentLinkBlobRewraps>[0],\n \"apiClient\" | \"refreshListing\" | \"stillCurrent\"\n >,\n documentId: string,\n): Promise<BlobAttachmentSummary[]> {\n // An operation that ended before or while listing cancels instead of\n // failing. The shared listing still reports its own failed request.\n assertProjectionVerificationCurrent(input.stillCurrent);\n const bindings = await input.apiClient.listDocumentAttachments(\n documentId,\n input.refreshListing ? { refresh: true } : undefined,\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n // The API refuses the link unless every active binding is rewrapped, so an\n // unavailable listing (offline, or a 409 while a bind is mid-flight) is a\n // retryable availability failure of this mutation, not integrity evidence.\n if (!bindings)\n throw new ProjectionDependencyUnavailableError(\n \"Document attachments are unavailable for relinking\",\n );\n return bindings;\n}\n\nasync function wrapBlobKeyForTarget(input: {\n binding: BlobAttachmentSummary;\n contentKey: Uint8Array;\n documentId: string;\n kek: Uint8Array;\n target: DocumentContentKeyTarget;\n}) {\n const { binding, target } = input;\n const wrapped = await wrapContentKey(input.contentKey, input.kek, {\n kind: \"Blob\",\n objectId: binding.blobId,\n contentKeyEpoch: binding.contentKeyBundle.contentKeyEpoch,\n containerId: target.containerId,\n containerKeyEpochId: target.containerKeyEpochId,\n });\n return {\n ...target,\n bindingId: binding.bindingId,\n documentId: input.documentId,\n wrappedKey: bytesToBase64(wrapped.ciphertext),\n wrappingMetadata: {\n suite: BLOB_CONTENT_KEY_WRAP_SUITE,\n iv: bytesToBase64(wrapped.iv),\n },\n };\n}\n\nfunction retainedTarget(\n binding: BlobAttachmentSummary,\n target: DocumentContentKeyTarget,\n documentId: string,\n) {\n return binding.contentKeyBundle.targets.find(\n (candidate) =>\n candidate.bindingId === binding.bindingId &&\n candidate.documentId === documentId &&\n candidate.containerId === target.containerId &&\n candidate.containerKeyEpochId === target.containerKeyEpochId,\n );\n}\n\nasync function collectRelinkKeks(\n input: Parameters<typeof prepareDocumentLinkBlobRewraps>[0],\n): Promise<Map<string, Uint8Array>> {\n const keks = new Map<string, Uint8Array>();\n for (const projection of [\n ...documentContainerProjections(input.writerProjection),\n input.targetContainerProjection,\n ]) {\n const keys = await unwrapContainerKekPath({\n projection,\n secretKey: input.targetSecretKey,\n execSql: input.execSql,\n ...projectionVerificationOptions(input),\n });\n // Every node of this verified path has a current signed head. Historical\n // keyring entries may open source bytes, but never enter the destination map.\n for (const [index, head] of projection.containerKeks.entries()) {\n const target = deriveDocumentTargetFromProjection({\n ...projection,\n containerId: head.containerId,\n path: projection.path.slice(0, index + 1),\n containerKeks: projection.containerKeks.slice(0, index + 1),\n });\n const key = keys.get(target.containerKeyEpochId);\n // A direct child grantee need not possess any ancestor secret.\n if (!key) continue;\n const id = targetKey(target);\n const previous = keks.get(id);\n if (previous)\n assertEqualBytes(\n previous,\n key,\n \"Attachment link projections contain conflicting KEKs\",\n );\n keks.set(id, key);\n }\n }\n return keks;\n}\n\nfunction compareBlobIds(a: { blobId: string }, b: { blobId: string }): number {\n return a.blobId < b.blobId ? -1 : a.blobId > b.blobId ? 1 : 0;\n}\n"]}