@hyperframes/share 0.9.31 → 0.9.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +64 -3
  2. package/dist/index.d.mts +2 -0
  3. package/dist/projectLock.d.mts +2 -2
  4. package/dist/projectSnapshot.d.mts +3 -1
  5. package/dist/reviewClient.d.mts +8 -0
  6. package/dist/reviewExport.d.mts +20 -10
  7. package/dist/reviewShare.d.mts +3 -2
  8. package/dist/reviewUpload.d.mts +2 -0
  9. package/dist/reviewVersionSentences.d.mts +2 -2
  10. package/dist/shareSources.d.mts +24 -0
  11. package/dist/sourceIgnore.d.mts +6 -0
  12. package/dist/sources/adapterTypes.d.ts +39 -0
  13. package/dist/sources/api.d.mts +29 -0
  14. package/dist/sources/capture.d.mts +24 -0
  15. package/dist/sources/contract.d.mts +2 -0
  16. package/dist/sources/errors.d.mts +24 -0
  17. package/dist/sources/limits.d.mts +12 -0
  18. package/dist/sources/manifest.d.mts +23 -0
  19. package/dist/sources/pathPolicy.d.mts +25 -0
  20. package/dist/sources/projectState.d.mts +9 -0
  21. package/dist/sources/store.d.mts +3 -0
  22. package/dist/sources/transfer.d.mts +45 -0
  23. package/dist/sources/types.d.ts +353 -0
  24. package/dist/sources/unicode.d.mts +15 -0
  25. package/dist/sources/upload.d.mts +9 -0
  26. package/dist/sources/uploadFiles.d.mts +31 -0
  27. package/dist/sources/wire.d.mts +21 -0
  28. package/dist/types/reviewWire.d.ts +2 -0
  29. package/package.json +1 -1
  30. package/scripts/copy-types.mjs +3 -0
  31. package/src/index.mjs +8 -0
  32. package/src/projectLock.mjs +126 -38
  33. package/src/projectSnapshot.mjs +22 -6
  34. package/src/reviewClient.mjs +8 -1
  35. package/src/reviewExport.mjs +178 -53
  36. package/src/reviewShare.mjs +11 -2
  37. package/src/reviewUpload.mjs +18 -16
  38. package/src/reviewVersionSentences.mjs +10 -8
  39. package/src/shareSources.mjs +236 -0
  40. package/src/sourceIgnore.mjs +92 -0
  41. package/src/sources/adapterTypes.d.ts +39 -0
  42. package/src/sources/api.mjs +114 -0
  43. package/src/sources/capture.mjs +264 -0
  44. package/src/sources/contract/LICENSE-Unicode.txt +39 -0
  45. package/src/sources/contract/path-policy.json +311 -0
  46. package/src/sources/contract/unicode-15.1.0.json +6179 -0
  47. package/src/sources/contract.mjs +13 -0
  48. package/src/sources/errors.mjs +77 -0
  49. package/src/sources/limits.mjs +48 -0
  50. package/src/sources/manifest.mjs +154 -0
  51. package/src/sources/pathPolicy.mjs +197 -0
  52. package/src/sources/projectState.mjs +59 -0
  53. package/src/sources/store.mjs +82 -0
  54. package/src/sources/transfer.mjs +196 -0
  55. package/src/sources/types.d.ts +353 -0
  56. package/src/sources/unicode.mjs +163 -0
  57. package/src/sources/upload.mjs +201 -0
  58. package/src/sources/uploadFiles.mjs +263 -0
  59. package/src/sources/wire.mjs +205 -0
  60. package/src/types/reviewWire.d.ts +2 -0
  61. package/LICENSE +0 -190
@@ -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,29 +89,77 @@ 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
- /** @template T @param {string} projectPath @param {"review" | "export"} lane @param {() => Promise<T>} run
162
+ /** @template T @param {string} projectPath @param {"review" | "export" | "source" | "operation"} lane @param {() => Promise<T>} run
84
163
  * @param {{ timeoutMs?: number, signal?: AbortSignal }} [options] @returns {Promise<T>} */
85
164
  export async function withProjectShareLock(
86
165
  projectPath,
@@ -90,22 +169,27 @@ export async function withProjectShareLock(
90
169
  ) {
91
170
  const root = await realpath(projectPath);
92
171
  const folder = await mkdirInside(root, ".hyperframes");
93
- const lock = join(folder, lane === "review" ? "review.lock" : "review-export.lock");
172
+ const lock = join(
173
+ folder,
174
+ lane === "operation"
175
+ ? "share-operation.lock"
176
+ : lane === "review"
177
+ ? "review.lock"
178
+ : lane === "source"
179
+ ? "share-source.lock"
180
+ : "review-export.lock",
181
+ );
94
182
  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 });
183
+ const draft = `${lock}.${owner.token}.tmp`;
184
+ const marker = `${owner.token}.json`;
185
+ await mkdir(draft, { mode: 0o700 });
97
186
  const deadline = Date.now() + timeoutMs;
98
- let held = false;
187
+ let held = null;
99
188
  try {
189
+ await writeFile(join(draft, marker), JSON.stringify(owner), { flag: "wx", mode: 0o600 });
100
190
  while (!held) {
101
191
  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
- );
192
+ held = await claim(draft, marker, lock, deadline);
109
193
  if (held) break;
110
194
  await reap(lock);
111
195
  if (Date.now() >= deadline) throw new ShareBusyError(lock);
@@ -114,7 +198,11 @@ export async function withProjectShareLock(
114
198
  signal?.throwIfAborted();
115
199
  return await run();
116
200
  } finally {
117
- if (held && (await ownerAt(lock))?.token === owner.token) await unlink(lock);
118
- await unlink(candidate);
201
+ try {
202
+ if (held === "directory") await releaseDirectory(lock, marker);
203
+ if (held === "file" && (await ownerAt(lock))?.token === owner.token) await unlink(lock);
204
+ } finally {
205
+ await releaseDirectory(draft, marker);
206
+ }
119
207
  }
120
208
  }
@@ -1,6 +1,7 @@
1
1
  // @ts-check
2
2
  // A project's files as change detection sees them: every file the film can use (isOutsideFilm), keyed by mtime and
3
3
  // size, except html, keyed by content without the data-hf-id stamps. A run's change set and the watcher both read it.
4
+ import { readSourceIgnore } from "./sourceIgnore.mjs";
4
5
  import fs from "node:fs/promises";
5
6
  import { constants } from "node:fs";
6
7
  import path from "node:path";
@@ -31,7 +32,7 @@ async function snapshotKey(full, byContent) {
31
32
  const stat = await handle.stat();
32
33
  if (!stat.isFile()) return undefined;
33
34
  if (full.endsWith(".html")) return contentKey(await handle.readFile("utf8"));
34
- if (byContent) return sha256(await handle.readFile());
35
+ if (byContent) return await hashFile(handle);
35
36
  return `${stat.mtimeMs}:${stat.size}`;
36
37
  } catch {
37
38
  return undefined;
@@ -40,6 +41,13 @@ async function snapshotKey(full, byContent) {
40
41
  }
41
42
  }
42
43
 
44
+ /** @param {import("node:fs/promises").FileHandle} handle */
45
+ async function hashFile(handle) {
46
+ const hash = createHash("sha256");
47
+ for await (const chunk of handle.createReadStream({ autoClose: false })) hash.update(chunk);
48
+ return hash.digest("hex");
49
+ }
50
+
43
51
  /** @param {import("node:fs").Dirent} entry @param {string} full @param {boolean} followSymlinks */
44
52
  async function entryKind(entry, full, followSymlinks) {
45
53
  if (!entry.isSymbolicLink()) return entry;
@@ -53,6 +61,7 @@ async function entryKind(entry, full, followSymlinks) {
53
61
  export async function snapshotProject(dir, { byContent = false, followSymlinks = false } = {}) {
54
62
  /** @type {Snapshot} */
55
63
  const result = new Map();
64
+ const ignored = await readSourceIgnore(dir);
56
65
  /** @param {string} current @param {Set<string>} ancestors */
57
66
  async function walk(current, ancestors) {
58
67
  const real = await fs.realpath(current).catch(() => null);
@@ -67,7 +76,7 @@ export async function snapshotProject(dir, { byContent = false, followSymlinks =
67
76
  }
68
77
  for (const entry of entries) {
69
78
  const full = path.join(current, entry.name);
70
- if (isOutsideFilm(path.relative(dir, full))) continue;
79
+ if (excludedFromSnapshot(dir, full, ignored)) continue;
71
80
  const kind = await entryKind(entry, full, followSymlinks);
72
81
  if (kind?.isDirectory()) await walk(full, parents);
73
82
  else if (kind?.isFile()) {
@@ -93,11 +102,12 @@ export function snapshotFingerprint(snapshot) {
93
102
  export async function snapshotFiles(dir, files) {
94
103
  /** @type {Map<string, unknown>} */
95
104
  const result = new Map();
105
+ const ignored = await readSourceIgnore(dir);
96
106
  for (const file of files) {
97
107
  const full = path.join(dir, file);
98
108
  const stat = await fs.lstat(full).catch(() => null);
99
109
  if (stat?.isDirectory()) return null;
100
- const holds = stat?.isFile() && !isOutsideFilm(path.relative(dir, full));
110
+ const holds = stat?.isFile() && !excludedFromSnapshot(dir, full, ignored);
101
111
  result.set(file, holds ? await snapshotKey(full, false) : undefined);
102
112
  }
103
113
  return result;
@@ -115,6 +125,12 @@ export function diffChangedFiles(before, after) {
115
125
  return changed;
116
126
  }
117
127
 
118
- /** @param {string} projectPath */
119
- export const projectFingerprint = async (projectPath) =>
120
- snapshotFingerprint(await snapshotProject(projectPath, { followSymlinks: true }));
128
+ /** @param {string} projectPath @param {{ byContent?: boolean }} [options] */
129
+ export const projectFingerprint = async (projectPath, options) =>
130
+ snapshotFingerprint(await snapshotProject(projectPath, { ...options, followSymlinks: true }));
131
+
132
+ /** @param {string} dir @param {string} full @param {(path: string) => boolean} ignored */
133
+ function excludedFromSnapshot(dir, full, ignored) {
134
+ const relative = path.relative(dir, full);
135
+ return isOutsideFilm(relative) || ignored(relative.split(path.sep).join("/"));
136
+ }
@@ -40,7 +40,8 @@ async function dataOf(reply, what) {
40
40
 
41
41
  /** @param {Response} reply @param {string} what @param {import("./types/reviewWire.js").ErrorEnvelope["data"] | undefined} data */
42
42
  function responseFailure(reply, what, data) {
43
- console.error(`[review] ${what} refused:`, reply.status, data?.reason);
43
+ if (process.env.HF_DEBUG_SHARE === "1")
44
+ console.error(`[review] ${what} refused:`, reply.status, data?.reason);
44
45
  const retryAfter = Number(reply.headers.get("retry-after") ?? NaN);
45
46
  return new ReviewFailed(
46
47
  reply.status,
@@ -114,6 +115,12 @@ export function reviewClient({ access, fetchImpl = fetch, signedInEmail = async
114
115
  linkOff: (id) => call("DELETE", `${project(id)}/share`),
115
116
  /** @param {string} id @returns {Promise<ProjectDTO>} */
116
117
  project: (id) => call("GET", project(id)),
118
+ /** @param {string} id @returns {Promise<{frames: unknown[]}>} */
119
+ storyboard: (id) =>
120
+ call("GET", `/v1/hyperframes/projects/${encodeURIComponent(id)}/storyboard`),
121
+ /** @param {string} id @param {string} compositionId @returns {Promise<{composition_id: string}>} */
122
+ bindComposition: (id, compositionId) =>
123
+ call("PUT", `${project(id)}/composition`, { composition_id: compositionId }),
117
124
  /** One page of the project's comments, every state. @param {string} id @param {URLSearchParams} query
118
125
  * @returns {Promise<import("./types/reviewWire.js").FeedbackPage>} */
119
126
  feedback: (id, query) => call("GET", `${project(id)}/feedback?${query}`),