Skip to content

Commit 46a4537

Browse files
committed
Update and modernize adapter-cloudflare-workers
1 parent f0df782 commit 46a4537

File tree

11 files changed

+278
-153
lines changed

11 files changed

+278
-153
lines changed

.changeset/tidy-paws-rest.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@sveltejs/adapter-cloudflare-workers': patch
3+
---
4+
5+
Update adapter to use modules API and match the standard adapter-cloudflare implementation more closely
Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
.DS_Store
22
node_modules
3-
target
3+
target
4+
/files

packages/adapter-cloudflare-workers/README.md

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,19 @@ export default {
3333

3434
**You will need [Wrangler](https://developers.cloudflare.com/workers/cli-wrangler/install-update) installed on your system**
3535

36-
This adapter expects to find a [wrangler.toml](https://developers.cloudflare.com/workers/platform/sites/configuration) file in the project root. It will determine where to write static assets and the worker based on the `site.bucket` and `site.entry-point` settings.
36+
This adapter expects to find a [wrangler.toml](https://developers.cloudflare.com/workers/platform/sites/configuration) file in the project root. It will determine where to write static assets and the worker based on the `site.bucket` and `build.upload` settings. These values must be set to the following:
3737

38-
Generate this file using `wrangler` from your project directory
38+
```toml
39+
[build.upload]
40+
format = "modules"
41+
dir = "./.svelte-kit/cloudflare"
42+
main = "./_worker.mjs"
43+
44+
[site]
45+
bucket = "./.svelte-kit/cloudflare-bucket"
46+
```
47+
48+
To get started, generate this file using `wrangler` from your project directory
3949

4050
```sh
4151
wrangler init --site my-site-name
@@ -48,24 +58,31 @@ Now you should get some details from Cloudflare. You should get your:
4858

4959
Get them by visiting your [Cloudflare dashboard](https://dash.cloudflare.com) and click on any domain. There, you can scroll down and on the left, you can see your details under **API**.
5060

51-
Then configure your sites build directory and your account-details in the config file:
61+
Then configure your account-details in the config file:
5262

5363
```toml
54-
account_id = 'YOUR ACCOUNT_ID'
55-
zone_id = 'YOUR ZONE_ID' # optional, if you don't specify this a workers.dev subdomain will be used.
56-
site = {bucket = "./build", entry-point = "./workers-site"}
57-
64+
name = "<your-site-name>"
5865
type = "javascript"
66+
account_id = "<your-account-id>"
67+
workers_dev = true
68+
route = ""
69+
zone_id = ""
70+
71+
compatibility_date = "2022-02-09"
5972

6073
[build]
6174
# Assume it's already been built. You can make this "npm run build" to ensure a build before publishing
6275
command = ""
6376

77+
# All values below here are required by adapter-cloudflare-workers and should not change
6478
[build.upload]
65-
format = "service-worker"
66-
```
79+
format = "modules"
80+
dir = "./.svelte-kit/cloudflare"
81+
main = "./_worker.mjs"
6782

68-
It's recommended that you add the `build` and `workers-site` folders (or whichever other folders you specify) to your `.gitignore`.
83+
[site]
84+
bucket = "./.svelte-kit/cloudflare-bucket"
85+
```
6986

7087
Now, log in with wrangler:
7188

packages/adapter-cloudflare-workers/ambient.d.ts

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,10 @@ declare module 'MANIFEST' {
66
import { SSRManifest } from '@sveltejs/kit';
77

88
export const manifest: SSRManifest;
9-
export const prerendered: Set<string>;
9+
export const prerendered: Map<string, { file: string }>;
1010
}
1111

12-
declare abstract class FetchEvent extends Event {
13-
readonly request: Request;
14-
respondWith(promise: Response | Promise<Response>): void;
15-
passThroughOnException(): void;
16-
waitUntil(promise: Promise<any>): void;
12+
declare module '__STATIC_CONTENT_MANIFEST' {
13+
const value: string;
14+
export = value;
1715
}

packages/adapter-cloudflare-workers/files/entry.js

Lines changed: 0 additions & 61 deletions
This file was deleted.
Lines changed: 121 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,34 @@
11
import { existsSync, readFileSync, writeFileSync } from 'fs';
22
import { posix } from 'path';
33
import { execSync } from 'child_process';
4-
import esbuild from 'esbuild';
4+
import * as esbuild from 'esbuild';
55
import toml from '@iarna/toml';
66
import { fileURLToPath } from 'url';
77

88
/** @type {import('.')} */
9-
export default function () {
9+
export default function (options = {}) {
1010
return {
1111
name: '@sveltejs/adapter-cloudflare-workers',
12-
1312
async adapt(builder) {
14-
const { site } = validate_config(builder);
15-
16-
// @ts-ignore
17-
const { bucket } = site;
13+
validate_config(builder);
1814

1915
// @ts-ignore
20-
const entrypoint = site['entry-point'] || 'workers-site';
21-
2216
const files = fileURLToPath(new URL('./files', import.meta.url).href);
23-
const tmp = builder.getBuildDirectory('cloudflare-workers-tmp');
17+
const dest = builder.getBuildDirectory('cloudflare');
18+
const bucket = builder.getBuildDirectory('cloudflare-bucket');
19+
const tmp = builder.getBuildDirectory('cloudflare-tmp');
2420

21+
builder.rimraf(dest);
2522
builder.rimraf(bucket);
26-
builder.rimraf(entrypoint);
23+
builder.rimraf(tmp);
24+
25+
builder.mkdirp(tmp);
26+
27+
builder.writeStatic(bucket);
28+
builder.writeClient(bucket);
29+
builder.writePrerendered(bucket);
30+
31+
const relativePath = posix.relative(tmp, builder.getServerDirectory());
2732

2833
builder.log.info('Installing worker dependencies...');
2934
builder.copy(`${files}/_package.json`, `${tmp}/package.json`);
@@ -33,83 +38,130 @@ export default function () {
3338
builder.log.info(stdout.toString());
3439

3540
builder.log.minor('Generating worker...');
36-
const relativePath = posix.relative(tmp, builder.getServerDirectory());
37-
38-
builder.copy(`${files}/entry.js`, `${tmp}/entry.js`, {
39-
replace: {
40-
SERVER: `${relativePath}/index.js`,
41-
MANIFEST: './manifest.js'
42-
}
43-
});
4441

4542
writeFileSync(
4643
`${tmp}/manifest.js`,
4744
`export const manifest = ${builder.generateManifest({
4845
relativePath
49-
})};\n\nexport const prerendered = new Set(${JSON.stringify(builder.prerendered.paths)});\n`
46+
})};\n\nexport const prerendered = new Map(${JSON.stringify(
47+
Array.from(builder.prerendered.pages.entries())
48+
)});\n`
5049
);
5150

51+
builder.copy(`${files}/worker.js`, `${tmp}/_worker.js`, {
52+
replace: {
53+
SERVER: `${relativePath}/index.js`,
54+
MANIFEST: './manifest.js'
55+
}
56+
});
57+
5258
await esbuild.build({
53-
entryPoints: [`${tmp}/entry.js`],
54-
outfile: `${entrypoint}/index.js`,
55-
bundle: true,
5659
target: 'es2020',
57-
platform: 'browser'
60+
platform: 'browser',
61+
...options,
62+
entryPoints: [`${tmp}/_worker.js`],
63+
external: ['__STATIC_CONTENT_MANIFEST'],
64+
outfile: `${dest}/_worker.mjs`,
65+
allowOverwrite: true,
66+
format: 'esm',
67+
bundle: true
5868
});
59-
60-
writeFileSync(`${entrypoint}/package.json`, JSON.stringify({ main: 'index.js' }));
61-
62-
builder.log.minor('Copying assets...');
63-
builder.writeClient(bucket);
64-
builder.writeStatic(bucket);
65-
builder.writePrerendered(bucket);
6669
}
6770
};
6871
}
6972

7073
/** @param {import('@sveltejs/kit').Builder} builder */
7174
function validate_config(builder) {
72-
if (existsSync('wrangler.toml')) {
73-
let wrangler_config;
74-
75-
try {
76-
wrangler_config = toml.parse(readFileSync('wrangler.toml', 'utf-8'));
77-
} catch (err) {
78-
err.message = `Error parsing wrangler.toml: ${err.message}`;
79-
throw err;
80-
}
75+
if (!existsSync('wrangler.toml')) {
76+
builder.log.error(
77+
'Consult https://developers.cloudflare.com/workers/platform/sites/configuration on how to setup your site'
78+
);
79+
80+
builder.log(
81+
`
82+
Sample wrangler.toml:
83+
84+
name = "<your-site-name>"
85+
type = "javascript"
86+
account_id = "<your-account-id>"
87+
workers_dev = true
88+
route = ""
89+
zone_id = ""
90+
91+
compatibility_date = "2022-02-09"
92+
93+
[build]
94+
# Assume it's already been built. You can make this "npm run build" to ensure a build before publishing
95+
command = ""
96+
97+
# All values below here are required by adapter-cloudflare-workers and should not change
98+
[build.upload]
99+
format = "modules"
100+
dir = "./.svelte-kit/cloudflare"
101+
main = "./_worker.mjs"
102+
103+
[site]
104+
bucket = "./.svelte-kit/cloudflare-bucket"`
105+
.replace(/^\t+/gm, '')
106+
.trim()
107+
);
108+
109+
throw new Error('Missing a wrangler.toml file');
110+
}
111+
112+
let wrangler_config;
113+
114+
try {
115+
wrangler_config = toml.parse(readFileSync('wrangler.toml', 'utf-8'));
116+
} catch (err) {
117+
err.message = `Error parsing wrangler.toml: ${err.message}`;
118+
throw err;
119+
}
120+
121+
// @ts-ignore
122+
if (!wrangler_config.site || wrangler_config.site.bucket !== './.svelte-kit/cloudflare-bucket') {
123+
throw new Error(
124+
'You must specify site.bucket in wrangler.toml, and it must equal "./.svelte-kit/cloudflare-bucket"'
125+
);
126+
}
81127

128+
// @ts-ignore
129+
if (
82130
// @ts-ignore
83-
if (!wrangler_config.site || !wrangler_config.site.bucket) {
84-
throw new Error(
85-
'You must specify site.bucket in wrangler.toml. Consult https://developers.cloudflare.com/workers/platform/sites/configuration'
86-
);
87-
}
131+
!wrangler_config.build ||
132+
// @ts-ignore
133+
!wrangler_config.build.upload ||
134+
// @ts-ignore
135+
wrangler_config.build.upload.format !== 'module'
136+
) {
137+
throw new Error(
138+
'You must specify build.upload.format in wrangler.toml, and it must equal "modules"'
139+
);
140+
}
88141

89-
return wrangler_config;
142+
if (
143+
// @ts-ignore
144+
!wrangler_config.build ||
145+
// @ts-ignore
146+
!wrangler_config.build.upload ||
147+
// @ts-ignore
148+
wrangler_config.build.upload.dir !== './.svelte-kit/cloudflare'
149+
) {
150+
throw new Error(
151+
'You must specify build.upload.dir in wrangler.toml, and it must equal "./.svelte-kit/cloudflare"'
152+
);
90153
}
91154

92-
builder.log.error(
93-
'Consult https://developers.cloudflare.com/workers/platform/sites/configuration on how to setup your site'
94-
);
95-
96-
builder.log(
97-
`
98-
Sample wrangler.toml:
99-
100-
name = "<your-site-name>"
101-
type = "javascript"
102-
account_id = "<your-account-id>"
103-
workers_dev = true
104-
route = ""
105-
zone_id = ""
106-
107-
[site]
108-
bucket = "./.cloudflare/assets"
109-
entry-point = "./.cloudflare/worker"`
110-
.replace(/^\t+/gm, '')
111-
.trim()
112-
);
113-
114-
throw new Error('Missing a wrangler.toml file');
155+
if (
156+
// @ts-ignore
157+
!wrangler_config.build ||
158+
// @ts-ignore
159+
!wrangler_config.build.upload ||
160+
// @ts-ignore
161+
wrangler_config.build.upload.main !== './_worker.mjs'
162+
) {
163+
throw new Error(
164+
'You must specify build.upload.main in wrangler.toml, and it must equal "./_worker.mjs"'
165+
);
166+
}
115167
}

0 commit comments

Comments
 (0)