td-ai-tools 1.5.3 → 1.6.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.
- package/package.json +1 -1
- package/skills/README.md +2 -7
- package/skills/cloudflare/SKILL.md +9 -1
- package/skills/cloudflare/assets/wrangler.jsonc +11 -9
- package/skills/cloudflare/references/auth-and-accounts.md +1 -1
- package/skills/cloudflare/references/ci-cd.md +11 -6
- package/skills/cloudflare/references/data-d1-kv-r2.md +4 -4
- package/skills/cloudflare/references/deploy-and-release.md +2 -2
- package/skills/cloudflare/references/forms-email-turnstile.md +1 -1
- package/skills/cloudflare/references/launch-new-site.md +30 -49
- package/skills/cloudflare/references/observability-and-incidents.md +1 -1
- package/skills/cloudflare-init/SKILL.md +101 -0
- package/skills/cloudflare-init/agents/openai.yaml +4 -0
- package/skills/cloudflare-init/assets/placeholder-worker.js +15 -0
- package/skills/cloudflare-init/assets/worker.emdash.ts +10 -0
- package/skills/cloudflare-init/assets/wrangler.jsonc +65 -0
- package/skills/cloudflare-init/scripts/cloudflare-init.mjs +598 -0
package/package.json
CHANGED
package/skills/README.md
CHANGED
|
@@ -1,13 +1,11 @@
|
|
|
1
1
|
# skills
|
|
2
2
|
|
|
3
3
|
## Available Skills
|
|
4
|
-
- `
|
|
5
|
-
- `barrage`: Convert a group of Basecamp todos or cards into a td-barrage queue.json task file, and maintain an existing…
|
|
4
|
+
- `barrage`
|
|
6
5
|
- `basecamp`: Interact with Basecamp via the Basecamp CLI.
|
|
7
6
|
- `browser-validation`: Before completing a task validate frontend or template changes in a real browser with the Playwright-CLI…
|
|
8
|
-
- `cache-reset`: Clear and warm Laravel and Statamic caches (including Statamic Glide image caches) after content or template…
|
|
9
|
-
- `client-overview`: Generate a client-facing markdown report that summarizes all changes on the current branch against the…
|
|
10
7
|
- `cloudflare`: Operate Theory Digital's Cloudflare-hosted sites (Leyline / Astro on Workers) with wrangler and the…
|
|
8
|
+
- `cloudflare-init`: Provision the Cloudflare resources for a new Theory Digital / Leyline site before its domain is set up, with…
|
|
11
9
|
- `debugging-ios-webkit`: Debugs iOS Safari/Chrome-iOS rendering bugs — stale paints, viewport/browser-chrome clipping, mobile-only CSS…
|
|
12
10
|
- `forge-cli`: Manage Laravel Forge organizations, servers, sites, and provisioned resources with Forge CLI 2.x, falling…
|
|
13
11
|
- `horizon-component-migration`: Bundle Shopify Horizon components into a migration package for a different theme, including recursive…
|
|
@@ -18,9 +16,6 @@
|
|
|
18
16
|
- `shopify-cli`: Shopify CLI workflows for theme development.
|
|
19
17
|
- `shopify-lint`: Run Shopify CLI Theme Check and Theory Digital's bundled Liquid, JavaScript, and CSS rules together, linting…
|
|
20
18
|
- `shopify-pre-pr`: Prepare a Shopify theme branch for pull request.
|
|
21
|
-
- `stylesheet-migration`: Migrate Shopify Liquid `{% stylesheet %}` blocks into theme CSS assets using bundled Python scripts.
|
|
22
|
-
- `td-js-vanilla-rules`: Theory Digital vanilla JavaScript standards for Shopify theme work.
|
|
23
|
-
- `td-review`: Run parallel code review agents on a PR (including TD theme compliance) and produce a synthesized findings…
|
|
24
19
|
- `visual-regression`: Single-site visual regression workflow for comparing a live URL against a preview/staging URL in Playwright…
|
|
25
20
|
|
|
26
21
|
## Skill Structure Convention
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: cloudflare
|
|
3
|
-
version: 1.
|
|
3
|
+
version: 1.1.0
|
|
4
4
|
description: Operate Theory Digital's Cloudflare-hosted sites (Leyline / Astro on Workers) with wrangler and the Cloudflare API — launch a new site end to end, deploy and roll back, preview branches, manage secrets, D1/KV/R2, custom domains and DNS, zone settings (AI crawlers, redirects, caching, SSL), Turnstile, email routing, logs, CI/CD, account/profile switching, client handoff and decommissioning. Use this whenever the user mentions Cloudflare, wrangler, Workers, deploying/shipping/publishing a site, going live, a domain or DNS change, a rollback, a secret or env var, D1 migrations, "the site is down/500ing", tailing logs, or moving a site to a client's account — even if they don't say "Cloudflare" explicitly.
|
|
5
5
|
---
|
|
6
6
|
|
|
@@ -46,6 +46,7 @@ Read only the file for the task at hand. Each one is self-contained.
|
|
|
46
46
|
|
|
47
47
|
| Task | Read |
|
|
48
48
|
|---|---|
|
|
49
|
+
| Set up a new site's Cloudflare resources before it has a domain | the **`cloudflare-init`** skill (one script, standard names) |
|
|
49
50
|
| Launch a brand-new site (repo → live on its domain) | `references/launch-new-site.md` |
|
|
50
51
|
| Deploy, gradual rollout, preview a branch, roll back, check what's live | `references/deploy-and-release.md` |
|
|
51
52
|
| Login, auth profiles, multiple accounts, API tokens, token permissions | `references/auth-and-accounts.md` |
|
|
@@ -61,6 +62,13 @@ Read only the file for the task at hand. Each one is self-contained.
|
|
|
61
62
|
|
|
62
63
|
When a task spans several areas (a launch touches nearly all of them), follow the primary file. It points to the others at the step where they become relevant.
|
|
63
64
|
|
|
65
|
+
**Naming standard** (owned by `cloudflare-init`, which enforces it):
|
|
66
|
+
- The Worker is the project slug: the brand in kebab-case, e.g. `access-matting`, not the domain.
|
|
67
|
+
- Resources are `<slug>-<binding>`: D1 `<slug>-db`, KV `<slug>-session`, R2 `<slug>-media`.
|
|
68
|
+
- The Turnstile widget is `<slug>`, and the repo is `Theory-Digital/<slug>`.
|
|
69
|
+
- Each site gets its own rate-limit `namespace_id`.
|
|
70
|
+
- Name anything new you create for a site this way. Existing sites predate the standard; their deviations are listed in Leyline's `docs/sites.md` ("Known inconsistencies"). Use their real names, and don't rename them in passing.
|
|
71
|
+
|
|
64
72
|
## 4. Bundled tools
|
|
65
73
|
|
|
66
74
|
- `scripts/preflight.sh [dir]`: read-only orientation report (above).
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
//
|
|
1
|
+
// Reference config for a Leyline site on Cloudflare Workers. New sites: run the cloudflare-init skill,
|
|
2
|
+
// which provisions the resources and writes this file with the standard names filled in.
|
|
2
3
|
// Replace every <PLACEHOLDER>. Don't set "main" or "assets": @astrojs/cloudflare generates them
|
|
3
4
|
// into dist/server/wrangler.json at build time, and `wrangler deploy` reads that file.
|
|
4
5
|
{
|
|
5
6
|
"$schema": "node_modules/wrangler/config-schema.json",
|
|
6
|
-
"name": "<
|
|
7
|
+
"name": "<slug>",
|
|
7
8
|
// Pins every wrangler command in this repo to the right account (wrangler whoami lists IDs).
|
|
8
9
|
"account_id": "<ACCOUNT_ID>",
|
|
9
10
|
// Pin it and bump it deliberately (see site-lifecycle.md).
|
|
@@ -34,29 +35,30 @@
|
|
|
34
35
|
// npx wrangler email sending enable <domain>. Remove for the Postmark transport.
|
|
35
36
|
"send_email": [{ "name": "EMAIL", "allowed_sender_addresses": ["web@<DOMAIN>"] }],
|
|
36
37
|
|
|
37
|
-
// Forms with `persist`: store submissions. `npx wrangler d1 create <
|
|
38
|
+
// Forms with `persist`: store submissions. `npx wrangler d1 create <slug>-db --location wnam`
|
|
38
39
|
"d1_databases": [
|
|
39
40
|
{
|
|
40
41
|
"binding": "DB",
|
|
41
|
-
"database_name": "<
|
|
42
|
+
"database_name": "<slug>-db",
|
|
42
43
|
"database_id": "<DATABASE_ID>",
|
|
43
44
|
"migrations_dir": "migrations"
|
|
44
45
|
}
|
|
45
46
|
],
|
|
46
47
|
|
|
47
|
-
// Forms with `rateLimit`. namespace_id:
|
|
48
|
+
// Forms with `rateLimit`. namespace_id: unique in the account (cloudflare-init allocates 1 + the highest in use).
|
|
49
|
+
// Sites sharing an ID share counters.
|
|
48
50
|
"ratelimits": [
|
|
49
|
-
{ "name": "FORM_RATE_LIMITER", "namespace_id": "<
|
|
51
|
+
{ "name": "FORM_RATE_LIMITER", "namespace_id": "<NAMESPACE_ID>", "simple": { "limit": 5, "period": 60 } }
|
|
50
52
|
]
|
|
51
53
|
|
|
52
54
|
// Optional staging Worker. Bindings and vars do NOT inherit, so repeat them here.
|
|
53
55
|
// "env": {
|
|
54
56
|
// "staging": {
|
|
55
|
-
// "name": "<
|
|
57
|
+
// "name": "<slug>-staging",
|
|
56
58
|
// "routes": [{ "pattern": "staging.<domain>", "custom_domain": true }],
|
|
57
59
|
// "vars": { "PUBLIC_TURNSTILE_SITE_KEY": "<SITEKEY>" },
|
|
58
|
-
// "d1_databases": [{ "binding": "DB", "database_name": "<
|
|
59
|
-
// "ratelimits": [{ "name": "FORM_RATE_LIMITER", "namespace_id": "<
|
|
60
|
+
// "d1_databases": [{ "binding": "DB", "database_name": "<slug>-staging-db", "database_id": "<ID>", "migrations_dir": "migrations" }],
|
|
61
|
+
// "ratelimits": [{ "name": "FORM_RATE_LIMITER", "namespace_id": "<STAGING_NAMESPACE_ID>", "simple": { "limit": 5, "period": 60 } }]
|
|
60
62
|
// }
|
|
61
63
|
// }
|
|
62
64
|
}
|
|
@@ -41,7 +41,7 @@ Create tokens at dash.cloudflare.com → My Profile → API Tokens (user-owned),
|
|
|
41
41
|
Recommended permission sets:
|
|
42
42
|
|
|
43
43
|
**Site operator token** (used interactively with this skill):
|
|
44
|
-
- Account: Workers Scripts Edit · D1 Edit · Workers KV Storage Edit · Workers R2 Storage Edit · Turnstile Sites Edit · Account Settings Read
|
|
44
|
+
- Account: Workers Scripts Edit · D1 Edit · Workers KV Storage Edit · Workers R2 Storage Edit · Turnstile Sites Edit · Workers Builds Configuration Edit · Account Settings Read. This is the set `cloudflare-init` needs. Keep the token **user-owned**: the Builds API rejects account-owned tokens
|
|
45
45
|
- Zone (specific zones, or all zones in the account): Zone Read · DNS Edit · Zone Settings Edit · Workers Routes Edit · Bot Management Edit · Dynamic URL Redirects Edit (Single Redirects) · Cache Rules Edit · Email Routing Rules Edit · SSL and Certificates Edit
|
|
46
46
|
- Adding new zones needs **Zone: Edit** at the account level. Grant it only to tokens that launch sites.
|
|
47
47
|
|
|
@@ -6,11 +6,11 @@ There are two ways to deploy automatically. Pick one per site; using both causes
|
|
|
6
6
|
|---|---|---|
|
|
7
7
|
| Setup | Workflow file plus repo secrets | Connect the repo in the dashboard (Worker → Settings → Builds) |
|
|
8
8
|
| Runs | In GitHub, with your own test steps | In Cloudflare's build environment |
|
|
9
|
-
| PR previews | Via `versions upload --preview-alias`, commented on the PR |
|
|
10
|
-
| Migrations / secrets | Scriptable in the workflow |
|
|
11
|
-
| Good for | Sites
|
|
9
|
+
| PR previews | Via `versions upload --preview-alias`, commented on the PR | "Preview other branches" trigger: `versions upload`, URL posted in the GitHub check |
|
|
10
|
+
| Migrations / secrets | Scriptable in the workflow | Migrations in the deploy command (the standard trigger does this); runtime secrets live on the Worker |
|
|
11
|
+
| Good for | Sites not on Leyline updates that need custom CI steps | Leyline sites (the TD default; the update pipeline reads its preview check) |
|
|
12
12
|
|
|
13
|
-
The Theory Digital default is **
|
|
13
|
+
The Theory Digital default for Leyline sites is **Workers Builds**, set up by `cloudflare-init`. The Leyline update pipeline reads the preview URL that Workers Builds posts in its GitHub check. Use GitHub Actions only for a site that isn't on Leyline updates.
|
|
14
14
|
|
|
15
15
|
## GitHub Actions setup
|
|
16
16
|
|
|
@@ -36,9 +36,14 @@ Worker runtime secrets (`FORM_SIGNING_SECRET` etc.) stay on the Worker. Set them
|
|
|
36
36
|
|
|
37
37
|
## Workers Builds notes
|
|
38
38
|
|
|
39
|
-
-
|
|
39
|
+
- Standard triggers (created by `cloudflare-init`):
|
|
40
|
+
- **Deploy production** (`main`): `npm run build`, then `npx wrangler d1 migrations apply DB --remote && npx wrangler deploy`.
|
|
41
|
+
- **Preview other branches** (`*` except `main`): `npm run build`, then `npx wrangler versions upload`.
|
|
42
|
+
- Build cache on, and `NPM_TOKEN` a secret on both.
|
|
43
|
+
- The previews beta is off (`previews_enabled: false`). Turning it off deletes non-production triggers, so it's done before the preview trigger is created.
|
|
44
|
+
- The Builds API (`/accounts/{id}/builds/...`) needs a **user-owned** token with Workers Builds Configuration Edit; account-owned tokens get "Invalid token". `GET /builds/workers/{tag}/builds` lists builds, and `GET /builds/builds/{uuid}/logs` returns a build's log.
|
|
40
45
|
- Builds run in the account that owns the Worker, so the client's account needs the Git connection authorized there. For client-owned accounts, the client may need to approve the GitHub app.
|
|
41
|
-
- Inspect builds in the dashboard. There
|
|
46
|
+
- Inspect builds in the dashboard or through the Builds API (above). There is no first-class wrangler command for build logs.
|
|
42
47
|
|
|
43
48
|
## Troubleshooting CI
|
|
44
49
|
|
|
@@ -13,8 +13,8 @@
|
|
|
13
13
|
|
|
14
14
|
```bash
|
|
15
15
|
npx wrangler d1 list
|
|
16
|
-
npx wrangler d1 info acme-
|
|
17
|
-
npx wrangler d1 create acme-
|
|
16
|
+
npx wrangler d1 info acme-db # size, region, tables
|
|
17
|
+
npx wrangler d1 create acme-db --location wnam # (confirm) also --jurisdiction eu|us|fedramp for data residency (permanent)
|
|
18
18
|
```
|
|
19
19
|
|
|
20
20
|
### Migrations
|
|
@@ -52,7 +52,7 @@ npx wrangler d1 time-travel restore DB --timestamp 2026-10-01T12:00:00Z # (conf
|
|
|
52
52
|
A restore rewinds every table, including legitimate submissions received since then. Before a restore, export the current state, so lost rows can be re-inserted selectively. The restore prints a bookmark for the pre-restore state; record it, because it makes the restore itself undoable.
|
|
53
53
|
|
|
54
54
|
### Delete
|
|
55
|
-
`npx wrangler d1 delete acme-
|
|
55
|
+
`npx wrangler d1 delete acme-db` (confirm, and export first). Remove the binding from the config, or the next deploy fails.
|
|
56
56
|
|
|
57
57
|
## Form submissions: common queries
|
|
58
58
|
|
|
@@ -70,7 +70,7 @@ SELECT created_at, flags FROM leyline_submissions WHERE flags <> '[]' ORDER BY c
|
|
|
70
70
|
|
|
71
71
|
## EmDash on D1
|
|
72
72
|
|
|
73
|
-
Production EmDash sites use `@emdash-cms/cloudflare`'s `d1()` driver (see Leyline's `docs/CONTENT-MODEL.md`).
|
|
73
|
+
Production EmDash sites use `@emdash-cms/cloudflare`'s `d1()` driver (see Leyline's `docs/CONTENT-MODEL.md`). The standard (`cloudflare-init --emdash`) is one database, `<slug>-db` bound as `DB`, holding both EmDash content and Leyline form submissions, plus an R2 bucket `<slug>-media` bound as `MEDIA`. A restore therefore rewinds both, so export first and re-insert submissions selectively. Content seeding: `leyline-seed` generates seed JSON from a static site, and EmDash's CLI applies it. Treat a content-DB restore as an editor-visible event and tell the client.
|
|
74
74
|
|
|
75
75
|
## KV
|
|
76
76
|
|
|
@@ -91,10 +91,10 @@ Optional. Use it for clients who want sign-off before production. In `wrangler.j
|
|
|
91
91
|
```jsonc
|
|
92
92
|
"env": {
|
|
93
93
|
"staging": {
|
|
94
|
-
"name": "acme-
|
|
94
|
+
"name": "acme-staging", // explicit is clearer than the implicit suffix
|
|
95
95
|
"routes": [{ "pattern": "staging.acme.com", "custom_domain": true }],
|
|
96
96
|
"vars": { "PUBLIC_TURNSTILE_SITE_KEY": "1x00000000000000000000AA" },
|
|
97
|
-
"d1_databases": [{ "binding": "DB", "database_name": "acme-
|
|
97
|
+
"d1_databases": [{ "binding": "DB", "database_name": "acme-staging-db", "database_id": "…", "migrations_dir": "migrations" }]
|
|
98
98
|
}
|
|
99
99
|
}
|
|
100
100
|
```
|
|
@@ -43,7 +43,7 @@ confirmation: {
|
|
|
43
43
|
|
|
44
44
|
```bash
|
|
45
45
|
npx wrangler turnstile widget list
|
|
46
|
-
npx wrangler turnstile widget create
|
|
46
|
+
npx wrangler turnstile widget create acme --domain acme.com --domain www.acme.com --mode managed --json # (confirm)
|
|
47
47
|
npx wrangler turnstile widget get <sitekey>
|
|
48
48
|
npx wrangler turnstile widget update <sitekey> --domain acme.com --domain www.acme.com --domain staging.acme.com # (confirm)
|
|
49
49
|
```
|
|
@@ -6,9 +6,7 @@ The end-to-end runbook, from an empty directory (or a finished repo) to a site l
|
|
|
6
6
|
0. Gather inputs
|
|
7
7
|
1. Account and auth
|
|
8
8
|
2. Scaffold or adopt the repo
|
|
9
|
-
3. `wrangler.jsonc`
|
|
10
|
-
4. Data: D1 and rate limiting
|
|
11
|
-
5. Secrets and Turnstile
|
|
9
|
+
3–5. Provision with `cloudflare-init` (resources, secrets, Builds, `wrangler.jsonc`)
|
|
12
10
|
6. Build and preview locally
|
|
13
11
|
7. First deploy (workers.dev)
|
|
14
12
|
8. Get the zone onto Cloudflare
|
|
@@ -29,13 +27,15 @@ Ask for whatever the user hasn't supplied. Don't guess the account or the domain
|
|
|
29
27
|
| **Which Cloudflare account**: Theory Digital's, or the client's own? | Everything is created there; moving it later is real work (see `site-lifecycle.md`) |
|
|
30
28
|
| Is the domain **already a zone on Cloudflare**? Who controls the registrar? | Decides whether phase 8 is needed, and who has to change nameservers |
|
|
31
29
|
| Does the domain receive **email** today (MX records)? | A nameserver switch that drops MX/TXT records breaks the client's email. This is the most common launch disaster |
|
|
32
|
-
| Forms?
|
|
30
|
+
| Forms? Turnstile? Email transport (Cloudflare or Postmark)? | `cloudflare-init` flags (`--no-turnstile`), and phase 5's transport notes |
|
|
33
31
|
| Content source: static Markdown or EmDash? | EmDash on Workers needs its own D1 and, usually, R2 (see `data-d1-kv-r2.md`) |
|
|
34
32
|
| Locales | `site.locales`, and the sitemap check |
|
|
35
33
|
|
|
36
|
-
Naming
|
|
37
|
-
-
|
|
38
|
-
- D1
|
|
34
|
+
Naming (the `cloudflare-init` standard; its script enforces it):
|
|
35
|
+
- Slug: the brand in kebab-case, not the domain (`acme`, `access-matting`). The Worker is the slug, so it serves at `<slug>.theory-digital.workers.dev`.
|
|
36
|
+
- Resources are `<slug>-<binding>`: D1 `acme-db`, KV `acme-session`, R2 `acme-media`. The Turnstile widget is `acme`, and the repo is `Theory-Digital/acme`.
|
|
37
|
+
- Staging: `acme-staging`, with `acme-staging-db` and so on.
|
|
38
|
+
- Auth profile: `td` or `client-<client>`.
|
|
39
39
|
|
|
40
40
|
## 1. Account and auth
|
|
41
41
|
|
|
@@ -64,49 +64,29 @@ Set `site.url` to the **final production origin** now, even before the domain wo
|
|
|
64
64
|
|
|
65
65
|
Make sure `.gitignore` covers `.wrangler/`, `.dev.vars*`, and `dist/`.
|
|
66
66
|
|
|
67
|
-
## 3. `
|
|
67
|
+
## 3–5. Provision with `cloudflare-init`
|
|
68
68
|
|
|
69
|
-
|
|
69
|
+
Use the `cloudflare-init` skill. Its script creates everything that doesn't need the domain, under the standard names:
|
|
70
|
+
- D1 `<slug>-db` (WNAM), KV `<slug>-session`, and for EmDash R2 `<slug>-media`.
|
|
71
|
+
- Turnstile widget `<slug>`, on the workers.dev hosts.
|
|
72
|
+
- A rate-limit namespace unique in the account.
|
|
73
|
+
- The Worker, with `FORM_SIGNING_SECRET` and `TURNSTILE_SECRET_KEY` set.
|
|
74
|
+
- Workers Builds triggers, with `NPM_TOKEN`.
|
|
75
|
+
- `wrangler.jsonc` and `.dev.vars`.
|
|
70
76
|
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
## 4. Data: D1 and rate limiting
|
|
74
|
-
|
|
75
|
-
Skip this phase if forms don't use `persist` or `rateLimit`.
|
|
76
|
-
|
|
77
|
-
```bash
|
|
78
|
-
npx wrangler d1 create acme-site --location enam # (confirm) choose the location hint nearest the audience; Canada/US East → enam
|
|
79
|
-
```
|
|
80
|
-
|
|
81
|
-
Paste the returned `database_id` into `d1_databases`. Alternatively, run `--binding DB --update-config` to let wrangler write it, then check the `migrations_dir`. If the site or client is under EU data rules, use `--jurisdiction eu`. That choice can't be changed later.
|
|
77
|
+
It plans first, and changes nothing until it's re-run with `--apply` after the user agrees. For a client-owned account, pass `--account`.
|
|
82
78
|
|
|
79
|
+
Then, in the repo:
|
|
83
80
|
```bash
|
|
84
81
|
mkdir -p migrations
|
|
85
82
|
cp node_modules/@theory-digital/leyline/src/forms/migrations/*.sql migrations/
|
|
86
83
|
npx wrangler d1 migrations apply DB --local # for wrangler dev
|
|
87
84
|
```
|
|
85
|
+
The production trigger applies remote migrations before each deploy.
|
|
88
86
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
Rate limiting: the `ratelimits[].namespace_id` is a number you choose. It only has to be unique among the Workers in that account that shouldn't share counters. Use a distinct one per site (e.g. 1001, 1002, …) and record it in the README.
|
|
92
|
-
|
|
93
|
-
✅ `npx wrangler d1 list` shows the database, and the ID in the config isn't the `0000…` placeholder.
|
|
94
|
-
|
|
95
|
-
## 5. Secrets and Turnstile
|
|
87
|
+
Don't hand-pick a rate-limit `namespace_id` or copy one from another site. Sites that share one also share counters, because Leyline keys limits by `form:ip`.
|
|
96
88
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
Local first. Create `.dev.vars` (gitignored):
|
|
100
|
-
```
|
|
101
|
-
FORM_SIGNING_SECRET=<openssl rand -base64 48>
|
|
102
|
-
POSTMARK_SERVER_TOKEN=<from Postmark → server → API tokens> # Postmark transport only
|
|
103
|
-
```
|
|
104
|
-
|
|
105
|
-
Turnstile, if enabled. The widget needs the production hostname, plus `localhost` if you want it to work in dev:
|
|
106
|
-
```bash
|
|
107
|
-
npx wrangler turnstile widget create "acme site" --domain acme.com --domain www.acme.com --mode managed --json # (confirm)
|
|
108
|
-
```
|
|
109
|
-
Put the returned `sitekey` in `vars.PUBLIC_TURNSTILE_SITE_KEY` in `wrangler.jsonc`, and the `secret` in `.dev.vars` as `TURNSTILE_SECRET_KEY`. Treat the secret like a password. Don't repeat it back in chat beyond writing it to the file. For local development, Cloudflare's always-pass test keys work. The Leyline action check lets them through.
|
|
89
|
+
✅ The script's summary shows every resource as `exists`/`created`, with no `SKIP`. `bash scripts/preflight.sh` shows the right name and account.
|
|
110
90
|
|
|
111
91
|
Email transport (see `forms-email-turnstile.md` → "Choosing a transport"):
|
|
112
92
|
- **Cloudflare** (`transport: 'cloudflare'`): add the `send_email` binding to `wrangler.jsonc`. Onboarding the domain (`wrangler email sending enable`) needs the zone on Cloudflare DNS, so it waits for phase 8 if the zone is moving; until then the form only works in `wrangler dev` (logged, not sent).
|
|
@@ -124,21 +104,17 @@ Use this, not `astro preview`. In Astro 7.3 it returns 500s for prerendered page
|
|
|
124
104
|
|
|
125
105
|
## 7. First deploy (workers.dev) (confirm)
|
|
126
106
|
|
|
127
|
-
Deploying first to `<
|
|
107
|
+
Deploying first to `<slug>.<subdomain>.workers.dev` proves the Worker, bindings and secrets work before any DNS changes. Until then, `cloudflare-init` leaves a placeholder there (503, noindex).
|
|
128
108
|
|
|
109
|
+
Merge or push to `main`. The "Deploy production" Workers Builds trigger applies D1 migrations and deploys. Follow the build in the dashboard, or with `GET /builds/workers/{tag}/builds` (see `ci-cd.md`). Without Workers Builds, do it by hand:
|
|
129
110
|
```bash
|
|
130
111
|
npx wrangler d1 migrations apply DB --remote # (confirm)
|
|
131
112
|
npx astro build
|
|
132
113
|
npx wrangler deploy --tag "$(git rev-parse --short HEAD)" --message "Initial deploy" # (confirm)
|
|
133
|
-
printf %s "$(grep ^FORM_SIGNING_SECRET= .dev.vars | cut -d= -f2-)" | npx wrangler secret put FORM_SIGNING_SECRET # (confirm)
|
|
134
|
-
printf %s "$(grep ^POSTMARK_SERVER_TOKEN= .dev.vars | cut -d= -f2-)" | npx wrangler secret put POSTMARK_SERVER_TOKEN # Postmark transport only
|
|
135
|
-
# + TURNSTILE_SECRET_KEY if used
|
|
136
114
|
```
|
|
137
|
-
|
|
115
|
+
Secrets were set by `cloudflare-init` and survive deploys. Postmark transport only: `printf %s "$(grep ^POSTMARK_SERVER_TOKEN= .dev.vars | cut -d= -f2-)" | npx wrangler secret put POSTMARK_SERVER_TOKEN` (confirm). Rotating `FORM_SIGNING_SECRET` invalidates tokens that are already open in visitors' browsers.
|
|
138
116
|
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
✅ `bash scripts/verify-site.sh https://acme-site.<sub>.workers.dev --no-www-check`. Expect robots, sitemap and canonical warnings pointing at the production URL; that's correct. The form token endpoint should return 200.
|
|
117
|
+
✅ `bash scripts/verify-site.sh https://acme.<sub>.workers.dev --no-www-check`. Expect robots, sitemap and canonical warnings pointing at the production URL; that's correct. The form token endpoint should return 200.
|
|
142
118
|
|
|
143
119
|
## 8. Get the zone onto Cloudflare
|
|
144
120
|
|
|
@@ -163,7 +139,12 @@ Custom domains create the DNS record and certificate automatically. They **fail
|
|
|
163
139
|
|
|
164
140
|
Then build and deploy again. Add a www→apex redirect (or the reverse) as described in `zone-settings.md` → "Canonical host redirect". Using both hosts as custom domains plus a redirect rule is the simplest setup that gets an edge certificate on both.
|
|
165
141
|
|
|
166
|
-
|
|
142
|
+
Then finish what `cloudflare-init` left for launch (confirm each):
|
|
143
|
+
- Add `acme.com` and `www.acme.com` to the Turnstile widget `acme` (`forms-email-turnstile.md`).
|
|
144
|
+
- Run `npx wrangler email sending enable acme.com`, and lock the `EMAIL` binding to `"allowed_sender_addresses": ["web@acme.com"]`.
|
|
145
|
+
- Switch `production-url` in `.github/workflows/leyline-update.yml` to `https://acme.com`.
|
|
146
|
+
|
|
147
|
+
Keep `"workers_dev": true` and `preview_urls` on Leyline sites. The update pipeline tests previews on them, and Leyline serves the workers.dev host with `X-Robots-Tag: noindex`.
|
|
167
148
|
|
|
168
149
|
## 10. Zone settings (confirm)
|
|
169
150
|
|
|
@@ -63,7 +63,7 @@ There's also a query API (`/accounts/{account}/workers/observability/telemetry/q
|
|
|
63
63
|
```bash
|
|
64
64
|
curl -sS https://api.cloudflare.com/client/v4/graphql -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" -H 'Content-Type: application/json' --data '{
|
|
65
65
|
"query":"query($a:String!,$s:String!,$from:Date!){viewer{accounts(filter:{accountTag:$a}){workersInvocationsAdaptive(limit:31,filter:{scriptName:$s,date_geq:$from},orderBy:[date_ASC]){sum{requests errors} dimensions{date}}}}}",
|
|
66
|
-
"variables":{"a":"'"$CLOUDFLARE_ACCOUNT_ID"'","s":"acme
|
|
66
|
+
"variables":{"a":"'"$CLOUDFLARE_ACCOUNT_ID"'","s":"acme","from":"2026-09-01"}}' | jq
|
|
67
67
|
```
|
|
68
68
|
The token needs Account Analytics Read.
|
|
69
69
|
- Zone-level traffic (all hostnames, cache ratio, countries): `httpRequests1dGroups` on `zones(filter:{zoneTag:…})`.
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: cloudflare-init
|
|
3
|
+
version: 1.0.0
|
|
4
|
+
description: Provision the Cloudflare resources for a new Theory Digital / Leyline site before its domain is set up, with standard names. Creates the Worker, D1, SESSION KV, R2 media (EmDash), Turnstile widget, rate-limit namespace, Worker secrets and Workers Builds triggers, and writes the site's wrangler.jsonc. Static site by default; pass --emdash for an EmDash site. Use whenever the user is starting, setting up, bootstrapping or provisioning a new site or project on Cloudflare, or asks which names a new site's Worker, database or bucket should have.
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# cloudflare-init
|
|
8
|
+
|
|
9
|
+
A new site's Cloudflare setup is done by one idempotent script, not by hand. That keeps names and settings identical across projects. Everything that needs the domain (zone, DNS, routes, Email Sending onboarding, the production Turnstile hostname) happens later, at launch, with the `cloudflare` skill (`references/launch-new-site.md`, phases 8–11).
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
node <skill-dir>/scripts/cloudflare-init.mjs <slug> [--emdash] [--dir <site repo>] # plan (read-only)
|
|
13
|
+
node <skill-dir>/scripts/cloudflare-init.mjs <slug> [--emdash] [--dir <site repo>] --apply # do it
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Run it with no arguments, or with `--help`, for every option.
|
|
17
|
+
|
|
18
|
+
## 1. Pick the slug
|
|
19
|
+
|
|
20
|
+
Everything is named from one slug, so get it right first and confirm it with the user.
|
|
21
|
+
|
|
22
|
+
- Use the client's **brand** words in kebab-case, not the domain: `access-matting`, `rig-mats-alberta`, `house-of-xm`, `plainsman-mfg`. Domains change (landbouw launched as landbouwcivil.com), and a domain isn't known yet anyway.
|
|
23
|
+
- Lowercase `a-z0-9`, single hyphens between words, at most 40 characters. Keep abbreviations the way the brand writes them (`mfg`, `xm`). Don't add `-site`, `-web` or a TLD.
|
|
24
|
+
- The GitHub repo should be `Theory-Digital/<slug>` too. If the repo already exists under another name, pass `--repo`.
|
|
25
|
+
|
|
26
|
+
## 2. Naming standard
|
|
27
|
+
|
|
28
|
+
The script enforces this standard; it is listed here so you can answer naming questions without running it.
|
|
29
|
+
|
|
30
|
+
| Thing | Name | Example |
|
|
31
|
+
|---|---|---|
|
|
32
|
+
| Worker | `<slug>` | `access-matting` → `access-matting.theory-digital.workers.dev` |
|
|
33
|
+
| D1 (binding `DB`) | `<slug>-db` | `access-matting-db` |
|
|
34
|
+
| KV (binding `SESSION`) | `<slug>-session` | `access-matting-session` |
|
|
35
|
+
| R2 (binding `MEDIA`, EmDash only) | `<slug>-media` | `access-matting-media` |
|
|
36
|
+
| Turnstile widget | `<slug>` | `access-matting` |
|
|
37
|
+
| Rate limit (binding `FORM_RATE_LIMITER`) | `namespace_id` = 1 + the highest in the account | `1004` |
|
|
38
|
+
| Workers Builds triggers | `Deploy production`, `Preview other branches` | |
|
|
39
|
+
| GitHub repo | `Theory-Digital/<slug>` | |
|
|
40
|
+
|
|
41
|
+
The rule: the Worker is the slug, and every resource is `<slug>-<binding in lowercase>`. Binding names are fixed by Leyline and the Astro adapter.
|
|
42
|
+
|
|
43
|
+
**Near-miss guard.** The script compares names with `-`/`_` stripped against every existing Worker, D1, KV, R2, Turnstile widget and `Theory-Digital` repo. If anything matches without being the exact standard name (`accessmatting` vs `access-matting`, or a D1 called `<slug>` instead of `<slug>-db`), it stops with `CLASH` (exit 3). Don't reach for `--allow-similar` by reflex. Tell the user what clashed. Usually either the slug is wrong or the project already exists. Only pass the flag once they've decided.
|
|
44
|
+
|
|
45
|
+
## 3. Defaults and what gets created
|
|
46
|
+
|
|
47
|
+
| | Static (default) | `--emdash` |
|
|
48
|
+
|---|---|---|
|
|
49
|
+
| Compatibility | today's date, no flags | today's date, `nodejs_compat` |
|
|
50
|
+
| Entry | adapter default | `main: ./src/worker.ts` (written from `assets/worker.emdash.ts` if missing) + cron `* * * * *` for scheduled publishing |
|
|
51
|
+
| D1 `<slug>-db` | form submissions | EmDash content + form submissions |
|
|
52
|
+
| KV `<slug>-session` | ✓ | ✓ |
|
|
53
|
+
| R2 `<slug>-media` | — | ✓ |
|
|
54
|
+
| Email Sending `EMAIL` | binding, no sender allow-list until launch | same |
|
|
55
|
+
| Turnstile `<slug>` (managed) | ✓ unless `--no-turnstile` | same |
|
|
56
|
+
| Rate limit `FORM_RATE_LIMITER` (5/60s) | ✓ | ✓ |
|
|
57
|
+
|
|
58
|
+
On both variants:
|
|
59
|
+
- **Account**: Theory Digital (`cfb16515b630dbcddca02b1f6a2585ca`, Kyle@theorydigital.ca's Account). `--account` is for a client-owned account; confirm the ID with the user first.
|
|
60
|
+
- **Location**: D1 and R2 use `wnam` (closest to Alberta). Use `--location` only when the audience is elsewhere. It can't be changed after creation.
|
|
61
|
+
- **Worker**: if missing, a placeholder (503, `noindex`) is uploaded with the real bindings, `workers_dev`, `preview_urls` and observability. Secrets and Builds need the Worker to exist, and its live bindings reserve the rate-limit ID. The site's first build replaces the placeholder; secrets survive it.
|
|
62
|
+
- **Secrets**: `FORM_SIGNING_SECRET` (random) and `TURNSTILE_SECRET_KEY` (from the widget) go straight to the Worker and are never printed.
|
|
63
|
+
- **Local files** in `--dir`:
|
|
64
|
+
- `wrangler.jsonc`, from `assets/wrangler.jsonc`. An existing file that differs is diffed and kept unless you pass `--write-config`.
|
|
65
|
+
- `.dev.vars`, if missing, with a separate dev signing secret and Cloudflare's Turnstile test secret.
|
|
66
|
+
- **Workers Builds**:
|
|
67
|
+
- Turns the previews beta off.
|
|
68
|
+
- Creates "Deploy production" (`main`: `npm run build` / `npx wrangler d1 migrations apply DB --remote && npx wrangler deploy`) and "Preview other branches" (everything but `main`: `npm run build` / `npx wrangler versions upload`), with build cache on.
|
|
69
|
+
- Sets `NPM_TOKEN` as a secret on both.
|
|
70
|
+
- The repo connection and the account's build token are reused.
|
|
71
|
+
- **Turnstile domains**: `<slug>.theory-digital.workers.dev` and `theory-digital.workers.dev` (preview hosts). The production hostname is added at launch.
|
|
72
|
+
|
|
73
|
+
## 4. Flow
|
|
74
|
+
|
|
75
|
+
1. **Inputs.** Get the slug (§1), static or EmDash, and the site repo path. Ask only if the user hasn't said. The repo needs a `package.json`; otherwise the local files are skipped.
|
|
76
|
+
2. **Credentials** (check, never echo):
|
|
77
|
+
- `[ -n "$CLOUDFLARE_TOKEN" ] && echo set` is the TD shell convention. `CLOUDFLARE_API_TOKEN` overrides it.
|
|
78
|
+
- The token must be **user-owned** (the Builds API rejects account tokens) with edit on Workers Scripts, D1, Workers KV, Workers R2, Turnstile and Workers Builds Configuration.
|
|
79
|
+
- `NPM_TOKEN` (npm read token for `@theory-digital`) must be exported for the Builds env var.
|
|
80
|
+
- `gh auth status` must pass for the repo checks.
|
|
81
|
+
3. **Plan.** Run without `--apply`. Show the user the plan: names, what's `create` vs `exists`, the rate-limit ID, and any `CLASH`/`SKIP` lines.
|
|
82
|
+
4. **Apply** after the user says yes: the same command plus `--apply`. Creating Cloudflare resources is a write to the account, so the plan → yes → apply order is not optional.
|
|
83
|
+
5. **Finish what was skipped.** Builds skip when the repo doesn't exist yet or `NPM_TOKEN` isn't exported. Once fixed, re-run with `--only builds --apply`. Re-running is always safe: existing resources are reused, never recreated.
|
|
84
|
+
6. **Report and hand off.**
|
|
85
|
+
- The script prints a ready-to-paste `docs/sites.md` entry and next steps: copy Leyline's form migrations, commit `wrangler.jsonc`, push to `main` for the first build, then enrol in Leyline updates (`docs/sites.md`, "Enrolling a site").
|
|
86
|
+
- Relay those steps, along with any `!` warnings it printed.
|
|
87
|
+
|
|
88
|
+
## 5. Not covered here
|
|
89
|
+
|
|
90
|
+
- Domain, zone, DNS, routes or custom domains, Email Sending onboarding and the sender allow-list, the zone launch baseline: the `cloudflare` skill at launch.
|
|
91
|
+
- Postmark: an external service. The default transport is Cloudflare Email Sending. If a client needs Postmark, add `POSTMARK_SERVER_TOKEN` with `wrangler secret put` and drop the `EMAIL` binding.
|
|
92
|
+
- `IMAGES`: the Astro adapter adds the binding itself.
|
|
93
|
+
- Staging Workers, and moving or renaming an existing site's resources.
|
|
94
|
+
|
|
95
|
+
## Troubleshooting
|
|
96
|
+
|
|
97
|
+
- `token check failed`: the token is missing, expired, or can't see the account. Check `bash <cloudflare-skill>/scripts/cf-api.sh GET /user/tokens/verify`.
|
|
98
|
+
- `10000 Authentication error` on one step: the token lacks that product's permission. Add it to the token and re-run; finished steps are skipped.
|
|
99
|
+
- `Builds API ... Invalid token`: the token is account-owned. Use a user-owned one.
|
|
100
|
+
- Several build tokens: pass `--build-token <uuid>` (the script lists them).
|
|
101
|
+
- A step's API shape changed: the Builds API reference is at `https://developers.cloudflare.com/workers/ci-cd/builds/api-reference/index.md`.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// Uploaded by cloudflare-init so the Worker exists (for secrets and Workers Builds) before the
|
|
2
|
+
// site's first build. The first `wrangler deploy` from Workers Builds replaces it; secrets stay.
|
|
3
|
+
export default {
|
|
4
|
+
fetch() {
|
|
5
|
+
return new Response('This site has not been deployed yet.\n', {
|
|
6
|
+
status: 503,
|
|
7
|
+
headers: {
|
|
8
|
+
'content-type': 'text/plain; charset=utf-8',
|
|
9
|
+
'cache-control': 'no-store',
|
|
10
|
+
'retry-after': '3600',
|
|
11
|
+
'x-robots-tag': 'noindex',
|
|
12
|
+
},
|
|
13
|
+
});
|
|
14
|
+
},
|
|
15
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// Worker entry for an EmDash site (wrangler.jsonc "main"): the Astro/EmDash handler, plus the
|
|
2
|
+
// scheduled handler that the cron trigger runs for scheduled publishing and cleanup.
|
|
3
|
+
import handler, { createScheduledHandler, PluginBridge } from '@emdash-cms/cloudflare/worker';
|
|
4
|
+
|
|
5
|
+
export { PluginBridge };
|
|
6
|
+
|
|
7
|
+
export default {
|
|
8
|
+
...handler,
|
|
9
|
+
scheduled: createScheduledHandler(),
|
|
10
|
+
} satisfies ExportedHandler;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// Generated by cloudflare-init ({{VARIANT}} site). Names follow the cloudflare-init naming standard:
|
|
2
|
+
// the Worker is the project slug, and each resource is `<slug>-<binding>`. Don't rename them by hand.
|
|
3
|
+
{
|
|
4
|
+
"$schema": "node_modules/wrangler/config-schema.json",
|
|
5
|
+
"name": "{{SLUG}}",
|
|
6
|
+
// {{ACCOUNT_NAME}}. Pins every wrangler command in this repo to it.
|
|
7
|
+
"account_id": "{{ACCOUNT_ID}}",
|
|
8
|
+
"compatibility_date": "{{COMPAT_DATE}}",
|
|
9
|
+
//#if emdash
|
|
10
|
+
"compatibility_flags": ["nodejs_compat"],
|
|
11
|
+
// EmDash's Worker entry: the adapter's handler plus the scheduled handler (scheduled publishing, cleanup).
|
|
12
|
+
"main": "./src/worker.ts",
|
|
13
|
+
"triggers": { "crons": ["* * * * *"] },
|
|
14
|
+
//#endif
|
|
15
|
+
|
|
16
|
+
// Launch: once the zone is active on Cloudflare, attach the domain here (cloudflare skill,
|
|
17
|
+
// references/launch-new-site.md, phase 9) and switch the Leyline workflow's production-url.
|
|
18
|
+
// "routes": [
|
|
19
|
+
// { "pattern": "<domain>", "custom_domain": true },
|
|
20
|
+
// { "pattern": "www.<domain>", "custom_domain": true },
|
|
21
|
+
// ],
|
|
22
|
+
// Until launch the site is served (noindex) at https://{{WORKERS_DEV_HOST}}.
|
|
23
|
+
"workers_dev": true,
|
|
24
|
+
// Per-version preview URLs: the Leyline update pipeline tests each PR on one.
|
|
25
|
+
"preview_urls": true,
|
|
26
|
+
|
|
27
|
+
"observability": { "enabled": true, "head_sampling_rate": 1 },
|
|
28
|
+
//#if turnstile
|
|
29
|
+
|
|
30
|
+
// Turnstile widget "{{SLUG}}" (managed). TURNSTILE_SECRET_KEY is a Worker secret.
|
|
31
|
+
"vars": { "PUBLIC_TURNSTILE_SITE_KEY": "{{TURNSTILE_SITEKEY}}" },
|
|
32
|
+
//#endif
|
|
33
|
+
|
|
34
|
+
// Secrets (never in this file): FORM_SIGNING_SECRET{{SECRETS_EXTRA}}
|
|
35
|
+
// local: .dev.vars production: set by cloudflare-init (npx wrangler secret put NAME to rotate)
|
|
36
|
+
|
|
37
|
+
"d1_databases": [
|
|
38
|
+
{
|
|
39
|
+
"binding": "DB",
|
|
40
|
+
//#if emdash
|
|
41
|
+
// EmDash content and Leyline form submissions.
|
|
42
|
+
//#endif
|
|
43
|
+
"database_name": "{{SLUG}}-db",
|
|
44
|
+
"database_id": "{{D1_ID}}",
|
|
45
|
+
"migrations_dir": "migrations",
|
|
46
|
+
},
|
|
47
|
+
],
|
|
48
|
+
// Astro sessions (the adapter binds SESSION). Declared so wrangler doesn't auto-provision another one.
|
|
49
|
+
"kv_namespaces": [{ "binding": "SESSION", "id": "{{KV_ID}}" }],
|
|
50
|
+
//#if emdash
|
|
51
|
+
// EmDash media library.
|
|
52
|
+
"r2_buckets": [{ "binding": "MEDIA", "bucket_name": "{{SLUG}}-media" }],
|
|
53
|
+
//#endif
|
|
54
|
+
|
|
55
|
+
// Cloudflare Email Sending for form notifications and visitor confirmations.
|
|
56
|
+
// Launch: `npx wrangler email sending enable <domain>`, then lock the sender:
|
|
57
|
+
// "allowed_sender_addresses": ["web@<domain>"]
|
|
58
|
+
"send_email": [{ "name": "EMAIL" }],
|
|
59
|
+
|
|
60
|
+
// Form rate limiting. namespace_id is allocated by cloudflare-init and unique in the account:
|
|
61
|
+
// never copy it from another site, or the sites share counters.
|
|
62
|
+
"ratelimits": [
|
|
63
|
+
{ "name": "FORM_RATE_LIMITER", "namespace_id": "{{RATELIMIT_ID}}", "simple": { "limit": 5, "period": 60 } },
|
|
64
|
+
],
|
|
65
|
+
}
|
|
@@ -0,0 +1,598 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// cloudflare-init: provisions the Cloudflare side of a new Leyline site before its domain exists,
|
|
3
|
+
// with standard names. Read-only plan by default; --apply makes the changes. Idempotent: anything
|
|
4
|
+
// that already exists under its standard name is reused, so re-running finishes a partial run.
|
|
5
|
+
//
|
|
6
|
+
// Usage: cloudflare-init.mjs <slug> [options]
|
|
7
|
+
// --emdash EmDash site (default: static). Adds R2 media, nodejs_compat, the cron entry.
|
|
8
|
+
// --apply Make the changes. Without it, print the plan and change nothing.
|
|
9
|
+
// --dir <path> Site repo to write wrangler.jsonc, .dev.vars (and src/worker.ts) into. Default: .
|
|
10
|
+
// --repo <owner/name> GitHub repo for Workers Builds. Default: Theory-Digital/<slug>
|
|
11
|
+
// --location <hint> D1/R2 location hint (wnam, enam, weur, eeur, apac, oc). Default: wnam
|
|
12
|
+
// --no-turnstile Skip the Turnstile widget, var and secret.
|
|
13
|
+
// --account <id> Cloudflare account. Default: Theory Digital (Kyle@theorydigital.ca's Account)
|
|
14
|
+
// --only <steps> Comma list of: resources,config,worker,secrets,builds. Default: all.
|
|
15
|
+
// --build-token <uuid> Workers Builds build token, when the account has more than one.
|
|
16
|
+
// --allow-similar Proceed despite near-miss names (e.g. accessmatting vs access-matting).
|
|
17
|
+
// --write-config Overwrite an existing wrangler.jsonc that differs from the standard one.
|
|
18
|
+
//
|
|
19
|
+
// Auth: CLOUDFLARE_API_TOKEN, else CLOUDFLARE_TOKEN (never printed). Needs Workers Scripts, D1,
|
|
20
|
+
// Workers KV, Workers R2, Turnstile and Workers Builds Configuration edit on the account (user-owned
|
|
21
|
+
// token: the Builds API rejects account-owned ones). NPM_TOKEN (npm read token) is set on the build
|
|
22
|
+
// triggers when exported. `gh` must be logged in for the builds step.
|
|
23
|
+
// Exit codes: 0 ok, 1 error, 2 usage, 3 plan has clashes.
|
|
24
|
+
|
|
25
|
+
import { execFileSync } from 'node:child_process';
|
|
26
|
+
import { randomBytes } from 'node:crypto';
|
|
27
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';
|
|
28
|
+
import { tmpdir } from 'node:os';
|
|
29
|
+
import { dirname, join, resolve } from 'node:path';
|
|
30
|
+
import { fileURLToPath } from 'node:url';
|
|
31
|
+
|
|
32
|
+
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
33
|
+
const ASSETS = join(HERE, '..', 'assets');
|
|
34
|
+
const API = 'https://api.cloudflare.com/client/v4';
|
|
35
|
+
const DEFAULT_ACCOUNT = 'cfb16515b630dbcddca02b1f6a2585ca';
|
|
36
|
+
const GH_ORG = 'Theory-Digital';
|
|
37
|
+
const SLUG_RE = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;
|
|
38
|
+
const LOCATIONS = ['wnam', 'enam', 'weur', 'eeur', 'apac', 'oc'];
|
|
39
|
+
const STEPS = ['resources', 'config', 'worker', 'secrets', 'builds'];
|
|
40
|
+
const RATELIMIT_BASE = 1000; // first allocated ID is 1001
|
|
41
|
+
const TURNSTILE_TEST = { site: '1x00000000000000000000AA', secret: '1x0000000000000000000000000000000AA' };
|
|
42
|
+
const TRIGGERS = {
|
|
43
|
+
production: {
|
|
44
|
+
trigger_name: 'Deploy production',
|
|
45
|
+
branch_includes: ['main'],
|
|
46
|
+
branch_excludes: [],
|
|
47
|
+
build_command: 'npm run build',
|
|
48
|
+
deploy_command: 'npx wrangler d1 migrations apply DB --remote && npx wrangler deploy',
|
|
49
|
+
},
|
|
50
|
+
preview: {
|
|
51
|
+
trigger_name: 'Preview other branches',
|
|
52
|
+
branch_includes: ['*'],
|
|
53
|
+
branch_excludes: ['main'],
|
|
54
|
+
build_command: 'npm run build',
|
|
55
|
+
deploy_command: 'npx wrangler versions upload',
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
// --- args -----------------------------------------------------------------------------------
|
|
60
|
+
|
|
61
|
+
function usage(code = 2) {
|
|
62
|
+
const text = readFileSync(fileURLToPath(import.meta.url), 'utf8').split('\n');
|
|
63
|
+
console.error(text.slice(1, 23).map((l) => l.replace(/^\/\/ ?/, '')).join('\n'));
|
|
64
|
+
process.exit(code);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const opts = { emdash: false, apply: false, dir: '.', location: 'wnam', turnstile: true, account: DEFAULT_ACCOUNT, only: STEPS, allowSimilar: false, writeConfig: false };
|
|
68
|
+
{
|
|
69
|
+
const argv = process.argv.slice(2);
|
|
70
|
+
const take = (i, flag) => {
|
|
71
|
+
if (argv[i + 1] === undefined || argv[i + 1].startsWith('--')) die(`${flag} needs a value`, 2);
|
|
72
|
+
return argv[i + 1];
|
|
73
|
+
};
|
|
74
|
+
for (let i = 0; i < argv.length; i++) {
|
|
75
|
+
const a = argv[i];
|
|
76
|
+
switch (a) {
|
|
77
|
+
case '-h': case '--help': usage(0); break;
|
|
78
|
+
case '--emdash': opts.emdash = true; break;
|
|
79
|
+
case '--apply': opts.apply = true; break;
|
|
80
|
+
case '--no-turnstile': opts.turnstile = false; break;
|
|
81
|
+
case '--allow-similar': opts.allowSimilar = true; break;
|
|
82
|
+
case '--write-config': opts.writeConfig = true; break;
|
|
83
|
+
case '--dir': opts.dir = take(i++, a); break;
|
|
84
|
+
case '--repo': opts.repo = take(i++, a); break;
|
|
85
|
+
case '--location': opts.location = take(i++, a); break;
|
|
86
|
+
case '--account': opts.account = take(i++, a); break;
|
|
87
|
+
case '--build-token': opts.buildToken = take(i++, a); break;
|
|
88
|
+
case '--only': opts.only = take(i++, a).split(',').map((s) => s.trim()).filter(Boolean); break;
|
|
89
|
+
default:
|
|
90
|
+
if (a.startsWith('-')) die(`unknown option ${a}`, 2);
|
|
91
|
+
if (opts.slug) die('one slug only', 2);
|
|
92
|
+
opts.slug = a;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
if (!opts.slug) usage();
|
|
96
|
+
if (!SLUG_RE.test(opts.slug) || opts.slug.length > 40)
|
|
97
|
+
die(`slug "${opts.slug}" must be kebab-case brand words (a-z, 0-9, single hyphens), at most 40 characters`, 2);
|
|
98
|
+
if (!LOCATIONS.includes(opts.location)) die(`--location must be one of ${LOCATIONS.join(', ')}`, 2);
|
|
99
|
+
for (const s of opts.only) if (!STEPS.includes(s)) die(`--only takes ${STEPS.join(',')}`, 2);
|
|
100
|
+
opts.repo ??= `${GH_ORG}/${opts.slug}`;
|
|
101
|
+
opts.dir = resolve(opts.dir);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const S = opts.slug;
|
|
105
|
+
const NAMES = {
|
|
106
|
+
worker: S,
|
|
107
|
+
d1: `${S}-db`,
|
|
108
|
+
kv: `${S}-session`,
|
|
109
|
+
r2: `${S}-media`,
|
|
110
|
+
turnstile: S,
|
|
111
|
+
};
|
|
112
|
+
const wants = (step) => opts.only.includes(step);
|
|
113
|
+
const TOKEN = process.env.CLOUDFLARE_API_TOKEN || process.env.CLOUDFLARE_TOKEN;
|
|
114
|
+
if (!TOKEN) die('set CLOUDFLARE_TOKEN (or CLOUDFLARE_API_TOKEN); see the cloudflare skill, references/auth-and-accounts.md');
|
|
115
|
+
|
|
116
|
+
// --- helpers --------------------------------------------------------------------------------
|
|
117
|
+
|
|
118
|
+
function die(msg, code = 1) {
|
|
119
|
+
console.error(`cloudflare-init: ${msg}`);
|
|
120
|
+
process.exit(code);
|
|
121
|
+
}
|
|
122
|
+
const norm = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, '');
|
|
123
|
+
const ACC = `/accounts/${opts.account}`;
|
|
124
|
+
|
|
125
|
+
class ApiError extends Error {
|
|
126
|
+
constructor(method, path, errors) {
|
|
127
|
+
super(`${method} ${path}: ${errors.map((e) => `${e.code} ${e.message}`).join('; ') || 'request failed'}`);
|
|
128
|
+
this.codes = errors.map((e) => e.code);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async function api(method, path, body, { raw = false } = {}) {
|
|
133
|
+
const init = { method, headers: { Authorization: `Bearer ${TOKEN}` } };
|
|
134
|
+
if (body instanceof FormData) init.body = body;
|
|
135
|
+
else if (body !== undefined) {
|
|
136
|
+
init.headers['Content-Type'] = 'application/json';
|
|
137
|
+
init.body = JSON.stringify(body);
|
|
138
|
+
}
|
|
139
|
+
const res = await fetch(API + path, init);
|
|
140
|
+
const json = await res.json().catch(() => ({ success: false, errors: [{ code: res.status, message: res.statusText }] }));
|
|
141
|
+
if (!json.success) throw new ApiError(method, path, json.errors ?? []);
|
|
142
|
+
return raw ? json : json.result;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async function listAll(path, pick = (r) => r) {
|
|
146
|
+
const out = [];
|
|
147
|
+
for (let page = 1; ; page++) {
|
|
148
|
+
const sep = path.includes('?') ? '&' : '?';
|
|
149
|
+
const json = await api('GET', `${path}${sep}page=${page}&per_page=100`, undefined, { raw: true });
|
|
150
|
+
const items = pick(json.result) ?? [];
|
|
151
|
+
out.push(...items);
|
|
152
|
+
const info = json.result_info;
|
|
153
|
+
if (!info || items.length < 100 || (info.total_pages && page >= info.total_pages)) break;
|
|
154
|
+
}
|
|
155
|
+
return out;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function gh(args, json = true) {
|
|
159
|
+
try {
|
|
160
|
+
const out = execFileSync('gh', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 64 * 1024 * 1024 });
|
|
161
|
+
return json ? JSON.parse(out) : out;
|
|
162
|
+
} catch {
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Strips comments and trailing commas from JSONC, leaving strings alone. */
|
|
168
|
+
function parseJsonc(text) {
|
|
169
|
+
let out = '';
|
|
170
|
+
for (let i = 0; i < text.length; i++) {
|
|
171
|
+
const c = text[i];
|
|
172
|
+
if (c === '"') {
|
|
173
|
+
let j = i + 1;
|
|
174
|
+
while (j < text.length && text[j] !== '"') j += text[j] === '\\' ? 2 : 1;
|
|
175
|
+
out += text.slice(i, j + 1);
|
|
176
|
+
i = j;
|
|
177
|
+
} else if (c === '/' && text[i + 1] === '/') {
|
|
178
|
+
while (i < text.length && text[i] !== '\n') i++;
|
|
179
|
+
out += '\n';
|
|
180
|
+
} else if (c === '/' && text[i + 1] === '*') {
|
|
181
|
+
i = text.indexOf('*/', i + 2) + 1;
|
|
182
|
+
} else out += c;
|
|
183
|
+
}
|
|
184
|
+
return JSON.parse(out.replace(/,(\s*[}\]])/g, '$1'));
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const rows = [];
|
|
188
|
+
let clashes = 0;
|
|
189
|
+
function row(kind, name, status, detail = '') {
|
|
190
|
+
rows.push({ kind, name, status, detail });
|
|
191
|
+
if (status === 'CLASH') clashes++;
|
|
192
|
+
}
|
|
193
|
+
function printRows() {
|
|
194
|
+
const w = [0, 0, 0].map((_, i) => Math.max(...rows.map((r) => [r.kind, r.name, r.status][i].length)));
|
|
195
|
+
for (const r of rows) console.log(` ${r.kind.padEnd(w[0])} ${r.name.padEnd(w[1])} ${r.status.padEnd(w[2])} ${r.detail}`);
|
|
196
|
+
rows.length = 0;
|
|
197
|
+
}
|
|
198
|
+
const step = (t) => console.log(`\n▶ ${t}`);
|
|
199
|
+
const verb = (created) => (opts.apply ? (created ? 'created' : 'exists') : created ? 'create' : 'exists');
|
|
200
|
+
|
|
201
|
+
// --- 1. preflight ---------------------------------------------------------------------------
|
|
202
|
+
|
|
203
|
+
step(`Preflight: ${S} (${opts.emdash ? 'EmDash' : 'static'}), ${opts.apply ? 'APPLY' : 'plan only'}`);
|
|
204
|
+
let account;
|
|
205
|
+
try {
|
|
206
|
+
await api('GET', '/user/tokens/verify');
|
|
207
|
+
account = await api('GET', ACC);
|
|
208
|
+
} catch (e) {
|
|
209
|
+
die(`token check failed (${e.message}). The token must be user-owned and see account ${opts.account}.`);
|
|
210
|
+
}
|
|
211
|
+
const subdomain = (await api('GET', `${ACC}/workers/subdomain`)).subdomain;
|
|
212
|
+
const host = `${S}.${subdomain}.workers.dev`;
|
|
213
|
+
console.log(` account ${account.name} (${account.id})`);
|
|
214
|
+
console.log(` host https://${host}`);
|
|
215
|
+
|
|
216
|
+
const [workers, d1s, kvs, r2s, widgets] = await Promise.all([
|
|
217
|
+
api('GET', `${ACC}/workers/scripts`),
|
|
218
|
+
listAll(`${ACC}/d1/database`),
|
|
219
|
+
listAll(`${ACC}/storage/kv/namespaces`),
|
|
220
|
+
api('GET', `${ACC}/r2/buckets?per_page=1000`).then((r) => r.buckets ?? []),
|
|
221
|
+
listAll(`${ACC}/challenges/widgets`),
|
|
222
|
+
]);
|
|
223
|
+
const existing = {
|
|
224
|
+
worker: workers.map((w) => ({ name: w.id, id: w.tag })),
|
|
225
|
+
d1: d1s.map((d) => ({ name: d.name, id: d.uuid })),
|
|
226
|
+
kv: kvs.map((k) => ({ name: k.title, id: k.id })),
|
|
227
|
+
r2: r2s.map((b) => ({ name: b.name, id: b.name })),
|
|
228
|
+
turnstile: widgets.map((w) => ({ name: w.name, id: w.sitekey })),
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
// Near-miss guard: anything whose normalized name matches one of this project's standard names
|
|
232
|
+
// (or the bare slug) but isn't the exact standard name for its kind.
|
|
233
|
+
const targets = new Set([S, ...Object.values(NAMES)].map(norm));
|
|
234
|
+
for (const [kind, list] of Object.entries(existing)) {
|
|
235
|
+
for (const r of list) {
|
|
236
|
+
if (r.name === NAMES[kind]) continue;
|
|
237
|
+
if (targets.has(norm(r.name))) row(kind, r.name, 'CLASH', `near-miss of ${NAMES[kind]}: rename, reuse it deliberately, or pick another slug`);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
const orgRepos = gh(['api', '--paginate', `orgs/${GH_ORG}/repos?per_page=100`, '--jq', '.[].name'], false)?.split('\n').filter(Boolean) ?? [];
|
|
241
|
+
if (!orgRepos.length) console.log(` ! couldn't list ${GH_ORG} repos (gh auth status?): repo near-miss check skipped`);
|
|
242
|
+
const repoName = opts.repo.split('/')[1];
|
|
243
|
+
for (const r of orgRepos) {
|
|
244
|
+
if (r !== repoName && norm(r) === norm(S)) row('repo', `${GH_ORG}/${r}`, 'CLASH', `near-miss of ${opts.repo}; pass --repo ${GH_ORG}/${r} if this is the site`);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const pkgPath = join(opts.dir, 'package.json');
|
|
248
|
+
const pkg = existsSync(pkgPath) ? JSON.parse(readFileSync(pkgPath, 'utf8')) : null;
|
|
249
|
+
if (pkg) {
|
|
250
|
+
const hasEmdash = Boolean(pkg.dependencies?.emdash ?? pkg.devDependencies?.emdash);
|
|
251
|
+
if (hasEmdash !== opts.emdash)
|
|
252
|
+
console.log(` ! ${pkgPath} ${hasEmdash ? 'depends on emdash but --emdash is off' : 'has no emdash dependency but --emdash is on'}`);
|
|
253
|
+
} else {
|
|
254
|
+
console.log(` ! no package.json in ${opts.dir}: local files (wrangler.jsonc, .dev.vars) are skipped`);
|
|
255
|
+
}
|
|
256
|
+
if (rows.length) printRows();
|
|
257
|
+
if (clashes && !opts.allowSimilar) {
|
|
258
|
+
console.log(`\n${clashes} near-miss name(s). Nothing was changed. Resolve them or re-run with --allow-similar.`);
|
|
259
|
+
process.exit(3);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// --- 2. resources ---------------------------------------------------------------------------
|
|
263
|
+
|
|
264
|
+
step('Resources');
|
|
265
|
+
const find = (kind) => existing[kind].find((r) => r.name === NAMES[kind]);
|
|
266
|
+
const ids = {};
|
|
267
|
+
const pending = '<created on apply>';
|
|
268
|
+
const canCreate = opts.apply && wants('resources');
|
|
269
|
+
|
|
270
|
+
async function ensure(kind, label, create) {
|
|
271
|
+
const hit = find(kind);
|
|
272
|
+
if (hit) {
|
|
273
|
+
ids[kind] = hit.id;
|
|
274
|
+
row(label, NAMES[kind], verb(false), hit.id);
|
|
275
|
+
} else if (canCreate) {
|
|
276
|
+
ids[kind] = await create();
|
|
277
|
+
row(label, NAMES[kind], verb(true), ids[kind]);
|
|
278
|
+
} else {
|
|
279
|
+
ids[kind] = pending;
|
|
280
|
+
row(label, NAMES[kind], wants('resources') ? 'create' : 'MISSING', wants('resources') ? '' : '(not in --only)');
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
await ensure('d1', 'D1 DB', async () =>
|
|
285
|
+
(await api('POST', `${ACC}/d1/database`, { name: NAMES.d1, primary_location_hint: opts.location })).uuid,
|
|
286
|
+
);
|
|
287
|
+
await ensure('kv', 'KV SESSION', async () =>
|
|
288
|
+
(await api('POST', `${ACC}/storage/kv/namespaces`, { title: NAMES.kv })).id,
|
|
289
|
+
);
|
|
290
|
+
if (opts.emdash) {
|
|
291
|
+
await ensure('r2', 'R2 MEDIA', async () => {
|
|
292
|
+
await api('POST', `${ACC}/r2/buckets`, { name: NAMES.r2, locationHint: opts.location });
|
|
293
|
+
return NAMES.r2;
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
let turnstileSecret;
|
|
297
|
+
if (opts.turnstile) {
|
|
298
|
+
const domains = [host, `${subdomain}.workers.dev`];
|
|
299
|
+
await ensure('turnstile', 'Turnstile', async () => {
|
|
300
|
+
const w = await api('POST', `${ACC}/challenges/widgets`, { name: NAMES.turnstile, domains, mode: 'managed' });
|
|
301
|
+
turnstileSecret = w.secret;
|
|
302
|
+
return w.sitekey;
|
|
303
|
+
});
|
|
304
|
+
const w = widgets.find((x) => x.name === NAMES.turnstile);
|
|
305
|
+
const missing = w ? domains.filter((d) => !w.domains.includes(d)) : [];
|
|
306
|
+
if (missing.length) console.log(` ! widget ${w.sitekey} lacks ${missing.join(', ')}; add them (cloudflare skill, forms-email-turnstile.md)`);
|
|
307
|
+
}
|
|
308
|
+
if (!opts.apply && wants('resources')) {
|
|
309
|
+
const loc = opts.location.toUpperCase();
|
|
310
|
+
console.log(` D1 location ${loc}${opts.emdash ? `, R2 location ${loc}` : ''}${opts.turnstile ? `, Turnstile domains ${host}, ${subdomain}.workers.dev` : ''}`);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// Rate-limit namespace: reuse this Worker's, else one above the highest bound in the account.
|
|
314
|
+
const settings = {};
|
|
315
|
+
await Promise.all(
|
|
316
|
+
workers.map(async (w) => {
|
|
317
|
+
settings[w.id] = await api('GET', `${ACC}/workers/scripts/${w.id}/settings`).catch(() => ({ bindings: [] }));
|
|
318
|
+
}),
|
|
319
|
+
);
|
|
320
|
+
const own = settings[S]?.bindings?.find((b) => b.type === 'ratelimit' && b.name === 'FORM_RATE_LIMITER');
|
|
321
|
+
const used = Object.values(settings).flatMap((s) => s.bindings.filter((b) => b.type === 'ratelimit').map((b) => Number(b.namespace_id)));
|
|
322
|
+
ids.ratelimit = own ? String(own.namespace_id) : String(Math.max(RATELIMIT_BASE, ...used.filter(Number.isFinite)) + 1);
|
|
323
|
+
row('Rate limit', 'FORM_RATE_LIMITER', own ? 'exists' : 'allocate', `namespace_id ${ids.ratelimit}`);
|
|
324
|
+
printRows();
|
|
325
|
+
|
|
326
|
+
// --- 3. config ------------------------------------------------------------------------------
|
|
327
|
+
|
|
328
|
+
const configPath = join(opts.dir, 'wrangler.jsonc');
|
|
329
|
+
let current = null;
|
|
330
|
+
if (existsSync(configPath)) {
|
|
331
|
+
try {
|
|
332
|
+
current = parseJsonc(readFileSync(configPath, 'utf8'));
|
|
333
|
+
} catch (e) {
|
|
334
|
+
console.log(` ! could not parse ${configPath}: ${e.message}`);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
const compatDate = current?.compatibility_date ?? new Date().toISOString().slice(0, 10);
|
|
338
|
+
|
|
339
|
+
function render() {
|
|
340
|
+
const flags = { emdash: opts.emdash, turnstile: opts.turnstile };
|
|
341
|
+
const vals = {
|
|
342
|
+
VARIANT: opts.emdash ? 'EmDash' : 'static',
|
|
343
|
+
SLUG: S,
|
|
344
|
+
ACCOUNT_NAME: account.name,
|
|
345
|
+
ACCOUNT_ID: account.id,
|
|
346
|
+
COMPAT_DATE: compatDate,
|
|
347
|
+
WORKERS_DEV_HOST: host,
|
|
348
|
+
TURNSTILE_SITEKEY: ids.turnstile,
|
|
349
|
+
SECRETS_EXTRA: opts.turnstile ? ', TURNSTILE_SECRET_KEY' : '',
|
|
350
|
+
D1_ID: ids.d1,
|
|
351
|
+
KV_ID: ids.kv,
|
|
352
|
+
RATELIMIT_ID: ids.ratelimit,
|
|
353
|
+
};
|
|
354
|
+
const out = [];
|
|
355
|
+
const stack = [];
|
|
356
|
+
for (const line of readFileSync(join(ASSETS, 'wrangler.jsonc'), 'utf8').split('\n')) {
|
|
357
|
+
const m = line.match(/^\/\/#if (\w+)$/);
|
|
358
|
+
if (m) stack.push(Boolean(flags[m[1]]));
|
|
359
|
+
else if (line === '//#endif') stack.pop();
|
|
360
|
+
else if (stack.every(Boolean)) out.push(line.replace(/\{\{(\w+)\}\}/g, (_, k) => vals[k]));
|
|
361
|
+
}
|
|
362
|
+
return out.join('\n');
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
if (wants('config')) {
|
|
366
|
+
step('Local files');
|
|
367
|
+
if (!pkg) {
|
|
368
|
+
console.log(' skipped (no package.json in --dir)');
|
|
369
|
+
} else {
|
|
370
|
+
const text = render();
|
|
371
|
+
if (current && current.name !== S) console.log(` ! existing wrangler.jsonc names the Worker "${current.name}", not "${S}"`);
|
|
372
|
+
const prev = existsSync(configPath) ? readFileSync(configPath, 'utf8') : null;
|
|
373
|
+
if (prev === text) row('file', 'wrangler.jsonc', 'up to date');
|
|
374
|
+
else if (prev === null || opts.writeConfig) {
|
|
375
|
+
const ready = !text.includes(pending);
|
|
376
|
+
if (opts.apply && ready) writeFileSync(configPath, text);
|
|
377
|
+
row('file', 'wrangler.jsonc', opts.apply ? (ready ? 'written' : 'NOT written (resources missing)') : prev === null ? 'write' : 'overwrite');
|
|
378
|
+
} else {
|
|
379
|
+
row('file', 'wrangler.jsonc', 'differs', 'kept; diff below, --write-config replaces it');
|
|
380
|
+
const tmp = mkdtempSync(join(tmpdir(), 'cf-init-'));
|
|
381
|
+
writeFileSync(join(tmp, 'wrangler.jsonc'), text);
|
|
382
|
+
try {
|
|
383
|
+
execFileSync('git', ['diff', '--no-index', '--no-color', configPath, join(tmp, 'wrangler.jsonc')], { stdio: 'inherit' });
|
|
384
|
+
} catch {
|
|
385
|
+
/* diff exits 1 when files differ */
|
|
386
|
+
}
|
|
387
|
+
rmSync(tmp, { recursive: true });
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
const devVars = join(opts.dir, '.dev.vars');
|
|
391
|
+
if (existsSync(devVars)) row('file', '.dev.vars', 'exists');
|
|
392
|
+
else {
|
|
393
|
+
if (opts.apply) {
|
|
394
|
+
const lines = [
|
|
395
|
+
'# Local secrets for wrangler dev (gitignored). Production values are Worker secrets.',
|
|
396
|
+
`FORM_SIGNING_SECRET=${randomBytes(36).toString('base64')}`,
|
|
397
|
+
];
|
|
398
|
+
if (opts.turnstile) lines.push('# Cloudflare test keys: always pass. Leyline allows them through the action check.', `TURNSTILE_SECRET_KEY=${TURNSTILE_TEST.secret}`);
|
|
399
|
+
writeFileSync(devVars, lines.join('\n') + '\n', { mode: 0o600 });
|
|
400
|
+
}
|
|
401
|
+
row('file', '.dev.vars', opts.apply ? 'written' : 'write', 'dev-only signing secret' + (opts.turnstile ? ', Turnstile test secret' : ''));
|
|
402
|
+
}
|
|
403
|
+
const gi = join(opts.dir, '.gitignore');
|
|
404
|
+
const ignored = existsSync(gi) && /^\.dev\.vars\*?$/m.test(readFileSync(gi, 'utf8'));
|
|
405
|
+
if (!ignored) console.log(' ! .gitignore does not list .dev.vars: add `.dev.vars*` before committing');
|
|
406
|
+
|
|
407
|
+
if (opts.emdash) {
|
|
408
|
+
const entry = join(opts.dir, 'src', 'worker.ts');
|
|
409
|
+
if (existsSync(entry)) row('file', 'src/worker.ts', 'exists');
|
|
410
|
+
else {
|
|
411
|
+
if (opts.apply) {
|
|
412
|
+
mkdirSync(dirname(entry), { recursive: true });
|
|
413
|
+
writeFileSync(entry, readFileSync(join(ASSETS, 'worker.emdash.ts'), 'utf8'));
|
|
414
|
+
}
|
|
415
|
+
row('file', 'src/worker.ts', opts.apply ? 'written' : 'write', 'EmDash entry with the scheduled handler');
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
printRows();
|
|
419
|
+
if (opts.turnstile) console.log(` local dev Turnstile sitekey: set PUBLIC_TURNSTILE_SITE_KEY=${TURNSTILE_TEST.site} in .dev.vars to override the real one`);
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// --- 4. worker ------------------------------------------------------------------------------
|
|
424
|
+
|
|
425
|
+
let worker = workers.find((w) => w.id === S);
|
|
426
|
+
if (wants('worker')) {
|
|
427
|
+
step('Worker');
|
|
428
|
+
if (worker) row('Worker', S, 'exists', `tag ${worker.tag}`);
|
|
429
|
+
else if (!opts.apply) row('Worker', S, 'create', 'placeholder (503, noindex) with the site bindings; the first build replaces it');
|
|
430
|
+
else if (Object.values(ids).includes(pending)) row('Worker', S, 'NOT created', 'resources are missing; run with --only resources first');
|
|
431
|
+
else {
|
|
432
|
+
const bindings = [
|
|
433
|
+
{ type: 'd1', name: 'DB', id: ids.d1 },
|
|
434
|
+
{ type: 'kv_namespace', name: 'SESSION', namespace_id: ids.kv },
|
|
435
|
+
{ type: 'send_email', name: 'EMAIL' },
|
|
436
|
+
{ type: 'ratelimit', name: 'FORM_RATE_LIMITER', namespace_id: ids.ratelimit, simple: { limit: 5, period: 60 } },
|
|
437
|
+
];
|
|
438
|
+
if (opts.emdash) bindings.push({ type: 'r2_bucket', name: 'MEDIA', bucket_name: NAMES.r2 });
|
|
439
|
+
if (opts.turnstile) bindings.push({ type: 'plain_text', name: 'PUBLIC_TURNSTILE_SITE_KEY', text: ids.turnstile });
|
|
440
|
+
const metadata = {
|
|
441
|
+
main_module: 'index.js',
|
|
442
|
+
compatibility_date: compatDate,
|
|
443
|
+
compatibility_flags: opts.emdash ? ['nodejs_compat'] : [],
|
|
444
|
+
bindings,
|
|
445
|
+
observability: { enabled: true, head_sampling_rate: 1 },
|
|
446
|
+
};
|
|
447
|
+
const form = new FormData();
|
|
448
|
+
form.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' }));
|
|
449
|
+
form.append('index.js', new Blob([readFileSync(join(ASSETS, 'placeholder-worker.js'))], { type: 'application/javascript+module' }), 'index.js');
|
|
450
|
+
await api('PUT', `${ACC}/workers/scripts/${S}`, form);
|
|
451
|
+
await api('POST', `${ACC}/workers/scripts/${S}/subdomain`, { enabled: true, previews_enabled: true });
|
|
452
|
+
worker = (await api('GET', `${ACC}/workers/scripts`)).find((w) => w.id === S);
|
|
453
|
+
row('Worker', S, 'created', `tag ${worker.tag}, https://${host}`);
|
|
454
|
+
}
|
|
455
|
+
printRows();
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// --- 5. secrets -----------------------------------------------------------------------------
|
|
459
|
+
|
|
460
|
+
if (wants('secrets')) {
|
|
461
|
+
step('Worker secrets');
|
|
462
|
+
const have = worker ? (await api('GET', `${ACC}/workers/scripts/${S}/secrets`)).map((s) => s.name) : [];
|
|
463
|
+
const wanted = ['FORM_SIGNING_SECRET', ...(opts.turnstile ? ['TURNSTILE_SECRET_KEY'] : [])];
|
|
464
|
+
for (const name of wanted) {
|
|
465
|
+
if (have.includes(name)) row('secret', name, 'exists');
|
|
466
|
+
else if (!opts.apply) row('secret', name, 'set', name === 'FORM_SIGNING_SECRET' ? 'random 48 bytes' : 'from the Turnstile widget');
|
|
467
|
+
else if (!worker) row('secret', name, 'NOT set', 'the Worker does not exist yet');
|
|
468
|
+
else {
|
|
469
|
+
let text;
|
|
470
|
+
if (name === 'FORM_SIGNING_SECRET') text = randomBytes(48).toString('base64');
|
|
471
|
+
else text = turnstileSecret ?? (ids.turnstile !== pending ? (await api('GET', `${ACC}/challenges/widgets/${ids.turnstile}`)).secret : undefined);
|
|
472
|
+
if (!text) row('secret', name, 'NOT set', 'Turnstile widget missing');
|
|
473
|
+
else {
|
|
474
|
+
await api('PUT', `${ACC}/workers/scripts/${S}/secrets`, { name, text, type: 'secret_text' });
|
|
475
|
+
row('secret', name, 'set');
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
printRows();
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// --- 6. Workers Builds ----------------------------------------------------------------------
|
|
483
|
+
|
|
484
|
+
let buildsNote = '';
|
|
485
|
+
if (wants('builds')) {
|
|
486
|
+
step(`Workers Builds (${opts.repo})`);
|
|
487
|
+
const repo = gh(['api', `repos/${opts.repo}`]);
|
|
488
|
+
let tokens = [];
|
|
489
|
+
try {
|
|
490
|
+
tokens = await api('GET', `${ACC}/builds/tokens`);
|
|
491
|
+
} catch (e) {
|
|
492
|
+
buildsNote = `token can't reach the Builds API (${e.message}); it needs Workers Builds Configuration Edit and must be user-owned`;
|
|
493
|
+
}
|
|
494
|
+
const buildToken = opts.buildToken ?? (tokens.length === 1 ? tokens[0].build_token_uuid : undefined);
|
|
495
|
+
if (!buildsNote && !repo) buildsNote = `GitHub repo ${opts.repo} not found (create it, or check \`gh auth status\`), then re-run with --only builds`;
|
|
496
|
+
if (!buildsNote && !buildToken)
|
|
497
|
+
buildsNote = tokens.length ? `the account has ${tokens.length} build tokens; pass --build-token (${tokens.map((t) => `${t.build_token_uuid} "${t.build_token_name}"`).join(', ')})` : 'the account has no build token; create one in the dashboard (Worker → Settings → Builds → API token)';
|
|
498
|
+
if (!buildsNote && !worker) buildsNote = opts.apply ? 'the Worker does not exist yet' : '';
|
|
499
|
+
|
|
500
|
+
if (buildsNote) console.log(` skipped: ${buildsNote}`);
|
|
501
|
+
else if (!worker) {
|
|
502
|
+
for (const t of Object.values(TRIGGERS)) row('trigger', t.trigger_name, 'create', `${t.build_command} / ${t.deploy_command}`);
|
|
503
|
+
row('setting', 'previews_enabled', 'set false');
|
|
504
|
+
row('env', 'NPM_TOKEN', process.env.NPM_TOKEN ? 'set' : 'SKIP', process.env.NPM_TOKEN ? 'secret, both triggers' : 'export NPM_TOKEN (npm read token) first');
|
|
505
|
+
} else {
|
|
506
|
+
const tag = worker.tag;
|
|
507
|
+
const listTriggers = () => api('GET', `${ACC}/builds/workers/${tag}/triggers`).catch((e) => (e.codes.includes(12000) ? [] : Promise.reject(e)));
|
|
508
|
+
const role = (t) => (t.branch_includes?.includes('main') && !t.branch_excludes?.length ? 'production' : t.branch_excludes?.includes('main') ? 'preview' : null);
|
|
509
|
+
let triggers = await listTriggers();
|
|
510
|
+
let connection = triggers[0]?.repo_connection?.repo_connection_uuid;
|
|
511
|
+
if (!connection && opts.apply) {
|
|
512
|
+
connection = (
|
|
513
|
+
await api('PUT', `${ACC}/builds/repos/connections`, {
|
|
514
|
+
provider_type: 'github',
|
|
515
|
+
provider_account_id: String(repo.owner.id),
|
|
516
|
+
provider_account_name: repo.owner.login,
|
|
517
|
+
repo_id: String(repo.id),
|
|
518
|
+
repo_name: repo.name,
|
|
519
|
+
})
|
|
520
|
+
).repo_connection_uuid;
|
|
521
|
+
}
|
|
522
|
+
const create = async (key) => {
|
|
523
|
+
const t = TRIGGERS[key];
|
|
524
|
+
const existingT = triggers.find((x) => role(x) === key);
|
|
525
|
+
if (existingT) {
|
|
526
|
+
const same = existingT.trigger_name === t.trigger_name && existingT.build_command === t.build_command && existingT.deploy_command === t.deploy_command;
|
|
527
|
+
row('trigger', existingT.trigger_name, 'exists', same ? '' : `differs from the standard "${t.trigger_name}": ${t.build_command} / ${t.deploy_command}`);
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
530
|
+
if (!opts.apply) return row('trigger', t.trigger_name, 'create', `${t.build_command} / ${t.deploy_command}`);
|
|
531
|
+
await api('POST', `${ACC}/builds/triggers`, {
|
|
532
|
+
...t,
|
|
533
|
+
external_script_id: tag,
|
|
534
|
+
repo_connection_uuid: connection,
|
|
535
|
+
build_token_uuid: buildToken,
|
|
536
|
+
root_directory: '/',
|
|
537
|
+
path_includes: ['*'],
|
|
538
|
+
path_excludes: [],
|
|
539
|
+
build_caching_enabled: true,
|
|
540
|
+
});
|
|
541
|
+
row('trigger', t.trigger_name, 'created', `${t.build_command} / ${t.deploy_command}`);
|
|
542
|
+
};
|
|
543
|
+
|
|
544
|
+
await create('production');
|
|
545
|
+
// Previews beta off before the preview trigger: turning it off deletes non-production triggers.
|
|
546
|
+
const cfg = await api('GET', `${ACC}/builds/workers/${tag}`).catch(() => null);
|
|
547
|
+
if (cfg?.previews_enabled === false) row('setting', 'previews_enabled', 'false');
|
|
548
|
+
else if (opts.apply) {
|
|
549
|
+
await api('PATCH', `${ACC}/builds/workers/${tag}`, { previews_enabled: false });
|
|
550
|
+
row('setting', 'previews_enabled', 'set false');
|
|
551
|
+
} else row('setting', 'previews_enabled', 'set false');
|
|
552
|
+
triggers = await listTriggers();
|
|
553
|
+
await create('preview');
|
|
554
|
+
|
|
555
|
+
triggers = opts.apply ? await listTriggers() : triggers;
|
|
556
|
+
for (const t of triggers.filter((x) => role(x))) {
|
|
557
|
+
const vars = await api('GET', `${ACC}/builds/triggers/${t.trigger_uuid}/environment_variables`).catch(() => ({}));
|
|
558
|
+
if (vars?.NPM_TOKEN) row('env', `NPM_TOKEN (${t.trigger_name})`, 'exists');
|
|
559
|
+
else if (!process.env.NPM_TOKEN) row('env', `NPM_TOKEN (${t.trigger_name})`, 'SKIP', 'export NPM_TOKEN (npm read token), then re-run --only builds');
|
|
560
|
+
else if (!opts.apply) row('env', `NPM_TOKEN (${t.trigger_name})`, 'set', 'secret');
|
|
561
|
+
else {
|
|
562
|
+
await api('PATCH', `${ACC}/builds/triggers/${t.trigger_uuid}/environment_variables`, { NPM_TOKEN: { value: process.env.NPM_TOKEN, is_secret: true } });
|
|
563
|
+
row('env', `NPM_TOKEN (${t.trigger_name})`, 'set', 'secret');
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
if (!opts.apply && !triggers.length) row('env', 'NPM_TOKEN', process.env.NPM_TOKEN ? 'set' : 'SKIP', process.env.NPM_TOKEN ? 'secret, both triggers' : 'export NPM_TOKEN first');
|
|
567
|
+
}
|
|
568
|
+
printRows();
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
// --- 7. summary -----------------------------------------------------------------------------
|
|
572
|
+
|
|
573
|
+
if (!opts.apply) {
|
|
574
|
+
console.log('\nPlan only: nothing was changed. Re-run with --apply to make these changes.');
|
|
575
|
+
process.exit(clashes ? 3 : 0);
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
const repoUrl = `https://github.com/${opts.repo}`;
|
|
579
|
+
console.log(`
|
|
580
|
+
▶ Done. Entry for docs/sites.md (fill in the dates and anything marked TODO):
|
|
581
|
+
|
|
582
|
+
### ${repoName}
|
|
583
|
+
|
|
584
|
+
- Worker \`${S}\` (tag \`${worker?.tag ?? 'TODO'}\`). Compatibility date ${compatDate}${opts.emdash ? ', `nodejs_compat`' : ', no flags'}, observability on.${opts.emdash ? ' Custom entry `src/worker.ts`, with a cron trigger every minute (`* * * * *`).' : ''}
|
|
585
|
+
- Domains: none yet. Pre-launch on https://${host}, which is also the workflow's \`production-url\`.
|
|
586
|
+
- Builds: production "Deploy production" and preview "Preview other branches", \`NPM_TOKEN\` a secret on both.${buildsNote ? ` TODO: ${buildsNote}.` : ''}
|
|
587
|
+
- Bindings:
|
|
588
|
+
- D1 \`DB\` → \`${NAMES.d1}\` (\`${ids.d1}\`, ${opts.location.toUpperCase()})
|
|
589
|
+
- KV \`SESSION\` → \`${NAMES.kv}\`${opts.emdash ? `\n - R2 \`MEDIA\` → \`${NAMES.r2}\`` : ''}
|
|
590
|
+
- Email Sending \`EMAIL\` (no sender allow-list until launch)
|
|
591
|
+
- rate limit \`FORM_RATE_LIMITER\` (5/60s, namespace ${ids.ratelimit})${opts.turnstile ? `\n - var \`PUBLIC_TURNSTILE_SITE_KEY\` (widget \`${NAMES.turnstile}\`, \`${ids.turnstile}\`)` : ''}
|
|
592
|
+
- Worker secrets: \`FORM_SIGNING_SECRET\`${opts.turnstile ? ', `TURNSTILE_SECRET_KEY`' : ''}.
|
|
593
|
+
|
|
594
|
+
Next:
|
|
595
|
+
1. Copy Leyline's form migrations: cp node_modules/@theory-digital/leyline/src/forms/migrations/*.sql migrations/
|
|
596
|
+
2. Commit wrangler.jsonc${opts.emdash ? ', src/worker.ts' : ''} and migrations/, and push to main (${repoUrl}). The first build applies migrations and replaces the placeholder.
|
|
597
|
+
3. Enrol in Leyline updates: docs/sites.md, "Enrolling a site" (workflow file, then the leyline-site topic).
|
|
598
|
+
4. At launch, with the cloudflare skill: zone, routes, Turnstile hostname, email sending enable + allowed_sender_addresses, production-url.`);
|