@foleo/cli 0.1.36 → 0.1.45

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.
package/dist/index.js CHANGED
@@ -1,14 +1,18 @@
1
1
  #!/usr/bin/env node
2
+ import { workspaceCommand, WORKSPACE_HELP } from "./workspaces.js";
2
3
  import { spawn } from "node:child_process";
3
4
  import { createHash, randomUUID } from "node:crypto";
4
5
  import { constants } from "node:fs";
5
- import { lstat as defaultLstat, readFile, realpath, stat as defaultStat, } from "node:fs/promises";
6
+ import { mkdir, mkdtemp, rm, writeFile, lstat as defaultLstat, readFile, realpath, stat as defaultStat, } from "node:fs/promises";
6
7
  import { open } from "node:fs/promises";
7
8
  import { lstat, readdir } from "node:fs/promises";
9
+ import { tmpdir } from "node:os";
8
10
  import { createServer } from "node:http";
9
11
  import { dirname, join, relative, resolve, sep } from "node:path";
10
12
  import { fileURLToPath, pathToFileURL } from "node:url";
11
13
  import { FoleoError, LocalError, renderFailure, toFoleoError, UsageError, } from "./errors.js";
14
+ import { auditImages } from "./images.js";
15
+ import { optimizeImages, } from "./image-encoder.js";
12
16
  import { deriveArtifactName, resolveHtmlTitle, resolveVisibility, } from "./plan.js";
13
17
  const KEYCHAIN_SERVICE = "com.contraverse.foleo.cli";
14
18
  /**
@@ -33,6 +37,7 @@ const CLI_KEY_SCOPES = [
33
37
  "html:unpublish",
34
38
  ];
35
39
  const HTML_BUNDLE_MAX_FILES = 1_000;
40
+ const HTML_BUNDLE_MAX_NEW_FILES = 300;
36
41
  const HTML_BUNDLE_MAX_HTML_FILES = 100;
37
42
  const HTML_BUNDLE_MAX_BYTES = 100 * 1024 * 1024;
38
43
  const HTML_BUNDLE_MAX_FILE_BYTES = 8 * 1024 * 1024;
@@ -102,6 +107,87 @@ const LIVE_DOC_ASSET_MEDIA_TYPES = {
102
107
  ".webp": "image/webp",
103
108
  ".avif": "image/avif",
104
109
  };
110
+ const uploadRuns = new WeakMap();
111
+ const jsonOutputs = new WeakMap();
112
+ /** Cleanup cannot turn an already observed failure into cancellation. */
113
+ async function cancelUploadSessions(deps, sessions) {
114
+ const cleanup = new AbortController();
115
+ let timer;
116
+ try {
117
+ await Promise.race([
118
+ new Promise((resolve) => {
119
+ timer = setTimeout(resolve, 2800);
120
+ }),
121
+ (async () => {
122
+ const credential = await resolveCredentialWithSource(deps);
123
+ if (!credential)
124
+ return;
125
+ await Promise.allSettled([...sessions].map((id) => deps.fetch(`${apiBase(deps)}/uploads/${encodeURIComponent(id)}/cancel`, {
126
+ method: "POST",
127
+ headers: { authorization: `Bearer ${credential.token}` },
128
+ signal: cleanup.signal,
129
+ })));
130
+ })(),
131
+ ]);
132
+ }
133
+ catch {
134
+ // Expiry remains the fallback when cancellation is unavailable.
135
+ }
136
+ finally {
137
+ clearTimeout(timer);
138
+ cleanup.abort();
139
+ }
140
+ }
141
+ function uploadRun(deps) {
142
+ const existing = uploadRuns.get(deps);
143
+ if (existing)
144
+ return existing;
145
+ const controller = new AbortController();
146
+ const sessions = new Set();
147
+ let stopping = false;
148
+ const handler = (signal) => {
149
+ if (stopping || run.failed)
150
+ return;
151
+ stopping = true;
152
+ if (!run.submitted) {
153
+ const rendered = renderFailure(new LocalError("cancelled", "Upload cancelled; nothing was published.", { retryable: true }), jsonOutputs.get(deps) ?? false);
154
+ if (rendered.stdout !== null)
155
+ deps.stdout(rendered.stdout);
156
+ if (rendered.stderr !== null)
157
+ deps.stderr(rendered.stderr);
158
+ run.reported = true;
159
+ }
160
+ controller.abort();
161
+ void cancelUploadSessions(deps, sessions).finally(() => {
162
+ (deps.exit ?? process.exit)(signal === "SIGINT" ? 130 : 143);
163
+ });
164
+ };
165
+ const onInt = () => handler("SIGINT");
166
+ const onTerm = () => handler("SIGTERM");
167
+ const remove = deps.onUploadSignal
168
+ ? deps.onUploadSignal(handler)
169
+ : (() => {
170
+ process.on("SIGINT", onInt);
171
+ process.on("SIGTERM", onTerm);
172
+ return () => {
173
+ process.off("SIGINT", onInt);
174
+ process.off("SIGTERM", onTerm);
175
+ };
176
+ })();
177
+ const run = {
178
+ reported: false,
179
+ submitted: false,
180
+ failed: false,
181
+ sessions,
182
+ controller,
183
+ dispose: () => {
184
+ remove();
185
+ uploadRuns.delete(deps);
186
+ },
187
+ };
188
+ uploadRuns.set(deps, run);
189
+ return run;
190
+ }
105
191
  export async function runCli(argv, deps = {
106
192
  fetch,
107
193
  readFile,
@@ -110,17 +196,26 @@ export async function runCli(argv, deps = {
110
196
  stderr: (message) => process.stderr.write(message),
111
197
  }) {
112
198
  const wantsJson = argv.includes("--json");
199
+ let activeDeps = deps;
113
200
  try {
114
201
  const global = parseGlobalFlags(argv);
115
202
  const commandDeps = global.environment
116
203
  ? { ...deps, env: { ...deps.env, FOLEO_ENV: global.environment } }
117
204
  : deps;
205
+ activeDeps = commandDeps;
206
+ jsonOutputs.set(commandDeps, wantsJson);
118
207
  const [command, ...rest] = global.argv;
208
+ if (rest.includes("--optimize-images") &&
209
+ !["publish", "update"].includes(command ?? "")) {
210
+ throw new UsageError("--optimize-images applies to an HTML bundle folder", "image_optimization_not_applicable");
211
+ }
119
212
  if (command === undefined ||
120
213
  command === "help" ||
121
214
  command === "--help" ||
122
- command === "-h") {
123
- commandDeps.stdout(help());
215
+ command === "-h" ||
216
+ (command === "settings" &&
217
+ (rest.includes("--help") || rest.includes("-h")))) {
218
+ commandDeps.stdout(help() + "\n" + WORKSPACE_HELP);
124
219
  return 0;
125
220
  }
126
221
  if (command === "--version" || command === "-v" || command === "version") {
@@ -148,6 +243,35 @@ export async function runCli(argv, deps = {
148
243
  operation: describeArgvToken(command),
149
244
  });
150
245
  }
246
+ if (command === "workspace" ||
247
+ command === "capabilities" ||
248
+ command === "approval") {
249
+ return await workspaceCommand(command === "capabilities"
250
+ ? ["capabilities", ...rest]
251
+ : command === "approval"
252
+ ? ["approval", ...rest]
253
+ : rest, {
254
+ stdout: commandDeps.stdout,
255
+ readStdin: () => readStdinText(commandDeps),
256
+ request: async (path, init) => {
257
+ const credential = await resolveCredentialWithSource(commandDeps);
258
+ if (!credential)
259
+ throw new LocalError("credential_missing", "No Foleo credential found.", { next: "Sign in or set FOLEO_TOKEN." });
260
+ const response = await commandDeps.fetch(`${apiBase(commandDeps)}${path}`, init
261
+ ? {
262
+ ...init,
263
+ headers: {
264
+ ...Object.fromEntries(new Headers(init.headers)),
265
+ authorization: `Bearer ${credential.token}`,
266
+ },
267
+ }
268
+ : { headers: { authorization: `Bearer ${credential.token}` } });
269
+ if (!response.ok)
270
+ throw apiResponseError(response.status, await response.json());
271
+ return response;
272
+ },
273
+ });
274
+ }
151
275
  if (command === "publish")
152
276
  return await publish(rest, commandDeps);
153
277
  if (command === "update")
@@ -170,6 +294,8 @@ export async function runCli(argv, deps = {
170
294
  return await status(rest, commandDeps);
171
295
  if (command === "get")
172
296
  return await status(rest, commandDeps);
297
+ if (command === "export")
298
+ return await exportArtifact(rest, commandDeps);
173
299
  if (command === "html-publish") {
174
300
  warnDeprecatedAlias(commandDeps, "html-publish", "publish <path> --accept-hosting-risk");
175
301
  return await htmlPublish(rest, commandDeps);
@@ -224,6 +350,15 @@ export async function runCli(argv, deps = {
224
350
  return 2;
225
351
  }
226
352
  catch (error) {
353
+ const run = uploadRuns.get(activeDeps);
354
+ if (run?.reported)
355
+ return 1;
356
+ if (run) {
357
+ // Capture the cause before any asynchronous cleanup or later signal.
358
+ run.failed = true;
359
+ if (!run.submitted && run.sessions.size)
360
+ await cancelUploadSessions(activeDeps, run.sessions);
361
+ }
227
362
  const rendered = renderFailure(normalizeThrown(error), wantsJson);
228
363
  if (rendered.stdout !== null)
229
364
  deps.stdout(rendered.stdout);
@@ -231,6 +366,10 @@ export async function runCli(argv, deps = {
231
366
  deps.stderr(rendered.stderr);
232
367
  return rendered.exitCode;
233
368
  }
369
+ finally {
370
+ uploadRuns.get(activeDeps)?.dispose();
371
+ jsonOutputs.delete(activeDeps);
372
+ }
234
373
  }
235
374
  /**
236
375
  * Usage-shaped failures exit 2 even when they were thrown as a plain `Error`.
@@ -612,8 +751,23 @@ function stringArray(value) {
612
751
  async function login(args, deps) {
613
752
  const parsed = parseFlags(args, { allowLoginScopeFlags: true });
614
753
  if (parsed.positionals.length > 0)
615
- throw new Error("Usage: foleo login [--allow-purge] [--json]");
754
+ throw new Error("Usage: foleo login [--allow-purge] [--allow-workspaces] [--allow-workspace-sharing] [--json]");
616
755
  const base = apiBase(deps);
756
+ const workspaceScopes = [
757
+ ...(parsed.allowWorkspaces || parsed.allowWorkspaceSharing
758
+ ? ["workspaces:read"]
759
+ : []),
760
+ ...(parsed.allowWorkspaces ? ["workspaces:write"] : []),
761
+ ...(parsed.allowWorkspaceSharing ? ["workspaces:share"] : []),
762
+ ];
763
+ const target = new URL(base);
764
+ if (workspaceScopes.length &&
765
+ !(target.origin === "https://api-staging.foleo.app" ||
766
+ (target.protocol === "http:" &&
767
+ ["localhost", "127.0.0.1", "[::1]"].includes(target.hostname))))
768
+ throw new LocalError("workspace_login_unavailable", "Workspace login flags are available only on staging/local. Production workspace access is disabled.", {
769
+ next: "Use FOLEO_ENV=staging foleo login --allow-workspaces (add --allow-workspace-sharing for sharing).",
770
+ });
617
771
  announceApi(deps, parsed.json);
618
772
  const verifyStore = deps.verifyCredentialStore ?? verifyKeychainWritable;
619
773
  const saveCredential = deps.saveCredential ?? saveKeychainCredential;
@@ -631,7 +785,12 @@ async function login(args, deps) {
631
785
  let loginResult = null;
632
786
  let operationError = null;
633
787
  try {
634
- const start = await requestPublicJson(deps, "/desktop/handoff/start", { nonce, callbackUrl: callback.callbackUrl, clientKind: "cli" });
788
+ const start = await requestPublicJson(deps, "/desktop/handoff/start", {
789
+ nonce,
790
+ callbackUrl: callback.callbackUrl,
791
+ clientKind: "cli",
792
+ ...(workspaceScopes.length ? { workspaceScopes } : {}),
793
+ });
635
794
  deps.stderr("Opening Foleo sign-in in your browser...\n");
636
795
  try {
637
796
  await openUrl(start.authorizeUrl);
@@ -656,6 +815,7 @@ async function login(args, deps) {
656
815
  scopes: [
657
816
  ...CLI_KEY_SCOPES,
658
817
  ...(parsed.allowPurge ? ["artifacts:purge"] : []),
818
+ ...workspaceScopes.filter((scope) => exchanged.approvedWorkspaceScopes?.includes(scope)),
659
819
  ],
660
820
  deferredActivation: true,
661
821
  },
@@ -885,7 +1045,8 @@ function refuseUnavailableName(label, availability, next) {
885
1045
  /** The largest bundle files by size, so a dry run can flag a heavy upload before it starts. */
886
1046
  const DRY_RUN_LARGEST_FILES_SHOWN = 5;
887
1047
  async function htmlPublishDryRun(root, name, parsed, deps) {
888
- const { files, skipped, routes } = await scanBundle(root, deps);
1048
+ const { files, skipped, routes, warnings, imageOptimization } = await prepareImageBundle(root, deps, parsed);
1049
+ assertFirstPublishFileBudget(files.length);
889
1050
  const htmlFiles = files.filter((file) => file.mediaType === "text/html; charset=utf-8");
890
1051
  const entryFile = files.find((file) => file.path === "/index.html");
891
1052
  const entryHtml = entryFile
@@ -968,6 +1129,8 @@ async function htmlPublishDryRun(root, name, parsed, deps) {
968
1129
  const previewUrl = artifactPreviewUrl(derived, deps);
969
1130
  const plan = {
970
1131
  ok: true,
1132
+ warnings,
1133
+ ...(imageOptimization ? { imageOptimization } : {}),
971
1134
  plan: {
972
1135
  action: "create",
973
1136
  scope: cost === null ? "bundle-only" : "full",
@@ -1017,6 +1180,7 @@ async function htmlPublishDryRun(root, name, parsed, deps) {
1017
1180
  totalBytes: files.reduce((n, file) => n + file.byteSize, 0),
1018
1181
  entry: "/index.html",
1019
1182
  routes,
1183
+ files: files.map(({ bytes: _bytes, ...file }) => file),
1020
1184
  notFoundPage: files.some((file) => file.path === "/404.html")
1021
1185
  ? "/404.html"
1022
1186
  : null,
@@ -1099,6 +1263,8 @@ function htmlWireOptions(parsed) {
1099
1263
  ? {}
1100
1264
  : { runtimeProfile: parsed.runtimeProfile }),
1101
1265
  acknowledgeAccessWidening: parsed.acknowledgeAccessWidening,
1266
+ optimizeImages: parsed.optimizeImages,
1267
+ json: parsed.json,
1102
1268
  };
1103
1269
  }
1104
1270
  async function htmlUpdate(args, deps) {
@@ -1191,7 +1357,7 @@ async function settingsCommand(args, deps) {
1191
1357
  }
1192
1358
  announceApi(deps, parsed.json);
1193
1359
  if (Object.keys(patch).length === 0) {
1194
- writeResult(deps, await requestJson(deps, `/artifacts/${encodeURIComponent(id)}/settings`, {
1360
+ writeSettingsResult(deps, await requestJson(deps, `/artifacts/${encodeURIComponent(id)}/settings`, {
1195
1361
  method: "GET",
1196
1362
  body: undefined,
1197
1363
  }), parsed.json);
@@ -1201,7 +1367,7 @@ async function settingsCommand(args, deps) {
1201
1367
  if (revision === null) {
1202
1368
  throw new Error("Usage: foleo settings <id> --set k=v ... --revision <etag> [--acknowledge-access-widening] [--json]");
1203
1369
  }
1204
- writeResult(deps, await requestJson(deps, `/artifacts/${encodeURIComponent(id)}/settings`, {
1370
+ writeSettingsResult(deps, await requestJson(deps, `/artifacts/${encodeURIComponent(id)}/settings`, {
1205
1371
  method: "PATCH",
1206
1372
  body: {
1207
1373
  settings: patch,
@@ -1332,6 +1498,125 @@ async function htmlUnpublish(args, deps) {
1332
1498
  writeResult(deps, result, parsed.json);
1333
1499
  return 0;
1334
1500
  }
1501
+ function withImageReport(result, warnings, imageOptimization) {
1502
+ const record = result !== null && typeof result === "object"
1503
+ ? result
1504
+ : {};
1505
+ return {
1506
+ ...record,
1507
+ ...(warnings.length
1508
+ ? {
1509
+ warnings: [
1510
+ ...(Array.isArray(record.warnings) ? record.warnings : []),
1511
+ ...warnings,
1512
+ ],
1513
+ }
1514
+ : {}),
1515
+ ...(imageOptimization ? { imageOptimization } : {}),
1516
+ };
1517
+ }
1518
+ function reportHeavyImages(deps, warnings, html, json = false) {
1519
+ if (json || !warnings.length)
1520
+ return;
1521
+ for (const w of warnings.slice(0, 10))
1522
+ deps.stderr(`Heavy image: ${w.path} (${w.bytes} bytes${w.width ? `, ${w.width} × ${w.height}` : ""})\n`);
1523
+ if (warnings.length > 10)
1524
+ deps.stderr(`(+${warnings.length - 10} more)\n`);
1525
+ const mb = (warnings.reduce((n, w) => n + w.bytes, 0) / 1_000_000).toFixed(2);
1526
+ deps.stderr(`${warnings.length} images are heavy (${mb} MB). ${html ? "For HTML, --optimize-images makes smaller AVIF copies for readers; your folder is not changed." : "Resize images before publishing to reduce what readers download."}\n`);
1527
+ }
1528
+ export async function prepareImageBundle(root, deps, options = {}) {
1529
+ const scanned = await scanBundle(root, deps);
1530
+ const localDigest = htmlLocalDigest(scanned.files);
1531
+ let files = scanned.files;
1532
+ let imageOptimization;
1533
+ const encoderWarnings = [];
1534
+ let optimized;
1535
+ if (options.optimizeImages !== false) {
1536
+ try {
1537
+ optimized = await optimizeImages(files, deps.imageProcessRunner);
1538
+ }
1539
+ catch (error) {
1540
+ if (options.optimizeImages === true ||
1541
+ !(error instanceof LocalError) ||
1542
+ error.code !== "image_encoder_unavailable")
1543
+ throw error;
1544
+ encoderWarnings.push({
1545
+ code: "image_encoder_unavailable",
1546
+ message: error.message,
1547
+ });
1548
+ if (!options.json)
1549
+ deps.stderr(`image_encoder_unavailable: ${error.message} Publishing without image optimization.\n`);
1550
+ }
1551
+ }
1552
+ if (optimized) {
1553
+ imageOptimization = optimized.imageOptimization;
1554
+ const scannedByPath = new Map(scanned.files.map((file) => [file.path, file]));
1555
+ files = optimized.files.map((file) => {
1556
+ const original = scannedByPath.get(file.path);
1557
+ if (original?.bytes === file.bytes)
1558
+ return original;
1559
+ return {
1560
+ path: file.path,
1561
+ bytes: file.bytes,
1562
+ byteSize: file.bytes.byteLength,
1563
+ sha256: createHash("sha256").update(file.bytes).digest("hex"),
1564
+ mediaType: mediaTypeFor(file.path),
1565
+ };
1566
+ });
1567
+ const total = files.reduce((n, f) => n + f.byteSize, 0);
1568
+ const extra = ` --optimize-images added ${imageOptimization.addedFiles} files / ${imageOptimization.addedBytes} bytes: ${imageOptimization.images.flatMap((i) => i.variants.map((v) => v.path)).join(", ")}`;
1569
+ const fail = (code, message) => {
1570
+ throw new LocalError(code, message + extra);
1571
+ };
1572
+ if (files.length > HTML_BUNDLE_MAX_FILES)
1573
+ fail("bundle_too_many_files", "Bundle exceeds the file-count limit.");
1574
+ if (total > HTML_BUNDLE_MAX_BYTES)
1575
+ fail("bundle_total_too_large", "Bundle exceeds the total size limit.");
1576
+ for (const f of files) {
1577
+ if (f.byteSize > HTML_BUNDLE_MAX_FILE_BYTES)
1578
+ fail("bundle_file_too_large", `Bundle file exceeds the per-file limit: ${f.path}`);
1579
+ if (f.mediaType === "text/html; charset=utf-8" &&
1580
+ f.byteSize > HTML_BUNDLE_MAX_HTML_BYTES)
1581
+ fail("bundle_html_too_large", `HTML file exceeds the size limit: ${f.path}`);
1582
+ if (Buffer.byteLength(f.path) > HTML_BUNDLE_MAX_PATH_BYTES ||
1583
+ f.path
1584
+ .split("/")
1585
+ .some((p) => Buffer.byteLength(p) > HTML_BUNDLE_MAX_PATH_SEGMENT_BYTES))
1586
+ fail("bundle_path_invalid", `Invalid bundle path: ${f.path}`);
1587
+ }
1588
+ if (!options.json) {
1589
+ const r = imageOptimization;
1590
+ const before = r.images.reduce((n, i) => n + i.bytes, 0);
1591
+ const after = r.images.reduce((n, i) => n +
1592
+ (i.variants.find((v) => v.width >= 1280) ?? i.variants.at(-1)).bytes, 0);
1593
+ if (r.images.length)
1594
+ deps.stderr(`Optimized ${r.images.length} images (${r.images.reduce((n, i) => n + i.tags, 0)} tags on ${optimized.pages} pages): readers download about ${(after / 1_000_000).toFixed(2)} MB instead of ${(before / 1_000_000).toFixed(2)} MB at 1280 px. Added ${r.addedFiles} files / ${r.addedBytes} bytes.\n`);
1595
+ for (const skip of r.skipped.slice(0, 10))
1596
+ deps.stderr(`image_optimize_skipped: ${skip.path} (${skip.reason})\n`);
1597
+ if (r.skipped.length > 10)
1598
+ deps.stderr(`(+${r.skipped.length - 10} more)\n`);
1599
+ }
1600
+ }
1601
+ const warnings = auditImages(files, new Set(imageOptimization?.images.map((i) => i.path)));
1602
+ reportHeavyImages(deps, warnings, true, options.json);
1603
+ return {
1604
+ ...scanned,
1605
+ localDigest,
1606
+ files,
1607
+ warnings: [...encoderWarnings, ...warnings],
1608
+ ...(imageOptimization ? { imageOptimization } : {}),
1609
+ };
1610
+ }
1611
+ function assertFirstPublishFileBudget(count) {
1612
+ if (count > HTML_BUNDLE_MAX_NEW_FILES) {
1613
+ const message = `This bundle has ${count} new files; the limit is ${HTML_BUNDLE_MAX_NEW_FILES} per first publish. Reduce the bundle before publishing. Updates may contain 1,000 total files when the server can reuse enough files.`;
1614
+ throw new LocalError("bundle_new_files_limit", message, {
1615
+ context: { limit: HTML_BUNDLE_MAX_NEW_FILES, count: count },
1616
+ next: "Reduce the bundle. For updates, keep files unchanged so the server can reuse them.",
1617
+ });
1618
+ }
1619
+ }
1335
1620
  async function publishBundle(root, deps, update, hostingRiskAcknowledged = false, publishSeparately = false, settings, wire = {}) {
1336
1621
  // Top-level fields every HTML create/update body carries (spec 103): the
1337
1622
  // runtime profile only when the caller chose one, and the widening
@@ -1342,7 +1627,7 @@ async function publishBundle(root, deps, update, hostingRiskAcknowledged = false
1342
1627
  : { runtimeProfile: wire.runtimeProfile }),
1343
1628
  ...accessWideningField(wire.acknowledgeAccessWidening === true),
1344
1629
  };
1345
- const { files, skipped } = await scanBundle(root, deps);
1630
+ const { files, skipped, warnings, imageOptimization, localDigest } = await prepareImageBundle(root, deps, wire);
1346
1631
  if (skipped.length > 0) {
1347
1632
  // Spec 089 §K.3 / L914: a dropped `.well-known/` must never be silent on
1348
1633
  // a real run either, not only in a `--dry-run` plan. stderr, unconditionally
@@ -1354,7 +1639,10 @@ async function publishBundle(root, deps, update, hostingRiskAcknowledged = false
1354
1639
  const rest = skipped.length > 10 ? ` (+${skipped.length - 10} more)` : "";
1355
1640
  deps.stderr(`Skipped ${skipped.length} bundle ${skipped.length === 1 ? "entry" : "entries"} not uploaded: ${shown}${rest}\n`);
1356
1641
  }
1642
+ if (!update)
1643
+ assertFirstPublishFileBudget(files.length);
1357
1644
  const manifest = files.map(({ bytes: _bytes, ...file }) => file);
1645
+ const filesByPath = new Map(files.map((file) => [file.path, file]));
1358
1646
  // One pacer for every /v1/ call in this publish: the zone rate-limit fence
1359
1647
  // counts the session create and complete calls against the same budget as the
1360
1648
  // file PUTs, so pacing only the PUTs overspends it.
@@ -1363,101 +1651,129 @@ async function publishBundle(root, deps, update, hostingRiskAcknowledged = false
1363
1651
  // retry is another request against the same fence, so pacing only the first
1364
1652
  // attempt spends the budget it was meant to protect.
1365
1653
  const budget = createRetryBudget();
1366
- const uploadKey = randomUUID();
1367
- const upload = await withRateLimitRetry(deps, "starting the upload", async () => {
1368
- await pace();
1369
- return requestJson(deps, "/uploads", {
1370
- method: "POST",
1371
- body: {
1372
- kind: "html-artifact-bundle",
1373
- manifest,
1374
- declaredBytes: manifest.reduce((n, file) => n + file.byteSize, 0),
1375
- },
1376
- headers: { "idempotency-key": uploadKey },
1377
- });
1378
- }, budget);
1379
- let uploaded = 0;
1380
- for (const plan of upload.files) {
1381
- const file = files.find((candidate) => candidate.path === plan.path);
1382
- if (!file)
1383
- throw new LocalError("upload_manifest_mismatch", "Server returned an unexpected upload file", { context: { path: plan.path } });
1384
- await withRateLimitRetry(deps, `uploading ${plan.path}`, async (attemptIndex) => {
1385
- await pace();
1386
- return requestRaw(deps, `/uploads/${upload.uploadId}/files/${plan.fileToken}`, file.bytes, { "content-length": String(file.byteSize) }, attemptIndex > 0);
1387
- }, budget);
1388
- uploaded += 1;
1389
- // A large bundle is paced to well under a minute's worth of requests, so a
1390
- // silent multi-minute publish reads as a hang. Progress goes to stderr so
1391
- // `--json` stdout stays machine-parseable.
1392
- if (upload.files.length > 20 && uploaded % 20 === 0) {
1393
- deps.stderr(`Uploaded ${uploaded}/${upload.files.length} files.\n`);
1394
- }
1395
- }
1396
- const completeKey = randomUUID();
1397
- await withRateLimitRetry(deps, "finishing the upload", async () => {
1398
- await pace();
1399
- return requestJson(deps, `/uploads/${upload.uploadId}/complete`, {
1400
- method: "POST",
1401
- body: {},
1402
- headers: { "idempotency-key": completeKey },
1403
- });
1404
- }, budget);
1405
- if (update)
1406
- await pace();
1407
- const sourceId = update
1408
- ? await ownerArtifactSourceId(deps, update.id)
1409
- : undefined;
1410
- const source = publishSourcePayload(upload.manifestHash, sourceId);
1411
- // The whole bundle is already uploaded by the time we get here, so losing this
1412
- // one request to a throttle discards the entire publish — the exact failure
1413
- // spec 089 exists to close. The key is minted ONCE outside the retry closure,
1414
- // so a retry reuses it and cannot double-create.
1415
- const createKey = randomUUID();
1416
- return withRateLimitRetry(deps, "creating the artifact", async () => {
1417
- await pace();
1418
- if (update?.family === "compatibility") {
1419
- return requestJson(deps, `/artifacts/html/${encodeURIComponent(update.id)}`, {
1420
- method: "PUT",
1421
- body: {
1422
- uploadId: upload.uploadId,
1423
- manifestHash: upload.manifestHash,
1424
- source,
1425
- ...wireFields,
1426
- },
1427
- headers: {
1428
- "if-match": `"r${update.revision}"`,
1429
- "idempotency-key": createKey,
1430
- },
1431
- });
1654
+ for (let attempt = 0; attempt < 2; attempt++) {
1655
+ const reuseFrom = update && attempt === 0 ? update.id : undefined;
1656
+ try {
1657
+ const uploadKey = randomUUID();
1658
+ const upload = await withRateLimitRetry(deps, "starting the upload", async () => {
1659
+ await pace();
1660
+ return requestJson(deps, "/uploads", {
1661
+ method: "POST",
1662
+ body: {
1663
+ kind: "html-artifact-bundle",
1664
+ ...(reuseFrom ? { reuseFrom } : {}),
1665
+ manifest,
1666
+ declaredBytes: manifest.reduce((n, file) => n + file.byteSize, 0),
1667
+ },
1668
+ headers: { "idempotency-key": uploadKey },
1669
+ });
1670
+ }, budget);
1671
+ let uploaded = 0;
1672
+ let bytesUploaded = 0;
1673
+ for (const plan of upload.files) {
1674
+ const file = filesByPath.get(plan.path);
1675
+ if (!file)
1676
+ throw new LocalError("upload_manifest_mismatch", "Server returned an unexpected upload file", { context: { path: plan.path } });
1677
+ await withRateLimitRetry(deps, `uploading ${plan.path}`, async (attemptIndex) => {
1678
+ await pace();
1679
+ return requestRaw(deps, `/uploads/${upload.uploadId}/files/${plan.fileToken}`, file.bytes, { "content-length": String(file.byteSize) }, attemptIndex > 0);
1680
+ }, budget);
1681
+ uploaded += 1;
1682
+ bytesUploaded += file.byteSize;
1683
+ // A large bundle is paced to well under a minute's worth of requests, so a
1684
+ // silent multi-minute publish reads as a hang. Progress goes to stderr so
1685
+ // `--json` stdout stays machine-parseable.
1686
+ if (upload.files.length > 20 && uploaded % 20 === 0) {
1687
+ deps.stderr(`Uploaded ${uploaded}/${upload.files.length} files.\n`);
1688
+ }
1689
+ }
1690
+ const completeKey = randomUUID();
1691
+ await withRateLimitRetry(deps, "finishing the upload", async () => {
1692
+ await pace();
1693
+ return requestJson(deps, `/uploads/${upload.uploadId}/complete`, {
1694
+ method: "POST",
1695
+ body: {},
1696
+ headers: { "idempotency-key": completeKey },
1697
+ });
1698
+ }, budget);
1699
+ if (update)
1700
+ await pace();
1701
+ const sourceId = update
1702
+ ? await ownerArtifactSourceId(deps, update.id)
1703
+ : undefined;
1704
+ const source = {
1705
+ ...publishSourcePayload(upload.manifestHash, sourceId),
1706
+ localDigest,
1707
+ };
1708
+ // The whole bundle is already uploaded by the time we get here, so losing this
1709
+ // one request to a throttle discards the entire publish — the exact failure
1710
+ // spec 089 exists to close. The key is minted ONCE outside the retry closure,
1711
+ // so a retry reuses it and cannot double-create.
1712
+ const createKey = randomUUID();
1713
+ const result = await withRateLimitRetry(deps, "creating the artifact", async () => {
1714
+ await pace();
1715
+ if (update?.family === "compatibility") {
1716
+ return requestJson(deps, `/artifacts/html/${encodeURIComponent(update.id)}`, {
1717
+ method: "PUT",
1718
+ body: {
1719
+ uploadId: upload.uploadId,
1720
+ manifestHash: upload.manifestHash,
1721
+ source,
1722
+ ...wireFields,
1723
+ },
1724
+ headers: {
1725
+ "if-match": `"r${update.revision}"`,
1726
+ "idempotency-key": createKey,
1727
+ },
1728
+ });
1729
+ }
1730
+ if (update?.family === "generic") {
1731
+ return requestJson(deps, `/artifacts/${encodeURIComponent(update.id)}`, {
1732
+ method: "PUT",
1733
+ body: {
1734
+ sourceFormat: "html",
1735
+ uploadId: upload.uploadId,
1736
+ manifestHash: upload.manifestHash,
1737
+ source,
1738
+ ...wireFields,
1739
+ },
1740
+ headers: artifactMutationHeaders(update.etag, createKey),
1741
+ });
1742
+ }
1743
+ return requestJson(deps, "/artifacts", {
1744
+ method: "POST",
1745
+ body: {
1746
+ sourceFormat: "html",
1747
+ uploadId: upload.uploadId,
1748
+ manifestHash: upload.manifestHash,
1749
+ hostingRiskAcknowledged,
1750
+ source,
1751
+ ...(publishSeparately ? { allowDuplicate: true } : {}),
1752
+ ...(settings && Object.keys(settings).length > 0
1753
+ ? { settings }
1754
+ : {}),
1755
+ ...wireFields,
1756
+ },
1757
+ headers: { "idempotency-key": createKey },
1758
+ });
1759
+ }, budget);
1760
+ const reused = upload.reused?.length ?? 0;
1761
+ if (!wire.json)
1762
+ deps.stderr(`Uploaded ${uploaded} of ${files.length} files (${reused} unchanged, reused).\nBytes uploaded: ${bytesUploaded}.\n`);
1763
+ return withImageReport({
1764
+ ...result,
1765
+ upload: { uploaded, reused, bytesUploaded },
1766
+ }, warnings, imageOptimization);
1432
1767
  }
1433
- if (update?.family === "generic") {
1434
- return requestJson(deps, `/artifacts/${encodeURIComponent(update.id)}`, {
1435
- method: "PUT",
1436
- body: {
1437
- sourceFormat: "html",
1438
- uploadId: upload.uploadId,
1439
- manifestHash: upload.manifestHash,
1440
- source,
1441
- ...wireFields,
1442
- },
1443
- headers: artifactMutationHeaders(update.etag, createKey),
1444
- });
1768
+ catch (error) {
1769
+ if (!reuseFrom ||
1770
+ !(error instanceof FoleoError) ||
1771
+ error.code !== "reuse_source_missing")
1772
+ throw error;
1773
+ deps.stderr("Reuse source missing; retrying once with a full upload.\n");
1445
1774
  }
1446
- return requestJson(deps, "/artifacts", {
1447
- method: "POST",
1448
- body: {
1449
- sourceFormat: "html",
1450
- uploadId: upload.uploadId,
1451
- manifestHash: upload.manifestHash,
1452
- hostingRiskAcknowledged,
1453
- source,
1454
- ...(publishSeparately ? { allowDuplicate: true } : {}),
1455
- ...(settings && Object.keys(settings).length > 0 ? { settings } : {}),
1456
- ...wireFields,
1457
- },
1458
- headers: { "idempotency-key": createKey },
1459
- });
1460
- }, budget);
1775
+ }
1776
+ throw new LocalError("reuse_source_missing", "Full upload retry exhausted.");
1461
1777
  }
1462
1778
  function revisionHeaders(revision) {
1463
1779
  return { "if-match": `"r${revision}"`, "idempotency-key": randomUUID() };
@@ -1966,8 +2282,10 @@ async function publish(args, deps) {
1966
2282
  const parsed = parseFlags(args);
1967
2283
  const file = parsed.positionals[0];
1968
2284
  if (!file || parsed.positionals.length !== 1)
1969
- throw new Error("Usage: foleo publish <path> [--title <title>] [--settings <json>] [--password-stdin] [--publish-separately] [--accept-hosting-risk] [--name <label>] [--runtime-profile auto|open|contained] [--acknowledge-access-widening] [--dry-run] [--json]\nAn HTML site bundle also requires --name <label>; Markdown does not.");
2285
+ throw new Error("Usage: foleo publish <path> [--title <title>] [--settings <json>] [--password-stdin] [--publish-separately] [--accept-hosting-risk] [--name <label>] [--runtime-profile auto|open|contained] [--optimize-images | --no-optimize-images] [--acknowledge-access-widening] [--dry-run] [--json]\nAn HTML site bundle also requires --name <label>; Markdown does not.");
1970
2286
  const isDirectory = await pathIsDirectory(file, deps);
2287
+ if (parsed.optimizeImages && !isDirectory)
2288
+ throw new UsageError("--optimize-images applies to an HTML bundle folder", "image_optimization_not_applicable");
1971
2289
  if (!isDirectory && parsed.dryRun) {
1972
2290
  throw new UsageError("--dry-run is only implemented for HTML site bundles (a directory with --accept-hosting-risk). A Markdown publish is not previewable yet; run it without --dry-run, or use `foleo publish <dir> --accept-hosting-risk --name <label> --dry-run`.", "dry_run_unsupported", { sourceFormat: "markdown" });
1973
2291
  }
@@ -1984,7 +2302,7 @@ async function publish(args, deps) {
1984
2302
  throw runtimeProfileNotApplicable({ sourceFormat: "markdown" });
1985
2303
  }
1986
2304
  const markdown = await deps.readFile(file, "utf8");
1987
- const assets = await uploadMarkdownAssets(file, markdown, deps);
2305
+ const assets = await uploadMarkdownAssets(file, markdown, deps, parsed.json);
1988
2306
  const result = await requestJson(deps, "/artifacts", {
1989
2307
  method: "POST",
1990
2308
  body: {
@@ -2001,32 +2319,61 @@ async function publish(args, deps) {
2001
2319
  : {}),
2002
2320
  ...accessWideningField(parsed.acknowledgeAccessWidening),
2003
2321
  },
2322
+ headers: { "idempotency-key": randomUUID() },
2004
2323
  });
2005
- writeResult(deps, result, parsed.json);
2324
+ writeResult(deps, withImageReport(result, assets?.warnings ?? []), parsed.json);
2006
2325
  return 0;
2007
2326
  }
2008
2327
  async function update(args, deps) {
2009
2328
  resolveUploadRate(deps);
2010
2329
  const parsed = parseFlags(args);
2011
- // Asking for a plan must never mutate. Until an update plan exists, refuse
2012
- // the flag rather than silently performing the real update.
2013
- if (parsed.dryRun) {
2014
- throw new UsageError("--dry-run is not implemented for update. Run the update without it.", "dry_run_unsupported", { operation: "update" });
2015
- }
2016
2330
  const [id, file] = parsed.positionals;
2017
2331
  if (!id || !file || parsed.positionals.length !== 2) {
2018
- throw new Error("Usage: foleo update <id> <path> --revision <etag> [--runtime-profile auto|open|contained] [--acknowledge-access-widening] [--json] (or Markdown compatibility --version <version>)");
2332
+ throw new Error("Usage: foleo update <id> <path> --revision <etag> [--runtime-profile auto|open|contained] [--optimize-images | --no-optimize-images] [--acknowledge-access-widening] [--dry-run] [--json] (or Markdown compatibility --version <version>)");
2019
2333
  }
2020
2334
  const isDirectory = await pathIsDirectory(file, deps);
2335
+ if (parsed.optimizeImages && !isDirectory)
2336
+ throw new UsageError("--optimize-images applies to an HTML bundle folder", "image_optimization_not_applicable");
2021
2337
  if (isDirectory) {
2338
+ if (parsed.dryRun) {
2339
+ const bundle = await prepareImageBundle(file, deps, parsed);
2340
+ const plan = {
2341
+ ok: true,
2342
+ plan: {
2343
+ action: "update",
2344
+ id,
2345
+ scope: "bundle-only",
2346
+ executable: false,
2347
+ note: "Revision, access widening and safety review are checked by the server on apply.",
2348
+ bundle: {
2349
+ fileCount: bundle.files.length,
2350
+ totalBytes: bundle.files.reduce((n, f) => n + f.byteSize, 0),
2351
+ files: bundle.files.map(({ bytes: _bytes, ...f }) => f),
2352
+ routes: bundle.routes,
2353
+ skipped: bundle.skipped,
2354
+ },
2355
+ },
2356
+ warnings: bundle.warnings,
2357
+ ...(bundle.imageOptimization
2358
+ ? { imageOptimization: bundle.imageOptimization }
2359
+ : {}),
2360
+ };
2361
+ if (parsed.json)
2362
+ deps.stdout(`${JSON.stringify(plan, null, 2)}\n`);
2363
+ else
2364
+ deps.stdout(`plan: update ${id} (bundle-only; server checks pending)\nfiles: ${bundle.files.length}\n`);
2365
+ return 0;
2366
+ }
2022
2367
  const revision = artifactRevision(parsed.revision);
2023
2368
  if (revision === null) {
2024
- throw new Error("Usage: foleo update <id> <bundle-root> --revision <etag> [--runtime-profile auto|open|contained] [--acknowledge-access-widening] [--json]");
2369
+ throw new Error("Usage: foleo update <id> <bundle-root> --revision <etag> [--runtime-profile auto|open|contained] [--optimize-images | --no-optimize-images] [--acknowledge-access-widening] [--dry-run] [--json]");
2025
2370
  }
2026
2371
  const result = await publishBundle(file, deps, { family: "generic", id, etag: revision }, false, false, undefined, htmlWireOptions(parsed));
2027
2372
  writeResult(deps, result, parsed.json);
2028
2373
  return 0;
2029
2374
  }
2375
+ if (parsed.dryRun)
2376
+ throw new UsageError("--dry-run is only implemented for HTML bundle folders", "dry_run_unsupported", { operation: "update" });
2030
2377
  if (!file.toLowerCase().endsWith(".md")) {
2031
2378
  throw new Error("Unsupported update input. Use a .md file or an HTML site directory.");
2032
2379
  }
@@ -2041,36 +2388,66 @@ async function update(args, deps) {
2041
2388
  throw new UsageError("--revision requires an opaque Artifact ETag", "revision_invalid");
2042
2389
  }
2043
2390
  const markdown = await deps.readFile(file, "utf8");
2044
- const assets = await uploadMarkdownAssets(file, markdown, deps);
2045
2391
  const sourceId = await ownerArtifactSourceId(deps, id);
2046
2392
  const source = publishSourcePayload(sha256Utf8(markdown), sourceId);
2047
- const result = opaqueRevision !== null
2048
- ? await requestJson(deps, `/artifacts/${encodeURIComponent(id)}`, {
2049
- method: "PUT",
2050
- body: {
2051
- sourceFormat: "markdown",
2052
- markdown,
2053
- source,
2054
- ...(assets
2055
- ? { uploadId: assets.uploadId, manifestHash: assets.manifestHash }
2056
- : {}),
2057
- ...accessWideningField(parsed.acknowledgeAccessWidening),
2058
- },
2059
- headers: artifactMutationHeaders(opaqueRevision, randomUUID()),
2060
- })
2061
- : await requestJson(deps, `/docs/${encodeURIComponent(id)}`, {
2062
- method: "PUT",
2063
- body: {
2064
- markdown,
2065
- version: parsed.version,
2066
- source,
2067
- ...(assets
2068
- ? { uploadId: assets.uploadId, manifestHash: assets.manifestHash }
2069
- : {}),
2070
- ...accessWideningField(parsed.acknowledgeAccessWidening),
2071
- },
2072
- });
2073
- writeResult(deps, result, parsed.json);
2393
+ let assets = null;
2394
+ let result;
2395
+ for (let attempt = 0; attempt < 2; attempt++) {
2396
+ const reuseFrom = attempt === 0 ? id : undefined;
2397
+ try {
2398
+ assets = await uploadMarkdownAssets(file, markdown, deps, parsed.json, reuseFrom, id);
2399
+ result =
2400
+ opaqueRevision !== null
2401
+ ? await requestJson(deps, `/artifacts/${encodeURIComponent(id)}`, {
2402
+ method: "PUT",
2403
+ body: {
2404
+ sourceFormat: "markdown",
2405
+ markdown,
2406
+ source,
2407
+ ...(assets
2408
+ ? {
2409
+ uploadId: assets.uploadId,
2410
+ manifestHash: assets.manifestHash,
2411
+ }
2412
+ : {}),
2413
+ ...accessWideningField(parsed.acknowledgeAccessWidening),
2414
+ },
2415
+ headers: artifactMutationHeaders(opaqueRevision, randomUUID()),
2416
+ })
2417
+ : await requestJson(deps, `/docs/${encodeURIComponent(id)}`, {
2418
+ method: "PUT",
2419
+ body: {
2420
+ markdown,
2421
+ version: parsed.version,
2422
+ source,
2423
+ ...(assets
2424
+ ? {
2425
+ uploadId: assets.uploadId,
2426
+ manifestHash: assets.manifestHash,
2427
+ }
2428
+ : {}),
2429
+ ...accessWideningField(parsed.acknowledgeAccessWidening),
2430
+ },
2431
+ headers: { "idempotency-key": randomUUID() },
2432
+ });
2433
+ break;
2434
+ }
2435
+ catch (error) {
2436
+ if (!reuseFrom ||
2437
+ !(error instanceof FoleoError) ||
2438
+ error.code !== "reuse_source_missing")
2439
+ throw error;
2440
+ deps.stderr("Reuse source missing; retrying once with a full upload.\n");
2441
+ }
2442
+ }
2443
+ writeResult(deps, {
2444
+ ...withImageReport(result, assets?.warnings ?? []),
2445
+ upload: assets?.upload ?? { uploaded: 0, reused: 0, bytesUploaded: 0 },
2446
+ }, parsed.json);
2447
+ if (!parsed.json) {
2448
+ const upload = assets?.upload ?? { uploaded: 0, reused: 0 };
2449
+ deps.stdout(`Uploaded ${upload.uploaded} of ${upload.uploaded + upload.reused} images (${upload.reused} reused).\n`);
2450
+ }
2074
2451
  return 0;
2075
2452
  }
2076
2453
  async function pathIsDirectory(path, deps) {
@@ -2212,10 +2589,27 @@ function liveDocAssetMediaType(path) {
2212
2589
  const extension = path.slice(path.lastIndexOf(".")).toLowerCase();
2213
2590
  return LIVE_DOC_ASSET_MEDIA_TYPES[extension] ?? null;
2214
2591
  }
2215
- async function uploadMarkdownAssets(markdownPath, markdown, deps) {
2592
+ async function uploadMarkdownAssets(markdownPath, markdown, deps, json, reuseFrom, replaceEmptyFor) {
2216
2593
  const files = await scanMarkdownAssets(markdownPath, markdown, deps);
2217
- if (files.length === 0)
2218
- return null;
2594
+ const warnings = auditImages(files);
2595
+ reportHeavyImages(deps, warnings, false, json);
2596
+ if (files.length === 0) {
2597
+ if (!replaceEmptyFor)
2598
+ return null;
2599
+ // An omitted upload preserves the current attachments. Only request an
2600
+ // empty replacement when the owner read confirms there are attachments.
2601
+ let previous;
2602
+ try {
2603
+ previous = await requestJson(deps, `/artifacts/${encodeURIComponent(replaceEmptyFor)}/source/content?manifest=1`, { method: "GET", body: undefined });
2604
+ }
2605
+ catch (error) {
2606
+ if (error instanceof ApiRequestError && error.status === 404)
2607
+ return null;
2608
+ throw error;
2609
+ }
2610
+ if (!(typeof previous.fileCount === "number" && previous.fileCount > 1))
2611
+ return null;
2612
+ }
2219
2613
  const manifest = files.map(({ bytes: _bytes, ...file }) => file);
2220
2614
  // Same pacing and retry contract as the HTML bundle path: this loop hits the
2221
2615
  // same /v1/ fence and previously discarded the whole upload on one 429. The
@@ -2230,6 +2624,7 @@ async function uploadMarkdownAssets(markdownPath, markdown, deps) {
2230
2624
  method: "POST",
2231
2625
  body: {
2232
2626
  kind: "live-doc-assets",
2627
+ ...(reuseFrom ? { reuseFrom } : {}),
2233
2628
  manifest,
2234
2629
  declaredBytes: manifest.reduce((n, file) => n + file.byteSize, 0),
2235
2630
  },
@@ -2254,7 +2649,16 @@ async function uploadMarkdownAssets(markdownPath, markdown, deps) {
2254
2649
  headers: { "idempotency-key": completeKey },
2255
2650
  });
2256
2651
  }, budget);
2257
- return { uploadId: upload.uploadId, manifestHash: upload.manifestHash };
2652
+ return {
2653
+ uploadId: upload.uploadId,
2654
+ manifestHash: upload.manifestHash,
2655
+ warnings,
2656
+ upload: {
2657
+ uploaded: upload.files.length,
2658
+ reused: files.length - upload.files.length,
2659
+ bytesUploaded: upload.files.reduce((n, plan) => n + files.find((file) => file.path === plan.path).byteSize, 0),
2660
+ },
2661
+ };
2258
2662
  }
2259
2663
  async function unpublish(args, deps) {
2260
2664
  const parsed = parseFlags(args);
@@ -2763,14 +3167,40 @@ async function deletionStatus(args, deps) {
2763
3167
  async function status(args, deps) {
2764
3168
  const parsed = parseFlags(args);
2765
3169
  const id = parsed.positionals[0];
2766
- if (!id || parsed.positionals.length !== 1) {
2767
- throw new Error("Usage: foleo status <id> [--json]");
3170
+ if (!id ||
3171
+ parsed.positionals.length > 2 ||
3172
+ (parsed.positionals[1] && parsed.sourcePath)) {
3173
+ throw new Error("Usage: foleo status <id> [<path> | --source <path>] [--json]");
2768
3174
  }
2769
3175
  const result = await requestJson(deps, `/artifacts/${encodeURIComponent(id)}`, {
2770
3176
  method: "GET",
2771
3177
  body: undefined,
2772
3178
  });
2773
- writeStatusResult(deps, result, parsed.json);
3179
+ const path = parsed.sourcePath ?? parsed.positionals[1];
3180
+ if (path && isRecord(result)) {
3181
+ const artifact = nestedRecord(result, "artifact") ?? result;
3182
+ const source = nestedRecord(artifact, "source");
3183
+ const remoteDigest = source ? stringField(source, "localDigest") : null;
3184
+ let localDrift = "unknown";
3185
+ if (remoteDigest) {
3186
+ const format = stringField(artifact, "sourceFormat") ??
3187
+ (source ? stringField(source, "sourceFormat") : null);
3188
+ let digest;
3189
+ if (format === "markdown") {
3190
+ const markdown = await deps.readFile(path, "utf8");
3191
+ digest = markdownLocalDigest(markdown, await scanMarkdownAssets(path, markdown, deps));
3192
+ }
3193
+ else if (format === "html") {
3194
+ digest = htmlLocalDigest((await scanBundle(path, deps)).files);
3195
+ }
3196
+ if (digest)
3197
+ localDrift = digest === remoteDigest ? "in_sync" : "local_changed";
3198
+ }
3199
+ writeStatusResult(deps, { ...result, localDrift }, parsed.json);
3200
+ }
3201
+ else {
3202
+ writeStatusResult(deps, result, parsed.json);
3203
+ }
2774
3204
  return 0;
2775
3205
  }
2776
3206
  async function list(args, deps) {
@@ -2875,6 +3305,213 @@ function environmentCommand(args, deps) {
2875
3305
  deps.stdout(`Environment: ${info.name}\nAPI: ${info.apiBase}\n`);
2876
3306
  return 0;
2877
3307
  }
3308
+ /** Download one revision completely before writing any destination files. */
3309
+ async function exportArtifact(args, deps) {
3310
+ const force = args.includes("--force");
3311
+ const parsed = parseFlags(args.filter((arg) => arg !== "--force"));
3312
+ if (parsed.positionals.length !== 2)
3313
+ throw new UsageError("Usage: foleo export <id> <dir> [--force] [--json]");
3314
+ const [id, directory] = parsed.positionals;
3315
+ const root = resolve(directory);
3316
+ const inspect = async (path) => {
3317
+ try {
3318
+ return await lstat(path);
3319
+ }
3320
+ catch (error) {
3321
+ if (isRecord(error) && error.code === "ENOENT")
3322
+ return null;
3323
+ throw error;
3324
+ }
3325
+ };
3326
+ const existing = await inspect(root);
3327
+ if (existing && (!existing.isDirectory() || existing.isSymbolicLink()))
3328
+ throw new LocalError("export_unsafe_path", "Export destination must be a directory, not a symlink.");
3329
+ if (existing && !force && (await readdir(root)).length)
3330
+ throw new LocalError("export_directory_not_empty", "Export destination is not empty. Use --force to overwrite matching files.");
3331
+ const discover = () => requestJson(deps, `/artifacts/${encodeURIComponent(id)}/source/content?manifest=1`, {
3332
+ method: "GET",
3333
+ body: undefined,
3334
+ });
3335
+ const source = await discover();
3336
+ const origin = new URL(apiBase(deps)).origin;
3337
+ // Source URLs are signed capabilities. Never forward the API bearer token.
3338
+ const download = async (url) => {
3339
+ const target = new URL(url);
3340
+ if (target.origin !== origin || target.pathname !== "/v1/source-downloads")
3341
+ throw new LocalError("export_invalid_manifest", "Invalid source download URL.");
3342
+ const response = await deps.fetch(target.href, { redirect: "error" });
3343
+ if (!response.ok)
3344
+ throw apiResponseError(response.status, await response.json().catch(() => null));
3345
+ return response;
3346
+ };
3347
+ const loadManifest = async (current) => {
3348
+ if (current.delivery.kind !== "manifest_url" ||
3349
+ !current.delivery.url ||
3350
+ !Number.isSafeInteger(current.fileCount) ||
3351
+ current.fileCount < 1 ||
3352
+ current.fileCount > 1000)
3353
+ throw new LocalError("export_invalid_manifest", "Invalid source manifest.");
3354
+ const files = [];
3355
+ const seen = new Set();
3356
+ let next = current.delivery.url;
3357
+ for (let page = 0; next && page < 10; page++) {
3358
+ const manifest = (await (await download(next)).json());
3359
+ if (manifest.id !== id ||
3360
+ manifest.sourceRevisionId !== current.sourceRevisionId ||
3361
+ manifest.fileCount !== current.fileCount ||
3362
+ !Array.isArray(manifest.files))
3363
+ throw new LocalError("export_invalid_manifest", "Source manifest changed during export.");
3364
+ for (const file of manifest.files) {
3365
+ if (typeof file.path !== "string" ||
3366
+ !file.path.startsWith("/") ||
3367
+ file.path.includes("\\") ||
3368
+ [...file.path].some((char) => char.charCodeAt(0) <= 31 || char.charCodeAt(0) === 127) ||
3369
+ file.path
3370
+ .slice(1)
3371
+ .split("/")
3372
+ .some((part) => !part || part === "." || part === "..") ||
3373
+ seen.has(file.path) ||
3374
+ !/^[a-f0-9]{64}$/.test(file.sha256) ||
3375
+ !Number.isSafeInteger(file.byteSize) ||
3376
+ file.byteSize < 0 ||
3377
+ file.byteSize > HTML_BUNDLE_MAX_FILE_BYTES ||
3378
+ typeof file.url !== "string")
3379
+ throw new LocalError("export_invalid_manifest", "Unsafe or invalid source file entry.");
3380
+ seen.add(file.path);
3381
+ files.push(file);
3382
+ }
3383
+ if (files.length > current.fileCount)
3384
+ throw new LocalError("export_invalid_manifest", "Source manifest has too many files.");
3385
+ next = manifest.nextUrl;
3386
+ }
3387
+ if (next ||
3388
+ files.length !== current.fileCount ||
3389
+ files.reduce((sum, file) => sum + file.byteSize, 0) >
3390
+ HTML_BUNDLE_MAX_BYTES)
3391
+ throw new LocalError("export_invalid_manifest", "Source manifest is incomplete or exceeds export limits.");
3392
+ return files;
3393
+ };
3394
+ const loadFreshManifest = async (initial) => {
3395
+ let current = initial;
3396
+ for (let refresh = 0;; refresh++) {
3397
+ if (current.sourceFormat !== source.sourceFormat ||
3398
+ current.sourceRevisionId !== source.sourceRevisionId ||
3399
+ current.contentHash !== source.contentHash ||
3400
+ current.fileCount !== source.fileCount)
3401
+ throw new LocalError("export_revision_changed", "Source changed while renewing download URLs. Restart export.");
3402
+ try {
3403
+ return await loadManifest(current);
3404
+ }
3405
+ catch (error) {
3406
+ if (!(error instanceof FoleoError) ||
3407
+ error.httpStatus !== 410 ||
3408
+ error.code !== "source_url_expired" ||
3409
+ refresh >= 3)
3410
+ throw error;
3411
+ current = await discover();
3412
+ }
3413
+ }
3414
+ };
3415
+ let files = await loadFreshManifest(source);
3416
+ const identity = (entries) => JSON.stringify(entries
3417
+ .map(({ path, sha256, byteSize, mediaType }) => ({
3418
+ path,
3419
+ sha256,
3420
+ byteSize,
3421
+ mediaType,
3422
+ }))
3423
+ .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)));
3424
+ const originalIdentity = identity(files);
3425
+ const staging = await mkdtemp(join(tmpdir(), "foleo-export-"));
3426
+ try {
3427
+ for (let index = 0; index < files.length; index++) {
3428
+ let file = files[index];
3429
+ let response;
3430
+ // Refresh only the pending file's capabilities; verified staging files
3431
+ // survive refresh. Bound repeated expiry so a broken clock cannot loop.
3432
+ for (let refresh = 0;; refresh++) {
3433
+ try {
3434
+ response = await download(file.url);
3435
+ break;
3436
+ }
3437
+ catch (error) {
3438
+ if (!(error instanceof FoleoError) ||
3439
+ error.httpStatus !== 410 ||
3440
+ error.code !== "source_url_expired" ||
3441
+ refresh >= 3)
3442
+ throw error;
3443
+ const current = await discover();
3444
+ const renewed = await loadFreshManifest(current);
3445
+ if (current.sourceFormat !== source.sourceFormat ||
3446
+ current.sourceRevisionId !== source.sourceRevisionId ||
3447
+ current.contentHash !== source.contentHash ||
3448
+ identity(renewed) !== originalIdentity)
3449
+ throw new LocalError("export_revision_changed", "Source changed while renewing download URLs. Restart export.");
3450
+ const byPath = new Map(renewed.map((entry) => [entry.path, entry]));
3451
+ files = files.map((entry) => byPath.get(entry.path));
3452
+ file = files[index];
3453
+ }
3454
+ }
3455
+ const bytes = new Uint8Array(await response.arrayBuffer());
3456
+ if (bytes.byteLength !== file.byteSize ||
3457
+ createHash("sha256").update(bytes).digest("hex") !== file.sha256)
3458
+ throw new LocalError("export_hash_mismatch", `Source integrity check failed for ${file.path}.`);
3459
+ await writeFile(join(staging, String(index)), bytes);
3460
+ }
3461
+ await mkdir(root, { recursive: true });
3462
+ // Check each component: --force permits replacing regular files only.
3463
+ for (const file of files) {
3464
+ const parts = file.path.slice(1).split("/");
3465
+ let parent = root;
3466
+ for (const part of parts.slice(0, -1)) {
3467
+ parent = join(parent, part);
3468
+ try {
3469
+ await mkdir(parent);
3470
+ }
3471
+ catch (error) {
3472
+ if (!isRecord(error) || error.code !== "EEXIST")
3473
+ throw error;
3474
+ }
3475
+ const entry = await lstat(parent);
3476
+ if (entry.isSymbolicLink() || !entry.isDirectory())
3477
+ throw new LocalError("export_unsafe_path", "Export path contains a symlink or non-directory.");
3478
+ }
3479
+ const entry = await inspect(join(root, ...parts));
3480
+ if (entry &&
3481
+ (!force || !entry.isFile() || entry.isSymbolicLink() || entry.nlink > 1))
3482
+ throw new LocalError("export_unsafe_path", `Refusing to overwrite ${file.path}.`);
3483
+ }
3484
+ for (const [index, file] of files.entries()) {
3485
+ const handle = await open(join(root, file.path.slice(1)), constants.O_WRONLY |
3486
+ constants.O_CREAT |
3487
+ constants.O_NOFOLLOW |
3488
+ (force ? constants.O_TRUNC : constants.O_EXCL), 0o600);
3489
+ try {
3490
+ await handle.writeFile(await readFile(join(staging, String(index))));
3491
+ }
3492
+ finally {
3493
+ await handle.close();
3494
+ }
3495
+ }
3496
+ }
3497
+ finally {
3498
+ await rm(staging, { recursive: true, force: true });
3499
+ }
3500
+ const summary = {
3501
+ id,
3502
+ directory: root,
3503
+ sourceFormat: source.sourceFormat,
3504
+ sourceRevisionId: source.sourceRevisionId,
3505
+ fileCount: files.length,
3506
+ byteSize: files.reduce((sum, file) => sum + file.byteSize, 0),
3507
+ verified: true,
3508
+ exportNote: source.exportNote,
3509
+ };
3510
+ deps.stdout(parsed.json
3511
+ ? `${JSON.stringify(summary, null, 2)}\n`
3512
+ : `Exported ${files.length} files (${summary.byteSize} bytes) to ${root}; SHA-256 verified.\n${source.exportNote ?? ""}\n`);
3513
+ return 0;
3514
+ }
2878
3515
  async function requestJson(deps, path, init) {
2879
3516
  const credential = await resolveCredentialWithSource(deps);
2880
3517
  if (!credential)
@@ -2891,12 +3528,58 @@ async function requestJsonWithToken(deps, path, token, init) {
2891
3528
  "content-type": "application/json",
2892
3529
  ...init.headers,
2893
3530
  };
2894
- const response = await deps.fetch(`${apiBase(deps)}${path}`, {
2895
- method: init.method,
2896
- headers,
2897
- ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),
2898
- });
2899
- const body = await response.json().catch(() => null);
3531
+ uploadRuns.get(deps)?.controller.signal.throwIfAborted();
3532
+ if (uploadRuns.has(deps) &&
3533
+ /^\/(?:artifacts|docs)(?:\/|$)/u.test(path) &&
3534
+ init.method !== "GET")
3535
+ uploadRuns.get(deps).submitted = true;
3536
+ const frozenBody = init.body === undefined ? undefined : JSON.stringify(init.body);
3537
+ const key = init.headers?.["idempotency-key"];
3538
+ const receiptWrite = key &&
3539
+ (init.method === "POST" || init.method === "PUT") &&
3540
+ /^\/(?:artifacts(?:\/html)?|docs)(?:\/[^/]+)?$/u.test(path);
3541
+ let response;
3542
+ let body;
3543
+ for (let retry = 0;; retry++) {
3544
+ try {
3545
+ response = await deps.fetch(`${apiBase(deps)}${path}`, {
3546
+ method: init.method,
3547
+ ...(uploadRuns.has(deps)
3548
+ ? { signal: uploadRuns.get(deps).controller.signal }
3549
+ : {}),
3550
+ headers,
3551
+ ...(frozenBody === undefined ? {} : { body: frozenBody }),
3552
+ });
3553
+ if (!receiptWrite ||
3554
+ (response.status !== 502 && response.status !== 504)) {
3555
+ if (response.ok && receiptWrite)
3556
+ body = await response.json();
3557
+ else
3558
+ body = await response.json().catch(() => null);
3559
+ break;
3560
+ }
3561
+ await response.body?.cancel();
3562
+ }
3563
+ catch (error) {
3564
+ // fetch throws TypeError for network loss; Node also exposes reset/socket
3565
+ // codes. Local validation/auth failures never enter this transport loop.
3566
+ if (!receiptWrite ||
3567
+ uploadRuns.get(deps)?.controller.signal.aborted ||
3568
+ !(error instanceof TypeError ||
3569
+ (isRecord(error) &&
3570
+ ["ECONNRESET", "ETIMEDOUT", "EPIPE", "UND_ERR_SOCKET"].includes(String(error.code)))))
3571
+ throw error;
3572
+ }
3573
+ if (retry >= 3)
3574
+ throw new LocalError("write_result_unknown", "The write may have succeeded, but its response could not be recovered.", {
3575
+ retryable: true,
3576
+ context: { idempotencyKey: key, method: init.method, path },
3577
+ next: `Replay the original ${init.method} ${path} JSON body and precondition with Idempotency-Key: ${key}. Do not start a new publish; the accepted receipt returns the original result.`,
3578
+ });
3579
+ deps.stderr(`Response lost; replaying the same write (attempt ${retry + 2}).\n`);
3580
+ await (deps.sleep ??
3581
+ ((ms) => new Promise((resolve) => setTimeout(resolve, ms))))(Math.min(4000, 500 * 2 ** retry));
3582
+ }
2900
3583
  if (RETRYABLE_STATUSES.has(response.status)) {
2901
3584
  // Thrown ahead of ApiRequestError so `withRateLimitRetry` can act on it. The
2902
3585
  // zone fence in front of this API answers with a Cloudflare error page rather
@@ -2907,6 +3590,11 @@ async function requestJsonWithToken(deps, path, token, init) {
2907
3590
  if (!response.ok) {
2908
3591
  throw new ApiRequestError(response.status, apiErrorCode(body, response.status), body);
2909
3592
  }
3593
+ if (path === "/uploads" &&
3594
+ isRecord(body) &&
3595
+ typeof body.uploadId === "string") {
3596
+ uploadRun(deps).sessions.add(body.uploadId);
3597
+ }
2910
3598
  return body;
2911
3599
  }
2912
3600
  class ApiRequestError extends FoleoError {
@@ -2924,19 +3612,43 @@ class ApiRequestError extends FoleoError {
2924
3612
  : null;
2925
3613
  super({
2926
3614
  code,
2927
- message: code === "matching_source_exists"
2928
- ? matchingSourceExistsMessage(body)
2929
- : code === "acknowledgement_required" &&
2930
- envelope?.field !== "acknowledgeLinkBreakage"
2931
- ? "Foleo API error: acknowledgement_required. This change would expose the artifact to more readers or add a working address. Only after the human approves it, re-run the same command with --acknowledge-access-widening."
2932
- : code === "contained_profile_unavailable"
2933
- ? containedProfileUnavailableMessage(references ?? [])
2934
- : `Foleo API error: ${code}`,
3615
+ message: code === "bundle_new_files_limit" &&
3616
+ typeof envelope?.message === "string"
3617
+ ? envelope.message
3618
+ : code === "matching_source_exists"
3619
+ ? matchingSourceExistsMessage(body)
3620
+ : code === "acknowledgement_required" &&
3621
+ envelope?.field !== "acknowledgeLinkBreakage"
3622
+ ? "Foleo API error: acknowledgement_required. This change would expose the artifact to more readers or add a working address. Only after the human approves it, re-run the same command with --acknowledge-access-widening."
3623
+ : code === "contained_profile_unavailable"
3624
+ ? containedProfileUnavailableMessage(references ?? [])
3625
+ : `Foleo API error: ${code}`,
2935
3626
  httpStatus: status,
2936
3627
  source: "api",
2937
3628
  retryable,
2938
3629
  ...(next === null ? {} : { next }),
2939
- ...(references === null ? {} : { context: { references } }),
3630
+ ...(["approval_required", "input_required"].includes(code) && envelope
3631
+ ? {
3632
+ next: `Open ${String(envelope.reviewUrl ?? "Foleo")} to review, then use foleo approval commit ${String(envelope.approvalId ?? "<id>")} --idempotency-key <key>.`,
3633
+ context: Object.fromEntries([
3634
+ "approvalId",
3635
+ "reviewUrl",
3636
+ "approvalReason",
3637
+ "targetType",
3638
+ "audiences",
3639
+ ]
3640
+ .filter((key) => envelope[key] !== undefined)
3641
+ .map((key) => [key, envelope[key]])),
3642
+ }
3643
+ : code === "bundle_new_files_limit" && envelope
3644
+ ? {
3645
+ context: Object.fromEntries(["limit", "count", "newFiles", "copiedFiles", "sharedObjects"]
3646
+ .filter((field) => envelope[field] !== undefined)
3647
+ .map((field) => [field, envelope[field]])),
3648
+ }
3649
+ : references === null
3650
+ ? {}
3651
+ : { context: { references } }),
2940
3652
  });
2941
3653
  this.name = "ApiRequestError";
2942
3654
  this.status = status;
@@ -3020,8 +3732,12 @@ allowReplay = false) {
3020
3732
  next: "Run `npx -y @foleo/cli login` or set FOLEO_TOKEN.",
3021
3733
  });
3022
3734
  const bytes = body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength);
3735
+ uploadRuns.get(deps)?.controller.signal.throwIfAborted();
3023
3736
  const response = await deps.fetch(`${apiBase(deps)}${path}`, {
3024
3737
  method: "PUT",
3738
+ ...(uploadRuns.has(deps)
3739
+ ? { signal: uploadRuns.get(deps).controller.signal }
3740
+ : {}),
3025
3741
  headers: { authorization: `Bearer ${credential.token}`, ...headers },
3026
3742
  body: bytes,
3027
3743
  });
@@ -3258,6 +3974,26 @@ function loopbackSuccessBody() {
3258
3974
  function sha256Utf8(value) {
3259
3975
  return createHash("sha256").update(value, "utf8").digest("hex");
3260
3976
  }
3977
+ /** SHA-256 of UTF-8 JSON ["html-v1", sorted [path, sha256, byteSize] triples].
3978
+ * Paths are the upload scanner's root-relative POSIX paths, with leading slash.
3979
+ * Capture this before optimization: the uploaded manifest has different bytes.
3980
+ */
3981
+ export function htmlLocalDigest(files) {
3982
+ const sorted = [...files].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
3983
+ return sha256Utf8(JSON.stringify([
3984
+ "html-v1",
3985
+ sorted.map(({ path, sha256, byteSize }) => [path, sha256, byteSize]),
3986
+ ]));
3987
+ }
3988
+ /** Must match the server's markdownLocalDigest, including preserved images. */
3989
+ export function markdownLocalDigest(markdown, images) {
3990
+ const sorted = [...images].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
3991
+ return sha256Utf8(JSON.stringify([
3992
+ "markdown-v1",
3993
+ markdown,
3994
+ sorted.map(({ path, sha256 }) => [path, sha256]),
3995
+ ]));
3996
+ }
3261
3997
  function publishSourcePayload(contentHash, sourceId) {
3262
3998
  return {
3263
3999
  provider: "local",
@@ -3366,6 +4102,8 @@ function writeResult(deps, result, json) {
3366
4102
  }
3367
4103
  if (result !== null && typeof result === "object" && "url" in result) {
3368
4104
  deps.stdout(`${String(result.url)}\n`);
4105
+ if ("unchanged" in result && result.unchanged === true)
4106
+ deps.stderr("Unchanged; the existing published version is current.\n");
3369
4107
  // The applied HTML runtime profile is chosen by the server; say which one
3370
4108
  // a human got. stderr, so stdout stays the bare URL it always was.
3371
4109
  const profile = stringField(result, "runtimeProfile");
@@ -3377,6 +4115,34 @@ function writeResult(deps, result, json) {
3377
4115
  }
3378
4116
  deps.stdout(`${JSON.stringify(result)}\n`);
3379
4117
  }
4118
+ /** Render the server's visibility descriptor; never infer capabilities from the id. */
4119
+ function writeSettingsResult(deps, result, json) {
4120
+ if (json || !isRecord(result) || !Array.isArray(result.visibilityOptions)) {
4121
+ writeResult(deps, result, json);
4122
+ return;
4123
+ }
4124
+ const settings = nestedRecord(result, "settings") ?? {};
4125
+ const options = result.visibilityOptions.filter(isRecord);
4126
+ const selected = options.find((option) => option.value === settings.visibility);
4127
+ const lines = [
4128
+ `Visibility: ${stringField(selected, "label") ?? settings.visibility ?? "-"}`,
4129
+ ];
4130
+ for (const option of options) {
4131
+ const disabled = option.available === false;
4132
+ lines.push(` ${String(option.label)} (${String(option.value)})${disabled ? " [disabled]" : ""}: ${String(option.audience)}`);
4133
+ if (disabled && typeof option.reason === "string")
4134
+ lines.push(` ${option.reason}`);
4135
+ if (option.widening === true)
4136
+ lines.push(" Access widening; existing connection policy or API-key acknowledgement rules apply.");
4137
+ }
4138
+ for (const [key, value] of Object.entries(settings)) {
4139
+ if (key !== "visibility")
4140
+ lines.push(`${key}: ${typeof value === "string" ? value : JSON.stringify(value)}`);
4141
+ }
4142
+ if (typeof result.stateRevision === "number")
4143
+ lines.push(`State revision: ${result.stateRevision}`);
4144
+ deps.stdout(`${lines.join("\n")}\n`);
4145
+ }
3380
4146
  function writeStatusResult(deps, result, json) {
3381
4147
  if (json) {
3382
4148
  writeResult(deps, result, true);
@@ -3397,6 +4163,9 @@ function writeStatusResult(deps, result, json) {
3397
4163
  lines.push(`Version: ${statusRecord.version}`);
3398
4164
  if (typeof statusRecord.stateRevision === "number")
3399
4165
  lines.push(`State revision: ${statusRecord.stateRevision}`);
4166
+ const localDrift = stringField(result, "localDrift");
4167
+ if (localDrift)
4168
+ lines.push(`Local drift: ${localDrift}`);
3400
4169
  const revision = stringField(statusRecord, "etag");
3401
4170
  if (revision)
3402
4171
  lines.push(`Revision: ${revision}`);
@@ -3437,6 +4206,7 @@ function writeDeletionResult(deps, result, json) {
3437
4206
  }
3438
4207
  function parseFlags(args, options = {}) {
3439
4208
  const positionals = [];
4209
+ let sourcePath;
3440
4210
  let json = false;
3441
4211
  let title;
3442
4212
  let version;
@@ -3454,8 +4224,11 @@ function parseFlags(args, options = {}) {
3454
4224
  let publishSeparately = false;
3455
4225
  let allowDelete = false;
3456
4226
  let allowPurge = false;
4227
+ let allowWorkspaces = false;
4228
+ let allowWorkspaceSharing = false;
3457
4229
  let name;
3458
4230
  let dryRun = false;
4231
+ let optimizeImages;
3459
4232
  let previous;
3460
4233
  let acknowledgeLinkBreakage = false;
3461
4234
  let acknowledgeAccessWidening = false;
@@ -3480,6 +4253,14 @@ function parseFlags(args, options = {}) {
3480
4253
  throw new UsageError("--name requires a value", "name_missing");
3481
4254
  continue;
3482
4255
  }
4256
+ if (arg === "--optimize-images") {
4257
+ optimizeImages = true;
4258
+ continue;
4259
+ }
4260
+ if (arg === "--no-optimize-images") {
4261
+ optimizeImages = false;
4262
+ continue;
4263
+ }
3483
4264
  if (arg === "--dry-run") {
3484
4265
  dryRun = true;
3485
4266
  continue;
@@ -3511,6 +4292,12 @@ function parseFlags(args, options = {}) {
3511
4292
  throw new Error("--kind requires a value");
3512
4293
  continue;
3513
4294
  }
4295
+ if (arg === "--source") {
4296
+ sourcePath = args[++i];
4297
+ if (!sourcePath)
4298
+ throw new Error("--source requires a path");
4299
+ continue;
4300
+ }
3514
4301
  if (arg === "--format") {
3515
4302
  format = args[++i];
3516
4303
  if (!format)
@@ -3601,6 +4388,15 @@ function parseFlags(args, options = {}) {
3601
4388
  allowDelete = true;
3602
4389
  continue;
3603
4390
  }
4391
+ if (arg === "--allow-workspaces" || arg === "--allow-workspace-sharing") {
4392
+ if (!options.allowLoginScopeFlags)
4393
+ throw new UsageError(`${arg} is valid only with login`);
4394
+ if (arg === "--allow-workspaces")
4395
+ allowWorkspaces = true;
4396
+ else
4397
+ allowWorkspaceSharing = true;
4398
+ continue;
4399
+ }
3604
4400
  if (arg === "--allow-purge") {
3605
4401
  if (!options.allowLoginScopeFlags)
3606
4402
  throw new Error("--allow-purge is valid only with login");
@@ -3612,6 +4408,7 @@ function parseFlags(args, options = {}) {
3612
4408
  positionals.push(arg);
3613
4409
  }
3614
4410
  return {
4411
+ ...(sourcePath ? { sourcePath } : {}),
3615
4412
  positionals,
3616
4413
  json,
3617
4414
  ...(title !== undefined ? { title } : {}),
@@ -3630,8 +4427,11 @@ function parseFlags(args, options = {}) {
3630
4427
  publishSeparately,
3631
4428
  allowDelete,
3632
4429
  allowPurge,
4430
+ allowWorkspaces,
4431
+ allowWorkspaceSharing,
3633
4432
  ...(name === undefined ? {} : { name }),
3634
4433
  dryRun,
4434
+ optimizeImages,
3635
4435
  ...(previous === undefined ? {} : { previous }),
3636
4436
  acknowledgeLinkBreakage,
3637
4437
  acknowledgeAccessWidening,
@@ -3654,8 +4454,10 @@ function help() {
3654
4454
  return [
3655
4455
  "Usage:",
3656
4456
  " foleo --help",
3657
- " foleo login [--allow-purge] [--json]",
4457
+ " foleo login [--allow-purge] [--allow-workspaces] [--allow-workspace-sharing] [--json]",
3658
4458
  " foleo logout [--no-revoke] [--json]",
4459
+ " Workspace login flags are staging/local only; browser consent starts unchecked.",
4460
+ " --allow-workspaces requests read + write; --allow-workspace-sharing requests share + read.",
3659
4461
  " foleo whoami [--json]",
3660
4462
  " foleo doctor [--json]",
3661
4463
  " foleo skill get|path",
@@ -3663,16 +4465,20 @@ function help() {
3663
4465
  " foleo environment [--json]",
3664
4466
  " foleo list [--kind <kind>] [--format <format>] [--runtime <class>] [--limit <n>] [--json]",
3665
4467
  " foleo get <id> [--json]",
4468
+ " foleo export <id> <dir> [--force] [--json] (source and assets; SHA-256 verified)",
3666
4469
  " foleo publish <path> [--title <title>] [--settings <json>] [--password-stdin] [--publish-separately] [--acknowledge-access-widening] [--json]",
3667
- " foleo publish <dir> --accept-hosting-risk --name <label> [--runtime-profile auto|open|contained] [--dry-run] [--json]",
3668
- " foleo update <id> <path> --revision <etag> [--runtime-profile auto|open|contained] [--acknowledge-access-widening] [--json]",
4470
+ " foleo publish <dir> --accept-hosting-risk --name <label> [--runtime-profile auto|open|contained] [--optimize-images | --no-optimize-images] [--dry-run] [--json]",
4471
+ " foleo update <id> <path> --revision <etag> [--runtime-profile auto|open|contained] [--optimize-images | --no-optimize-images] [--acknowledge-access-widening] [--dry-run] [--json]",
3669
4472
  " foleo update <id> <file.md> --version <version> [--acknowledge-access-widening] [--json] (compatibility)",
4473
+ " Identical updates may return unchanged: true; revision/ETag stay unchanged. Retry an interrupted request with the same idempotency key.",
4474
+ " Shared storage can reuse files from retained versions of the same artifact; legacy storage reuses only its live version.",
3670
4475
  " foleo name-check <label> [--json]",
3671
4476
  " foleo names [--artifact <id>] [--limit <n>] [--cursor <cursor>] [--json]",
3672
4477
  " foleo name attach <id> <label> [--revision <etag>] [--acknowledge-access-widening] [--dry-run] [--json]",
3673
4478
  " foleo name set <id> <label> --previous keep-as-alias|release [--revision <etag>] [--acknowledge-access-widening] [--dry-run] [--json]",
3674
4479
  " foleo name release <id> <label> --acknowledge-link-breakage [--revision <etag>] [--dry-run] [--json]",
3675
- " foleo status <id> [--json]",
4480
+ " foleo status <id> [<path>] [--json]",
4481
+ " foleo get <id> [--source <path>] [--json]",
3676
4482
  " foleo settings <id> [--json]",
3677
4483
  " foleo settings <id> --set k=v [--set k=v ...] [--password-stdin] --revision <etag> [--acknowledge-access-widening] [--json]",
3678
4484
  " foleo limits [--json]",
@@ -3702,6 +4508,12 @@ function help() {
3702
4508
  " The chosen name is the artifact's only address; there is no generated",
3703
4509
  " fallback, and the old generated a-<id> hosts no longer serve.",
3704
4510
  "",
4511
+ " HTML bundles: 300 new files per publish/update, 1,000 total with server reuse.",
4512
+ " Legacy storage copies every file and permits 300 total. See `foleo limits`.",
4513
+ " HTML bundle folders get responsive AVIF copies by default; --no-optimize-images opts out.",
4514
+ " Optimization runs locally; create dry-runs still probe name and access.",
4515
+ " HTML update dry-runs are local bundle plans without network.",
4516
+ " --optimize-images explicitly requires the macOS encoder (fails if unavailable).",
3705
4517
  " --dry-run plans an HTML publish without uploading, creating, or spending",
3706
4518
  " quota. It reports the resolved name and availability, url, title with its",
3707
4519
  " resolvedFrom source, visibility, routes, largestFiles and skipped[], the",
@@ -3730,6 +4542,11 @@ function help() {
3730
4542
  " name-check <label> is free and checks availability without publishing.",
3731
4543
  "",
3732
4544
  "Access control:",
4545
+ " Visibility labels: Private (private), Link (unlisted), Link + password",
4546
+ " (password), Public (public). Private: Only you and your organization.",
4547
+ " settings <id> lists all options; unavailable options are disabled with",
4548
+ " their reason. --json includes visibilityOptions and its widening flags.",
4549
+ " HTML Public is gated by the Public Suffix List (public_publish_gated).",
3733
4550
  " A Markdown document is unlisted (anyone with the link) or private (signed-in",
3734
4551
  " members of your Foleo organization, at the same URL): settings <id> --set",
3735
4552
  " visibility=private|unlisted --revision <etag>. Private to unlisted lets more",