mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-23 11:29:54 +00:00
fix(studio-server): an undo never deletes a file a page it leaves still names (#8186)
* test(studio-server): an undo keeps a file a page it leaves still names * fix(studio-server): an undo never deletes a file a page it leaves still names * fix(studio-server): keep the undo's page check small and comment-free * refactor(studio-server): the history reads file references without loading the file routes * fix(studio-server): the history loads the file routes only when an undo would delete a file * refactor(studio-server): history and renames share one core-free file reference matcher * test(studio-server): undo steps past a kept upload and keeps a kept page's files * fix(studio-server): undo steps past kept files and keeps what a kept page names * refactor(studio-server): split the kept-empty undo check out of commit * test(studio-server): a kept upload is redone, after reopening too, and a kept redo never traps undo * fix(studio-server): an undo or redo records the files it kept, so redo and undo step past them * test(studio-server): kept files go through redo's conflict check, newest redo and step paths * fix(studio-server): a step over kept files checks later edits and names the files it writes * test(studio-server): keep-later-edits over a kept upload leaves Cmd+Z on the earlier edit * fix(studio-server): a redo that keeps every later edit records nothing, so Cmd+Z moves on
This commit is contained in:
@@ -0,0 +1,378 @@
|
||||
import { sep } from "node:path";
|
||||
import { decodeCssEscapes, decodedUrlPath, encodeUrlPath } from "@hyperframes/parsers/asset-paths";
|
||||
import {
|
||||
HTML_ATTRIBUTE_ENTITIES,
|
||||
decodeAuthoredAttribute,
|
||||
scanHtmlOpeningTags,
|
||||
type HtmlAttributeSpan,
|
||||
} from "@hyperframes/parsers/html-attribute-spans";
|
||||
import { decodeWellFormedEscapes } from "./requestSubPath.js";
|
||||
|
||||
const escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
|
||||
const SEPARATOR = String.raw`\\{0,2}[\\/]`;
|
||||
const REFERENCE_START = String.raw`(?<![\w./\\+-])`;
|
||||
const FILE_END = String.raw`(?![\w-]|\.\w)`;
|
||||
|
||||
const ENTITY_SPELLINGS = HTML_ATTRIBUTE_ENTITIES;
|
||||
|
||||
const BACKSLASHED = ["'", '"', "`", "$", " ", "(", ")"];
|
||||
|
||||
function urlSpellings(char: string): string[] {
|
||||
const encoded = encodeUrlPath(char);
|
||||
return encoded === char
|
||||
? []
|
||||
: [encoded.replace(/[A-F]/g, (hex) => `[${hex}${hex.toLowerCase()}]`)];
|
||||
}
|
||||
|
||||
function escapedSpellings(char: string): string[] {
|
||||
const spellings = BACKSLASHED.includes(char)
|
||||
? [escapeRegExp(`\${char}`), escapeRegExp(`\${escapeHtmlReference(char)}`)]
|
||||
: [];
|
||||
const scriptSpelling = escapeQuotedReference(char, '"');
|
||||
if (scriptSpelling !== char) spellings.push(escapeRegExp(scriptSpelling));
|
||||
if (BACKSLASHED.includes(char) && char !== '"') spellings.push(escapeRegExp(`\\${char}`));
|
||||
return spellings;
|
||||
}
|
||||
|
||||
function controlSpellings(char: string): string[] {
|
||||
const spellings = /[\t\n\f\r =<>`]/.test(char) ? [`&#${char.codePointAt(0)!};`] : [];
|
||||
const code = char.charCodeAt(0);
|
||||
if (code < 0x20 || code === 0x7f) spellings.push(escapeRegExp(`\\${code.toString(16)} `));
|
||||
return spellings;
|
||||
}
|
||||
|
||||
function referenceSpellings(char: string): string {
|
||||
const spellings = [
|
||||
escapeRegExp(char),
|
||||
...urlSpellings(char),
|
||||
...(ENTITY_SPELLINGS[char] ?? []),
|
||||
...escapedSpellings(char),
|
||||
...controlSpellings(char),
|
||||
];
|
||||
return spellings.length === 1 ? spellings[0]! : `(?:${spellings.join("|")})`;
|
||||
}
|
||||
|
||||
export type ReferenceSyntax = "html" | "script" | "css" | "plain";
|
||||
interface ReferenceContext {
|
||||
syntax: ReferenceSyntax;
|
||||
url: boolean;
|
||||
htmlAttribute: boolean;
|
||||
encodeAll: boolean;
|
||||
quote: string;
|
||||
}
|
||||
|
||||
function escapeHtmlReference(path: string): string {
|
||||
return path.replace(/[&"']/g, (char) => ENTITY_SPELLINGS[char]![0]!);
|
||||
}
|
||||
|
||||
function escapeQuotedReference(path: string, quote: string): string {
|
||||
const escaped = JSON.stringify(path).slice(1, -1);
|
||||
return quote === '"'
|
||||
? escaped
|
||||
: escaped.replace(new RegExp(escapeRegExp(quote), "g"), `\\${quote}`);
|
||||
}
|
||||
|
||||
function escapeRawUrlPath(path: string): string {
|
||||
const encodeSpaces = path.startsWith(" ") || path.endsWith(" ");
|
||||
return path.replace(/[\s\S]/g, (char) => {
|
||||
if (char.charCodeAt(0) < 0x20 || ":?%#\\".includes(char) || (encodeSpaces && char === " ")) {
|
||||
return encodeUrlPath(char);
|
||||
}
|
||||
return char;
|
||||
});
|
||||
}
|
||||
|
||||
function spellHtml(path: string, { url, quote }: ReferenceContext): string {
|
||||
const escaped = escapeHtmlReference(url ? escapeRawUrlPath(path) : path);
|
||||
return ["'", '"'].includes(quote)
|
||||
? escaped
|
||||
: escaped.replace(/[\t\n\f\r =<>`]/g, (char) => `&#${char.codePointAt(0)!};`);
|
||||
}
|
||||
|
||||
function spellScript(path: string, { quote }: ReferenceContext): string {
|
||||
if (!["'", '"', "`"].includes(quote)) return path;
|
||||
const escaped = escapeQuotedReference(path, quote);
|
||||
return quote === "`" ? escaped.replace(/\$\{/g, "\\${") : escaped;
|
||||
}
|
||||
|
||||
const SPELLINGS = {
|
||||
html: spellHtml,
|
||||
script: spellScript,
|
||||
css: (path, { url }) => (url ? encodeUrlPath(path) : path),
|
||||
plain: (path) => path,
|
||||
} satisfies Record<ReferenceSyntax, (path: string, context: ReferenceContext) => string>;
|
||||
|
||||
const encodesWhole = (reference: string, oldPath: string, { url, encodeAll }: ReferenceContext) =>
|
||||
url && (encodeAll || (reference !== oldPath && /%[0-9A-Fa-f]{2}/.test(reference)));
|
||||
|
||||
function spellLike(
|
||||
reference: string,
|
||||
path: string,
|
||||
oldPath: string,
|
||||
context: ReferenceContext,
|
||||
): string {
|
||||
if (encodesWhole(reference, oldPath, context)) return encodeUrlPath(path);
|
||||
return SPELLINGS[context.syntax](path, context);
|
||||
}
|
||||
|
||||
export function referenceSyntax(file: string): ReferenceSyntax {
|
||||
if (/\.html$/i.test(file)) return "html";
|
||||
if (/\.css$/i.test(file)) return "css";
|
||||
if (/\.(?:[cm]?js|jsx|tsx?|json)$/i.test(file)) return "script";
|
||||
return "plain";
|
||||
}
|
||||
|
||||
function decodeQuotedReference(text: string, syntax: ReferenceSyntax): string {
|
||||
if (syntax === "css") return decodeCssEscapes(text);
|
||||
if (syntax === "script") {
|
||||
const controls: Record<string, string> = { b: "\b", f: "\f", n: "\n", r: "\r", t: "\t" };
|
||||
return text.replace(
|
||||
/\\(?:u([0-9a-fA-F]{4})|([bfnrt"'`$\\/]))/g,
|
||||
(_escaped, hex: string | undefined, char: string | undefined) => {
|
||||
if (hex !== undefined) return String.fromCharCode(Number.parseInt(hex, 16));
|
||||
return controls[char!] ?? char!;
|
||||
},
|
||||
);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
function referencePattern(oldPath: string, isDirectory: boolean): RegExp {
|
||||
const name = oldPath
|
||||
.split("/")
|
||||
.map((segment) => Array.from(segment, referenceSpellings).join(""))
|
||||
.join(SEPARATOR);
|
||||
const end = isDirectory ? `(?=${SEPARATOR})` : FILE_END;
|
||||
return new RegExp(
|
||||
String.raw`${REFERENCE_START}(?<lead>(?:\.{1,2}${SEPARATOR}|${SEPARATOR}){0,4})${name}${end}`,
|
||||
"g",
|
||||
);
|
||||
}
|
||||
|
||||
type ValueAttribute = Extract<HtmlAttributeSpan, { kind: "value" }>;
|
||||
|
||||
function rewrittenEntityValue(attr: ValueAttribute, rewrite: (text: string) => string) {
|
||||
const decoded = decodeAuthoredAttribute(attr.value);
|
||||
if (decoded === attr.value) return null;
|
||||
let value = escapeHtmlReference(decoded);
|
||||
if (!attr.quote)
|
||||
value = value.replace(/[\t\n\f\r =<>`]/g, (char) => `&#${char.codePointAt(0)!};`);
|
||||
const source = `<x ${attr.name}=${attr.quote}${value}${attr.quote}>`;
|
||||
const updated = rewrite(source);
|
||||
if (updated === source) return null;
|
||||
const replacement = scanHtmlOpeningTags(updated)[0]!.attributes[0]!;
|
||||
if (replacement.kind !== "value") throw new Error("Reference rewrite removed its attribute");
|
||||
return replacement.value;
|
||||
}
|
||||
|
||||
function rewriteEntityAttributes(text: string, rewrite: (text: string) => string): string {
|
||||
const parts: string[] = [];
|
||||
let cursor = 0;
|
||||
const values = scanHtmlOpeningTags(text).flatMap((tag) =>
|
||||
tag.attributes.flatMap((attr) => (attr.kind === "value" ? [attr] : [])),
|
||||
);
|
||||
for (const attr of values) {
|
||||
const value = rewrittenEntityValue(attr, rewrite);
|
||||
if (value === null) continue;
|
||||
parts.push(text.slice(cursor, attr.valueStart), value);
|
||||
cursor = attr.valueEnd;
|
||||
}
|
||||
parts.push(text.slice(cursor));
|
||||
return parts.join("");
|
||||
}
|
||||
|
||||
type Region<T> = { start: number; end: number } & T;
|
||||
|
||||
function advancing<T>(regions: readonly Region<T>[]): (offset: number) => Region<T> | undefined {
|
||||
let index = 0;
|
||||
return (offset) => {
|
||||
while (regions[index] && regions[index]!.end <= offset) index++;
|
||||
return regions[index];
|
||||
};
|
||||
}
|
||||
|
||||
const inside = (region: { start: number } | undefined, offset: number) =>
|
||||
!!region && offset >= region.start;
|
||||
|
||||
function matchContext(
|
||||
text: string,
|
||||
offset: number,
|
||||
syntax: ReferenceSyntax,
|
||||
region: Region<{ syntax: ReferenceSyntax }> | undefined,
|
||||
urlRegion: Region<Omit<ReferenceContext, "url" | "quote">> | undefined,
|
||||
): ReferenceContext {
|
||||
const quote = text[offset - 1] ?? "";
|
||||
const matchSyntax = inside(region, offset) ? region!.syntax : syntax;
|
||||
if (matchSyntax === "script" || !inside(urlRegion, offset))
|
||||
return { syntax: matchSyntax, url: false, htmlAttribute: false, encodeAll: false, quote };
|
||||
const { htmlAttribute, encodeAll } = urlRegion!;
|
||||
return { syntax: urlRegion!.syntax, url: true, htmlAttribute, encodeAll, quote };
|
||||
}
|
||||
|
||||
// A match inside the longer path of a file or folder that exists (`a.png&b.png`, `other assets/`) is that path's.
|
||||
// Existing paths are indexed by the text after the old path, then the text before it, so a match costs a few lookups.
|
||||
export function referenceRewriter(
|
||||
oldPath: string,
|
||||
newPath: string,
|
||||
isDirectory: boolean,
|
||||
existing: readonly string[] = [],
|
||||
): (text: string, syntax?: ReferenceSyntax) => string {
|
||||
const oldIdentity = sep === "\\" ? oldPath.replace(/\\/g, "/") : oldPath;
|
||||
const pattern = referencePattern(oldPath, isDirectory);
|
||||
const around = new Map<string, Map<number, Set<string>>>();
|
||||
const afterLengths = new Set<number>();
|
||||
let window = 0;
|
||||
for (const path of existing) {
|
||||
if (path.length <= oldPath.length) continue;
|
||||
for (const start of occurrences(path, oldPath)) {
|
||||
const [before, after] = [path.slice(0, start), path.slice(start + oldPath.length)];
|
||||
const befores = around.get(after) ?? around.set(after, new Map()).get(after)!;
|
||||
(befores.get(before.length) ?? befores.set(before.length, new Set()).get(before.length)!).add(
|
||||
before,
|
||||
);
|
||||
afterLengths.add(after.length);
|
||||
window = Math.max(window, path.length * 9);
|
||||
}
|
||||
}
|
||||
const normalized = (text: string, context: ReferenceContext, full = false) => {
|
||||
let value = text;
|
||||
if (context.syntax === "html" || context.htmlAttribute) {
|
||||
value = decodeAuthoredAttribute(value);
|
||||
}
|
||||
value = decodeQuotedReference(value, context.syntax);
|
||||
if (context.url) {
|
||||
value = value.replace(/\\/g, "/");
|
||||
value = full ? decodedUrlPath(value) : decodeWellFormedEscapes(value);
|
||||
}
|
||||
return sep === "\\" ? value.replace(/\\/g, "/") : value;
|
||||
};
|
||||
const inLonger = (head: string, tail: string) =>
|
||||
[...afterLengths].some((after) => {
|
||||
const befores = tail.length >= after && around.get(tail.slice(0, after));
|
||||
return (
|
||||
befores &&
|
||||
[...befores].some(
|
||||
([length, set]) => head.length >= length && set.has(head.slice(head.length - length)),
|
||||
)
|
||||
);
|
||||
});
|
||||
const namesOldPath = (
|
||||
text: string,
|
||||
offset: number,
|
||||
match: string,
|
||||
lead: string,
|
||||
context: ReferenceContext,
|
||||
) => {
|
||||
const end = offset + match.length;
|
||||
if (normalized(match.slice(lead.length), context, true) !== oldIdentity) return false;
|
||||
if (isDirectory && !normalized(text.slice(end, end + 4), context).startsWith("/")) return false;
|
||||
const at = offset + lead.length;
|
||||
const head = normalized(text.slice(Math.max(0, at - window), at), context);
|
||||
return !inLonger(head, normalized(text.slice(end, end + window), context, context.url));
|
||||
};
|
||||
return function rewriteText(text, syntax = "html", normalizeEntities = true) {
|
||||
if (syntax === "html" && normalizeEntities) {
|
||||
text = rewriteEntityAttributes(text, (source) => rewriteText(source, "html", false));
|
||||
}
|
||||
pattern.lastIndex = 0;
|
||||
if (!pattern.test(text)) return text;
|
||||
pattern.lastIndex = 0;
|
||||
const tags = syntax === "html" ? scanHtmlOpeningTags(text) : [];
|
||||
const inlineRegions = tags
|
||||
.filter(
|
||||
(tag) => tag.closed && ["script", "style"].includes(tag.name) && tag.rawTextEnd !== null,
|
||||
)
|
||||
.map((tag) => ({
|
||||
start: tag.end,
|
||||
end: tag.rawTextEnd!,
|
||||
syntax: tag.name === "style" ? ("css" as const) : ("script" as const),
|
||||
}));
|
||||
const attributes = tags.flatMap((tag) =>
|
||||
tag.attributes.flatMap((attr) => (attr.kind === "value" ? [attr] : [])),
|
||||
);
|
||||
const cssContexts =
|
||||
syntax === "css"
|
||||
? [{ start: 0, end: text.length, htmlAttribute: false }]
|
||||
: [
|
||||
...inlineRegions
|
||||
.filter((region) => region.syntax === "css")
|
||||
.map((region) => ({ ...region, htmlAttribute: false })),
|
||||
...attributes
|
||||
.filter((attr) => attr.name === "style")
|
||||
.map((attr) => ({ ...attr, htmlAttribute: true })),
|
||||
];
|
||||
const cssFields = (pattern: RegExp) =>
|
||||
cssContexts.flatMap((context) =>
|
||||
[...text.slice(context.start, context.end).matchAll(pattern)].map((match) => {
|
||||
const prefix = /^(?:url\(\s*|@import\s+)/i.exec(match[0])![0];
|
||||
const rest = match[0].slice(prefix.length);
|
||||
const delimiter = context.htmlAttribute
|
||||
? /^(?:["']|"|'|')/.exec(rest)?.[0]
|
||||
: /^["']/.exec(rest)?.[0];
|
||||
const start = context.start + match.index! + prefix.length + (delimiter?.length ?? 0);
|
||||
return {
|
||||
start,
|
||||
end: context.start + match.index! + match[0].length,
|
||||
syntax: "css" as const,
|
||||
htmlAttribute: context.htmlAttribute,
|
||||
encodeAll: true,
|
||||
};
|
||||
}),
|
||||
);
|
||||
const urlRegions = [
|
||||
...attributes
|
||||
.filter((attr) => ["src", "href", "poster", "xlink:href"].includes(attr.name))
|
||||
.map((attr) => ({
|
||||
start: attr.valueStart + (/^[\t\n\f\r ]*/.exec(attr.value)?.[0].length ?? 0),
|
||||
end: attr.valueEnd,
|
||||
syntax: "html" as const,
|
||||
htmlAttribute: true,
|
||||
encodeAll: false,
|
||||
})),
|
||||
...attributes
|
||||
.filter((attr) => attr.name === "srcset")
|
||||
.flatMap((attr) =>
|
||||
[...attr.value.matchAll(/(^|,)[\t\n\f\r ]*([^,\t\n\f\r ]+)/g)].map((match) => ({
|
||||
start: attr.valueStart + match.index! + match[0].length - match[2]!.length,
|
||||
end: attr.valueStart + match.index! + match[0].length,
|
||||
syntax: "html" as const,
|
||||
htmlAttribute: true,
|
||||
encodeAll: true,
|
||||
})),
|
||||
),
|
||||
...cssFields(
|
||||
/\burl\((?:\s*"(?:\\.|[^"\\])*"\s*|\s*'(?:\\.|[^'\\])*'\s*|(?:\\.|[^)\\])*)\)/gi,
|
||||
),
|
||||
...cssFields(/@import\s+(?:"[^"]*"|'[^']*')/gi),
|
||||
].sort((a, b) => a.start - b.start);
|
||||
const inlineAt = advancing(inlineRegions);
|
||||
const urlAt = advancing(urlRegions);
|
||||
return text.replace(pattern, (...args) => {
|
||||
const [match, offset] = [args[0] as string, args.at(-3) as number];
|
||||
const { lead } = args.at(-1) as { lead: string };
|
||||
const urlRegion = urlAt(offset);
|
||||
const context = matchContext(text, offset, syntax, inlineAt(offset), urlRegion);
|
||||
if (context.url && offset !== urlRegion!.start) return match;
|
||||
const reference = match.slice(lead.length);
|
||||
if (!namesOldPath(text, offset, match, lead, context)) return match;
|
||||
return `${lead}${spellLike(reference, newPath, oldPath, context)}`;
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
export const canNameFiles = (file: string) =>
|
||||
/\.(html|css|js|jsx|ts|tsx|json|mjs|cjs|md|mdx)$/i.test(file);
|
||||
|
||||
export const fileNames = (
|
||||
file: string,
|
||||
text: string,
|
||||
path: string,
|
||||
existing: readonly string[] = [],
|
||||
) => referenceRewriter(path, `${path}\0`, false, existing)(text, referenceSyntax(file)) !== text;
|
||||
|
||||
function occurrences(text: string, part: string): number[] {
|
||||
const at: number[] = [];
|
||||
for (let i = text.indexOf(part); i >= 0; i = text.indexOf(part, i + 1)) at.push(i);
|
||||
return at;
|
||||
}
|
||||
@@ -38,6 +38,7 @@ export interface HistoryEntry {
|
||||
undoes?: string;
|
||||
/** Set on a restore: the point (an entry id, or START) the files were made equal to. */
|
||||
restoredTo?: string;
|
||||
keptInPlace?: Record<string, string>;
|
||||
}
|
||||
|
||||
/** The point before the first kept entry. */
|
||||
@@ -165,6 +166,10 @@ export function undoneIds(entries: readonly HistoryEntry[]): Set<string> {
|
||||
return undone;
|
||||
}
|
||||
|
||||
export const stepPaths = (entry: HistoryEntry): string[] => [
|
||||
...new Set([...entry.files.map((file) => file.path), ...Object.keys(entry.keptInPlace ?? {})]),
|
||||
];
|
||||
|
||||
/**
|
||||
* What Cmd+Z (back) or Cmd+Shift+Z (forward) reverts for `mine`. Back: the newest change `mine` owns that is still
|
||||
* in effect. Forward: the newest of `mine`'s undos still in effect, while `mine` has made no change since.
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
// @vitest-environment node
|
||||
// An undo or a restore never deletes a file that a page it leaves in the project still names.
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { openProjectHistory } from "./projectHistory";
|
||||
import type { HistoryWho } from "./historyLog";
|
||||
|
||||
const you: HistoryWho = { kind: "person", name: "You" };
|
||||
const agent: HistoryWho = { kind: "agent", name: "Agent" };
|
||||
const cleanup: Array<() => unknown> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
for (const step of cleanup.splice(0).reverse()) await step();
|
||||
});
|
||||
|
||||
function tempDir(prefix: string): string {
|
||||
const dir = mkdtempSync(join(tmpdir(), prefix));
|
||||
cleanup.push(() => rmSync(dir, { recursive: true, force: true }));
|
||||
return dir;
|
||||
}
|
||||
|
||||
async function project(files: Record<string, string>) {
|
||||
const projectDir = tempDir("hf-history-named-");
|
||||
const write = (path: string, content: string) => {
|
||||
mkdirSync(dirname(join(projectDir, path)), { recursive: true });
|
||||
writeFileSync(join(projectDir, path), content);
|
||||
};
|
||||
for (const [path, content] of Object.entries(files)) write(path, content);
|
||||
const historyRoot = tempDir("hf-history-root-");
|
||||
const open = async () => {
|
||||
const opened = await openProjectHistory({ projectDir, historyRoot });
|
||||
cleanup.push(() => opened.close());
|
||||
return opened;
|
||||
};
|
||||
const history = await open();
|
||||
const reopen = async () => (await history.close(), open());
|
||||
const read = (path: string) => readFileSync(join(projectDir, path), "utf-8");
|
||||
const has = (path: string) => existsSync(join(projectDir, path));
|
||||
const remove = (path: string) => rmSync(join(projectDir, path));
|
||||
return { history, write, read, has, remove, reopen };
|
||||
}
|
||||
|
||||
const SONG = '<audio id="a1" src="assets/song.mp3"></audio>';
|
||||
const SCENE =
|
||||
'<template><div data-composition-id="scene"><audio id="a2" src="../assets/song.mp3"></audio></div></template>';
|
||||
|
||||
const NOTES_SCENE =
|
||||
'<template><div data-composition-id="notes"><a href="../assets/notes.txt">notes</a></div></template>';
|
||||
|
||||
type History = Awaited<ReturnType<typeof openProjectHistory>>;
|
||||
|
||||
/** An edit, then an upload a later page of another author's plays; Cmd+Z twice keeps the upload and undoes the edit. */
|
||||
async function pastAnUploadAndBack(
|
||||
history: History,
|
||||
write: (path: string, content: string) => void,
|
||||
) {
|
||||
write("index.html", "after");
|
||||
await history.claim(you, "Edited", ["index.html"]);
|
||||
write("assets/song.mp3", "mp3");
|
||||
await history.claim(you, "Uploaded", ["assets/song.mp3"]);
|
||||
write("compositions/scene.html", SCENE);
|
||||
await history.claim(agent, "Music in a scene", ["compositions/scene.html"]);
|
||||
expect(await history.step("back", you)).toMatchObject({ ok: true });
|
||||
expect(await history.step("back", you)).toMatchObject({ ok: true });
|
||||
}
|
||||
|
||||
/** Cmd+Shift+Z twice: the edit comes back, then the kept upload's undo is redone and the upload is in effect again. */
|
||||
async function redoBoth(history: History) {
|
||||
expect(await history.step("forward", you)).toMatchObject({ ok: true });
|
||||
expect(history.next("forward", you)?.label).toBe("Undid: Uploaded");
|
||||
const redo = await history.step("forward", you);
|
||||
expect(redo).toMatchObject({ ok: true, entry: { label: "Redid: Uploaded" } });
|
||||
expect(history.list().find((entry) => entry.label === "Uploaded")?.undone).toBe(false);
|
||||
}
|
||||
|
||||
describe("undo keeps a file a page still names", () => {
|
||||
it("Cmd+Z of a drop keeps its file while a later page of the agent's still plays it", async () => {
|
||||
const { history, write, read, has } = await project({ "index.html": "<h1>Hi</h1>" });
|
||||
write("assets/song.mp3", "mp3");
|
||||
write("index.html", `<h1>Hi</h1>${SONG}`);
|
||||
await history.claim(you, "Dropped on timeline", ["assets/song.mp3", "index.html"]);
|
||||
write("compositions/scene.html", SCENE);
|
||||
await history.claim(agent, "Music in a scene", ["compositions/scene.html"]);
|
||||
|
||||
expect(await history.step("back", you)).toMatchObject({ ok: true });
|
||||
expect(read("index.html")).toBe("<h1>Hi</h1>");
|
||||
expect(has("assets/song.mp3")).toBe(true);
|
||||
expect(read("compositions/scene.html")).toBe(SCENE);
|
||||
});
|
||||
|
||||
it("a run's Undo keeps a file it made while a later page of the person's still plays it", async () => {
|
||||
const { history, write, has } = await project({ "index.html": "<h1>Hi</h1>" });
|
||||
write("assets/song.mp3", "mp3");
|
||||
write("index.html", `<h1>Hi</h1>${SONG}`);
|
||||
await history.claim(agent, "Made music", ["assets/song.mp3", "index.html"]);
|
||||
const [made] = history.list();
|
||||
write("compositions/scene.html", SCENE);
|
||||
await history.claim(you, "Edited in Studio", ["compositions/scene.html"]);
|
||||
|
||||
expect(await history.undo(made!.id, { who: you })).toMatchObject({ ok: true });
|
||||
expect(has("assets/song.mp3")).toBe(true);
|
||||
});
|
||||
|
||||
it("an undo still deletes a file it made once no page left names it", async () => {
|
||||
const { history, write, read, has } = await project({ "index.html": "<h1>Hi</h1>" });
|
||||
write("assets/song.mp3", "mp3");
|
||||
write("index.html", `<h1>Hi</h1>${SONG}`);
|
||||
await history.claim(you, "Dropped on timeline", ["assets/song.mp3", "index.html"]);
|
||||
|
||||
expect(await history.step("back", you)).toMatchObject({ ok: true });
|
||||
expect(read("index.html")).toBe("<h1>Hi</h1>");
|
||||
expect(has("assets/song.mp3")).toBe(false);
|
||||
});
|
||||
|
||||
// fails without the fix: the undo that kept the upload recorded no file, so no redo reached it and the upload
|
||||
// stayed undone.
|
||||
it("Cmd+Z steps past an upload it may not delete, reaches the edit before it, and redoes both", async () => {
|
||||
const { history, write, read, has } = await project({ "index.html": "before" });
|
||||
await pastAnUploadAndBack(history, write);
|
||||
expect(read("index.html")).toBe("before");
|
||||
expect(has("assets/song.mp3")).toBe(true);
|
||||
await redoBoth(history);
|
||||
expect(read("index.html")).toBe("after");
|
||||
expect(has("assets/song.mp3")).toBe(true);
|
||||
});
|
||||
|
||||
it("the upload an undo kept is still redone after the project is closed and opened again", async () => {
|
||||
const { history, write, reopen } = await project({ "index.html": "before" });
|
||||
await pastAnUploadAndBack(history, write);
|
||||
await redoBoth(await reopen());
|
||||
});
|
||||
|
||||
// fails without the fix: the redo kept the file a page names, but the next undo compared it against the deletion
|
||||
// that did not happen and stopped with a conflict before the earlier edit.
|
||||
it("after a redo that kept a file a page names, Cmd+Z steps past it to the edit before", async () => {
|
||||
const { history, write, read, has, remove } = await project({
|
||||
"index.html": "before",
|
||||
"assets/notes.txt": "notes",
|
||||
});
|
||||
write("index.html", "after");
|
||||
await history.claim(you, "Edited", ["index.html"]);
|
||||
remove("assets/notes.txt");
|
||||
await history.claim(you, "Deleted notes", ["assets/notes.txt"]);
|
||||
expect(await history.step("back", you)).toMatchObject({ ok: true });
|
||||
expect(read("assets/notes.txt")).toBe("notes");
|
||||
write("compositions/scene.html", NOTES_SCENE);
|
||||
await history.claim(agent, "Notes in a scene", ["compositions/scene.html"]);
|
||||
expect(await history.step("forward", you)).toMatchObject({ ok: true });
|
||||
expect(has("assets/notes.txt")).toBe(true);
|
||||
|
||||
expect(await history.step("back", you)).toMatchObject({ ok: true });
|
||||
expect(await history.step("back", you)).toMatchObject({ ok: true });
|
||||
expect(read("index.html")).toBe("before");
|
||||
expect(read("assets/notes.txt")).toBe("notes");
|
||||
});
|
||||
|
||||
it("an undo keeps a page another page names, and the files that page names", async () => {
|
||||
const { history, write, has } = await project({ "index.html": "<h1>Hi</h1>" });
|
||||
write("compositions/scene.html", SCENE);
|
||||
write("assets/song.mp3", "mp3");
|
||||
await history.claim(agent, "Scene with music", ["compositions/scene.html", "assets/song.mp3"]);
|
||||
const [made] = history.list();
|
||||
write("index.html", '<h1>Hi</h1><div data-composition-src="compositions/scene.html"></div>');
|
||||
await history.claim(you, "Edited in Studio", ["index.html"]);
|
||||
|
||||
expect(await history.undo(made!.id, { who: you })).toMatchObject({ ok: true });
|
||||
expect(has("compositions/scene.html")).toBe(true);
|
||||
expect(has("assets/song.mp3")).toBe(true);
|
||||
});
|
||||
|
||||
it("a page naming a longer file that exists does not keep the shorter one", async () => {
|
||||
const { history, write, has } = await project({
|
||||
"index.html": '<img src="assets/a.png&backup.png">',
|
||||
"assets/a.png&backup.png": "png",
|
||||
});
|
||||
write("assets/a.png", "png");
|
||||
await history.claim(you, "Uploaded", ["assets/a.png"]);
|
||||
|
||||
expect(await history.step("back", you)).toMatchObject({ ok: true });
|
||||
expect(has("assets/a.png")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
const NOTES =
|
||||
'<template><div data-composition-id="notes"><a href="../assets/notes.txt">n</a></div></template>';
|
||||
|
||||
describe("a step over files an undo kept", () => {
|
||||
/** An upload another author's page names, undone (so kept), then revised by that author. */
|
||||
async function keptThenRevised() {
|
||||
const opened = await project({ "index.html": "<h1>Hi</h1>" });
|
||||
const { history, write } = opened;
|
||||
write("index.html", "<h1>Hello</h1>");
|
||||
await history.claim(you, "Edited title", ["index.html"]);
|
||||
write("assets/notes.txt", "first");
|
||||
await history.claim(you, "Uploaded", ["assets/notes.txt"]);
|
||||
write("compositions/notes.html", NOTES);
|
||||
await history.claim(agent, "Notes in a scene", ["compositions/notes.html"]);
|
||||
expect(await history.step("back", you)).toMatchObject({ ok: true });
|
||||
write("assets/notes.txt", "revised");
|
||||
await history.claim(agent, "Revised notes", ["assets/notes.txt"]);
|
||||
return opened;
|
||||
}
|
||||
|
||||
// fails without the fix: the kept file skipped the conflict check, so redo put "first" back over "revised".
|
||||
it("redo of a kept upload stops at another author's later edit, and keep-later-edits keeps it", async () => {
|
||||
const { history, read } = await keptThenRevised();
|
||||
expect(await history.step("forward", you)).toMatchObject({ ok: false });
|
||||
expect(read("assets/notes.txt")).toBe("revised");
|
||||
const undid = history.list().find((entry) => entry.label === "Undid: Uploaded")!;
|
||||
expect(await history.undo(undid.id, { who: you, mode: "keep-later-edits" })).toEqual({
|
||||
ok: true,
|
||||
entry: null,
|
||||
});
|
||||
expect(read("assets/notes.txt")).toBe("revised");
|
||||
// fails without the fix: an empty redo put the upload back on top, so Cmd+Z hit the same conflict again.
|
||||
expect(history.next("back", you)?.label).toBe("Edited title");
|
||||
expect(await history.step("back", you)).toMatchObject({ ok: true });
|
||||
expect(read("index.html")).toBe("<h1>Hi</h1>");
|
||||
});
|
||||
|
||||
it("the same later edit stops the redo after the project is reopened", async () => {
|
||||
const { read, reopen } = await keptThenRevised();
|
||||
expect(await (await reopen()).step("forward", you)).toMatchObject({ ok: false });
|
||||
expect(read("assets/notes.txt")).toBe("revised");
|
||||
});
|
||||
|
||||
// fails without the fix: the step back compared the deleted file against what an older redo had kept.
|
||||
it("after a later redo really deletes a kept file, Cmd+Z restores it without a conflict", async () => {
|
||||
const { history, write, read, has, remove } = await project({
|
||||
"index.html": "<h1>Hi</h1>",
|
||||
"assets/notes.txt": "notes",
|
||||
});
|
||||
remove("assets/notes.txt");
|
||||
await history.claim(you, "Deleted notes", ["assets/notes.txt"]);
|
||||
expect(await history.step("back", you)).toMatchObject({ ok: true });
|
||||
write("compositions/notes.html", NOTES);
|
||||
await history.claim(agent, "Notes in a scene", ["compositions/notes.html"]);
|
||||
expect(await history.step("forward", you)).toMatchObject({ ok: true });
|
||||
expect(has("assets/notes.txt")).toBe(true);
|
||||
expect(await history.step("back", you)).toMatchObject({ ok: true });
|
||||
write("compositions/notes.html", "<template></template>");
|
||||
await history.claim(agent, "Notes gone", ["compositions/notes.html"]);
|
||||
expect(await history.step("forward", you)).toMatchObject({ ok: true });
|
||||
expect(has("assets/notes.txt")).toBe(false);
|
||||
|
||||
expect(await history.step("back", you)).toMatchObject({ ok: true });
|
||||
expect(read("assets/notes.txt")).toBe("notes");
|
||||
});
|
||||
|
||||
// fails without the fix: the redo changed no file and recorded none, so Cmd+Z had nothing of the person's to step to.
|
||||
it("a person who undoes and redoes an agent's kept upload can step back over it", async () => {
|
||||
const { history, write } = await project({ "index.html": "<h1>Hi</h1>" });
|
||||
write("assets/song.mp3", "mp3");
|
||||
await history.claim(agent, "Made music", ["assets/song.mp3"]);
|
||||
const [made] = history.list();
|
||||
write("compositions/scene.html", SCENE);
|
||||
await history.claim(agent, "Music in a scene", ["compositions/scene.html"]);
|
||||
const undid = await history.undo(made!.id, { who: you });
|
||||
expect(undid).toMatchObject({ ok: true });
|
||||
expect(await history.step("forward", you)).toMatchObject({ ok: true });
|
||||
expect(history.next("back", you)?.id).toBe(made!.id);
|
||||
});
|
||||
|
||||
// fails without the fix: "constructor" read the empty record's inherited value, a conflict with no newer change.
|
||||
it("undoing an edit to a file named like an object's own key is no conflict", async () => {
|
||||
const { history, write, read } = await project({ constructor: "a" });
|
||||
write("constructor", "b");
|
||||
await history.claim(you, "Edited", ["constructor"]);
|
||||
expect(await history.step("back", you)).toMatchObject({ ok: true });
|
||||
expect(read("constructor")).toBe("a");
|
||||
});
|
||||
});
|
||||
@@ -50,6 +50,7 @@ import {
|
||||
type FolderIdentity,
|
||||
} from "./historyId.js";
|
||||
import { takeHistoryOwnership } from "./ownerLock.js";
|
||||
import { canNameFiles, fileNames } from "../helpers/fileReferences.js";
|
||||
import { writeHistoryState } from "./videoState.js";
|
||||
import {
|
||||
START,
|
||||
@@ -62,6 +63,7 @@ import {
|
||||
referencedHashes,
|
||||
stepTarget,
|
||||
undoneIds,
|
||||
stepPaths,
|
||||
writeLog,
|
||||
type HistoryEntry,
|
||||
type HistoryTarget,
|
||||
@@ -399,6 +401,9 @@ function addChange(group: Group, path: string, before: string | null, after: str
|
||||
const targetKey = (target: HistoryTarget) =>
|
||||
JSON.stringify([target.file, target.id, target.hfId, target.selector, target.selectorIndex]);
|
||||
|
||||
const keptHash = (kept: Record<string, string>, path: string) =>
|
||||
Object.hasOwn(kept, path) ? kept[path] : undefined;
|
||||
|
||||
function keepTargetsOfItsFiles(entry: HistoryEntry): HistoryEntry {
|
||||
const targets = entry.targets?.filter((target) =>
|
||||
entry.files.some((file) => file.path === target.file),
|
||||
@@ -1075,10 +1080,15 @@ class Engine {
|
||||
if (group) await this.commit(group);
|
||||
}
|
||||
|
||||
keepsEmpty(extra: Partial<HistoryEntry>): boolean {
|
||||
if (extra.undoes === undefined) return false;
|
||||
const target = this.log.entries.find((entry) => entry.id === extra.undoes);
|
||||
// Only an older log's emptied entry: a kept undo has paths, so skipping them all leaves it in effect.
|
||||
return extra.keptInPlace !== undefined || (target !== undefined && !stepPaths(target).length);
|
||||
}
|
||||
|
||||
async commit(group: Group, extra: Partial<HistoryEntry> = {}): Promise<HistoryEntry | null> {
|
||||
const undoesEmptied =
|
||||
this.log.entries.find((entry) => entry.id === extra.undoes)?.files.length === 0;
|
||||
if (!group.changes.size && !undoesEmptied) return null;
|
||||
if (!group.changes.size && !this.keepsEmpty(extra)) return null;
|
||||
const pending = this.pendingEntry(group);
|
||||
const endedAt = Math.max(pending.endedAt, this.log.entries.at(-1)?.endedAt ?? 0);
|
||||
const entry = keepTargetsOfItsFiles({ ...pending, endedAt, ...extra });
|
||||
@@ -1268,11 +1278,13 @@ class Engine {
|
||||
extra: Partial<HistoryEntry>,
|
||||
): Promise<HistoryEntry | null> {
|
||||
this.assertWritable();
|
||||
const changes = [...target]
|
||||
.filter(
|
||||
([path, hash]) =>
|
||||
this.studioWouldWrite(path) && (this.tracked.get(path)?.hash ?? null) !== hash,
|
||||
)
|
||||
const wanted = [...target].filter(
|
||||
([path, hash]) =>
|
||||
this.studioWouldWrite(path) && (this.tracked.get(path)?.hash ?? null) !== hash,
|
||||
);
|
||||
const named = await this.stillNamed(wanted);
|
||||
const changes = wanted
|
||||
.filter(([path, hash]) => hash !== null || !named.has(path))
|
||||
.sort(([, a], [, b]) => Number(a !== null) - Number(b !== null));
|
||||
const setAsideByDeletesFirst = new Set(
|
||||
changes.filter(([, hash]) => hash === null).map(([path]) => this.tracked.get(path)?.hash),
|
||||
@@ -1301,7 +1313,62 @@ class Engine {
|
||||
} finally {
|
||||
this.windows = this.windows.filter((open) => open !== group);
|
||||
}
|
||||
return this.commit(group, extra);
|
||||
const leftInPlace = [...named].map((path) => [path, this.tracked.get(path)!.hash]);
|
||||
const kept = { ...extra.keptInPlace, ...Object.fromEntries(leftInPlace) };
|
||||
return this.commit(group, { ...extra, ...(Object.keys(kept).length && { keptInPlace: kept }) });
|
||||
}
|
||||
|
||||
async stillNamed(changes: readonly (readonly [string, string | null])[]): Promise<Set<string>> {
|
||||
const deleting = changes.flatMap(([path, hash]) => (hash === null ? [path] : []));
|
||||
const named = new Set<string>();
|
||||
if (!deleting.length) return named;
|
||||
const after = this.filesAfter(changes);
|
||||
const existing = [...after].flatMap(([path, hash]) => (hash === null ? [] : [path]));
|
||||
let pages = this.pagesOf(after);
|
||||
while (pages.length) {
|
||||
const candidates = deleting.filter((path) => !named.has(path));
|
||||
const rescued = await this.namedBy(pages, candidates, existing);
|
||||
for (const path of rescued) named.add(path);
|
||||
pages = this.pagesOf(new Map(rescued.map((path) => [path, this.tracked.get(path)!.hash])));
|
||||
}
|
||||
return named;
|
||||
}
|
||||
|
||||
filesAfter(changes: readonly (readonly [string, string | null])[]): Map<string, string | null> {
|
||||
const after = new Map(
|
||||
[...this.tracked].map(([path, file]) => [path, file.hash as string | null]),
|
||||
);
|
||||
for (const [path, hash] of changes) after.set(path, hash);
|
||||
return after;
|
||||
}
|
||||
|
||||
pagesOf(files: Map<string, string | null>): [string, string][] {
|
||||
return [...files].filter(
|
||||
(entry): entry is [string, string] =>
|
||||
entry[1] !== null && this.studioWouldWrite(entry[0]) && canNameFiles(entry[0]),
|
||||
);
|
||||
}
|
||||
|
||||
async namedBy(
|
||||
pages: readonly [string, string][],
|
||||
candidates: readonly string[],
|
||||
existing: readonly string[],
|
||||
): Promise<string[]> {
|
||||
const found = new Set<string>();
|
||||
for (const [page, hash] of pages) {
|
||||
const text = await this.pageText(page, hash);
|
||||
for (const path of candidates) if (fileNames(page, text, path, existing)) found.add(path);
|
||||
}
|
||||
return [...found];
|
||||
}
|
||||
|
||||
async pageText(page: string, hash: string): Promise<string> {
|
||||
try {
|
||||
if (this.blobs.has(hash)) return (await this.blobs.read(hash)).toString("utf-8");
|
||||
return readFileSync(join(this.dir, page), "utf-8");
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes one project file (null deletes it), first leaving the running operation's receipt for its echo. */
|
||||
@@ -1346,7 +1413,9 @@ class Engine {
|
||||
|
||||
async undoNow(id: string, who: HistoryWho, mode?: UndoMode): Promise<HistoryResult> {
|
||||
const entry = this.entry(id);
|
||||
const changed = this.movedOn(entry);
|
||||
const hashOf = (path: string) => this.tracked.get(path)?.hash ?? null;
|
||||
const steps = this.stepsOf(entry);
|
||||
const changed = steps.filter((step) => hashOf(step.path) !== step.holds);
|
||||
if (changed.length && !mode) return { ok: false, conflict: this.conflict(entry, changed) };
|
||||
if (mode === "back-to-before") {
|
||||
const index = this.log.entries.indexOf(entry);
|
||||
@@ -1356,22 +1425,51 @@ class Engine {
|
||||
entry: await this.restoreNow(point, who, `Went back to before: ${entry.label}`),
|
||||
};
|
||||
}
|
||||
const target = new Map(
|
||||
entry.files
|
||||
.filter((file) => mode !== "keep-later-edits" || !changed.includes(file))
|
||||
.map((file) => [file.path, file.before]),
|
||||
const taken = steps.filter((step) => mode !== "keep-later-edits" || !changed.includes(step));
|
||||
const inPlace = taken.flatMap((step) =>
|
||||
step.to !== null && hashOf(step.path) === step.to ? [[step.path, step.to]] : [],
|
||||
);
|
||||
return {
|
||||
ok: true,
|
||||
entry: await this.writeAs(who, this.undoLabel(entry), target, {
|
||||
undoes: id,
|
||||
...(entry.targets && { targets: entry.targets }),
|
||||
}),
|
||||
entry: await this.writeAs(
|
||||
who,
|
||||
this.undoLabel(entry),
|
||||
new Map(taken.map((step) => [step.path, step.to])),
|
||||
{
|
||||
undoes: id,
|
||||
...(entry.targets && { targets: entry.targets }),
|
||||
...(inPlace.length && { keptInPlace: Object.fromEntries(inPlace) }),
|
||||
},
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
movedOn(entry: HistoryEntry): HistoryFileChange[] {
|
||||
return entry.files.filter((file) => (this.tracked.get(file.path)?.hash ?? null) !== file.after);
|
||||
/** Each file a step over `entry` writes, what it writes there, and what the file must still hold so the step undoes
|
||||
* nobody's later work: the entry's own files, and the files an undo that kept them left (back to the original's). */
|
||||
stepsOf(entry: HistoryEntry): { path: string; to: string | null; holds: string | null }[] {
|
||||
const redoKept = this.keptByRedo(entry);
|
||||
const own = entry.files.map((file) => ({
|
||||
path: file.path,
|
||||
to: file.before,
|
||||
holds: keptHash(redoKept, file.path) ?? file.after,
|
||||
}));
|
||||
const original = entry.undoes ? this.log.entries.find((e) => e.id === entry.undoes) : undefined;
|
||||
const left = entry.keptInPlace ?? {};
|
||||
const kept = Object.keys(left).flatMap((path) => {
|
||||
const file = original?.files.find((change) => change.path === path);
|
||||
return file ? [{ path, to: file.after, holds: left[path]! }] : [];
|
||||
});
|
||||
return [...own, ...kept];
|
||||
}
|
||||
|
||||
/** What the redo of `entry` now in effect left in place of its changes, path to hash; empty when it kept none. */
|
||||
keptByRedo(entry: HistoryEntry): Record<string, string> {
|
||||
const undone = undoneIds(this.log.entries);
|
||||
const undoOf = (id: string) => this.log.entries.find((e) => e.id === id)?.undoes;
|
||||
const redo = [...this.log.entries]
|
||||
.reverse()
|
||||
.find((e) => e.undoes !== undefined && !undone.has(e.id) && undoOf(e.undoes) === entry.id);
|
||||
return redo?.keptInPlace ?? {};
|
||||
}
|
||||
|
||||
next(direction: "back" | "forward", who: HistoryWho): HistoryEntry | undefined {
|
||||
@@ -1388,9 +1486,7 @@ class Engine {
|
||||
return stepTarget(
|
||||
this.log.entries,
|
||||
direction,
|
||||
(entry) =>
|
||||
writes(entry.files.map((file) => file.path)) &&
|
||||
(mine(entry.who) || (everyone && !ofOpenTurn(entry))),
|
||||
(entry) => writes(stepPaths(entry)) && (mine(entry.who) || (everyone && !ofOpenTurn(entry))),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1411,7 +1507,7 @@ class Engine {
|
||||
|
||||
conflict(
|
||||
entry: HistoryEntry,
|
||||
changed: HistoryFileChange[],
|
||||
changed: readonly { path: string }[],
|
||||
): { files: string[]; newer: string[] } {
|
||||
const paths = new Set(changed.map((file) => file.path));
|
||||
const after = this.log.entries.slice(this.log.entries.indexOf(entry) + 1);
|
||||
|
||||
@@ -3,7 +3,8 @@ import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { Hono } from "hono";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { referenceRewriter, registerFileRoutes } from "./files";
|
||||
import { registerFileRoutes } from "./files";
|
||||
import { referenceRewriter } from "../helpers/fileReferences";
|
||||
import type { StudioApiAdapter } from "../types";
|
||||
|
||||
const rewrite = (text: string, from: string, to: string, folder: boolean) =>
|
||||
|
||||
@@ -3,12 +3,6 @@
|
||||
// parallel — two writers, same switch-case interface. Structural duplication
|
||||
// is load-bearing (both paths must remain testable in isolation).
|
||||
import type { Hono } from "hono";
|
||||
import { encodeUrlPath, decodedUrlPath, decodeCssEscapes } from "@hyperframes/parsers/asset-paths";
|
||||
import {
|
||||
scanHtmlOpeningTags,
|
||||
decodeAuthoredAttribute,
|
||||
HTML_ATTRIBUTE_ENTITIES,
|
||||
} from "@hyperframes/parsers";
|
||||
import { bodyLimit } from "hono/body-limit";
|
||||
import {
|
||||
closeSync,
|
||||
@@ -26,7 +20,7 @@ import {
|
||||
realpathSync,
|
||||
type Dirent,
|
||||
} from "node:fs";
|
||||
import { resolve, dirname, join, sep } from "node:path";
|
||||
import { resolve, dirname, join } from "node:path";
|
||||
import type { StudioApiAdapter } from "../types.js";
|
||||
import { isAudioFile } from "../helpers/mime.js";
|
||||
import { lengthIsTimeline } from "../helpers/compositionInputs.js";
|
||||
@@ -118,7 +112,8 @@ import {
|
||||
insertCompositionIntoSource,
|
||||
} from "../helpers/compositionInsertion.js";
|
||||
import { resolveGsapWriter } from "./gsapMutationCapabilities.js";
|
||||
import { decodeWellFormedEscapes, requestSubPath } from "../helpers/requestSubPath.js";
|
||||
import { requestSubPath } from "../helpers/requestSubPath.js";
|
||||
import { canNameFiles, referenceRewriter, referenceSyntax } from "../helpers/fileReferences.js";
|
||||
import {
|
||||
hasCompositionOutsideTemplates,
|
||||
insertBeforeCloseTag,
|
||||
@@ -715,318 +710,6 @@ function readableText(file: string): string | null {
|
||||
}
|
||||
}
|
||||
|
||||
const escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
|
||||
const SEPARATOR = String.raw`\\{0,2}[\\/]`;
|
||||
const REFERENCE_START = String.raw`(?<![\w./\\+-])`;
|
||||
const FILE_END = String.raw`(?![\w-]|\.\w)`;
|
||||
|
||||
const ENTITY_SPELLINGS = HTML_ATTRIBUTE_ENTITIES;
|
||||
|
||||
function referenceSpellings(char: string): string {
|
||||
const spellings = [escapeRegExp(char)];
|
||||
const encoded = encodeUrlPath(char);
|
||||
if (encoded !== char)
|
||||
spellings.push(encoded.replace(/[A-F]/g, (hex) => `[${hex}${hex.toLowerCase()}]`));
|
||||
if (ENTITY_SPELLINGS[char]) spellings.push(...ENTITY_SPELLINGS[char]);
|
||||
if (["'", '"', "`", "$", " ", "(", ")"].includes(char)) {
|
||||
spellings.push(escapeRegExp(`\${char}`), escapeRegExp(`\${escapeHtmlReference(char)}`));
|
||||
}
|
||||
const scriptSpelling = escapeQuotedReference(char, '"');
|
||||
if (scriptSpelling !== char) spellings.push(escapeRegExp(scriptSpelling));
|
||||
if (["'", "`", "$", " ", "(", ")"].includes(char)) spellings.push(escapeRegExp(`\\${char}`));
|
||||
if (/[\t\n\f\r =<>`]/.test(char)) spellings.push(`&#${char.codePointAt(0)!};`);
|
||||
if (char.charCodeAt(0) < 0x20 || char.charCodeAt(0) === 0x7f) {
|
||||
spellings.push(escapeRegExp(`\\${char.charCodeAt(0).toString(16)} `));
|
||||
}
|
||||
return spellings.length === 1 ? spellings[0]! : `(?:${spellings.join("|")})`;
|
||||
}
|
||||
|
||||
type ReferenceSyntax = "html" | "script" | "css" | "plain";
|
||||
interface ReferenceContext {
|
||||
syntax: ReferenceSyntax;
|
||||
url: boolean;
|
||||
htmlAttribute: boolean;
|
||||
encodeAll: boolean;
|
||||
quote: string;
|
||||
}
|
||||
|
||||
function escapeHtmlReference(path: string): string {
|
||||
return path.replace(/[&"']/g, (char) => ENTITY_SPELLINGS[char]![0]!);
|
||||
}
|
||||
|
||||
function escapeQuotedReference(path: string, quote: string): string {
|
||||
const escaped = JSON.stringify(path).slice(1, -1);
|
||||
return quote === '"'
|
||||
? escaped
|
||||
: escaped.replace(new RegExp(escapeRegExp(quote), "g"), `\\${quote}`);
|
||||
}
|
||||
|
||||
function escapeRawUrlPath(path: string): string {
|
||||
const encodeSpaces = path.startsWith(" ") || path.endsWith(" ");
|
||||
return path.replace(/[\s\S]/g, (char) => {
|
||||
if (char.charCodeAt(0) < 0x20 || ":?%#\\".includes(char) || (encodeSpaces && char === " ")) {
|
||||
return encodeUrlPath(char);
|
||||
}
|
||||
return char;
|
||||
});
|
||||
}
|
||||
|
||||
function spellLike(
|
||||
reference: string,
|
||||
path: string,
|
||||
oldPath: string,
|
||||
context: ReferenceContext,
|
||||
): string {
|
||||
const { syntax, quote, url, encodeAll } = context;
|
||||
if (url && (encodeAll || (reference !== oldPath && /%[0-9A-Fa-f]{2}/.test(reference))))
|
||||
return encodeUrlPath(path);
|
||||
switch (syntax) {
|
||||
case "html": {
|
||||
const escaped = escapeHtmlReference(url ? escapeRawUrlPath(path) : path);
|
||||
return ["'", '"'].includes(quote)
|
||||
? escaped
|
||||
: escaped.replace(/[\t\n\f\r =<>`]/g, (char) => `&#${char.codePointAt(0)!};`);
|
||||
}
|
||||
case "script": {
|
||||
if (!["'", '"', "`"].includes(quote)) return path;
|
||||
const escaped = escapeQuotedReference(path, quote);
|
||||
return quote === "`" ? escaped.replace(/\$\{/g, "\\${") : escaped;
|
||||
}
|
||||
case "css":
|
||||
return url ? encodeUrlPath(path) : path;
|
||||
case "plain":
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
||||
function referenceSyntax(file: string): ReferenceSyntax {
|
||||
if (/\.html$/i.test(file)) return "html";
|
||||
if (/\.css$/i.test(file)) return "css";
|
||||
if (/\.(?:[cm]?js|jsx|tsx?|json)$/i.test(file)) return "script";
|
||||
return "plain";
|
||||
}
|
||||
|
||||
function decodeQuotedReference(text: string, syntax: ReferenceSyntax): string {
|
||||
if (syntax === "css") return decodeCssEscapes(text);
|
||||
if (syntax === "script") {
|
||||
const controls: Record<string, string> = { b: "\b", f: "\f", n: "\n", r: "\r", t: "\t" };
|
||||
return text.replace(
|
||||
/\\(?:u([0-9a-fA-F]{4})|([bfnrt"'`$\\/]))/g,
|
||||
(_escaped, hex: string | undefined, char: string | undefined) => {
|
||||
if (hex !== undefined) return String.fromCharCode(Number.parseInt(hex, 16));
|
||||
return controls[char!] ?? char!;
|
||||
},
|
||||
);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
function referencePattern(oldPath: string, isDirectory: boolean): RegExp {
|
||||
const name = oldPath
|
||||
.split("/")
|
||||
.map((segment) => Array.from(segment, referenceSpellings).join(""))
|
||||
.join(SEPARATOR);
|
||||
const end = isDirectory ? `(?=${SEPARATOR})` : FILE_END;
|
||||
return new RegExp(
|
||||
String.raw`${REFERENCE_START}(?<lead>(?:\.{1,2}${SEPARATOR}|${SEPARATOR}){0,4})${name}${end}`,
|
||||
"g",
|
||||
);
|
||||
}
|
||||
|
||||
function rewriteEntityAttributes(text: string, rewrite: (text: string) => string): string {
|
||||
const parts: string[] = [];
|
||||
let cursor = 0;
|
||||
for (const tag of scanHtmlOpeningTags(text)) {
|
||||
for (const attr of tag.attributes) {
|
||||
if (attr.kind !== "value") continue;
|
||||
const decoded = decodeAuthoredAttribute(attr.value);
|
||||
if (decoded === attr.value) continue;
|
||||
let value = escapeHtmlReference(decoded);
|
||||
if (!attr.quote)
|
||||
value = value.replace(/[\t\n\f\r =<>`]/g, (char) => `&#${char.codePointAt(0)!};`);
|
||||
const source = `<x ${attr.name}=${attr.quote}${value}${attr.quote}>`;
|
||||
const updated = rewrite(source);
|
||||
if (updated === source) continue;
|
||||
const replacement = scanHtmlOpeningTags(updated)[0]!.attributes[0]!;
|
||||
if (replacement.kind !== "value") throw new Error("Reference rewrite removed its attribute");
|
||||
parts.push(text.slice(cursor, attr.valueStart), replacement.value);
|
||||
cursor = attr.valueEnd;
|
||||
}
|
||||
}
|
||||
parts.push(text.slice(cursor));
|
||||
return parts.join("");
|
||||
}
|
||||
|
||||
// A match inside the longer path of a file or folder that exists (`a.png&b.png`, `other assets/`) is that path's.
|
||||
// Existing paths are indexed by the text after the old path, then the text before it, so a match costs a few lookups.
|
||||
export function referenceRewriter(
|
||||
oldPath: string,
|
||||
newPath: string,
|
||||
isDirectory: boolean,
|
||||
existing: readonly string[] = [],
|
||||
): (text: string, syntax?: ReferenceSyntax) => string {
|
||||
const oldIdentity = sep === "\\" ? oldPath.replace(/\\/g, "/") : oldPath;
|
||||
const pattern = referencePattern(oldPath, isDirectory);
|
||||
const around = new Map<string, Map<number, Set<string>>>();
|
||||
const afterLengths = new Set<number>();
|
||||
let window = 0;
|
||||
for (const path of existing) {
|
||||
if (path.length <= oldPath.length) continue;
|
||||
for (const start of occurrences(path, oldPath)) {
|
||||
const [before, after] = [path.slice(0, start), path.slice(start + oldPath.length)];
|
||||
const befores = around.get(after) ?? around.set(after, new Map()).get(after)!;
|
||||
(befores.get(before.length) ?? befores.set(before.length, new Set()).get(before.length)!).add(
|
||||
before,
|
||||
);
|
||||
afterLengths.add(after.length);
|
||||
window = Math.max(window, path.length * 9);
|
||||
}
|
||||
}
|
||||
const normalized = (text: string, context: ReferenceContext, full = false) => {
|
||||
let value = text;
|
||||
if (context.syntax === "html" || context.htmlAttribute) {
|
||||
value = decodeAuthoredAttribute(value);
|
||||
}
|
||||
value = decodeQuotedReference(value, context.syntax);
|
||||
if (context.url) {
|
||||
value = value.replace(/\\/g, "/");
|
||||
value = full ? decodedUrlPath(value) : decodeWellFormedEscapes(value);
|
||||
}
|
||||
return sep === "\\" ? value.replace(/\\/g, "/") : value;
|
||||
};
|
||||
return function rewriteText(text, syntax = "html", normalizeEntities = true) {
|
||||
if (syntax === "html" && normalizeEntities) {
|
||||
text = rewriteEntityAttributes(text, (source) => rewriteText(source, "html", false));
|
||||
}
|
||||
pattern.lastIndex = 0;
|
||||
if (!pattern.test(text)) return text;
|
||||
pattern.lastIndex = 0;
|
||||
const tags = syntax === "html" ? scanHtmlOpeningTags(text) : [];
|
||||
const inlineRegions = tags
|
||||
.filter(
|
||||
(tag) => tag.closed && ["script", "style"].includes(tag.name) && tag.rawTextEnd !== null,
|
||||
)
|
||||
.map((tag) => ({
|
||||
start: tag.end,
|
||||
end: tag.rawTextEnd!,
|
||||
syntax: tag.name === "style" ? ("css" as const) : ("script" as const),
|
||||
}));
|
||||
const attributes = tags.flatMap((tag) =>
|
||||
tag.attributes.flatMap((attr) => (attr.kind === "value" ? [attr] : [])),
|
||||
);
|
||||
const cssContexts =
|
||||
syntax === "css"
|
||||
? [{ start: 0, end: text.length, htmlAttribute: false }]
|
||||
: [
|
||||
...inlineRegions
|
||||
.filter((region) => region.syntax === "css")
|
||||
.map((region) => ({ ...region, htmlAttribute: false })),
|
||||
...attributes
|
||||
.filter((attr) => attr.name === "style")
|
||||
.map((attr) => ({ ...attr, htmlAttribute: true })),
|
||||
];
|
||||
const cssFields = (pattern: RegExp) =>
|
||||
cssContexts.flatMap((context) =>
|
||||
[...text.slice(context.start, context.end).matchAll(pattern)].map((match) => {
|
||||
const prefix = /^(?:url\(\s*|@import\s+)/i.exec(match[0])![0];
|
||||
const rest = match[0].slice(prefix.length);
|
||||
const delimiter = context.htmlAttribute
|
||||
? /^(?:["']|"|'|')/.exec(rest)?.[0]
|
||||
: /^["']/.exec(rest)?.[0];
|
||||
const start = context.start + match.index! + prefix.length + (delimiter?.length ?? 0);
|
||||
return {
|
||||
start,
|
||||
end: context.start + match.index! + match[0].length,
|
||||
syntax: "css" as const,
|
||||
htmlAttribute: context.htmlAttribute,
|
||||
encodeAll: true,
|
||||
};
|
||||
}),
|
||||
);
|
||||
const urlRegions = [
|
||||
...attributes
|
||||
.filter((attr) => ["src", "href", "poster", "xlink:href"].includes(attr.name))
|
||||
.map((attr) => ({
|
||||
start: attr.valueStart + (/^[\t\n\f\r ]*/.exec(attr.value)?.[0].length ?? 0),
|
||||
end: attr.valueEnd,
|
||||
syntax: "html" as const,
|
||||
htmlAttribute: true,
|
||||
encodeAll: false,
|
||||
})),
|
||||
...attributes
|
||||
.filter((attr) => attr.name === "srcset")
|
||||
.flatMap((attr) =>
|
||||
[...attr.value.matchAll(/(^|,)[\t\n\f\r ]*([^,\t\n\f\r ]+)/g)].map((match) => ({
|
||||
start: attr.valueStart + match.index! + match[0].length - match[2]!.length,
|
||||
end: attr.valueStart + match.index! + match[0].length,
|
||||
syntax: "html" as const,
|
||||
htmlAttribute: true,
|
||||
encodeAll: true,
|
||||
})),
|
||||
),
|
||||
...cssFields(
|
||||
/\burl\((?:\s*"(?:\\.|[^"\\])*"\s*|\s*'(?:\\.|[^'\\])*'\s*|(?:\\.|[^)\\])*)\)/gi,
|
||||
),
|
||||
...cssFields(/@import\s+(?:"[^"]*"|'[^']*')/gi),
|
||||
].sort((a, b) => a.start - b.start);
|
||||
let urlIndex = 0;
|
||||
let regionIndex = 0;
|
||||
return text.replace(pattern, (...args) => {
|
||||
const [match, offset] = [args[0] as string, args.at(-3) as number];
|
||||
const { lead } = args.at(-1) as { lead: string };
|
||||
while (inlineRegions[regionIndex] && inlineRegions[regionIndex]!.end <= offset) regionIndex++;
|
||||
const region = inlineRegions[regionIndex];
|
||||
const matchSyntax = region && offset >= region.start ? region.syntax : syntax;
|
||||
while (urlRegions[urlIndex] && urlRegions[urlIndex]!.end <= offset) urlIndex++;
|
||||
const urlRegion = urlRegions[urlIndex];
|
||||
const url = matchSyntax !== "script" && !!urlRegion && offset >= urlRegion.start;
|
||||
const context: ReferenceContext = {
|
||||
syntax: url ? urlRegion!.syntax : matchSyntax,
|
||||
url,
|
||||
htmlAttribute: url && urlRegion!.htmlAttribute,
|
||||
encodeAll: url && urlRegion!.encodeAll,
|
||||
quote: text[offset - 1] ?? "",
|
||||
};
|
||||
if (url && offset !== urlRegion!.start) return match;
|
||||
const reference = match.slice(lead.length);
|
||||
if (normalized(reference, context, true) !== oldIdentity) return match;
|
||||
if (
|
||||
isDirectory &&
|
||||
!normalized(
|
||||
text.slice(offset + match.length, offset + match.length + 4),
|
||||
context,
|
||||
).startsWith("/")
|
||||
)
|
||||
return match;
|
||||
const at = offset + lead.length;
|
||||
const head = normalized(text.slice(Math.max(0, at - window), at), context);
|
||||
const tail = normalized(
|
||||
text.slice(offset + match.length, offset + match.length + window),
|
||||
context,
|
||||
context.url,
|
||||
);
|
||||
const inLonger = [...afterLengths].some((after) => {
|
||||
const befores = tail.length >= after && around.get(tail.slice(0, after));
|
||||
return (
|
||||
befores &&
|
||||
[...befores].some(
|
||||
([length, set]) => head.length >= length && set.has(head.slice(head.length - length)),
|
||||
)
|
||||
);
|
||||
});
|
||||
if (inLonger) return match;
|
||||
return `${lead}${spellLike(reference, newPath, oldPath, context)}`;
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
function occurrences(text: string, part: string): number[] {
|
||||
const at: number[] = [];
|
||||
for (let i = text.indexOf(part); i >= 0; i = text.indexOf(part, i + 1)) at.push(i);
|
||||
return at;
|
||||
}
|
||||
|
||||
function projectPaths(
|
||||
root: string,
|
||||
dir = root,
|
||||
@@ -1062,9 +745,7 @@ function updateReferences(
|
||||
newPath: string,
|
||||
isDirectory: boolean,
|
||||
): number {
|
||||
const textFiles = walkFiles(projectDir, (name) =>
|
||||
/\.(html|css|js|jsx|ts|tsx|json|mjs|cjs|md|mdx)$/i.test(name),
|
||||
);
|
||||
const textFiles = walkFiles(projectDir, canNameFiles);
|
||||
|
||||
const rewrite = referenceRewriter(oldPath, newPath, isDirectory, projectPaths(projectDir));
|
||||
let updatedCount = 0;
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
// @vitest-environment node
|
||||
// fallow-ignore-file code-duplication
|
||||
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import {
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readdirSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { createServer } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
@@ -228,6 +236,21 @@ describe("history routes", () => {
|
||||
expect((await call(`/blob/${encodeURIComponent(outsideHistory)}`)).status).toBe(404);
|
||||
});
|
||||
|
||||
// fails without the fix: the redo of an undo that kept its file changes no file, so it named no paths.
|
||||
it("name the file a redo of a kept upload will write", async () => {
|
||||
const { projectDir, history, call } = await demoProject();
|
||||
const you = { kind: "person", name: "You" } as const;
|
||||
mkdirSync(join(projectDir, "assets"));
|
||||
writeFileSync(join(projectDir, "assets/song.mp3"), "mp3");
|
||||
await history.claim(you, "Uploaded", ["assets/song.mp3"]);
|
||||
writeFileSync(join(projectDir, "index.html"), '<audio src="assets/song.mp3"></audio>');
|
||||
await history.claim({ kind: "agent", name: "Agent" }, "Music", ["index.html"]);
|
||||
expect(await history.step("back", you)).toMatchObject({ ok: true });
|
||||
expect(await (await call("")).json()).toMatchObject({
|
||||
forward: { label: "Undid: Uploaded", paths: ["assets/song.mp3"] },
|
||||
});
|
||||
});
|
||||
|
||||
it("name what Cmd+Z and Cmd+Shift+Z would revert next", async () => {
|
||||
const { projectDir, call } = await demoProject();
|
||||
expect(await (await call("")).json()).toMatchObject({ back: null, forward: null });
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
type HistoryWindow,
|
||||
type ProjectHistory,
|
||||
} from "../history/projectHistory.js";
|
||||
import type { HistoryWho, HistoryTarget } from "../history/historyLog.js";
|
||||
import { stepPaths, type HistoryWho, type HistoryTarget } from "../history/historyLog.js";
|
||||
import { HistoryBusyError } from "../history/ownerLock.js";
|
||||
|
||||
const YOU: HistoryWho = { kind: "person", name: "You" };
|
||||
@@ -97,7 +97,7 @@ const isSelectorIndex = (value: unknown): value is number =>
|
||||
function nextStep(history: ProjectHistory, direction: "back" | "forward") {
|
||||
const target = history.next(direction, YOU);
|
||||
if (!target) return null;
|
||||
const paths = target.files.map((file) => file.path);
|
||||
const paths = stepPaths(target);
|
||||
return { id: target.id, label: target.label, endedAt: target.endedAt, paths };
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user