@tearleads/client-sdk 0.1.216 → 0.1.217

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.
@@ -45,15 +45,26 @@ export interface OrganizationSyncPauses {
45
45
  */
46
46
  runExclusive<T>(task: () => Promise<T>): Promise<T>;
47
47
  }
48
- /** The one pause set for a domain scope; a new scope starts unloaded. */
49
- export declare function getOrCreateOrganizationSyncPauses(domainScope: DomainScope): OrganizationSyncPauses;
50
48
  /**
51
- * Records, in the caller's transaction, that a pause's cleanup removed this
52
- * document, so reopening it does not recreate it while the pause lasts.
49
+ * Persistence for organization sync pauses and the documents a pause's
50
+ * cleanup removed, bound to one executor.
53
51
  */
54
- export declare function recordPauseRemovedDocument(execSql: ExecSql, removal: {
55
- readonly localId: string;
56
- readonly organizationId: string;
57
- }): Promise<void>;
58
- /** Whether a pause's cleanup removed this document and the pause still holds. */
59
- export declare function isPauseRemovedDocument(execSql: ExecSql, localId: string): Promise<boolean>;
52
+ export declare class OrganizationSyncPauseRepository {
53
+ private readonly execSql;
54
+ constructor(execSql: ExecSql);
55
+ readPausedOrganizationIds(): Promise<Set<string>>;
56
+ writePausedOrganizationIds(organizationIds: ReadonlySet<string>): Promise<void>;
57
+ /**
58
+ * Records, in the caller's transaction, that a pause's cleanup removed this
59
+ * document, so reopening it does not recreate it while the pause lasts.
60
+ * A plain insert on the bound executor; it never opens a transaction.
61
+ */
62
+ recordPauseRemovedDocument(removal: {
63
+ readonly localId: string;
64
+ readonly organizationId: string;
65
+ }): Promise<void>;
66
+ /** Whether a pause's cleanup removed this document and the pause holds. */
67
+ isPauseRemovedDocument(localId: string): Promise<boolean>;
68
+ }
69
+ /** The one pause set for a domain scope; a new scope starts unloaded. */
70
+ export declare function getOrCreateOrganizationSyncPauses(domainScope: DomainScope): OrganizationSyncPauses;
@@ -12,41 +12,78 @@ import { ensureSqlTables, runSerializedSqlMutation, } from "../sqlite/sqlSchema.
12
12
  export function isRetainedWhileSyncPaused(container) {
13
13
  return container.parentId === null && Boolean(container.systemSlot);
14
14
  }
15
- async function readPausedOrganizationIds(execSql) {
16
- await ensureSqlTables(execSql, organizationSyncPauseTables);
17
- const rows = await getClientSQLitePersistenceRuntime(execSql)
18
- .db.select({ organizationId: organizationSyncPauses.organizationId })
19
- .from(organizationSyncPauses);
20
- return new Set(rows.map((row) => row.organizationId));
21
- }
22
- // One transaction replaces the whole set, so a failed write keeps the
23
- // previous pauses in force; inserts go in batches within SQLite's bind budget.
24
- async function writePausedOrganizationIds(execSql, organizationIds) {
25
- await runSerializedSqlMutation(execSql, async (lockedExecSql) => {
26
- await ensureSqlTables(lockedExecSql, organizationSyncPauseTables);
27
- const ids = [...organizationIds];
28
- const batchSize = sqliteInsertBatchSize(organizationSyncPauses);
29
- await getClientSQLitePersistenceRuntime(lockedExecSql).transaction(async (tx) => {
30
- await tx.delete(organizationSyncPauses).run();
31
- for (let index = 0; index < ids.length; index += batchSize) {
15
+ /**
16
+ * Persistence for organization sync pauses and the documents a pause's
17
+ * cleanup removed, bound to one executor.
18
+ */
19
+ export class OrganizationSyncPauseRepository {
20
+ execSql;
21
+ constructor(execSql) {
22
+ this.execSql = execSql;
23
+ }
24
+ async readPausedOrganizationIds() {
25
+ await ensureSqlTables(this.execSql, organizationSyncPauseTables);
26
+ const rows = await getClientSQLitePersistenceRuntime(this.execSql)
27
+ .db.select({ organizationId: organizationSyncPauses.organizationId })
28
+ .from(organizationSyncPauses);
29
+ return new Set(rows.map((row) => row.organizationId));
30
+ }
31
+ // One transaction replaces the whole set, so a failed write keeps the
32
+ // previous pauses in force; inserts go in batches within SQLite's bind
33
+ // budget.
34
+ async writePausedOrganizationIds(organizationIds) {
35
+ await runSerializedSqlMutation(this.execSql, async (lockedExecSql) => {
36
+ await ensureSqlTables(lockedExecSql, organizationSyncPauseTables);
37
+ const ids = [...organizationIds];
38
+ const batchSize = sqliteInsertBatchSize(organizationSyncPauses);
39
+ await getClientSQLitePersistenceRuntime(lockedExecSql).transaction(async (tx) => {
40
+ await tx.delete(organizationSyncPauses).run();
41
+ for (let index = 0; index < ids.length; index += batchSize) {
42
+ await tx
43
+ .insert(organizationSyncPauses)
44
+ .values(ids
45
+ .slice(index, index + batchSize)
46
+ .map((organizationId) => ({ organizationId })))
47
+ .run();
48
+ }
49
+ // A resumed organization's removed documents may be reopened again.
32
50
  await tx
33
- .insert(organizationSyncPauses)
34
- .values(ids
35
- .slice(index, index + batchSize)
36
- .map((organizationId) => ({ organizationId })))
51
+ .delete(organizationSyncPauseRemovals)
52
+ .where(notInArray(organizationSyncPauseRemovals.organizationId, tx
53
+ .select({
54
+ organizationId: organizationSyncPauses.organizationId,
55
+ })
56
+ .from(organizationSyncPauses)))
37
57
  .run();
38
- }
39
- // A resumed organization's removed documents may be reopened again.
40
- await tx
41
- .delete(organizationSyncPauseRemovals)
42
- .where(notInArray(organizationSyncPauseRemovals.organizationId, tx
43
- .select({
44
- organizationId: organizationSyncPauses.organizationId,
45
- })
46
- .from(organizationSyncPauses)))
47
- .run();
58
+ });
48
59
  });
49
- });
60
+ }
61
+ /**
62
+ * Records, in the caller's transaction, that a pause's cleanup removed this
63
+ * document, so reopening it does not recreate it while the pause lasts.
64
+ * A plain insert on the bound executor; it never opens a transaction.
65
+ */
66
+ async recordPauseRemovedDocument(removal) {
67
+ await ensureSqlTables(this.execSql, organizationSyncPauseTables);
68
+ await getClientSQLitePersistenceRuntime(this.execSql)
69
+ .db.insert(organizationSyncPauseRemovals)
70
+ .values(removal)
71
+ .onConflictDoUpdate({
72
+ set: { organizationId: removal.organizationId },
73
+ target: organizationSyncPauseRemovals.localId,
74
+ })
75
+ .run();
76
+ }
77
+ /** Whether a pause's cleanup removed this document and the pause holds. */
78
+ async isPauseRemovedDocument(localId) {
79
+ await ensureSqlTables(this.execSql, organizationSyncPauseTables);
80
+ const rows = await getClientSQLitePersistenceRuntime(this.execSql)
81
+ .db.select({ localId: organizationSyncPauseRemovals.localId })
82
+ .from(organizationSyncPauseRemovals)
83
+ .where(eq(organizationSyncPauseRemovals.localId, localId))
84
+ .limit(1);
85
+ return rows.length > 0;
86
+ }
50
87
  }
51
88
  function createOrganizationSyncPauses() {
52
89
  let paused = new Set();
@@ -60,7 +97,9 @@ function createOrganizationSyncPauses() {
60
97
  };
61
98
  const pauses = {
62
99
  load(execSql) {
63
- loading ??= readPausedOrganizationIds(execSql).then((stored) => {
100
+ loading ??= new OrganizationSyncPauseRepository(execSql)
101
+ .readPausedOrganizationIds()
102
+ .then((stored) => {
64
103
  paused = stored;
65
104
  if (stored.size > 0)
66
105
  notify();
@@ -89,7 +128,7 @@ function createOrganizationSyncPauses() {
89
128
  if (change.paused.length === 0 && change.resumed.length === 0) {
90
129
  return change;
91
130
  }
92
- await writePausedOrganizationIds(execSql, next);
131
+ await new OrganizationSyncPauseRepository(execSql).writePausedOrganizationIds(next);
93
132
  paused = next;
94
133
  notify();
95
134
  return change;
@@ -121,29 +160,4 @@ export function getOrCreateOrganizationSyncPauses(domainScope) {
121
160
  }
122
161
  return pauses;
123
162
  }
124
- /**
125
- * Records, in the caller's transaction, that a pause's cleanup removed this
126
- * document, so reopening it does not recreate it while the pause lasts.
127
- */
128
- export async function recordPauseRemovedDocument(execSql, removal) {
129
- await ensureSqlTables(execSql, organizationSyncPauseTables);
130
- await getClientSQLitePersistenceRuntime(execSql)
131
- .db.insert(organizationSyncPauseRemovals)
132
- .values(removal)
133
- .onConflictDoUpdate({
134
- set: { organizationId: removal.organizationId },
135
- target: organizationSyncPauseRemovals.localId,
136
- })
137
- .run();
138
- }
139
- /** Whether a pause's cleanup removed this document and the pause still holds. */
140
- export async function isPauseRemovedDocument(execSql, localId) {
141
- await ensureSqlTables(execSql, organizationSyncPauseTables);
142
- const rows = await getClientSQLitePersistenceRuntime(execSql)
143
- .db.select({ localId: organizationSyncPauseRemovals.localId })
144
- .from(organizationSyncPauseRemovals)
145
- .where(eq(organizationSyncPauseRemovals.localId, localId))
146
- .limit(1);
147
- return rows.length > 0;
148
- }
149
163
  //# sourceMappingURL=organizationSyncPauses.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"organizationSyncPauses.js","sourceRoot":"","sources":["organizationSyncPauses.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAE7C,OAAO,EACL,6BAA6B,EAC7B,sBAAsB,EACtB,2BAA2B,GAC5B,MAAM,8CAA8C,CAAC;AACtD,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACnE,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AACvF,OAAO,EAEL,eAAe,EACf,wBAAwB,GACzB,MAAM,qBAAqB,CAAC;AAS7B;;;;;GAKG;AACH,MAAM,UAAU,yBAAyB,CACvC,SAAuC;IAEvC,OAAO,SAAS,CAAC,QAAQ,KAAK,IAAI,IAAI,OAAO,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;AACtE,CAAC;AA0CD,KAAK,UAAU,yBAAyB,CACtC,OAAgB;IAEhB,MAAM,eAAe,CAAC,OAAO,EAAE,2BAA2B,CAAC,CAAC;IAC5D,MAAM,IAAI,GAAG,MAAM,iCAAiC,CAAC,OAAO,CAAC;SAC1D,EAAE,CAAC,MAAM,CAAC,EAAE,cAAc,EAAE,sBAAsB,CAAC,cAAc,EAAE,CAAC;SACpE,IAAI,CAAC,sBAAsB,CAAC,CAAC;IAChC,OAAO,IAAI,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC;AACxD,CAAC;AAED,sEAAsE;AACtE,+EAA+E;AAC/E,KAAK,UAAU,0BAA0B,CACvC,OAAgB,EAChB,eAAoC;IAEpC,MAAM,wBAAwB,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;QAC9D,MAAM,eAAe,CAAC,aAAa,EAAE,2BAA2B,CAAC,CAAC;QAClE,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AG,aAAa,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IAC5C,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,GAAG,4BAA4B,EAAE,CAAC;QACxC,aAAa,CAAC,GAAG,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;IACzC,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,0BAA0B,CAC9C,OAAgB,EAChB,OAAsE;IAEtE,MAAM,eAAe,CAAC,OAAO,EAAE,2BAA2B,CAAC,CAAC;IAC5D,MAAM,iCAAiC,CAAC,OAAO,CAAC;SAC7C,EAAE,CAAC,MAAM,CAAC,6BAA6B,CAAC;SACxC,MAAM,CAAC,OAAO,CAAC;SACf,kBAAkB,CAAC;QAClB,GAAG,EAAE,EAAE,cAAc,EAAE,OAAO,CAAC,cAAc,EAAE;QAC/C,MAAM,EAAE,6BAA6B,CAAC,OAAO;KAC9C,CAAC;SACD,GAAG,EAAE,CAAC;AACX,CAAC;AAED,iFAAiF;AACjF,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,OAAgB,EAChB,OAAe;IAEf,MAAM,eAAe,CAAC,OAAO,EAAE,2BAA2B,CAAC,CAAC;IAC5D,MAAM,IAAI,GAAG,MAAM,iCAAiC,CAAC,OAAO,CAAC;SAC1D,EAAE,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,6BAA6B,CAAC,OAAO,EAAE,CAAC;SAC7D,IAAI,CAAC,6BAA6B,CAAC;SACnC,KAAK,CAAC,EAAE,CAAC,6BAA6B,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;SACzD,KAAK,CAAC,CAAC,CAAC,CAAC;IACZ,OAAO,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;AACzB,CAAC","sourcesContent":["import { eq, notInArray } from \"drizzle-orm\";\nimport type { DomainScope } from \"../shared/domainScope\";\nimport {\n organizationSyncPauseRemovals,\n organizationSyncPauses,\n organizationSyncPauseTables,\n} from \"../sqlite/schema/organizationSyncPauseSchema\";\nimport { sqliteInsertBatchSize } from \"../sqlite/sqliteBindBudget\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../sqlite/sqlSchema\";\n\n/** The container fields the pause rule reads. */\nexport interface OrganizationSyncPauseSubject {\n readonly organizationId: string;\n readonly parentId: string | null;\n readonly systemSlot?: string | null | undefined;\n}\n\n/**\n * Whether a container stays on the device while its organization is paused:\n * only the organization's parentless system root, the metadata root every\n * Members recipient reads, which keeps the organization named and its\n * membership visible.\n */\nexport function isRetainedWhileSyncPaused(\n container: OrganizationSyncPauseSubject,\n): boolean {\n return container.parentId === null && Boolean(container.systemSlot);\n}\n\nexport interface OrganizationSyncPauseChange {\n readonly paused: readonly string[];\n readonly resumed: readonly string[];\n}\n\n/**\n * Which organizations this user paused syncing to their devices, for one\n * domain scope. Sync reads it synchronously once `load` has settled; the\n * persisted set lets a device that starts offline keep honoring a pause.\n */\nexport interface OrganizationSyncPauses {\n /** Loads the persisted set once; concurrent and later calls share it. */\n load(execSql: ExecSql): Promise<void>;\n isOrganizationPaused(organizationId: string): boolean;\n /**\n * Whether sync skips this container: every container of a paused\n * organization except the one `isRetainedWhileSyncPaused` keeps. The\n * session's active organization is never skipped, even when paused from\n * another device: its root is the session's workspace until it switches\n * away.\n */\n isContainerPaused(\n container: OrganizationSyncPauseSubject,\n activeOrganizationId: string | null,\n ): boolean;\n pausedOrganizationIds(): ReadonlySet<string>;\n /** Persists exactly this set and reports which organizations changed. */\n replace(\n execSql: ExecSql,\n organizationIds: Iterable<string>,\n ): Promise<OrganizationSyncPauseChange>;\n subscribe(listener: () => void): () => void;\n /**\n * Runs membership work for this scope one task at a time, so a membership\n * read that started before a pause or resume cannot apply after it.\n * Re-entrant calls from inside a task would wait on themselves.\n */\n runExclusive<T>(task: () => Promise<T>): Promise<T>;\n}\n\nasync function readPausedOrganizationIds(\n execSql: ExecSql,\n): Promise<Set<string>> {\n await ensureSqlTables(execSql, organizationSyncPauseTables);\n const rows = await getClientSQLitePersistenceRuntime(execSql)\n .db.select({ organizationId: organizationSyncPauses.organizationId })\n .from(organizationSyncPauses);\n return new Set(rows.map((row) => row.organizationId));\n}\n\n// One transaction replaces the whole set, so a failed write keeps the\n// previous pauses in force; inserts go in batches within SQLite's bind budget.\nasync function writePausedOrganizationIds(\n execSql: ExecSql,\n organizationIds: ReadonlySet<string>,\n): Promise<void> {\n await runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureSqlTables(lockedExecSql, organizationSyncPauseTables);\n const ids = [...organizationIds];\n const batchSize = sqliteInsertBatchSize(organizationSyncPauses);\n await getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n await tx.delete(organizationSyncPauses).run();\n for (let index = 0; index < ids.length; index += batchSize) {\n await tx\n .insert(organizationSyncPauses)\n .values(\n ids\n .slice(index, index + batchSize)\n .map((organizationId) => ({ organizationId })),\n )\n .run();\n }\n // A resumed organization's removed documents may be reopened again.\n await tx\n .delete(organizationSyncPauseRemovals)\n .where(\n notInArray(\n organizationSyncPauseRemovals.organizationId,\n tx\n .select({\n organizationId: organizationSyncPauses.organizationId,\n })\n .from(organizationSyncPauses),\n ),\n )\n .run();\n },\n );\n });\n}\n\nfunction createOrganizationSyncPauses(): OrganizationSyncPauses {\n let paused: ReadonlySet<string> = new Set();\n let loading: Promise<void> | null = null;\n let replacing: Promise<void> = Promise.resolve();\n let exclusive: Promise<void> = Promise.resolve();\n const listeners = new Set<() => void>();\n const notify = () => {\n for (const listener of listeners) listener();\n };\n\n const pauses: OrganizationSyncPauses = {\n load(execSql) {\n loading ??= readPausedOrganizationIds(execSql).then(\n (stored) => {\n paused = stored;\n if (stored.size > 0) notify();\n },\n (error: unknown) => {\n // Let a later call retry a failed read.\n loading = null;\n throw error;\n },\n );\n return loading;\n },\n isOrganizationPaused: (organizationId) => paused.has(organizationId),\n isContainerPaused: (container, activeOrganizationId) =>\n paused.has(container.organizationId) &&\n container.organizationId !== activeOrganizationId &&\n !isRetainedWhileSyncPaused(container),\n pausedOrganizationIds: () => paused,\n replace(execSql, organizationIds) {\n const next = new Set(organizationIds);\n // Serialize replacements so each one diffs against the set the previous\n // one committed.\n const run = replacing.then(async () => {\n await pauses.load(execSql);\n const change = {\n paused: [...next].filter((id) => !paused.has(id)).sort(),\n resumed: [...paused].filter((id) => !next.has(id)).sort(),\n };\n if (change.paused.length === 0 && change.resumed.length === 0) {\n return change;\n }\n await writePausedOrganizationIds(execSql, next);\n paused = next;\n notify();\n return change;\n });\n replacing = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n runExclusive(task) {\n const run = exclusive.then(task);\n exclusive = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n },\n };\n return pauses;\n}\n\nconst pausesByScope = new WeakMap<DomainScope, OrganizationSyncPauses>();\n\n/** The one pause set for a domain scope; a new scope starts unloaded. */\nexport function getOrCreateOrganizationSyncPauses(\n domainScope: DomainScope,\n): OrganizationSyncPauses {\n let pauses = pausesByScope.get(domainScope);\n if (!pauses) {\n pauses = createOrganizationSyncPauses();\n pausesByScope.set(domainScope, pauses);\n }\n return pauses;\n}\n\n/**\n * Records, in the caller's transaction, that a pause's cleanup removed this\n * document, so reopening it does not recreate it while the pause lasts.\n */\nexport async function recordPauseRemovedDocument(\n execSql: ExecSql,\n removal: { readonly localId: string; readonly organizationId: string },\n): Promise<void> {\n await ensureSqlTables(execSql, organizationSyncPauseTables);\n await getClientSQLitePersistenceRuntime(execSql)\n .db.insert(organizationSyncPauseRemovals)\n .values(removal)\n .onConflictDoUpdate({\n set: { organizationId: removal.organizationId },\n target: organizationSyncPauseRemovals.localId,\n })\n .run();\n}\n\n/** Whether a pause's cleanup removed this document and the pause still holds. */\nexport async function isPauseRemovedDocument(\n execSql: ExecSql,\n localId: string,\n): Promise<boolean> {\n await ensureSqlTables(execSql, organizationSyncPauseTables);\n const rows = await getClientSQLitePersistenceRuntime(execSql)\n .db.select({ localId: organizationSyncPauseRemovals.localId })\n .from(organizationSyncPauseRemovals)\n .where(eq(organizationSyncPauseRemovals.localId, localId))\n .limit(1);\n return rows.length > 0;\n}\n"]}
1
+ {"version":3,"file":"organizationSyncPauses.js","sourceRoot":"","sources":["organizationSyncPauses.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAE7C,OAAO,EACL,6BAA6B,EAC7B,sBAAsB,EACtB,2BAA2B,GAC5B,MAAM,8CAA8C,CAAC;AACtD,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACnE,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AACvF,OAAO,EAEL,eAAe,EACf,wBAAwB,GACzB,MAAM,qBAAqB,CAAC;AAS7B;;;;;GAKG;AACH,MAAM,UAAU,yBAAyB,CACvC,SAAuC;IAEvC,OAAO,SAAS,CAAC,QAAQ,KAAK,IAAI,IAAI,OAAO,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;AACtE,CAAC;AA0CD;;;GAGG;AACH,MAAM,OAAO,+BAA+B;IACzB,OAAO,CAAU;IAElC,YAAY,OAAgB;QAC1B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED,KAAK,CAAC,yBAAyB;QAC7B,MAAM,eAAe,CAAC,IAAI,CAAC,OAAO,EAAE,2BAA2B,CAAC,CAAC;QACjE,MAAM,IAAI,GAAG,MAAM,iCAAiC,CAAC,IAAI,CAAC,OAAO,CAAC;aAC/D,EAAE,CAAC,MAAM,CAAC,EAAE,cAAc,EAAE,sBAAsB,CAAC,cAAc,EAAE,CAAC;aACpE,IAAI,CAAC,sBAAsB,CAAC,CAAC;QAChC,OAAO,IAAI,GAAG,CAAC,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,UAAU,iCAAiC,CAC/C,WAAwB;IAExB,IAAI,MAAM,GAAG,aAAa,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IAC5C,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,GAAG,4BAA4B,EAAE,CAAC;QACxC,aAAa,CAAC,GAAG,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;IACzC,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { eq, notInArray } from \"drizzle-orm\";\nimport type { DomainScope } from \"../shared/domainScope\";\nimport {\n organizationSyncPauseRemovals,\n organizationSyncPauses,\n organizationSyncPauseTables,\n} from \"../sqlite/schema/organizationSyncPauseSchema\";\nimport { sqliteInsertBatchSize } from \"../sqlite/sqliteBindBudget\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../sqlite/sqlSchema\";\n\n/** The container fields the pause rule reads. */\nexport interface OrganizationSyncPauseSubject {\n readonly organizationId: string;\n readonly parentId: string | null;\n readonly systemSlot?: string | null | undefined;\n}\n\n/**\n * Whether a container stays on the device while its organization is paused:\n * only the organization's parentless system root, the metadata root every\n * Members recipient reads, which keeps the organization named and its\n * membership visible.\n */\nexport function isRetainedWhileSyncPaused(\n container: OrganizationSyncPauseSubject,\n): boolean {\n return container.parentId === null && Boolean(container.systemSlot);\n}\n\nexport interface OrganizationSyncPauseChange {\n readonly paused: readonly string[];\n readonly resumed: readonly string[];\n}\n\n/**\n * Which organizations this user paused syncing to their devices, for one\n * domain scope. Sync reads it synchronously once `load` has settled; the\n * persisted set lets a device that starts offline keep honoring a pause.\n */\nexport interface OrganizationSyncPauses {\n /** Loads the persisted set once; concurrent and later calls share it. */\n load(execSql: ExecSql): Promise<void>;\n isOrganizationPaused(organizationId: string): boolean;\n /**\n * Whether sync skips this container: every container of a paused\n * organization except the one `isRetainedWhileSyncPaused` keeps. The\n * session's active organization is never skipped, even when paused from\n * another device: its root is the session's workspace until it switches\n * away.\n */\n isContainerPaused(\n container: OrganizationSyncPauseSubject,\n activeOrganizationId: string | null,\n ): boolean;\n pausedOrganizationIds(): ReadonlySet<string>;\n /** Persists exactly this set and reports which organizations changed. */\n replace(\n execSql: ExecSql,\n organizationIds: Iterable<string>,\n ): Promise<OrganizationSyncPauseChange>;\n subscribe(listener: () => void): () => void;\n /**\n * Runs membership work for this scope one task at a time, so a membership\n * read that started before a pause or resume cannot apply after it.\n * Re-entrant calls from inside a task would wait on themselves.\n */\n runExclusive<T>(task: () => Promise<T>): Promise<T>;\n}\n\n/**\n * Persistence for organization sync pauses and the documents a pause's\n * cleanup removed, bound to one executor.\n */\nexport class OrganizationSyncPauseRepository {\n private readonly execSql: ExecSql;\n\n constructor(execSql: ExecSql) {\n this.execSql = execSql;\n }\n\n async readPausedOrganizationIds(): Promise<Set<string>> {\n await ensureSqlTables(this.execSql, organizationSyncPauseTables);\n const rows = await getClientSQLitePersistenceRuntime(this.execSql)\n .db.select({ organizationId: organizationSyncPauses.organizationId })\n .from(organizationSyncPauses);\n return new Set(rows.map((row) => row.organizationId));\n }\n\n // One transaction replaces the whole set, so a failed write keeps the\n // previous pauses in force; inserts go in batches within SQLite's bind\n // budget.\n async writePausedOrganizationIds(\n organizationIds: ReadonlySet<string>,\n ): Promise<void> {\n await runSerializedSqlMutation(this.execSql, async (lockedExecSql) => {\n await ensureSqlTables(lockedExecSql, organizationSyncPauseTables);\n const ids = [...organizationIds];\n const batchSize = sqliteInsertBatchSize(organizationSyncPauses);\n await getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n await tx.delete(organizationSyncPauses).run();\n for (let index = 0; index < ids.length; index += batchSize) {\n await tx\n .insert(organizationSyncPauses)\n .values(\n ids\n .slice(index, index + batchSize)\n .map((organizationId) => ({ organizationId })),\n )\n .run();\n }\n // A resumed organization's removed documents may be reopened again.\n await tx\n .delete(organizationSyncPauseRemovals)\n .where(\n notInArray(\n organizationSyncPauseRemovals.organizationId,\n tx\n .select({\n organizationId: organizationSyncPauses.organizationId,\n })\n .from(organizationSyncPauses),\n ),\n )\n .run();\n },\n );\n });\n }\n\n /**\n * Records, in the caller's transaction, that a pause's cleanup removed this\n * document, so reopening it does not recreate it while the pause lasts.\n * A plain insert on the bound executor; it never opens a transaction.\n */\n async recordPauseRemovedDocument(removal: {\n readonly localId: string;\n readonly organizationId: string;\n }): Promise<void> {\n await ensureSqlTables(this.execSql, organizationSyncPauseTables);\n await getClientSQLitePersistenceRuntime(this.execSql)\n .db.insert(organizationSyncPauseRemovals)\n .values(removal)\n .onConflictDoUpdate({\n set: { organizationId: removal.organizationId },\n target: organizationSyncPauseRemovals.localId,\n })\n .run();\n }\n\n /** Whether a pause's cleanup removed this document and the pause holds. */\n async isPauseRemovedDocument(localId: string): Promise<boolean> {\n await ensureSqlTables(this.execSql, organizationSyncPauseTables);\n const rows = await getClientSQLitePersistenceRuntime(this.execSql)\n .db.select({ localId: organizationSyncPauseRemovals.localId })\n .from(organizationSyncPauseRemovals)\n .where(eq(organizationSyncPauseRemovals.localId, localId))\n .limit(1);\n return rows.length > 0;\n }\n}\n\nfunction createOrganizationSyncPauses(): OrganizationSyncPauses {\n let paused: ReadonlySet<string> = new Set();\n let loading: Promise<void> | null = null;\n let replacing: Promise<void> = Promise.resolve();\n let exclusive: Promise<void> = Promise.resolve();\n const listeners = new Set<() => void>();\n const notify = () => {\n for (const listener of listeners) listener();\n };\n\n const pauses: OrganizationSyncPauses = {\n load(execSql) {\n loading ??= new OrganizationSyncPauseRepository(execSql)\n .readPausedOrganizationIds()\n .then(\n (stored) => {\n paused = stored;\n if (stored.size > 0) notify();\n },\n (error: unknown) => {\n // Let a later call retry a failed read.\n loading = null;\n throw error;\n },\n );\n return loading;\n },\n isOrganizationPaused: (organizationId) => paused.has(organizationId),\n isContainerPaused: (container, activeOrganizationId) =>\n paused.has(container.organizationId) &&\n container.organizationId !== activeOrganizationId &&\n !isRetainedWhileSyncPaused(container),\n pausedOrganizationIds: () => paused,\n replace(execSql, organizationIds) {\n const next = new Set(organizationIds);\n // Serialize replacements so each one diffs against the set the previous\n // one committed.\n const run = replacing.then(async () => {\n await pauses.load(execSql);\n const change = {\n paused: [...next].filter((id) => !paused.has(id)).sort(),\n resumed: [...paused].filter((id) => !next.has(id)).sort(),\n };\n if (change.paused.length === 0 && change.resumed.length === 0) {\n return change;\n }\n await new OrganizationSyncPauseRepository(\n execSql,\n ).writePausedOrganizationIds(next);\n paused = next;\n notify();\n return change;\n });\n replacing = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n runExclusive(task) {\n const run = exclusive.then(task);\n exclusive = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n },\n };\n return pauses;\n}\n\nconst pausesByScope = new WeakMap<DomainScope, OrganizationSyncPauses>();\n\n/** The one pause set for a domain scope; a new scope starts unloaded. */\nexport function getOrCreateOrganizationSyncPauses(\n domainScope: DomainScope,\n): OrganizationSyncPauses {\n let pauses = pausesByScope.get(domainScope);\n if (!pauses) {\n pauses = createOrganizationSyncPauses();\n pausesByScope.set(domainScope, pauses);\n }\n return pauses;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/client-sdk",
3
- "version": "0.1.216",
3
+ "version": "0.1.217",
4
4
  "description": "React-free Tearleads client runtime: local SQLite persistence, keys, sync, encrypted blobs, and domain workflows.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -4,7 +4,7 @@ import { DEFAULT_DOCUMENT_ACCESS_EPOCH, DEFAULT_DOCUMENT_KIND, } from "../../../
4
4
  import { initializeStoredDocumentKind, readStoredDocumentState, } from "../../../../data/documents/documentKinds.js";
5
5
  import { createPendingUpdateFields } from "../../../../data/documents/documentSync.js";
6
6
  import { isDatabaseUnavailableError, loadPersistedDocumentStoreState, } from "../../../../workflows/documents/index.js";
7
- import { isPauseRemovedDocument } from "../../../../workflows/sync/index.js";
7
+ import { OrganizationSyncPauseRepository } from "../../../../workflows/sync/index.js";
8
8
  import { chainIdentityWrite } from "../identityWriteChain.js";
9
9
  import { runDocumentOrphanMaintenance } from "../orphanMaintenance.js";
10
10
  import { advancePendingBaseVersion, documentSummaryFromRecord, persistDocument, saveDocumentRecord, } from "../persistence.js";
@@ -159,7 +159,7 @@ async function initializeDocumentStore(state, scheduleSync) {
159
159
  // download the organization's content while the pause lasts. A later open
160
160
  // retries, so it loads once the organization resumes.
161
161
  if (!persistedState.document &&
162
- (await isPauseRemovedDocument(state.runtime.infra.execSql, state.localId))) {
162
+ (await new OrganizationSyncPauseRepository(state.runtime.infra.execSql).isPauseRemovedDocument(state.localId))) {
163
163
  state.initializePromise = null;
164
164
  return;
165
165
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,gBAAgB,EAChB,yBAAyB,EACzB,mBAAmB,GACpB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,6BAA6B,EAC7B,qBAAqB,GACtB,MAAM,8CAA8C,CAAC;AACtD,OAAO,EACL,4BAA4B,EAC5B,uBAAuB,GACxB,MAAM,0CAA0C,CAAC;AAElD,OAAO,EAAE,yBAAyB,EAAE,MAAM,yCAAyC,CAAC;AACpF,OAAO,EAEL,0BAA0B,EAC1B,+BAA+B,GAChC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAEpE,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAE3D,OAAO,EAAE,4BAA4B,EAAE,MAAM,sBAAsB,CAAC;AACpE,OAAO,EACL,yBAAyB,EACzB,yBAAyB,EACzB,eAAe,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D,OAAO,yBAAyB,CAC9B,SAAS,CAAC,MAAM,EAChB,SAAS,CAAC,SAAS,EACnB,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,kBAAkB,CACvC,CAAC;AACJ,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n emptyVersionVector,\n encodeVersionVector,\n exportAllUpdates,\n exportFullHistorySnapshot,\n mergeVersionVectors,\n} from \"@tearleads/loro\";\nimport {\n DEFAULT_DOCUMENT_ACCESS_EPOCH,\n DEFAULT_DOCUMENT_KIND,\n} from \"../../../../data/documents/documentConstants\";\nimport {\n initializeStoredDocumentKind,\n readStoredDocumentState,\n} from \"../../../../data/documents/documentKinds\";\nimport type { DocumentSummary } from \"../../../../data/documents/documentSummary\";\nimport { createPendingUpdateFields } from \"../../../../data/documents/documentSync\";\nimport {\n type DocumentRecord,\n isDatabaseUnavailableError,\n loadPersistedDocumentStoreState,\n} from \"../../../../workflows/documents\";\nimport { isPauseRemovedDocument } from \"../../../../workflows/sync\";\nimport type { DocumentStoreRelinkInput } from \"../../types\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport type { DocumentRelinkCommitSideEffect } from \"../internalRelink\";\nimport { runDocumentOrphanMaintenance } from \"../orphanMaintenance\";\nimport {\n advancePendingBaseVersion,\n documentSummaryFromRecord,\n persistDocument,\n saveDocumentRecord,\n} from \"../persistence\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n setReadySnapshot,\n} from \"../state\";\nimport { createStoredDocument } from \"../storedDocument\";\nimport { logRevalidationScheduled } from \"../sync/remoteRevalidationTelemetry\";\nimport { deferStartupProbeToPendingConnect } from \"../sync/startupProbeDeferral\";\nimport {\n allowDocumentStoreRemoteSync,\n captureDocumentStoreSyncGeneration,\n invalidateDocumentStoreRemoteSync,\n isDocumentStoreSyncGenerationCurrent,\n markDocumentStoreRemoteSyncPending,\n} from \"../sync/syncGeneration\";\nimport { writeInitialDocumentContent } from \"./initialContent\";\nimport {\n installPersistedAttachments,\n type LoadedDocumentStoreState,\n} from \"./initializationAttachments\";\nimport {\n type RestoredHistoryState,\n restoredRemoteTailCoverage,\n restorePersistedDocumentContent,\n} from \"./initializationHistory\";\nimport {\n healLocalAttachmentDetachState,\n recoverDroppedAttachmentSlots,\n} from \"./initializationRecovery\";\nimport { relinkRecordPatch } from \"./relinkRecordPatch\";\n\nasync function createInitialDocumentRecord(\n state: DocumentStoreState,\n nextDoc: DocumentState,\n): ReturnType<typeof saveDocumentRecord> {\n initializeStoredDocumentKind(\n nextDoc,\n state.initialDocumentKind,\n state.runtime.infra.documentProjectors,\n );\n if (state.initialText.length > 0) {\n nextDoc.getText(\"text\").update(state.initialText);\n }\n const wroteInitialContent = writeInitialDocumentContent(state, nextDoc);\n const initialDocumentState = readStoredDocumentState(\n nextDoc,\n state.runtime.infra.documentProjectors,\n );\n const hasInitialContent =\n wroteInitialContent ||\n state.initialText.length > 0 ||\n state.initialDocumentKind !== DEFAULT_DOCUMENT_KIND;\n const initialUpdate = hasInitialContent\n ? createPendingUpdateFields(exportAllUpdates(nextDoc))\n : null;\n // A deferred birth still commits its checkpoint, but leaves the marker at the\n // empty version with nothing queued: the promised attach exports every op\n // since that marker, so one update carries the birth and the attachment.\n const birthDurability = !initialUpdate\n ? {}\n : state.deferInitialUpdate\n ? { pendingBaseVersionOverride: emptyVersionVector() }\n : { pendingUpdate: initialUpdate };\n\n const created: DocumentRecord = {\n id: state.localId,\n containerId: state.runtime.state.containerId ?? null,\n documentId: state.initialDocumentId,\n documentKind: initialDocumentState.documentKind,\n text: initialDocumentState.text,\n title: initialDocumentState.title,\n snapshotEndVersion: encodeVersionVector(nextDoc),\n accessEpoch: DEFAULT_DOCUMENT_ACCESS_EPOCH,\n accessStateHash: null,\n effectiveAccessLevel: \"admin\",\n lastCommitLsn: null,\n contentKeyBundle: null,\n documentKekTargets: null,\n documentManifestBundle: null,\n };\n // The create-only persistence primitive commits the canonical row and birth\n // checkpoint together. A concurrent initializer either wins both or adopts\n // both, so it cannot replace another pane's history or keying state.\n const persisted = await saveDocumentRecord(\n state,\n nextDoc,\n {\n ...created,\n snapshotEndVersion: encodeVersionVector(nextDoc),\n },\n {\n historyCheckpoint: {\n coveredTailIds: [],\n endVersionVector: encodeVersionVector(nextDoc),\n pruneCoveredLocalState: false,\n snapshot: bytesToBase64(exportFullHistorySnapshot(nextDoc)),\n },\n ...birthDurability,\n },\n );\n return persisted;\n}\n\nfunction installPersistedDocumentRecord(\n state: DocumentStoreState,\n record: NonNullable<DocumentStoreState[\"record\"]>,\n): void {\n state.record = record;\n state.pullContinuation = record.pullContinuation ?? null;\n}\n\ninterface RestoredInitialDocumentState {\n activePersistedState: LoadedDocumentStoreState;\n activeRecord: NonNullable<DocumentStoreState[\"record\"]>;\n doc: DocumentState;\n history: RestoredHistoryState | null;\n}\n\nasync function restoreLoadedInitialDocument(input: {\n initializeGeneration: number;\n nextDoc: DocumentState;\n persistedState: LoadedDocumentStoreState;\n state: DocumentStoreState;\n}): Promise<RestoredInitialDocumentState | null> {\n const { initializeGeneration, persistedState, state } = input;\n const record = persistedState.document;\n if (!record) return null;\n const history = await restorePersistedDocumentContent(\n input.nextDoc,\n persistedState.historyRestoreState,\n );\n if (state.localWriteGeneration !== initializeGeneration) return null;\n installPersistedDocumentRecord(state, record);\n return {\n activePersistedState: persistedState,\n activeRecord: record,\n doc: input.nextDoc,\n history,\n };\n}\n\nasync function restoreOrCreateInitialDocument(input: {\n initializeGeneration: number;\n nextDoc: DocumentState;\n persistedState: LoadedDocumentStoreState;\n state: DocumentStoreState;\n}): Promise<RestoredInitialDocumentState | null> {\n const { initializeGeneration, persistedState, state } = input;\n if (persistedState.document) {\n return restoreLoadedInitialDocument(input);\n }\n const created = await createInitialDocumentRecord(state, input.nextDoc);\n if (!created || state.localWriteGeneration !== initializeGeneration) {\n return null;\n }\n const activePersistedState = await loadPersistedDocumentStoreState({\n execSql: state.runtime.infra.execSql,\n localId: state.localId,\n persistence: state.persistence,\n });\n if (state.localWriteGeneration !== initializeGeneration) {\n return null;\n }\n if (!activePersistedState.document) {\n throw new Error(\"Document creation completed without a durable record\");\n }\n const replacementDoc = await createStoredDocument(state);\n return restoreLoadedInitialDocument({\n initializeGeneration,\n nextDoc: replacementDoc,\n persistedState: activePersistedState,\n state,\n });\n}\n\nfunction restorePendingBaseVersion(input: {\n activeRecord: NonNullable<DocumentStoreState[\"record\"]>;\n doc: DocumentState;\n history: RestoredHistoryState | null;\n state: DocumentStoreState;\n}): void {\n const { activeRecord, doc, history, state } = input;\n const markerBase =\n activeRecord.pendingBaseVersion ??\n (activeRecord.snapshotEndVersion.length > 0\n ? activeRecord.snapshotEndVersion\n : null);\n if (markerBase === null) {\n advancePendingBaseVersion(state, doc);\n return;\n }\n\n const remoteCoverage = restoredRemoteTailCoverage(history);\n state.pendingBaseVersion =\n remoteCoverage.length > 0\n ? mergeVersionVectors([markerBase, ...remoteCoverage])\n : markerBase;\n}\n\nasync function initializeDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n) {\n if (state.runtime.infra.dbStatus !== \"ready\") {\n return;\n }\n\n // A store reset while this fire-and-forget initialization is loading (a\n // runtime swap, or a local-edits discard that re-seeds the persisted rows)\n // must win: assigning the state loaded BEFORE the reset would bring the\n // replaced record and doc back to life. Every reset bumps the local write\n // generation, so a stale capture here aborts before each assignment batch.\n const initializeGeneration = state.localWriteGeneration;\n\n const nextDoc = await createStoredDocument(state);\n const persistedState = await loadPersistedDocumentStoreState({\n execSql: state.runtime.infra.execSql,\n localId: state.localId,\n persistence: state.persistence,\n });\n if (state.localWriteGeneration !== initializeGeneration) {\n return;\n }\n // A paused organization's cleanup removed it; creating it again would\n // download the organization's content while the pause lasts. A later open\n // retries, so it loads once the organization resumes.\n if (\n !persistedState.document &&\n (await isPauseRemovedDocument(state.runtime.infra.execSql, state.localId))\n ) {\n state.initializePromise = null;\n return;\n }\n const restored = await restoreOrCreateInitialDocument({\n initializeGeneration,\n nextDoc,\n persistedState,\n state,\n });\n if (!restored) {\n if (state.localWriteGeneration === initializeGeneration) {\n state.initializePromise = null;\n }\n return;\n }\n const activePersistedState = restored.activePersistedState;\n installPersistedAttachments(state, activePersistedState);\n\n state.doc = restored.doc;\n // Restore the durable outgoing-delta marker. Re-seeding it to the restored\n // document's version would move it PAST any device-first `deferRemoteSync`\n // op (persisted into the durable history but deliberately left un-enqueued\n // and behind the marker), permanently dropping that op from sync across a\n // restart. When a marker was persisted, restore it so the next edit still\n // re-derives the deferred delta. Only seed for rows that never persisted\n // one, from the RECORD's persisted frontier rather than the restored\n // document: a crash between the tail append and the queue/marker writes can\n // resurrect ops the outgoing queue never durably received, and seeding from\n // the restored document would classify those as covered and orphan them\n // from sync forever.\n restorePendingBaseVersion({\n activeRecord: restored.activeRecord,\n doc: restored.doc,\n history: restored.history,\n state,\n });\n // Heal attachment slots lost to an interrupted attach write before marking\n // ready, so the recovered slots are in the snapshot the editor first renders\n // and are queued for sync. recoverDroppedAttachmentSlots advances the marker\n // again for whatever it re-derives. Both helpers gate every durable write\n // on this generation (validated inside the writes' serialized mutations),\n // so a reset mid-helper cannot repopulate discarded state.\n const writeGeneration = captureDocumentStoreSyncGeneration(\n state,\n restored.doc,\n );\n if (!writeGeneration) {\n return;\n }\n await recoverDroppedAttachmentSlots(state, restored.doc, writeGeneration);\n if (state.localWriteGeneration !== initializeGeneration) {\n return;\n }\n await healLocalAttachmentDetachState(\n state,\n restored.doc,\n activePersistedState,\n writeGeneration,\n );\n if (state.localWriteGeneration !== initializeGeneration) {\n return;\n }\n state.initialized = true;\n state.initializePromise = null;\n setReadySnapshot(state, restored.doc, false);\n\n // Websocket invalidations are intentionally session-local. A process can\n // stop before receiving a peer device's update event, and no event survives\n // the restart to distinguish a clean local snapshot from a stale one. Probe\n // each opened remote document once after loading it; unopened documents stay\n // lazy, while body and attachment state for a restored window converges.\n // A connect attempt in flight arms a later probe on its acknowledgement,\n // which covers this one, so the startup probe waits on that attempt.\n if (\n restored.activeRecord.documentId &&\n state.scheduleStartupRemoteSync &&\n !deferStartupProbeToPendingConnect(state)\n ) {\n allowDocumentStoreRemoteSync(state);\n markDocumentStoreRemoteSyncPending(state, \"independent\");\n logRevalidationScheduled(state.runtime, \"startup\");\n }\n scheduleSync();\n void runDocumentOrphanMaintenance(state);\n}\n\nexport function ensureDocumentStoreInitialized(\n state: DocumentStoreState,\n scheduleSync: () => void,\n) {\n if (\n state.initialized ||\n state.initializePromise ||\n state.runtime.infra.dbStatus !== \"ready\"\n ) {\n return;\n }\n\n const initializePromise = initializeDocumentStore(state, scheduleSync).catch(\n (error: unknown) => {\n state.initializePromise = null;\n // A caller that deferred the birth for its attach may give up once\n // opening fails; never leave its durable birth holding sync. No attach\n // has reached a live doc yet, so lifting the hold ships nothing unsafe.\n state.deferInitialUpdate = false;\n\n if (isDatabaseUnavailableError(error)) {\n return;\n }\n\n throw error;\n },\n );\n state.initializePromise = initializePromise;\n void initializePromise.catch(() => undefined);\n}\n\nexport async function awaitInitializationForSync(state: DocumentStoreState) {\n if (!state.initializePromise) {\n return state.initialized;\n }\n\n try {\n await state.initializePromise;\n return state.initialized;\n } catch (error) {\n if (isDatabaseUnavailableError(error)) {\n return false;\n }\n\n throw error;\n }\n}\n\nexport async function ensureDocumentStoreReady(\n state: DocumentStoreState,\n scheduleSync: () => void,\n): Promise<boolean> {\n ensureDocumentStoreInitialized(state, scheduleSync);\n\n if (state.initialized) {\n return true;\n }\n\n if (!state.initializePromise) {\n return false;\n }\n\n return awaitInitializationForSync(state);\n}\n\nexport async function relinkDocumentStore(\n state: DocumentStoreState,\n input: DocumentStoreRelinkInput,\n scheduleSync: () => void,\n commitSideEffect?: DocumentRelinkCommitSideEffect,\n): Promise<DocumentSummary | null> {\n if (\n input.stillCurrent?.() === false ||\n !(await ensureDocumentStoreReady(state, scheduleSync)) ||\n input.stillCurrent?.() === false ||\n !state.doc\n ) {\n return null;\n }\n const currentDoc = state.doc;\n const generation = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!generation) return null;\n // Read the record and persist on the identity-write chain so an in-flight\n // eager create cannot interleave: a create that captured a null identity\n // before its network round trip would otherwise write the derived documentId\n // over the one this relink assigns.\n const persisted = await chainIdentityWrite(state, async () => {\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) return null;\n const currentDocumentId = state.record?.documentId ?? null;\n const patch = relinkRecordPatch(state.record, input);\n\n // Relink rewrites access/identity metadata, not content. If it lands while\n // the user is mid-edit, re-deriving text/structured fields from the\n // (possibly lagging) doc would republish a stale read over the live\n // optimistic snapshot and drop in-flight keystrokes; preserve the snapshot\n // like the keystroke and sync persists do.\n // A prior chained write may have cleared this store (resurrect-guard\n // refusal): persisting the captured doc against a null record would\n // resurrect the document as a create. The identity check runs inside\n // the chain, after every earlier write settled.\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n return null;\n }\n const result = await persistDocument(\n state,\n currentDoc,\n patch,\n {\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n stillCurrent: input.stillCurrent,\n },\n generation,\n commitSideEffect,\n );\n if (result && currentDocumentId !== input.documentId) {\n state.writerProjection = null;\n invalidateDocumentStoreRemoteSync(state);\n }\n return result;\n });\n // A refused persist means the durable row vanished mid-relink (resurrect\n // guard); there is no summary to report.\n if (!persisted) {\n return null;\n }\n if (persisted.updatedAt === undefined) {\n return null;\n }\n return documentSummaryFromRecord(\n persisted.record,\n persisted.updatedAt,\n state.runtime.infra.documentProjectors,\n );\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,gBAAgB,EAChB,yBAAyB,EACzB,mBAAmB,GACpB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,6BAA6B,EAC7B,qBAAqB,GACtB,MAAM,8CAA8C,CAAC;AACtD,OAAO,EACL,4BAA4B,EAC5B,uBAAuB,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AAM,IAAI,iBAAiB,KAAK,KAAK,CAAC,UAAU,EAAE,CAAC;YACrD,KAAK,CAAC,gBAAgB,GAAG,IAAI,CAAC;YAC9B,iCAAiC,CAAC,KAAK,CAAC,CAAC;QAC3C,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC,CAAC;IACH,yEAAyE;IACzE,yCAAyC;IACzC,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,SAAS,CAAC,SAAS,KAAK,SAAS,EAAE,CAAC;QACtC,OAAO,IAAI,CAAC;IACd,CAAC;IACD,OAAO,yBAAyB,CAC9B,SAAS,CAAC,MAAM,EAChB,SAAS,CAAC,SAAS,EACnB,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,kBAAkB,CACvC,CAAC;AACJ,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n emptyVersionVector,\n encodeVersionVector,\n exportAllUpdates,\n exportFullHistorySnapshot,\n mergeVersionVectors,\n} from \"@tearleads/loro\";\nimport {\n DEFAULT_DOCUMENT_ACCESS_EPOCH,\n DEFAULT_DOCUMENT_KIND,\n} from \"../../../../data/documents/documentConstants\";\nimport {\n initializeStoredDocumentKind,\n readStoredDocumentState,\n} from \"../../../../data/documents/documentKinds\";\nimport type { DocumentSummary } from \"../../../../data/documents/documentSummary\";\nimport { createPendingUpdateFields } from \"../../../../data/documents/documentSync\";\nimport {\n type DocumentRecord,\n isDatabaseUnavailableError,\n loadPersistedDocumentStoreState,\n} from \"../../../../workflows/documents\";\nimport { OrganizationSyncPauseRepository } from \"../../../../workflows/sync\";\nimport type { DocumentStoreRelinkInput } from \"../../types\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport type { DocumentRelinkCommitSideEffect } from \"../internalRelink\";\nimport { runDocumentOrphanMaintenance } from \"../orphanMaintenance\";\nimport {\n advancePendingBaseVersion,\n documentSummaryFromRecord,\n persistDocument,\n saveDocumentRecord,\n} from \"../persistence\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n setReadySnapshot,\n} from \"../state\";\nimport { createStoredDocument } from \"../storedDocument\";\nimport { logRevalidationScheduled } from \"../sync/remoteRevalidationTelemetry\";\nimport { deferStartupProbeToPendingConnect } from \"../sync/startupProbeDeferral\";\nimport {\n allowDocumentStoreRemoteSync,\n captureDocumentStoreSyncGeneration,\n invalidateDocumentStoreRemoteSync,\n isDocumentStoreSyncGenerationCurrent,\n markDocumentStoreRemoteSyncPending,\n} from \"../sync/syncGeneration\";\nimport { writeInitialDocumentContent } from \"./initialContent\";\nimport {\n installPersistedAttachments,\n type LoadedDocumentStoreState,\n} from \"./initializationAttachments\";\nimport {\n type RestoredHistoryState,\n restoredRemoteTailCoverage,\n restorePersistedDocumentContent,\n} from \"./initializationHistory\";\nimport {\n healLocalAttachmentDetachState,\n recoverDroppedAttachmentSlots,\n} from \"./initializationRecovery\";\nimport { relinkRecordPatch } from \"./relinkRecordPatch\";\n\nasync function createInitialDocumentRecord(\n state: DocumentStoreState,\n nextDoc: DocumentState,\n): ReturnType<typeof saveDocumentRecord> {\n initializeStoredDocumentKind(\n nextDoc,\n state.initialDocumentKind,\n state.runtime.infra.documentProjectors,\n );\n if (state.initialText.length > 0) {\n nextDoc.getText(\"text\").update(state.initialText);\n }\n const wroteInitialContent = writeInitialDocumentContent(state, nextDoc);\n const initialDocumentState = readStoredDocumentState(\n nextDoc,\n state.runtime.infra.documentProjectors,\n );\n const hasInitialContent =\n wroteInitialContent ||\n state.initialText.length > 0 ||\n state.initialDocumentKind !== DEFAULT_DOCUMENT_KIND;\n const initialUpdate = hasInitialContent\n ? createPendingUpdateFields(exportAllUpdates(nextDoc))\n : null;\n // A deferred birth still commits its checkpoint, but leaves the marker at the\n // empty version with nothing queued: the promised attach exports every op\n // since that marker, so one update carries the birth and the attachment.\n const birthDurability = !initialUpdate\n ? {}\n : state.deferInitialUpdate\n ? { pendingBaseVersionOverride: emptyVersionVector() }\n : { pendingUpdate: initialUpdate };\n\n const created: DocumentRecord = {\n id: state.localId,\n containerId: state.runtime.state.containerId ?? null,\n documentId: state.initialDocumentId,\n documentKind: initialDocumentState.documentKind,\n text: initialDocumentState.text,\n title: initialDocumentState.title,\n snapshotEndVersion: encodeVersionVector(nextDoc),\n accessEpoch: DEFAULT_DOCUMENT_ACCESS_EPOCH,\n accessStateHash: null,\n effectiveAccessLevel: \"admin\",\n lastCommitLsn: null,\n contentKeyBundle: null,\n documentKekTargets: null,\n documentManifestBundle: null,\n };\n // The create-only persistence primitive commits the canonical row and birth\n // checkpoint together. A concurrent initializer either wins both or adopts\n // both, so it cannot replace another pane's history or keying state.\n const persisted = await saveDocumentRecord(\n state,\n nextDoc,\n {\n ...created,\n snapshotEndVersion: encodeVersionVector(nextDoc),\n },\n {\n historyCheckpoint: {\n coveredTailIds: [],\n endVersionVector: encodeVersionVector(nextDoc),\n pruneCoveredLocalState: false,\n snapshot: bytesToBase64(exportFullHistorySnapshot(nextDoc)),\n },\n ...birthDurability,\n },\n );\n return persisted;\n}\n\nfunction installPersistedDocumentRecord(\n state: DocumentStoreState,\n record: NonNullable<DocumentStoreState[\"record\"]>,\n): void {\n state.record = record;\n state.pullContinuation = record.pullContinuation ?? null;\n}\n\ninterface RestoredInitialDocumentState {\n activePersistedState: LoadedDocumentStoreState;\n activeRecord: NonNullable<DocumentStoreState[\"record\"]>;\n doc: DocumentState;\n history: RestoredHistoryState | null;\n}\n\nasync function restoreLoadedInitialDocument(input: {\n initializeGeneration: number;\n nextDoc: DocumentState;\n persistedState: LoadedDocumentStoreState;\n state: DocumentStoreState;\n}): Promise<RestoredInitialDocumentState | null> {\n const { initializeGeneration, persistedState, state } = input;\n const record = persistedState.document;\n if (!record) return null;\n const history = await restorePersistedDocumentContent(\n input.nextDoc,\n persistedState.historyRestoreState,\n );\n if (state.localWriteGeneration !== initializeGeneration) return null;\n installPersistedDocumentRecord(state, record);\n return {\n activePersistedState: persistedState,\n activeRecord: record,\n doc: input.nextDoc,\n history,\n };\n}\n\nasync function restoreOrCreateInitialDocument(input: {\n initializeGeneration: number;\n nextDoc: DocumentState;\n persistedState: LoadedDocumentStoreState;\n state: DocumentStoreState;\n}): Promise<RestoredInitialDocumentState | null> {\n const { initializeGeneration, persistedState, state } = input;\n if (persistedState.document) {\n return restoreLoadedInitialDocument(input);\n }\n const created = await createInitialDocumentRecord(state, input.nextDoc);\n if (!created || state.localWriteGeneration !== initializeGeneration) {\n return null;\n }\n const activePersistedState = await loadPersistedDocumentStoreState({\n execSql: state.runtime.infra.execSql,\n localId: state.localId,\n persistence: state.persistence,\n });\n if (state.localWriteGeneration !== initializeGeneration) {\n return null;\n }\n if (!activePersistedState.document) {\n throw new Error(\"Document creation completed without a durable record\");\n }\n const replacementDoc = await createStoredDocument(state);\n return restoreLoadedInitialDocument({\n initializeGeneration,\n nextDoc: replacementDoc,\n persistedState: activePersistedState,\n state,\n });\n}\n\nfunction restorePendingBaseVersion(input: {\n activeRecord: NonNullable<DocumentStoreState[\"record\"]>;\n doc: DocumentState;\n history: RestoredHistoryState | null;\n state: DocumentStoreState;\n}): void {\n const { activeRecord, doc, history, state } = input;\n const markerBase =\n activeRecord.pendingBaseVersion ??\n (activeRecord.snapshotEndVersion.length > 0\n ? activeRecord.snapshotEndVersion\n : null);\n if (markerBase === null) {\n advancePendingBaseVersion(state, doc);\n return;\n }\n\n const remoteCoverage = restoredRemoteTailCoverage(history);\n state.pendingBaseVersion =\n remoteCoverage.length > 0\n ? mergeVersionVectors([markerBase, ...remoteCoverage])\n : markerBase;\n}\n\nasync function initializeDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n) {\n if (state.runtime.infra.dbStatus !== \"ready\") {\n return;\n }\n\n // A store reset while this fire-and-forget initialization is loading (a\n // runtime swap, or a local-edits discard that re-seeds the persisted rows)\n // must win: assigning the state loaded BEFORE the reset would bring the\n // replaced record and doc back to life. Every reset bumps the local write\n // generation, so a stale capture here aborts before each assignment batch.\n const initializeGeneration = state.localWriteGeneration;\n\n const nextDoc = await createStoredDocument(state);\n const persistedState = await loadPersistedDocumentStoreState({\n execSql: state.runtime.infra.execSql,\n localId: state.localId,\n persistence: state.persistence,\n });\n if (state.localWriteGeneration !== initializeGeneration) {\n return;\n }\n // A paused organization's cleanup removed it; creating it again would\n // download the organization's content while the pause lasts. A later open\n // retries, so it loads once the organization resumes.\n if (\n !persistedState.document &&\n (await new OrganizationSyncPauseRepository(\n state.runtime.infra.execSql,\n ).isPauseRemovedDocument(state.localId))\n ) {\n state.initializePromise = null;\n return;\n }\n const restored = await restoreOrCreateInitialDocument({\n initializeGeneration,\n nextDoc,\n persistedState,\n state,\n });\n if (!restored) {\n if (state.localWriteGeneration === initializeGeneration) {\n state.initializePromise = null;\n }\n return;\n }\n const activePersistedState = restored.activePersistedState;\n installPersistedAttachments(state, activePersistedState);\n\n state.doc = restored.doc;\n // Restore the durable outgoing-delta marker. Re-seeding it to the restored\n // document's version would move it PAST any device-first `deferRemoteSync`\n // op (persisted into the durable history but deliberately left un-enqueued\n // and behind the marker), permanently dropping that op from sync across a\n // restart. When a marker was persisted, restore it so the next edit still\n // re-derives the deferred delta. Only seed for rows that never persisted\n // one, from the RECORD's persisted frontier rather than the restored\n // document: a crash between the tail append and the queue/marker writes can\n // resurrect ops the outgoing queue never durably received, and seeding from\n // the restored document would classify those as covered and orphan them\n // from sync forever.\n restorePendingBaseVersion({\n activeRecord: restored.activeRecord,\n doc: restored.doc,\n history: restored.history,\n state,\n });\n // Heal attachment slots lost to an interrupted attach write before marking\n // ready, so the recovered slots are in the snapshot the editor first renders\n // and are queued for sync. recoverDroppedAttachmentSlots advances the marker\n // again for whatever it re-derives. Both helpers gate every durable write\n // on this generation (validated inside the writes' serialized mutations),\n // so a reset mid-helper cannot repopulate discarded state.\n const writeGeneration = captureDocumentStoreSyncGeneration(\n state,\n restored.doc,\n );\n if (!writeGeneration) {\n return;\n }\n await recoverDroppedAttachmentSlots(state, restored.doc, writeGeneration);\n if (state.localWriteGeneration !== initializeGeneration) {\n return;\n }\n await healLocalAttachmentDetachState(\n state,\n restored.doc,\n activePersistedState,\n writeGeneration,\n );\n if (state.localWriteGeneration !== initializeGeneration) {\n return;\n }\n state.initialized = true;\n state.initializePromise = null;\n setReadySnapshot(state, restored.doc, false);\n\n // Websocket invalidations are intentionally session-local. A process can\n // stop before receiving a peer device's update event, and no event survives\n // the restart to distinguish a clean local snapshot from a stale one. Probe\n // each opened remote document once after loading it; unopened documents stay\n // lazy, while body and attachment state for a restored window converges.\n // A connect attempt in flight arms a later probe on its acknowledgement,\n // which covers this one, so the startup probe waits on that attempt.\n if (\n restored.activeRecord.documentId &&\n state.scheduleStartupRemoteSync &&\n !deferStartupProbeToPendingConnect(state)\n ) {\n allowDocumentStoreRemoteSync(state);\n markDocumentStoreRemoteSyncPending(state, \"independent\");\n logRevalidationScheduled(state.runtime, \"startup\");\n }\n scheduleSync();\n void runDocumentOrphanMaintenance(state);\n}\n\nexport function ensureDocumentStoreInitialized(\n state: DocumentStoreState,\n scheduleSync: () => void,\n) {\n if (\n state.initialized ||\n state.initializePromise ||\n state.runtime.infra.dbStatus !== \"ready\"\n ) {\n return;\n }\n\n const initializePromise = initializeDocumentStore(state, scheduleSync).catch(\n (error: unknown) => {\n state.initializePromise = null;\n // A caller that deferred the birth for its attach may give up once\n // opening fails; never leave its durable birth holding sync. No attach\n // has reached a live doc yet, so lifting the hold ships nothing unsafe.\n state.deferInitialUpdate = false;\n\n if (isDatabaseUnavailableError(error)) {\n return;\n }\n\n throw error;\n },\n );\n state.initializePromise = initializePromise;\n void initializePromise.catch(() => undefined);\n}\n\nexport async function awaitInitializationForSync(state: DocumentStoreState) {\n if (!state.initializePromise) {\n return state.initialized;\n }\n\n try {\n await state.initializePromise;\n return state.initialized;\n } catch (error) {\n if (isDatabaseUnavailableError(error)) {\n return false;\n }\n\n throw error;\n }\n}\n\nexport async function ensureDocumentStoreReady(\n state: DocumentStoreState,\n scheduleSync: () => void,\n): Promise<boolean> {\n ensureDocumentStoreInitialized(state, scheduleSync);\n\n if (state.initialized) {\n return true;\n }\n\n if (!state.initializePromise) {\n return false;\n }\n\n return awaitInitializationForSync(state);\n}\n\nexport async function relinkDocumentStore(\n state: DocumentStoreState,\n input: DocumentStoreRelinkInput,\n scheduleSync: () => void,\n commitSideEffect?: DocumentRelinkCommitSideEffect,\n): Promise<DocumentSummary | null> {\n if (\n input.stillCurrent?.() === false ||\n !(await ensureDocumentStoreReady(state, scheduleSync)) ||\n input.stillCurrent?.() === false ||\n !state.doc\n ) {\n return null;\n }\n const currentDoc = state.doc;\n const generation = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!generation) return null;\n // Read the record and persist on the identity-write chain so an in-flight\n // eager create cannot interleave: a create that captured a null identity\n // before its network round trip would otherwise write the derived documentId\n // over the one this relink assigns.\n const persisted = await chainIdentityWrite(state, async () => {\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) return null;\n const currentDocumentId = state.record?.documentId ?? null;\n const patch = relinkRecordPatch(state.record, input);\n\n // Relink rewrites access/identity metadata, not content. If it lands while\n // the user is mid-edit, re-deriving text/structured fields from the\n // (possibly lagging) doc would republish a stale read over the live\n // optimistic snapshot and drop in-flight keystrokes; preserve the snapshot\n // like the keystroke and sync persists do.\n // A prior chained write may have cleared this store (resurrect-guard\n // refusal): persisting the captured doc against a null record would\n // resurrect the document as a create. The identity check runs inside\n // the chain, after every earlier write settled.\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n return null;\n }\n const result = await persistDocument(\n state,\n currentDoc,\n patch,\n {\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n stillCurrent: input.stillCurrent,\n },\n generation,\n commitSideEffect,\n );\n if (result && currentDocumentId !== input.documentId) {\n state.writerProjection = null;\n invalidateDocumentStoreRemoteSync(state);\n }\n return result;\n });\n // A refused persist means the durable row vanished mid-relink (resurrect\n // guard); there is no summary to report.\n if (!persisted) {\n return null;\n }\n if (persisted.updatedAt === undefined) {\n return null;\n }\n return documentSummaryFromRecord(\n persisted.record,\n persisted.updatedAt,\n state.runtime.infra.documentProjectors,\n );\n}\n"]}
@@ -2,7 +2,7 @@ import { listDocumentLocalIdsPlacedOnlyIn } from "../../../data/persistence/cont
2
2
  import { runSerializedSqlMutation } from "../../../data/sqlite/sqlExec.js";
3
3
  import { registerClientSQLiteCommitGuard } from "../../../data/sqlite/sqliteCommitGuards.js";
4
4
  import { defaultDocumentsPersistence, deletePersistedDocument, } from "../../documents/index.js";
5
- import { recordPauseRemovedDocument } from "../../sync/index.js";
5
+ import { OrganizationSyncPauseRepository } from "../../sync/index.js";
6
6
  import { carriesLocalWrites, listPendingWrites } from "../pendingWrites/index.js";
7
7
  // The deletion cascade binds several values per container across its
8
8
  // statements (its tombstone row alone binds a value per column), so a large
@@ -52,7 +52,7 @@ async function deleteDocumentUnlessEdited(input) {
52
52
  try {
53
53
  const deleted = await deletePersistedDocument({
54
54
  beforeDeleteInTransaction: async (transactionExecSql) => {
55
- await recordPauseRemovedDocument(transactionExecSql, {
55
+ await new OrganizationSyncPauseRepository(transactionExecSql).recordPauseRemovedDocument({
56
56
  localId: input.localId,
57
57
  organizationId: input.organizationId,
58
58
  });
@@ -1 +1 @@
1
- {"version":3,"file":"documentRemoval.js","sourceRoot":"","sources":["documentRemoval.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gCAAgC,EAAE,MAAM,0EAA0E,CAAC;AAC5H,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,+BAA+B,EAAE,MAAM,yCAAyC,CAAC;AAE1F,OAAO,EACL,2BAA2B,EAC3B,uBAAuB,GACxB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,0BAA0B,EAAE,MAAM,YAAY,CAAC;AACxD,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAmBzE,qEAAqE;AACrE,4EAA4E;AAC5E,4EAA4E;AAC5E,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ACtC,MAAM,OAAO,GAAG,MAAM,iBAAiB,CAAC,aAAa,CAAC,CAAC;QACvD,IACE,OAAO,CAAC,IAAI,CACV,CAAC,IAAI,EAAE,EAAE,CACP,kBAAkB,CAAC,IAAI,CAAC;YACxB,CAAC,IAAI,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;gBAC3C,CAAC,IAAI,CAAC,WAAW,KAAK,IAAI,IAAI,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;gBACjE,WAAW,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CACnC,EACD,CAAC;YACD,OAAO,OAAO,CAAC,gBAAgB,CAAC,CAAC;QACnC,CAAC;QACD,IAAI,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,eAAe,CAAC;YAAE,OAAO,OAAO,CAAC,cAAc,CAAC,CAAC;QAEzE,MAAM,mBAAmB,GAAG,MAAM,yBAAyB,CACzD,aAAa,EACb,CAAC,GAAG,YAAY,CAAC,EACjB,KAAK,CAAC,gBAAgB,CACvB,CAAC;QACF,IAAI,mBAAmB,CAAC,MAAM,KAAK,YAAY,CAAC,IAAI,EAAE,CAAC;YACrD,OAAO;gBACL,mBAAmB;gBACnB,eAAe,EAAE,EAAE;gBACnB,MAAM,EAAE,aAAa;aACtB,CAAC;QACJ,CAAC;QACD,MAAM,eAAe,GAAG,MAAM,uBAAuB,CACnD,KAAK,EACL,aAAa,EACb,QAAQ,CACT,CAAC;QACF,OAAO;YACL,mBAAmB;YACnB,eAAe;YACf,MAAM,EACJ,eAAe,CAAC,MAAM,KAAK,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,aAAa;SACzE,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { listDocumentLocalIdsPlacedOnlyIn } from \"../../../data/persistence/container-contents/exclusiveDocumentPlacements\";\nimport { runSerializedSqlMutation } from \"../../../data/sqlite/sqlExec\";\nimport { registerClientSQLiteCommitGuard } from \"../../../data/sqlite/sqliteCommitGuards\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n defaultDocumentsPersistence,\n deletePersistedDocument,\n} from \"../../documents\";\nimport { recordPauseRemovedDocument } from \"../../sync\";\nimport { carriesLocalWrites, listPendingWrites } from \"../pendingWrites\";\nimport type { ContainerContentsWorkflowRuntimeInfra } from \"../runtime\";\n\nexport interface OrganizationContentRemoval {\n /**\n * `removed` when every targeted container and document is gone.\n * `pending-writes` and `queued-edits` refused before deleting anything.\n * `interrupted` stopped part way: the removal stopped being current, or a\n * document was edited while it ran and stayed.\n */\n readonly status:\n | \"removed\"\n | \"pending-writes\"\n | \"queued-edits\"\n | \"interrupted\";\n readonly deletedContainerIds: readonly string[];\n readonly deletedLocalIds: readonly string[];\n}\n\n// The deletion cascade binds several values per container across its\n// statements (its tombstone row alone binds a value per column), so a large\n// organization is removed in batches that stay within SQLite's bind budget.\nconst CONTAINER_REMOVAL_BATCH_SIZE = 50;\n\nconst refused = (\n status: \"pending-writes\" | \"queued-edits\",\n): OrganizationContentRemoval => ({\n deletedContainerIds: [],\n deletedLocalIds: [],\n status,\n});\n\ninterface ContainerRemoval {\n readonly containerId: string;\n readonly reason: \"access_revoked\";\n readonly updatedAt: string;\n}\n\n/** Stops at the first batch that is no longer current. */\nasync function deleteContainersInBatches(\n lockedExecSql: ExecSql,\n containerIds: readonly string[],\n deleteContainers: (\n lockedExecSql: ExecSql,\n removals: readonly ContainerRemoval[],\n ) => Promise<readonly string[]>,\n): Promise<string[]> {\n const removedAt = new Date().toISOString();\n const deleted: string[] = [];\n for (\n let index = 0;\n index < containerIds.length;\n index += CONTAINER_REMOVAL_BATCH_SIZE\n ) {\n const batch = containerIds.slice(\n index,\n index + CONTAINER_REMOVAL_BATCH_SIZE,\n );\n const removed = await deleteContainers(\n lockedExecSql,\n batch.map((containerId) => ({\n containerId,\n reason: \"access_revoked\",\n updatedAt: removedAt,\n })),\n );\n deleted.push(...removed);\n if (removed.length !== batch.length) break;\n }\n return deleted;\n}\n\nclass DocumentRemovalNotCurrent extends Error {}\n\n/**\n * Deletes one document unless the removal stopped being current or a store\n * queued a write for it. The check runs as a commit guard, in the same\n * synchronous slice as the COMMIT, so an edit queued while the rows were being\n * deleted rolls the deletion back. When the COMMIT-time check passes, the\n * document's store is retired in that same slice, so an open editor turns\n * read-only before the deletion commits and no later edit can be accepted and\n * lost; a COMMIT that then fails restores it.\n */\nasync function deleteDocumentUnlessEdited(input: {\n readonly documentProjectors: ContainerContentsWorkflowRuntimeInfra[\"documentProjectors\"];\n readonly execSql: ExecSql;\n readonly hasQueuedWrites: (localId: string) => boolean;\n readonly localId: string;\n readonly organizationId: string;\n readonly restoreDocument: (localId: string) => void;\n readonly retireDocument: (localId: string) => void;\n readonly stillCurrent: () => boolean;\n}): Promise<boolean> {\n const expectedRecord = await defaultDocumentsPersistence.loadDocument(\n input.execSql,\n input.localId,\n );\n if (!expectedRecord) return false;\n // The guard runs once when registered and again right before the COMMIT;\n // only that last run retires the store.\n let guardRuns = 0;\n let retired = false;\n try {\n const deleted = await deletePersistedDocument({\n beforeDeleteInTransaction: async (transactionExecSql) => {\n await recordPauseRemovedDocument(transactionExecSql, {\n localId: input.localId,\n organizationId: input.organizationId,\n });\n registerClientSQLiteCommitGuard(transactionExecSql, () => {\n if (!input.stillCurrent() || input.hasQueuedWrites(input.localId)) {\n throw new DocumentRemovalNotCurrent();\n }\n guardRuns += 1;\n if (guardRuns > 1) {\n retired = true;\n input.retireDocument(input.localId);\n }\n });\n },\n documentProjectors: input.documentProjectors,\n execSql: input.execSql,\n expectedRecord,\n localId: input.localId,\n persistence: defaultDocumentsPersistence,\n });\n if (!deleted && retired) input.restoreDocument(input.localId);\n return deleted;\n } catch (error) {\n if (retired) input.restoreDocument(input.localId);\n if (error instanceof DocumentRemovalNotCurrent) return false;\n throw error;\n }\n}\n\n/**\n * Removes a paused organization's containers and the documents placed only in\n * them, unless a persisted pending write (a queued update, a deferred tail, an\n * intent, or an attachment upload) touches the organization, those\n * containers, or those documents. The scan and every deletion hold one SQLite\n * mutation lock, so no persisted write can land between them.\n *\n * An open store may also hold edits that have not reached SQLite yet, so\n * the removal refuses while any targeted document has queued writes; they\n * persist as pending writes and upload, and a later pass removes the rest.\n * The containers go first, under `stillCurrent`; documents are deleted only\n * after every container was, each under a commit guard against an edit\n * queued meanwhile or the removal no longer applying. A document edited mid-removal stays as a detached local\n * copy, like any document whose container this device lost. Documents that\n * were already detached are never touched: they may be the only copy of work\n * a recovery still needs.\n */\n/** Deletes documents in order until the removal stops being current. */\nasync function deleteUneditedDocuments(\n input: Parameters<typeof removeOrganizationContentUnlessPending>[0],\n lockedExecSql: ExecSql,\n localIds: readonly string[],\n): Promise<string[]> {\n const deletedLocalIds: string[] = [];\n for (const localId of localIds) {\n if (!input.stillCurrent()) break;\n if (\n await deleteDocumentUnlessEdited({\n documentProjectors: input.documentProjectors,\n execSql: lockedExecSql,\n hasQueuedWrites: input.hasQueuedWrites,\n localId,\n organizationId: input.organizationId,\n restoreDocument: input.restoreDocument,\n retireDocument: input.retireDocument,\n stillCurrent: input.stillCurrent,\n })\n ) {\n deletedLocalIds.push(localId);\n }\n }\n return deletedLocalIds;\n}\n\nexport async function removeOrganizationContentUnlessPending(input: {\n readonly containerIds: readonly string[];\n readonly deleteContainers: (\n lockedExecSql: ExecSql,\n removals: readonly ContainerRemoval[],\n ) => Promise<readonly string[]>;\n readonly documentProjectors: ContainerContentsWorkflowRuntimeInfra[\"documentProjectors\"];\n readonly execSql: ExecSql;\n /** Whether an open store holds writes for the document not yet in SQLite. */\n readonly hasQueuedWrites: (localId: string) => boolean;\n readonly organizationId: string;\n /** Undoes retireDocument when the deletion did not commit. */\n readonly restoreDocument: (localId: string) => void;\n /** Retires a deleted document's store; see deleteDocumentUnlessEdited. */\n readonly retireDocument: (localId: string) => void;\n /** Whether the removal still applies, e.g. the session did not switch in. */\n readonly stillCurrent: () => boolean;\n}): Promise<OrganizationContentRemoval> {\n return runSerializedSqlMutation(input.execSql, async (lockedExecSql) => {\n const containerIds = new Set(input.containerIds);\n const localIds = await listDocumentLocalIdsPlacedOnlyIn(\n lockedExecSql,\n input.containerIds,\n );\n if (containerIds.size === 0 && localIds.length === 0) {\n return {\n deletedContainerIds: [],\n deletedLocalIds: [],\n status: \"removed\",\n };\n }\n const documentIds = new Set(localIds);\n const pending = await listPendingWrites(lockedExecSql);\n if (\n pending.some(\n (item) =>\n carriesLocalWrites(item) &&\n (item.organizationId === input.organizationId ||\n (item.containerId !== null && containerIds.has(item.containerId)) ||\n documentIds.has(item.localId)),\n )\n ) {\n return refused(\"pending-writes\");\n }\n if (localIds.some(input.hasQueuedWrites)) return refused(\"queued-edits\");\n\n const deletedContainerIds = await deleteContainersInBatches(\n lockedExecSql,\n [...containerIds],\n input.deleteContainers,\n );\n if (deletedContainerIds.length !== containerIds.size) {\n return {\n deletedContainerIds,\n deletedLocalIds: [],\n status: \"interrupted\",\n };\n }\n const deletedLocalIds = await deleteUneditedDocuments(\n input,\n lockedExecSql,\n localIds,\n );\n return {\n deletedContainerIds,\n deletedLocalIds,\n status:\n deletedLocalIds.length === localIds.length ? \"removed\" : \"interrupted\",\n };\n });\n}\n"]}
1
+ {"version":3,"file":"documentRemoval.js","sourceRoot":"","sources":["documentRemoval.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gCAAgC,EAAE,MAAM,0EAA0E,CAAC;AAC5H,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,+BAA+B,EAAE,MAAM,yCAAyC,CAAC;AAE1F,OAAO,EACL,2BAA2B,EAC3B,uBAAuB,GACxB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,+BAA+B,EAAE,MAAM,YAAY,CAAC;AAC7D,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAmBzE,qEAAqE;AACrE,4EAA4E;AAC5E,4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AG,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAC;QACtC,MAAM,OAAO,GAAG,MAAM,iBAAiB,CAAC,aAAa,CAAC,CAAC;QACvD,IACE,OAAO,CAAC,IAAI,CACV,CAAC,IAAI,EAAE,EAAE,CACP,kBAAkB,CAAC,IAAI,CAAC;YACxB,CAAC,IAAI,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;gBAC3C,CAAC,IAAI,CAAC,WAAW,KAAK,IAAI,IAAI,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;gBACjE,WAAW,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CACnC,EACD,CAAC;YACD,OAAO,OAAO,CAAC,gBAAgB,CAAC,CAAC;QACnC,CAAC;QACD,IAAI,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,eAAe,CAAC;YAAE,OAAO,OAAO,CAAC,cAAc,CAAC,CAAC;QAEzE,MAAM,mBAAmB,GAAG,MAAM,yBAAyB,CACzD,aAAa,EACb,CAAC,GAAG,YAAY,CAAC,EACjB,KAAK,CAAC,gBAAgB,CACvB,CAAC;QACF,IAAI,mBAAmB,CAAC,MAAM,KAAK,YAAY,CAAC,IAAI,EAAE,CAAC;YACrD,OAAO;gBACL,mBAAmB;gBACnB,eAAe,EAAE,EAAE;gBACnB,MAAM,EAAE,aAAa;aACtB,CAAC;QACJ,CAAC;QACD,MAAM,eAAe,GAAG,MAAM,uBAAuB,CACnD,KAAK,EACL,aAAa,EACb,QAAQ,CACT,CAAC;QACF,OAAO;YACL,mBAAmB;YACnB,eAAe;YACf,MAAM,EACJ,eAAe,CAAC,MAAM,KAAK,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,aAAa;SACzE,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { listDocumentLocalIdsPlacedOnlyIn } from \"../../../data/persistence/container-contents/exclusiveDocumentPlacements\";\nimport { runSerializedSqlMutation } from \"../../../data/sqlite/sqlExec\";\nimport { registerClientSQLiteCommitGuard } from \"../../../data/sqlite/sqliteCommitGuards\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n defaultDocumentsPersistence,\n deletePersistedDocument,\n} from \"../../documents\";\nimport { OrganizationSyncPauseRepository } from \"../../sync\";\nimport { carriesLocalWrites, listPendingWrites } from \"../pendingWrites\";\nimport type { ContainerContentsWorkflowRuntimeInfra } from \"../runtime\";\n\nexport interface OrganizationContentRemoval {\n /**\n * `removed` when every targeted container and document is gone.\n * `pending-writes` and `queued-edits` refused before deleting anything.\n * `interrupted` stopped part way: the removal stopped being current, or a\n * document was edited while it ran and stayed.\n */\n readonly status:\n | \"removed\"\n | \"pending-writes\"\n | \"queued-edits\"\n | \"interrupted\";\n readonly deletedContainerIds: readonly string[];\n readonly deletedLocalIds: readonly string[];\n}\n\n// The deletion cascade binds several values per container across its\n// statements (its tombstone row alone binds a value per column), so a large\n// organization is removed in batches that stay within SQLite's bind budget.\nconst CONTAINER_REMOVAL_BATCH_SIZE = 50;\n\nconst refused = (\n status: \"pending-writes\" | \"queued-edits\",\n): OrganizationContentRemoval => ({\n deletedContainerIds: [],\n deletedLocalIds: [],\n status,\n});\n\ninterface ContainerRemoval {\n readonly containerId: string;\n readonly reason: \"access_revoked\";\n readonly updatedAt: string;\n}\n\n/** Stops at the first batch that is no longer current. */\nasync function deleteContainersInBatches(\n lockedExecSql: ExecSql,\n containerIds: readonly string[],\n deleteContainers: (\n lockedExecSql: ExecSql,\n removals: readonly ContainerRemoval[],\n ) => Promise<readonly string[]>,\n): Promise<string[]> {\n const removedAt = new Date().toISOString();\n const deleted: string[] = [];\n for (\n let index = 0;\n index < containerIds.length;\n index += CONTAINER_REMOVAL_BATCH_SIZE\n ) {\n const batch = containerIds.slice(\n index,\n index + CONTAINER_REMOVAL_BATCH_SIZE,\n );\n const removed = await deleteContainers(\n lockedExecSql,\n batch.map((containerId) => ({\n containerId,\n reason: \"access_revoked\",\n updatedAt: removedAt,\n })),\n );\n deleted.push(...removed);\n if (removed.length !== batch.length) break;\n }\n return deleted;\n}\n\nclass DocumentRemovalNotCurrent extends Error {}\n\n/**\n * Deletes one document unless the removal stopped being current or a store\n * queued a write for it. The check runs as a commit guard, in the same\n * synchronous slice as the COMMIT, so an edit queued while the rows were being\n * deleted rolls the deletion back. When the COMMIT-time check passes, the\n * document's store is retired in that same slice, so an open editor turns\n * read-only before the deletion commits and no later edit can be accepted and\n * lost; a COMMIT that then fails restores it.\n */\nasync function deleteDocumentUnlessEdited(input: {\n readonly documentProjectors: ContainerContentsWorkflowRuntimeInfra[\"documentProjectors\"];\n readonly execSql: ExecSql;\n readonly hasQueuedWrites: (localId: string) => boolean;\n readonly localId: string;\n readonly organizationId: string;\n readonly restoreDocument: (localId: string) => void;\n readonly retireDocument: (localId: string) => void;\n readonly stillCurrent: () => boolean;\n}): Promise<boolean> {\n const expectedRecord = await defaultDocumentsPersistence.loadDocument(\n input.execSql,\n input.localId,\n );\n if (!expectedRecord) return false;\n // The guard runs once when registered and again right before the COMMIT;\n // only that last run retires the store.\n let guardRuns = 0;\n let retired = false;\n try {\n const deleted = await deletePersistedDocument({\n beforeDeleteInTransaction: async (transactionExecSql) => {\n await new OrganizationSyncPauseRepository(\n transactionExecSql,\n ).recordPauseRemovedDocument({\n localId: input.localId,\n organizationId: input.organizationId,\n });\n registerClientSQLiteCommitGuard(transactionExecSql, () => {\n if (!input.stillCurrent() || input.hasQueuedWrites(input.localId)) {\n throw new DocumentRemovalNotCurrent();\n }\n guardRuns += 1;\n if (guardRuns > 1) {\n retired = true;\n input.retireDocument(input.localId);\n }\n });\n },\n documentProjectors: input.documentProjectors,\n execSql: input.execSql,\n expectedRecord,\n localId: input.localId,\n persistence: defaultDocumentsPersistence,\n });\n if (!deleted && retired) input.restoreDocument(input.localId);\n return deleted;\n } catch (error) {\n if (retired) input.restoreDocument(input.localId);\n if (error instanceof DocumentRemovalNotCurrent) return false;\n throw error;\n }\n}\n\n/**\n * Removes a paused organization's containers and the documents placed only in\n * them, unless a persisted pending write (a queued update, a deferred tail, an\n * intent, or an attachment upload) touches the organization, those\n * containers, or those documents. The scan and every deletion hold one SQLite\n * mutation lock, so no persisted write can land between them.\n *\n * An open store may also hold edits that have not reached SQLite yet, so\n * the removal refuses while any targeted document has queued writes; they\n * persist as pending writes and upload, and a later pass removes the rest.\n * The containers go first, under `stillCurrent`; documents are deleted only\n * after every container was, each under a commit guard against an edit\n * queued meanwhile or the removal no longer applying. A document edited mid-removal stays as a detached local\n * copy, like any document whose container this device lost. Documents that\n * were already detached are never touched: they may be the only copy of work\n * a recovery still needs.\n */\n/** Deletes documents in order until the removal stops being current. */\nasync function deleteUneditedDocuments(\n input: Parameters<typeof removeOrganizationContentUnlessPending>[0],\n lockedExecSql: ExecSql,\n localIds: readonly string[],\n): Promise<string[]> {\n const deletedLocalIds: string[] = [];\n for (const localId of localIds) {\n if (!input.stillCurrent()) break;\n if (\n await deleteDocumentUnlessEdited({\n documentProjectors: input.documentProjectors,\n execSql: lockedExecSql,\n hasQueuedWrites: input.hasQueuedWrites,\n localId,\n organizationId: input.organizationId,\n restoreDocument: input.restoreDocument,\n retireDocument: input.retireDocument,\n stillCurrent: input.stillCurrent,\n })\n ) {\n deletedLocalIds.push(localId);\n }\n }\n return deletedLocalIds;\n}\n\nexport async function removeOrganizationContentUnlessPending(input: {\n readonly containerIds: readonly string[];\n readonly deleteContainers: (\n lockedExecSql: ExecSql,\n removals: readonly ContainerRemoval[],\n ) => Promise<readonly string[]>;\n readonly documentProjectors: ContainerContentsWorkflowRuntimeInfra[\"documentProjectors\"];\n readonly execSql: ExecSql;\n /** Whether an open store holds writes for the document not yet in SQLite. */\n readonly hasQueuedWrites: (localId: string) => boolean;\n readonly organizationId: string;\n /** Undoes retireDocument when the deletion did not commit. */\n readonly restoreDocument: (localId: string) => void;\n /** Retires a deleted document's store; see deleteDocumentUnlessEdited. */\n readonly retireDocument: (localId: string) => void;\n /** Whether the removal still applies, e.g. the session did not switch in. */\n readonly stillCurrent: () => boolean;\n}): Promise<OrganizationContentRemoval> {\n return runSerializedSqlMutation(input.execSql, async (lockedExecSql) => {\n const containerIds = new Set(input.containerIds);\n const localIds = await listDocumentLocalIdsPlacedOnlyIn(\n lockedExecSql,\n input.containerIds,\n );\n if (containerIds.size === 0 && localIds.length === 0) {\n return {\n deletedContainerIds: [],\n deletedLocalIds: [],\n status: \"removed\",\n };\n }\n const documentIds = new Set(localIds);\n const pending = await listPendingWrites(lockedExecSql);\n if (\n pending.some(\n (item) =>\n carriesLocalWrites(item) &&\n (item.organizationId === input.organizationId ||\n (item.containerId !== null && containerIds.has(item.containerId)) ||\n documentIds.has(item.localId)),\n )\n ) {\n return refused(\"pending-writes\");\n }\n if (localIds.some(input.hasQueuedWrites)) return refused(\"queued-edits\");\n\n const deletedContainerIds = await deleteContainersInBatches(\n lockedExecSql,\n [...containerIds],\n input.deleteContainers,\n );\n if (deletedContainerIds.length !== containerIds.size) {\n return {\n deletedContainerIds,\n deletedLocalIds: [],\n status: \"interrupted\",\n };\n }\n const deletedLocalIds = await deleteUneditedDocuments(\n input,\n lockedExecSql,\n localIds,\n );\n return {\n deletedContainerIds,\n deletedLocalIds,\n status:\n deletedLocalIds.length === localIds.length ? \"removed\" : \"interrupted\",\n };\n });\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  export { createDomainScope, type DomainScope, } from "../../data/shared/domainScope.js";
2
2
  export { getRuntimePeerSeed } from "../../data/sync/crdtPeerSeed.js";
3
- export { getOrCreateOrganizationSyncPauses, isPauseRemovedDocument, isRetainedWhileSyncPaused, type OrganizationSyncPauseChange, type OrganizationSyncPauseSubject, type OrganizationSyncPauses, recordPauseRemovedDocument, } from "../../data/sync/organizationSyncPauses.js";
3
+ export { getOrCreateOrganizationSyncPauses, isRetainedWhileSyncPaused, type OrganizationSyncPauseChange, OrganizationSyncPauseRepository, type OrganizationSyncPauseSubject, type OrganizationSyncPauses, } from "../../data/sync/organizationSyncPauses.js";
4
4
  export { markOriginatedDocuments } from "../../data/sync/originatedDocuments.js";
5
5
  export type { DomainSyncCoordinator, DomainSyncSnapshot, SyncIdleOptions, SyncLane, SyncLaneConfig, SyncLaneLastAction, SyncLanePhase, SyncLaneProgress, SyncLaneSnapshot, SyncLaneStatus, UploadSyncLane, UploadSyncLaneOptions, } from "../../data/sync/syncCoordinator.js";
6
6
  export { beginDomainSyncUploadLane, getDomainSyncCoordinatorSnapshot, getOrCreateDomainSyncCoordinator, hasDomainSyncCoordinatorPendingWork, requestAllDomainSyncLanes, subscribeToDomainSyncCoordinator, waitForDomainSyncCoordinatorToSettle, } from "../../data/sync/syncCoordinator.js";
@@ -1,6 +1,6 @@
1
1
  export { createDomainScope, } from "../../data/shared/domainScope.js";
2
2
  export { getRuntimePeerSeed } from "../../data/sync/crdtPeerSeed.js";
3
- export { getOrCreateOrganizationSyncPauses, isPauseRemovedDocument, isRetainedWhileSyncPaused, recordPauseRemovedDocument, } from "../../data/sync/organizationSyncPauses.js";
3
+ export { getOrCreateOrganizationSyncPauses, isRetainedWhileSyncPaused, OrganizationSyncPauseRepository, } from "../../data/sync/organizationSyncPauses.js";
4
4
  export { markOriginatedDocuments } from "../../data/sync/originatedDocuments.js";
5
5
  export { beginDomainSyncUploadLane, getDomainSyncCoordinatorSnapshot, getOrCreateDomainSyncCoordinator, hasDomainSyncCoordinatorPendingWork, requestAllDomainSyncLanes, subscribeToDomainSyncCoordinator, waitForDomainSyncCoordinatorToSettle, } from "../../data/sync/syncCoordinator.js";
6
6
  export { clearRemoteSyncState, } from "./remoteReset.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,GAElB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EACL,iCAAiC,EACjC,sBAAsB,EACtB,yBAAyB,EAIzB,0BAA0B,GAC3B,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,uBAAuB,EAAE,MAAM,qCAAqC,CAAC;AAe9E,OAAO,EACL,yBAAyB,EACzB,gCAAgC,EAChC,gCAAgC,EAChC,mCAAmC,EACnC,yBAAyB,EACzB,gCAAgC,EAChC,oCAAoC,GACrC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAEL,oBAAoB,GAGrB,MAAM,eAAe,CAAC","sourcesContent":["export {\n createDomainScope,\n type DomainScope,\n} from \"../../data/shared/domainScope\";\nexport { getRuntimePeerSeed } from \"../../data/sync/crdtPeerSeed\";\nexport {\n getOrCreateOrganizationSyncPauses,\n isPauseRemovedDocument,\n isRetainedWhileSyncPaused,\n type OrganizationSyncPauseChange,\n type OrganizationSyncPauseSubject,\n type OrganizationSyncPauses,\n recordPauseRemovedDocument,\n} from \"../../data/sync/organizationSyncPauses\";\nexport { markOriginatedDocuments } from \"../../data/sync/originatedDocuments\";\nexport type {\n DomainSyncCoordinator,\n DomainSyncSnapshot,\n SyncIdleOptions,\n SyncLane,\n SyncLaneConfig,\n SyncLaneLastAction,\n SyncLanePhase,\n SyncLaneProgress,\n SyncLaneSnapshot,\n SyncLaneStatus,\n UploadSyncLane,\n UploadSyncLaneOptions,\n} from \"../../data/sync/syncCoordinator\";\nexport {\n beginDomainSyncUploadLane,\n getDomainSyncCoordinatorSnapshot,\n getOrCreateDomainSyncCoordinator,\n hasDomainSyncCoordinatorPendingWork,\n requestAllDomainSyncLanes,\n subscribeToDomainSyncCoordinator,\n waitForDomainSyncCoordinatorToSettle,\n} from \"../../data/sync/syncCoordinator\";\nexport {\n type ClearRemoteSyncStateResult,\n clearRemoteSyncState,\n type RemoteResetInput,\n type RemoteResetReplacement,\n} from \"./remoteReset\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,GAElB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EACL,iCAAiC,EACjC,yBAAyB,EAEzB,+BAA+B,GAGhC,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,uBAAuB,EAAE,MAAM,qCAAqC,CAAC;AAe9E,OAAO,EACL,yBAAyB,EACzB,gCAAgC,EAChC,gCAAgC,EAChC,mCAAmC,EACnC,yBAAyB,EACzB,gCAAgC,EAChC,oCAAoC,GACrC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAEL,oBAAoB,GAGrB,MAAM,eAAe,CAAC","sourcesContent":["export {\n createDomainScope,\n type DomainScope,\n} from \"../../data/shared/domainScope\";\nexport { getRuntimePeerSeed } from \"../../data/sync/crdtPeerSeed\";\nexport {\n getOrCreateOrganizationSyncPauses,\n isRetainedWhileSyncPaused,\n type OrganizationSyncPauseChange,\n OrganizationSyncPauseRepository,\n type OrganizationSyncPauseSubject,\n type OrganizationSyncPauses,\n} from \"../../data/sync/organizationSyncPauses\";\nexport { markOriginatedDocuments } from \"../../data/sync/originatedDocuments\";\nexport type {\n DomainSyncCoordinator,\n DomainSyncSnapshot,\n SyncIdleOptions,\n SyncLane,\n SyncLaneConfig,\n SyncLaneLastAction,\n SyncLanePhase,\n SyncLaneProgress,\n SyncLaneSnapshot,\n SyncLaneStatus,\n UploadSyncLane,\n UploadSyncLaneOptions,\n} from \"../../data/sync/syncCoordinator\";\nexport {\n beginDomainSyncUploadLane,\n getDomainSyncCoordinatorSnapshot,\n getOrCreateDomainSyncCoordinator,\n hasDomainSyncCoordinatorPendingWork,\n requestAllDomainSyncLanes,\n subscribeToDomainSyncCoordinator,\n waitForDomainSyncCoordinatorToSettle,\n} from \"../../data/sync/syncCoordinator\";\nexport {\n type ClearRemoteSyncStateResult,\n clearRemoteSyncState,\n type RemoteResetInput,\n type RemoteResetReplacement,\n} from \"./remoteReset\";\n"]}