mirror of
https://github.com/webstudio-is/webstudio.git
synced 2026-12-01 21:05:42 +09:00
Malformed saved CSS can stop a site from publishing. This restores Vite's stylesheet pipeline with Lightning CSS and lets publishing continue when generated CSS is invalid. ## What changed - Save validation uses the shared CSS parser for touched declarations and now rejects malformed style state selectors. The CSS editor already reports malformed pasted declarations and omits them from saved styles. - Publish skips older malformed declarations and warns without including their values. - Generated CSS is imported by Remix, React Router, and Vike, so Vite processes the stylesheet and emits its asset. - Before Vite runs, the CLI checks generated CSS with Lightning CSS and esbuild. If the stylesheet cannot build, it warns and uses preset and font CSS; if that also fails, it uses an empty stylesheet. - The domain publish check parses the current project CSS and shows a warning without blocking publish. The parser catches the malformed cases reproduced with Lightning CSS and esbuild; the CLI's compiler check remains the final guard. It skips malformed declarations just as the CLI does. The early check reads assets and generates and parses CSS once more per validation. Content Block styles created during publishing and static template publishing are covered by the CLI fallback, but not by this early warning. - The temporary hashed public stylesheet path and its larger fixture size allowances are removed. The direct PostCSS dependency remains removed. ## Checklist - [x] Restore Vite CSS imports with Lightning CSS in every site template. - [x] Keep malformed CSS from failing publish and warn when fallback CSS is used. - [x] Test the reported escaped property in React Router and Cloudflare Remix builds. - [x] Test malformed CSS recovery in React Router and Vike builds. - [x] Verify the prerendered Vike page links to the generated CSS asset. - [x] Regenerate fixtures and review the diff. - [x] Review documentation impact: the existing publishing guide needs no change for this warning in the publish flow. - [x] Run CLI typecheck, lint, formatting, package boundaries, CLI build, and frozen lockfile check. - [x] Confirm CSS compiler failure cases with focused tests. - [x] Validate CSS-affecting inputs at save, including style states that bypass the editor picker. - [x] Warn in domain pre-publish validation when current project CSS fails compiler checks. - [x] Verify pasted CSS diagnostics and save behavior in the editor. - [x] Review the new diff and rerun relevant tests, typechecks, and Builder build. - [x] Remove the Builder runtime's native Lightning CSS dependency and test the known compiler failure cases with CSS-tree. - [x] Verify staging Builder and CLI workflows for the latest commit. - [ ] Verify a site publish on staging with a project compatible with this branch. The first attempt used a project with a style source type this branch cannot read. - [x] Reject CSS-tree recoverable parse errors in declaration validation and add a regression test. - [x] Keep project-build within its existing package entrypoints and rerun the affected checks. - [x] Monitor required PR checks to completion. ## Verification Local: affected tests, four package typechecks, Builder and CLI builds, root lint, formatting, package boundaries, and frozen lockfile check passed. The fixture pipeline passed for the earlier commit; this commit changes no fixture inputs or outputs. The new invalid-declaration regression test failed when its filter was removed, then passed when restored. The incomplete `rgb()` parser test failed before the review fix and passed afterward. Full css-data and project-build test suites passed. The Builder runtime uses CSS-tree for the early warning because Vercel omitted Lightning CSS's native binary from the deployed function; the CLI still runs Lightning CSS and esbuild during publishing. The replacement staging deployment, fixture checks, both CLI R2 workflows, main workflow, and all required PR checks passed. Staging publish attempt: CLI sync stopped at `build.styleSources[520]` before CSS generation. This branch accepts only `token` and `local` sources; open PR #6663 adds `tagStyle` and the CSS generation it needs. The failing record could not be read directly with the available share token, so the exact saved type remains unconfirmed. Use a project without Tag styles, or test a combined integration branch after an explicit scope decision. Replaces #6662. --------- Co-authored-by: Codex <codex@users.noreply.github.com>
462 lines
12 KiB
TypeScript
462 lines
12 KiB
TypeScript
import {
|
|
AuthorizationError,
|
|
authorizeProject,
|
|
type AppContext,
|
|
} from "@webstudio-is/trpc-interface/index.server";
|
|
import {
|
|
serializeConfig,
|
|
serializeData,
|
|
serializeStyles,
|
|
serializeStyleSourceSelections,
|
|
writableStyles,
|
|
} from "@webstudio-is/project-build/persistence";
|
|
import {
|
|
createAssetFolderRows,
|
|
createAssetRows,
|
|
formatAsset,
|
|
getCollectionFolderIds,
|
|
chunkPostgrestFileNames,
|
|
validateCollectionFolder,
|
|
type AssetObjectReader,
|
|
} from "@webstudio-is/asset-uploader/server";
|
|
import { loadDevBuildByProjectId } from "@webstudio-is/project-build/server";
|
|
import {
|
|
hasHistoricalFormComponentIdentityVersion,
|
|
migratePages,
|
|
serializePages,
|
|
} from "@webstudio-is/project-migrations/pages";
|
|
import { migrateResourceFormInstancesMutable } from "@webstudio-is/project-migrations";
|
|
import {
|
|
createProjectSettingsFromPages,
|
|
removeLegacyProjectSettingsFromPages,
|
|
} from "@webstudio-is/project-build";
|
|
import {
|
|
isAssetFileName,
|
|
MissingImportedAssetFilesError,
|
|
getBundleVersionMismatchMessage,
|
|
bundleVersion,
|
|
type PublishedProjectBundle,
|
|
type ProjectBundle,
|
|
} from "@webstudio-is/protocol";
|
|
import {
|
|
createId,
|
|
getHomePage,
|
|
normalizeAssetFolderData,
|
|
assetFolders as assetFoldersSchema,
|
|
type Asset,
|
|
type AssetFolder,
|
|
type Breakpoint,
|
|
type DataSource,
|
|
type Instance,
|
|
type Prop,
|
|
type Resource,
|
|
type StyleSource,
|
|
} from "@webstudio-is/sdk";
|
|
import { createAssetClient } from "~/shared/asset-client";
|
|
|
|
const toMap = <Key extends string, Value>(entries: [Key, Value][]) =>
|
|
new Map<Key, Value>(entries);
|
|
|
|
const assertBundleVersion = (
|
|
data: Pick<PublishedProjectBundle, "bundleVersion">
|
|
) => {
|
|
if (data.bundleVersion !== bundleVersion) {
|
|
throw new Error(
|
|
getBundleVersionMismatchMessage({
|
|
ignoreVersionCheckHint:
|
|
"explicitly ignore the version check if you know the source and target data formats are compatible",
|
|
receivedVersion: data.bundleVersion,
|
|
})
|
|
);
|
|
}
|
|
};
|
|
|
|
export const assertProjectBuildPermit = async ({
|
|
ctx,
|
|
hasProjectPermit = authorizeProject.hasProjectPermit,
|
|
projectId,
|
|
}: {
|
|
ctx: AppContext;
|
|
hasProjectPermit?: typeof authorizeProject.hasProjectPermit;
|
|
projectId: string;
|
|
}) => {
|
|
const canBuild = await hasProjectPermit({ projectId, permit: "build" }, ctx);
|
|
if (canBuild === false) {
|
|
throw new AuthorizationError(
|
|
"You don't have permission to build this project."
|
|
);
|
|
}
|
|
};
|
|
|
|
const createBuildImportUpdate = ({
|
|
data,
|
|
lastTransactionId,
|
|
updatedAt,
|
|
version,
|
|
}: {
|
|
data: ProjectBundle;
|
|
lastTransactionId: string;
|
|
updatedAt: string;
|
|
version: number;
|
|
}) => {
|
|
const hasModernFormMarker = hasHistoricalFormComponentIdentityVersion(
|
|
data.build.pages
|
|
);
|
|
const pages = migratePages(data.build.pages);
|
|
const instances = toMap(
|
|
data.build.instances.map(([id, instance]) => [id, { ...instance }])
|
|
);
|
|
migrateResourceFormInstancesMutable(instances.values(), hasModernFormMarker);
|
|
const projectSettings =
|
|
data.build.projectSettings ?? createProjectSettingsFromPages(pages);
|
|
return {
|
|
version,
|
|
lastTransactionId,
|
|
updatedAt,
|
|
pages: JSON.stringify(
|
|
serializePages(removeLegacyProjectSettingsFromPages(pages))
|
|
),
|
|
projectSettings: serializeConfig(projectSettings),
|
|
...(data.build.marketplaceProduct === undefined
|
|
? {}
|
|
: {
|
|
marketplaceProduct: serializeConfig(data.build.marketplaceProduct),
|
|
}),
|
|
breakpoints: serializeData<Breakpoint>(toMap(data.build.breakpoints)),
|
|
styles: serializeStyles(writableStyles.parse(toMap(data.build.styles))),
|
|
styleSources: serializeData<StyleSource>(toMap(data.build.styleSources)),
|
|
styleSourceSelections: serializeStyleSourceSelections(
|
|
toMap(data.build.styleSourceSelections)
|
|
),
|
|
props: serializeData<Prop>(toMap(data.build.props)),
|
|
dataSources: serializeData<DataSource>(toMap(data.build.dataSources)),
|
|
resources: serializeData<Resource>(toMap(data.build.resources)),
|
|
instances: serializeData<Instance>(instances),
|
|
};
|
|
};
|
|
|
|
const getImportedPreviewImageAssetId = (data: ProjectBundle) => {
|
|
const socialImageAssetId = getHomePage(migratePages(data.build.pages)).meta
|
|
.socialImageAssetId;
|
|
if (socialImageAssetId === undefined) {
|
|
return null;
|
|
}
|
|
const importedAssetIds = new Set(data.assets.map((asset) => asset.id));
|
|
return importedAssetIds.has(socialImageAssetId) ? socialImageAssetId : null;
|
|
};
|
|
|
|
const assertImportedAssetNames = (assets: Asset[]) => {
|
|
const assetIds = new Set<string>();
|
|
|
|
for (const asset of assets) {
|
|
if (asset.id === "") {
|
|
throw new Error("Imported asset id is invalid.");
|
|
}
|
|
if (assetIds.has(asset.id)) {
|
|
throw new Error(`Imported asset id is duplicated: ${asset.id}`);
|
|
}
|
|
if (isAssetFileName(asset.name) === false) {
|
|
throw new Error(`Imported asset name is invalid: ${asset.name}`);
|
|
}
|
|
assetIds.add(asset.id);
|
|
}
|
|
};
|
|
|
|
const assertImportedAssets = (assets: Asset[]) => {
|
|
assertImportedAssetNames(assets);
|
|
};
|
|
|
|
const normalizeImportedAssetFolderData = (
|
|
folders: AssetFolder[],
|
|
assets: Asset[]
|
|
) => {
|
|
const folderMap = new Map(folders.map((folder) => [folder.id, folder]));
|
|
if (folderMap.size !== folders.length) {
|
|
throw new Error("Imported asset folder id is duplicated.");
|
|
}
|
|
const validatedFolders = assetFoldersSchema.parse(folderMap);
|
|
return normalizeAssetFolderData({
|
|
assets,
|
|
folders: Array.from(validatedFolders.values()),
|
|
});
|
|
};
|
|
|
|
const loadImportedAssetFiles = async ({
|
|
assets,
|
|
ctx,
|
|
projectId,
|
|
}: {
|
|
assets: Asset[];
|
|
ctx: AppContext;
|
|
projectId: string;
|
|
}) => {
|
|
if (assets.length === 0) {
|
|
return { assets, fileNames: new Set<string>() };
|
|
}
|
|
|
|
const filesByName = new Map<
|
|
string,
|
|
Parameters<typeof formatAsset>[0]["file"]
|
|
>();
|
|
for (const names of chunkPostgrestFileNames(
|
|
assets.map((asset) => asset.name)
|
|
)) {
|
|
const files = await ctx.postgrest.client
|
|
.from("File")
|
|
.select("name, format, description, size, createdAt, updatedAt, meta")
|
|
.eq("status", "UPLOADED")
|
|
.eq("uploaderProjectId", projectId)
|
|
.in("name", names);
|
|
if (files.error) {
|
|
throw files.error;
|
|
}
|
|
for (const file of files.data ?? []) {
|
|
filesByName.set(file.name, file);
|
|
}
|
|
}
|
|
const missingAssets = assets.filter(
|
|
(asset) => filesByName.has(asset.name) === false
|
|
);
|
|
if (missingAssets.length > 0) {
|
|
throw new MissingImportedAssetFilesError(
|
|
missingAssets.map((asset) => asset.name)
|
|
);
|
|
}
|
|
|
|
return {
|
|
assets: assets.map((asset) => {
|
|
const file = filesByName.get(asset.name);
|
|
if (file === undefined) {
|
|
throw new Error(`Imported asset file is missing: ${asset.name}`);
|
|
}
|
|
return formatAsset({
|
|
assetId: asset.id,
|
|
projectId,
|
|
filename: asset.filename ?? null,
|
|
description: asset.description ?? null,
|
|
folderId: asset.folderId,
|
|
file,
|
|
});
|
|
}),
|
|
fileNames: new Set(filesByName.keys()),
|
|
};
|
|
};
|
|
|
|
const restoreImportedAssetFiles = async ({
|
|
fileNames,
|
|
ctx,
|
|
projectId,
|
|
}: {
|
|
fileNames: ReadonlySet<string>;
|
|
ctx: AppContext;
|
|
projectId: string;
|
|
}) => {
|
|
if (fileNames.size === 0) {
|
|
return;
|
|
}
|
|
for (const names of chunkPostgrestFileNames(fileNames)) {
|
|
const visibleFiles = await ctx.postgrest.client
|
|
.from("File")
|
|
.update({ isDeleted: false })
|
|
.eq("uploaderProjectId", projectId)
|
|
.in("name", names);
|
|
if (visibleFiles.error) {
|
|
throw visibleFiles.error;
|
|
}
|
|
}
|
|
};
|
|
|
|
const validateImportedCollections = async ({
|
|
assets,
|
|
assetStore,
|
|
}: {
|
|
assets: readonly Asset[];
|
|
assetStore: AssetObjectReader;
|
|
}) => {
|
|
for (const folderId of getCollectionFolderIds(assets)) {
|
|
await validateCollectionFolder({ assets, folderId, assetStore });
|
|
}
|
|
};
|
|
|
|
const replaceProjectAssetRows = async ({
|
|
assets,
|
|
assetFolders,
|
|
ctx,
|
|
projectId,
|
|
}: {
|
|
assets: Asset[];
|
|
assetFolders: AssetFolder[];
|
|
ctx: AppContext;
|
|
projectId: string;
|
|
}) => {
|
|
const resetPreviewImage = await ctx.postgrest.client
|
|
.from("Project")
|
|
.update({ previewImageAssetId: null })
|
|
.eq("id", projectId);
|
|
if (resetPreviewImage.error) {
|
|
throw resetPreviewImage.error;
|
|
}
|
|
|
|
const deletedAssets = await ctx.postgrest.client
|
|
.from("Asset")
|
|
.delete()
|
|
.eq("projectId", projectId);
|
|
if (deletedAssets.error) {
|
|
throw deletedAssets.error;
|
|
}
|
|
|
|
const deletedFolders = await ctx.postgrest.client
|
|
.from("AssetFolder")
|
|
.delete()
|
|
.eq("projectId", projectId);
|
|
if (deletedFolders.error) {
|
|
throw deletedFolders.error;
|
|
}
|
|
|
|
if (assetFolders.length > 0) {
|
|
const insertedFolder = await ctx.postgrest.client
|
|
.from("AssetFolder")
|
|
.insert(createAssetFolderRows(assetFolders, projectId));
|
|
if (insertedFolder.error) {
|
|
throw insertedFolder.error;
|
|
}
|
|
}
|
|
|
|
if (assets.length === 0) {
|
|
return;
|
|
}
|
|
|
|
const insertedAssets = await ctx.postgrest.client
|
|
.from("Asset")
|
|
.insert(createAssetRows(assets, projectId));
|
|
if (insertedAssets.error) {
|
|
throw insertedAssets.error;
|
|
}
|
|
};
|
|
|
|
const updateProjectPreviewImage = async ({
|
|
assetId,
|
|
ctx,
|
|
projectId,
|
|
}: {
|
|
assetId: string | null;
|
|
ctx: AppContext;
|
|
projectId: string;
|
|
}) => {
|
|
const updatedProject = await ctx.postgrest.client
|
|
.from("Project")
|
|
.update({ previewImageAssetId: assetId })
|
|
.eq("id", projectId);
|
|
if (updatedProject.error) {
|
|
throw updatedProject.error;
|
|
}
|
|
};
|
|
|
|
export const importPublishedProjectBundle = async (
|
|
{
|
|
ctx,
|
|
data,
|
|
ignoreVersionCheck = false,
|
|
projectId,
|
|
}: {
|
|
ctx: AppContext;
|
|
data: PublishedProjectBundle;
|
|
ignoreVersionCheck?: boolean;
|
|
projectId: string;
|
|
},
|
|
dependencies: {
|
|
hasProjectPermit: typeof authorizeProject.hasProjectPermit;
|
|
loadDevBuildByProjectId: typeof loadDevBuildByProjectId;
|
|
assetStore?: AssetObjectReader;
|
|
} = {
|
|
hasProjectPermit: authorizeProject.hasProjectPermit,
|
|
loadDevBuildByProjectId,
|
|
}
|
|
) => {
|
|
if (ignoreVersionCheck === false) {
|
|
assertBundleVersion(data);
|
|
}
|
|
|
|
await assertProjectBuildPermit({
|
|
ctx,
|
|
hasProjectPermit: dependencies.hasProjectPermit,
|
|
projectId,
|
|
});
|
|
|
|
const build = await dependencies.loadDevBuildByProjectId(ctx, projectId);
|
|
const nextVersion = build.version + 1;
|
|
const buildUpdate = createBuildImportUpdate({
|
|
data,
|
|
lastTransactionId: createId(),
|
|
updatedAt: new Date().toISOString(),
|
|
version: nextVersion,
|
|
});
|
|
|
|
assertImportedAssets(data.assets);
|
|
const { assets: normalizedAssets, folders: importedAssetFolders } =
|
|
normalizeImportedAssetFolderData(data.assetFolders ?? [], data.assets);
|
|
|
|
const { assets: importedAssets, fileNames: importedFileNames } =
|
|
await loadImportedAssetFiles({
|
|
assets: normalizedAssets,
|
|
ctx,
|
|
projectId,
|
|
});
|
|
const collectionFolderIds = getCollectionFolderIds(importedAssets);
|
|
if (collectionFolderIds.size > 0) {
|
|
await validateImportedCollections({
|
|
assets: importedAssets,
|
|
assetStore: dependencies.assetStore ?? createAssetClient(),
|
|
});
|
|
}
|
|
const update = await ctx.postgrest.client
|
|
.from("Build")
|
|
.update(buildUpdate, { count: "exact" })
|
|
.match({
|
|
id: build.id,
|
|
projectId,
|
|
version: build.version,
|
|
});
|
|
|
|
if (update.error) {
|
|
throw update.error;
|
|
}
|
|
if (update.count !== 1) {
|
|
throw new Error("Unable to import project bundle because build changed.");
|
|
}
|
|
|
|
await replaceProjectAssetRows({
|
|
assets: importedAssets,
|
|
assetFolders: importedAssetFolders,
|
|
ctx,
|
|
projectId,
|
|
});
|
|
|
|
await restoreImportedAssetFiles({
|
|
fileNames: importedFileNames,
|
|
ctx,
|
|
projectId,
|
|
});
|
|
|
|
await updateProjectPreviewImage({
|
|
assetId: getImportedPreviewImageAssetId(data),
|
|
ctx,
|
|
projectId,
|
|
});
|
|
|
|
return { version: nextVersion };
|
|
};
|
|
|
|
export const __testing__ = {
|
|
assertProjectBuildPermit,
|
|
assertBundleVersion,
|
|
createBuildImportUpdate,
|
|
getImportedPreviewImageAssetId,
|
|
assertImportedAssetNames,
|
|
assertImportedAssets,
|
|
normalizeImportedAssetFolderData,
|
|
loadImportedAssetFiles,
|
|
restoreImportedAssetFiles,
|
|
validateImportedCollections,
|
|
};
|