@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.
@@ -0,0 +1,221 @@
1
+ // @ts-check
2
+ import { createHash } from "node:crypto";
3
+ import { decodeTextHonoringBom } from "@hyperframes/parsers/asset-resolution";
4
+ import { mountedAsset } from "./variableAssets.mjs";
5
+ import { collectAssetReferences } from "./assetReferences.mjs";
6
+
7
+ /** @typedef {import("./types.js").Found} Found @typedef {import("./types.js").Walk} Walk */
8
+ const PROJECT = "https://project.invalid";
9
+ const sourcePath = /\.(?:html?|svg|css|[cm]?js)$/i;
10
+ const scriptPath = /\.[cm]?js$/i;
11
+ const maxSourceBytes = 16 * 1024 * 1024;
12
+ const maxGraphBytes = 64 * 1024 * 1024;
13
+ const maxReferences = 100_000;
14
+ /** Script references use either the module URL or the importing document's base URL. */
15
+ const importingDocument = new URL("https://document.invalid");
16
+
17
+ /** @param {string} path */
18
+ const urlOf = (path) => new URL(path.split("/").map(encodeURIComponent).join("/"), PROJECT);
19
+
20
+ /** Resolve against the inventory of regular, portable files; a reference never grants filesystem access.
21
+ * @param {string} raw @param {URL} base @param {ReadonlyMap<string, Found>} files
22
+ * @param {Walk["directoryEntries"]} directories */
23
+ function referencedPath(raw, base, files, directories, allowFallback = true) {
24
+ const value = raw.trim();
25
+ if (!value || /^(?:[?#]|[a-z][a-z\d+.-]*:|[/\\]{2})/i.test(value)) return null;
26
+ try {
27
+ const url = new URL(value, base);
28
+ if (url.origin !== PROJECT || /%2f|%5c/i.test(url.pathname)) return null;
29
+ const path = decodeURIComponent(url.pathname.slice(1));
30
+ if (files.has(path)) return path;
31
+ return allowFallback ? rootFallback(value, base, files, path, directories) : null;
32
+ } catch {
33
+ /* A malformed or external URL cannot name an inventory entry. */
34
+ }
35
+ return null;
36
+ }
37
+
38
+ /** A nested composition can fall back to the root only when its sibling is missing. An entry
39
+ * skipped during capture, including a symlink or pruned directory, shadows the root candidate.
40
+ * @param {string} value @param {URL} base @param {ReadonlyMap<string, Found>} files
41
+ * @param {string} sibling @param {Walk["directoryEntries"]} directories */
42
+ function rootFallback(value, base, files, sibling, directories) {
43
+ if (!/\.html?$/i.test(base.pathname) || /^(?:\.{1,2}\/|\/)/.test(value)) return null;
44
+ let directory = "";
45
+ for (const name of sibling.split("/")) {
46
+ const entries = directories.get(directory);
47
+ if (!entries) return null;
48
+ if (!entries.has(name)) {
49
+ const path = decodeURIComponent(new URL(value, PROJECT).pathname.slice(1));
50
+ return files.has(path) ? path : null;
51
+ }
52
+ directory = directory ? directory + "/" + name : name;
53
+ }
54
+ return null;
55
+ }
56
+
57
+ /** @param {string} root @param {Found} file @param {typeof import("./capture.mjs").openListed} openListed */
58
+ async function readSource(root, file, openListed) {
59
+ if (file.size > maxSourceBytes) throw new Error("Dependency source exceeds the scan limit");
60
+ const handle = await openListed(root, file);
61
+ if (!handle) return null;
62
+ try {
63
+ // Bound the read even if another process grows the file after it was opened.
64
+ const bytes = Buffer.alloc(file.size);
65
+ let at = 0;
66
+ while (at < bytes.length) {
67
+ const { bytesRead } = await handle.read(bytes, at, bytes.length - at, at);
68
+ if (!bytesRead) return null;
69
+ at += bytesRead;
70
+ }
71
+ const after = await handle.stat();
72
+ if (after.mtimeMs !== file.mtimeMs || after.size !== file.size) return null;
73
+ return bytes;
74
+ } finally {
75
+ await handle.close();
76
+ }
77
+ }
78
+
79
+ /** @typedef {import("./assetReferences.mjs").Host & { ordinal: number }} Mount
80
+ * @typedef {{ value: string, base: URL, mount?: Mount }} AssetReference
81
+ * @typedef {{ references: AssetReference[], html: ReturnType<typeof collectAssetReferences> }} Scanned */
82
+
83
+ /** @param {string} root @param {typeof import("./capture.mjs").openListed} openListed
84
+ * @param {Map<string, string>} hashes */
85
+ function referenceReader(root, openListed, hashes) {
86
+ /** @type {Map<string, Scanned>} */
87
+ const cache = new Map();
88
+ let bytesRemaining = maxGraphBytes;
89
+ let referencesRemaining = maxReferences;
90
+ /** @param {Found} file @returns {Promise<Scanned | null>} */
91
+ return async function referencesFor(file) {
92
+ const cached = cache.get(file.path);
93
+ if (cached) return cached;
94
+ bytesRemaining -= file.size;
95
+ if (bytesRemaining < 0) throw new Error("Project dependency sources exceed the scan limit");
96
+ const bytes = await readSource(root, file, openListed);
97
+ if (!bytes) return null;
98
+ /** @type {AssetReference[]} */
99
+ const references = [];
100
+ const html = collectAssetReferences(
101
+ file.path,
102
+ decodeTextHonoringBom(bytes),
103
+ urlOf(file.path),
104
+ importingDocument,
105
+ (value, base, host) => {
106
+ if (--referencesRemaining < 0)
107
+ throw new Error("Project dependency references exceed the scan limit");
108
+ references.push({
109
+ value,
110
+ base,
111
+ ...(host && { mount: { ...host, ordinal: referencesRemaining } }),
112
+ });
113
+ },
114
+ );
115
+ hashes.set(file.path, createHash("sha256").update(bytes).digest("hex"));
116
+ const scanned = { references, html };
117
+ cache.set(file.path, scanned);
118
+ return scanned;
119
+ };
120
+ }
121
+
122
+ /** @param {AssetReference[]} references @param {Found} file @param {URL} documentUrl
123
+ * @param {Map<string, Found>} inventory @param {Walk["directoryEntries"]} directories
124
+ * @param {{ edges: number, urlCharacters: number }} remaining */
125
+ function* targets(references, file, documentUrl, inventory, directories, remaining) {
126
+ remaining.edges -= references.length;
127
+ if (remaining.edges < 0) throw new Error("Project dependency graph exceeds the scan limit");
128
+ for (const { value, base, mount } of references) {
129
+ const context = base === importingDocument ? documentUrl : base;
130
+ remaining.urlCharacters -= value.length + context.href.length;
131
+ if (remaining.urlCharacters < 0)
132
+ throw new Error("Dependency URL resolution exceeds the scan limit");
133
+ const path = referencedPath(value, context, inventory, directories);
134
+ if (path)
135
+ yield { path, mount, documentUrl: /\.html?$/i.test(file.path) ? context : documentUrl };
136
+ }
137
+ }
138
+
139
+ /** @param {Scanned} scanned @param {Mount|undefined} mount @param {URL} base
140
+ * @param {{edges:number,urlCharacters:number}} remaining @param {Map<string,Found>} inventory @param {Walk["directoryEntries"]} dirs */
141
+ function* mountedTargets(scanned, mount, base, remaining, inventory, dirs) {
142
+ if (!mount || !scanned.html?.mediaSlots) return;
143
+ for (const [id, value] of Object.entries(mount.values)) {
144
+ if (--remaining.edges < 0) throw new Error("Project dependency graph exceeds the scan limit");
145
+ const raw = mountedAsset(scanned.html.mediaSlots, mount.id, id, value);
146
+ if (!raw) continue;
147
+ remaining.urlCharacters -= raw.length + base.href.length;
148
+ if (remaining.urlCharacters < 0)
149
+ throw new Error("Dependency URL resolution exceeds the scan limit");
150
+ const path = referencedPath(raw, base, inventory, dirs, false);
151
+ if (path) yield path;
152
+ }
153
+ }
154
+
155
+ /** Keep reachable hidden dependencies and the hashes of the exact bytes used for discovery.
156
+ * @param {string} root @param {Walk} walk @param {typeof import("./capture.mjs").openListed} openListed */
157
+ export async function retainReferencedFiles(root, walk, openListed) {
158
+ /** @type {Map<string, string>} */
159
+ const hashes = new Map();
160
+ if (!walk.files.some((file) => file.include_hidden)) return hashes;
161
+ const inventory = new Map(walk.files.map((file) => [file.path, file]));
162
+ const needed = new Set();
163
+ const queued = new Set();
164
+ /** @type {{ file: Found, documentUrl: URL, mount?: Mount, pageBase?: URL }[]} */
165
+ const pending = [];
166
+ const remaining = { edges: maxReferences, urlCharacters: maxGraphBytes };
167
+
168
+ /** @param {string} path @param {URL} documentUrl @param {Mount} [mount] @param {URL} [pageBase] */
169
+ function enqueue(path, documentUrl, mount, pageBase) {
170
+ const file = inventory.get(path);
171
+ if (!file) return;
172
+ needed.add(path);
173
+ if (!sourcePath.test(path)) return;
174
+ const key = mount
175
+ ? JSON.stringify([path, mount.ordinal, pageBase?.href])
176
+ : scriptPath.test(path)
177
+ ? JSON.stringify([path, documentUrl.href])
178
+ : path;
179
+ if (queued.has(key)) return;
180
+ queued.add(key);
181
+ pending.push({ file, documentUrl, mount, pageBase });
182
+ }
183
+
184
+ const referencesFor = referenceReader(root, openListed, hashes);
185
+
186
+ enqueue("index.html", urlOf("index.html"));
187
+ for (let next = pending.pop(); next; next = pending.pop()) {
188
+ const { file, documentUrl } = next;
189
+ try {
190
+ const scanned = await referencesFor(file);
191
+ if (!scanned) {
192
+ walk.problems.push({ path: file.path, problem: "changed" });
193
+ break;
194
+ }
195
+ const pageBase = next.pageBase ?? scanned.html?.base ?? documentUrl;
196
+ for (const path of mountedTargets(
197
+ scanned,
198
+ next.mount,
199
+ pageBase,
200
+ remaining,
201
+ inventory,
202
+ walk.directoryEntries,
203
+ ))
204
+ enqueue(path, pageBase);
205
+ for (const target of targets(
206
+ scanned.references,
207
+ file,
208
+ documentUrl,
209
+ inventory,
210
+ walk.directoryEntries,
211
+ remaining,
212
+ ))
213
+ enqueue(target.path, target.documentUrl, target.mount, target.mount && pageBase);
214
+ } catch {
215
+ walk.problems.push({ path: file.path, problem: "unreadable" });
216
+ break;
217
+ }
218
+ }
219
+ walk.files = walk.files.filter((file) => !file.include_hidden || needed.has(file.path));
220
+ return hashes;
221
+ }
@@ -14,6 +14,7 @@ export interface SyncCaptureProblem {
14
14
  }
15
15
 
16
16
  export interface ManifestFile {
17
+ include_hidden?: true;
17
18
  path: string;
18
19
  sha256: string;
19
20
  size: number;
@@ -97,6 +98,7 @@ export type SyncLimitsRead =
97
98
 
98
99
  /** A file a capture lists, before hashing. */
99
100
  export interface Found {
101
+ include_hidden?: true;
100
102
  path: string;
101
103
  full: string;
102
104
  size: number;
@@ -106,6 +108,7 @@ export interface Found {
106
108
  }
107
109
 
108
110
  export interface Walk {
111
+ directoryEntries: Map<string, Set<string>>;
109
112
  files: Found[];
110
113
  problems: CaptureProblem[];
111
114
  waiting: string[];
@@ -2,7 +2,7 @@
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { join } from "node:path";
4
4
  import { NotWritable, uploadNeeded } from "./uploadFiles.mjs";
5
- import { canUploadStoredPath } from "./pathPolicy.mjs";
5
+ import { canReplayUploadFile } from "./pathPolicy.mjs";
6
6
  import { readUploadIntent } from "./manifest.mjs";
7
7
  import { SyncApiError } from "./errors.mjs";
8
8
 
@@ -124,18 +124,29 @@ async function cancelPending({ binding, api }, receipt) {
124
124
  }
125
125
  }
126
126
 
127
+ /** An unconfirmed Begin has to re-list its original files to recover its ID. Every marked file must
128
+ * still be part of the current capture with the same bytes. @param {import("./types.js").Manifest} saved
129
+ * @param {import("./types.js").Manifest} current */
130
+ function mayReplayManifest(saved, current) {
131
+ const disclosed = new Map(
132
+ current.document.files.filter((file) => file.include_hidden).map((file) => [file.path, file]),
133
+ );
134
+ return saved.document.files.every((file) => {
135
+ if (!canReplayUploadFile(file)) return false;
136
+ if (!file.include_hidden) return true;
137
+ const approved = disclosed.get(file.path);
138
+ return approved?.sha256 === file.sha256 && approved.size === file.size;
139
+ });
140
+ }
141
+
127
142
  /** Resolve an older capture before starting an upload for the current files.
128
- * @param {SourceUpload} job @returns {Promise<import("./adapterTypes.js").SourceResult | null>} */
143
+ * @param {SourceUpload & Pick<SourceRun, "manifest">} job @returns {Promise<import("./adapterTypes.js").SourceResult | null>} */
129
144
  export async function recoverSourceUpload(job) {
130
145
  const { binding, api } = job;
131
146
  const saved = binding.inflight;
132
147
  if (!saved) return null;
133
148
  const intent = readUploadIntent(saved);
134
- if (
135
- !intent ||
136
- ("manifest" in intent &&
137
- intent.manifest.document.files.some(({ path }) => !canUploadStoredPath(path)))
138
- ) {
149
+ if (!intent || ("manifest" in intent && !mayReplayManifest(intent.manifest, job.manifest))) {
139
150
  await clearIntent(job);
140
151
  return null;
141
152
  }
@@ -0,0 +1,116 @@
1
+ // @ts-check
2
+ import { DOMParser } from "linkedom";
3
+ import { readCompositionVariables } from "@hyperframes/parsers/composition";
4
+
5
+ /** @param {unknown} value @param {"url"|"source"} key */
6
+ function assetValue(value, key) {
7
+ if (typeof value === "string") return key === "url" ? value : null;
8
+ if (!value || typeof value !== "object") return null;
9
+ const path = Reflect.get(value, key);
10
+ return typeof path === "string" ? path : null;
11
+ }
12
+
13
+ /** @param {string | null} raw @returns {Record<string,unknown>} */
14
+ export function overrides(raw) {
15
+ if (!raw) return {};
16
+ try {
17
+ const value = JSON.parse(raw);
18
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
19
+ } catch {
20
+ return {};
21
+ }
22
+ }
23
+
24
+ /** @param {Element} scope */
25
+ function scopeValues(scope) {
26
+ const { declarations } = readCompositionVariables(
27
+ scope.getAttribute("data-composition-variables"),
28
+ );
29
+ const values = new Map(declarations.map((v) => [v.id, /** @type {unknown} */ (v.default)]));
30
+ for (const [key, value] of Object.entries(overrides(scope.getAttribute("data-variable-values"))))
31
+ values.set(key, value);
32
+ return { declarations, values };
33
+ }
34
+
35
+ const declaredScope = "[data-composition-variables],[data-variable-values]";
36
+ const boundMedia = "img[data-var-src],video[data-var-src],audio[data-var-src],source[data-var-src]";
37
+ const parseDocument = (/** @type {string} */ source) =>
38
+ new DOMParser().parseFromString(source, "text/html");
39
+
40
+ /** @param {ReturnType<typeof parseDocument>} fragment @param {(url:string)=>void} add */
41
+ function declaredAssets(fragment, add) {
42
+ for (const scope of fragment.querySelectorAll(declaredScope)) {
43
+ const { declarations, values } = scopeValues(scope);
44
+ for (const v of declarations) {
45
+ if (v.type !== "image" && v.type !== "font") continue;
46
+ const url = assetValue(values.get(v.id), v.type === "image" ? "url" : "source");
47
+ if (url) add(url);
48
+ }
49
+ }
50
+ }
51
+
52
+ /** @param {ReturnType<typeof parseDocument>} fragment @param {(url:string)=>void} add */
53
+ function boundAssets(fragment, add) {
54
+ const cache = new Map();
55
+ for (const el of fragment.querySelectorAll(boundMedia)) {
56
+ const scope = el.closest(declaredScope);
57
+ if (!scope) continue;
58
+ if (!cache.has(scope)) cache.set(scope, scopeValues(scope).values);
59
+ const url = assetValue(cache.get(scope).get(el.getAttribute("data-var-src")?.trim()), "url");
60
+ if (url) add(url);
61
+ }
62
+ }
63
+
64
+ /** @typedef {"url"|"source"} AssetKey
65
+ * @typedef {{first:string|null, scopes: Map<string, Map<string,AssetKey>>}} MediaSlots */
66
+
67
+ /** @param {Element} element @param {Element|null} scope @param {Map<string,AssetKey>} keys */
68
+ function recordAssetKeys(element, scope, keys) {
69
+ const bound = element.matches(boundMedia) && element.getAttribute("data-var-src")?.trim();
70
+ if (bound) keys.set(bound, "url");
71
+ if (element !== scope && element.tagName.toLowerCase() !== "html") return;
72
+ const { declarations } = readCompositionVariables(
73
+ element.getAttribute("data-composition-variables"),
74
+ );
75
+ for (const declaration of declarations) {
76
+ if (declaration.type === "image") keys.set(declaration.id, "url");
77
+ if (declaration.type === "font") keys.set(declaration.id, "source");
78
+ }
79
+ }
80
+
81
+ /** A host binds values to the child document's declarations and its mounted composition scope.
82
+ * A text value names an asset only when the child binds it to a media element.
83
+ * @param {ReturnType<typeof parseDocument>} fragment @param {MediaSlots} slots */
84
+ function mediaSlots(fragment, slots) {
85
+ slots.first ??=
86
+ fragment.querySelector("[data-composition-id]")?.getAttribute("data-composition-id") ?? null;
87
+ for (const element of fragment.querySelectorAll("[data-composition-variables]," + boundMedia)) {
88
+ const scope = element.closest("[data-composition-id]");
89
+ const id = scope?.getAttribute("data-composition-id") ?? "";
90
+ let keys = slots.scopes.get(id);
91
+ if (!keys) slots.scopes.set(id, (keys = new Map()));
92
+ recordAssetKeys(element, scope, keys);
93
+ }
94
+ }
95
+
96
+ /** @param {MediaSlots | undefined} slots @param {string} id @param {string} key @param {unknown} value */
97
+ export function mountedAsset(slots, id, key, value) {
98
+ const scoped = slots?.scopes.get(id || slots.first || "");
99
+ const kind = scoped?.get(key) ?? slots?.scopes.get("")?.get(key);
100
+ return kind ? assetValue(value, kind) : null;
101
+ }
102
+
103
+ /** @param {string} source @param {(url:string)=>void} add @returns {MediaSlots|undefined} */
104
+ export function variableReferences(source, add) {
105
+ if (!/data-(?:var-src|composition-variables|variable-values)\s*=/i.test(source)) return;
106
+ /** @type {MediaSlots} */
107
+ const slots = { first: null, scopes: new Map() };
108
+ const pending = [parseDocument(source)];
109
+ for (let fragment = pending.pop(); fragment; fragment = pending.pop()) {
110
+ for (const template of fragment.querySelectorAll("template")) pending.push(template.content);
111
+ declaredAssets(fragment, add);
112
+ boundAssets(fragment, add);
113
+ mediaSlots(fragment, slots);
114
+ }
115
+ return slots;
116
+ }