@hyperframes/core 0.9.64 → 0.9.66

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 (39) hide show
  1. package/dist/canary.d.ts +15 -0
  2. package/dist/canary.js +1 -1
  3. package/dist/compiler/compositionScoping.d.ts +2 -0
  4. package/dist/compiler/compositionScoping.js +44 -14
  5. package/dist/compiler/htmlBundler.d.ts +5 -1
  6. package/dist/compiler/htmlBundler.js +48 -13
  7. package/dist/compiler/index.d.ts +1 -1
  8. package/dist/compiler/index.js +1 -1
  9. package/dist/compiler/inlineSubCompositions.d.ts +7 -0
  10. package/dist/compiler/inlineSubCompositions.js +36 -17
  11. package/dist/compiler/selectorIdTokens.d.ts +2 -0
  12. package/dist/compiler/selectorIdTokens.js +17 -0
  13. package/dist/compiler/svgIdNamespacing.d.ts +4 -2
  14. package/dist/compiler/svgIdNamespacing.js +58 -18
  15. package/dist/figma/bindings.js +7 -6
  16. package/dist/figma/index.d.ts +2 -1
  17. package/dist/figma/index.js +2 -1
  18. package/dist/figma/manifest.d.ts +2 -0
  19. package/dist/figma/manifest.js +13 -4
  20. package/dist/figma/mediaIndex.d.ts +2 -3
  21. package/dist/figma/mediaIndex.js +17 -17
  22. package/dist/figma/projectFiles.d.ts +16 -0
  23. package/dist/figma/projectFiles.js +81 -0
  24. package/dist/generated/runtime-inline.js +1 -1
  25. package/dist/generated/svg-selector-aliases-inline.js +1 -1
  26. package/dist/hyperframe.runtime.iife.js +72 -71
  27. package/dist/runtime/editing/editElement.d.ts +18 -0
  28. package/dist/runtime/editing/editElement.js +72 -0
  29. package/dist/runtime/editing/gsapSnapshot.d.ts +43 -0
  30. package/dist/runtime/editing/gsapSnapshot.js +169 -0
  31. package/dist/runtime/editing/gsapSnapshotLimits.d.ts +6 -0
  32. package/dist/runtime/editing/gsapSnapshotLimits.js +6 -0
  33. package/dist/runtime/editing/motionPathHome.d.ts +19 -0
  34. package/dist/runtime/editing/motionPathHome.js +85 -0
  35. package/dist/runtime/editingHandles.js +34 -10
  36. package/dist/runtime/editingPort.d.ts +36 -1
  37. package/dist/runtime/editingPort.js +20 -1
  38. package/dist/safePath.js +3 -1
  39. package/package.json +4 -4
@@ -7,7 +7,8 @@
7
7
  */
8
8
  import { replaceMatches, urlHashRefMatches } from "@hyperframes/parsers/css-url-scans";
9
9
  import postcss from "postcss";
10
- import { escapeCssIdentifier } from "./selectorIdTokens.js";
10
+ import { fnv1a32 } from "../canary.js";
11
+ import { escapeCssIdentifier, selectorIdTokens } from "./selectorIdTokens.js";
11
12
  import { SVG_REFERENCE_ALIASES_ATTR, readSvgReferenceAliases, rewriteSvgSelectors, } from "./svgSelectorAliases.js";
12
13
  const ID_ATTR = "id";
13
14
  /** Reused from `compositionScoping.ts`'s `AUTHORED_ROOT_ID_ATTR` in spirit —
@@ -23,8 +24,13 @@ export const SVG_AUTHORED_ID_ATTR = "data-hf-authored-id";
23
24
  function isHrefAttrName(name) {
24
25
  return name === "href" || name.endsWith(":href");
25
26
  }
27
+ const MAX_NAMESPACE_PREFIX = 48;
28
+ /** A namespace this long keeps its head and a hash of the whole, so a renamed id's length never depends on it. */
26
29
  function sanitizeNamespaceSegment(value) {
27
- return value.replace(/[^a-zA-Z0-9_-]/g, "-");
30
+ const segment = value.replace(/[^a-zA-Z0-9_-]/g, "-");
31
+ if (segment.length <= MAX_NAMESPACE_PREFIX)
32
+ return segment;
33
+ return `${segment.slice(0, 32)}-${fnv1a32(value).toString(16).padStart(8, "0")}`;
28
34
  }
29
35
  /**
30
36
  * Rewrites each `url(#id)` funcref, quoted or bare, in a property value: `clip-path`, `filter`,
@@ -218,8 +224,8 @@ function buildIdCensus(document) {
218
224
  return { elementsById, usedIds };
219
225
  }
220
226
  /** A namespaced id that is not already taken anywhere in the document. */
221
- function mintNamespacedId(namespace, originalId, usedIds) {
222
- const base = `${sanitizeNamespaceSegment(namespace)}--${originalId}`;
227
+ function mintNamespacedId(prefix, originalId, usedIds) {
228
+ const base = `${prefix}--${originalId}`;
223
229
  let candidate = base;
224
230
  for (let n = 2; usedIds.has(candidate); n += 1)
225
231
  candidate = `${base}-${n}`;
@@ -240,11 +246,13 @@ function collisionScopes(id, elements, scopeIndexByRenamable) {
240
246
  */
241
247
  function planRenames(census, scopes, scopeIndexByRenamable) {
242
248
  const idMaps = scopes.map(() => new Map());
249
+ const prefixes = [];
243
250
  for (const [id, elements] of census.elementsById) {
244
251
  if (elements.length < 2)
245
252
  continue;
246
253
  for (const index of collisionScopes(id, elements, scopeIndexByRenamable)) {
247
- idMaps[index].set(id, mintNamespacedId(scopes[index].namespace, id, census.usedIds));
254
+ prefixes[index] ??= sanitizeNamespaceSegment(scopes[index].namespace);
255
+ idMaps[index].set(id, mintNamespacedId(prefixes[index], id, census.usedIds));
248
256
  }
249
257
  }
250
258
  return idMaps;
@@ -278,10 +286,39 @@ function localReferenceBindings(elements) {
278
286
  }
279
287
  return { ids, renamed };
280
288
  }
289
+ /** One scope's renames read through to the document's shared table, never copied per scope. */
290
+ class ScopedIdMap {
291
+ own;
292
+ shared;
293
+ hidden;
294
+ constructor(own, shared, hidden) {
295
+ this.own = own;
296
+ this.shared = shared;
297
+ this.hidden = hidden;
298
+ }
299
+ get(id) {
300
+ return this.own.get(id) ?? (this.hidden.has(id) ? undefined : this.shared.get(id));
301
+ }
302
+ has(id) {
303
+ return this.get(id) !== undefined;
304
+ }
305
+ get size() {
306
+ let size = this.own.size + this.shared.size;
307
+ for (const id of this.own.keys())
308
+ if (this.shared.has(id))
309
+ size -= 1;
310
+ for (const id of this.hidden)
311
+ if (id !== null && !this.own.has(id) && this.shared.has(id))
312
+ size -= 1;
313
+ return size;
314
+ }
315
+ }
316
+ const attributeBytes = (el) => Array.from(el.attributes ?? [], (attr) => attr.name.length + attr.value.length + 4).reduce((sum, bytes) => sum + bytes, 0);
281
317
  /** Rename the planned elements in one scope and rewrite every reference in
282
- * that scope's attributes to match. */
283
- function applyRenames(resolved, idMap) {
318
+ * that scope's attributes to match. `charge` gets each element's added bytes. */
319
+ function applyRenames(resolved, idMap, charge) {
284
320
  for (const el of resolved.elements) {
321
+ const before = charge ? attributeBytes(el) : 0;
285
322
  const currentId = el.getAttribute(ID_ATTR);
286
323
  if (currentId && resolved.renamable.has(el) && idMap.has(currentId)) {
287
324
  if (!el.hasAttribute(SVG_AUTHORED_ID_ATTR))
@@ -299,6 +336,8 @@ function applyRenames(resolved, idMap) {
299
336
  el.setAttribute(ID_ATTR, after);
300
337
  }
301
338
  rewriteElementIdReferences(el, idMap);
339
+ if (charge)
340
+ charge(attributeBytes(el) - before);
302
341
  }
303
342
  }
304
343
  const CLIP_SELECTOR = "[data-start]:not([data-composition-id]):not([data-composition-src])";
@@ -327,7 +366,7 @@ export function sceneClipRoots(document, hosts) {
327
366
  * document declares itself, since those collide with an inlined instance's
328
367
  * ids just as two instances collide with each other.
329
368
  */
330
- export function namespaceCollidingSvgIds(document, scopes, finalizedIds) {
369
+ export function namespaceCollidingSvgIds(document, scopes, finalizedIds, charge) {
331
370
  if (scopes.length === 0)
332
371
  return [];
333
372
  const census = buildIdCensus(document);
@@ -349,11 +388,10 @@ export function namespaceCollidingSvgIds(document, scopes, finalizedIds) {
349
388
  const documentTargets = documentReferenceTargets(census, idMaps, scopeIndexByRenamable);
350
389
  const referenceMaps = resolved.map((scope, index) => {
351
390
  const local = localReferenceBindings(scopes[index].referenceTarget === "document" ? [] : scope.elements);
352
- const inherited = [...documentTargets].filter(([id]) => !local.ids.has(id));
353
- return new Map([...inherited, ...local.renamed, ...idMaps[index]]);
391
+ return new ScopedIdMap(new Map([...local.renamed, ...idMaps[index]]), documentTargets, local.ids);
354
392
  });
355
393
  referenceMaps.forEach((idMap, index) => {
356
- applyRenames(resolved[index], idMap);
394
+ applyRenames(resolved[index], idMap, charge && ((bytes) => charge(index, bytes)));
357
395
  });
358
396
  for (const el of newlyEligible)
359
397
  finalizedIds?.add(el);
@@ -388,14 +426,16 @@ export function rewriteSvgIdReferencesInCss(css, idMap, references = []) {
388
426
  }
389
427
  let mutated = false;
390
428
  const recordedIds = new Set(references.filter((alias) => alias.name === ID_ATTR).map((alias) => alias.before));
391
- const ids = [...idMap]
392
- .filter(([id]) => !recordedIds.has(id))
393
- .map(([id, renamed]) => ({
394
- id,
395
- replacement: `:is(#${escapeCssIdentifier(id)}, #${escapeCssIdentifier(renamed)})`,
396
- }));
429
+ const idsNamedBy = (selector) => selectorIdTokens(selector).flatMap((id) => {
430
+ const renamed = recordedIds.has(id) ? undefined : idMap.get(id);
431
+ if (!renamed)
432
+ return [];
433
+ return [
434
+ { id, replacement: `:is(#${escapeCssIdentifier(id)}, #${escapeCssIdentifier(renamed)})` },
435
+ ];
436
+ });
397
437
  root.walkRules((rule) => {
398
- const rewritten = rule.selectors.map((selector) => rewriteSvgSelectors(selector, ids, references));
438
+ const rewritten = rule.selectors.map((selector) => rewriteSvgSelectors(selector, idsNamedBy(selector), references));
399
439
  if (rewritten.some((selector, index) => selector !== rule.selectors[index])) {
400
440
  rule.selectors = rewritten;
401
441
  mutated = true;
@@ -7,10 +7,11 @@
7
7
  * a missed link bakes a correct literal; a wrong link silently changes
8
8
  * color at the next brand refresh. Never match by value or name.
9
9
  */
10
- import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
11
10
  import { join } from "node:path";
11
+ import { replaceFileAtomically } from "../atomicFile.js";
12
12
  import { readJsonlValues } from "./jsonl.js";
13
- import { mediaDir } from "./manifest.js";
13
+ import { mediaDir, ownMediaDir } from "./manifest.js";
14
+ import { appendWithoutFollowing } from "./projectFiles.js";
14
15
  const BINDINGS_FILE = "figma-bindings.jsonl";
15
16
  function bindingsPath(projectDir) {
16
17
  return join(mediaDir(projectDir), BINDINGS_FILE);
@@ -36,8 +37,8 @@ function readLines(projectDir) {
36
37
  return readJsonlValues(bindingsPath(projectDir));
37
38
  }
38
39
  function appendLine(projectDir, record) {
39
- mkdirSync(mediaDir(projectDir), { recursive: true });
40
- appendFileSync(bindingsPath(projectDir), JSON.stringify(record) + "\n");
40
+ ownMediaDir(projectDir);
41
+ appendWithoutFollowing(bindingsPath(projectDir), JSON.stringify(record) + "\n");
41
42
  }
42
43
  export function readBindings(projectDir) {
43
44
  return readLines(projectDir).filter(isBindingRecord);
@@ -54,9 +55,9 @@ export function appendBinding(projectDir, record) {
54
55
  export function upsertBindings(projectDir, records) {
55
56
  const incoming = new Set(records.map((r) => r.figmaId));
56
57
  const survivors = readLines(projectDir).filter((line) => !(isBindingRecord(line) && incoming.has(line.figmaId)));
57
- mkdirSync(mediaDir(projectDir), { recursive: true });
58
+ ownMediaDir(projectDir);
58
59
  const lines = [...survivors, ...records].map((r) => JSON.stringify(r)).join("\n");
59
- writeFileSync(bindingsPath(projectDir), lines.length > 0 ? lines + "\n" : "");
60
+ replaceFileAtomically(bindingsPath(projectDir), lines.length > 0 ? lines + "\n" : "");
60
61
  }
61
62
  /** Exact-ID lookup, checking alias chains too. Never value/name matching. */
62
63
  export function findBindingByFigmaId(projectDir, figmaId) {
@@ -3,8 +3,9 @@ export { createFigmaClient, FigmaClientError } from "./client.js";
3
3
  export type { FigmaClient, FigmaClientErrorCode, FigmaClientOptions, FigmaFetch, FigmaFileVersion, FigmaNodeDocument, FigmaStyleMeta, FigmaVariablePayload, FigmaVariablesResult, RenderedNode, RenderNodeOptions, } from "./client.js";
4
4
  export { parseFigmaRef } from "./parseFigmaRef.js";
5
5
  export { MAX_FREEZE_BYTES, exceedsFreezeCap, freezeBytes, freezeUrl, freezeLocalFile, } from "./freeze.js";
6
- export { mediaDir, manifestPath, typeDirPath, updateRecord, isFigmaManifestRecord, readManifest, appendRecord, findAllByFigmaNode, findByFigmaNode, nextId, } from "./manifest.js";
6
+ export { mediaDir, manifestPath, typeDirPath, ownTypeDir, updateRecord, isFigmaManifestRecord, readManifest, appendRecord, findAllByFigmaNode, findByFigmaNode, nextId, } from "./manifest.js";
7
7
  export { regenerateIndex } from "./mediaIndex.js";
8
+ export { ownProjectDir } from "./projectFiles.js";
8
9
  export { buildAssetSnippet } from "./assetSnippet.js";
9
10
  export { sanitizeSvg } from "./sanitizeSvg.js";
10
11
  export { appendBinding, upsertBindings, findBindingByFigmaId, readBindings, readLibraryMap, recordLibraryFile, } from "./bindings.js";
@@ -1,8 +1,9 @@
1
1
  export { createFigmaClient, FigmaClientError } from "./client.js";
2
2
  export { parseFigmaRef } from "./parseFigmaRef.js";
3
3
  export { MAX_FREEZE_BYTES, exceedsFreezeCap, freezeBytes, freezeUrl, freezeLocalFile, } from "./freeze.js";
4
- export { mediaDir, manifestPath, typeDirPath, updateRecord, isFigmaManifestRecord, readManifest, appendRecord, findAllByFigmaNode, findByFigmaNode, nextId, } from "./manifest.js";
4
+ export { mediaDir, manifestPath, typeDirPath, ownTypeDir, updateRecord, isFigmaManifestRecord, readManifest, appendRecord, findAllByFigmaNode, findByFigmaNode, nextId, } from "./manifest.js";
5
5
  export { regenerateIndex } from "./mediaIndex.js";
6
+ export { ownProjectDir } from "./projectFiles.js";
6
7
  export { buildAssetSnippet } from "./assetSnippet.js";
7
8
  export { sanitizeSvg } from "./sanitizeSvg.js";
8
9
  export { appendBinding, upsertBindings, findBindingByFigmaId, readBindings, readLibraryMap, recordLibraryFile, } from "./bindings.js";
@@ -2,6 +2,8 @@ import type { FigmaManifestRecord } from "./types.js";
2
2
  export declare function mediaDir(projectDir: string): string;
3
3
  export declare function manifestPath(projectDir: string): string;
4
4
  export declare function typeDirPath(projectDir: string, type: FigmaManifestRecord["type"]): string;
5
+ export declare function ownMediaDir(projectDir: string): string;
6
+ export declare function ownTypeDir(projectDir: string, type: FigmaManifestRecord["type"]): string;
5
7
  /**
6
8
  * Guards figma-OWNED rows only — media-use rows (bgm/sfx/icon, no
7
9
  * provenance.source) legitimately fail this and are filtered out of
@@ -1,6 +1,8 @@
1
- import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
1
+ import { existsSync, readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
+ import { replaceFileAtomically } from "../atomicFile.js";
3
4
  import { readJsonlValues } from "./jsonl.js";
5
+ import { appendWithoutFollowing, ownProjectDir } from "./projectFiles.js";
4
6
  const MANIFEST_FILE = "manifest.jsonl";
5
7
  // Mirrors the media-use `.media/` layout for interop (one shared inventory).
6
8
  const TYPE_DIRS = {
@@ -16,6 +18,12 @@ export function manifestPath(projectDir) {
16
18
  export function typeDirPath(projectDir, type) {
17
19
  return join(mediaDir(projectDir), TYPE_DIRS[type]);
18
20
  }
21
+ export function ownMediaDir(projectDir) {
22
+ return ownProjectDir(projectDir, mediaDir(projectDir));
23
+ }
24
+ export function ownTypeDir(projectDir, type) {
25
+ return ownProjectDir(projectDir, typeDirPath(projectDir, type));
26
+ }
19
27
  /**
20
28
  * Guards figma-OWNED rows only — media-use rows (bgm/sfx/icon, no
21
29
  * provenance.source) legitimately fail this and are filtered out of
@@ -49,8 +57,8 @@ export function readManifest(projectDir) {
49
57
  return readJsonlValues(manifestPath(projectDir)).filter(isFigmaManifestRecord);
50
58
  }
51
59
  export function appendRecord(projectDir, record) {
52
- mkdirSync(typeDirPath(projectDir, record.type), { recursive: true });
53
- appendFileSync(manifestPath(projectDir), JSON.stringify(record) + "\n");
60
+ ownTypeDir(projectDir, record.type);
61
+ appendWithoutFollowing(manifestPath(projectDir), JSON.stringify(record) + "\n");
54
62
  }
55
63
  export function findByFigmaNode(projectDir, fileKey, nodeId) {
56
64
  return findAllByFigmaNode(projectDir, fileKey, nodeId)[0] ?? null;
@@ -81,7 +89,8 @@ export function updateRecord(projectDir, record) {
81
89
  }
82
90
  return line;
83
91
  });
84
- writeFileSync(p, out.join("\n"));
92
+ ownMediaDir(projectDir);
93
+ replaceFileAtomically(p, out.join("\n"));
85
94
  }
86
95
  export function nextId(projectDir, type) {
87
96
  const re = new RegExp(`^${type}_(\\d+)$`);
@@ -2,9 +2,8 @@
2
2
  * Regenerate .media/index.md — the agent-readable inventory table — after a
3
3
  * figma import, exactly the way media-use does after a resolve. Both writers
4
4
  * regenerate the SAME file from the manifest's current rows (all writers'), so the
5
- * output format AND row selection here must stay byte-identical with
6
- * skills/media-use/scripts/lib/index-gen.mjs — including rendering every
7
- * JSON-parseable row (no shape filtering), or the file would flip-flop
5
+ * output format AND row selection (every JSON-parseable row, no shape filtering) must stay
6
+ * byte-identical with skills/media-use/scripts/lib/index-gen.mjs, or the file would flip-flop
8
7
  * depending on which writer ran last.
9
8
  */
10
9
  type IndexRow = Record<string, unknown>;
@@ -2,23 +2,27 @@
2
2
  * Regenerate .media/index.md — the agent-readable inventory table — after a
3
3
  * figma import, exactly the way media-use does after a resolve. Both writers
4
4
  * regenerate the SAME file from the manifest's current rows (all writers'), so the
5
- * output format AND row selection here must stay byte-identical with
6
- * skills/media-use/scripts/lib/index-gen.mjs — including rendering every
7
- * JSON-parseable row (no shape filtering), or the file would flip-flop
5
+ * output format AND row selection (every JSON-parseable row, no shape filtering) must stay
6
+ * byte-identical with skills/media-use/scripts/lib/index-gen.mjs, or the file would flip-flop
8
7
  * depending on which writer ran last.
9
8
  */
10
- import { mkdirSync, writeFileSync } from "node:fs";
11
- import { dirname, join } from "node:path";
9
+ import { join } from "node:path";
10
+ import { replaceFileAtomically } from "../atomicFile.js";
11
+ import { terminalText } from "../terminalText.js";
12
12
  import { readJsonlValues } from "./jsonl.js";
13
- import { manifestPath, mediaDir } from "./manifest.js";
13
+ import { manifestPath, mediaDir, ownMediaDir } from "./manifest.js";
14
14
  function isRow(value) {
15
15
  return typeof value === "object" && value !== null;
16
16
  }
17
17
  export function indexPath(projectDir) {
18
18
  return join(mediaDir(projectDir), "index.md");
19
19
  }
20
+ const LINE_BREAKS = /\s*[\r\n\v\f\u0085\u2028\u2029]+\s*/g;
21
+ function singleLineCell(value) {
22
+ return terminalText(String(value ?? "").replace(LINE_BREAKS, " "));
23
+ }
20
24
  function pad(str, len) {
21
- return String(str ?? "").padEnd(len);
25
+ return singleLineCell(str).padEnd(len);
22
26
  }
23
27
  function formatDur(r) {
24
28
  if (r.duration == null)
@@ -32,9 +36,6 @@ function formatDims(r) {
32
36
  return "svg";
33
37
  return "—";
34
38
  }
35
- function len(value) {
36
- return String(value ?? "").length;
37
- }
38
39
  export function generateIndexContent(records) {
39
40
  const count = records.length;
40
41
  const header = `# .media · ${count} asset${count === 1 ? "" : "s"}\n`;
@@ -42,11 +43,11 @@ export function generateIndexContent(records) {
42
43
  return header;
43
44
  const cols = { id: 4, type: 5, dur: 4, dims: 5, path: 5 };
44
45
  for (const r of records) {
45
- cols.id = Math.max(cols.id, len(r.id));
46
- cols.type = Math.max(cols.type, len(r.type));
46
+ cols.id = Math.max(cols.id, singleLineCell(r.id).length);
47
+ cols.type = Math.max(cols.type, singleLineCell(r.type).length);
47
48
  cols.dur = Math.max(cols.dur, formatDur(r).length);
48
49
  cols.dims = Math.max(cols.dims, formatDims(r).length);
49
- cols.path = Math.max(cols.path, len(r.path));
50
+ cols.path = Math.max(cols.path, singleLineCell(r.path).length);
50
51
  }
51
52
  const heading = pad("id", cols.id + 2) +
52
53
  pad("type", cols.type + 2) +
@@ -61,7 +62,7 @@ export function generateIndexContent(records) {
61
62
  pad(formatDur(r), cols.dur + 2) +
62
63
  pad(formatDims(r), cols.dims + 2) +
63
64
  pad(r.path, cols.path + 2) +
64
- String(r.description ?? ""));
65
+ singleLineCell(r.description));
65
66
  }
66
67
  return lines.join("\n") + "\n";
67
68
  }
@@ -71,8 +72,7 @@ export function regenerateIndex(projectDir) {
71
72
  const last = new Map(rows.map((row, index) => [row.path, index]));
72
73
  const records = rows.filter((row, index) => !row.path || last.get(row.path) === index);
73
74
  const content = generateIndexContent(records);
74
- const p = indexPath(projectDir);
75
- mkdirSync(dirname(p), { recursive: true });
76
- writeFileSync(p, content);
75
+ ownMediaDir(projectDir);
76
+ replaceFileAtomically(indexPath(projectDir), content);
77
77
  return content;
78
78
  }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Folders and appends for figma's project writes that never follow a link out
3
+ * of the project. Whole-file rewrites use `replaceFileAtomically`, whose rename
4
+ * replaces a link instead of writing through it.
5
+ */
6
+ /**
7
+ * Creates `dir` under `projectDir` one folder at a time and returns it. Throws
8
+ * when any folder on the way is a link or not a folder.
9
+ */
10
+ export declare function ownProjectDir(projectDir: string, dir: string): string;
11
+ /**
12
+ * Throws on a link at `path` instead of appending through it. Opened first, then
13
+ * written only when `lstat` finds the same single-link plain file at the path, as
14
+ * projectRecords' appendRecord does; O_NOFOLLOW is undefined on Windows.
15
+ */
16
+ export declare function appendWithoutFollowing(path: string, text: string): void;
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Folders and appends for figma's project writes that never follow a link out
3
+ * of the project. Whole-file rewrites use `replaceFileAtomically`, whose rename
4
+ * replaces a link instead of writing through it.
5
+ */
6
+ import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, realpathSync, statSync, writeSync, } from "node:fs";
7
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
8
+ function leadsOutside(dir) {
9
+ return new Error(`${dir} leads outside the project folder; nothing was written there`);
10
+ }
11
+ /**
12
+ * Creates `dir` under `projectDir` one folder at a time and returns it. Throws
13
+ * when any folder on the way is a link or not a folder.
14
+ */
15
+ export function ownProjectDir(projectDir, dir) {
16
+ const root = resolve(projectDir);
17
+ const target = resolve(dir);
18
+ const rel = relative(root, target);
19
+ if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel))
20
+ throw leadsOutside(target);
21
+ mkdirSync(root, { recursive: true });
22
+ let current = root;
23
+ // The JS realpathSync, not .native: it keeps the case asked for, as `expected` does.
24
+ let expected = realpathSync(root);
25
+ for (const segment of rel.split(sep).filter(Boolean)) {
26
+ current = join(current, segment);
27
+ expected = join(expected, segment);
28
+ try {
29
+ mkdirSync(current);
30
+ }
31
+ catch (error) {
32
+ if (error.code !== "EEXIST")
33
+ throw error;
34
+ }
35
+ if (lstatSync(current).isSymbolicLink() || realpathSync(current) !== expected) {
36
+ throw leadsOutside(current);
37
+ }
38
+ if (!statSync(current).isDirectory()) {
39
+ throw new Error(`${current} is not a folder; nothing was written there`);
40
+ }
41
+ }
42
+ return target;
43
+ }
44
+ function notPlainFile(path) {
45
+ return new Error(`${path} is a link or not a plain file; nothing was written through it`);
46
+ }
47
+ /**
48
+ * Throws on a link at `path` instead of appending through it. Opened first, then
49
+ * written only when `lstat` finds the same single-link plain file at the path, as
50
+ * projectRecords' appendRecord does; O_NOFOLLOW is undefined on Windows.
51
+ */
52
+ export function appendWithoutFollowing(path, text) {
53
+ let fd;
54
+ try {
55
+ fd = openSync(path, constants.O_WRONLY |
56
+ constants.O_APPEND |
57
+ constants.O_CREAT |
58
+ (constants.O_NOFOLLOW ?? 0) |
59
+ (constants.O_NONBLOCK ?? 0), 0o666);
60
+ }
61
+ catch (error) {
62
+ if (error.code === "ELOOP")
63
+ throw notPlainFile(path);
64
+ throw error;
65
+ }
66
+ try {
67
+ const opened = fstatSync(fd);
68
+ const named = lstatSync(path);
69
+ const samePlainFile = opened.isFile() &&
70
+ named.isFile() &&
71
+ opened.nlink === 1 &&
72
+ named.ino === opened.ino &&
73
+ named.dev === opened.dev;
74
+ if (!samePlainFile)
75
+ throw notPlainFile(path);
76
+ writeSync(fd, text);
77
+ }
78
+ finally {
79
+ closeSync(fd);
80
+ }
81
+ }