@foleo/cli 0.1.9 → 0.1.11

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
@@ -10,6 +10,8 @@ import { dirname, join, relative, resolve, sep } from "node:path";
10
10
  import { fileURLToPath, pathToFileURL } from "node:url";
11
11
  const KEYCHAIN_SERVICE = "com.contraverse.foleo.cli";
12
12
  const CLI_KEY_SCOPES = [
13
+ "artifacts:read",
14
+ "artifacts:unpublish",
13
15
  "docs:write",
14
16
  "docs:unpublish",
15
17
  "html:write",
@@ -71,8 +73,18 @@ export async function runCli(argv, deps = {
71
73
  return await update(rest, commandDeps);
72
74
  if (command === "unpublish")
73
75
  return await unpublish(rest, commandDeps);
76
+ if (command === "delete")
77
+ return await deleteArtifact(rest, commandDeps);
78
+ if (command === "restore")
79
+ return await restoreArtifact(rest, commandDeps);
80
+ if (command === "purge")
81
+ return await purgeArtifact(rest, commandDeps);
82
+ if (command === "deletion-status")
83
+ return await deletionStatus(rest, commandDeps);
74
84
  if (command === "status")
75
85
  return await status(rest, commandDeps);
86
+ if (command === "get")
87
+ return await status(rest, commandDeps);
76
88
  if (command === "html-publish")
77
89
  return await htmlPublish(rest, commandDeps);
78
90
  if (command === "html-update")
@@ -356,9 +368,9 @@ function stringArray(value) {
356
368
  : [];
357
369
  }
358
370
  async function login(args, deps) {
359
- const parsed = parseFlags(args);
371
+ const parsed = parseFlags(args, { allowLoginScopeFlags: true });
360
372
  if (parsed.positionals.length > 0)
361
- throw new Error("Usage: foleo login [--json]");
373
+ throw new Error("Usage: foleo login [--allow-delete] [--allow-purge] [--json]");
362
374
  const base = apiBase(deps);
363
375
  announceApi(deps, parsed.json);
364
376
  const verifyStore = deps.verifyCredentialStore ?? verifyKeychainWritable;
@@ -393,7 +405,11 @@ async function login(args, deps) {
393
405
  method: "POST",
394
406
  body: {
395
407
  name: "Foleo CLI",
396
- scopes: CLI_KEY_SCOPES,
408
+ scopes: [
409
+ ...CLI_KEY_SCOPES,
410
+ ...(parsed.allowDelete ? ["artifacts:delete"] : []),
411
+ ...(parsed.allowPurge ? ["artifacts:purge"] : []),
412
+ ],
397
413
  deferredActivation: true,
398
414
  },
399
415
  });
@@ -456,14 +472,12 @@ async function htmlPublish(args, deps) {
456
472
  async function htmlUpdate(args, deps) {
457
473
  const parsed = parseFlags(args);
458
474
  const [id, root] = parsed.positionals;
459
- if (!id ||
460
- !root ||
461
- parsed.positionals.length !== 2 ||
462
- parsed.revision === undefined)
475
+ const revision = legacyRevision(parsed.revision);
476
+ if (!id || !root || parsed.positionals.length !== 2 || revision === null)
463
477
  throw new Error("Usage: foleo html-update <id> <bundle-root> --revision <stateRevision> [--json]");
464
478
  const result = await publishBundle(root, deps, {
465
479
  id,
466
- revision: parsed.revision,
480
+ revision,
467
481
  });
468
482
  writeResult(deps, result, parsed.json);
469
483
  return 0;
@@ -478,9 +492,10 @@ async function htmlStatus(args, deps) {
478
492
  async function htmlVisibility(args, deps) {
479
493
  const parsed = parseFlags(args);
480
494
  const id = parsed.positionals[0];
495
+ const revision = legacyRevision(parsed.revision);
481
496
  if (!id ||
482
497
  parsed.positionals.length !== 1 ||
483
- parsed.revision === undefined ||
498
+ revision === null ||
484
499
  !parsed.set ||
485
500
  !["unlisted", "password", "private"].includes(parsed.set))
486
501
  throw new Error("Usage: foleo html-visibility <id> --set unlisted|password|private --revision <stateRevision> [--json]");
@@ -488,7 +503,7 @@ async function htmlVisibility(args, deps) {
488
503
  const result = await requestJson(deps, `/artifacts/html/${encodeURIComponent(id)}/visibility`, {
489
504
  method: "PATCH",
490
505
  body: { visibility: parsed.set },
491
- headers: revisionHeaders(parsed.revision),
506
+ headers: revisionHeaders(revision),
492
507
  });
493
508
  writeResult(deps, result, parsed.json);
494
509
  return 0;
@@ -496,16 +511,17 @@ async function htmlVisibility(args, deps) {
496
511
  async function htmlPassword(args, deps) {
497
512
  const parsed = parseFlags(args);
498
513
  const id = parsed.positionals[0];
514
+ const revision = legacyRevision(parsed.revision);
499
515
  if (!id ||
500
516
  parsed.positionals.length !== 1 ||
501
- parsed.revision === undefined ||
517
+ revision === null ||
502
518
  !parsed.password)
503
519
  throw new Error("Usage: foleo html-password <id> --password <12–256 characters> --revision <stateRevision> [--json]");
504
520
  announceApi(deps, parsed.json);
505
521
  const result = await requestJson(deps, `/artifacts/html/${encodeURIComponent(id)}/password`, {
506
522
  method: "PATCH",
507
523
  body: { password: parsed.password },
508
- headers: revisionHeaders(parsed.revision),
524
+ headers: revisionHeaders(revision),
509
525
  });
510
526
  writeResult(deps, result, parsed.json);
511
527
  return 0;
@@ -513,13 +529,14 @@ async function htmlPassword(args, deps) {
513
529
  async function htmlUnpublish(args, deps) {
514
530
  const parsed = parseFlags(args);
515
531
  const id = parsed.positionals[0];
516
- if (!id || parsed.positionals.length !== 1 || parsed.revision === undefined)
532
+ const revision = legacyRevision(parsed.revision);
533
+ if (!id || parsed.positionals.length !== 1 || revision === null)
517
534
  throw new Error("Usage: foleo html-unpublish <id> --revision <stateRevision> [--json]");
518
535
  const result = await requestJson(deps, `/artifacts/html/${encodeURIComponent(id)}/unpublish`, {
519
536
  method: "POST",
520
537
  body: {},
521
538
  headers: {
522
- "if-match": `"r${parsed.revision}"`,
539
+ "if-match": `"r${revision}"`,
523
540
  "idempotency-key": randomUUID(),
524
541
  },
525
542
  });
@@ -529,32 +546,55 @@ async function htmlUnpublish(args, deps) {
529
546
  async function publishBundle(root, deps, update, hostingRiskAcknowledged = false) {
530
547
  const files = await scanBundle(root, deps);
531
548
  const manifest = files.map(({ bytes: _bytes, ...file }) => file);
532
- const upload = await requestJson(deps, "/uploads", {
549
+ // One pacer for every /v1/ call in this publish: the zone rate-limit fence
550
+ // counts the session create and complete calls against the same budget as the
551
+ // file PUTs, so pacing only the PUTs overspends it.
552
+ const pace = createHtmlUploadPacer(deps);
553
+ const uploadKey = randomUUID();
554
+ await pace();
555
+ const upload = await withRateLimitRetry(deps, "starting the upload", () => requestJson(deps, "/uploads", {
533
556
  method: "POST",
534
557
  body: {
535
558
  kind: "html-artifact-bundle",
536
559
  manifest,
537
560
  declaredBytes: manifest.reduce((n, file) => n + file.byteSize, 0),
538
561
  },
539
- headers: { "idempotency-key": randomUUID() },
540
- });
541
- const beforeFilePut = createHtmlUploadPacer(deps);
562
+ headers: { "idempotency-key": uploadKey },
563
+ }));
564
+ let uploaded = 0;
542
565
  for (const plan of upload.files) {
543
566
  const file = files.find((candidate) => candidate.path === plan.path);
544
567
  if (!file)
545
568
  throw new Error("Server returned an unexpected upload file");
546
- await beforeFilePut();
547
- await requestRaw(deps, `/uploads/${upload.uploadId}/files/${plan.fileToken}`, file.bytes, { "content-length": String(file.byteSize) });
569
+ await pace();
570
+ await withRateLimitRetry(deps, `uploading ${plan.path}`, () => requestRaw(deps, `/uploads/${upload.uploadId}/files/${plan.fileToken}`, file.bytes, { "content-length": String(file.byteSize) }));
571
+ uploaded += 1;
572
+ // A large bundle is paced to well under a minute's worth of requests, so a
573
+ // silent multi-minute publish reads as a hang. Progress goes to stderr so
574
+ // `--json` stdout stays machine-parseable.
575
+ if (upload.files.length > 20 && uploaded % 20 === 0) {
576
+ deps.stderr(`Uploaded ${uploaded}/${upload.files.length} files.\n`);
577
+ }
548
578
  }
549
- await requestJson(deps, `/uploads/${upload.uploadId}/complete`, {
579
+ const completeKey = randomUUID();
580
+ await pace();
581
+ await withRateLimitRetry(deps, "finishing the upload", () => requestJson(deps, `/uploads/${upload.uploadId}/complete`, {
550
582
  method: "POST",
551
583
  body: {},
552
- headers: { "idempotency-key": randomUUID() },
553
- });
584
+ headers: { "idempotency-key": completeKey },
585
+ }));
586
+ const sourceId = update
587
+ ? await ownerArtifactSourceId(deps, update.id)
588
+ : undefined;
589
+ const source = publishSourcePayload(upload.manifestHash, sourceId);
554
590
  return update
555
591
  ? requestJson(deps, `/artifacts/html/${encodeURIComponent(update.id)}`, {
556
592
  method: "PUT",
557
- body: { uploadId: upload.uploadId, manifestHash: upload.manifestHash },
593
+ body: {
594
+ uploadId: upload.uploadId,
595
+ manifestHash: upload.manifestHash,
596
+ source,
597
+ },
558
598
  headers: {
559
599
  "if-match": `"r${update.revision}"`,
560
600
  "idempotency-key": randomUUID(),
@@ -566,6 +606,7 @@ async function publishBundle(root, deps, update, hostingRiskAcknowledged = false
566
606
  uploadId: upload.uploadId,
567
607
  manifestHash: upload.manifestHash,
568
608
  hostingRiskAcknowledged,
609
+ source,
569
610
  },
570
611
  headers: { "idempotency-key": randomUUID() },
571
612
  });
@@ -573,26 +614,134 @@ async function publishBundle(root, deps, update, hostingRiskAcknowledged = false
573
614
  function revisionHeaders(revision) {
574
615
  return { "if-match": `"r${revision}"`, "idempotency-key": randomUUID() };
575
616
  }
617
+ function legacyRevision(value) {
618
+ if (value === undefined || !/^\d+$/.test(value))
619
+ return null;
620
+ const revision = Number(value);
621
+ return Number.isSafeInteger(revision) && revision > 0 ? revision : null;
622
+ }
623
+ function artifactRevision(value) {
624
+ return value && /^(?:W\/)?"[\x21\x23-\x7e]{1,500}"$/.test(value)
625
+ ? value
626
+ : null;
627
+ }
628
+ function artifactMutationHeaders(revision, idempotencyKey) {
629
+ return { "if-match": revision, "idempotency-key": idempotencyKey };
630
+ }
631
+ /**
632
+ * Sliding-window pacer for API calls made during a bundle publish.
633
+ *
634
+ * VERIFIED context: publishes are throttled by a Cloudflare zone rate-limit rule
635
+ * on `/v1/*` (10 requests / 10s, keyed on `cf.colo.id` + `ip.src`), not by the
636
+ * API worker's own limiter — production `audit_events` contains zero
637
+ * `rate_limit.reject` rows while the limiter is enabled and the table is
638
+ * otherwise populated.
639
+ *
640
+ * NOT the cause: this client's own pacing. A simulation across latencies from 0
641
+ * to 1400ms shows the previous fixed-window pacer never placed more than 7
642
+ * requests in any 10s window, and the fence allows 10. Do not "fix" throughput
643
+ * here expecting the 429s to stop.
644
+ *
645
+ * The remaining explanation, unconfirmed: the budget is per source IP and is
646
+ * shared with every other `/v1/` caller behind it — the desktop app, an open
647
+ * dashboard, a second CLI session. A 400-file publish runs for many minutes, so
648
+ * the chance of overlapping some other request approaches certainty, which fits
649
+ * the observed "fails at a random file, scales with bundle size, uncorrelated
650
+ * with rate" signature. Confirming that needs a reproduction with the zone rule's
651
+ * counters observable, which the Cloudflare API does not expose per-request.
652
+ *
653
+ * The sliding window is kept because it is unconditionally the correct shape for
654
+ * pacing against a sliding limiter and costs nothing, not because it fixes the
655
+ * reported bug. `withRateLimitRetry` is what actually makes a publish survive a
656
+ * throttle, whatever the source.
657
+ *
658
+ * One pacer covers every `/v1/` call in the flow, not just the file PUTs: the
659
+ * zone rule counts the upload-session create and complete calls against the same
660
+ * budget.
661
+ */
576
662
  function createHtmlUploadPacer(deps) {
577
663
  const now = deps.now ?? Date.now;
578
664
  const sleep = deps.sleep ??
579
665
  ((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)));
580
- let windowStartedAt = now();
581
- let requests = 0;
666
+ const random = deps.random ?? Math.random;
667
+ const recent = [];
582
668
  return async () => {
583
- const elapsed = now() - windowStartedAt;
584
- if (elapsed >= HTML_UPLOAD_FILE_WINDOW_MS) {
585
- windowStartedAt = now();
586
- requests = 0;
587
- }
588
- else if (requests >= HTML_UPLOAD_FILE_PUTS_PER_WINDOW) {
589
- await sleep(HTML_UPLOAD_FILE_WINDOW_MS - elapsed);
590
- windowStartedAt = now();
591
- requests = 0;
669
+ for (;;) {
670
+ const cutoff = now() - HTML_UPLOAD_FILE_WINDOW_MS;
671
+ while (recent.length > 0 && recent[0] <= cutoff)
672
+ recent.shift();
673
+ if (recent.length < HTML_UPLOAD_FILE_PUTS_PER_WINDOW)
674
+ break;
675
+ // Wait for the oldest request to age out of the window, plus a little
676
+ // jitter so retries from separate processes do not re-align.
677
+ const wait = recent[0] - cutoff + 1 + Math.floor(random() * 250);
678
+ await sleep(wait);
592
679
  }
593
- requests += 1;
680
+ recent.push(now());
594
681
  };
595
682
  }
683
+ /**
684
+ * Retry a request that the edge or API refused for rate-limiting reasons.
685
+ *
686
+ * The CLI previously had no 429 handling at all (`grep -n "429" src/index.ts`
687
+ * returned nothing), so a single throttled request threw and discarded every file
688
+ * already uploaded in that session — and, because the artifact-create attempt had
689
+ * already been counted, burned one of ten daily attempts to learn nothing.
690
+ *
691
+ * Retries only on 429/503, which mean "not processed": the request had no effect,
692
+ * so re-sending is safe. Every mutating call in this flow also carries an
693
+ * `idempotency-key`, so a retry cannot double-apply even if the first attempt did
694
+ * land. Other 4xx failures are real and must surface immediately rather than be
695
+ * hidden behind a retry loop.
696
+ *
697
+ * `Retry-After` is honored when present, because the server knows when its window
698
+ * resets and guessing shorter just burns the budget again.
699
+ */
700
+ const RETRYABLE_STATUSES = new Set([429, 503]);
701
+ const MAX_RATE_LIMIT_RETRIES = 6;
702
+ async function withRateLimitRetry(deps, describe, attempt) {
703
+ const sleep = deps.sleep ??
704
+ ((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)));
705
+ for (let retry = 0;; retry++) {
706
+ try {
707
+ return await attempt();
708
+ }
709
+ catch (error) {
710
+ if (!(error instanceof RateLimitedError) ||
711
+ !RETRYABLE_STATUSES.has(error.status)) {
712
+ throw error;
713
+ }
714
+ if (retry >= MAX_RATE_LIMIT_RETRIES) {
715
+ throw new Error(`${describe} was rate limited ${retry + 1} times; giving up. Try again shortly.`);
716
+ }
717
+ const backoff = Math.min(30_000, 1_000 * 2 ** retry);
718
+ const wait = (error.retryAfterMs ?? backoff) +
719
+ Math.floor((deps.random ?? Math.random)() * 500);
720
+ deps.stderr(`Rate limited on ${describe}; retrying in ${Math.ceil(wait / 1000)}s (attempt ${retry + 2}).\n`);
721
+ await sleep(wait);
722
+ }
723
+ }
724
+ }
725
+ class RateLimitedError extends Error {
726
+ status;
727
+ retryAfterMs;
728
+ constructor(status, retryAfterMs) {
729
+ super(`Foleo API error: HTTP ${status}`);
730
+ this.status = status;
731
+ this.retryAfterMs = retryAfterMs;
732
+ this.name = "RateLimitedError";
733
+ }
734
+ }
735
+ /** `Retry-After` is seconds or an HTTP-date; both are valid per RFC 9110. */
736
+ function retryAfterMs(header, now) {
737
+ if (header === null)
738
+ return null;
739
+ const seconds = Number(header.trim());
740
+ if (Number.isFinite(seconds) && seconds >= 0)
741
+ return seconds * 1_000;
742
+ const at = Date.parse(header);
743
+ return Number.isFinite(at) ? Math.max(0, at - now) : null;
744
+ }
596
745
  export async function scanBundle(root, deps) {
597
746
  const base = resolve(root);
598
747
  const realBase = deps.readFileBytes ? base : await realpath(base);
@@ -601,6 +750,7 @@ export async function scanBundle(root, deps) {
601
750
  const bytesFor = deps.readFileBytes ??
602
751
  ((path) => boundedReadFileBytes(path, HTML_BUNDLE_MAX_FILE_BYTES, realBase));
603
752
  const files = [];
753
+ const unsupported = [];
604
754
  let fileCount = 0;
605
755
  let totalBytes = 0;
606
756
  async function walk(dir) {
@@ -637,8 +787,14 @@ export async function scanBundle(root, deps) {
637
787
  if (fileCount + 1 > HTML_BUNDLE_MAX_FILES)
638
788
  throw new Error("Bundle exceeds Foleo limits");
639
789
  const mediaType = mediaTypeFor(path);
640
- if (!mediaType)
641
- throw new Error(`Unsupported bundle file: ${path}`);
790
+ // Collect every unsupported path and report them together after the walk.
791
+ // Failing on the first one turned a Next/Astro export with three stray file
792
+ // types into three separate publish attempts, each burning a daily
793
+ // create-attempt quota slot to learn one more filename.
794
+ if (!mediaType) {
795
+ unsupported.push(path);
796
+ continue;
797
+ }
642
798
  const bytes = await bytesFor(absolute);
643
799
  if (mediaType === "text/html; charset=utf-8" &&
644
800
  (bytes.byteLength > HTML_BUNDLE_MAX_HTML_BYTES || !isValidUtf8(bytes)))
@@ -658,6 +814,11 @@ export async function scanBundle(root, deps) {
658
814
  }
659
815
  }
660
816
  await walk(base);
817
+ if (unsupported.length > 0) {
818
+ const shown = unsupported.slice(0, 10).join(", ");
819
+ const rest = unsupported.length > 10 ? ` (+${unsupported.length - 10} more)` : "";
820
+ throw new Error(`Unsupported bundle file${unsupported.length > 1 ? "s" : ""}: ${shown}${rest}`);
821
+ }
661
822
  if (!files.some((file) => file.path === "/index.html"))
662
823
  throw new Error("Bundle root must contain index.html");
663
824
  const htmlFiles = files.filter((file) => file.mediaType === "text/html; charset=utf-8");
@@ -685,8 +846,16 @@ function isValidUtf8(bytes) {
685
846
  return false;
686
847
  }
687
848
  }
849
+ // Mirrors infra/publish/src/html-artifacts.ts MEDIA_TYPES, which is the server
850
+ // allowlist and the source of truth. scripts/media-type-allowlist.test.mjs fails
851
+ // if they diverge. Extension is taken from the last path segment so extensionless
852
+ // files (`/LICENSE`, `/_headers`) do not resolve a bogus single-character type.
688
853
  function mediaTypeFor(path) {
689
- const extension = path.slice(path.lastIndexOf(".")).toLowerCase();
854
+ const segment = path.slice(path.lastIndexOf("/") + 1);
855
+ const dot = segment.lastIndexOf(".");
856
+ if (dot <= 0)
857
+ return null;
858
+ const extension = segment.slice(dot).toLowerCase();
690
859
  return ({
691
860
  ".html": "text/html; charset=utf-8",
692
861
  ".htm": "text/html; charset=utf-8",
@@ -694,6 +863,11 @@ function mediaTypeFor(path) {
694
863
  ".js": "text/javascript; charset=utf-8",
695
864
  ".mjs": "text/javascript; charset=utf-8",
696
865
  ".json": "application/json",
866
+ ".map": "application/json",
867
+ ".webmanifest": "application/manifest+json",
868
+ ".txt": "text/plain; charset=utf-8",
869
+ ".xml": "application/xml",
870
+ ".vtt": "text/vtt",
697
871
  ".wasm": "application/wasm",
698
872
  ".svg": "image/svg+xml",
699
873
  ".png": "image/png",
@@ -761,6 +935,7 @@ async function publish(args, deps) {
761
935
  method: "POST",
762
936
  body: {
763
937
  markdown,
938
+ source: publishSourcePayload(sha256Utf8(markdown)),
764
939
  ...(parsed.title ? { title: parsed.title } : {}),
765
940
  ...(assets
766
941
  ? { uploadId: assets.uploadId, manifestHash: assets.manifestHash }
@@ -781,11 +956,13 @@ async function update(args, deps) {
781
956
  }
782
957
  const markdown = await deps.readFile(file, "utf8");
783
958
  const assets = await uploadMarkdownAssets(file, markdown, deps);
959
+ const sourceId = await ownerArtifactSourceId(deps, id);
784
960
  const result = await requestJson(deps, `/docs/${encodeURIComponent(id)}`, {
785
961
  method: "PUT",
786
962
  body: {
787
963
  markdown,
788
964
  version: parsed.version,
965
+ source: publishSourcePayload(sha256Utf8(markdown), sourceId),
789
966
  ...(assets
790
967
  ? { uploadId: assets.uploadId, manifestHash: assets.manifestHash }
791
968
  : {}),
@@ -917,40 +1094,108 @@ async function uploadMarkdownAssets(markdownPath, markdown, deps) {
917
1094
  },
918
1095
  headers: { "idempotency-key": randomUUID() },
919
1096
  });
920
- const beforeFilePut = createHtmlUploadPacer(deps);
1097
+ // Same pacing and retry contract as the HTML bundle path: this loop hits the
1098
+ // same /v1/ fence and previously discarded the whole upload on one 429.
1099
+ const pace = createHtmlUploadPacer(deps);
921
1100
  for (const plan of upload.files) {
922
1101
  const file = files.find((candidate) => candidate.path === plan.path);
923
1102
  if (!file)
924
1103
  throw new Error("Server returned an unexpected upload file");
925
- await beforeFilePut();
926
- await requestRaw(deps, `/uploads/${upload.uploadId}/files/${plan.fileToken}`, file.bytes, { "content-length": String(file.byteSize) });
1104
+ await pace();
1105
+ await withRateLimitRetry(deps, `uploading ${plan.path}`, () => requestRaw(deps, `/uploads/${upload.uploadId}/files/${plan.fileToken}`, file.bytes, { "content-length": String(file.byteSize) }));
927
1106
  }
928
- await requestJson(deps, `/uploads/${upload.uploadId}/complete`, {
1107
+ const completeKey = randomUUID();
1108
+ await pace();
1109
+ await withRateLimitRetry(deps, "finishing the upload", () => requestJson(deps, `/uploads/${upload.uploadId}/complete`, {
929
1110
  method: "POST",
930
1111
  body: {},
931
- headers: { "idempotency-key": randomUUID() },
932
- });
1112
+ headers: { "idempotency-key": completeKey },
1113
+ }));
933
1114
  return { uploadId: upload.uploadId, manifestHash: upload.manifestHash };
934
1115
  }
935
1116
  async function unpublish(args, deps) {
936
1117
  const parsed = parseFlags(args);
937
1118
  const id = parsed.positionals[0];
938
- if (!id || parsed.positionals.length !== 1)
939
- throw new Error("Usage: foleo unpublish <id> [--json]");
940
- const result = await requestJson(deps, `/docs/${encodeURIComponent(id)}/unpublish`, {
1119
+ const revision = artifactRevision(parsed.revision);
1120
+ if (!id || parsed.positionals.length !== 1 || revision === null)
1121
+ throw new Error("Usage: foleo unpublish <id> --revision <etag> [--json]");
1122
+ const idempotencyKey = randomUUID();
1123
+ const result = await withRateLimitRetry(deps, "unpublishing the artifact", () => requestJson(deps, `/artifacts/${encodeURIComponent(id)}/unpublish`, {
941
1124
  method: "POST",
942
- body: {},
943
- });
1125
+ body: undefined,
1126
+ headers: artifactMutationHeaders(revision, idempotencyKey),
1127
+ }));
944
1128
  writeResult(deps, result, parsed.json);
945
1129
  return 0;
946
1130
  }
1131
+ async function deleteArtifact(args, deps) {
1132
+ const parsed = parseFlags(args);
1133
+ const id = parsed.positionals[0];
1134
+ const revision = artifactRevision(parsed.revision);
1135
+ if (!id || parsed.positionals.length !== 1 || revision === null) {
1136
+ throw new Error("Usage: foleo delete <id> --revision <etag> [--json]");
1137
+ }
1138
+ const idempotencyKey = randomUUID();
1139
+ const result = await withRateLimitRetry(deps, "deleting the artifact", () => requestJson(deps, `/artifacts/${encodeURIComponent(id)}`, {
1140
+ method: "DELETE",
1141
+ body: undefined,
1142
+ headers: artifactMutationHeaders(revision, idempotencyKey),
1143
+ }));
1144
+ writeDeletionResult(deps, result, parsed.json);
1145
+ return 0;
1146
+ }
1147
+ async function restoreArtifact(args, deps) {
1148
+ const parsed = parseFlags(args);
1149
+ const id = parsed.positionals[0];
1150
+ const revision = artifactRevision(parsed.revision);
1151
+ if (!id || parsed.positionals.length !== 1 || revision === null) {
1152
+ throw new Error("Usage: foleo restore <id> --revision <etag> [--json]");
1153
+ }
1154
+ const idempotencyKey = randomUUID();
1155
+ const result = await withRateLimitRetry(deps, "restoring the artifact", () => requestJson(deps, `/artifacts/${encodeURIComponent(id)}/restore`, {
1156
+ method: "POST",
1157
+ body: undefined,
1158
+ headers: artifactMutationHeaders(revision, idempotencyKey),
1159
+ }));
1160
+ writeDeletionResult(deps, result, parsed.json);
1161
+ return 0;
1162
+ }
1163
+ async function purgeArtifact(args, deps) {
1164
+ const parsed = parseFlags(args);
1165
+ const id = parsed.positionals[0];
1166
+ const revision = artifactRevision(parsed.revision);
1167
+ if (!id ||
1168
+ parsed.positionals.length !== 1 ||
1169
+ revision === null ||
1170
+ parsed.confirm !== id) {
1171
+ throw new Error("Usage: foleo purge <id> --revision <etag> --confirm <id> [--json]");
1172
+ }
1173
+ const idempotencyKey = randomUUID();
1174
+ const result = await withRateLimitRetry(deps, "starting permanent deletion", () => requestJson(deps, `/artifacts/${encodeURIComponent(id)}/purge`, {
1175
+ method: "POST",
1176
+ body: { confirmArtifactId: id },
1177
+ headers: artifactMutationHeaders(revision, idempotencyKey),
1178
+ }));
1179
+ writeDeletionResult(deps, result, parsed.json);
1180
+ return 0;
1181
+ }
1182
+ async function deletionStatus(args, deps) {
1183
+ const parsed = parseFlags(args);
1184
+ const id = parsed.positionals[0];
1185
+ if (!id || parsed.positionals.length !== 1) {
1186
+ throw new Error("Usage: foleo deletion-status <id> [--json]");
1187
+ }
1188
+ const result = await requestJson(deps, `/artifacts/${encodeURIComponent(id)}/deletion`, { method: "GET", body: undefined });
1189
+ writeDeletionResult(deps, result, parsed.json);
1190
+ return 0;
1191
+ }
947
1192
  async function status(args, deps) {
948
1193
  const parsed = parseFlags(args);
949
1194
  const id = parsed.positionals[0];
950
1195
  if (!id || parsed.positionals.length !== 1) {
951
1196
  throw new Error("Usage: foleo status <id> [--json]");
952
1197
  }
953
- const result = await requestJson(deps, `/docs/${encodeURIComponent(id)}`, {
1198
+ const result = await requestJson(deps, `/artifacts/${encodeURIComponent(id)}`, {
954
1199
  method: "GET",
955
1200
  body: undefined,
956
1201
  });
@@ -959,54 +1204,63 @@ async function status(args, deps) {
959
1204
  }
960
1205
  async function list(args, deps) {
961
1206
  const parsed = parseFlags(args);
1207
+ const legacyFormat = parsed.kind === "docs"
1208
+ ? "markdown"
1209
+ : parsed.kind === "html"
1210
+ ? "html"
1211
+ : null;
1212
+ const kind = parsed.kind === "all" ? undefined : parsed.kind;
962
1213
  if (parsed.positionals.length > 0 ||
963
- !["all", "docs", "html"].includes(parsed.kind ?? "all")) {
964
- throw new Error("Usage: foleo list [--kind all|docs|html] [--limit <n>] [--json]");
1214
+ (kind !== undefined &&
1215
+ legacyFormat === null &&
1216
+ ![
1217
+ "document",
1218
+ "site",
1219
+ "dataset",
1220
+ "diagram",
1221
+ "media",
1222
+ "collection",
1223
+ ].includes(kind)) ||
1224
+ (parsed.format !== undefined &&
1225
+ ![
1226
+ "markdown",
1227
+ "html",
1228
+ "csv",
1229
+ "tsv",
1230
+ "mermaid",
1231
+ "svg",
1232
+ "png",
1233
+ "jpeg",
1234
+ ].includes(parsed.format)) ||
1235
+ (parsed.runtime !== undefined &&
1236
+ !["inert", "rendered", "active"].includes(parsed.runtime))) {
1237
+ throw new Error("Usage: foleo list [--kind <kind>] [--format <format>] [--runtime <class>] [--limit <n>] [--json]");
1238
+ }
1239
+ if (legacyFormat) {
1240
+ deps.stderr(`Deprecated: --kind ${parsed.kind} means --format ${legacyFormat}; use --format going forward.\n`);
965
1241
  }
966
1242
  const credential = await resolveCredentialWithSource(deps);
967
1243
  if (!credential)
968
1244
  throw new Error("No Foleo credential found. Run `npx -y @foleo/cli login` or set FOLEO_TOKEN.");
969
- const kind = parsed.kind ?? "all";
970
- const [docsResult, htmlResult] = await Promise.all([
971
- kind === "html"
972
- ? Promise.resolve(null)
973
- : requestJsonWithToken(deps, "/docs", credential.token, { method: "GET", body: undefined }),
974
- kind === "docs"
975
- ? Promise.resolve(null)
976
- : requestJsonWithToken(deps, "/artifacts/html", credential.token, { method: "GET", body: undefined }).catch((error) => {
977
- if (error instanceof ApiRequestError &&
978
- error.status === 404 &&
979
- kind === "all")
980
- return null;
981
- throw error;
982
- }),
983
- ]);
984
- const docs = docsResult && Array.isArray(docsResult.docs) ? docsResult.docs : [];
985
- const html = htmlResult && Array.isArray(htmlResult.artifacts)
986
- ? htmlResult.artifacts
987
- : [];
988
- const allItems = [
989
- ...docs.map((item) => ({
990
- ...(isRecord(item) ? item : { value: item }),
991
- kind: "doc",
992
- })),
993
- ...html.map((item) => ({
994
- ...(isRecord(item) ? item : { value: item }),
995
- kind: "html",
996
- })),
997
- ];
998
- const items = parsed.limit === undefined ? allItems : allItems.slice(0, parsed.limit);
999
- const truncated = docs.length === 500 ? { docs: true } : undefined;
1000
- const result = {
1001
- items,
1002
- ...(truncated ? { truncated } : {}),
1245
+ const query = new URLSearchParams();
1246
+ if (kind && legacyFormat === null)
1247
+ query.set("kind", kind);
1248
+ if (parsed.format ?? legacyFormat) {
1249
+ query.set("format", parsed.format ?? legacyFormat);
1250
+ }
1251
+ if (parsed.runtime)
1252
+ query.set("runtime", parsed.runtime);
1253
+ if (parsed.limit !== undefined)
1254
+ query.set("limit", String(parsed.limit));
1255
+ const response = await requestJsonWithToken(deps, `/artifacts${query.size > 0 ? `?${query.toString()}` : ""}`, credential.token, { method: "GET", body: undefined });
1256
+ const items = Array.isArray(response.artifacts) ? response.artifacts : [];
1257
+ const output = {
1258
+ artifacts: items,
1259
+ nextCursor: typeof response.nextCursor === "string" ? response.nextCursor : null,
1003
1260
  credentialSource: credential.source,
1004
- ...(kind === "all" && htmlResult === null
1005
- ? { unavailable: { html: true } }
1006
- : {}),
1007
1261
  };
1008
1262
  if (parsed.json) {
1009
- deps.stdout(`${JSON.stringify(result, null, 2)}\n`);
1263
+ deps.stdout(`${JSON.stringify(output, null, 2)}\n`);
1010
1264
  return 0;
1011
1265
  }
1012
1266
  if (items.length === 0) {
@@ -1015,10 +1269,6 @@ async function list(args, deps) {
1015
1269
  }
1016
1270
  for (const item of items)
1017
1271
  deps.stdout(`${artifactLine(item)}\n`);
1018
- if (truncated)
1019
- deps.stderr("Warning: Markdown results reached the 500-item server limit and may be incomplete.\n");
1020
- if (kind === "all" && htmlResult === null)
1021
- deps.stderr("Note: HTML publishing is unavailable for this account; Markdown results are shown.\n");
1022
1272
  return 0;
1023
1273
  }
1024
1274
  async function whoami(args, deps) {
@@ -1070,6 +1320,12 @@ async function requestJsonWithToken(deps, path, token, init) {
1070
1320
  ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),
1071
1321
  });
1072
1322
  const body = await response.json().catch(() => null);
1323
+ if (RETRYABLE_STATUSES.has(response.status)) {
1324
+ // Thrown ahead of ApiRequestError so `withRateLimitRetry` can act on it. The
1325
+ // zone fence in front of this API answers with a Cloudflare error page rather
1326
+ // than the API's JSON envelope, so the status is the only reliable signal.
1327
+ throw new RateLimitedError(response.status, retryAfterMs(response.headers.get("retry-after"), (deps.now ?? Date.now)()));
1328
+ }
1073
1329
  if (!response.ok) {
1074
1330
  const code = body !== null &&
1075
1331
  typeof body === "object" &&
@@ -1114,6 +1370,9 @@ async function requestRaw(deps, path, body, headers) {
1114
1370
  headers: { authorization: `Bearer ${credential.token}`, ...headers },
1115
1371
  body: bytes,
1116
1372
  });
1373
+ if (RETRYABLE_STATUSES.has(response.status)) {
1374
+ throw new RateLimitedError(response.status, retryAfterMs(response.headers.get("retry-after"), (deps.now ?? Date.now)()));
1375
+ }
1117
1376
  if (!response.ok)
1118
1377
  throw new Error(`Foleo API error: HTTP ${response.status}`);
1119
1378
  }
@@ -1315,6 +1574,35 @@ function callbackHeaders(contentType) {
1315
1574
  function loopbackSuccessBody() {
1316
1575
  return `<!doctype html><meta charset="utf-8"><title>Foleo sign-in complete</title><p><a href="${FOLEO_LOGIN_SUCCESS_URL}">Continue</a></p>`;
1317
1576
  }
1577
+ function sha256Utf8(value) {
1578
+ return createHash("sha256").update(value, "utf8").digest("hex");
1579
+ }
1580
+ function publishSourcePayload(contentHash, sourceId) {
1581
+ return {
1582
+ provider: "local",
1583
+ contentHash,
1584
+ ...(sourceId ? { id: sourceId } : {}),
1585
+ };
1586
+ }
1587
+ async function ownerArtifactSourceId(deps, id) {
1588
+ try {
1589
+ const result = await requestJson(deps, `/artifacts/${encodeURIComponent(id)}`, {
1590
+ method: "GET",
1591
+ body: undefined,
1592
+ });
1593
+ if (!isRecord(result))
1594
+ return undefined;
1595
+ const artifact = isRecord(result.artifact) ? result.artifact : result;
1596
+ const source = isRecord(artifact.source) ? artifact.source : null;
1597
+ return typeof source?.id === "string" && source.id.length > 0
1598
+ ? source.id
1599
+ : undefined;
1600
+ }
1601
+ catch {
1602
+ // Old servers or a missing catalog field: still send the hash without an id.
1603
+ return undefined;
1604
+ }
1605
+ }
1318
1606
  function isRecord(value) {
1319
1607
  return value !== null && typeof value === "object" && !Array.isArray(value);
1320
1608
  }
@@ -1326,13 +1614,25 @@ function stringField(value, field) {
1326
1614
  : null;
1327
1615
  }
1328
1616
  function artifactLine(artifact) {
1329
- const kind = stringField(artifact, "kind") ?? "-";
1617
+ const kind = stringField(artifact, "artifactKind") ??
1618
+ stringField(artifact, "kind") ??
1619
+ "-";
1620
+ const format = stringField(artifact, "sourceFormat");
1621
+ const runtime = stringField(artifact, "runtimeClass");
1622
+ const descriptor = [kind, format, runtime].filter(Boolean).join("/");
1330
1623
  const id = stringField(artifact, "id") ?? "-";
1331
1624
  const url = stringField(artifact, "url") ?? "-";
1332
1625
  const status = stringField(artifact, "status") ?? "-";
1333
1626
  const visibility = stringField(artifact, "visibility") ?? "-";
1334
1627
  const title = stringField(artifact, "title");
1335
- return [kind, id, url, status, visibility, ...(title ? [title] : [])].join(" ");
1628
+ return [
1629
+ descriptor,
1630
+ id,
1631
+ url,
1632
+ status,
1633
+ visibility,
1634
+ ...(title ? [title] : []),
1635
+ ].join(" ");
1336
1636
  }
1337
1637
  function nestedRecord(value, field) {
1338
1638
  return isRecord(value) && isRecord(value[field]) ? value[field] : null;
@@ -1391,32 +1691,71 @@ function writeStatusResult(deps, result, json) {
1391
1691
  writeResult(deps, result, false);
1392
1692
  return;
1393
1693
  }
1694
+ const statusRecord = nestedRecord(result, "artifact") ?? result;
1394
1695
  const lines = [
1395
- `ID: ${stringField(result, "id") ?? "-"}`,
1396
- `URL: ${stringField(result, "url") ?? "-"}`,
1397
- `Status: ${stringField(result, "status") ?? "-"}`,
1398
- `Visibility: ${stringField(result, "visibility") ?? "-"}`,
1696
+ `ID: ${stringField(statusRecord, "id") ?? "-"}`,
1697
+ `URL: ${stringField(statusRecord, "url") ?? "-"}`,
1698
+ `Status: ${stringField(statusRecord, "status") ?? "-"}`,
1699
+ `Visibility: ${stringField(statusRecord, "visibility") ?? "-"}`,
1399
1700
  ];
1400
- if (typeof result.version === "number")
1401
- lines.push(`Version: ${result.version}`);
1402
- if (typeof result.stateRevision === "number")
1403
- lines.push(`State revision: ${result.stateRevision}`);
1404
- const title = stringField(result, "title");
1701
+ if (typeof statusRecord.version === "number")
1702
+ lines.push(`Version: ${statusRecord.version}`);
1703
+ if (typeof statusRecord.stateRevision === "number")
1704
+ lines.push(`State revision: ${statusRecord.stateRevision}`);
1705
+ const revision = stringField(statusRecord, "etag");
1706
+ if (revision)
1707
+ lines.push(`Revision: ${revision}`);
1708
+ const title = stringField(statusRecord, "title");
1405
1709
  if (title)
1406
1710
  lines.push(`Title: ${title}`);
1407
1711
  deps.stdout(`${lines.join("\n")}\n`);
1408
1712
  }
1409
- function parseFlags(args) {
1713
+ function writeDeletionResult(deps, result, json) {
1714
+ if (json) {
1715
+ writeResult(deps, result, true);
1716
+ return;
1717
+ }
1718
+ const operation = nestedRecord(result, "operation");
1719
+ if (!operation) {
1720
+ writeResult(deps, result, false);
1721
+ return;
1722
+ }
1723
+ const state = stringField(operation, "state") ?? "unknown";
1724
+ const lines = [
1725
+ `Operation: ${stringField(operation, "operationId") ?? "-"}`,
1726
+ `Artifact: ${stringField(operation, "artifactId") ?? "-"}`,
1727
+ `State: ${state}`,
1728
+ ];
1729
+ const purgeAfter = stringField(operation, "purgeAfter");
1730
+ if (purgeAfter)
1731
+ lines.push(`Purge after: ${purgeAfter}`);
1732
+ if (state === "complete") {
1733
+ lines.push("Foleo-held bytes are confirmed erased.");
1734
+ }
1735
+ else if (state === "restored") {
1736
+ lines.push("Artifact restored as unpublished.");
1737
+ }
1738
+ else {
1739
+ lines.push("Foleo-held bytes are not yet confirmed erased.");
1740
+ }
1741
+ deps.stdout(`${lines.join("\n")}\n`);
1742
+ }
1743
+ function parseFlags(args, options = {}) {
1410
1744
  const positionals = [];
1411
1745
  let json = false;
1412
1746
  let title;
1413
1747
  let version;
1414
1748
  let revision;
1749
+ let confirm;
1415
1750
  let kind;
1751
+ let format;
1752
+ let runtime;
1416
1753
  let set;
1417
1754
  let password;
1418
1755
  let limit;
1419
1756
  let acceptHostingRisk = false;
1757
+ let allowDelete = false;
1758
+ let allowPurge = false;
1420
1759
  for (let i = 0; i < args.length; i++) {
1421
1760
  const arg = args[i];
1422
1761
  if (arg === "--json") {
@@ -1439,10 +1778,15 @@ function parseFlags(args) {
1439
1778
  }
1440
1779
  if (arg === "--revision") {
1441
1780
  const raw = args[++i];
1442
- const parsed = raw === undefined ? Number.NaN : Number(raw);
1443
- if (!Number.isInteger(parsed))
1444
- throw new Error("--revision requires an integer");
1445
- revision = parsed;
1781
+ if (!raw)
1782
+ throw new Error("--revision requires a value");
1783
+ revision = raw;
1784
+ continue;
1785
+ }
1786
+ if (arg === "--confirm") {
1787
+ confirm = args[++i];
1788
+ if (!confirm)
1789
+ throw new Error("--confirm requires a value");
1446
1790
  continue;
1447
1791
  }
1448
1792
  if (arg === "--kind") {
@@ -1451,6 +1795,18 @@ function parseFlags(args) {
1451
1795
  throw new Error("--kind requires a value");
1452
1796
  continue;
1453
1797
  }
1798
+ if (arg === "--format") {
1799
+ format = args[++i];
1800
+ if (!format)
1801
+ throw new Error("--format requires a value");
1802
+ continue;
1803
+ }
1804
+ if (arg === "--runtime") {
1805
+ runtime = args[++i];
1806
+ if (!runtime)
1807
+ throw new Error("--runtime requires a value");
1808
+ continue;
1809
+ }
1454
1810
  if (arg === "--set") {
1455
1811
  set = args[++i];
1456
1812
  if (!set)
@@ -1475,6 +1831,18 @@ function parseFlags(args) {
1475
1831
  acceptHostingRisk = true;
1476
1832
  continue;
1477
1833
  }
1834
+ if (arg === "--allow-delete") {
1835
+ if (!options.allowLoginScopeFlags)
1836
+ throw new Error("--allow-delete is valid only with login");
1837
+ allowDelete = true;
1838
+ continue;
1839
+ }
1840
+ if (arg === "--allow-purge") {
1841
+ if (!options.allowLoginScopeFlags)
1842
+ throw new Error("--allow-purge is valid only with login");
1843
+ allowPurge = true;
1844
+ continue;
1845
+ }
1478
1846
  if (arg.startsWith("-"))
1479
1847
  throw new Error(`Unknown option: ${arg}`);
1480
1848
  positionals.push(arg);
@@ -1485,11 +1853,16 @@ function parseFlags(args) {
1485
1853
  ...(title !== undefined ? { title } : {}),
1486
1854
  ...(version !== undefined ? { version } : {}),
1487
1855
  ...(revision !== undefined ? { revision } : {}),
1856
+ ...(confirm !== undefined ? { confirm } : {}),
1488
1857
  ...(kind !== undefined ? { kind } : {}),
1858
+ ...(format !== undefined ? { format } : {}),
1859
+ ...(runtime !== undefined ? { runtime } : {}),
1489
1860
  ...(set !== undefined ? { set } : {}),
1490
1861
  ...(password !== undefined ? { password } : {}),
1491
1862
  ...(limit !== undefined ? { limit } : {}),
1492
1863
  acceptHostingRisk,
1864
+ allowDelete,
1865
+ allowPurge,
1493
1866
  };
1494
1867
  }
1495
1868
  function parseGlobalFlags(argv) {
@@ -1505,17 +1878,22 @@ function parseGlobalFlags(argv) {
1505
1878
  function help() {
1506
1879
  return [
1507
1880
  "Usage:",
1508
- " foleo login [--json]",
1881
+ " foleo login [--allow-delete] [--allow-purge] [--json]",
1509
1882
  " foleo whoami [--json]",
1510
1883
  " foleo doctor [--json]",
1511
1884
  " foleo skill get|path",
1512
1885
  " foleo --version [--json]",
1513
1886
  " foleo environment [--json]",
1514
- " foleo list [--kind all|docs|html] [--limit <n>] [--json]",
1887
+ " foleo list [--kind <kind>] [--format <format>] [--runtime <class>] [--limit <n>] [--json]",
1888
+ " foleo get <id> [--json]",
1515
1889
  " foleo publish <file> [--title <title>] [--json]",
1516
1890
  " foleo update <id> <file> --version <version> [--json]",
1517
1891
  " foleo status <id> [--json]",
1518
- " foleo unpublish <id> [--json]",
1892
+ " foleo unpublish <id> --revision <etag> [--json]",
1893
+ " foleo delete <id> --revision <etag> [--json]",
1894
+ " foleo restore <id> --revision <etag> [--json]",
1895
+ " foleo purge <id> --revision <etag> --confirm <id> [--json]",
1896
+ " foleo deletion-status <id> [--json]",
1519
1897
  " foleo html-publish <bundle-root> --accept-hosting-risk [--json]",
1520
1898
  " foleo html-update <id> <bundle-root> --revision <stateRevision> [--json]",
1521
1899
  " foleo html-status <id> [--json]",