Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
Add initial trpc interface package (#780)
Ivan Starkov2f171e0f42e4
diff --git a/apps/designer/.env.example b/apps/designer/.env.exampleindex e9ee507863..c67a069218 100644--- a/apps/designer/.env.example+++ b/apps/designer/.env.example@@ -40,4 +40,8 @@ BUILD_ORIGIN=BUILD_REQUIRE_SUBDOMAIN=# Enable features behind a flag, * enables all.-FEATURES=*\ No newline at end of file+FEATURES=*++# TRCP server url and API token. If empty local TRPC server is used+TRPC_SERVER_URL=+TRPC_SERVER_API_TOKEN=\ No newline at end of filediff --git a/apps/designer/app/services/trpc.server.ts b/apps/designer/app/services/trpc.server.tsnew file mode 100644index 0000000000..bddf43dc67--- /dev/null+++ b/apps/designer/app/services/trpc.server.ts@@ -0,0 +1,13 @@+import { createTrpcProxyServiceClient } from "@webstudio-is/trpc-interface/server";++const TRPC_SERVER_URL = process.env.TRPC_SERVER_URL;+const TRPC_SERVER_API_TOKEN = process.env.TRPC_SERVER_API_TOKEN;++export const trpcClient = createTrpcProxyServiceClient(+ TRPC_SERVER_URL !== undefined && TRPC_SERVER_API_TOKEN !== undefined+ ? {+ url: TRPC_SERVER_URL,+ token: TRPC_SERVER_API_TOKEN,+ }+ : undefined+);diff --git a/apps/designer/package.json b/apps/designer/package.jsonindex 1e1542458d..4db8e9bb26 100644--- a/apps/designer/package.json+++ b/apps/designer/package.json@@ -45,6 +45,7 @@"@webstudio-is/prisma-client": "workspace:^","@webstudio-is/project": "workspace:^","@webstudio-is/react-sdk": "workspace:^",+ "@webstudio-is/trpc-interface": "workspace:^","bson-objectid": "^2.0.4","camelcase": "^6.3.0","colord": "^2.9.3",diff --git a/packages/trpc-interface/LICENSE b/packages/trpc-interface/LICENSEnew file mode 100644index 0000000000..1f6edad9a7--- /dev/null+++ b/packages/trpc-interface/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2022 Webstudio++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/packages/trpc-interface/README.md b/packages/trpc-interface/README.mdnew file mode 100644index 0000000000..db79137b8b--- /dev/null+++ b/packages/trpc-interface/README.md@@ -0,0 +1,5 @@+# trpc-interface++- `trpc-interface` can implement various TRPC server routers.++- it can act as a proxy for TRPC services implemented in any other apps (those services must have the same API interface).diff --git a/packages/trpc-interface/jest.config.js b/packages/trpc-interface/jest.config.jsnew file mode 100644index 0000000000..e7fc137533--- /dev/null+++ b/packages/trpc-interface/jest.config.js@@ -0,0 +1 @@+export { default } from "@webstudio-is/jest-config";diff --git a/packages/trpc-interface/package.json b/packages/trpc-interface/package.jsonnew file mode 100644index 0000000000..48841dcd25--- /dev/null+++ b/packages/trpc-interface/package.json@@ -0,0 +1,41 @@+{+ "name": "@webstudio-is/trpc-interface",+ "version": "0.20.0",+ "description": "Webstudio TRPC Interface",+ "author": "Webstudio <[email protected]>",+ "homepage": "https://webstudio.is",+ "type": "module",+ "scripts": {+ "typecheck": "tsc --noEmit",+ "test": "NODE_OPTIONS=--experimental-vm-modules jest",+ "checks": "pnpm typecheck && pnpm lint",+ "dev": "build-package --watch",+ "build": "build-package",+ "lint": "eslint ./src --ext .ts,.tsx --max-warnings 0"+ },+ "dependencies": {+ "@trpc/client": "^10.9.0",+ "@trpc/server": "^10.9.0",+ "@webstudio-is/prisma-client": "workspace:^",+ "zod": "^3.19.1"+ },+ "devDependencies": {+ "@types/node": "^17.0.21",+ "@webstudio-is/scripts": "workspace:^",+ "@webstudio-is/tsconfig": "workspace:^",+ "@webstudio-is/jest-config": "workspace:^",+ "typescript": "4.7.4"+ },+ "exports": {+ "./server": "./server.js"+ },+ "types": "src/index.server.ts",+ "files": [+ "lib/*",+ "src/*",+ "!*.test.*"+ ],+ "license": "MIT",+ "private": false,+ "sideEffects": false+}diff --git a/packages/trpc-interface/server.d.ts b/packages/trpc-interface/server.d.tsnew file mode 100644index 0000000000..ad6dde9958--- /dev/null+++ b/packages/trpc-interface/server.d.ts@@ -0,0 +1 @@+export * from "./src/index.server";diff --git a/packages/trpc-interface/server.js b/packages/trpc-interface/server.jsnew file mode 100644index 0000000000..a6fbe7c12c--- /dev/null+++ b/packages/trpc-interface/server.js@@ -0,0 +1 @@+export * from "./lib/index.server";diff --git a/packages/trpc-interface/src/index.server.ts b/packages/trpc-interface/src/index.server.tsnew file mode 100644index 0000000000..1b82adc223--- /dev/null+++ b/packages/trpc-interface/src/index.server.ts@@ -0,0 +1,2 @@+export type { SharedRouter } from "./shared/shared-router";+export { createTrpcProxyServiceClient } from "./shared/client";diff --git a/packages/trpc-interface/src/index.ts b/packages/trpc-interface/src/index.tsnew file mode 100644index 0000000000..f04101500d--- /dev/null+++ b/packages/trpc-interface/src/index.ts@@ -0,0 +1 @@+export * from "./index.server";diff --git a/packages/trpc-interface/src/shared/authorization-router.ts b/packages/trpc-interface/src/shared/authorization-router.tsnew file mode 100644index 0000000000..7899b0781c--- /dev/null+++ b/packages/trpc-interface/src/shared/authorization-router.ts@@ -0,0 +1,11 @@+import { z } from "zod";+import { router, procedure } from "./trpc";++export const authorizationRouter = router({+ check: procedure+ .input(z.object({ name: z.string() }))+ .output(z.object({ allowed: z.boolean() }))+ .query(async () => {+ return { allowed: false };+ }),+});diff --git a/packages/trpc-interface/src/shared/client.ts b/packages/trpc-interface/src/shared/client.tsnew file mode 100644index 0000000000..2b108339c9--- /dev/null+++ b/packages/trpc-interface/src/shared/client.ts@@ -0,0 +1,37 @@+import { createTRPCProxyClient, httpBatchLink } from "@trpc/client";+import { sharedRouter, type SharedRouter } from "./shared-router";+import { callerLink } from "../trpc-caller-link";++type SharedClientOptions = {+ url: string;+ token: string;+};++export const createTrpcProxyServiceClient = (+ options?: SharedClientOptions | undefined+) => {+ if (options !== undefined) {+ const remoteClient = createTRPCProxyClient<SharedRouter>({+ links: [+ httpBatchLink({+ url: options.url,+ headers: () => ({+ Authorization: options.token,+ }),+ }),+ ],+ });++ return remoteClient;+ }++ const client = createTRPCProxyClient<SharedRouter>({+ links: [+ callerLink({+ appRouter: sharedRouter,+ }),+ ],+ });++ return client;+};diff --git a/packages/trpc-interface/src/shared/shared-router.ts b/packages/trpc-interface/src/shared/shared-router.tsnew file mode 100644index 0000000000..046baabab2--- /dev/null+++ b/packages/trpc-interface/src/shared/shared-router.ts@@ -0,0 +1,8 @@+import { router } from "./trpc";+import { authorizationRouter } from "./authorization-router";++export const sharedRouter = router({+ authorize: authorizationRouter,+});++export type SharedRouter = typeof sharedRouter;diff --git a/packages/trpc-interface/src/shared/trpc.ts b/packages/trpc-interface/src/shared/trpc.tsnew file mode 100644index 0000000000..7f457749d1--- /dev/null+++ b/packages/trpc-interface/src/shared/trpc.ts@@ -0,0 +1,11 @@+import { initTRPC, type inferAsyncReturnType } from "@trpc/server";++export const createContext = async () => {+ return {};+};++export type Context = inferAsyncReturnType<typeof createContext>;++export const { router, procedure, middleware } = initTRPC+ .context<Context>()+ .create();diff --git a/packages/trpc-interface/src/trpc-caller-link.test.ts b/packages/trpc-interface/src/trpc-caller-link.test.tsnew file mode 100644index 0000000000..d53beb7a33--- /dev/null+++ b/packages/trpc-interface/src/trpc-caller-link.test.ts@@ -0,0 +1,117 @@+import { initTRPC } from "@trpc/server";+import { describe, test, expect } from "@jest/globals";+import { callerLink } from "./trpc-caller-link";+import { createTRPCProxyClient } from "@trpc/client";+import { z } from "zod";++type Context = {+ someCtx: string;+};++export const { router, procedure, middleware } = initTRPC+ .context<Context>()+ .create();++const authorize = router({+ noInput: procedure.query(async () => "hello"),+ stringInput: procedure.input(z.string()).query(({ input }) => input),+ objectInput: procedure+ .input(z.object({ hello: z.string() }))+ .query(({ input }) => input),+ objectInputTransform: procedure+ .input(+ z+ .object({ hello: z.string() })+ .transform((obj) => ({ [obj.hello]: "hello" }))+ )+ .query(({ input }) => input),++ objectInputWithContext: procedure+ .input(z.object({ hello: z.string() }))+ .query(({ input, ctx }) => ({ ...ctx, ...input })),++ objectInputWithTransformedOutput: procedure+ .input(z.object({ hello: z.string() }))+ .output(+ z+ .object({ hello: z.string(), someCtx: z.string() })+ .transform((obj) => ({ obj }))+ )+ .query(({ input, ctx }) => ({ ...ctx, ...input })),++ mutateNoInput: procedure.mutation(async () => "hello"),+});++const appRouter = router({+ test: procedure.query(async () => "hello"),+ authorize,+});++const contextValue = { someCtx: "hello" };++const client = createTRPCProxyClient<typeof appRouter>({+ links: [+ callerLink({+ appRouter,+ createContext: (): Context => contextValue,+ }),+ ],+});++const caller = appRouter.createCaller(contextValue);++describe("trpc-caller-link", () => {+ test("direct call works", async () => {+ const res = await client.test.query();+ expect(res).toEqual(await caller.test());+ });++ test("namespace no input call", async () => {+ const res = await client.authorize.noInput.query();+ expect(res).toEqual(await caller.authorize.noInput());+ });++ test("namespace input string call", async () => {+ const res = await client.authorize.stringInput.query("world");+ expect(res).toEqual(await caller.authorize.stringInput("world"));+ });++ test("namespace input object call", async () => {+ const res = await client.authorize.objectInput.query({ hello: "world" });+ expect(res).toEqual(await caller.authorize.objectInput({ hello: "world" }));+ });++ test("namespace transformed input object call", async () => {+ const res = await client.authorize.objectInputTransform.query({+ hello: "world",+ });+ expect(res).toEqual(+ await caller.authorize.objectInputTransform({ hello: "world" })+ );+ });++ test("namespace input object with context call", async () => {+ const res = await client.authorize.objectInputWithContext.query({+ hello: "world",+ });+ expect(res).toEqual(+ await caller.authorize.objectInputWithContext({ hello: "world" })+ );+ });++ test("namespace input object with output transform", async () => {+ const res = await client.authorize.objectInputWithTransformedOutput.query({+ hello: "world",+ });+ expect(res).toEqual(+ await caller.authorize.objectInputWithTransformedOutput({+ hello: "world",+ })+ );+ });++ test("namespace mutation input object with output transform", async () => {+ const res = await client.authorize.mutateNoInput.mutate();+ expect(res).toEqual(await caller.authorize.mutateNoInput());+ });+});diff --git a/packages/trpc-interface/src/trpc-caller-link.ts b/packages/trpc-interface/src/trpc-caller-link.tsnew file mode 100644index 0000000000..eeff491c15--- /dev/null+++ b/packages/trpc-interface/src/trpc-caller-link.ts@@ -0,0 +1,57 @@+import { AnyRouter } from "@trpc/server";+// eslint-disable-next-line import/no-internal-modules+import { observable } from "@trpc/server/observable";+import { TRPCClientError, TRPCLink } from "@trpc/client";++type MemoryLinkOptions<TemplateRouter extends AnyRouter> = {+ appRouter: TemplateRouter;+ createContext?: () => TemplateRouter["_def"]["_config"]["$types"]["ctx"];+};++/**+ * https://github.com/trpc/trpc/issues/3335+ *+ * createCaller and createTRPCProxyClient provides different interfaces,+ * here we provide callerLink which can be used as a [trpc client link](https://trpc.io/docs/links)+ * Allowing us to call router api without http but through createTRPCProxyClient interface+ * See trpc-caller-link.test.ts for details+ **/+export const callerLink = <TemplateRouter extends AnyRouter>(+ opts: MemoryLinkOptions<TemplateRouter>+): TRPCLink<TemplateRouter> => {+ const { appRouter, createContext } = opts;++ return (runtime) =>+ ({ op }) =>+ observable((observer) => {+ const caller = appRouter.createCaller(createContext?.() ?? {});+ const { path, input } = op;++ const paths = path.split(".");++ let localCaller = caller as unknown as (+ arg: unknown+ ) => Promise<unknown>;++ for (const functionName of paths) {+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment+ // @ts-ignore+ localCaller = localCaller[functionName];+ }++ const promise = localCaller(input);++ promise+ .then((data) => {+ observer.next({+ result: { data },+ });+ observer.complete();+ })+ .catch((cause) => observer.error(TRPCClientError.from(cause)));++ return () => {+ // nothing to cancel+ };+ });+};diff --git a/packages/trpc-interface/tsconfig.json b/packages/trpc-interface/tsconfig.jsonnew file mode 100644index 0000000000..ecb353d7bb--- /dev/null+++ b/packages/trpc-interface/tsconfig.json@@ -0,0 +1,11 @@+{+ "extends": "@webstudio-is/tsconfig/base.json",+ "include": ["src", "../../@types/**/*.d.ts"],+ "compilerOptions": {+ "module": "ES2020",+ "target": "ES2020",+ "baseUrl": ".",+ "outDir": "./lib",+ "rootDir": "./src"+ }+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 853a109024..6b2d1dc68b 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -95,6 +95,7 @@ importers:'@webstudio-is/project': workspace:^'@webstudio-is/react-sdk': workspace:^'@webstudio-is/storybook-config': workspace:^+ '@webstudio-is/trpc-interface': workspace:^'@webstudio-is/tsconfig': workspace:^babel-loader: ^8.2.5bson-objectid: ^2.0.4@@ -175,6 +176,7 @@ importers:'@webstudio-is/prisma-client': link:../../packages/prisma-client'@webstudio-is/project': link:../../packages/project'@webstudio-is/react-sdk': link:../../packages/react-sdk+ '@webstudio-is/trpc-interface': link:../../packages/trpc-interfacebson-objectid: 2.0.4camelcase: 6.3.0colord: 2.9.3@@ -875,6 +877,29 @@ importers:'@storybook/builder-webpack5': 6.5.14_u3szbfbwz52ckww23jbmu3kdiy'@storybook/manager-webpack5': 6.5.14+ packages/trpc-interface:+ specifiers:+ '@trpc/client': ^10.9.0+ '@trpc/server': ^10.9.0+ '@types/node': ^17.0.21+ '@webstudio-is/jest-config': workspace:^+ '@webstudio-is/prisma-client': workspace:^+ '@webstudio-is/scripts': workspace:^+ '@webstudio-is/tsconfig': workspace:^+ typescript: 4.7.4+ zod: ^3.19.1+ dependencies:+ '@trpc/client': 10.9.0_@[email protected]+ '@trpc/server': 10.9.0+ '@webstudio-is/prisma-client': link:../prisma-client+ zod: 3.19.1+ devDependencies:+ '@types/node': 17.0.45+ '@webstudio-is/jest-config': link:../jest-config+ '@webstudio-is/scripts': link:../scripts+ '@webstudio-is/tsconfig': link:../tsconfig+ typescript: 4.7.4+packages/tsconfig:specifiers: {}@@ -9542,6 +9567,18 @@ packages:engines: {node: '>= 6'}dev: true+ /@trpc/client/10.9.0_@[email protected]:+ resolution: {integrity: sha512-id6318qpgqllNOuBp7nuciXFPXCe+zae5d4r1hze6Eyp5fFFNO58TqA+4Q44KIcHgpfWyW2egs6iPeql3PrdKA==}+ peerDependencies:+ '@trpc/server': 10.9.0+ dependencies:+ '@trpc/server': 10.9.0+ dev: false++ /@trpc/server/10.9.0:+ resolution: {integrity: sha512-5psyZgbvy29pJND32hwkWTMbv6s86IbsPOeDopsgNF0VegZT6Dsijmb7Ub/TDhuJVQVq5u4u5briMXi3SxmBkw==}+ dev: false+/@trysound/sax/0.2.0:resolution: {integrity: sha512-L7z9BgrNEcYyUYtF+HaEfiS5ebkh9jXqbszz7pC0hRBPaatV0XjSD3+eHrpqFemQfgwiFF0QPIarnIihIDn7OA==}engines: {node: '>=10.13.0'}