@astrojs/cloudflare 0.3.0 → 1.0.0

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.
@@ -1,5 +1,5 @@
1
- @astrojs/cloudflare:build: cache hit, replaying output 7d2a1e1c56d7ba86
2
- @astrojs/cloudflare:build: 
3
- @astrojs/cloudflare:build: > @astrojs/cloudflare@0.3.0 build /home/runner/work/astro/astro/packages/integrations/cloudflare
4
- @astrojs/cloudflare:build: > astro-scripts build "src/**/*.ts" && tsc
5
- @astrojs/cloudflare:build: 
1
+ @astrojs/cloudflare:build: cache hit, replaying output 25c70881b302d92a
2
+ @astrojs/cloudflare:build: 
3
+ @astrojs/cloudflare:build: > @astrojs/cloudflare@1.0.0 build /home/runner/work/astro/astro/packages/integrations/cloudflare
4
+ @astrojs/cloudflare:build: > astro-scripts build "src/**/*.ts" && tsc
5
+ @astrojs/cloudflare:build: 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # @astrojs/cloudflare
2
2
 
3
+ ## 1.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - [`04ad44563`](https://github.com/withastro/astro/commit/04ad445632c67bdd60c1704e1e0dcbcaa27b9308) - > Astro v1.0 is out! Read the [official announcement post](https://astro.build/blog/astro-1/).
8
+
9
+ **No breaking changes**. This package is now officially stable and compatible with `astro@1.0.0`!
10
+
11
+ ## 0.5.0
12
+
13
+ ### Minor Changes
14
+
15
+ - [#3806](https://github.com/withastro/astro/pull/3806) [`f4c571bdb`](https://github.com/withastro/astro/commit/f4c571bdb0bbcd0dfed68a484dfbfe274f8a5f45) Thanks [@nrgnrg](https://github.com/nrgnrg)! - add support for compiling functions to a functions directory rather than `_worker.js`
16
+
17
+ ## 0.4.0
18
+
19
+ ### Minor Changes
20
+
21
+ - [#4068](https://github.com/withastro/astro/pull/4068) [`54b33d50f`](https://github.com/withastro/astro/commit/54b33d50fdb995ac056461be7e2128d911624f2d) Thanks [@matthewp](https://github.com/matthewp)! - Add explicit errors when omitting output config
22
+
23
+ ### Patch Changes
24
+
25
+ - [#4072](https://github.com/withastro/astro/pull/4072) [`a198028b0`](https://github.com/withastro/astro/commit/a198028b04234d0b8dcb0b6bcb47c5831d7a15f9) Thanks [@matthewp](https://github.com/matthewp)! - Fixes Cloudflare throwing an error for process
26
+
3
27
  ## 0.3.0
4
28
 
5
29
  ### Minor Changes
@@ -34,7 +58,7 @@
34
58
  The new `Astro.clientAddress` property allows you to get the IP address of the requested user.
35
59
 
36
60
  ```astro
37
- <div>Your address { Astro.clientAddress }</div>
61
+ <div>Your address {Astro.clientAddress}</div>
38
62
  ```
39
63
 
40
64
  This property is only available when building for SSR, and only if the adapter you are using supports providing the IP address. If you attempt to access the property in a SSG app it will throw an error.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @astrojs/cloudflare
2
2
 
3
- An SSR adapter for use with Cloudflare Pages Functions targets. Write your code in Astro/Node and deploy to Cloudflare Pages.
3
+ An SSR adapter for use with Cloudflare Pages Functions targets. Write your code in Astro/Javascript and deploy to Cloudflare Pages.
4
4
 
5
5
  In your `astro.config.mjs` use:
6
6
 
@@ -14,6 +14,29 @@ export default defineConfig({
14
14
  });
15
15
  ```
16
16
 
17
+ ## Options
18
+
19
+
20
+ ### Mode
21
+
22
+ `mode: "advanced" | "directory"`
23
+
24
+ default `"advanced"`
25
+
26
+ Cloudflare Pages has 2 different modes for deploying functions, `advanced` mode which picks up the `_worker.js` in `dist`, or a directory mode where pages will compile the worker out of a functions folder in the project root.
27
+
28
+ For most projects the adaptor default of `advanced` will be sufficiant, when in this mode the `dist` folder will contain your compiled project. However if you'd like to use [pages plugins](https://developers.cloudflare.com/pages/platform/functions/plugins/) such as [Sentry](https://developers.cloudflare.com/pages/platform/functions/plugins/sentry/) for example to enable logging, you'll need to use directory mode.
29
+
30
+ In directory mode the adaptor will compile the client side part of you app the same way, but it will move the worker script into a `functions` folder in the project root. The adaptor will only ever place a `[[path]].js` in that folder, allowing you to add additional plugins and pages middlewhere which can be checked into version control .
31
+
32
+ ```ts
33
+ // directory mode
34
+ export default defineConfig({
35
+ adapter: cloudflare({ mode: "directory" }),
36
+ });
37
+
38
+ ```
39
+
17
40
  ## Enabling Preview
18
41
 
19
42
  In order for preview to work you must install `wrangler`
package/dist/index.d.ts CHANGED
@@ -1,3 +1,7 @@
1
1
  import type { AstroAdapter, AstroIntegration } from 'astro';
2
- export declare function getAdapter(): AstroAdapter;
3
- export default function createIntegration(): AstroIntegration;
2
+ declare type Options = {
3
+ mode: 'directory' | 'advanced';
4
+ };
5
+ export declare function getAdapter(isModeDirectory: boolean): AstroAdapter;
6
+ export default function createIntegration(args?: Options): AstroIntegration;
7
+ export {};
package/dist/index.js CHANGED
@@ -1,35 +1,42 @@
1
1
  import esbuild from "esbuild";
2
2
  import * as fs from "fs";
3
3
  import { fileURLToPath } from "url";
4
- function getAdapter() {
5
- return {
4
+ function getAdapter(isModeDirectory) {
5
+ return isModeDirectory ? {
6
+ name: "@astrojs/cloudflare",
7
+ serverEntrypoint: "@astrojs/cloudflare/server.directory.js",
8
+ exports: ["onRequest"]
9
+ } : {
6
10
  name: "@astrojs/cloudflare",
7
- serverEntrypoint: "@astrojs/cloudflare/server.js",
11
+ serverEntrypoint: "@astrojs/cloudflare/server.advanced.js",
8
12
  exports: ["default"]
9
13
  };
10
14
  }
11
- function createIntegration() {
15
+ const SHIM = `globalThis.process = {
16
+ argv: [],
17
+ env: {},
18
+ };`;
19
+ function createIntegration(args) {
12
20
  let _config;
13
21
  let _buildConfig;
22
+ const isModeDirectory = (args == null ? void 0 : args.mode) === "directory";
14
23
  return {
15
24
  name: "@astrojs/cloudflare",
16
25
  hooks: {
17
26
  "astro:config:done": ({ setAdapter, config }) => {
18
- setAdapter(getAdapter());
27
+ setAdapter(getAdapter(isModeDirectory));
19
28
  _config = config;
20
29
  if (config.output === "static") {
21
- console.warn(
22
- `[@astrojs/cloudflare] \`output: "server"\` is required to use this adapter.`
23
- );
24
- console.warn(
25
- `[@astrojs/cloudflare] Otherwise, this adapter is not required to deploy a static site to Cloudflare.`
26
- );
30
+ throw new Error(`
31
+ [@astrojs/cloudflare] \`output: "server"\` is required to use this adapter. Otherwise, this adapter is not necessary to deploy a static site to Cloudflare.
32
+
33
+ `);
27
34
  }
28
35
  },
29
36
  "astro:build:start": ({ buildConfig }) => {
30
37
  _buildConfig = buildConfig;
31
- buildConfig.serverEntry = "_worker.js";
32
38
  buildConfig.client = new URL("./static/", _config.outDir);
39
+ buildConfig.serverEntry = "_worker.js";
33
40
  buildConfig.server = new URL("./", _config.outDir);
34
41
  },
35
42
  "astro:build:setup": ({ vite, target }) => {
@@ -61,10 +68,19 @@ function createIntegration() {
61
68
  allowOverwrite: true,
62
69
  format: "esm",
63
70
  bundle: true,
64
- minify: true
71
+ minify: true,
72
+ banner: {
73
+ js: SHIM
74
+ }
65
75
  });
66
76
  const chunksUrl = new URL("./chunks", _buildConfig.server);
67
77
  await fs.promises.rm(chunksUrl, { recursive: true, force: true });
78
+ if (isModeDirectory) {
79
+ const functionsUrl = new URL(`file://${process.cwd()}/functions/`);
80
+ await fs.promises.mkdir(functionsUrl, { recursive: true });
81
+ const directoryUrl = new URL("[[path]].js", functionsUrl);
82
+ await fs.promises.rename(entryUrl, directoryUrl);
83
+ }
68
84
  }
69
85
  }
70
86
  };
File without changes
File without changes
@@ -0,0 +1,8 @@
1
+ import './shim.js';
2
+ import type { SSRManifest } from 'astro';
3
+ export declare function createExports(manifest: SSRManifest): {
4
+ onRequest: ({ request, next, }: {
5
+ request: Request;
6
+ next: (request: Request) => void;
7
+ }) => Promise<void | Response>;
8
+ };
@@ -0,0 +1,32 @@
1
+ import "./shim.js";
2
+ import { App } from "astro/app";
3
+ function createExports(manifest) {
4
+ const app = new App(manifest, false);
5
+ const onRequest = async ({
6
+ request,
7
+ next
8
+ }) => {
9
+ const { origin, pathname } = new URL(request.url);
10
+ if (manifest.assets.has(pathname)) {
11
+ const assetRequest = new Request(`${origin}/static${pathname}`, request);
12
+ return next(assetRequest);
13
+ }
14
+ let routeData = app.match(request, { matchNotFound: true });
15
+ if (routeData) {
16
+ Reflect.set(
17
+ request,
18
+ Symbol.for("astro.clientAddress"),
19
+ request.headers.get("cf-connecting-ip")
20
+ );
21
+ return app.render(request, routeData);
22
+ }
23
+ return new Response(null, {
24
+ status: 404,
25
+ statusText: "Not found"
26
+ });
27
+ };
28
+ return { onRequest };
29
+ }
30
+ export {
31
+ createExports
32
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@astrojs/cloudflare",
3
3
  "description": "Deploy your site to cloudflare pages functions",
4
- "version": "0.3.0",
4
+ "version": "1.0.0",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",
7
7
  "author": "withastro",
@@ -18,19 +18,22 @@
18
18
  "homepage": "https://docs.astro.build/en/guides/integrations-guide/cloudflare/",
19
19
  "exports": {
20
20
  ".": "./dist/index.js",
21
- "./server.js": "./dist/server.js",
21
+ "./server.advanced.js": "./dist/server.advanced.js",
22
+ "./server.directory.js": "./dist/server.directory.js",
22
23
  "./package.json": "./package.json"
23
24
  },
24
25
  "dependencies": {
25
26
  "esbuild": "^0.14.42"
26
27
  },
27
28
  "devDependencies": {
28
- "astro": "1.0.0-rc.1",
29
- "astro-scripts": "0.0.6"
29
+ "astro": "1.0.0",
30
+ "astro-scripts": "0.0.7",
31
+ "wrangler": "^2.0.23"
30
32
  },
31
33
  "scripts": {
32
34
  "build": "astro-scripts build \"src/**/*.ts\" && tsc",
33
35
  "build:ci": "astro-scripts build \"src/**/*.ts\"",
34
- "dev": "astro-scripts dev \"src/**/*.ts\""
36
+ "dev": "astro-scripts dev \"src/**/*.ts\"",
37
+ "test": "mocha --exit --timeout 30000 test/"
35
38
  }
36
39
  }
package/src/index.ts CHANGED
@@ -3,38 +3,52 @@ import esbuild from 'esbuild';
3
3
  import * as fs from 'fs';
4
4
  import { fileURLToPath } from 'url';
5
5
 
6
- export function getAdapter(): AstroAdapter {
7
- return {
8
- name: '@astrojs/cloudflare',
9
- serverEntrypoint: '@astrojs/cloudflare/server.js',
10
- exports: ['default'],
11
- };
6
+ type Options = {
7
+ mode: 'directory' | 'advanced';
8
+ };
9
+
10
+ export function getAdapter(isModeDirectory: boolean): AstroAdapter {
11
+ return isModeDirectory
12
+ ? {
13
+ name: '@astrojs/cloudflare',
14
+ serverEntrypoint: '@astrojs/cloudflare/server.directory.js',
15
+ exports: ['onRequest'],
16
+ }
17
+ : {
18
+ name: '@astrojs/cloudflare',
19
+ serverEntrypoint: '@astrojs/cloudflare/server.advanced.js',
20
+ exports: ['default'],
21
+ };
12
22
  }
13
23
 
14
- export default function createIntegration(): AstroIntegration {
24
+ const SHIM = `globalThis.process = {
25
+ argv: [],
26
+ env: {},
27
+ };`;
28
+
29
+ export default function createIntegration(args?: Options): AstroIntegration {
15
30
  let _config: AstroConfig;
16
31
  let _buildConfig: BuildConfig;
32
+ const isModeDirectory = args?.mode === 'directory';
17
33
 
18
34
  return {
19
35
  name: '@astrojs/cloudflare',
20
36
  hooks: {
21
37
  'astro:config:done': ({ setAdapter, config }) => {
22
- setAdapter(getAdapter());
38
+ setAdapter(getAdapter(isModeDirectory));
23
39
  _config = config;
24
40
 
25
41
  if (config.output === 'static') {
26
- console.warn(
27
- `[@astrojs/cloudflare] \`output: "server"\` is required to use this adapter.`
28
- );
29
- console.warn(
30
- `[@astrojs/cloudflare] Otherwise, this adapter is not required to deploy a static site to Cloudflare.`
31
- );
42
+ throw new Error(`
43
+ [@astrojs/cloudflare] \`output: "server"\` is required to use this adapter. Otherwise, this adapter is not necessary to deploy a static site to Cloudflare.
44
+
45
+ `);
32
46
  }
33
47
  },
34
48
  'astro:build:start': ({ buildConfig }) => {
35
49
  _buildConfig = buildConfig;
36
- buildConfig.serverEntry = '_worker.js';
37
50
  buildConfig.client = new URL('./static/', _config.outDir);
51
+ buildConfig.serverEntry = '_worker.js';
38
52
  buildConfig.server = new URL('./', _config.outDir);
39
53
  },
40
54
  'astro:build:setup': ({ vite, target }) => {
@@ -61,7 +75,6 @@ export default function createIntegration(): AstroIntegration {
61
75
  'astro:build:done': async () => {
62
76
  const entryUrl = new URL(_buildConfig.serverEntry, _buildConfig.server);
63
77
  const pkg = fileURLToPath(entryUrl);
64
-
65
78
  await esbuild.build({
66
79
  target: 'es2020',
67
80
  platform: 'browser',
@@ -71,11 +84,21 @@ export default function createIntegration(): AstroIntegration {
71
84
  format: 'esm',
72
85
  bundle: true,
73
86
  minify: true,
87
+ banner: {
88
+ js: SHIM,
89
+ },
74
90
  });
75
91
 
76
92
  // throw the server folder in the bin
77
93
  const chunksUrl = new URL('./chunks', _buildConfig.server);
78
94
  await fs.promises.rm(chunksUrl, { recursive: true, force: true });
95
+
96
+ if (isModeDirectory) {
97
+ const functionsUrl = new URL(`file://${process.cwd()}/functions/`);
98
+ await fs.promises.mkdir(functionsUrl, { recursive: true });
99
+ const directoryUrl = new URL('[[path]].js', functionsUrl);
100
+ await fs.promises.rename(entryUrl, directoryUrl);
101
+ }
79
102
  },
80
103
  },
81
104
  };
File without changes
@@ -0,0 +1,41 @@
1
+ import './shim.js';
2
+
3
+ import type { SSRManifest } from 'astro';
4
+ import { App } from 'astro/app';
5
+
6
+ export function createExports(manifest: SSRManifest) {
7
+ const app = new App(manifest, false);
8
+
9
+ const onRequest = async ({
10
+ request,
11
+ next,
12
+ }: {
13
+ request: Request;
14
+ next: (request: Request) => void;
15
+ }) => {
16
+ const { origin, pathname } = new URL(request.url);
17
+
18
+ // static assets
19
+ if (manifest.assets.has(pathname)) {
20
+ const assetRequest = new Request(`${origin}/static${pathname}`, request);
21
+ return next(assetRequest);
22
+ }
23
+
24
+ let routeData = app.match(request, { matchNotFound: true });
25
+ if (routeData) {
26
+ Reflect.set(
27
+ request,
28
+ Symbol.for('astro.clientAddress'),
29
+ request.headers.get('cf-connecting-ip')
30
+ );
31
+ return app.render(request, routeData);
32
+ }
33
+
34
+ return new Response(null, {
35
+ status: 404,
36
+ statusText: 'Not found',
37
+ });
38
+ };
39
+
40
+ return { onRequest };
41
+ }
@@ -0,0 +1,31 @@
1
+ import { loadFixture, runCLI } from './test-utils.js';
2
+ import { expect } from 'chai';
3
+ import * as cheerio from 'cheerio';
4
+
5
+ describe.skip('Basic app', () => {
6
+ /** @type {import('./test-utils').Fixture} */
7
+ let fixture;
8
+
9
+ before(async () => {
10
+ fixture = await loadFixture({
11
+ root: './fixtures/basics/',
12
+ });
13
+ await fixture.build();
14
+ });
15
+
16
+ it('can render', async () => {
17
+ const { ready, stop } = runCLI('./fixtures/basics/', { silent: true });
18
+
19
+ try {
20
+ await ready;
21
+
22
+ let res = await fetch(`http://localhost:8787/`);
23
+ expect(res.status).to.equal(200);
24
+ let html = await res.text();
25
+ let $ = cheerio.load(html);
26
+ expect($('h1').text()).to.equal('Testing');
27
+ } finally {
28
+ stop();
29
+ }
30
+ });
31
+ });
@@ -0,0 +1,7 @@
1
+ import { defineConfig } from 'astro/config';
2
+ import cloudflare from '@astrojs/cloudflare';
3
+
4
+ export default defineConfig({
5
+ adapter: cloudflare(),
6
+ output: 'server',
7
+ });
@@ -0,0 +1,17 @@
1
+ #!/bin/sh
2
+ basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
3
+
4
+ case `uname` in
5
+ *CYGWIN*) basedir=`cygpath -w "$basedir"`;;
6
+ esac
7
+
8
+ if [ -z "$NODE_PATH" ]; then
9
+ export NODE_PATH="/home/runner/work/astro/astro/node_modules/.pnpm/node_modules"
10
+ else
11
+ export NODE_PATH="$NODE_PATH:/home/runner/work/astro/astro/node_modules/.pnpm/node_modules"
12
+ fi
13
+ if [ -x "$basedir/node" ]; then
14
+ exec "$basedir/node" "$basedir/../../../../../../../astro/astro.js" "$@"
15
+ else
16
+ exec node "$basedir/../../../../../../../astro/astro.js" "$@"
17
+ fi
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "@test/astro-cloudflare-basics",
3
+ "version": "0.0.0",
4
+ "private": true,
5
+ "dependencies": {
6
+ "@astrojs/cloudflare": "workspace:*",
7
+ "astro": "workspace:*"
8
+ }
9
+ }
@@ -0,0 +1,8 @@
1
+ <html>
2
+ <head>
3
+ <title>Testing</title>
4
+ </head>
5
+ <body>
6
+ <h1>Testing</h1>
7
+ </body>
8
+ </html>
@@ -0,0 +1,6 @@
1
+ import { defineConfig } from 'astro/config';
2
+ import cloudflare from '@astrojs/cloudflare';
3
+
4
+ export default defineConfig({
5
+ adapter: cloudflare()
6
+ });
@@ -0,0 +1,17 @@
1
+ #!/bin/sh
2
+ basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
3
+
4
+ case `uname` in
5
+ *CYGWIN*) basedir=`cygpath -w "$basedir"`;;
6
+ esac
7
+
8
+ if [ -z "$NODE_PATH" ]; then
9
+ export NODE_PATH="/home/runner/work/astro/astro/node_modules/.pnpm/node_modules"
10
+ else
11
+ export NODE_PATH="$NODE_PATH:/home/runner/work/astro/astro/node_modules/.pnpm/node_modules"
12
+ fi
13
+ if [ -x "$basedir/node" ]; then
14
+ exec "$basedir/node" "$basedir/../../../../../../../astro/astro.js" "$@"
15
+ else
16
+ exec node "$basedir/../../../../../../../astro/astro.js" "$@"
17
+ fi
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "@test/astro-cloudflare-no-output",
3
+ "version": "0.0.0",
4
+ "private": true,
5
+ "dependencies": {
6
+ "@astrojs/cloudflare": "workspace:*",
7
+ "astro": "workspace:*"
8
+ }
9
+ }
@@ -0,0 +1,24 @@
1
+ import { loadFixture } from './test-utils.js';
2
+ import { expect } from 'chai';
3
+
4
+ describe('Missing output config', () => {
5
+ /** @type {import('./test-utils').Fixture} */
6
+ let fixture;
7
+
8
+ before(async () => {
9
+ fixture = await loadFixture({
10
+ root: './fixtures/no-output/',
11
+ });
12
+ });
13
+
14
+ it('throws during the build', async () => {
15
+ let error = undefined;
16
+ try {
17
+ await fixture.build();
18
+ } catch (err) {
19
+ error = err;
20
+ }
21
+ expect(error).to.not.be.equal(undefined);
22
+ expect(error.message).to.include(`output: "server"`);
23
+ });
24
+ });
@@ -0,0 +1,62 @@
1
+ import { loadFixture as baseLoadFixture } from '../../../astro/test/test-utils.js';
2
+ import { spawn } from 'child_process';
3
+ import { fileURLToPath } from 'url';
4
+
5
+ export { fixLineEndings } from '../../../astro/test/test-utils.js';
6
+
7
+ export function loadFixture(config) {
8
+ if (config?.root) {
9
+ config.root = new URL(config.root, import.meta.url);
10
+ }
11
+ return baseLoadFixture(config);
12
+ }
13
+
14
+ const wranglerPath = fileURLToPath(
15
+ new URL('../node_modules/wrangler/bin/wrangler.js', import.meta.url)
16
+ );
17
+
18
+ export function runCLI(basePath, { silent }) {
19
+ const script = fileURLToPath(new URL(`${basePath}/dist/_worker.js`, import.meta.url));
20
+ const p = spawn('node', [wranglerPath, 'dev', '-l', script]);
21
+
22
+ p.stderr.setEncoding('utf-8');
23
+ p.stdout.setEncoding('utf-8');
24
+
25
+ const timeout = 10000;
26
+
27
+ const ready = new Promise(async (resolve, reject) => {
28
+ const failed = setTimeout(
29
+ () => reject(new Error(`Timed out starting the wrangler CLI`)),
30
+ timeout
31
+ );
32
+
33
+ (async function () {
34
+ for (const msg of p.stderr) {
35
+ if (!silent) {
36
+ // eslint-disable-next-line
37
+ console.error(msg);
38
+ }
39
+ }
40
+ })();
41
+
42
+ for await (const msg of p.stdout) {
43
+ if (!silent) {
44
+ // eslint-disable-next-line
45
+ console.log(msg);
46
+ }
47
+ if (msg.includes(`Listening on`)) {
48
+ break;
49
+ }
50
+ }
51
+
52
+ clearTimeout(failed);
53
+ resolve();
54
+ });
55
+
56
+ return {
57
+ ready,
58
+ stop() {
59
+ p.kill();
60
+ },
61
+ };
62
+ }