@vite-hub/workspace 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +62 -19
  2. package/dist/{abort-BCwpdrN0.js → abort-CQGxJBqa.js} +1 -2
  3. package/dist/{asset-registry-DfBV5kmw.js → asset-registry-0CdRAjIV.js} +2 -3
  4. package/dist/blob-database/postgres.d.ts +423 -0
  5. package/dist/blob-database/postgres.js +1 -0
  6. package/dist/blob-database-sources-CQPAyCz3.js +8 -0
  7. package/dist/blob-database.d.ts +29 -449
  8. package/dist/blob-database.js +636 -210
  9. package/dist/checkout.d.ts +1 -2
  10. package/dist/checkout.js +3 -4
  11. package/dist/cloudflare.d.ts +1 -5
  12. package/dist/cloudflare.js +1 -2
  13. package/dist/{config-B-863EgC.js → config-CsgNNVAI.js} +1 -2
  14. package/dist/{config-CDeGd0RB.d.ts → config-DeA287c0.d.ts} +1 -5
  15. package/dist/{config-D1QENneP.js → config-jo5QgE1w.js} +18 -27
  16. package/dist/{discard-CNNtCozM.js → discard-BkoLmmmN.js} +1 -2
  17. package/dist/durability.d.ts +10 -4
  18. package/dist/durability.js +47 -6
  19. package/dist/{error-diagnostics-B5s9kNEA.js → error-diagnostics-B4me-ouV.js} +11 -4
  20. package/dist/{error-diagnostics-CQ4BUqRe.js → error-diagnostics-kKXseq8d.js} +10 -3
  21. package/dist/{path-uxLkzrZm.d.ts → errors-CnFDXxeJ.d.ts} +0 -3
  22. package/dist/{file-CqG9zqiF.js → file-BrNAXQgY.js} +4 -8
  23. package/dist/{target-Dm9dHAVJ.js → file-metadata-Bpsvjw_X.js} +3 -32
  24. package/dist/{files-B6wpAhEx.js → files--z2dLC5z.js} +3 -4
  25. package/dist/files.d.ts +12 -8
  26. package/dist/files.js +7 -6
  27. package/dist/{github-DKAlO0Vh.js → github-k--_LCrX.js} +7 -9
  28. package/dist/{glob-BOqSKzSg.js → glob-BEutagp1.js} +9 -10
  29. package/dist/{glob-Cjxms1t7.js → glob-BreFjNAV.js} +3 -4
  30. package/dist/history-schema-BR4UDPHL.d.ts +434 -0
  31. package/dist/history-schema-postgres-DZepCSBq.js +40 -0
  32. package/dist/{host-Bf1a2uo_.js → host-C8yZizfk.js} +153 -22
  33. package/dist/{hosted-zG7HJaE4.js → hosted-8BTKAtMX.js} +27 -21
  34. package/dist/{hosted-vercel-blob-AbXG8fvR.js → hosted-vercel-blob-B6kygYqn.js} +10 -12
  35. package/dist/hosted-vercel-blob.d.ts +1 -3
  36. package/dist/hosted-vercel-blob.js +1 -2
  37. package/dist/hosted.d.ts +1 -3
  38. package/dist/hosted.js +1 -2
  39. package/dist/index.d.ts +11 -41
  40. package/dist/index.js +34 -116
  41. package/dist/internal/path.d.ts +1 -1
  42. package/dist/internal/path.js +1 -2
  43. package/dist/internal/workspace.d.ts +10 -0
  44. package/dist/internal/workspace.js +85 -0
  45. package/dist/{lifecycle-D8FdpBod.js → lifecycle-IReZfi0b.js} +15 -13
  46. package/dist/lineage.d.ts +1 -3
  47. package/dist/lineage.js +1 -2
  48. package/dist/loader.d.ts +1 -7
  49. package/dist/loader.js +4 -6
  50. package/dist/{mcp-resources-DntxtmDU.js → mcp-resources-DeJnbOaw.js} +4 -5
  51. package/dist/{memory-D5jq9HZW.js → memory-BlSRrBH1.js} +19 -13
  52. package/dist/{metadata-target-DDoOQNp1.js → metadata-target-CaGLY4ay.js} +214 -77
  53. package/dist/{object-Da1zyPCR.js → object-CAK6UYR5.js} +1 -2
  54. package/dist/{operation-definition-nmRu_O3V.d.ts → operation-definition-CqZkx1Rm.d.ts} +8 -6
  55. package/dist/{operations-DsY2MQnG.js → operations-CtRDU3cA.js} +34 -29
  56. package/dist/{operations-D8uCpzhM.js → operations-DfbqHWAe.js} +7 -8
  57. package/dist/operations.d.ts +2 -6
  58. package/dist/operations.js +2 -2
  59. package/dist/{path--wrT_Azm.js → path-Bb9OIc_F.js} +3 -19
  60. package/dist/{path-zHxQUbqa.d.ts → path-C0uZxDdW.d.ts} +0 -2
  61. package/dist/{path-DrSIenjj.js → path-CuYE8-X6.js} +2 -4
  62. package/dist/{plugins-CsrXCA1Q.d.ts → plugins-CLc32jvL.d.ts} +1 -3
  63. package/dist/{provider-sm9uzkLg.js → provider-CN14ewvx.js} +30 -22
  64. package/dist/providers/github/store.d.ts +2 -4
  65. package/dist/providers/github/store.js +1 -2
  66. package/dist/{registry-CFl1Htyc.d.ts → registry-B0g19sdy.d.ts} +5 -8
  67. package/dist/{registry-DmVfUe4K.js → registry-BbUg9vJB.js} +10 -6
  68. package/dist/registry-s2Ob9PeX.d.ts +9 -0
  69. package/dist/{request-scope-Dw5n8bMC.js → request-scope-CXCI_wCb.js} +4 -4
  70. package/dist/{results-DgkZUmTL.js → results-z-HpV9EP.js} +1 -2
  71. package/dist/{rolldown-runtime-rQ84J-ij.js → rolldown-runtime-DnNXxpGL.js} +2 -3
  72. package/dist/rule-keys-BLEbi1h5.js +18 -0
  73. package/dist/rules-BPDXypZV.js +267 -0
  74. package/dist/runtime/assets.d.ts +2 -3
  75. package/dist/runtime/assets.js +5 -6
  76. package/dist/runtime/empty-assets-registry.d.ts +1 -3
  77. package/dist/runtime/empty-assets-registry.js +1 -2
  78. package/dist/runtime/empty-registry.d.ts +2 -4
  79. package/dist/runtime/empty-registry.js +1 -2
  80. package/dist/runtime/registry.d.ts +2 -2
  81. package/dist/runtime/registry.js +2 -3
  82. package/dist/runtime/request.d.ts +1 -3
  83. package/dist/runtime/request.js +2 -3
  84. package/dist/runtime/state.d.ts +5 -4
  85. package/dist/runtime/state.js +18 -7
  86. package/dist/runtime/workspace.d.ts +1 -1
  87. package/dist/runtime/workspace.js +1 -2
  88. package/dist/runtime.d.ts +9 -24
  89. package/dist/runtime.js +29 -25
  90. package/dist/{search-C_RfoM2j.js → search-C_nVorq7.js} +3 -4
  91. package/dist/{server-Cd4-iCh5.js → server-aa1a4rkV.js} +8 -10
  92. package/dist/server.d.ts +3 -4
  93. package/dist/server.js +1 -2
  94. package/dist/{shared-ovXVSV3-.js → shared-C20Wh1mp.js} +23 -19
  95. package/dist/source-metadata.d.ts +2 -6
  96. package/dist/source-metadata.js +4 -5
  97. package/dist/state-BdDfBtOR.d.ts +17 -0
  98. package/dist/{store-NZoRto-Y.js → store-cx3OqNTi.js} +42 -44
  99. package/dist/{sync-CrT8zjwc.js → sync-BBfR4g5y.js} +6 -7
  100. package/dist/test.d.ts +1 -1
  101. package/dist/test.js +1 -2
  102. package/dist/{types-1Z-tKK3g.d.ts → types-Bel5IDmF.d.ts} +52 -6
  103. package/dist/{use-CjbF8EO9.d.ts → use-CpphIBof.d.ts} +20 -32
  104. package/dist/{use-B0o5HoBl.js → use-D0DyTMxM.js} +19 -21
  105. package/dist/use-tools-CAK10LTc.d.ts +10 -0
  106. package/dist/{state-Cb_hIyAw.js → use-tools-CHduR5k6.js} +8 -24
  107. package/dist/{utils-Dw-WULEZ.js → utils-DXP9xfXo.js} +80 -273
  108. package/dist/vite.d.ts +30 -19
  109. package/dist/vite.js +1481 -1617
  110. package/dist/vitehub-grants-Co713QTg.js +36 -0
  111. package/dist/workspace-BOuxrZrP.d.ts +5 -0
  112. package/dist/{workspace-DvKu5PRa.js → workspace-CLuPkyZR.js} +28 -36
  113. package/package.json +34 -24
  114. package/dist/registry-CwryP59t.d.ts +0 -9
  115. package/dist/state-C-YtsaiJ.d.ts +0 -35
  116. package/dist/workspace-CIXgHeyX.d.ts +0 -7
@@ -1,52 +1,486 @@
1
- import { n as forkMemoryWorkspaceStore, r as vitehubOwnedPrefix, t as createMemoryWorkspaceStore } from "./memory-D5jq9HZW.js";
2
- import { s as workspaceError, t as normalizeSafeWorkspacePath } from "./path-DrSIenjj.js";
3
- import { o as copyJsonFileMetadata, r as workspaceStoreTarget, s as copyJsonWorkspaceMetadata } from "./target-Dm9dHAVJ.js";
4
- import { a as isExcludedWorkspacePath, f as sha256, i as decodeFile, o as isWorkspaceBytes, r as contentToBytes } from "./path--wrT_Azm.js";
5
- import { t as workspaceErrorDiagnostics } from "./error-diagnostics-B5s9kNEA.js";
6
- import { d as normalizeHistoryRef, f as rejectHistoryHead, l as historyConflict, m as validateHistoryMessage, n as createSnapshotFromEntries, r as diffSnapshots, u as normalizeHistoryPath } from "./utils-Dw-WULEZ.js";
7
- import { and, desc, eq, inArray, isNotNull, lt, sql } from "drizzle-orm";
1
+ import { n as forkMemoryWorkspaceStore, r as vitehubOwnedPrefix, t as createMemoryWorkspaceStore } from "./memory-BlSRrBH1.js";
2
+ import { a as workspaceConflict, s as workspaceError, t as normalizeSafeWorkspacePath } from "./path-CuYE8-X6.js";
3
+ import { n as copyJsonWorkspaceMetadata, t as copyJsonFileMetadata } from "./file-metadata-Bpsvjw_X.js";
4
+ import { d as normalizeHistoryPath, f as normalizeHistoryRef, g as validateHistoryMessage, m as rejectHistoryHead, n as createSnapshotFromEntries, p as readHistoryDeleteRef, r as diffSnapshots, u as historyConflict } from "./utils-DXP9xfXo.js";
5
+ import { a as isExcludedWorkspacePath, d as sha256, i as decodeFile, o as isWorkspaceBytes, r as contentToBytes } from "./path-Bb9OIc_F.js";
6
+ import { a as provideWorkspaceStoreTarget } from "./vitehub-grants-Co713QTg.js";
7
+ import { t as blobDatabaseSources } from "./blob-database-sources-CQPAyCz3.js";
8
+ import { t as workspaceErrorDiagnostics } from "./error-diagnostics-B4me-ouV.js";
9
+ import { t as workspaceHistorySchema$1 } from "./history-schema-postgres-DZepCSBq.js";
10
+ import { and, desc, eq, exists, getColumns, gte, inArray, is, isNotNull, isNull, lt, ne, notExists, sql } from "drizzle-orm";
11
+ import { PgAsyncDatabase } from "drizzle-orm/pg-core/async/db";
8
12
  import { ViteHubError } from "@vite-hub/runtime";
9
- import { index, integer, primaryKey, sqliteTable, text } from "drizzle-orm/sqlite-core";
13
+ import { alias } from "drizzle-orm/pg-core";
14
+ import { index as index$1, integer as integer$1, primaryKey as primaryKey$1, sqliteTable, text as text$1 } from "drizzle-orm/sqlite-core";
15
+ // src/storage/history-index-postgres.ts
16
+ const { workspaceHistoryWorkspaces: workspaces$2, workspaceHistoryRefs: refs$2, workspaceHistoryRevisions: revisions$2, workspaceHistoryObjects: objects$2, workspaceHistoryMetadata: metadata$2 } = workspaceHistorySchema$1;
17
+ const crossRef = alias(refs$2, "cross_ref");
18
+ const { fileIndex: _fileIndex, ...revisionColumns } = getColumns(revisions$2);
19
+ function active$1(workspace) {
20
+ return sql`exists (select 1 from ${workspaces$2} where ${workspaces$2.workspace} = ${workspace} and not ${workspaces$2.deleted})`;
21
+ }
22
+ const digestOf = sql`left(${objects$2.digest}, 64)`;
23
+ function manifestDigests(where) {
24
+ return sql`(select file.value->>'digest' from ${revisions$2} cross join lateral jsonb_each(${revisions$2.fileIndex}) as file where ${where})`;
25
+ }
26
+ function textValues(values) {
27
+ return sql`(select jsonb_array_elements_text(${JSON.stringify(values)}::text::jsonb))`;
28
+ }
29
+ async function indexFiles(entries) {
30
+ return Object.fromEntries(await Promise.all(Object.entries(entries).map(async ([path, file]) => {
31
+ const canonical = JSON.stringify(file, (_key, value) => value && typeof value === "object" && !Array.isArray(value) ? Object.fromEntries(Object.keys(value).sort().map((key) => [key, Reflect.get(value, key)])) : value);
32
+ return [JSON.stringify(path), {
33
+ digest: file.digest,
34
+ size: file.size,
35
+ fingerprint: await sha256(canonical)
36
+ }];
37
+ })));
38
+ }
39
+ async function lock(tx, workspace) {
40
+ const [row] = await tx.select({ deleted: workspaces$2.deleted }).from(workspaces$2).where(eq(workspaces$2.workspace, workspace)).for("update");
41
+ return row !== void 0 && !row.deleted;
42
+ }
43
+ async function activeKeys(db, workspace, digests) {
44
+ if (!digests.length) return [];
45
+ return (await db.select({ key: objects$2.digest }).from(objects$2).where(and(eq(objects$2.workspace, workspace), gte(objects$2.size, 0), sql`${digestOf} in ${textValues(digests)}`))).map((row) => [row.key.slice(0, 64), row.key]);
46
+ }
47
+ /** Each write is one transaction that locks the identity row. */
48
+ function postgresHistoryIndex(db) {
49
+ return {
50
+ async claim(current, legacy) {
51
+ try {
52
+ const rows = await db.select({ workspace: workspaces$2.workspace }).from(workspaces$2).where(inArray(workspaces$2.workspace, legacy === void 0 ? [current] : [current, legacy]));
53
+ if (rows.some((row) => row.workspace === current)) return current;
54
+ if (legacy !== void 0 && rows.some((row) => row.workspace === legacy)) return legacy;
55
+ await db.insert(workspaces$2).values({ workspace: current }).onConflictDoNothing();
56
+ return current;
57
+ } catch (error) {
58
+ if ([error, error instanceof Error ? error.cause : void 0].some((value) => value instanceof Error && "code" in value && value.code === "42P01")) throw workspaceErrorDiagnostics.WORKSPACE_POSTGRES_HISTORY_SCHEMA_MISSING({ cause: error });
59
+ throw error;
60
+ }
61
+ },
62
+ async deleted(workspace) {
63
+ const [row] = await db.select({ deleted: workspaces$2.deleted }).from(workspaces$2).where(eq(workspaces$2.workspace, workspace));
64
+ return row?.deleted;
65
+ },
66
+ async ref(workspace, ref) {
67
+ const [row] = await db.select({
68
+ ref: refs$2.ref,
69
+ head: refs$2.head,
70
+ sequence: refs$2.sequence
71
+ }).from(refs$2).where(and(eq(refs$2.workspace, workspace), eq(refs$2.ref, ref), active$1(workspace)));
72
+ return row;
73
+ },
74
+ async heads(workspace) {
75
+ const heads = await db.select({
76
+ ref: refs$2.ref,
77
+ head: refs$2.head
78
+ }).from(refs$2).where(and(eq(refs$2.workspace, workspace), isNotNull(refs$2.head), active$1(workspace)));
79
+ if (!heads.length) return [];
80
+ const rows = await db.select(revisionColumns).from(revisions$2).where(and(eq(revisions$2.workspace, workspace), eq(revisions$2.committed, true), sql`${revisions$2.id} in ${textValues(heads.map((row) => row.head))}`, active$1(workspace)));
81
+ const byId = new Map(rows.map((row) => [row.id, row]));
82
+ return heads.flatMap(({ ref, head }) => {
83
+ const revision = byId.get(head);
84
+ return revision ? [{
85
+ ref,
86
+ revision
87
+ }] : [];
88
+ });
89
+ },
90
+ async revision(workspace, id) {
91
+ const [row] = await db.select(revisionColumns).from(revisions$2).where(and(eq(revisions$2.workspace, workspace), eq(revisions$2.id, id), eq(revisions$2.committed, true), active$1(workspace)));
92
+ return row;
93
+ },
94
+ async list(workspace, { ref, before, path, limit }) {
95
+ const previousIndex = sql`coalesce((
96
+ select previous.file_index from ${revisions$2} as previous
97
+ where previous.workspace = ${revisions$2.workspace} and previous.id = ${revisions$2.parentId} and previous.committed
98
+ ), '{}'::jsonb)`;
99
+ const encodedPath = JSON.stringify(path);
100
+ const encodedPrefix = JSON.stringify(`${path}/`).slice(0, -1);
101
+ const inPath = (key) => sql`(${key} = ${encodedPath} or starts_with(${key}, ${encodedPrefix}))`;
102
+ const pathFilter = path === void 0 ? void 0 : sql`(
103
+ exists (
104
+ select 1
105
+ from jsonb_each(${revisions$2.fileIndex}) as current_file
106
+ left join jsonb_each(${previousIndex}) as previous_file on previous_file.key = current_file.key
107
+ where ${inPath(sql`current_file.key`)}
108
+ and current_file.value is distinct from previous_file.value
109
+ )
110
+ or exists (
111
+ select 1
112
+ from jsonb_each(${previousIndex}) as previous_file
113
+ where ${inPath(sql`previous_file.key`)} and not (${revisions$2.fileIndex} ? previous_file.key)
114
+ )
115
+ )`;
116
+ return await db.select(revisionColumns).from(revisions$2).where(and(eq(revisions$2.workspace, workspace), eq(revisions$2.ref, ref), eq(revisions$2.committed, true), before === void 0 ? void 0 : lt(revisions$2.sequence, before), pathFilter, active$1(workspace))).orderBy(desc(revisions$2.sequence)).limit(limit);
117
+ },
118
+ async usage(workspace) {
119
+ const [result] = await db.execute(sql`
120
+ select coalesce(sum(used.size), 0) as bytes, count(*) as objects from (
121
+ select distinct file.value->>'digest' as digest, (file.value->>'size')::bigint as size
122
+ from ${revisions$2} cross join lateral jsonb_each(${revisions$2.fileIndex}) as file
123
+ where ${revisions$2.workspace} = ${workspace} and ${revisions$2.committed} and ${active$1(workspace)}
124
+ ) as used
125
+ `, "objects");
126
+ return {
127
+ bytes: Number(result?.bytes ?? 0),
128
+ objects: Number(result?.objects ?? 0)
129
+ };
130
+ },
131
+ async objectKey(workspace, digest) {
132
+ const [object] = await db.select({ key: objects$2.digest }).from(objects$2).where(and(eq(objects$2.workspace, workspace), gte(objects$2.size, 0), eq(digestOf, digest))).limit(1);
133
+ return object?.key;
134
+ },
135
+ async register(workspace, registry) {
136
+ await db.transaction(async (tx) => {
137
+ if (!await lock(tx, workspace)) return;
138
+ const registered = new Set((await activeKeys(tx, workspace, registry.map((object) => object.digest))).map(([digest]) => digest));
139
+ const missing = registry.filter((object) => !registered.has(object.digest));
140
+ if (missing.length) await tx.execute(sql`
141
+ insert into ${objects$2} (workspace, digest, size)
142
+ select ${workspace}, key, size from jsonb_to_recordset(${JSON.stringify(missing)}::text::jsonb) as entry(key text, size bigint)
143
+ on conflict do nothing
144
+ `);
145
+ });
146
+ },
147
+ async objectKeys(workspace, digests) {
148
+ return await activeKeys(db, workspace, digests);
149
+ },
150
+ async hasObject(workspace, key) {
151
+ const [row] = await db.select({ key: objects$2.digest }).from(objects$2).where(and(eq(objects$2.workspace, workspace), eq(objects$2.digest, key), gte(objects$2.size, 0))).limit(1);
152
+ return row !== void 0;
153
+ },
154
+ async publish(workspace, { revision, ifHead, ifHeads, keys, complete }) {
155
+ if (!complete) return false;
156
+ const fileIndex = await indexFiles(revision.entries);
157
+ return await db.transaction(async (tx) => {
158
+ if (!await lock(tx, workspace)) return false;
159
+ const uploaded = [...new Set(keys)];
160
+ if (uploaded.length) {
161
+ if ((await tx.select({ key: objects$2.digest }).from(objects$2).where(and(eq(objects$2.workspace, workspace), sql`${objects$2.digest} in ${textValues(uploaded)}`, gte(objects$2.size, 0)))).length !== uploaded.length) return false;
162
+ }
163
+ await tx.insert(refs$2).values({
164
+ workspace,
165
+ ref: revision.ref
166
+ }).onConflictDoNothing();
167
+ await tx.insert(revisions$2).values({
168
+ ...revision,
169
+ fileIndex,
170
+ committed: false
171
+ }).onConflictDoNothing();
172
+ const crossHead = (ref, head) => tx.select({ ref: crossRef.ref }).from(crossRef).where(and(eq(crossRef.workspace, workspace), eq(crossRef.ref, ref), head));
173
+ if (!(await tx.update(refs$2).set({
174
+ head: revision.id,
175
+ sequence: sql`${refs$2.sequence} + 1`
176
+ }).where(and(eq(refs$2.workspace, workspace), eq(refs$2.ref, revision.ref), ifHead === null ? isNull(refs$2.head) : eq(refs$2.head, ifHead), ...ifHeads.map(([ref, head]) => head === null ? notExists(crossHead(ref, isNotNull(crossRef.head))) : exists(crossHead(ref, eq(crossRef.head, head)))))).returning({ head: refs$2.head })).length) return false;
177
+ await tx.update(revisions$2).set({ committed: true }).where(and(eq(revisions$2.workspace, workspace), eq(revisions$2.id, revision.id)));
178
+ return true;
179
+ });
180
+ },
181
+ async deleteRef(workspace, ref, head) {
182
+ return await db.transaction(async (tx) => {
183
+ if (!await lock(tx, workspace)) return false;
184
+ const [current] = await tx.select({ head: refs$2.head }).from(refs$2).where(and(eq(refs$2.workspace, workspace), eq(refs$2.ref, ref)));
185
+ if (!current || current.head !== head) return false;
186
+ await tx.update(objects$2).set({ size: -1 }).where(and(eq(objects$2.workspace, workspace), gte(objects$2.size, 0), sql`${digestOf} in ${manifestDigests(and(eq(revisions$2.workspace, workspace), eq(revisions$2.ref, ref)))}`, sql`${digestOf} not in ${manifestDigests(and(eq(revisions$2.workspace, workspace), ne(revisions$2.ref, ref), eq(revisions$2.committed, true)))}`));
187
+ await tx.delete(revisions$2).where(and(eq(revisions$2.workspace, workspace), eq(revisions$2.ref, ref)));
188
+ await tx.delete(refs$2).where(and(eq(refs$2.workspace, workspace), eq(refs$2.ref, ref)));
189
+ return true;
190
+ });
191
+ },
192
+ async markedObjects(workspace) {
193
+ return (await db.select({ key: objects$2.digest }).from(objects$2).where(and(eq(objects$2.workspace, workspace), lt(objects$2.size, 0)))).map((row) => row.key);
194
+ },
195
+ async dropMarkedObjects(workspace, keys) {
196
+ if (!keys.length) return;
197
+ await db.delete(objects$2).where(and(eq(objects$2.workspace, workspace), sql`${objects$2.digest} in ${textValues(keys)}`, lt(objects$2.size, 0)));
198
+ },
199
+ async tombstone(workspace) {
200
+ await db.transaction(async (tx) => {
201
+ await tx.update(workspaces$2).set({ deleted: true }).where(eq(workspaces$2.workspace, workspace));
202
+ await tx.delete(refs$2).where(eq(refs$2.workspace, workspace));
203
+ });
204
+ },
205
+ async objects(workspace) {
206
+ return (await db.select({ key: objects$2.digest }).from(objects$2).where(eq(objects$2.workspace, workspace))).map((row) => row.key);
207
+ },
208
+ async purge(workspace) {
209
+ await db.transaction(async (tx) => {
210
+ await tx.delete(revisions$2).where(eq(revisions$2.workspace, workspace));
211
+ await tx.delete(objects$2).where(eq(objects$2.workspace, workspace));
212
+ await tx.delete(metadata$2).where(eq(metadata$2.workspace, workspace));
213
+ });
214
+ },
215
+ async getMeta(workspace, key) {
216
+ const [row] = await db.select({ value: metadata$2.value }).from(metadata$2).where(and(eq(metadata$2.workspace, workspace), eq(metadata$2.key, key), active$1(workspace)));
217
+ return row?.value;
218
+ },
219
+ async setMeta(workspace, key, value) {
220
+ await db.transaction(async (tx) => {
221
+ if (!await lock(tx, workspace)) return;
222
+ await tx.insert(metadata$2).values({
223
+ workspace,
224
+ key,
225
+ value: value === null ? sql`'null'::json` : value
226
+ }).onConflictDoUpdate({
227
+ target: [metadata$2.workspace, metadata$2.key],
228
+ set: { value: sql`excluded.value` }
229
+ });
230
+ });
231
+ },
232
+ async deleteMeta(workspace, key) {
233
+ await db.delete(metadata$2).where(and(eq(metadata$2.workspace, workspace), eq(metadata$2.key, key)));
234
+ }
235
+ };
236
+ }
10
237
  /** Include these tables in a Database Definition and apply its migrations. */
11
238
  const workspaceHistorySchema = {
12
239
  workspaceHistoryWorkspaces: sqliteTable("workspace_history_workspaces", {
13
- workspace: text("workspace").primaryKey(),
14
- deleted: integer("deleted", { mode: "boolean" }).notNull().default(false)
240
+ workspace: text$1("workspace").primaryKey(),
241
+ deleted: integer$1("deleted", { mode: "boolean" }).notNull().default(false)
15
242
  }),
16
243
  workspaceHistoryRefs: sqliteTable("workspace_history_refs", {
17
- workspace: text("workspace").notNull(),
18
- ref: text("ref").notNull(),
19
- head: text("head"),
20
- sequence: integer("sequence").notNull().default(0)
21
- }, (table) => [primaryKey({ columns: [table.workspace, table.ref] })]),
244
+ workspace: text$1("workspace").notNull(),
245
+ ref: text$1("ref").notNull(),
246
+ head: text$1("head"),
247
+ sequence: integer$1("sequence").notNull().default(0)
248
+ }, (table) => [primaryKey$1({ columns: [table.workspace, table.ref] })]),
22
249
  workspaceHistoryRevisions: sqliteTable("workspace_history_revisions", {
23
- workspace: text("workspace").notNull(),
24
- id: text("id").notNull(),
25
- ref: text("ref").notNull(),
26
- parentId: text("parent_id"),
27
- sequence: integer("sequence").notNull(),
28
- createdAt: text("created_at").notNull(),
29
- message: text("message"),
30
- metadata: text("metadata", { mode: "json" }).$type(),
31
- files: integer("files").notNull(),
32
- bytes: integer("bytes").notNull(),
33
- entries: text("entries", { mode: "json" }).$type().notNull(),
34
- committed: integer("committed", { mode: "boolean" }).notNull().default(false)
35
- }, (table) => [primaryKey({ columns: [table.workspace, table.id] }), index("workspace_history_timeline").on(table.workspace, table.ref, table.committed, table.sequence)]),
250
+ workspace: text$1("workspace").notNull(),
251
+ id: text$1("id").notNull(),
252
+ ref: text$1("ref").notNull(),
253
+ parentId: text$1("parent_id"),
254
+ sequence: integer$1("sequence").notNull(),
255
+ createdAt: text$1("created_at").notNull(),
256
+ message: text$1("message"),
257
+ metadata: text$1("metadata", { mode: "json" }).$type(),
258
+ files: integer$1("files").notNull(),
259
+ bytes: integer$1("bytes").notNull(),
260
+ entries: text$1("entries", { mode: "json" }).$type().notNull(),
261
+ committed: integer$1("committed", { mode: "boolean" }).notNull().default(false)
262
+ }, (table) => [primaryKey$1({ columns: [table.workspace, table.id] }), index$1("workspace_history_timeline").on(table.workspace, table.ref, table.committed, table.sequence)]),
36
263
  workspaceHistoryObjects: sqliteTable("workspace_history_objects", {
37
- workspace: text("workspace").notNull(),
38
- digest: text("digest").notNull(),
39
- size: integer("size").notNull()
40
- }, (table) => [primaryKey({ columns: [table.workspace, table.digest] })]),
264
+ workspace: text$1("workspace").notNull(),
265
+ digest: text$1("digest").notNull(),
266
+ size: integer$1("size").notNull()
267
+ }, (table) => [primaryKey$1({ columns: [table.workspace, table.digest] })]),
41
268
  workspaceHistoryMetadata: sqliteTable("workspace_history_metadata", {
42
- workspace: text("workspace").notNull(),
43
- key: text("key").notNull(),
44
- value: text("value", { mode: "json" }).$type().notNull()
45
- }, (table) => [primaryKey({ columns: [table.workspace, table.key] })])
269
+ workspace: text$1("workspace").notNull(),
270
+ key: text$1("key").notNull(),
271
+ value: text$1("value", { mode: "json" }).$type().notNull()
272
+ }, (table) => [primaryKey$1({ columns: [table.workspace, table.key] })])
46
273
  };
47
- //#endregion
48
- //#region src/storage/blob-database.ts
274
+ // src/storage/history-index-sqlite.ts
49
275
  const { workspaceHistoryWorkspaces: workspaces, workspaceHistoryRefs: refs, workspaceHistoryRevisions: revisions, workspaceHistoryObjects: objects, workspaceHistoryMetadata: metadata } = workspaceHistorySchema;
276
+ function activeObject(workspace, digest) {
277
+ return sql`${objects.workspace} = ${workspace} and ${objects.size} >= 0
278
+ and ${objects.digest} >= ${digest} and ${objects.digest} < ${digest} || '.'`;
279
+ }
280
+ function active(workspace) {
281
+ return sql`exists (select 1 from ${workspaces} where ${workspaces.workspace} = ${workspace} and ${workspaces.deleted} = 0)`;
282
+ }
283
+ /** Each write is one atomic batch. */
284
+ function sqliteHistoryIndex(db) {
285
+ const ref = async (workspace, name) => {
286
+ const [row] = await db.select().from(refs).where(and(eq(refs.workspace, workspace), eq(refs.ref, name), active(workspace)));
287
+ return row;
288
+ };
289
+ return {
290
+ async claim(current, legacy) {
291
+ const [currentRows, legacyRows] = await db.batch([
292
+ db.select({ workspace: workspaces.workspace }).from(workspaces).where(eq(workspaces.workspace, current)),
293
+ db.select({ workspace: workspaces.workspace }).from(workspaces).where(eq(workspaces.workspace, legacy ?? current)),
294
+ db.insert(workspaces).select(sql`
295
+ select ${current}, 0
296
+ where not exists (
297
+ select 1 from ${workspaces} where ${workspaces.workspace} = ${legacy ?? current}
298
+ )
299
+ `).onConflictDoNothing()
300
+ ]);
301
+ return currentRows[0]?.workspace ?? legacyRows[0]?.workspace ?? current;
302
+ },
303
+ async deleted(workspace) {
304
+ const [row] = await db.select({ deleted: workspaces.deleted }).from(workspaces).where(eq(workspaces.workspace, workspace));
305
+ return row?.deleted;
306
+ },
307
+ ref,
308
+ async heads(workspace) {
309
+ const heads = await db.select({
310
+ ref: refs.ref,
311
+ head: refs.head
312
+ }).from(refs).where(and(eq(refs.workspace, workspace), isNotNull(refs.head), active(workspace)));
313
+ if (!heads.length) return [];
314
+ const rows = await db.select().from(revisions).where(and(eq(revisions.workspace, workspace), eq(revisions.committed, true), inArray(revisions.id, heads.map((row) => row.head)), active(workspace)));
315
+ const byId = new Map(rows.map((row) => [row.id, row]));
316
+ return heads.flatMap(({ ref, head }) => {
317
+ const revision = byId.get(head);
318
+ return revision ? [{
319
+ ref,
320
+ revision
321
+ }] : [];
322
+ });
323
+ },
324
+ async revision(workspace, id) {
325
+ const [row] = await db.select().from(revisions).where(and(eq(revisions.workspace, workspace), eq(revisions.id, id), eq(revisions.committed, true), active(workspace)));
326
+ return row;
327
+ },
328
+ async list(workspace, { ref, before, path, limit }) {
329
+ const previousEntries = sql`
330
+ coalesce((
331
+ select previous.entries
332
+ from ${revisions} as previous
333
+ where previous.workspace = ${revisions.workspace}
334
+ and previous.id = ${revisions.parentId}
335
+ and previous.committed = 1
336
+ ), '{}')
337
+ `;
338
+ const pathFilter = path === void 0 ? void 0 : sql`(
339
+ exists (
340
+ select 1
341
+ from json_each(${revisions.entries}) as current_file
342
+ left join json_each(${previousEntries}) as previous_file
343
+ on previous_file.key = current_file.key
344
+ where (current_file.key = ${path} or substr(current_file.key, 1, length(${path}) + 1) = ${path} || '/')
345
+ and (
346
+ previous_file.key is null
347
+ or json_extract(current_file.value, '$.digest') is not json_extract(previous_file.value, '$.digest')
348
+ or json_extract(current_file.value, '$.size') is not json_extract(previous_file.value, '$.size')
349
+ or json_extract(current_file.value, '$.mediaType') is not json_extract(previous_file.value, '$.mediaType')
350
+ or json_extract(current_file.value, '$.metadata') is not json_extract(previous_file.value, '$.metadata')
351
+ )
352
+ )
353
+ or exists (
354
+ select 1
355
+ from json_each(${previousEntries}) as previous_file
356
+ left join json_each(${revisions.entries}) as current_file
357
+ on current_file.key = previous_file.key
358
+ where (previous_file.key = ${path} or substr(previous_file.key, 1, length(${path}) + 1) = ${path} || '/')
359
+ and current_file.key is null
360
+ )
361
+ )`;
362
+ return await db.select().from(revisions).where(and(eq(revisions.workspace, workspace), eq(revisions.ref, ref), eq(revisions.committed, true), before === void 0 ? void 0 : lt(revisions.sequence, before), pathFilter, active(workspace))).orderBy(desc(revisions.sequence)).limit(limit);
363
+ },
364
+ async usage(workspace) {
365
+ const [result] = await db.values(sql`
366
+ select coalesce(sum(size), 0) as bytes, count(*) as objects from (
367
+ select distinct json_extract(file.value, '$.digest') as digest,
368
+ json_extract(file.value, '$.size') as size
369
+ from ${revisions}, json_each(${revisions.entries}) as file
370
+ where ${revisions.workspace} = ${workspace} and ${revisions.committed} = 1
371
+ and ${active(workspace)}
372
+ )
373
+ `);
374
+ return {
375
+ bytes: result?.[0] ?? 0,
376
+ objects: result?.[1] ?? 0
377
+ };
378
+ },
379
+ async objectKey(workspace, digest) {
380
+ const [object] = await db.select({ key: objects.digest }).from(objects).where(activeObject(workspace, digest)).limit(1);
381
+ return object?.key;
382
+ },
383
+ async register(workspace, registry) {
384
+ await db.insert(objects).select(sql`
385
+ select ${workspaces.workspace}, json_extract(object.value, '$.key'), json_extract(object.value, '$.size')
386
+ from ${workspaces}, json_each(${JSON.stringify(registry)}) as object
387
+ where ${workspaces.workspace} = ${workspace} and ${workspaces.deleted} = 0
388
+ and not exists (select 1 from ${objects} where ${activeObject(workspace, sql`json_extract(object.value, '$.digest')`)})
389
+ `).onConflictDoNothing();
390
+ },
391
+ async objectKeys(workspace, digests) {
392
+ return await db.values(sql`
393
+ select needed.value, ${objects.digest}
394
+ from json_each(${JSON.stringify(digests)}) as needed join ${objects} on ${activeObject(workspace, sql`needed.value`)}
395
+ `);
396
+ },
397
+ async hasObject(workspace, key) {
398
+ const [row] = await db.select({ key: objects.digest }).from(objects).where(and(eq(objects.workspace, workspace), eq(objects.digest, key), sql`${objects.size} >= 0`)).limit(1);
399
+ return row !== void 0;
400
+ },
401
+ async publish(workspace, { revision: row, ifHead, ifHeads, keys, complete }) {
402
+ const objectsReady = sql`${complete} and not exists (
403
+ select 1 from json_each(${JSON.stringify(keys)}) as verified
404
+ where not exists (
405
+ select 1 from ${objects}
406
+ where ${objects.workspace} = ${workspace} and ${objects.digest} = verified.value and ${objects.size} >= 0
407
+ )
408
+ )`;
409
+ const [, , changed] = await db.batch([
410
+ db.insert(refs).select(sql`
411
+ select ${workspaces.workspace}, ${row.ref}, null, 0
412
+ from ${workspaces} where ${workspaces.workspace} = ${workspace} and ${workspaces.deleted} = 0 and ${objectsReady}
413
+ `).onConflictDoNothing(),
414
+ db.insert(revisions).select(sql`
415
+ select ${row.workspace}, ${row.id}, ${row.ref}, ${row.parentId}, ${row.sequence}, ${row.createdAt},
416
+ ${row.message}, ${row.metadata === null ? null : JSON.stringify(row.metadata)},
417
+ ${row.files}, ${row.bytes}, ${JSON.stringify(row.entries)}, 0
418
+ from ${workspaces} where ${workspaces.workspace} = ${workspace} and ${workspaces.deleted} = 0 and ${objectsReady}
419
+ `).onConflictDoNothing(),
420
+ db.update(refs).set({
421
+ head: row.id,
422
+ sequence: sql`${refs.sequence} + 1`
423
+ }).where(and(eq(refs.workspace, workspace), eq(refs.ref, row.ref), sql`${refs.head} is ${ifHead}`, ...ifHeads.map(([expectedRef, expectedHead]) => expectedHead === null ? sql`(not exists (select 1 from ${refs} as cross_ref where cross_ref.workspace = ${workspace} and cross_ref.ref = ${expectedRef}) or exists (select 1 from ${refs} as cross_ref where cross_ref.workspace = ${workspace} and cross_ref.ref = ${expectedRef} and cross_ref.head is null))` : sql`exists (select 1 from ${refs} as cross_ref where cross_ref.workspace = ${workspace} and cross_ref.ref = ${expectedRef} and cross_ref.head is ${expectedHead})`), objectsReady, active(workspace))).returning({ head: refs.head }),
424
+ db.update(revisions).set({ committed: true }).where(and(eq(revisions.workspace, workspace), eq(revisions.id, row.id), sql`exists (select 1 from ${refs} where ${refs.workspace} = ${workspace} and ${refs.ref} = ${row.ref} and ${refs.head} = ${row.id})`, active(workspace)))
425
+ ]);
426
+ return changed.length > 0;
427
+ },
428
+ async deleteRef(workspace, ref, head) {
429
+ const sameHead = sql`exists (select 1 from ${refs} where ${refs.workspace} = ${workspace} and ${refs.ref} = ${ref} and ${refs.head} is ${head})`;
430
+ const [, , removed] = await db.batch([
431
+ db.update(objects).set({ size: -1 }).where(and(eq(objects.workspace, workspace), sql`${objects.size} >= 0`, sameHead, sql`substr(${objects.digest}, 1, 64) in (
432
+ select json_extract(file.value, '$.digest')
433
+ from ${revisions}, json_each(${revisions.entries}) as file
434
+ where ${revisions.workspace} = ${workspace} and ${revisions.ref} = ${ref}
435
+ )`, sql`substr(${objects.digest}, 1, 64) not in (
436
+ select json_extract(file.value, '$.digest')
437
+ from ${revisions}, json_each(${revisions.entries}) as file
438
+ where ${revisions.workspace} = ${workspace} and ${revisions.ref} <> ${ref} and ${revisions.committed} = 1
439
+ )`)),
440
+ db.delete(revisions).where(and(eq(revisions.workspace, workspace), eq(revisions.ref, ref), sameHead)),
441
+ db.delete(refs).where(and(eq(refs.workspace, workspace), eq(refs.ref, ref), sql`${refs.head} is ${head}`)).returning({ ref: refs.ref })
442
+ ]);
443
+ return removed.length > 0;
444
+ },
445
+ async markedObjects(workspace) {
446
+ return (await db.select({ key: objects.digest }).from(objects).where(and(eq(objects.workspace, workspace), sql`${objects.size} < 0`))).map((row) => row.key);
447
+ },
448
+ async dropMarkedObjects(workspace, keys) {
449
+ await db.delete(objects).where(and(eq(objects.workspace, workspace), inArray(objects.digest, keys), sql`${objects.size} < 0`));
450
+ },
451
+ async tombstone(workspace) {
452
+ await db.batch([db.update(workspaces).set({ deleted: true }).where(eq(workspaces.workspace, workspace)), db.delete(refs).where(eq(refs.workspace, workspace))]);
453
+ },
454
+ async objects(workspace) {
455
+ return (await db.select({ key: objects.digest }).from(objects).where(eq(objects.workspace, workspace))).map((row) => row.key);
456
+ },
457
+ async purge(workspace) {
458
+ await db.batch([
459
+ db.delete(revisions).where(eq(revisions.workspace, workspace)),
460
+ db.delete(objects).where(eq(objects.workspace, workspace)),
461
+ db.delete(metadata).where(eq(metadata.workspace, workspace))
462
+ ]);
463
+ },
464
+ async getMeta(workspace, key) {
465
+ const [row] = await db.select().from(metadata).where(and(eq(metadata.workspace, workspace), eq(metadata.key, key), active(workspace)));
466
+ return row?.value;
467
+ },
468
+ async setMeta(workspace, key, value) {
469
+ await db.insert(metadata).select(db.select({
470
+ workspace: sql`${workspace}`.as("workspace"),
471
+ key: sql`${key}`.as("key"),
472
+ value: sql`${JSON.stringify(value)}`.as("value")
473
+ }).from(workspaces).where(and(eq(workspaces.workspace, workspace), eq(workspaces.deleted, false)))).onConflictDoUpdate({
474
+ target: [metadata.workspace, metadata.key],
475
+ set: { value: sql`${JSON.stringify(value)}` }
476
+ });
477
+ },
478
+ async deleteMeta(workspace, key) {
479
+ await db.delete(metadata).where(and(eq(metadata.workspace, workspace), eq(metadata.key, key)));
480
+ }
481
+ };
482
+ }
483
+ // src/storage/blob-database.ts
50
484
  function publicRevision(row) {
51
485
  const revision = {
52
486
  id: row.id,
@@ -68,7 +502,7 @@ var ContentAddressedWorkspaceStore = class {
68
502
  #dirty = false;
69
503
  #baseline;
70
504
  #queue = Promise.resolve();
71
- #database;
505
+ #backend;
72
506
  constructor(options) {
73
507
  this.options = options;
74
508
  if (typeof options.workspace !== "string" || !options.workspace) throw workspaceError("[vitehub] Blob + Database Store requires a workspace identity.");
@@ -81,42 +515,63 @@ var ContentAddressedWorkspaceStore = class {
81
515
  const legacy = `${legacyPrefix}/${digest}`;
82
516
  return legacy === current ? [current] : [current, legacy];
83
517
  });
518
+ provideWorkspaceStoreTarget(this, () => this.#storeTarget());
84
519
  }
85
- [workspaceStoreTarget]() {
520
+ async #storeTarget() {
521
+ return (await this.#backendReady()).target;
522
+ }
523
+ [blobDatabaseSources]() {
524
+ const { blob, database } = this.options;
86
525
  return {
87
- provider: "blob-database",
88
- workspace: this.options.workspace,
89
- database: this.#db
526
+ blob: typeof blob === "string" ? blob : void 0,
527
+ database: typeof database === "string" ? database : void 0
90
528
  };
91
529
  }
92
- get #db() {
93
- if (this.#database) return this.#database;
94
- const { database } = this.options;
95
- const resolved = typeof database === "function" ? database() : database;
96
- if (typeof resolved?.batch !== "function") throw workspaceErrorDiagnostics.WORKSPACE_R0077({ message: `[vitehub] The \`database\` of the Blob + Database Store for workspace "${this.options.workspace}" is not a Drizzle database.` });
97
- return this.#database = resolved;
530
+ #backendReady() {
531
+ this.#backend ??= this.#connect().catch((error) => {
532
+ this.#backend = void 0;
533
+ throw error;
534
+ });
535
+ return this.#backend;
536
+ }
537
+ async #connect() {
538
+ const { blob, database, workspace } = this.options;
539
+ const storage = typeof blob === "string" ? await useBlobStore(blob) : blob;
540
+ const db = typeof database === "string" ? (await useNamedDatabase())(database).db : typeof database === "function" ? database() : database;
541
+ if (is(db, PgAsyncDatabase)) return {
542
+ blob: storage,
543
+ index: postgresHistoryIndex(db),
544
+ target: {
545
+ provider: "blob-database",
546
+ workspace,
547
+ dialect: "postgresql",
548
+ database: db
549
+ }
550
+ };
551
+ if (isSqliteDatabase(db)) return {
552
+ blob: storage,
553
+ index: sqliteHistoryIndex(db),
554
+ target: {
555
+ provider: "blob-database",
556
+ workspace,
557
+ dialect: "sqlite",
558
+ database: db
559
+ }
560
+ };
561
+ throw workspaceErrorDiagnostics.WORKSPACE_R0077({ message: `[vitehub] The \`database\` of the Blob + Database Store for workspace "${workspace}" is not a Drizzle database.` });
562
+ }
563
+ async #index() {
564
+ return (await this.#backendReady()).index;
565
+ }
566
+ async #blob() {
567
+ return (await this.#backendReady()).blob;
98
568
  }
99
569
  history = {
100
570
  head: async (options) => await this.#head(normalizeHistoryRef(options?.ref)),
101
571
  list: async (options) => await this.#listHistory(options),
102
572
  refs: async () => await this.#refs(),
103
573
  open: async (id) => await this.#open(id),
104
- usage: async () => {
105
- const workspace = await this.#key();
106
- const [result] = await this.#db.values(sql`
107
- select coalesce(sum(size), 0) as bytes, count(*) as objects from (
108
- select distinct json_extract(file.value, '$.digest') as digest,
109
- json_extract(file.value, '$.size') as size
110
- from ${revisions}, json_each(${revisions.entries}) as file
111
- where ${revisions.workspace} = ${workspace} and ${revisions.committed} = 1
112
- and ${this.#active(workspace)}
113
- )
114
- `);
115
- return {
116
- bytes: result?.[0] ?? 0,
117
- objects: result?.[1] ?? 0
118
- };
119
- },
574
+ usage: async () => await (await this.#index()).usage(await this.#key()),
120
575
  commit: async (options) => await this.#mutate(async () => {
121
576
  const revision = await this.#commit(options);
122
577
  if (revision.ref === "main") {
@@ -125,40 +580,24 @@ var ContentAddressedWorkspaceStore = class {
125
580
  this.#baseline = void 0;
126
581
  }
127
582
  return revision;
128
- })
583
+ }),
584
+ deleteRef: async (options) => await this.#mutate(async () => await this.#deleteRef(readHistoryDeleteRef(options)))
129
585
  };
130
586
  async #key() {
131
- const candidates = await this.#namespace;
132
- this.#ready ??= this.#db.batch([
133
- this.#db.select({ workspace: workspaces.workspace }).from(workspaces).where(eq(workspaces.workspace, candidates[0])),
134
- this.#db.select({ workspace: workspaces.workspace }).from(workspaces).where(eq(workspaces.workspace, candidates[1] ?? candidates[0])),
135
- this.#db.insert(workspaces).select(sql`
136
- select ${candidates[0]}, 0
137
- where not exists (
138
- select 1 from ${workspaces} where ${workspaces.workspace} = ${candidates[1] ?? candidates[0]}
139
- )
140
- `).onConflictDoNothing()
141
- ]).then((results) => {
142
- const [current, legacy] = results;
143
- return current[0]?.workspace ?? legacy[0]?.workspace ?? candidates[0];
144
- }).catch((error) => {
587
+ this.#ready ??= Promise.all([this.#namespace, this.#index()]).then(([candidates, index]) => index.claim(candidates[0], candidates[1])).catch((error) => {
145
588
  this.#ready = void 0;
146
589
  throw error;
147
590
  });
148
591
  return await this.#ready;
149
592
  }
150
- #active(workspace) {
151
- return sql`exists (select 1 from ${workspaces} where ${workspaces.workspace} = ${workspace} and ${workspaces.deleted} = 0)`;
152
- }
153
593
  async #isDeleted() {
154
594
  const workspace = await this.#key();
155
- const [row] = await this.#db.select({ deleted: workspaces.deleted }).from(workspaces).where(eq(workspaces.workspace, workspace));
156
- if (!row) throw workspaceError("[vitehub] Workspace history identity is missing.");
157
- return row.deleted;
595
+ const deleted = await (await this.#index()).deleted(workspace);
596
+ if (deleted === void 0) throw workspaceError("[vitehub] Workspace history identity is missing.");
597
+ return deleted;
158
598
  }
159
599
  async #ref(workspace, ref) {
160
- const [row] = await this.#db.select().from(refs).where(and(eq(refs.workspace, workspace), eq(refs.ref, ref), this.#active(workspace)));
161
- return row;
600
+ return await (await this.#index()).ref(workspace, ref);
162
601
  }
163
602
  async #head(ref) {
164
603
  const workspace = await this.#key();
@@ -167,20 +606,10 @@ var ContentAddressedWorkspaceStore = class {
167
606
  }
168
607
  async #refs() {
169
608
  const workspace = await this.#key();
170
- const heads = await this.#db.select({
171
- ref: refs.ref,
172
- head: refs.head
173
- }).from(refs).where(and(eq(refs.workspace, workspace), isNotNull(refs.head), this.#active(workspace)));
174
- if (!heads.length) return [];
175
- const rows = await this.#db.select().from(revisions).where(and(eq(revisions.workspace, workspace), eq(revisions.committed, true), inArray(revisions.id, heads.map((row) => row.head)), this.#active(workspace)));
176
- const byId = new Map(rows.map((row) => [row.id, row]));
177
- return heads.flatMap(({ ref, head }) => {
178
- const row = byId.get(head);
179
- return row ? [{
180
- name: ref,
181
- head: publicRevision(row)
182
- }] : [];
183
- }).sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
609
+ return (await (await this.#index()).heads(workspace)).map(({ ref, revision }) => ({
610
+ name: ref,
611
+ head: publicRevision(revision)
612
+ })).sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
184
613
  }
185
614
  #deleted() {
186
615
  throw new ViteHubError("WORKSPACE_NOT_FOUND", "[vitehub] This Workspace has been deleted. Use a new workspace identity.", { details: { workspace: this.options.workspace } });
@@ -190,7 +619,7 @@ var ContentAddressedWorkspaceStore = class {
190
619
  }
191
620
  async #revision(id) {
192
621
  const workspace = await this.#key();
193
- const [row] = await this.#db.select().from(revisions).where(and(eq(revisions.workspace, workspace), eq(revisions.id, id), eq(revisions.committed, true), this.#active(workspace)));
622
+ const row = await (await this.#index()).revision(workspace, id);
194
623
  if (!row) throw new ViteHubError("WORKSPACE_NOT_FOUND", `[vitehub] Workspace revision does not exist: ${id}.`);
195
624
  return row;
196
625
  }
@@ -202,40 +631,12 @@ var ContentAddressedWorkspaceStore = class {
202
631
  const workspace = await this.#key();
203
632
  const cursor = options.cursor ? await this.#revision(options.cursor) : void 0;
204
633
  if (cursor && cursor.ref !== ref) throw workspaceErrorDiagnostics.WORKSPACE_R0070({ message: `[vitehub] History cursor belongs to ref "${cursor.ref}". Pass it with the ref that returned it.` });
205
- const previousEntries = sql`
206
- coalesce((
207
- select previous.entries
208
- from ${revisions} as previous
209
- where previous.workspace = ${revisions.workspace}
210
- and previous.id = ${revisions.parentId}
211
- and previous.committed = 1
212
- ), '{}')
213
- `;
214
- const pathFilter = path === void 0 ? void 0 : sql`(
215
- exists (
216
- select 1
217
- from json_each(${revisions.entries}) as current_file
218
- left join json_each(${previousEntries}) as previous_file
219
- on previous_file.key = current_file.key
220
- where (current_file.key = ${path} or substr(current_file.key, 1, length(${path}) + 1) = ${path} || '/')
221
- and (
222
- previous_file.key is null
223
- or json_extract(current_file.value, '$.digest') is not json_extract(previous_file.value, '$.digest')
224
- or json_extract(current_file.value, '$.size') is not json_extract(previous_file.value, '$.size')
225
- or json_extract(current_file.value, '$.mediaType') is not json_extract(previous_file.value, '$.mediaType')
226
- or json_extract(current_file.value, '$.metadata') is not json_extract(previous_file.value, '$.metadata')
227
- )
228
- )
229
- or exists (
230
- select 1
231
- from json_each(${previousEntries}) as previous_file
232
- left join json_each(${revisions.entries}) as current_file
233
- on current_file.key = previous_file.key
234
- where (previous_file.key = ${path} or substr(previous_file.key, 1, length(${path}) + 1) = ${path} || '/')
235
- and current_file.key is null
236
- )
237
- )`;
238
- const rows = await this.#db.select().from(revisions).where(and(eq(revisions.workspace, workspace), eq(revisions.ref, ref), eq(revisions.committed, true), cursor ? lt(revisions.sequence, cursor.sequence) : void 0, pathFilter, this.#active(workspace))).orderBy(desc(revisions.sequence)).limit(limit + 1);
634
+ const rows = await (await this.#index()).list(workspace, {
635
+ ref,
636
+ before: cursor?.sequence,
637
+ path,
638
+ limit: limit + 1
639
+ });
239
640
  const result = { revisions: rows.slice(0, limit).map(publicRevision) };
240
641
  if (rows.length > limit) result.cursor = rows[limit - 1].id;
241
642
  return result;
@@ -286,7 +687,9 @@ var ContentAddressedWorkspaceStore = class {
286
687
  const normalized = normalizeHistoryPath(path);
287
688
  const file = Object.hasOwn(row.entries, normalized) ? row.entries[normalized] : void 0;
288
689
  if (!file) throw workspaceError(`[vitehub] Workspace file does not exist: ${path}.`);
289
- const [error, body] = await this.options.blob.get(`${workspace}/sha256/${file.digest}`);
690
+ const key = await (await this.#index()).objectKey(workspace, file.digest);
691
+ if (!key) throw workspaceError(`[vitehub] Retained history object is missing: ${file.digest}.`);
692
+ const [error, body] = await (await this.#blob()).get(`${workspace}/sha256/${key}`);
290
693
  if (error) throw error;
291
694
  if (!body) throw workspaceError(`[vitehub] Retained history object is missing: ${file.digest}.`);
292
695
  const bytes = new Uint8Array(await body.arrayBuffer());
@@ -304,6 +707,8 @@ var ContentAddressedWorkspaceStore = class {
304
707
  return [normalizeHistoryRef(name), head];
305
708
  });
306
709
  const workspace = await this.#key();
710
+ const index = await this.#index();
711
+ const blob = await this.#blob();
307
712
  await this.#assertActive();
308
713
  const current = await this.#ref(workspace, ref);
309
714
  if ((current?.head ?? null) !== options.ifHead) rejectHistoryHead(options, this.#conflict(ref, options.ifHead, current?.head ?? null));
@@ -349,40 +754,41 @@ var ContentAddressedWorkspaceStore = class {
349
754
  entries: sorted
350
755
  };
351
756
  const id = await sha256(manifest);
352
- const registry = [...contents].map(([digest, bytes]) => ({
353
- digest,
354
- size: bytes.byteLength
355
- }));
356
- await this.#db.insert(objects).select(sql`
357
- select ${workspaces.workspace}, json_extract(object.value, '$.digest'), json_extract(object.value, '$.size')
358
- from ${workspaces}, json_each(${JSON.stringify(registry)}) as object
359
- where ${workspaces.workspace} = ${workspace} and ${workspaces.deleted} = 0
360
- `).onConflictDoNothing();
361
- await this.#assertActive();
362
- const upload = async ([digest, bytes]) => {
363
- const key = `${workspace}/sha256/${digest}`;
364
- const [headError, object] = await this.options.blob.head(key);
757
+ const register = async () => {
758
+ await index.register(workspace, [...contents].map(([digest, bytes]) => ({
759
+ digest,
760
+ key: `${digest}-${crypto.randomUUID()}`,
761
+ size: bytes.byteLength
762
+ })));
763
+ await this.#assertActive();
764
+ return await index.objectKeys(workspace, [...contents.keys()]);
765
+ };
766
+ const upload = async ([digest, generation]) => {
767
+ const key = `${workspace}/sha256/${generation}`;
768
+ const [headError, object] = await blob.head(key);
365
769
  if (headError && headError.code !== "BLOB_NOT_FOUND") throw headError;
366
770
  if (!object) {
367
- const [uploadError] = await this.options.blob.put(key, bytes, {
771
+ const [uploadError] = await blob.put(key, contents.get(digest), {
368
772
  addRandomSuffix: false,
369
773
  contentType: "application/octet-stream"
370
774
  });
775
+ if (!await index.hasObject(workspace, generation) || await this.#isDeleted()) {
776
+ await this.#removeObject(key);
777
+ await this.#assertActive();
778
+ return;
779
+ }
371
780
  if (uploadError) {
372
- const [concurrentError, concurrentObject] = await this.options.blob.head(key);
781
+ const [concurrentError, concurrentObject] = await blob.head(key);
373
782
  if (concurrentError || !concurrentObject) throw uploadError;
374
783
  }
375
784
  }
376
- if (await this.#isDeleted()) {
377
- await this.#removeObject(key);
378
- this.#deleted();
785
+ };
786
+ const uploadAll = async (uploads) => {
787
+ for (let offset = 0; offset < uploads.length; offset += 8) {
788
+ const results = await Promise.allSettled(uploads.slice(offset, offset + 8).map(upload));
789
+ for (const result of results) if (result.status === "rejected") throw result.reason;
379
790
  }
380
791
  };
381
- const uploads = [...contents];
382
- for (let offset = 0; offset < uploads.length; offset += 8) {
383
- const results = await Promise.allSettled(uploads.slice(offset, offset + 8).map(upload));
384
- for (const result of results) if (result.status === "rejected") throw result.reason;
385
- }
386
792
  const row = {
387
793
  ...manifest,
388
794
  entries: { ...sorted },
@@ -392,46 +798,70 @@ var ContentAddressedWorkspaceStore = class {
392
798
  files: Object.keys(sorted).length,
393
799
  bytes: Object.values(sorted).reduce((total, entry) => total + entry.size, 0)
394
800
  };
395
- expectedHeads.map(([name, head]) => sql`(select expected.head from ${refs} as expected where expected.workspace = ${workspace} and expected.ref = ${name}) is ${head}`);
396
- const [, , changed] = await this.#db.batch([
397
- this.#db.insert(refs).select(sql`
398
- select ${workspaces.workspace}, ${ref}, null, 0
399
- from ${workspaces} where ${workspaces.workspace} = ${workspace} and ${workspaces.deleted} = 0
400
- `).onConflictDoNothing(),
401
- this.#db.insert(revisions).select(sql`
402
- select ${row.workspace}, ${row.id}, ${row.ref}, ${row.parentId}, ${row.sequence}, ${row.createdAt},
403
- ${row.message}, ${row.metadata === null ? null : JSON.stringify(row.metadata)},
404
- ${row.files}, ${row.bytes}, ${JSON.stringify(row.entries)}, 0
405
- from ${workspaces} where ${workspaces.workspace} = ${workspace} and ${workspaces.deleted} = 0
406
- `).onConflictDoNothing(),
407
- this.#db.update(refs).set({
408
- head: id,
409
- sequence: sql`${refs.sequence} + 1`
410
- }).where(and(eq(refs.workspace, workspace), eq(refs.ref, ref), sql`${refs.head} is ${options.ifHead}`, ...Object.entries(options.ifHeads ?? {}).map(([expectedRef, expectedHead]) => expectedHead === null ? sql`(not exists (select 1 from ${refs} as cross_ref where cross_ref.workspace = ${workspace} and cross_ref.ref = ${expectedRef}) or exists (select 1 from ${refs} as cross_ref where cross_ref.workspace = ${workspace} and cross_ref.ref = ${expectedRef} and cross_ref.head is null))` : sql`exists (select 1 from ${refs} as cross_ref where cross_ref.workspace = ${workspace} and cross_ref.ref = ${expectedRef} and cross_ref.head is ${expectedHead})`), this.#active(workspace))).returning({ head: refs.head }),
411
- this.#db.update(revisions).set({ committed: true }).where(and(eq(revisions.workspace, workspace), eq(revisions.id, id), sql`exists (select 1 from ${refs} where ${refs.workspace} = ${workspace} and ${refs.ref} = ${ref} and ${refs.head} = ${id})`, this.#active(workspace)))
412
- ]);
413
- if (!changed.length) {
801
+ for (let attempt = 0;; attempt++) {
802
+ const uploads = await register();
803
+ await uploadAll(uploads);
804
+ if (await index.publish(workspace, {
805
+ revision: {
806
+ ...row,
807
+ committed: false
808
+ },
809
+ ifHead: options.ifHead,
810
+ ifHeads: expectedHeads,
811
+ keys: uploads.map(([, key]) => key),
812
+ complete: uploads.length === contents.size
813
+ })) break;
414
814
  if (await this.#isDeleted()) this.#deleted();
415
815
  for (const [name, expected] of expectedHeads) {
416
816
  const actual = (await this.#ref(workspace, name))?.head ?? null;
417
817
  if (actual !== expected) throw this.#conflict(name, expected, actual);
418
818
  }
419
- rejectHistoryHead(options, this.#conflict(ref, options.ifHead, (await this.#ref(workspace, ref))?.head ?? null));
819
+ const actual = (await this.#ref(workspace, ref))?.head ?? null;
820
+ if (actual !== options.ifHead) rejectHistoryHead(options, this.#conflict(ref, options.ifHead, actual));
821
+ if (attempt === 4) throw workspaceConflict("[vitehub] History objects of this commit are being deleted by history.deleteRef(). Retry the commit.", { details: {
822
+ workspace: this.options.workspace,
823
+ ref
824
+ } });
825
+ await new Promise((resolve) => setTimeout(resolve, 50 * 2 ** attempt));
420
826
  }
421
827
  return publicRevision({
422
828
  ...row,
423
829
  committed: true
424
830
  });
425
831
  }
832
+ async #deleteRef({ ref, ifHead }) {
833
+ const workspace = await this.#key();
834
+ await this.#assertActive();
835
+ const current = await this.#ref(workspace, ref);
836
+ const head = current?.head ?? null;
837
+ if (ifHead !== void 0 && head !== ifHead) throw this.#conflict(ref, ifHead, head);
838
+ if (!current) {
839
+ await this.#removeUnusedObjects(workspace);
840
+ return false;
841
+ }
842
+ if (!await (await this.#index()).deleteRef(workspace, ref, head)) throw this.#conflict(ref, head, (await this.#ref(workspace, ref))?.head ?? null);
843
+ await this.#removeUnusedObjects(workspace);
844
+ return true;
845
+ }
846
+ async #removeUnusedObjects(workspace) {
847
+ const index = await this.#index();
848
+ const marked = await index.markedObjects(workspace);
849
+ for (let offset = 0; offset < marked.length; offset += 8) {
850
+ const batch = marked.slice(offset, offset + 8);
851
+ await Promise.all(batch.map((key) => this.#removeObject(`${workspace}/sha256/${key}`)));
852
+ await index.dropMarkedObjects(workspace, batch);
853
+ }
854
+ }
426
855
  #conflict(ref, expected, actual) {
427
856
  return historyConflict(ref, expected, actual, { workspace: this.options.workspace });
428
857
  }
429
858
  async #removeObject(key) {
430
- const [headError, object] = await this.options.blob.head(key);
859
+ const blob = await this.#blob();
860
+ const [headError, object] = await blob.head(key);
431
861
  if (headError?.code === "BLOB_NOT_FOUND") return;
432
862
  if (headError) throw headError;
433
863
  if (!object) return;
434
- const [error] = await this.options.blob.delete(key);
864
+ const [error] = await blob.delete(key);
435
865
  if (error && error.code !== "BLOB_NOT_FOUND") throw error;
436
866
  }
437
867
  async delete() {
@@ -439,14 +869,15 @@ var ContentAddressedWorkspaceStore = class {
439
869
  }
440
870
  async #delete() {
441
871
  const workspace = await this.#key();
442
- await this.#db.batch([this.#db.update(workspaces).set({ deleted: true }).where(eq(workspaces.workspace, workspace)), this.#db.delete(refs).where(eq(refs.workspace, workspace))]);
443
- const catalog = await this.#db.select().from(objects).where(eq(objects.workspace, workspace));
444
- for (const object of catalog) await this.#removeObject(`${workspace}/sha256/${object.digest}`);
872
+ const index = await this.#index();
873
+ const blob = await this.#blob();
874
+ await index.tombstone(workspace);
875
+ for (const key of await index.objects(workspace)) await this.#removeObject(`${workspace}/sha256/${key}`);
445
876
  let cursor;
446
877
  const cursors = /* @__PURE__ */ new Set();
447
878
  const remaining = [];
448
879
  do {
449
- const [error, page] = await this.options.blob.list({
880
+ const [error, page] = await blob.list({
450
881
  prefix: `${workspace}/sha256/`,
451
882
  cursor,
452
883
  limit: 1e3
@@ -458,14 +889,10 @@ var ContentAddressedWorkspaceStore = class {
458
889
  if (cursor) cursors.add(cursor);
459
890
  } while (cursor);
460
891
  for (let offset = 0; offset < remaining.length; offset += 1e3) {
461
- const [error] = await this.options.blob.delete(remaining.slice(offset, offset + 1e3));
892
+ const [error] = await blob.delete(remaining.slice(offset, offset + 1e3));
462
893
  if (error) throw error;
463
894
  }
464
- await this.#db.batch([
465
- this.#db.delete(revisions).where(eq(revisions.workspace, workspace)),
466
- this.#db.delete(objects).where(eq(objects.workspace, workspace)),
467
- this.#db.delete(metadata).where(eq(metadata.workspace, workspace))
468
- ]);
895
+ await index.purge(workspace);
469
896
  this.#draft = void 0;
470
897
  this.#dirty = false;
471
898
  }
@@ -579,30 +1006,29 @@ var ContentAddressedWorkspaceStore = class {
579
1006
  return diffSnapshots(baseline, await createSnapshotFromEntries(await draft.store.list("", { recursive: true })));
580
1007
  }
581
1008
  async getMeta(key) {
582
- const workspace = await this.#key();
583
- const [row] = await this.#db.select().from(metadata).where(and(eq(metadata.workspace, workspace), eq(metadata.key, key), this.#active(workspace)));
584
- return row?.value;
1009
+ return await (await this.#index()).getMeta(await this.#key(), key);
585
1010
  }
586
1011
  async setMeta(key, value) {
587
1012
  await this.#assertActive();
588
1013
  const workspace = await this.#key();
589
- if (value === void 0) {
590
- await this.#db.delete(metadata).where(and(eq(metadata.workspace, workspace), eq(metadata.key, key)));
591
- return;
592
- }
593
- await this.#db.insert(metadata).select(this.#db.select({
594
- workspace: sql`${workspace}`.as("workspace"),
595
- key: sql`${key}`.as("key"),
596
- value: sql`${JSON.stringify(value)}`.as("value")
597
- }).from(workspaces).where(and(eq(workspaces.workspace, workspace), eq(workspaces.deleted, false)))).onConflictDoUpdate({
598
- target: [metadata.workspace, metadata.key],
599
- set: { value: sql`${JSON.stringify(value)}` }
600
- });
1014
+ const index = await this.#index();
1015
+ if (value === void 0) await index.deleteMeta(workspace, key);
1016
+ else await index.setMeta(workspace, key, value);
601
1017
  }
602
1018
  };
603
- /** Blob stores bytes; Database atomically publishes immutable folder manifests. */
1019
+ function isSqliteDatabase(value) {
1020
+ return typeof value === "object" && value !== null && typeof Reflect.get(value, "batch") === "function";
1021
+ }
1022
+ async function useNamedDatabase() {
1023
+ const { useDatabase } = await import("@vite-hub/database/runtime/registry");
1024
+ return useDatabase;
1025
+ }
1026
+ async function useBlobStore(name) {
1027
+ const { blob } = await import("@vite-hub/blob");
1028
+ return name === "default" ? blob : blob.store(name);
1029
+ }
1030
+ /** Blob stores bytes. The Database publishes immutable folder manifests and rejects a commit from a stale head. */
604
1031
  function createBlobDatabaseWorkspaceStore(options) {
605
1032
  return new ContentAddressedWorkspaceStore(options);
606
1033
  }
607
- //#endregion
608
1034
  export { createBlobDatabaseWorkspaceStore, workspaceHistorySchema };