diff --git a/apps/builder/app/builder/features/publish/domain-checkbox.test.ts b/apps/builder/app/builder/features/publish/domain-checkbox.test.tsx similarity index 51% rename from apps/builder/app/builder/features/publish/domain-checkbox.test.ts rename to apps/builder/app/builder/features/publish/domain-checkbox.test.tsx index 580217e8ca..ef2f30ee71 100644 --- a/apps/builder/app/builder/features/publish/domain-checkbox.test.ts +++ b/apps/builder/app/builder/features/publish/domain-checkbox.test.tsx @@ -1,8 +1,86 @@ -import { describe, test, expect } from "vitest"; +import { afterAll, afterEach, describe, test, expect } from "vitest"; +import { createRoot, type Root } from "react-dom/client"; +import { act } from "react-dom/test-utils"; +import { TooltipProvider } from "@webstudio-is/design-system"; +import type { Project } from "@webstudio-is/project"; +import { $project } from "~/shared/sync/data-stores"; +import { $authPermit, $planFeatures } from "~/shared/nano-states"; +import { DomainCheckbox, domainToPublishName } from "./domain-checkbox"; import { __testing__ } from "./domain-checkbox"; const { isCustomDomainPublishRestricted } = __testing__; +const initialPlan = $planFeatures.get(); +const initialAuthPermit = $authPermit.get(); +let root: Root | undefined; +let container: HTMLDivElement | undefined; + +const reactEnvironment = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }; +const originalActEnvironment = reactEnvironment.IS_REACT_ACT_ENVIRONMENT; +reactEnvironment.IS_REACT_ACT_ENVIRONMENT = true; + +afterAll(() => { + reactEnvironment.IS_REACT_ACT_ENVIRONMENT = originalActEnvironment; +}); + +afterEach(() => { + act(() => root?.unmount()); + root = undefined; + container?.remove(); + container = undefined; + $project.set(undefined); + $planFeatures.set(initialPlan); + $authPermit.set(initialAuthPermit); +}); + +const renderCheckbox = () => { + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + act(() => + root?.render( + +
+ + +
+ ) + ); + return { + checkbox: container.querySelector('[role="checkbox"]')!, + form: container.querySelector("form")!, + }; +}; + +test("removes a selected custom domain from the form when publishing becomes restricted", async () => { + $project.set({ + id: "project-1", + domainsVirtual: [ + { domain: "custom.example", status: "ACTIVE", verified: true }, + ], + } as Project); + $planFeatures.set({ ...initialPlan, allowStagingPublish: true }); + $authPermit.set("own"); + const { checkbox, form } = renderCheckbox(); + expect(checkbox).toBeEnabled(); + expect(checkbox.getAttribute("aria-checked")).toBe("true"); + expect(new FormData(form).getAll(domainToPublishName)).toEqual([ + "custom.example", + ]); + + await act(async () => $authPermit.set("build")); + const restrictedCheckbox = + form.querySelector('[role="checkbox"]')!; + expect(restrictedCheckbox).toBeDisabled(); + expect(restrictedCheckbox.getAttribute("aria-checked")).toBe("false"); + expect(new FormData(form).getAll(domainToPublishName)).toEqual([]); +}); + describe("isCustomDomainPublishRestricted", () => { describe("free plan (allowStagingPublish=false), no builder role", () => { test("custom domain → restricted", () => { diff --git a/apps/builder/app/builder/features/publish/publish-click.render.test.tsx b/apps/builder/app/builder/features/publish/publish-click.render.test.tsx index 15d522140e..041985c109 100644 --- a/apps/builder/app/builder/features/publish/publish-click.render.test.tsx +++ b/apps/builder/app/builder/features/publish/publish-click.render.test.tsx @@ -71,6 +71,14 @@ beforeAll(async () => { data: 0, limit: 100, }), + "api.publish.validate": () => ({ + diagnostics: { mdxErrors: [], mdxOmissions: [] }, + cssValid: true, + }), + "build.contentDatabasePublishDiagnostics": () => ({ + mdxErrors: [], + mdxOmissions: [], + }), }, (route, input) => requests.push({ path: `/trpc/${route}`, input: { "0": input } }) @@ -121,6 +129,23 @@ const mount = async (dialog: "publish" | "export" = "publish") => { ); }; +const selectStaticDestination = async () => { + const destination = document.body.querySelector( + 'button[role="combobox"]' + ); + expect(destination).not.toBeNull(); + await act(async () => { + destination?.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }) + ); + }); + const staticOption = Array.from( + document.body.querySelectorAll('[role="option"]') + ).find((option) => option.textContent?.trim() === "Static"); + expect(staticOption).toBeDefined(); + await act(async () => staticOption?.click()); +}; + test("a successful site runner finishes the current publish and retains its report", async () => { jobStatus = "success"; publishResponse = { @@ -154,6 +179,24 @@ test("a successful site runner finishes the current publish and retains its repo "/trpc/api.publish.getJob" ); expect(publish.disabled).toBe(false); + const seeLogs = Array.from( + document.body.querySelectorAll("button") + ).find((button) => button.textContent?.trim() === "See logs"); + expect(seeLogs).toBeDefined(); + expect(seeLogs?.parentElement?.textContent).toContain( + "Published successfully." + ); + await act(async () => seeLogs?.click()); + expect(builderStates.$publishDialog.get()).toBe("none"); + expect( + document.body.querySelector('[role="tab"][aria-selected="true"]') + ?.textContent + ).toBe("Publish"); + expect( + document.body.querySelector('[role="tabpanel"][data-state="active"]') + ?.textContent + ).toContain("Upgrade to Pro to view publish logs."); + await act(async () => builderStates.$publishDialog.set("publish")); const report = document.body.querySelector( 'button[aria-label^="Publish log:"]' )!; @@ -174,6 +217,107 @@ test("a successful site runner finishes the current publish and retains its repo ).toContain("Published"); }); +test("a successful static export links to its publish report until another export starts", async () => { + const { ExportContent } = await import("./publish-ui"); + const onOpenReport = vi.fn(); + const flow = { + isPublishing: false, + publishes: [ + { + buildId: "build-1", + target: "static" as const, + domains: [], + findings: [], + status: "success" as const, + staticName: "site.zip", + }, + ], + openStaticReport: onOpenReport, + exportStatic: () => {}, + } satisfies Parameters[0]["flow"]; + stores.$project.set({ + id: "project-1", + domain: "example", + domainsVirtual: [], + latestStaticBuild: { + buildId: "build-1", + updatedAt: new Date().toISOString(), + publishStatus: "PUBLISHED", + }, + } as unknown as Project); + const container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + await act(async () => + root?.render( + + + + ) + ); + await selectStaticDestination(); + const seeLogs = Array.from( + document.body.querySelectorAll("button") + ).find((button) => button.textContent?.trim() === "See logs"); + expect(seeLogs).toBeDefined(); + expect(seeLogs?.parentElement?.textContent).toContain("Downloaded"); + await act(async () => seeLogs?.click()); + expect(onOpenReport).toHaveBeenCalledWith("publish"); + await act(async () => + root?.render( + + + + ) + ); + expect( + Array.from( + document.body.querySelectorAll("button") + ).find((button) => button.textContent?.trim() === "See logs") + ).toBeUndefined(); + await act(async () => + root?.render( + + + + ) + ); + expect( + Array.from( + document.body.querySelectorAll("button") + ).find((button) => button.textContent?.trim() === "See logs") + ).toBeUndefined(); + await act(async () => + root?.render( + + + + ) + ); + expect( + Array.from( + document.body.querySelectorAll("button") + ).find((button) => button.textContent?.trim() === "See logs") + ).toBeUndefined(); +}); + afterEach(() => { act(() => { root?.unmount(); @@ -211,23 +355,7 @@ afterAll(() => { test("static export reaches the server without waiting for diagnostics", async () => { await mount("export"); - - const destination = document.body.querySelector( - 'button[role="combobox"]' - ); - expect(destination).not.toBeNull(); - await act(async () => { - destination?.dispatchEvent( - new KeyboardEvent("keydown", { key: "Enter", bubbles: true }) - ); - }); - const staticOption = Array.from( - document.body.querySelectorAll('[role="option"]') - ).find((option) => option.textContent?.trim() === "Static"); - expect(staticOption).toBeDefined(); - await act(async () => { - staticOption?.click(); - }); + await selectStaticDestination(); const buildButton = Array.from( document.body.querySelectorAll("button") ).find( diff --git a/apps/builder/app/builder/features/publish/publish-session.render.test.tsx b/apps/builder/app/builder/features/publish/publish-session.render.test.tsx index 8d4e3dc233..1f4fffffcc 100644 --- a/apps/builder/app/builder/features/publish/publish-session.render.test.tsx +++ b/apps/builder/app/builder/features/publish/publish-session.render.test.tsx @@ -121,6 +121,10 @@ beforeAll(async () => { mdxErrors: [], mdxOmissions: [], }), + "api.publish.validate": () => ({ + diagnostics: { mdxErrors: [], mdxOmissions: [] }, + cssValid: true, + }), }); interceptor.start(); PublishButton = (await import("./publish")).PublishButton; diff --git a/apps/builder/app/builder/features/publish/publish-test-utils.test.ts b/apps/builder/app/builder/features/publish/publish-test-utils.test.ts new file mode 100644 index 0000000000..a66e4171e4 --- /dev/null +++ b/apps/builder/app/builder/features/publish/publish-test-utils.test.ts @@ -0,0 +1,63 @@ +import { expect, test } from "vitest"; +import { createTrpcInterceptor } from "./publish-test-utils"; + +const requestUrl = "/trpc/api.publish.getJob?input=%7B%220%22%3Anull%7D"; + +test("reports an unexpected procedure instead of treating it as a network failure", async () => { + const interceptor = createTrpcInterceptor({}); + interceptor.start(); + try { + await expect(fetch(requestUrl)).rejects.toThrow(); + } finally { + expect(() => interceptor.stop()).toThrow("Unexpected request"); + } +}); + +test("preserves an HTTP error response from a procedure", async () => { + const interceptor = createTrpcInterceptor({ + "api.publish.getJob": () => + new Response(JSON.stringify({ error: { message: "Unavailable" } }), { + status: 503, + headers: { "Content-Type": "application/json" }, + }), + }); + interceptor.start(); + try { + const response = await fetch(requestUrl); + expect(response.status).toBe(503); + expect(await response.json()).toEqual({ + error: { message: "Unavailable" }, + }); + } finally { + interceptor.stop(); + } +}); + +test("rejects unsupported request methods", async () => { + const interceptor = createTrpcInterceptor({ + "api.publish.getJob": () => ({ status: "success" }), + }); + interceptor.start(); + try { + await fetch("/trpc/api.publish.getJob", { + method: "PUT", + body: JSON.stringify({ "0": null }), + }).catch(() => {}); + } finally { + expect(() => interceptor.stop()).toThrow("Unexpected request method"); + } +}); + +test("rejects an invalid tRPC batch envelope", async () => { + const interceptor = createTrpcInterceptor({ + "api.publish.getJob": () => ({ status: "success" }), + }); + interceptor.start(); + try { + await expect( + fetch("/trpc/api.publish.getJob?input=null") + ).rejects.toThrow(); + } finally { + expect(() => interceptor.stop()).toThrow("Unexpected request input"); + } +}); diff --git a/apps/builder/app/builder/features/publish/publish-test-utils.ts b/apps/builder/app/builder/features/publish/publish-test-utils.ts index 5bb3125465..ca331b80f1 100644 --- a/apps/builder/app/builder/features/publish/publish-test-utils.ts +++ b/apps/builder/app/builder/features/publish/publish-test-utils.ts @@ -26,33 +26,72 @@ export const createTrpcInterceptor = ( onRequest?: (route: string, input: unknown) => void ) => { const interceptor = new FetchInterceptor(); + const unexpectedRequests: string[] = []; interceptor.on("request", async ({ request, controller }) => { const url = new URL(request.url); if (url.origin !== location.origin || !url.pathname.startsWith("/trpc/")) { return; } + if (request.method !== "GET" && request.method !== "POST") { + const message = `Unexpected request method: ${request.method} ${url.pathname}`; + unexpectedRequests.push(message); + controller.errorWith(new Error(message)); + return; + } + let input: Record; try { - const input = JSON.parse( + const parsedInput: unknown = JSON.parse( request.method === "GET" ? (url.searchParams.get("input") ?? "{}") : await request.clone().text() ); - const routes = url.pathname.slice("/trpc/".length).split(","); + if ( + parsedInput === null || + typeof parsedInput !== "object" || + Array.isArray(parsedInput) + ) { + throw new Error("Invalid tRPC batch envelope"); + } + input = parsedInput as Record; + } catch (error) { + unexpectedRequests.push(`Unexpected request input: ${url.pathname}`); + controller.errorWith(error); + return; + } + const routes = url.pathname.slice("/trpc/".length).split(","); + const missingRoute = routes.find((route) => handlers[route] === undefined); + if (missingRoute !== undefined) { + const message = `Unexpected request: ${missingRoute}`; + unexpectedRequests.push(message); + controller.errorWith(new Error(message)); + return; + } + try { const results = await Promise.all( routes.map(async (route, index) => { - const handler = handlers[route]; - if (handler === undefined) { - throw new Error(`Unexpected request: ${route}`); - } const value = input[String(index)]; onRequest?.(route, value); - return { result: { data: await handler(value) } }; + return handlers[route](value); }) ); + const response = results.find((result) => result instanceof Response); + if (response !== undefined) { + if (results.length !== 1) { + const message = `Unexpected batched HTTP response: ${url.pathname}`; + unexpectedRequests.push(message); + controller.errorWith(new Error(message)); + return; + } + controller.respondWith(response); + return; + } controller.respondWith( - new Response(JSON.stringify(results), { - headers: { "Content-Type": "application/json" }, - }) + new Response( + JSON.stringify(results.map((data) => ({ result: { data } }))), + { + headers: { "Content-Type": "application/json" }, + } + ) ); } catch (error) { controller.errorWith(error); @@ -60,6 +99,11 @@ export const createTrpcInterceptor = ( }); return { start: () => interceptor.apply(), - stop: () => interceptor.dispose(), + stop: () => { + interceptor.dispose(); + if (unexpectedRequests.length > 0) { + throw new Error(unexpectedRequests.join("\n")); + } + }, }; }; diff --git a/apps/builder/app/builder/features/publish/publish-ui.tsx b/apps/builder/app/builder/features/publish/publish-ui.tsx index 791c104750..054e595ae1 100644 --- a/apps/builder/app/builder/features/publish/publish-ui.tsx +++ b/apps/builder/app/builder/features/publish/publish-ui.tsx @@ -128,6 +128,37 @@ type PublishUiState = { exportStatic: (templates: readonly Templates[]) => void; }; +type StaticPublishUiState = Pick< + PublishUiState, + | "isPublishing" + | "publishes" + | "staticFailureFinding" + | "openStaticReport" + | "exportStatic" +>; + +const PublishSuccessBanner = ({ + message, + onOpen, +}: { + message: string; + onOpen: () => void; +}) => ( + + + {message} + + + +); + type ChangeProjectDomainProps = { project: Project; refresh: () => Promise; @@ -473,7 +504,8 @@ const Publish = ({ const getForm = () => buttonRef.current?.closest("form"); const findings = flow.siteFindings; - const hasSessionPublish = publishes.some(({ target }) => target === "site"); + const latestSitePublish = publishes.find(({ target }) => target === "site"); + const hasSessionPublish = latestSitePublish !== undefined; return ( @@ -502,6 +534,11 @@ const Publish = ({ + ) : latestSitePublish?.status === "success" && !isPublishInProgress ? ( + onOpenReport(undefined, "publish")} + /> ) : ( { const { isPublishing, @@ -579,11 +616,7 @@ const PublishStatic = ({ project.latestStaticBuild == null ? { status: "LOADED" as const, statusContent: "Not published" } : getStaticPublishStatusDisplay(project.latestStaticBuild); - const latestPublish = publishes.find( - (item) => - item.target === "static" && - item.buildId === project.latestStaticBuild?.buildId - ); + const latestPublish = publishes.find((item) => item.target === "static"); const logStatus = staticFailureFinding !== undefined ? "FAILED" @@ -599,6 +632,15 @@ const PublishStatic = ({ return ( + {latestPublish?.status === "success" && + latestPublish.staticName !== undefined && + !isPublishInProgress && + staticFailureFinding === undefined && ( + onOpenReport("publish")} + /> + )} Object.keys(deployTargets).includes(value); -export const ExportContent = (props: { flow: PublishUiState }) => { +export const ExportContent = (props: { flow: StaticPublishUiState }) => { const npxCommand = "npx webstudio@latest"; const [deployTarget, setDeployTarget] = useState("docker"); diff --git a/apps/builder/app/shared/array-utils.test.ts b/apps/builder/app/shared/array-utils.node.test.ts similarity index 100% rename from apps/builder/app/shared/array-utils.test.ts rename to apps/builder/app/shared/array-utils.node.test.ts diff --git a/apps/builder/app/shared/collection-equality.test.ts b/apps/builder/app/shared/collection-equality.node.test.ts similarity index 100% rename from apps/builder/app/shared/collection-equality.test.ts rename to apps/builder/app/shared/collection-equality.node.test.ts diff --git a/apps/builder/app/shared/db/user.server.test.ts b/apps/builder/app/shared/db/user.server.test.ts index d749ac764a..6fb2f8f64c 100644 --- a/apps/builder/app/shared/db/user.server.test.ts +++ b/apps/builder/app/shared/db/user.server.test.ts @@ -38,7 +38,12 @@ const userRow = { describe("getUserById (msw)", () => { test("returns user when found", async () => { - server.use(db.get("User", () => json(userRow))); + server.use( + db.get("User", ({ request }) => { + expect(new URL(request.url).searchParams.get("id")).toBe("eq.user-1"); + return json(userRow); + }) + ); const result = await getUserById(createContext(), "user-1"); expect(result.id).toBe("user-1"); @@ -69,9 +74,17 @@ describe("createOrLoginWithDev (msw)", () => { let workspaceChecked = false; server.use( // User SELECT resolves successfully → existing user - db.get("User", () => json(userRow)), + db.get("User", ({ request }) => { + expect(new URL(request.url).searchParams.get("email")).toBe( + "eq.test@example.com" + ); + return json(userRow); + }), // Workspace check — has default workspace - db.get("Workspace", () => { + db.get("Workspace", ({ request }) => { + const filters = new URL(request.url).searchParams; + expect(filters.get("userId")).toBe("eq.user-1"); + expect(filters.get("isDefault")).toBe("eq.true"); workspaceChecked = true; return json({ id: "ws-1" }); }) @@ -91,7 +104,12 @@ describe("createOrLoginWithDev (msw)", () => { db.get("User", () => json(userRow)), // maybeSingle returns null when no row exists db.get("Workspace", () => json(null)), - db.post("Workspace", () => { + db.post("Workspace", async ({ request }) => { + expect(await request.json()).toEqual({ + name: "My workspace", + isDefault: true, + userId: "user-1", + }); workspaceCreated = true; return json({ id: "ws-new" }, { status: 201 }); }) @@ -106,21 +124,36 @@ describe("createOrLoginWithDev (msw)", () => { }); test("creates new user and workspace when email not found", async () => { - let userInserted = false; + let insertedUserId: string | undefined; let workspaceInserted = false; server.use( // User SELECT → PGRST116 (not found) - db.get("User", () => - json( + db.get("User", ({ request }) => { + expect(new URL(request.url).searchParams.get("email")).toBe( + "eq.new@example.com" + ); + return json( { code: "PGRST116", message: "Row not found", details: "", hint: "" }, { status: 406 } - ) - ), - db.post("User", () => { - userInserted = true; - return json({ ...userRow, id: "new-user" }, { status: 201 }); + ); }), - db.post("Workspace", () => { + db.post("User", async ({ request }) => { + const body = (await request.json()) as Record; + expect(body).toMatchObject({ + email: "new@example.com", + username: "admin", + provider: "dev", + }); + expect(body.id).toEqual(expect.any(String)); + insertedUserId = body.id as string; + return json({ ...userRow, ...body }, { status: 201 }); + }), + db.post("Workspace", async ({ request }) => { + expect(await request.json()).toEqual({ + name: "My workspace", + isDefault: true, + userId: insertedUserId, + }); workspaceInserted = true; return json({ id: "ws-new" }, { status: 201 }); }) @@ -131,8 +164,8 @@ describe("createOrLoginWithDev (msw)", () => { "new@example.com" ); - expect(result.email).toBe("test@example.com"); // from userRow mock - expect(userInserted).toBe(true); + expect(result.email).toBe("new@example.com"); + expect(insertedUserId).toBeDefined(); expect(workspaceInserted).toBe(true); }); @@ -167,6 +200,7 @@ describe("createOrLoginWithOAuth (msw)", () => { server.use( db.get("User", () => json(userRow)), db.patch("User", async ({ request }) => { + expect(new URL(request.url).searchParams.get("id")).toBe("eq.user-1"); capturedBody = await request.json(); return json(updatedUser); }), @@ -196,9 +230,11 @@ describe("updateUserProjectsTags (msw)", () => { test("returns updated tags", async () => { server.use( - db.patch("User", () => - json({ ...userRow, projectsTags: tags }, { status: 200 }) - ) + db.patch("User", async ({ request }) => { + expect(new URL(request.url).searchParams.get("id")).toBe("eq.user-1"); + expect(await request.json()).toEqual({ projectsTags: tags }); + return json({ ...userRow, projectsTags: tags }, { status: 200 }); + }) ); const result = await updateUserProjectsTags({ tags }, createContext()); diff --git a/apps/builder/app/shared/permissions.test.ts b/apps/builder/app/shared/permissions.node.test.ts similarity index 97% rename from apps/builder/app/shared/permissions.test.ts rename to apps/builder/app/shared/permissions.node.test.ts index aa227dbcde..d5cb8dbe09 100644 --- a/apps/builder/app/shared/permissions.test.ts +++ b/apps/builder/app/shared/permissions.node.test.ts @@ -599,16 +599,6 @@ describe("getPermissions", () => { }).maxDomainsAllowedPerUser ).toBe(100); }); - - test("free plan has 0", () => { - expect( - getPermissions({ - role: "own", - planFeatures: freePlan, - workspaces: [], - }).maxDomainsAllowedPerUser - ).toBe(0); - }); }); describe("maxDailyPublishesPerUser", () => { @@ -631,16 +621,6 @@ describe("getPermissions", () => { }).maxDailyPublishesPerUser ).toBe(100); }); - - test("free plan allows limited publishes", () => { - expect( - getPermissions({ - role: "own", - planFeatures: freePlan, - workspaces: [], - }).maxDailyPublishesPerUser - ).toBe(10); - }); }); describe("canInviteMembers", () => { diff --git a/apps/builder/app/shared/sync/patch/patch-service.server.test.ts b/apps/builder/app/shared/sync/patch/patch-service.server.test.ts index 74fdcb6719..17e909fb70 100644 --- a/apps/builder/app/shared/sync/patch/patch-service.server.test.ts +++ b/apps/builder/app/shared/sync/patch/patch-service.server.test.ts @@ -24,11 +24,6 @@ import type { AppContext } from "@webstudio-is/trpc-interface/index.server"; import * as assetUploader from "@webstudio-is/asset-uploader/server"; import type { NormalizedPatchRequest } from "./patch-normalize.server"; -const applyPatchRequestForTest = ( - context: AppContext, - patch: NormalizedPatchRequest -) => applyPatchRequest(context, patch); - const configuredResources = JSON.stringify([ { id: "posts", @@ -60,33 +55,42 @@ const createContext = () => { const context = { postgrest: { client: { - from: () => ({ - select: (columns: string) => ({ - selectedColumns, - eq: () => { - selectedColumns.push(columns); - const result = Promise.resolve({ - data: [ - Object.fromEntries( - columns - .split(", ") - .map((column) => [ - column, - buildRow[column as keyof typeof buildRow], - ]) - ), - ], - error: undefined, - }); - return Object.assign(result, { - single: async () => ({ - data: buildRow, + from: (table: string) => { + if (table !== "Build") { + throw new Error(`Unexpected table: ${table}`); + } + return { + select: (columns: string) => ({ + eq: (column: string, value: string) => { + if (column !== "id" || value !== "build-1") { + throw new Error( + `Unexpected Build filter: ${column}=${value}` + ); + } + selectedColumns.push(columns); + const result = Promise.resolve({ + data: [ + Object.fromEntries( + columns + .split(", ") + .map((column) => [ + column, + buildRow[column as keyof typeof buildRow], + ]) + ), + ], error: undefined, - }), - }); - }, - }), - }), + }); + return Object.assign(result, { + single: async () => ({ + data: buildRow, + error: undefined, + }), + }); + }, + }), + }; + }, }, }, }; @@ -143,7 +147,7 @@ describe("applyPatchRequest", () => { }); const context = createContext(); await expect( - applyPatchRequestForTest(context, { ...patch, entries: [entry] }) + applyPatchRequest(context, { ...patch, entries: [entry] }) ).resolves.toMatchObject({ status: "ok" }); const columns = context.selectedColumns.at(-1)?.split(", "); expect(columns).toEqual(expect.arrayContaining(["instances", "props"])); @@ -152,7 +156,7 @@ describe("applyPatchRequest", () => { } ); - test("applies a combined resource and asset patch without derived work", async () => { + test("forwards a combined resource and asset patch", async () => { const combinedEntry = { ...patch.entries[0], transaction: { @@ -192,13 +196,30 @@ describe("applyPatchRequest", () => { version: 4, build: { ...build, version: 4, resources: nextResources }, })); - await applyPatchRequestForTest(createContext(), { + const context = createContext(); + const result = await applyPatchRequest(context, { ...patch, entries: [combinedEntry], }); + expect(context.selectedColumns).toEqual([ + "projectId, version", + "projectId, version, lastTransactionId, resources, props, instances", + ]); + expect(patchLoadedBuild).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + transactions: [combinedEntry.transaction], + build: expect.objectContaining({ resources: configuredResources }), + }), + { writer: 1 } + ); + expect(result).toEqual({ + status: "ok", + version: 4, + entries: [{ seq: 1, transactionId: "tx-combined", status: "accepted" }], + }); }); - test("applies asset-folder patches without derived work", async () => { + test("forwards asset-folder patches", async () => { const folderEntry = { ...patch.entries[0], transaction: { @@ -223,15 +244,22 @@ describe("applyPatchRequest", () => { build: { ...build, version: 4 }, })); - await expect( - applyPatchRequestForTest(createContext(), { - ...patch, - entries: [folderEntry], - }) - ).resolves.toMatchObject({ status: "ok" }); + const result = await applyPatchRequest(createContext(), { + ...patch, + entries: [folderEntry], + }); + expect(patchLoadedBuild).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ transactions: [folderEntry.transaction] }), + { writer: 1 } + ); + expect(result).toEqual({ + status: "ok", + version: 4, + entries: [{ seq: 1, transactionId: "tx-folder", status: "accepted" }], + }); }); - test("applies added assets without derived work", async () => { + test("forwards added assets", async () => { const assetEntry = { ...patch.entries[0], transaction: { @@ -260,15 +288,22 @@ describe("applyPatchRequest", () => { build: { ...build, version: 4 }, })); - await expect( - applyPatchRequestForTest(createContext(), { - ...patch, - entries: [assetEntry], - }) - ).resolves.toMatchObject({ status: "ok" }); + const result = await applyPatchRequest(createContext(), { + ...patch, + entries: [assetEntry], + }); + expect(patchLoadedBuild).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ transactions: [assetEntry.transaction] }), + { writer: 1 } + ); + expect(result).toEqual({ + status: "ok", + version: 4, + entries: [{ seq: 1, transactionId: "tx-asset-add", status: "accepted" }], + }); }); - test("applies a swapped asset revision without derived work", async () => { + test("forwards a swapped asset revision", async () => { const assetEntry = { ...patch.entries[0], transaction: { @@ -297,13 +332,24 @@ describe("applyPatchRequest", () => { build: { ...build, version: 4 }, })); - await applyPatchRequestForTest(createContext(), { + const result = await applyPatchRequest(createContext(), { ...patch, entries: [assetEntry], }); + expect(patchLoadedBuild).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ transactions: [assetEntry.transaction] }), + { writer: 1 } + ); + expect(result).toEqual({ + status: "ok", + version: 4, + entries: [ + { seq: 1, transactionId: "tx-asset-revision", status: "accepted" }, + ], + }); }); - test("applies standard asset metadata changes without derived work", async () => { + test("forwards standard asset metadata changes", async () => { const assetEntry = { ...patch.entries[0], transaction: { @@ -332,13 +378,24 @@ describe("applyPatchRequest", () => { build: { ...build, version: 4 }, })); - await applyPatchRequestForTest(createContext(), { + const result = await applyPatchRequest(createContext(), { ...patch, entries: [assetEntry], }); + expect(patchLoadedBuild).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ transactions: [assetEntry.transaction] }), + { writer: 1 } + ); + expect(result).toEqual({ + status: "ok", + version: 4, + entries: [ + { seq: 1, transactionId: "tx-asset-filename", status: "accepted" }, + ], + }); }); - test("applies asset descriptions without derived work", async () => { + test("forwards asset descriptions", async () => { const assetEntry = { ...patch.entries[0], transaction: { @@ -367,10 +424,21 @@ describe("applyPatchRequest", () => { build: { ...build, version: 4 }, })); - await applyPatchRequestForTest(createContext(), { + const result = await applyPatchRequest(createContext(), { ...patch, entries: [assetEntry], }); + expect(patchLoadedBuild).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ transactions: [assetEntry.transaction] }), + { writer: 1 } + ); + expect(result).toEqual({ + status: "ok", + version: 4, + entries: [ + { seq: 1, transactionId: "tx-asset-description", status: "accepted" }, + ], + }); }); test("returns per-entry partial results while applying authorized entries", async () => { @@ -391,7 +459,7 @@ describe("applyPatchRequest", () => { const context = createContext(); - const result = await applyPatchRequestForTest(context, patch); + const result = await applyPatchRequest(context, patch); expect(createContentModeCapabilities).not.toHaveBeenCalled(); expect(context.selectedColumns).toEqual([ @@ -442,7 +510,7 @@ describe("applyPatchRequest", () => { })); const context = createContext(); - const result = await applyPatchRequestForTest(context, patch); + const result = await applyPatchRequest(context, patch); expect(createContentModeCapabilities).toHaveBeenCalledWith({ breakpoints: JSON.stringify([]), @@ -491,12 +559,12 @@ describe("applyPatchRequest", () => { ); try { - await applyPatchRequestForTest(createContext(), folderPatch); + await applyPatchRequest(createContext(), folderPatch); expect(loadFolders).toHaveBeenCalledTimes(1); expect(loadFolders).toHaveBeenCalledWith("project-1", expect.anything(), { skipPermissionsCheck: true, }); - await applyPatchRequestForTest(createContext(), patch); + await applyPatchRequest(createContext(), patch); expect(loadFolders).toHaveBeenCalledTimes(1); } finally { loadFolders.mockRestore(); @@ -515,7 +583,7 @@ describe("applyPatchRequest", () => { }); const context = createContext(); - const result = await applyPatchRequestForTest(context, patch); + const result = await applyPatchRequest(context, patch); expect(context.selectedColumns).toEqual(["projectId, version"]); expect(patchLoadedBuild).not.toHaveBeenCalled(); @@ -555,7 +623,7 @@ describe("applyPatchRequest", () => { })); const context = createContext(); - const result = await applyPatchRequestForTest(context, assetsPatch); + const result = await applyPatchRequest(context, assetsPatch); expect(context.selectedColumns).toEqual([ "projectId, version", @@ -597,7 +665,7 @@ describe("applyPatchRequest", () => { })) .mockResolvedValueOnce({ status: "error", errors: "entry failed" }); - const result = await applyPatchRequestForTest(createContext(), patch); + const result = await applyPatchRequest(createContext(), patch); expect(result).toEqual({ status: "partial", @@ -627,7 +695,7 @@ describe("applyPatchRequest", () => { errors: "first save failed", }); - const result = await applyPatchRequestForTest(createContext(), patch); + const result = await applyPatchRequest(createContext(), patch); expect(patchLoadedBuild).toHaveBeenCalledTimes(1); expect(result).toEqual({ @@ -670,7 +738,7 @@ describe("applyPatchRequest", () => { build: { ...build, version: 5 }, })); - const result = await applyPatchRequestForTest(createContext(), patch); + const result = await applyPatchRequest(createContext(), patch); expect(patchLoadedBuild).toHaveBeenCalledTimes(2); expect(patchLoadedBuild).toHaveBeenNthCalledWith( @@ -734,10 +802,7 @@ describe("applyPatchRequest", () => { build: { ...build, version: 4 }, })); - const result = await applyPatchRequestForTest( - createContext(), - duplicatePatch - ); + const result = await applyPatchRequest(createContext(), duplicatePatch); expect(result).toEqual({ status: "partial", @@ -772,9 +837,9 @@ describe("applyPatchRequest", () => { })) .mockRejectedValueOnce(new Error("PostgREST unavailable")); - await expect( - applyPatchRequestForTest(createContext(), patch) - ).rejects.toThrow("PostgREST unavailable"); + await expect(applyPatchRequest(createContext(), patch)).rejects.toThrow( + "PostgREST unavailable" + ); }); }); diff --git a/docs/university/foundations/publishing-and-custom-domains.md b/docs/university/foundations/publishing-and-custom-domains.md index d6c0d3cc9a..35f738582b 100644 --- a/docs/university/foundations/publishing-and-custom-domains.md +++ b/docs/university/foundations/publishing-and-custom-domains.md @@ -33,6 +33,8 @@ When validation passes with no issues, the popover says it is ready to publish. If publishing fails, the popover shows the failure and a **See issues** button. It opens **Publish** for a publish that started, or **Errors** if the request failed before a publish started. +After a successful publish, choose **See logs** in the success notice to open +the **Publish** tab. Free plans can open the tab but cannot view its logs. Click the status icon beside a domain to open the same dialog on the **Publish** tab for that domain. For a static export, click its status icon. If a static export fails before a build starts, open its status icon to see the diff --git a/docs/university/self-hosting/download.md b/docs/university/self-hosting/download.md index aa91bf50ef..26ef765831 100644 --- a/docs/university/self-hosting/download.md +++ b/docs/university/self-hosting/download.md @@ -30,6 +30,9 @@ See [export types](./#export-types) for more information about JavaScript applic 5. Wait while Webstudio builds and downloads the project. +After the download succeeds, choose **See logs** in the success notice to open +the **Publish** tab. Free plans can open the tab but cannot view its logs. + The export contains a static site consisting of HTML, CSS, JS, and images ready to be uploaded to another platform. To check an export, open **Publish**, choose **Export**, and click the status