@hyperframes/share 0.9.96 → 0.9.97

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.
@@ -13,6 +13,11 @@ export type SourceResult =
13
13
  export interface SourceOptions {
14
14
  access: SignedInAccess;
15
15
  spaceId: string;
16
+ /** Parse project exclusions with gitignore rules on every source capture. The default uses strict project-relative patterns. */
17
+ ignoreSyntax?: import("../sourceIgnore.mjs").SourceIgnoreSyntax;
18
+ expectedReferencedHiddenDigest?: string;
19
+ /** Only verify a published snapshot. Never start or recover an upload. */
20
+ reuseOnly?: boolean;
16
21
  store?: SourceStore;
17
22
  enabled?: () => boolean;
18
23
  fingerprint?: (path: string) => Promise<string | null>;
@@ -0,0 +1,209 @@
1
+ // @ts-check
2
+ import { parse as parseScript } from "acorn";
3
+ import { overrides, variableReferences } from "./variableAssets.mjs";
4
+ import { simple } from "acorn-walk";
5
+ import { parse as parseCss, walk as walkCss } from "css-tree";
6
+ import { rewriteSrcsetUrls } from "@hyperframes/parsers/asset-paths";
7
+ import {
8
+ scanHtmlOpeningTags,
9
+ decodeAuthoredAttribute,
10
+ } from "@hyperframes/parsers/html-attribute-spans";
11
+
12
+ /** @typedef {{ id: string, values: Record<string,unknown> }} Host
13
+ * @typedef {(value: string, base: URL, host?: Host) => void} Reference */
14
+
15
+ /** @param {string} source @param {URL} base @param {Reference} add @param {"stylesheet"|"declarationList"|"value"} context */
16
+ function cssReferences(source, base, add, context) {
17
+ const tree = parseCss(source, { context, parseCustomProperty: true });
18
+ walkCss(tree, function (node) {
19
+ if (node.type === "Url") add(node.value, base);
20
+ if (
21
+ node.type === "String" &&
22
+ (this.atrule?.name.toLowerCase() === "import" ||
23
+ /^(?:-webkit-)?image-set$/i.test(this.function?.name ?? ""))
24
+ )
25
+ add(node.value, base);
26
+ });
27
+ }
28
+
29
+ /** @param {import("acorn").Node | null | undefined} node */
30
+ function literal(node) {
31
+ if (node && "value" in node && typeof node.value === "string") return node.value;
32
+ if (node?.type === "TemplateLiteral") {
33
+ const template = /** @type {import("acorn").TemplateLiteral} */ (node);
34
+ if (!template.expressions.length) return template.quasis[0]?.value.cooked;
35
+ }
36
+ return null;
37
+ }
38
+
39
+ /** @param {import("acorn").Node} node */
40
+ function nameOf(node) {
41
+ if ("name" in node) return node.name;
42
+ if (node.type === "MemberExpression") {
43
+ const { property, computed } = /** @type {import("acorn").MemberExpression} */ (node);
44
+ return !computed && "name" in property ? property.name : literal(property);
45
+ }
46
+ return null;
47
+ }
48
+
49
+ /** @param {import("acorn").Node | undefined} node */
50
+ function isImportMetaUrl(node) {
51
+ if (node?.type !== "MemberExpression") return false;
52
+ const member = /** @type {import("acorn").MemberExpression} */ (node);
53
+ return (
54
+ nameOf(member) === "url" &&
55
+ member.object.type === "MetaProperty" &&
56
+ member.object.meta.name === "import"
57
+ );
58
+ }
59
+
60
+ /** @param {string} source @param {URL} moduleUrl @param {URL} documentUrl @param {Reference} add */
61
+ function scriptReferences(source, moduleUrl, documentUrl, add) {
62
+ let tree;
63
+ try {
64
+ tree = parseScript(source, {
65
+ ecmaVersion: "latest",
66
+ sourceType: "module",
67
+ allowReturnOutsideFunction: true,
68
+ });
69
+ } catch (error) {
70
+ if (!(error instanceof SyntaxError)) throw error;
71
+ tree = parseScript(source, {
72
+ ecmaVersion: "latest",
73
+ sourceType: "script",
74
+ allowReturnOutsideFunction: true,
75
+ });
76
+ }
77
+ /** @param {import("acorn").Node | null | undefined} node @param {URL} base */
78
+ const ref = (node, base) => {
79
+ const url = literal(node);
80
+ if (url) add(url, base);
81
+ };
82
+ /** @param {import("acorn").Node|null|undefined} node */
83
+ const moduleRef = (node) => {
84
+ const specifier = literal(node);
85
+ if (specifier && /^(?:\.\.?\/|\/)/.test(specifier)) add(specifier, moduleUrl);
86
+ };
87
+ simple(tree, {
88
+ ImportDeclaration: (n) => moduleRef(n.source),
89
+ ExportNamedDeclaration: (n) => moduleRef(n.source),
90
+ ExportAllDeclaration: (n) => moduleRef(n.source),
91
+ ImportExpression: (n) => moduleRef(n.source),
92
+ AssignmentExpression(n) {
93
+ if (n.left.type === "MemberExpression" && ["src", "poster"].includes(String(nameOf(n.left))))
94
+ ref(n.right, documentUrl);
95
+ },
96
+ CallExpression(n) {
97
+ const name = nameOf(n.callee);
98
+ if (name === "fetch") ref(n.arguments[0], documentUrl);
99
+ if (name === "setAttribute" && ["src", "poster"].includes(String(literal(n.arguments[0]))))
100
+ ref(n.arguments[1], documentUrl);
101
+ },
102
+ NewExpression(n) {
103
+ if (nameOf(n.callee) === "Audio") ref(n.arguments[0], documentUrl);
104
+ if (nameOf(n.callee) === "FontFace") {
105
+ const source = literal(n.arguments[1]);
106
+ if (source) cssReferences(source, documentUrl, add, "value");
107
+ }
108
+ const base = n.arguments[1];
109
+ if (nameOf(n.callee) === "URL" && isImportMetaUrl(base)) ref(n.arguments[0], moduleUrl);
110
+ },
111
+ });
112
+ }
113
+
114
+ const SOURCE_TAGS = new Set([
115
+ "img",
116
+ "video",
117
+ "audio",
118
+ "source",
119
+ "track",
120
+ "script",
121
+ "iframe",
122
+ "embed",
123
+ "input",
124
+ ]);
125
+ const SVG_HREF_TAGS = new Set(["use", "image", "feimage"]);
126
+ const RESOURCE_RELS = /(?:^|\s)(?:stylesheet|icon|preload|modulepreload)(?:\s|$)/i;
127
+ const JS_TYPE = /^(?:module|(?:(?:text|application)\/(?:java|ecma)script)(?:\s*;.*)?)?$/i;
128
+
129
+ /** @param {import("@hyperframes/parsers/html-attribute-spans").HtmlOpeningTagSpan} tag */
130
+ function attributes(tag) {
131
+ /** @type {Map<string, string>} */
132
+ const values = new Map();
133
+ for (const attr of tag.attributes) {
134
+ if (attr.kind === "value" && !values.has(attr.name))
135
+ values.set(attr.name, decodeAuthoredAttribute(attr.value));
136
+ }
137
+ return values;
138
+ }
139
+
140
+ /** @param {string} tag @param {Map<string,string>} attrs */
141
+ function resourceAttributes(tag, attrs) {
142
+ const names = [];
143
+ if (SOURCE_TAGS.has(tag)) names.push("src");
144
+ if (tag === "video") names.push("poster");
145
+ if (tag === "object") names.push("data");
146
+ if (SVG_HREF_TAGS.has(tag)) names.push(attrs.has("href") ? "href" : "xlink:href");
147
+ if (tag === "link" && RESOURCE_RELS.test(attrs.get("rel") ?? "")) names.push("href");
148
+ return names;
149
+ }
150
+
151
+ /** @param {Map<string,string>} attrs @param {URL} base @param {Reference} add */
152
+ function compositionReference(attrs, base, add) {
153
+ const child = attrs.get("data-composition-src");
154
+ if (child)
155
+ add(child, base, {
156
+ id: (
157
+ attrs.get("data-hf-original-composition-id") ||
158
+ attrs.get("data-composition-id") ||
159
+ ""
160
+ ).trim(),
161
+ values: overrides(attrs.get("data-variable-values") ?? null),
162
+ });
163
+ }
164
+
165
+ /** @param {string} tag @param {Map<string,string>} attrs @param {URL} base @param {Reference} add */
166
+ function attributeReferences(tag, attrs, base, add) {
167
+ compositionReference(attrs, base, add);
168
+ for (const name of resourceAttributes(tag, attrs)) {
169
+ const value = attrs.get(name);
170
+ if (value) add(value, base);
171
+ }
172
+ const srcset = tag === "link" ? attrs.get("imagesrcset") : attrs.get("srcset");
173
+ if (srcset && ["img", "source", "link"].includes(tag))
174
+ rewriteSrcsetUrls(srcset, (value) => {
175
+ add(value, base);
176
+ return value;
177
+ });
178
+ const style = attrs.get("style");
179
+ if (style) cssReferences(style, base, add, "declarationList");
180
+ }
181
+
182
+ /** @param {string} tag @param {Map<string,string>} attrs @param {string} body @param {URL} base @param {Reference} add */
183
+ function inlineReferences(tag, attrs, body, base, add) {
184
+ if (tag === "style") cssReferences(body, base, add, "stylesheet");
185
+ if (tag === "script" && !attrs.has("src") && JS_TYPE.test(attrs.get("type") ?? ""))
186
+ scriptReferences(body, base, base, add);
187
+ }
188
+
189
+ /** @param {string} source @param {URL} url @param {Reference} add */
190
+ function htmlReferences(source, url, add) {
191
+ const tags = scanHtmlOpeningTags(source);
192
+ const baseTag = tags.find((tag) => tag.name === "base" && attributes(tag).has("href"));
193
+ const base = baseTag ? new URL(attributes(baseTag).get("href") ?? "", url) : url;
194
+ const mediaSlots = variableReferences(source, (value) => add(value, base));
195
+ for (const tag of tags) {
196
+ const attrs = attributes(tag);
197
+ attributeReferences(tag.name, attrs, base, add);
198
+ if (tag.rawTextEnd !== null)
199
+ inlineReferences(tag.name, attrs, source.slice(tag.end, tag.rawTextEnd), base, add);
200
+ }
201
+ return { base, mediaSlots };
202
+ }
203
+
204
+ /** @param {string} path @param {string} source @param {URL} url @param {URL} documentUrl @param {Reference} add */
205
+ export function collectAssetReferences(path, source, url, documentUrl, add) {
206
+ if (/\.css$/i.test(path)) cssReferences(source, url, add, "stylesheet");
207
+ else if (/\.[cm]?js$/i.test(path)) scriptReferences(source, url, documentUrl, add);
208
+ else return htmlReferences(source, url, add);
209
+ }
@@ -16,6 +16,7 @@ import {
16
16
  classifyPath,
17
17
  excludedFolder,
18
18
  isPrivateSourcePath,
19
+ isEligibleHiddenSourcePath,
19
20
  prefiltered,
20
21
  skippedSymlink,
21
22
  validatePath,
@@ -43,9 +44,18 @@ async function visit(root, rel, entry, walk, dirs) {
43
44
  if (!excludedFolder(rel)) dirs.push(rel);
44
45
  return;
45
46
  }
46
- const action = classifyPath(rel).client_action;
47
+ const rule = classifyPath(rel);
48
+ if (rule.id === "hidden-asset") {
49
+ if (entry.isFile() && isEligibleHiddenSourcePath(rel)) await visitFile(root, rel, walk, true);
50
+ return;
51
+ }
52
+ const action = rule.client_action;
47
53
  if (action === "exclude") return;
48
54
  if (action === "wait_then_exclude") return void walk.waiting.push(rel);
55
+ await visitPortableEntry(root, rel, entry, walk);
56
+ }
57
+ /** @param {string} root @param {string} rel @param {import("node:fs").Dirent} entry @param {Walk} walk */
58
+ async function visitPortableEntry(root, rel, entry, walk) {
49
59
  if (entry.isSymbolicLink()) {
50
60
  if (skippedSymlink(rel)) walk.skippedLinks.push(rel);
51
61
  else walk.problems.push({ path: rel, problem: "symlink" });
@@ -54,18 +64,30 @@ async function visit(root, rel, entry, walk, dirs) {
54
64
  if (!entry.isFile()) return void walk.problems.push({ path: rel, problem: "special-file" });
55
65
  await visitFile(root, rel, walk);
56
66
  }
57
- /** @param {string} root @param {string} rel @param {Walk} walk */
58
- async function visitFile(root, rel, walk) {
67
+ /** @param {string} root @param {string} rel @param {Walk} walk @param {boolean} [includeHidden] */
68
+ async function visitFile(root, rel, walk, includeHidden = false) {
59
69
  try {
60
- validatePath(rel);
70
+ validatePath(rel, "current", includeHidden);
61
71
  } catch (error) {
62
72
  if (!(error instanceof PathViolation)) throw error;
63
- return void walk.problems.push({ path: rel, problem: "invalid-name", code: error.code });
73
+ return void walk.problems.push({
74
+ path: rel,
75
+ problem: "invalid-name",
76
+ code: error.code,
77
+ });
64
78
  }
65
79
  const full = join(root, rel);
66
80
  try {
67
81
  const { size, mtimeMs, ino, dev } = await lstat(full);
68
- walk.files.push({ path: rel, full, size, mtimeMs, ino, dev });
82
+ walk.files.push({
83
+ path: rel,
84
+ full,
85
+ size,
86
+ mtimeMs,
87
+ ino,
88
+ dev,
89
+ ...(includeHidden && { include_hidden: true }),
90
+ });
69
91
  } catch {
70
92
  walk.problems.push({ path: rel, problem: "unreadable" });
71
93
  }
@@ -88,11 +110,17 @@ async function listFolder(root, dir) {
88
110
  }
89
111
 
90
112
  /** Every file a capture would list, and what keeps one from being listed. @param {string} root
91
- * @param {(rel: string) => boolean} renderOutput @returns {Promise<Walk>} */
92
- async function walkProject(root, renderOutput) {
113
+ * @param {(rel: string) => boolean} renderOutput @param {import("../sourceIgnore.mjs").SourceIgnore} ignored
114
+ * @returns {Promise<Walk>} */
115
+ async function walkProject(root, renderOutput, ignored) {
93
116
  /** @type {Walk} */
94
- const walk = { files: [], problems: [], waiting: [], skippedLinks: [] };
95
- const ignored = await readSourceIgnore(root);
117
+ const walk = {
118
+ files: [],
119
+ problems: [],
120
+ waiting: [],
121
+ skippedLinks: [],
122
+ directoryEntries: new Map(),
123
+ };
96
124
  const dirs = [""];
97
125
  for (let dir = dirs.pop(); dir !== undefined; dir = dirs.pop()) {
98
126
  let entries;
@@ -100,25 +128,68 @@ async function walkProject(root, renderOutput) {
100
128
  entries = await listFolder(root, dir);
101
129
  } catch (error) {
102
130
  const changed = error instanceof FolderMoved;
103
- walk.problems.push({ path: dir, problem: changed ? "changed" : "unreadable" });
131
+ walk.problems.push({
132
+ path: dir,
133
+ problem: changed ? "changed" : "unreadable",
134
+ });
104
135
  continue;
105
136
  }
137
+ walk.directoryEntries.set(dir, new Set(entries.map((entry) => entry.name)));
106
138
  for (const entry of entries) {
107
139
  const rel = dir ? `${dir}/${entry.name}` : entry.name;
108
- if (prefiltered(entry.name) || renderOutput(rel) || ignored(rel)) continue;
140
+ if (prefiltered(entry.name) || renderOutput(rel) || ignored(rel, entry.isDirectory()))
141
+ continue;
109
142
  await visit(root, rel, entry, walk, dirs);
110
143
  }
111
144
  }
112
145
  return walk;
113
146
  }
114
147
 
148
+ /** @param {string} root @param {Walk} walk */
149
+ async function selectDependencies(root, walk) {
150
+ if (!walk.files.some((file) => file.include_hidden)) return new Map();
151
+ const { retainReferencedFiles } = await import("./referencedFiles.mjs");
152
+ return retainReferencedFiles(root, walk, openListed);
153
+ }
154
+
155
+ /** Paths included by a normal editable Share or Send. A host can reuse the project rules from its inventory walk.
156
+ * @param {string} root @param {Map<string,string>} [observed]
157
+ * @param {{ignored: import("../sourceIgnore.mjs").SourceIgnore, ignoreSyntax?: never} |
158
+ * {ignored?: never, ignoreSyntax?: import("../sourceIgnore.mjs").SourceIgnoreSyntax}} [options] */
159
+ export async function listReferencedHiddenSourceAssets(
160
+ root,
161
+ observed,
162
+ { ignored, ignoreSyntax } = {},
163
+ ) {
164
+ observed?.clear();
165
+ const dir = await realpath(root);
166
+ const walk = await walkProject(
167
+ dir,
168
+ await readRenderOutputs(dir),
169
+ ignored ?? (await readSourceIgnore(dir, { syntax: ignoreSyntax })),
170
+ );
171
+ const before = walk.problems.length;
172
+ const hashes = await selectDependencies(dir, walk);
173
+ if (walk.problems.length > before) throw new Error("Cannot verify project asset references");
174
+ if (observed) for (const [path, hash] of hashes) observed.set(path, hash);
175
+ return walk.files
176
+ .filter((file) => file.include_hidden)
177
+ .map((file) => file.path)
178
+ .sort();
179
+ }
180
+
115
181
  /** The manifest's canonical length, from paths and sizes alone: every SHA-256 is 64 characters.
116
182
  * @param {Found[]} files */
117
183
  const manifestBytes = (files) =>
118
184
  canonicalBytes({
119
185
  format_version: 1,
120
186
  entrypoint: ENTRYPOINT,
121
- files: files.map(({ path, size }) => ({ path, sha256: "0".repeat(64), size })),
187
+ files: files.map(({ path, size, include_hidden }) => ({
188
+ path,
189
+ sha256: "0".repeat(64),
190
+ size,
191
+ include_hidden,
192
+ })),
122
193
  }).length;
123
194
 
124
195
  /** A file changed this recently can be written again within its time's granularity, keeping its size and time. */
@@ -148,7 +219,7 @@ export function hashMemo(now = Date.now) {
148
219
  * opened file is the same regular file (inode, device, size) found inside the project, so a file or folder swapped
149
220
  * for a link after the walk is refused rather than followed. Null when it is not. @param {string} root
150
221
  * @param {Found} file @param {typeof realpath} [resolve] */
151
- async function openListed(root, file, resolve = realpath) {
222
+ export async function openListed(root, file, resolve = realpath) {
152
223
  const handle = await open(file.full, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)).catch(
153
224
  (/** @type {NodeJS.ErrnoException} */ error) => {
154
225
  if (error.code === "ELOOP" || error.code === "EMLINK") return null;
@@ -210,7 +281,12 @@ async function hashAll(root, files, memo) {
210
281
  else if (sha256 === null) problems.push({ path: file.path, problem: "changed" });
211
282
  else {
212
283
  memo.set(file, sha256);
213
- hashed.push({ path: file.path, sha256, size: file.size });
284
+ hashed.push({
285
+ path: file.path,
286
+ sha256,
287
+ size: file.size,
288
+ ...(file.include_hidden && { include_hidden: true }),
289
+ });
214
290
  }
215
291
  }
216
292
  };
@@ -233,19 +309,37 @@ function inventoryProblems(files) {
233
309
  }
234
310
 
235
311
  /** Captures `root` (a project's real path). `memo` reuses hashes of unchanged files; a send should pass a fresh one.
236
- * @param {string} root @param {{ memo?: ReturnType<typeof hashMemo>, limits?: import("./types.js").Limits }} [options]
312
+ * @param {string} root @param {{ memo?: ReturnType<typeof hashMemo>, limits?: import("./types.js").Limits,
313
+ * ignoreSyntax?: import("../sourceIgnore.mjs").SourceIgnoreSyntax }} [options]
237
314
  * @returns {Promise<Capture>} */
238
- export async function captureProject(root, { memo = hashMemo(), limits = V1_LIMITS } = {}) {
239
- const renderOutput = await readRenderOutputs(root);
240
- const walk = await walkProject(root, renderOutput);
315
+ export async function captureProject(
316
+ root,
317
+ { memo = hashMemo(), limits = V1_LIMITS, ignoreSyntax } = {},
318
+ ) {
319
+ root = await realpath(root);
320
+ const walk = await walkProject(
321
+ root,
322
+ await readRenderOutputs(root),
323
+ await readSourceIgnore(root, { syntax: ignoreSyntax }),
324
+ );
325
+ const references = await selectDependencies(root, walk);
241
326
  const problems = walk.problems.length ? walk.problems : inventoryProblems(walk.files);
242
327
  if (problems.length) return { at: "problems", problems };
243
328
  const over = overLimit(walk.files, manifestBytes(walk.files), limits);
244
329
  if (over) return { at: "too-big", over };
245
330
  const { hashed, problems: unhashed } = await hashAll(await realpath(root), walk.files, memo);
331
+ for (const file of hashed) {
332
+ const referenceHash = references.get(file.path);
333
+ if (referenceHash && file.sha256 !== referenceHash)
334
+ unhashed.push({ path: file.path, problem: "changed" });
335
+ }
246
336
  if (unhashed.length) return { at: "problems", problems: unhashed };
247
337
  try {
248
- const manifest = parseManifest({ format_version: 1, entrypoint: ENTRYPOINT, files: hashed });
338
+ const manifest = parseManifest({
339
+ format_version: 1,
340
+ entrypoint: ENTRYPOINT,
341
+ files: hashed,
342
+ });
249
343
  const settled = await settledState(root);
250
344
  return {
251
345
  at: "captured",
@@ -13,6 +13,9 @@
13
13
  "sha256",
14
14
  "size"
15
15
  ],
16
+ "optional_file_fields": {
17
+ "include_hidden": "The literal true on a hidden-asset entry marks that exact hidden path as a project dependency included in this upload. Omit this field on every other entry."
18
+ },
16
19
  "sha256": "64 lowercase hex characters: the SHA-256 of the file's exact bytes",
17
20
  "size": "the file's byte length, an integer from 0 to 9007199254740991 (2^53 - 1, the largest integer every JSON client reads exactly)",
18
21
  "same_digest_same_size": "two entries with the same sha256 must have the same size",
@@ -327,7 +330,7 @@
327
330
  },
328
331
  {
329
332
  "id": "portable-transcripts",
330
- "regex": "\\.hyperframes/transcripts/(?:[^/]+/)*[^/]+\\.json",
333
+ "regex": "\\.hyperframes/transcripts/(?:[^./][^/]*/)*[^./][^/]*\\.json",
331
334
  "client_action": "include",
332
335
  "server_action": "allow",
333
336
  "basis": "Completed transcripts, keyed by media hash; costly to regenerate"
@@ -362,7 +365,7 @@
362
365
  },
363
366
  {
364
367
  "id": "portable-podcast-media",
365
- "regex": "\\.hyperframes/prepared-assets/podcast/(?:[^/]+/)*[^./][^/]*",
368
+ "regex": "\\.hyperframes/prepared-assets/podcast/(?:[^./][^/]*/)*[^./][^/]*",
366
369
  "client_action": "include",
367
370
  "server_action": "allow",
368
371
  "basis": "Desktop's podcast camera and recorder transcodes (media/, proxies/), which the page plays by this path and a receiving client cannot regenerate without the original files; a dotfile there stays out"
@@ -416,6 +419,27 @@
416
419
  "server_action": "reject",
417
420
  "basis": "Third-party reference video, large and re-downloadable"
418
421
  },
422
+ {
423
+ "id": "portable-hidden-sources",
424
+ "regex": "(?:[^./][^/]*/)*(?:\\.gitignore|\\.vsignore|\\.hyperframesignore)|\\.media/(?:[^./][^/]*/)*[^./][^/]*|\\.github/(?:agents\\.md|workflows/(?:[^./][^/]*/)*[^./][^/]*\\.ya?ml|instructions/(?:[^./][^/]*/)*[^./][^/]*\\.md)",
425
+ "client_action": "include",
426
+ "server_action": "allow",
427
+ "basis": "Portable project ignore files, root media assets and authored GitHub metadata."
428
+ },
429
+ {
430
+ "id": "hidden-asset",
431
+ "regex": "(?!.*(?:^|/)(?:\\.next|\\.nuxt|\\.output|\\.svelte-kit|\\.vercel|\\.netlify|\\.wrangler|\\.astro|\\.turbo|\\.venv|\\.github)(?:/|$))(?=(?:[^/]+/)*\\.[^/]+/)(?:[^/]+/)+[^./][^/]*\\.(?:png|jpe?g|gif|webp|avif|svg|ico|bmp|tiff?|heic|heif|mp4|m4v|mov|webm|mkv|mxf|avi|mp3|wav|m4a|aac|ogg|oga|opus|flac|woff2?|ttf|otf|css|m?js|cjs)",
432
+ "client_action": "exclude",
433
+ "server_action": "reject",
434
+ "basis": "A referenced project asset in a hidden directory may travel only with include_hidden: true. Both the folded path and parser spelling must match this rule. Earlier exclusions take precedence."
435
+ },
436
+ {
437
+ "id": "unrecognized-hidden",
438
+ "regex": "(?:[^/]+/)*\\.[^/]*(?:/.*)?",
439
+ "client_action": "exclude",
440
+ "server_action": "reject",
441
+ "basis": "Hidden paths stay local unless a portable HyperFrames rule names them, or they are ordinary media-library files, ignore files or recognized GitHub project metadata. This file rule must not prune directories containing allowed descendants."
442
+ },
419
443
  {
420
444
  "id": "default-authored-file",
421
445
  "regex": ".+",
@@ -455,7 +479,12 @@
455
479
  "git-directory-head": "(?!)",
456
480
  "nested-hyperframes-state": "(?!)",
457
481
  "credential-files": "(?:[^/]+/)*(?:\\.netrc|\\.pypirc|\\.git-credentials|[^/]*\\.(?:pem|p12|pfx)|id_rsa[^/]*|id_ed25519[^/]*|(?:\\.ssh|\\.aws)(?:/.*)?)",
458
- "private-source": "(?!)"
482
+ "private-source": "(?!)",
483
+ "hidden-asset": "(?!)",
484
+ "unrecognized-hidden": "(?!)",
485
+ "portable-hidden-sources": "(?!)",
486
+ "portable-transcripts": "\\.hyperframes/transcripts/(?:[^/]+/)*[^/]+\\.json",
487
+ "portable-podcast-media": "\\.hyperframes/prepared-assets/podcast/(?:[^/]+/)*[^./][^/]*"
459
488
  },
460
489
  "legacy_short_name_alias_names": [
461
490
  ".agent",
@@ -46,18 +46,20 @@ function fileOf(raw, out, policy) {
46
46
  if (!isObject(raw)) return (out.push({ code: "invalid_schema" }), null);
47
47
  const before = out.length;
48
48
  const { path, sha256, size } = raw;
49
+ if ("include_hidden" in raw && raw.include_hidden !== true) out.push({ code: "invalid_schema" });
50
+ const marker = raw.include_hidden === true ? { include_hidden: /** @type {const} */ (true) } : {};
49
51
  if (typeof path !== "string") out.push({ code: "invalid_schema" });
50
52
  else {
51
53
  try {
52
- validatePath(path, policy.mode);
54
+ validatePath(path, policy.mode, marker.include_hidden);
53
55
  } catch (error) {
54
56
  policy.pathErrors.push(violationOf(error));
55
57
  }
56
58
  }
57
59
  checkBlob(sha256, size, out);
58
- unknownFields(raw, ["path", "sha256", "size"], out);
60
+ unknownFields(raw, ["path", "sha256", "size", "include_hidden"], out);
59
61
  return out.length === before
60
- ? { path: String(path), sha256: String(sha256), size: Number(size) }
62
+ ? { path: String(path), sha256: String(sha256), size: Number(size), ...marker }
61
63
  : null;
62
64
  }
63
65
 
@@ -109,8 +111,8 @@ function filesOf(raw, out, policy) {
109
111
  export function canonicalBytes(document) {
110
112
  const files = document.files
111
113
  .map(
112
- ({ path, sha256, size }) =>
113
- `{"path":${JSON.stringify(path)},"sha256":${JSON.stringify(sha256)},"size":${size}}`,
114
+ ({ path, sha256, size, include_hidden }) =>
115
+ `{${include_hidden ? '"include_hidden":true,' : ""}"path":${JSON.stringify(path)},"sha256":${JSON.stringify(sha256)},"size":${size}}`,
114
116
  )
115
117
  .join(",");
116
118
  const text = `{"entrypoint":${JSON.stringify(document.entrypoint)},"files":[${files}],"format_version":${document.format_version}}`;
@@ -113,16 +113,32 @@ const foldedPath = (path) => path.split("/").map(comparisonKey).join("/");
113
113
  /** @param {{ pattern: RegExp, rule: PathRule }} entry @param {string} folded @param {string} path */
114
114
  const matches = ({ pattern, rule }, folded, path) =>
115
115
  pattern.test(folded) ||
116
- (rule.id === "private-source" && pattern.test(privateSourceSpelling(path)));
116
+ ((rule.id === "private-source" || rule.id === "unrecognized-hidden") &&
117
+ pattern.test(privateSourceSpelling(path)));
117
118
 
118
119
  /** The first rule matching a path's folded spelling. @param {string} path @returns {PathRule} */
119
120
  export function classifyPath(path) {
120
121
  const folded = foldedPath(path);
121
- const found = policy().rules.find((entry) => matches(entry, folded, path));
122
+ const found = policy().rules.find((entry) =>
123
+ entry.rule.id === "portable-hidden-sources"
124
+ ? entry.pattern.test(path) && entry.pattern.test(folded)
125
+ : matches(entry, folded, path),
126
+ );
122
127
  if (!found) throw new Error("the path policy's catch-all rule did not match");
123
128
  return found.rule;
124
129
  }
125
130
 
131
+ /** @param {string} path */
132
+ export function isEligibleHiddenSourcePath(path) {
133
+ try {
134
+ validatePath(path, "current", true);
135
+ return true;
136
+ } catch (error) {
137
+ if (!(error instanceof PathViolation)) throw error;
138
+ return false;
139
+ }
140
+ }
141
+
126
142
  /** Checks 1 to 10 of the registry's `path.checks`: the ones about the string itself. @param {string} path @param {boolean} localV4 */
127
143
  function checkSpelling(path, localV4) {
128
144
  const { limits, invalidCharacter } = policy();
@@ -162,8 +178,8 @@ function isShortNameAlias(key, stems) {
162
178
 
163
179
  /** `path` unchanged when every client can store it and the policy lets it travel; throws PathViolation otherwise,
164
180
  * naming the first failing check in the registry's order. @param {string} path
165
- * @param {PathMode} [mode] */
166
- export function validatePath(path, mode = "current") {
181
+ * @param {PathMode} [mode] @param {boolean} [includeHidden] */
182
+ export function validatePath(path, mode = "current", includeHidden = false) {
167
183
  const segments = checkSpelling(path, mode === "localV4");
168
184
  const keys = segments.map(mode === "localV4" ? v4ComparisonKey : comparisonKey);
169
185
  const { reservedSegment, canonicalRoots } = policy();
@@ -177,6 +193,7 @@ export function validatePath(path, mode = "current") {
177
193
  const folded = keys.join("/");
178
194
  const found = rules.find((entry) => matches(entry, folded, path));
179
195
  if (!found) throw new Error("the path policy's catch-all rule did not match");
196
+ if (includeHidden && mode === "current") return validateHiddenSelection(path, found.rule);
180
197
  if (found.rule.server_action === "reject")
181
198
  throw new PathViolation("excluded_path", path, found.rule.id);
182
199
  if (!found.pattern.test(path))
@@ -184,6 +201,16 @@ export function validatePath(path, mode = "current") {
184
201
  return path;
185
202
  }
186
203
 
204
+ /** @param {string} path @param {PathRule} rule */
205
+ function validateHiddenSelection(path, rule) {
206
+ if (rule.server_action === "allow") throw new PathViolation("invalid_schema", path);
207
+ if (rule.id !== "hidden-asset") throw new PathViolation("excluded_path", path, rule.id);
208
+ const normalized = classifyPath(privateSourceSpelling(path));
209
+ if (normalized.id !== "hidden-asset")
210
+ throw new PathViolation("excluded_path", path, normalized.id);
211
+ return path;
212
+ }
213
+
187
214
  /** Refuses duplicates, and any two paths (or a path and a directory prefix) one filesystem would store as one name.
188
215
  * Each path must already pass validatePath. @param {readonly string[]} paths @param {(value: string) => string} [keyOf] */
189
216
  export function checkInventoryPaths(paths, keyOf = comparisonKey) {
@@ -240,7 +267,10 @@ export function excludedFolder(dir) {
240
267
  const folded = foldedPath(dir);
241
268
  const at = policy().rules.findIndex(
242
269
  ({ pattern, rule }) =>
243
- rule.client_action !== "include" && pattern.test(folded) && pattern.test(`${folded}/x`),
270
+ rule.id !== "unrecognized-hidden" &&
271
+ rule.client_action !== "include" &&
272
+ pattern.test(folded) &&
273
+ pattern.test(`${folded}/x`),
244
274
  );
245
275
  if (at < 0) return false;
246
276
  return policy()
@@ -252,11 +282,12 @@ export function excludedFolder(dir) {
252
282
  });
253
283
  }
254
284
 
255
- /** A stored manifest may contain paths that are no longer eligible for upload. @param {string} path */
256
- export function canUploadStoredPath(path) {
285
+ /** Can an unconfirmed Begin replay this stored entry under today's rules?
286
+ * @param {import("./types.js").ManifestFile} file */
287
+ export function canReplayUploadFile({ path, include_hidden }) {
257
288
  if (isPrivateSourcePath(path)) return false;
258
289
  try {
259
- validatePath(path);
290
+ validatePath(path, "current", include_hidden === true);
260
291
  return true;
261
292
  } catch (error) {
262
293
  if (error instanceof PathViolation) return false;