@phnx-labs/artifacts-cli 0.8.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,8 +5,8 @@
5
5
  // injects og:image / twitter:card meta, so the link unfurls into a preview card in
6
6
  // Slack / iMessage / Twitter / Discord. The cover is best-effort: if no headless
7
7
  // browser is available it's skipped and the plain link still publishes.
8
- import { readFileSync } from 'node:fs';
9
- import { basename } from 'node:path';
8
+ import { closeSync, createReadStream, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmdirSync, rmSync, statSync, writeFileSync, } from 'node:fs';
9
+ import { basename, dirname, join, resolve } from 'node:path';
10
10
  import { execFileSync } from 'node:child_process';
11
11
  import { hostname as osHostname } from 'node:os';
12
12
  import { createHash, randomBytes } from 'node:crypto';
@@ -21,6 +21,7 @@ import { PUBLISH_VISIBILITY_LEVELS as MODEL_PUBLISH_VISIBILITY_LEVELS, EDITABLE_
21
21
  import { injectAnalyticsBeacon } from './analytics.js';
22
22
  import { prepareShareHtml } from './html.js';
23
23
  import { injectShareQr, stripShareQr } from './qr.js';
24
+ import { stateDir } from '../config.js';
24
25
  /** Read the Worker's `x-collab-registered` / `x-collab-error` response headers. */
25
26
  export function readCollabRegistration(headers) {
26
27
  const registered = headers.get('x-collab-registered');
@@ -116,6 +117,11 @@ export const RESERVED_META_KEYS = [
116
117
  'og-source-etag',
117
118
  'comment-policy',
118
119
  'body-revision',
120
+ 'media',
121
+ 'media-error',
122
+ 'media-job',
123
+ 'media-derived',
124
+ 'media-source',
119
125
  ];
120
126
  const META_KEY_RE = /^[a-z0-9-]{1,64}$/;
121
127
  /**
@@ -169,7 +175,7 @@ export function resolveShareAvatar(opts = {}) {
169
175
  * the provenance the CLI sets automatically, plus label/label-source) — throws
170
176
  * naming the offending pair on any violation.
171
177
  */
172
- export function parseMetaEntries(pairs) {
178
+ function parseMetaPairs(pairs, filter) {
173
179
  const meta = {};
174
180
  for (const pair of pairs) {
175
181
  const eq = pair.indexOf('=');
@@ -178,7 +184,7 @@ export function parseMetaEntries(pairs) {
178
184
  }
179
185
  const key = pair.slice(0, eq).trim();
180
186
  const value = pair.slice(eq + 1);
181
- if (RESERVED_META_KEYS.includes(key)) {
187
+ if (RESERVED_META_KEYS.includes(key) && !(filter && key === 'media')) {
182
188
  throw new Error(`--meta ${key}=… is reserved (Worker-stamped, or set automatically from your session/git) — pass a different key.`);
183
189
  }
184
190
  if (!META_KEY_RE.test(key)) {
@@ -188,6 +194,13 @@ export function parseMetaEntries(pairs) {
188
194
  }
189
195
  return meta;
190
196
  }
197
+ export function parseMetaEntries(pairs) {
198
+ return parseMetaPairs(pairs, false);
199
+ }
200
+ /** Parse list filters; the Worker-owned media state is queryable but not writable. */
201
+ export function parseMetaFilterEntries(pairs) {
202
+ return parseMetaPairs(pairs, true);
203
+ }
191
204
  /** S3's `x-amz-meta` convention caps user metadata around 2KB; R2 publishes no
192
205
  * hard limit of its own, so stay under that ceiling to keep a share portable to
193
206
  * an S3-compatible mirror. Checked over the FULL customMetadata payload
@@ -566,6 +579,123 @@ export function buildShareKey(username, slugPart) {
566
579
  throw new Error('Share slug is empty.');
567
580
  return `${user}/${part}`;
568
581
  }
582
+ /** The managed Worker's single-request limit and the client-side multipart size. */
583
+ const SHARE_SINGLE_PUT_MAX_BYTES = 20 * 1024 * 1024;
584
+ const SHARE_MULTIPART_PART_BYTES = 50 * 1024 * 1024;
585
+ async function sha256File(filePath) {
586
+ const hash = createHash('sha256');
587
+ for await (const chunk of createReadStream(filePath))
588
+ hash.update(chunk);
589
+ return hash.digest('hex');
590
+ }
591
+ function validateMultipartState(parsed, file) {
592
+ const state = parsed;
593
+ if (!state ||
594
+ typeof state.uploadId !== 'string' ||
595
+ !state.uploadId ||
596
+ typeof state.path !== 'string' ||
597
+ !state.path ||
598
+ !Array.isArray(state.completedParts) ||
599
+ (state.totalSize !== undefined && (!Number.isSafeInteger(state.totalSize) || state.totalSize <= 0)) ||
600
+ (state.baseUrl !== undefined && typeof state.baseUrl !== 'string') ||
601
+ (state.createFingerprint !== undefined &&
602
+ (typeof state.createFingerprint !== 'string' || !/^[a-f0-9]{64}$/.test(state.createFingerprint))) ||
603
+ (state.expireSpec !== undefined && typeof state.expireSpec !== 'string') ||
604
+ (state.expiresAt !== undefined &&
605
+ (typeof state.expiresAt !== 'string' || Number.isNaN(Date.parse(state.expiresAt)))) ||
606
+ state.completedParts.some((part) => !part ||
607
+ !Number.isSafeInteger(part.partNumber) ||
608
+ part.partNumber < 1 ||
609
+ typeof part.etag !== 'string' ||
610
+ !part.etag) ||
611
+ new Set(state.completedParts.map((part) => part.partNumber)).size !== state.completedParts.length) {
612
+ throw new Error(`Corrupt resumable upload state at ${file}: unexpected shape`);
613
+ }
614
+ return state;
615
+ }
616
+ function readMultipartState(file) {
617
+ if (!existsSync(file))
618
+ return undefined;
619
+ let parsed;
620
+ try {
621
+ parsed = JSON.parse(readFileSync(file, 'utf8'));
622
+ }
623
+ catch (error) {
624
+ throw new Error(`Corrupt resumable upload state at ${file}: ${error.message}`);
625
+ }
626
+ return validateMultipartState(parsed, file);
627
+ }
628
+ function writeMultipartJson(file, value) {
629
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
630
+ const tmp = join(dirname(file), `.${basename(file)}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`);
631
+ const fd = openSync(tmp, 'wx', 0o600);
632
+ try {
633
+ writeFileSync(fd, `${JSON.stringify(value, null, 2)}\n`);
634
+ fsyncSync(fd);
635
+ }
636
+ finally {
637
+ closeSync(fd);
638
+ }
639
+ renameSync(tmp, file);
640
+ }
641
+ function writeMultipartState(file, state) {
642
+ writeMultipartJson(file, state);
643
+ }
644
+ function multipartPathIndexFile(uploadRoot, sourcePath) {
645
+ const pathDigest = createHash('sha256').update(sourcePath).digest('hex');
646
+ return join(uploadRoot, '.paths', `${pathDigest}.json`);
647
+ }
648
+ function readMultipartPathIndex(file, sourcePath) {
649
+ if (!existsSync(file))
650
+ return undefined;
651
+ let parsed;
652
+ try {
653
+ parsed = JSON.parse(readFileSync(file, 'utf8'));
654
+ }
655
+ catch (error) {
656
+ throw new Error(`Corrupt resumable upload path index at ${file}: ${error.message}`);
657
+ }
658
+ const index = parsed;
659
+ if (!index ||
660
+ index.sourcePath !== sourcePath ||
661
+ typeof index.digest !== 'string' ||
662
+ !/^[a-f0-9]{64}$/.test(index.digest) ||
663
+ !index.state) {
664
+ throw new Error(`Corrupt resumable upload path index at ${file}: unexpected shape`);
665
+ }
666
+ return { ...index, state: validateMultipartState(index.state, `${file} (embedded state)`) };
667
+ }
668
+ function writeMultipartPathIndex(file, index) {
669
+ writeMultipartJson(file, index);
670
+ }
671
+ function removeMultipartPathIndex(file) {
672
+ rmSync(file, { force: true });
673
+ try {
674
+ rmdirSync(dirname(file));
675
+ }
676
+ catch {
677
+ // Another active source-path index still owns the directory.
678
+ }
679
+ }
680
+ function multipartUrl(pageUrl, action, params = {}) {
681
+ const url = new URL(pageUrl);
682
+ url.searchParams.set('multipart', action);
683
+ for (const [key, value] of Object.entries(params))
684
+ url.searchParams.set(key, value);
685
+ return url.toString();
686
+ }
687
+ async function responseJson(response, operation) {
688
+ const text = await response.text();
689
+ try {
690
+ const value = JSON.parse(text);
691
+ if (!value || typeof value !== 'object' || Array.isArray(value))
692
+ throw new Error('not an object');
693
+ return value;
694
+ }
695
+ catch {
696
+ throw new Error(`Multipart ${operation} returned an invalid JSON response.`);
697
+ }
698
+ }
569
699
  export async function publishFile(filePath, opts = {}) {
570
700
  const backend = resolveShareBackend(opts);
571
701
  const managedHandle = backend.kind === 'managed' ? requireManagedHandle(opts.handle) : '';
@@ -602,10 +732,18 @@ export async function publishToEndpoint(filePath, endpoint, opts = {}) {
602
732
  // derived handle is proven by the email; an alternate one must be declared).
603
733
  const managedHandle = opts.backendKind === 'managed' ? requireManagedHandle(opts.handle) : '';
604
734
  const username = managedHandle || (await resolveShareUsername(opts));
605
- let body = readFileSync(filePath);
606
- const expiresAt = resolveExpire(opts.expire);
735
+ let expiresAt = resolveExpire(opts.expire);
607
736
  const visibility = resolveShareVisibility(opts);
608
737
  const unlisted = visibility === 'unlisted';
738
+ const contentType = opts.contentType ?? guessContentType(filePath);
739
+ const initialStat = statSync(filePath);
740
+ const multipart = opts.backendKind === 'managed' &&
741
+ (visibility === 'me' || visibility === 'org') &&
742
+ contentType.toLowerCase().startsWith('video/') &&
743
+ initialStat.size > SHARE_SINGLE_PUT_MAX_BYTES;
744
+ // A multipart video is never loaded wholesale: its label/slug both fall back
745
+ // to the filename and its body is sent later from bounded filesystem ranges.
746
+ let body = multipart ? Buffer.alloc(0) : readFileSync(filePath);
609
747
  // A capability-URL publish (unlisted / token-gated private) must not have a
610
748
  // guessable slug — that was the PHNX-3654 hole. Without an explicit --slug the
611
749
  // slug always carries a 64-bit random tail (a title-derived prefix may lead it,
@@ -639,6 +777,26 @@ export async function publishToEndpoint(filePath, endpoint, opts = {}) {
639
777
  const body = await res.text().catch(() => undefined);
640
778
  return { ok: false, status: res.status, url: u, body, retryAfter: res.headers.get('retry-after') ?? undefined };
641
779
  });
780
+ const failPublish = (status, responseBody, retryAfter) => {
781
+ // 409 has two distinct shapes on the managed Worker: 'handle taken' (the
782
+ // caller's namespace belongs to another account) and 'publish conflict'
783
+ // (a concurrent write won the republish race — retry, per PHNX-3547).
784
+ const httpError = extractShareHttpError({ status, body: responseBody, retryAfter });
785
+ if (status === 409 && httpError.serverMessage === 'handle taken' && opts.backendKind === 'managed') {
786
+ throw new Error(`Handle '${username}' is already claimed by another account. ` +
787
+ 'If you signed in again and got a new account id, republishing with the same email re-binds your handle automatically; ' +
788
+ 'otherwise pick a different public namespace with --handle <name>.');
789
+ }
790
+ const detail = formatShareHttpErrorDetail(httpError);
791
+ let advice = '';
792
+ if (status === 401 || status === 403) {
793
+ advice =
794
+ opts.backendKind === 'managed'
795
+ ? ". Check that you're signed in — run 'artifacts auth login'."
796
+ : ". Check the write token, or that 'artifacts share setup' completed.";
797
+ }
798
+ throw new Error(`Publish failed (${status}) for ${pageUrl}${detail}${advice}`);
799
+ };
642
800
  let coverUrl;
643
801
  const isHtml = /\.html?$/i.test(filePath);
644
802
  if (isHtml) {
@@ -799,30 +957,477 @@ export async function publishToEndpoint(filePath, endpoint, opts = {}) {
799
957
  const shareUrl = viewerToken ? `${pageUrl}?k=${encodeURIComponent(viewerToken)}` : pageUrl;
800
958
  body = Buffer.from(await injectShareQr(body.toString('utf8'), shareUrl), 'utf8');
801
959
  }
802
- const r = await put(pageUrl, body, authHeaders(opts.contentType ?? guessContentType(filePath)));
803
- if (!r.ok) {
804
- // 409 has two distinct shapes on the managed Worker: 'handle taken' (the
805
- // caller's namespace belongs to another account) and 'publish conflict'
806
- // (a concurrent write won the republish race — retry, per PHNX-3547).
807
- const httpError = extractShareHttpError({ status: r.status, body: r.body, retryAfter: r.retryAfter });
808
- if (r.status === 409 && httpError.serverMessage === 'handle taken' && opts.backendKind === 'managed') {
809
- throw new Error(`Handle '${username}' is already claimed by another account. ` +
810
- 'If you signed in again and got a new account id, republishing with the same email re-binds your handle automatically; ' +
811
- 'otherwise pick a different public namespace with --handle <name>.');
960
+ if (multipart) {
961
+ const fetchMultipart = opts.fetcher ?? fetch;
962
+ const uploadRoot = opts.uploadStateDir ?? join(stateDir(), 'uploads');
963
+ const normalizedBaseUrl = endpoint.baseUrl.replace(/\/+$/, '');
964
+ const expireSpec = (opts.expire ?? DEFAULT_SHARE_EXPIRE).trim().toLowerCase();
965
+ const digest = await sha256File(filePath);
966
+ const stateFile = join(uploadRoot, `${digest}.json`);
967
+ const sourcePath = resolve(filePath);
968
+ const indexFile = multipartPathIndexFile(uploadRoot, sourcePath);
969
+ const unchanged = () => {
970
+ const current = statSync(filePath);
971
+ return current.size === initialStat.size && current.mtimeMs === initialStat.mtimeMs;
972
+ };
973
+ if (!unchanged()) {
974
+ throw new Error(`Video changed while its upload fingerprint was being calculated: ${filePath}`);
812
975
  }
813
- const detail = formatShareHttpErrorDetail(httpError);
814
- // The write-token/setup advice is only meaningful for an auth failure — a
815
- // 413 (quota/size) or 429 (rate) rejection has nothing to do with the
816
- // token, and 'Check the write token' there is plain wrong (PHNX-3579).
817
- // Managed endpoints carry a Phoenix bearer, so the recovery is re-login.
818
- let advice = '';
819
- if (r.status === 401 || r.status === 403) {
820
- advice =
821
- opts.backendKind === 'managed'
822
- ? ". Check that you're signed in — run 'artifacts auth login'."
823
- : ". Check the write token, or that 'artifacts share setup' completed.";
976
+ const checkedFetch = async (url, init) => {
977
+ const response = await fetchMultipart(url, init);
978
+ if (!response.ok) {
979
+ const responseBody = await response.text().catch(() => undefined);
980
+ failPublish(response.status, responseBody, response.headers.get('retry-after') ?? undefined);
981
+ }
982
+ return response;
983
+ };
984
+ const resume = async (state, expectedTotalSize) => {
985
+ const stateBaseUrl = (state.baseUrl || normalizedBaseUrl).replace(/\/+$/, '');
986
+ const statePageUrl = new URL(state.path.replace(/^\/+/, ''), `${stateBaseUrl}/`).toString();
987
+ const response = await fetchMultipart(multipartUrl(statePageUrl, 'resume', { uploadId: state.uploadId }), { method: 'POST', headers: { authorization: `Bearer ${endpoint.token}` } });
988
+ const responseBody = await response.text().catch(() => '');
989
+ let resumed;
990
+ try {
991
+ const parsed = JSON.parse(responseBody);
992
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
993
+ throw new Error('not an object');
994
+ resumed = parsed;
995
+ }
996
+ catch {
997
+ if (!response.ok) {
998
+ failPublish(response.status, responseBody, response.headers.get('retry-after') ?? undefined);
999
+ }
1000
+ throw new Error('Multipart resume returned an invalid JSON response.');
1001
+ }
1002
+ const terminalStatus = resumed.status;
1003
+ if (!response.ok) {
1004
+ if (resumed.restart === true &&
1005
+ (terminalStatus === 'aborted' || terminalStatus === 'rejected' || terminalStatus === 'missing')) {
1006
+ return {
1007
+ kind: 'restart',
1008
+ response,
1009
+ responseBody,
1010
+ status: terminalStatus,
1011
+ };
1012
+ }
1013
+ // A conflict is recoverable only when the Worker explicitly identifies
1014
+ // a terminal multipart record. Auth, network, and arbitrary 409 failures
1015
+ // must remain loud and must not discard the only recovery handle.
1016
+ failPublish(response.status, responseBody, response.headers.get('retry-after') ?? undefined);
1017
+ }
1018
+ if (resumed.uploadId !== state.uploadId ||
1019
+ String(resumed.path ?? '').replace(/^\/+/, '') !== state.path.replace(/^\/+/, '')) {
1020
+ throw new Error('Multipart resume returned a different upload id or object path.');
1021
+ }
1022
+ if (!Number.isSafeInteger(resumed.totalSize) ||
1023
+ (expectedTotalSize !== undefined && resumed.totalSize !== expectedTotalSize)) {
1024
+ throw new Error('Multipart resume returned an invalid authoritative total size.');
1025
+ }
1026
+ if (terminalStatus === 'complete') {
1027
+ const result = resumed.result;
1028
+ if (!result || typeof result !== 'object' || Array.isArray(result)) {
1029
+ throw new Error('Multipart resume returned an invalid completion result.');
1030
+ }
1031
+ return { kind: 'complete', response, body: resumed, result: result };
1032
+ }
1033
+ if (terminalStatus === 'completing') {
1034
+ return { kind: 'completing', response, body: resumed };
1035
+ }
1036
+ if (terminalStatus !== undefined && terminalStatus !== 'active' && terminalStatus !== 'completing') {
1037
+ throw new Error('Multipart resume returned an invalid upload status.');
1038
+ }
1039
+ return { kind: 'active', response, body: resumed };
1040
+ };
1041
+ const abort = async (state) => {
1042
+ const stateBaseUrl = (state.baseUrl || normalizedBaseUrl).replace(/\/+$/, '');
1043
+ const statePageUrl = new URL(state.path.replace(/^\/+/, ''), `${stateBaseUrl}/`).toString();
1044
+ await checkedFetch(multipartUrl(statePageUrl, 'abort', { uploadId: state.uploadId }), { method: 'DELETE', headers: { authorization: `Bearer ${endpoint.token}` } });
1045
+ };
1046
+ const isTerminalCleanupResponse = (body) => body.status === 'complete' ||
1047
+ (body.restart === true &&
1048
+ (body.status === 'aborted' || body.status === 'rejected' || body.status === 'missing'));
1049
+ const abortSuperseded = async (state) => {
1050
+ const stateBaseUrl = (state.baseUrl || normalizedBaseUrl).replace(/\/+$/, '');
1051
+ const statePageUrl = new URL(state.path.replace(/^\/+/, ''), `${stateBaseUrl}/`).toString();
1052
+ const response = await fetchMultipart(multipartUrl(statePageUrl, 'abort', { uploadId: state.uploadId }), { method: 'DELETE', headers: { authorization: `Bearer ${endpoint.token}` } });
1053
+ if (response.ok)
1054
+ return;
1055
+ const responseBody = await response.text().catch(() => '');
1056
+ let parsed;
1057
+ try {
1058
+ const value = JSON.parse(responseBody);
1059
+ if (value && typeof value === 'object' && !Array.isArray(value))
1060
+ parsed = value;
1061
+ }
1062
+ catch {
1063
+ // The ordinary HTTP error below retains the raw response detail.
1064
+ }
1065
+ if (parsed && isTerminalCleanupResponse(parsed))
1066
+ return;
1067
+ failPublish(response.status, responseBody, response.headers.get('retry-after') ?? undefined);
1068
+ };
1069
+ const completingParts = (body) => {
1070
+ if (!Array.isArray(body.parts) || body.parts.length === 0 || !Number.isSafeInteger(body.totalSize)) {
1071
+ throw new Error('Multipart completing resume returned invalid authoritative parts.');
1072
+ }
1073
+ const parts = body.parts.map((value) => value).sort((a, b) => Number(a.partNumber) - Number(b.partNumber));
1074
+ let total = 0;
1075
+ let nonFinalSize;
1076
+ const completed = [];
1077
+ for (let index = 0; index < parts.length; index++) {
1078
+ const part = parts[index];
1079
+ const final = index === parts.length - 1;
1080
+ if (part.partNumber !== index + 1 ||
1081
+ typeof part.etag !== 'string' ||
1082
+ !part.etag ||
1083
+ !Number.isSafeInteger(part.size) ||
1084
+ part.size <= 0 ||
1085
+ part.final !== final) {
1086
+ throw new Error('Multipart completing resume returned invalid authoritative parts.');
1087
+ }
1088
+ if (!final) {
1089
+ if (part.size < 5 * 1024 * 1024 || (nonFinalSize !== undefined && part.size !== nonFinalSize)) {
1090
+ throw new Error('Multipart completing resume returned invalid authoritative parts.');
1091
+ }
1092
+ nonFinalSize = part.size;
1093
+ }
1094
+ total += part.size;
1095
+ completed.push({ partNumber: part.partNumber, etag: part.etag });
1096
+ }
1097
+ if (total !== body.totalSize) {
1098
+ throw new Error('Multipart completing resume returned invalid authoritative parts.');
1099
+ }
1100
+ return completed;
1101
+ };
1102
+ const completeSuperseded = async (state, outcome) => {
1103
+ const parts = completingParts(outcome.body);
1104
+ const stateBaseUrl = (state.baseUrl || normalizedBaseUrl).replace(/\/+$/, '');
1105
+ const statePageUrl = new URL(state.path.replace(/^\/+/, ''), `${stateBaseUrl}/`).toString();
1106
+ const response = await fetchMultipart(multipartUrl(statePageUrl, 'complete', { uploadId: state.uploadId }), {
1107
+ method: 'POST',
1108
+ headers: { authorization: `Bearer ${endpoint.token}`, 'content-type': 'application/json' },
1109
+ body: JSON.stringify({ parts }),
1110
+ });
1111
+ const responseBody = await response.text().catch(() => '');
1112
+ let completed;
1113
+ try {
1114
+ const parsed = JSON.parse(responseBody);
1115
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
1116
+ throw new Error('not an object');
1117
+ completed = parsed;
1118
+ }
1119
+ catch {
1120
+ if (!response.ok) {
1121
+ failPublish(response.status, responseBody, response.headers.get('retry-after') ?? undefined);
1122
+ }
1123
+ throw new Error('Multipart complete returned an invalid JSON response.');
1124
+ }
1125
+ if (!response.ok) {
1126
+ if (isTerminalCleanupResponse(completed))
1127
+ return;
1128
+ // cleanup_pending and every other nonterminal error retain both local
1129
+ // records so the next invocation can resume the same completion.
1130
+ failPublish(response.status, responseBody, response.headers.get('retry-after') ?? undefined);
1131
+ }
1132
+ if (completed.ok !== true ||
1133
+ String(completed.path ?? '').replace(/^\/+/, '') !== state.path.replace(/^\/+/, '') ||
1134
+ completed.size !== outcome.body.totalSize) {
1135
+ throw new Error('Multipart complete returned an invalid terminal result; resumable state was preserved.');
1136
+ }
1137
+ };
1138
+ const persistState = (state) => {
1139
+ // The digest record is canonical. The source-path index is a safe lookup
1140
+ // for the next invocation if the same pathname's bytes (and digest) change.
1141
+ // Write the self-contained index first: if the process stops between the
1142
+ // two atomic renames, it still carries everything needed to abort/resume
1143
+ // and can restore the required canonical <file-sha256>.json record.
1144
+ writeMultipartPathIndex(indexFile, { sourcePath, digest, state });
1145
+ writeMultipartState(stateFile, state);
1146
+ };
1147
+ const removeState = () => {
1148
+ rmSync(stateFile, { force: true });
1149
+ removeMultipartPathIndex(indexFile);
1150
+ };
1151
+ const removeIndexedState = (indexedDigest) => {
1152
+ rmSync(join(uploadRoot, `${indexedDigest}.json`), { force: true });
1153
+ removeMultipartPathIndex(indexFile);
1154
+ };
1155
+ const reconcileSupersededState = async (superseded, indexedDigest) => {
1156
+ const outcome = await resume(superseded, superseded.totalSize);
1157
+ if (outcome.kind === 'active')
1158
+ await abortSuperseded(superseded);
1159
+ if (outcome.kind === 'completing')
1160
+ await completeSuperseded(superseded, outcome);
1161
+ // complete/rejected/aborted/missing are terminal. Their server-side path
1162
+ // lock is already released (or absent), so a DELETE would only turn a
1163
+ // successfully reconciled stale record into a misleading conflict.
1164
+ removeIndexedState(indexedDigest);
1165
+ };
1166
+ const pathIndex = readMultipartPathIndex(indexFile, sourcePath);
1167
+ let state;
1168
+ if (pathIndex) {
1169
+ const indexedStateFile = join(uploadRoot, `${pathIndex.digest}.json`);
1170
+ if (pathIndex.digest !== digest) {
1171
+ // The source pathname now contains different bytes. Its old digest file
1172
+ // is still the only durable handle to the R2 upload/path lock. Resume it
1173
+ // first: abort only an active upload, while a complete/rejected/aborted
1174
+ // receipt (or a missing record after cleanup) needs local cleanup only.
1175
+ await reconcileSupersededState(pathIndex.state, pathIndex.digest);
1176
+ }
1177
+ else {
1178
+ const canonicalState = readMultipartState(indexedStateFile);
1179
+ if (canonicalState && canonicalState.uploadId !== pathIndex.state.uploadId) {
1180
+ throw new Error(`Stale resumable upload path index at ${indexFile}: its upload id conflicts with ${basename(indexedStateFile)}; ` +
1181
+ 'refusing network access until the recovery records agree.');
1182
+ }
1183
+ state = pathIndex.state;
1184
+ }
1185
+ }
1186
+ else {
1187
+ // Backward-compatible recovery for state written before the path index was
1188
+ // introduced. The next successful persistence backfills the index.
1189
+ state = readMultipartState(stateFile);
1190
+ }
1191
+ // A relative expiry such as the default 30d resolves to a new timestamp on
1192
+ // every invocation. For the identical option, keep the create request's
1193
+ // exact timestamp; a genuinely changed --expire value still fingerprints
1194
+ // differently and forces a clean restart.
1195
+ const invocationExpiresAt = expiresAt;
1196
+ if (state?.expireSpec === expireSpec)
1197
+ expiresAt = state.expiresAt;
1198
+ const createIdentity = () => {
1199
+ const headers = authHeaders(contentType);
1200
+ headers['x-share-total-size'] = String(initialStat.size);
1201
+ // The Worker uses this as the idempotency key for a create whose response
1202
+ // never reached the client. Bind every durable create option plus the file
1203
+ // digest, but use the raw expiry spec instead of its freshly resolved
1204
+ // timestamp so `30d` means the same upload on tomorrow's retry.
1205
+ const multipartKey = createHash('sha256').update(JSON.stringify({
1206
+ digest,
1207
+ baseUrl: normalizedBaseUrl,
1208
+ path: key,
1209
+ contentType,
1210
+ visibility,
1211
+ expireSpec,
1212
+ headers: Object.fromEntries(Object.entries(headers)
1213
+ .filter(([name]) => {
1214
+ const lower = name.toLowerCase();
1215
+ return lower !== 'authorization' && lower !== 'x-share-expires-at';
1216
+ })
1217
+ .sort(([a], [b]) => a.localeCompare(b))),
1218
+ })).digest('hex');
1219
+ headers['x-share-multipart-key'] = multipartKey;
1220
+ const fingerprint = createHash('sha256').update(JSON.stringify({
1221
+ baseUrl: normalizedBaseUrl,
1222
+ path: key,
1223
+ contentType,
1224
+ visibility,
1225
+ expiresAt: expiresAt ?? null,
1226
+ headers: Object.fromEntries(Object.entries(headers)
1227
+ .filter(([name]) => name.toLowerCase() !== 'authorization')
1228
+ .sort(([a], [b]) => a.localeCompare(b))),
1229
+ })).digest('hex');
1230
+ return { headers, fingerprint };
1231
+ };
1232
+ let { headers: createHeaders, fingerprint: createFingerprint } = createIdentity();
1233
+ if (state &&
1234
+ (state.path !== key ||
1235
+ state.baseUrl !== normalizedBaseUrl ||
1236
+ state.createFingerprint !== createFingerprint)) {
1237
+ // The state filename is content-addressed, so changing --slug for the same
1238
+ // file or changing create-time metadata can point at another final object.
1239
+ // Reconcile first because the Worker may already have completed or
1240
+ // rejected it after the client lost the response.
1241
+ await reconcileSupersededState(state, digest);
1242
+ state = undefined;
1243
+ expiresAt = invocationExpiresAt;
1244
+ ({ headers: createHeaders, fingerprint: createFingerprint } = createIdentity());
1245
+ }
1246
+ let activeResume;
1247
+ if (state) {
1248
+ const outcome = await resume(state, initialStat.size);
1249
+ if (outcome.kind === 'complete') {
1250
+ const completed = outcome.result;
1251
+ if (completed.ok !== true ||
1252
+ String(completed.path ?? '').replace(/^\/+/, '') !== key ||
1253
+ completed.size !== initialStat.size) {
1254
+ throw new Error('Multipart resume returned an invalid completion result; resumable state was preserved.');
1255
+ }
1256
+ removeState();
1257
+ const completeUrl = typeof completed.url === 'string' && completed.url ? completed.url : pageUrl;
1258
+ const collab = readCollabRegistration(outcome.response.headers);
1259
+ return {
1260
+ url: completeUrl,
1261
+ slug: key.slice(key.indexOf('/') + 1),
1262
+ expiresAt,
1263
+ label,
1264
+ labelSource,
1265
+ visibility,
1266
+ ...(collab ? { collab } : {}),
1267
+ };
1268
+ }
1269
+ if (outcome.kind === 'restart') {
1270
+ removeState();
1271
+ state = undefined;
1272
+ // A quota rejection is authoritative for these exact bytes/options.
1273
+ // Recreating it would only re-upload and receive the same 413 again.
1274
+ if (outcome.status === 'rejected' && outcome.response.status === 413) {
1275
+ failPublish(outcome.response.status, outcome.responseBody, outcome.response.headers.get('retry-after') ?? undefined);
1276
+ }
1277
+ expiresAt = invocationExpiresAt;
1278
+ ({ headers: createHeaders, fingerprint: createFingerprint } = createIdentity());
1279
+ }
1280
+ else if (outcome.kind === 'active' || outcome.kind === 'completing') {
1281
+ activeResume = outcome;
1282
+ }
1283
+ }
1284
+ if (state) {
1285
+ if (!activeResume) {
1286
+ throw new Error('Multipart resume state changed during reconciliation.');
1287
+ }
1288
+ const resumedBody = activeResume.body;
1289
+ if (!Array.isArray(resumedBody.parts)) {
1290
+ throw new Error('Multipart resume returned an invalid completed-parts list.');
1291
+ }
1292
+ const serverParts = [];
1293
+ const seen = new Set();
1294
+ const totalParts = Math.ceil(initialStat.size / SHARE_MULTIPART_PART_BYTES);
1295
+ for (const value of resumedBody.parts) {
1296
+ const part = value;
1297
+ const partNumber = part.partNumber;
1298
+ const expectedBytes = typeof partNumber === 'number'
1299
+ ? Math.min(SHARE_MULTIPART_PART_BYTES, initialStat.size - (partNumber - 1) * SHARE_MULTIPART_PART_BYTES)
1300
+ : 0;
1301
+ if (!Number.isSafeInteger(partNumber) ||
1302
+ partNumber < 1 ||
1303
+ partNumber > totalParts ||
1304
+ seen.has(partNumber) ||
1305
+ typeof part.etag !== 'string' ||
1306
+ !part.etag ||
1307
+ part.size !== expectedBytes ||
1308
+ part.final !== (partNumber === totalParts)) {
1309
+ throw new Error('Multipart resume returned invalid completed-part metadata.');
1310
+ }
1311
+ seen.add(partNumber);
1312
+ serverParts.push({ partNumber: partNumber, etag: part.etag });
1313
+ }
1314
+ state.completedParts = serverParts.sort((a, b) => a.partNumber - b.partNumber);
1315
+ state.totalSize = resumedBody.totalSize;
1316
+ persistState(state);
1317
+ }
1318
+ if (!state) {
1319
+ const response = await checkedFetch(multipartUrl(pageUrl, 'create'), { method: 'POST', headers: createHeaders });
1320
+ const created = await responseJson(response, 'create');
1321
+ const uploadId = typeof created.uploadId === 'string' ? created.uploadId : '';
1322
+ const path = typeof created.path === 'string' ? created.path.replace(/^\/+/, '') : '';
1323
+ if (!uploadId || path !== key) {
1324
+ throw new Error('Multipart create returned an invalid upload id or object path.');
1325
+ }
1326
+ if (!Number.isSafeInteger(created.totalSize) || created.totalSize !== initialStat.size) {
1327
+ throw new Error('Multipart create returned an invalid authoritative total size.');
1328
+ }
1329
+ const authoritativeExpiresAt = created.expiresAt;
1330
+ if (authoritativeExpiresAt !== null &&
1331
+ (typeof authoritativeExpiresAt !== 'string' ||
1332
+ !authoritativeExpiresAt ||
1333
+ Number.isNaN(Date.parse(authoritativeExpiresAt)))) {
1334
+ throw new Error('Multipart create returned an invalid authoritative expiry.');
1335
+ }
1336
+ // A recovered create retains the first request's custom metadata. Adopt
1337
+ // that receipt instead of reporting/persisting the retry's newly resolved
1338
+ // relative expiry, then fingerprint the state against the same value.
1339
+ expiresAt = authoritativeExpiresAt ?? undefined;
1340
+ ({ headers: createHeaders, fingerprint: createFingerprint } = createIdentity());
1341
+ state = {
1342
+ uploadId,
1343
+ path,
1344
+ completedParts: [],
1345
+ totalSize: created.totalSize,
1346
+ baseUrl: normalizedBaseUrl,
1347
+ createFingerprint,
1348
+ expireSpec,
1349
+ ...(expiresAt ? { expiresAt } : {}),
1350
+ };
1351
+ persistState(state);
1352
+ }
1353
+ const totalParts = Math.ceil(initialStat.size / SHARE_MULTIPART_PART_BYTES);
1354
+ if (state.completedParts.some((part) => part.partNumber > totalParts)) {
1355
+ throw new Error(`Corrupt resumable upload state at ${stateFile}: part number exceeds the video size`);
824
1356
  }
825
- throw new Error(`Publish failed (${r.status}) for ${pageUrl}${detail}${advice}`);
1357
+ const partBytes = (partNumber) => Math.min(SHARE_MULTIPART_PART_BYTES, initialStat.size - (partNumber - 1) * SHARE_MULTIPART_PART_BYTES);
1358
+ let uploadedBytes = state.completedParts.reduce((sum, part) => sum + partBytes(part.partNumber), 0);
1359
+ opts.onUploadProgress?.(uploadedBytes, initialStat.size);
1360
+ for (let partNumber = 1; partNumber <= totalParts; partNumber++) {
1361
+ if (state.completedParts.some((part) => part.partNumber === partNumber))
1362
+ continue;
1363
+ if (!unchanged()) {
1364
+ await abort(state);
1365
+ removeState();
1366
+ throw new Error(`Video changed during multipart upload; the incomplete upload was aborted: ${filePath}`);
1367
+ }
1368
+ const length = partBytes(partNumber);
1369
+ const start = (partNumber - 1) * SHARE_MULTIPART_PART_BYTES;
1370
+ const stream = createReadStream(filePath, { start, end: start + length - 1 });
1371
+ let response;
1372
+ try {
1373
+ response = await checkedFetch(multipartUrl(pageUrl, 'part', { uploadId: state.uploadId, partNumber: String(partNumber) }), {
1374
+ method: 'PUT',
1375
+ headers: {
1376
+ authorization: `Bearer ${endpoint.token}`,
1377
+ 'content-type': contentType,
1378
+ 'content-length': String(length),
1379
+ ...(partNumber === totalParts ? { 'x-share-final-part': '1' } : {}),
1380
+ },
1381
+ body: stream,
1382
+ duplex: 'half',
1383
+ });
1384
+ }
1385
+ finally {
1386
+ stream.destroy();
1387
+ }
1388
+ const uploaded = await responseJson(response, `part ${partNumber}`);
1389
+ const etag = typeof uploaded.etag === 'string' ? uploaded.etag : '';
1390
+ if (uploaded.partNumber !== partNumber || !etag) {
1391
+ throw new Error(`Multipart part ${partNumber} returned an invalid part number or etag.`);
1392
+ }
1393
+ if (!unchanged()) {
1394
+ await abort(state);
1395
+ removeState();
1396
+ throw new Error(`Video changed during multipart upload; the incomplete upload was aborted: ${filePath}`);
1397
+ }
1398
+ state.completedParts.push({ partNumber, etag });
1399
+ state.completedParts.sort((a, b) => a.partNumber - b.partNumber);
1400
+ persistState(state);
1401
+ uploadedBytes += length;
1402
+ opts.onUploadProgress?.(uploadedBytes, initialStat.size);
1403
+ }
1404
+ const completedResponse = await checkedFetch(multipartUrl(pageUrl, 'complete', { uploadId: state.uploadId }), {
1405
+ method: 'POST',
1406
+ headers: { authorization: `Bearer ${endpoint.token}`, 'content-type': 'application/json' },
1407
+ body: JSON.stringify({ parts: state.completedParts }),
1408
+ });
1409
+ const completed = await responseJson(completedResponse, 'complete');
1410
+ if (completed.ok !== true ||
1411
+ String(completed.path ?? '').replace(/^\/+/, '') !== key ||
1412
+ completed.size !== initialStat.size) {
1413
+ throw new Error('Multipart complete returned an invalid path or size; resumable state was preserved.');
1414
+ }
1415
+ removeState();
1416
+ const completeUrl = typeof completed.url === 'string' && completed.url ? completed.url : pageUrl;
1417
+ const collab = readCollabRegistration(completedResponse.headers);
1418
+ return {
1419
+ url: completeUrl,
1420
+ slug: key.slice(key.indexOf('/') + 1),
1421
+ expiresAt,
1422
+ label,
1423
+ labelSource,
1424
+ visibility,
1425
+ ...(collab ? { collab } : {}),
1426
+ };
1427
+ }
1428
+ const r = await put(pageUrl, body, authHeaders(contentType));
1429
+ if (!r.ok) {
1430
+ failPublish(r.status, r.body, r.retryAfter);
826
1431
  }
827
1432
  // A token-gated page is only reachable WITH its key, so the URL we hand back
828
1433
  // (and store nowhere) carries it — https://<host>/<user>/<slug>?k=<token>.