cloudflare / workerd

The JavaScript / Wasm runtime that powers Cloudflare Workers
https://blog.cloudflare.com/workerd-open-source-workers-runtime/
Apache License 2.0
6.28k stars 304 forks source link

Challenges and Solutions for Using Types in Turborepo with Service Bindings #3113

Open j4tmr opened 1 week ago

j4tmr commented 1 week ago

I am using Cloudflare Workers with tRPC and Turborepo. I wrote a service with Workers and created an API using Service Bindings.

// @package/cfw-services
import { WorkerEntrypoint } from 'cloudflare:workers';
export class ServiceWorker extends WorkerEntrypoint<Env> {
        // Currently, entrypoints without a named handler are not supported
    async fetch(request: Request) {
        return new Response(null, { status: 404 });
    }
}
// api env
import type { ServiceWorker } from '@packages/cfw-services';
export interface Env {
    SERVICES: Service<ServiceWorker>;
}

My issue is that when compiling the tRPC client, it references 'cloudflare:workers', which is defined in @cloudflare/workers-types but is not an exported module. My solution is, in the project where the tRPC client adding

"compilerOptions": {
    "types": [
      "@cloudflare/workers-types"
    ]
}

in the tsconfig.json.

This temporarily solves the issue, but in the future, any other app that needs to use the tRPC API will also need to add a reference to @cloudflare/workers-types in their tsconfig. So I’m considering whether it would be better to directly add an export for types like WorkerEntrypoint in the 'cloudflare:workers' module.

petebacondarwin commented 1 week ago

Is the problem here that your tRPC server has an import on cloudflare:workers that is somehow being pulled into the tRPC client typings where that module has no typings? Can you flesh out the tRPC server side of the example above so it is concrete what is happening? Or perhaps provide a reproduction we could play with?

j4tmr commented 1 week ago

@petebacondarwin In short, tRPC server imports cloudflare:workers because types like WorkerEntrypoint can’t be directly referenced from @cloudflare/workers-types as they aren’t exported.

j4tmr commented 1 week ago

@petebacondarwin https://github.com/j4tmr/test-cfw-types. The project is still a bit complex. To put it simply, both the API and services are Cloudflare Workers, while the frontend is a Next.js project. You just need to cd apps/frontend and then npm run build to get a general idea. To fix it: in the tsconfig of the frontend project, add:

"types": [
      "@cloudflare/workers-types"
    ]

Then, start the API project, and the build should pass. The main issue is what I mentioned above, which aligns with your understanding—using cloudflare:workers in Turborepo has some optimization challenges.