@tearleads/client-sdk 0.1.259 → 0.1.261

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 (39) hide show
  1. package/data/blobs/attachments/types.d.ts +3 -1
  2. package/data/blobs/attachments/types.js.map +1 -1
  3. package/data/documents/documentContent.d.ts +1 -0
  4. package/data/documents/documentContent.js +8 -0
  5. package/data/documents/documentContent.js.map +1 -1
  6. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js +1 -0
  7. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js.map +1 -1
  8. package/data/persistence/documents/internal/discardDocument.js +6 -1
  9. package/data/persistence/documents/internal/discardDocument.js.map +1 -1
  10. package/data/persistence/documents/internal/documentMutationPersistence.js +1 -0
  11. package/data/persistence/documents/internal/documentMutationPersistence.js.map +1 -1
  12. package/data/persistence/documents/internal/documentRows.js +3 -0
  13. package/data/persistence/documents/internal/documentRows.js.map +1 -1
  14. package/data/persistence/documents/types.d.ts +2 -0
  15. package/data/persistence/documents/types.js.map +1 -1
  16. package/data/sqlite/migrations/localSchemaMigrations.js +9 -0
  17. package/data/sqlite/migrations/localSchemaMigrations.js.map +1 -1
  18. package/data/sqlite/schema/documentProjectionSchema.js +12 -2
  19. package/data/sqlite/schema/documentProjectionSchema.js.map +1 -1
  20. package/package.json +1 -1
  21. package/workflows/blobs/hydration/hydrate.js +3 -1
  22. package/workflows/blobs/hydration/hydrate.js.map +1 -1
  23. package/workflows/container-contents/info/blobInfo.js +38 -124
  24. package/workflows/container-contents/info/blobInfo.js.map +1 -1
  25. package/workflows/container-contents/info/blobInfoReferenceQuery.js +109 -0
  26. package/workflows/container-contents/info/blobInfoReferenceQuery.js.map +1 -0
  27. package/workflows/documents/attachments/attachmentFilenameBackfill.d.ts +2 -0
  28. package/workflows/documents/attachments/attachmentFilenameBackfill.js +65 -0
  29. package/workflows/documents/attachments/attachmentFilenameBackfill.js.map +1 -0
  30. package/workflows/documents/create/documentCreationPersistence.js +6 -8
  31. package/workflows/documents/create/documentCreationPersistence.js.map +1 -1
  32. package/workflows/documents/documentMutationCommit.js +13 -18
  33. package/workflows/documents/documentMutationCommit.js.map +1 -1
  34. package/workflows/documents/historyContent.d.ts +1 -0
  35. package/workflows/documents/historyContent.js +14 -8
  36. package/workflows/documents/historyContent.js.map +1 -1
  37. package/workflows/documents/index.d.ts +1 -0
  38. package/workflows/documents/index.js +1 -0
  39. package/workflows/documents/index.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"blobInfo.js","sourceRoot":"","sources":["blobInfo.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,GAAG,EACH,KAAK,EACL,aAAa,EACb,IAAI,EACJ,EAAE,EACF,EAAE,EACF,OAAO,EACP,MAAM,EACN,GAAG,GACJ,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AACnD,OAAO,EAAE,qBAAqB,EAAE,MAAM,mEAAmE,CAAC;AAC1G,OAAO,EAAE,uBAAuB,EAAE,MAAM,0DAA0D,CAAC;AACnG,OAAO,EACL,UAAU,EACV,gCAAgC,EAChC,0BAA0B,GAC3B,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,kBAAkB,EAAE,MAAM,sDAAsD,CAAC;AAC1F,OAAO,EAEL,iCAAiC,GAClC,MAAM,+CAA+C,CAAC;AAEvD,OAAO,EACL,wBAAwB,EACxB,uBAAuB,EACvB,cAAc,EACd,kBAAkB,GACnB,MAAM,gBAAgB,CAAC;AAqBxB,MAAM,uBAAuB,GAAG,GAAG,CAAC;AACpC,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAChC,MAAM,sBAAsB,GAAiB;IAC3C,SAAS,EAAE,MAAM;IACjB,GAAG,EAAE,SAAS;CACf,CAAC;AAEF,SAAS,4BAA4B,CAAC,KAAyB;IAC7D,IAAI,KAAK,KAAK,SAAS,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,K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C,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAEhE,MAAM,UAAU,GAAG,MAAM,iBAAiB,CAAC;QACzC,EAAE;QACF,KAAK;KACN,CAAC,CAAC;IACH,IAAI,KAAK,KAAK,CAAC,IAAI,MAAM,IAAI,UAAU,EAAE,CAAC;QACxC,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,UAAU,EAAE,CAAC;IAClC,CAAC;IAED,MAAM,WAAW,GAAG,MAAM,gBAAgB,CAAC;QACzC,EAAE;QACF,KAAK;QACL,MAAM;QACN,KAAK;QACL,IAAI;KACL,CAAC,CAAC;IACH,MAAM,UAAU,GAAG,MAAM,6BAA6B,CAAC;QACrD,EAAE;QACF,IAAI,EAAE,WAAW,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC;KACxC,CAAC,CAAC;IAEH,OAAO;QACL,IAAI,EAAE,wBAAwB,CAAC,EAAE,UAAU,EAAE,IAAI,EAAE,WAAW,EAAE,CAAC;QACjE,UAAU;KACX,CAAC;AACJ,CAAC","sourcesContent":["import {\n asc,\n count,\n countDistinct,\n desc,\n eq,\n gt,\n inArray,\n isNull,\n sql,\n} from \"drizzle-orm\";\nimport { unionAll } from \"drizzle-orm/sqlite-core\";\nimport { ensureContainerTables } from \"../../../data/persistence/container-contents/containerPersistence\";\nimport { sqlDocumentsPersistence } from \"../../../data/persistence/documents/documentsPersistence\";\nimport {\n containers,\n documentAttachmentBlobProjection,\n documentPendingAttachments,\n} from \"../../../data/sqlite/schema\";\nimport { documentProjection } from \"../../../data/sqlite/schema/documentProjectionSchema\";\nimport {\n type ClientSQLiteDatabase,\n getClientSQLitePersistenceRuntime,\n} from \"../../../data/sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n attachBlobInfoReferences,\n mapBlobInfoReferenceRow,\n mapBlobInfoRow,\n readRequiredNumber,\n} from \"./blobInfoRows\";\nimport type {\n BlobInfo,\n BlobInfoAttachmentKind,\n BlobInfoDocumentReference,\n BlobInfoInput,\n BlobInfoList,\n BlobInfoSort,\n} from \"./blobInfoTypes\";\n\nexport type {\n BlobInfo,\n BlobInfoAttachmentKind,\n BlobInfoDocumentReference,\n BlobInfoInput,\n BlobInfoList,\n BlobInfoSort,\n BlobInfoSortDirection,\n BlobInfoSortKey,\n} from \"./blobInfoTypes\";\n\nconst DEFAULT_BLOB_INFO_LIMIT = 200;\nconst MAX_BLOB_INFO_LIMIT = 999;\nconst DEFAULT_BLOB_INFO_SORT: BlobInfoSort = {\n direction: \"desc\",\n key: \"updated\",\n};\n\nfunction normalizeBlobInfoWindowValue(value: number | undefined): number {\n if (value === undefined || !Number.isFinite(value)) {\n return 0;\n }\n\n return Math.max(0, Math.trunc(value));\n}\n\nfunction normalizeBlobInfoLimit(value: number | undefined): number {\n if (value === undefined) {\n return DEFAULT_BLOB_INFO_LIMIT;\n }\n\n return Math.min(MAX_BLOB_INFO_LIMIT, normalizeBlobInfoWindowValue(value));\n}\n\nfunction normalizeBlobInfoQuery(value: string | undefined): string {\n return value?.trim().toLocaleLowerCase() ?? \"\";\n}\n\nfunction normalizeBlobInfoSort(value: BlobInfoSort | undefined): BlobInfoSort {\n if (!value) {\n return DEFAULT_BLOB_INFO_SORT;\n }\n\n if (\n (value.direction !== \"asc\" && value.direction !== \"desc\") ||\n (value.key !== \"byteLength\" &&\n value.key !== \"mimeType\" &&\n value.key !== \"updated\")\n ) {\n return DEFAULT_BLOB_INFO_SORT;\n }\n\n return value;\n}\n\nfunction createPendingBlobInfoReferencesSelect(db: ClientSQLiteDatabase) {\n return db\n .select({\n attachmentKind: sql<BlobInfoAttachmentKind>`'pending'`.as(\n \"attachment_kind\",\n ),\n blobId: sql<string | null>`NULL`.as(\"blob_id\"),\n blobKey:\n sql<string>`'storage:' || ${documentPendingAttachments.storageKey}`.as(\n \"blob_key\",\n ),\n byteLength: documentPendingAttachments.byteLength,\n changedAtSort: sql<string>`${documentPendingAttachments.createdAt}`.as(\n \"changed_at_sort\",\n ),\n containerId: documentProjection.containerId,\n createdAt: sql<string | null>`${documentPendingAttachments.createdAt}`.as(\n \"created_at\",\n ),\n documentId: documentProjection.documentId,\n documentKind: documentProjection.documentKind,\n documentTitle: documentProjection.title,\n localId: documentPendingAttachments.localId,\n mimeType: documentPendingAttachments.mimeType,\n name: sql<string | null>`${documentPendingAttachments.name}`.as(\"name\"),\n organizationId: sql<string | null>`COALESCE(\n NULLIF(${containers.organizationId}, ''),\n NULLIF(${documentProjection.organizationId}, '')\n )`.as(\"organization_id\"),\n searchText: sql<string>`LOWER(\n COALESCE(${documentPendingAttachments.storageKey}, '')\n || CHAR(0) || COALESCE(${documentPendingAttachments.mimeType}, '')\n || CHAR(0) || COALESCE(${documentPendingAttachments.name}, '')\n || CHAR(0) || COALESCE(${documentPendingAttachments.localId}, '')\n || CHAR(0) || COALESCE(${documentProjection.documentId}, '')\n || CHAR(0) || COALESCE(${documentProjection.title}, '')\n || CHAR(0) || COALESCE(${documentProjection.containerId}, '')\n || CHAR(0) || COALESCE(\n NULLIF(${containers.organizationId}, ''),\n NULLIF(${documentProjection.organizationId}, ''),\n ''\n )\n || CHAR(0) || COALESCE(${documentPendingAttachments.slotId}, '')\n )`.as(\"search_text\"),\n slotId: documentPendingAttachments.slotId,\n storageKey: documentPendingAttachments.storageKey,\n updatedAt: sql<string | null>`NULL`.as(\"updated_at\"),\n })\n .from(documentPendingAttachments)\n .leftJoin(\n documentProjection,\n eq(documentProjection.localId, documentPendingAttachments.localId),\n )\n .leftJoin(containers, eq(containers.id, documentProjection.containerId));\n}\n\n// Detached rows are excluded here rather than at each call site: a slot unlinked\n// from a synced document keeps its row until the detach reaches the server, and\n// it stops being a reference the moment it is unlinked.\nfunction createLocalBlobInfoReferencesSelect(db: ClientSQLiteDatabase) {\n return db\n .select({\n attachmentKind: sql<BlobInfoAttachmentKind>`'local'`.as(\n \"attachment_kind\",\n ),\n blobId: documentAttachmentBlobProjection.blobId,\n blobKey: sql<string>`CASE\n WHEN ${documentAttachmentBlobProjection.blobId} IS NOT NULL\n AND ${documentAttachmentBlobProjection.blobId} <> ''\n THEN 'blob:' || ${documentAttachmentBlobProjection.blobId}\n ELSE 'storage:' || ${documentAttachmentBlobProjection.storageKey}\n END`.as(\"blob_key\"),\n byteLength: documentAttachmentBlobProjection.byteLength,\n changedAtSort:\n sql<string>`${documentAttachmentBlobProjection.updatedAt}`.as(\n \"changed_at_sort\",\n ),\n containerId: documentProjection.containerId,\n createdAt: sql<string | null>`NULL`.as(\"created_at\"),\n documentId: documentProjection.documentId,\n documentKind: documentProjection.documentKind,\n documentTitle: documentProjection.title,\n localId: documentAttachmentBlobProjection.localId,\n mimeType: documentAttachmentBlobProjection.mimeType,\n name: sql<string | null>`NULL`.as(\"name\"),\n organizationId: sql<string | null>`COALESCE(\n NULLIF(${containers.organizationId}, ''),\n NULLIF(${documentProjection.organizationId}, '')\n )`.as(\"organization_id\"),\n searchText: sql<string>`LOWER(\n COALESCE(${documentAttachmentBlobProjection.blobId}, '')\n || CHAR(0) || COALESCE(${documentAttachmentBlobProjection.storageKey}, '')\n || CHAR(0) || COALESCE(${documentAttachmentBlobProjection.mimeType}, '')\n || CHAR(0) || COALESCE(${documentAttachmentBlobProjection.localId}, '')\n || CHAR(0) || COALESCE(${documentProjection.documentId}, '')\n || CHAR(0) || COALESCE(${documentProjection.title}, '')\n || CHAR(0) || COALESCE(${documentProjection.containerId}, '')\n || CHAR(0) || COALESCE(\n NULLIF(${containers.organizationId}, ''),\n NULLIF(${documentProjection.organizationId}, ''),\n ''\n )\n || CHAR(0) || COALESCE(${documentAttachmentBlobProjection.slotId}, '')\n )`.as(\"search_text\"),\n slotId: documentAttachmentBlobProjection.slotId,\n storageKey: documentAttachmentBlobProjection.storageKey,\n updatedAt: sql<\n string | null\n >`${documentAttachmentBlobProjection.updatedAt}`.as(\"updated_at\"),\n })\n .from(documentAttachmentBlobProjection)\n .leftJoin(\n documentProjection,\n eq(documentProjection.localId, documentAttachmentBlobProjection.localId),\n )\n .leftJoin(containers, eq(containers.id, documentProjection.containerId))\n .where(isNull(documentAttachmentBlobProjection.detachedAt));\n}\n\nfunction createBlobInfoReferencesCte(db: ClientSQLiteDatabase) {\n return db\n .$with(\"blob_info_references\")\n .as(\n unionAll(\n createPendingBlobInfoReferencesSelect(db),\n createLocalBlobInfoReferencesSelect(db),\n ),\n );\n}\n\nfunction createGroupedBlobInfoCtes(input: {\n readonly db: ClientSQLiteDatabase;\n readonly query: string;\n}) {\n const blobInfoReferences = createBlobInfoReferencesCte(input.db);\n const groupedBlobInfoSelection = {\n blobId: sql<\n string | null\n >`MIN(NULLIF(${blobInfoReferences.blobId}, ''))`.as(\"blob_id\"),\n blobKey: blobInfoReferences.blobKey,\n byteLength: sql<number>`MAX(${blobInfoReferences.byteLength})`.as(\n \"byte_length\",\n ),\n changedAtSort: sql<string | null>`COALESCE(\n MAX(NULLIF(${blobInfoReferences.updatedAt}, '')),\n MIN(NULLIF(${blobInfoReferences.createdAt}, ''))\n )`.as(\"changed_at_sort\"),\n createdAt: sql<\n string | null\n >`MIN(NULLIF(${blobInfoReferences.createdAt}, ''))`.as(\"created_at\"),\n documentCount: countDistinct(blobInfoReferences.localId).as(\n \"document_count\",\n ),\n mimeType: sql<\n string | null\n >`MIN(NULLIF(${blobInfoReferences.mimeType}, ''))`.as(\"mime_type\"),\n name: sql<string | null>`MIN(NULLIF(${blobInfoReferences.name}, ''))`.as(\n \"name\",\n ),\n organizationId: sql<string | null>`CASE\n WHEN COUNT(NULLIF(${blobInfoReferences.organizationId}, '')) = COUNT(*)\n AND COUNT(DISTINCT NULLIF(${blobInfoReferences.organizationId}, '')) = 1\n THEN MIN(NULLIF(${blobInfoReferences.organizationId}, ''))\n ELSE NULL\n END`.as(\"organization_id\"),\n referenceCount: count().as(\"reference_count\"),\n storageKey: sql<string>`MIN(${blobInfoReferences.storageKey})`.as(\n \"storage_key\",\n ),\n updatedAt: sql<\n string | null\n >`MAX(NULLIF(${blobInfoReferences.updatedAt}, ''))`.as(\"updated_at\"),\n };\n\n if (input.query === \"\") {\n const groupedBlobInfo = input.db.$with(\"grouped_blob_info\").as(\n input.db\n .select(groupedBlobInfoSelection)\n .from(blobInfoReferences)\n .groupBy(({ blobKey }) => blobKey),\n );\n\n return { blobInfoReferences, groupedBlobInfo, matchingBlobKeys: null };\n }\n\n const matchingBlobKeys = input.db.$with(\"matching_blob_keys\").as(\n input.db\n .selectDistinct({\n matchingBlobKey: sql<string>`${blobInfoReferences.blobKey}`.as(\n \"matching_blob_key\",\n ),\n })\n .from(blobInfoReferences)\n .where(\n gt(\n sql<number>`INSTR(${blobInfoReferences.searchText}, ${input.query})`,\n 0,\n ),\n ),\n );\n const groupedBlobInfo = input.db.$with(\"grouped_blob_info\").as(\n input.db\n .select(groupedBlobInfoSelection)\n .from(blobInfoReferences)\n .innerJoin(\n matchingBlobKeys,\n eq(matchingBlobKeys.matchingBlobKey, blobInfoReferences.blobKey),\n )\n .groupBy(({ blobKey }) => blobKey),\n );\n\n return { blobInfoReferences, groupedBlobInfo, matchingBlobKeys };\n}\n\nasync function countBlobInfoRows(input: {\n readonly db: ClientSQLiteDatabase;\n readonly query: string;\n}): Promise<number> {\n const { blobInfoReferences, groupedBlobInfo, matchingBlobKeys } =\n createGroupedBlobInfoCtes(input);\n const rows =\n matchingBlobKeys === null\n ? await input.db\n .with(blobInfoReferences, groupedBlobInfo)\n .select({ totalCount: count().as(\"total_count\") })\n .from(groupedBlobInfo)\n : await input.db\n .with(blobInfoReferences, matchingBlobKeys, groupedBlobInfo)\n .select({ totalCount: count().as(\"total_count\") })\n .from(groupedBlobInfo);\n\n return readRequiredNumber(rows[0]?.totalCount, \"total_count\");\n}\n\nasync function listBlobInfoRows(input: {\n readonly db: ClientSQLiteDatabase;\n readonly limit: number;\n readonly offset: number;\n readonly query: string;\n readonly sort: BlobInfoSort;\n}): Promise<Array<Omit<BlobInfo, \"references\">>> {\n const { blobInfoReferences, groupedBlobInfo, matchingBlobKeys } =\n createGroupedBlobInfoCtes(input);\n const changedAtSortDirection =\n input.sort.direction === \"desc\"\n ? desc(groupedBlobInfo.changedAtSort)\n : asc(groupedBlobInfo.changedAtSort);\n const byteLengthSortDirection =\n input.sort.direction === \"desc\"\n ? desc(groupedBlobInfo.byteLength)\n : asc(groupedBlobInfo.byteLength);\n let orderBy: ReturnType<typeof asc | typeof desc>[];\n if (input.sort.key === \"mimeType\") {\n orderBy = [\n asc(sql`${groupedBlobInfo.mimeType} IS NULL`),\n input.sort.direction === \"desc\"\n ? desc(sql`${groupedBlobInfo.mimeType} COLLATE NOCASE`)\n : asc(sql`${groupedBlobInfo.mimeType} COLLATE NOCASE`),\n desc(groupedBlobInfo.changedAtSort),\n asc(groupedBlobInfo.blobKey),\n ];\n } else if (input.sort.key === \"byteLength\") {\n orderBy = [\n byteLengthSortDirection,\n desc(groupedBlobInfo.changedAtSort),\n asc(groupedBlobInfo.blobKey),\n ];\n } else {\n orderBy = [\n asc(sql`${groupedBlobInfo.changedAtSort} IS NULL`),\n changedAtSortDirection,\n asc(groupedBlobInfo.blobKey),\n ];\n }\n const selection = {\n blobId: groupedBlobInfo.blobId,\n blobKey: groupedBlobInfo.blobKey,\n byteLength: groupedBlobInfo.byteLength,\n createdAt: groupedBlobInfo.createdAt,\n documentCount: groupedBlobInfo.documentCount,\n mimeType: groupedBlobInfo.mimeType,\n name: groupedBlobInfo.name,\n organizationId: groupedBlobInfo.organizationId,\n referenceCount: groupedBlobInfo.referenceCount,\n storageKey: groupedBlobInfo.storageKey,\n updatedAt: groupedBlobInfo.updatedAt,\n };\n const rows =\n matchingBlobKeys === null\n ? await input.db\n .with(blobInfoReferences, groupedBlobInfo)\n .select(selection)\n .from(groupedBlobInfo)\n .orderBy(...orderBy)\n .limit(input.limit)\n .offset(input.offset)\n : await input.db\n .with(blobInfoReferences, matchingBlobKeys, groupedBlobInfo)\n .select(selection)\n .from(groupedBlobInfo)\n .orderBy(...orderBy)\n .limit(input.limit)\n .offset(input.offset);\n\n return rows.map(mapBlobInfoRow);\n}\n\nasync function listBlobInfoReferencesForKeys(input: {\n readonly db: ClientSQLiteDatabase;\n readonly keys: ReadonlyArray<string>;\n}): Promise<BlobInfoDocumentReference[]> {\n if (input.keys.length === 0) {\n return [];\n }\n\n const blobInfoReferences = createBlobInfoReferencesCte(input.db);\n const rows = await input.db\n .with(blobInfoReferences)\n .select({\n attachmentKind: blobInfoReferences.attachmentKind,\n blobId: blobInfoReferences.blobId,\n byteLength: blobInfoReferences.byteLength,\n containerId: blobInfoReferences.containerId,\n createdAt: blobInfoReferences.createdAt,\n documentId: blobInfoReferences.documentId,\n documentKind: blobInfoReferences.documentKind,\n documentTitle: blobInfoReferences.documentTitle,\n localId: blobInfoReferences.localId,\n mimeType: blobInfoReferences.mimeType,\n name: blobInfoReferences.name,\n slotId: blobInfoReferences.slotId,\n storageKey: blobInfoReferences.storageKey,\n updatedAt: blobInfoReferences.updatedAt,\n })\n .from(blobInfoReferences)\n .where(inArray(blobInfoReferences.blobKey, [...input.keys]))\n .orderBy(\n asc(blobInfoReferences.blobKey),\n desc(blobInfoReferences.changedAtSort),\n asc(blobInfoReferences.localId),\n asc(blobInfoReferences.slotId),\n );\n\n return rows.map(mapBlobInfoReferenceRow);\n}\n\nexport async function listBlobInfo(\n input: BlobInfoInput & { readonly execSql?: ExecSql | null | undefined },\n): Promise<BlobInfoList> {\n if (!input.execSql) {\n return { rows: [], totalCount: 0 };\n }\n\n const query = normalizeBlobInfoQuery(input.query);\n const limit = normalizeBlobInfoLimit(input.limit);\n const offset = normalizeBlobInfoWindowValue(input.offset);\n const sort = normalizeBlobInfoSort(input.sort);\n await sqlDocumentsPersistence.ensureSchema(input.execSql);\n await ensureContainerTables(input.execSql);\n const { db } = getClientSQLitePersistenceRuntime(input.execSql);\n\n const totalCount = await countBlobInfoRows({\n db,\n query,\n });\n if (limit === 0 || offset >= totalCount) {\n return { rows: [], totalCount };\n }\n\n const groupedRows = await listBlobInfoRows({\n db,\n limit,\n offset,\n query,\n sort,\n });\n const references = await listBlobInfoReferencesForKeys({\n db,\n keys: groupedRows.map((row) => row.key),\n });\n\n return {\n rows: attachBlobInfoReferences({ references, rows: groupedRows }),\n totalCount,\n };\n}\n"]}
1
+ {"version":3,"file":"blobInfo.js","sourceRoot":"","sources":["blobInfo.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,KAAK,EAAE,aAAa,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAChF,OAAO,EAAE,qBAAqB,EAAE,MAAM,mEAAmE,CAAC;AAC1G,OAAO,EAAE,uBAAuB,EAAE,MAAM,0DAA0D,CAAC;AACnG,OAAO,EAEL,iCAAiC,GAClC,MAAM,+CAA+C,CAAC;AAEvD,OAAO,EAAE,+BAA+B,EAAE,MAAM,iBAAiB,CAAC;AAClE,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EACL,wBAAwB,EACxB,uBAAuB,EACvB,cAAc,EACd,kBAAkB,GACnB,MAAM,gBAAgB,CAAC;AAoBxB,MAAM,uBAAuB,GAAG,GAAG,CAAC;AACpC,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAChC,MAAM,sBAAsB,GAAiB;IAC3C,SAAS,EAAE,MAAM;IACjB,GAAG,EAAE,SAAS;CACf,CAAC;AAEF,SAAS,4BAA4B,CAAC,KAAyB;IAC7D,IAAI,KAAK,KAAK,SAAS,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QACnD,OAAO,CAAC,CAAC;IACX,CAAC;IAED,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;AACxC,CAAC;AAED,SAAS,sBAAsB,CAAC,KAAyB;IACvD,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;Q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,CAAC,IAAI,CAAC,EAAE,UAAU,EAAE,CAAC;IACxD,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC;AAC9B,CAAC","sourcesContent":["import { asc, count, countDistinct, desc, eq, inArray, sql } from \"drizzle-orm\";\nimport { ensureContainerTables } from \"../../../data/persistence/container-contents/containerPersistence\";\nimport { sqlDocumentsPersistence } from \"../../../data/persistence/documents/documentsPersistence\";\nimport {\n type ClientSQLiteDatabase,\n getClientSQLitePersistenceRuntime,\n} from \"../../../data/sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { backfillDocumentAttachmentNames } from \"../../documents\";\nimport { createBlobInfoReferencesCte } from \"./blobInfoReferenceQuery\";\nimport {\n attachBlobInfoReferences,\n mapBlobInfoReferenceRow,\n mapBlobInfoRow,\n readRequiredNumber,\n} from \"./blobInfoRows\";\nimport type {\n BlobInfo,\n BlobInfoDocumentReference,\n BlobInfoInput,\n BlobInfoList,\n BlobInfoSort,\n} from \"./blobInfoTypes\";\n\nexport type {\n BlobInfo,\n BlobInfoAttachmentKind,\n BlobInfoDocumentReference,\n BlobInfoInput,\n BlobInfoList,\n BlobInfoSort,\n BlobInfoSortDirection,\n BlobInfoSortKey,\n} from \"./blobInfoTypes\";\n\nconst DEFAULT_BLOB_INFO_LIMIT = 200;\nconst MAX_BLOB_INFO_LIMIT = 999;\nconst DEFAULT_BLOB_INFO_SORT: BlobInfoSort = {\n direction: \"desc\",\n key: \"updated\",\n};\n\nfunction normalizeBlobInfoWindowValue(value: number | undefined): number {\n if (value === undefined || !Number.isFinite(value)) {\n return 0;\n }\n\n return Math.max(0, Math.trunc(value));\n}\n\nfunction normalizeBlobInfoLimit(value: number | undefined): number {\n if (value === undefined) {\n return DEFAULT_BLOB_INFO_LIMIT;\n }\n\n return Math.min(MAX_BLOB_INFO_LIMIT, normalizeBlobInfoWindowValue(value));\n}\n\nfunction normalizeBlobInfoSort(value: BlobInfoSort | undefined): BlobInfoSort {\n if (!value) {\n return DEFAULT_BLOB_INFO_SORT;\n }\n\n if (\n (value.direction !== \"asc\" && value.direction !== \"desc\") ||\n (value.key !== \"byteLength\" &&\n value.key !== \"mimeType\" &&\n value.key !== \"updated\")\n ) {\n return DEFAULT_BLOB_INFO_SORT;\n }\n\n return value;\n}\n\nfunction createGroupedBlobInfoCtes(input: {\n readonly db: ClientSQLiteDatabase;\n readonly query: string;\n}) {\n const blobInfoReferences = createBlobInfoReferencesCte(input.db);\n const groupedBlobInfoSelection = {\n blobId: sql<\n string | null\n >`MIN(NULLIF(${blobInfoReferences.blobId}, ''))`.as(\"blob_id\"),\n blobKey: blobInfoReferences.blobKey,\n byteLength: sql<number>`MAX(${blobInfoReferences.byteLength})`.as(\n \"byte_length\",\n ),\n changedAtSort: sql<string | null>`COALESCE(\n MAX(NULLIF(${blobInfoReferences.updatedAt}, '')),\n MIN(NULLIF(${blobInfoReferences.createdAt}, ''))\n )`.as(\"changed_at_sort\"),\n createdAt: sql<\n string | null\n >`MIN(NULLIF(${blobInfoReferences.createdAt}, ''))`.as(\"created_at\"),\n documentCount: countDistinct(blobInfoReferences.localId).as(\n \"document_count\",\n ),\n mimeType: sql<\n string | null\n >`MIN(NULLIF(${blobInfoReferences.mimeType}, ''))`.as(\"mime_type\"),\n name: sql<string | null>`MIN(NULLIF(${blobInfoReferences.name}, ''))`.as(\n \"name\",\n ),\n organizationId: sql<string | null>`CASE\n WHEN COUNT(NULLIF(${blobInfoReferences.organizationId}, '')) = COUNT(*)\n AND COUNT(DISTINCT NULLIF(${blobInfoReferences.organizationId}, '')) = 1\n THEN MIN(NULLIF(${blobInfoReferences.organizationId}, ''))\n ELSE NULL\n END`.as(\"organization_id\"),\n referenceCount: count().as(\"reference_count\"),\n storageKey: sql<string>`MIN(${blobInfoReferences.storageKey})`.as(\n \"storage_key\",\n ),\n updatedAt: sql<\n string | null\n >`MAX(NULLIF(${blobInfoReferences.updatedAt}, ''))`.as(\"updated_at\"),\n };\n\n if (input.query === \"\") {\n const groupedBlobInfo = input.db.$with(\"grouped_blob_info\").as(\n input.db\n .select(groupedBlobInfoSelection)\n .from(blobInfoReferences)\n .groupBy(({ blobKey }) => blobKey),\n );\n\n return { blobInfoReferences, groupedBlobInfo, matchingBlobKeys: null };\n }\n\n const folded = input.query.toLowerCase();\n const search = blobInfoReferences.searchText;\n const foldedMatch = sql`INSTR(${search}, ${folded})`;\n // SQLite folds only ASCII. Also match its spelling of a verbatim filename.\n const matchingBlobKeys = input.db.$with(\"matching_blob_keys\").as(\n input.db\n .selectDistinct({\n matchingBlobKey: sql<string>`${blobInfoReferences.blobKey}`.as(\n \"matching_blob_key\",\n ),\n })\n .from(blobInfoReferences)\n .where(\n input.query === folded\n ? foldedMatch\n : sql`${foldedMatch} OR INSTR(${search}, LOWER(${input.query}))`,\n ),\n );\n const groupedBlobInfo = input.db.$with(\"grouped_blob_info\").as(\n input.db\n .select(groupedBlobInfoSelection)\n .from(blobInfoReferences)\n .innerJoin(\n matchingBlobKeys,\n eq(matchingBlobKeys.matchingBlobKey, blobInfoReferences.blobKey),\n )\n .groupBy(({ blobKey }) => blobKey),\n );\n\n return { blobInfoReferences, groupedBlobInfo, matchingBlobKeys };\n}\n\nasync function countBlobInfoRows(input: {\n readonly db: ClientSQLiteDatabase;\n readonly query: string;\n}): Promise<number> {\n const { blobInfoReferences, groupedBlobInfo, matchingBlobKeys } =\n createGroupedBlobInfoCtes(input);\n const rows =\n matchingBlobKeys === null\n ? await input.db\n .with(blobInfoReferences, groupedBlobInfo)\n .select({ totalCount: count().as(\"total_count\") })\n .from(groupedBlobInfo)\n : await input.db\n .with(blobInfoReferences, matchingBlobKeys, groupedBlobInfo)\n .select({ totalCount: count().as(\"total_count\") })\n .from(groupedBlobInfo);\n\n return readRequiredNumber(rows[0]?.totalCount, \"total_count\");\n}\n\nasync function listBlobInfoRows(input: {\n readonly db: ClientSQLiteDatabase;\n readonly limit: number;\n readonly offset: number;\n readonly query: string;\n readonly sort: BlobInfoSort;\n}): Promise<Array<Omit<BlobInfo, \"references\">>> {\n const { blobInfoReferences, groupedBlobInfo, matchingBlobKeys } =\n createGroupedBlobInfoCtes(input);\n const changedAtSortDirection =\n input.sort.direction === \"desc\"\n ? desc(groupedBlobInfo.changedAtSort)\n : asc(groupedBlobInfo.changedAtSort);\n const byteLengthSortDirection =\n input.sort.direction === \"desc\"\n ? desc(groupedBlobInfo.byteLength)\n : asc(groupedBlobInfo.byteLength);\n let orderBy: ReturnType<typeof asc | typeof desc>[];\n if (input.sort.key === \"mimeType\") {\n orderBy = [\n asc(sql`${groupedBlobInfo.mimeType} IS NULL`),\n input.sort.direction === \"desc\"\n ? desc(sql`${groupedBlobInfo.mimeType} COLLATE NOCASE`)\n : asc(sql`${groupedBlobInfo.mimeType} COLLATE NOCASE`),\n desc(groupedBlobInfo.changedAtSort),\n asc(groupedBlobInfo.blobKey),\n ];\n } else if (input.sort.key === \"byteLength\") {\n orderBy = [\n byteLengthSortDirection,\n desc(groupedBlobInfo.changedAtSort),\n asc(groupedBlobInfo.blobKey),\n ];\n } else {\n orderBy = [\n asc(sql`${groupedBlobInfo.changedAtSort} IS NULL`),\n changedAtSortDirection,\n asc(groupedBlobInfo.blobKey),\n ];\n }\n const selection = {\n blobId: groupedBlobInfo.blobId,\n blobKey: groupedBlobInfo.blobKey,\n byteLength: groupedBlobInfo.byteLength,\n createdAt: groupedBlobInfo.createdAt,\n documentCount: groupedBlobInfo.documentCount,\n mimeType: groupedBlobInfo.mimeType,\n name: groupedBlobInfo.name,\n organizationId: groupedBlobInfo.organizationId,\n referenceCount: groupedBlobInfo.referenceCount,\n storageKey: groupedBlobInfo.storageKey,\n updatedAt: groupedBlobInfo.updatedAt,\n };\n const rows =\n matchingBlobKeys === null\n ? await input.db\n .with(blobInfoReferences, groupedBlobInfo)\n .select(selection)\n .from(groupedBlobInfo)\n .orderBy(...orderBy)\n .limit(input.limit)\n .offset(input.offset)\n : await input.db\n .with(blobInfoReferences, matchingBlobKeys, groupedBlobInfo)\n .select(selection)\n .from(groupedBlobInfo)\n .orderBy(...orderBy)\n .limit(input.limit)\n .offset(input.offset);\n\n return rows.map(mapBlobInfoRow);\n}\n\nasync function listBlobInfoReferencesForKeys(input: {\n readonly db: ClientSQLiteDatabase;\n readonly keys: ReadonlyArray<string>;\n}): Promise<BlobInfoDocumentReference[]> {\n if (input.keys.length === 0) {\n return [];\n }\n\n const blobInfoReferences = createBlobInfoReferencesCte(input.db);\n const rows = await input.db\n .with(blobInfoReferences)\n .select({\n attachmentKind: blobInfoReferences.attachmentKind,\n blobId: blobInfoReferences.blobId,\n byteLength: blobInfoReferences.byteLength,\n containerId: blobInfoReferences.containerId,\n createdAt: blobInfoReferences.createdAt,\n documentId: blobInfoReferences.documentId,\n documentKind: blobInfoReferences.documentKind,\n documentTitle: blobInfoReferences.documentTitle,\n localId: blobInfoReferences.localId,\n mimeType: blobInfoReferences.mimeType,\n name: blobInfoReferences.name,\n slotId: blobInfoReferences.slotId,\n storageKey: blobInfoReferences.storageKey,\n updatedAt: blobInfoReferences.updatedAt,\n })\n .from(blobInfoReferences)\n .where(inArray(blobInfoReferences.blobKey, [...input.keys]))\n .orderBy(\n asc(blobInfoReferences.blobKey),\n desc(blobInfoReferences.changedAtSort),\n asc(blobInfoReferences.localId),\n asc(blobInfoReferences.slotId),\n );\n\n return rows.map(mapBlobInfoReferenceRow);\n}\n\nasync function readBlobPage(input: Parameters<typeof listBlobInfoRows>[0]) {\n const rows = await listBlobInfoRows(input);\n const references = await listBlobInfoReferencesForKeys({\n db: input.db,\n keys: rows.map((row) => row.key),\n });\n return attachBlobInfoReferences({ rows, references });\n}\n\nfunction localIdsMissingFilenames(rows: readonly BlobInfo[]): string[] {\n const missing = new Set<string>();\n for (const row of rows) {\n for (const ref of row.references) {\n if (ref.attachmentKind === \"local\" && ref.name === null)\n missing.add(ref.localId);\n }\n }\n return [...missing];\n}\n\nexport async function listBlobInfo(\n input: BlobInfoInput & { readonly execSql?: ExecSql | null | undefined },\n): Promise<BlobInfoList> {\n if (!input.execSql) {\n return { rows: [], totalCount: 0 };\n }\n\n const query = input.query?.trim() ?? \"\";\n const limit = normalizeBlobInfoLimit(input.limit);\n const offset = normalizeBlobInfoWindowValue(input.offset);\n const sort = normalizeBlobInfoSort(input.sort);\n await sqlDocumentsPersistence.ensureSchema(input.execSql);\n await ensureContainerTables(input.execSql);\n if (query) await backfillDocumentAttachmentNames(input.execSql);\n const { db } = getClientSQLitePersistenceRuntime(input.execSql);\n\n const totalCount = await countBlobInfoRows({\n db,\n query,\n });\n if (limit === 0 || offset >= totalCount) {\n return { rows: [], totalCount };\n }\n\n const page = { db, limit, offset, query, sort };\n const rows = await readBlobPage(page);\n if (\n !query &&\n (await backfillDocumentAttachmentNames(\n input.execSql,\n localIdsMissingFilenames(rows),\n ))\n ) {\n return { rows: await readBlobPage(page), totalCount };\n }\n return { rows, totalCount };\n}\n"]}
@@ -0,0 +1,109 @@
1
+ import { eq, isNull, sql } from "drizzle-orm";
2
+ import { unionAll } from "drizzle-orm/sqlite-core";
3
+ import { containers, documentAttachmentBlobProjection, documentPendingAttachments, } from "../../../data/sqlite/schema/index.js";
4
+ import { documentProjection, documentProjectionText, } from "../../../data/sqlite/schema/documentProjectionSchema.js";
5
+ function createPendingBlobInfoReferencesSelect(db) {
6
+ return db
7
+ .select({
8
+ attachmentKind: sql `'pending'`.as("attachment_kind"),
9
+ blobId: sql `NULL`.as("blob_id"),
10
+ blobKey: sql `'storage:' || ${documentPendingAttachments.storageKey}`.as("blob_key"),
11
+ byteLength: documentPendingAttachments.byteLength,
12
+ changedAtSort: sql `${documentPendingAttachments.createdAt}`.as("changed_at_sort"),
13
+ containerId: documentProjection.containerId,
14
+ createdAt: sql `${documentPendingAttachments.createdAt}`.as("created_at"),
15
+ documentId: documentProjection.documentId,
16
+ documentKind: documentProjection.documentKind,
17
+ documentTitle: documentProjection.title,
18
+ localId: documentPendingAttachments.localId,
19
+ mimeType: documentPendingAttachments.mimeType,
20
+ name: sql `${documentPendingAttachments.name}`.as("name"),
21
+ organizationId: sql `COALESCE(
22
+ NULLIF(${containers.organizationId}, ''),
23
+ NULLIF(${documentProjection.organizationId}, '')
24
+ )`.as("organization_id"),
25
+ searchText: sql `LOWER(
26
+ COALESCE(${documentPendingAttachments.storageKey}, '')
27
+ || CHAR(0) || COALESCE(${documentPendingAttachments.mimeType}, '')
28
+ || CHAR(0) || COALESCE(${documentPendingAttachments.name}, '')
29
+ || CHAR(0) || COALESCE(${documentPendingAttachments.localId}, '')
30
+ || CHAR(0) || COALESCE(${documentProjection.documentId}, '')
31
+ || CHAR(0) || COALESCE(${documentProjection.title}, '')
32
+ || CHAR(0) || COALESCE(${documentProjection.containerId}, '')
33
+ || CHAR(0) || COALESCE(
34
+ NULLIF(${containers.organizationId}, ''),
35
+ NULLIF(${documentProjection.organizationId}, ''),
36
+ ''
37
+ )
38
+ || CHAR(0) || COALESCE(${documentPendingAttachments.slotId}, '')
39
+ )`.as("search_text"),
40
+ slotId: documentPendingAttachments.slotId,
41
+ storageKey: documentPendingAttachments.storageKey,
42
+ updatedAt: sql `NULL`.as("updated_at"),
43
+ })
44
+ .from(documentPendingAttachments)
45
+ .leftJoin(documentProjection, eq(documentProjection.localId, documentPendingAttachments.localId))
46
+ .leftJoin(containers, eq(containers.id, documentProjection.containerId));
47
+ }
48
+ // Detached rows are excluded here rather than at each call site: a slot unlinked
49
+ // from a synced document keeps its row until the detach reaches the server, and
50
+ // it stops being a reference the moment it is unlinked.
51
+ function createLocalBlobInfoReferencesSelect(db) {
52
+ const path = sql `'$.' || json_quote(${documentAttachmentBlobProjection.contentSha256} || ':' || ${documentAttachmentBlobProjection.slotId})`;
53
+ const names = documentProjectionText.attachmentNames;
54
+ return db
55
+ .select({
56
+ attachmentKind: sql `'local'`.as("attachment_kind"),
57
+ blobId: documentAttachmentBlobProjection.blobId,
58
+ blobKey: sql `CASE
59
+ WHEN ${documentAttachmentBlobProjection.blobId} IS NOT NULL
60
+ AND ${documentAttachmentBlobProjection.blobId} <> ''
61
+ THEN 'blob:' || ${documentAttachmentBlobProjection.blobId}
62
+ ELSE 'storage:' || ${documentAttachmentBlobProjection.storageKey}
63
+ END`.as("blob_key"),
64
+ byteLength: documentAttachmentBlobProjection.byteLength,
65
+ changedAtSort: sql `${documentAttachmentBlobProjection.updatedAt}`.as("changed_at_sort"),
66
+ containerId: documentProjection.containerId,
67
+ createdAt: sql `NULL`.as("created_at"),
68
+ documentId: documentProjection.documentId,
69
+ documentKind: documentProjection.documentKind,
70
+ documentTitle: documentProjection.title,
71
+ localId: documentAttachmentBlobProjection.localId,
72
+ mimeType: documentAttachmentBlobProjection.mimeType,
73
+ name: sql `json_extract(${names}, ${path} || '.name')`.as("name"),
74
+ organizationId: sql `COALESCE(
75
+ NULLIF(${containers.organizationId}, ''),
76
+ NULLIF(${documentProjection.organizationId}, '')
77
+ )`.as("organization_id"),
78
+ searchText: sql `LOWER(
79
+ COALESCE(${documentAttachmentBlobProjection.blobId}, '')
80
+ || CHAR(0) || COALESCE(${documentAttachmentBlobProjection.storageKey}, '')
81
+ || CHAR(0) || COALESCE(json_extract(${names}, ${path} || '.search'), '')
82
+ || CHAR(0) || COALESCE(${documentAttachmentBlobProjection.mimeType}, '')
83
+ || CHAR(0) || COALESCE(${documentAttachmentBlobProjection.localId}, '')
84
+ || CHAR(0) || COALESCE(${documentProjection.documentId}, '')
85
+ || CHAR(0) || COALESCE(${documentProjection.title}, '')
86
+ || CHAR(0) || COALESCE(${documentProjection.containerId}, '')
87
+ || CHAR(0) || COALESCE(
88
+ NULLIF(${containers.organizationId}, ''),
89
+ NULLIF(${documentProjection.organizationId}, ''),
90
+ ''
91
+ )
92
+ || CHAR(0) || COALESCE(${documentAttachmentBlobProjection.slotId}, '')
93
+ )`.as("search_text"),
94
+ slotId: documentAttachmentBlobProjection.slotId,
95
+ storageKey: documentAttachmentBlobProjection.storageKey,
96
+ updatedAt: sql `${documentAttachmentBlobProjection.updatedAt}`.as("updated_at"),
97
+ })
98
+ .from(documentAttachmentBlobProjection)
99
+ .leftJoin(documentProjectionText, eq(documentProjectionText.localId, documentAttachmentBlobProjection.localId))
100
+ .leftJoin(documentProjection, eq(documentProjection.localId, documentAttachmentBlobProjection.localId))
101
+ .leftJoin(containers, eq(containers.id, documentProjection.containerId))
102
+ .where(isNull(documentAttachmentBlobProjection.detachedAt));
103
+ }
104
+ export function createBlobInfoReferencesCte(db) {
105
+ return db
106
+ .$with("blob_info_references")
107
+ .as(unionAll(createPendingBlobInfoReferencesSelect(db), createLocalBlobInfoReferencesSelect(db)));
108
+ }
109
+ //# sourceMappingURL=blobInfoReferenceQuery.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"blobInfoReferenceQuery.js","sourceRoot":"","sources":["blobInfoReferenceQuery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AACnD,OAAO,EACL,UAAU,EACV,gCAAgC,EAChC,0BAA0B,GAC3B,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACL,kBAAkB,EAClB,sBAAsB,GACvB,MAAM,sDAAsD,CAAC;AAI9D,SAAS,qCAAqC,CAAC,EAAwB;IACrE,OAAO,EAAE;SACN,MAAM,CAAC;QACN,cAAc,EAAE,GAAG,CAAwB,WAAW,CAAC,EAAE,CACvD,iBAAiB,CAClB;QACD,MAAM,EAAE,GAAG,CAAe,MAAM,CAAC,EAAE,CAAC,SAAS,CAAC;QAC9C,OAAO,EACL,GAAG,CAAQ,iBAAiB,0BAA0B,CAAC,UAAU,EAAE,CAAC,EAAE,CACpE,UAAU,CACX;QACH,UAAU,EAAE,0BAA0B,CAAC,UAAU;QACjD,aAAa,EAAE,GAAG,CAAQ,GAAG,0BAA0B,CAAC,SAAS,EAAE,CAAC,EAAE,CACpE,iBAAiB,CAClB;QACD,WAAW,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"drizzle-orm\";\nimport { unionAll } from \"drizzle-orm/sqlite-core\";\nimport {\n containers,\n documentAttachmentBlobProjection,\n documentPendingAttachments,\n} from \"../../../data/sqlite/schema\";\nimport {\n documentProjection,\n documentProjectionText,\n} from \"../../../data/sqlite/schema/documentProjectionSchema\";\nimport type { ClientSQLiteDatabase } from \"../../../data/sqlite/sqlitePersistenceRuntime\";\nimport type { BlobInfoAttachmentKind } from \"./blobInfoTypes\";\n\nfunction createPendingBlobInfoReferencesSelect(db: ClientSQLiteDatabase) {\n return db\n .select({\n attachmentKind: sql<BlobInfoAttachmentKind>`'pending'`.as(\n \"attachment_kind\",\n ),\n blobId: sql<string | null>`NULL`.as(\"blob_id\"),\n blobKey:\n sql<string>`'storage:' || ${documentPendingAttachments.storageKey}`.as(\n \"blob_key\",\n ),\n byteLength: documentPendingAttachments.byteLength,\n changedAtSort: sql<string>`${documentPendingAttachments.createdAt}`.as(\n \"changed_at_sort\",\n ),\n containerId: documentProjection.containerId,\n createdAt: sql<string | null>`${documentPendingAttachments.createdAt}`.as(\n \"created_at\",\n ),\n documentId: documentProjection.documentId,\n documentKind: documentProjection.documentKind,\n documentTitle: documentProjection.title,\n localId: documentPendingAttachments.localId,\n mimeType: documentPendingAttachments.mimeType,\n name: sql<string | null>`${documentPendingAttachments.name}`.as(\"name\"),\n organizationId: sql<string | null>`COALESCE(\n NULLIF(${containers.organizationId}, ''),\n NULLIF(${documentProjection.organizationId}, '')\n )`.as(\"organization_id\"),\n searchText: sql<string>`LOWER(\n COALESCE(${documentPendingAttachments.storageKey}, '')\n || CHAR(0) || COALESCE(${documentPendingAttachments.mimeType}, '')\n || CHAR(0) || COALESCE(${documentPendingAttachments.name}, '')\n || CHAR(0) || COALESCE(${documentPendingAttachments.localId}, '')\n || CHAR(0) || COALESCE(${documentProjection.documentId}, '')\n || CHAR(0) || COALESCE(${documentProjection.title}, '')\n || CHAR(0) || COALESCE(${documentProjection.containerId}, '')\n || CHAR(0) || COALESCE(\n NULLIF(${containers.organizationId}, ''),\n NULLIF(${documentProjection.organizationId}, ''),\n ''\n )\n || CHAR(0) || COALESCE(${documentPendingAttachments.slotId}, '')\n )`.as(\"search_text\"),\n slotId: documentPendingAttachments.slotId,\n storageKey: documentPendingAttachments.storageKey,\n updatedAt: sql<string | null>`NULL`.as(\"updated_at\"),\n })\n .from(documentPendingAttachments)\n .leftJoin(\n documentProjection,\n eq(documentProjection.localId, documentPendingAttachments.localId),\n )\n .leftJoin(containers, eq(containers.id, documentProjection.containerId));\n}\n\n// Detached rows are excluded here rather than at each call site: a slot unlinked\n// from a synced document keeps its row until the detach reaches the server, and\n// it stops being a reference the moment it is unlinked.\nfunction createLocalBlobInfoReferencesSelect(db: ClientSQLiteDatabase) {\n const path = sql`'$.' || json_quote(${documentAttachmentBlobProjection.contentSha256} || ':' || ${documentAttachmentBlobProjection.slotId})`;\n const names = documentProjectionText.attachmentNames;\n return db\n .select({\n attachmentKind: sql<BlobInfoAttachmentKind>`'local'`.as(\n \"attachment_kind\",\n ),\n blobId: documentAttachmentBlobProjection.blobId,\n blobKey: sql<string>`CASE\n WHEN ${documentAttachmentBlobProjection.blobId} IS NOT NULL\n AND ${documentAttachmentBlobProjection.blobId} <> ''\n THEN 'blob:' || ${documentAttachmentBlobProjection.blobId}\n ELSE 'storage:' || ${documentAttachmentBlobProjection.storageKey}\n END`.as(\"blob_key\"),\n byteLength: documentAttachmentBlobProjection.byteLength,\n changedAtSort:\n sql<string>`${documentAttachmentBlobProjection.updatedAt}`.as(\n \"changed_at_sort\",\n ),\n containerId: documentProjection.containerId,\n createdAt: sql<string | null>`NULL`.as(\"created_at\"),\n documentId: documentProjection.documentId,\n documentKind: documentProjection.documentKind,\n documentTitle: documentProjection.title,\n localId: documentAttachmentBlobProjection.localId,\n mimeType: documentAttachmentBlobProjection.mimeType,\n name: sql<string | null>`json_extract(${names}, ${path} || '.name')`.as(\n \"name\",\n ),\n organizationId: sql<string | null>`COALESCE(\n NULLIF(${containers.organizationId}, ''),\n NULLIF(${documentProjection.organizationId}, '')\n )`.as(\"organization_id\"),\n searchText: sql<string>`LOWER(\n COALESCE(${documentAttachmentBlobProjection.blobId}, '')\n || CHAR(0) || COALESCE(${documentAttachmentBlobProjection.storageKey}, '')\n || CHAR(0) || COALESCE(json_extract(${names}, ${path} || '.search'), '')\n || CHAR(0) || COALESCE(${documentAttachmentBlobProjection.mimeType}, '')\n || CHAR(0) || COALESCE(${documentAttachmentBlobProjection.localId}, '')\n || CHAR(0) || COALESCE(${documentProjection.documentId}, '')\n || CHAR(0) || COALESCE(${documentProjection.title}, '')\n || CHAR(0) || COALESCE(${documentProjection.containerId}, '')\n || CHAR(0) || COALESCE(\n NULLIF(${containers.organizationId}, ''),\n NULLIF(${documentProjection.organizationId}, ''),\n ''\n )\n || CHAR(0) || COALESCE(${documentAttachmentBlobProjection.slotId}, '')\n )`.as(\"search_text\"),\n slotId: documentAttachmentBlobProjection.slotId,\n storageKey: documentAttachmentBlobProjection.storageKey,\n updatedAt: sql<\n string | null\n >`${documentAttachmentBlobProjection.updatedAt}`.as(\"updated_at\"),\n })\n .from(documentAttachmentBlobProjection)\n .leftJoin(\n documentProjectionText,\n eq(\n documentProjectionText.localId,\n documentAttachmentBlobProjection.localId,\n ),\n )\n .leftJoin(\n documentProjection,\n eq(documentProjection.localId, documentAttachmentBlobProjection.localId),\n )\n .leftJoin(containers, eq(containers.id, documentProjection.containerId))\n .where(isNull(documentAttachmentBlobProjection.detachedAt));\n}\n\nexport function createBlobInfoReferencesCte(db: ClientSQLiteDatabase) {\n return db\n .$with(\"blob_info_references\")\n .as(\n unionAll(\n createPendingBlobInfoReferencesSelect(db),\n createLocalBlobInfoReferencesSelect(db),\n ),\n );\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
2
+ export declare function backfillDocumentAttachmentNames(execSql: ExecSql, localIds?: readonly string[]): Promise<boolean>;
@@ -0,0 +1,65 @@
1
+ import { and, asc, eq, exists, gt, isNull, sql } from "drizzle-orm";
2
+ import { serializeDocumentAttachmentNames } from "../../../data/documents/documentContent.js";
3
+ import { sqlDocumentsPersistence } from "../../../data/persistence/documents/documentsPersistence.js";
4
+ import { documentAttachmentBlobProjection } from "../../../data/sqlite/schema/index.js";
5
+ import { documentProjectionText } from "../../../data/sqlite/schema/documentProjectionSchema.js";
6
+ import { getClientSQLitePersistenceRuntime } from "../../../data/sqlite/sqlitePersistenceRuntime.js";
7
+ import { restorePersistedDocumentContent } from "../historyContent.js";
8
+ const BATCH_SIZE = 16;
9
+ async function restoreAttachmentNames(execSql, localId) {
10
+ const projection = documentProjectionText;
11
+ const history = await sqlDocumentsPersistence.loadHistoryRestoreState(execSql, localId);
12
+ // A missing or unreadable history may become available on a later pull.
13
+ const doc = await restorePersistedDocumentContent(history).catch(() => null);
14
+ if (!doc)
15
+ return false;
16
+ let attachmentNames;
17
+ try {
18
+ attachmentNames = serializeDocumentAttachmentNames(doc);
19
+ }
20
+ finally {
21
+ doc.free();
22
+ }
23
+ // A concurrent document save already projected the authoritative names.
24
+ await getClientSQLitePersistenceRuntime(execSql).runMutation((db) => db
25
+ .update(projection)
26
+ .set({ attachmentNames })
27
+ .where(and(eq(projection.localId, localId), isNull(projection.attachmentNames))));
28
+ return true;
29
+ }
30
+ // A page supplies its document IDs. Filename searches also need the names of
31
+ // off-page references, so visit missing projections in bounded key order.
32
+ export async function backfillDocumentAttachmentNames(execSql, localIds) {
33
+ if (localIds?.length === 0)
34
+ return false;
35
+ const runtime = getClientSQLitePersistenceRuntime(execSql);
36
+ const projection = documentProjectionText;
37
+ const blob = documentAttachmentBlobProjection;
38
+ // Bind a page's IDs as one value even when a shared blob has many references.
39
+ const scope = localIds &&
40
+ sql `${projection.localId} IN (SELECT value FROM json_each(${JSON.stringify(localIds)}))`;
41
+ let after;
42
+ let restored = false;
43
+ for (;;) {
44
+ const candidates = await runtime.db
45
+ .select({ localId: projection.localId })
46
+ .from(projection)
47
+ .where(and(isNull(projection.attachmentNames), scope, after === undefined ? undefined : gt(projection.localId, after), exists(runtime.db
48
+ .select({ one: sql `1` })
49
+ .from(blob)
50
+ .where(and(eq(blob.localId, projection.localId), isNull(blob.detachedAt))))))
51
+ .orderBy(asc(projection.localId))
52
+ .limit(BATCH_SIZE);
53
+ for (const { localId } of candidates) {
54
+ if (localId === null)
55
+ continue;
56
+ after = localId;
57
+ if (await restoreAttachmentNames(execSql, localId))
58
+ restored = true;
59
+ }
60
+ if (candidates.length < BATCH_SIZE)
61
+ return restored;
62
+ await new Promise((resolve) => setTimeout(resolve, 0));
63
+ }
64
+ }
65
+ //# sourceMappingURL=attachmentFilenameBackfill.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attachmentFilenameBackfill.js","sourceRoot":"","sources":["attachmentFilenameBackfill.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AACpE,OAAO,EAAE,gCAAgC,EAAE,MAAM,yCAAyC,CAAC;AAC3F,OAAO,EAAE,uBAAuB,EAAE,MAAM,0DAA0D,CAAC;AACnG,OAAO,EAAE,gCAAgC,EAAE,MAAM,6BAA6B,CAAC;AAC/E,OAAO,EAAE,sBAAsB,EAAE,MAAM,sDAAsD,CAAC;AAC9F,OAAO,EAAE,iCAAiC,EAAE,MAAM,+CAA+C,CAAC;AAElG,OAAO,EAAE,+BAA+B,EAAE,MAAM,mBAAmB,CAAC;AAEpE,MAAM,UAAU,GAAG,EAAE,CAAC;AAEtB,KAAK,UAAU,sBAAsB,CACnC,OAAgB,EAChB,OAAe;IAEf,MAAM,UAAU,GAAG,sBAAsB,CAAC;IAC1C,MAAM,OAAO,GAAG,MAAM,uBAAuB,CAAC,uBAAuB,CACnE,OAAO,EACP,OAAO,CACR,CAAC;IACF,wEAAwE;IACxE,MAAM,GAAG,GAAG,MAAM,+BAA+B,CAAC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AAE,OAAO,EAAE,UAAU,CAAC,OAAO,EAAE,CAAC;aACvC,IAAI,CAAC,UAAU,CAAC;aAChB,KAAK,CACJ,GAAG,CACD,MAAM,CAAC,UAAU,CAAC,eAAe,CAAC,EAClC,KAAK,EACL,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,KAAK,CAAC,EAC/D,MAAM,CACJ,OAAO,CAAC,EAAE;aACP,MAAM,CAAC,EAAE,GAAG,EAAE,GAAG,CAAA,GAAG,EAAE,CAAC;aACvB,IAAI,CAAC,IAAI,CAAC;aACV,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,UAAU,CAAC,OAAO,CAAC,EACpC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CACxB,CACF,CACJ,CACF,CACF;aACA,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;aAChC,KAAK,CAAC,UAAU,CAAC,CAAC;QAErB,KAAK,MAAM,EAAE,OAAO,EAAE,IAAI,UAAU,EAAE,CAAC;YACrC,IAAI,OAAO,KAAK,IAAI;gBAAE,SAAS;YAC/B,KAAK,GAAG,OAAO,CAAC;YAChB,IAAI,MAAM,sBAAsB,CAAC,OAAO,EAAE,OAAO,CAAC;gBAAE,QAAQ,GAAG,IAAI,CAAC;QACtE,CAAC;QACD,IAAI,UAAU,CAAC,MAAM,GAAG,UAAU;YAAE,OAAO,QAAQ,CAAC;QACpD,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC;IAC/D,CAAC;AACH,CAAC","sourcesContent":["import { and, asc, eq, exists, gt, isNull, sql } from \"drizzle-orm\";\nimport { serializeDocumentAttachmentNames } from \"../../../data/documents/documentContent\";\nimport { sqlDocumentsPersistence } from \"../../../data/persistence/documents/documentsPersistence\";\nimport { documentAttachmentBlobProjection } from \"../../../data/sqlite/schema\";\nimport { documentProjectionText } from \"../../../data/sqlite/schema/documentProjectionSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../data/sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { restorePersistedDocumentContent } from \"../historyContent\";\n\nconst BATCH_SIZE = 16;\n\nasync function restoreAttachmentNames(\n execSql: ExecSql,\n localId: string,\n): Promise<boolean> {\n const projection = documentProjectionText;\n const history = await sqlDocumentsPersistence.loadHistoryRestoreState(\n execSql,\n localId,\n );\n // A missing or unreadable history may become available on a later pull.\n const doc = await restorePersistedDocumentContent(history).catch(() => null);\n if (!doc) return false;\n let attachmentNames: string;\n try {\n attachmentNames = serializeDocumentAttachmentNames(doc);\n } finally {\n doc.free();\n }\n // A concurrent document save already projected the authoritative names.\n await getClientSQLitePersistenceRuntime(execSql).runMutation((db) =>\n db\n .update(projection)\n .set({ attachmentNames })\n .where(\n and(\n eq(projection.localId, localId),\n isNull(projection.attachmentNames),\n ),\n ),\n );\n return true;\n}\n\n// A page supplies its document IDs. Filename searches also need the names of\n// off-page references, so visit missing projections in bounded key order.\nexport async function backfillDocumentAttachmentNames(\n execSql: ExecSql,\n localIds?: readonly string[],\n): Promise<boolean> {\n if (localIds?.length === 0) return false;\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const projection = documentProjectionText;\n const blob = documentAttachmentBlobProjection;\n // Bind a page's IDs as one value even when a shared blob has many references.\n const scope =\n localIds &&\n sql`${projection.localId} IN (SELECT value FROM json_each(${JSON.stringify(localIds)}))`;\n let after: string | undefined;\n let restored = false;\n for (;;) {\n const candidates: { localId: string | null }[] = await runtime.db\n .select({ localId: projection.localId })\n .from(projection)\n .where(\n and(\n isNull(projection.attachmentNames),\n scope,\n after === undefined ? undefined : gt(projection.localId, after),\n exists(\n runtime.db\n .select({ one: sql`1` })\n .from(blob)\n .where(\n and(\n eq(blob.localId, projection.localId),\n isNull(blob.detachedAt),\n ),\n ),\n ),\n ),\n )\n .orderBy(asc(projection.localId))\n .limit(BATCH_SIZE);\n\n for (const { localId } of candidates) {\n if (localId === null) continue;\n after = localId;\n if (await restoreAttachmentNames(execSql, localId)) restored = true;\n }\n if (candidates.length < BATCH_SIZE) return restored;\n await new Promise<void>((resolve) => setTimeout(resolve, 0));\n }\n}\n"]}
@@ -1,16 +1,14 @@
1
1
  import { bytesToBase64 } from "../../../internal/encoding/index.js";
2
2
  import { encodeVersionVector, exportFullHistorySnapshot, } from "../../../internal/loro/index.js";
3
+ import { serializeDocumentAttachmentNames } from "../../../data/documents/documentContent.js";
3
4
  export function createInitialDocumentRows(input) {
4
5
  return input.persistence.createDocumentWithHistoryCheckpoint(input.execSql, input.record, {
5
6
  endVersionVector: encodeVersionVector(input.currentDoc),
6
7
  snapshot: bytesToBase64(exportFullHistorySnapshot(input.currentDoc)),
7
- }, input.pendingUpdate || input.stillCurrent
8
- ? {
9
- ...(input.pendingUpdate
10
- ? { pendingUpdate: input.pendingUpdate }
11
- : {}),
12
- ...(input.stillCurrent ? { stillCurrent: input.stillCurrent } : {}),
13
- }
14
- : undefined, input.saveClientProjection);
8
+ }, {
9
+ attachmentNames: serializeDocumentAttachmentNames(input.currentDoc),
10
+ ...(input.pendingUpdate ? { pendingUpdate: input.pendingUpdate } : {}),
11
+ stillCurrent: input.stillCurrent,
12
+ }, input.saveClientProjection);
15
13
  }
16
14
  //# sourceMappingURL=documentCreationPersistence.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"documentCreationPersistence.js","sourceRoot":"","sources":["documentCreationPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,mBAAmB,EACnB,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;AAQzB,MAAM,UAAU,yBAAyB,CAAC,KAUzC;IACC,OAAO,KAAK,CAAC,WAAW,CAAC,mCAAmC,CAC1D,KAAK,CAAC,OAAO,EACb,KAAK,CAAC,MAAM,EACZ;QACE,gBAAgB,EAAE,mBAAmB,CAAC,KAAK,CAAC,UAAU,CAAC;QACvD,QAAQ,EAAE,aAAa,CAAC,yBAAyB,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;KACrE,EACD,KAAK,CAAC,aAAa,IAAI,KAAK,CAAC,YAAY;QACvC,CAAC,CAAC;YACE,GAAG,CAAC,KAAK,CAAC,aAAa;gBACrB,CAAC,CAAC,EAAE,aAAa,EAAE,KAAK,CAAC,aAAa,EAAE;gBACxC,CAAC,CAAC,EAAE,CAAC;YACP,GAAG,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,KAAK,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACpE;QACH,CAAC,CAAC,SAAS,EACb,KAAK,CAAC,oBAAoB,CAC3B,CAAC;AACJ,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n encodeVersionVector,\n exportFullHistorySnapshot,\n} from \"@tearleads/loro\";\nimport type {\n DocumentsPersistence,\n StoredDocumentRecord,\n} from \"../../../data/persistence/documents/documentsPersistence\";\nimport type { PendingUpdateFields } from \"../../../data/persistence/documents/records\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\n\nexport function createInitialDocumentRows(input: {\n currentDoc: Parameters<typeof encodeVersionVector>[0];\n execSql: ExecSql;\n persistence: DocumentsPersistence;\n pendingUpdate?: PendingUpdateFields | undefined;\n record: StoredDocumentRecord;\n stillCurrent?: (() => boolean) | undefined;\n saveClientProjection: Parameters<\n DocumentsPersistence[\"createDocumentWithHistoryCheckpoint\"]\n >[4];\n}): ReturnType<DocumentsPersistence[\"createDocumentWithHistoryCheckpoint\"]> {\n return input.persistence.createDocumentWithHistoryCheckpoint(\n input.execSql,\n input.record,\n {\n endVersionVector: encodeVersionVector(input.currentDoc),\n snapshot: bytesToBase64(exportFullHistorySnapshot(input.currentDoc)),\n },\n input.pendingUpdate || input.stillCurrent\n ? {\n ...(input.pendingUpdate\n ? { pendingUpdate: input.pendingUpdate }\n : {}),\n ...(input.stillCurrent ? { stillCurrent: input.stillCurrent } : {}),\n }\n : undefined,\n input.saveClientProjection,\n );\n}\n"]}
1
+ {"version":3,"file":"documentCreationPersistence.js","sourceRoot":"","sources":["documentCreationPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,mBAAmB,EACnB,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,gCAAgC,EAAE,MAAM,yCAAyC,CAAC;AAQ3F,MAAM,UAAU,yBAAyB,CAAC,KAUzC;IACC,OAAO,KAAK,CAAC,WAAW,CAAC,mCAAmC,CAC1D,KAAK,CAAC,OAAO,EACb,KAAK,CAAC,MAAM,EACZ;QACE,gBAAgB,EAAE,mBAAmB,CAAC,KAAK,CAAC,UAAU,CAAC;QACvD,QAAQ,EAAE,aAAa,CAAC,yBAAyB,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;KACrE,EACD;QACE,eAAe,EAAE,gCAAgC,CAAC,KAAK,CAAC,UAAU,CAAC;QACnE,GAAG,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,KAAK,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACtE,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,EACD,KAAK,CAAC,oBAAoB,CAC3B,CAAC;AACJ,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n encodeVersionVector,\n exportFullHistorySnapshot,\n} from \"@tearleads/loro\";\nimport { serializeDocumentAttachmentNames } from \"../../../data/documents/documentContent\";\nimport type {\n DocumentsPersistence,\n StoredDocumentRecord,\n} from \"../../../data/persistence/documents/documentsPersistence\";\nimport type { PendingUpdateFields } from \"../../../data/persistence/documents/records\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\n\nexport function createInitialDocumentRows(input: {\n currentDoc: Parameters<typeof encodeVersionVector>[0];\n execSql: ExecSql;\n persistence: DocumentsPersistence;\n pendingUpdate?: PendingUpdateFields | undefined;\n record: StoredDocumentRecord;\n stillCurrent?: (() => boolean) | undefined;\n saveClientProjection: Parameters<\n DocumentsPersistence[\"createDocumentWithHistoryCheckpoint\"]\n >[4];\n}): ReturnType<DocumentsPersistence[\"createDocumentWithHistoryCheckpoint\"]> {\n return input.persistence.createDocumentWithHistoryCheckpoint(\n input.execSql,\n input.record,\n {\n endVersionVector: encodeVersionVector(input.currentDoc),\n snapshot: bytesToBase64(exportFullHistorySnapshot(input.currentDoc)),\n },\n {\n attachmentNames: serializeDocumentAttachmentNames(input.currentDoc),\n ...(input.pendingUpdate ? { pendingUpdate: input.pendingUpdate } : {}),\n stillCurrent: input.stillCurrent,\n },\n input.saveClientProjection,\n );\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  import { getTextValue } from "../../internal/loro/index.js";
2
2
  import { DEFAULT_DOCUMENT_ACCESS_EPOCH, DEFAULT_DOCUMENT_KIND, } from "../../data/documents/documentConstants.js";
3
+ import { serializeDocumentAttachmentNames } from "../../data/documents/documentContent.js";
3
4
  import { readStoredDocumentState, } from "../../data/documents/documentKinds.js";
4
5
  import { createInitialDocumentRows } from "./create/documentCreationPersistence.js";
5
6
  import { documentSyncSecurityContextMatches, } from "./documentMutationPreparation.js";
@@ -192,6 +193,15 @@ async function commitOnePreparedDocumentMutation(input) {
192
193
  localId: persistInput.localId,
193
194
  patch: mutation.resolvedPatch,
194
195
  });
196
+ const saveClientProjection = (execSql, updatedAt) => saveDocumentClientProjection({
197
+ currentRecord: mutation.mutationCurrentRecord,
198
+ documentProjectors: input.documentProjectors,
199
+ documentState,
200
+ execSql,
201
+ localId: persistInput.localId,
202
+ record,
203
+ updatedAt,
204
+ });
195
205
  if (!mutation.mutationCurrentRecord) {
196
206
  const savedAt = await createInitialDocumentRows({
197
207
  currentDoc: persistInput.currentDoc,
@@ -200,15 +210,7 @@ async function commitOnePreparedDocumentMutation(input) {
200
210
  persistence: persistInput.persistence,
201
211
  record,
202
212
  stillCurrent: persistInput.canStartDurableMutation,
203
- saveClientProjection: (transactionExecSql, updatedAt) => saveDocumentClientProjection({
204
- currentRecord: null,
205
- documentProjectors: input.documentProjectors,
206
- documentState,
207
- execSql: transactionExecSql,
208
- localId: persistInput.localId,
209
- record,
210
- updatedAt,
211
- }),
213
+ saveClientProjection,
212
214
  });
213
215
  return resolveInitialDocumentCreation({
214
216
  execSql: input.lockedExecSql,
@@ -219,6 +221,7 @@ async function commitOnePreparedDocumentMutation(input) {
219
221
  }
220
222
  const committed = await persistInput.persistence.commitDocumentMutation(input.lockedExecSql, {
221
223
  acceptedPendingUpdateIds: input.acceptedPendingUpdateIds,
224
+ attachmentNames: serializeDocumentAttachmentNames(persistInput.currentDoc),
222
225
  clearSyncFailure: persistInput.clearSyncFailure,
223
226
  ...(persistInput.attachmentRemoval
224
227
  ? { attachmentRemoval: persistInput.attachmentRemoval }
@@ -245,15 +248,7 @@ async function commitOnePreparedDocumentMutation(input) {
245
248
  ? { stillCurrent: persistInput.canStartDurableMutation }
246
249
  : {}),
247
250
  }, async (transactionExecSql, updatedAt) => {
248
- await saveDocumentClientProjection({
249
- currentRecord: mutation.mutationCurrentRecord,
250
- documentProjectors: input.documentProjectors,
251
- documentState,
252
- execSql: transactionExecSql,
253
- localId: persistInput.localId,
254
- record,
255
- updatedAt,
256
- });
251
+ await saveClientProjection(transactionExecSql, updatedAt);
257
252
  await persistInput.commitSideEffect?.(transactionExecSql);
258
253
  });
259
254
  return resolveDocumentMutationCommit({
@@ -1 +1 @@
1
- {"version":3,"file":"documentMutationCommit.js","sourceRoot":"","sources":["documentMutationCommit.ts"],"names":[],"mappings":"AAAA,OAAO,EAA4B,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACzE,OAAO,EACL,6BAA6B,E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,CAAC,kBAAkB;YAC5C,KAAK,EAAE,OAAO,KAAK,CAAC;YACpB,aAAa;YACb,KAAK,EAAE,KAAK,CAAC,KAAK;YAClB,YAAY;SACb,CAAC,CAAC;QACH,IAAI,CAAC,QAAQ;YAAE,OAAO,IAAI,CAAC;QAC3B,IAAI,QAAQ,CAAC,0BAA0B,EAAE,CAAC;YACxC,OAAO,gCAAgC,CAAC;gBACtC,wBAAwB;gBACxB,aAAa;gBACb,QAAQ;gBACR,YAAY;aACb,CAAC,CAAC;QACL,CAAC;QACD,MAAM,MAAM,GAAG,MAAM,iCAAiC,CAAC;YACrD,wBAAwB;YACxB,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;YAC5C,aAAa;YACb,QAAQ;YACR,YAAY;SACb,CAAC,CAAC;QACH,IAAI,MAAM,KAAK,OAAO;YAAE,OAAO,MAAM,CAAC;IACxC,CAAC;IACD,MAAM,IAAI,KAAK,CACb,0CAA0C,qCAAqC,uBAAuB,CACvG,CAAC;AACJ,CAAC","sourcesContent":["import { type encodeVersionVector, getTextValue } from \"@tearleads/loro\";\nimport {\n DEFAULT_DOCUMENT_ACCESS_EPOCH,\n DEFAULT_DOCUMENT_KIND,\n} from \"../../data/documents/documentConstants\";\nimport {\n type DocumentProjectorRegistry,\n type DocumentProjectorRegistryInput,\n readStoredDocumentState,\n} from \"../../data/documents/documentKinds\";\nimport type {\n DocumentPlacementCleanup,\n DocumentsPersistence,\n StoredDocumentRecord,\n} from \"../../data/persistence/documents/documentsPersistence\";\nimport type { PendingUpdateFields } from \"../../data/persistence/documents/records\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { createInitialDocumentRows } from \"./create/documentCreationPersistence\";\nimport {\n documentSyncSecurityContextMatches,\n type PrepareDocumentMutationInput,\n type prepareDocumentMutation,\n} from \"./documentMutationPreparation\";\nimport { prepareDocumentMutationUnlessDeleted } from \"./documentPersistGuards\";\n\ntype DocumentContentState = Parameters<typeof encodeVersionVector>[0];\ntype NullableDocumentRuntimeField =\n | \"accessStateHash\"\n | \"lastCommitLsn\"\n | \"contentKeyBundle\"\n | \"documentKekTargets\"\n | \"documentManifestBundle\";\n\nconst MAX_DOCUMENT_MUTATION_COMMIT_ATTEMPTS = 8;\n\nexport interface PersistedDocumentState {\n creationSuperseded?: true;\n historyRestoreState?:\n | Awaited<ReturnType<DocumentsPersistence[\"loadHistoryRestoreState\"]>>\n | undefined;\n pullContinuationSuperseded?: true;\n record: StoredDocumentRecord;\n syncIdentitySuperseded?: true;\n updatedAt?: string | undefined;\n}\n\nexport interface PersistDocumentStateInput\n extends PrepareDocumentMutationInput {\n acceptedPendingUpdateIds?: readonly string[] | undefined;\n attachmentRemoval?:\n | Parameters<\n DocumentsPersistence[\"commitDocumentMutation\"]\n >[1][\"attachmentRemoval\"]\n | undefined;\n attachmentStaging?:\n | Parameters<\n DocumentsPersistence[\"commitDocumentMutation\"]\n >[1][\"attachmentStaging\"]\n | undefined;\n canStartDurableMutation?: (() => boolean) | undefined;\n clearSyncFailure?: boolean | undefined;\n commitSideEffect?: (transactionExecSql: ExecSql) => Promise<void>;\n containerId?: string | null | undefined;\n deleteDocumentPlacements: DocumentPlacementCleanup;\n documentProjectors: DocumentProjectorRegistryInput;\n execSql: ExecSql;\n patch?: Partial<StoredDocumentRecord> | undefined;\n pendingUpdate?: PendingUpdateFields | undefined;\n}\n\nasync function loadSupersededPersistedDocumentState(input: {\n creationSuperseded: boolean;\n execSql: ExecSql;\n localId: string;\n persistence: DocumentsPersistence;\n record: StoredDocumentRecord;\n syncIdentitySuperseded: boolean;\n}): Promise<PersistedDocumentState | null> {\n const { document, historyRestoreState } =\n await input.persistence.loadDocumentWithHistoryRestoreState(\n input.execSql,\n input.localId,\n );\n if (!document) return null;\n const syncIdentitySuperseded =\n input.syncIdentitySuperseded ||\n !documentSyncSecurityContextMatches(document, input.record);\n return {\n ...(input.creationSuperseded ? { creationSuperseded: true as const } : {}),\n historyRestoreState,\n pullContinuationSuperseded: true,\n record: document,\n ...(syncIdentitySuperseded\n ? { syncIdentitySuperseded: true as const }\n : {}),\n };\n}\n\nfunction resolveNullableDocumentRuntimeField(\n patch: Partial<StoredDocumentRecord>,\n key: NullableDocumentRuntimeField,\n currentValue: string | null | undefined,\n resetWhenUnpatched = false,\n): string | null {\n if (Object.hasOwn(patch, key)) return patch[key] ?? null;\n return resetWhenUnpatched ? null : (currentValue ?? null);\n}\n\nfunction resolveStoredDocumentContainerId(input: {\n containerId?: string | null | undefined;\n currentRecord: StoredDocumentRecord | null;\n patch: Partial<StoredDocumentRecord>;\n}): string | null {\n if (Object.hasOwn(input.patch, \"containerId\")) {\n return input.patch.containerId ?? null;\n }\n return input.currentRecord?.containerId ?? input.containerId ?? null;\n}\n\nfunction resolveStoredDocumentPullState(input: {\n currentRecord: StoredDocumentRecord | null;\n patch: Partial<StoredDocumentRecord>;\n securityContextChanged: boolean;\n}): Pick<\n StoredDocumentRecord,\n \"pullContinuation\" | \"pullContinuationRecoveryRequired\"\n> {\n if (Object.hasOwn(input.patch, \"pullContinuation\")) {\n return { pullContinuation: input.patch.pullContinuation ?? null };\n }\n if (input.securityContextChanged) return { pullContinuation: null };\n if (input.currentRecord?.pullContinuationRecoveryRequired) {\n return { pullContinuationRecoveryRequired: true };\n }\n return { pullContinuation: input.currentRecord?.pullContinuation ?? null };\n}\n\nfunction buildStoredDocumentRecord(input: {\n containerId?: string | null | undefined;\n currentDoc: DocumentContentState;\n currentRecord: StoredDocumentRecord | null;\n documentProjectors: DocumentProjectorRegistry;\n localId: string;\n patch: Partial<StoredDocumentRecord>;\n}) {\n const { currentDoc, currentRecord, documentProjectors, localId, patch } =\n input;\n const currentDocumentId = currentRecord?.documentId ?? null;\n const nextDocumentId = patch.documentId ?? currentDocumentId;\n const documentIdChanged = nextDocumentId !== currentDocumentId;\n const currentAccessEpoch =\n currentRecord?.accessEpoch ?? DEFAULT_DOCUMENT_ACCESS_EPOCH;\n const nextAccessEpoch = patch.accessEpoch ?? currentAccessEpoch;\n const securityContextChanged =\n documentIdChanged || nextAccessEpoch !== currentAccessEpoch;\n const documentState = readStoredDocumentState(currentDoc, documentProjectors);\n const record: StoredDocumentRecord = {\n id: currentRecord?.id ?? localId,\n accessEpoch: nextAccessEpoch,\n accessStateHash: resolveNullableDocumentRuntimeField(\n patch,\n \"accessStateHash\",\n currentRecord?.accessStateHash,\n securityContextChanged,\n ),\n containerId: resolveStoredDocumentContainerId({\n containerId: input.containerId,\n currentRecord,\n patch,\n }),\n contentKeyBundle: resolveNullableDocumentRuntimeField(\n patch,\n \"contentKeyBundle\",\n currentRecord?.contentKeyBundle,\n securityContextChanged,\n ),\n documentId: nextDocumentId,\n effectiveAccessLevel:\n patch.effectiveAccessLevel ?? currentRecord?.effectiveAccessLevel ?? null,\n documentKekTargets: resolveNullableDocumentRuntimeField(\n patch,\n \"documentKekTargets\",\n currentRecord?.documentKekTargets,\n securityContextChanged,\n ),\n documentKind: patch.documentKind ?? documentState.documentKind,\n documentManifestBundle: resolveNullableDocumentRuntimeField(\n patch,\n \"documentManifestBundle\",\n currentRecord?.documentManifestBundle,\n securityContextChanged,\n ),\n lastCommitLsn: resolveNullableDocumentRuntimeField(\n patch,\n \"lastCommitLsn\",\n currentRecord?.lastCommitLsn,\n documentIdChanged,\n ),\n snapshotEndVersion:\n patch.snapshotEndVersion ?? currentRecord?.snapshotEndVersion ?? \"\",\n pendingBaseVersion:\n patch.pendingBaseVersion !== undefined\n ? patch.pendingBaseVersion\n : (currentRecord?.pendingBaseVersion ?? null),\n recoveryGeneration:\n patch.recoveryGeneration ?? currentRecord?.recoveryGeneration ?? 0,\n ...resolveStoredDocumentPullState({\n currentRecord,\n patch,\n securityContextChanged,\n }),\n text: patch.text ?? getTextValue(currentDoc),\n title: patch.title ?? documentState.title,\n };\n return { documentState, record };\n}\n\nasync function saveDocumentClientProjection(input: {\n currentRecord: StoredDocumentRecord | null;\n documentProjectors: DocumentProjectorRegistry;\n documentState: ReturnType<typeof readStoredDocumentState>;\n execSql: ExecSql;\n localId: string;\n record: StoredDocumentRecord;\n updatedAt: string;\n}): Promise<void> {\n const previousKind =\n input.currentRecord?.documentKind ?? DEFAULT_DOCUMENT_KIND;\n const nextKind = input.record.documentKind ?? DEFAULT_DOCUMENT_KIND;\n if (previousKind !== nextKind) {\n await input.documentProjectors.deleteStoredDocumentClientProjection({\n documentKind: previousKind,\n execSql: input.execSql,\n localId: input.localId,\n });\n }\n await input.documentProjectors.saveStoredDocumentClientProjection({\n containerId: input.record.containerId,\n documentId: input.record.documentId,\n documentKind: nextKind,\n execSql: input.execSql,\n localId: input.record.id,\n structuredFields: input.documentState.structuredFields,\n text: input.record.text,\n title: input.record.title ?? input.documentState.title,\n updatedAt: input.updatedAt,\n });\n}\n\nasync function settleSupersededDocumentMutation(input: {\n acceptedPendingUpdateIds: readonly string[];\n lockedExecSql: ExecSql;\n mutation: Awaited<ReturnType<typeof prepareDocumentMutation>>;\n persistInput: PersistDocumentStateInput;\n}): Promise<PersistedDocumentState | null> {\n const { mutation, persistInput } = input;\n if (!mutation.mutationCurrentRecord) return null;\n const authoritativeRecord = persistInput.expectedSyncState\n ? await persistInput.persistence.settleAcceptedPendingUpdates(\n input.lockedExecSql,\n {\n expectedRecord: persistInput.expectedSyncState.record,\n pendingUpdateIds: input.acceptedPendingUpdateIds,\n },\n )\n : mutation.mutationCurrentRecord;\n if (!authoritativeRecord) return null;\n return loadSupersededPersistedDocumentState({\n creationSuperseded: mutation.creationSuperseded,\n execSql: input.lockedExecSql,\n localId: persistInput.localId,\n persistence: persistInput.persistence,\n record: authoritativeRecord,\n syncIdentitySuperseded: !mutation.securityContextMatches,\n });\n}\n\nasync function loadConcurrentCreationWinner(input: {\n execSql: ExecSql;\n persistInput: PersistDocumentStateInput;\n}): Promise<PersistedDocumentState> {\n const winningRecord = await input.persistInput.persistence.loadDocument(\n input.execSql,\n input.persistInput.localId,\n );\n if (!winningRecord) {\n throw new Error(\"Concurrent document creation lost without a winner\");\n }\n const winner = await loadSupersededPersistedDocumentState({\n creationSuperseded: true,\n execSql: input.execSql,\n localId: input.persistInput.localId,\n persistence: input.persistInput.persistence,\n record: winningRecord,\n syncIdentitySuperseded: true,\n });\n if (!winner) {\n throw new Error(\"Concurrent document creation winner disappeared\");\n }\n return winner;\n}\n\nasync function resolveInitialDocumentCreation(input: {\n execSql: ExecSql;\n persistInput: PersistDocumentStateInput;\n record: StoredDocumentRecord;\n savedAt: Awaited<\n ReturnType<DocumentsPersistence[\"createDocumentWithHistoryCheckpoint\"]>\n >;\n}): Promise<PersistedDocumentState | null> {\n if (typeof input.savedAt === \"string\") {\n return { record: input.record, updatedAt: input.savedAt };\n }\n // A discovered alias is not a concurrent local winner. Leave its backing\n // store untouched and refuse until a caller can establish verified identity.\n if (input.savedAt?.status === \"remote-alias\") return null;\n if (\n input.persistInput.canStartDurableMutation &&\n !input.persistInput.canStartDurableMutation()\n ) {\n return null;\n }\n return loadConcurrentCreationWinner({\n execSql: input.execSql,\n persistInput: input.persistInput,\n });\n}\n\nasync function resolveDocumentMutationCommit(input: {\n committed: Awaited<\n ReturnType<DocumentsPersistence[\"commitDocumentMutation\"]>\n >;\n lockedExecSql: ExecSql;\n persistInput: PersistDocumentStateInput;\n record: StoredDocumentRecord;\n}): Promise<PersistedDocumentState | null | \"retry\"> {\n const { committed, persistInput, record } = input;\n if (\n persistInput.canStartDurableMutation &&\n !persistInput.canStartDurableMutation()\n ) {\n return null;\n }\n if (committed.committed) return { record, updatedAt: committed.updatedAt };\n if (!committed.currentRecord) return null;\n if (persistInput.expectedSyncState === undefined) return \"retry\";\n return loadSupersededPersistedDocumentState({\n creationSuperseded: false,\n execSql: input.lockedExecSql,\n localId: persistInput.localId,\n persistence: persistInput.persistence,\n record: committed.currentRecord,\n syncIdentitySuperseded: !documentSyncSecurityContextMatches(\n committed.currentRecord,\n persistInput.expectedSyncState.record,\n ),\n });\n}\n\nasync function commitOnePreparedDocumentMutation(input: {\n acceptedPendingUpdateIds: readonly string[];\n documentProjectors: DocumentProjectorRegistry;\n lockedExecSql: ExecSql;\n mutation: Exclude<\n Awaited<ReturnType<typeof prepareDocumentMutation>>,\n { pullContinuationSuperseded: true }\n >;\n persistInput: PersistDocumentStateInput;\n}): Promise<PersistedDocumentState | null | \"retry\"> {\n const { mutation, persistInput } = input;\n const { documentState, record } = buildStoredDocumentRecord({\n containerId: persistInput.containerId,\n currentDoc: persistInput.currentDoc,\n currentRecord: mutation.mutationCurrentRecord,\n documentProjectors: input.documentProjectors,\n localId: persistInput.localId,\n patch: mutation.resolvedPatch,\n });\n if (!mutation.mutationCurrentRecord) {\n const savedAt = await createInitialDocumentRows({\n currentDoc: persistInput.currentDoc,\n execSql: input.lockedExecSql,\n pendingUpdate: persistInput.pendingUpdate,\n persistence: persistInput.persistence,\n record,\n stillCurrent: persistInput.canStartDurableMutation,\n saveClientProjection: (transactionExecSql, updatedAt) =>\n saveDocumentClientProjection({\n currentRecord: null,\n documentProjectors: input.documentProjectors,\n documentState,\n execSql: transactionExecSql,\n localId: persistInput.localId,\n record,\n updatedAt,\n }),\n });\n return resolveInitialDocumentCreation({\n execSql: input.lockedExecSql,\n persistInput,\n record,\n savedAt,\n });\n }\n\n const committed = await persistInput.persistence.commitDocumentMutation(\n input.lockedExecSql,\n {\n acceptedPendingUpdateIds: input.acceptedPendingUpdateIds,\n clearSyncFailure: persistInput.clearSyncFailure,\n ...(persistInput.attachmentRemoval\n ? { attachmentRemoval: persistInput.attachmentRemoval }\n : {}),\n ...(persistInput.attachmentStaging\n ? { attachmentStaging: persistInput.attachmentStaging }\n : {}),\n document: record,\n expectedRecord: mutation.mutationCurrentRecord,\n ...(persistInput.historyCheckpoint\n ? { historyCheckpoint: persistInput.historyCheckpoint }\n : {}),\n ...(persistInput.historyUpdateOrigin\n ? { historyUpdateOrigin: persistInput.historyUpdateOrigin }\n : {}),\n ...(persistInput.historyUpdates\n ? { historyUpdates: persistInput.historyUpdates }\n : {}),\n ...(persistInput.pendingUpdate\n ? { pendingUpdate: persistInput.pendingUpdate }\n : {}),\n settleAcceptedPendingOnConflict:\n persistInput.expectedSyncState !== undefined,\n ...(persistInput.canStartDurableMutation\n ? { stillCurrent: persistInput.canStartDurableMutation }\n : {}),\n },\n async (transactionExecSql, updatedAt) => {\n await saveDocumentClientProjection({\n currentRecord: mutation.mutationCurrentRecord,\n documentProjectors: input.documentProjectors,\n documentState,\n execSql: transactionExecSql,\n localId: persistInput.localId,\n record,\n updatedAt,\n });\n await persistInput.commitSideEffect?.(transactionExecSql);\n },\n );\n return resolveDocumentMutationCommit({\n committed,\n lockedExecSql: input.lockedExecSql,\n persistInput,\n record,\n });\n}\n\nexport async function commitPreparedDocumentState(input: {\n documentProjectors: DocumentProjectorRegistry;\n lockedExecSql: ExecSql;\n patch: Partial<StoredDocumentRecord>;\n persistInput: PersistDocumentStateInput;\n}): Promise<PersistedDocumentState | null> {\n const { lockedExecSql, persistInput } = input;\n const acceptedPendingUpdateIds = persistInput.acceptedPendingUpdateIds ?? [];\n for (\n let attempt = 0;\n attempt < MAX_DOCUMENT_MUTATION_COMMIT_ATTEMPTS;\n attempt += 1\n ) {\n const mutation = await prepareDocumentMutationUnlessDeleted({\n deleteDocumentPlacements: persistInput.deleteDocumentPlacements,\n documentProjectors: input.documentProjectors,\n guard: attempt === 0,\n lockedExecSql,\n patch: input.patch,\n persistInput,\n });\n if (!mutation) return null;\n if (mutation.pullContinuationSuperseded) {\n return settleSupersededDocumentMutation({\n acceptedPendingUpdateIds,\n lockedExecSql,\n mutation,\n persistInput,\n });\n }\n const result = await commitOnePreparedDocumentMutation({\n acceptedPendingUpdateIds,\n documentProjectors: input.documentProjectors,\n lockedExecSql,\n mutation,\n persistInput,\n });\n if (result !== \"retry\") return result;\n }\n throw new Error(\n `Document mutation commit gave up after ${MAX_DOCUMENT_MUTATION_COMMIT_ATTEMPTS} concurrent conflicts`,\n );\n}\n"]}
1
+ {"version":3,"file":"documentMutationCommit.js","sourceRoot":"","sources":["documentMutationCommit.ts"],"names":[],"mapp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AAY,CAAC,wBAAwB;YAC/D,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;YAC5C,KAAK,EAAE,OAAO,KAAK,CAAC;YACpB,aAAa;YACb,KAAK,EAAE,KAAK,CAAC,KAAK;YAClB,YAAY;SACb,CAAC,CAAC;QACH,IAAI,CAAC,QAAQ;YAAE,OAAO,IAAI,CAAC;QAC3B,IAAI,QAAQ,CAAC,0BAA0B,EAAE,CAAC;YACxC,OAAO,gCAAgC,CAAC;gBACtC,wBAAwB;gBACxB,aAAa;gBACb,QAAQ;gBACR,YAAY;aACb,CAAC,CAAC;QACL,CAAC;QACD,MAAM,MAAM,GAAG,MAAM,iCAAiC,CAAC;YACrD,wBAAwB;YACxB,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;YAC5C,aAAa;YACb,QAAQ;YACR,YAAY;SACb,CAAC,CAAC;QACH,IAAI,MAAM,KAAK,OAAO;YAAE,OAAO,MAAM,CAAC;IACxC,CAAC;IACD,MAAM,IAAI,KAAK,CACb,0CAA0C,qCAAqC,uBAAuB,CACvG,CAAC;AACJ,CAAC","sourcesContent":["import { type encodeVersionVector, getTextValue } from \"@tearleads/loro\";\nimport {\n DEFAULT_DOCUMENT_ACCESS_EPOCH,\n DEFAULT_DOCUMENT_KIND,\n} from \"../../data/documents/documentConstants\";\nimport { serializeDocumentAttachmentNames } from \"../../data/documents/documentContent\";\nimport {\n type DocumentProjectorRegistry,\n type DocumentProjectorRegistryInput,\n readStoredDocumentState,\n} from \"../../data/documents/documentKinds\";\nimport type {\n DocumentPlacementCleanup,\n DocumentsPersistence,\n StoredDocumentRecord,\n} from \"../../data/persistence/documents/documentsPersistence\";\nimport type { PendingUpdateFields } from \"../../data/persistence/documents/records\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { createInitialDocumentRows } from \"./create/documentCreationPersistence\";\nimport {\n documentSyncSecurityContextMatches,\n type PrepareDocumentMutationInput,\n type prepareDocumentMutation,\n} from \"./documentMutationPreparation\";\nimport { prepareDocumentMutationUnlessDeleted } from \"./documentPersistGuards\";\n\ntype DocumentContentState = Parameters<typeof encodeVersionVector>[0];\ntype NullableDocumentRuntimeField =\n | \"accessStateHash\"\n | \"lastCommitLsn\"\n | \"contentKeyBundle\"\n | \"documentKekTargets\"\n | \"documentManifestBundle\";\n\nconst MAX_DOCUMENT_MUTATION_COMMIT_ATTEMPTS = 8;\n\nexport interface PersistedDocumentState {\n creationSuperseded?: true;\n historyRestoreState?:\n | Awaited<ReturnType<DocumentsPersistence[\"loadHistoryRestoreState\"]>>\n | undefined;\n pullContinuationSuperseded?: true;\n record: StoredDocumentRecord;\n syncIdentitySuperseded?: true;\n updatedAt?: string | undefined;\n}\n\nexport interface PersistDocumentStateInput\n extends PrepareDocumentMutationInput {\n acceptedPendingUpdateIds?: readonly string[] | undefined;\n attachmentRemoval?:\n | Parameters<\n DocumentsPersistence[\"commitDocumentMutation\"]\n >[1][\"attachmentRemoval\"]\n | undefined;\n attachmentStaging?:\n | Parameters<\n DocumentsPersistence[\"commitDocumentMutation\"]\n >[1][\"attachmentStaging\"]\n | undefined;\n canStartDurableMutation?: (() => boolean) | undefined;\n clearSyncFailure?: boolean | undefined;\n commitSideEffect?: (transactionExecSql: ExecSql) => Promise<void>;\n containerId?: string | null | undefined;\n deleteDocumentPlacements: DocumentPlacementCleanup;\n documentProjectors: DocumentProjectorRegistryInput;\n execSql: ExecSql;\n patch?: Partial<StoredDocumentRecord> | undefined;\n pendingUpdate?: PendingUpdateFields | undefined;\n}\n\nasync function loadSupersededPersistedDocumentState(input: {\n creationSuperseded: boolean;\n execSql: ExecSql;\n localId: string;\n persistence: DocumentsPersistence;\n record: StoredDocumentRecord;\n syncIdentitySuperseded: boolean;\n}): Promise<PersistedDocumentState | null> {\n const { document, historyRestoreState } =\n await input.persistence.loadDocumentWithHistoryRestoreState(\n input.execSql,\n input.localId,\n );\n if (!document) return null;\n const syncIdentitySuperseded =\n input.syncIdentitySuperseded ||\n !documentSyncSecurityContextMatches(document, input.record);\n return {\n ...(input.creationSuperseded ? { creationSuperseded: true as const } : {}),\n historyRestoreState,\n pullContinuationSuperseded: true,\n record: document,\n ...(syncIdentitySuperseded\n ? { syncIdentitySuperseded: true as const }\n : {}),\n };\n}\n\nfunction resolveNullableDocumentRuntimeField(\n patch: Partial<StoredDocumentRecord>,\n key: NullableDocumentRuntimeField,\n currentValue: string | null | undefined,\n resetWhenUnpatched = false,\n): string | null {\n if (Object.hasOwn(patch, key)) return patch[key] ?? null;\n return resetWhenUnpatched ? null : (currentValue ?? null);\n}\n\nfunction resolveStoredDocumentContainerId(input: {\n containerId?: string | null | undefined;\n currentRecord: StoredDocumentRecord | null;\n patch: Partial<StoredDocumentRecord>;\n}): string | null {\n if (Object.hasOwn(input.patch, \"containerId\")) {\n return input.patch.containerId ?? null;\n }\n return input.currentRecord?.containerId ?? input.containerId ?? null;\n}\n\nfunction resolveStoredDocumentPullState(input: {\n currentRecord: StoredDocumentRecord | null;\n patch: Partial<StoredDocumentRecord>;\n securityContextChanged: boolean;\n}): Pick<\n StoredDocumentRecord,\n \"pullContinuation\" | \"pullContinuationRecoveryRequired\"\n> {\n if (Object.hasOwn(input.patch, \"pullContinuation\")) {\n return { pullContinuation: input.patch.pullContinuation ?? null };\n }\n if (input.securityContextChanged) return { pullContinuation: null };\n if (input.currentRecord?.pullContinuationRecoveryRequired) {\n return { pullContinuationRecoveryRequired: true };\n }\n return { pullContinuation: input.currentRecord?.pullContinuation ?? null };\n}\n\nfunction buildStoredDocumentRecord(input: {\n containerId?: string | null | undefined;\n currentDoc: DocumentContentState;\n currentRecord: StoredDocumentRecord | null;\n documentProjectors: DocumentProjectorRegistry;\n localId: string;\n patch: Partial<StoredDocumentRecord>;\n}) {\n const { currentDoc, currentRecord, documentProjectors, localId, patch } =\n input;\n const currentDocumentId = currentRecord?.documentId ?? null;\n const nextDocumentId = patch.documentId ?? currentDocumentId;\n const documentIdChanged = nextDocumentId !== currentDocumentId;\n const currentAccessEpoch =\n currentRecord?.accessEpoch ?? DEFAULT_DOCUMENT_ACCESS_EPOCH;\n const nextAccessEpoch = patch.accessEpoch ?? currentAccessEpoch;\n const securityContextChanged =\n documentIdChanged || nextAccessEpoch !== currentAccessEpoch;\n const documentState = readStoredDocumentState(currentDoc, documentProjectors);\n const record: StoredDocumentRecord = {\n id: currentRecord?.id ?? localId,\n accessEpoch: nextAccessEpoch,\n accessStateHash: resolveNullableDocumentRuntimeField(\n patch,\n \"accessStateHash\",\n currentRecord?.accessStateHash,\n securityContextChanged,\n ),\n containerId: resolveStoredDocumentContainerId({\n containerId: input.containerId,\n currentRecord,\n patch,\n }),\n contentKeyBundle: resolveNullableDocumentRuntimeField(\n patch,\n \"contentKeyBundle\",\n currentRecord?.contentKeyBundle,\n securityContextChanged,\n ),\n documentId: nextDocumentId,\n effectiveAccessLevel:\n patch.effectiveAccessLevel ?? currentRecord?.effectiveAccessLevel ?? null,\n documentKekTargets: resolveNullableDocumentRuntimeField(\n patch,\n \"documentKekTargets\",\n currentRecord?.documentKekTargets,\n securityContextChanged,\n ),\n documentKind: patch.documentKind ?? documentState.documentKind,\n documentManifestBundle: resolveNullableDocumentRuntimeField(\n patch,\n \"documentManifestBundle\",\n currentRecord?.documentManifestBundle,\n securityContextChanged,\n ),\n lastCommitLsn: resolveNullableDocumentRuntimeField(\n patch,\n \"lastCommitLsn\",\n currentRecord?.lastCommitLsn,\n documentIdChanged,\n ),\n snapshotEndVersion:\n patch.snapshotEndVersion ?? currentRecord?.snapshotEndVersion ?? \"\",\n pendingBaseVersion:\n patch.pendingBaseVersion !== undefined\n ? patch.pendingBaseVersion\n : (currentRecord?.pendingBaseVersion ?? null),\n recoveryGeneration:\n patch.recoveryGeneration ?? currentRecord?.recoveryGeneration ?? 0,\n ...resolveStoredDocumentPullState({\n currentRecord,\n patch,\n securityContextChanged,\n }),\n text: patch.text ?? getTextValue(currentDoc),\n title: patch.title ?? documentState.title,\n };\n return { documentState, record };\n}\n\nasync function saveDocumentClientProjection(input: {\n currentRecord: StoredDocumentRecord | null;\n documentProjectors: DocumentProjectorRegistry;\n documentState: ReturnType<typeof readStoredDocumentState>;\n execSql: ExecSql;\n localId: string;\n record: StoredDocumentRecord;\n updatedAt: string;\n}): Promise<void> {\n const previousKind =\n input.currentRecord?.documentKind ?? DEFAULT_DOCUMENT_KIND;\n const nextKind = input.record.documentKind ?? DEFAULT_DOCUMENT_KIND;\n if (previousKind !== nextKind) {\n await input.documentProjectors.deleteStoredDocumentClientProjection({\n documentKind: previousKind,\n execSql: input.execSql,\n localId: input.localId,\n });\n }\n await input.documentProjectors.saveStoredDocumentClientProjection({\n containerId: input.record.containerId,\n documentId: input.record.documentId,\n documentKind: nextKind,\n execSql: input.execSql,\n localId: input.record.id,\n structuredFields: input.documentState.structuredFields,\n text: input.record.text,\n title: input.record.title ?? input.documentState.title,\n updatedAt: input.updatedAt,\n });\n}\n\nasync function settleSupersededDocumentMutation(input: {\n acceptedPendingUpdateIds: readonly string[];\n lockedExecSql: ExecSql;\n mutation: Awaited<ReturnType<typeof prepareDocumentMutation>>;\n persistInput: PersistDocumentStateInput;\n}): Promise<PersistedDocumentState | null> {\n const { mutation, persistInput } = input;\n if (!mutation.mutationCurrentRecord) return null;\n const authoritativeRecord = persistInput.expectedSyncState\n ? await persistInput.persistence.settleAcceptedPendingUpdates(\n input.lockedExecSql,\n {\n expectedRecord: persistInput.expectedSyncState.record,\n pendingUpdateIds: input.acceptedPendingUpdateIds,\n },\n )\n : mutation.mutationCurrentRecord;\n if (!authoritativeRecord) return null;\n return loadSupersededPersistedDocumentState({\n creationSuperseded: mutation.creationSuperseded,\n execSql: input.lockedExecSql,\n localId: persistInput.localId,\n persistence: persistInput.persistence,\n record: authoritativeRecord,\n syncIdentitySuperseded: !mutation.securityContextMatches,\n });\n}\n\nasync function loadConcurrentCreationWinner(input: {\n execSql: ExecSql;\n persistInput: PersistDocumentStateInput;\n}): Promise<PersistedDocumentState> {\n const winningRecord = await input.persistInput.persistence.loadDocument(\n input.execSql,\n input.persistInput.localId,\n );\n if (!winningRecord) {\n throw new Error(\"Concurrent document creation lost without a winner\");\n }\n const winner = await loadSupersededPersistedDocumentState({\n creationSuperseded: true,\n execSql: input.execSql,\n localId: input.persistInput.localId,\n persistence: input.persistInput.persistence,\n record: winningRecord,\n syncIdentitySuperseded: true,\n });\n if (!winner) {\n throw new Error(\"Concurrent document creation winner disappeared\");\n }\n return winner;\n}\n\nasync function resolveInitialDocumentCreation(input: {\n execSql: ExecSql;\n persistInput: PersistDocumentStateInput;\n record: StoredDocumentRecord;\n savedAt: Awaited<\n ReturnType<DocumentsPersistence[\"createDocumentWithHistoryCheckpoint\"]>\n >;\n}): Promise<PersistedDocumentState | null> {\n if (typeof input.savedAt === \"string\") {\n return { record: input.record, updatedAt: input.savedAt };\n }\n // A discovered alias is not a concurrent local winner. Leave its backing\n // store untouched and refuse until a caller can establish verified identity.\n if (input.savedAt?.status === \"remote-alias\") return null;\n if (\n input.persistInput.canStartDurableMutation &&\n !input.persistInput.canStartDurableMutation()\n ) {\n return null;\n }\n return loadConcurrentCreationWinner({\n execSql: input.execSql,\n persistInput: input.persistInput,\n });\n}\n\nasync function resolveDocumentMutationCommit(input: {\n committed: Awaited<\n ReturnType<DocumentsPersistence[\"commitDocumentMutation\"]>\n >;\n lockedExecSql: ExecSql;\n persistInput: PersistDocumentStateInput;\n record: StoredDocumentRecord;\n}): Promise<PersistedDocumentState | null | \"retry\"> {\n const { committed, persistInput, record } = input;\n if (\n persistInput.canStartDurableMutation &&\n !persistInput.canStartDurableMutation()\n ) {\n return null;\n }\n if (committed.committed) return { record, updatedAt: committed.updatedAt };\n if (!committed.currentRecord) return null;\n if (persistInput.expectedSyncState === undefined) return \"retry\";\n return loadSupersededPersistedDocumentState({\n creationSuperseded: false,\n execSql: input.lockedExecSql,\n localId: persistInput.localId,\n persistence: persistInput.persistence,\n record: committed.currentRecord,\n syncIdentitySuperseded: !documentSyncSecurityContextMatches(\n committed.currentRecord,\n persistInput.expectedSyncState.record,\n ),\n });\n}\n\nasync function commitOnePreparedDocumentMutation(input: {\n acceptedPendingUpdateIds: readonly string[];\n documentProjectors: DocumentProjectorRegistry;\n lockedExecSql: ExecSql;\n mutation: Exclude<\n Awaited<ReturnType<typeof prepareDocumentMutation>>,\n { pullContinuationSuperseded: true }\n >;\n persistInput: PersistDocumentStateInput;\n}): Promise<PersistedDocumentState | null | \"retry\"> {\n const { mutation, persistInput } = input;\n const { documentState, record } = buildStoredDocumentRecord({\n containerId: persistInput.containerId,\n currentDoc: persistInput.currentDoc,\n currentRecord: mutation.mutationCurrentRecord,\n documentProjectors: input.documentProjectors,\n localId: persistInput.localId,\n patch: mutation.resolvedPatch,\n });\n const saveClientProjection = (execSql: ExecSql, updatedAt: string) =>\n saveDocumentClientProjection({\n currentRecord: mutation.mutationCurrentRecord,\n documentProjectors: input.documentProjectors,\n documentState,\n execSql,\n localId: persistInput.localId,\n record,\n updatedAt,\n });\n if (!mutation.mutationCurrentRecord) {\n const savedAt = await createInitialDocumentRows({\n currentDoc: persistInput.currentDoc,\n execSql: input.lockedExecSql,\n pendingUpdate: persistInput.pendingUpdate,\n persistence: persistInput.persistence,\n record,\n stillCurrent: persistInput.canStartDurableMutation,\n saveClientProjection,\n });\n return resolveInitialDocumentCreation({\n execSql: input.lockedExecSql,\n persistInput,\n record,\n savedAt,\n });\n }\n\n const committed = await persistInput.persistence.commitDocumentMutation(\n input.lockedExecSql,\n {\n acceptedPendingUpdateIds: input.acceptedPendingUpdateIds,\n attachmentNames: serializeDocumentAttachmentNames(\n persistInput.currentDoc,\n ),\n clearSyncFailure: persistInput.clearSyncFailure,\n ...(persistInput.attachmentRemoval\n ? { attachmentRemoval: persistInput.attachmentRemoval }\n : {}),\n ...(persistInput.attachmentStaging\n ? { attachmentStaging: persistInput.attachmentStaging }\n : {}),\n document: record,\n expectedRecord: mutation.mutationCurrentRecord,\n ...(persistInput.historyCheckpoint\n ? { historyCheckpoint: persistInput.historyCheckpoint }\n : {}),\n ...(persistInput.historyUpdateOrigin\n ? { historyUpdateOrigin: persistInput.historyUpdateOrigin }\n : {}),\n ...(persistInput.historyUpdates\n ? { historyUpdates: persistInput.historyUpdates }\n : {}),\n ...(persistInput.pendingUpdate\n ? { pendingUpdate: persistInput.pendingUpdate }\n : {}),\n settleAcceptedPendingOnConflict:\n persistInput.expectedSyncState !== undefined,\n ...(persistInput.canStartDurableMutation\n ? { stillCurrent: persistInput.canStartDurableMutation }\n : {}),\n },\n async (transactionExecSql, updatedAt) => {\n await saveClientProjection(transactionExecSql, updatedAt);\n await persistInput.commitSideEffect?.(transactionExecSql);\n },\n );\n return resolveDocumentMutationCommit({\n committed,\n lockedExecSql: input.lockedExecSql,\n persistInput,\n record,\n });\n}\n\nexport async function commitPreparedDocumentState(input: {\n documentProjectors: DocumentProjectorRegistry;\n lockedExecSql: ExecSql;\n patch: Partial<StoredDocumentRecord>;\n persistInput: PersistDocumentStateInput;\n}): Promise<PersistedDocumentState | null> {\n const { lockedExecSql, persistInput } = input;\n const acceptedPendingUpdateIds = persistInput.acceptedPendingUpdateIds ?? [];\n for (\n let attempt = 0;\n attempt < MAX_DOCUMENT_MUTATION_COMMIT_ATTEMPTS;\n attempt += 1\n ) {\n const mutation = await prepareDocumentMutationUnlessDeleted({\n deleteDocumentPlacements: persistInput.deleteDocumentPlacements,\n documentProjectors: input.documentProjectors,\n guard: attempt === 0,\n lockedExecSql,\n patch: input.patch,\n persistInput,\n });\n if (!mutation) return null;\n if (mutation.pullContinuationSuperseded) {\n return settleSupersededDocumentMutation({\n acceptedPendingUpdateIds,\n lockedExecSql,\n mutation,\n persistInput,\n });\n }\n const result = await commitOnePreparedDocumentMutation({\n acceptedPendingUpdateIds,\n documentProjectors: input.documentProjectors,\n lockedExecSql,\n mutation,\n persistInput,\n });\n if (result !== \"retry\") return result;\n }\n throw new Error(\n `Document mutation commit gave up after ${MAX_DOCUMENT_MUTATION_COMMIT_ATTEMPTS} concurrent conflicts`,\n );\n}\n"]}
@@ -26,3 +26,4 @@ export declare function loadPersistedDocumentContent(input: {
26
26
  localId: string;
27
27
  persistence: DocumentsPersistence;
28
28
  }): Promise<Awaited<ReturnType<typeof createDocument>> | null>;
29
+ export declare function restorePersistedDocumentContent(history: Awaited<ReturnType<DocumentsPersistence["loadHistoryRestoreState"]>>): Promise<Awaited<ReturnType<typeof createDocument>> | null>;