Skip to content
Merged
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
5 changes: 5 additions & 0 deletions .github/workflows/lint.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ jobs:
node-version: lts/*
cache: 'npm'

- name: Setup Deno
uses: denoland/setup-deno@v1
with:
deno-version: 2.2.4

- name: Install dependencies
run: npm ci --no-audit

Expand Down
4 changes: 4 additions & 0 deletions .github/workflows/publint.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ jobs:
with:
node-version: lts/*
cache: 'npm'
- name: Setup Deno
uses: denoland/setup-deno@v1
with:
deno-version: 2.2.4
- name: Install dependencies
run: npm ci
- name: Build
Expand Down
2 changes: 1 addition & 1 deletion eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export default tseslint.config(

// TODO: Move this to `edge-functions` package.
{
ignores: ['packages/**/deno'],
ignores: ['packages/**/deno', 'packages/edge-functions/bootstrap-bundle.mjs'],
},

// JavaScript-specific rules
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion packages/edge-functions/.gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
dist
dist-dev
dist-dev
dev/deno/bootstrap.mjs
15 changes: 15 additions & 0 deletions packages/edge-functions/bootstrap-bundle.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import * as esbuild from 'npm:esbuild'
import { denoPlugins } from 'jsr:@luca/esbuild-deno-loader@^0.11.1'

const [entryPoint, outfile] = Deno.args

await esbuild.build({
bundle: true,
entryPoints: [entryPoint],
format: 'esm',
minify: true,
outfile,
plugins: denoPlugins(),
})

await esbuild.stop()
6 changes: 2 additions & 4 deletions packages/edge-functions/dev/deno/invoke.mjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// @ts-check

/**
* @typedef {import('./workers/types.js').Message} Message
* @typedef {import('./workers/types.ts').Message} Message
*/

/**
Expand All @@ -10,11 +10,10 @@
* construct a `Response`.
*
* @param {Request} req
* @param {string} bootstrapURL
* @param {Record<string, string>} functions
* @param {number} requestTimeout
*/
export function invoke(req, bootstrapURL, functions, requestTimeout) {
export function invoke(req, functions, requestTimeout) {
return new Promise((resolve, reject) => {
const worker = new Worker(new URL('./workers/runner.mjs', import.meta.url).href, {
type: 'module',
Expand Down Expand Up @@ -43,7 +42,6 @@ export function invoke(req, bootstrapURL, functions, requestTimeout) {
type: 'request',
data: {
body: await req.arrayBuffer(),
bootstrapURL,
functions,
headers: Object.fromEntries(req.headers.entries()),
method: req.method,
Expand Down
10 changes: 5 additions & 5 deletions packages/edge-functions/dev/deno/server.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { invoke } from './invoke.mjs'
*
* @param {RunOptions} options
*/
export const serveLocal = ({ bootstrapURL, denoPort: port, requestTimeout }) => {
export const serveLocal = ({ denoPort: port, requestTimeout }) => {
const serveOptions = {
// Adding a no-op listener to avoid the default one, which prints a message
// we don't want.
Expand All @@ -37,11 +37,11 @@ export const serveLocal = ({ bootstrapURL, denoPort: port, requestTimeout }) =>
// the Deno server take a list of functions, import them, and return their
// configs.
if (method === 'NETLIFYCONFIG') {
const functionsParam = url.searchParams.get('functions')

// This is the list of all the functions found in the project.
/** @type {Record<string, string>} */
const availableFunctions = url.searchParams.has('functions')
? JSON.parse(decodeURIComponent(url.searchParams.get('functions')))
: {}
const availableFunctions = functionsParam ? JSON.parse(decodeURIComponent(functionsParam)) : {}

functions = availableFunctions

Expand All @@ -59,7 +59,7 @@ export const serveLocal = ({ bootstrapURL, denoPort: port, requestTimeout }) =>
}

try {
return await invoke(request, bootstrapURL, functions, requestTimeout)
return await invoke(request, functions, requestTimeout)
} catch (error) {
return getErrorResponse(error)
}
Expand Down
13 changes: 9 additions & 4 deletions packages/edge-functions/dev/deno/workers/config.mjs
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
// @ts-check
/// <reference lib="deno.worker" />

/**
* @typedef {import('../../shared/types.ts').SerializedError} SerializedError
* @typedef {import('./types.js').ConfigResponseMessage} ConfigResponseMessage
* @typedef {import('./types.ts').ConfigResponseMessage} ConfigResponseMessage
* @typedef {import('./types.ts').Message} Message
*/

self.onmessage = async (e) => {
/** @type {DedicatedWorkerGlobalScope} */
// @ts-ignore We are inside a worker, so the global scope is `DedicatedWorkerGlobalScope`.
const worker = globalThis

worker.addEventListener('message', async (e) => {
const message = /** @type {Message} */ (e.data)

if (message.type === 'configRequest') {
Expand Down Expand Up @@ -38,10 +43,10 @@ self.onmessage = async (e) => {

await Promise.allSettled(imports)

self.postMessage(/** @type {ConfigResponseMessage} */ ({ type: 'configResponse', data: { configs, errors } }))
worker.postMessage(/** @type {ConfigResponseMessage} */ ({ type: 'configResponse', data: { configs, errors } }))

return
}

throw new Error('Unsupported message')
}
})
28 changes: 18 additions & 10 deletions packages/edge-functions/dev/deno/workers/runner.mjs
Original file line number Diff line number Diff line change
@@ -1,21 +1,26 @@
// @ts-check
/// <reference lib="deno.worker" />
import { handleRequest } from '../bootstrap.mjs'

/**
* @typedef {import('./types.js').Message} Message
* @typedef {import('./types.js').RunResponseStartMessage} RunResponseStartMessage
* @typedef {import('./types.js').RunResponseChunkMessage} RunResponseChunkMessage
* @typedef {import('./types.js').RunResponseEndMessage} RunResponseEndMessage
* @typedef {import('./types.ts').Message} Message
* @typedef {import('./types.ts').RunResponseStartMessage} RunResponseStartMessage
* @typedef {import('./types.ts').RunResponseChunkMessage} RunResponseChunkMessage
* @typedef {import('./types.ts').RunResponseEndMessage} RunResponseEndMessage
*/

const consoleLog = globalThis.console.log
/** @type {Map<string, string>} */
const fetchRewrites = new Map()

self.onmessage = async (e) => {
/** @type {DedicatedWorkerGlobalScope} */
// @ts-ignore We are inside a worker, so the global scope is `DedicatedWorkerGlobalScope`.
const worker = globalThis

worker.addEventListener('message', async (e) => {
const message = /** @type {Message} */ (e.data)

if (message.type === 'request') {
const { handleRequest } = await import(message.data.bootstrapURL)
const body = message.data.method === 'GET' || message.data.method === 'HEAD' ? undefined : message.data.body
const req = new Request(message.data.url, {
body,
Expand All @@ -35,12 +40,14 @@ self.onmessage = async (e) => {
await Promise.allSettled(imports)

const res = await handleRequest(req, functions, {
// @ts-ignore TODO: Figure out why `fetchRewrites` is not being picked up
// as part of the type.
fetchRewrites,
rawLogger: consoleLog,
requestTimeout: message.data.timeout,
})

self.postMessage(
worker.postMessage(
/** @type {RunResponseStartMessage} */ ({
type: 'responseStart',
data: {
Expand All @@ -58,7 +65,8 @@ self.onmessage = async (e) => {
break
}

self.postMessage(
// @ts-expect-error TODO: Figure out type mismatch.
worker.postMessage(
/** @type {RunResponseChunkMessage} */ ({
type: 'responseChunk',
data: { chunk: value },
Expand All @@ -68,10 +76,10 @@ self.onmessage = async (e) => {
}
}

self.postMessage(/** @type {RunResponseEndMessage} */ ({ type: 'responseEnd' }))
worker.postMessage(/** @type {RunResponseEndMessage} */ ({ type: 'responseEnd' }))

return
}

throw new Error('Unsupported message')
}
})
1 change: 0 additions & 1 deletion packages/edge-functions/dev/deno/workers/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ export interface RunRequestMessage {
type: 'request'
data: {
body: ArrayBuffer
bootstrapURL: string
functions: Record<string, string>
headers: Record<string, string>
method: string
Expand Down
2 changes: 0 additions & 2 deletions packages/edge-functions/dev/node/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import {
EdgeFunction,
FunctionConfig,
} from '@netlify/edge-bundler'
import { getURL as getBootstrapURL } from '@netlify/edge-functions-bootstrap/version'
import { base64Encode } from '@netlify/runtime-utils'
import getAvailablePort from 'get-port'

Expand Down Expand Up @@ -272,7 +271,6 @@ export class EdgeFunctionsHandler {
versionRange: '^2.2.4',
})
const runOptions: RunOptions = {
bootstrapURL: await getBootstrapURL(),
denoPort,
requestTimeout: this.requestTimeout,
}
Expand Down
1 change: 0 additions & 1 deletion packages/edge-functions/dev/shared/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
export interface RunOptions {
bootstrapURL: string
denoPort: number
requestTimeout: number
}
Expand Down
1 change: 1 addition & 0 deletions packages/edge-functions/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
},
"devDependencies": {
"@netlify/types": "2.0.2",
"execa": "^8.0.1",
"tsup": "^8.0.0",
"vitest": "^3.0.0"
},
Expand Down
23 changes: 23 additions & 0 deletions packages/edge-functions/tsup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,14 @@ import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { argv } from 'node:process'

import { getURL } from '@netlify/edge-functions-bootstrap/version'
import { execa } from 'execa'
import { defineConfig } from 'tsup'

const __filename = fileURLToPath(import.meta.url)

const BOOTSTRAP_FILENAME = 'bootstrap.mjs'

export default defineConfig([
{
clean: true,
Expand Down Expand Up @@ -45,10 +49,29 @@ export default defineConfig([
// preserve the original structure, so that the relative path to the worker
// files is consistent.
onSuccess: async () => {
const bootstrapURL = await getURL()
const denoPath = path.resolve(path.dirname(__filename), 'dev', 'deno')
const distPath = path.resolve(path.dirname(__filename), 'dist-dev')

await fs.cp(denoPath, path.resolve(distPath, 'deno'), { recursive: true })

// We need to bundle the bootstrap layer with the package because Deno
// does not support HTTP imports when inside a `node_modukes` directory.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// does not support HTTP imports when inside a `node_modukes` directory.
// does not support HTTP imports when inside a `node_modules` directory.

const distBootstrapPath = path.resolve(distPath, 'deno', BOOTSTRAP_FILENAME)
await execa(
'deno',
['run', '--allow-all', '--no-lock', 'bootstrap-bundle.mjs', bootstrapURL, distBootstrapPath],
{
stdio: 'inherit',
},
)

// In addition to putting the bootstrap file in `dist-dev`, we must also
// put it in the source directory so that the reference to the bootstrap
// file still works in tests and local development. This is not great. At
// least we're gitignoring the file so that it doesn't end up in version
// control.
await fs.cp(distBootstrapPath, path.resolve(denoPath, BOOTSTRAP_FILENAME))
},
},
])
Loading