perf: share CLI startup for user-site publishing (#6704)

This PR reduces user-site publish time by sharing CLI startup between
sync and build, reducing asset downloads when hosted builds do not need
them, and testing smaller publish artifacts. The paired [SaaS PR
#685](https://github.com/webstudio-is/webstudio-saas/pull/685) uses the
combined CLI path when the Builder artifact advertises support; older
artifacts keep the existing split path.

The paired staging publish served HTML and JavaScript successfully. The
combined CLI step took 4 s versus about 8 s for the previous split steps
in that run; total publish time remained about 40 s. This is one
observation, not a controlled benchmark or a large-site measurement.
Local artifact pruning reduced the compressed archive from 119 MiB to
111 MiB (6.7%); it was not adopted. The full artifact is still
downloaded and extracted on every publish.

## Checklist

- [x] Preserve standalone sync/build behavior and gate combined
sync/build with an artifact capability marker.
- [x] Skip hosted asset downloads only when content indexing does not
need them; preserve static and MDX-required downloads.
- [x] Test CLI startup, synthetic build, and artifact-size
opportunities; record why no riskier change was adopted.
- [x] Verify the paired staging publish and review Builder
documentation.
- [x] Keep only the E2E schema snapshot matching current inputs; no
migration source or migration was added.
- [x] Retry the failing `pages-drag` shard: all 17 tests passed,
including the drag-and-nest test.
- [x] Resolve the two outdated review threads; current code retains
finding details and closes diagnostics on element navigation.
- [x] Required CI on the cleanup commit passed, including all Builder
E2E shards, visual regression, and the existing migration-chain check.
- [ ] Run the agent evaluation suite only after separate approval;
remind the user before merging.

No large-site publish or production release has been tested.
This commit is contained in:
Oleg Isonen authored and GitHub committed 2026-11-17 14:04:00 +01:00
1 parent 9a86222afd
commit b9319a3891
17 files changed
+2593 -101

No files matched your search

+3 -1
View File
@@ -59,7 +59,9 @@ jobs:
# Despite being listed as a dependency, @remix-run/dev does not install the remix cli.
# TODO: Minimize artefact size due to frequent downloads on each publish.
- name: pnpm deploy
run: pnpm --filter 'ssg-cloudflare-pages' deploy "${{ github.workspace }}/../ssg-template"
run: |
pnpm --filter 'ssg-cloudflare-pages' deploy "${{ github.workspace }}/../ssg-template"
touch "${{ github.workspace }}/../ssg-template/.webstudio-cli-sync-build-v1"
- name: Verify optional Assets build dependency is omitted
run: test ! -e node_modules/@webstudio-is/content-engine/package.json
+3 -4
View File
@@ -56,11 +56,10 @@ jobs:
- name: pnpm build
run: pnpm --filter 'webstudio-cloudflare-template^...' run build
# Ideally, execute 'pnpm deploy --prod', but @remix-run/dev doesn't support this flag.
# Despite being listed as a dependency, @remix-run/dev does not install the remix cli.
# TODO: Minimize artefact size due to frequent downloads on each publish.
- name: pnpm deploy
run: pnpm --filter 'webstudio-cloudflare-template' deploy "${{ github.workspace }}/../cloudflare-template"
run: |
pnpm --filter 'webstudio-cloudflare-template' deploy --prod "${{ github.workspace }}/../cloudflare-template"
touch "${{ github.workspace }}/../cloudflare-template/.webstudio-cli-sync-build-v1"
- name: Verify optional Assets build dependency is omitted
run: test ! -e node_modules/@webstudio-is/content-engine/package.json
File diff suppressed because it is too large. Load diff
@@ -30,6 +30,7 @@
"dependencies": {
"@remix-run/cloudflare": "2.16.5",
"@remix-run/cloudflare-pages": "2.16.5",
"@remix-run/dev": "2.16.5",
"@remix-run/node": "2.16.5",
"@remix-run/react": "2.16.5",
"@remix-run/server-runtime": "2.16.5",
@@ -49,18 +50,17 @@
"zod": "^4.4.3",
"@shikijs/langs": "4.4.1",
"@shikijs/themes": "4.4.1",
"shiki": "4.4.1"
"lightningcss": "1.31.1",
"shiki": "4.4.1",
"vite": "^6.3.4",
"wrangler": "4.130.0"
},
"devDependencies": {
"@cloudflare/workers-types": "^4.20240620.0",
"@remix-run/dev": "2.16.5",
"@types/react": "^18.2.70",
"@types/react-dom": "^18.2.25",
"fast-glob": "^3.3.2",
"typescript": "7.0.2",
"vite": "^6.3.4",
"wrangler": "4.130.0",
"lightningcss": "1.31.1"
"typescript": "7.0.2"
},
"devEngines": {
"runtime": {
+1 -2
View File
@@ -42,8 +42,7 @@
"@types/react": "^18.2.70",
"@types/react-dom": "^18.2.25",
"fast-glob": "^3.3.2",
"typescript": "7.0.2",
"webstudio": "workspace:*"
"typescript": "7.0.2"
},
"engines": {
"node": ">=22.12.0"
+32 -1
View File
@@ -1,6 +1,6 @@
import { spawnSync } from "node:child_process";
import { existsSync } from "node:fs";
import { mkdtemp, readFile, rm } from "node:fs/promises";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
@@ -95,3 +95,34 @@ test("local launcher restores shell cwd when pnpm starts from package directory"
await rm(projectRoot, { recursive: true, force: true });
}
}, 15_000);
test("build without a template keeps its existing CLI error", async () => {
const projectRoot = await mkdtemp(
join(tmpdir(), "webstudio-bin-build-test-")
);
const env: NodeJS.ProcessEnv = {
...process.env,
PWD: projectRoot,
WEBSTUDIO_CONFIG_DIR: join(projectRoot, "config"),
};
delete env.NODE_OPTIONS;
delete env.WEBSTUDIO_LOCAL_CLI_BOOTSTRAPPED;
try {
await mkdir(join(projectRoot, ".webstudio"));
await writeFile(join(projectRoot, ".webstudio", "data.json"), "{}");
const result = spawnSync(process.execPath, [localPath, "build"], {
cwd: packageRoot,
env,
encoding: "utf-8",
});
expect(result.status).toBe(1);
expect(result.stdout + result.stderr).toContain("Template is not provided");
expect(result.stdout + result.stderr).toContain(
"Please check webstudio --help for more details"
);
} finally {
await rm(projectRoot, { recursive: true, force: true });
}
}, 30_000);
+26
View File
@@ -6,6 +6,7 @@ import {
cliCommandMetadata,
} from "./commands/api-command-metadata";
import {
buildCommandOptions,
getTopLevelMcpToolForwardArgs,
getTopLevelMcpToolHint,
handleOutputStreamError,
@@ -101,6 +102,31 @@ const getHelpOutput = async (args: string[]) => {
};
describe("registerCommands", () => {
test("build accepts sync flags without requiring a template", async () => {
const output = await getHelpOutput(["build", "--help"]);
expect(output).toContain("--buildId");
expect(output).toContain("--origin");
expect(output).toContain("--authToken");
expect(output).toContain("--template");
});
test("build requires a template without a build id", async () => {
const cli = (makeCLI() as CommonYargsArgv)
.exitProcess(false)
.command("build", "", buildCommandOptions, () => undefined)
.fail((message, error) => {
throw error ?? new Error(message);
});
await expect(async () => cli.parseAsync(["build"])).rejects.toThrow(
"Template is not provided\nPlease check webstudio --help for more details"
);
await expect(
cli.parseAsync(["build", "--buildId", "build-1"])
).resolves.toMatchObject({ buildId: "build-1", template: [] });
});
test("exits successfully on broken pipe output errors", () => {
const exitProcess = vi.fn((code?: number) => {
throw new Error(`exit ${code}`);
+12 -12
View File
@@ -178,20 +178,20 @@ export const rootCliEpilogue = [
"MCP tool shortcuts are forwarded to mcp single-op-call for shell-driven agents.",
].join("\n");
export const buildCommandOptions = (yargs: CommonYargsArgv) =>
buildOptions(syncOptions(yargs)).check((options) => {
if (options.buildId === undefined && options.template.length === 0) {
return "Template is not provided\nPlease check webstudio --help for more details";
}
return true;
});
export const registerCommands = (cmd: CommonYargsArgv) => {
cmd.command(
["build"],
"Build the project",
(yargs: CommonYargsArgv) => {
return buildOptions(yargs).demandOption(
"template",
"Please specify a template to use for the build"
);
},
build
);
cmd.command(["build"], "Build the project", buildCommandOptions, build);
cmd.command(["link"], "Link the project with the cloud", linkOptions, link);
cmd.command(["sync"], "Sync your project", syncOptions, sync);
cmd.command(["sync"], "Sync your project", syncOptions, async (options) => {
await sync(options);
});
cmd.command(
["import"],
"Import the synced project bundle into another project",
+129
View File
@@ -0,0 +1,129 @@
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, expect, test, vi } from "vitest";
import { build } from "./build";
const originalCwd = process.cwd();
const directories: string[] = [];
const useSyncedProject = async () => {
const directory = await mkdtemp(join(tmpdir(), "webstudio-build-command-"));
directories.push(directory);
process.chdir(directory);
await mkdir(".webstudio");
await writeFile(".webstudio/data.json", "{}");
};
afterEach(async () => {
vi.restoreAllMocks();
process.chdir(originalCwd);
await Promise.all(
directories
.splice(0)
.map((directory) => rm(directory, { recursive: true, force: true }))
);
});
test("syncs before building and expands published static templates", async () => {
await useSyncedProject();
const order: string[] = [];
const sync = vi.fn(async () => {
order.push("sync");
return ["ssg-netlify" as const];
});
const prebuild = vi.fn(async () => {
order.push("build");
});
await build(
{
assets: true,
template: [],
buildId: "build-1",
origin: "https://example.com",
authToken: "token",
},
{ sync, prebuild }
);
expect(order).toEqual(["sync", "build"]);
expect(sync).toHaveBeenCalledWith({
assets: true,
template: [],
buildId: "build-1",
origin: "https://example.com",
authToken: "token",
});
expect(prebuild).toHaveBeenCalledWith(
expect.objectContaining({ template: ["ssg", "ssg-netlify"] })
);
});
test("keeps explicit templates for hosted publishing", async () => {
await useSyncedProject();
const sync = vi.fn(async () => ["ssg" as const]);
const prebuild = vi.fn(async () => undefined);
await build(
{ assets: false, template: ["internal", "cloudflare"], buildId: "build-1" },
{ sync, prebuild }
);
expect(prebuild).toHaveBeenCalledWith(
expect.objectContaining({ template: ["internal", "cloudflare"] })
);
});
test("does not build if sync fails", async () => {
const failure = new Error("sync failed");
const sync = vi.fn(async (): Promise<undefined> => {
throw failure;
});
const prebuild = vi.fn(async () => undefined);
await expect(
build(
{ assets: true, template: ["ssg"], buildId: "build-1" },
{ sync, prebuild }
)
).rejects.toBe(failure);
expect(prebuild).not.toHaveBeenCalled();
});
test("passes missing hosted templates to existing build validation", async () => {
await useSyncedProject();
const sync = vi.fn(async () => undefined);
const prebuild = vi.fn(async ({ template }: { template: string[] }) => {
if (template.length === 0) {
throw new Error("missing template");
}
});
await expect(
build(
{ assets: true, template: [], buildId: "build-1" },
{ sync, prebuild }
)
).rejects.toThrow("missing template");
expect(sync).toHaveBeenCalledOnce();
expect(prebuild).toHaveBeenCalledWith(
expect.objectContaining({ template: [] })
);
});
test("builds an already synced project without fetching it again", async () => {
await useSyncedProject();
const sync = vi.fn(async () => undefined);
const prebuild = vi.fn(async () => undefined);
await build(
{ assets: false, template: ["react-router"] },
{ sync, prebuild }
);
expect(sync).not.toHaveBeenCalled();
expect(prebuild).toHaveBeenCalledWith(
expect.objectContaining({ template: ["react-router"] })
);
});
+17 -2
View File
@@ -12,6 +12,7 @@ import type {
StrictYargsOptionsToInterface,
} from "./yargs-types";
import { mapToTemplatesFromOptions } from "../build-utils";
import { sync } from "./sync";
export const buildOptions = (yargs: CommonYargsArgv) =>
yargs
@@ -34,8 +35,22 @@ export const buildOptions = (yargs: CommonYargsArgv) =>
// @todo: use options.assets to define if we need to download assets
export const build = async (
options: StrictYargsOptionsToInterface<typeof buildOptions>
options: StrictYargsOptionsToInterface<typeof buildOptions> & {
buildId?: string;
origin?: string;
authToken?: string;
},
dependencies = { sync, prebuild }
) => {
const syncedTemplates =
options.buildId === undefined
? undefined
: await dependencies.sync(options);
const templates =
options.template.length > 0
? options.template
: mapToTemplatesFromOptions(syncedTemplates ?? []);
try {
await access(LOCAL_DATA_FILE);
} catch (error: unknown) {
@@ -49,5 +64,5 @@ export const build = async (
throw error;
}
await prebuild(options);
await dependencies.prebuild({ ...options, template: templates });
};
+165 -8
View File
@@ -272,10 +272,71 @@ test("downloads project bundle asset files into local project bundle", async ()
expect(indicator.message).toHaveBeenCalledWith("Downloading 1 asset files");
});
test("skips asset downloads for a hosted build with assets disabled", async () => {
const assets = [createImageAssetFixture()];
loadProjectBundleByBuildId.mockResolvedValue(
createProjectBundle({
assets,
build: { deployment: { destination: "saas", domains: [] } },
})
);
await sync(
{
assets: false,
authToken: "token-1",
buildId: "build-1",
origin: "https://example.com",
},
dependencies
);
expect(downloadAssetFiles).not.toHaveBeenCalled();
const data = JSON.parse(await readFile(".webstudio/data.json", "utf8"));
expect(data.assets).toEqual(assets);
});
test.each([
{
name: "static build",
deployment: {
destination: "static" as const,
name: "site.zip",
assetsDomain: "https://assets.example.com",
templates: ["ssg" as const],
},
},
{ name: "build without a destination", deployment: undefined },
])(
"downloads non-MDX assets for a $name with assets disabled",
async ({ deployment }) => {
const assets = [createImageAssetFixture()];
loadProjectBundleByBuildId.mockResolvedValue(
createProjectBundle({ assets, build: { deployment } })
);
await sync(
{
assets: false,
authToken: "token-1",
buildId: "build-1",
origin: "https://example.com",
},
dependencies
);
expect(downloadAssetFiles).toHaveBeenCalledWith({
assets,
origin: "https://example.com",
});
}
);
test.each([
{
name: "hosted",
deployment: { destination: "saas" as const, domains: [] },
fullContentQuery: false,
},
{
name: "SSG",
@@ -285,10 +346,21 @@ test.each([
assetsDomain: "https://assets.example.com",
templates: ["ssg" as const],
},
fullContentQuery: false,
},
{
name: "build without a destination",
deployment: undefined,
fullContentQuery: false,
},
{
name: "hosted with a full-content text query",
deployment: { destination: "saas" as const, domains: [] },
fullContentQuery: true,
},
])(
"$name publish sync compiles required MDX articles",
async ({ deployment }) => {
async ({ deployment, fullContentQuery }) => {
const source = "# Published from the runner";
const article = {
...createImageAssetFixture(),
@@ -300,9 +372,19 @@ test.each([
meta: {},
};
const image = createImageAssetFixture();
const textAsset = {
...createImageAssetFixture(),
id: "text",
name: "note.txt",
type: "file" as const,
format: "txt",
size: new TextEncoder().encode("Important note").byteLength,
meta: {},
};
const assets = [article, image, ...(fullContentQuery ? [textAsset] : [])];
loadProjectBundleByBuildId.mockResolvedValue(
createProjectBundle({
assets: [article, image],
assets,
build: {
deployment,
instances: [
@@ -345,7 +427,57 @@ test.each([
value: article.id,
},
],
...(fullContentQuery
? [
[
"text-query-prop",
{
id: "text-query-prop",
instanceId: "root",
name: "text",
type: "resource" as const,
value: "text-query",
},
] as [
string,
{
id: string;
instanceId: string;
name: string;
type: "resource";
value: string;
},
],
]
: []),
],
resources: fullContentQuery
? [
[
"text-query",
{
id: "text-query",
name: "Text",
control: "system" as const,
method: "post" as const,
url: '"/$resources/assets"',
headers: [],
body: createStructuredAssetQueryResourceBody({
where: {
field: ["id"],
operator: "eq",
value: '"text"',
},
sort: [],
limit: "1",
offset: "0",
output: { mode: "all", includeMetadata: true },
content: { mode: "full" },
}),
},
],
]
: [],
},
})
);
@@ -355,14 +487,19 @@ test.each([
assets.map((asset: { id: string; name: string }) =>
writeFile(
`.webstudio/assets/${asset.name}`,
asset.id === article.id ? source : "image"
asset.id === article.id
? source
: asset.id === textAsset.id
? "Important note"
: "image"
)
)
);
});
await sync(
const syncedTemplates = await sync(
{
assets: false,
authToken: "token-1",
buildId: "build-1",
origin: "https://example.com",
@@ -370,19 +507,32 @@ test.each([
dependencies
);
expect(syncedTemplates).toEqual(
deployment?.destination === "static" ? ["ssg"] : undefined
);
const data = JSON.parse(await readFile(".webstudio/data.json", "utf8"));
expect(downloadAssetFiles).toHaveBeenCalledWith({
assets: [article, image],
assets:
deployment?.destination === "saas" && !fullContentQuery
? [article]
: assets,
origin: "https://example.com",
});
expect(data.assetIndex.documents).toContainEqual(
expect.objectContaining({ _id: article.id, extension: "mdx" })
);
expect(data.assets).toEqual(assets);
expect(Object.values(data.assetIndex.contents)).toContain(source);
if (fullContentQuery) {
expect(Object.values(data.assetIndex.contents)).toContain(
"Important note"
);
}
await prebuild({
assets: false,
template: [deployment.destination === "static" ? "ssg" : "react-router"],
template: [deployment?.destination === "static" ? "ssg" : "react-router"],
});
const generatedPage = await readFile(
"app/__generated__/_index.tsx",
@@ -800,11 +950,14 @@ test("syncs current editable data without requiring a published project", async
}));
const current = createProjectBundle({
build: { version: 438 },
build: {
version: 438,
deployment: { destination: "saas", domains: [] },
},
assets: [createImageAssetFixture()],
});
loadCurrentProjectBundle.mockResolvedValue(current);
await sync({}, { ...dependencies, resolveApiConnection });
await sync({ assets: false }, { ...dependencies, resolveApiConnection });
expect(loadProjectBundleByProjectId).not.toHaveBeenCalled();
expect(loadCurrentProjectBundle).toHaveBeenCalledWith({
authToken: "share-token",
@@ -815,6 +968,10 @@ test("syncs current editable data without requiring a published project", async
const data = JSON.parse(await readFile(".webstudio/data.json", "utf8"));
expect(data.build.version).toBe(438);
expect(data.assets).toEqual(current.assets);
expect(downloadAssetFiles).toHaveBeenCalledWith({
assets: current.assets,
origin: "https://example.com",
});
});
test("explains unpublished project bundle errors when synchronizing by build id", async () => {
+46 -9
View File
@@ -49,8 +49,12 @@ import {
import {
createReachableAssetContentCompilationPlan,
getHomePage,
getMimeTypeByFilename,
} from "@webstudio-is/sdk";
import { parseContentDatabaseMaxBytes } from "@webstudio-is/content-engine";
import {
getDocumentFormatByContentType,
parseContentDatabaseMaxBytes,
} from "@webstudio-is/content-engine";
import {
compileContentSource,
compileContentUntilPlanIsStable,
@@ -154,7 +158,11 @@ export const syncOptions = (yargs: CommonYargsArgv) =>
describe: "[Experimental] Service token",
});
type SyncOptions = Partial<StrictYargsOptionsToInterface<typeof syncOptions>>;
type SyncOptions = Partial<
StrictYargsOptionsToInterface<typeof syncOptions>
> & {
assets?: boolean;
};
const unpublishedProjectBundleMessage = [
"The selected build cannot be exported.",
@@ -275,13 +283,14 @@ export const sync = async (
},
});
const createContentSource = () =>
const createContentSource = (metadataOnlyNonDocumentAssets = false) =>
createFileSystemContentSource({
projectId: project.build.projectId,
assets: project.assets,
folders: new Map(
(project.assetFolders ?? []).map((folder) => [folder.id, folder])
),
metadataOnlyNonDocumentAssets,
});
const isStaticBuild = project.build.deployment?.destination === "static";
@@ -307,12 +316,36 @@ export const sync = async (
publicationPlan?.queries.some(({ id }) =>
id.startsWith("__content-block-mdx__:")
) === true;
const metadataOnlyNonDocumentAssets =
options.assets === false &&
options.buildId !== undefined &&
project.build.deployment?.destination === "saas" &&
needsMdxCompilation &&
publicationPlan?.queries.some(
({ id, content }) =>
!id.startsWith("__content-block-mdx__:") &&
(content.mode === "full" || content.mode === "range")
) !== true;
const assetsToDownload =
options.buildId !== undefined && !isStaticBuild && !needsMdxCompilation
? project.assets.filter(
(asset) => asset.format !== "md" && asset.format !== "mdx"
)
: project.assets;
options.assets === false &&
options.buildId !== undefined &&
project.build.deployment?.destination === "saas" &&
!needsMdxCompilation
? []
: metadataOnlyNonDocumentAssets
? project.assets.filter(
(asset) =>
getDocumentFormatByContentType(
getMimeTypeByFilename(asset.name)
) !== undefined
)
: options.buildId !== undefined &&
!isStaticBuild &&
!needsMdxCompilation
? project.assets.filter(
(asset) => asset.format !== "md" && asset.format !== "mdx"
)
: project.assets;
if (assetsToDownload.length > 0) {
syncing.message(`Downloading ${assetsToDownload.length} asset files`);
if (project.origin === undefined) {
@@ -348,7 +381,7 @@ export const sync = async (
const plan = candidateDiscoveryPlan ?? publicationPlan;
if (plan !== undefined) {
syncing.message("Preparing local content index");
const source = createContentSource();
const source = createContentSource(metadataOnlyNonDocumentAssets);
const maxBytes = getPublishedMdxContentDatabaseMaxBytes({
baseBytes: parseContentDatabaseMaxBytes(
process.env.CONTENT_DATABASE_MAX_BYTES
@@ -423,4 +456,8 @@ export const sync = async (
? `Project bundle synchronized; AGENTS.md blocked by user-owned file at ${agents.path}. Next: webstudio build`
: `Project bundle synchronized successfully (AGENTS.md: ${agents.status}). Next: webstudio build`
);
return project.build.deployment?.destination === "static"
? project.build.deployment.templates
: undefined;
};
@@ -29,7 +29,7 @@ afterEach(async () => {
);
});
const createAsset = (name: string): Asset => ({
const createAsset = (name: string): Extract<Asset, { type: "file" }> => ({
id: "post",
projectId: "project",
type: "file",
@@ -78,6 +78,125 @@ const plan = createContentCompilationPlan([
]);
describe("filesystem content source", () => {
test("indexes binary metadata without local bytes while reading JSON, Markdown, and MDX", async () => {
const directory = await createTemporaryDirectory();
const documents = [
{ name: "data.json", format: "json", content: '{"title":"Data"}' },
{ name: "article.md", format: "md", content: "# Markdown" },
{ name: "article.mdx", format: "mdx", content: "# MDX" },
];
const assets: Asset[] = [
...documents.map(({ name, format, content }) => ({
...createAsset(name),
id: name,
format,
size: new TextEncoder().encode(content).byteLength,
})),
{
...createAsset("image.png"),
id: "image",
format: "png",
size: 123,
},
];
for (const { name, content } of documents) {
await writeFile(join(directory, name), content);
}
const source = createFileSystemContentSource({
projectId: "project",
assets,
folders,
assetsDirectory: directory,
metadataOnlyNonDocumentAssets: true,
});
const snapshot = await source.openSnapshot();
expect(snapshot.files).toContainEqual(
expect.objectContaining({
id: "image",
size: 123,
contentType: "image/png",
})
);
const documentSources = await snapshot.loadDocumentSources?.();
expect(documentSources?.map(({ id }) => id)).toEqual(
documents.map(({ name }) => name)
);
for (const [index, { content }] of documents.entries()) {
expect(
new TextDecoder().decode(
await readBoundedBytes(documentSources?.[index].source ?? "", 100)
)
).toBe(content);
}
const metadataPlan = createContentCompilationPlan([
createLiteralContentCompilationQuery({
id: "files",
query: {
where: { all: [] },
sort: [],
limit: 10,
offset: 0,
output: { mode: "all", includeMetadata: true },
content: { mode: "none" },
},
}),
]);
const { artifact } = await compileContentSource({
projectId: "project",
source,
plan: metadataPlan,
});
expect(artifact.documents).toContainEqual(
expect.objectContaining({
_id: "image",
size: 123,
mimeType: "image/png",
})
);
const fullContentPlan = createContentCompilationPlan([
createLiteralContentCompilationQuery({
id: "documents",
query: {
where: {
any: ["application/json", "text/markdown", "text/mdx"].map(
(mimeType) => ({
field: ["mimeType"],
operator: "eq" as const,
value: mimeType,
})
),
},
sort: [],
limit: 10,
offset: 0,
output: { mode: "all", includeMetadata: true },
content: { mode: "full" },
},
}),
]);
const compiledDocuments = await compileContentSource({
projectId: "project",
source,
plan: fullContentPlan,
});
expect(Object.values(compiledDocuments.artifact.contents ?? {})).toEqual(
expect.arrayContaining(documents.map(({ content }) => content))
);
});
test("rejects unsafe metadata-only asset paths", async () => {
const directory = await createTemporaryDirectory();
await expect(
createFileSystemContentSource({
projectId: "project",
assets: [createAsset("../outside.png")],
folders,
assetsDirectory: directory,
metadataOnlyNonDocumentAssets: true,
}).openSnapshot()
).rejects.toThrow("Asset path escapes");
});
test("uses the shared parser and hydrates matching local content", async () => {
const directory = await createTemporaryDirectory();
const name = "hello_hash.md";
+80 -38
View File
@@ -18,6 +18,7 @@ import {
} from "@webstudio-is/content-engine";
import {
createAssetFolderHierarchy,
createAssetContentRevision,
formatAssetName,
getFileNameParts,
getMimeTypeByFilename,
@@ -149,28 +150,50 @@ export const createFileSystemContentSource = ({
assets,
folders,
assetsDirectory = LOCAL_ASSETS_DIR,
metadataOnlyNonDocumentAssets = false,
}: {
projectId: string;
assets: readonly Asset[];
folders: AssetFolders;
assetsDirectory?: string;
metadataOnlyNonDocumentAssets?: boolean;
}): ContentSource => ({
openSnapshot: async () => {
const hierarchy = createAssetFolderHierarchy(folders);
const requestedAssetsDirectoryPath = resolve(assetsDirectory);
const hasLocalFiles = assets.some(
(asset) =>
metadataOnlyNonDocumentAssets === false ||
getDocumentFormatByContentType(getMimeTypeByFilename(asset.name)) !==
undefined
);
const assetsDirectoryPath =
assets.length === 0
hasLocalFiles === false
? requestedAssetsDirectoryPath
: await realpath(requestedAssetsDirectoryPath);
const captured = await Promise.all(
assets.map(async (asset) => {
const mimeType = getMimeTypeByFilename(asset.name);
const metadataOnly =
metadataOnlyNonDocumentAssets &&
getDocumentFormatByContentType(mimeType) === undefined;
const sourcePath = getLocalAssetPath(asset.name, assetsDirectory);
const filePath = await resolveContentFilePath({
assetsDirectoryPath,
filePath: sourcePath,
});
const identity = await getFileIdentity(filePath);
const revision = `fs:${serializeFileIdentity(identity)}`;
const filePath = metadataOnly
? undefined
: await resolveContentFilePath({
assetsDirectoryPath,
filePath: sourcePath,
});
const identity =
filePath === undefined ? undefined : await getFileIdentity(filePath);
const revision =
identity === undefined
? createAssetContentRevision({
storageName: asset.name,
updatedAt: asset.updatedAt ?? asset.createdAt,
size: asset.size,
})
: `fs:${serializeFileIdentity(identity)}`;
const name = formatAssetName(asset);
const extension = getFileNameParts(asset.name).extension.toLowerCase();
const folderId = hierarchy.resolveFolderId(asset.folderId);
@@ -192,8 +215,8 @@ export const createFileSystemContentSource = ({
: { description: asset.description }),
...(extension === "" ? {} : { extension }),
...(folderId === undefined ? {} : { folderId, folderNames }),
mimeType: getMimeTypeByFilename(asset.name),
size: Number(identity.size),
mimeType,
size: identity === undefined ? asset.size : Number(identity.size),
createdAt: asset.createdAt,
revision,
contentRef: asset.name,
@@ -215,28 +238,35 @@ export const createFileSystemContentSource = ({
revision,
files: captured.map(({ entry }) => createContentSourceFile(entry)),
loadDocumentSources: async () =>
captured
.filter(
({ entry }) =>
getDocumentFormatByContentType(entry.document.mimeType) !==
undefined
)
.map(({ entry, filePath, identity }) => ({
id: entry.assetId,
source: {
async *[Symbol.asyncIterator]() {
const bytes = await readSnapshotFile({
path: filePath,
identity,
maximumBytes: entry.document.size,
});
if (bytes.byteLength !== entry.document.size) {
throw new Error("Content source file size changed");
}
yield bytes;
captured.flatMap(({ entry, filePath, identity }) => {
if (
getDocumentFormatByContentType(entry.document.mimeType) ===
undefined
) {
return [];
}
if (filePath === undefined || identity === undefined) {
throw new Error("Content source document is missing");
}
return [
{
id: entry.assetId,
source: {
async *[Symbol.asyncIterator]() {
const bytes = await readSnapshotFile({
path: filePath,
identity,
maximumBytes: entry.document.size,
});
if (bytes.byteLength !== entry.document.size) {
throw new Error("Content source file size changed");
}
yield bytes;
},
},
},
})),
];
}),
loadEntries: async (
plan?: ContentCompilationPlan,
options?: { maximumContentBytes: number }
@@ -261,11 +291,15 @@ export const createFileSystemContentSource = ({
base: entry,
requirements,
readBytes: (maximumBytes) =>
readSnapshotFile({
path: filePath,
identity,
maximumBytes,
}),
filePath === undefined || identity === undefined
? Promise.reject(
new Error("Content source file is missing")
)
: readSnapshotFile({
path: filePath,
identity,
maximumBytes,
}),
})
)
);
@@ -274,7 +308,10 @@ export const createFileSystemContentSource = ({
plan,
loadContent: async (entry) => {
const capturedFile = capturedById.get(entry.assetId);
if (capturedFile === undefined) {
if (
capturedFile?.filePath === undefined ||
capturedFile.identity === undefined
) {
throw new Error("Content source snapshot is incomplete");
}
const bytes = await readSnapshotFile({
@@ -299,7 +336,7 @@ export const createFileSystemContentSource = ({
isCurrent: async () => {
try {
if (
assets.length > 0 &&
hasLocalFiles &&
(await realpath(requestedAssetsDirectoryPath)) !==
assetsDirectoryPath
) {
@@ -309,8 +346,13 @@ export const createFileSystemContentSource = ({
await Promise.all(
captured.map(
async ({ sourcePath, filePath, identity }) =>
(await realpath(sourcePath)) === filePath &&
isSameFileIdentity(identity, await getFileIdentity(filePath))
filePath === undefined ||
identity === undefined ||
((await realpath(sourcePath)) === filePath &&
isSameFileIdentity(
identity,
await getFileIdentity(filePath)
))
)
)
).every(Boolean);
+8
View File
@@ -8473,6 +8473,11 @@ export const createManagedFormResourceFetch = () => {
dependencies: {
"local-package": "1.0.0",
},
devDependencies: {
"local-package": "1.0.0",
"local-dev-package": "1.0.0",
existing: "2.0.0",
},
}),
"utf8"
);
@@ -8523,6 +8528,9 @@ export const createManagedFormResourceFetch = () => {
expect(packageJson.scripts.local).toEqual("echo local");
expect(packageJson.dependencies.existing).toEqual("1.0.0");
expect(packageJson.dependencies["local-package"]).toEqual("1.0.0");
expect(packageJson.devDependencies["local-package"]).toBeUndefined();
expect(packageJson.devDependencies["local-dev-package"]).toEqual("1.0.0");
expect(packageJson.devDependencies.existing).toEqual("2.0.0");
const tsconfig = JSON.parse(await readFile("tsconfig.json", "utf8"));
expect(tsconfig.compilerOptions.strict).toEqual(false);
+19 -5
View File
@@ -565,13 +565,27 @@ const mergeJsonInto = async (sourcePath: string, destinationPath: string) => {
throw new Error(error);
}
);
const content = JSON.stringify(
merge(JSON.parse(destinationJson), JSON.parse(sourceJson), {
const mergedJson = merge(
JSON.parse(destinationJson),
JSON.parse(sourceJson),
{
arrayMerge: (_target, source) => source,
}),
null,
" "
}
);
if (basename(destinationPath) === "package.json") {
const packageJson = mergedJson as {
dependencies?: Record<string, string>;
devDependencies?: Record<string, string>;
};
for (const [dependency, specifier] of Object.entries(
packageJson.dependencies ?? {}
)) {
if (packageJson.devDependencies?.[dependency] === specifier) {
delete packageJson.devDependencies[dependency];
}
}
}
const content = JSON.stringify(mergedJson, null, " ");
await writeFile(destinationPath, content, "utf8");
};
+12 -12
View File
@@ -1025,6 +1025,9 @@ importers:
'@remix-run/cloudflare-pages':
specifier: 2.16.5
version: 2.16.5(@cloudflare/workers-types@4.20240701.0)(typescript@7.0.2)
'@remix-run/dev':
specifier: 2.16.5
version: 2.16.5(patch_hash=yortwzoeu3uj2blmdikhhw5byy)(@remix-run/react@2.16.5(react-dom@18.3.0-canary-14898b6a9-20240318(react@18.3.0-canary-14898b6a9-20240318))(react@18.3.0-canary-14898b6a9-20240318)(typescript@7.0.2))(@remix-run/serve@2.16.5(typescript@7.0.2))(@types/node@22.13.10)(jiti@2.4.2)(lightningcss@1.31.1)(tsx@4.19.3)(typescript@7.0.2)(vite@6.3.4(@types/node@22.13.10)(jiti@2.4.2)(lightningcss@1.31.1)(tsx@4.19.3)(yaml@2.9.0))(wrangler@4.130.0(@cloudflare/workers-types@4.20240701.0))(yaml@2.9.0)
'@remix-run/node':
specifier: 2.16.5
version: 2.16.5(typescript@7.0.2)
@@ -1067,6 +1070,9 @@ importers:
isbot:
specifier: ^5.1.25
version: 5.1.25
lightningcss:
specifier: 1.31.1
version: 1.31.1
react:
specifier: 18.3.0-canary-14898b6a9-20240318
version: 18.3.0-canary-14898b6a9-20240318
@@ -1076,12 +1082,18 @@ importers:
shiki:
specifier: 4.4.1
version: 4.4.1
vite:
specifier: 6.3.4
version: 6.3.4(@types/node@22.13.10)(jiti@2.4.2)(lightningcss@1.31.1)(tsx@4.19.3)(yaml@2.9.0)
webstudio:
specifier: workspace:*
version: link:../../packages/cli
worktop:
specifier: 0.8.0-next.18
version: 0.8.0-next.18
wrangler:
specifier: 4.130.0
version: 4.130.0(@cloudflare/workers-types@4.20240701.0)
zod:
specifier: ^4.4.3
version: 4.4.3
@@ -1089,9 +1101,6 @@ importers:
'@cloudflare/workers-types':
specifier: ^4.20240620.0
version: 4.20240701.0
'@remix-run/dev':
specifier: 2.16.5
version: 2.16.5(patch_hash=yortwzoeu3uj2blmdikhhw5byy)(@remix-run/react@2.16.5(react-dom@18.3.0-canary-14898b6a9-20240318(react@18.3.0-canary-14898b6a9-20240318))(react@18.3.0-canary-14898b6a9-20240318)(typescript@7.0.2))(@remix-run/serve@2.16.5(typescript@7.0.2))(@types/node@22.13.10)(jiti@2.4.2)(lightningcss@1.31.1)(tsx@4.19.3)(typescript@7.0.2)(vite@6.3.4(@types/node@22.13.10)(jiti@2.4.2)(lightningcss@1.31.1)(tsx@4.19.3)(yaml@2.9.0))(wrangler@4.130.0(@cloudflare/workers-types@4.20240701.0))(yaml@2.9.0)
'@types/react':
specifier: ^18.2.70
version: 18.2.79
@@ -1101,18 +1110,9 @@ importers:
fast-glob:
specifier: ^3.3.2
version: 3.3.2
lightningcss:
specifier: 1.31.1
version: 1.31.1
typescript:
specifier: 7.0.2
version: 7.0.2
vite:
specifier: 6.3.4
version: 6.3.4(@types/node@22.13.10)(jiti@2.4.2)(lightningcss@1.31.1)(tsx@4.19.3)(yaml@2.9.0)
wrangler:
specifier: 4.130.0
version: 4.130.0(@cloudflare/workers-types@4.20240701.0)
fixtures/webstudio-features:
dependencies: