@hyperframes/share 0.9.31 → 0.9.32

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/README.md CHANGED
@@ -43,9 +43,11 @@ Before first registration the host must obtain explicit audience consent and pre
43
43
 
44
44
  Hosts can sync a renamed project with `client.updateTitle(id, { title, expected_title })`. An optional `fromReview` hook on `addVersion` supplies feedback attribution after sign-in on each send. Pass the same hook to `recheckHeld` or `refreshReviewExport` to clear the recorded activity when a pending version becomes ready.
45
45
 
46
+ If a create request had no confirmed outcome, a later refusal keeps the original request and its idempotency key. The original request may still create a version. When the server has no more specific recovery instruction, check the review page and export a new video with different settings before adding another version.
47
+
46
48
  Identity remains in the project’s generated review.json metadata (or the existing backend-specific filename); pending export requests remain in the generated review-export.json metadata. No bearer is stored there. A copied folder must deliberately reset sharing identity when creating a new project; a renamed folder retains it. A malformed/unreadable record fails instead of silently registering a new project. The error identifies the metadata file and asks the owner to restore a backup or contact support to reconnect the existing share; deleting the file can discard recovery state or consume another slot.
47
49
 
48
- Metadata mutations and version uploads use separate cross-process locks under `.hyperframes`. Locks normally publish complete owner metadata with a hard link. Volumes that reject hard links use exclusive file creation instead; contenders wait while the owner metadata is written. An interrupted empty/malformed fallback lock is not automatically stolen. A lock is reclaimed only when the same machine proves its owner process is dead; live, foreign-machine and malformed locks are not stolen. Interrupted upload operations resume with their saved idempotency keys. Concurrent identical uploads re-read the completed version under the lock and do not create another version.
50
+ Metadata mutations and version uploads use separate cross-process locks under `.hyperframes`. Locks publish complete owner metadata with a hard link or, on volumes that reject hard links, an atomic rename of a directory containing the owner record. The kernel reclaims a recorded owner only when the same machine proves that process is dead. Older clients may report a filesystem error while a fallback directory is held. An empty legacy lock file still requires manual recovery after stopping all sharing processes that can access the project. Interrupted upload operations resume with their saved idempotency keys. Concurrent identical uploads re-read the completed version under the lock and do not create another version.
49
51
 
50
52
  `snapshotProject` skips symlinks by default, retaining Desktop watcher, change-set and saved-render compatibility; `snapshotFiles` also skips symlink entries. Set `followSymlinks: true` for a link-aware full snapshot. The CLI-facing `projectFingerprint` opts into following linked media (with cycle detection), so edited linked files invalidate its cached render. Both comparisons ignore HTML ID stamps. Export/history metadata, caches, hidden folders and installed packages are excluded. Hosts must record the fingerprint of the actual rendered source and must not relabel an old render with a newer fingerprint.
51
53
 
@@ -85,6 +85,15 @@ export function pendingReviewExport(projectPath: string): Promise<{
85
85
  export type SavedLast = Omit<NonNullable<VersionRecord["last"]>, "fingerprint"> & {
86
86
  fingerprint?: string;
87
87
  };
88
+ export type Said = {
89
+ sentence: string;
90
+ final: boolean;
91
+ exportHelps: boolean;
92
+ held?: boolean;
93
+ };
94
+ export type Failure = Said & {
95
+ exportKey: string;
96
+ };
88
97
  export type ReviewClient = import("./reviewClient.mjs").ReviewClient;
89
98
  export type ExportDTO = import("./types/reviewWire.js").ExportDTO;
90
99
  export type ExportRequest = import("./types/reviewWire.js").ExportRequest;
@@ -160,13 +169,4 @@ export type VersionRequest = VersionHooks & {
160
169
  * The snapshot of `rendered`, the project as the export was rendered; null when the folder is not that render.
161
170
  */
162
171
  export type FilesForRender = (projectPath: string, rendered: string | null) => Promise<import("./types/reviewWire.js").SnapshotRef | null>;
163
- export type Said = {
164
- sentence: string;
165
- final: boolean;
166
- exportHelps: boolean;
167
- held?: boolean;
168
- };
169
- export type Failure = Said & {
170
- exportKey: string;
171
- };
172
172
  import { putFile } from "./reviewUpload.mjs";
@@ -56,7 +56,7 @@ export function reviewDestination({ client, projectPath }: {
56
56
  export function setReviewSite(now: string): void;
57
57
  export function reviewRecordPath(projectPath: string): string;
58
58
  export function takenDown(share: ShareDTO): boolean;
59
- export function listSpaces(client: ReviewClient): Promise<import("./types/reviewWire.js").SpaceDTO[] | never[]>;
59
+ export function listSpaces(client: ReviewClient): Promise<never[] | import("./types/reviewWire.js").SpaceDTO[]>;
60
60
  export function ownerOf(reason: string): string | null;
61
61
  export function oneAtATime<T>(projectPath: string, run: () => Promise<T>): Promise<T>;
62
62
  export function reviewRecord(projectPath: string): Promise<ReviewRecord | null>;
@@ -1,2 +1,2 @@
1
- /** @param {unknown} error */
2
- export function versionSentence(error: unknown): string;
1
+ /** @param {unknown} error @param {string} [fallback] */
2
+ export function versionSentence(error: unknown, fallback?: string): string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyperframes/share",
3
- "version": "0.9.31",
3
+ "version": "0.9.32",
4
4
  "description": "Shared review identity, version upload and sharing state for HyperFrames hosts",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -1,9 +1,19 @@
1
1
  // @ts-check
2
- import fs, { open, readFile, realpath, unlink, writeFile } from "node:fs/promises";
2
+ import fs, {
3
+ lstat,
4
+ mkdir,
5
+ open,
6
+ readdir,
7
+ readFile,
8
+ realpath,
9
+ rmdir,
10
+ unlink,
11
+ writeFile,
12
+ } from "node:fs/promises";
3
13
  import { join } from "node:path";
4
14
  import { hostname } from "node:os";
5
15
  import { randomUUID } from "node:crypto";
6
- import { errorCode, mkdirInside } from "./storage.mjs";
16
+ import { errorCode, isJsonObject, mkdirInside } from "./storage.mjs";
7
17
 
8
18
  export class ShareBusyError extends Error {
9
19
  /** @param {string} path */
@@ -15,19 +25,27 @@ export class ShareBusyError extends Error {
15
25
  }
16
26
  }
17
27
  /** @typedef {{ token: string, pid: number, hostname: string }} Owner */
28
+ /** @param {unknown} value @returns {value is Owner} */
29
+ function isOwner(value) {
30
+ return (
31
+ isJsonObject(value) &&
32
+ typeof value.token === "string" &&
33
+ /^[a-f0-9-]{36}$/.test(value.token) &&
34
+ typeof value.pid === "number" &&
35
+ Number.isInteger(value.pid) &&
36
+ value.pid > 0 &&
37
+ typeof value.hostname === "string"
38
+ );
39
+ }
40
+
18
41
  /** @param {string} path @returns {Promise<Owner | null>} */
19
42
  async function ownerAt(path) {
20
43
  try {
21
44
  const value = JSON.parse(await readFile(path, "utf8"));
22
- return typeof value.token === "string" &&
23
- /^[a-f0-9-]{36}$/.test(value.token) &&
24
- Number.isInteger(value.pid) &&
25
- value.pid > 0 &&
26
- typeof value.hostname === "string"
27
- ? value
28
- : null;
45
+ return isOwner(value) ? value : null;
29
46
  } catch (error) {
30
- if (errorCode(error) === "ENOENT" || error instanceof SyntaxError) return null;
47
+ if (missing(error) || errorCode(error) === "EISDIR" || error instanceof SyntaxError)
48
+ return null;
31
49
  throw error;
32
50
  }
33
51
  }
@@ -41,8 +59,21 @@ function isDead(owner) {
41
59
  return errorCode(error) === "ESRCH";
42
60
  }
43
61
  }
44
- /** A claim scoped to the old owner prevents two stale readers deleting a replacement lock. @param {string} path */
45
- async function reap(path) {
62
+ /** @param {unknown} error */
63
+ function missing(error) {
64
+ return errorCode(error) === "ENOENT" || errorCode(error) === "ENOTDIR";
65
+ }
66
+
67
+ /** @param {string} path */
68
+ function lockAt(path) {
69
+ return lstat(path).catch((error) => {
70
+ if (missing(error)) return null;
71
+ throw error;
72
+ });
73
+ }
74
+
75
+ /** A claim scoped to the old owner prevents two stale readers deleting a replacement file. @param {string} path */
76
+ async function reapFile(path) {
46
77
  const old = await ownerAt(path);
47
78
  if (!old || !isDead(old)) return;
48
79
  const claim = `${path}.reap-${old.token}`;
@@ -58,26 +89,74 @@ async function reap(path) {
58
89
  await unlink(claim);
59
90
  }
60
91
  }
61
- /** @param {string} candidate @param {string} lock @param {Owner} owner */
62
- async function claim(candidate, lock, owner) {
92
+ /** Remove only an empty directory: a replacement is published with its owner already inside. @param {string} path */
93
+ async function removeEmptyDirectory(path) {
94
+ await rmdir(path).catch((error) => {
95
+ if (!missing(error) && !["ENOTEMPTY", "EEXIST"].includes(String(errorCode(error)))) throw error;
96
+ });
97
+ }
98
+
99
+ /** @param {string} path @param {string} marker */
100
+ async function releaseDirectory(path, marker) {
101
+ await unlink(join(path, marker)).catch((error) => {
102
+ if (!missing(error)) throw error;
103
+ });
104
+ await removeEmptyDirectory(path);
105
+ }
106
+
107
+ /** @param {string} path */
108
+ async function reapDirectory(path) {
109
+ const entries = await readdir(path, { withFileTypes: true }).catch((error) => {
110
+ if (missing(error)) return [];
111
+ throw error;
112
+ });
113
+ if (entries.length === 0) return removeEmptyDirectory(path);
114
+ const [entry] = entries;
115
+ if (entries.length !== 1 || !entry?.isFile()) return;
116
+ const owner = await ownerAt(join(path, entry.name));
117
+ if (owner && entry.name === `${owner.token}.json` && isDead(owner))
118
+ await releaseDirectory(path, entry.name);
119
+ }
120
+
121
+ /** @param {string} path */
122
+ async function reap(path) {
123
+ const stat = await lockAt(path);
124
+ if (stat?.isFile()) return reapFile(path);
125
+ if (stat?.isDirectory()) return reapDirectory(path);
126
+ }
127
+
128
+ /** @param {string} draft @param {string} marker @param {string} lock @param {number} deadline */
129
+ async function claim(draft, marker, lock, deadline) {
63
130
  try {
64
- await fs.link(candidate, lock);
131
+ await fs.link(join(draft, marker), lock);
132
+ return "file";
65
133
  } catch (error) {
134
+ if (errorCode(error) === "EEXIST") return null;
66
135
  if (
67
- !["EPERM", "ENOTSUP", "EOPNOTSUPP", "EXDEV", "EINVAL", "EISDIR"].includes(
136
+ !["EPERM", "ENOTSUP", "EOPNOTSUPP", "EXDEV", "EINVAL", "EISDIR", "EACCES"].includes(
68
137
  String(errorCode(error)),
69
138
  )
70
139
  )
71
140
  throw error;
72
- const handle = await open(lock, "wx", 0o600);
73
- let written = false;
74
- try {
75
- await handle.writeFile(JSON.stringify(owner));
76
- written = true;
77
- } finally {
78
- await handle.close();
79
- if (!written) await unlink(lock);
141
+ }
142
+ return claimDirectory(draft, lock, deadline);
143
+ }
144
+
145
+ /** @param {string} draft @param {string} lock @param {number} deadline */
146
+ async function claimDirectory(draft, lock, deadline) {
147
+ // A directory rename publishes the owner atomically and cannot replace a file or a nonempty directory.
148
+ try {
149
+ await fs.rename(draft, lock);
150
+ return "directory";
151
+ } catch (error) {
152
+ const code = String(errorCode(error));
153
+ if (["EEXIST", "ENOTEMPTY", "ENOTDIR", "EISDIR"].includes(code)) return null;
154
+ if (["EPERM", "EACCES", "EBUSY"].includes(code)) {
155
+ if (await lockAt(lock)) return null;
156
+ // Windows can deny the rename while another process has a handle open on the draft.
157
+ if (process.platform === "win32" && Date.now() < deadline) return null;
80
158
  }
159
+ throw error;
81
160
  }
82
161
  }
83
162
  /** @template T @param {string} projectPath @param {"review" | "export"} lane @param {() => Promise<T>} run
@@ -92,20 +171,16 @@ export async function withProjectShareLock(
92
171
  const folder = await mkdirInside(root, ".hyperframes");
93
172
  const lock = join(folder, lane === "review" ? "review.lock" : "review-export.lock");
94
173
  const owner = { token: randomUUID(), pid: process.pid, hostname: hostname() };
95
- const candidate = `${lock}.${owner.token}.tmp`;
96
- await writeFile(candidate, JSON.stringify(owner), { flag: "wx", mode: 0o600 });
174
+ const draft = `${lock}.${owner.token}.tmp`;
175
+ const marker = `${owner.token}.json`;
176
+ await mkdir(draft, { mode: 0o700 });
97
177
  const deadline = Date.now() + timeoutMs;
98
- let held = false;
178
+ let held = null;
99
179
  try {
180
+ await writeFile(join(draft, marker), JSON.stringify(owner), { flag: "wx", mode: 0o600 });
100
181
  while (!held) {
101
182
  signal?.throwIfAborted();
102
- held = await claim(candidate, lock, owner).then(
103
- () => true,
104
- (error) => {
105
- if (errorCode(error) === "EEXIST") return false;
106
- throw error;
107
- },
108
- );
183
+ held = await claim(draft, marker, lock, deadline);
109
184
  if (held) break;
110
185
  await reap(lock);
111
186
  if (Date.now() >= deadline) throw new ShareBusyError(lock);
@@ -114,7 +189,11 @@ export async function withProjectShareLock(
114
189
  signal?.throwIfAborted();
115
190
  return await run();
116
191
  } finally {
117
- if (held && (await ownerAt(lock))?.token === owner.token) await unlink(lock);
118
- await unlink(candidate);
192
+ try {
193
+ if (held === "directory") await releaseDirectory(lock, marker);
194
+ if (held === "file" && (await ownerAt(lock))?.token === owner.token) await unlink(lock);
195
+ } finally {
196
+ await releaseDirectory(draft, marker);
197
+ }
119
198
  }
120
199
  }
@@ -69,6 +69,8 @@ const SLOW_POLL_MS = 30_000;
69
69
  const FINAL = new Set(["export_blocked", "content_rejected", "feature_unavailable"]);
70
70
  /** Too big or too long: the same file is refused again, but a smaller or shorter export can go up. */
71
71
  const TOO_BIG = new Set(["export_too_large", "export_too_long"]);
72
+ const UNCONFIRMED_VERSION =
73
+ "Couldn't confirm whether the previous version was created. Check the review page. To add a new version, change the export settings and export again.";
72
74
  /** Longer than the backend's own limiter ever asks, and short enough that a laptop waking up checks again soon. */
73
75
  const MAX_WAIT_MS = 5 * 60_000;
74
76
  /** A run stops watching after this long; the video stays recorded, so the next press reads it back. */
@@ -210,13 +212,19 @@ async function writeState(dir, state) {
210
212
 
211
213
  /** @typedef {{ sentence: string, final: boolean, exportHelps: boolean, held?: boolean }} Said
212
214
  * @typedef {Said & { exportKey: string }} Failure */
213
- /** @param {unknown} error @returns {Said} */
214
- const said = (error) => ({
215
- sentence: versionSentence(error),
216
- final: error instanceof ReviewFailed && (FINAL.has(error.reason) || TOO_BIG.has(error.reason)),
217
- exportHelps: error instanceof ReviewFailed && TOO_BIG.has(error.reason),
218
- ...(error instanceof ReviewFailed && error.reason === "held_for_review" && { held: true }),
219
- });
215
+ /** @param {unknown} error @param {boolean} [refusedReplay] @returns {Said} */
216
+ function said(error, refusedReplay = false) {
217
+ const sentence = versionSentence(error, refusedReplay ? UNCONFIRMED_VERSION : undefined);
218
+ const exportHelps =
219
+ sentence === UNCONFIRMED_VERSION ||
220
+ (error instanceof ReviewFailed && TOO_BIG.has(error.reason));
221
+ return {
222
+ sentence,
223
+ final: exportHelps || (error instanceof ReviewFailed && FINAL.has(error.reason)),
224
+ exportHelps,
225
+ ...(error instanceof ReviewFailed && error.reason === "held_for_review" && { held: true }),
226
+ };
227
+ }
220
228
 
221
229
  /** A failure found here, before the server: fixing the export fixes it. @param {string} sentence @returns {Said} */
222
230
  const local = (sentence) => ({ sentence, final: false, exportHelps: false });
@@ -234,7 +242,7 @@ const failures = new Map();
234
242
  /** Which export a failure was about: the newest export file and the project as it was rendered. @param {string} dir */
235
243
  const exportKeyOf = (dir) => {
236
244
  const latest = latestExportFile(dir);
237
- return latest ? `${latest.path}\n${latest.fingerprint ?? ""}` : "";
245
+ return latest ? `${latest.id}\n${latest.path}\n${latest.fingerprint ?? ""}` : "";
238
246
  };
239
247
 
240
248
  /** Whether the newest export can go up now: there is one, it is MP4, and the project has not moved past it.
@@ -549,11 +557,8 @@ async function poll(r, id, current, until, every) {
549
557
  }
550
558
  }
551
559
 
552
- /** A refusal the same body would get again, or a spent upload, needs a new key next time.
553
- * A refusal of a replay cannot settle an earlier unanswered create.
554
- * @param {unknown} error @param {VersionRecord["pending"]} pending */
555
- const spent = (error, pending) =>
556
- (!pending?.unanswered || pending.videoId !== null) &&
560
+ /** @param {unknown} error */
561
+ const permanentRefusal = (error) =>
557
562
  error instanceof ReviewFailed &&
558
563
  error.status >= 400 &&
559
564
  error.status < 500 &&
@@ -631,12 +636,20 @@ async function sendVersion(r, report, source, id, state) {
631
636
  const done = await watch(r, id, uploaded, size, report, clock);
632
637
  return finishRun(r, state, pending, id, done, first);
633
638
  } catch (error) {
634
- if (spent(error, state.pending)) await writeState(r.projectPath, { ...state, pending: null });
635
- console.error("[review] version failed:", error);
636
- return said(error);
639
+ return failedSend(r.projectPath, state, error);
637
640
  }
638
641
  }
639
642
 
643
+ /** @param {string} dir @param {VersionRecord} state @param {unknown} error */
644
+ async function failedSend(dir, state, error) {
645
+ const refused = permanentRefusal(error);
646
+ // An earlier create can still be in flight when the replay is refused.
647
+ const unansweredCreate = state.pending?.unanswered === true && state.pending.videoId === null;
648
+ if (refused && !unansweredCreate) await writeState(dir, { ...state, pending: null });
649
+ console.error("[review] version failed:", error);
650
+ return said(error, refused && unansweredCreate);
651
+ }
652
+
640
653
  /** @param {Required<VersionRequest>} r @param {VersionRecord} state
641
654
  * @param {NonNullable<VersionRecord["pending"]>} pending @param {string} id @param {ExportDTO} done @param {boolean} first */
642
655
  async function finishRun(r, state, pending, id, done, first) {
@@ -24,9 +24,9 @@ const SAID = {
24
24
  held_for_review: HELD_FOR_REVIEW,
25
25
  };
26
26
 
27
- /** @param {unknown} error */
28
- export function versionSentence(error) {
29
- if (!(error instanceof ReviewFailed)) return "Couldn't add this version. Try again.";
27
+ /** @param {unknown} error @param {string} [fallback] */
28
+ export function versionSentence(error, fallback = "Couldn't add this version. Try again.") {
29
+ if (!(error instanceof ReviewFailed)) return fallback;
30
30
  const said = SAID[error.reason];
31
31
  if (said) return typeof said === "function" ? said(error) : said;
32
32
  if (error.status === 0) return "Couldn't reach HeyGen. Check your connection and try again.";
@@ -35,7 +35,7 @@ export function versionSentence(error) {
35
35
  // written for developers, so it is never shown.
36
36
  if (error.status === 200)
37
37
  return "HyperFrames couldn't process this video. Export it again, then try again.";
38
- return "Couldn't add this version. Try again.";
38
+ return fallback;
39
39
  }
40
40
 
41
41
  /** "in about 3 hours", from the server's Retry-After. @param {number | undefined} ms */