Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: initial commit for wrangler support #26

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion packages/dev-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@
},
"dependencies": {
"@hono/node-server": "^1.2.0",
"miniflare": "^3.20231016.0"
"@iarna/toml": "^2.2.5",
"dotenv": "^16.3.1",
"miniflare": "^3.20231025.1"
}
}
29 changes: 6 additions & 23 deletions packages/dev-server/src/dev-server.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,16 @@
import type http from 'http'
import { getRequestListener } from '@hono/node-server'
import type { Miniflare, MiniflareOptions, WorkerOptions } from 'miniflare'
import type { Miniflare } from 'miniflare'
import type { Plugin, ViteDevServer, Connect } from 'vite'
import { prepareMiniflare, type PrepareMiniflareOptions } from './miniflare'

export type DevServerOptions = {
entry?: string
injectClientScript?: boolean
exclude?: (string | RegExp)[]
cf?: Partial<
Omit<
WorkerOptions,
// We can ignore these properties:
'name' | 'script' | 'scriptPath' | 'modules' | 'modulesRoot' | 'modulesRules'
> &
Pick<
MiniflareOptions,
'cachePersist' | 'd1Persist' | 'durableObjectsPersist' | 'kvPersist' | 'r2Persist'
>
>
}
} & PrepareMiniflareOptions

export const defaultOptions: Required<Omit<DevServerOptions, 'cf'>> = {
export const defaultOptions: Required<Omit<DevServerOptions, 'cf' | 'wranglerTomlPath'>> = {
entry: './src/index.ts',
injectClientScript: true,
exclude: [
Expand All @@ -40,8 +30,6 @@ interface ExecutionContext {

type Fetch = (request: Request, env: {}, executionContext: ExecutionContext) => Promise<Response>

const nullScript = 'export default { fetch: () => new Response(null, { status: 404 }) };'

export function devServer(options?: DevServerOptions): Plugin {
const entry = options?.entry ?? defaultOptions.entry
const plugin: Plugin = {
Expand All @@ -50,13 +38,8 @@ export function devServer(options?: DevServerOptions): Plugin {
let mf: undefined | Miniflare = undefined

// Dynamic import Miniflare for environments like Bun.
if (options?.cf) {
const { Miniflare } = await import('miniflare')
mf = new Miniflare({
modules: true,
script: nullScript,
...options.cf,
})
if (options?.cf || options?.wranglerTomlPath) {
mf = await prepareMiniflare(options)
}

async function createMiddleware(server: ViteDevServer): Promise<Connect.HandleFunction> {
Expand Down
19 changes: 19 additions & 0 deletions packages/dev-server/src/miniflare/dev-vars.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// https://github.com/cloudflare/workers-sdk/blob/3637d97a99c9d5e8d0d2b5f3adaf4bd9993265f0/packages/wrangler/src/dev/dev-vars.ts#L14
import * as path from 'node:path'
import { tryLoadDotEnv } from './dotenv.js'
import type { Config } from './types/config.js'

export function getVarsForDev(configPath: string): Config['vars'] {
const configDir = path.resolve(path.dirname(configPath ?? '.'))
const devVarsPath = path.resolve(configDir, '.dev.vars')
const loaded = tryLoadDotEnv(devVarsPath)
if (loaded !== undefined) {
const devVarsRelativePath = path.relative(process.cwd(), loaded.path)
console.log(`Using vars defined in ${devVarsRelativePath}`)
return {
...loaded.parsed,
}
} else {
return {}
}
}
16 changes: 16 additions & 0 deletions packages/dev-server/src/miniflare/dotenv.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import fs from 'node:fs'
import dotenv from 'dotenv'

export interface DotEnv {
path: string
parsed: dotenv.DotenvParseOutput
}

export function tryLoadDotEnv(path: string): DotEnv | undefined {
try {
const parsed = dotenv.parse(fs.readFileSync(path))
return { path, parsed }
} catch (e) {
console.error(`Failed to load .env file "${path}":`, e)
}
}
28 changes: 28 additions & 0 deletions packages/dev-server/src/miniflare/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { type PartialWorkerOptions } from './types/worker.js'
import { getWranglerWorkerOptions } from './wrangler.js'

const nullScript = 'export default { fetch: () => new Response(null, { status: 404 }) };'

export type PrepareMiniflareOptions = {
cf?: PartialWorkerOptions
wranglerTomlPath?: string
}

export const prepareMiniflare = async (options: PrepareMiniflareOptions) => {
const { Miniflare } = await import('miniflare')
const workerOptions: PartialWorkerOptions = options.cf ?? {}
workerOptions.bindings ??= {}
workerOptions.d1Databases ??= []

if (options.wranglerTomlPath !== undefined) {
const wranglerOptions = await getWranglerWorkerOptions(options.wranglerTomlPath)
Object.assign(workerOptions, wranglerOptions)
}

const mf = new Miniflare({
modules: true,
script: nullScript,
...workerOptions,
})
return mf
}
Loading