Skip to content

Commit

Permalink
feat(cloudflare): major refactor for v10 (#159)
Browse files Browse the repository at this point in the history
Co-authored-by: Matthew Phillips <[email protected]>
Co-authored-by: Emanuele Stoppa <[email protected]>
Co-authored-by: Erika <[email protected]>
Co-authored-by: Sarah Rainsberger <[email protected]>
  • Loading branch information
5 people authored Mar 28, 2024
1 parent 778eea5 commit adb8bf2
Show file tree
Hide file tree
Showing 114 changed files with 1,771 additions and 2,936 deletions.
193 changes: 193 additions & 0 deletions .changeset/sharp-knives-yell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
---
'@astrojs/cloudflare': major
---

Updates and prepares the adapter to be more flexibile, stable and composable for the future. Includes several breaking changes.

## Upgrade Guide

We are commited to provide a smooth upgrade path for our users. This guide will describe what has changed from v9.x to v10 to help you to migrate your existing projects to the latest version of the adapter. For complete documentation of all v10 configuration settings and usage, please see [the current, updated Cloudflare adapter documentation](https://docs.astro.build/en/guides/integrations-guide/cloudflare/).

We will provide at least 4 weeks of limited maintanance support for the previous version 9 of the adapter. Please plan to upgrade your project within this time frame, using the instructions below.

### Adapter's `mode` option & Cloudflare Functions

The `mode` option has been removed from the adapter. The adapter now defaults to the previous `advanced` mode and this is the only official supported option moving forward.

If you are already using `mode: 'advanced'` in your `astro.config.mjs` file, you can safely remove it.

```diff
import cloudflare from '@astrojs/cloudflare';
import { defineConfig } from 'astro/config';

export default defineConfig({
adapter: cloudflare({
- mode: 'advanced',
}),
});
```

If you are using `mode: 'directory'`, and don't have any custom Cloudflare functions in the `/function` folder, you should be able to remove the `mode` option, without any issues.

```diff
import cloudflare from '@astrojs/cloudflare';
import { defineConfig } from 'astro/config';

export default defineConfig({
adapter: cloudflare({
- mode: 'directory',
}),
});
```

If you are using `mode: 'directory'`, **and you have custom Cloudflare functions in the `/function` folder**, you will need to manually migrate them to [Astro Server Endpoints (API Routes)](https://docs.astro.build/en/guides/endpoints/#server-endpoints-api-routes). If you need to access Cloudflare Bindings, you can use `ctx.locals`. For further reference, please check the [Adapters Documentation on Cloudflare Runtime Usage](https://docs.astro.build/en/guides/integrations-guide/cloudflare/#usage).

### Adapter's `functionPerRoute` option

The `functionPerRoute` option has been removed from the adapter. The adapter now defaults to the previous `false` value. If you are using `functionPerRoute: true` in your `astro.config.mjs` file, you can safely remove it. This change will not break any existing projects, but you will no longer be generating a single function for each route.

```diff
import cloudflare from '@astrojs/cloudflare';
import { defineConfig } from 'astro/config';

export default defineConfig({
adapter: cloudflare({
- functionPerRoute: true,
}),
});
```

### Local Runtime

The adapter replaces the `runtime` options with a new set of `platformProxy` options to enable local runtime support when using `astro dev`.

If you are already using a `wrangler.toml` file, you can safely replace your existing `runtime` options with the appropriate `platformProxy` options.

```diff
import cloudflare from '@astrojs/cloudflare';
import { defineConfig } from 'astro/config';

export default defineConfig({
adapter: cloudflare({
- runtime: {
- mode: 'local',
- type: 'workers',
- },
+ platformProxy: {
+ enabled: true,
+ },
}),
});
```

If you define your bindings in the `astro.config.mjs` file, you need to first migrate your project to use a `wrangler.toml` configuration file for defining your bindings. You can find more information on how to do this in the [Cloudflare docs about wrangler](https://developers.cloudflare.com/workers/wrangler/configuration/#d1-databases). Then, replace `runtime` options with the new corresponding `platformProxy` options as above.

```diff
import cloudflare from '@astrojs/cloudflare';
import { defineConfig } from 'astro/config';

export default defineConfig({
adapter: cloudflare({
- runtime: {
- mode: 'local',
- type: 'pages',
- bindings: {
- // ...
- },
- },
+ platformProxy: {
+ enabled: true,
+ },
}),
});
```

If you have typed `locals` in your `./src/env.d.ts` file, you need to run `wrangler types` in your project and update the file.

```diff
/// <reference types="astro/client" />

- type KVNamespace = import('@cloudflare/workers-types/experimental').KVNamespace;
- type ENV = {
- SERVER_URL: string;
- KV_BINDING: KVNamespace;
- };

- type Runtime = import('@astrojs/cloudflare').AdvancedRuntime<ENV>;
+ type Runtime = import('@astrojs/cloudflare').Runtime<Env>;

declare namespace App {
interface Locals extends Runtime {
user: {
name: string;
surname: string;
};
}
}
```

### Routes

The `routes.strategy` option has been removed as you will no longer have the option to choose a strategy in v10 of this adpater.

If you are using `routes.strategy`, you can remove it. You might observe a different `dist/_routes.json` file, but it should not affect your project's behavior.

```diff
import cloudflare from '@astrojs/cloudflare';
import { defineConfig } from 'astro/config';

export default defineConfig({
adapter: cloudflare({
- routes: {
- strategy: 'include',
- },
}),
});
```

Additionally the `routes.include` & `routes.exclude` options have changed their name and type. If you were previously using them, move these to the new `routes.extend` property and update their types:

```diff
import cloudflare from '@astrojs/cloudflare';
import { defineConfig } from 'astro/config';

export default defineConfig({
adapter: cloudflare({
routes: {
- include: ['/api/*'],
- exclude: ['/fonts/*'],
+ extend: {
+ include: [{ pattern: '/api/*' }],
+ exclude: [{ pattern: '/fonts/*' }],
+ },
},
}),
});
```

### process.env

In the old version of the adapter we used to expose all the environment variables to `process.env`. This is no longer the case, as it was unsafe. If you need to use environment variables, you need to use either `Astro.locals.runtime.env` or `context.locals.runtime.env`. There is no way to access the environment variables directly from `process.env` or in the global scope.

If you need to access the environment variables in global scope, you should refactor your code to pass the environment variables as arguments to your function or file.

If you rely on any third library that uses `process.env`, please open an issue and we can investigate what the best way to handle this is.

### Node.js APIs compatibility

The adapter still supports the same Node.js APIs as Cloudflare does, but you need to adapt your vite configuration and enable the Cloudflare `nodejs_compat` flag.

```diff
import {defineConfig} from "astro/config";
import cloudflare from '@astrojs/cloudflare';

export default defineConfig({
adapter: cloudflare({}),
output: 'server',
+ vite: {
+ ssr: {
+ external: ['node:buffer'],
+ },
+ },
})
```
18 changes: 7 additions & 11 deletions packages/cloudflare/package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
{
"//comment": "test changeset-bot",
"name": "@astrojs/cloudflare",
"description": "Deploy your site to Cloudflare Workers/Pages",
"version": "9.2.1",
Expand Down Expand Up @@ -30,25 +29,22 @@
},
"dependencies": {
"@astrojs/underscore-redirects": "^0.3.3",
"@cloudflare/workers-types": "^4.20231025.0",
"miniflare": "3.20231030.2",
"@iarna/toml": "^2.2.5",
"dotenv": "^16.3.1",
"@astrojs/internal-helpers": "0.3.0",
"@cloudflare/workers-types": "^4.20240320.1",
"miniflare": "^3.20240320.0",
"esbuild": "^0.19.5",
"find-up": "^6.3.0",
"tiny-glob": "^0.2.9"
"tiny-glob": "^0.2.9",
"wrangler": "^3.36.0"
},
"peerDependencies": {
"astro": "^4.2.0"
},
"devDependencies": {
"execa": "^8.0.1",
"fast-glob": "^3.3.1",
"@types/iarna__toml": "^2.0.2",
"fast-glob": "^3.3.2",
"strip-ansi": "^7.1.0",
"astro": "^4.3.5",
"astro": "^4.5.8",
"cheerio": "1.0.0-rc.12",
"wrangler": "^3.15.0",
"@astrojs/test-utils": "workspace:*",
"astro-scripts": "workspace:*"
},
Expand Down
2 changes: 2 additions & 0 deletions packages/cloudflare/src/entrypoints/image-endpoint.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// NOTE: this file is empty on purpose
// it allows use to offer `imageService: 'compile'`
3 changes: 2 additions & 1 deletion packages/cloudflare/src/entrypoints/image-service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import type { ExternalImageService } from 'astro';

import { joinPaths } from '@astrojs/internal-helpers/path';
import { baseService } from 'astro/assets';
import { isESMImportedImage, isRemoteAllowed, joinPaths } from '../utils/assets.js';
import { isESMImportedImage, isRemoteAllowed } from '../utils/assets.js';

const service: ExternalImageService = {
...baseService,
Expand Down
50 changes: 31 additions & 19 deletions packages/cloudflare/src/entrypoints/server.advanced.ts
Original file line number Diff line number Diff line change
@@ -1,59 +1,71 @@
import type {
Request as CFRequest,
CacheStorage,
CacheStorage as CLOUDFLARE_CACHESTORAGE,
Request as CLOUDFLARE_REQUEST,
ExecutionContext,
} from '@cloudflare/workers-types';
import type { SSRManifest } from 'astro';
import { App } from 'astro/app';
import { getProcessEnvProxy, isNode } from '../util.js';

if (!isNode) {
process.env = getProcessEnvProxy();
}

type Env = {
ASSETS: { fetch: (req: Request) => Promise<Response> };
ASSETS: { fetch: (req: Request | string) => Promise<Response> };
ASTRO_STUDIO_APP_TOKEN?: string;
};

export interface AdvancedRuntime<T extends object = object> {
export interface Runtime<T extends object = object> {
runtime: {
waitUntil: (promise: Promise<any>) => void;
env: Env & T;
cf: CFRequest['cf'];
caches: CacheStorage;
cf: CLOUDFLARE_REQUEST['cf'];
caches: CLOUDFLARE_CACHESTORAGE;
};
}

export function createExports(manifest: SSRManifest) {
const app = new App(manifest);

const fetch = async (request: Request & CFRequest, env: Env, context: ExecutionContext) => {
// TODO: remove this any cast in the future
// REF: the type cast to any is needed because the Cloudflare Env Type is not assignable to type 'ProcessEnv'
process.env = env as any;

const fetch = async (
request: Request & CLOUDFLARE_REQUEST,
env: Env,
context: ExecutionContext
) => {
const { pathname } = new URL(request.url);

// static assets fallback, in case default _routes.json is not used
if (manifest.assets.has(pathname)) {
return env.ASSETS.fetch(request);
return env.ASSETS.fetch(request.url.replace(/\.html$/, ''));
}

const routeData = app.match(request);
if (!routeData) {
// https://developers.cloudflare.com/pages/functions/api-reference/#envassetsfetch
const asset = await env.ASSETS.fetch(
request.url.replace(/index.html$/, '').replace(/\.html$/, '')
);
if (asset.status !== 404) {
return asset;
}
}

Reflect.set(
request,
Symbol.for('astro.clientAddress'),
request.headers.get('cf-connecting-ip')
);

const locals: AdvancedRuntime = {
process.env.ASTRO_STUDIO_APP_TOKEN ??= (() => {
if (typeof env.ASTRO_STUDIO_APP_TOKEN === 'string') {
return env.ASTRO_STUDIO_APP_TOKEN;
}
})();

const locals: Runtime = {
runtime: {
waitUntil: (promise: Promise<any>) => {
context.waitUntil(promise);
},
env: env,
cf: request.cf,
caches: caches as unknown as CacheStorage,
caches: caches as unknown as CLOUDFLARE_CACHESTORAGE,
},
};

Expand Down
Loading

0 comments on commit adb8bf2

Please sign in to comment.