@astrojs/cloudflare 7.2.0 → 7.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +228 -94
- package/dist/{server.advanced.js → entrypoints/server.advanced.js} +1 -1
- package/dist/{server.directory.d.ts → entrypoints/server.directory.d.ts} +1 -1
- package/dist/{server.directory.js → entrypoints/server.directory.js} +1 -1
- package/dist/getAdapter.d.ts +5 -0
- package/dist/getAdapter.js +36 -0
- package/dist/index.d.ts +17 -7
- package/dist/index.js +112 -178
- package/dist/utils/deduplicatePatterns.d.ts +8 -0
- package/dist/utils/deduplicatePatterns.js +15 -0
- package/dist/utils/getCFObject.d.ts +2 -0
- package/dist/utils/getCFObject.js +68 -0
- package/dist/utils/prependForwardSlash.d.ts +1 -0
- package/dist/utils/prependForwardSlash.js +6 -0
- package/dist/utils/rewriteWasmImportPath.d.ts +8 -0
- package/dist/utils/rewriteWasmImportPath.js +25 -0
- package/dist/utils/wasm-module-loader.d.ts +14 -0
- package/dist/utils/wasm-module-loader.js +88 -0
- package/package.json +7 -12
- /package/dist/{server.advanced.d.ts → entrypoints/server.advanced.d.ts} +0 -0
- /package/dist/{parser.d.ts → utils/parser.d.ts} +0 -0
- /package/dist/{parser.js → utils/parser.js} +0 -0
package/README.md
CHANGED
|
@@ -25,77 +25,208 @@ npm install @astrojs/cloudflare
|
|
|
25
25
|
|
|
26
26
|
2. Add the following to your `astro.config.mjs` file:
|
|
27
27
|
|
|
28
|
-
```
|
|
29
|
-
// astro.config.mjs
|
|
30
|
-
import { defineConfig } from 'astro/config';
|
|
31
|
-
import cloudflare from '@astrojs/cloudflare';
|
|
32
|
-
|
|
33
|
-
export default defineConfig({
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
});
|
|
28
|
+
```diff lang="js"
|
|
29
|
+
// astro.config.mjs
|
|
30
|
+
import { defineConfig } from 'astro/config';
|
|
31
|
+
+ import cloudflare from '@astrojs/cloudflare';
|
|
32
|
+
|
|
33
|
+
export default defineConfig({
|
|
34
|
+
+ output: 'server',
|
|
35
|
+
+ adapter: cloudflare(),
|
|
36
|
+
});
|
|
37
37
|
```
|
|
38
38
|
|
|
39
39
|
## Options
|
|
40
40
|
|
|
41
|
-
###
|
|
41
|
+
### `mode`
|
|
42
42
|
|
|
43
43
|
`mode: "advanced" | "directory"`
|
|
44
44
|
|
|
45
45
|
default `"advanced"`
|
|
46
46
|
|
|
47
|
-
|
|
47
|
+
This configuration option defines how your Astro project is deployed to Cloudflare Pages.
|
|
48
48
|
|
|
49
|
-
|
|
49
|
+
- `advanced` mode picks up the `_worker.js` file in the `dist` folder
|
|
50
|
+
- `directory` mode picks up the files in the `functions` folder, by default only one `[[path]].js` file is generated
|
|
50
51
|
|
|
51
|
-
Switching to directory mode allows you to
|
|
52
|
+
Switching to directory mode allows you to add additional files manually such as [Cloudflare Pages Plugins](https://developers.cloudflare.com/pages/platform/functions/plugins/), [Cloudflare Pages Middleware](https://developers.cloudflare.com/pages/platform/functions/middleware/) or custom functions using [Cloudflare Pages Functions Routing](https://developers.cloudflare.com/pages/platform/functions/routing/).
|
|
52
53
|
|
|
53
|
-
```
|
|
54
|
+
```js
|
|
54
55
|
// astro.config.mjs
|
|
55
56
|
export default defineConfig({
|
|
56
57
|
adapter: cloudflare({ mode: 'directory' }),
|
|
57
58
|
});
|
|
58
59
|
```
|
|
59
60
|
|
|
60
|
-
|
|
61
|
+
To compile a separate bundle for each page, set the `functionPerRoute` option in your Cloudflare adapter config. This option requires some manual maintenance of the `functions` folder. Files emitted by Astro will overwrite existing files with identical names in the `functions` folder, so you must choose unique file names for each file you manually add. Additionally, the adapter will never empty the `functions` folder of outdated files, so you must clean up the folder manually when you remove pages.
|
|
62
|
+
|
|
63
|
+
```diff lang="js"
|
|
64
|
+
// astro.config.mjs
|
|
65
|
+
import {defineConfig} from "astro/config";
|
|
66
|
+
import cloudflare from '@astrojs/cloudflare';
|
|
67
|
+
|
|
68
|
+
export default defineConfig({
|
|
69
|
+
adapter: cloudflare({
|
|
70
|
+
mode: 'directory',
|
|
71
|
+
+ functionPerRoute: true
|
|
72
|
+
})
|
|
73
|
+
})
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
This adapter doesn't support the [`edgeMiddleware`](https://docs.astro.build/en/reference/adapter-reference/#edgemiddleware) option.
|
|
77
|
+
|
|
78
|
+
### `routes.strategy`
|
|
79
|
+
|
|
80
|
+
`routes.strategy: "auto" | "include" | "exclude"`
|
|
81
|
+
|
|
82
|
+
default `"auto"`
|
|
83
|
+
|
|
84
|
+
Determines how `routes.json` will be generated if no [custom `_routes.json`](#custom-_routesjson) is provided.
|
|
85
|
+
|
|
86
|
+
There are three options available:
|
|
87
|
+
|
|
88
|
+
- **`"auto"` (default):** Will automatically select the strategy that generates the fewest entries. This should almost always be sufficient, so choose this option unless you have a specific reason not to.
|
|
89
|
+
|
|
90
|
+
- **`include`:** Pages and endpoints that are not pre-rendered are listed as `include` entries, telling Cloudflare to invoke these routes as functions. `exclude` entries are only used to resolve conflicts. Usually the best strategy when your website has mostly static pages and only a few dynamic pages or endpoints.
|
|
91
|
+
|
|
92
|
+
Example: For `src/pages/index.astro` (static), `src/pages/company.astro` (static), `src/pages/users/faq.astro` (static) and `/src/pages/users/[id].astro` (SSR) this will produce the following `_routes.json`:
|
|
93
|
+
|
|
94
|
+
```json
|
|
95
|
+
{
|
|
96
|
+
"version": 1,
|
|
97
|
+
"include": [
|
|
98
|
+
"/_image", // Astro's image endpoint
|
|
99
|
+
"/users/*" // Dynamic route
|
|
100
|
+
],
|
|
101
|
+
"exclude": [
|
|
102
|
+
// Static routes that needs to be exempted from the dynamic wildcard route above
|
|
103
|
+
"/users/faq/",
|
|
104
|
+
"/users/faq/index.html"
|
|
105
|
+
]
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
- **`exclude`:** Pre-rendered pages are listed as `exclude` entries (telling Cloudflare to handle these routes as static assets). Usually the best strategy when your website has mostly dynamic pages or endpoints and only a few static pages.
|
|
110
|
+
|
|
111
|
+
Example: For the same pages as in the previous example this will produce the following `_routes.json`:
|
|
112
|
+
|
|
113
|
+
```json
|
|
114
|
+
{
|
|
115
|
+
"version": 1,
|
|
116
|
+
"include": [
|
|
117
|
+
"/*" // Handle everything as function except the routes below
|
|
118
|
+
],
|
|
119
|
+
"exclude": [
|
|
120
|
+
// All static assets
|
|
121
|
+
"/",
|
|
122
|
+
"/company/",
|
|
123
|
+
"/index.html",
|
|
124
|
+
"/users/faq/",
|
|
125
|
+
"/favicon.png",
|
|
126
|
+
"/company/index.html",
|
|
127
|
+
"/users/faq/index.html"
|
|
128
|
+
]
|
|
129
|
+
}
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
### `routes.include`
|
|
133
|
+
|
|
134
|
+
`routes.include: string[]`
|
|
135
|
+
|
|
136
|
+
default `[]`
|
|
137
|
+
|
|
138
|
+
If you want to use the automatic `_routes.json` generation, but want to include additional routes (e.g. when having custom functions in the `functions` folder), you can use the `routes.include` option to add additional routes to the `include` array.
|
|
139
|
+
|
|
140
|
+
### `routes.exclude`
|
|
141
|
+
|
|
142
|
+
`routes.exclude: string[]`
|
|
143
|
+
|
|
144
|
+
default `[]`
|
|
145
|
+
|
|
146
|
+
If you want to use the automatic `_routes.json` generation, but want to exclude additional routes, you can use the `routes.exclude` option to add additional routes to the `exclude` array.
|
|
147
|
+
|
|
148
|
+
The following example automatically generates `_routes.json` while including and excluding additional routes. Note that that is only necessary if you have custom functions in the `functions` folder that are not handled by Astro.
|
|
149
|
+
|
|
150
|
+
```diff lang="js"
|
|
151
|
+
// astro.config.mjs
|
|
152
|
+
export default defineConfig({
|
|
153
|
+
adapter: cloudflare({
|
|
154
|
+
mode: 'directory',
|
|
155
|
+
+ routes: {
|
|
156
|
+
+ strategy: 'include',
|
|
157
|
+
+ include: ['/users/*'], // handled by custom function: functions/users/[id].js
|
|
158
|
+
+ exclude: ['/users/faq'], // handled by static page: pages/users/faq.astro
|
|
159
|
+
+ },
|
|
160
|
+
}),
|
|
161
|
+
});
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
### `wasmModuleImports`
|
|
165
|
+
|
|
166
|
+
`wasmModuleImports: boolean`
|
|
167
|
+
|
|
168
|
+
default: `false`
|
|
61
169
|
|
|
62
|
-
|
|
170
|
+
Whether or not to import `.wasm` files [directly as ES modules](https://github.com/WebAssembly/esm-integration/tree/main/proposals/esm-integration) using the `.wasm?module` import syntax.
|
|
63
171
|
|
|
64
|
-
|
|
172
|
+
Add `wasmModuleImports: true` to `astro.config.mjs` to enable this functionality in both the Cloudflare build and the Astro dev server. [Read more](#use-wasm-modules)
|
|
173
|
+
|
|
174
|
+
```diff lang="js"
|
|
175
|
+
// astro.config.mjs
|
|
65
176
|
import {defineConfig} from "astro/config";
|
|
66
177
|
import cloudflare from '@astrojs/cloudflare';
|
|
67
178
|
|
|
68
179
|
export default defineConfig({
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
180
|
+
adapter: cloudflare({
|
|
181
|
+
+ wasmModuleImports: true
|
|
182
|
+
}),
|
|
183
|
+
output: 'server'
|
|
73
184
|
})
|
|
74
185
|
```
|
|
75
186
|
|
|
76
|
-
|
|
187
|
+
### `runtime`
|
|
77
188
|
|
|
78
|
-
|
|
189
|
+
`runtime: "off" | "local" | "remote"`
|
|
79
190
|
|
|
80
|
-
|
|
191
|
+
default `"off"`
|
|
81
192
|
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
193
|
+
Determines whether and how the Cloudflare Runtime is added to `astro dev`.
|
|
194
|
+
|
|
195
|
+
The Cloudflare Runtime includes [Cloudflare bindings](https://developers.cloudflare.com/pages/platform/functions/bindings), [environment variables](https://developers.cloudflare.com/pages/platform/functions/bindings/#environment-variables), and the [cf object](https://developers.cloudflare.com/workers/runtime-apis/request/#incomingrequestcfproperties). Read more about [accessing the Cloudflare Runtime](#access-to-the-cloudflare-runtime).
|
|
196
|
+
|
|
197
|
+
- `local`: uses bindings mocking and locally static placeholdes
|
|
198
|
+
- `remote`: uses remote bindings and a live fetched cf object
|
|
199
|
+
- `off`: no access to the Cloudflare runtime using `astro dev`. You can alternatively use [Preview with Wrangler](#preview-with-wrangler)
|
|
85
200
|
|
|
86
|
-
|
|
201
|
+
```diff lang="js"
|
|
202
|
+
// astro.config.mjs
|
|
203
|
+
import { defineConfig } from 'astro/config';
|
|
204
|
+
import cloudflare from '@astrojs/cloudflare';
|
|
205
|
+
|
|
206
|
+
export default defineConfig({
|
|
207
|
+
output: 'server',
|
|
208
|
+
adapter: cloudflare({
|
|
209
|
+
+ runtime: 'local',
|
|
210
|
+
}),
|
|
211
|
+
});
|
|
212
|
+
```
|
|
87
213
|
|
|
88
|
-
##
|
|
214
|
+
## Cloudflare runtime
|
|
89
215
|
|
|
90
|
-
|
|
216
|
+
Gives you access to [environment variables](https://developers.cloudflare.com/pages/platform/functions/bindings/#environment-variables).
|
|
91
217
|
|
|
92
|
-
|
|
218
|
+
You can access the runtime from Astro components through `Astro.locals` inside any .astro` file.
|
|
93
219
|
|
|
94
220
|
```astro
|
|
95
|
-
|
|
221
|
+
---
|
|
222
|
+
// src/pages/index.astro
|
|
223
|
+
const runtime = Astro.locals.runtime;
|
|
224
|
+
---
|
|
225
|
+
|
|
226
|
+
<pre>{JSON.stringify(runtime.env)}</pre>
|
|
96
227
|
```
|
|
97
228
|
|
|
98
|
-
|
|
229
|
+
You can access the runtime from API endpoints through `context.locals`:
|
|
99
230
|
|
|
100
231
|
```js
|
|
101
232
|
// src/pages/api/someFile.js
|
|
@@ -106,21 +237,24 @@ export function GET(context) {
|
|
|
106
237
|
}
|
|
107
238
|
```
|
|
108
239
|
|
|
109
|
-
|
|
240
|
+
### Typing
|
|
110
241
|
|
|
111
|
-
If you
|
|
242
|
+
If you have configured `mode: advanced`, you can type the `runtime` object using `AdvancedRuntime`:
|
|
112
243
|
|
|
113
244
|
```ts
|
|
114
245
|
// src/env.d.ts
|
|
115
246
|
/// <reference types="astro/client" />
|
|
116
|
-
import type { AdvancedRuntime } from '@astrojs/cloudflare';
|
|
117
247
|
|
|
248
|
+
type KVNamespace = import('@cloudflare/workers-types/experimental').KVNamespace;
|
|
118
249
|
type ENV = {
|
|
119
250
|
SERVER_URL: string;
|
|
251
|
+
KV_BINDING: KVNamespace;
|
|
120
252
|
};
|
|
121
253
|
|
|
254
|
+
type Runtime = import('@astrojs/cloudflare').AdvancedRuntime<ENV>;
|
|
255
|
+
|
|
122
256
|
declare namespace App {
|
|
123
|
-
interface Locals extends
|
|
257
|
+
interface Locals extends Runtime {
|
|
124
258
|
user: {
|
|
125
259
|
name: string;
|
|
126
260
|
surname: string;
|
|
@@ -129,19 +263,22 @@ declare namespace App {
|
|
|
129
263
|
}
|
|
130
264
|
```
|
|
131
265
|
|
|
132
|
-
If you
|
|
266
|
+
If you have configured `mode: directory`, you can type the `runtime` object using `DirectoryRuntime`:
|
|
133
267
|
|
|
134
268
|
```ts
|
|
135
269
|
// src/env.d.ts
|
|
136
270
|
/// <reference types="astro/client" />
|
|
137
|
-
import type { DirectoryRuntime } from '@astrojs/cloudflare';
|
|
138
271
|
|
|
272
|
+
type KVNamespace = import('@cloudflare/workers-types/experimental').KVNamespace;
|
|
139
273
|
type ENV = {
|
|
140
274
|
SERVER_URL: string;
|
|
275
|
+
KV_BINDING: KVNamespace;
|
|
141
276
|
};
|
|
142
277
|
|
|
278
|
+
type Runtime = import('@astrojs/cloudflare').DirectoryRuntime<ENV>;
|
|
279
|
+
|
|
143
280
|
declare namespace App {
|
|
144
|
-
interface Locals extends
|
|
281
|
+
interface Locals extends Runtime {
|
|
145
282
|
user: {
|
|
146
283
|
name: string;
|
|
147
284
|
surname: string;
|
|
@@ -150,57 +287,44 @@ declare namespace App {
|
|
|
150
287
|
}
|
|
151
288
|
```
|
|
152
289
|
|
|
153
|
-
|
|
290
|
+
## Platform
|
|
154
291
|
|
|
155
|
-
|
|
292
|
+
### Headers
|
|
156
293
|
|
|
157
|
-
|
|
158
|
-
// pages/[id].json.js
|
|
159
|
-
|
|
160
|
-
export function GET({ params }) {
|
|
161
|
-
// Access environment variables per request inside a function
|
|
162
|
-
const serverUrl = import.meta.env.SERVER_URL;
|
|
163
|
-
const result = await fetch(serverUrl + "/user/" + params.id);
|
|
164
|
-
return {
|
|
165
|
-
body: await result.text(),
|
|
166
|
-
};
|
|
167
|
-
}
|
|
168
|
-
```
|
|
294
|
+
You can attach [custom headers](https://developers.cloudflare.com/pages/platform/headers/) to your responses by adding a `_headers` file in your Astro project's `public/` folder. This file will be copied to your build output directory.
|
|
169
295
|
|
|
170
|
-
###
|
|
296
|
+
### Redirects
|
|
171
297
|
|
|
172
|
-
`
|
|
173
|
-
default `"off"`
|
|
298
|
+
You can declare [custom redirects](https://developers.cloudflare.com/pages/platform/redirects/) using Cloudflare Pages. This allows you to redirect requests to a different URL. You can add a `_redirects` file in your Astro project's `public/` folder. This file will be copied to your build output directory.
|
|
174
299
|
|
|
175
|
-
|
|
300
|
+
### Routes
|
|
176
301
|
|
|
177
|
-
|
|
178
|
-
- `remote`: environment variables and the live, fetched request object are available.
|
|
179
|
-
- `off`: the Astro dev server will populate neither environment variables nor the request object. Use Wrangler to access Cloudflare bindings and environment variables.
|
|
302
|
+
You can define which routes are invoking functions and which are static assets, using [Cloudflare routing](https://developers.cloudflare.com/pages/platform/functions/routing/#functions-invocation-routes) via a `_routes.json` file. This file is automatically generated by Astro.
|
|
180
303
|
|
|
181
|
-
|
|
182
|
-
// astro.config.mjs
|
|
183
|
-
import { defineConfig } from 'astro/config';
|
|
184
|
-
import cloudflare from '@astrojs/cloudflare';
|
|
304
|
+
#### Custom `_routes.json`
|
|
185
305
|
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
}),
|
|
191
|
-
});
|
|
192
|
-
```
|
|
306
|
+
By default, `@astrojs/cloudflare` will generate a `_routes.json` file with `include` and `exclude` rules based on your applications's dynamic and static routes.
|
|
307
|
+
This will enable Cloudflare to serve files and process static redirects without a function invocation. Creating a custom `_routes.json` will override this automatic optimization. See [Cloudflare's documentation on creating a custom `routes.json`](https://developers.cloudflare.com/pages/platform/functions/routing/#create-a-_routesjson-file) for more details.
|
|
308
|
+
|
|
309
|
+
## Use Wasm modules
|
|
193
310
|
|
|
194
|
-
|
|
311
|
+
The following is an example of importing a Wasm module that then responds to requests by adding the request's number parameters together.
|
|
195
312
|
|
|
196
|
-
|
|
313
|
+
```js
|
|
314
|
+
// pages/add/[a]/[b].js
|
|
315
|
+
import mod from '../util/add.wasm?module';
|
|
197
316
|
|
|
198
|
-
|
|
317
|
+
// instantiate ahead of time to share module
|
|
318
|
+
const addModule: any = new WebAssembly.Instance(mod);
|
|
199
319
|
|
|
200
|
-
|
|
201
|
-
|
|
320
|
+
export async function GET(context) {
|
|
321
|
+
const a = Number.parseInt(context.params.a);
|
|
322
|
+
const b = Number.parseInt(context.params.b);
|
|
323
|
+
return new Response(`${addModule.exports.add(a, b)}`);
|
|
324
|
+
}
|
|
325
|
+
```
|
|
202
326
|
|
|
203
|
-
|
|
327
|
+
While this example is trivial, Wasm can be used to accelerate computationally intensive operations which do not involve significant I/O such as embedding an image processing library.
|
|
204
328
|
|
|
205
329
|
## Node.js compatibility
|
|
206
330
|
|
|
@@ -225,33 +349,43 @@ export const prerender = false;
|
|
|
225
349
|
import { Buffer } from 'node:buffer';
|
|
226
350
|
```
|
|
227
351
|
|
|
228
|
-
Additionally, you'll need to enable the Compatibility Flag in Cloudflare. The configuration for this flag may vary based on where you deploy your Astro site.
|
|
352
|
+
Additionally, you'll need to enable the Compatibility Flag in Cloudflare. The configuration for this flag may vary based on where you deploy your Astro site. For detailed guidance, please refer to the [Cloudflare documentation on enabling Node.js compatibility](https://developers.cloudflare.com/workers/runtime-apis/nodejs).
|
|
229
353
|
|
|
230
|
-
|
|
354
|
+
## Preview with Wrangler
|
|
231
355
|
|
|
232
|
-
|
|
356
|
+
To use [`wrangler`](https://developers.cloudflare.com/workers/wrangler/) to run your application locally, update the preview script:
|
|
233
357
|
|
|
234
|
-
|
|
358
|
+
```json
|
|
359
|
+
//package.json
|
|
360
|
+
"preview": "wrangler pages dev ./dist"
|
|
361
|
+
```
|
|
235
362
|
|
|
236
|
-
|
|
363
|
+
[`wrangler`](https://developers.cloudflare.com/workers/wrangler/) gives you access to [Cloudflare bindings](https://developers.cloudflare.com/pages/platform/functions/bindings), [environment variables](https://developers.cloudflare.com/pages/platform/functions/bindings/#environment-variables), and the [cf object](https://developers.cloudflare.com/workers/runtime-apis/request/#incomingrequestcfproperties). Getting hot reloading or the astro dev server to work with Wrangler might require custom setup. See [community examples](https://github.com/withastro/roadmap/discussions/590).
|
|
237
364
|
|
|
238
365
|
### Meaningful error messages
|
|
239
366
|
|
|
240
|
-
Currently, errors during running your application in Wrangler are not very useful, due to the minification of your code. For better debugging, you can add `vite.build.minify = false` setting to your `astro.config.
|
|
367
|
+
Currently, errors during running your application in Wrangler are not very useful, due to the minification of your code. For better debugging, you can add `vite.build.minify = false` setting to your `astro.config.mjs`.
|
|
241
368
|
|
|
242
|
-
```js
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
369
|
+
```diff lang="js"
|
|
370
|
+
// astro.config.mjs
|
|
371
|
+
export default defineConfig({
|
|
372
|
+
adapter: cloudflare(),
|
|
373
|
+
output: 'server',
|
|
246
374
|
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
});
|
|
375
|
+
+ vite: {
|
|
376
|
+
+ build: {
|
|
377
|
+
+ minify: false,
|
|
378
|
+
+ },
|
|
379
|
+
+ },
|
|
380
|
+
});
|
|
253
381
|
```
|
|
254
382
|
|
|
383
|
+
## Troubleshooting
|
|
384
|
+
|
|
385
|
+
For help, check out the `#support` channel on [Discord](https://astro.build/chat). Our friendly Support Squad members are here to help!
|
|
386
|
+
|
|
387
|
+
You can also check our [Astro Integration Documentation][astro-integration] for more on integrations.
|
|
388
|
+
|
|
255
389
|
## Contributing
|
|
256
390
|
|
|
257
391
|
This package is maintained by Astro's Core team. You're welcome to submit an issue or PR!
|
|
@@ -9,6 +9,6 @@ export interface DirectoryRuntime<T extends object = object> {
|
|
|
9
9
|
};
|
|
10
10
|
}
|
|
11
11
|
export declare function createExports(manifest: SSRManifest): {
|
|
12
|
-
onRequest: (context: EventContext<unknown, string, unknown>) => Promise<import("@cloudflare/workers-types").Response
|
|
12
|
+
onRequest: (context: EventContext<unknown, string, unknown>) => Promise<Response | import("@cloudflare/workers-types").Response>;
|
|
13
13
|
manifest: SSRManifest;
|
|
14
14
|
};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
function getAdapter({
|
|
2
|
+
isModeDirectory,
|
|
3
|
+
functionPerRoute
|
|
4
|
+
}) {
|
|
5
|
+
const astroFeatures = {
|
|
6
|
+
hybridOutput: "stable",
|
|
7
|
+
staticOutput: "unsupported",
|
|
8
|
+
serverOutput: "stable",
|
|
9
|
+
assets: {
|
|
10
|
+
supportKind: "stable",
|
|
11
|
+
isSharpCompatible: false,
|
|
12
|
+
isSquooshCompatible: false
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
if (isModeDirectory) {
|
|
16
|
+
return {
|
|
17
|
+
name: "@astrojs/cloudflare",
|
|
18
|
+
serverEntrypoint: "@astrojs/cloudflare/entrypoints/server.directory.js",
|
|
19
|
+
exports: ["onRequest", "manifest"],
|
|
20
|
+
adapterFeatures: {
|
|
21
|
+
functionPerRoute,
|
|
22
|
+
edgeMiddleware: false
|
|
23
|
+
},
|
|
24
|
+
supportedAstroFeatures: astroFeatures
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
return {
|
|
28
|
+
name: "@astrojs/cloudflare",
|
|
29
|
+
serverEntrypoint: "@astrojs/cloudflare/entrypoints/server.advanced.js",
|
|
30
|
+
exports: ["default"],
|
|
31
|
+
supportedAstroFeatures: astroFeatures
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
export {
|
|
35
|
+
getAdapter
|
|
36
|
+
};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,18 +1,28 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
export type { AdvancedRuntime } from './server.advanced.js';
|
|
3
|
-
export type { DirectoryRuntime } from './server.directory.js';
|
|
1
|
+
import type { AstroIntegration } from 'astro';
|
|
2
|
+
export type { AdvancedRuntime } from './entrypoints/server.advanced.js';
|
|
3
|
+
export type { DirectoryRuntime } from './entrypoints/server.directory.js';
|
|
4
4
|
type Options = {
|
|
5
5
|
mode?: 'directory' | 'advanced';
|
|
6
6
|
functionPerRoute?: boolean;
|
|
7
|
+
/** Configure automatic `routes.json` generation */
|
|
8
|
+
routes?: {
|
|
9
|
+
/** Strategy for generating `include` and `exclude` patterns
|
|
10
|
+
* - `auto`: Will use the strategy that generates the least amount of entries.
|
|
11
|
+
* - `include`: For each page or endpoint in your application that is not prerendered, an entry in the `include` array will be generated. For each page that is prerendered and whoose path is matched by an `include` entry, an entry in the `exclude` array will be generated.
|
|
12
|
+
* - `exclude`: One `"/*"` entry in the `include` array will be generated. For each page that is prerendered, an entry in the `exclude` array will be generated.
|
|
13
|
+
* */
|
|
14
|
+
strategy?: 'auto' | 'include' | 'exclude';
|
|
15
|
+
/** Additional `include` patterns */
|
|
16
|
+
include?: string[];
|
|
17
|
+
/** Additional `exclude` patterns */
|
|
18
|
+
exclude?: string[];
|
|
19
|
+
};
|
|
7
20
|
/**
|
|
8
21
|
* 'off': current behaviour (wrangler is needed)
|
|
9
22
|
* 'local': use a static req.cf object, and env vars defined in wrangler.toml & .dev.vars (astro dev is enough)
|
|
10
23
|
* 'remote': use a dynamic real-live req.cf object, and env vars defined in wrangler.toml & .dev.vars (astro dev is enough)
|
|
11
24
|
*/
|
|
12
25
|
runtime?: 'off' | 'local' | 'remote';
|
|
26
|
+
wasmModuleImports?: boolean;
|
|
13
27
|
};
|
|
14
|
-
export declare function getAdapter({ isModeDirectory, functionPerRoute, }: {
|
|
15
|
-
isModeDirectory: boolean;
|
|
16
|
-
functionPerRoute: boolean;
|
|
17
|
-
}): AstroAdapter;
|
|
18
28
|
export default function createIntegration(args?: Options): AstroIntegration;
|
package/dist/index.js
CHANGED
|
@@ -6,10 +6,16 @@ import { AstroError } from "astro/errors";
|
|
|
6
6
|
import esbuild from "esbuild";
|
|
7
7
|
import * as fs from "node:fs";
|
|
8
8
|
import * as os from "node:os";
|
|
9
|
-
import { sep } from "node:path";
|
|
9
|
+
import { dirname, relative, sep } from "node:path";
|
|
10
10
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
11
11
|
import glob from "tiny-glob";
|
|
12
|
-
import {
|
|
12
|
+
import { getAdapter } from "./getAdapter.js";
|
|
13
|
+
import { deduplicatePatterns } from "./utils/deduplicatePatterns.js";
|
|
14
|
+
import { getCFObject } from "./utils/getCFObject.js";
|
|
15
|
+
import { getEnvVars } from "./utils/parser.js";
|
|
16
|
+
import { prependForwardSlash } from "./utils/prependForwardSlash.js";
|
|
17
|
+
import { rewriteWasmImportPath } from "./utils/rewriteWasmImportPath.js";
|
|
18
|
+
import { wasmModuleLoader } from "./utils/wasm-module-loader.js";
|
|
13
19
|
class StorageFactory {
|
|
14
20
|
storages = /* @__PURE__ */ new Map();
|
|
15
21
|
storage(namespace) {
|
|
@@ -20,119 +26,11 @@ class StorageFactory {
|
|
|
20
26
|
return storage;
|
|
21
27
|
}
|
|
22
28
|
}
|
|
23
|
-
function getAdapter({
|
|
24
|
-
isModeDirectory,
|
|
25
|
-
functionPerRoute
|
|
26
|
-
}) {
|
|
27
|
-
return isModeDirectory ? {
|
|
28
|
-
name: "@astrojs/cloudflare",
|
|
29
|
-
serverEntrypoint: "@astrojs/cloudflare/server.directory.js",
|
|
30
|
-
exports: ["onRequest", "manifest"],
|
|
31
|
-
adapterFeatures: {
|
|
32
|
-
functionPerRoute,
|
|
33
|
-
edgeMiddleware: false
|
|
34
|
-
},
|
|
35
|
-
supportedAstroFeatures: {
|
|
36
|
-
hybridOutput: "stable",
|
|
37
|
-
staticOutput: "unsupported",
|
|
38
|
-
serverOutput: "stable",
|
|
39
|
-
assets: {
|
|
40
|
-
supportKind: "stable",
|
|
41
|
-
isSharpCompatible: false,
|
|
42
|
-
isSquooshCompatible: false
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
} : {
|
|
46
|
-
name: "@astrojs/cloudflare",
|
|
47
|
-
serverEntrypoint: "@astrojs/cloudflare/server.advanced.js",
|
|
48
|
-
exports: ["default"],
|
|
49
|
-
supportedAstroFeatures: {
|
|
50
|
-
hybridOutput: "stable",
|
|
51
|
-
staticOutput: "unsupported",
|
|
52
|
-
serverOutput: "stable",
|
|
53
|
-
assets: {
|
|
54
|
-
supportKind: "stable",
|
|
55
|
-
isSharpCompatible: false,
|
|
56
|
-
isSquooshCompatible: false
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
};
|
|
60
|
-
}
|
|
61
|
-
async function getCFObject(runtimeMode) {
|
|
62
|
-
const CF_ENDPOINT = "https://workers.cloudflare.com/cf.json";
|
|
63
|
-
const CF_FALLBACK = {
|
|
64
|
-
asOrganization: "",
|
|
65
|
-
asn: 395747,
|
|
66
|
-
colo: "DFW",
|
|
67
|
-
city: "Austin",
|
|
68
|
-
region: "Texas",
|
|
69
|
-
regionCode: "TX",
|
|
70
|
-
metroCode: "635",
|
|
71
|
-
postalCode: "78701",
|
|
72
|
-
country: "US",
|
|
73
|
-
continent: "NA",
|
|
74
|
-
timezone: "America/Chicago",
|
|
75
|
-
latitude: "30.27130",
|
|
76
|
-
longitude: "-97.74260",
|
|
77
|
-
clientTcpRtt: 0,
|
|
78
|
-
httpProtocol: "HTTP/1.1",
|
|
79
|
-
requestPriority: "weight=192;exclusive=0",
|
|
80
|
-
tlsCipher: "AEAD-AES128-GCM-SHA256",
|
|
81
|
-
tlsVersion: "TLSv1.3",
|
|
82
|
-
tlsClientAuth: {
|
|
83
|
-
certPresented: "0",
|
|
84
|
-
certVerified: "NONE",
|
|
85
|
-
certRevoked: "0",
|
|
86
|
-
certIssuerDN: "",
|
|
87
|
-
certSubjectDN: "",
|
|
88
|
-
certIssuerDNRFC2253: "",
|
|
89
|
-
certSubjectDNRFC2253: "",
|
|
90
|
-
certIssuerDNLegacy: "",
|
|
91
|
-
certSubjectDNLegacy: "",
|
|
92
|
-
certSerial: "",
|
|
93
|
-
certIssuerSerial: "",
|
|
94
|
-
certSKI: "",
|
|
95
|
-
certIssuerSKI: "",
|
|
96
|
-
certFingerprintSHA1: "",
|
|
97
|
-
certFingerprintSHA256: "",
|
|
98
|
-
certNotBefore: "",
|
|
99
|
-
certNotAfter: ""
|
|
100
|
-
},
|
|
101
|
-
edgeRequestKeepAliveStatus: 0,
|
|
102
|
-
hostMetadata: void 0,
|
|
103
|
-
clientTrustScore: 99,
|
|
104
|
-
botManagement: {
|
|
105
|
-
corporateProxy: false,
|
|
106
|
-
verifiedBot: false,
|
|
107
|
-
ja3Hash: "25b4882c2bcb50cd6b469ff28c596742",
|
|
108
|
-
staticResource: false,
|
|
109
|
-
detectionIds: [],
|
|
110
|
-
score: 99
|
|
111
|
-
}
|
|
112
|
-
};
|
|
113
|
-
if (runtimeMode === "local") {
|
|
114
|
-
return CF_FALLBACK;
|
|
115
|
-
} else if (runtimeMode === "remote") {
|
|
116
|
-
try {
|
|
117
|
-
const res = await fetch(CF_ENDPOINT);
|
|
118
|
-
const cfText = await res.text();
|
|
119
|
-
const storedCf = JSON.parse(cfText);
|
|
120
|
-
return storedCf;
|
|
121
|
-
} catch (e) {
|
|
122
|
-
return CF_FALLBACK;
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
const SHIM = `globalThis.process = {
|
|
127
|
-
argv: [],
|
|
128
|
-
env: {},
|
|
129
|
-
};`;
|
|
130
|
-
const SERVER_BUILD_FOLDER = "/$server_build/";
|
|
131
|
-
const potentialFunctionRouteTypes = ["endpoint", "page"];
|
|
132
29
|
function createIntegration(args) {
|
|
133
30
|
let _config;
|
|
134
31
|
let _buildConfig;
|
|
135
32
|
let _entryPoints = /* @__PURE__ */ new Map();
|
|
33
|
+
const SERVER_BUILD_FOLDER = "/$server_build/";
|
|
136
34
|
const isModeDirectory = args?.mode === "directory";
|
|
137
35
|
const functionPerRoute = args?.functionPerRoute ?? false;
|
|
138
36
|
const runtimeMode = args?.runtime ?? "off";
|
|
@@ -146,6 +44,15 @@ function createIntegration(args) {
|
|
|
146
44
|
server: new URL(`.${SERVER_BUILD_FOLDER}`, config.outDir),
|
|
147
45
|
serverEntry: "_worker.mjs",
|
|
148
46
|
redirects: false
|
|
47
|
+
},
|
|
48
|
+
vite: {
|
|
49
|
+
// load .wasm files as WebAssembly modules
|
|
50
|
+
plugins: [
|
|
51
|
+
wasmModuleLoader({
|
|
52
|
+
disabled: !args?.wasmModuleImports,
|
|
53
|
+
assetsDirectory: config.build.assets
|
|
54
|
+
})
|
|
55
|
+
]
|
|
149
56
|
}
|
|
150
57
|
});
|
|
151
58
|
},
|
|
@@ -153,12 +60,12 @@ function createIntegration(args) {
|
|
|
153
60
|
setAdapter(getAdapter({ isModeDirectory, functionPerRoute }));
|
|
154
61
|
_config = config;
|
|
155
62
|
_buildConfig = config.build;
|
|
156
|
-
if (
|
|
63
|
+
if (_config.output === "static") {
|
|
157
64
|
throw new AstroError(
|
|
158
65
|
'[@astrojs/cloudflare] `output: "server"` or `output: "hybrid"` is required to use this adapter. Otherwise, this adapter is not necessary to deploy a static site to Cloudflare.'
|
|
159
66
|
);
|
|
160
67
|
}
|
|
161
|
-
if (
|
|
68
|
+
if (_config.base === SERVER_BUILD_FOLDER) {
|
|
162
69
|
throw new AstroError(
|
|
163
70
|
'[@astrojs/cloudflare] `base: "${SERVER_BUILD_FOLDER}"` is not allowed. Please change your `base` config to something else.'
|
|
164
71
|
);
|
|
@@ -229,6 +136,7 @@ function createIntegration(args) {
|
|
|
229
136
|
},
|
|
230
137
|
"astro:build:done": async ({ pages, routes, dir }) => {
|
|
231
138
|
const functionsUrl = new URL("functions/", _config.root);
|
|
139
|
+
const assetsUrl = new URL(_buildConfig.assets, _buildConfig.client);
|
|
232
140
|
if (isModeDirectory) {
|
|
233
141
|
await fs.promises.mkdir(functionsUrl, { recursive: true });
|
|
234
142
|
}
|
|
@@ -237,35 +145,59 @@ function createIntegration(args) {
|
|
|
237
145
|
const entryPaths = entryPointsURL.map((entry) => fileURLToPath(entry));
|
|
238
146
|
const outputUrl = new URL("$astro", _buildConfig.server);
|
|
239
147
|
const outputDir = fileURLToPath(outputUrl);
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
148
|
+
const entryPathsGroupedByDepth = !args.wasmModuleImports ? [entryPaths] : entryPaths.reduce((sum, thisPath) => {
|
|
149
|
+
const depthFromRoot = thisPath.split(sep).length;
|
|
150
|
+
sum.set(depthFromRoot, (sum.get(depthFromRoot) || []).concat(thisPath));
|
|
151
|
+
return sum;
|
|
152
|
+
}, /* @__PURE__ */ new Map()).values();
|
|
153
|
+
for (const pathsGroup of entryPathsGroupedByDepth) {
|
|
154
|
+
const pagesDirname = relative(fileURLToPath(_buildConfig.server), pathsGroup[0]).split(
|
|
155
|
+
sep
|
|
156
|
+
)[0];
|
|
157
|
+
const absolutePagesDirname = fileURLToPath(new URL(pagesDirname, _buildConfig.server));
|
|
158
|
+
const urlWithinFunctions = new URL(
|
|
159
|
+
relative(absolutePagesDirname, pathsGroup[0]),
|
|
160
|
+
functionsUrl
|
|
161
|
+
);
|
|
162
|
+
const relativePathToAssets = relative(
|
|
163
|
+
dirname(fileURLToPath(urlWithinFunctions)),
|
|
164
|
+
fileURLToPath(assetsUrl)
|
|
165
|
+
);
|
|
166
|
+
await esbuild.build({
|
|
167
|
+
target: "es2020",
|
|
168
|
+
platform: "browser",
|
|
169
|
+
conditions: ["workerd", "worker", "browser"],
|
|
170
|
+
external: [
|
|
171
|
+
"node:assert",
|
|
172
|
+
"node:async_hooks",
|
|
173
|
+
"node:buffer",
|
|
174
|
+
"node:diagnostics_channel",
|
|
175
|
+
"node:events",
|
|
176
|
+
"node:path",
|
|
177
|
+
"node:process",
|
|
178
|
+
"node:stream",
|
|
179
|
+
"node:string_decoder",
|
|
180
|
+
"node:util"
|
|
181
|
+
],
|
|
182
|
+
entryPoints: pathsGroup,
|
|
183
|
+
outbase: absolutePagesDirname,
|
|
184
|
+
outdir: outputDir,
|
|
185
|
+
allowOverwrite: true,
|
|
186
|
+
format: "esm",
|
|
187
|
+
bundle: true,
|
|
188
|
+
minify: _config.vite?.build?.minify !== false,
|
|
189
|
+
banner: {
|
|
190
|
+
js: `globalThis.process = {
|
|
191
|
+
argv: [],
|
|
192
|
+
env: {},
|
|
193
|
+
};`
|
|
194
|
+
},
|
|
195
|
+
logOverride: {
|
|
196
|
+
"ignored-bare-import": "silent"
|
|
197
|
+
},
|
|
198
|
+
plugins: !args?.wasmModuleImports ? [] : [rewriteWasmImportPath({ relativePathToAssets })]
|
|
199
|
+
});
|
|
200
|
+
}
|
|
269
201
|
const outputFiles = await glob(`**/*`, {
|
|
270
202
|
cwd: outputDir,
|
|
271
203
|
filesOnly: true
|
|
@@ -318,11 +250,19 @@ function createIntegration(args) {
|
|
|
318
250
|
bundle: true,
|
|
319
251
|
minify: _config.vite?.build?.minify !== false,
|
|
320
252
|
banner: {
|
|
321
|
-
js:
|
|
253
|
+
js: `globalThis.process = {
|
|
254
|
+
argv: [],
|
|
255
|
+
env: {},
|
|
256
|
+
};`
|
|
322
257
|
},
|
|
323
258
|
logOverride: {
|
|
324
259
|
"ignored-bare-import": "silent"
|
|
325
|
-
}
|
|
260
|
+
},
|
|
261
|
+
plugins: !args?.wasmModuleImports ? [] : [
|
|
262
|
+
rewriteWasmImportPath({
|
|
263
|
+
relativePathToAssets: isModeDirectory ? relative(fileURLToPath(functionsUrl), fileURLToPath(assetsUrl)) : relative(fileURLToPath(_buildConfig.client), fileURLToPath(assetsUrl))
|
|
264
|
+
})
|
|
265
|
+
]
|
|
326
266
|
});
|
|
327
267
|
await fs.promises.rename(buildPath, finalBuildUrl);
|
|
328
268
|
if (isModeDirectory) {
|
|
@@ -344,8 +284,12 @@ function createIntegration(args) {
|
|
|
344
284
|
}
|
|
345
285
|
}
|
|
346
286
|
}
|
|
287
|
+
if (!isModeDirectory) {
|
|
288
|
+
cloudflareSpecialFiles.push("_worker.js");
|
|
289
|
+
}
|
|
347
290
|
const routesExists = await fs.promises.stat(new URL("./_routes.json", _config.outDir)).then((stat) => stat.isFile()).catch(() => false);
|
|
348
291
|
if (!routesExists) {
|
|
292
|
+
const potentialFunctionRouteTypes = ["endpoint", "page"];
|
|
349
293
|
const functionEndpoints = routes.filter((route) => potentialFunctionRouteTypes.includes(route.type) && !route.prerender).map((route) => {
|
|
350
294
|
const includePattern = "/" + route.segments.flat().map((segment) => segment.dynamic ? "*" : segment.content).join("/");
|
|
351
295
|
const regexp = new RegExp(
|
|
@@ -358,7 +302,8 @@ function createIntegration(args) {
|
|
|
358
302
|
});
|
|
359
303
|
const staticPathList = (await glob(`${fileURLToPath(_buildConfig.client)}/**/*`, {
|
|
360
304
|
cwd: fileURLToPath(_config.outDir),
|
|
361
|
-
filesOnly: true
|
|
305
|
+
filesOnly: true,
|
|
306
|
+
dot: true
|
|
362
307
|
})).filter((file) => cloudflareSpecialFiles.indexOf(file) < 0).map((file) => `/${file.replace(/\\/g, "/")}`);
|
|
363
308
|
for (let page of pages) {
|
|
364
309
|
let pagePath = prependForwardSlash(page.pathname);
|
|
@@ -399,29 +344,34 @@ function createIntegration(args) {
|
|
|
399
344
|
);
|
|
400
345
|
}
|
|
401
346
|
staticPathList.push(...routes.filter((r) => r.type === "redirect").map((r) => r.route));
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
347
|
+
const strategy = args?.routes?.strategy ?? "auto";
|
|
348
|
+
const includeStrategy = strategy === "exclude" ? void 0 : {
|
|
349
|
+
include: deduplicatePatterns(
|
|
350
|
+
functionEndpoints.map((endpoint) => endpoint.includePattern).concat(args?.routes?.include ?? [])
|
|
351
|
+
),
|
|
352
|
+
exclude: deduplicatePatterns(
|
|
353
|
+
staticPathList.filter(
|
|
354
|
+
(file) => functionEndpoints.some((endpoint) => endpoint.regexp.test(file))
|
|
355
|
+
).concat(args?.routes?.exclude ?? [])
|
|
408
356
|
)
|
|
409
|
-
|
|
410
|
-
if (include.length === 0) {
|
|
411
|
-
include = ["/"];
|
|
412
|
-
exclude = ["/"];
|
|
413
|
-
}
|
|
414
|
-
if (include.length + exclude.length > staticPathList.length) {
|
|
415
|
-
include = ["/*"];
|
|
416
|
-
exclude = deduplicatePatterns(staticPathList);
|
|
357
|
+
};
|
|
358
|
+
if (includeStrategy?.include.length === 0) {
|
|
359
|
+
includeStrategy.include = ["/"];
|
|
360
|
+
includeStrategy.exclude = ["/"];
|
|
417
361
|
}
|
|
362
|
+
const excludeStrategy = strategy === "include" ? void 0 : {
|
|
363
|
+
include: ["/*"],
|
|
364
|
+
exclude: deduplicatePatterns(staticPathList.concat(args?.routes?.exclude ?? []))
|
|
365
|
+
};
|
|
366
|
+
const includeStrategyLength = includeStrategy ? includeStrategy.include.length + includeStrategy.exclude.length : Infinity;
|
|
367
|
+
const excludeStrategyLength = excludeStrategy ? excludeStrategy.include.length + excludeStrategy.exclude.length : Infinity;
|
|
368
|
+
const winningStrategy = includeStrategyLength <= excludeStrategyLength ? includeStrategy : excludeStrategy;
|
|
418
369
|
await fs.promises.writeFile(
|
|
419
370
|
new URL("./_routes.json", _config.outDir),
|
|
420
371
|
JSON.stringify(
|
|
421
372
|
{
|
|
422
373
|
version: 1,
|
|
423
|
-
|
|
424
|
-
exclude
|
|
374
|
+
...winningStrategy
|
|
425
375
|
},
|
|
426
376
|
null,
|
|
427
377
|
2
|
|
@@ -432,22 +382,6 @@ function createIntegration(args) {
|
|
|
432
382
|
}
|
|
433
383
|
};
|
|
434
384
|
}
|
|
435
|
-
function prependForwardSlash(path) {
|
|
436
|
-
return path[0] === "/" ? path : "/" + path;
|
|
437
|
-
}
|
|
438
|
-
function deduplicatePatterns(patterns) {
|
|
439
|
-
const openPatterns = [];
|
|
440
|
-
return [...new Set(patterns)].sort((a, b) => a.length - b.length).filter((pattern) => {
|
|
441
|
-
if (openPatterns.some((p) => p.test(pattern))) {
|
|
442
|
-
return false;
|
|
443
|
-
}
|
|
444
|
-
if (pattern.endsWith("*")) {
|
|
445
|
-
openPatterns.push(new RegExp(`^${pattern.replace(/(\*\/)*\*$/g, ".*")}`));
|
|
446
|
-
}
|
|
447
|
-
return true;
|
|
448
|
-
});
|
|
449
|
-
}
|
|
450
385
|
export {
|
|
451
|
-
createIntegration as default
|
|
452
|
-
getAdapter
|
|
386
|
+
createIntegration as default
|
|
453
387
|
};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Remove duplicates and redundant patterns from an `include` or `exclude` list.
|
|
3
|
+
* Otherwise Cloudflare will throw an error on deployment. Plus, it saves more entries.
|
|
4
|
+
* E.g. `['/foo/*', '/foo/*', '/foo/bar'] => ['/foo/*']`
|
|
5
|
+
* @param patterns a list of `include` or `exclude` patterns
|
|
6
|
+
* @returns a deduplicated list of patterns
|
|
7
|
+
*/
|
|
8
|
+
export declare function deduplicatePatterns(patterns: string[]): string[];
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
function deduplicatePatterns(patterns) {
|
|
2
|
+
const openPatterns = [];
|
|
3
|
+
return [...new Set(patterns)].sort((a, b) => a.length - b.length).filter((pattern) => {
|
|
4
|
+
if (openPatterns.some((p) => p.test(pattern))) {
|
|
5
|
+
return false;
|
|
6
|
+
}
|
|
7
|
+
if (pattern.endsWith("*")) {
|
|
8
|
+
openPatterns.push(new RegExp(`^${pattern.replace(/(\*\/)*\*$/g, ".*")}`));
|
|
9
|
+
}
|
|
10
|
+
return true;
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
export {
|
|
14
|
+
deduplicatePatterns
|
|
15
|
+
};
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
async function getCFObject(runtimeMode) {
|
|
2
|
+
const CF_ENDPOINT = "https://workers.cloudflare.com/cf.json";
|
|
3
|
+
const CF_FALLBACK = {
|
|
4
|
+
asOrganization: "",
|
|
5
|
+
asn: 395747,
|
|
6
|
+
colo: "DFW",
|
|
7
|
+
city: "Austin",
|
|
8
|
+
region: "Texas",
|
|
9
|
+
regionCode: "TX",
|
|
10
|
+
metroCode: "635",
|
|
11
|
+
postalCode: "78701",
|
|
12
|
+
country: "US",
|
|
13
|
+
continent: "NA",
|
|
14
|
+
timezone: "America/Chicago",
|
|
15
|
+
latitude: "30.27130",
|
|
16
|
+
longitude: "-97.74260",
|
|
17
|
+
clientTcpRtt: 0,
|
|
18
|
+
httpProtocol: "HTTP/1.1",
|
|
19
|
+
requestPriority: "weight=192;exclusive=0",
|
|
20
|
+
tlsCipher: "AEAD-AES128-GCM-SHA256",
|
|
21
|
+
tlsVersion: "TLSv1.3",
|
|
22
|
+
tlsClientAuth: {
|
|
23
|
+
certPresented: "0",
|
|
24
|
+
certVerified: "NONE",
|
|
25
|
+
certRevoked: "0",
|
|
26
|
+
certIssuerDN: "",
|
|
27
|
+
certSubjectDN: "",
|
|
28
|
+
certIssuerDNRFC2253: "",
|
|
29
|
+
certSubjectDNRFC2253: "",
|
|
30
|
+
certIssuerDNLegacy: "",
|
|
31
|
+
certSubjectDNLegacy: "",
|
|
32
|
+
certSerial: "",
|
|
33
|
+
certIssuerSerial: "",
|
|
34
|
+
certSKI: "",
|
|
35
|
+
certIssuerSKI: "",
|
|
36
|
+
certFingerprintSHA1: "",
|
|
37
|
+
certFingerprintSHA256: "",
|
|
38
|
+
certNotBefore: "",
|
|
39
|
+
certNotAfter: ""
|
|
40
|
+
},
|
|
41
|
+
edgeRequestKeepAliveStatus: 0,
|
|
42
|
+
hostMetadata: void 0,
|
|
43
|
+
clientTrustScore: 99,
|
|
44
|
+
botManagement: {
|
|
45
|
+
corporateProxy: false,
|
|
46
|
+
verifiedBot: false,
|
|
47
|
+
ja3Hash: "25b4882c2bcb50cd6b469ff28c596742",
|
|
48
|
+
staticResource: false,
|
|
49
|
+
detectionIds: [],
|
|
50
|
+
score: 99
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
if (runtimeMode === "local") {
|
|
54
|
+
return CF_FALLBACK;
|
|
55
|
+
} else if (runtimeMode === "remote") {
|
|
56
|
+
try {
|
|
57
|
+
const res = await fetch(CF_ENDPOINT);
|
|
58
|
+
const cfText = await res.text();
|
|
59
|
+
const storedCf = JSON.parse(cfText);
|
|
60
|
+
return storedCf;
|
|
61
|
+
} catch (e) {
|
|
62
|
+
return CF_FALLBACK;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
export {
|
|
67
|
+
getCFObject
|
|
68
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function prependForwardSlash(path: string): string;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import esbuild from 'esbuild';
|
|
2
|
+
/**
|
|
3
|
+
*
|
|
4
|
+
* @param relativePathToAssets - relative path from the final location for the current esbuild output bundle, to the assets directory.
|
|
5
|
+
*/
|
|
6
|
+
export declare function rewriteWasmImportPath({ relativePathToAssets, }: {
|
|
7
|
+
relativePathToAssets: string;
|
|
8
|
+
}): esbuild.Plugin;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import esbuild from "esbuild";
|
|
2
|
+
import { basename } from "node:path";
|
|
3
|
+
function rewriteWasmImportPath({
|
|
4
|
+
relativePathToAssets
|
|
5
|
+
}) {
|
|
6
|
+
return {
|
|
7
|
+
name: "wasm-loader",
|
|
8
|
+
setup(build) {
|
|
9
|
+
build.onResolve({ filter: /.*\.wasm.mjs$/ }, (args) => {
|
|
10
|
+
const updatedPath = [
|
|
11
|
+
relativePathToAssets.replaceAll("\\", "/"),
|
|
12
|
+
basename(args.path).replace(/\.mjs$/, "")
|
|
13
|
+
].join("/");
|
|
14
|
+
return {
|
|
15
|
+
path: updatedPath,
|
|
16
|
+
external: true
|
|
17
|
+
// mark it as external in the bundle
|
|
18
|
+
};
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
export {
|
|
24
|
+
rewriteWasmImportPath
|
|
25
|
+
};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { type Plugin } from 'vite';
|
|
2
|
+
/**
|
|
3
|
+
* Loads '*.wasm?module' imports as WebAssembly modules, which is the only way to load WASM in cloudflare workers.
|
|
4
|
+
* Current proposal for WASM modules: https://github.com/WebAssembly/esm-integration/tree/main/proposals/esm-integration
|
|
5
|
+
* Cloudflare worker WASM from javascript support: https://developers.cloudflare.com/workers/runtime-apis/webassembly/javascript/
|
|
6
|
+
* @param disabled - if true throws a helpful error message if wasm is encountered and wasm imports are not enabled,
|
|
7
|
+
* otherwise it will error obscurely in the esbuild and vite builds
|
|
8
|
+
* @param assetsDirectory - the folder name for the assets directory in the build directory. Usually '_astro'
|
|
9
|
+
* @returns Vite plugin to load WASM tagged with '?module' as a WASM modules
|
|
10
|
+
*/
|
|
11
|
+
export declare function wasmModuleLoader({ disabled, assetsDirectory, }: {
|
|
12
|
+
disabled: boolean;
|
|
13
|
+
assetsDirectory: string;
|
|
14
|
+
}): Plugin;
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import {} from "vite";
|
|
4
|
+
function wasmModuleLoader({
|
|
5
|
+
disabled,
|
|
6
|
+
assetsDirectory
|
|
7
|
+
}) {
|
|
8
|
+
const postfix = ".wasm?module";
|
|
9
|
+
let isDev = false;
|
|
10
|
+
return {
|
|
11
|
+
name: "vite:wasm-module-loader",
|
|
12
|
+
enforce: "pre",
|
|
13
|
+
configResolved(config) {
|
|
14
|
+
isDev = config.command === "serve";
|
|
15
|
+
},
|
|
16
|
+
config(_, __) {
|
|
17
|
+
return {
|
|
18
|
+
assetsInclude: ["**/*.wasm?module"],
|
|
19
|
+
build: { rollupOptions: { external: /^__WASM_ASSET__.+\.wasm\.mjs$/i } }
|
|
20
|
+
};
|
|
21
|
+
},
|
|
22
|
+
load(id, _) {
|
|
23
|
+
if (!id.endsWith(postfix)) {
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
if (disabled) {
|
|
27
|
+
throw new Error(
|
|
28
|
+
`WASM module's cannot be loaded unless you add \`wasmModuleImports: true\` to your astro config.`
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
const filePath = id.slice(0, -1 * "?module".length);
|
|
32
|
+
const data = fs.readFileSync(filePath);
|
|
33
|
+
const base64 = data.toString("base64");
|
|
34
|
+
const base64Module = `
|
|
35
|
+
const wasmModule = new WebAssembly.Module(Uint8Array.from(atob("${base64}"), c => c.charCodeAt(0)));
|
|
36
|
+
export default wasmModule
|
|
37
|
+
`;
|
|
38
|
+
if (isDev) {
|
|
39
|
+
return base64Module;
|
|
40
|
+
} else {
|
|
41
|
+
let hash = hashString(base64);
|
|
42
|
+
const assetName = path.basename(filePath).split(".")[0] + "." + hash + ".wasm";
|
|
43
|
+
this.emitFile({
|
|
44
|
+
type: "asset",
|
|
45
|
+
// put it explicitly in the _astro assets directory with `fileName` rather than `name` so that
|
|
46
|
+
// vite doesn't give it a random id in its name. We need to be able to easily rewrite from
|
|
47
|
+
// the .mjs loader and the actual wasm asset later in the ESbuild for the worker
|
|
48
|
+
fileName: path.join(assetsDirectory, assetName),
|
|
49
|
+
source: fs.readFileSync(filePath)
|
|
50
|
+
});
|
|
51
|
+
const chunkId = this.emitFile({
|
|
52
|
+
type: "prebuilt-chunk",
|
|
53
|
+
fileName: assetName + ".mjs",
|
|
54
|
+
code: base64Module
|
|
55
|
+
});
|
|
56
|
+
return `
|
|
57
|
+
import wasmModule from "__WASM_ASSET__${chunkId}.wasm.mjs";
|
|
58
|
+
export default wasmModule;
|
|
59
|
+
`;
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
// output original wasm file relative to the chunk
|
|
63
|
+
renderChunk(code, chunk, _) {
|
|
64
|
+
if (isDev)
|
|
65
|
+
return;
|
|
66
|
+
if (!/__WASM_ASSET__/g.test(code))
|
|
67
|
+
return;
|
|
68
|
+
const final = code.replaceAll(/__WASM_ASSET__([a-z\d]+).wasm.mjs/g, (s, assetId) => {
|
|
69
|
+
const fileName = this.getFileName(assetId);
|
|
70
|
+
const relativePath = path.relative(path.dirname(chunk.fileName), fileName).replaceAll("\\", "/");
|
|
71
|
+
return `./${relativePath}`;
|
|
72
|
+
});
|
|
73
|
+
return { code: final };
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
function hashString(str) {
|
|
78
|
+
let hash = 0;
|
|
79
|
+
for (let i = 0; i < str.length; i++) {
|
|
80
|
+
const char = str.charCodeAt(i);
|
|
81
|
+
hash = (hash << 5) - hash + char;
|
|
82
|
+
hash &= hash;
|
|
83
|
+
}
|
|
84
|
+
return new Uint32Array([hash])[0].toString(36);
|
|
85
|
+
}
|
|
86
|
+
export {
|
|
87
|
+
wasmModuleLoader
|
|
88
|
+
};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astrojs/cloudflare",
|
|
3
3
|
"description": "Deploy your site to Cloudflare Workers/Pages",
|
|
4
|
-
"version": "7.
|
|
4
|
+
"version": "7.3.1",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
7
7
|
"author": "withastro",
|
|
@@ -19,17 +19,12 @@
|
|
|
19
19
|
"homepage": "https://docs.astro.build/en/guides/integrations-guide/cloudflare/",
|
|
20
20
|
"exports": {
|
|
21
21
|
".": "./dist/index.js",
|
|
22
|
-
"./
|
|
23
|
-
|
|
24
|
-
"default": "./dist/runtime.js"
|
|
25
|
-
},
|
|
26
|
-
"./server.advanced.js": "./dist/server.advanced.js",
|
|
27
|
-
"./server.directory.js": "./dist/server.directory.js",
|
|
22
|
+
"./entrypoints/server.advanced.js": "./dist/entrypoints/server.advanced.js",
|
|
23
|
+
"./entrypoints/server.directory.js": "./dist/entrypoints/server.directory.js",
|
|
28
24
|
"./package.json": "./package.json"
|
|
29
25
|
},
|
|
30
26
|
"files": [
|
|
31
|
-
"dist"
|
|
32
|
-
"runtime.d.ts"
|
|
27
|
+
"dist"
|
|
33
28
|
],
|
|
34
29
|
"dependencies": {
|
|
35
30
|
"@cloudflare/workers-types": "^4.20230821.0",
|
|
@@ -41,19 +36,19 @@
|
|
|
41
36
|
"esbuild": "^0.19.2",
|
|
42
37
|
"find-up": "^6.3.0",
|
|
43
38
|
"tiny-glob": "^0.2.9",
|
|
39
|
+
"vite": "^4.4.9",
|
|
44
40
|
"@astrojs/underscore-redirects": "0.3.0"
|
|
45
41
|
},
|
|
46
42
|
"peerDependencies": {
|
|
47
|
-
"astro": "^3.
|
|
43
|
+
"astro": "^3.2.0"
|
|
48
44
|
},
|
|
49
45
|
"devDependencies": {
|
|
50
46
|
"@types/iarna__toml": "^2.0.2",
|
|
51
47
|
"chai": "^4.3.7",
|
|
52
48
|
"cheerio": "1.0.0-rc.12",
|
|
53
|
-
"kill-port": "^2.0.1",
|
|
54
49
|
"mocha": "^10.2.0",
|
|
55
50
|
"wrangler": "^3.5.1",
|
|
56
|
-
"astro": "3.
|
|
51
|
+
"astro": "3.2.0",
|
|
57
52
|
"astro-scripts": "0.0.14"
|
|
58
53
|
},
|
|
59
54
|
"scripts": {
|
|
File without changes
|
|
File without changes
|
|
File without changes
|