create-cloudflare 0.0.0-ca4d27bd
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 +61 -0
- package/dist/angular/templates/src/_routes.json +5 -0
- package/dist/angular/templates/src/main.server.ts +35 -0
- package/dist/angular/templates/tools/bundle.mjs +74 -0
- package/dist/angular/templates/tools/copy-client-files.mjs +4 -0
- package/dist/angular/templates/tools/copy-worker-files.mjs +10 -0
- package/dist/angular/templates/tools/paths.mjs +9 -0
- package/dist/angular/templates/tsconfig.server.json +5 -0
- package/dist/cli.js +58556 -0
- package/package.json +73 -0
- package/templates/chatgptPlugin/ts/.assets/example.png +0 -0
- package/templates/chatgptPlugin/ts/README.md +25 -0
- package/templates/chatgptPlugin/ts/package.json +16 -0
- package/templates/chatgptPlugin/ts/src/index.ts +33 -0
- package/templates/chatgptPlugin/ts/src/search.ts +63 -0
- package/templates/chatgptPlugin/ts/wrangler.toml +3 -0
- package/templates/common/js/.editorconfig +13 -0
- package/templates/common/js/.prettierrc +6 -0
- package/templates/common/js/package.json +14 -0
- package/templates/common/js/src/ab-test.js +41 -0
- package/templates/common/js/src/proxy.js +23 -0
- package/templates/common/js/src/redirect.js +13 -0
- package/templates/common/js/src/router.js +22 -0
- package/templates/common/js/src/worker.js +46 -0
- package/templates/common/js/wrangler.toml +51 -0
- package/templates/common/ts/.editorconfig +13 -0
- package/templates/common/ts/.prettierrc +6 -0
- package/templates/common/ts/package.json +15 -0
- package/templates/common/ts/src/ab-test.ts +41 -0
- package/templates/common/ts/src/proxy.ts +23 -0
- package/templates/common/ts/src/redirect.ts +13 -0
- package/templates/common/ts/src/router.ts +22 -0
- package/templates/common/ts/src/worker.ts +46 -0
- package/templates/common/ts/tsconfig.json +101 -0
- package/templates/common/ts/worker-configuration.d.ts +16 -0
- package/templates/common/ts/wrangler.toml +51 -0
- package/templates/hello-world/js/.editorconfig +13 -0
- package/templates/hello-world/js/.prettierrc +6 -0
- package/templates/hello-world/js/package.json +14 -0
- package/templates/hello-world/js/src/worker.js +15 -0
- package/templates/hello-world/js/wrangler.toml +51 -0
- package/templates/hello-world/ts/.editorconfig +13 -0
- package/templates/hello-world/ts/.prettierrc +6 -0
- package/templates/hello-world/ts/package.json +14 -0
- package/templates/hello-world/ts/src/worker.ts +32 -0
- package/templates/hello-world/ts/tsconfig.json +101 -0
- package/templates/hello-world/ts/wrangler.toml +51 -0
package/package.json
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "create-cloudflare",
|
|
3
|
+
"version": "0.0.0-ca4d27bd",
|
|
4
|
+
"description": "A CLI for creating and deploying new applications to Cloudflare.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"cloudflare",
|
|
7
|
+
"workers",
|
|
8
|
+
"cloudflare workers",
|
|
9
|
+
"serverless",
|
|
10
|
+
"serverless application"
|
|
11
|
+
],
|
|
12
|
+
"repository": {
|
|
13
|
+
"type": "git",
|
|
14
|
+
"url": "https://github.com/cloudflare/workers-sdk.git",
|
|
15
|
+
"directory": "packages/create-cloudflare"
|
|
16
|
+
},
|
|
17
|
+
"license": "MIT OR Apache-2.0",
|
|
18
|
+
"author": "wrangler@cloudflare.com",
|
|
19
|
+
"exports": {
|
|
20
|
+
".": "./dist/cli.js"
|
|
21
|
+
},
|
|
22
|
+
"main": "./dist/cli.js",
|
|
23
|
+
"bin": "./dist/cli.js",
|
|
24
|
+
"files": [
|
|
25
|
+
"dist",
|
|
26
|
+
"templates"
|
|
27
|
+
],
|
|
28
|
+
"scripts": {
|
|
29
|
+
"build": "node scripts/build.js",
|
|
30
|
+
"check:lint": "eslint .",
|
|
31
|
+
"check:type": "tsc",
|
|
32
|
+
"lint": "eslint",
|
|
33
|
+
"prepublishOnly": "npm run build",
|
|
34
|
+
"test:e2e": "npm run build && vitest run --config ./vitest-e2e.config.ts",
|
|
35
|
+
"test:unit": "vitest run --config ./vitest.config.ts",
|
|
36
|
+
"watch": "node scripts/build.js --watch"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@babel/parser": "^7.21.3",
|
|
40
|
+
"@babel/types": "^7.21.4",
|
|
41
|
+
"@clack/prompts": "^0.6.3",
|
|
42
|
+
"@cloudflare/eslint-config-worker": "*",
|
|
43
|
+
"@cloudflare/workers-tsconfig": "*",
|
|
44
|
+
"@cloudflare/workers-types": "^4.20230419.0",
|
|
45
|
+
"@types/command-exists": "^1.2.0",
|
|
46
|
+
"@types/cross-spawn": "^6.0.2",
|
|
47
|
+
"@types/esprima": "^4.0.3",
|
|
48
|
+
"@types/node": "^18.15.3",
|
|
49
|
+
"@types/which-pm-runs": "^1.0.0",
|
|
50
|
+
"@types/yargs": "^17.0.22",
|
|
51
|
+
"@typescript-eslint/eslint-plugin": "^5.55.0",
|
|
52
|
+
"@typescript-eslint/parser": "^5.55.0",
|
|
53
|
+
"chalk": "^5.2.0",
|
|
54
|
+
"command-exists": "^1.2.9",
|
|
55
|
+
"cross-spawn": "^7.0.3",
|
|
56
|
+
"esbuild": "^0.17.12",
|
|
57
|
+
"execa": "^7.1.1",
|
|
58
|
+
"haikunator": "^2.1.2",
|
|
59
|
+
"log-update": "^5.0.1",
|
|
60
|
+
"open": "^8.4.0",
|
|
61
|
+
"recast": "^0.22.0",
|
|
62
|
+
"typescript": "^5.0.2",
|
|
63
|
+
"undici": "^5.22.0",
|
|
64
|
+
"vite-tsconfig-paths": "^4.0.8",
|
|
65
|
+
"vitest": "^0.30.0",
|
|
66
|
+
"which-pm-runs": "^1.1.0",
|
|
67
|
+
"wrangler": "*",
|
|
68
|
+
"yargs": "^17.7.1"
|
|
69
|
+
},
|
|
70
|
+
"engines": {
|
|
71
|
+
"node": ">=16.13.0"
|
|
72
|
+
}
|
|
73
|
+
}
|
|
Binary file
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# Example ChatGPT Plugin for Cloudflare Workers
|
|
2
|
+
|
|
3
|
+
This is an example plugin showing how to build [ChatGPT plugins](https://platform.openai.com/docs/plugins/introduction) using [Cloudflare Workers](https://workers.dev). Using this example, you can deploy a plugin to Cloudflare Workers in just a few minutes.
|
|
4
|
+
|
|
5
|
+
The sample plugin allows ChatGPT users to search for repositories using GitHub's search API. The plugin is implemented in TypeScript and uses the [OpenAPI](https://www.openapis.org/) specification to define the plugin's API.
|
|
6
|
+
|
|
7
|
+

|
|
8
|
+
|
|
9
|
+
## Get started
|
|
10
|
+
|
|
11
|
+
0. Sign up for [Cloudflare Workers](https://workers.dev). The free tier is more than enough for most use cases.
|
|
12
|
+
1. Install [wrangler](https://developers.cloudflare.com/workers/cli-wrangler/install-update), the Cloudflare Workers CLI
|
|
13
|
+
2. Clone this project and install dependencies with `npm install`
|
|
14
|
+
3. Run `wrangler login` to login to your Cloudflare account in wrangler
|
|
15
|
+
4. Run `wrangler publish` to publish the plugin to Cloudflare Workers
|
|
16
|
+
|
|
17
|
+
## Usage
|
|
18
|
+
|
|
19
|
+
1. You can configure the `.well-known/ai-plugin.json` route in `index.ts`.
|
|
20
|
+
2. Update the OpenAPI schema in `openapi.ts`.
|
|
21
|
+
3. You can set up any new routes and the associated OpenAPI schema by defining new routes. See `search.ts` for an example.
|
|
22
|
+
|
|
23
|
+
## Deploying to OpenAI's API
|
|
24
|
+
|
|
25
|
+
Follow the instructions [in the ChatGPT documentation](https://platform.openai.com/docs/plugins/introduction/plugin-flow) to deploy your plugin and begin using it in ChatGPT.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "cloudflare-workers-chatgpt-plugin-example",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"private": true,
|
|
5
|
+
"scripts": {
|
|
6
|
+
"deploy": "wrangler publish",
|
|
7
|
+
"start": "wrangler dev"
|
|
8
|
+
},
|
|
9
|
+
"dependencies": {
|
|
10
|
+
"@cloudflare/itty-router-openapi": "^0.1.2"
|
|
11
|
+
},
|
|
12
|
+
"devDependencies": {
|
|
13
|
+
"@cloudflare/workers-types": "^4.20230404.0",
|
|
14
|
+
"wrangler": "^3.0.0"
|
|
15
|
+
}
|
|
16
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { OpenAPIRouter } from "@cloudflare/itty-router-openapi";
|
|
2
|
+
import { GetSearch } from "./search";
|
|
3
|
+
|
|
4
|
+
export const router = OpenAPIRouter({
|
|
5
|
+
schema: {
|
|
6
|
+
info: {
|
|
7
|
+
title: "GitHub Repositories Search API",
|
|
8
|
+
description:
|
|
9
|
+
"A plugin that allows the user to search for GitHub repositories using ChatGPT",
|
|
10
|
+
version: "v0.0.1",
|
|
11
|
+
},
|
|
12
|
+
},
|
|
13
|
+
docs_url: "/",
|
|
14
|
+
aiPlugin: {
|
|
15
|
+
name_for_human: "GitHub Repositories Search",
|
|
16
|
+
name_for_model: "github_repositories_search",
|
|
17
|
+
description_for_human: "GitHub Repositories Search plugin for ChatGPT.",
|
|
18
|
+
description_for_model:
|
|
19
|
+
"GitHub Repositories Search plugin for ChatGPT. You can search for GitHub repositories using this plugin.",
|
|
20
|
+
contact_email: "support@example.com",
|
|
21
|
+
legal_info_url: "http://www.example.com/legal",
|
|
22
|
+
logo_url: "https://workers.cloudflare.com/resources/logo/logo.svg",
|
|
23
|
+
},
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
router.get("/search", GetSearch);
|
|
27
|
+
|
|
28
|
+
// 404 for everything else
|
|
29
|
+
router.all("*", () => new Response("Not Found.", { status: 404 }));
|
|
30
|
+
|
|
31
|
+
export default {
|
|
32
|
+
fetch: router.handle,
|
|
33
|
+
};
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ApiException,
|
|
3
|
+
OpenAPIRoute,
|
|
4
|
+
Query,
|
|
5
|
+
ValidationError,
|
|
6
|
+
} from "@cloudflare/itty-router-openapi";
|
|
7
|
+
|
|
8
|
+
export class GetSearch extends OpenAPIRoute {
|
|
9
|
+
static schema = {
|
|
10
|
+
tags: ["Search"],
|
|
11
|
+
summary: "Search repositories by a query parameter",
|
|
12
|
+
parameters: {
|
|
13
|
+
q: Query(String, {
|
|
14
|
+
description: "The query to search for",
|
|
15
|
+
default: "cloudflare workers",
|
|
16
|
+
}),
|
|
17
|
+
},
|
|
18
|
+
responses: {
|
|
19
|
+
"200": {
|
|
20
|
+
schema: {
|
|
21
|
+
repos: [
|
|
22
|
+
{
|
|
23
|
+
name: "itty-router-openapi",
|
|
24
|
+
description:
|
|
25
|
+
"OpenAPI 3 schema generator and validator for Cloudflare Workers",
|
|
26
|
+
stars: "80",
|
|
27
|
+
url: "https://github.com/cloudflare/itty-router-openapi",
|
|
28
|
+
},
|
|
29
|
+
],
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
async handle(request: Request, env, ctx, data: Record<string, any>) {
|
|
36
|
+
const url = `https://api.github.com/search/repositories?q=${data.q}`;
|
|
37
|
+
|
|
38
|
+
const resp = await fetch(url, {
|
|
39
|
+
headers: {
|
|
40
|
+
Accept: "application/vnd.github.v3+json",
|
|
41
|
+
"User-Agent": "RepoAI - Cloudflare Workers ChatGPT Plugin Example",
|
|
42
|
+
},
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
if (!resp.ok) {
|
|
46
|
+
return new Response(await resp.text(), { status: 400 });
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const json = await resp.json();
|
|
50
|
+
|
|
51
|
+
// @ts-ignore
|
|
52
|
+
const repos = json.items.map((item: any) => ({
|
|
53
|
+
name: item.name,
|
|
54
|
+
description: item.description,
|
|
55
|
+
stars: item.stargazers_count,
|
|
56
|
+
url: item.html_url,
|
|
57
|
+
}));
|
|
58
|
+
|
|
59
|
+
return {
|
|
60
|
+
repos: repos,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "<TBD>",
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"private": true,
|
|
5
|
+
"scripts": {
|
|
6
|
+
"deploy": "wrangler publish",
|
|
7
|
+
"start": "wrangler dev"
|
|
8
|
+
},
|
|
9
|
+
"devDependencies": {
|
|
10
|
+
"@cloudflare/workers-types": "^4.20230419.0",
|
|
11
|
+
"itty-router": "^3.0.12",
|
|
12
|
+
"wrangler": "^3.0.0"
|
|
13
|
+
}
|
|
14
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
const ORIGIN_URL = 'https://example.com';
|
|
2
|
+
const EXPERIMENTS = [
|
|
3
|
+
{ name: 'big-button', threshold: 0.5 }, // enable the Big Button experiment for 50% of users
|
|
4
|
+
{ name: 'new-brand', threshold: 0.1 }, // enable the New Brand experiment for 10% of users
|
|
5
|
+
{ name: 'new-layout', threshold: 0.02 }, // enable the New Layout experiment for 2% of users
|
|
6
|
+
];
|
|
7
|
+
|
|
8
|
+
export default {
|
|
9
|
+
async fetch(request, env, ctx) {
|
|
10
|
+
const fingerprint = [request.headers.get('cf-connecting-ip'), request.cf?.postalCode]; // add any values you want considered as a fingerprint
|
|
11
|
+
const activeExperiments = await getActiveExperiments(fingerprint, EXPERIMENTS);
|
|
12
|
+
|
|
13
|
+
// add a data-experiments attribute to the <body> tag
|
|
14
|
+
// which can be styled in CSS with a wildcard selector like [data-experiments*="big-button"]
|
|
15
|
+
const rewriter = new HTMLRewriter().on('body', {
|
|
16
|
+
element(element) {
|
|
17
|
+
element.setAttribute('data-experiments', activeExperiments.join(' '));
|
|
18
|
+
},
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
const res = await fetch(ORIGIN_URL, request);
|
|
22
|
+
|
|
23
|
+
return rewriter.transform(res);
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
// Get active experiments by hashing a fingerprint
|
|
28
|
+
async function getActiveExperiments(fingerprint, experiments) {
|
|
29
|
+
const fingerprintHash = await hash('SHA-1', JSON.stringify(fingerprint));
|
|
30
|
+
const MAX_UINT8 = 255;
|
|
31
|
+
const activeExperiments = experiments.filter((exp, i) => fingerprintHash[i] <= exp.threshold * MAX_UINT8);
|
|
32
|
+
return activeExperiments.map((exp) => exp.name);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Hash a string using the Web Crypto API
|
|
36
|
+
async function hash(algorithm, message) {
|
|
37
|
+
const msgUint8 = new TextEncoder().encode(message); // encode as (utf-8) Uint8Array
|
|
38
|
+
const hashBuffer = await crypto.subtle.digest(algorithm, msgUint8); // hash the message
|
|
39
|
+
const hashArray = new Uint8Array(hashBuffer); // convert buffer to byte array
|
|
40
|
+
return hashArray;
|
|
41
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export default {
|
|
2
|
+
async fetch(request, env, ctx) {
|
|
3
|
+
const url = new URL(request.url);
|
|
4
|
+
|
|
5
|
+
const proxyUrl = url.searchParams.get('proxyUrl'); // get a query param value (?proxyUrl=...)
|
|
6
|
+
const modify = url.searchParams.has('modify'); // check if a query param is set (?proxyUrl=...&modify)
|
|
7
|
+
|
|
8
|
+
if (!proxyUrl) {
|
|
9
|
+
return new Response('Bad request: Missing `proxyUrl` query param', { status: 400 });
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// make subrequests with the global `fetch()` function
|
|
13
|
+
let res = await fetch(proxyUrl, request);
|
|
14
|
+
|
|
15
|
+
// optionally, modify the respone
|
|
16
|
+
if (modify) {
|
|
17
|
+
res = new Response(res.body, res);
|
|
18
|
+
res.headers.set('X-My-Header', 'My Header Value');
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
return res;
|
|
22
|
+
},
|
|
23
|
+
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export default {
|
|
2
|
+
async fetch(request, env, ctx) {
|
|
3
|
+
const url = new URL(request.url);
|
|
4
|
+
const redirectUrl = url.searchParams.get('redirectUrl'); // get a query param value (?redirectUrl=...)
|
|
5
|
+
|
|
6
|
+
if (!redirectUrl) {
|
|
7
|
+
return new Response('Bad request: Missing `redirectUrl` query param', { status: 400 });
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
// The Response class has static methods to create common Response objects as a convenience
|
|
11
|
+
return Response.redirect(redirectUrl);
|
|
12
|
+
},
|
|
13
|
+
};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { Router } from 'itty-router';
|
|
2
|
+
|
|
3
|
+
// now let's create a router (note the lack of "new")
|
|
4
|
+
const router = Router();
|
|
5
|
+
|
|
6
|
+
// GET collection index
|
|
7
|
+
router.get('/api/todos', () => new Response('Todos Index!'));
|
|
8
|
+
|
|
9
|
+
// GET item
|
|
10
|
+
router.get('/api/todos/:id', ({ params }) => new Response(`Todo #${params.id}`));
|
|
11
|
+
|
|
12
|
+
// POST to the collection (we'll use async here)
|
|
13
|
+
router.post('/api/todos', async (request) => {
|
|
14
|
+
const content = await request.json();
|
|
15
|
+
|
|
16
|
+
return new Response('Creating Todo: ' + JSON.stringify(content));
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
// 404 for everything else
|
|
20
|
+
router.all('*', () => new Response('Not Found.', { status: 404 }));
|
|
21
|
+
|
|
22
|
+
export default router;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Welcome to Cloudflare Workers! This is your first worker.
|
|
3
|
+
*
|
|
4
|
+
* - Run `npm run dev` in your terminal to start a development server
|
|
5
|
+
* - Open a browser tab at http://localhost:8787/ to see your worker in action
|
|
6
|
+
* - Run `npm run deploy` to publish your worker
|
|
7
|
+
*
|
|
8
|
+
* Learn more at https://developers.cloudflare.com/workers/
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import handleProxy from './proxy';
|
|
12
|
+
import handleRedirect from './redirect';
|
|
13
|
+
import apiRouter from './router';
|
|
14
|
+
|
|
15
|
+
// Export a default object containing event handlers
|
|
16
|
+
export default {
|
|
17
|
+
// The fetch handler is invoked when this worker receives a HTTP(S) request
|
|
18
|
+
// and should return a Response (optionally wrapped in a Promise)
|
|
19
|
+
async fetch(request, env, ctx) {
|
|
20
|
+
// You'll find it helpful to parse the request.url string into a URL object. Learn more at https://developer.mozilla.org/en-US/docs/Web/API/URL
|
|
21
|
+
const url = new URL(request.url);
|
|
22
|
+
|
|
23
|
+
// You can get pretty far with simple logic like if/switch-statements
|
|
24
|
+
switch (url.pathname) {
|
|
25
|
+
case '/redirect':
|
|
26
|
+
return handleRedirect.fetch(request, env, ctx);
|
|
27
|
+
|
|
28
|
+
case '/proxy':
|
|
29
|
+
return handleProxy.fetch(request, env, ctx);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
if (url.pathname.startsWith('/api/')) {
|
|
33
|
+
// You can also use more robust routing
|
|
34
|
+
return apiRouter.handle(request);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
return new Response(
|
|
38
|
+
`Try making requests to:
|
|
39
|
+
<ul>
|
|
40
|
+
<li><code><a href="/redirect?redirectUrl=https://example.com/">/redirect?redirectUrl=https://example.com/</a></code>,</li>
|
|
41
|
+
<li><code><a href="/proxy?modify&proxyUrl=https://example.com/">/proxy?modify&proxyUrl=https://example.com/</a></code>, or</li>
|
|
42
|
+
<li><code><a href="/api/todos">/api/todos</a></code></li>`,
|
|
43
|
+
{ headers: { 'Content-Type': 'text/html' } }
|
|
44
|
+
);
|
|
45
|
+
},
|
|
46
|
+
};
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
name = "<TBD>"
|
|
2
|
+
main = "src/worker.js"
|
|
3
|
+
compatibility_date = "2023-04-21"
|
|
4
|
+
|
|
5
|
+
# Variable bindings. These are arbitrary, plaintext strings (similar to environment variables)
|
|
6
|
+
# Note: Use secrets to store sensitive data.
|
|
7
|
+
# Docs: https://developers.cloudflare.com/workers/platform/environment-variables
|
|
8
|
+
# [vars]
|
|
9
|
+
# MY_VARIABLE = "production_value"
|
|
10
|
+
|
|
11
|
+
# Bind a KV Namespace. Use KV as persistent storage for small key-value pairs.
|
|
12
|
+
# Docs: https://developers.cloudflare.com/workers/runtime-apis/kv
|
|
13
|
+
# [[kv_namespaces]]
|
|
14
|
+
# binding = "MY_KV_NAMESPACE"
|
|
15
|
+
# id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
|
|
16
|
+
|
|
17
|
+
# Bind an R2 Bucket. Use R2 to store arbitrarily large blobs of data, such as files.
|
|
18
|
+
# Docs: https://developers.cloudflare.com/r2/api/workers/workers-api-usage/
|
|
19
|
+
# [[r2_buckets]]
|
|
20
|
+
# binding = "MY_BUCKET"
|
|
21
|
+
# bucket_name = "my-bucket"
|
|
22
|
+
|
|
23
|
+
# Bind a Queue producer. Use this binding to schedule an arbitrary task that may be processed later by a Queue consumer.
|
|
24
|
+
# Docs: https://developers.cloudflare.com/queues/get-started
|
|
25
|
+
# [[queues.producers]]
|
|
26
|
+
# binding = "MY_QUEUE"
|
|
27
|
+
# queue = "my-queue"
|
|
28
|
+
|
|
29
|
+
# Bind a Queue consumer. Queue Consumers can retrieve tasks scheduled by Producers to act on them.
|
|
30
|
+
# Docs: https://developers.cloudflare.com/queues/get-started
|
|
31
|
+
# [[queues.consumers]]
|
|
32
|
+
# queue = "my-queue"
|
|
33
|
+
|
|
34
|
+
# Bind another Worker service. Use this binding to call another Worker without network overhead.
|
|
35
|
+
# Docs: https://developers.cloudflare.com/workers/platform/services
|
|
36
|
+
# [[services]]
|
|
37
|
+
# binding = "MY_SERVICE"
|
|
38
|
+
# service = "/api/*"
|
|
39
|
+
|
|
40
|
+
# Bind a Durable Object. Durable objects are a scale-to-zero compute primitive based on the actor model.
|
|
41
|
+
# Durable Objects can live for as long as needed. Use these when you need a long-running "server", such as in realtime apps.
|
|
42
|
+
# Docs: https://developers.cloudflare.com/workers/runtime-apis/durable-objects
|
|
43
|
+
# [[durable_objects.bindings]]
|
|
44
|
+
# name = "MY_DURABLE_OBJECT"
|
|
45
|
+
# class_name = "MyDurableObject"
|
|
46
|
+
|
|
47
|
+
# Durable Object migrations.
|
|
48
|
+
# Docs: https://developers.cloudflare.com/workers/learning/using-durable-objects#configure-durable-object-classes-with-migrations
|
|
49
|
+
# [[migrations]]
|
|
50
|
+
# tag = "v1"
|
|
51
|
+
# new_classes = ["MyDurableObject"]
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "<TBD>",
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"private": true,
|
|
5
|
+
"scripts": {
|
|
6
|
+
"deploy": "wrangler publish",
|
|
7
|
+
"start": "wrangler dev"
|
|
8
|
+
},
|
|
9
|
+
"devDependencies": {
|
|
10
|
+
"@cloudflare/workers-types": "^4.20230419.0",
|
|
11
|
+
"itty-router": "^3.0.12",
|
|
12
|
+
"typescript": "^5.0.4",
|
|
13
|
+
"wrangler": "^3.0.0"
|
|
14
|
+
}
|
|
15
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
const ORIGIN_URL = 'https://example.com';
|
|
2
|
+
const EXPERIMENTS = [
|
|
3
|
+
{ name: 'big-button', threshold: 0.5 }, // enable the Big Button experiment for 50% of users
|
|
4
|
+
{ name: 'new-brand', threshold: 0.1 }, // enable the New Brand experiment for 10% of users
|
|
5
|
+
{ name: 'new-layout', threshold: 0.02 }, // enable the New Layout experiment for 2% of users
|
|
6
|
+
];
|
|
7
|
+
|
|
8
|
+
export default {
|
|
9
|
+
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
|
|
10
|
+
const fingerprint = [request.headers.get('cf-connecting-ip'), request.cf?.postalCode]; // add any values you want considered as a fingerprint
|
|
11
|
+
const activeExperiments = await getActiveExperiments(fingerprint, EXPERIMENTS);
|
|
12
|
+
|
|
13
|
+
// add a data-experiments attribute to the <body> tag
|
|
14
|
+
// which can be styled in CSS with a wildcard selector like [data-experiments*="big-button"]
|
|
15
|
+
const rewriter = new HTMLRewriter().on('body', {
|
|
16
|
+
element(element: Element) {
|
|
17
|
+
element.setAttribute('data-experiments', activeExperiments.join(' '));
|
|
18
|
+
},
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
const res = await fetch(ORIGIN_URL, request);
|
|
22
|
+
|
|
23
|
+
return rewriter.transform(res);
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
// Get active experiments by hashing a fingerprint
|
|
28
|
+
async function getActiveExperiments(fingerprint: unknown, experiments: Array<{ name: string; threshold: number }>) {
|
|
29
|
+
const fingerprintHash: Uint8Array = await hash('SHA-1', JSON.stringify(fingerprint));
|
|
30
|
+
const MAX_UINT8 = 255;
|
|
31
|
+
const activeExperiments = experiments.filter((exp, i) => fingerprintHash[i] <= exp.threshold * MAX_UINT8);
|
|
32
|
+
return activeExperiments.map((exp) => exp.name);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Hash a string using the Web Crypto API
|
|
36
|
+
async function hash(algorithm: 'SHA-1' | 'SHA-256' | 'SHA-512', message: string): Promise<Uint8Array> {
|
|
37
|
+
const msgUint8 = new TextEncoder().encode(message); // encode as (utf-8) Uint8Array
|
|
38
|
+
const hashBuffer = await crypto.subtle.digest(algorithm, msgUint8); // hash the message
|
|
39
|
+
const hashArray = new Uint8Array(hashBuffer); // convert buffer to byte array
|
|
40
|
+
return hashArray;
|
|
41
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export default {
|
|
2
|
+
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
|
|
3
|
+
const url = new URL(request.url);
|
|
4
|
+
|
|
5
|
+
const proxyUrl = url.searchParams.get('proxyUrl'); // get a query param value (?proxyUrl=...)
|
|
6
|
+
const modify = url.searchParams.has('modify'); // check if a query param is set (?proxyUrl=...&modify)
|
|
7
|
+
|
|
8
|
+
if (!proxyUrl) {
|
|
9
|
+
return new Response('Bad request: Missing `proxyUrl` query param', { status: 400 });
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// make subrequests with the global `fetch()` function
|
|
13
|
+
let res = await fetch(proxyUrl, request);
|
|
14
|
+
|
|
15
|
+
// optionally, modify the respone
|
|
16
|
+
if (modify) {
|
|
17
|
+
res = new Response(res.body, res);
|
|
18
|
+
res.headers.set('X-My-Header', 'My Header Value');
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
return res;
|
|
22
|
+
},
|
|
23
|
+
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export default {
|
|
2
|
+
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
|
|
3
|
+
const url = new URL(request.url);
|
|
4
|
+
const redirectUrl = url.searchParams.get('redirectUrl'); // get a query param value (?redirectUrl=...)
|
|
5
|
+
|
|
6
|
+
if (!redirectUrl) {
|
|
7
|
+
return new Response('Bad request: Missing `redirectUrl` query param', { status: 400 });
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
// The Response class has static methods to create common Response objects as a convenience
|
|
11
|
+
return Response.redirect(redirectUrl);
|
|
12
|
+
},
|
|
13
|
+
};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { Router } from 'itty-router';
|
|
2
|
+
|
|
3
|
+
// now let's create a router (note the lack of "new")
|
|
4
|
+
const router = Router();
|
|
5
|
+
|
|
6
|
+
// GET collection index
|
|
7
|
+
router.get('/api/todos', () => new Response('Todos Index!'));
|
|
8
|
+
|
|
9
|
+
// GET item
|
|
10
|
+
router.get('/api/todos/:id', ({ params }) => new Response(`Todo #${params.id}`));
|
|
11
|
+
|
|
12
|
+
// POST to the collection (we'll use async here)
|
|
13
|
+
router.post('/api/todos', async (request) => {
|
|
14
|
+
const content = await request.json();
|
|
15
|
+
|
|
16
|
+
return new Response('Creating Todo: ' + JSON.stringify(content));
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
// 404 for everything else
|
|
20
|
+
router.all('*', () => new Response('Not Found.', { status: 404 }));
|
|
21
|
+
|
|
22
|
+
export default router;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Welcome to Cloudflare Workers! This is your first worker.
|
|
3
|
+
*
|
|
4
|
+
* - Run `npm run dev` in your terminal to start a development server
|
|
5
|
+
* - Open a browser tab at http://localhost:8787/ to see your worker in action
|
|
6
|
+
* - Run `npm run deploy` to publish your worker
|
|
7
|
+
*
|
|
8
|
+
* Learn more at https://developers.cloudflare.com/workers/
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import handleProxy from './proxy';
|
|
12
|
+
import handleRedirect from './redirect';
|
|
13
|
+
import apiRouter from './router';
|
|
14
|
+
|
|
15
|
+
// Export a default object containing event handlers
|
|
16
|
+
export default {
|
|
17
|
+
// The fetch handler is invoked when this worker receives a HTTP(S) request
|
|
18
|
+
// and should return a Response (optionally wrapped in a Promise)
|
|
19
|
+
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
|
|
20
|
+
// You'll find it helpful to parse the request.url string into a URL object. Learn more at https://developer.mozilla.org/en-US/docs/Web/API/URL
|
|
21
|
+
const url = new URL(request.url);
|
|
22
|
+
|
|
23
|
+
// You can get pretty far with simple logic like if/switch-statements
|
|
24
|
+
switch (url.pathname) {
|
|
25
|
+
case '/redirect':
|
|
26
|
+
return handleRedirect.fetch(request, env, ctx);
|
|
27
|
+
|
|
28
|
+
case '/proxy':
|
|
29
|
+
return handleProxy.fetch(request, env, ctx);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
if (url.pathname.startsWith('/api/')) {
|
|
33
|
+
// You can also use more robust routing
|
|
34
|
+
return apiRouter.handle(request);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
return new Response(
|
|
38
|
+
`Try making requests to:
|
|
39
|
+
<ul>
|
|
40
|
+
<li><code><a href="/redirect?redirectUrl=https://example.com/">/redirect?redirectUrl=https://example.com/</a></code>,</li>
|
|
41
|
+
<li><code><a href="/proxy?modify&proxyUrl=https://example.com/">/proxy?modify&proxyUrl=https://example.com/</a></code>, or</li>
|
|
42
|
+
<li><code><a href="/api/todos">/api/todos</a></code></li>`,
|
|
43
|
+
{ headers: { 'Content-Type': 'text/html' } }
|
|
44
|
+
);
|
|
45
|
+
},
|
|
46
|
+
};
|