@hyperframes/share 0.9.103 → 0.9.106

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
@@ -21,7 +21,7 @@ bindShareHost({
21
21
  reviewUploadOrigins: ["https://review-bucket.s3.us-east-1.amazonaws.com"],
22
22
  signedInRequest,
23
23
  projectFingerprint,
24
- latestExportFile, // (dir) => { path, fingerprint, id } | null
24
+ latestExportFile, // (dir) => { path, fingerprint, id } | null, or a promise of it
25
25
  ffBinary, // ('ffprobe') => executable path
26
26
  });
27
27
  const client = reviewClient({ access, signedInEmail });
@@ -109,7 +109,14 @@ Hosts with their own file inventory can instead read `readSourceIgnore(projectPa
109
109
  once per capture. Pass the resulting `ignored` function to the inventory walk as
110
110
  `ignored(relativePath, entry.isDirectory())` and reuse it for
111
111
  `listReferencedHiddenSourceAssets(projectPath, observed, { ignored })`. Private-path rules apply
112
- even when an ignore rule re-includes a path.
112
+ even when an ignore rule re-includes a path. The gitignore reader accepts 256 active rules of 256 UTF-16 code units each. A rule can have
113
+ up to four wildcard components with one star apiece, including one recursive globstar.
114
+ Two stars within a filename pattern, such as `*draft*` or `*.min.*`, are supported when the
115
+ other components are literal or the filename is prefixed with `**/`. A recursive contents rule such as `**/cache/**` is supported
116
+ with literal components between the globstars. Avoid bracket expressions and backslash escapes
117
+ in rules containing multiple stars. With active rules, capture stops if a path exceeds 64
118
+ components or 1024 UTF-16 code units. For a path-limit failure, `SourceIgnoreError.relativePath`
119
+ provides an abbreviated project-relative path for local display. Simplify the rules or shorten the path to resume.
113
120
 
114
121
  Editable source includes referenced WOFF, WOFF2, TTF and OTF files with dot-prefixed names, such as
115
122
  `.brand/.Atlas.woff2`. The same private-path and ignore rules apply to these fonts. Preview and render servers can call
package/dist/hosts.d.ts CHANGED
@@ -25,7 +25,13 @@ export interface ShareHost {
25
25
  /** Requests to HeyGen's sign-in host as the signed-in person, traced as the host traces its API calls. */
26
26
  signedInRequest(deps: Omit<SignedInDeps, "trace">): ReturnType<typeof signedInRequest>;
27
27
  /** The newest finished export recorded in the project's renders folder whose file is still there. */
28
- latestExportFile(dir: string): { path: string; fingerprint?: string; id: string } | null;
28
+ /** May answer later, so a host can read its disk off its main thread. */
29
+ latestExportFile(
30
+ dir: string,
31
+ ):
32
+ | { path: string; fingerprint?: string; id: string }
33
+ | null
34
+ | Promise<{ path: string; fingerprint?: string; id: string } | null>;
29
35
  /** Trusted video upload origins configured by the host independently of the review API response. */
30
36
  reviewUploadOrigins?: readonly string[];
31
37
  /** This install's own secret: change-of-space journals are sealed with it; one it did not seal reads as none. */
@@ -13,7 +13,16 @@ export function readSourceIgnore(root: string, { syntax }?: {
13
13
  * @returns {Promise<(path: string) => boolean>} */
14
14
  export function readChangeIgnore(root: string): Promise<(path: string) => boolean>;
15
15
  export class SourceIgnoreError extends Error {
16
+ /** @param {string} [message] @param {ErrorOptions & {reason?: "rule" | "file" | "read" | "path", relativePath?: string | undefined}} [options] */
17
+ constructor(message?: string, options?: ErrorOptions & {
18
+ reason?: "rule" | "file" | "read" | "path";
19
+ relativePath?: string | undefined;
20
+ });
21
+ reason: "file" | "rule" | "read" | "path";
22
+ /** A relative path for local display, kept out of the message and enumerable error fields. */
23
+ get relativePath(): string | undefined;
16
24
  code: string;
25
+ #private;
17
26
  }
18
27
  export type SourceIgnoreSyntax = "gitignore";
19
28
  export type SourceIgnore = (path: string, directory?: boolean) => boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyperframes/share",
3
- "version": "0.9.103",
3
+ "version": "0.9.106",
4
4
  "description": "Shared review identity, version upload and sharing state for HyperFrames hosts",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -113,7 +113,7 @@
113
113
  "css-tree": "^3.2.1",
114
114
  "ignore": "^5.3.2",
115
115
  "linkedom": "^0.18.12",
116
- "@hyperframes/parsers": "0.9.103"
116
+ "@hyperframes/parsers": "0.9.106"
117
117
  },
118
118
  "devDependencies": {
119
119
  "@types/css-tree": "^3.2.0",
package/src/hosts.d.ts CHANGED
@@ -25,7 +25,13 @@ export interface ShareHost {
25
25
  /** Requests to HeyGen's sign-in host as the signed-in person, traced as the host traces its API calls. */
26
26
  signedInRequest(deps: Omit<SignedInDeps, "trace">): ReturnType<typeof signedInRequest>;
27
27
  /** The newest finished export recorded in the project's renders folder whose file is still there. */
28
- latestExportFile(dir: string): { path: string; fingerprint?: string; id: string } | null;
28
+ /** May answer later, so a host can read its disk off its main thread. */
29
+ latestExportFile(
30
+ dir: string,
31
+ ):
32
+ | { path: string; fingerprint?: string; id: string }
33
+ | null
34
+ | Promise<{ path: string; fingerprint?: string; id: string } | null>;
29
35
  /** Trusted video upload origins configured by the host independently of the review API response. */
30
36
  reviewUploadOrigins?: readonly string[];
31
37
  /** This install's own secret: change-of-space journals are sealed with it; one it did not seal reads as none. */
@@ -261,15 +261,15 @@ const woken = new Set();
261
261
  const failures = new Map();
262
262
 
263
263
  /** Which export a failure was about: the newest export file and the project as it was rendered. @param {string} dir */
264
- const exportKeyOf = (dir) => {
265
- const latest = latestExportFile(dir);
264
+ const exportKeyOf = async (dir) => {
265
+ const latest = await latestExportFile(dir);
266
266
  return latest ? `${latest.id}\n${latest.path}\n${latest.fingerprint ?? ""}` : "";
267
267
  };
268
268
 
269
269
  /** Whether the newest export can go up now: there is one, it is MP4, and the project has not moved past it.
270
- * @param {string} dir @param {string} now @returns {ReviewVersion["source"]} */
271
- function sourceOf(dir, now) {
272
- const latest = latestExportFile(dir);
270
+ * @param {string} dir @param {string} now @returns {Promise<ReviewVersion["source"]>} */
271
+ async function sourceOf(dir, now) {
272
+ const latest = await latestExportFile(dir);
273
273
  if (!latest) return "none";
274
274
  if (!/\.mp4$/i.test(latest.path)) return "not-mp4";
275
275
  return latest.fingerprint === now ? "ready" : "stale";
@@ -290,13 +290,17 @@ export async function reviewVersion(projectPath, server = {}) {
290
290
  server.latestReadyVersionId === undefined || server.latestReadyVersionId === last?.versionId;
291
291
  const savedFailure = state.failure?.projectId === projectId ? state.failure : null;
292
292
  const failed = savedFailure ?? failures.get(key);
293
+ const [source, exportKey] = await Promise.all([
294
+ sourceOf(projectPath, now),
295
+ exportKeyOf(projectPath),
296
+ ]);
293
297
  return {
294
298
  last: last
295
299
  ? { exportedAt: last.exportedAt, current: last.fingerprint === now && onServer }
296
300
  : null,
297
- source: sourceOf(projectPath, now),
301
+ source,
298
302
  exporting: inFlight.get(key) ?? null,
299
- ...(failed?.exportKey === exportKeyOf(projectPath)
303
+ ...(failed?.exportKey === exportKey
300
304
  ? {
301
305
  failure: failed.sentence,
302
306
  retryable: !failed.final,
@@ -311,8 +315,8 @@ export async function reviewVersion(projectPath, server = {}) {
311
315
  * @param {string} dir @param {string} title @param {(file: string) => Promise<VideoFacts | null>} probe
312
316
  * @param {FilesForRender} filesForExport @param {boolean} requireSource */
313
317
  async function exportSource(dir, title, probe, filesForExport, requireSource) {
314
- const latest = latestExportFile(dir);
315
- if (!latest || sourceOf(dir, await projectFingerprint(dir)) !== "ready")
318
+ const latest = await latestExportFile(dir);
319
+ if (!latest || (await sourceOf(dir, await projectFingerprint(dir))) !== "ready")
316
320
  return { failure: local("Export an MP4 of the project as it is now first.") };
317
321
  const { size } = await stat(latest.path);
318
322
  if (size > MAX_BYTES) return { failure: said(new ReviewFailed(400, "export_too_large")) };
@@ -623,14 +627,14 @@ async function finish(dir, state, pending, id, done, fromReview) {
623
627
  /** @param {string} dir @param {NonNullable<VersionRecord["pending"]>} pending */
624
628
  async function failedExportKey(dir, pending) {
625
629
  if (typeof pending.renderKey === "string") return pending.renderKey;
626
- const latest = latestExportFile(dir);
630
+ const latest = await latestExportFile(dir);
627
631
  if (!latest) return "";
628
632
  const checksum =
629
633
  latest.fingerprint === pending.body.source_fingerprint
630
634
  ? await fileSha256Base64(latest.path).catch(() => null)
631
635
  : null;
632
636
  return checksum === pending.body.local_upload.checksum_sha256
633
- ? exportKeyOf(dir)
637
+ ? await exportKeyOf(dir)
634
638
  : `pending:${pending.body.client_operation_id}`;
635
639
  }
636
640
 
@@ -681,7 +685,7 @@ async function alreadyUploaded(client, id, state, body) {
681
685
  * @param {{file: string, body: ExportRequest}} source @param {string} id @param {VersionRecord} state */
682
686
  async function sendVersion(r, report, source, id, state) {
683
687
  const first = state.last?.projectId !== id;
684
- let pending = bindRenderKey(bodyToSend(state, source.body, id), r.projectPath);
688
+ let pending = await bindRenderKey(bodyToSend(state, source.body, id), r.projectPath);
685
689
  const sourceConflict = pendingSourceConflict(r, pending, source.body);
686
690
  if (sourceConflict) return local(sourceConflict);
687
691
  await writeState(r.projectPath, (state = { ...state, pending, failure: null }));
@@ -788,7 +792,7 @@ export async function addVersion(request) {
788
792
  report({ step: "preparing", sent: 0, total: 0 });
789
793
  const failure = await withProjectShareLock(r.projectPath, "export", () => run(r, report));
790
794
  const kept = failure && (uploaded || !request.projectId);
791
- if (kept) failures.set(key, { ...failure, exportKey: exportKeyOf(r.projectPath) });
795
+ if (kept) failures.set(key, { ...failure, exportKey: await exportKeyOf(r.projectPath) });
792
796
  return failure?.sentence ?? null;
793
797
  } catch (error) {
794
798
  const sentence =
@@ -797,7 +801,7 @@ export async function addVersion(request) {
797
801
  sentence,
798
802
  final: false,
799
803
  exportHelps: false,
800
- exportKey: exportKeyOf(r.projectPath),
804
+ exportKey: await exportKeyOf(r.projectPath),
801
805
  });
802
806
  return sentence;
803
807
  } finally {
@@ -863,7 +867,7 @@ async function settleSavedExport(dir, client, fromReview) {
863
867
  if (done.status === "upload_pending" || going(done)) return;
864
868
  const failure = await finish(dir, state, pending, id, done, fromReview);
865
869
  const key = normalize(dir);
866
- if (failure) failures.set(key, { ...failure, exportKey: exportKeyOf(dir) });
870
+ if (failure) failures.set(key, { ...failure, exportKey: await exportKeyOf(dir) });
867
871
  else failures.delete(key);
868
872
  }
869
873
 
@@ -887,7 +891,7 @@ export async function versionFacts(dir) {
887
891
  const last = state.last?.projectId === projectId ? state.last : null;
888
892
  return {
889
893
  last: last && { ...last, current: last.fingerprint === now },
890
- source: sourceOf(dir, now),
894
+ source: await sourceOf(dir, now),
891
895
  running: inFlight.has(normalize(dir)),
892
896
  };
893
897
  }
@@ -945,8 +949,8 @@ function readyRecord(pending, id, done) {
945
949
  }
946
950
 
947
951
  /** @param {NonNullable<VersionRecord["pending"]>} pending @param {string} dir */
948
- function bindRenderKey(pending, dir) {
952
+ async function bindRenderKey(pending, dir) {
949
953
  return typeof pending.renderKey === "string"
950
954
  ? pending
951
- : { ...pending, renderKey: exportKeyOf(dir) };
955
+ : { ...pending, renderKey: await exportKeyOf(dir) };
952
956
  }
@@ -4,6 +4,22 @@ import { lstat, open } from "node:fs/promises";
4
4
  import { join } from "node:path";
5
5
 
6
6
  export class SourceIgnoreError extends Error {
7
+ #relativePath;
8
+
9
+ /** @param {string} [message] @param {ErrorOptions & {reason?: "rule" | "file" | "read" | "path", relativePath?: string | undefined}} [options] */
10
+ constructor(message, options) {
11
+ super(message, options);
12
+ this.reason = options?.reason ?? "rule";
13
+ this.#relativePath = options?.relativePath ? localPathLabel(options.relativePath) : undefined;
14
+ }
15
+
16
+ /** A relative path for local display, kept out of the message and enumerable error fields. */
17
+ // Package hosts read this field when presenting a capture failure.
18
+ // fallow-ignore-next-line unused-class-member
19
+ get relativePath() {
20
+ return this.#relativePath;
21
+ }
22
+
7
23
  code = "invalid_source_ignore";
8
24
  }
9
25
  const scratch = (/** @type {string} */ path) => /(?:^|\/)[^/]+\.(?:log|swp)$/.test(path);
@@ -18,13 +34,23 @@ export async function readSourceIgnore(root, { syntax } = {}) {
18
34
  const text = await readIgnoreText(root);
19
35
  if (!text) return scratch;
20
36
  if (syntax === "gitignore") {
37
+ const lines = boundedGitignoreRules(text);
38
+ if (!lines.length) return scratch;
21
39
  const { default: ignore } = await import("ignore");
22
- const rules = ignore({ allowRelativePaths: true }).add(text);
40
+ const rules = ignore({ allowRelativePaths: true }).add(lines);
23
41
  if (rules.ignores("index.html"))
24
42
  throw new SourceIgnoreError(
25
43
  ".hyperframesignore must include index.html at the project root.",
26
44
  );
27
- return (path, directory) => scratch(path) || rules.ignores(directory ? `${path}/` : path);
45
+ return (path, directory) => {
46
+ // The matcher checks each ancestor. Bound that work before entering it, including on a cold cache.
47
+ if (path.length > 1024 || path.split("/").length > 64)
48
+ throw new SourceIgnoreError(
49
+ ".hyperframesignore supports paths up to 1024 characters and 64 components.",
50
+ { reason: "path", relativePath: path },
51
+ );
52
+ return scratch(path) || rules.ignores(directory ? `${path}/` : path);
53
+ };
28
54
  }
29
55
  const paths = text
30
56
  .split(/\r?\n/)
@@ -34,9 +60,72 @@ export async function readSourceIgnore(root, { syntax } = {}) {
34
60
  return (path) => scratch(path) || entries.some((entry) => entry.test(path));
35
61
  }
36
62
 
63
+ /** @param {string} path */
64
+ function localPathLabel(path) {
65
+ if (/^(?:\/|[a-z]:)|\\|(?:^|\/)\.\.(?:\/|$)/i.test(path)) return undefined;
66
+ const brief = path.length > 160 ? path.slice(0, 60) + "…" + path.slice(-96) : path;
67
+ return JSON.stringify(brief)
68
+ .slice(1, -1)
69
+ .replace(/[\u202a-\u202e\u2066-\u2069]/g, "�");
70
+ }
71
+
72
+ /** @param {string} pattern */
73
+ function checkWildcardComponents(pattern) {
74
+ const wildcardParts = pattern.split("/").filter((part) => part.includes("*"));
75
+ if (wildcardParts.length > 4)
76
+ throw new SourceIgnoreError(
77
+ ".hyperframesignore allows up to four wildcard path components per rule.",
78
+ );
79
+ const ordinary = wildcardParts.filter((part) => part !== "**");
80
+ const globstars = wildcardParts.length - ordinary.length;
81
+ // A trailing /** only tests for contents. Keep the common **/folder/** form.
82
+ const contentsOnly =
83
+ wildcardParts.length === 2 && /(?:^|\/)\*\*\/(?:[^*?/]+\/)+\*\*$/.test(pattern);
84
+ if (globstars > 1 && !contentsOnly)
85
+ throw new SourceIgnoreError(
86
+ ".hyperframesignore allows one recursive wildcard and an optional trailing /**.",
87
+ );
88
+ // A two-star filename such as *.min.* is confined to one component. Keep the remaining
89
+ // components literal so matching one filename cannot multiply work in another.
90
+ const maxStars = wildcardParts.length === 1 ? 2 : 1;
91
+ if (ordinary.some((part) => part.split("*").length - 1 > maxStars))
92
+ throw new SourceIgnoreError(
93
+ ".hyperframesignore allows a two-star filename with otherwise literal components.",
94
+ );
95
+ }
96
+
97
+ /** @param {string} line */
98
+ function boundedGitignoreRule(line) {
99
+ if (line.length > 256)
100
+ throw new SourceIgnoreError(".hyperframesignore rules may contain up to 256 characters.");
101
+ const pattern = line.replace(/^!/, "");
102
+ // A leading **/ before a single filename is the ordinary basename match. Only
103
+ // simplify validation; pass the original rule to the matcher to preserve its semantics.
104
+ const basename = /^\*\*\/([^/]+)$/.exec(pattern)?.[1];
105
+ checkWildcardComponents(basename && basename !== "**" ? basename : pattern);
106
+ // Count stars before interpreting escapes and classes, which can change component boundaries.
107
+ if (pattern.indexOf("*") !== pattern.lastIndexOf("*") && /[\\[]/.test(pattern))
108
+ throw new SourceIgnoreError(
109
+ ".hyperframesignore rule combines unsupported wildcards or escapes.",
110
+ );
111
+ // A standalone globstar has no adjacent path component to span.
112
+ return /^!?\/?\*\*\/?$/.test(line) ? line.replace("**", "*") : line;
113
+ }
114
+
115
+ /** @param {string} text */
116
+ function boundedGitignoreRules(text) {
117
+ const lines = text.split(/\r?\n/).filter((line) => !line.startsWith("#") && line.trim());
118
+ if (lines.length > 256) throw new SourceIgnoreError(".hyperframesignore allows up to 256 rules.");
119
+ return lines.map(boundedGitignoreRule);
120
+ }
121
+
122
+ const unreadableIgnoreFile = () =>
123
+ new SourceIgnoreError(".hyperframesignore could not be read.", { reason: "read" });
124
+
37
125
  const invalidIgnoreFile = () =>
38
126
  new SourceIgnoreError(
39
127
  ".hyperframesignore must be a regular file inside the project, smaller than 64 KiB.",
128
+ { reason: "file" },
40
129
  );
41
130
 
42
131
  /** @param {string} file */
@@ -45,11 +134,12 @@ async function openIgnoreFile(file) {
45
134
  file,
46
135
  constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0),
47
136
  ).catch(async (/** @type {NodeJS.ErrnoException} */ error) => {
48
- if (error.code !== "ENOENT") throw invalidIgnoreFile();
137
+ if (error.code === "ELOOP" || error.code === "EMLINK") throw invalidIgnoreFile();
138
+ if (error.code !== "ENOENT") throw unreadableIgnoreFile();
49
139
  // An absent file means no exclusions; a dangling symlink is invalid.
50
140
  const named = await lstat(file).catch((/** @type {NodeJS.ErrnoException} */ missing) => {
51
141
  if (missing.code === "ENOENT") return null;
52
- throw invalidIgnoreFile();
142
+ throw unreadableIgnoreFile();
53
143
  });
54
144
  if (named) throw invalidIgnoreFile();
55
145
  return null;