@vite-hub/workspace 0.4.1 → 0.5.0

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 (95) hide show
  1. package/README.md +62 -19
  2. package/dist/blob-database/postgres.d.ts +424 -0
  3. package/dist/blob-database/postgres.js +2 -0
  4. package/dist/blob-database-sources-DDZ1wV9w.js +9 -0
  5. package/dist/blob-database.d.ts +33 -447
  6. package/dist/blob-database.js +637 -208
  7. package/dist/checkout.js +1 -1
  8. package/dist/cloudflare.d.ts +1 -1
  9. package/dist/cloudflare.js +1 -1
  10. package/dist/{config-D1QENneP.js → config-DiyPi3Ff.js} +7 -7
  11. package/dist/{config-CDeGd0RB.d.ts → config-hxABr_Gg.d.ts} +1 -1
  12. package/dist/durability.d.ts +11 -2
  13. package/dist/durability.js +46 -4
  14. package/dist/{error-diagnostics-CQ4BUqRe.js → error-diagnostics-C0KyI408.js} +5 -1
  15. package/dist/{error-diagnostics-B5s9kNEA.js → error-diagnostics-Cth97txN.js} +10 -2
  16. package/dist/{path-uxLkzrZm.d.ts → errors-DXCZjdUU.d.ts} +0 -1
  17. package/dist/{file-CqG9zqiF.js → file-C1DYoGz3.js} +1 -1
  18. package/dist/{target-Dm9dHAVJ.js → file-metadata-Dv2JZwal.js} +1 -29
  19. package/dist/{files-B6wpAhEx.js → files-iHyik8jj.js} +2 -2
  20. package/dist/files.d.ts +13 -5
  21. package/dist/files.js +6 -5
  22. package/dist/{github-DKAlO0Vh.js → github-CFHl6RI0.js} +4 -4
  23. package/dist/{glob-BOqSKzSg.js → glob-BitxqDhb.js} +7 -7
  24. package/dist/{glob-Cjxms1t7.js → glob-Buxfvmyy.js} +1 -1
  25. package/dist/history-schema-BBWbpDk4.d.ts +436 -0
  26. package/dist/history-schema-postgres-U_ueRvmO.js +41 -0
  27. package/dist/{host-Bf1a2uo_.js → host-Dmr2Ctem.js} +150 -16
  28. package/dist/{hosted-zG7HJaE4.js → hosted-BktlvkF2.js} +20 -11
  29. package/dist/{hosted-vercel-blob-AbXG8fvR.js → hosted-vercel-blob-D0IPAjb1.js} +5 -5
  30. package/dist/hosted-vercel-blob.d.ts +1 -1
  31. package/dist/hosted-vercel-blob.js +1 -1
  32. package/dist/hosted.d.ts +1 -1
  33. package/dist/hosted.js +1 -1
  34. package/dist/index.d.ts +11 -23
  35. package/dist/index.js +28 -106
  36. package/dist/internal/workspace.d.ts +14 -0
  37. package/dist/internal/workspace.js +86 -0
  38. package/dist/{lifecycle-D8FdpBod.js → lifecycle-D6WN2dd_.js} +11 -8
  39. package/dist/loader.d.ts +1 -1
  40. package/dist/loader.js +2 -2
  41. package/dist/{mcp-resources-DntxtmDU.js → mcp-resources-TtxLNSL6.js} +1 -1
  42. package/dist/{memory-D5jq9HZW.js → memory-DjzwSng2.js} +16 -8
  43. package/dist/{metadata-target-DDoOQNp1.js → metadata-target-CR0aDtvS.js} +205 -60
  44. package/dist/{operation-definition-nmRu_O3V.d.ts → operation-definition-CI2PJGqu.d.ts} +8 -2
  45. package/dist/{operations-D8uCpzhM.js → operations-Cib30_dt.js} +5 -5
  46. package/dist/{operations-DsY2MQnG.js → operations-dtcU5LkD.js} +22 -7
  47. package/dist/operations.d.ts +2 -2
  48. package/dist/operations.js +1 -1
  49. package/dist/{path--wrT_Azm.js → path-BlIBpI7U.js} +1 -16
  50. package/dist/{plugins-CsrXCA1Q.d.ts → plugins-DKCBrH31.d.ts} +1 -1
  51. package/dist/{provider-sm9uzkLg.js → provider-Fc3M6bEx.js} +23 -10
  52. package/dist/providers/github/store.d.ts +1 -1
  53. package/dist/providers/github/store.js +1 -1
  54. package/dist/{registry-CwryP59t.d.ts → registry-CLL0TY0L.d.ts} +5 -3
  55. package/dist/{registry-DmVfUe4K.js → registry-CedQvQxW.js} +8 -3
  56. package/dist/{registry-CFl1Htyc.d.ts → registry-DpB5PBA4.d.ts} +5 -4
  57. package/dist/{request-scope-Dw5n8bMC.js → request-scope-Bcv2kD8h.js} +2 -1
  58. package/dist/rule-keys-Bsz6jTTF.js +19 -0
  59. package/dist/rules-OHaPFopX.js +269 -0
  60. package/dist/runtime/assets.d.ts +1 -1
  61. package/dist/runtime/assets.js +3 -3
  62. package/dist/runtime/empty-assets-registry.d.ts +1 -1
  63. package/dist/runtime/empty-registry.d.ts +2 -2
  64. package/dist/runtime/registry.d.ts +2 -2
  65. package/dist/runtime/request.js +1 -1
  66. package/dist/runtime/state.d.ts +5 -4
  67. package/dist/runtime/state.js +18 -6
  68. package/dist/runtime/workspace.d.ts +1 -1
  69. package/dist/runtime/workspace.js +1 -1
  70. package/dist/runtime.d.ts +9 -8
  71. package/dist/runtime.js +23 -16
  72. package/dist/{search-C_RfoM2j.js → search-BqNV9LnO.js} +1 -1
  73. package/dist/{server-Cd4-iCh5.js → server-CFtrOPk6.js} +5 -5
  74. package/dist/server.d.ts +2 -2
  75. package/dist/server.js +1 -1
  76. package/dist/{shared-ovXVSV3-.js → shared-BgDjxY3J.js} +14 -3
  77. package/dist/source-metadata.d.ts +2 -2
  78. package/dist/source-metadata.js +3 -3
  79. package/dist/{state-C-YtsaiJ.d.ts → state-DBV6VHS6.d.ts} +13 -21
  80. package/dist/{store-NZoRto-Y.js → store-BRMdD8Ft.js} +37 -36
  81. package/dist/{sync-CrT8zjwc.js → sync-BezGVzrW.js} +4 -4
  82. package/dist/test.d.ts +1 -1
  83. package/dist/test.js +1 -1
  84. package/dist/{types-1Z-tKK3g.d.ts → types-9DMtFjaa.d.ts} +52 -4
  85. package/dist/{use-B0o5HoBl.js → use-Dm2tbI5F.js} +15 -15
  86. package/dist/{use-CjbF8EO9.d.ts → use-Dv973swc.d.ts} +20 -28
  87. package/dist/{state-Cb_hIyAw.js → use-tools-C1qvhzme.js} +4 -17
  88. package/dist/use-tools-CMUthOdy.d.ts +12 -0
  89. package/dist/{utils-Dw-WULEZ.js → utils-C0Au2R16.js} +77 -268
  90. package/dist/vite.d.ts +32 -3
  91. package/dist/vite.js +990 -1286
  92. package/dist/vitehub-grants-C8IAl5-M.js +38 -0
  93. package/dist/{workspace-DvKu5PRa.js → workspace-CFrwWhEm.js} +18 -17
  94. package/dist/{workspace-CIXgHeyX.d.ts → workspace-Cw4ycIW-.d.ts} +1 -1
  95. package/package.json +22 -12
@@ -1,9 +1,10 @@
1
1
  import { s as workspaceError, t as normalizeSafeWorkspacePath } from "./path-DrSIenjj.js";
2
- import { n as resolveWorkspaceStoreTarget, o as copyJsonFileMetadata, t as forwardWorkspaceStoreTarget } from "./target-Dm9dHAVJ.js";
3
- import { f as sha256, i as decodeFile, l as normalizeWorkspacePath, n as contentStreamToBytes, o as isWorkspaceBytes, t as contentStreamChunks } from "./path--wrT_Azm.js";
4
- import { t as workspaceErrorDiagnostics } from "./error-diagnostics-B5s9kNEA.js";
5
- import { t as searchText } from "./search-C_RfoM2j.js";
6
- import { a as normalizeWorkspaceSources, c as sourceMountIntersectsPath, f as prepareWorkspaceSource, n as createSourceContext, s as sourceMountContainsPath } from "./config-D1QENneP.js";
2
+ import { t as copyJsonFileMetadata } from "./file-metadata-Dv2JZwal.js";
3
+ import { d as sha256, i as decodeFile, l as normalizeWorkspacePath, n as contentStreamToBytes, o as isWorkspaceBytes, t as contentStreamChunks } from "./path-BlIBpI7U.js";
4
+ import { t as workspaceErrorDiagnostics } from "./error-diagnostics-Cth97txN.js";
5
+ import { i as forwardWorkspaceStoreTarget, o as resolveWorkspaceStoreTarget } from "./vitehub-grants-C8IAl5-M.js";
6
+ import { t as searchText } from "./search-BqNV9LnO.js";
7
+ import { a as normalizeWorkspaceSources, c as sourceMountIntersectsPath, f as prepareWorkspaceSource, n as createSourceContext, s as sourceMountContainsPath } from "./config-DiyPi3Ff.js";
7
8
  import { posix } from "node:path";
8
9
  import { createHash } from "node:crypto";
9
10
  //#region src/storage/identity.ts
@@ -143,6 +144,30 @@ async function removeWorkspaceOwnedFile(store, path) {
143
144
  await store.rm(path, { force: true });
144
145
  await removeWorkspaceFileOwner(store, path);
145
146
  }
147
+ async function writeWorkspaceOwnedFiles(store, files) {
148
+ const keys = files.map(({ file }) => fileOwnerMetaKey(file.path));
149
+ const written = /* @__PURE__ */ new Set();
150
+ try {
151
+ await store.writeFiles(files.map(({ file }) => file), Object.fromEntries(files.map(({ owner }, index) => [keys[index], owner])), (path) => {
152
+ written.add(path);
153
+ });
154
+ const owners = volatileOwners.get(workspaceStoreIdentity(store));
155
+ for (const key of keys) owners?.delete(key);
156
+ } catch (error) {
157
+ const failures = [];
158
+ for (const { file } of files) {
159
+ if (!written.has(file.path)) continue;
160
+ try {
161
+ await store.rm(file.path, { force: true });
162
+ await removeWorkspaceFileOwner(store, file.path);
163
+ } catch (rollbackError) {
164
+ failures.push(rollbackError);
165
+ }
166
+ }
167
+ if (failures.length) throw new AggregateError([error, ...failures], "Workspace batch write and rollback failed.");
168
+ throw error;
169
+ }
170
+ }
146
171
  async function withWorkspaceFileCheckpoint(store, path, write, checkpoint, rollbackCheckpoint) {
147
172
  const previous = (await store.stat(path))?.type === "file" ? await store.readFile(path) : void 0;
148
173
  const owner = await readWorkspaceFileOwner(store, path);
@@ -295,6 +320,10 @@ function createWorkspaceSourceMountAuthority(owner) {
295
320
  };
296
321
  if (store.writeFileConditional) scoped.writeFileConditional = async (path, file, ifDigest) => await store.writeFileConditional(assertInMount(path), file, ifDigest);
297
322
  if (store.writeFileStream) scoped.writeFileStream = async (path, file) => await store.writeFileStream(assertInMount(path), file);
323
+ if (store.writeFiles) scoped.writeFiles = async (files, meta, onWrite) => await store.writeFiles(files.map((file) => ({
324
+ ...file,
325
+ path: assertInMount(file.path)
326
+ })), meta, onWrite);
298
327
  if (store.removeEmptyDirectory) scoped.removeEmptyDirectory = async (path) => await store.removeEmptyDirectory(assertInMount(path, true));
299
328
  if (store.getMeta) scoped.getMeta = async (key) => await store.getMeta(key);
300
329
  if (store.setMeta) scoped.setMeta = async (key, value) => await store.setMeta(key, value);
@@ -362,14 +391,20 @@ async function invalidateSourceSnapshot(store, workspace, sourceKey) {
362
391
  status: "updating"
363
392
  });
364
393
  }
365
- async function hasCurrentSourceSnapshot(store, workspace, source, verifyOwnership = false, activeSources = [], path) {
394
+ function scopedSnapshotPaths(items, scope) {
395
+ const all = items || {};
396
+ if (scope === void 0) return Object.keys(all);
397
+ if (typeof scope === "string") return Object.hasOwn(all, scope) ? [scope] : [];
398
+ const prefix = scope.directory ? `${scope.directory}/` : "";
399
+ return Object.keys(all).filter((path) => path.startsWith(prefix));
400
+ }
401
+ async function hasCurrentSourceSnapshot(store, workspace, source, verifyOwnership = false, activeSources = [], scope) {
366
402
  const configHash = await sourceConfigHash(source, store);
367
403
  const meta = await readSourceSnapshotMetadata(store, workspace, source.key, source);
368
404
  if (meta?.status !== "ready" || meta.configHash !== configHash) return false;
369
405
  if (verifyOwnership === "workspace") {
370
406
  if (Object.keys(meta.items || {}).length === 0 && meta.ownsMount !== false && meta.mountPath && (await store.stat(meta.mountPath))?.type !== "directory") return false;
371
- const paths = path === void 0 ? Object.keys(meta.items || {}) : Object.hasOwn(meta.items || {}, path) ? [path] : [];
372
- for (const path of paths) {
407
+ for (const path of scopedSnapshotPaths(meta.items, scope)) {
373
408
  const file = await store.readFile(path);
374
409
  if (!file) return false;
375
410
  const inlineOwner = file.metadata?.workspaceSourceOwner;
@@ -380,13 +415,12 @@ async function hasCurrentSourceSnapshot(store, workspace, source, verifyOwnershi
380
415
  }
381
416
  return true;
382
417
  }
383
- return !verifyOwnership || await snapshotHasCurrentOwners(store, workspace, source, meta, activeSources, path);
418
+ return !verifyOwnership || await snapshotHasCurrentOwners(store, workspace, source, meta, activeSources, scope);
384
419
  }
385
- async function snapshotHasCurrentOwners(store, workspace, source, meta, activeSources = [], path) {
420
+ async function snapshotHasCurrentOwners(store, workspace, source, meta, activeSources = [], scope) {
386
421
  if (Object.keys(meta.items || {}).length === 0 && meta.mountPath && (await store.stat(meta.mountPath))?.type !== "directory") return false;
387
- const listed = path === void 0 && source.mountPath ? new Map((await store.list(source.mountPath, { recursive: true })).map((entry) => [entry.path, entry])) : void 0;
388
- const paths = path === void 0 ? Object.keys(meta.items || {}) : Object.hasOwn(meta.items || {}, path) ? [path] : [];
389
- for (const path of paths) {
422
+ const listed = typeof scope !== "string" && source.mountPath ? new Map((await store.list(source.mountPath, { recursive: true })).map((entry) => [entry.path, entry])) : void 0;
423
+ for (const path of scopedSnapshotPaths(meta.items, scope)) {
390
424
  const stat = listed?.get(path) ?? await store.stat(path);
391
425
  if (await materializedFileHasCurrentOwner(store, workspace, source.key, path, stat)) continue;
392
426
  const owner = await readWorkspaceFileOwner(store, path);
@@ -868,13 +902,6 @@ function isMaterializedStartupSource(value) {
868
902
  const source = value;
869
903
  return readStringMeta(source, "key") !== void 0 && readStringMeta(source, "mountPath") !== void 0;
870
904
  }
871
- async function* iterateSourceItems(source, ctx) {
872
- if (source.source.getItems) {
873
- yield* await source.source.getItems(ctx);
874
- return;
875
- }
876
- for (const key of await source.source.getKeys(ctx)) yield await source.source.getItem(key, ctx);
877
- }
878
905
  function createMaterializationEntry(source, item, upstreamMeta) {
879
906
  const { path, sourcePath } = normalizeSourceItemPath(source, item, { operation: "source materialization" });
880
907
  return {
@@ -903,9 +930,14 @@ async function* iterateMaterializationEntries(source, ctx, store, snapshot, conf
903
930
  return;
904
931
  }
905
932
  if (source.source.getItems) {
906
- for await (const item of iterateSourceItems(source, ctx)) {
933
+ const items = await source.source.getItems(ctx);
934
+ const batchable = !source.source.getMeta || items.every((item) => item.metadata != null);
935
+ for (const item of items) {
907
936
  const entry = createMaterializationEntry(source, item, item.metadata ?? await source.source.getMeta?.(item.key, ctx));
908
- if (materializationPathMatches(entry.path, options)) yield entry;
937
+ if (materializationPathMatches(entry.path, options)) yield {
938
+ ...entry,
939
+ batchable
940
+ };
909
941
  }
910
942
  return;
911
943
  }
@@ -1092,36 +1124,20 @@ async function materializeWorkspaceSourcesInternal(definition, store, options, c
1092
1124
  revision = ctx.revision;
1093
1125
  const directorySet = new Set(source.mountPath ? [source.mountPath] : []);
1094
1126
  const nextPaths = /* @__PURE__ */ new Set();
1095
- for await (const entry of iterateMaterializationEntries(source, ctx, store, existing, configHash, options, workspace)) {
1096
- throwIfAborted(options.abortSignal);
1127
+ const reportUpdate = async (force = false) => {
1128
+ if (!force && !shouldReportMaterializationUpdate(lastProgressAt, sourceFiles)) return;
1129
+ await reportMaterializationProgress(options, source, {
1130
+ bytes: sourceBytes,
1131
+ cacheStatus,
1132
+ counts: { ...counts },
1133
+ files: sourceFiles,
1134
+ revision,
1135
+ status: "updating"
1136
+ });
1137
+ lastProgressAt = Date.now();
1138
+ };
1139
+ const writeOne = async (entry, item) => {
1097
1140
  const path = entry.path;
1098
- nextPaths.add(path);
1099
- const parts = path.split("/");
1100
- for (let index = 1; index < parts.length; index++) directorySet.add(parts.slice(0, index).join("/"));
1101
- if (entry.reused) {
1102
- itemMetadata[path] = entry.metadata;
1103
- sourceFiles++;
1104
- const reusedFile = entry.reused.size === void 0 ? await store.readFile(path) : void 0;
1105
- sourceBytes += entry.reused.size ?? (reusedFile ? contentSize(reusedFile.content) : 0);
1106
- counts.unchanged++;
1107
- paths.push({
1108
- path,
1109
- status: "unchanged"
1110
- });
1111
- if (shouldReportMaterializationUpdate(lastProgressAt, sourceFiles)) {
1112
- await reportMaterializationProgress(options, source, {
1113
- bytes: sourceBytes,
1114
- cacheStatus,
1115
- counts: { ...counts },
1116
- files: sourceFiles,
1117
- revision,
1118
- status: "updating"
1119
- });
1120
- lastProgressAt = Date.now();
1121
- }
1122
- continue;
1123
- }
1124
- const item = entry.item;
1125
1141
  const metadata = normalizeSourceFileMetadata(item.metadata || {});
1126
1142
  const previousStat = await store.stat(path);
1127
1143
  const previous = entry.contentStream && store.writeFileStream ? void 0 : await store.readFile(path);
@@ -1179,18 +1195,147 @@ async function materializeWorkspaceSourcesInternal(definition, store, options, c
1179
1195
  path,
1180
1196
  status
1181
1197
  });
1182
- if (shouldReportMaterializationUpdate(lastProgressAt, sourceFiles)) {
1183
- await reportMaterializationProgress(options, source, {
1184
- bytes: sourceBytes,
1185
- cacheStatus,
1186
- counts: { ...counts },
1187
- files: sourceFiles,
1188
- revision,
1189
- status: "updating"
1198
+ await reportUpdate();
1199
+ };
1200
+ const batchWrites = source.materialize === "startup" && Boolean(sourceStore.writeFiles && store.getMeta && store.setMeta);
1201
+ let pending = [];
1202
+ let pendingBytes = 0;
1203
+ const pendingPaths = /* @__PURE__ */ new Set();
1204
+ const pendingDirectories = /* @__PURE__ */ new Set();
1205
+ const overlapsPending = (path) => pendingPaths.has(path) || pendingDirectories.has(path) || parentDirectoryPaths(path).some((directory) => pendingPaths.has(directory));
1206
+ const flush = async () => {
1207
+ if (!pending.length) return;
1208
+ const batch = pending;
1209
+ pending = [];
1210
+ pendingBytes = 0;
1211
+ pendingPaths.clear();
1212
+ pendingDirectories.clear();
1213
+ const replaced = [];
1214
+ const written = await control.mutate(() => withWorkspaceStoreMutation(store, async () => {
1215
+ const existingPaths = new Map((await store.list(source.mountPath, { recursive: true })).map((entry) => [entry.path, entry.type]));
1216
+ const verifiedPaths = /* @__PURE__ */ new Map();
1217
+ const pathType = async (path) => {
1218
+ const listed = existingPaths.get(path);
1219
+ if (listed) return listed;
1220
+ if (!verifiedPaths.has(path)) verifiedPaths.set(path, (await store.stat(path))?.type);
1221
+ return verifiedPaths.get(path);
1222
+ };
1223
+ const missingDirectories = /* @__PURE__ */ new Set();
1224
+ const fresh = [];
1225
+ for (const { entry, item } of batch) {
1226
+ const ancestors = parentDirectoryPaths(entry.path);
1227
+ let blocked = false;
1228
+ const absent = [];
1229
+ for (const directory of ancestors) {
1230
+ const type = await pathType(directory);
1231
+ if (type === "file") {
1232
+ blocked = true;
1233
+ break;
1234
+ }
1235
+ if (!type && directory !== source.mountPath && sourceOwnsDirectory(source, directory)) absent.push(directory);
1236
+ }
1237
+ if (blocked || await pathType(entry.path)) {
1238
+ replaced.push({
1239
+ entry,
1240
+ item
1241
+ });
1242
+ continue;
1243
+ }
1244
+ for (const directory of absent) missingDirectories.add(directory);
1245
+ const fileMetadata = normalizeSourceFileMetadata({
1246
+ ...normalizeSourceFileMetadata(item.metadata || {}),
1247
+ ...entry.metadata,
1248
+ source: source.key,
1249
+ workspaceSourceOwner: workspace
1250
+ });
1251
+ fresh.push({
1252
+ entry,
1253
+ item,
1254
+ fileMetadata,
1255
+ digest: await sha256(entry.content),
1256
+ size: contentSize(entry.content)
1257
+ });
1258
+ }
1259
+ throwIfAborted(options.abortSignal);
1260
+ if (fresh.length) await writeWorkspaceOwnedFiles(sourceStore, fresh.map(({ entry, item, fileMetadata, digest }) => ({
1261
+ file: {
1262
+ path: entry.path,
1263
+ content: entry.content,
1264
+ mediaType: item.mediaType,
1265
+ metadata: fileMetadata
1266
+ },
1267
+ owner: {
1268
+ workspace,
1269
+ source: source.key,
1270
+ digest
1271
+ }
1272
+ })));
1273
+ for (const directory of missingDirectories) ownedDirectories.add(directory);
1274
+ return fresh;
1275
+ }));
1276
+ const previousFileCount = sourceFiles;
1277
+ for (const { entry, item, fileMetadata, digest, size } of written) {
1278
+ const path = entry.path;
1279
+ const previousBytes = Object.hasOwn(itemMetadata, path) ? itemMetadata[path]?.materializedBytes ?? 0 : 0;
1280
+ itemMetadata[path] = {
1281
+ ...entry.metadata,
1282
+ materializedAttributes: true,
1283
+ materializedContentDigest: digest,
1284
+ materializedBytes: size,
1285
+ materializedMediaType: item.mediaType,
1286
+ materializedMetadata: observableFileMetadata(fileMetadata)
1287
+ };
1288
+ sourceFiles++;
1289
+ sourceBytes += size;
1290
+ persistedBytesDelta += size - previousBytes;
1291
+ counts.added++;
1292
+ paths.push({
1293
+ path,
1294
+ status: "added"
1295
+ });
1296
+ }
1297
+ if (written.length) await reportUpdate(previousFileCount === 0 || Math.floor(previousFileCount / 25) < Math.floor(sourceFiles / 25));
1298
+ for (const { entry, item } of replaced) await writeOne(entry, item);
1299
+ };
1300
+ for await (const entry of iterateMaterializationEntries(source, ctx, store, existing, configHash, options, workspace)) {
1301
+ throwIfAborted(options.abortSignal);
1302
+ const path = entry.path;
1303
+ nextPaths.add(path);
1304
+ const parts = path.split("/");
1305
+ for (let index = 1; index < parts.length; index++) directorySet.add(parts.slice(0, index).join("/"));
1306
+ if (entry.reused) {
1307
+ itemMetadata[path] = entry.metadata;
1308
+ sourceFiles++;
1309
+ const reusedFile = entry.reused.size === void 0 ? await store.readFile(path) : void 0;
1310
+ sourceBytes += entry.reused.size ?? (reusedFile ? contentSize(reusedFile.content) : 0);
1311
+ counts.unchanged++;
1312
+ paths.push({
1313
+ path,
1314
+ status: "unchanged"
1190
1315
  });
1191
- lastProgressAt = Date.now();
1316
+ await reportUpdate();
1317
+ continue;
1318
+ }
1319
+ const item = entry.item;
1320
+ if (overlapsPending(path)) await flush();
1321
+ if (batchWrites && entry.batchable && entry.content !== void 0 && !entry.contentStream) {
1322
+ pending.push({
1323
+ entry: {
1324
+ ...entry,
1325
+ content: entry.content
1326
+ },
1327
+ item
1328
+ });
1329
+ pendingPaths.add(path);
1330
+ for (const directory of parentDirectoryPaths(path)) pendingDirectories.add(directory);
1331
+ pendingBytes += contentSize(entry.content);
1332
+ if (pending.length >= 512 || pendingBytes >= 33554432) await flush();
1333
+ continue;
1192
1334
  }
1335
+ await flush();
1336
+ await writeOne(entry, item);
1193
1337
  }
1338
+ await flush();
1194
1339
  throwIfAborted(options.abortSignal);
1195
1340
  const removedDirectories = await removeStaleMaterializedSourceFiles(store, grant, workspace, source, configuredSources, nextPaths, options, control, existing, ownedDirectories, async (path, owned) => {
1196
1341
  const previouslyOwned = ownedDirectories.has(path);
@@ -104,6 +104,11 @@ interface OperationAccess {
104
104
  */
105
105
  readonly sections: "all" | readonly string[];
106
106
  readonly user?: OperationUser;
107
+ /**
108
+ * Who signed the call: `"console"` when the ViteHub Console signed it for a person, whose `user` is then a Console
109
+ * account and not an app user, or `"cli"` for a key. Not set for other calls.
110
+ */
111
+ readonly via?: "console" | "cli";
107
112
  }
108
113
  interface OperationContext {
109
114
  /** The checked Console access of the call. */
@@ -166,7 +171,8 @@ interface OperationDefinition<Input, Output> {
166
171
  /** Standard Schema (valibot in this repo). Its Standard JSON Schema builds CLI flags and the MCP input schema. */
167
172
  input: StandardSchemaV1<unknown, Input>;
168
173
  output?: StandardSchemaV1<unknown, Output>;
169
- cli?: {
174
+ /** `false`: no `vitehub` command. The Console and MCP still call the operation. */
175
+ cli?: false | {
170
176
  /** Defaults: namespace = section, command = verb. */
171
177
  namespace?: string;
172
178
  /** A space groups commands: `jobs list` and `jobs show` run as `vitehub <namespace> jobs list` and `jobs show`. */
@@ -207,7 +213,7 @@ interface OperationDefinition<Input, Output> {
207
213
  /** An operation of any input and output, as a registry holds it. */
208
214
  interface AnyOperation extends Omit<OperationDefinition<unknown, unknown>, "cli" | "input" | "mcp" | "output" | "readOnlyWhen" | "run" | "scope" | "section"> {
209
215
  readOnlyWhen?: (input: never) => boolean;
210
- cli?: {
216
+ cli?: false | {
211
217
  namespace?: string;
212
218
  command?: string;
213
219
  default?: boolean;
@@ -1,10 +1,10 @@
1
1
  import { a as workspaceConflict } from "./path-DrSIenjj.js";
2
- import { r as contentToBytes } from "./path--wrT_Azm.js";
3
- import { t as workspaceErrorDiagnostics } from "./error-diagnostics-B5s9kNEA.js";
4
- import { u as normalizeHistoryPath } from "./utils-Dw-WULEZ.js";
2
+ import { r as contentToBytes } from "./path-BlIBpI7U.js";
3
+ import { t as workspaceErrorDiagnostics } from "./error-diagnostics-Cth97txN.js";
4
+ import { d as normalizeHistoryPath } from "./utils-C0Au2R16.js";
5
5
  import { readDerivedFrom, staleDerivedFiles } from "./lineage.js";
6
- import { r as useWorkspaceFiles } from "./use-B0o5HoBl.js";
7
- import { _ as redactInspectionText } from "./operations-DsY2MQnG.js";
6
+ import { r as useWorkspaceFiles } from "./use-Dm2tbI5F.js";
7
+ import { _ as redactInspectionText } from "./operations-dtcU5LkD.js";
8
8
  //#region src/runtime/operations.ts
9
9
  const invalidRequestCodes = /* @__PURE__ */ new Set([
10
10
  "WORKSPACE_HISTORY_INVALID",
@@ -1,6 +1,6 @@
1
1
  import { t as workspaceCommitRequestBytes } from "./results-DgkZUmTL.js";
2
2
  import { n as isRecordOrFunction, t as isRecord } from "./object-Da1zyPCR.js";
3
- import { t as internalErrorDiagnostics } from "./error-diagnostics-CQ4BUqRe.js";
3
+ import { t as internalErrorDiagnostics } from "./error-diagnostics-C0KyI408.js";
4
4
  import { basename, dirname, join, parse, resolve } from "node:path";
5
5
  import { mkdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
6
6
  import "node:fs/promises";
@@ -408,14 +408,17 @@ function isServerEnvironment(name, config) {
408
408
  * Use one app's effective Nitro runner for both environment configuration and generated imports.
409
409
  * `configureEnvironment` reads the runner after Nitro's `build:before` hooks and saves the decision for `load`.
410
410
  */
411
- function createNativePackageLoading() {
411
+ function createNativePackageLoading(ssrPackageEntries = []) {
412
412
  let nitro;
413
413
  let native = false;
414
+ let nativeSsr = false;
415
+ const ssrDistDirs = ssrPackageEntries.map((entry) => dirname(fileURLToPath(entry)).replace(/\\/g, "/") + "/");
414
416
  return {
415
417
  nitro: { setup(instance) {
416
418
  nitro = instance;
417
419
  } },
418
- configureEnvironment(name, env) {
420
+ configureEnvironment(name, env, options) {
421
+ if (name === "ssr") nativeSsr = env.command === "serve" && !env.isSsrTargetWebworker && !options?.resolve?.conditions?.some((condition) => condition === "worker" || condition === "workerd" || condition === "browser" || condition === "edge-light" || condition === "deno");
419
422
  if (name !== "nitro") return false;
420
423
  const runner = nitro?.options.devServer?.runner || process.env.NITRO_DEV_RUNNER || "node-worker";
421
424
  native = env.command === "serve" && (runner === "node-worker" || runner === "node-process");
@@ -423,6 +426,11 @@ function createNativePackageLoading() {
423
426
  },
424
427
  load(id, environmentName) {
425
428
  if (environmentName === "nitro" && native) return loadNativePackageModule(id);
429
+ if (environmentName === "ssr" && nativeSsr && ssrDistDirs.length) {
430
+ const file = id.startsWith("file:") ? fileURLToPath(id) : id;
431
+ const path = file.replace(/\\/g, "/");
432
+ if (/^vitehub-grants(?:-[\w-]+)?\.js$/.test(basename(path)) && ssrDistDirs.some((dir) => dirname(path) + "/" === dir)) return reexportNativeModule(file);
433
+ }
426
434
  }
427
435
  };
428
436
  }
@@ -436,6 +444,9 @@ const nativePackageDistFile = /\/node_modules\/@vite-hub\/(?:agent|connections|r
436
444
  function loadNativePackageModule(id) {
437
445
  const file = id.startsWith("file:") ? fileURLToPath(id) : id;
438
446
  if (!nativePackageDistFile.test(file.replace(/\\/g, "/"))) return;
447
+ return reexportNativeModule(file);
448
+ }
449
+ function reexportNativeModule(file) {
439
450
  const url = JSON.stringify(pathToFileURL(realpathSync(file)).href);
440
451
  const hasDefault = /\bexport default\b|\bas default\b/.test(readFileSync(file, "utf8"));
441
452
  const native = JSON.stringify(`data:text/javascript,${encodeURIComponent(`export * from ${url}${hasDefault ? `\nexport { default } from ${url}` : ""}`)}`);
@@ -483,7 +494,7 @@ function hasProjectRootDirectoryMarker(root) {
483
494
  for (const marker of projectRootDirectoryMarkers) try {
484
495
  if (statSync(resolve(root, ...marker)).isDirectory()) return true;
485
496
  } catch (error) {
486
- if (error.code !== "ENOENT") throw error;
497
+ if (!isMissingProjectMarker(error)) throw error;
487
498
  }
488
499
  return false;
489
500
  }
@@ -497,11 +508,15 @@ function hasProjectRootFileMarker(root, markers) {
497
508
  try {
498
509
  if (statSync(resolve(root, ...path)).isFile()) return true;
499
510
  } catch (error) {
500
- if (error.code !== "ENOENT") throw error;
511
+ if (!isMissingProjectMarker(error)) throw error;
501
512
  }
502
513
  }
503
514
  return false;
504
515
  }
516
+ function isMissingProjectMarker(error) {
517
+ const code = error.code;
518
+ return code === "ENOENT" || code === "ENOTDIR";
519
+ }
505
520
  function viteHubEnvPublicModulePath(root) {
506
521
  return resolve(root, ".vitehub", "env", "public.mjs");
507
522
  }
@@ -1075,7 +1090,7 @@ function table(rows) {
1075
1090
  }
1076
1091
  //#endregion
1077
1092
  //#region src/operations.ts
1078
- const runtime = () => import("./operations-D8uCpzhM.js");
1093
+ const runtime = () => import("./operations-Cib30_dt.js");
1079
1094
  const name = v.pipe(v.string(), v.check((value) => value.trim() !== "", "Name a Workspace."));
1080
1095
  const nonEmpty = (message) => v.pipe(v.string(), v.check((value) => value !== "", message));
1081
1096
  function defineWorkspaceOperation(definition, kind = "read") {
@@ -1194,7 +1209,7 @@ const refs = defineWorkspaceOperation({
1194
1209
  });
1195
1210
  const show = defineWorkspaceOperation({
1196
1211
  cli: {
1197
- command: "show",
1212
+ command: "get",
1198
1213
  format: formatShow,
1199
1214
  namespace: "workspace",
1200
1215
  positional: [
@@ -1,6 +1,6 @@
1
- import { Mt as WorkspaceRevision } from "./types-1Z-tKK3g.js";
1
+ import { It as WorkspaceRevision } from "./types-9DMtFjaa.js";
2
2
  import { WorkspaceStaleFile } from "./lineage.js";
3
- import { t as AnyOperation } from "./operation-definition-nmRu_O3V.js";
3
+ import { t as AnyOperation } from "./operation-definition-CI2PJGqu.js";
4
4
  //#region src/results.d.ts
5
5
  /**
6
6
  * The largest `workspace.commit` request body: 4 MiB of JSON, with base64 for binary files. Vercel Functions accept
@@ -1,3 +1,3 @@
1
1
  import { t as workspaceCommitRequestBytes } from "./results-DgkZUmTL.js";
2
- import { t as workspaceOperations } from "./operations-DsY2MQnG.js";
2
+ import { t as workspaceOperations } from "./operations-dtcU5LkD.js";
3
3
  export { workspaceCommitRequestBytes, workspaceOperations };
@@ -1,23 +1,8 @@
1
- import { n as __exportAll } from "./rolldown-runtime-rQ84J-ij.js";
2
1
  import { l as workspacePathError, t as normalizeSafeWorkspacePath } from "./path-DrSIenjj.js";
3
2
  import { isAbsolute, relative, resolve, sep } from "node:path";
4
3
  import { createHash } from "node:crypto";
5
4
  import { minimatch } from "minimatch";
6
5
  //#region src/core/path.ts
7
- var path_exports = /* @__PURE__ */ __exportAll({
8
- contentStreamChunks: () => contentStreamChunks,
9
- contentStreamToBytes: () => contentStreamToBytes,
10
- contentToBytes: () => contentToBytes,
11
- decodeFile: () => decodeFile,
12
- isExcludedWorkspacePath: () => isExcludedWorkspacePath,
13
- isWorkspaceBytes: () => isWorkspaceBytes,
14
- matchesAny: () => matchesAny,
15
- normalizeSafeWorkspacePath: () => normalizeSafeWorkspacePath,
16
- normalizeSafeWorkspacePattern: () => normalizeSafeWorkspacePattern,
17
- normalizeWorkspacePath: () => normalizeWorkspacePath,
18
- resolveInside: () => resolveInside,
19
- sha256: () => sha256
20
- });
21
6
  function normalizeWorkspacePath(path = "") {
22
7
  return path.replace(/\\/g, "/").replace(/^\/+/, "").replace(/\/+$/, "");
23
8
  }
@@ -110,4 +95,4 @@ async function sha256(input) {
110
95
  return createHash("sha256").update(bytes).digest("hex");
111
96
  }
112
97
  //#endregion
113
- export { isExcludedWorkspacePath as a, normalizeSafeWorkspacePattern as c, resolveInside as d, sha256 as f, decodeFile as i, normalizeWorkspacePath as l, contentStreamToBytes as n, isWorkspaceBytes as o, contentToBytes as r, matchesAny as s, contentStreamChunks as t, path_exports as u };
98
+ export { isExcludedWorkspacePath as a, normalizeSafeWorkspacePattern as c, sha256 as d, decodeFile as i, normalizeWorkspacePath as l, contentStreamToBytes as n, isWorkspaceBytes as o, contentToBytes as r, matchesAny as s, contentStreamChunks as t, resolveInside as u };
@@ -1,4 +1,4 @@
1
- import { Dt as WorkspacePlugin } from "./types-1Z-tKK3g.js";
1
+ import { jt as WorkspacePlugin } from "./types-9DMtFjaa.js";
2
2
  //#region src/core/plugins.d.ts
3
3
  /**
4
4
  * Add a plugin's rules and hooks to a Workspace by name, including discovered Workspaces the caller does not define.
@@ -1,11 +1,12 @@
1
- import { r as vitehubOwnedPrefix, t as createMemoryWorkspaceStore } from "./memory-D5jq9HZW.js";
1
+ import { r as vitehubOwnedPrefix, t as createMemoryWorkspaceStore } from "./memory-DjzwSng2.js";
2
2
  import { n as assertWorkspaceDigest, o as workspaceConflictError, s as workspaceError } from "./path-DrSIenjj.js";
3
- import { o as copyJsonFileMetadata, r as workspaceStoreTarget } from "./target-Dm9dHAVJ.js";
4
- import { a as isExcludedWorkspacePath, d as resolveInside, f as sha256, l as normalizeWorkspacePath, r as contentToBytes, t as contentStreamChunks } from "./path--wrT_Azm.js";
5
- import { t as workspaceErrorDiagnostics } from "./error-diagnostics-B5s9kNEA.js";
6
- import { t as createWorkspaceGlobMatcher } from "./glob-Cjxms1t7.js";
7
- import { M as readForgeEnv, j as forgeEnv, t as assertNoGitHubRepositoryKey } from "./shared-ovXVSV3-.js";
8
- import { t as createGitHubWorkspaceStore } from "./store-NZoRto-Y.js";
3
+ import { t as copyJsonFileMetadata } from "./file-metadata-Dv2JZwal.js";
4
+ import { a as isExcludedWorkspacePath, d as sha256, l as normalizeWorkspacePath, r as contentToBytes, t as contentStreamChunks, u as resolveInside } from "./path-BlIBpI7U.js";
5
+ import { t as workspaceErrorDiagnostics } from "./error-diagnostics-Cth97txN.js";
6
+ import { t as createWorkspaceGlobMatcher } from "./glob-Buxfvmyy.js";
7
+ import { a as provideWorkspaceStoreTarget } from "./vitehub-grants-C8IAl5-M.js";
8
+ import { M as readForgeEnv, j as forgeEnv, t as assertNoGitHubRepositoryKey } from "./shared-BgDjxY3J.js";
9
+ import { t as createGitHubWorkspaceStore } from "./store-BRMdD8Ft.js";
9
10
  import { t as getWorkspaceRuntimeConfig } from "./config-B-863EgC.js";
10
11
  import { dirname, join, relative, resolve, sep } from "node:path";
11
12
  import { createHash, randomUUID } from "node:crypto";
@@ -686,7 +687,7 @@ async function fileDigest(path) {
686
687
  }
687
688
  var LocalWorkspaceStore = class {
688
689
  root;
689
- [workspaceStoreTarget]() {
690
+ #storeTarget() {
690
691
  return {
691
692
  provider: "local",
692
693
  containsPath: async (ancestor, path) => {
@@ -720,6 +721,7 @@ var LocalWorkspaceStore = class {
720
721
  this.#processLocks = options.locks === "process";
721
722
  this.#fileMetadataRoot = `${root}/.vitehub/file-metadata`;
722
723
  this.#metaPath = `${root}.meta.json`;
724
+ provideWorkspaceStoreTarget(this, () => this.#storeTarget());
723
725
  }
724
726
  async #pathLock(root, path, operation, readOnly = false) {
725
727
  return this.#processLocks ? await withProcessPathLock(root, path, operation, readOnly) : await withWorkspacePathLock(root, path, operation, readOnly);
@@ -911,7 +913,7 @@ var LocalWorkspaceStore = class {
911
913
  await this.#writeFile(normalized, file);
912
914
  });
913
915
  }
914
- async #writeFile(path, file) {
916
+ async #writeFile(path, file, createOnly = false) {
915
917
  file = {
916
918
  ...file,
917
919
  metadata: assertFileMetadata(path, file.metadata)
@@ -927,6 +929,7 @@ var LocalWorkspaceStore = class {
927
929
  const bytes = contentToBytes(file.content);
928
930
  const digest = await sha256(bytes);
929
931
  const existing = await this.#stat(normalized);
932
+ if (createOnly && existing) throw workspaceError(`[vitehub] Cannot create a Workspace file over an existing path: ${normalized}.`);
930
933
  if (existing?.type === "directory") throw workspaceError(`[vitehub] Cannot write a file over directory: ${normalized}.`);
931
934
  if (existing?.type === "file" && existing.digest === digest) {
932
935
  await this.#writeFileMetadata(normalized, {
@@ -1243,12 +1246,22 @@ var LocalWorkspaceStore = class {
1243
1246
  return structuredClone((await this.#readMeta()).get(key));
1244
1247
  }
1245
1248
  async setMeta(key, value) {
1249
+ await this.#setMetaEntries({ [key]: value });
1250
+ }
1251
+ async #setMetaEntries(entries) {
1246
1252
  await this.#pathLock(this.root, ".vitehub/metadata", async () => {
1247
1253
  const metadata = new Map(await this.#readMeta());
1248
- metadata.set(key, value);
1254
+ for (const [key, value] of Object.entries(entries)) metadata.set(key, value);
1249
1255
  await this.#writeMeta(metadata);
1250
1256
  });
1251
1257
  }
1258
+ async writeFiles(files, meta, onWrite) {
1259
+ for (const file of files) {
1260
+ await this.#pathLock(this.root, file.path, () => this.#writeFile(file.path, file, true));
1261
+ onWrite?.(file.path);
1262
+ }
1263
+ if (meta && Object.keys(meta).length) await this.#setMetaEntries(meta);
1264
+ }
1252
1265
  async #createSnapshot(name) {
1253
1266
  const entries = Object.create(null);
1254
1267
  for (const entry of await this.#list("", { recursive: true }, true)) entries[entry.path] = {
@@ -1,4 +1,4 @@
1
- import { Sn as WorkspaceStore, s as GitHubWorkspaceStoreOptions } from "../../types-1Z-tKK3g.js";
1
+ import { En as WorkspaceStore, s as GitHubWorkspaceStoreOptions } from "../../types-9DMtFjaa.js";
2
2
  //#region src/providers/github/store.d.ts
3
3
  export declare function createGitHubWorkspaceStore(options: GitHubWorkspaceStoreOptions, workspaceName: string): WorkspaceStore;
4
4
  //#endregion
@@ -1,2 +1,2 @@
1
- import { t as createGitHubWorkspaceStore } from "../../store-NZoRto-Y.js";
1
+ import { t as createGitHubWorkspaceStore } from "../../store-BRMdD8Ft.js";
2
2
  export { createGitHubWorkspaceStore };
@@ -1,9 +1,11 @@
1
- import { I as WorkspaceDefinition, L as WorkspaceDefinitionInput } from "./types-1Z-tKK3g.js";
2
- import "./registry-CFl1Htyc.js";
1
+ import { L as WorkspaceDefinition, R as WorkspaceDefinitionInput, w as ValidatedWorkspaceName } from "./types-9DMtFjaa.js";
2
+ import "./registry-DpB5PBA4.js";
3
3
  //#region src/core/registry.d.ts
4
4
  declare function registerWorkspace(name: string, definition: WorkspaceDefinitionInput): WorkspaceDefinition;
5
5
  /** Replace one generated catalog's definitions without replacing application registrations. */
6
6
  declare function setWorkspaceRuntimeDefinitions(scope: string, definitions: Record<string, WorkspaceDefinitionInput>): void;
7
+ /** Whether a Workspace Definition has this name. Use it to check a name that comes from a request or a database. */
8
+ declare function isWorkspaceName(name: string): name is ValidatedWorkspaceName;
7
9
  declare function resolveRegisteredWorkspaceDefinition(name: string, abortSignal?: AbortSignal): Promise<WorkspaceDefinition>;
8
10
  //#endregion
9
- export { resolveRegisteredWorkspaceDefinition as n, setWorkspaceRuntimeDefinitions as r, registerWorkspace as t };
11
+ export { setWorkspaceRuntimeDefinitions as i, registerWorkspace as n, resolveRegisteredWorkspaceDefinition as r, isWorkspaceName as t };