mirror of
https://github.com/webstudio-is/webstudio.git
synced 2026-12-01 21:05:42 +09:00
test: Cover Builder tRPC request workflows (#6720)
Builder features that use tRPC need request-level coverage beyond publishing. This PR shares the publish request interceptor and uses it to test uncovered UI flows across the HTTP boundary. It only changes test support and tests; product behavior and API contracts stay unchanged. ## Todos - [x] Move the tRPC interceptor into shared Builder test support and update its publish tests. - [x] Replace the JSX paste test’s tRPC client mock with an intercepted request. - [x] Test workspace member invitations for success and server rejection. - [x] Test accepting and declining notifications. - [x] Test backup loading and both successful and failed restores. - [x] Make the shared interceptor reject invalid batch requests, enforce each request's method, and reject unregistered routes. - [x] Review Builder docs; the existing dashboard guide already describes invitations, and these test-only changes need no doc update. - [x] Run focused browser tests, Builder typecheck, lint, and formatting checks. - [x] Wait for CI on the latest commit. ## Verification - Publish browser tests: 19 files, 199 tests passed. - Shared tRPC, notifications, and backups: 3 files, 12 tests passed. - JSX paste request tests: 1 file, 6 tests passed. - Workspace member request tests: 1 file, 2 tests passed. - New regression tests failed against the previous implementation and passed with the fix. - Builder typecheck, changed-file lint, formatting, diff checks, and CI passed. Ref #6719
This commit is contained in:
1 parent
0fc5744719
commit
fc5b7e140e
14 files changed
+927
-379
No files matched your search
@@ -13,9 +13,9 @@ import { TooltipProvider, toast } from "@webstudio-is/design-system";
|
||||
import type { Project } from "@webstudio-is/project";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import type { Instance } from "@webstudio-is/sdk";
|
||||
import { createTrpcInterceptor } from "~/shared/trpc/trpc-test-utils";
|
||||
import {
|
||||
createPublishAuditFinding,
|
||||
createTrpcInterceptor,
|
||||
selectStaticDestination,
|
||||
selectTab,
|
||||
} from "./publish-test-utils";
|
||||
@@ -46,46 +46,50 @@ beforeAll(async () => {
|
||||
vi.resetModules();
|
||||
interceptor = createTrpcInterceptor(
|
||||
{
|
||||
"domain.publish": () => {
|
||||
didPublish = (publishResponse as { success: boolean }).success;
|
||||
return publishResponse;
|
||||
POST: {
|
||||
"domain.publish": () => {
|
||||
didPublish = (publishResponse as { success: boolean }).success;
|
||||
return publishResponse;
|
||||
},
|
||||
},
|
||||
"api.publish.getJob": () => {
|
||||
return { status: jobStatus, code: "BUILD_FAILED" };
|
||||
},
|
||||
"domain.project": () => {
|
||||
return {
|
||||
GET: {
|
||||
"api.publish.getJob": () => {
|
||||
return { status: jobStatus, code: "BUILD_FAILED" };
|
||||
},
|
||||
"domain.project": () => {
|
||||
return {
|
||||
success: true,
|
||||
project: {
|
||||
id: "project-1",
|
||||
domain: "example",
|
||||
domainsVirtual: [],
|
||||
latestBuildVirtual: didPublish
|
||||
? {
|
||||
domain: "example",
|
||||
buildId: "build-1",
|
||||
createdAt: new Date().toISOString(),
|
||||
publishStatus:
|
||||
jobStatus === "success" ? "PUBLISHED" : "FAILED",
|
||||
}
|
||||
: null,
|
||||
},
|
||||
};
|
||||
},
|
||||
"domain.countTotalDomains": () => ({ success: true, data: 0 }),
|
||||
"project.userPublishCount": () => ({
|
||||
success: true,
|
||||
project: {
|
||||
id: "project-1",
|
||||
domain: "example",
|
||||
domainsVirtual: [],
|
||||
latestBuildVirtual: didPublish
|
||||
? {
|
||||
domain: "example",
|
||||
buildId: "build-1",
|
||||
createdAt: new Date().toISOString(),
|
||||
publishStatus:
|
||||
jobStatus === "success" ? "PUBLISHED" : "FAILED",
|
||||
}
|
||||
: null,
|
||||
},
|
||||
};
|
||||
data: 0,
|
||||
limit: 100,
|
||||
}),
|
||||
"api.publish.validate": () => ({
|
||||
diagnostics: { mdxErrors: [], mdxOmissions: [] },
|
||||
cssValid: true,
|
||||
}),
|
||||
"build.contentDatabasePublishDiagnostics": () => ({
|
||||
mdxErrors: [],
|
||||
mdxOmissions: [],
|
||||
}),
|
||||
},
|
||||
"domain.countTotalDomains": () => ({ success: true, data: 0 }),
|
||||
"project.userPublishCount": () => ({
|
||||
success: true,
|
||||
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 } })
|
||||
|
||||
@@ -14,9 +14,9 @@ import { TooltipProvider, toast } from "@webstudio-is/design-system";
|
||||
import { createAssetContentSession } from "@webstudio-is/content-engine/asset-content-session";
|
||||
import type { Project } from "@webstudio-is/project";
|
||||
import type { Pages } from "@webstudio-is/sdk";
|
||||
import { createTrpcInterceptor } from "~/shared/trpc/trpc-test-utils";
|
||||
import {
|
||||
createPublishAuditFinding,
|
||||
createTrpcInterceptor,
|
||||
deferred,
|
||||
selectTab,
|
||||
} from "./publish-test-utils";
|
||||
@@ -42,54 +42,58 @@ beforeAll(async () => {
|
||||
).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
vi.resetModules();
|
||||
interceptor = createTrpcInterceptor({
|
||||
"domain.publish": () => {
|
||||
publishRequests += 1;
|
||||
return dispatch.promise;
|
||||
},
|
||||
"api.publish.getJob": () => ({
|
||||
status: "failed",
|
||||
code: "BUILD_FAILED",
|
||||
}),
|
||||
"api.publish.getLog": () => ({
|
||||
availability: "available",
|
||||
log: {
|
||||
encoding: "base64url",
|
||||
chunk: btoa("older publish output"),
|
||||
complete: true,
|
||||
issues: [{ severity: "error", message: "older build issue" }],
|
||||
POST: {
|
||||
"domain.publish": () => {
|
||||
publishRequests += 1;
|
||||
return dispatch.promise;
|
||||
},
|
||||
}),
|
||||
"domain.project": () => ({
|
||||
success: true,
|
||||
project: stores.$project.get(),
|
||||
}),
|
||||
"domain.countTotalDomains": () => ({ success: true, data: 0 }),
|
||||
"project.userPublishCount": () => ({
|
||||
success: true,
|
||||
data: 0,
|
||||
limit: 100,
|
||||
}),
|
||||
"api.publish.validate": async () => {
|
||||
checkRequests += 1;
|
||||
try {
|
||||
const result = await checks.promise;
|
||||
checksRead += 1;
|
||||
return result;
|
||||
} catch (error) {
|
||||
checksRead += 1;
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
"build.contentDatabasePublishDiagnostics": async () => {
|
||||
checkRequests += 1;
|
||||
try {
|
||||
const result = await checks.promise;
|
||||
checksRead += 1;
|
||||
return result;
|
||||
} catch (error) {
|
||||
checksRead += 1;
|
||||
throw error;
|
||||
}
|
||||
GET: {
|
||||
"api.publish.getJob": () => ({
|
||||
status: "failed",
|
||||
code: "BUILD_FAILED",
|
||||
}),
|
||||
"api.publish.getLog": () => ({
|
||||
availability: "available",
|
||||
log: {
|
||||
encoding: "base64url",
|
||||
chunk: btoa("older publish output"),
|
||||
complete: true,
|
||||
issues: [{ severity: "error", message: "older build issue" }],
|
||||
},
|
||||
}),
|
||||
"domain.project": () => ({
|
||||
success: true,
|
||||
project: stores.$project.get(),
|
||||
}),
|
||||
"domain.countTotalDomains": () => ({ success: true, data: 0 }),
|
||||
"project.userPublishCount": () => ({
|
||||
success: true,
|
||||
data: 0,
|
||||
limit: 100,
|
||||
}),
|
||||
"api.publish.validate": async () => {
|
||||
checkRequests += 1;
|
||||
try {
|
||||
const result = await checks.promise;
|
||||
checksRead += 1;
|
||||
return result;
|
||||
} catch (error) {
|
||||
checksRead += 1;
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
"build.contentDatabasePublishDiagnostics": async () => {
|
||||
checkRequests += 1;
|
||||
try {
|
||||
const result = await checks.promise;
|
||||
checksRead += 1;
|
||||
return result;
|
||||
} catch (error) {
|
||||
checksRead += 1;
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
||||
interceptor.start();
|
||||
|
||||
@@ -13,9 +13,9 @@ import {
|
||||
import { TooltipProvider, toast } from "@webstudio-is/design-system";
|
||||
import type { Project } from "@webstudio-is/project";
|
||||
import { createAssetContentSession } from "@webstudio-is/content-engine/asset-content-session";
|
||||
import { createTrpcInterceptor } from "~/shared/trpc/trpc-test-utils";
|
||||
import {
|
||||
createPublishAuditFinding,
|
||||
createTrpcInterceptor,
|
||||
deferred,
|
||||
selectTab,
|
||||
} from "./publish-test-utils";
|
||||
@@ -68,20 +68,22 @@ beforeAll(async () => {
|
||||
vi.resetModules();
|
||||
interceptor = createTrpcInterceptor(
|
||||
{
|
||||
"domain.project": () => refresh(),
|
||||
"domain.publish": () => publish(),
|
||||
"api.publish.validate": () => validate(),
|
||||
"build.contentDatabasePublishDiagnostics": () => validate(),
|
||||
"api.publish.getJob": () => job(),
|
||||
"domain.countTotalDomains": () => ({
|
||||
success: true,
|
||||
data: 0,
|
||||
}),
|
||||
"project.userPublishCount": () => ({
|
||||
success: true,
|
||||
data: 0,
|
||||
limit: 100,
|
||||
}),
|
||||
POST: { "domain.publish": () => publish() },
|
||||
GET: {
|
||||
"domain.project": () => refresh(),
|
||||
"api.publish.validate": () => validate(),
|
||||
"build.contentDatabasePublishDiagnostics": () => validate(),
|
||||
"api.publish.getJob": () => job(),
|
||||
"domain.countTotalDomains": () => ({
|
||||
success: true,
|
||||
data: 0,
|
||||
}),
|
||||
"project.userPublishCount": () => ({
|
||||
success: true,
|
||||
data: 0,
|
||||
limit: 100,
|
||||
}),
|
||||
},
|
||||
},
|
||||
(route, input) => requests.push({ route, input })
|
||||
);
|
||||
|
||||
@@ -11,11 +11,8 @@ import {
|
||||
} from "vitest";
|
||||
import { TooltipProvider } from "@webstudio-is/design-system";
|
||||
import type { Project } from "@webstudio-is/project";
|
||||
import {
|
||||
createTrpcInterceptor,
|
||||
deferred,
|
||||
selectTab,
|
||||
} from "./publish-test-utils";
|
||||
import { createTrpcInterceptor } from "~/shared/trpc/trpc-test-utils";
|
||||
import { deferred, selectTab } from "./publish-test-utils";
|
||||
|
||||
const encoded = (bytes: number[]) => btoa(String.fromCharCode(...bytes));
|
||||
const logRequests: Array<{
|
||||
@@ -56,85 +53,89 @@ beforeAll(async () => {
|
||||
});
|
||||
vi.resetModules();
|
||||
interceptor = createTrpcInterceptor({
|
||||
"domain.project": () => ({
|
||||
success: true,
|
||||
project: {
|
||||
...stores.$project.get(),
|
||||
latestBuildVirtual: {
|
||||
domain: "example",
|
||||
buildId: acceptedBuildId,
|
||||
createdAt: new Date().toISOString(),
|
||||
publishStatus: "PUBLISHED",
|
||||
},
|
||||
POST: {
|
||||
"domain.publish": async () => {
|
||||
publishRequests += 1;
|
||||
const data = heldPublish
|
||||
? await heldPublish.promise
|
||||
: {
|
||||
success: true,
|
||||
buildId,
|
||||
...(withHandle ? { logHandle: "handle" } : {}),
|
||||
findings: [],
|
||||
};
|
||||
acceptedBuildId = (data as { buildId: string }).buildId;
|
||||
return data;
|
||||
},
|
||||
}),
|
||||
"domain.countTotalDomains": () => ({ success: true, data: 0 }),
|
||||
"project.userPublishCount": () => ({
|
||||
success: true,
|
||||
data: 0,
|
||||
limit: 100,
|
||||
}),
|
||||
"domain.publish": async () => {
|
||||
publishRequests += 1;
|
||||
const data = heldPublish
|
||||
? await heldPublish.promise
|
||||
: {
|
||||
success: true,
|
||||
buildId,
|
||||
...(withHandle ? { logHandle: "handle" } : {}),
|
||||
findings: [],
|
||||
};
|
||||
acceptedBuildId = (data as { buildId: string }).buildId;
|
||||
return data;
|
||||
},
|
||||
"api.publish.getJob": () =>
|
||||
heldJob ? heldJob.promise : { status: "success" },
|
||||
"api.publish.getLog": async (value) => {
|
||||
const input = value as (typeof logRequests)[number];
|
||||
logRequests.push(input);
|
||||
if (pendingLogResponses > 0) {
|
||||
pendingLogResponses -= 1;
|
||||
return { availability: "pending" };
|
||||
}
|
||||
if (failedLogResponses > 0) {
|
||||
failedLogResponses -= 1;
|
||||
throw new Error("Temporary log failure");
|
||||
}
|
||||
const first = input.cursor === undefined;
|
||||
if (
|
||||
input.buildId === "build-1" &&
|
||||
holdLog &&
|
||||
holdLog.cursor === input.cursor
|
||||
) {
|
||||
await holdLog.response.promise;
|
||||
}
|
||||
return {
|
||||
availability: "available",
|
||||
startedAt: "2026-11-13T10:00:00.000Z",
|
||||
completedAt: "2026-11-13T10:00:03.000Z",
|
||||
log: {
|
||||
encoding: "base64url",
|
||||
chunk: first ? encoded([0xe2]) : encoded([0x82, 0xac]),
|
||||
complete: !first,
|
||||
nextCursor: first ? 1 : undefined,
|
||||
issues: [
|
||||
{
|
||||
severity: first ? "warning" : "error",
|
||||
message: first ? "Early warning" : "Late error",
|
||||
},
|
||||
],
|
||||
issuesOmitted: first ? 1 : 0,
|
||||
GET: {
|
||||
"domain.project": () => ({
|
||||
success: true,
|
||||
project: {
|
||||
...stores.$project.get(),
|
||||
latestBuildVirtual: {
|
||||
domain: "example",
|
||||
buildId: acceptedBuildId,
|
||||
createdAt: new Date().toISOString(),
|
||||
publishStatus: "PUBLISHED",
|
||||
},
|
||||
},
|
||||
};
|
||||
}),
|
||||
"domain.countTotalDomains": () => ({ success: true, data: 0 }),
|
||||
"project.userPublishCount": () => ({
|
||||
success: true,
|
||||
data: 0,
|
||||
limit: 100,
|
||||
}),
|
||||
"api.publish.getJob": () =>
|
||||
heldJob ? heldJob.promise : { status: "success" },
|
||||
"api.publish.getLog": async (value) => {
|
||||
const input = value as (typeof logRequests)[number];
|
||||
logRequests.push(input);
|
||||
if (pendingLogResponses > 0) {
|
||||
pendingLogResponses -= 1;
|
||||
return { availability: "pending" };
|
||||
}
|
||||
if (failedLogResponses > 0) {
|
||||
failedLogResponses -= 1;
|
||||
throw new Error("Temporary log failure");
|
||||
}
|
||||
const first = input.cursor === undefined;
|
||||
if (
|
||||
input.buildId === "build-1" &&
|
||||
holdLog &&
|
||||
holdLog.cursor === input.cursor
|
||||
) {
|
||||
await holdLog.response.promise;
|
||||
}
|
||||
return {
|
||||
availability: "available",
|
||||
startedAt: "2026-11-13T10:00:00.000Z",
|
||||
completedAt: "2026-11-13T10:00:03.000Z",
|
||||
log: {
|
||||
encoding: "base64url",
|
||||
chunk: first ? encoded([0xe2]) : encoded([0x82, 0xac]),
|
||||
complete: !first,
|
||||
nextCursor: first ? 1 : undefined,
|
||||
issues: [
|
||||
{
|
||||
severity: first ? "warning" : "error",
|
||||
message: first ? "Early warning" : "Late error",
|
||||
},
|
||||
],
|
||||
issuesOmitted: first ? 1 : 0,
|
||||
},
|
||||
};
|
||||
},
|
||||
"build.contentDatabasePublishDiagnostics": () => ({
|
||||
mdxErrors: [],
|
||||
mdxOmissions: [],
|
||||
}),
|
||||
"api.publish.validate": () => ({
|
||||
diagnostics: { mdxErrors: [], mdxOmissions: [] },
|
||||
cssValid: true,
|
||||
}),
|
||||
},
|
||||
"build.contentDatabasePublishDiagnostics": () => ({
|
||||
mdxErrors: [],
|
||||
mdxOmissions: [],
|
||||
}),
|
||||
"api.publish.validate": () => ({
|
||||
diagnostics: { mdxErrors: [], mdxOmissions: [] },
|
||||
cssValid: true,
|
||||
}),
|
||||
});
|
||||
interceptor.start();
|
||||
PublishButton = (await import("./publish")).PublishButton;
|
||||
|
||||
@@ -3,9 +3,9 @@ import { act } from "react-dom/test-utils";
|
||||
import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
|
||||
import { TooltipProvider, toast } from "@webstudio-is/design-system";
|
||||
import type { Project } from "@webstudio-is/project";
|
||||
import { createTrpcInterceptor } from "~/shared/trpc/trpc-test-utils";
|
||||
import {
|
||||
createPublishAuditFinding,
|
||||
createTrpcInterceptor,
|
||||
selectStaticDestination,
|
||||
} from "./publish-test-utils";
|
||||
|
||||
@@ -47,32 +47,36 @@ beforeAll(async () => {
|
||||
window.navigation.addEventListener("navigate", interceptDownload);
|
||||
vi.resetModules();
|
||||
interceptor = createTrpcInterceptor({
|
||||
"build.contentDatabasePublishDiagnostics": () => ({
|
||||
mdxErrors: [],
|
||||
mdxOmissions: [],
|
||||
}),
|
||||
"domain.publish": () => {
|
||||
publishRequests += 1;
|
||||
return staticResponse;
|
||||
},
|
||||
"api.publish.getJob": () => {
|
||||
jobRequests += 1;
|
||||
return { status: getJobStatus };
|
||||
},
|
||||
"domain.project": () => ({
|
||||
success: true,
|
||||
project: {
|
||||
...projectStore.get(),
|
||||
latestStaticBuild:
|
||||
publishRequests === 0
|
||||
? (projectStore.get()?.latestStaticBuild ?? null)
|
||||
: {
|
||||
buildId: "static-1",
|
||||
updatedAt: new Date().toISOString(),
|
||||
publishStatus: buildStatus,
|
||||
},
|
||||
POST: {
|
||||
"domain.publish": () => {
|
||||
publishRequests += 1;
|
||||
return staticResponse;
|
||||
},
|
||||
}),
|
||||
},
|
||||
GET: {
|
||||
"build.contentDatabasePublishDiagnostics": () => ({
|
||||
mdxErrors: [],
|
||||
mdxOmissions: [],
|
||||
}),
|
||||
"api.publish.getJob": () => {
|
||||
jobRequests += 1;
|
||||
return { status: getJobStatus };
|
||||
},
|
||||
"domain.project": () => ({
|
||||
success: true,
|
||||
project: {
|
||||
...projectStore.get(),
|
||||
latestStaticBuild:
|
||||
publishRequests === 0
|
||||
? (projectStore.get()?.latestStaticBuild ?? null)
|
||||
: {
|
||||
buildId: "static-1",
|
||||
updatedAt: new Date().toISOString(),
|
||||
publishStatus: buildStatus,
|
||||
},
|
||||
},
|
||||
}),
|
||||
},
|
||||
});
|
||||
interceptor.start();
|
||||
publishModule = await import("./publish");
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
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");
|
||||
}
|
||||
});
|
||||
@@ -1,4 +1,3 @@
|
||||
import { FetchInterceptor } from "@mswjs/interceptors/fetch";
|
||||
import { act } from "react-dom/test-utils";
|
||||
import { expect, vi } from "vitest";
|
||||
|
||||
@@ -67,90 +66,3 @@ export const deferred = <T>() => {
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
};
|
||||
|
||||
export const createTrpcInterceptor = (
|
||||
handlers: Record<string, (input: unknown) => unknown | Promise<unknown>>,
|
||||
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<string, unknown>;
|
||||
try {
|
||||
const parsedInput: unknown = JSON.parse(
|
||||
request.method === "GET"
|
||||
? (url.searchParams.get("input") ?? "{}")
|
||||
: await request.clone().text()
|
||||
);
|
||||
if (
|
||||
parsedInput === null ||
|
||||
typeof parsedInput !== "object" ||
|
||||
Array.isArray(parsedInput)
|
||||
) {
|
||||
throw new Error("Invalid tRPC batch envelope");
|
||||
}
|
||||
input = parsedInput as Record<string, unknown>;
|
||||
} 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 value = input[String(index)];
|
||||
onRequest?.(route, 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.map((data) => ({ result: { data } }))),
|
||||
{
|
||||
headers: { "Content-Type": "application/json" },
|
||||
}
|
||||
)
|
||||
);
|
||||
} catch (error) {
|
||||
controller.errorWith(error);
|
||||
}
|
||||
});
|
||||
return {
|
||||
start: () => interceptor.apply(),
|
||||
stop: () => {
|
||||
interceptor.dispose();
|
||||
if (unexpectedRequests.length > 0) {
|
||||
throw new Error(unexpectedRequests.join("\n"));
|
||||
}
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,132 @@
|
||||
import { act } from "react-dom/test-utils";
|
||||
import { page } from "@vitest/browser/context";
|
||||
import { createMemoryRouter, RouterProvider } from "react-router-dom";
|
||||
import {
|
||||
afterAll,
|
||||
afterEach,
|
||||
beforeAll,
|
||||
beforeEach,
|
||||
expect,
|
||||
test,
|
||||
vi,
|
||||
} from "vitest";
|
||||
import { TooltipProvider } from "@webstudio-is/design-system";
|
||||
import type { Workspace } from "@webstudio-is/project";
|
||||
import { createBrowserTestRenderer } from "~/shared/test-utils";
|
||||
import { createTrpcInterceptor } from "~/shared/trpc/trpc-test-utils";
|
||||
|
||||
const requests: Array<{ path: string; input: unknown }> = [];
|
||||
let addMemberResult: unknown = { success: true };
|
||||
const interceptor = createTrpcInterceptor(
|
||||
{
|
||||
GET: {
|
||||
"workspace.listMembers": () => ({
|
||||
success: true,
|
||||
data: {
|
||||
owner: { email: "owner@example.com" },
|
||||
members: [],
|
||||
pendingInvites: [],
|
||||
maxSeats: 5,
|
||||
},
|
||||
}),
|
||||
},
|
||||
POST: { "workspace.addMember": () => addMemberResult },
|
||||
},
|
||||
(path, input) => requests.push({ path, input })
|
||||
);
|
||||
|
||||
let renderer: ReturnType<typeof createBrowserTestRenderer>;
|
||||
let ManageMembersDialog: typeof import("./manage-members-dialog").ManageMembersDialog;
|
||||
|
||||
beforeAll(async () => {
|
||||
vi.resetModules();
|
||||
interceptor.start();
|
||||
({ ManageMembersDialog } = await import("./manage-members-dialog"));
|
||||
const { updateCsrfToken } = await import("~/shared/csrf.client");
|
||||
updateCsrfToken("test-token");
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
requests.length = 0;
|
||||
addMemberResult = { success: true };
|
||||
renderer = createBrowserTestRenderer();
|
||||
});
|
||||
|
||||
afterEach(() => renderer.unmount());
|
||||
|
||||
afterAll(() => interceptor.stop());
|
||||
|
||||
const render = async () => {
|
||||
const router = createMemoryRouter(
|
||||
[
|
||||
{
|
||||
path: "/",
|
||||
element: (
|
||||
<TooltipProvider>
|
||||
<ManageMembersDialog
|
||||
workspace={
|
||||
{
|
||||
id: "workspace-1",
|
||||
name: "Design team",
|
||||
isDefault: false,
|
||||
isDeleted: false,
|
||||
createdAt: "2026-11-18T00:00:00.000Z",
|
||||
userId: "owner-1",
|
||||
} as Workspace
|
||||
}
|
||||
userId="owner-1"
|
||||
isOpen
|
||||
onOpenChange={() => {}}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
),
|
||||
},
|
||||
],
|
||||
{ initialEntries: ["/"] }
|
||||
);
|
||||
await renderer.render(<RouterProvider router={router} />);
|
||||
};
|
||||
|
||||
const waitForRequest = async (path: string) => {
|
||||
await vi.waitFor(() =>
|
||||
expect(requests.some((request) => request.path === path)).toBe(true)
|
||||
);
|
||||
};
|
||||
|
||||
test("invites a workspace member through tRPC and shows the pending member", async () => {
|
||||
await render();
|
||||
await waitForRequest("workspace.listMembers");
|
||||
const input = page.getByPlaceholder("alice@example.com, bob@example.com");
|
||||
await act(async () => input.fill("new-member@example.com"));
|
||||
await act(async () => page.getByRole("button", { name: "Invite" }).click());
|
||||
await waitForRequest("workspace.addMember");
|
||||
|
||||
expect(requests).toContainEqual({
|
||||
path: "workspace.addMember",
|
||||
input: {
|
||||
workspaceId: "workspace-1",
|
||||
email: "new-member@example.com",
|
||||
relation: "viewers",
|
||||
},
|
||||
});
|
||||
expect(document.body.textContent).toContain("new-member@example.com");
|
||||
});
|
||||
|
||||
test("shows the server error when the member invite is rejected", async () => {
|
||||
addMemberResult = { success: false, error: "Invite is not allowed" };
|
||||
await render();
|
||||
await waitForRequest("workspace.listMembers");
|
||||
await act(async () =>
|
||||
page
|
||||
.getByPlaceholder("alice@example.com, bob@example.com")
|
||||
.fill("blocked@example.com")
|
||||
);
|
||||
await act(async () => page.getByRole("button", { name: "Invite" }).click());
|
||||
await waitForRequest("workspace.addMember");
|
||||
|
||||
await vi.waitFor(() =>
|
||||
expect(document.body.textContent).toContain(
|
||||
"blocked@example.com: Invite is not allowed"
|
||||
)
|
||||
);
|
||||
});
|
||||
@@ -1,27 +1,23 @@
|
||||
import { beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import {
|
||||
afterAll,
|
||||
beforeAll,
|
||||
beforeEach,
|
||||
describe,
|
||||
expect,
|
||||
test,
|
||||
vi,
|
||||
} from "vitest";
|
||||
import { createEmptyWebstudioFragment } from "@webstudio-is/project-build/runtime";
|
||||
import { inspectWebstudioJsxFragmentSyntax } from "@webstudio-is/project-build/transfer";
|
||||
import { isLikelyWebstudioJsx, jsx } from "./plugin-jsx";
|
||||
import { $project } from "../sync/data-stores";
|
||||
import { pasteHandled, pasteIgnored } from "./copy-paste";
|
||||
import { updateCsrfToken } from "../csrf.client";
|
||||
import { createTrpcInterceptor } from "../trpc/trpc-test-utils";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
createJsxFragment: vi.fn(),
|
||||
insertWebstudioFragmentAt: vi.fn(),
|
||||
toastError: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../trpc/trpc-client", async (importOriginal) => ({
|
||||
...(await importOriginal()),
|
||||
nativeClient: {
|
||||
build: {
|
||||
createJsxFragment: {
|
||||
query: mocks.createJsxFragment,
|
||||
},
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../instance-utils/insert", async (importOriginal) => ({
|
||||
...(await importOriginal()),
|
||||
insertWebstudioFragmentAt: mocks.insertWebstudioFragmentAt,
|
||||
@@ -37,9 +33,34 @@ vi.mock("../builder-api", async (importOriginal) => ({
|
||||
},
|
||||
}));
|
||||
|
||||
let requestInput: unknown;
|
||||
let createFragmentResponse: unknown = createEmptyWebstudioFragment();
|
||||
let jsx: typeof import("./plugin-jsx").jsx;
|
||||
let isLikelyWebstudioJsx: typeof import("./plugin-jsx").isLikelyWebstudioJsx;
|
||||
let pasteHandled: typeof import("./copy-paste").pasteHandled;
|
||||
let pasteIgnored: typeof import("./copy-paste").pasteIgnored;
|
||||
const interceptor = createTrpcInterceptor({
|
||||
GET: {
|
||||
"build.createJsxFragment": (input) => {
|
||||
requestInput = input;
|
||||
return createFragmentResponse;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
beforeAll(async () => {
|
||||
interceptor.start();
|
||||
({ pasteHandled, pasteIgnored } = await import("./copy-paste"));
|
||||
({ jsx, isLikelyWebstudioJsx } = await import("./plugin-jsx"));
|
||||
});
|
||||
afterAll(() => interceptor.stop());
|
||||
|
||||
describe("jsx paste plugin", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
requestInput = undefined;
|
||||
createFragmentResponse = createEmptyWebstudioFragment();
|
||||
updateCsrfToken("test-token");
|
||||
$project.set({ id: "project-id" } as never);
|
||||
});
|
||||
|
||||
@@ -62,15 +83,15 @@ describe("jsx paste plugin", () => {
|
||||
|
||||
test("converts and inserts Webstudio JSX", async () => {
|
||||
const fragment = createEmptyWebstudioFragment();
|
||||
mocks.createJsxFragment.mockResolvedValue(fragment);
|
||||
createFragmentResponse = fragment;
|
||||
mocks.insertWebstudioFragmentAt.mockReturnValue(true);
|
||||
|
||||
await expect(jsx.onPaste?.("<Box />")).resolves.toEqual(pasteHandled);
|
||||
|
||||
expect(mocks.createJsxFragment).toHaveBeenCalledWith({
|
||||
const result = await jsx.onPaste?.("<Box />");
|
||||
expect(requestInput).toEqual({
|
||||
projectId: "project-id",
|
||||
source: "<Box />",
|
||||
});
|
||||
expect(result).toEqual(pasteHandled);
|
||||
expect(mocks.insertWebstudioFragmentAt).toHaveBeenCalledWith(
|
||||
fragment,
|
||||
undefined,
|
||||
@@ -86,7 +107,7 @@ describe("jsx paste plugin", () => {
|
||||
pasteIgnored
|
||||
);
|
||||
|
||||
expect(mocks.createJsxFragment).not.toHaveBeenCalled();
|
||||
expect(requestInput).toBeUndefined();
|
||||
expect(mocks.insertWebstudioFragmentAt).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -95,12 +116,26 @@ describe("jsx paste plugin", () => {
|
||||
|
||||
await expect(jsx.onPaste?.("<Box />")).resolves.toEqual(pasteIgnored);
|
||||
|
||||
expect(mocks.createJsxFragment).not.toHaveBeenCalled();
|
||||
expect(requestInput).toBeUndefined();
|
||||
expect(mocks.insertWebstudioFragmentAt).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("reports conversion errors and stops paste fallback", async () => {
|
||||
mocks.createJsxFragment.mockRejectedValue(new Error("Invalid JSX"));
|
||||
createFragmentResponse = new Response(
|
||||
JSON.stringify([
|
||||
{
|
||||
error: {
|
||||
message: "Invalid JSX",
|
||||
code: -32600,
|
||||
data: { code: "BAD_REQUEST", httpStatus: 400 },
|
||||
},
|
||||
},
|
||||
]),
|
||||
{
|
||||
status: 400,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
}
|
||||
);
|
||||
|
||||
await expect(jsx.onPaste?.('<Box ws:id="0" />')).resolves.toEqual({
|
||||
success: false,
|
||||
@@ -109,5 +144,9 @@ describe("jsx paste plugin", () => {
|
||||
|
||||
expect(mocks.toastError).not.toHaveBeenCalled();
|
||||
expect(mocks.insertWebstudioFragmentAt).not.toHaveBeenCalled();
|
||||
expect(requestInput).toEqual({
|
||||
projectId: "project-id",
|
||||
source: '<Box ws:id="0" />',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
import { act } from "react-dom/test-utils";
|
||||
import { createMemoryRouter, RouterProvider } from "react-router-dom";
|
||||
import {
|
||||
afterAll,
|
||||
afterEach,
|
||||
beforeAll,
|
||||
beforeEach,
|
||||
expect,
|
||||
test,
|
||||
vi,
|
||||
} from "vitest";
|
||||
import { IconButton, TooltipProvider } from "@webstudio-is/design-system";
|
||||
import { createBrowserTestRenderer } from "~/shared/test-utils";
|
||||
import { createTrpcInterceptor } from "~/shared/trpc/trpc-test-utils";
|
||||
|
||||
const requests: Array<{ path: string; input: unknown }> = [];
|
||||
const interceptor = createTrpcInterceptor(
|
||||
{
|
||||
POST: {
|
||||
"notification.accept": () => ({ success: true }),
|
||||
"notification.decline": () => ({ success: true }),
|
||||
},
|
||||
},
|
||||
(path, input) => requests.push({ path, input })
|
||||
);
|
||||
|
||||
let renderer: ReturnType<typeof createBrowserTestRenderer>;
|
||||
let NotificationPopover: typeof import("./notification-popover").NotificationPopover;
|
||||
|
||||
beforeAll(async () => {
|
||||
vi.resetModules();
|
||||
interceptor.start();
|
||||
({ NotificationPopover } = await import("./notification-popover"));
|
||||
const { updateCsrfToken } = await import("~/shared/csrf.client");
|
||||
updateCsrfToken("test-token");
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
requests.length = 0;
|
||||
renderer = createBrowserTestRenderer();
|
||||
});
|
||||
|
||||
afterEach(() => renderer.unmount());
|
||||
|
||||
afterAll(() => interceptor.stop());
|
||||
|
||||
const render = async () => {
|
||||
const notifications = [
|
||||
{
|
||||
id: "accept-me",
|
||||
type: "workspaceInvite",
|
||||
status: "pending",
|
||||
payload: { workspaceId: "workspace-1", relation: "viewers" },
|
||||
createdAt: "2026-11-18T00:00:00.000Z",
|
||||
senderEmail: "owner@example.com",
|
||||
senderName: "Owner",
|
||||
workspaceName: "Design team",
|
||||
projectTitle: undefined,
|
||||
description: 'Owner invited you to "Design team" as viewer',
|
||||
},
|
||||
{
|
||||
id: "decline-me",
|
||||
type: "projectTransfer",
|
||||
status: "pending",
|
||||
payload: { projectId: "project-1" },
|
||||
createdAt: "2026-11-18T00:00:00.000Z",
|
||||
senderEmail: "owner@example.com",
|
||||
senderName: "Owner",
|
||||
workspaceName: undefined,
|
||||
projectTitle: "Landing page",
|
||||
description: 'Owner wants to transfer "Landing page" to you',
|
||||
},
|
||||
] as const;
|
||||
const router = createMemoryRouter(
|
||||
[
|
||||
{
|
||||
path: "/",
|
||||
element: (
|
||||
<TooltipProvider>
|
||||
<NotificationPopover
|
||||
defaultOpen
|
||||
initialNotifications={[...notifications]}
|
||||
renderTrigger={(props) => <IconButton color="ghost" {...props} />}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
),
|
||||
},
|
||||
],
|
||||
{ initialEntries: ["/"] }
|
||||
);
|
||||
await renderer.render(<RouterProvider router={router} />);
|
||||
};
|
||||
|
||||
const waitForRequest = async (path: string) => {
|
||||
await vi.waitFor(() =>
|
||||
expect(requests.some((request) => request.path === path)).toBe(true)
|
||||
);
|
||||
};
|
||||
|
||||
test("accepts a workspace invitation through the tRPC request", async () => {
|
||||
await render();
|
||||
const accept = Array.from(document.querySelectorAll("button")).find(
|
||||
(button) => button.textContent === "Accept"
|
||||
);
|
||||
expect(accept).toBeDefined();
|
||||
await act(async () => accept?.click());
|
||||
await waitForRequest("notification.accept");
|
||||
|
||||
expect(requests).toContainEqual({
|
||||
path: "notification.accept",
|
||||
input: { notificationId: "accept-me" },
|
||||
});
|
||||
});
|
||||
|
||||
test("declines a notification through the tRPC request", async () => {
|
||||
await render();
|
||||
const decline = document.querySelectorAll<HTMLButtonElement>(
|
||||
'button[aria-label="Decline"]'
|
||||
)[1];
|
||||
expect(decline).toBeDefined();
|
||||
await act(async () => decline?.click());
|
||||
await waitForRequest("notification.decline");
|
||||
|
||||
expect(requests).toContainEqual({
|
||||
path: "notification.decline",
|
||||
input: { notificationId: "decline-me" },
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
import { act } from "react-dom/test-utils";
|
||||
import { page } from "@vitest/browser/context";
|
||||
import {
|
||||
afterAll,
|
||||
afterEach,
|
||||
beforeAll,
|
||||
beforeEach,
|
||||
expect,
|
||||
test,
|
||||
vi,
|
||||
} from "vitest";
|
||||
import { defaultPlanFeatures } from "@webstudio-is/plans";
|
||||
import { toast, TooltipProvider } from "@webstudio-is/design-system";
|
||||
import { createBrowserTestRenderer } from "~/shared/test-utils";
|
||||
import { createTrpcInterceptor } from "~/shared/trpc/trpc-test-utils";
|
||||
|
||||
const requests: Array<{ path: string; input: unknown }> = [];
|
||||
let restoreResult: unknown = { success: false, error: "Restore failed" };
|
||||
const interceptor = createTrpcInterceptor(
|
||||
{
|
||||
GET: {
|
||||
"project.publishedBuilds": () => ({
|
||||
success: true,
|
||||
data: [
|
||||
{
|
||||
buildId: "build-1",
|
||||
createdAt: "2026-11-17T10:00:00.000Z",
|
||||
domains: "example.com",
|
||||
},
|
||||
],
|
||||
}),
|
||||
},
|
||||
POST: { "project.restoreDevelopmentBuild": () => restoreResult },
|
||||
},
|
||||
(path, input) => requests.push({ path, input })
|
||||
);
|
||||
|
||||
let renderer: ReturnType<typeof createBrowserTestRenderer>;
|
||||
let SectionBackups: typeof import("./section-backups").SectionBackups;
|
||||
let nanoStates: typeof import("~/shared/nano-states");
|
||||
let originalPlan: ReturnType<
|
||||
typeof import("~/shared/nano-states").$planFeatures.get
|
||||
>;
|
||||
|
||||
beforeAll(async () => {
|
||||
vi.resetModules();
|
||||
interceptor.start();
|
||||
({ SectionBackups } = await import("./section-backups"));
|
||||
nanoStates = await import("~/shared/nano-states");
|
||||
originalPlan = nanoStates.$planFeatures.get();
|
||||
const { updateCsrfToken } = await import("~/shared/csrf.client");
|
||||
updateCsrfToken("test-token");
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
requests.length = 0;
|
||||
restoreResult = { success: false, error: "Restore failed" };
|
||||
nanoStates.$planFeatures.set({
|
||||
...defaultPlanFeatures,
|
||||
canRestoreBackups: true,
|
||||
});
|
||||
renderer = createBrowserTestRenderer();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
renderer.unmount();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
nanoStates.$planFeatures.set(originalPlan);
|
||||
interceptor.stop();
|
||||
});
|
||||
|
||||
const render = async () => {
|
||||
await renderer.render(
|
||||
<TooltipProvider>
|
||||
<SectionBackups projectId="project-1" />
|
||||
</TooltipProvider>
|
||||
);
|
||||
};
|
||||
|
||||
const waitForRequest = async (path: string) => {
|
||||
await act(async () => {
|
||||
await vi.waitFor(() =>
|
||||
expect(requests.some((request) => request.path === path)).toBe(true)
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
const restoreBackup = async () => {
|
||||
await act(async () => page.getByRole("combobox").click());
|
||||
await act(async () =>
|
||||
page.getByRole("option", { name: /example\.com/ }).click()
|
||||
);
|
||||
await act(async () => page.getByRole("button", { name: "Restore" }).click());
|
||||
await act(async () =>
|
||||
page.getByRole("dialog").getByRole("button", { name: "Restore" }).click()
|
||||
);
|
||||
};
|
||||
|
||||
test("reloads the page after a successful restore", async () => {
|
||||
restoreResult = { success: true };
|
||||
const onReload = vi.fn();
|
||||
// Observe the real reload without navigating away from the test runner.
|
||||
const interceptReload = (event: NavigateEvent) => {
|
||||
if (event.navigationType === "reload") {
|
||||
event.preventDefault();
|
||||
onReload();
|
||||
}
|
||||
};
|
||||
window.navigation.addEventListener("navigate", interceptReload);
|
||||
try {
|
||||
await render();
|
||||
await restoreBackup();
|
||||
await vi.waitFor(() => expect(onReload).toHaveBeenCalledOnce());
|
||||
expect(requests).toContainEqual({
|
||||
path: "project.restoreDevelopmentBuild",
|
||||
input: { projectId: "project-1", fromBuildId: "build-1" },
|
||||
});
|
||||
} finally {
|
||||
window.navigation.removeEventListener("navigate", interceptReload);
|
||||
}
|
||||
});
|
||||
|
||||
test("loads backups and reports a failed restore request", async () => {
|
||||
const showError = vi.spyOn(toast, "error");
|
||||
await render();
|
||||
await waitForRequest("project.publishedBuilds");
|
||||
expect(requests).toContainEqual({
|
||||
path: "project.publishedBuilds",
|
||||
input: { projectId: "project-1" },
|
||||
});
|
||||
await restoreBackup();
|
||||
await waitForRequest("project.restoreDevelopmentBuild");
|
||||
|
||||
await vi.waitFor(() =>
|
||||
expect(showError).toHaveBeenCalledWith("Restore failed")
|
||||
);
|
||||
expect(requests).toContainEqual({
|
||||
path: "project.restoreDevelopmentBuild",
|
||||
input: { projectId: "project-1", fromBuildId: "build-1" },
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { act } from "react-dom/test-utils";
|
||||
import { createRoot } from "react-dom/client";
|
||||
|
||||
export const createBrowserTestRenderer = () => {
|
||||
const global = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean };
|
||||
const previousActEnvironment = global.IS_REACT_ACT_ENVIRONMENT;
|
||||
global.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
|
||||
return {
|
||||
render: async (element: ReactNode) => act(async () => root.render(element)),
|
||||
unmount: () => {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
global.IS_REACT_ACT_ENVIRONMENT = previousActEnvironment;
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,118 @@
|
||||
import { expect, test } from "vitest";
|
||||
import { createTrpcInterceptor } from "./trpc-test-utils";
|
||||
|
||||
const procedure = "api.publish.getJob";
|
||||
const input = JSON.stringify({ 0: { projectId: "project-1", jobId: "job-1" } });
|
||||
const encodedInput = encodeURIComponent(input);
|
||||
const requestUrl = `/trpc/${procedure}?batch=1&input=${encodedInput}`;
|
||||
const queries = { [procedure]: () => ({ status: "success" }) };
|
||||
|
||||
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 error = {
|
||||
message: "Publish job not found",
|
||||
code: -32004,
|
||||
data: { code: "NOT_FOUND", httpStatus: 404, path: procedure },
|
||||
};
|
||||
const interceptor = createTrpcInterceptor({
|
||||
GET: {
|
||||
[procedure]: () => Response.json([{ error }], { status: 404 }),
|
||||
},
|
||||
});
|
||||
interceptor.start();
|
||||
try {
|
||||
const response = await fetch(requestUrl);
|
||||
expect(response.status).toBe(404);
|
||||
expect(await response.json()).toEqual([{ error }]);
|
||||
} finally {
|
||||
interceptor.stop();
|
||||
}
|
||||
});
|
||||
|
||||
test("rejects unsupported request methods", async () => {
|
||||
const interceptor = createTrpcInterceptor({
|
||||
GET: queries,
|
||||
});
|
||||
interceptor.start();
|
||||
try {
|
||||
await expect(
|
||||
fetch(`/trpc/${procedure}?batch=1`, {
|
||||
method: "PUT",
|
||||
body: input,
|
||||
})
|
||||
).rejects.toThrow();
|
||||
} finally {
|
||||
expect(() => interceptor.stop()).toThrow("Unexpected request method");
|
||||
}
|
||||
});
|
||||
|
||||
test.each([
|
||||
{ name: "missing", flag: "" },
|
||||
{ name: "incorrect", flag: "batch=0&" },
|
||||
])("rejects a request with a $name batch flag", async ({ flag }) => {
|
||||
const interceptor = createTrpcInterceptor({
|
||||
GET: queries,
|
||||
});
|
||||
interceptor.start();
|
||||
try {
|
||||
await expect(
|
||||
fetch(`/trpc/${procedure}?${flag}input=${encodedInput}`)
|
||||
).rejects.toThrow();
|
||||
} finally {
|
||||
expect(() => interceptor.stop()).toThrow("Unexpected request batch");
|
||||
}
|
||||
});
|
||||
|
||||
test("rejects POST for a query procedure", async () => {
|
||||
const interceptor = createTrpcInterceptor({
|
||||
GET: queries,
|
||||
});
|
||||
interceptor.start();
|
||||
try {
|
||||
await expect(
|
||||
fetch(`/trpc/${procedure}?batch=1`, {
|
||||
method: "POST",
|
||||
body: input,
|
||||
})
|
||||
).rejects.toThrow();
|
||||
} finally {
|
||||
expect(() => interceptor.stop()).toThrow("Unexpected request method");
|
||||
}
|
||||
});
|
||||
|
||||
test("does not match inherited properties as procedures", async () => {
|
||||
const interceptor = createTrpcInterceptor({
|
||||
GET: queries,
|
||||
});
|
||||
interceptor.start();
|
||||
try {
|
||||
await expect(
|
||||
fetch(`/trpc/toString?batch=1&input=${encodedInput}`)
|
||||
).rejects.toThrow();
|
||||
} finally {
|
||||
expect(() => interceptor.stop()).toThrow("Unexpected request: toString");
|
||||
}
|
||||
});
|
||||
|
||||
test("rejects an invalid tRPC batch envelope", async () => {
|
||||
const interceptor = createTrpcInterceptor({
|
||||
GET: queries,
|
||||
});
|
||||
interceptor.start();
|
||||
try {
|
||||
await expect(
|
||||
fetch(`/trpc/${procedure}?batch=1&input=null`)
|
||||
).rejects.toThrow();
|
||||
} finally {
|
||||
expect(() => interceptor.stop()).toThrow("Unexpected request input");
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
import { FetchInterceptor } from "@mswjs/interceptors/fetch";
|
||||
|
||||
type Handlers = Record<string, (input: unknown) => unknown>;
|
||||
|
||||
export const createTrpcInterceptor = (
|
||||
{ GET = {}, POST = {} }: { GET?: Handlers; POST?: Handlers },
|
||||
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;
|
||||
}
|
||||
const rejectRequest = (message: string) => {
|
||||
unexpectedRequests.push(message);
|
||||
controller.errorWith(new Error(message));
|
||||
};
|
||||
if (url.searchParams.get("batch") !== "1") {
|
||||
rejectRequest(`Unexpected request batch: ${url.pathname}`);
|
||||
return;
|
||||
}
|
||||
if (request.method !== "GET" && request.method !== "POST") {
|
||||
rejectRequest(
|
||||
`Unexpected request method: ${request.method} ${url.pathname}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
const handlers = request.method === "GET" ? GET : POST;
|
||||
const routes = url.pathname.slice("/trpc/".length).split(",");
|
||||
for (const route of routes) {
|
||||
if (Object.hasOwn(handlers, route)) {
|
||||
continue;
|
||||
}
|
||||
if (Object.hasOwn(GET, route) || Object.hasOwn(POST, route)) {
|
||||
rejectRequest(`Unexpected request method: ${request.method} ${route}`);
|
||||
return;
|
||||
}
|
||||
rejectRequest(`Unexpected request: ${route}`);
|
||||
return;
|
||||
}
|
||||
let input: Record<string, unknown>;
|
||||
try {
|
||||
const parsedInput: unknown = JSON.parse(
|
||||
request.method === "GET"
|
||||
? (url.searchParams.get("input") ?? "{}")
|
||||
: await request.clone().text()
|
||||
);
|
||||
if (
|
||||
parsedInput === null ||
|
||||
typeof parsedInput !== "object" ||
|
||||
Array.isArray(parsedInput)
|
||||
) {
|
||||
throw new Error("Invalid tRPC batch envelope");
|
||||
}
|
||||
input = parsedInput as Record<string, unknown>;
|
||||
} catch (error) {
|
||||
unexpectedRequests.push(`Unexpected request input: ${url.pathname}`);
|
||||
controller.errorWith(error);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const results = await Promise.all(
|
||||
routes.map(async (route, index) => {
|
||||
const value = input[String(index)];
|
||||
onRequest?.(route, value);
|
||||
return handlers[route](value);
|
||||
})
|
||||
);
|
||||
const response = results.find((result) => result instanceof Response);
|
||||
if (response !== undefined) {
|
||||
if (results.length !== 1) {
|
||||
rejectRequest(`Unexpected batched HTTP response: ${url.pathname}`);
|
||||
return;
|
||||
}
|
||||
controller.respondWith(response);
|
||||
return;
|
||||
}
|
||||
controller.respondWith(
|
||||
new Response(
|
||||
JSON.stringify(results.map((data) => ({ result: { data } }))),
|
||||
{
|
||||
headers: { "Content-Type": "application/json" },
|
||||
}
|
||||
)
|
||||
);
|
||||
} catch (error) {
|
||||
controller.errorWith(error);
|
||||
}
|
||||
});
|
||||
return {
|
||||
start: () => interceptor.apply(),
|
||||
stop: () => {
|
||||
interceptor.dispose();
|
||||
if (unexpectedRequests.length > 0) {
|
||||
throw new Error(unexpectedRequests.join("\n"));
|
||||
}
|
||||
},
|
||||
};
|
||||
};
|
||||
Reference in new issue
Block a user