diff --git a/bun.lock b/bun.lock index 4e0c0e79f..f53610ad9 100644 --- a/bun.lock +++ b/bun.lock @@ -150,6 +150,24 @@ "typescript": "^5.6.0", }, }, + "packs/cloudflare/typescript": { + "name": "@metaobjectsdev/pack-cloudflare", + "version": "0.1.0", + "dependencies": { + "@metaobjectsdev/pack-config": "workspace:*", + "@metaobjectsdev/pack-delivery": "workspace:*", + "@metaobjectsdev/pack-systems": "workspace:*", + }, + "devDependencies": { + "@metaobjectsdev/codegen-ts": "workspace:*", + "@metaobjectsdev/metadata": "workspace:*", + "ajv": "^8.20.0", + }, + "peerDependencies": { + "@metaobjectsdev/codegen-ts": ">=1.3.0 <2.0.0", + "@metaobjectsdev/metadata": ">=1.3.0 <2.0.0", + }, + }, "packs/config/typescript": { "name": "@metaobjectsdev/pack-config", "version": "0.1.0", @@ -806,6 +824,8 @@ "@metaobjectsdev/migrate-ts": ["@metaobjectsdev/migrate-ts@workspace:server/typescript/packages/migrate-ts"], + "@metaobjectsdev/pack-cloudflare": ["@metaobjectsdev/pack-cloudflare@workspace:packs/cloudflare/typescript"], + "@metaobjectsdev/pack-config": ["@metaobjectsdev/pack-config@workspace:packs/config/typescript"], "@metaobjectsdev/pack-delivery": ["@metaobjectsdev/pack-delivery@workspace:packs/delivery/typescript"], diff --git a/packs/README.md b/packs/README.md index ffe883f31..4cb553ec7 100644 --- a/packs/README.md +++ b/packs/README.md @@ -10,6 +10,7 @@ that is not part of core, built and versioned as if it were its own repository | [`systems`](systems/README.md) | systems, apps (service, client, job), resources | core | TypeScript | | [`delivery`](delivery/README.md) | environments, builds, runtime processes, deployments, value bindings | `systems` | TypeScript | | [`railway`](railway/README.md) | `deployment.railway`; `.railway/railway.ts` (Railway Infrastructure as Code), unexpressed-facts list, secret sync, deploy and doctor scripts and a deploy skill | `delivery`, `config` | TypeScript | +| [`cloudflare`](cloudflare/README.md) | `deployment.worker`, `deployment.pages` and a Worker's D1, KV, R2, queue and rate limiting bindings; `wrangler.jsonc`, token-scoped deploy, secret sync and doctor script generators | `delivery`, `config` | TypeScript | An independent pack is not in the default bundle. A project opts in by naming its provider. It is never in `fixtures/registry-conformance/expected-registry.json` and never moves diff --git a/packs/cloudflare/CHANGELOG.md b/packs/cloudflare/CHANGELOG.md new file mode 100644 index 000000000..28d4f04d9 --- /dev/null +++ b/packs/cloudflare/CHANGELOG.md @@ -0,0 +1,22 @@ +# Changelog: cloudflare pack + +This pack's own changelog (ADR-0069). The root `CHANGELOG.md` records core only. + +## [0.1.0] - unreleased + +- **First version.** `deployment.worker` (a Worker, with or without static assets) and + `deployment.pages` (a Pages site) on the delivery pack's `deployment.base`, held to its + references, and the Worker's bindings `cloudflare.d1`, `.kv`, `.r2`, `.queue` and + `.ratelimit`. An abstract deployment holds what every environment shares; each environment's + deployment `extends` it and holds only its differences. +- **Generators**: `wrangler.jsonc` (the top-level environment plus one complete `env` block per + other environment, each fact commented with the model node it comes from, valid against + Wrangler 4.168.0's schema), `deploy/cloudflare/wrangler.sh` (wrangler as the deployment's + narrow API token from the vault, the global-key variables unset, a pinned wrangler), + `deploy.sh`, `sync-secrets.sh` (vault to Cloudflare through `keys-axi`, `wrangler secret put` + from stdin), `doctor.sh` and `unexpressed.md`. +- Fixtures `cloudflare-worker-environments`, `cloudflare-worker-cron-ratelimits`, + `cloudflare-pages-site` and `cloudflare-pages-secrets` with golden output, five load-error + fixtures, a coverage test that holds the output to every fact of the hand-written configurations + the fixtures are modelled on, and tests that run the generated scripts against stubbed + `keys-axi` and `npx`. TypeScript port. diff --git a/packs/cloudflare/README.md b/packs/cloudflare/README.md new file mode 100644 index 000000000..dce8be66e --- /dev/null +++ b/packs/cloudflare/README.md @@ -0,0 +1,187 @@ +# cloudflare pack + +`metaobjects-cloudflare`, version 0.1.0, **preview**, unpublished. An independent pack +([ADR-0069](../../spec/decisions/ADR-0069-independent-packs.md)). Requires +[`delivery`](../delivery/README.md) and [`config`](../config/README.md). + +Cloudflare as a deployment platform. It registers `deployment.worker` (a Worker, with or without +static assets) and `deployment.pages` (a Pages site), and the bindings a Worker reaches its +resources through. It generates the Worker's `wrangler.jsonc` and the scripts beside it: a +wrangler wrapper that runs as the deployment's narrow API token, a deploy script, a script that +copies the declared secrets from the vault to Cloudflare, a doctor script, and the facts no file +holds. The generators write files and stop: MetaObjects never talks to Cloudflare or to a vault. +The scripts do, with `wrangler` and `keys-axi`, when someone runs them. + +## Vocabulary + +| Node | Attributes | +|---|---| +| `deployment.worker` | every `deployment.base` attribute (`@app`, `@environment`, `@domains`, `@branch`, `@secrets`, and `value.*` children), plus `@compatibilityDate` (required), `@tokenSecret` (required), `@script` (the Worker's name; absent: the app's), `@main`, `@compatibilityFlags`, `@workersDev`, `@assetsBinding`, `@notFound`, `@workerFirst` or `@workerFirstPaths`, `@jobs`, `@tokenVault`, `@extra` | +| `deployment.pages` | every `deployment.base` attribute, plus `@project` (required), `@tokenSecret` (required), `@tokenVault` | +| `cloudflare.d1` | `@databaseName` (required), `@databaseId`, `@migrationsDir` | +| `cloudflare.kv` | `@namespaceId` (required) | +| `cloudflare.r2` | `@bucketName` (required) | +| `cloudflare.queue` | `@queue` (required) | +| `cloudflare.ratelimit` | `@namespaceId`, `@limit`, `@period` (all required; the period is 10 or 60) | + +The `cloudflare.*` nodes are children of a `deployment.worker`. A D1, KV, R2 or queue binding is +named after the resource it places, one the app `@needs` (`resource.database`, `.keyvalue`, +`.bucket`, `.queue`); its binding name is the node's name in upper snake case (`rateLimit` is +`RATE_LIMIT`). A rate limiter places no resource and is named freely. Every resource the app needs +that Cloudflare manages must be bound in every environment; a resource with `@managedBy: external` +is reached through settings and listed, not bound. + +The token: the deploy scripts read `@tokenSecret` and `CLOUDFLARE_ACCOUNT_ID` from the +environment's scope of `@tokenVault` (absent: the `@secrets` vault). The scope is the one named +after the environment, else the vault's `@defaultScope`, so one deploy-token scope can serve every +environment. + +`@extra` is the escape hatch: a JSON object of Wrangler keys this pack does not model +(`placement`, `observability`, ...), copied into the environment's block. A key the generator +writes itself is refused. A key Wrangler fills into an env block that omits it (`observability`, +`placement`, `limits`, `rules`, ...) is set in every environment or in none, like `@main`. + +### One abstract deployment, one per environment + +What every environment shares (the app, the entry module, the compatibility date, the assets +behaviour, the token, the bindings) sits on an abstract `deployment.worker`; each environment's +deployment `extends` it and holds only what differs: `@environment`, `@domains`, `@branch`, a +binding with that environment's ids, a value. A child the extender redeclares by name replaces +the inherited one. The generators read through `extends`, so an inherited binding or value counts, +and they skip the abstract base. + +## Generators + +| Generator | Writes | What it is | +|---|---|---| +| `wranglerConfigFile()` | `wrangler.jsonc` | The Worker's configuration (Workers only) | +| `cloudflareRunnerScript()` | `deploy/cloudflare/wrangler.sh` | Runs wrangler as the environment's narrow token: `keys-axi run` reads it and `CLOUDFLARE_ACCOUNT_ID`, the global-key variables `CLOUDFLARE_EMAIL` and `CLOUDFLARE_API_KEY` and any `CLOUDFLARE_API_TOKEN` the shell holds are unset, the vault's token becomes `CLOUDFLARE_API_TOKEN`, and `npx wrangler@4.168.0` runs (`WRANGLER_VERSION` overrides) | +| `cloudflareDeployScript()` | `deploy/cloudflare/deploy.sh` | Exports the build-time settings the model gives values, builds (the app's `build.command` or `build.static @command`), syncs the secrets, then `wrangler deploy [--env ]` or `wrangler pages deploy --project-name --branch --commit-hash` | +| `cloudflareSyncSecretsScript()` | `deploy/cloudflare/sync-secrets.sh` | Copies each secret setting from its vault scope to the Worker (`wrangler secret put`) or to the Pages project's environment the deployment serves (`wrangler pages secret put --env production` or `preview`), the value through a pipe | +| `cloudflareDoctorScript()` | `deploy/cloudflare/doctor.sh` | Checks, by name only, that the token, the account id and each secret are in the vault, that each secret is on Cloudflare (the Worker, or the Pages project's environment the deployment serves), that the configuration builds (`wrangler deploy --dry-run`), and that each domain answers | +| `cloudflareUnexpressedFile()` | `deploy/cloudflare/unexpressed.md` | Per deployment, each fact the files do not hold and how it is carried instead | +| `cloudflareFiles()` | all six | The six generators with the same options | + +Each takes `{ target?, app?, topLevel?, paths? }`. One set of files is for one app: a model that +deploys several apps to Cloudflare needs `app`. `topLevel` is the environment written at the top +level of `wrangler.jsonc` (what `wrangler deploy` with no `--env` deploys); absent, it is the only +environment, else `production`. `paths` moves any file; the scripts name each other and the +configuration by those paths, so pass every generator the same. + +### What `wrangler.jsonc` says + +| Model | `wrangler.jsonc` | +|---|---| +| `@script` | `name`; in an env block `-` (Wrangler's own default) unless the deployment's `@script` differs, and two environments never deploy one Worker | +| `@main`, `@compatibilityDate`, `@compatibilityFlags`, `@workersDev` | `main`, `compatibility_date`, `compatibility_flags`, `workers_dev` | +| `@domains` | `routes`, each a custom domain | +| the app's `build.static @directory`, `@assetsBinding`, `@notFound`, `@workerFirst` / `@workerFirstPaths` | `assets.directory`, `.binding`, `.not_found_handling`, `.run_worker_first` | +| `@jobs` (each an `app.job`) | `triggers.crons`, from each job's `@schedule` | +| the app's non-secret runtime settings | `vars`: a `value.literal` here, else the `@default`; a required one with neither is refused | +| the app's `@secret` runtime settings | `secrets.required` (names only; the sync script copies the values) | +| `cloudflare.d1` / `.kv` / `.r2` / `.queue` / `.ratelimit` | `d1_databases`, `kv_namespaces`, `r2_buckets`, `queues.producers`, `ratelimits` | +| `value.ref` of another Cloudflare-deployed app's `host` / `publicUrl` | its first `@domains` entry in the same environment (`publicUrl` is `https://` and the domain, with the ref's `@path` appended) | +| the app's build-time settings | not in the file: `deploy.sh` exports each one the model gives a value, for the build to read | + +Wrangler does not inherit `vars`, `secrets` or any binding into an `env` block, and a key it does +inherit is easy to forget. So every env block is written in full: every key the top level has, +with that environment's own value, an empty one included. Every fact carries a `//` comment naming +the model node it came from, `(from )` when an environment inherits it. Paths are rewritten +relative to the file. + +A Pages site has no `wrangler.jsonc`: `wrangler pages deploy` takes the directory, project and +branch as arguments, and the Pages project keeps its environment variables and domains in its own +settings (both are listed in `unexpressed.md`). + +A Pages project has two environments, `production` and `preview`, each with its own variables and +secrets. The upload of the project's production branch serves `production` and every other upload +serves `preview`. The model states the production branch with the `@branch` of the +`deployment.pages` in the environment named `production`: a deployment serves `production` when +its `@branch` is that branch, and `preview` otherwise. The scripts pass that environment to +`wrangler pages secret put|list --env`, so one environment's secrets never land in another's. + +Build-time settings (`@phase: build`) are not Cloudflare settings. `deploy.sh` exports each one +the model gives a value (a `value.literal`, else the `@default`) and then runs the app's build +command, when it has one; whatever builds an app without one reads them from its own environment. +A build-time `@secret` and a build-time `value.ref` are refused: the scripts copy a secret to +Cloudflare, never to a build, and resolve no reference on the deploying machine. + +### Checks + +The generators refuse, naming each node, a model Cloudflare could not deploy: a binding for a +resource the app does not need, a needed resource with no binding in some environment, a binding +name used twice in the Worker's env, a rate limiter period other than 10 or 60, a required setting +with no value, a value for a secret setting or for a setting the app does not read, a `value.ref` +Cloudflare cannot resolve, a build-time secret setting or a build-time `value.ref`, `@jobs` that +are not scheduled jobs, both worker-first forms, asset attributes with no `build.static`, a Worker +with neither `@main` nor assets, a secret setting with no vault, a vault with no scope for an +environment, `@main`, `@workersDev`, assets or an inheritable `@extra` key set in some +environments and not others (Wrangler would fill the gap from the top level), an `@extra` that is +not a JSON object or sets a generated key, two environments deploying one Worker, one app deployed +both as a Worker and as a Pages site, a Pages deployment that reads a secret when the model does +not say which branch is the production branch, two Pages deployments that serve one Pages +project's environment and read their secrets from different vault scopes, several apps without +`app`, and several environments with no top level. + +### Wiring + +These files belong at the repository root, so give them a target whose `outDir` is `"."`. As for +the config pack, `meta gen` runs no generator over a model with no object at all: systems, +deployments and vaults are not objects, so the model needs its settings groups (`object.settings`) +for these files to be written. + +```ts +import { defineConfig } from "@metaobjectsdev/cli"; +import { cloudflareFiles, provider as cloudflareProvider } from "@metaobjectsdev/pack-cloudflare"; +import { configProvider } from "@metaobjectsdev/pack-config"; +import { provider as deliveryProvider } from "@metaobjectsdev/pack-delivery"; +import { provider as systemsProvider } from "@metaobjectsdev/pack-systems"; + +export default defineConfig({ + outDir: "src/generated", // the project's existing setting + providers: [systemsProvider, deliveryProvider, configProvider, cloudflareProvider], + targets: { root: { outDir: "." } }, + generators: [...cloudflareFiles({ target: "root" })], +}); +``` + +## Fixtures + +- [`cloudflare-worker-environments/`](fixtures/conformance/cloudflare-worker-environments/): a + Worker with static assets, a D1 database and a KV namespace in production and staging, from one + abstract `deployment.worker`. Staging redeclares the two bindings with its own ids and overrides + one value; everything else it inherits. +- [`cloudflare-worker-cron-ratelimits/`](fixtures/conformance/cloudflare-worker-cron-ratelimits/): + a Worker in front of its assets for every request, with a daily job, D1 with its migrations + directory, R2, five rate limiters, three plain settings and five secrets, off workers.dev. +- [`cloudflare-pages-site/`](fixtures/conformance/cloudflare-pages-site/): a static site on Pages, + production and a preview branch from one abstract `deployment.pages`. +- [`cloudflare-pages-secrets/`](fixtures/conformance/cloudflare-pages-secrets/): a Pages site + whose Pages Functions read a secret, with one value for the production branch and one for a + preview branch: each `deploy.sh ` copies to that environment. +- `error-*`: a concrete Worker missing `@compatibilityDate`, an unknown `@notFound`, a binding + under a Pages site, an authored `cloudflare.base`, an `@app` that resolves to nothing. + +Names, domains, ids and token names are placeholders. The generated files are in +[`typescript/test/golden/`](typescript/test/golden/). + +The first three success fixtures are modelled on three adopters' hand-written Cloudflare configuration +(a `wrangler.jsonc`, a `wrangler.toml` and a Pages deploy script). The bar is coverage, not +identity: `typescript/test/coverage.test.ts` checks every fact of each, with its values replaced +by the placeholders, fact by fact. Where the generated files go further: + +- `wrangler.jsonc` validates against Wrangler's own JSON schema (vendored in + `typescript/test/wrangler-schema/`), and points editors at it with `$schema`; +- rate limiters are the first-class `ratelimits` key, not untyped `unsafe.bindings`; +- environments are correct by construction: every env block repeats every key with its own value, + where Wrangler would silently drop vars and bindings it does not inherit; +- the Worker's secrets are declared (`secrets.required`), so a missing one is a deploy error + rather than a runtime surprise, and their values come from the vault through the sync script; +- every fact names the model node it came from; the facts no file can hold are listed in + `deploy/cloudflare/unexpressed.md` instead of dropped; +- every Wrangler call runs as the environment's narrow token with the global-key variables unset, + and the doctor checks the vault, Cloudflare, the build and the domains by name. + +## Ports + +TypeScript only. diff --git a/packs/cloudflare/fixtures/conformance/cloudflare-pages-secrets/expected.json b/packs/cloudflare/fixtures/conformance/cloudflare-pages-secrets/expected.json new file mode 100644 index 000000000..8cc1cd5c4 --- /dev/null +++ b/packs/cloudflare/fixtures/conformance/cloudflare-pages-secrets/expected.json @@ -0,0 +1,122 @@ +{ + "metadata.root": { + "package": "acme::help", + "children": [ + { + "system.internal": { + "name": "Help", + "@description": "A help center on Cloudflare Pages: a static site whose Pages Functions read a secret, with one value per Pages environment.", + "children": [ + { + "app.client": { + "name": "site", + "@settings": [ + "Search" + ], + "children": [ + { + "build.static": { + "name": "pages", + "@command": "npm run build", + "@directory": "dist" + } + } + ] + } + } + ] + } + }, + { + "object.settings": { + "name": "Search", + "children": [ + { + "field.string": { + "name": "apiKey", + "@envName": "SEARCH_API_KEY", + "@required": true, + "@secret": true + } + } + ] + } + }, + { + "vault.infisical": { + "name": "keys", + "children": [ + { + "scope.env": { + "name": "production", + "@env": "prod", + "@project": "acme-help" + } + }, + { + "scope.env": { + "name": "preview", + "@env": "preview", + "@project": "acme-help-preview" + } + } + ] + } + }, + { + "vault.infisical": { + "name": "deployKeys", + "@defaultScope": "dev", + "children": [ + { + "scope.env": { + "name": "dev", + "@project": "acme-deploy" + } + } + ] + } + }, + { + "environment.standing": { + "name": "production" + } + }, + { + "environment.ephemeral": { + "name": "preview" + } + }, + { + "deployment.pages": { + "name": "siteBase", + "abstract": true, + "@app": "Help.site", + "@project": "help-site", + "@secrets": "keys", + "@tokenSecret": "ACME_PAGES_TOKEN", + "@tokenVault": "deployKeys" + } + }, + { + "deployment.pages": { + "name": "siteProduction", + "extends": "acme::help::siteBase", + "@branch": "main", + "@domains": [ + "help.example.com" + ], + "@environment": "production" + } + }, + { + "deployment.pages": { + "name": "sitePreview", + "extends": "acme::help::siteBase", + "@branch": "preview", + "@environment": "preview" + } + } + ] + } +} diff --git a/packs/cloudflare/fixtures/conformance/cloudflare-pages-secrets/input/meta.help.json b/packs/cloudflare/fixtures/conformance/cloudflare-pages-secrets/input/meta.help.json new file mode 100644 index 000000000..6ea94ce91 --- /dev/null +++ b/packs/cloudflare/fixtures/conformance/cloudflare-pages-secrets/input/meta.help.json @@ -0,0 +1,53 @@ +{ + "metadata.root": { + "package": "acme::help", + "children": [ + { "system.internal": { + "name": "Help", + "@description": "A help center on Cloudflare Pages: a static site whose Pages Functions read a secret, with one value per Pages environment.", + "children": [ + { "app.client": { + "name": "site", + "@settings": ["Search"], + "children": [ + { "build.static": { "name": "pages", "@directory": "dist", "@command": "npm run build" } } + ] + } } + ] + } }, + { "object.settings": { + "name": "Search", + "children": [ + { "field.string": { "name": "apiKey", "@envName": "SEARCH_API_KEY", "@required": true, "@secret": true } } + ] + } }, + { "vault.infisical": { + "name": "keys", + "children": [ + { "scope.env": { "name": "production", "@project": "acme-help", "@env": "prod" } }, + { "scope.env": { "name": "preview", "@project": "acme-help-preview", "@env": "preview" } } + ] + } }, + { "vault.infisical": { + "name": "deployKeys", + "@defaultScope": "dev", + "children": [ + { "scope.env": { "name": "dev", "@project": "acme-deploy" } } + ] + } }, + { "environment.standing": { "name": "production" } }, + { "environment.ephemeral": { "name": "preview" } }, + { "deployment.pages": { + "name": "siteBase", + "abstract": true, + "@app": "Help.site", + "@project": "help-site", + "@secrets": "keys", + "@tokenVault": "deployKeys", + "@tokenSecret": "ACME_PAGES_TOKEN" + } }, + { "deployment.pages": { "name": "siteProduction", "extends": "siteBase", "@environment": "production", "@branch": "main", "@domains": ["help.example.com"] } }, + { "deployment.pages": { "name": "sitePreview", "extends": "siteBase", "@environment": "preview", "@branch": "preview" } } + ] + } +} diff --git a/packs/cloudflare/fixtures/conformance/cloudflare-pages-secrets/providers.json b/packs/cloudflare/fixtures/conformance/cloudflare-pages-secrets/providers.json new file mode 100644 index 000000000..139d85434 --- /dev/null +++ b/packs/cloudflare/fixtures/conformance/cloudflare-pages-secrets/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-documentation", "metaobjects-systems", "metaobjects-delivery", "metaobjects-config", "metaobjects-cloudflare"] diff --git a/packs/cloudflare/fixtures/conformance/cloudflare-pages-site/expected.json b/packs/cloudflare/fixtures/conformance/cloudflare-pages-site/expected.json new file mode 100644 index 000000000..fc13636fb --- /dev/null +++ b/packs/cloudflare/fixtures/conformance/cloudflare-pages-site/expected.json @@ -0,0 +1,100 @@ +{ + "metadata.root": { + "package": "acme::docs", + "children": [ + { + "system.internal": { + "name": "Docs", + "@description": "A static documentation site on Cloudflare Pages.", + "children": [ + { + "app.client": { + "name": "site", + "@settings": [ + "Site" + ], + "children": [ + { + "build.static": { + "name": "pages", + "@command": "npm run build", + "@directory": "dist" + } + } + ] + } + } + ] + } + }, + { + "object.settings": { + "name": "Site", + "children": [ + { + "field.string": { + "name": "url", + "@default": "https://docs.example.com", + "@envName": "SITE_URL", + "@phase": "build" + } + } + ] + } + }, + { + "vault.infisical": { + "name": "deployKeys", + "@defaultScope": "dev", + "children": [ + { + "scope.env": { + "name": "dev", + "@project": "acme-deploy" + } + } + ] + } + }, + { + "environment.standing": { + "name": "production" + } + }, + { + "environment.ephemeral": { + "name": "preview" + } + }, + { + "deployment.pages": { + "name": "siteBase", + "abstract": true, + "@app": "Docs.site", + "@project": "docs-site", + "@tokenSecret": "ACME_PAGES_TOKEN", + "@tokenVault": "deployKeys" + } + }, + { + "deployment.pages": { + "name": "siteProduction", + "extends": "acme::docs::siteBase", + "@branch": "main", + "@domains": [ + "docs.example.com" + ], + "@environment": "production" + } + }, + { + "deployment.pages": { + "name": "sitePreview", + "extends": "acme::docs::siteBase", + "@branch": "preview", + "@environment": "preview" + } + } + ] + } +} diff --git a/packs/cloudflare/fixtures/conformance/cloudflare-pages-site/input/meta.docs.json b/packs/cloudflare/fixtures/conformance/cloudflare-pages-site/input/meta.docs.json new file mode 100644 index 000000000..736150c4f --- /dev/null +++ b/packs/cloudflare/fixtures/conformance/cloudflare-pages-site/input/meta.docs.json @@ -0,0 +1,45 @@ +{ + "metadata.root": { + "package": "acme::docs", + "children": [ + { "system.internal": { + "name": "Docs", + "@description": "A static documentation site on Cloudflare Pages.", + "children": [ + { "app.client": { + "name": "site", + "@settings": ["Site"], + "children": [ + { "build.static": { "name": "pages", "@directory": "dist", "@command": "npm run build" } } + ] + } } + ] + } }, + { "object.settings": { + "name": "Site", + "children": [ + { "field.string": { "name": "url", "@envName": "SITE_URL", "@phase": "build", "@default": "https://docs.example.com" } } + ] + } }, + { "vault.infisical": { + "name": "deployKeys", + "@defaultScope": "dev", + "children": [ + { "scope.env": { "name": "dev", "@project": "acme-deploy" } } + ] + } }, + { "environment.standing": { "name": "production" } }, + { "environment.ephemeral": { "name": "preview" } }, + { "deployment.pages": { + "name": "siteBase", + "abstract": true, + "@app": "Docs.site", + "@project": "docs-site", + "@tokenVault": "deployKeys", + "@tokenSecret": "ACME_PAGES_TOKEN" + } }, + { "deployment.pages": { "name": "siteProduction", "extends": "siteBase", "@environment": "production", "@branch": "main", "@domains": ["docs.example.com"] } }, + { "deployment.pages": { "name": "sitePreview", "extends": "siteBase", "@environment": "preview", "@branch": "preview" } } + ] + } +} diff --git a/packs/cloudflare/fixtures/conformance/cloudflare-pages-site/providers.json b/packs/cloudflare/fixtures/conformance/cloudflare-pages-site/providers.json new file mode 100644 index 000000000..139d85434 --- /dev/null +++ b/packs/cloudflare/fixtures/conformance/cloudflare-pages-site/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-documentation", "metaobjects-systems", "metaobjects-delivery", "metaobjects-config", "metaobjects-cloudflare"] diff --git a/packs/cloudflare/fixtures/conformance/cloudflare-worker-cron-ratelimits/expected.json b/packs/cloudflare/fixtures/conformance/cloudflare-worker-cron-ratelimits/expected.json new file mode 100644 index 000000000..3dceaef12 --- /dev/null +++ b/packs/cloudflare/fixtures/conformance/cloudflare-worker-cron-ratelimits/expected.json @@ -0,0 +1,274 @@ +{ + "metadata.root": { + "package": "acme::trips", + "children": [ + { + "system.internal": { + "name": "Trips", + "@description": "A trip journal: one Worker in front of its assets, with D1, R2, rate limiters and a daily clean-up.", + "children": [ + { + "app.service": { + "name": "web", + "@needs": [ + "db", + "photos" + ], + "@settings": [ + "Access", + "Notify", + "Auth" + ], + "children": [ + { + "build.static": { + "name": "client", + "@command": "pnpm build", + "@directory": "dist/client" + } + } + ] + } + }, + { + "app.job": { + "name": "coverCleanup", + "@description": "Deletes cover images no trip references.", + "@schedule": "0 4 * * *" + } + }, + { + "resource.database": { + "name": "db" + } + }, + { + "resource.bucket": { + "name": "photos" + } + } + ] + } + }, + { + "object.settings": { + "name": "Access", + "children": [ + { + "field.string": { + "name": "teamDomain", + "@envName": "ACCESS_TEAM_DOMAIN", + "@required": true + } + }, + { + "field.string": { + "name": "aud", + "@envName": "ACCESS_AUD", + "@required": true + } + } + ] + } + }, + { + "object.settings": { + "name": "Notify", + "children": [ + { + "field.string": { + "name": "email", + "@envName": "NOTIFY_EMAIL", + "@required": true + } + } + ] + } + }, + { + "object.settings": { + "name": "Auth", + "children": [ + { + "field.string": { + "name": "sessionSecret", + "@envName": "SESSION_SECRET", + "@required": true, + "@secret": true + } + }, + { + "field.string": { + "name": "resendApiKey", + "@envName": "RESEND_API_KEY", + "@required": true, + "@secret": true + } + }, + { + "field.string": { + "name": "passphrasePepper", + "@envName": "PASSPHRASE_PEPPER", + "@required": true, + "@secret": true + } + }, + { + "field.string": { + "name": "recoveryEncKey", + "@envName": "RECOVERY_ENC_KEY", + "@required": true, + "@secret": true + } + }, + { + "field.string": { + "name": "recoveryHmacKey", + "@envName": "RECOVERY_HMAC_KEY", + "@required": true, + "@secret": true + } + } + ] + } + }, + { + "vault.infisical": { + "name": "keys", + "children": [ + { + "scope.env": { + "name": "production", + "@env": "prod", + "@project": "trips" + } + } + ] + } + }, + { + "vault.infisical": { + "name": "deployKeys", + "@defaultScope": "dev", + "children": [ + { + "scope.env": { + "name": "dev", + "@project": "acme-deploy" + } + } + ] + } + }, + { + "environment.standing": { + "name": "production" + } + }, + { + "deployment.worker": { + "name": "webProduction", + "@app": "Trips.web", + "@assetsBinding": "ASSETS", + "@compatibilityDate": "2026-07-01", + "@compatibilityFlags": [ + "nodejs_compat" + ], + "@domains": [ + "trips.example.com", + "www.trips.example.com" + ], + "@environment": "production", + "@jobs": [ + "Trips.coverCleanup" + ], + "@main": "src/worker.ts", + "@notFound": "single-page-application", + "@script": "trips", + "@secrets": "keys", + "@tokenSecret": "ACME_WORKERS_TOKEN", + "@tokenVault": "deployKeys", + "@workerFirst": true, + "@workersDev": false, + "children": [ + { + "cloudflare.d1": { + "name": "db", + "@databaseId": "00000000-0000-4000-8000-000000000003", + "@databaseName": "trips", + "@migrationsDir": ".metaobjects/migrations" + } + }, + { + "cloudflare.r2": { + "name": "photos", + "@bucketName": "trips-photos" + } + }, + { + "cloudflare.ratelimit": { + "name": "enterLimiter", + "@limit": 10, + "@namespaceId": "1001", + "@period": 60 + } + }, + { + "cloudflare.ratelimit": { + "name": "adminLimiter", + "@limit": 200, + "@namespaceId": "1002", + "@period": 60 + } + }, + { + "cloudflare.ratelimit": { + "name": "loginLimiter", + "@limit": 10, + "@namespaceId": "1003", + "@period": 60 + } + }, + { + "cloudflare.ratelimit": { + "name": "loginLockoutLimiter", + "@limit": 4, + "@namespaceId": "1004", + "@period": 60 + } + }, + { + "cloudflare.ratelimit": { + "name": "recoveryLimiter", + "@limit": 3, + "@namespaceId": "1005", + "@period": 60 + } + }, + { + "value.literal": { + "name": "teamDomain", + "@literal": "team.example.com", + "@setting": "Access.teamDomain" + } + }, + { + "value.literal": { + "name": "aud", + "@literal": "0000000000000000000000000000000000000000000000000000000000000000", + "@setting": "Access.aud" + } + }, + { + "value.literal": { + "name": "notifyEmail", + "@literal": "host@example.com", + "@setting": "Notify.email" + } + } + ] + } + } + ] + } +} diff --git a/packs/cloudflare/fixtures/conformance/cloudflare-worker-cron-ratelimits/input/meta.trips.json b/packs/cloudflare/fixtures/conformance/cloudflare-worker-cron-ratelimits/input/meta.trips.json new file mode 100644 index 000000000..c21a35cb1 --- /dev/null +++ b/packs/cloudflare/fixtures/conformance/cloudflare-worker-cron-ratelimits/input/meta.trips.json @@ -0,0 +1,91 @@ +{ + "metadata.root": { + "package": "acme::trips", + "children": [ + { "system.internal": { + "name": "Trips", + "@description": "A trip journal: one Worker in front of its assets, with D1, R2, rate limiters and a daily clean-up.", + "children": [ + { "app.service": { + "name": "web", + "@needs": ["db", "photos"], + "@settings": ["Access", "Notify", "Auth"], + "children": [ + { "build.static": { "name": "client", "@directory": "dist/client", "@command": "pnpm build" } } + ] + } }, + { "app.job": { "name": "coverCleanup", "@description": "Deletes cover images no trip references.", "@schedule": "0 4 * * *" } }, + { "resource.database": { "name": "db" } }, + { "resource.bucket": { "name": "photos" } } + ] + } }, + { "object.settings": { + "name": "Access", + "children": [ + { "field.string": { "name": "teamDomain", "@envName": "ACCESS_TEAM_DOMAIN", "@required": true } }, + { "field.string": { "name": "aud", "@envName": "ACCESS_AUD", "@required": true } } + ] + } }, + { "object.settings": { + "name": "Notify", + "children": [ + { "field.string": { "name": "email", "@envName": "NOTIFY_EMAIL", "@required": true } } + ] + } }, + { "object.settings": { + "name": "Auth", + "children": [ + { "field.string": { "name": "sessionSecret", "@envName": "SESSION_SECRET", "@required": true, "@secret": true } }, + { "field.string": { "name": "resendApiKey", "@envName": "RESEND_API_KEY", "@required": true, "@secret": true } }, + { "field.string": { "name": "passphrasePepper", "@envName": "PASSPHRASE_PEPPER", "@required": true, "@secret": true } }, + { "field.string": { "name": "recoveryEncKey", "@envName": "RECOVERY_ENC_KEY", "@required": true, "@secret": true } }, + { "field.string": { "name": "recoveryHmacKey", "@envName": "RECOVERY_HMAC_KEY", "@required": true, "@secret": true } } + ] + } }, + { "vault.infisical": { + "name": "keys", + "children": [ + { "scope.env": { "name": "production", "@project": "trips", "@env": "prod" } } + ] + } }, + { "vault.infisical": { + "name": "deployKeys", + "@defaultScope": "dev", + "children": [ + { "scope.env": { "name": "dev", "@project": "acme-deploy" } } + ] + } }, + { "environment.standing": { "name": "production" } }, + { "deployment.worker": { + "name": "webProduction", + "@app": "Trips.web", + "@environment": "production", + "@script": "trips", + "@main": "src/worker.ts", + "@compatibilityDate": "2026-07-01", + "@compatibilityFlags": ["nodejs_compat"], + "@domains": ["trips.example.com", "www.trips.example.com"], + "@workersDev": false, + "@assetsBinding": "ASSETS", + "@notFound": "single-page-application", + "@workerFirst": true, + "@jobs": ["Trips.coverCleanup"], + "@secrets": "keys", + "@tokenVault": "deployKeys", + "@tokenSecret": "ACME_WORKERS_TOKEN", + "children": [ + { "cloudflare.d1": { "name": "db", "@databaseName": "trips", "@databaseId": "00000000-0000-4000-8000-000000000003", "@migrationsDir": ".metaobjects/migrations" } }, + { "cloudflare.r2": { "name": "photos", "@bucketName": "trips-photos" } }, + { "cloudflare.ratelimit": { "name": "enterLimiter", "@namespaceId": "1001", "@limit": 10, "@period": 60 } }, + { "cloudflare.ratelimit": { "name": "adminLimiter", "@namespaceId": "1002", "@limit": 200, "@period": 60 } }, + { "cloudflare.ratelimit": { "name": "loginLimiter", "@namespaceId": "1003", "@limit": 10, "@period": 60 } }, + { "cloudflare.ratelimit": { "name": "loginLockoutLimiter", "@namespaceId": "1004", "@limit": 4, "@period": 60 } }, + { "cloudflare.ratelimit": { "name": "recoveryLimiter", "@namespaceId": "1005", "@limit": 3, "@period": 60 } }, + { "value.literal": { "name": "teamDomain", "@setting": "Access.teamDomain", "@literal": "team.example.com" } }, + { "value.literal": { "name": "aud", "@setting": "Access.aud", "@literal": "0000000000000000000000000000000000000000000000000000000000000000" } }, + { "value.literal": { "name": "notifyEmail", "@setting": "Notify.email", "@literal": "host@example.com" } } + ] + } } + ] + } +} diff --git a/packs/cloudflare/fixtures/conformance/cloudflare-worker-cron-ratelimits/providers.json b/packs/cloudflare/fixtures/conformance/cloudflare-worker-cron-ratelimits/providers.json new file mode 100644 index 000000000..139d85434 --- /dev/null +++ b/packs/cloudflare/fixtures/conformance/cloudflare-worker-cron-ratelimits/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-documentation", "metaobjects-systems", "metaobjects-delivery", "metaobjects-config", "metaobjects-cloudflare"] diff --git a/packs/cloudflare/fixtures/conformance/cloudflare-worker-environments/expected.json b/packs/cloudflare/fixtures/conformance/cloudflare-worker-environments/expected.json new file mode 100644 index 000000000..197475d2b --- /dev/null +++ b/packs/cloudflare/fixtures/conformance/cloudflare-worker-environments/expected.json @@ -0,0 +1,248 @@ +{ + "metadata.root": { + "package": "acme::quiz", + "children": [ + { + "system.internal": { + "name": "Quiz", + "@description": "A quiz site: one Worker with static assets, a D1 database and a KV namespace.", + "children": [ + { + "app.service": { + "name": "site", + "@needs": [ + "db", + "rateLimit" + ], + "@settings": [ + "Limits", + "Turnstile", + "Search" + ], + "children": [ + { + "build.static": { + "name": "assets", + "@directory": "public" + } + } + ] + } + }, + { + "resource.database": { + "name": "db" + } + }, + { + "resource.keyvalue": { + "name": "rateLimit" + } + } + ] + } + }, + { + "object.settings": { + "name": "Limits", + "children": [ + { + "field.int": { + "name": "maxQuestionsPerDay", + "@default": 5, + "@envName": "MAX_QUESTIONS_PER_DAY" + } + }, + { + "field.int": { + "name": "globalMaxPerDay", + "@default": 200, + "@envName": "GLOBAL_MAX_PER_DAY" + } + }, + { + "field.int": { + "name": "ipMaxPerDay", + "@default": 10, + "@envName": "IP_MAX_PER_DAY" + } + }, + { + "field.string": { + "name": "killSwitch", + "@default": "off", + "@envName": "KILL_SWITCH" + } + } + ] + } + }, + { + "object.settings": { + "name": "Turnstile", + "children": [ + { + "field.string": { + "name": "siteKey", + "@envName": "TURNSTILE_SITE_KEY", + "@required": true + } + } + ] + } + }, + { + "object.settings": { + "name": "Search", + "children": [ + { + "field.string": { + "name": "url", + "@envName": "SEARCH_URL", + "@secret": true + } + } + ] + } + }, + { + "vault.infisical": { + "name": "keys", + "children": [ + { + "scope.env": { + "name": "production", + "@env": "prod", + "@project": "quiz" + } + }, + { + "scope.env": { + "name": "staging", + "@env": "staging", + "@project": "quiz" + } + } + ] + } + }, + { + "vault.infisical": { + "name": "deployKeys", + "@defaultScope": "dev", + "children": [ + { + "scope.env": { + "name": "dev", + "@project": "acme-deploy" + } + } + ] + } + }, + { + "environment.standing": { + "name": "production" + } + }, + { + "environment.standing": { + "name": "staging" + } + }, + { + "deployment.worker": { + "name": "siteBase", + "abstract": true, + "@app": "Quiz.site", + "@assetsBinding": "ASSETS", + "@compatibilityDate": "2024-12-30", + "@compatibilityFlags": [ + "nodejs_compat" + ], + "@description": "What every environment of the site shares.", + "@main": "src/index.ts", + "@notFound": "single-page-application", + "@script": "quiz", + "@secrets": "keys", + "@tokenSecret": "ACME_WORKERS_TOKEN", + "@tokenVault": "deployKeys", + "@workerFirstPaths": [ + "/api/*", + "/c/*" + ], + "children": [ + { + "cloudflare.d1": { + "name": "db", + "@databaseId": "00000000-0000-4000-8000-000000000001", + "@databaseName": "quiz", + "@migrationsDir": "migrations" + } + }, + { + "cloudflare.kv": { + "name": "rateLimit", + "@namespaceId": "00000000000000000000000000000001" + } + }, + { + "value.literal": { + "name": "siteKey", + "@literal": "1x00000000000000000000AA", + "@setting": "Turnstile.siteKey" + } + } + ] + } + }, + { + "deployment.worker": { + "name": "siteProduction", + "extends": "acme::quiz::siteBase", + "@branch": "main", + "@domains": [ + "quiz.example.com", + "www.quiz.example.com" + ], + "@environment": "production" + } + }, + { + "deployment.worker": { + "name": "siteStaging", + "extends": "acme::quiz::siteBase", + "@branch": "staging", + "@description": "Only what differs in staging: its own database, namespace and domain, and the kill switch on.", + "@domains": [ + "staging.quiz.example.com" + ], + "@environment": "staging", + "children": [ + { + "cloudflare.d1": { + "name": "db", + "@databaseId": "00000000-0000-4000-8000-000000000002", + "@databaseName": "quiz-staging", + "@migrationsDir": "migrations" + } + }, + { + "cloudflare.kv": { + "name": "rateLimit", + "@namespaceId": "00000000000000000000000000000002" + } + }, + { + "value.literal": { + "name": "killSwitch", + "@literal": "on", + "@setting": "Limits.killSwitch" + } + } + ] + } + } + ] + } +} diff --git a/packs/cloudflare/fixtures/conformance/cloudflare-worker-environments/input/meta.quiz.json b/packs/cloudflare/fixtures/conformance/cloudflare-worker-environments/input/meta.quiz.json new file mode 100644 index 000000000..2203d52b3 --- /dev/null +++ b/packs/cloudflare/fixtures/conformance/cloudflare-worker-environments/input/meta.quiz.json @@ -0,0 +1,101 @@ +{ + "metadata.root": { + "package": "acme::quiz", + "children": [ + { "system.internal": { + "name": "Quiz", + "@description": "A quiz site: one Worker with static assets, a D1 database and a KV namespace.", + "children": [ + { "app.service": { + "name": "site", + "@needs": ["db", "rateLimit"], + "@settings": ["Limits", "Turnstile", "Search"], + "children": [ + { "build.static": { "name": "assets", "@directory": "public" } } + ] + } }, + { "resource.database": { "name": "db" } }, + { "resource.keyvalue": { "name": "rateLimit" } } + ] + } }, + { "object.settings": { + "name": "Limits", + "children": [ + { "field.int": { "name": "maxQuestionsPerDay", "@envName": "MAX_QUESTIONS_PER_DAY", "@default": 5 } }, + { "field.int": { "name": "globalMaxPerDay", "@envName": "GLOBAL_MAX_PER_DAY", "@default": 200 } }, + { "field.int": { "name": "ipMaxPerDay", "@envName": "IP_MAX_PER_DAY", "@default": 10 } }, + { "field.string": { "name": "killSwitch", "@envName": "KILL_SWITCH", "@default": "off" } } + ] + } }, + { "object.settings": { + "name": "Turnstile", + "children": [ + { "field.string": { "name": "siteKey", "@envName": "TURNSTILE_SITE_KEY", "@required": true } } + ] + } }, + { "object.settings": { + "name": "Search", + "children": [ + { "field.string": { "name": "url", "@envName": "SEARCH_URL", "@secret": true } } + ] + } }, + { "vault.infisical": { + "name": "keys", + "children": [ + { "scope.env": { "name": "production", "@project": "quiz", "@env": "prod" } }, + { "scope.env": { "name": "staging", "@project": "quiz", "@env": "staging" } } + ] + } }, + { "vault.infisical": { + "name": "deployKeys", + "@defaultScope": "dev", + "children": [ + { "scope.env": { "name": "dev", "@project": "acme-deploy" } } + ] + } }, + { "environment.standing": { "name": "production" } }, + { "environment.standing": { "name": "staging" } }, + { "deployment.worker": { + "name": "siteBase", + "abstract": true, + "@description": "What every environment of the site shares.", + "@app": "Quiz.site", + "@script": "quiz", + "@main": "src/index.ts", + "@compatibilityDate": "2024-12-30", + "@compatibilityFlags": ["nodejs_compat"], + "@assetsBinding": "ASSETS", + "@notFound": "single-page-application", + "@workerFirstPaths": ["/api/*", "/c/*"], + "@secrets": "keys", + "@tokenVault": "deployKeys", + "@tokenSecret": "ACME_WORKERS_TOKEN", + "children": [ + { "cloudflare.d1": { "name": "db", "@databaseName": "quiz", "@databaseId": "00000000-0000-4000-8000-000000000001", "@migrationsDir": "migrations" } }, + { "cloudflare.kv": { "name": "rateLimit", "@namespaceId": "00000000000000000000000000000001" } }, + { "value.literal": { "name": "siteKey", "@setting": "Turnstile.siteKey", "@literal": "1x00000000000000000000AA" } } + ] + } }, + { "deployment.worker": { + "name": "siteProduction", + "extends": "siteBase", + "@environment": "production", + "@branch": "main", + "@domains": ["quiz.example.com", "www.quiz.example.com"] + } }, + { "deployment.worker": { + "name": "siteStaging", + "extends": "siteBase", + "@description": "Only what differs in staging: its own database, namespace and domain, and the kill switch on.", + "@environment": "staging", + "@branch": "staging", + "@domains": ["staging.quiz.example.com"], + "children": [ + { "cloudflare.d1": { "name": "db", "@databaseName": "quiz-staging", "@databaseId": "00000000-0000-4000-8000-000000000002", "@migrationsDir": "migrations" } }, + { "cloudflare.kv": { "name": "rateLimit", "@namespaceId": "00000000000000000000000000000002" } }, + { "value.literal": { "name": "killSwitch", "@setting": "Limits.killSwitch", "@literal": "on" } } + ] + } } + ] + } +} diff --git a/packs/cloudflare/fixtures/conformance/cloudflare-worker-environments/providers.json b/packs/cloudflare/fixtures/conformance/cloudflare-worker-environments/providers.json new file mode 100644 index 000000000..139d85434 --- /dev/null +++ b/packs/cloudflare/fixtures/conformance/cloudflare-worker-environments/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-documentation", "metaobjects-systems", "metaobjects-delivery", "metaobjects-config", "metaobjects-cloudflare"] diff --git a/packs/cloudflare/fixtures/conformance/error-binding-base-authored/expected-errors.json b/packs/cloudflare/fixtures/conformance/error-binding-base-authored/expected-errors.json new file mode 100644 index 000000000..c46a2ac14 --- /dev/null +++ b/packs/cloudflare/fixtures/conformance/error-binding-base-authored/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_ABSTRACT_SUBTYPE_AUTHORED", + "source": { + "format": "json", + "files": [ + "meta.shop.json" + ], + "jsonPath": "$['metadata.root'].children[2]['deployment.worker'].children[0]['cloudflare.base']" + } + } + ], + "warnings": [] +} diff --git a/packs/cloudflare/fixtures/conformance/error-binding-base-authored/input/meta.shop.json b/packs/cloudflare/fixtures/conformance/error-binding-base-authored/input/meta.shop.json new file mode 100644 index 000000000..e7dc55010 --- /dev/null +++ b/packs/cloudflare/fixtures/conformance/error-binding-base-authored/input/meta.shop.json @@ -0,0 +1,8 @@ +{ "metadata.root": { "package": "acme::shop", "children": [ + { "system.internal": { "name": "Shop", "children": [ + { "app.service": { "name": "site", "@needs": ["db"], "children": [ { "build.static": { "name": "assets", "@directory": "public" } } ] } }, + { "resource.database": { "name": "db" } } ] } }, + { "environment.standing": { "name": "production" } }, + { "deployment.worker": { "name": "siteProduction", "@app": "Shop.site", "@environment": "production", "@compatibilityDate": "2026-07-01", "@tokenSecret": "ACME_WORKERS_TOKEN", "children": [ + { "cloudflare.base": { "name": "db" } } ] } } +]}} diff --git a/packs/cloudflare/fixtures/conformance/error-binding-base-authored/providers.json b/packs/cloudflare/fixtures/conformance/error-binding-base-authored/providers.json new file mode 100644 index 000000000..139d85434 --- /dev/null +++ b/packs/cloudflare/fixtures/conformance/error-binding-base-authored/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-documentation", "metaobjects-systems", "metaobjects-delivery", "metaobjects-config", "metaobjects-cloudflare"] diff --git a/packs/cloudflare/fixtures/conformance/error-binding-on-pages/expected-errors.json b/packs/cloudflare/fixtures/conformance/error-binding-on-pages/expected-errors.json new file mode 100644 index 000000000..f2a3722d9 --- /dev/null +++ b/packs/cloudflare/fixtures/conformance/error-binding-on-pages/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_CHILD_NOT_ALLOWED", + "source": { + "format": "json", + "files": [ + "meta.shop.json" + ], + "jsonPath": "$['metadata.root'].children[2]['deployment.pages']" + } + } + ], + "warnings": [] +} diff --git a/packs/cloudflare/fixtures/conformance/error-binding-on-pages/input/meta.shop.json b/packs/cloudflare/fixtures/conformance/error-binding-on-pages/input/meta.shop.json new file mode 100644 index 000000000..0f5f0bb87 --- /dev/null +++ b/packs/cloudflare/fixtures/conformance/error-binding-on-pages/input/meta.shop.json @@ -0,0 +1,8 @@ +{ "metadata.root": { "package": "acme::shop", "children": [ + { "system.internal": { "name": "Shop", "children": [ + { "app.service": { "name": "site", "@needs": ["db"], "children": [ { "build.static": { "name": "assets", "@directory": "public" } } ] } }, + { "resource.database": { "name": "db" } } ] } }, + { "environment.standing": { "name": "production" } }, + { "deployment.pages": { "name": "siteProduction", "@app": "Shop.site", "@environment": "production", "@project": "shop", "@tokenSecret": "ACME_PAGES_TOKEN", "children": [ + { "cloudflare.d1": { "name": "db", "@databaseName": "shop" } } ] } } +]}} diff --git a/packs/cloudflare/fixtures/conformance/error-binding-on-pages/providers.json b/packs/cloudflare/fixtures/conformance/error-binding-on-pages/providers.json new file mode 100644 index 000000000..139d85434 --- /dev/null +++ b/packs/cloudflare/fixtures/conformance/error-binding-on-pages/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-documentation", "metaobjects-systems", "metaobjects-delivery", "metaobjects-config", "metaobjects-cloudflare"] diff --git a/packs/cloudflare/fixtures/conformance/error-not-found-not-allowed/expected-errors.json b/packs/cloudflare/fixtures/conformance/error-not-found-not-allowed/expected-errors.json new file mode 100644 index 000000000..c85037035 --- /dev/null +++ b/packs/cloudflare/fixtures/conformance/error-not-found-not-allowed/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.shop.json" + ], + "jsonPath": "$['metadata.root'].children[2]['deployment.worker']" + } + } + ], + "warnings": [] +} diff --git a/packs/cloudflare/fixtures/conformance/error-not-found-not-allowed/input/meta.shop.json b/packs/cloudflare/fixtures/conformance/error-not-found-not-allowed/input/meta.shop.json new file mode 100644 index 000000000..4bf88f127 --- /dev/null +++ b/packs/cloudflare/fixtures/conformance/error-not-found-not-allowed/input/meta.shop.json @@ -0,0 +1,7 @@ +{ "metadata.root": { "package": "acme::shop", "children": [ + { "system.internal": { "name": "Shop", "children": [ + { "app.service": { "name": "site", "@needs": ["db"], "children": [ { "build.static": { "name": "assets", "@directory": "public" } } ] } }, + { "resource.database": { "name": "db" } } ] } }, + { "environment.standing": { "name": "production" } }, + { "deployment.worker": { "name": "siteProduction", "@app": "Shop.site", "@environment": "production", "@compatibilityDate": "2026-07-01", "@tokenSecret": "ACME_WORKERS_TOKEN", "@notFound": "index" } } +]}} diff --git a/packs/cloudflare/fixtures/conformance/error-not-found-not-allowed/providers.json b/packs/cloudflare/fixtures/conformance/error-not-found-not-allowed/providers.json new file mode 100644 index 000000000..139d85434 --- /dev/null +++ b/packs/cloudflare/fixtures/conformance/error-not-found-not-allowed/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-documentation", "metaobjects-systems", "metaobjects-delivery", "metaobjects-config", "metaobjects-cloudflare"] diff --git a/packs/cloudflare/fixtures/conformance/error-worker-app-unresolved/expected-errors.json b/packs/cloudflare/fixtures/conformance/error-worker-app-unresolved/expected-errors.json new file mode 100644 index 000000000..eaa641f8b --- /dev/null +++ b/packs/cloudflare/fixtures/conformance/error-worker-app-unresolved/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_DELIVERY_UNRESOLVED_REF", + "source": { + "format": "json", + "files": [ + "meta.shop.json" + ], + "jsonPath": "$['metadata.root'].children[2]['deployment.worker']" + } + } + ], + "warnings": [] +} diff --git a/packs/cloudflare/fixtures/conformance/error-worker-app-unresolved/input/meta.shop.json b/packs/cloudflare/fixtures/conformance/error-worker-app-unresolved/input/meta.shop.json new file mode 100644 index 000000000..0ae8b6d27 --- /dev/null +++ b/packs/cloudflare/fixtures/conformance/error-worker-app-unresolved/input/meta.shop.json @@ -0,0 +1,7 @@ +{ "metadata.root": { "package": "acme::shop", "children": [ + { "system.internal": { "name": "Shop", "children": [ + { "app.service": { "name": "site", "@needs": ["db"], "children": [ { "build.static": { "name": "assets", "@directory": "public" } } ] } }, + { "resource.database": { "name": "db" } } ] } }, + { "environment.standing": { "name": "production" } }, + { "deployment.worker": { "name": "siteProduction", "@app": "Shop.web", "@environment": "production", "@compatibilityDate": "2026-07-01", "@tokenSecret": "ACME_WORKERS_TOKEN" } } +]}} diff --git a/packs/cloudflare/fixtures/conformance/error-worker-app-unresolved/providers.json b/packs/cloudflare/fixtures/conformance/error-worker-app-unresolved/providers.json new file mode 100644 index 000000000..139d85434 --- /dev/null +++ b/packs/cloudflare/fixtures/conformance/error-worker-app-unresolved/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-documentation", "metaobjects-systems", "metaobjects-delivery", "metaobjects-config", "metaobjects-cloudflare"] diff --git a/packs/cloudflare/fixtures/conformance/error-worker-missing-compatibility-date/expected-errors.json b/packs/cloudflare/fixtures/conformance/error-worker-missing-compatibility-date/expected-errors.json new file mode 100644 index 000000000..55769ca4a --- /dev/null +++ b/packs/cloudflare/fixtures/conformance/error-worker-missing-compatibility-date/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_MISSING_REQUIRED_ATTR", + "source": { + "format": "json", + "files": [ + "meta.shop.json" + ], + "jsonPath": "$['metadata.root'].children[3]['deployment.worker']" + } + } + ], + "warnings": [] +} diff --git a/packs/cloudflare/fixtures/conformance/error-worker-missing-compatibility-date/input/meta.shop.json b/packs/cloudflare/fixtures/conformance/error-worker-missing-compatibility-date/input/meta.shop.json new file mode 100644 index 000000000..0f166b1d2 --- /dev/null +++ b/packs/cloudflare/fixtures/conformance/error-worker-missing-compatibility-date/input/meta.shop.json @@ -0,0 +1,8 @@ +{ "metadata.root": { "package": "acme::shop", "children": [ + { "system.internal": { "name": "Shop", "children": [ + { "app.service": { "name": "site", "@needs": ["db"], "children": [ { "build.static": { "name": "assets", "@directory": "public" } } ] } }, + { "resource.database": { "name": "db" } } ] } }, + { "environment.standing": { "name": "production" } }, + { "deployment.worker": { "name": "siteBase", "abstract": true, "@app": "Shop.site", "@tokenSecret": "ACME_WORKERS_TOKEN" } }, + { "deployment.worker": { "name": "siteProduction", "extends": "siteBase", "@environment": "production" } } +]}} diff --git a/packs/cloudflare/fixtures/conformance/error-worker-missing-compatibility-date/providers.json b/packs/cloudflare/fixtures/conformance/error-worker-missing-compatibility-date/providers.json new file mode 100644 index 000000000..139d85434 --- /dev/null +++ b/packs/cloudflare/fixtures/conformance/error-worker-missing-compatibility-date/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-documentation", "metaobjects-systems", "metaobjects-delivery", "metaobjects-config", "metaobjects-cloudflare"] diff --git a/packs/cloudflare/fixtures/expected-vocabulary.json b/packs/cloudflare/fixtures/expected-vocabulary.json new file mode 100644 index 000000000..c3a7059d2 --- /dev/null +++ b/packs/cloudflare/fixtures/expected-vocabulary.json @@ -0,0 +1,391 @@ +{ + "pack": "metaobjects-cloudflare", + "types": [ + { + "type": "cloudflare", + "subType": "base", + "description": "Abstract Cloudflare binding base: one binding of a Worker, a child of a deployment.worker. Its binding name is the node's name in upper snake case (`rateLimit` is RATE_LIMIT). Not authored directly: a `cloudflare.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED).", + "attrs": [], + "children": [] + }, + { + "type": "cloudflare", + "subType": "d1", + "description": "Where a resource.database the app needs lives on D1 in this environment. Named after the resource.", + "whenToUse": "Each D1 database a Worker binds.", + "attrs": [ + { + "name": "databaseId", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The D1 database's id." + }, + { + "name": "databaseName", + "valueType": "string", + "isArray": false, + "required": true, + "description": "The D1 database's name." + }, + { + "name": "migrationsDir", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The directory of its migrations, from the repository root, for `wrangler d1 migrations`." + } + ], + "children": [] + }, + { + "type": "cloudflare", + "subType": "kv", + "description": "Where a resource.keyvalue the app needs lives in Workers KV in this environment. Named after the resource.", + "whenToUse": "Each KV namespace a Worker binds.", + "attrs": [ + { + "name": "namespaceId", + "valueType": "string", + "isArray": false, + "required": true, + "description": "The KV namespace's id." + } + ], + "children": [] + }, + { + "type": "cloudflare", + "subType": "queue", + "description": "Where a resource.queue the app sends to lives in Cloudflare Queues in this environment. Named after the resource.", + "whenToUse": "Each queue a Worker produces messages on.", + "attrs": [ + { + "name": "queue", + "valueType": "string", + "isArray": false, + "required": true, + "description": "The queue's name." + } + ], + "children": [] + }, + { + "type": "cloudflare", + "subType": "r2", + "description": "Where a resource.bucket the app needs lives in R2 in this environment. Named after the resource.", + "whenToUse": "Each R2 bucket a Worker binds.", + "attrs": [ + { + "name": "bucketName", + "valueType": "string", + "isArray": false, + "required": true, + "description": "The R2 bucket's name." + } + ], + "children": [] + }, + { + "type": "cloudflare", + "subType": "ratelimit", + "description": "A Workers rate limiting binding: at most @limit calls per key in @period seconds.", + "whenToUse": "Each rate limiter a Worker checks.", + "attrs": [ + { + "name": "limit", + "valueType": "int", + "isArray": false, + "required": true, + "description": "The calls allowed per key in one period." + }, + { + "name": "namespaceId", + "valueType": "string", + "isArray": false, + "required": true, + "description": "The limiter's namespace id, unique in the account (`1001`)." + }, + { + "name": "period", + "valueType": "int", + "isArray": false, + "required": true, + "description": "The period in seconds: 10 or 60, the only two Cloudflare accepts." + } + ], + "children": [] + }, + { + "type": "deployment", + "subType": "pages", + "description": "An app deployed as a Cloudflare Pages site in one environment: the directory of its build.static, uploaded by `wrangler pages deploy`. Takes every deployment.base attribute; @branch is the branch the upload is recorded on (the project's production branch, or a preview branch). A Pages project has two environments, production and preview, each with its own variables: the upload of the production branch serves production and every other upload serves preview, and the secret sync writes to the environment the @branch serves. The model states the production branch with the @branch of the deployment.pages in the environment named `production`; when it states none, a deployment that reads a secret is refused.", + "whenToUse": "Each (app, environment) pair that ships as a Cloudflare Pages site.", + "attrs": [ + { + "name": "app", + "valueType": "string", + "isArray": false, + "required": true, + "description": "The app deployed: `System.app` (`Shop.web`), or `pkg::System.app` from another package. It must resolve to an app.* node (ERR_DELIVERY_UNRESOLVED_REF)." + }, + { + "name": "branch", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The repository branch whose pushes deploy here." + }, + { + "name": "domains", + "valueType": "string", + "isArray": true, + "required": false, + "description": "The public host names that route to the app here." + }, + { + "name": "environment", + "valueType": "string", + "isArray": false, + "required": true, + "description": "The environment.* node it deploys to, by name (or `pkg::name`). It must resolve (ERR_DELIVERY_UNRESOLVED_REF)." + }, + { + "name": "project", + "valueType": "string", + "isArray": false, + "required": true, + "description": "The Pages project's name." + }, + { + "name": "region", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The platform's region name." + }, + { + "name": "replicas", + "valueType": "int", + "isArray": false, + "required": false, + "description": "How many copies run. Absent means the platform's default." + }, + { + "name": "secrets", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The vault the deployment's secret settings come from, by name (a vault.* of the config pack). Recorded by name only: this pack does not require the config pack." + }, + { + "name": "tokenSecret", + "valueType": "string", + "isArray": false, + "required": true, + "description": "The name, in the vault, of the narrow Cloudflare API token the deploy scripts use for this site (Pages Write). The scripts map it to CLOUDFLARE_API_TOKEN and unset the global-key variables. The vault entry CLOUDFLARE_ACCOUNT_ID sits beside it." + }, + { + "name": "tokenVault", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The vault (a vault.* of the config pack, by name) whose scope for this environment holds @tokenSecret and CLOUDFLARE_ACCOUNT_ID. Absent means the @secrets vault." + } + ], + "children": [ + { + "childType": "value", + "childSubType": [ + "literal", + "ref" + ], + "childName": "*", + "min": 0, + "max": null + } + ] + }, + { + "type": "deployment", + "subType": "worker", + "description": "An app deployed as one Cloudflare Worker, with or without static assets, in one environment. Takes every deployment.base attribute (@app, @environment, @domains, @branch, @secrets, and value.* children) and adds the Worker's own. The facts every environment shares belong on an abstract deployment.worker that each environment's deployment extends; the environment's deployment then holds only what differs there. The wrangler.jsonc generator writes the top-level environment and one complete env block per other environment.", + "whenToUse": "Each (app, environment) pair that runs as a Cloudflare Worker.", + "attrs": [ + { + "name": "app", + "valueType": "string", + "isArray": false, + "required": true, + "description": "The app deployed: `System.app` (`Shop.web`), or `pkg::System.app` from another package. It must resolve to an app.* node (ERR_DELIVERY_UNRESOLVED_REF)." + }, + { + "name": "assetsBinding", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The binding the Worker reads its static assets through (`ASSETS`). The assets are the directory of the app's build.static. Absent: the Worker reads none itself." + }, + { + "name": "branch", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The repository branch whose pushes deploy here." + }, + { + "name": "compatibilityDate", + "valueType": "string", + "isArray": false, + "required": true, + "description": "The Workers runtime compatibility date (`2026-07-01`)." + }, + { + "name": "compatibilityFlags", + "valueType": "string", + "isArray": true, + "required": false, + "description": "Workers runtime compatibility flags (`nodejs_compat`)." + }, + { + "name": "domains", + "valueType": "string", + "isArray": true, + "required": false, + "description": "The public host names that route to the app here." + }, + { + "name": "environment", + "valueType": "string", + "isArray": false, + "required": true, + "description": "The environment.* node it deploys to, by name (or `pkg::name`). It must resolve (ERR_DELIVERY_UNRESOLVED_REF)." + }, + { + "name": "extra", + "valueType": "string", + "isArray": false, + "required": false, + "description": "A JSON object of Wrangler configuration keys this pack does not model, copied into the environment's block as written. The escape hatch: a key the generator writes itself is refused, and a key Wrangler fills into an env block that omits it (`observability`, `placement`, ...) is set in every environment or in none." + }, + { + "name": "jobs", + "valueType": "string", + "isArray": true, + "required": false, + "description": "The app.job nodes this Worker runs on their @schedule (its scheduled handler), as `System.job`. Each must resolve to an app.job with a @schedule; each schedule is a cron trigger." + }, + { + "name": "main", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The Worker's entry module from the repository root (`src/index.ts`). Absent for a Worker that only serves assets." + }, + { + "name": "notFound", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "single-page-application", + "404-page", + "none" + ], + "description": "What a request that matches no asset gets: single-page-application (the index page), 404-page (the nearest 404.html) or none (a 404, or the Worker). Cloudflare's own names." + }, + { + "name": "region", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The platform's region name." + }, + { + "name": "replicas", + "valueType": "int", + "isArray": false, + "required": false, + "description": "How many copies run. Absent means the platform's default." + }, + { + "name": "script", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The Worker's name on Cloudflare. Absent means the app's name. In an env block the name is `-` (Wrangler's own default) unless this deployment's @script differs from the top level's: two environments never deploy over one Worker." + }, + { + "name": "secrets", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The vault the deployment's secret settings come from, by name (a vault.* of the config pack). Recorded by name only: this pack does not require the config pack." + }, + { + "name": "tokenSecret", + "valueType": "string", + "isArray": false, + "required": true, + "description": "The name, in the vault, of the narrow Cloudflare API token the deploy scripts use for this Worker. The scripts map it to CLOUDFLARE_API_TOKEN and unset the global-key variables. The vault entry CLOUDFLARE_ACCOUNT_ID sits beside it." + }, + { + "name": "tokenVault", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The vault (a vault.* of the config pack, by name) whose scope for this environment holds @tokenSecret and CLOUDFLARE_ACCOUNT_ID. Absent means the @secrets vault." + }, + { + "name": "workerFirst", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "true: the Worker runs before the assets for every request. Not with @workerFirstPaths." + }, + { + "name": "workerFirstPaths", + "valueType": "string", + "isArray": true, + "required": false, + "description": "The route patterns the Worker runs before the assets for (`/api/*`); every other request is served from the assets first. Not with @workerFirst." + }, + { + "name": "workersDev", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "Whether the Worker is also served on its workers.dev subdomain. Absent leaves Wrangler's default (served)." + } + ], + "children": [ + { + "childType": "cloudflare", + "childSubType": [ + "d1", + "kv", + "r2", + "queue", + "ratelimit" + ], + "childName": "*", + "min": 0, + "max": null + }, + { + "childType": "value", + "childSubType": [ + "literal", + "ref" + ], + "childName": "*", + "min": 0, + "max": null + } + ] + } + ], + "extends": [], + "commonAttrs": [], + "defaultSubTypes": {} +} diff --git a/packs/cloudflare/metamodel/cloudflare.json b/packs/cloudflare/metamodel/cloudflare.json new file mode 100644 index 000000000..5ce5ebb9c --- /dev/null +++ b/packs/cloudflare/metamodel/cloudflare.json @@ -0,0 +1,99 @@ +{ + "provider": "metaobjects-cloudflare", + "types": [ + { + "type": "deployment", + "subType": "worker", + "extendsBase": true, + "description": "An app deployed as one Cloudflare Worker, with or without static assets, in one environment. Takes every deployment.base attribute (@app, @environment, @domains, @branch, @secrets, and value.* children) and adds the Worker's own. The facts every environment shares belong on an abstract deployment.worker that each environment's deployment extends; the environment's deployment then holds only what differs there. The wrangler.jsonc generator writes the top-level environment and one complete env block per other environment.", + "whenToUse": "Each (app, environment) pair that runs as a Cloudflare Worker.", + "children": [ + { "type": "attr", "subType": "string", "name": "script", "min": 0, "max": 1, "description": "The Worker's name on Cloudflare. Absent means the app's name. In an env block the name is `-` (Wrangler's own default) unless this deployment's @script differs from the top level's: two environments never deploy over one Worker." }, + { "type": "attr", "subType": "string", "name": "main", "min": 0, "max": 1, "description": "The Worker's entry module from the repository root (`src/index.ts`). Absent for a Worker that only serves assets." }, + { "type": "attr", "subType": "string", "name": "compatibilityDate", "min": 1, "max": 1, "description": "The Workers runtime compatibility date (`2026-07-01`)." }, + { "type": "attr", "subType": "string", "name": "compatibilityFlags", "isArray": true, "min": 0, "max": 1, "description": "Workers runtime compatibility flags (`nodejs_compat`)." }, + { "type": "attr", "subType": "boolean", "name": "workersDev", "min": 0, "max": 1, "description": "Whether the Worker is also served on its workers.dev subdomain. Absent leaves Wrangler's default (served)." }, + { "type": "attr", "subType": "string", "name": "assetsBinding", "min": 0, "max": 1, "description": "The binding the Worker reads its static assets through (`ASSETS`). The assets are the directory of the app's build.static. Absent: the Worker reads none itself." }, + { "type": "attr", "subType": "string", "name": "notFound", "min": 0, "max": 1, "allowedValues": ["single-page-application", "404-page", "none"], "description": "What a request that matches no asset gets: single-page-application (the index page), 404-page (the nearest 404.html) or none (a 404, or the Worker). Cloudflare's own names." }, + { "type": "attr", "subType": "boolean", "name": "workerFirst", "min": 0, "max": 1, "description": "true: the Worker runs before the assets for every request. Not with @workerFirstPaths." }, + { "type": "attr", "subType": "string", "name": "workerFirstPaths", "isArray": true, "min": 0, "max": 1, "description": "The route patterns the Worker runs before the assets for (`/api/*`); every other request is served from the assets first. Not with @workerFirst." }, + { "type": "attr", "subType": "string", "name": "jobs", "isArray": true, "min": 0, "max": 1, "description": "The app.job nodes this Worker runs on their @schedule (its scheduled handler), as `System.job`. Each must resolve to an app.job with a @schedule; each schedule is a cron trigger." }, + { "type": "attr", "subType": "string", "name": "tokenSecret", "min": 1, "max": 1, "description": "The name, in the vault, of the narrow Cloudflare API token the deploy scripts use for this Worker. The scripts map it to CLOUDFLARE_API_TOKEN and unset the global-key variables. The vault entry CLOUDFLARE_ACCOUNT_ID sits beside it." }, + { "type": "attr", "subType": "string", "name": "tokenVault", "min": 0, "max": 1, "description": "The vault (a vault.* of the config pack, by name) whose scope for this environment holds @tokenSecret and CLOUDFLARE_ACCOUNT_ID. Absent means the @secrets vault." }, + { "type": "attr", "subType": "string", "name": "extra", "min": 0, "max": 1, "description": "A JSON object of Wrangler configuration keys this pack does not model, copied into the environment's block as written. The escape hatch: a key the generator writes itself is refused, and a key Wrangler fills into an env block that omits it (`observability`, `placement`, ...) is set in every environment or in none." }, + { "type": "cloudflare", "subType": ["d1", "kv", "r2", "queue", "ratelimit"], "name": "*", "min": 0, "max": null } + ] + }, + { + "type": "deployment", + "subType": "pages", + "extendsBase": true, + "description": "An app deployed as a Cloudflare Pages site in one environment: the directory of its build.static, uploaded by `wrangler pages deploy`. Takes every deployment.base attribute; @branch is the branch the upload is recorded on (the project's production branch, or a preview branch). A Pages project has two environments, production and preview, each with its own variables: the upload of the production branch serves production and every other upload serves preview, and the secret sync writes to the environment the @branch serves. The model states the production branch with the @branch of the deployment.pages in the environment named `production`; when it states none, a deployment that reads a secret is refused.", + "whenToUse": "Each (app, environment) pair that ships as a Cloudflare Pages site.", + "children": [ + { "type": "attr", "subType": "string", "name": "project", "min": 1, "max": 1, "description": "The Pages project's name." }, + { "type": "attr", "subType": "string", "name": "tokenSecret", "min": 1, "max": 1, "description": "The name, in the vault, of the narrow Cloudflare API token the deploy scripts use for this site (Pages Write). The scripts map it to CLOUDFLARE_API_TOKEN and unset the global-key variables. The vault entry CLOUDFLARE_ACCOUNT_ID sits beside it." }, + { "type": "attr", "subType": "string", "name": "tokenVault", "min": 0, "max": 1, "description": "The vault (a vault.* of the config pack, by name) whose scope for this environment holds @tokenSecret and CLOUDFLARE_ACCOUNT_ID. Absent means the @secrets vault." } + ] + }, + { + "type": "cloudflare", + "subType": "base", + "description": "Abstract Cloudflare binding base: one binding of a Worker, a child of a deployment.worker. Its binding name is the node's name in upper snake case (`rateLimit` is RATE_LIMIT). Not authored directly: a `cloudflare.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED)." + }, + { + "type": "cloudflare", + "subType": "d1", + "extendsBase": true, + "description": "Where a resource.database the app needs lives on D1 in this environment. Named after the resource.", + "whenToUse": "Each D1 database a Worker binds.", + "children": [ + { "type": "attr", "subType": "string", "name": "databaseName", "min": 1, "max": 1, "description": "The D1 database's name." }, + { "type": "attr", "subType": "string", "name": "databaseId", "min": 0, "max": 1, "description": "The D1 database's id." }, + { "type": "attr", "subType": "string", "name": "migrationsDir", "min": 0, "max": 1, "description": "The directory of its migrations, from the repository root, for `wrangler d1 migrations`." } + ] + }, + { + "type": "cloudflare", + "subType": "kv", + "extendsBase": true, + "description": "Where a resource.keyvalue the app needs lives in Workers KV in this environment. Named after the resource.", + "whenToUse": "Each KV namespace a Worker binds.", + "children": [ + { "type": "attr", "subType": "string", "name": "namespaceId", "min": 1, "max": 1, "description": "The KV namespace's id." } + ] + }, + { + "type": "cloudflare", + "subType": "r2", + "extendsBase": true, + "description": "Where a resource.bucket the app needs lives in R2 in this environment. Named after the resource.", + "whenToUse": "Each R2 bucket a Worker binds.", + "children": [ + { "type": "attr", "subType": "string", "name": "bucketName", "min": 1, "max": 1, "description": "The R2 bucket's name." } + ] + }, + { + "type": "cloudflare", + "subType": "queue", + "extendsBase": true, + "description": "Where a resource.queue the app sends to lives in Cloudflare Queues in this environment. Named after the resource.", + "whenToUse": "Each queue a Worker produces messages on.", + "children": [ + { "type": "attr", "subType": "string", "name": "queue", "min": 1, "max": 1, "description": "The queue's name." } + ] + }, + { + "type": "cloudflare", + "subType": "ratelimit", + "extendsBase": true, + "description": "A Workers rate limiting binding: at most @limit calls per key in @period seconds.", + "whenToUse": "Each rate limiter a Worker checks.", + "children": [ + { "type": "attr", "subType": "string", "name": "namespaceId", "min": 1, "max": 1, "description": "The limiter's namespace id, unique in the account (`1001`)." }, + { "type": "attr", "subType": "int", "name": "limit", "min": 1, "max": 1, "description": "The calls allowed per key in one period." }, + { "type": "attr", "subType": "int", "name": "period", "min": 1, "max": 1, "description": "The period in seconds: 10 or 60, the only two Cloudflare accepts." } + ] + } + ] +} diff --git a/packs/cloudflare/pack.json b/packs/cloudflare/pack.json new file mode 100644 index 000000000..baee9ab7b --- /dev/null +++ b/packs/cloudflare/pack.json @@ -0,0 +1,10 @@ +{ + "id": "metaobjects-cloudflare", + "version": "0.1.0", + "stability": "preview", + "description": "Cloudflare as a deployment platform: deployment.worker (with static assets) and deployment.pages, the Worker's D1, KV, R2, queue and rate limiting bindings, and generators for wrangler.jsonc, a token-scoped wrangler wrapper, the deploy, secret sync and doctor scripts, and the facts no file holds.", + "requires": { "metamodel": ">=1.3 <2", "packs": { "metaobjects-delivery": ">=0.1.0 <0.2.0", "metaobjects-config": ">=0.1.0 <0.2.0" } }, + "ports": { + "typescript": { "package": "@metaobjectsdev/pack-cloudflare", "core": ">=1.3.0 <2.0.0", "publish": false } + } +} diff --git a/packs/cloudflare/typescript/package.json b/packs/cloudflare/typescript/package.json new file mode 100644 index 000000000..8e502e9e0 --- /dev/null +++ b/packs/cloudflare/typescript/package.json @@ -0,0 +1,31 @@ +{ + "name": "@metaobjectsdev/pack-cloudflare", + "version": "0.1.0", + "description": "The cloudflare pack: deployment.worker, deployment.pages and the Worker's bindings, and their generators (wrangler.jsonc, a token-scoped wrangler wrapper, deploy, secret sync and doctor scripts, the unexpressed facts). ADR-0069 independent pack, preview.", + "private": true, + "type": "module", + "exports": { + ".": { + "bun": "./src/index.ts", + "default": "./src/index.ts" + } + }, + "scripts": { + "typecheck": "tsc --noEmit -p ." + }, + "dependencies": { + "@metaobjectsdev/pack-config": "workspace:*", + "@metaobjectsdev/pack-delivery": "workspace:*", + "@metaobjectsdev/pack-systems": "workspace:*" + }, + "peerDependencies": { + "@metaobjectsdev/codegen-ts": ">=1.3.0 <2.0.0", + "@metaobjectsdev/metadata": ">=1.3.0 <2.0.0" + }, + "devDependencies": { + "@metaobjectsdev/codegen-ts": "workspace:*", + "@metaobjectsdev/metadata": "workspace:*", + "ajv": "^8.20.0" + }, + "license": "Apache-2.0" +} diff --git a/packs/cloudflare/typescript/src/constants.ts b/packs/cloudflare/typescript/src/constants.ts new file mode 100644 index 000000000..d9638e301 --- /dev/null +++ b/packs/cloudflare/typescript/src/constants.ts @@ -0,0 +1,69 @@ +// The cloudflare pack's vocabulary names and the Cloudflare spellings it writes, one constant +// each (metamodel/cloudflare.json is the vocabulary's definition). + +export const CLOUDFLARE_PROVIDER_ID = "metaobjects-cloudflare"; + +export const DEPLOYMENT_SUBTYPE_WORKER = "worker"; +export const DEPLOYMENT_SUBTYPE_PAGES = "pages"; + +/** The two environments a Pages project has, each with its own variables: what `pages secret put|list --env` takes. */ +export const PAGES_ENV_PRODUCTION = "production"; +export const PAGES_ENV_PREVIEW = "preview"; +export type PagesEnvironment = typeof PAGES_ENV_PRODUCTION | typeof PAGES_ENV_PREVIEW; + +export const WORKER_ATTR_SCRIPT = "script"; +export const WORKER_ATTR_MAIN = "main"; +export const WORKER_ATTR_COMPATIBILITY_DATE = "compatibilityDate"; +export const WORKER_ATTR_COMPATIBILITY_FLAGS = "compatibilityFlags"; +export const WORKER_ATTR_WORKERS_DEV = "workersDev"; +export const WORKER_ATTR_ASSETS_BINDING = "assetsBinding"; +export const WORKER_ATTR_NOT_FOUND = "notFound"; +export const WORKER_ATTR_WORKER_FIRST = "workerFirst"; +export const WORKER_ATTR_WORKER_FIRST_PATHS = "workerFirstPaths"; +export const WORKER_ATTR_JOBS = "jobs"; +export const WORKER_ATTR_EXTRA = "extra"; +export const PAGES_ATTR_PROJECT = "project"; +export const ATTR_TOKEN_SECRET = "tokenSecret"; +export const ATTR_TOKEN_VAULT = "tokenVault"; + +/** The binding children of a deployment.worker. */ +export const TYPE_CLOUDFLARE = "cloudflare"; +export const BINDING_D1 = "d1"; +export const BINDING_KV = "kv"; +export const BINDING_R2 = "r2"; +export const BINDING_QUEUE = "queue"; +export const BINDING_RATELIMIT = "ratelimit"; +export const D1_ATTR_DATABASE_NAME = "databaseName"; +export const D1_ATTR_DATABASE_ID = "databaseId"; +export const D1_ATTR_MIGRATIONS_DIR = "migrationsDir"; +export const KV_ATTR_NAMESPACE_ID = "namespaceId"; +export const R2_ATTR_BUCKET_NAME = "bucketName"; +export const QUEUE_ATTR_QUEUE = "queue"; +export const RATELIMIT_ATTR_NAMESPACE_ID = "namespaceId"; +export const RATELIMIT_ATTR_LIMIT = "limit"; +export const RATELIMIT_ATTR_PERIOD = "period"; +/** The periods the Workers rate limiting binding accepts, in seconds. */ +export const RATELIMIT_PERIODS: readonly number[] = [10, 60]; + +/** The vault entry, beside the deploy token, that holds the Cloudflare account id. */ +export const ACCOUNT_ID_SECRET = "CLOUDFLARE_ACCOUNT_ID"; +/** What Wrangler reads the token from; the scripts set it from the deployment's @tokenSecret. */ +export const API_TOKEN_VARIABLE = "CLOUDFLARE_API_TOKEN"; +/** The global-key variables Wrangler would prefer over a token: the scripts unset them. */ +export const GLOBAL_KEY_VARIABLES: readonly string[] = ["CLOUDFLARE_EMAIL", "CLOUDFLARE_API_KEY"]; + +/** What the runner clears before it sets the vault's token: the global key, and any token the shell already holds. */ +export const CLEARED_VARIABLES: readonly string[] = [...GLOBAL_KEY_VARIABLES, API_TOKEN_VARIABLE]; + +/** The `wrangler` npm package version the generated file and scripts were written against, and that the scripts pin. */ +export const WRANGLER_VERSION = "4.168.0"; +/** Where the generated file points editors for Wrangler's JSON schema (a project with wrangler installed). */ +export const WRANGLER_SCHEMA_REF = "node_modules/wrangler/config-schema.json"; + +/** Default output paths, relative to the generator's target (the repository root). */ +export const PATH_WRANGLER = "wrangler.jsonc"; +export const PATH_WRANGLER_RUNNER = "deploy/cloudflare/wrangler.sh"; +export const PATH_DEPLOY = "deploy/cloudflare/deploy.sh"; +export const PATH_SYNC_SECRETS = "deploy/cloudflare/sync-secrets.sh"; +export const PATH_DOCTOR = "deploy/cloudflare/doctor.sh"; +export const PATH_UNEXPRESSED = "deploy/cloudflare/unexpressed.md"; diff --git a/packs/cloudflare/typescript/src/files.ts b/packs/cloudflare/typescript/src/files.ts new file mode 100644 index 000000000..5ece6f6bc --- /dev/null +++ b/packs/cloudflare/typescript/src/files.ts @@ -0,0 +1,388 @@ +/** + * The files beside `wrangler.jsonc`: the token wrapper every Wrangler call goes through, the + * scripts that deploy, copy secrets and check, and the facts the configuration cannot hold. + * + * Every Wrangler call runs through `wrangler.sh`, which reads the deployment's narrow API token + * from the vault with `keys-axi run`, unsets the global-key variables (which Wrangler would + * otherwise prefer) and any token the shell already holds, maps the vault's token to + * CLOUDFLARE_API_TOKEN and runs a pinned wrangler. A secret's + * value only ever passes from `keys-axi run`'s environment through a pipe into + * `wrangler secret put`: no script prints one or puts one on a command line. + */ +import { posix } from "node:path"; +import { + ACCOUNT_ID_SECRET, + API_TOKEN_VARIABLE, + CLEARED_VARIABLES, + DEPLOYMENT_SUBTYPE_PAGES, + GLOBAL_KEY_VARIABLES, + WRANGLER_VERSION, +} from "./constants.js"; +import type { CloudflareApp, CloudflareDeployment, UnexpressedFact } from "./model.js"; + +/** Where each generated file lives, relative to the repository root. */ +export interface CloudflarePaths { + readonly config: string; + readonly runner: string; + readonly deploy: string; + readonly syncSecrets: string; + readonly doctor: string; + readonly unexpressed: string; +} + +/** A shell word: bare when it is safe, else single-quoted. */ +export function sh(s: string): string { + return /^[A-Za-z0-9_./:@=,+-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`; +} + +function md(s: string): string { + return `\`${s}\``; +} + +/** `cd` from the script's directory to the repository root. */ +function cdRoot(scriptPath: string): string { + const depth = posix.normalize(scriptPath).split("/").length - 1; + return depth === 0 ? 'cd "$(dirname "$0")"' : `cd "$(dirname "$0")/${Array(depth).fill("..").join("/")}"`; +} + +function shellHead(header: string, purpose: readonly string[], usage: string): string[] { + return ["#!/usr/bin/env bash", header, ...purpose.map((l) => (l === "" ? "#" : `# ${l}`)), "#", `# ${usage}`]; +} + +function environments(app: CloudflareApp): string[] { + return app.deployments.map((d) => d.environment); +} + +function caseBlock(app: CloudflareApp, body: (d: CloudflareDeployment) => string[], usage: string): string[] { + const lines = ['case "$ENVIRONMENT" in']; + for (const d of app.deployments) lines.push(` ${sh(d.environment)})`, ...body(d).map((l) => ` ${l}`), " ;;"); + lines.push(` *) echo ${sh(`usage: ${usage} (environments: ${environments(app).join(", ")})`)} >&2; exit 2 ;;`, "esac"); + return lines; +} + +/** The arguments that point a Worker command at this environment's block of the configuration. */ +function workerTarget(app: CloudflareApp, d: CloudflareDeployment, paths: CloudflarePaths): string { + return [`--config ${sh(paths.config)}`, ...(d.environment === app.topLevel ? [] : [`--env ${sh(d.environment)}`])].join(" "); +} + +// ── deploy/cloudflare/wrangler.sh ──────────────────────────────────────────── + +export function renderRunner(app: CloudflareApp, header: string, paths: CloudflarePaths): string { + const usage = `bash ${paths.runner} ...`; + const lines = [ + ...shellHead( + header, + [ + `Runs wrangler ${WRANGLER_VERSION} (WRANGLER_VERSION overrides) for ${app.appKey}, as the narrow`, + "Cloudflare API token of one environment's deployment. The token and CLOUDFLARE_ACCOUNT_ID are read", + `from the vault with keys-axi. The global-key variables (${GLOBAL_KEY_VARIABLES.join(", ")}) are unset`, + `so Wrangler cannot fall back to them, and so is any ${API_TOKEN_VARIABLE} the shell holds; the vault's token then becomes ${API_TOKEN_VARIABLE}.`, + "", + "Needs: keys-axi (KEYS_AXI overrides where it is) and npx.", + ], + usage, + ), + "set -euo pipefail", + cdRoot(paths.runner), + "", + 'ENVIRONMENT="${1:-}"', + '[ "$#" -gt 0 ] && shift', + `WRANGLER_VERSION="\${WRANGLER_VERSION:-${WRANGLER_VERSION}}"`, + 'KEYS_AXI="${KEYS_AXI:-$(command -v keys-axi || echo "$HOME/.local/bin/keys-axi")}"', + "", + ...caseBlock( + app, + (d) => [`VAULT_PROJECT=${sh(d.token.place.scope.project)} VAULT_ENV=${sh(d.token.place.scope.env)} TOKEN=${sh(d.token.secret)}`], + usage, + ), + "", + "# shellcheck disable=SC2016 # the inner shell expands them: the token never enters this one", + `exec env ${CLEARED_VARIABLES.map((v) => `-u ${v}`).join(" ")} \\`, + ` "$KEYS_AXI" run --project "$VAULT_PROJECT" --env "$VAULT_ENV" --only "$TOKEN" ${ACCOUNT_ID_SECRET} -- \\`, + " bash -c '", + " set -euo pipefail", + ' [ -n "${!1:-}" ] || { echo "wrangler.sh: the deploy token $1 is empty or is not in the vault scope" >&2; exit 1; }', + ` export ${API_TOKEN_VARIABLE}="\${!1}"`, + ` [ "$1" = ${API_TOKEN_VARIABLE} ] || unset "$1"`, + ` : "\${${ACCOUNT_ID_SECRET}:?${ACCOUNT_ID_SECRET} is not in the vault scope}"`, + ' version="$2"', + " shift 2", + ' exec npx --yes "wrangler@$version" "$@"', + ` ' wrangler "$TOKEN" "$WRANGLER_VERSION" "$@"`, + ]; + return `${lines.join("\n")}\n`; +} + +// ── deploy/cloudflare/sync-secrets.sh ──────────────────────────────────────── + +export function renderSyncSecrets(app: CloudflareApp, header: string, paths: CloudflarePaths): string { + const usage = `bash ${paths.syncSecrets} [--dry-run]`; + const pages = app.kind === DEPLOYMENT_SUBTYPE_PAGES; + const put = pages ? 'pages secret put "$1" --project-name "$3" --env "$4"' : 'secret put "$1" $3'; + const lines = [ + ...shellHead( + header, + [ + ...(pages + ? [ + `Copies every secret setting ${app.appKey} reads from the vault to the Pages project's environment,`, + "for one environment: production when its branch is the project's production branch, else preview.", + ] + : [`Copies every secret setting ${app.appKey} reads from the vault to Cloudflare, for one environment.`]), + `A value goes from keys-axi's environment through a pipe into \`wrangler ${pages ? "pages secret put" : "secret put"}\`:`, + "it is never printed and never on a command line.", + "", + `Needs: keys-axi (an identity that may read the vault scope) and what ${paths.runner} needs.`, + ], + usage, + ), + "set -euo pipefail", + cdRoot(paths.syncSecrets), + "", + 'ENVIRONMENT="${1:-}"', + "DRY_RUN=0", + 'for arg in "${@:2}"; do', + ' case "$arg" in', + " --dry-run) DRY_RUN=1 ;;", + ` *) echo ${sh(`usage: ${usage}`)} >&2; exit 2 ;;`, + " esac", + "done", + 'KEYS_AXI="${KEYS_AXI:-$(command -v keys-axi || echo "$HOME/.local/bin/keys-axi")}"', + "", + `# copy <${pages ? "Pages project> `, + "copy() {", + pages + ? ' if [ "$DRY_RUN" = 1 ]; then echo "would copy $3 from $1/$2 to Pages project $4, $5 environment ($ENVIRONMENT)"; return; fi' + : ' if [ "$DRY_RUN" = 1 ]; then echo "would copy $3 from $1/$2 to Cloudflare ($ENVIRONMENT)"; return; fi', + " # shellcheck disable=SC2016 # the inner shell expands it: the value never enters this one", + ' "$KEYS_AXI" run --project "$1" --env "$2" --only "$3" -- bash -c \'', + ' [ -n "${!1+set}" ] || { echo "sync-secrets: $1 is not in the vault scope" >&2; exit 1; }', + ' value="${!1}"', + ' unset "$1"', + ` printf %s "$value" | bash ${sh(paths.runner)} "$2" ${put} >/dev/null`, + ` ' sync-secret "$3" "$ENVIRONMENT" "$4"${pages ? ' "$5"' : ""}`, + pages + ? ' echo "copied $3 to Pages project $4, $5 environment ($ENVIRONMENT)"' + : ' echo "copied $3 to Cloudflare ($ENVIRONMENT)"', + "}", + "", + ...caseBlock( + app, + (d) => { + if (d.secrets.length === 0 || d.vault === undefined) return [`echo ${sh(`no secret settings to copy in ${d.environment}`)}`]; + const target = d.kind === DEPLOYMENT_SUBTYPE_PAGES ? `${sh(d.project)} ${sh(d.pagesEnvironment!)}` : sh(workerTarget(app, d, paths)); + return d.secrets.map((s) => `copy ${sh(d.vault!.scope.project)} ${sh(d.vault!.scope.env)} ${s} ${target}`); + }, + usage, + ), + ]; + return `${lines.join("\n")}\n`; +} + +// ── deploy/cloudflare/deploy.sh ────────────────────────────────────────────── + +export function renderDeploy(app: CloudflareApp, header: string, paths: CloudflarePaths): string { + const pages = app.kind === DEPLOYMENT_SUBTYPE_PAGES; + const build = app.deployments[0]?.build; + const builds = build?.command !== undefined; + const usage = `bash ${paths.deploy} ${builds ? " [--no-build]" : ""} [--no-secrets]`; + const anyBuildVar = app.deployments.some((d) => d.buildVars.length > 0); + const lines = [ + ...shellHead( + header, + [ + `Deploys ${app.appKey} to one environment, from the model:`, + ...[ + ...(build?.command === undefined ? [] : [`builds it (\`${build.command}\`, skipped with --no-build),`]), + `copies its secrets from the vault (${paths.syncSecrets}, skipped with --no-secrets),`, + pages + ? "uploads the build to the environment's Pages project and branch, recording the commit." + : `runs \`wrangler deploy\` with the environment's block of ${paths.config}.`, + ].map((step, i) => ` ${i + 1}. ${step}`), + ...(anyBuildVar + ? builds + ? ["Build-time settings are read by the build from this machine's environment; the values the model gives", "are exported first, and a value already in the environment wins."] + : [ + `Build-time settings are read from this machine's environment by whatever builds ${app.name}; deploy.sh runs no`, + "build (the app declares no build command), and exports the values the model gives first; a value already", + "in the environment wins.", + ] + : []), + "", + `Needs: what ${paths.runner} needs${pages ? ", and git" : ""}.`, + ], + usage, + ), + "set -euo pipefail", + cdRoot(paths.deploy), + "", + 'ENVIRONMENT="${1:-}"', + builds ? "BUILD=1; SECRETS=1" : "SECRETS=1", + 'for arg in "${@:2}"; do', + ' case "$arg" in', + ...(builds ? [" --no-build) BUILD=0 ;;"] : []), + " --no-secrets) SECRETS=0 ;;", + ` *) echo ${sh(`usage: ${usage}`)} >&2; exit 2 ;;`, + " esac", + "done", + ...(anyBuildVar + ? caseBlock(app, (d) => (d.buildVars.length === 0 ? [":"] : d.buildVars.flatMap((v) => [`# ${v.from}`, `[ -n "\${${v.name}:-}" ] || export ${v.name}=${sh(v.value)}`])), usage) + : [`case "$ENVIRONMENT" in ${environments(app).map(sh).join("|")}) ;; *) echo ${sh(`usage: ${usage} (environments: ${environments(app).join(", ")})`)} >&2; exit 2 ;; esac`]), + "", + ...(build?.command === undefined + ? [] + : ['if [ "$BUILD" = 1 ]; then', ` # ${build.from} @command`, ` ${build.command}`, "fi"]), + `if [ "$SECRETS" = 1 ]; then bash ${sh(paths.syncSecrets)} "$ENVIRONMENT"; fi`, + "", + ...caseBlock( + app, + (d) => + d.kind === DEPLOYMENT_SUBTYPE_PAGES + ? [ + `bash ${sh(paths.runner)} "$ENVIRONMENT" pages deploy ${sh(d.directory)} --project-name=${sh(d.project)}${d.branch === undefined ? "" : ` --branch=${sh(d.branch)}`} --commit-hash="$(git rev-parse HEAD)"`, + ] + : [`bash ${sh(paths.runner)} "$ENVIRONMENT" deploy ${workerTarget(app, d, paths)}`], + usage, + ), + ]; + return `${lines.join("\n")}\n`; +} + +// ── deploy/cloudflare/doctor.sh ────────────────────────────────────────────── + +export function renderDoctor(app: CloudflareApp, header: string, paths: CloudflarePaths): string { + const usage = `bash ${paths.doctor} `; + const pages = app.kind === DEPLOYMENT_SUBTYPE_PAGES; + const anyDomain = app.deployments.some((d) => d.domains.length > 0); + const anySecret = app.deployments.some((d) => d.secrets.length > 0 && d.vault !== undefined); + const lines = [ + ...shellHead( + header, + [ + `Checks ${app.appKey} on Cloudflare against the model, for one environment, by name only:`, + "the deploy token and account id are in the vault; every secret the model declares is in the vault", + pages ? "and on the Pages project's environment its branch serves (production or preview); each domain answers." : `and on the Worker; ${paths.config} builds (\`wrangler deploy --dry-run\`); each domain answers.`, + "Exits 1 when a check fails. It prints names, never a value.", + "", + `Needs: keys-axi, jq, curl, and what ${paths.runner} needs.`, + ], + usage, + ), + "set -uo pipefail", + `${cdRoot(paths.doctor)} || exit 2`, + "", + 'ENVIRONMENT="${1:-}"', + "FAIL=0", + 'ok() { echo "ok $*"; }', + 'bad() { echo "FAIL $*"; FAIL=1; }', + 'KEYS_AXI="${KEYS_AXI:-$(command -v keys-axi || echo "$HOME/.local/bin/keys-axi")}"', + '[ -x "$KEYS_AXI" ] || { echo "doctor: keys-axi is not installed" >&2; exit 2; }', + "for tool in jq curl npx; do", + ' command -v "$tool" >/dev/null || { echo "doctor: $tool is not installed" >&2; exit 2; }', + "done", + "", + "# in_vault ...", + "in_vault() {", + " local names", + ` names=$("$KEYS_AXI" ls --project "$1" --env "$2" --json | jq -r '.secrets[].name') || { bad "cannot list vault scope $1/$2"; return; }`, + ' local where="$1/$2"; shift 2', + ' for n in "$@"; do', + ' if grep -Fxq -e "$n" <<<"$names"; then ok "$n is in the vault ($where)"; else bad "$n is not in the vault ($where)"; fi', + " done", + "}", + "", + ...(anySecret + ? pages + ? [ + "# on_cloudflare ...", + "on_cloudflare() {", + " local names", + ` names=$(bash ${sh(paths.runner)} "$ENVIRONMENT" pages secret list --project-name "$1" --env "$2" 2>/dev/null | sed -n 's/^ *- \\([A-Za-z0-9_]*\\):.*/\\1/p') || { bad "cannot list the secrets of Pages project $1, $2 environment"; return; }`, + ' local where="Pages project $1, $2 environment"; shift 2', + ' for n in "$@"; do', + ` if grep -Fxq -e "$n" <<<"$names"; then ok "$n is set on $where"; else bad "$n is declared and not set on $where (run ${paths.syncSecrets})"; fi`, + " done", + "}", + "", + ] + : [ + "# on_cloudflare '' ...", + "on_cloudflare() {", + " local names", + " # shellcheck disable=SC2086 # the target arguments are words", + ` names=$(bash ${sh(paths.runner)} "$ENVIRONMENT" secret list $1 --format json | jq -r '.[].name') || { bad "cannot list the Worker's secrets"; return; }`, + " shift", + ' for n in "$@"; do', + ` if grep -Fxq -e "$n" <<<"$names"; then ok "$n is set on the Worker"; else bad "$n is declared and not set on the Worker (run ${paths.syncSecrets})"; fi`, + " done", + "}", + "", + ] + : []), + ...(pages + ? [] + : [ + "# builds '': the configuration and the Worker bundle build", + "builds() {", + " local out", + ' out=$(mktemp -d)', + " # shellcheck disable=SC2086 # the target arguments are words", + ` if bash ${sh(paths.runner)} "$ENVIRONMENT" deploy --dry-run --outdir "$out" $1 >/dev/null 2>&1; then ok "${paths.config} builds ($ENVIRONMENT)"; else bad "${paths.config} does not build ($ENVIRONMENT): run wrangler deploy --dry-run to see why"; fi`, + ' rm -rf "$out"', + "}", + "", + ]), + ...(anyDomain + ? [ + "# answers ", + "answers() {", + ' if curl -fsS -o /dev/null --max-time 10 "$1"; then ok "$1 answers"; else bad "$1 does not answer 2xx"; fi', + "}", + "", + ] + : []), + ...caseBlock( + app, + (d) => { + const body = [`in_vault ${sh(d.token.place.scope.project)} ${sh(d.token.place.scope.env)} ${sh(d.token.secret)} ${ACCOUNT_ID_SECRET}`]; + if (d.secrets.length > 0 && d.vault !== undefined) { + body.push(`in_vault ${sh(d.vault.scope.project)} ${sh(d.vault.scope.env)} ${d.secrets.join(" ")}`); + body.push(`on_cloudflare ${d.kind === DEPLOYMENT_SUBTYPE_PAGES ? `${sh(d.project)} ${sh(d.pagesEnvironment!)}` : sh(workerTarget(app, d, paths))} ${d.secrets.join(" ")}`); + } + if (d.kind !== DEPLOYMENT_SUBTYPE_PAGES) body.push(`builds ${sh(workerTarget(app, d, paths))}`); + for (const domain of d.domains) body.push(`answers ${sh(`https://${domain}/`)}`); + return body; + }, + usage, + ), + "", + 'exit "$FAIL"', + ]; + return `${lines.join("\n")}\n`; +} + +// ── deploy/cloudflare/unexpressed.md ───────────────────────────────────────── + +export function renderUnexpressed(app: CloudflareApp, header: string, paths: CloudflarePaths): string { + const [what, verb] = app.kind === DEPLOYMENT_SUBTYPE_PAGES ? ["the deploy scripts", "do not hold"] : [md(paths.config), "does not hold"]; + const lines = [ + header, + "", + `# What ${what} ${verb}: ${app.appKey}`, + "", + "Facts the model declares that Cloudflare's configuration cannot carry, or that it leaves to", + "something else, each with how it is carried instead. Generated from the model: change the", + "model, not this file.", + ]; + for (const d of app.deployments) { + const facts: readonly UnexpressedFact[] = d.unexpressed; + lines.push("", `## ${d.environment}`, "", `From deployment.${d.kind} ${md(d.key)}.`, ""); + if (facts.length === 0) { + lines.push("Nothing: the generated files hold every fact the model declares for this deployment."); + continue; + } + lines.push("| Fact | How it is carried |", "|---|---|"); + for (const f of facts) lines.push(`| ${f.fact} | ${f.how} |`); + } + return `${lines.join("\n")}\n`; +} diff --git a/packs/cloudflare/typescript/src/generators.ts b/packs/cloudflare/typescript/src/generators.ts new file mode 100644 index 000000000..5ca3317cd --- /dev/null +++ b/packs/cloudflare/typescript/src/generators.ts @@ -0,0 +1,141 @@ +/** + * The cloudflare pack's generators. Each writes one file for the model's Cloudflare app and + * stops: none talks to Cloudflare or to a vault, and no secret value reaches their output (the + * model holds none). + * + * - `wranglerConfigFile()` `wrangler.jsonc`, the Worker's configuration (Workers only). + * - `cloudflareRunnerScript()` `deploy/cloudflare/wrangler.sh`, wrangler as the narrow token. + * - `cloudflareDeployScript()` `deploy/cloudflare/deploy.sh`, build, sync secrets, deploy. + * - `cloudflareSyncSecretsScript()` `deploy/cloudflare/sync-secrets.sh`, vault → Cloudflare. + * - `cloudflareDoctorScript()` `deploy/cloudflare/doctor.sh`, the model against the vault and Cloudflare. + * - `cloudflareUnexpressedFile()` `deploy/cloudflare/unexpressed.md`, the facts no file holds. + * - `cloudflareFiles()` all six. + * + * Paths are relative to the generator's target; these files belong at the repository root, so + * wire them to a target whose `outDir` is `"."` (README, "Wiring"). The scripts name each + * other and the configuration by path, so every generator takes the same `paths`. A model that + * deploys nothing to Cloudflare gets no files. + */ +import { GENERATED_EDIT_NOTE, type EmittedFile, type Generator, type GenContext } from "@metaobjectsdev/codegen-ts"; +import { + DEPLOYMENT_SUBTYPE_WORKER, + PATH_DEPLOY, + PATH_DOCTOR, + PATH_SYNC_SECRETS, + PATH_UNEXPRESSED, + PATH_WRANGLER, + PATH_WRANGLER_RUNNER, +} from "./constants.js"; +import { renderDeploy, renderDoctor, renderRunner, renderSyncSecrets, renderUnexpressed, type CloudflarePaths } from "./files.js"; +import { CloudflareModelError, readCloudflare, type CloudflareApp, type ReadCloudflareOptions } from "./model.js"; +import { renderWrangler } from "./wrangler.js"; + +const PACKAGE = "@metaobjectsdev/pack-cloudflare"; + +export interface CloudflareGeneratorOptions extends ReadCloudflareOptions { + /** The codegen target the files are written under (its `outDir` should be the repository root). */ + readonly target?: string; + /** Where each file goes, relative to the target. Every generator must be given the same. */ + readonly paths?: Partial; +} + +function header(generator: string, comment: string): string { + return `${comment} @generated by ${PACKAGE} (${generator}) — ${GENERATED_EDIT_NOTE}`; +} + +function htmlHeader(generator: string): string { + return ``; +} + +export function resolvePaths(opts: CloudflareGeneratorOptions): CloudflarePaths { + const p = opts.paths ?? {}; + return { + config: p.config ?? PATH_WRANGLER, + runner: p.runner ?? PATH_WRANGLER_RUNNER, + deploy: p.deploy ?? PATH_DEPLOY, + syncSecrets: p.syncSecrets ?? PATH_SYNC_SECRETS, + doctor: p.doctor ?? PATH_DOCTOR, + unexpressed: p.unexpressed ?? PATH_UNEXPRESSED, + }; +} + +/** The model read once per run and per options, a refusal included (a run shares one `entities` array). */ +const cache = new WeakMap>(); + +function appFor(ctx: GenContext, { app, topLevel }: ReadCloudflareOptions): CloudflareApp | undefined { + const k = JSON.stringify([app ?? null, topLevel ?? null]); + const perRun = cache.get(ctx.entities) ?? new Map(); + cache.set(ctx.entities, perRun); + if (!perRun.has(k)) { + const read = { ...(app !== undefined ? { app } : {}), ...(topLevel !== undefined ? { topLevel } : {}) }; + try { + perRun.set(k, readCloudflare(ctx.loadedRoot, ctx.entities.filter(ctx.matches), (key) => ctx.select?.(key) ?? true, read)); + } catch (e) { + if (!(e instanceof CloudflareModelError)) throw e; + perRun.set(k, e); + } + } + const got = perRun.get(k); + if (got instanceof CloudflareModelError) throw got; + return got; +} + +function generator( + name: string, + opts: CloudflareGeneratorOptions, + path: (paths: CloudflarePaths) => string, + render: (app: CloudflareApp, paths: CloudflarePaths) => string | undefined, +): Generator { + return { + name, + ...(opts.target !== undefined ? { target: opts.target } : {}), + generate(ctx): EmittedFile[] { + const app = appFor(ctx, opts); + if (app === undefined) return []; + const paths = resolvePaths(opts); + const content = render(app, paths); + return content === undefined ? [] : [{ path: path(paths), content }]; + }, + }; +} + +/** `wrangler.jsonc`. A Pages site has none: `wrangler pages deploy` takes its facts as arguments. */ +export function wranglerConfigFile(opts: CloudflareGeneratorOptions = {}): Generator { + return generator("wrangler-config", opts, (p) => p.config, (app, p) => + app.kind === DEPLOYMENT_SUBTYPE_WORKER ? renderWrangler(app, header("wrangler-config", "//"), p.config) : undefined, + ); +} + +export function cloudflareRunnerScript(opts: CloudflareGeneratorOptions = {}): Generator { + return generator("cloudflare-wrangler", opts, (p) => p.runner, (app, p) => renderRunner(app, header("cloudflare-wrangler", "#"), p)); +} + +export function cloudflareDeployScript(opts: CloudflareGeneratorOptions = {}): Generator { + return generator("cloudflare-deploy", opts, (p) => p.deploy, (app, p) => renderDeploy(app, header("cloudflare-deploy", "#"), p)); +} + +export function cloudflareSyncSecretsScript(opts: CloudflareGeneratorOptions = {}): Generator { + return generator("cloudflare-sync-secrets", opts, (p) => p.syncSecrets, (app, p) => renderSyncSecrets(app, header("cloudflare-sync-secrets", "#"), p)); +} + +export function cloudflareDoctorScript(opts: CloudflareGeneratorOptions = {}): Generator { + return generator("cloudflare-doctor", opts, (p) => p.doctor, (app, p) => renderDoctor(app, header("cloudflare-doctor", "#"), p)); +} + +export function cloudflareUnexpressedFile(opts: CloudflareGeneratorOptions = {}): Generator { + return generator("cloudflare-unexpressed", opts, (p) => p.unexpressed, (app, p) => + renderUnexpressed(app, htmlHeader("cloudflare-unexpressed"), p), + ); +} + +/** All six generators with the same options. */ +export function cloudflareFiles(opts: CloudflareGeneratorOptions = {}): Generator[] { + return [ + wranglerConfigFile(opts), + cloudflareRunnerScript(opts), + cloudflareDeployScript(opts), + cloudflareSyncSecretsScript(opts), + cloudflareDoctorScript(opts), + cloudflareUnexpressedFile(opts), + ]; +} diff --git a/packs/cloudflare/typescript/src/index.ts b/packs/cloudflare/typescript/src/index.ts new file mode 100644 index 000000000..967344b76 --- /dev/null +++ b/packs/cloudflare/typescript/src/index.ts @@ -0,0 +1,61 @@ +/** + * @metaobjectsdev/pack-cloudflare — the cloudflare pack (ADR-0069): deployment.worker, + * deployment.pages and the Worker's cloudflare.* bindings, and the generators that turn them + * into `wrangler.jsonc` and the deploy scripts beside it. + * + * import { provider as cloudflareProvider, cloudflareFiles } from "@metaobjectsdev/pack-cloudflare"; + * export default defineConfig({ providers: [..., cloudflareProvider], generators: [...cloudflareFiles()] }); + */ +import { applyProviderDefinition, type MetaDataTypeProvider, type ProviderDefinition } from "@metaobjectsdev/metadata"; +import { DELIVERY_PROVIDER_ID, TYPE_DEPLOYMENT, validateDeployment } from "@metaobjectsdev/pack-delivery"; +import { packTypeMaps } from "@metaobjectsdev/pack-systems"; +import definition from "../../metamodel/cloudflare.json" with { type: "json" }; +import { CLOUDFLARE_PROVIDER_ID } from "./constants.js"; + +export * from "./constants.js"; +export { + CloudflareModelError, + GENERATED_WRANGLER_KEYS, + INHERITED_WRANGLER_KEYS, + bindingName, + isCloudflareDeployment, + readCloudflare, + workerName, + type CloudflareApp, + type CloudflareAssets, + type CloudflareBinding, + type CloudflareBuild, + type CloudflareCron, + type CloudflareDeployment, + type CloudflareVar, + type PagesDeployment, + type ReadCloudflareOptions, + type UnexpressedFact, + type VaultPlace, + type WorkerDeployment, +} from "./model.js"; +export { parseGeneratedJsonc, renderWrangler } from "./wrangler.js"; +export { renderDeploy, renderDoctor, renderRunner, renderSyncSecrets, renderUnexpressed, sh, type CloudflarePaths } from "./files.js"; +export { + cloudflareDeployScript, + cloudflareDoctorScript, + cloudflareFiles, + cloudflareRunnerScript, + cloudflareSyncSecretsScript, + cloudflareUnexpressedFile, + resolvePaths, + wranglerConfigFile, + type CloudflareGeneratorOptions, +} from "./generators.js"; + +export const CLOUDFLARE_DEFINITION = definition as ProviderDefinition; + +export const provider: MetaDataTypeProvider = { + id: CLOUDFLARE_PROVIDER_ID, + dependencies: ["metaobjects-core-types", DELIVERY_PROVIDER_ID], + description: "Cloudflare: deployment.worker, deployment.pages and the cloudflare.* bindings of a Worker.", + registerTypes(registry) { + const { factories, validators } = packTypeMaps(CLOUDFLARE_DEFINITION, { [TYPE_DEPLOYMENT]: validateDeployment }); + applyProviderDefinition(registry, CLOUDFLARE_DEFINITION, factories, validators); + }, +}; diff --git a/packs/cloudflare/typescript/src/model.ts b/packs/cloudflare/typescript/src/model.ts new file mode 100644 index 000000000..dc4bae45f --- /dev/null +++ b/packs/cloudflare/typescript/src/model.ts @@ -0,0 +1,857 @@ +/** + * What the model says about Cloudflare, read once for every generator in the pack. + * + * A deployment.worker or deployment.pages names its app and environment; the app holds the + * facts true everywhere (its build, the settings groups it reads, the resources it needs); + * the deployment adds what differs per environment. The facts every environment shares sit on + * an abstract deployment each environment's deployment `extends`, so they are read through + * the resolving accessors (ADR-0039) like a fact declared in place, and so is an estate + * overlay. Abstract deployments are bases, never deployed: they are skipped here. + * + * Problems a loader cannot see (a binding for a resource the app does not need, a resource + * with no binding in some environment, a required setting with no value) are collected and + * thrown together, each naming its node. + */ +import { toSnakeCase, type MetaData, type MetaObject, type MetaRoot } from "@metaobjectsdev/metadata"; +import { + ConfigModelError, + PHASE_BUILD, + VAULT_SUBTYPE_INFISICAL, + readSettings, + readVaults, + type Setting, + type SettingsGroup, + type Vault, + type VaultScope, +} from "@metaobjectsdev/pack-config"; +import { + BUILD_SUBTYPE_STATIC, + DEPLOYMENT_ATTR_APP, + DEPLOYMENT_ATTR_BRANCH, + DEPLOYMENT_ATTR_DOMAINS, + DEPLOYMENT_ATTR_ENVIRONMENT, + DEPLOYMENT_ATTR_REGION, + DEPLOYMENT_ATTR_REPLICAS, + DEPLOYMENT_ATTR_SECRETS, + TYPE_BUILD, + TYPE_DEPLOYMENT, + TYPE_ENVIRONMENT, + TYPE_VALUE, + VALUE_ATTR_LITERAL, + VALUE_ATTR_OUTPUT, + VALUE_ATTR_PATH, + VALUE_ATTR_PRODUCED_BY, + VALUE_ATTR_SETTING, + VALUE_SUBTYPE_LITERAL, + OUTPUT_HOST, + OUTPUT_PUBLIC_URL, + readBuild, + readProcesses, +} from "@metaobjectsdev/pack-delivery"; +import { + APP_ATTR_NEEDS, + APP_ATTR_SCHEDULE, + APP_ATTR_SETTINGS, + APP_SUBTYPE_JOB, + TYPE_APP, + TYPE_RESOURCE, + refList, + resolveSystemRef, +} from "@metaobjectsdev/pack-systems"; +import { + ATTR_TOKEN_SECRET, + ATTR_TOKEN_VAULT, + BINDING_D1, + BINDING_KV, + BINDING_QUEUE, + BINDING_R2, + BINDING_RATELIMIT, + D1_ATTR_DATABASE_ID, + D1_ATTR_DATABASE_NAME, + D1_ATTR_MIGRATIONS_DIR, + DEPLOYMENT_SUBTYPE_PAGES, + DEPLOYMENT_SUBTYPE_WORKER, + KV_ATTR_NAMESPACE_ID, + PAGES_ATTR_PROJECT, + PAGES_ENV_PRODUCTION, + PAGES_ENV_PREVIEW, + QUEUE_ATTR_QUEUE, + R2_ATTR_BUCKET_NAME, + RATELIMIT_ATTR_LIMIT, + RATELIMIT_ATTR_NAMESPACE_ID, + RATELIMIT_ATTR_PERIOD, + RATELIMIT_PERIODS, + TYPE_CLOUDFLARE, + WORKER_ATTR_ASSETS_BINDING, + WORKER_ATTR_COMPATIBILITY_DATE, + WORKER_ATTR_COMPATIBILITY_FLAGS, + WORKER_ATTR_EXTRA, + WORKER_ATTR_JOBS, + WORKER_ATTR_MAIN, + WORKER_ATTR_NOT_FOUND, + WORKER_ATTR_SCRIPT, + WORKER_ATTR_WORKERS_DEV, + WORKER_ATTR_WORKER_FIRST, + WORKER_ATTR_WORKER_FIRST_PATHS, + type PagesEnvironment, +} from "./constants.js"; +import { bindableKinds, bindingKindFor, describeResource, isExternal, resourceKindOf } from "./resources.js"; + +/** Thrown with every problem found, one per line, each naming its node. */ +export class CloudflareModelError extends Error { + constructor(readonly problems: readonly string[]) { + super(`cloudflare pack: ${problems.length} problem(s) in the model:\n${problems.map((p) => ` - ${p}`).join("\n")}`); + this.name = "CloudflareModelError"; + } +} + +/** A fact and the model node it comes from, for the comment beside it. */ +interface Traced { + readonly from: string; +} + +/** One entry of the Worker's `vars`. */ +export interface CloudflareVar extends Traced { + readonly name: string; + readonly value: string; +} + +export type CloudflareBinding = Traced & { readonly binding: string } & ( + | { readonly kind: typeof BINDING_D1; readonly databaseName: string; readonly databaseId?: string; readonly migrationsDir?: string } + | { readonly kind: typeof BINDING_KV; readonly namespaceId: string } + | { readonly kind: typeof BINDING_R2; readonly bucketName: string } + | { readonly kind: typeof BINDING_QUEUE; readonly queue: string } + | { readonly kind: typeof BINDING_RATELIMIT; readonly namespaceId: string; readonly limit: number; readonly period: number } + ); + +export interface CloudflareCron extends Traced { + readonly schedule: string; +} + +export interface CloudflareAssets { + readonly directory: string; + readonly binding?: string; + readonly notFound?: string; + /** true: every request; a list: those patterns. */ + readonly workerFirst?: true | readonly string[]; +} + +/** The app's build, as the deploy script runs it. */ +export interface CloudflareBuild { + readonly kind: string; + readonly command?: string; + readonly directory?: string; + readonly from: string; +} + +/** A fact the generated files do not carry, and how it is carried instead. */ +export interface UnexpressedFact { + readonly fact: string; + readonly how: string; +} + +/** Where a secret or the deploy token is read from. */ +export interface VaultPlace { + readonly key: string; + readonly scope: VaultScope; +} + +interface DeploymentCommon { + readonly key: string; + readonly environment: string; + readonly domains: readonly string[]; + readonly branch?: string; + readonly build?: CloudflareBuild; + /** The environment variables of the app's secret runtime settings, in model order. */ + readonly secrets: readonly string[]; + /** The app's non-secret build-time settings that have a value here: deploy.sh exports them before the build. */ + readonly buildVars: readonly CloudflareVar[]; + /** Where those secrets are read from at deploy. Absent when the app reads none. */ + readonly vault?: VaultPlace; + readonly token: { readonly secret: string; readonly place: VaultPlace }; + readonly unexpressed: readonly UnexpressedFact[]; +} + +export interface WorkerDeployment extends DeploymentCommon { + readonly kind: typeof DEPLOYMENT_SUBTYPE_WORKER; + /** The Worker's name as the model gives it (@script, else the app's name); the env block may suffix it. */ + readonly script: string; + readonly main?: string; + readonly compatibilityDate: string; + readonly compatibilityFlags: readonly string[]; + readonly workersDev?: boolean; + readonly assets?: CloudflareAssets; + readonly crons: readonly CloudflareCron[]; + readonly vars: readonly CloudflareVar[]; + readonly bindings: readonly CloudflareBinding[]; + readonly extra?: Readonly>; +} + +export interface PagesDeployment extends DeploymentCommon { + readonly kind: typeof DEPLOYMENT_SUBTYPE_PAGES; + readonly project: string; + readonly directory: string; + /** The Pages environment this deployment serves: production when its @branch is the project's production branch, else preview. Absent when the model does not say. */ + readonly pagesEnvironment?: PagesEnvironment; +} + +export type CloudflareDeployment = WorkerDeployment | PagesDeployment; + +/** One app's Cloudflare deployments: what one wrangler.jsonc and one set of scripts declare. */ +export interface CloudflareApp { + readonly name: string; + /** `app.service Shop.site`, for comments. */ + readonly appKey: string; + readonly kind: typeof DEPLOYMENT_SUBTYPE_WORKER | typeof DEPLOYMENT_SUBTYPE_PAGES; + /** The concrete deployments, the top-level one first, then the rest in model order. */ + readonly deployments: readonly CloudflareDeployment[]; + /** The environment written at the top level of wrangler.jsonc (`wrangler deploy` with no `--env`). */ + readonly topLevel: string; +} + +export interface ReadCloudflareOptions { + /** The app to read, as `System.app` or the app's name, when the model deploys more than one to Cloudflare. */ + readonly app?: string; + /** The environment written at the top level of wrangler.jsonc. Absent: the only one, else `production`. */ + readonly topLevel?: string; +} + +/** The environment a model with several picks for the top level when no option names one. */ +const DEFAULT_TOP_LEVEL = "production"; + +/** Keys the generator writes itself, which `@extra` may not set. */ +export const GENERATED_WRANGLER_KEYS: readonly string[] = [ + "$schema", "name", "main", "compatibility_date", "compatibility_flags", "workers_dev", "assets", "routes", "triggers", + "vars", "secrets", "d1_databases", "kv_namespaces", "r2_buckets", "queues", "ratelimits", "env", +]; + +/** + * The keys `@extra` may set that Wrangler fills into an env block which omits them, from the + * top level (Wrangler 4.168.0's `EnvironmentInheritable`, less those the generator writes): + * so each is set in every environment or none. + */ +export const INHERITED_WRANGLER_KEYS: readonly string[] = [ + "account_id", "find_additional_modules", "preserve_file_names", "base_dir", "preview_urls", "route", "tsconfig", "jsx_factory", "jsx_fragment", + "migrations", "exports", "limits", "rules", "build", "no_bundle", "minify", "keep_names", "first_party_worker", "logfwdr", "logpush", + "upload_source_maps", "placement", "observability", "access", "cache", "compliance_region", "python_modules", "previews", +]; + +function text(v: unknown): string | undefined { + return typeof v === "string" && v !== "" ? v : undefined; +} + +function int(v: unknown): number | undefined { + return typeof v === "number" && Number.isInteger(v) ? v : undefined; +} + +export function isCloudflareDeployment(node: MetaData): boolean { + return node.type === TYPE_DEPLOYMENT && (node.subType === DEPLOYMENT_SUBTYPE_WORKER || node.subType === DEPLOYMENT_SUBTYPE_PAGES); +} + +/** A node's binding name: its name in upper snake case (`rateLimit` is RATE_LIMIT). */ +export function bindingName(name: string): string { + return toSnakeCase(name).toUpperCase(); +} + +/** `app.service Shop.site`. */ +function appKeyOf(app: MetaData): string { + return `${app.type}.${app.subType} ${app.parent === undefined ? app.resolutionKey() : `${app.parent.resolutionKey()}.${app.name}`}`; +} + +/** The settings groups `names` names, reporting each that matches none or several. */ +function groupsNamed(names: readonly string[], groups: readonly SettingsGroup[], where: string, problems: string[]): SettingsGroup[] { + const out: SettingsGroup[] = []; + for (const n of names) { + const hits = groups.filter((g) => g.key === n || g.name === n); + if (hits.length === 1) out.push(hits[0]!); + else if (hits.length === 0) problems.push(`${where}: @${APP_ATTR_SETTINGS} names "${n}", which is no object.settings in the model`); + else problems.push(`${where}: @${APP_ATTR_SETTINGS} "${n}" matches ${hits.map((g) => g.key).join(" and ")}; name it by its package`); + } + return out; +} + +/** The setting `Group.field` names, among every group in the model. */ +function settingNamed(ref: string, groups: readonly SettingsGroup[]): Setting | undefined { + const dot = ref.lastIndexOf("."); + if (dot <= 0) return undefined; + const group = ref.slice(0, dot); + const field = ref.slice(dot + 1); + const hits = groups.filter((g) => g.key === group || g.name === group); + if (hits.length !== 1) return undefined; + return hits[0]!.settings.find((s) => s.setting === `${hits[0]!.key}.${field}`); +} + +/** The app's build as the delivery pack reads it, with the node it comes from. */ +function cloudflareBuild(app: MetaData): CloudflareBuild | undefined { + const b = readBuild(app); + // ADR-0039: resolving, the same build node readBuild read. + const node = app.children().find((c) => c.type === TYPE_BUILD); + if (b === undefined || node === undefined) return undefined; + const { kind, command, directory } = b; + return { kind, from: `build.${kind} ${node.name}`, ...(command !== undefined ? { command } : {}), ...(directory !== undefined ? { directory } : {}) }; +} + +interface Context { + readonly all: readonly MetaData[]; + readonly groups: readonly SettingsGroup[]; + readonly vaults: readonly Vault[]; +} + +/** The vault `ref` names and its scope for `env`, or a problem. */ +function vaultPlace(ref: string, env: string, attr: string, ctx: Context, where: string, problems: string[]): VaultPlace | undefined { + const v = ctx.vaults.find((x) => x.name === ref || x.key === ref); + // The scope named after the environment, else the vault's @defaultScope (one deploy-token scope serving every environment). + const scope = v?.scopes.find((s) => s.name === env) ?? v?.defaultScope; + if (v === undefined) problems.push(`${where}: @${attr} "${ref}" names no vault.* in the model`); + else if (v.product !== VAULT_SUBTYPE_INFISICAL) problems.push(`${where}: vault ${v.key} is vault.${v.product}; the scripts read vault.${VAULT_SUBTYPE_INFISICAL} through keys-axi`); + else if (scope === undefined) problems.push(`${where}: vault ${v.key} has no scope.env named "${env}" and no @defaultScope, so this environment has no place in it`); + else return { key: v.key, scope }; + return undefined; +} + +/** A vault scope as the model names it: its vault, its name and its place in the store. */ +function describeScope(place: VaultPlace): string { + return `vault ${place.key} scope ${place.scope.name} (${place.scope.project}/${place.scope.env})`; +} + +/** The deployment of `app` in `env` among the Cloudflare deployments, if any. */ +function deploymentOf(app: MetaData, env: MetaData, all: readonly MetaData[]): MetaData | undefined { + return all.find((d) => { + const a = refList(d, DEPLOYMENT_ATTR_APP)[0]; + const e = refList(d, DEPLOYMENT_ATTR_ENVIRONMENT)[0]; + return ( + a !== undefined && + e !== undefined && + resolveSystemRef(d, a, DEPLOYMENT_ATTR_APP, [TYPE_APP]) === app && + resolveSystemRef(d, e, DEPLOYMENT_ATTR_ENVIRONMENT, [TYPE_ENVIRONMENT]) === env + ); + }); +} + +/** + * A value.ref as the text Cloudflare is given. Cloudflare resolves no reference at deploy + * time, so only an address the model itself states can be written: another app's public + * host or URL, from its Cloudflare deployment's first @domains entry in the same environment. + */ +function referenceValue(value: MetaData, env: MetaData, ctx: Context, where: string, problems: string[]): string | undefined { + const producedBy = text(value.attr(VALUE_ATTR_PRODUCED_BY)) ?? ""; + const output = text(value.attr(VALUE_ATTR_OUTPUT)) ?? ""; + const target = resolveSystemRef(value, producedBy, VALUE_ATTR_PRODUCED_BY, [TYPE_RESOURCE, TYPE_APP]); + if (target === undefined) return undefined; // the delivery pack reports it at load + if (target.type === TYPE_APP && (output === OUTPUT_HOST || output === OUTPUT_PUBLIC_URL)) { + const d = deploymentOf(target, env, ctx.all); + const domain = d === undefined ? undefined : refList(d, DEPLOYMENT_ATTR_DOMAINS)[0]; + if (domain !== undefined) return output === OUTPUT_HOST ? domain : `https://${domain}${text(value.attr(VALUE_ATTR_PATH)) ?? ""}`; + problems.push(`${where}: app "${target.name}" has no Cloudflare deployment with @domains in environment ${env.name}, so its ${output} is not known`); + return undefined; + } + const only = "a value.ref can only take another Cloudflare-deployed app's host or publicUrl (from its @domains)"; + problems.push( + target.type === TYPE_APP + ? `${where}: Cloudflare resolves no reference at deploy time; ${only}, not an app's ${output}. Ask for its host or publicUrl, or give the setting a value.literal` + : `${where}: Cloudflare resolves no reference at deploy time; ${only}. Bind ${target.type}.${target.subType} "${target.name}" (a cloudflare.* child) or give the setting a value.literal or the vault (@secret)`, + ); + return undefined; +} + +/** ` (from siteBase)` when `child` is declared on a deployment `node` extends rather than on `node` itself. */ +function declaredIn(child: MetaData, node: MetaData): string { + return child.parent !== undefined && child.parent !== node ? ` (from ${child.parent.name})` : ""; +} + +/** The common part of a deployment, or undefined when its app or environment does not resolve. */ +function readCommon( + node: MetaData, + ctx: Context, + problems: string[], +): { app: MetaData; env: MetaData; where: string; settings: Setting[]; common: Omit & { token?: DeploymentCommon["token"] } } | undefined { + const where = `deployment.${node.subType} ${node.resolutionKey()}`; + const app = appOf(node); + const env = environmentOf(node); + if (app === undefined || env === undefined) return undefined; // the delivery pack reports it at load + + const settings = groupsNamed(refList(app, APP_ATTR_SETTINGS), ctx.groups, appKeyOf(app), problems).flatMap((g) => g.settings); + for (const s of settings) { + if (s.secret && s.phase === PHASE_BUILD) { + problems.push( + `${where}: ${s.setting} (${s.envName}) is @secret and @phase build; the scripts copy a secret to a Worker or to a Pages project, never to a build on this machine. Mark it @phase runtime if the Worker reads it; otherwise build by hand under keys-axi run and deploy with --no-build`, + ); + } + } + for (const v of node.children().filter((c) => c.type === TYPE_VALUE && c.subType !== VALUE_SUBTYPE_LITERAL)) { + const ref = text(v.attr(VALUE_ATTR_SETTING)) ?? ""; + if (settingNamed(ref, ctx.groups)?.phase === PHASE_BUILD) { + problems.push(`${where} value.ref ${v.name}: ${ref} is @phase build, and a build on the deploying machine has no reference to resolve; give it a value.literal or a @default`); + } + } + // Build-time settings with a value: a value.literal here (resolving, so the base's counts), else the @default. + const buildVars: CloudflareVar[] = []; + for (const s of settings.filter((x) => x.phase === PHASE_BUILD && !x.secret)) { + // ADR-0039: resolving, so a value the abstract base declares counts. + const v = node.children().find((c) => c.type === TYPE_VALUE && c.subType === VALUE_SUBTYPE_LITERAL && settingNamed(text(c.attr(VALUE_ATTR_SETTING)) ?? "", ctx.groups) === s); + // An empty literal is a value, as it is for a runtime var: it overrides the @default. + const raw = v?.attr(VALUE_ATTR_LITERAL); + const literal = typeof raw === "string" ? raw : undefined; + if (v !== undefined && literal !== undefined) buildVars.push({ name: s.envName, value: literal, from: `value.literal ${v.name}${declaredIn(v, node)}` }); + else if (s.default !== undefined) buildVars.push({ name: s.envName, value: s.default, from: `${s.setting} @default` }); + } + const secrets = settings.filter((s) => s.secret && s.phase !== PHASE_BUILD).map((s) => s.envName); + const secretsRef = text(node.attr(DEPLOYMENT_ATTR_SECRETS)); + let vault: VaultPlace | undefined; + if (secretsRef !== undefined) vault = vaultPlace(secretsRef, env.name, DEPLOYMENT_ATTR_SECRETS, ctx, where, problems); + else if (secrets.length > 0) problems.push(`${where}: ${app.name} reads ${secrets.length} secret setting(s) (${secrets.join(", ")}) and the deployment names no vault; set @${DEPLOYMENT_ATTR_SECRETS}`); + + const tokenSecret = text(node.attr(ATTR_TOKEN_SECRET)) ?? ""; + const tokenVaultRef = text(node.attr(ATTR_TOKEN_VAULT)); + let token: DeploymentCommon["token"] | undefined; + if (tokenVaultRef === undefined && secretsRef === undefined) { + problems.push(`${where}: the deploy token ${tokenSecret} has no vault: set @${ATTR_TOKEN_VAULT} (or @${DEPLOYMENT_ATTR_SECRETS})`); + } else { + const place = tokenVaultRef === undefined ? vault : vaultPlace(tokenVaultRef, env.name, ATTR_TOKEN_VAULT, ctx, where, problems); + if (place !== undefined) token = { secret: tokenSecret, place }; + } + + const build = cloudflareBuild(app); + const branch = text(node.attr(DEPLOYMENT_ATTR_BRANCH)); + return { + app, + env, + where, + settings, + common: { + key: node.resolutionKey(), + environment: env.name, + domains: refList(node, DEPLOYMENT_ATTR_DOMAINS), + ...(branch !== undefined ? { branch } : {}), + ...(build !== undefined ? { build } : {}), + secrets, + buildVars, + ...(vault !== undefined ? { vault } : {}), + ...(token !== undefined ? { token } : {}), + }, + }; +} + +/** Facts any Cloudflare deployment leaves to something else: processes, replicas, region, watch paths, build-time settings. `secretsOn` is where the doctor finds the secrets on Cloudflare. */ +function commonUnexpressed(node: MetaData, app: MetaData, settings: readonly Setting[], secrets: readonly string[], vault: VaultPlace | undefined, secretsOn: string): UnexpressedFact[] { + const out: UnexpressedFact[] = []; + for (const p of readProcesses(app)) { + // Each attribute the process sets: readProcesses names its fields after them. + const set = Object.keys(p).filter((k) => k !== "name"); + if (set.length > 0) { + out.push({ + fact: `runtime.process \`${p.name}\` (${set.map((a) => `@${a}`).join(", ")})`, + how: "Cloudflare runs a Worker per request, with no process to start, listen, health-check, drain or restart. Nothing to carry.", + }); + } + } + const replicas = int(node.attr(DEPLOYMENT_ATTR_REPLICAS)); + if (replicas !== undefined) out.push({ fact: `@replicas ${replicas}`, how: "Cloudflare runs a Worker in every location on demand; there is no replica count to set." }); + const region = text(node.attr(DEPLOYMENT_ATTR_REGION)); + if (region !== undefined) out.push({ fact: `@region \`${region}\``, how: "Cloudflare has no region for a Worker or a Pages site. Smart Placement, if wanted, goes in @extra as `placement`." }); + const b = readBuild(app); + const watch = b === undefined ? [] : [...b.watchInclude, ...b.watchExclude.map((g) => `!${g}`)]; + if (watch.length > 0) { + out.push({ fact: `Watch paths ${watch.map((g) => `\`${g}\``).join(", ")}`, how: "Deploys run from deploy/cloudflare/deploy.sh, not on a push, so nothing watches paths. Workers Builds and Pages Git integration keep their build watch paths in the dashboard." }); + } + const buildPhase = settings.filter((s) => s.phase === PHASE_BUILD).map((s) => s.envName); + if (buildPhase.length > 0) { + out.push({ + fact: `Build-time settings ${buildPhase.map((n) => `\`${n}\``).join(", ")}`, + how: + b?.command === undefined + ? `Read by whatever builds ${app.name}, from the environment it runs in: deploy/cloudflare/deploy.sh runs no build (${app.name} declares no build command) and exports each one the model gives a value (a value already in the environment wins) for what it runs next. They never reach Cloudflare as settings.` + : "Read by the build, which runs on the deploying machine: deploy/cloudflare/deploy.sh exports each one the model gives a value (a value already in the environment wins) and runs the build there. They never reach Cloudflare as settings.", + }); + } + if (secrets.length > 0 && vault !== undefined) { + out.push({ + fact: `Secret values: ${secrets.map((n) => `\`${n}\``).join(", ")}`, + how: `Never in a file. deploy/cloudflare/sync-secrets.sh copies them from the vault scope \`${vault.scope.project}/${vault.scope.env}\`; deploy/cloudflare/doctor.sh checks the names are in the vault and ${secretsOn}.`, + }); + } + return out; +} + +/** + * The deployment's value nodes that give a value to a setting the app reads which is not + * @secret, each with its setting. Every other value node is refused. + */ +function readValues( + node: MetaData, + app: MetaData, + settings: readonly Setting[], + ctx: Context, + where: string, + problems: string[], +): { readonly node: MetaData; readonly setting: Setting }[] { + const out: { node: MetaData; setting: Setting }[] = []; + // ADR-0039: resolving, so a value the abstract base or an estate overlay declares counts. + for (const v of node.children().filter((c) => c.type === TYPE_VALUE)) { + const vWhere = `${where} value.${v.subType} ${v.name}`; + const ref = text(v.attr(VALUE_ATTR_SETTING)) ?? ""; + const setting = settingNamed(ref, ctx.groups); + if (setting === undefined) { + problems.push(`${vWhere}: @${VALUE_ATTR_SETTING} "${ref}" names no setting (Group.field) of an object.settings in the model`); + continue; + } + if (!settings.includes(setting)) { + problems.push(`${vWhere}: ${ref} is not a setting of the groups ${app.name} reads (@${APP_ATTR_SETTINGS})`); + continue; + } + if (setting.secret) { + problems.push(`${vWhere}: ${ref} is @secret; its value comes from the vault, never from a value node`); + continue; + } + out.push({ node: v, setting }); + } + return out; +} + +function readWorker(node: MetaData, ctx: Context, problems: string[]): WorkerDeployment | undefined { + const read = readCommon(node, ctx, problems); + if (read === undefined) return undefined; + const { app, env, where, settings, common } = read; + const unexpressed = commonUnexpressed(node, app, settings, common.secrets, common.vault, "on Cloudflare"); + if (common.branch !== undefined) { + unexpressed.push({ fact: `@branch \`${common.branch}\``, how: "Deploys run from deploy/cloudflare/deploy.sh, not on a push to the branch, so no file holds it." }); + } + + // vars: each value node, then each non-secret runtime setting's default. + const fromValue = new Map(); + for (const { node: v, setting } of readValues(node, app, settings, ctx, where, problems)) { + if (setting.phase === PHASE_BUILD) continue; + const value = v.subType === VALUE_SUBTYPE_LITERAL ? (text(v.attr(VALUE_ATTR_LITERAL)) ?? "") : referenceValue(v, env, ctx, `${where} value.${v.subType} ${v.name}`, problems); + if (value !== undefined) fromValue.set(setting.envName, { name: setting.envName, value, from: `value.${v.subType} ${v.name}${declaredIn(v, node)}` }); + } + // In the order the settings are declared, so a value moving between the base and an environment moves no line. + const vars = new Map(); + const unset: string[] = []; + for (const s of settings) { + if (s.secret || s.phase === PHASE_BUILD) continue; + const given = fromValue.get(s.envName); + if (given !== undefined) vars.set(s.envName, given); + else if (s.default !== undefined) vars.set(s.envName, { name: s.envName, value: s.default, from: `${s.setting} @default` }); + else if (s.required) problems.push(`${where}: ${s.setting} (${s.envName}) is required and has no value here: give it a value.literal on the deployment, a @default, or mark it @secret`); + else unset.push(s.envName); + } + if (unset.length > 0) { + unexpressed.push({ fact: `Optional settings with no value: ${unset.map((n) => `\`${n}\``).join(", ")}`, how: "Not in `vars`, so the Worker reads them as unset. A deploy removes a var the file does not declare: give one a value.literal to set it." }); + } + + // Bindings: each cloudflare.* child (resolving, so the base's bindings count), placed on a resource the app needs. + const needed = refList(app, APP_ATTR_NEEDS) + .map((r) => resolveSystemRef(app, r, APP_ATTR_NEEDS, [TYPE_RESOURCE])) + .filter((r): r is MetaData => r !== undefined); + const bindings: CloudflareBinding[] = []; + const bound = new Set(); + for (const b of node.children().filter((c) => c.type === TYPE_CLOUDFLARE)) { + const bWhere = `${where} cloudflare.${b.subType} ${b.name}`; + const from = `cloudflare.${b.subType} ${b.name}${declaredIn(b, node)}`; + bound.add(b.name); + const binding = bindingName(b.name); + const resourceKind = resourceKindOf(b.subType); + if (resourceKind !== undefined && !needed.some((r) => r.name === b.name && r.subType === resourceKind)) { + problems.push(`${bWhere}: ${app.name} needs no resource.${resourceKind} named "${b.name}" (@${APP_ATTR_NEEDS}); a binding is named after the resource it places`); + } + switch (b.subType) { + case BINDING_D1: { + const id = text(b.attr(D1_ATTR_DATABASE_ID)); + const dir = text(b.attr(D1_ATTR_MIGRATIONS_DIR)); + bindings.push({ kind: BINDING_D1, binding, from, databaseName: text(b.attr(D1_ATTR_DATABASE_NAME)) ?? "", ...(id !== undefined ? { databaseId: id } : {}), ...(dir !== undefined ? { migrationsDir: dir } : {}) }); + break; + } + case BINDING_KV: + bindings.push({ kind: BINDING_KV, binding, from, namespaceId: text(b.attr(KV_ATTR_NAMESPACE_ID)) ?? "" }); + break; + case BINDING_R2: + bindings.push({ kind: BINDING_R2, binding, from, bucketName: text(b.attr(R2_ATTR_BUCKET_NAME)) ?? "" }); + break; + case BINDING_QUEUE: + bindings.push({ kind: BINDING_QUEUE, binding, from, queue: text(b.attr(QUEUE_ATTR_QUEUE)) ?? "" }); + break; + case BINDING_RATELIMIT: { + const period = int(b.attr(RATELIMIT_ATTR_PERIOD)) ?? 0; + if (!RATELIMIT_PERIODS.includes(period)) problems.push(`${bWhere}: @${RATELIMIT_ATTR_PERIOD} ${period}: the rate limiting binding accepts ${RATELIMIT_PERIODS.join(" or ")} seconds only`); + bindings.push({ kind: BINDING_RATELIMIT, binding, from, namespaceId: text(b.attr(RATELIMIT_ATTR_NAMESPACE_ID)) ?? "", limit: int(b.attr(RATELIMIT_ATTR_LIMIT)) ?? 0, period }); + break; + } + } + } + // Every resource the app needs is bound here, or said to be carried another way. + for (const r of needed) { + if (isExternal(r)) { + unexpressed.push({ fact: `${describeResource(r)}, managed outside Cloudflare`, how: "Not bound: the Worker reaches it through its settings." }); + continue; + } + const kind = bindingKindFor(r); + if (kind === undefined) { + unexpressed.push({ fact: describeResource(r), how: `Cloudflare has no binding for this kind of resource. Reach it through settings, or model it as a kind a Worker binds (${bindableKinds()}).` }); + } else if (!bound.has(r.name) || !bindings.some((b) => b.kind === kind && b.binding === bindingName(r.name))) { + problems.push(`${where}: ${app.name} needs resource.${r.subType} "${r.name}" and environment ${env.name} has no cloudflare.${kind} "${r.name}" binding it; the Worker would fail when it reaches for it`); + } + } + + // One name per binding in the Worker's env: vars, secrets, bindings and the assets binding share it. + const assetsBinding = text(node.attr(WORKER_ATTR_ASSETS_BINDING)); + const names = [...vars.keys(), ...common.secrets, ...bindings.map((b) => b.binding), ...(assetsBinding !== undefined ? [assetsBinding] : [])]; + for (const n of new Set(names.filter((n, i) => names.indexOf(n) !== i))) problems.push(`${where}: ${n} is bound twice in the Worker's env (a var, a secret, a binding and the assets binding share one namespace)`); + + // Assets: the directory is the app's build.static. + const notFound = text(node.attr(WORKER_ATTR_NOT_FOUND)); + const workerFirstAll = node.attr(WORKER_ATTR_WORKER_FIRST) === true; + const workerFirstPaths = refList(node, WORKER_ATTR_WORKER_FIRST_PATHS); + if (workerFirstAll && workerFirstPaths.length > 0) problems.push(`${where}: @${WORKER_ATTR_WORKER_FIRST} and @${WORKER_ATTR_WORKER_FIRST_PATHS} both set; say every request, or which paths`); + const build = common.build; + let assets: CloudflareAssets | undefined; + if (build?.kind === BUILD_SUBTYPE_STATIC && build.directory !== undefined) { + const workerFirst = workerFirstAll ? true : workerFirstPaths.length > 0 ? workerFirstPaths : undefined; + assets = { + directory: build.directory, + ...(assetsBinding !== undefined ? { binding: assetsBinding } : {}), + ...(notFound !== undefined ? { notFound } : {}), + ...(workerFirst !== undefined ? { workerFirst } : {}), + }; + } else if (assetsBinding !== undefined || notFound !== undefined || workerFirstAll || workerFirstPaths.length > 0) { + problems.push(`${where}: asset attributes are set and ${app.name} has no build.static, whose @directory holds the assets`); + } + const main = text(node.attr(WORKER_ATTR_MAIN)); + if (main === undefined && assets === undefined) problems.push(`${where}: a Worker needs @${WORKER_ATTR_MAIN} or static assets (a build.static on ${app.name})`); + if (build !== undefined && build.kind !== BUILD_SUBTYPE_STATIC && build.command === undefined) { + problems.push(`${where}: ${app.name} is built by build.${build.kind}, which a Worker cannot run; use build.command or build.static`); + } + + // Crons: each @jobs entry resolves to a scheduled app.job. + const crons: CloudflareCron[] = []; + for (const ref of refList(node, WORKER_ATTR_JOBS)) { + const job = resolveSystemRef(node, ref, WORKER_ATTR_JOBS, [`${TYPE_APP}.${APP_SUBTYPE_JOB}`]); + const schedule = job === undefined ? undefined : text(job.attr(APP_ATTR_SCHEDULE)); + if (job === undefined || job.subType !== APP_SUBTYPE_JOB) problems.push(`${where}: @${WORKER_ATTR_JOBS} "${ref}" does not resolve to an app.job (write System.job)`); + else if (schedule === undefined) problems.push(`${where}: @${WORKER_ATTR_JOBS} "${ref}" has no @${APP_ATTR_SCHEDULE}, so there is no cron to trigger it`); + else crons.push({ schedule, from: `${appKeyOf(job)} @${APP_ATTR_SCHEDULE}` }); + } + + let extra: Record | undefined; + const extraText = text(node.attr(WORKER_ATTR_EXTRA)); + if (extraText !== undefined) { + try { + const parsed: unknown = JSON.parse(extraText); + if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("not an object"); + extra = parsed as Record; + const clash = Object.keys(extra).filter((k) => GENERATED_WRANGLER_KEYS.includes(k)); + if (clash.length > 0) problems.push(`${where}: @${WORKER_ATTR_EXTRA} sets ${clash.join(", ")}, which the generator writes from the model; declare those facts in the model`); + } catch { + problems.push(`${where}: @${WORKER_ATTR_EXTRA} is not a JSON object`); + } + } + + if (common.domains.length > 0) { + unexpressed.push({ fact: `DNS for ${common.domains.map((d) => `\`${d}\``).join(", ")}`, how: "Each domain is a custom domain route: Cloudflare creates its DNS record and certificate on deploy. The domain's zone must be on the same Cloudflare account." }); + } + + const compatibilityDate = text(node.attr(WORKER_ATTR_COMPATIBILITY_DATE)) ?? ""; + const workersDev = node.attr(WORKER_ATTR_WORKERS_DEV); + if (common.token === undefined) return undefined; + return { + ...common, + token: common.token, + kind: DEPLOYMENT_SUBTYPE_WORKER, + script: text(node.attr(WORKER_ATTR_SCRIPT)) ?? app.name, + ...(main !== undefined ? { main } : {}), + compatibilityDate, + compatibilityFlags: refList(node, WORKER_ATTR_COMPATIBILITY_FLAGS), + ...(typeof workersDev === "boolean" ? { workersDev } : {}), + ...(assets !== undefined ? { assets } : {}), + crons, + vars: [...vars.values()], + bindings, + ...(extra !== undefined ? { extra } : {}), + unexpressed, + }; +} + +/** + * The Pages project's production branch, as the model states it: the @branch of the app's + * deployment in the environment named `production` (the delivery pack's meaning of @branch is + * the branch whose pushes deploy there). Undefined when the model states none. + */ +function productionBranchOf(nodes: readonly MetaData[]): string | undefined { + const production = nodes.find((d) => environmentOf(d)?.name === PAGES_ENV_PRODUCTION); + return production === undefined ? undefined : text(production.attr(DEPLOYMENT_ATTR_BRANCH)); +} + +function readPages(node: MetaData, productionBranch: string | undefined, ctx: Context, problems: string[]): PagesDeployment | undefined { + const read = readCommon(node, ctx, problems); + if (read === undefined) return undefined; + const { app, where, settings, common } = read; + const pagesEnvironment = + common.branch === undefined || productionBranch === undefined + ? undefined + : common.branch === productionBranch + ? PAGES_ENV_PRODUCTION + : PAGES_ENV_PREVIEW; + if (common.secrets.length > 0 && pagesEnvironment === undefined) { + problems.push( + `${where}: ${app.name} reads ${common.secrets.length} secret setting(s) (${common.secrets.join(", ")}) and the model does not say whether this deployment serves the Pages project's production or its preview environment, each of which keeps its own: ${ + common.branch === undefined ? "it has no @branch" : `no deployment.pages of ${app.name} in an environment named "${PAGES_ENV_PRODUCTION}" declares a @branch, the project's production branch` + }`, + ); + } + const unexpressed = commonUnexpressed(node, app, settings, common.secrets, common.vault, `on the Pages project's ${pagesEnvironment} environment`); + const build = common.build; + if (build?.kind !== BUILD_SUBTYPE_STATIC || build.directory === undefined) { + problems.push(`${where}: a Pages site uploads a directory of files: ${app.name} needs a build.static with @directory`); + } + const plain = settings.filter((s) => !s.secret && s.phase !== PHASE_BUILD).map((s) => s.envName); + const values = readValues(node, app, settings, ctx, where, problems) + .filter(({ setting }) => setting.phase !== PHASE_BUILD) + .map(({ node: v }) => v.name); + if (plain.length > 0 || values.length > 0) { + unexpressed.push({ + fact: `Non-secret settings${plain.length > 0 ? ` ${plain.map((n) => `\`${n}\``).join(", ")}` : ""}${values.length > 0 ? ` (value nodes ${values.map((n) => `\`${n}\``).join(", ")})` : ""}`, + how: "A Pages project keeps its environment variables in its own settings; `wrangler pages deploy` uploads files only. Set them in the project, or deploy the app as a Worker with assets.", + }); + } + if (common.domains.length > 0) { + unexpressed.push({ fact: `Custom domains ${common.domains.map((d) => `\`${d}\``).join(", ")}`, how: "Attached to the Pages project once, in the project's settings; an upload does not change them. deploy/cloudflare/doctor.sh checks each answers." }); + } + if (common.token === undefined) return undefined; + return { + ...common, + token: common.token, + kind: DEPLOYMENT_SUBTYPE_PAGES, + project: text(node.attr(PAGES_ATTR_PROJECT)) ?? "", + directory: build?.directory ?? "", + ...(pagesEnvironment !== undefined ? { pagesEnvironment } : {}), + unexpressed, + }; +} + +/** The config pack's readers, their problems folded into this pack's list. */ +function configRead(read: () => T, problems: string[], fallback: T): T { + try { + return read(); + } catch (e) { + if (!(e instanceof ConfigModelError)) throw e; + problems.push(...e.problems); + return fallback; + } +} + +/** The app a deployment names, as its node, or undefined. */ +function appOf(d: MetaData): MetaData | undefined { + const ref = refList(d, DEPLOYMENT_ATTR_APP)[0]; + return ref === undefined ? undefined : resolveSystemRef(d, ref, DEPLOYMENT_ATTR_APP, [TYPE_APP]); +} + +/** The environment a deployment names, as its node, or undefined. */ +function environmentOf(d: MetaData): MetaData | undefined { + const ref = refList(d, DEPLOYMENT_ATTR_ENVIRONMENT)[0]; + return ref === undefined ? undefined : resolveSystemRef(d, ref, DEPLOYMENT_ATTR_ENVIRONMENT, [TYPE_ENVIRONMENT]); +} + +/** + * The one app whose Cloudflare deployments the generators write (`opts.app`, or the model's + * only one), or undefined when the model deploys nothing to Cloudflare. `objects` are the + * run's objects (the settings groups are among them); `inScope` is the run's scope over a + * node's resolution key. Throws a {@link CloudflareModelError} listing every problem. + */ +export function readCloudflare( + root: MetaRoot, + objects: readonly MetaObject[], + inScope: (key: string) => boolean = () => true, + opts: ReadCloudflareOptions = {}, +): CloudflareApp | undefined { + const problems: string[] = []; + const groups = configRead(() => readSettings(objects), problems, []); + const vaults = configRead(() => readVaults(root, inScope), problems, []); + // A settings or vault problem makes every deployment that reads them look wrong too: report it alone. + if (problems.length > 0) throw new CloudflareModelError(problems); + // ADR-0039: resolving, the deployments the model effectively holds. An abstract one is a base, never deployed. + const all = root.children().filter((d) => isCloudflareDeployment(d) && !d.isAbstract); + const ctx: Context = { all, groups, vaults }; + + const inRun = all.filter((d) => inScope(d.resolutionKey())); + const apps = [...new Set(inRun.map(appOf).filter((a): a is MetaData => a !== undefined))]; + if (apps.length === 0) return undefined; + let app: MetaData | undefined; + if (opts.app !== undefined) { + app = apps.find((a) => a.name === opts.app || `${a.parent?.name}.${a.name}` === opts.app || appKeyOf(a).endsWith(` ${opts.app}`)); + if (app === undefined) throw new CloudflareModelError([`no Cloudflare deployment deploys app "${opts.app}" (the model deploys: ${apps.map(appKeyOf).join(", ")})`]); + } else if (apps.length > 1) { + throw new CloudflareModelError([`the model deploys ${apps.length} apps to Cloudflare (${apps.map(appKeyOf).join(", ")}); one wrangler.jsonc and one set of scripts are for one app, so pass { app } to the generators`]); + } else { + app = apps[0]!; + } + + const nodes = inRun.filter((d) => appOf(d) === app); + const kinds = new Set(nodes.map((d) => d.subType)); + if (kinds.size > 1) { + throw new CloudflareModelError([`${appKeyOf(app)} is deployed both as a Worker and as a Pages site; deploy one app one way (a Worker with static assets replaces a Pages site)`]); + } + const kind = nodes[0]!.subType === DEPLOYMENT_SUBTYPE_PAGES ? DEPLOYMENT_SUBTYPE_PAGES : DEPLOYMENT_SUBTYPE_WORKER; + const productionBranch = kind === DEPLOYMENT_SUBTYPE_PAGES ? productionBranchOf(nodes) : undefined; + const deployments = nodes + .map((d) => (kind === DEPLOYMENT_SUBTYPE_PAGES ? readPages(d, productionBranch, ctx, problems) : readWorker(d, ctx, problems))) + .filter((d): d is CloudflareDeployment => d !== undefined); + + const envs = deployments.map((d) => d.environment); + const topLevel = opts.topLevel ?? (envs.length === 1 ? envs[0] : envs.includes(DEFAULT_TOP_LEVEL) ? DEFAULT_TOP_LEVEL : undefined); + if (topLevel === undefined) { + // Only when some deployment read clean: otherwise the problems above are the whole story. + if (deployments.length > 0) problems.push(`${appKeyOf(app)} deploys to ${envs.join(", ")}, and none is named ${DEFAULT_TOP_LEVEL}: pass { topLevel } to the generators to say which environment \`wrangler deploy\` with no --env deploys`); + } else if (deployments.length > 0 && !envs.includes(topLevel)) { + problems.push(`{ topLevel: "${topLevel}" } names an environment ${appKeyOf(app)} is not deployed to (${envs.join(", ")})`); + } + if (kind === DEPLOYMENT_SUBTYPE_WORKER) { + const workers = deployments as WorkerDeployment[]; + // Two environments must not deploy over one Worker: the env-block names come from the top level's. + const top = topLevel === undefined ? undefined : workers.find((d) => d.environment === topLevel); + if (top !== undefined) { + const seen = new Map(); + for (const d of workers) { + const name = d === top ? d.script : workerName(d, top); + const other = seen.get(name); + if (other !== undefined) problems.push(`deployment.worker ${d.key}: deploys Worker "${name}", as ${other} does; give one a different @script`); + else seen.set(name, d.key); + } + } + // Wrangler inherits these into an env block that omits them: so every environment sets each, or none does. + const inherited: [string, (d: WorkerDeployment) => unknown][] = [ + ["@main", (d) => d.main], + ["@workersDev", (d) => d.workersDev], + ["assets (the app's build.static)", (d) => d.assets], + ...INHERITED_WRANGLER_KEYS.map((key): [string, (d: WorkerDeployment) => unknown] => [`@${WORKER_ATTR_EXTRA} ${key}`, (d) => d.extra?.[key]]), + ]; + for (const [what, get] of inherited) { + const unset = workers.filter((d) => get(d) === undefined); + if (unset.length > 0 && unset.length < workers.length) + problems.push(`${appKeyOf(app)}: ${what} is set in ${workers.filter((d) => get(d) !== undefined).map((d) => d.environment).join(", ")} and not in ${unset.map((d) => d.environment).join(", ")}; Wrangler would fill the gap from the top level, so set it in every environment or none`); + } + } else { + const serving = new Map(); + for (const d of deployments as PagesDeployment[]) { + if (d.secrets.length === 0 || d.pagesEnvironment === undefined || d.vault === undefined) continue; + const place = JSON.stringify([d.project, d.pagesEnvironment]); + const other = serving.get(place); + if (other === undefined) { + serving.set(place, { key: d.key, vault: d.vault }); + } else if (other.vault.key !== d.vault.key || other.vault.scope.project !== d.vault.scope.project || other.vault.scope.env !== d.vault.scope.env) { + problems.push( + `deployment.pages ${d.key}: serves the ${d.pagesEnvironment} environment of Pages project ${d.project}, as ${other.key} does, and reads its secrets from ${describeScope(d.vault)}, not from ${describeScope(other.vault)}; Pages keeps one value per name in a project environment, so the last deploy overwrites the other's secrets: give both deployments one vault scope`, + ); + } + } + } + if (problems.length > 0 || topLevel === undefined) throw new CloudflareModelError(problems); + const ordered = [...deployments.filter((d) => d.environment === topLevel), ...deployments.filter((d) => d.environment !== topLevel)]; + return { name: app.name, appKey: appKeyOf(app), kind, deployments: ordered, topLevel }; +} + +/** + * The Worker name an env block deploys: the deployment's own @script when it differs from the + * top level's, else `-`, Wrangler's own default for an env block. + */ +export function workerName(d: WorkerDeployment, top: WorkerDeployment): string { + return d.script !== top.script ? d.script : `${top.script}-${d.environment}`; +} diff --git a/packs/cloudflare/typescript/src/resources.ts b/packs/cloudflare/typescript/src/resources.ts new file mode 100644 index 000000000..42fd909fa --- /dev/null +++ b/packs/cloudflare/typescript/src/resources.ts @@ -0,0 +1,43 @@ +/** + * The one place the pack reads the systems pack's resource.* nodes: which Cloudflare binding + * places which kind of resource, and whether a resource lives outside the platform. Every + * other module asks these functions, so a change to how resources are described is a change + * here only. + */ +import type { MetaData } from "@metaobjectsdev/metadata"; +import { MANAGED_BY_EXTERNAL, RESOURCE_ATTR_ENGINE, RESOURCE_ATTR_MANAGED_BY } from "@metaobjectsdev/pack-systems"; +import { BINDING_D1, BINDING_KV, BINDING_QUEUE, BINDING_R2 } from "./constants.js"; + +/** The resource.* subtype each binding places. A rate limiter places none. */ +const BINDING_RESOURCE: Readonly> = { + [BINDING_D1]: "database", + [BINDING_KV]: "keyvalue", + [BINDING_R2]: "bucket", + [BINDING_QUEUE]: "queue", +}; + +/** The resource kind a binding subtype places, or undefined for a binding that places none. */ +export function resourceKindOf(bindingKind: string): string | undefined { + return BINDING_RESOURCE[bindingKind]; +} + +/** The binding subtype that places `resource` on Cloudflare, or undefined when none can. */ +export function bindingKindFor(resource: MetaData): string | undefined { + return Object.entries(BINDING_RESOURCE).find(([, sub]) => sub === resource.subType)?.[0]; +} + +/** Whether `resource` lives outside the platform and so is reached through settings, never bound. */ +export function isExternal(resource: MetaData): boolean { + return resource.attr(RESOURCE_ATTR_MANAGED_BY) === MANAGED_BY_EXTERNAL; +} + +/** `resource.database \`db\` (postgres)`, for the unexpressed-facts file. */ +export function describeResource(resource: MetaData): string { + const engine = resource.attr(RESOURCE_ATTR_ENGINE); + return `resource.${resource.subType} \`${resource.name}\`${typeof engine === "string" && engine !== "" ? ` (${engine})` : ""}`; +} + +/** The binding kinds that place a resource, for messages. */ +export function bindableKinds(): string { + return Object.entries(BINDING_RESOURCE).map(([b, r]) => `${r} on ${b}`).join(", "); +} diff --git a/packs/cloudflare/typescript/src/wrangler.ts b/packs/cloudflare/typescript/src/wrangler.ts new file mode 100644 index 000000000..4394708c7 --- /dev/null +++ b/packs/cloudflare/typescript/src/wrangler.ts @@ -0,0 +1,187 @@ +/** + * `wrangler.jsonc`: the Worker's Wrangler configuration, written from the model. + * + * The top-level environment's deployment is written at the top level (`wrangler deploy`), and + * every other environment is an `env.` block (`wrangler deploy --env `). Wrangler + * inherits some top-level keys into an env block and not others (`vars`, `secrets` and every + * binding are never inherited), and a forgotten key is a silent difference between + * environments. So each env block is written in full: every key the top level has, with that + * environment's own value, an empty one included. What one environment's block says never + * depends on what Wrangler would fill in. + * + * Every fact carries a `//` comment naming the model node it came from. Paths in the model are + * from the repository root; Wrangler reads them from the file's own directory, so they are + * rewritten relative to where the file is written. + */ +import { posix } from "node:path"; +import { WRANGLER_SCHEMA_REF } from "./constants.js"; +import { workerName, type CloudflareApp, type CloudflareBinding, type WorkerDeployment } from "./model.js"; + +// ── a small JSONC writer: objects whose entries may carry a comment line ───── + +interface Entry { + readonly key: string; + readonly value: Json; + readonly comment?: string; +} + +class Obj { + constructor(readonly entries: readonly Entry[]) {} +} + +type Json = string | number | boolean | null | readonly Json[] | Obj; + +function entry(key: string, value: Json, comment?: string): Entry { + return comment === undefined ? { key, value } : { key, value, comment }; +} + +function obj(...entries: (Entry | undefined)[]): Obj { + const kept = entries.filter((e): e is Entry => e !== undefined); + // A key written twice would parse as its last value, silently: refuse it here instead. + const dup = kept.find((e, i) => kept.findIndex((x) => x.key === e.key) !== i); + if (dup !== undefined) throw new Error(`wrangler.jsonc: key "${dup.key}" written twice`); + return new Obj(kept); +} + +function isScalar(v: Json): v is string | number | boolean | null { + return v === null || typeof v !== "object"; +} + +function print(v: Json, indent: string): string { + if (isScalar(v)) return JSON.stringify(v); + const inner = `${indent} `; + if (v instanceof Obj) { + if (v.entries.length === 0) return "{}"; + const lines: string[] = []; + v.entries.forEach((e, i) => { + if (e.comment !== undefined) for (const c of e.comment.split("\n")) lines.push(`${inner}// ${c}`); + lines.push(`${inner}${JSON.stringify(e.key)}: ${print(e.value, inner)}${i < v.entries.length - 1 ? "," : ""}`); + }); + return `{\n${lines.join("\n")}\n${indent}}`; + } + const arr = v as readonly Json[]; + if (arr.length === 0) return "[]"; + if (arr.every(isScalar)) return `[${arr.map((x) => JSON.stringify(x)).join(", ")}]`; + return `[\n${arr.map((x) => `${inner}${print(x, inner)}`).join(",\n")}\n${indent}]`; +} + +/** The text with its full-line `//` comments removed, as JSON. The generated file has no other comments. */ +export function parseGeneratedJsonc(text: string): unknown { + return JSON.parse( + text + .split("\n") + .filter((l) => !/^\s*\/\//.test(l)) + .join("\n"), + ); +} + +// ── the configuration ──────────────────────────────────────────────────────── + +/** A repository-root path as Wrangler reads it from the file at `configPath` (`src/index.ts`). */ +function fromConfig(configPath: string, path: string): string { + const rel = posix.relative(posix.dirname(posix.normalize(configPath)), posix.normalize(path)); + return rel === "" ? "." : rel; +} + +/** A directory as Wrangler's own examples write one: `./dist/client`. */ +function dirFromConfig(configPath: string, path: string): string { + const rel = fromConfig(configPath, path); + return rel === "." || rel.startsWith("../") ? rel : `./${rel}`; +} + +function bindingsOf(d: WorkerDeployment, kind: K): Extract[] { + return d.bindings.filter((b): b is Extract => b.kind === kind); +} + +/** One environment's keys, each written whether or not it is empty (see the module comment). */ +function environmentEntries(d: WorkerDeployment, name: string, configPath: string): Entry[] { + const out: Entry[] = []; + const push = (key: string, value: Json, comment?: string): void => { + out.push(entry(key, value, comment)); + }; + /** One binding list, its comment naming each binding's node. */ + const pushBindings = (key: string, kind: K, one: (b: Extract) => Obj, wrap: (list: Obj[]) => Json = (list) => list): void => { + const bs = bindingsOf(d, kind); + push(key, wrap(bs.map(one)), bs.length === 0 ? `no cloudflare.${kind} binding` : bs.map((b) => b.from).join("\n")); + }; + push("name", name, `deployment.worker ${d.key}: environment ${d.environment}`); + if (d.main !== undefined) push("main", fromConfig(configPath, d.main), "@main"); + push("compatibility_date", d.compatibilityDate, "@compatibilityDate"); + push("compatibility_flags", d.compatibilityFlags, "@compatibilityFlags"); + if (d.workersDev !== undefined) push("workers_dev", d.workersDev, "@workersDev"); + push( + "routes", + d.domains.map((pattern) => obj(entry("pattern", pattern), entry("custom_domain", true))), + "@domains: each a custom domain, its DNS record and certificate made by Cloudflare", + ); + if (d.assets !== undefined) { + const a = d.assets; + push( + "assets", + obj( + entry("directory", dirFromConfig(configPath, a.directory)), + a.binding === undefined ? undefined : entry("binding", a.binding, "@assetsBinding"), + a.notFound === undefined ? undefined : entry("not_found_handling", a.notFound, "@notFound"), + a.workerFirst === undefined ? undefined : entry("run_worker_first", a.workerFirst === true ? true : [...a.workerFirst], a.workerFirst === true ? "@workerFirst" : "@workerFirstPaths"), + ), + `the app's ${d.build?.from ?? "build.static"} @directory`, + ); + } + push("triggers", obj(entry("crons", d.crons.map((c) => c.schedule))), d.crons.length > 0 ? d.crons.map((c) => c.from).join("\n") : "@jobs: none, so no cron triggers"); + push("vars", obj(...d.vars.map((v) => entry(v.name, v.value, v.from))), "the app's non-secret runtime settings (@settings)"); + push( + "secrets", + obj(entry("required", [...d.secrets])), + "the app's @secret runtime settings: values from the vault, copied by deploy/cloudflare/sync-secrets.sh", + ); + pushBindings("d1_databases", "d1", (b) => + obj( + entry("binding", b.binding), + entry("database_name", b.databaseName), + b.databaseId === undefined ? undefined : entry("database_id", b.databaseId), + b.migrationsDir === undefined ? undefined : entry("migrations_dir", fromConfig(configPath, b.migrationsDir)), + ), + ); + pushBindings("kv_namespaces", "kv", (b) => obj(entry("binding", b.binding), entry("id", b.namespaceId))); + pushBindings("r2_buckets", "r2", (b) => obj(entry("binding", b.binding), entry("bucket_name", b.bucketName))); + pushBindings("queues", "queue", (b) => obj(entry("binding", b.binding), entry("queue", b.queue)), (list) => obj(entry("producers", list))); + pushBindings("ratelimits", "ratelimit", (b) => obj(entry("name", b.binding), entry("namespace_id", b.namespaceId), entry("simple", obj(entry("limit", b.limit), entry("period", b.period))))); + Object.entries(d.extra ?? {}).forEach(([k, v], i) => push(k, fromPlain(v), i === 0 ? "@extra: written as the model gives it" : undefined)); + return out; +} + +/** An `@extra` value (plain JSON) as a writer value. */ +function fromPlain(v: unknown): Json { + if (v === null) return null; + if (Array.isArray(v)) return v.map(fromPlain); + if (typeof v === "object") return new Obj(Object.entries(v as Record).map(([k, x]) => entry(k, fromPlain(x)))); + if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") return v; + return String(v); +} + +/** `wrangler.jsonc` for one Worker app, `configPath` being where it is written; `header` is a `//` line. */ +export function renderWrangler(app: CloudflareApp, header: string, configPath: string): string { + const workers = app.deployments as readonly WorkerDeployment[]; + const top = workers[0]!; + const rest = workers.slice(1); + const depth = posix.normalize(configPath).split("/").length - 1; + const schema = `${depth === 0 ? "./" : "../".repeat(depth)}${WRANGLER_SCHEMA_REF}`; + const root = obj( + entry("$schema", schema), + ...environmentEntries(top, top.script, configPath), + rest.length === 0 + ? undefined + : entry( + "env", + obj(...rest.map((d) => entry(d.environment, obj(...environmentEntries(d, workerName(d, top), configPath)), `\`wrangler deploy --env ${d.environment}\``))), + "Every environment is written in full: Wrangler does not inherit vars, secrets or bindings into an env block.", + ), + ); + const lines = [ + header, + `// Wrangler configuration for ${app.appKey}, from the model. \`wrangler deploy\` deploys ${app.topLevel};`, + `// ${rest.length === 0 ? "it is the only environment." : `\`wrangler deploy --env \` deploys ${rest.map((d) => d.environment).join(", ")}.`} Deploy with deploy/cloudflare/deploy.sh .`, + print(root, ""), + ]; + return `${lines.join("\n")}\n`; +} diff --git a/packs/cloudflare/typescript/test/coverage.test.ts b/packs/cloudflare/typescript/test/coverage.test.ts new file mode 100644 index 000000000..7145b2339 --- /dev/null +++ b/packs/cloudflare/typescript/test/coverage.test.ts @@ -0,0 +1,187 @@ +// Fact-for-fact coverage: every fact of three hand-written Cloudflare configurations is in +// what the generators write from the fixture models that describe the same sites. +// +// The references below are those configurations with every site-specific value replaced +// by the fixtures' placeholders (names, hostnames, ids, account values): the shape, keys, +// numbers, flags and paths are as the originals wrote them. Each leaf of a reference is one +// fact, and each must be in the generated file at the same path with the same value. +// +// The generated files are also checked against Wrangler's own JSON schema (vendored in +// wrangler-schema/), so a key Wrangler would reject fails here rather than on a deploy. +import { describe, expect, test } from "bun:test"; +import { parseGeneratedJsonc } from "../src/index.js"; +import { emitFixture } from "./model.js"; +import { wranglerSchemaErrors } from "./wrangler-schema.js"; + +type Plain = string | number | boolean | null | Plain[] | { [k: string]: Plain }; + +/** A Worker with assets, a D1 database and a KV namespace, configured in wrangler.jsonc. */ +export const WORKER_WITH_ASSETS: Plain = { + name: "quiz", + main: "src/index.ts", + compatibility_date: "2024-12-30", + compatibility_flags: ["nodejs_compat"], + assets: { + directory: "./public", + binding: "ASSETS", + not_found_handling: "single-page-application", + run_worker_first: ["/api/*", "/c/*"], + }, + vars: { + MAX_QUESTIONS_PER_DAY: "5", + GLOBAL_MAX_PER_DAY: "200", + IP_MAX_PER_DAY: "10", + KILL_SWITCH: "off", + TURNSTILE_SITE_KEY: "1x00000000000000000000AA", + }, + kv_namespaces: [{ binding: "RATE_LIMIT", id: "00000000000000000000000000000001" }], + d1_databases: [{ binding: "DB", database_name: "quiz", database_id: "00000000-0000-4000-8000-000000000001", migrations_dir: "migrations" }], + routes: [ + { pattern: "quiz.example.com", custom_domain: true }, + { pattern: "www.quiz.example.com", custom_domain: true }, + ], +}; +/** Its one fact held only in a comment: SEARCH_URL is a Worker secret. */ +export const WORKER_WITH_ASSETS_SECRETS = ["SEARCH_URL"]; + +/** A Worker in front of its assets, with a cron, D1, R2 and five rate limiters, configured in wrangler.toml. */ +export const WORKER_WITH_LIMITERS: Plain = { + name: "trips", + main: "src/worker.ts", + compatibility_date: "2026-07-01", + compatibility_flags: ["nodejs_compat"], + routes: [ + { pattern: "trips.example.com", custom_domain: true }, + { pattern: "www.trips.example.com", custom_domain: true }, + ], + workers_dev: false, + triggers: { crons: ["0 4 * * *"] }, + assets: { directory: "./dist/client", binding: "ASSETS", not_found_handling: "single-page-application", run_worker_first: true }, + d1_databases: [{ binding: "DB", database_name: "trips", database_id: "00000000-0000-4000-8000-000000000003", migrations_dir: ".metaobjects/migrations" }], + r2_buckets: [{ binding: "PHOTOS", bucket_name: "trips-photos" }], + unsafe: { + bindings: [ + { name: "ENTER_LIMITER", type: "ratelimit", namespace_id: "1001", simple: { limit: 10, period: 60 } }, + { name: "ADMIN_LIMITER", type: "ratelimit", namespace_id: "1002", simple: { limit: 200, period: 60 } }, + { name: "LOGIN_LIMITER", type: "ratelimit", namespace_id: "1003", simple: { limit: 10, period: 60 } }, + { name: "LOGIN_LOCKOUT_LIMITER", type: "ratelimit", namespace_id: "1004", simple: { limit: 4, period: 60 } }, + { name: "RECOVERY_LIMITER", type: "ratelimit", namespace_id: "1005", simple: { limit: 3, period: 60 } }, + ], + }, + vars: { + ACCESS_TEAM_DOMAIN: "team.example.com", + ACCESS_AUD: "0000000000000000000000000000000000000000000000000000000000000000", + NOTIFY_EMAIL: "host@example.com", + }, +}; +/** Its secrets, listed only in its .dev.vars.example (the local-only DEV_OPEN_ADMIN is not one). */ +export const WORKER_WITH_LIMITERS_SECRETS = ["SESSION_SECRET", "RESEND_API_KEY", "PASSPHRASE_PEPPER", "RECOVERY_ENC_KEY", "RECOVERY_HMAC_KEY"]; +/** Its deploy script: build, then deploy with the narrow token from the deploy vault scope. */ +export const WORKER_WITH_LIMITERS_DEPLOY = { build: "pnpm build", vaultProject: "acme-deploy", vaultEnv: "dev", token: "ACME_WORKERS_TOKEN" }; + +/** A Pages site's deploy: `npm run build`, then a pinned `wrangler pages deploy`. */ +export const PAGES_DEPLOY = { + build: "npm run build", + wranglerVersion: "4.168.0", + directory: "dist", + project: "docs-site", + branch: "main", + vaultProject: "acme-deploy", + vaultEnv: "dev", + token: "ACME_PAGES_TOKEN", +}; + +/** Each leaf of `v` as [path, value]; an array of scalars is one leaf. */ +function facts(v: Plain, path: string[] = []): [string[], Plain][] { + if (v === null || typeof v !== "object") return [[path, v]]; + if (Array.isArray(v)) return v.every((x) => x === null || typeof x !== "object") ? [[path, v]] : v.flatMap((x, i) => facts(x, [...path, String(i)])); + return Object.entries(v).flatMap(([k, x]) => facts(x, [...path, k])); +} + +function at(v: unknown, path: readonly string[]): unknown { + return path.reduce((o, k) => (o !== null && typeof o === "object" ? (o as Record)[k] : undefined), v); +} + +const generated = emitFixture; + +describe("a Worker with assets, D1 and KV (wrangler.jsonc)", () => { + test("every fact of the reference is at the top level of the generated file", async () => { + const config = parseGeneratedJsonc((await generated("cloudflare-worker-environments")).get("wrangler.jsonc")!); + for (const [path, value] of facts(WORKER_WITH_ASSETS)) { + const got = at(config, path); + expect({ fact: path.join("."), value: got }).toEqual({ fact: path.join("."), value }); + } + expect(at(config, ["secrets", "required"])).toEqual(WORKER_WITH_ASSETS_SECRETS); + }); + + test("the staging environment is a complete env block: every key the top level has, with staging's values", async () => { + const config = parseGeneratedJsonc((await generated("cloudflare-worker-environments")).get("wrangler.jsonc")!) as Record; + const staging = at(config, ["env", "staging"]) as Record; + const topKeys = Object.keys(config).filter((k) => k !== "$schema" && k !== "env"); + expect(Object.keys(staging)).toEqual(topKeys); + expect(staging["name"]).toBe("quiz-staging"); + expect(at(staging, ["d1_databases", "0", "database_name"])).toBe("quiz-staging"); + expect(at(staging, ["kv_namespaces", "0", "id"])).toBe("00000000000000000000000000000002"); + expect(at(staging, ["vars", "KILL_SWITCH"])).toBe("on"); + // Inherited from the abstract base, repeated by the generator. + expect(at(staging, ["vars", "TURNSTILE_SITE_KEY"])).toBe("1x00000000000000000000AA"); + expect(at(staging, ["assets", "run_worker_first"])).toEqual(["/api/*", "/c/*"]); + expect(at(staging, ["secrets", "required"])).toEqual(["SEARCH_URL"]); + }); +}); + +describe("a Worker with a cron, D1, R2 and rate limiters (wrangler.toml)", () => { + test("every fact of the reference is in the generated file; the unsafe rate limiters are first-class ratelimits", async () => { + const config = parseGeneratedJsonc((await generated("cloudflare-worker-cron-ratelimits")).get("wrangler.jsonc")!); + const { unsafe, ...rest } = WORKER_WITH_LIMITERS as Record; + for (const [path, value] of facts(rest)) { + const got = at(config, path); + expect({ fact: path.join("."), value: got }).toEqual({ fact: path.join("."), value }); + } + const limiters = (unsafe as { bindings: { name: string; namespace_id: string; simple: Plain }[] }).bindings; + expect(at(config, ["ratelimits"])).toEqual(limiters.map(({ name, namespace_id, simple }) => ({ name, namespace_id, simple }))); + expect(at(config, ["unsafe"])).toBeUndefined(); + expect(at(config, ["secrets", "required"])).toEqual(WORKER_WITH_LIMITERS_SECRETS); + }); + + test("the deploy builds, then deploys through the narrow-token wrapper", async () => { + const files = await generated("cloudflare-worker-cron-ratelimits"); + const deploy = files.get("deploy/cloudflare/deploy.sh")!; + const runner = files.get("deploy/cloudflare/wrangler.sh")!; + const d = WORKER_WITH_LIMITERS_DEPLOY; + expect(deploy).toContain(`\n ${d.build}\n`); + expect(deploy.indexOf(d.build)).toBeLessThan(deploy.indexOf('wrangler.sh "$ENVIRONMENT" deploy')); + expect(runner).toContain(`VAULT_PROJECT=${d.vaultProject} VAULT_ENV=${d.vaultEnv} TOKEN=${d.token}`); + expect(runner).toContain("exec env -u CLOUDFLARE_EMAIL -u CLOUDFLARE_API_KEY -u CLOUDFLARE_API_TOKEN"); + expect(runner).toContain('--only "$TOKEN" CLOUDFLARE_ACCOUNT_ID'); + expect(runner).toContain('export CLOUDFLARE_API_TOKEN="${!1}"'); + expect(runner).toContain(': "${CLOUDFLARE_ACCOUNT_ID:?'); + }); +}); + +describe("a Pages site (its deploy command)", () => { + test("every fact of the reference deploy is in the generated scripts", async () => { + const files = await generated("cloudflare-pages-site"); + expect(files.has("wrangler.jsonc")).toBe(false); + const deploy = files.get("deploy/cloudflare/deploy.sh")!; + const runner = files.get("deploy/cloudflare/wrangler.sh")!; + const p = PAGES_DEPLOY; + expect(deploy).toContain(`\n ${p.build}\n`); + expect(deploy).toContain(`wrangler.sh "$ENVIRONMENT" pages deploy ${p.directory} --project-name=${p.project} --branch=${p.branch} --commit-hash="$(git rev-parse HEAD)"`); + expect(runner).toContain(`WRANGLER_VERSION="\${WRANGLER_VERSION:-${p.wranglerVersion}}"`); + expect(runner).toContain('exec npx --yes "wrangler@$version" "$@"'); + expect(runner).toContain(`VAULT_PROJECT=${p.vaultProject} VAULT_ENV=${p.vaultEnv} TOKEN=${p.token}`); + expect(runner).toContain("exec env -u CLOUDFLARE_EMAIL -u CLOUDFLARE_API_KEY -u CLOUDFLARE_API_TOKEN"); + }); +}); + +describe("Wrangler's own schema", () => { + test.each(["cloudflare-worker-environments", "cloudflare-worker-cron-ratelimits"])("%s: wrangler.jsonc is valid", async (scenario) => { + const config = parseGeneratedJsonc((await generated(scenario)).get("wrangler.jsonc")!); + expect(wranglerSchemaErrors(config)).toEqual([]); + }); + + test("the schema is strict enough to catch a key Wrangler does not have", () => { + expect(wranglerSchemaErrors({ name: "x", compatibility_date: "2026-07-01", no_such_key: true })).not.toEqual([]); + }); +}); diff --git a/packs/cloudflare/typescript/test/emit.test.ts b/packs/cloudflare/typescript/test/emit.test.ts new file mode 100644 index 000000000..3e54c23f5 --- /dev/null +++ b/packs/cloudflare/typescript/test/emit.test.ts @@ -0,0 +1,71 @@ +// The generators' output for each fixture, pinned as golden files, and every script checked +// by bash and, where installed, shellcheck. +import { describe, expect, test } from "bun:test"; +import { spawnSync } from "node:child_process"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, relative } from "node:path"; +import { editFixture, emit, emitFixture, loadModels } from "./model.js"; + +const GOLDEN = join(import.meta.dir, "golden"); +/** `UPDATE_GOLDEN=1 bun test` rewrites the golden files from the generators. */ +const UPDATE = process.env["UPDATE_GOLDEN"] === "1"; +const SCENARIOS = ["cloudflare-worker-environments", "cloudflare-worker-cron-ratelimits", "cloudflare-pages-site", "cloudflare-pages-secrets"]; +const HAS_SHELLCHECK = spawnSync("shellcheck", ["--version"]).status === 0; + +function walk(dir: string): string[] { + return readdirSync(dir).flatMap((f) => { + const p = join(dir, f); + return statSync(p).isDirectory() ? walk(p) : [p]; + }); +} + +test("a build-time value with shell syntax in it is exported as written, and only when the variable is unset", async () => { + const sources = editFixture("cloudflare-pages-site", (r) => { + const d = (r["metadata.root"].children.find((c) => c["deployment.pages"]?.["name"] === "siteProduction") as Record>)["deployment.pages"]!; + ((d["children"] ??= []) as unknown[]).push({ "value.literal": { name: "url", "@setting": "Site.url", "@literal": `{"a":"$x}'"}` } }); + }); + const deploy = (await emit(await loadModels(sources))).get("deploy/cloudflare/deploy.sh")!; + const line = deploy.split("\n").find((l) => l.includes("export SITE_URL="))!.trim(); + const run = (env: Record) => spawnSync("bash", ["-c", `${line}; printf %s "$SITE_URL"`], { encoding: "utf8", env: { PATH: process.env.PATH ?? "", ...env } }).stdout; + expect(run({})).toBe(`{"a":"$x}'"}`); + expect(run({ SITE_URL: "custom" })).toBe("custom"); +}); + +describe.each(SCENARIOS)("%s", (scenario) => { + test("the generators write the golden files, and only those", async () => { + const files = await emitFixture(scenario); + const golden = join(GOLDEN, scenario); + if (UPDATE) { + rmSync(golden, { recursive: true, force: true }); + for (const [path, content] of files) { + mkdirSync(dirname(join(golden, path)), { recursive: true }); + writeFileSync(join(golden, path), content); + } + } + expect(existsSync(golden)).toBe(true); + const expected = new Map(walk(golden).map((p) => [relative(golden, p), readFileSync(p, "utf8")])); + expect([...files.keys()].sort()).toEqual([...expected.keys()].sort()); + for (const [path, content] of files) expect(content).toBe(expected.get(path)!); + }); + + test("every script parses, and passes shellcheck where it is installed", async () => { + const files = await emitFixture(scenario); + const dir = mkdtempSync(join(process.env.DEV_SCRATCH ?? tmpdir(), "pack-cloudflare-sh-")); + try { + for (const [path, content] of files) { + if (!path.endsWith(".sh")) continue; + const file = join(dir, path.replace(/\//g, "_")); + writeFileSync(file, content); + const parse = spawnSync("bash", ["-n", file], { encoding: "utf8" }); + expect({ path, stderr: parse.stderr }).toEqual({ path, stderr: "" }); + if (HAS_SHELLCHECK) { + const check = spawnSync("shellcheck", ["-s", "bash", file], { encoding: "utf8" }); + expect({ path, findings: check.stdout }).toEqual({ path, findings: "" }); + } + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/packs/cloudflare/typescript/test/golden/cloudflare-pages-secrets/deploy/cloudflare/deploy.sh b/packs/cloudflare/typescript/test/golden/cloudflare-pages-secrets/deploy/cloudflare/deploy.sh new file mode 100644 index 000000000..94270f829 --- /dev/null +++ b/packs/cloudflare/typescript/test/golden/cloudflare-pages-secrets/deploy/cloudflare/deploy.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +# @generated by @metaobjectsdev/pack-cloudflare (cloudflare-deploy) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +# Deploys app.client acme::help::Help.site to one environment, from the model: +# 1. builds it (`npm run build`, skipped with --no-build), +# 2. copies its secrets from the vault (deploy/cloudflare/sync-secrets.sh, skipped with --no-secrets), +# 3. uploads the build to the environment's Pages project and branch, recording the commit. +# +# Needs: what deploy/cloudflare/wrangler.sh needs, and git. +# +# bash deploy/cloudflare/deploy.sh [--no-build] [--no-secrets] +set -euo pipefail +cd "$(dirname "$0")/../.." + +ENVIRONMENT="${1:-}" +BUILD=1; SECRETS=1 +for arg in "${@:2}"; do + case "$arg" in + --no-build) BUILD=0 ;; + --no-secrets) SECRETS=0 ;; + *) echo 'usage: bash deploy/cloudflare/deploy.sh [--no-build] [--no-secrets]' >&2; exit 2 ;; + esac +done +case "$ENVIRONMENT" in production|preview) ;; *) echo 'usage: bash deploy/cloudflare/deploy.sh [--no-build] [--no-secrets] (environments: production, preview)' >&2; exit 2 ;; esac + +if [ "$BUILD" = 1 ]; then + # build.static pages @command + npm run build +fi +if [ "$SECRETS" = 1 ]; then bash deploy/cloudflare/sync-secrets.sh "$ENVIRONMENT"; fi + +case "$ENVIRONMENT" in + production) + bash deploy/cloudflare/wrangler.sh "$ENVIRONMENT" pages deploy dist --project-name=help-site --branch=main --commit-hash="$(git rev-parse HEAD)" + ;; + preview) + bash deploy/cloudflare/wrangler.sh "$ENVIRONMENT" pages deploy dist --project-name=help-site --branch=preview --commit-hash="$(git rev-parse HEAD)" + ;; + *) echo 'usage: bash deploy/cloudflare/deploy.sh [--no-build] [--no-secrets] (environments: production, preview)' >&2; exit 2 ;; +esac diff --git a/packs/cloudflare/typescript/test/golden/cloudflare-pages-secrets/deploy/cloudflare/doctor.sh b/packs/cloudflare/typescript/test/golden/cloudflare-pages-secrets/deploy/cloudflare/doctor.sh new file mode 100644 index 000000000..34fb59255 --- /dev/null +++ b/packs/cloudflare/typescript/test/golden/cloudflare-pages-secrets/deploy/cloudflare/doctor.sh @@ -0,0 +1,64 @@ +#!/usr/bin/env bash +# @generated by @metaobjectsdev/pack-cloudflare (cloudflare-doctor) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +# Checks app.client acme::help::Help.site on Cloudflare against the model, for one environment, by name only: +# the deploy token and account id are in the vault; every secret the model declares is in the vault +# and on the Pages project's environment its branch serves (production or preview); each domain answers. +# Exits 1 when a check fails. It prints names, never a value. +# +# Needs: keys-axi, jq, curl, and what deploy/cloudflare/wrangler.sh needs. +# +# bash deploy/cloudflare/doctor.sh +set -uo pipefail +cd "$(dirname "$0")/../.." || exit 2 + +ENVIRONMENT="${1:-}" +FAIL=0 +ok() { echo "ok $*"; } +bad() { echo "FAIL $*"; FAIL=1; } +KEYS_AXI="${KEYS_AXI:-$(command -v keys-axi || echo "$HOME/.local/bin/keys-axi")}" +[ -x "$KEYS_AXI" ] || { echo "doctor: keys-axi is not installed" >&2; exit 2; } +for tool in jq curl npx; do + command -v "$tool" >/dev/null || { echo "doctor: $tool is not installed" >&2; exit 2; } +done + +# in_vault ... +in_vault() { + local names + names=$("$KEYS_AXI" ls --project "$1" --env "$2" --json | jq -r '.secrets[].name') || { bad "cannot list vault scope $1/$2"; return; } + local where="$1/$2"; shift 2 + for n in "$@"; do + if grep -Fxq -e "$n" <<<"$names"; then ok "$n is in the vault ($where)"; else bad "$n is not in the vault ($where)"; fi + done +} + +# on_cloudflare ... +on_cloudflare() { + local names + names=$(bash deploy/cloudflare/wrangler.sh "$ENVIRONMENT" pages secret list --project-name "$1" --env "$2" 2>/dev/null | sed -n 's/^ *- \([A-Za-z0-9_]*\):.*/\1/p') || { bad "cannot list the secrets of Pages project $1, $2 environment"; return; } + local where="Pages project $1, $2 environment"; shift 2 + for n in "$@"; do + if grep -Fxq -e "$n" <<<"$names"; then ok "$n is set on $where"; else bad "$n is declared and not set on $where (run deploy/cloudflare/sync-secrets.sh)"; fi + done +} + +# answers +answers() { + if curl -fsS -o /dev/null --max-time 10 "$1"; then ok "$1 answers"; else bad "$1 does not answer 2xx"; fi +} + +case "$ENVIRONMENT" in + production) + in_vault acme-deploy dev ACME_PAGES_TOKEN CLOUDFLARE_ACCOUNT_ID + in_vault acme-help prod SEARCH_API_KEY + on_cloudflare help-site production SEARCH_API_KEY + answers https://help.example.com/ + ;; + preview) + in_vault acme-deploy dev ACME_PAGES_TOKEN CLOUDFLARE_ACCOUNT_ID + in_vault acme-help-preview preview SEARCH_API_KEY + on_cloudflare help-site preview SEARCH_API_KEY + ;; + *) echo 'usage: bash deploy/cloudflare/doctor.sh (environments: production, preview)' >&2; exit 2 ;; +esac + +exit "$FAIL" diff --git a/packs/cloudflare/typescript/test/golden/cloudflare-pages-secrets/deploy/cloudflare/sync-secrets.sh b/packs/cloudflare/typescript/test/golden/cloudflare-pages-secrets/deploy/cloudflare/sync-secrets.sh new file mode 100644 index 000000000..b7abc4150 --- /dev/null +++ b/packs/cloudflare/typescript/test/golden/cloudflare-pages-secrets/deploy/cloudflare/sync-secrets.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# @generated by @metaobjectsdev/pack-cloudflare (cloudflare-sync-secrets) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +# Copies every secret setting app.client acme::help::Help.site reads from the vault to the Pages project's environment, +# for one environment: production when its branch is the project's production branch, else preview. +# A value goes from keys-axi's environment through a pipe into `wrangler pages secret put`: +# it is never printed and never on a command line. +# +# Needs: keys-axi (an identity that may read the vault scope) and what deploy/cloudflare/wrangler.sh needs. +# +# bash deploy/cloudflare/sync-secrets.sh [--dry-run] +set -euo pipefail +cd "$(dirname "$0")/../.." + +ENVIRONMENT="${1:-}" +DRY_RUN=0 +for arg in "${@:2}"; do + case "$arg" in + --dry-run) DRY_RUN=1 ;; + *) echo 'usage: bash deploy/cloudflare/sync-secrets.sh [--dry-run]' >&2; exit 2 ;; + esac +done +KEYS_AXI="${KEYS_AXI:-$(command -v keys-axi || echo "$HOME/.local/bin/keys-axi")}" + +# copy +copy() { + if [ "$DRY_RUN" = 1 ]; then echo "would copy $3 from $1/$2 to Pages project $4, $5 environment ($ENVIRONMENT)"; return; fi + # shellcheck disable=SC2016 # the inner shell expands it: the value never enters this one + "$KEYS_AXI" run --project "$1" --env "$2" --only "$3" -- bash -c ' + [ -n "${!1+set}" ] || { echo "sync-secrets: $1 is not in the vault scope" >&2; exit 1; } + value="${!1}" + unset "$1" + printf %s "$value" | bash deploy/cloudflare/wrangler.sh "$2" pages secret put "$1" --project-name "$3" --env "$4" >/dev/null + ' sync-secret "$3" "$ENVIRONMENT" "$4" "$5" + echo "copied $3 to Pages project $4, $5 environment ($ENVIRONMENT)" +} + +case "$ENVIRONMENT" in + production) + copy acme-help prod SEARCH_API_KEY help-site production + ;; + preview) + copy acme-help-preview preview SEARCH_API_KEY help-site preview + ;; + *) echo 'usage: bash deploy/cloudflare/sync-secrets.sh [--dry-run] (environments: production, preview)' >&2; exit 2 ;; +esac diff --git a/packs/cloudflare/typescript/test/golden/cloudflare-pages-secrets/deploy/cloudflare/unexpressed.md b/packs/cloudflare/typescript/test/golden/cloudflare-pages-secrets/deploy/cloudflare/unexpressed.md new file mode 100644 index 000000000..bf82fc110 --- /dev/null +++ b/packs/cloudflare/typescript/test/golden/cloudflare-pages-secrets/deploy/cloudflare/unexpressed.md @@ -0,0 +1,24 @@ + + +# What the deploy scripts do not hold: app.client acme::help::Help.site + +Facts the model declares that Cloudflare's configuration cannot carry, or that it leaves to +something else, each with how it is carried instead. Generated from the model: change the +model, not this file. + +## production + +From deployment.pages `acme::help::siteProduction`. + +| Fact | How it is carried | +|---|---| +| Secret values: `SEARCH_API_KEY` | Never in a file. deploy/cloudflare/sync-secrets.sh copies them from the vault scope `acme-help/prod`; deploy/cloudflare/doctor.sh checks the names are in the vault and on the Pages project's production environment. | +| Custom domains `help.example.com` | Attached to the Pages project once, in the project's settings; an upload does not change them. deploy/cloudflare/doctor.sh checks each answers. | + +## preview + +From deployment.pages `acme::help::sitePreview`. + +| Fact | How it is carried | +|---|---| +| Secret values: `SEARCH_API_KEY` | Never in a file. deploy/cloudflare/sync-secrets.sh copies them from the vault scope `acme-help-preview/preview`; deploy/cloudflare/doctor.sh checks the names are in the vault and on the Pages project's preview environment. | diff --git a/packs/cloudflare/typescript/test/golden/cloudflare-pages-secrets/deploy/cloudflare/wrangler.sh b/packs/cloudflare/typescript/test/golden/cloudflare-pages-secrets/deploy/cloudflare/wrangler.sh new file mode 100644 index 000000000..2e09b6440 --- /dev/null +++ b/packs/cloudflare/typescript/test/golden/cloudflare-pages-secrets/deploy/cloudflare/wrangler.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# @generated by @metaobjectsdev/pack-cloudflare (cloudflare-wrangler) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +# Runs wrangler 4.168.0 (WRANGLER_VERSION overrides) for app.client acme::help::Help.site, as the narrow +# Cloudflare API token of one environment's deployment. The token and CLOUDFLARE_ACCOUNT_ID are read +# from the vault with keys-axi. The global-key variables (CLOUDFLARE_EMAIL, CLOUDFLARE_API_KEY) are unset +# so Wrangler cannot fall back to them, and so is any CLOUDFLARE_API_TOKEN the shell holds; the vault's token then becomes CLOUDFLARE_API_TOKEN. +# +# Needs: keys-axi (KEYS_AXI overrides where it is) and npx. +# +# bash deploy/cloudflare/wrangler.sh ... +set -euo pipefail +cd "$(dirname "$0")/../.." + +ENVIRONMENT="${1:-}" +[ "$#" -gt 0 ] && shift +WRANGLER_VERSION="${WRANGLER_VERSION:-4.168.0}" +KEYS_AXI="${KEYS_AXI:-$(command -v keys-axi || echo "$HOME/.local/bin/keys-axi")}" + +case "$ENVIRONMENT" in + production) + VAULT_PROJECT=acme-deploy VAULT_ENV=dev TOKEN=ACME_PAGES_TOKEN + ;; + preview) + VAULT_PROJECT=acme-deploy VAULT_ENV=dev TOKEN=ACME_PAGES_TOKEN + ;; + *) echo 'usage: bash deploy/cloudflare/wrangler.sh ... (environments: production, preview)' >&2; exit 2 ;; +esac + +# shellcheck disable=SC2016 # the inner shell expands them: the token never enters this one +exec env -u CLOUDFLARE_EMAIL -u CLOUDFLARE_API_KEY -u CLOUDFLARE_API_TOKEN \ + "$KEYS_AXI" run --project "$VAULT_PROJECT" --env "$VAULT_ENV" --only "$TOKEN" CLOUDFLARE_ACCOUNT_ID -- \ + bash -c ' + set -euo pipefail + [ -n "${!1:-}" ] || { echo "wrangler.sh: the deploy token $1 is empty or is not in the vault scope" >&2; exit 1; } + export CLOUDFLARE_API_TOKEN="${!1}" + [ "$1" = CLOUDFLARE_API_TOKEN ] || unset "$1" + : "${CLOUDFLARE_ACCOUNT_ID:?CLOUDFLARE_ACCOUNT_ID is not in the vault scope}" + version="$2" + shift 2 + exec npx --yes "wrangler@$version" "$@" + ' wrangler "$TOKEN" "$WRANGLER_VERSION" "$@" diff --git a/packs/cloudflare/typescript/test/golden/cloudflare-pages-site/deploy/cloudflare/deploy.sh b/packs/cloudflare/typescript/test/golden/cloudflare-pages-site/deploy/cloudflare/deploy.sh new file mode 100644 index 000000000..ff34fa69b --- /dev/null +++ b/packs/cloudflare/typescript/test/golden/cloudflare-pages-site/deploy/cloudflare/deploy.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# @generated by @metaobjectsdev/pack-cloudflare (cloudflare-deploy) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +# Deploys app.client acme::docs::Docs.site to one environment, from the model: +# 1. builds it (`npm run build`, skipped with --no-build), +# 2. copies its secrets from the vault (deploy/cloudflare/sync-secrets.sh, skipped with --no-secrets), +# 3. uploads the build to the environment's Pages project and branch, recording the commit. +# Build-time settings are read by the build from this machine's environment; the values the model gives +# are exported first, and a value already in the environment wins. +# +# Needs: what deploy/cloudflare/wrangler.sh needs, and git. +# +# bash deploy/cloudflare/deploy.sh [--no-build] [--no-secrets] +set -euo pipefail +cd "$(dirname "$0")/../.." + +ENVIRONMENT="${1:-}" +BUILD=1; SECRETS=1 +for arg in "${@:2}"; do + case "$arg" in + --no-build) BUILD=0 ;; + --no-secrets) SECRETS=0 ;; + *) echo 'usage: bash deploy/cloudflare/deploy.sh [--no-build] [--no-secrets]' >&2; exit 2 ;; + esac +done +case "$ENVIRONMENT" in + production) + # acme::docs::Site.url @default + [ -n "${SITE_URL:-}" ] || export SITE_URL=https://docs.example.com + ;; + preview) + # acme::docs::Site.url @default + [ -n "${SITE_URL:-}" ] || export SITE_URL=https://docs.example.com + ;; + *) echo 'usage: bash deploy/cloudflare/deploy.sh [--no-build] [--no-secrets] (environments: production, preview)' >&2; exit 2 ;; +esac + +if [ "$BUILD" = 1 ]; then + # build.static pages @command + npm run build +fi +if [ "$SECRETS" = 1 ]; then bash deploy/cloudflare/sync-secrets.sh "$ENVIRONMENT"; fi + +case "$ENVIRONMENT" in + production) + bash deploy/cloudflare/wrangler.sh "$ENVIRONMENT" pages deploy dist --project-name=docs-site --branch=main --commit-hash="$(git rev-parse HEAD)" + ;; + preview) + bash deploy/cloudflare/wrangler.sh "$ENVIRONMENT" pages deploy dist --project-name=docs-site --branch=preview --commit-hash="$(git rev-parse HEAD)" + ;; + *) echo 'usage: bash deploy/cloudflare/deploy.sh [--no-build] [--no-secrets] (environments: production, preview)' >&2; exit 2 ;; +esac diff --git a/packs/cloudflare/typescript/test/golden/cloudflare-pages-site/deploy/cloudflare/doctor.sh b/packs/cloudflare/typescript/test/golden/cloudflare-pages-site/deploy/cloudflare/doctor.sh new file mode 100644 index 000000000..7456129a2 --- /dev/null +++ b/packs/cloudflare/typescript/test/golden/cloudflare-pages-site/deploy/cloudflare/doctor.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +# @generated by @metaobjectsdev/pack-cloudflare (cloudflare-doctor) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +# Checks app.client acme::docs::Docs.site on Cloudflare against the model, for one environment, by name only: +# the deploy token and account id are in the vault; every secret the model declares is in the vault +# and on the Pages project's environment its branch serves (production or preview); each domain answers. +# Exits 1 when a check fails. It prints names, never a value. +# +# Needs: keys-axi, jq, curl, and what deploy/cloudflare/wrangler.sh needs. +# +# bash deploy/cloudflare/doctor.sh +set -uo pipefail +cd "$(dirname "$0")/../.." || exit 2 + +ENVIRONMENT="${1:-}" +FAIL=0 +ok() { echo "ok $*"; } +bad() { echo "FAIL $*"; FAIL=1; } +KEYS_AXI="${KEYS_AXI:-$(command -v keys-axi || echo "$HOME/.local/bin/keys-axi")}" +[ -x "$KEYS_AXI" ] || { echo "doctor: keys-axi is not installed" >&2; exit 2; } +for tool in jq curl npx; do + command -v "$tool" >/dev/null || { echo "doctor: $tool is not installed" >&2; exit 2; } +done + +# in_vault ... +in_vault() { + local names + names=$("$KEYS_AXI" ls --project "$1" --env "$2" --json | jq -r '.secrets[].name') || { bad "cannot list vault scope $1/$2"; return; } + local where="$1/$2"; shift 2 + for n in "$@"; do + if grep -Fxq -e "$n" <<<"$names"; then ok "$n is in the vault ($where)"; else bad "$n is not in the vault ($where)"; fi + done +} + +# answers +answers() { + if curl -fsS -o /dev/null --max-time 10 "$1"; then ok "$1 answers"; else bad "$1 does not answer 2xx"; fi +} + +case "$ENVIRONMENT" in + production) + in_vault acme-deploy dev ACME_PAGES_TOKEN CLOUDFLARE_ACCOUNT_ID + answers https://docs.example.com/ + ;; + preview) + in_vault acme-deploy dev ACME_PAGES_TOKEN CLOUDFLARE_ACCOUNT_ID + ;; + *) echo 'usage: bash deploy/cloudflare/doctor.sh (environments: production, preview)' >&2; exit 2 ;; +esac + +exit "$FAIL" diff --git a/packs/cloudflare/typescript/test/golden/cloudflare-pages-site/deploy/cloudflare/sync-secrets.sh b/packs/cloudflare/typescript/test/golden/cloudflare-pages-site/deploy/cloudflare/sync-secrets.sh new file mode 100644 index 000000000..debca5328 --- /dev/null +++ b/packs/cloudflare/typescript/test/golden/cloudflare-pages-site/deploy/cloudflare/sync-secrets.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# @generated by @metaobjectsdev/pack-cloudflare (cloudflare-sync-secrets) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +# Copies every secret setting app.client acme::docs::Docs.site reads from the vault to the Pages project's environment, +# for one environment: production when its branch is the project's production branch, else preview. +# A value goes from keys-axi's environment through a pipe into `wrangler pages secret put`: +# it is never printed and never on a command line. +# +# Needs: keys-axi (an identity that may read the vault scope) and what deploy/cloudflare/wrangler.sh needs. +# +# bash deploy/cloudflare/sync-secrets.sh [--dry-run] +set -euo pipefail +cd "$(dirname "$0")/../.." + +ENVIRONMENT="${1:-}" +DRY_RUN=0 +for arg in "${@:2}"; do + case "$arg" in + --dry-run) DRY_RUN=1 ;; + *) echo 'usage: bash deploy/cloudflare/sync-secrets.sh [--dry-run]' >&2; exit 2 ;; + esac +done +KEYS_AXI="${KEYS_AXI:-$(command -v keys-axi || echo "$HOME/.local/bin/keys-axi")}" + +# copy +copy() { + if [ "$DRY_RUN" = 1 ]; then echo "would copy $3 from $1/$2 to Pages project $4, $5 environment ($ENVIRONMENT)"; return; fi + # shellcheck disable=SC2016 # the inner shell expands it: the value never enters this one + "$KEYS_AXI" run --project "$1" --env "$2" --only "$3" -- bash -c ' + [ -n "${!1+set}" ] || { echo "sync-secrets: $1 is not in the vault scope" >&2; exit 1; } + value="${!1}" + unset "$1" + printf %s "$value" | bash deploy/cloudflare/wrangler.sh "$2" pages secret put "$1" --project-name "$3" --env "$4" >/dev/null + ' sync-secret "$3" "$ENVIRONMENT" "$4" "$5" + echo "copied $3 to Pages project $4, $5 environment ($ENVIRONMENT)" +} + +case "$ENVIRONMENT" in + production) + echo 'no secret settings to copy in production' + ;; + preview) + echo 'no secret settings to copy in preview' + ;; + *) echo 'usage: bash deploy/cloudflare/sync-secrets.sh [--dry-run] (environments: production, preview)' >&2; exit 2 ;; +esac diff --git a/packs/cloudflare/typescript/test/golden/cloudflare-pages-site/deploy/cloudflare/unexpressed.md b/packs/cloudflare/typescript/test/golden/cloudflare-pages-site/deploy/cloudflare/unexpressed.md new file mode 100644 index 000000000..18f5e70df --- /dev/null +++ b/packs/cloudflare/typescript/test/golden/cloudflare-pages-site/deploy/cloudflare/unexpressed.md @@ -0,0 +1,24 @@ + + +# What the deploy scripts do not hold: app.client acme::docs::Docs.site + +Facts the model declares that Cloudflare's configuration cannot carry, or that it leaves to +something else, each with how it is carried instead. Generated from the model: change the +model, not this file. + +## production + +From deployment.pages `acme::docs::siteProduction`. + +| Fact | How it is carried | +|---|---| +| Build-time settings `SITE_URL` | Read by the build, which runs on the deploying machine: deploy/cloudflare/deploy.sh exports each one the model gives a value (a value already in the environment wins) and runs the build there. They never reach Cloudflare as settings. | +| Custom domains `docs.example.com` | Attached to the Pages project once, in the project's settings; an upload does not change them. deploy/cloudflare/doctor.sh checks each answers. | + +## preview + +From deployment.pages `acme::docs::sitePreview`. + +| Fact | How it is carried | +|---|---| +| Build-time settings `SITE_URL` | Read by the build, which runs on the deploying machine: deploy/cloudflare/deploy.sh exports each one the model gives a value (a value already in the environment wins) and runs the build there. They never reach Cloudflare as settings. | diff --git a/packs/cloudflare/typescript/test/golden/cloudflare-pages-site/deploy/cloudflare/wrangler.sh b/packs/cloudflare/typescript/test/golden/cloudflare-pages-site/deploy/cloudflare/wrangler.sh new file mode 100644 index 000000000..1e1f5154c --- /dev/null +++ b/packs/cloudflare/typescript/test/golden/cloudflare-pages-site/deploy/cloudflare/wrangler.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# @generated by @metaobjectsdev/pack-cloudflare (cloudflare-wrangler) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +# Runs wrangler 4.168.0 (WRANGLER_VERSION overrides) for app.client acme::docs::Docs.site, as the narrow +# Cloudflare API token of one environment's deployment. The token and CLOUDFLARE_ACCOUNT_ID are read +# from the vault with keys-axi. The global-key variables (CLOUDFLARE_EMAIL, CLOUDFLARE_API_KEY) are unset +# so Wrangler cannot fall back to them, and so is any CLOUDFLARE_API_TOKEN the shell holds; the vault's token then becomes CLOUDFLARE_API_TOKEN. +# +# Needs: keys-axi (KEYS_AXI overrides where it is) and npx. +# +# bash deploy/cloudflare/wrangler.sh ... +set -euo pipefail +cd "$(dirname "$0")/../.." + +ENVIRONMENT="${1:-}" +[ "$#" -gt 0 ] && shift +WRANGLER_VERSION="${WRANGLER_VERSION:-4.168.0}" +KEYS_AXI="${KEYS_AXI:-$(command -v keys-axi || echo "$HOME/.local/bin/keys-axi")}" + +case "$ENVIRONMENT" in + production) + VAULT_PROJECT=acme-deploy VAULT_ENV=dev TOKEN=ACME_PAGES_TOKEN + ;; + preview) + VAULT_PROJECT=acme-deploy VAULT_ENV=dev TOKEN=ACME_PAGES_TOKEN + ;; + *) echo 'usage: bash deploy/cloudflare/wrangler.sh ... (environments: production, preview)' >&2; exit 2 ;; +esac + +# shellcheck disable=SC2016 # the inner shell expands them: the token never enters this one +exec env -u CLOUDFLARE_EMAIL -u CLOUDFLARE_API_KEY -u CLOUDFLARE_API_TOKEN \ + "$KEYS_AXI" run --project "$VAULT_PROJECT" --env "$VAULT_ENV" --only "$TOKEN" CLOUDFLARE_ACCOUNT_ID -- \ + bash -c ' + set -euo pipefail + [ -n "${!1:-}" ] || { echo "wrangler.sh: the deploy token $1 is empty or is not in the vault scope" >&2; exit 1; } + export CLOUDFLARE_API_TOKEN="${!1}" + [ "$1" = CLOUDFLARE_API_TOKEN ] || unset "$1" + : "${CLOUDFLARE_ACCOUNT_ID:?CLOUDFLARE_ACCOUNT_ID is not in the vault scope}" + version="$2" + shift 2 + exec npx --yes "wrangler@$version" "$@" + ' wrangler "$TOKEN" "$WRANGLER_VERSION" "$@" diff --git a/packs/cloudflare/typescript/test/golden/cloudflare-worker-cron-ratelimits/deploy/cloudflare/deploy.sh b/packs/cloudflare/typescript/test/golden/cloudflare-worker-cron-ratelimits/deploy/cloudflare/deploy.sh new file mode 100644 index 000000000..f255b40bf --- /dev/null +++ b/packs/cloudflare/typescript/test/golden/cloudflare-worker-cron-ratelimits/deploy/cloudflare/deploy.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# @generated by @metaobjectsdev/pack-cloudflare (cloudflare-deploy) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +# Deploys app.service acme::trips::Trips.web to one environment, from the model: +# 1. builds it (`pnpm build`, skipped with --no-build), +# 2. copies its secrets from the vault (deploy/cloudflare/sync-secrets.sh, skipped with --no-secrets), +# 3. runs `wrangler deploy` with the environment's block of wrangler.jsonc. +# +# Needs: what deploy/cloudflare/wrangler.sh needs. +# +# bash deploy/cloudflare/deploy.sh [--no-build] [--no-secrets] +set -euo pipefail +cd "$(dirname "$0")/../.." + +ENVIRONMENT="${1:-}" +BUILD=1; SECRETS=1 +for arg in "${@:2}"; do + case "$arg" in + --no-build) BUILD=0 ;; + --no-secrets) SECRETS=0 ;; + *) echo 'usage: bash deploy/cloudflare/deploy.sh [--no-build] [--no-secrets]' >&2; exit 2 ;; + esac +done +case "$ENVIRONMENT" in production) ;; *) echo 'usage: bash deploy/cloudflare/deploy.sh [--no-build] [--no-secrets] (environments: production)' >&2; exit 2 ;; esac + +if [ "$BUILD" = 1 ]; then + # build.static client @command + pnpm build +fi +if [ "$SECRETS" = 1 ]; then bash deploy/cloudflare/sync-secrets.sh "$ENVIRONMENT"; fi + +case "$ENVIRONMENT" in + production) + bash deploy/cloudflare/wrangler.sh "$ENVIRONMENT" deploy --config wrangler.jsonc + ;; + *) echo 'usage: bash deploy/cloudflare/deploy.sh [--no-build] [--no-secrets] (environments: production)' >&2; exit 2 ;; +esac diff --git a/packs/cloudflare/typescript/test/golden/cloudflare-worker-cron-ratelimits/deploy/cloudflare/doctor.sh b/packs/cloudflare/typescript/test/golden/cloudflare-worker-cron-ratelimits/deploy/cloudflare/doctor.sh new file mode 100644 index 000000000..9b36fe964 --- /dev/null +++ b/packs/cloudflare/typescript/test/golden/cloudflare-worker-cron-ratelimits/deploy/cloudflare/doctor.sh @@ -0,0 +1,71 @@ +#!/usr/bin/env bash +# @generated by @metaobjectsdev/pack-cloudflare (cloudflare-doctor) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +# Checks app.service acme::trips::Trips.web on Cloudflare against the model, for one environment, by name only: +# the deploy token and account id are in the vault; every secret the model declares is in the vault +# and on the Worker; wrangler.jsonc builds (`wrangler deploy --dry-run`); each domain answers. +# Exits 1 when a check fails. It prints names, never a value. +# +# Needs: keys-axi, jq, curl, and what deploy/cloudflare/wrangler.sh needs. +# +# bash deploy/cloudflare/doctor.sh +set -uo pipefail +cd "$(dirname "$0")/../.." || exit 2 + +ENVIRONMENT="${1:-}" +FAIL=0 +ok() { echo "ok $*"; } +bad() { echo "FAIL $*"; FAIL=1; } +KEYS_AXI="${KEYS_AXI:-$(command -v keys-axi || echo "$HOME/.local/bin/keys-axi")}" +[ -x "$KEYS_AXI" ] || { echo "doctor: keys-axi is not installed" >&2; exit 2; } +for tool in jq curl npx; do + command -v "$tool" >/dev/null || { echo "doctor: $tool is not installed" >&2; exit 2; } +done + +# in_vault ... +in_vault() { + local names + names=$("$KEYS_AXI" ls --project "$1" --env "$2" --json | jq -r '.secrets[].name') || { bad "cannot list vault scope $1/$2"; return; } + local where="$1/$2"; shift 2 + for n in "$@"; do + if grep -Fxq -e "$n" <<<"$names"; then ok "$n is in the vault ($where)"; else bad "$n is not in the vault ($where)"; fi + done +} + +# on_cloudflare '' ... +on_cloudflare() { + local names + # shellcheck disable=SC2086 # the target arguments are words + names=$(bash deploy/cloudflare/wrangler.sh "$ENVIRONMENT" secret list $1 --format json | jq -r '.[].name') || { bad "cannot list the Worker's secrets"; return; } + shift + for n in "$@"; do + if grep -Fxq -e "$n" <<<"$names"; then ok "$n is set on the Worker"; else bad "$n is declared and not set on the Worker (run deploy/cloudflare/sync-secrets.sh)"; fi + done +} + +# builds '': the configuration and the Worker bundle build +builds() { + local out + out=$(mktemp -d) + # shellcheck disable=SC2086 # the target arguments are words + if bash deploy/cloudflare/wrangler.sh "$ENVIRONMENT" deploy --dry-run --outdir "$out" $1 >/dev/null 2>&1; then ok "wrangler.jsonc builds ($ENVIRONMENT)"; else bad "wrangler.jsonc does not build ($ENVIRONMENT): run wrangler deploy --dry-run to see why"; fi + rm -rf "$out" +} + +# answers +answers() { + if curl -fsS -o /dev/null --max-time 10 "$1"; then ok "$1 answers"; else bad "$1 does not answer 2xx"; fi +} + +case "$ENVIRONMENT" in + production) + in_vault acme-deploy dev ACME_WORKERS_TOKEN CLOUDFLARE_ACCOUNT_ID + in_vault trips prod SESSION_SECRET RESEND_API_KEY PASSPHRASE_PEPPER RECOVERY_ENC_KEY RECOVERY_HMAC_KEY + on_cloudflare '--config wrangler.jsonc' SESSION_SECRET RESEND_API_KEY PASSPHRASE_PEPPER RECOVERY_ENC_KEY RECOVERY_HMAC_KEY + builds '--config wrangler.jsonc' + answers https://trips.example.com/ + answers https://www.trips.example.com/ + ;; + *) echo 'usage: bash deploy/cloudflare/doctor.sh (environments: production)' >&2; exit 2 ;; +esac + +exit "$FAIL" diff --git a/packs/cloudflare/typescript/test/golden/cloudflare-worker-cron-ratelimits/deploy/cloudflare/sync-secrets.sh b/packs/cloudflare/typescript/test/golden/cloudflare-worker-cron-ratelimits/deploy/cloudflare/sync-secrets.sh new file mode 100644 index 000000000..fe2d537e3 --- /dev/null +++ b/packs/cloudflare/typescript/test/golden/cloudflare-worker-cron-ratelimits/deploy/cloudflare/sync-secrets.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# @generated by @metaobjectsdev/pack-cloudflare (cloudflare-sync-secrets) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +# Copies every secret setting app.service acme::trips::Trips.web reads from the vault to Cloudflare, for one environment. +# A value goes from keys-axi's environment through a pipe into `wrangler secret put`: +# it is never printed and never on a command line. +# +# Needs: keys-axi (an identity that may read the vault scope) and what deploy/cloudflare/wrangler.sh needs. +# +# bash deploy/cloudflare/sync-secrets.sh [--dry-run] +set -euo pipefail +cd "$(dirname "$0")/../.." + +ENVIRONMENT="${1:-}" +DRY_RUN=0 +for arg in "${@:2}"; do + case "$arg" in + --dry-run) DRY_RUN=1 ;; + *) echo 'usage: bash deploy/cloudflare/sync-secrets.sh [--dry-run]' >&2; exit 2 ;; + esac +done +KEYS_AXI="${KEYS_AXI:-$(command -v keys-axi || echo "$HOME/.local/bin/keys-axi")}" + +# copy +copy() { + if [ "$DRY_RUN" = 1 ]; then echo "would copy $3 from $1/$2 to Cloudflare ($ENVIRONMENT)"; return; fi + # shellcheck disable=SC2016 # the inner shell expands it: the value never enters this one + "$KEYS_AXI" run --project "$1" --env "$2" --only "$3" -- bash -c ' + [ -n "${!1+set}" ] || { echo "sync-secrets: $1 is not in the vault scope" >&2; exit 1; } + value="${!1}" + unset "$1" + printf %s "$value" | bash deploy/cloudflare/wrangler.sh "$2" secret put "$1" $3 >/dev/null + ' sync-secret "$3" "$ENVIRONMENT" "$4" + echo "copied $3 to Cloudflare ($ENVIRONMENT)" +} + +case "$ENVIRONMENT" in + production) + copy trips prod SESSION_SECRET '--config wrangler.jsonc' + copy trips prod RESEND_API_KEY '--config wrangler.jsonc' + copy trips prod PASSPHRASE_PEPPER '--config wrangler.jsonc' + copy trips prod RECOVERY_ENC_KEY '--config wrangler.jsonc' + copy trips prod RECOVERY_HMAC_KEY '--config wrangler.jsonc' + ;; + *) echo 'usage: bash deploy/cloudflare/sync-secrets.sh [--dry-run] (environments: production)' >&2; exit 2 ;; +esac diff --git a/packs/cloudflare/typescript/test/golden/cloudflare-worker-cron-ratelimits/deploy/cloudflare/unexpressed.md b/packs/cloudflare/typescript/test/golden/cloudflare-worker-cron-ratelimits/deploy/cloudflare/unexpressed.md new file mode 100644 index 000000000..5b0b6dffa --- /dev/null +++ b/packs/cloudflare/typescript/test/golden/cloudflare-worker-cron-ratelimits/deploy/cloudflare/unexpressed.md @@ -0,0 +1,16 @@ + + +# What `wrangler.jsonc` does not hold: app.service acme::trips::Trips.web + +Facts the model declares that Cloudflare's configuration cannot carry, or that it leaves to +something else, each with how it is carried instead. Generated from the model: change the +model, not this file. + +## production + +From deployment.worker `acme::trips::webProduction`. + +| Fact | How it is carried | +|---|---| +| Secret values: `SESSION_SECRET`, `RESEND_API_KEY`, `PASSPHRASE_PEPPER`, `RECOVERY_ENC_KEY`, `RECOVERY_HMAC_KEY` | Never in a file. deploy/cloudflare/sync-secrets.sh copies them from the vault scope `trips/prod`; deploy/cloudflare/doctor.sh checks the names are in the vault and on Cloudflare. | +| DNS for `trips.example.com`, `www.trips.example.com` | Each domain is a custom domain route: Cloudflare creates its DNS record and certificate on deploy. The domain's zone must be on the same Cloudflare account. | diff --git a/packs/cloudflare/typescript/test/golden/cloudflare-worker-cron-ratelimits/deploy/cloudflare/wrangler.sh b/packs/cloudflare/typescript/test/golden/cloudflare-worker-cron-ratelimits/deploy/cloudflare/wrangler.sh new file mode 100644 index 000000000..257008f58 --- /dev/null +++ b/packs/cloudflare/typescript/test/golden/cloudflare-worker-cron-ratelimits/deploy/cloudflare/wrangler.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# @generated by @metaobjectsdev/pack-cloudflare (cloudflare-wrangler) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +# Runs wrangler 4.168.0 (WRANGLER_VERSION overrides) for app.service acme::trips::Trips.web, as the narrow +# Cloudflare API token of one environment's deployment. The token and CLOUDFLARE_ACCOUNT_ID are read +# from the vault with keys-axi. The global-key variables (CLOUDFLARE_EMAIL, CLOUDFLARE_API_KEY) are unset +# so Wrangler cannot fall back to them, and so is any CLOUDFLARE_API_TOKEN the shell holds; the vault's token then becomes CLOUDFLARE_API_TOKEN. +# +# Needs: keys-axi (KEYS_AXI overrides where it is) and npx. +# +# bash deploy/cloudflare/wrangler.sh ... +set -euo pipefail +cd "$(dirname "$0")/../.." + +ENVIRONMENT="${1:-}" +[ "$#" -gt 0 ] && shift +WRANGLER_VERSION="${WRANGLER_VERSION:-4.168.0}" +KEYS_AXI="${KEYS_AXI:-$(command -v keys-axi || echo "$HOME/.local/bin/keys-axi")}" + +case "$ENVIRONMENT" in + production) + VAULT_PROJECT=acme-deploy VAULT_ENV=dev TOKEN=ACME_WORKERS_TOKEN + ;; + *) echo 'usage: bash deploy/cloudflare/wrangler.sh ... (environments: production)' >&2; exit 2 ;; +esac + +# shellcheck disable=SC2016 # the inner shell expands them: the token never enters this one +exec env -u CLOUDFLARE_EMAIL -u CLOUDFLARE_API_KEY -u CLOUDFLARE_API_TOKEN \ + "$KEYS_AXI" run --project "$VAULT_PROJECT" --env "$VAULT_ENV" --only "$TOKEN" CLOUDFLARE_ACCOUNT_ID -- \ + bash -c ' + set -euo pipefail + [ -n "${!1:-}" ] || { echo "wrangler.sh: the deploy token $1 is empty or is not in the vault scope" >&2; exit 1; } + export CLOUDFLARE_API_TOKEN="${!1}" + [ "$1" = CLOUDFLARE_API_TOKEN ] || unset "$1" + : "${CLOUDFLARE_ACCOUNT_ID:?CLOUDFLARE_ACCOUNT_ID is not in the vault scope}" + version="$2" + shift 2 + exec npx --yes "wrangler@$version" "$@" + ' wrangler "$TOKEN" "$WRANGLER_VERSION" "$@" diff --git a/packs/cloudflare/typescript/test/golden/cloudflare-worker-cron-ratelimits/wrangler.jsonc b/packs/cloudflare/typescript/test/golden/cloudflare-worker-cron-ratelimits/wrangler.jsonc new file mode 100644 index 000000000..06f2121d1 --- /dev/null +++ b/packs/cloudflare/typescript/test/golden/cloudflare-worker-cron-ratelimits/wrangler.jsonc @@ -0,0 +1,123 @@ +// @generated by @metaobjectsdev/pack-cloudflare (wrangler-config) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Wrangler configuration for app.service acme::trips::Trips.web, from the model. `wrangler deploy` deploys production; +// it is the only environment. Deploy with deploy/cloudflare/deploy.sh . +{ + "$schema": "./node_modules/wrangler/config-schema.json", + // deployment.worker acme::trips::webProduction: environment production + "name": "trips", + // @main + "main": "src/worker.ts", + // @compatibilityDate + "compatibility_date": "2026-07-01", + // @compatibilityFlags + "compatibility_flags": ["nodejs_compat"], + // @workersDev + "workers_dev": false, + // @domains: each a custom domain, its DNS record and certificate made by Cloudflare + "routes": [ + { + "pattern": "trips.example.com", + "custom_domain": true + }, + { + "pattern": "www.trips.example.com", + "custom_domain": true + } + ], + // the app's build.static client @directory + "assets": { + "directory": "./dist/client", + // @assetsBinding + "binding": "ASSETS", + // @notFound + "not_found_handling": "single-page-application", + // @workerFirst + "run_worker_first": true + }, + // app.job acme::trips::Trips.coverCleanup @schedule + "triggers": { + "crons": ["0 4 * * *"] + }, + // the app's non-secret runtime settings (@settings) + "vars": { + // value.literal teamDomain + "ACCESS_TEAM_DOMAIN": "team.example.com", + // value.literal aud + "ACCESS_AUD": "0000000000000000000000000000000000000000000000000000000000000000", + // value.literal notifyEmail + "NOTIFY_EMAIL": "host@example.com" + }, + // the app's @secret runtime settings: values from the vault, copied by deploy/cloudflare/sync-secrets.sh + "secrets": { + "required": ["SESSION_SECRET", "RESEND_API_KEY", "PASSPHRASE_PEPPER", "RECOVERY_ENC_KEY", "RECOVERY_HMAC_KEY"] + }, + // cloudflare.d1 db + "d1_databases": [ + { + "binding": "DB", + "database_name": "trips", + "database_id": "00000000-0000-4000-8000-000000000003", + "migrations_dir": ".metaobjects/migrations" + } + ], + // no cloudflare.kv binding + "kv_namespaces": [], + // cloudflare.r2 photos + "r2_buckets": [ + { + "binding": "PHOTOS", + "bucket_name": "trips-photos" + } + ], + // no cloudflare.queue binding + "queues": { + "producers": [] + }, + // cloudflare.ratelimit enterLimiter + // cloudflare.ratelimit adminLimiter + // cloudflare.ratelimit loginLimiter + // cloudflare.ratelimit loginLockoutLimiter + // cloudflare.ratelimit recoveryLimiter + "ratelimits": [ + { + "name": "ENTER_LIMITER", + "namespace_id": "1001", + "simple": { + "limit": 10, + "period": 60 + } + }, + { + "name": "ADMIN_LIMITER", + "namespace_id": "1002", + "simple": { + "limit": 200, + "period": 60 + } + }, + { + "name": "LOGIN_LIMITER", + "namespace_id": "1003", + "simple": { + "limit": 10, + "period": 60 + } + }, + { + "name": "LOGIN_LOCKOUT_LIMITER", + "namespace_id": "1004", + "simple": { + "limit": 4, + "period": 60 + } + }, + { + "name": "RECOVERY_LIMITER", + "namespace_id": "1005", + "simple": { + "limit": 3, + "period": 60 + } + } + ] +} diff --git a/packs/cloudflare/typescript/test/golden/cloudflare-worker-environments/deploy/cloudflare/deploy.sh b/packs/cloudflare/typescript/test/golden/cloudflare-worker-environments/deploy/cloudflare/deploy.sh new file mode 100644 index 000000000..a974be94e --- /dev/null +++ b/packs/cloudflare/typescript/test/golden/cloudflare-worker-environments/deploy/cloudflare/deploy.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# @generated by @metaobjectsdev/pack-cloudflare (cloudflare-deploy) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +# Deploys app.service acme::quiz::Quiz.site to one environment, from the model: +# 1. copies its secrets from the vault (deploy/cloudflare/sync-secrets.sh, skipped with --no-secrets), +# 2. runs `wrangler deploy` with the environment's block of wrangler.jsonc. +# +# Needs: what deploy/cloudflare/wrangler.sh needs. +# +# bash deploy/cloudflare/deploy.sh [--no-secrets] +set -euo pipefail +cd "$(dirname "$0")/../.." + +ENVIRONMENT="${1:-}" +SECRETS=1 +for arg in "${@:2}"; do + case "$arg" in + --no-secrets) SECRETS=0 ;; + *) echo 'usage: bash deploy/cloudflare/deploy.sh [--no-secrets]' >&2; exit 2 ;; + esac +done +case "$ENVIRONMENT" in production|staging) ;; *) echo 'usage: bash deploy/cloudflare/deploy.sh [--no-secrets] (environments: production, staging)' >&2; exit 2 ;; esac + +if [ "$SECRETS" = 1 ]; then bash deploy/cloudflare/sync-secrets.sh "$ENVIRONMENT"; fi + +case "$ENVIRONMENT" in + production) + bash deploy/cloudflare/wrangler.sh "$ENVIRONMENT" deploy --config wrangler.jsonc + ;; + staging) + bash deploy/cloudflare/wrangler.sh "$ENVIRONMENT" deploy --config wrangler.jsonc --env staging + ;; + *) echo 'usage: bash deploy/cloudflare/deploy.sh [--no-secrets] (environments: production, staging)' >&2; exit 2 ;; +esac diff --git a/packs/cloudflare/typescript/test/golden/cloudflare-worker-environments/deploy/cloudflare/doctor.sh b/packs/cloudflare/typescript/test/golden/cloudflare-worker-environments/deploy/cloudflare/doctor.sh new file mode 100644 index 000000000..5e6cb3dce --- /dev/null +++ b/packs/cloudflare/typescript/test/golden/cloudflare-worker-environments/deploy/cloudflare/doctor.sh @@ -0,0 +1,78 @@ +#!/usr/bin/env bash +# @generated by @metaobjectsdev/pack-cloudflare (cloudflare-doctor) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +# Checks app.service acme::quiz::Quiz.site on Cloudflare against the model, for one environment, by name only: +# the deploy token and account id are in the vault; every secret the model declares is in the vault +# and on the Worker; wrangler.jsonc builds (`wrangler deploy --dry-run`); each domain answers. +# Exits 1 when a check fails. It prints names, never a value. +# +# Needs: keys-axi, jq, curl, and what deploy/cloudflare/wrangler.sh needs. +# +# bash deploy/cloudflare/doctor.sh +set -uo pipefail +cd "$(dirname "$0")/../.." || exit 2 + +ENVIRONMENT="${1:-}" +FAIL=0 +ok() { echo "ok $*"; } +bad() { echo "FAIL $*"; FAIL=1; } +KEYS_AXI="${KEYS_AXI:-$(command -v keys-axi || echo "$HOME/.local/bin/keys-axi")}" +[ -x "$KEYS_AXI" ] || { echo "doctor: keys-axi is not installed" >&2; exit 2; } +for tool in jq curl npx; do + command -v "$tool" >/dev/null || { echo "doctor: $tool is not installed" >&2; exit 2; } +done + +# in_vault ... +in_vault() { + local names + names=$("$KEYS_AXI" ls --project "$1" --env "$2" --json | jq -r '.secrets[].name') || { bad "cannot list vault scope $1/$2"; return; } + local where="$1/$2"; shift 2 + for n in "$@"; do + if grep -Fxq -e "$n" <<<"$names"; then ok "$n is in the vault ($where)"; else bad "$n is not in the vault ($where)"; fi + done +} + +# on_cloudflare '' ... +on_cloudflare() { + local names + # shellcheck disable=SC2086 # the target arguments are words + names=$(bash deploy/cloudflare/wrangler.sh "$ENVIRONMENT" secret list $1 --format json | jq -r '.[].name') || { bad "cannot list the Worker's secrets"; return; } + shift + for n in "$@"; do + if grep -Fxq -e "$n" <<<"$names"; then ok "$n is set on the Worker"; else bad "$n is declared and not set on the Worker (run deploy/cloudflare/sync-secrets.sh)"; fi + done +} + +# builds '': the configuration and the Worker bundle build +builds() { + local out + out=$(mktemp -d) + # shellcheck disable=SC2086 # the target arguments are words + if bash deploy/cloudflare/wrangler.sh "$ENVIRONMENT" deploy --dry-run --outdir "$out" $1 >/dev/null 2>&1; then ok "wrangler.jsonc builds ($ENVIRONMENT)"; else bad "wrangler.jsonc does not build ($ENVIRONMENT): run wrangler deploy --dry-run to see why"; fi + rm -rf "$out" +} + +# answers +answers() { + if curl -fsS -o /dev/null --max-time 10 "$1"; then ok "$1 answers"; else bad "$1 does not answer 2xx"; fi +} + +case "$ENVIRONMENT" in + production) + in_vault acme-deploy dev ACME_WORKERS_TOKEN CLOUDFLARE_ACCOUNT_ID + in_vault quiz prod SEARCH_URL + on_cloudflare '--config wrangler.jsonc' SEARCH_URL + builds '--config wrangler.jsonc' + answers https://quiz.example.com/ + answers https://www.quiz.example.com/ + ;; + staging) + in_vault acme-deploy dev ACME_WORKERS_TOKEN CLOUDFLARE_ACCOUNT_ID + in_vault quiz staging SEARCH_URL + on_cloudflare '--config wrangler.jsonc --env staging' SEARCH_URL + builds '--config wrangler.jsonc --env staging' + answers https://staging.quiz.example.com/ + ;; + *) echo 'usage: bash deploy/cloudflare/doctor.sh (environments: production, staging)' >&2; exit 2 ;; +esac + +exit "$FAIL" diff --git a/packs/cloudflare/typescript/test/golden/cloudflare-worker-environments/deploy/cloudflare/sync-secrets.sh b/packs/cloudflare/typescript/test/golden/cloudflare-worker-environments/deploy/cloudflare/sync-secrets.sh new file mode 100644 index 000000000..eb32c6c73 --- /dev/null +++ b/packs/cloudflare/typescript/test/golden/cloudflare-worker-environments/deploy/cloudflare/sync-secrets.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +# @generated by @metaobjectsdev/pack-cloudflare (cloudflare-sync-secrets) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +# Copies every secret setting app.service acme::quiz::Quiz.site reads from the vault to Cloudflare, for one environment. +# A value goes from keys-axi's environment through a pipe into `wrangler secret put`: +# it is never printed and never on a command line. +# +# Needs: keys-axi (an identity that may read the vault scope) and what deploy/cloudflare/wrangler.sh needs. +# +# bash deploy/cloudflare/sync-secrets.sh [--dry-run] +set -euo pipefail +cd "$(dirname "$0")/../.." + +ENVIRONMENT="${1:-}" +DRY_RUN=0 +for arg in "${@:2}"; do + case "$arg" in + --dry-run) DRY_RUN=1 ;; + *) echo 'usage: bash deploy/cloudflare/sync-secrets.sh [--dry-run]' >&2; exit 2 ;; + esac +done +KEYS_AXI="${KEYS_AXI:-$(command -v keys-axi || echo "$HOME/.local/bin/keys-axi")}" + +# copy +copy() { + if [ "$DRY_RUN" = 1 ]; then echo "would copy $3 from $1/$2 to Cloudflare ($ENVIRONMENT)"; return; fi + # shellcheck disable=SC2016 # the inner shell expands it: the value never enters this one + "$KEYS_AXI" run --project "$1" --env "$2" --only "$3" -- bash -c ' + [ -n "${!1+set}" ] || { echo "sync-secrets: $1 is not in the vault scope" >&2; exit 1; } + value="${!1}" + unset "$1" + printf %s "$value" | bash deploy/cloudflare/wrangler.sh "$2" secret put "$1" $3 >/dev/null + ' sync-secret "$3" "$ENVIRONMENT" "$4" + echo "copied $3 to Cloudflare ($ENVIRONMENT)" +} + +case "$ENVIRONMENT" in + production) + copy quiz prod SEARCH_URL '--config wrangler.jsonc' + ;; + staging) + copy quiz staging SEARCH_URL '--config wrangler.jsonc --env staging' + ;; + *) echo 'usage: bash deploy/cloudflare/sync-secrets.sh [--dry-run] (environments: production, staging)' >&2; exit 2 ;; +esac diff --git a/packs/cloudflare/typescript/test/golden/cloudflare-worker-environments/deploy/cloudflare/unexpressed.md b/packs/cloudflare/typescript/test/golden/cloudflare-worker-environments/deploy/cloudflare/unexpressed.md new file mode 100644 index 000000000..c648c44d9 --- /dev/null +++ b/packs/cloudflare/typescript/test/golden/cloudflare-worker-environments/deploy/cloudflare/unexpressed.md @@ -0,0 +1,27 @@ + + +# What `wrangler.jsonc` does not hold: app.service acme::quiz::Quiz.site + +Facts the model declares that Cloudflare's configuration cannot carry, or that it leaves to +something else, each with how it is carried instead. Generated from the model: change the +model, not this file. + +## production + +From deployment.worker `acme::quiz::siteProduction`. + +| Fact | How it is carried | +|---|---| +| Secret values: `SEARCH_URL` | Never in a file. deploy/cloudflare/sync-secrets.sh copies them from the vault scope `quiz/prod`; deploy/cloudflare/doctor.sh checks the names are in the vault and on Cloudflare. | +| @branch `main` | Deploys run from deploy/cloudflare/deploy.sh, not on a push to the branch, so no file holds it. | +| DNS for `quiz.example.com`, `www.quiz.example.com` | Each domain is a custom domain route: Cloudflare creates its DNS record and certificate on deploy. The domain's zone must be on the same Cloudflare account. | + +## staging + +From deployment.worker `acme::quiz::siteStaging`. + +| Fact | How it is carried | +|---|---| +| Secret values: `SEARCH_URL` | Never in a file. deploy/cloudflare/sync-secrets.sh copies them from the vault scope `quiz/staging`; deploy/cloudflare/doctor.sh checks the names are in the vault and on Cloudflare. | +| @branch `staging` | Deploys run from deploy/cloudflare/deploy.sh, not on a push to the branch, so no file holds it. | +| DNS for `staging.quiz.example.com` | Each domain is a custom domain route: Cloudflare creates its DNS record and certificate on deploy. The domain's zone must be on the same Cloudflare account. | diff --git a/packs/cloudflare/typescript/test/golden/cloudflare-worker-environments/deploy/cloudflare/wrangler.sh b/packs/cloudflare/typescript/test/golden/cloudflare-worker-environments/deploy/cloudflare/wrangler.sh new file mode 100644 index 000000000..0b8fb3708 --- /dev/null +++ b/packs/cloudflare/typescript/test/golden/cloudflare-worker-environments/deploy/cloudflare/wrangler.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# @generated by @metaobjectsdev/pack-cloudflare (cloudflare-wrangler) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +# Runs wrangler 4.168.0 (WRANGLER_VERSION overrides) for app.service acme::quiz::Quiz.site, as the narrow +# Cloudflare API token of one environment's deployment. The token and CLOUDFLARE_ACCOUNT_ID are read +# from the vault with keys-axi. The global-key variables (CLOUDFLARE_EMAIL, CLOUDFLARE_API_KEY) are unset +# so Wrangler cannot fall back to them, and so is any CLOUDFLARE_API_TOKEN the shell holds; the vault's token then becomes CLOUDFLARE_API_TOKEN. +# +# Needs: keys-axi (KEYS_AXI overrides where it is) and npx. +# +# bash deploy/cloudflare/wrangler.sh ... +set -euo pipefail +cd "$(dirname "$0")/../.." + +ENVIRONMENT="${1:-}" +[ "$#" -gt 0 ] && shift +WRANGLER_VERSION="${WRANGLER_VERSION:-4.168.0}" +KEYS_AXI="${KEYS_AXI:-$(command -v keys-axi || echo "$HOME/.local/bin/keys-axi")}" + +case "$ENVIRONMENT" in + production) + VAULT_PROJECT=acme-deploy VAULT_ENV=dev TOKEN=ACME_WORKERS_TOKEN + ;; + staging) + VAULT_PROJECT=acme-deploy VAULT_ENV=dev TOKEN=ACME_WORKERS_TOKEN + ;; + *) echo 'usage: bash deploy/cloudflare/wrangler.sh ... (environments: production, staging)' >&2; exit 2 ;; +esac + +# shellcheck disable=SC2016 # the inner shell expands them: the token never enters this one +exec env -u CLOUDFLARE_EMAIL -u CLOUDFLARE_API_KEY -u CLOUDFLARE_API_TOKEN \ + "$KEYS_AXI" run --project "$VAULT_PROJECT" --env "$VAULT_ENV" --only "$TOKEN" CLOUDFLARE_ACCOUNT_ID -- \ + bash -c ' + set -euo pipefail + [ -n "${!1:-}" ] || { echo "wrangler.sh: the deploy token $1 is empty or is not in the vault scope" >&2; exit 1; } + export CLOUDFLARE_API_TOKEN="${!1}" + [ "$1" = CLOUDFLARE_API_TOKEN ] || unset "$1" + : "${CLOUDFLARE_ACCOUNT_ID:?CLOUDFLARE_ACCOUNT_ID is not in the vault scope}" + version="$2" + shift 2 + exec npx --yes "wrangler@$version" "$@" + ' wrangler "$TOKEN" "$WRANGLER_VERSION" "$@" diff --git a/packs/cloudflare/typescript/test/golden/cloudflare-worker-environments/wrangler.jsonc b/packs/cloudflare/typescript/test/golden/cloudflare-worker-environments/wrangler.jsonc new file mode 100644 index 000000000..cb41e9e21 --- /dev/null +++ b/packs/cloudflare/typescript/test/golden/cloudflare-worker-environments/wrangler.jsonc @@ -0,0 +1,156 @@ +// @generated by @metaobjectsdev/pack-cloudflare (wrangler-config) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Wrangler configuration for app.service acme::quiz::Quiz.site, from the model. `wrangler deploy` deploys production; +// `wrangler deploy --env ` deploys staging. Deploy with deploy/cloudflare/deploy.sh . +{ + "$schema": "./node_modules/wrangler/config-schema.json", + // deployment.worker acme::quiz::siteProduction: environment production + "name": "quiz", + // @main + "main": "src/index.ts", + // @compatibilityDate + "compatibility_date": "2024-12-30", + // @compatibilityFlags + "compatibility_flags": ["nodejs_compat"], + // @domains: each a custom domain, its DNS record and certificate made by Cloudflare + "routes": [ + { + "pattern": "quiz.example.com", + "custom_domain": true + }, + { + "pattern": "www.quiz.example.com", + "custom_domain": true + } + ], + // the app's build.static assets @directory + "assets": { + "directory": "./public", + // @assetsBinding + "binding": "ASSETS", + // @notFound + "not_found_handling": "single-page-application", + // @workerFirstPaths + "run_worker_first": ["/api/*", "/c/*"] + }, + // @jobs: none, so no cron triggers + "triggers": { + "crons": [] + }, + // the app's non-secret runtime settings (@settings) + "vars": { + // acme::quiz::Limits.maxQuestionsPerDay @default + "MAX_QUESTIONS_PER_DAY": "5", + // acme::quiz::Limits.globalMaxPerDay @default + "GLOBAL_MAX_PER_DAY": "200", + // acme::quiz::Limits.ipMaxPerDay @default + "IP_MAX_PER_DAY": "10", + // acme::quiz::Limits.killSwitch @default + "KILL_SWITCH": "off", + // value.literal siteKey (from siteBase) + "TURNSTILE_SITE_KEY": "1x00000000000000000000AA" + }, + // the app's @secret runtime settings: values from the vault, copied by deploy/cloudflare/sync-secrets.sh + "secrets": { + "required": ["SEARCH_URL"] + }, + // cloudflare.d1 db (from siteBase) + "d1_databases": [ + { + "binding": "DB", + "database_name": "quiz", + "database_id": "00000000-0000-4000-8000-000000000001", + "migrations_dir": "migrations" + } + ], + // cloudflare.kv rateLimit (from siteBase) + "kv_namespaces": [ + { + "binding": "RATE_LIMIT", + "id": "00000000000000000000000000000001" + } + ], + // no cloudflare.r2 binding + "r2_buckets": [], + // no cloudflare.queue binding + "queues": { + "producers": [] + }, + // no cloudflare.ratelimit binding + "ratelimits": [], + // Every environment is written in full: Wrangler does not inherit vars, secrets or bindings into an env block. + "env": { + // `wrangler deploy --env staging` + "staging": { + // deployment.worker acme::quiz::siteStaging: environment staging + "name": "quiz-staging", + // @main + "main": "src/index.ts", + // @compatibilityDate + "compatibility_date": "2024-12-30", + // @compatibilityFlags + "compatibility_flags": ["nodejs_compat"], + // @domains: each a custom domain, its DNS record and certificate made by Cloudflare + "routes": [ + { + "pattern": "staging.quiz.example.com", + "custom_domain": true + } + ], + // the app's build.static assets @directory + "assets": { + "directory": "./public", + // @assetsBinding + "binding": "ASSETS", + // @notFound + "not_found_handling": "single-page-application", + // @workerFirstPaths + "run_worker_first": ["/api/*", "/c/*"] + }, + // @jobs: none, so no cron triggers + "triggers": { + "crons": [] + }, + // the app's non-secret runtime settings (@settings) + "vars": { + // acme::quiz::Limits.maxQuestionsPerDay @default + "MAX_QUESTIONS_PER_DAY": "5", + // acme::quiz::Limits.globalMaxPerDay @default + "GLOBAL_MAX_PER_DAY": "200", + // acme::quiz::Limits.ipMaxPerDay @default + "IP_MAX_PER_DAY": "10", + // value.literal killSwitch + "KILL_SWITCH": "on", + // value.literal siteKey (from siteBase) + "TURNSTILE_SITE_KEY": "1x00000000000000000000AA" + }, + // the app's @secret runtime settings: values from the vault, copied by deploy/cloudflare/sync-secrets.sh + "secrets": { + "required": ["SEARCH_URL"] + }, + // cloudflare.d1 db + "d1_databases": [ + { + "binding": "DB", + "database_name": "quiz-staging", + "database_id": "00000000-0000-4000-8000-000000000002", + "migrations_dir": "migrations" + } + ], + // cloudflare.kv rateLimit + "kv_namespaces": [ + { + "binding": "RATE_LIMIT", + "id": "00000000000000000000000000000002" + } + ], + // no cloudflare.r2 binding + "r2_buckets": [], + // no cloudflare.queue binding + "queues": { + "producers": [] + }, + // no cloudflare.ratelimit binding + "ratelimits": [] + } + } +} diff --git a/packs/cloudflare/typescript/test/model.test.ts b/packs/cloudflare/typescript/test/model.test.ts new file mode 100644 index 000000000..72ccbc7b2 --- /dev/null +++ b/packs/cloudflare/typescript/test/model.test.ts @@ -0,0 +1,426 @@ +// What the model reader does with each fixture, and what it refuses: every refusal names the +// node, and every problem in a model is reported at once. +import { describe, expect, test } from "bun:test"; +import { CloudflareModelError, parseGeneratedJsonc, readCloudflare, type PagesDeployment, type WorkerDeployment } from "../src/index.js"; +import { editFixture, emit, loadModels, type Source } from "./model.js"; +import { wranglerSchemaErrors } from "./wrangler-schema.js"; + +type Node = Record>; +type Root = { "metadata.root": { children: Node[] } }; + +/** The body of the root child `type` named `name`. */ +function child(root: Root, type: string, name: string): Record { + const hit = root["metadata.root"].children.find((c) => c[type]?.["name"] === name); + if (hit === undefined) throw new Error(`no ${type} ${name}`); + return hit[type]!; +} + +function children(node: Record): Node[] { + return (node["children"] ??= []) as Node[]; +} + +/** The problems reading `sources` reports, or [] when it reads clean. */ +async function problems(sources: readonly Source[], opts: Parameters[3] = {}): Promise { + const root = await loadModels(sources); + try { + readCloudflare(root, root.children().filter((c) => c.type === "object") as never, () => true, opts); + return []; + } catch (e) { + if (e instanceof CloudflareModelError) return e.problems; + throw e; + } +} + +async function read(sources: readonly Source[], opts: Parameters[3] = {}) { + const root = await loadModels(sources); + return readCloudflare(root, root.children().filter((c) => c.type === "object") as never, () => true, opts)!; +} + +const ENVS = "cloudflare-worker-environments"; +const TRIPS = "cloudflare-worker-cron-ratelimits"; +const PAGES = "cloudflare-pages-site"; +const PAGES_SECRETS = "cloudflare-pages-secrets"; + +describe("reading", () => { + test("an abstract deployment is a base, never deployed; each environment resolves what it inherits", async () => { + const app = await read(editFixture(ENVS, () => {})); + expect(app.deployments.map((d) => d.key)).toEqual(["acme::quiz::siteProduction", "acme::quiz::siteStaging"]); + const staging = app.deployments[1] as WorkerDeployment; + expect(staging.main).toBe("src/index.ts"); + expect(staging.bindings.map((b) => b.from)).toEqual(["cloudflare.d1 db", "cloudflare.kv rateLimit"]); + expect((app.deployments[0] as WorkerDeployment).bindings.map((b) => b.from)).toEqual(["cloudflare.d1 db (from siteBase)", "cloudflare.kv rateLimit (from siteBase)"]); + }); + + test("a resource managed outside Cloudflare is not bound, and is listed with how it is reached", async () => { + const sources = editFixture(TRIPS, (r) => { + const sys = child(r, "system.internal", "Trips"); + for (const c of children(sys)) if (c["resource.bucket"] !== undefined) c["resource.bucket"]["@managedBy"] = "external"; + const d = child(r, "deployment.worker", "webProduction"); + d["children"] = children(d).filter((c) => c["cloudflare.r2"] === undefined); + }); + const app = await read(sources); + const d = app.deployments[0] as WorkerDeployment; + expect(d.bindings.some((b) => b.kind === "r2")).toBe(false); + expect(d.unexpressed.map((f) => f.fact)).toContain("resource.bucket `photos`, managed outside Cloudflare"); + }); + + test("@extra keys reach the environment's block as written, and the result is still valid Wrangler", async () => { + const sources = editFixture(TRIPS, (r) => { + child(r, "deployment.worker", "webProduction")["@extra"] = JSON.stringify({ placement: { mode: "smart" }, observability: { enabled: true } }); + }); + const config = parseGeneratedJsonc((await emit(await loadModels(sources))).get("wrangler.jsonc")!) as Record; + expect(config["placement"]).toEqual({ mode: "smart" }); + expect(config["observability"]).toEqual({ enabled: true }); + expect(wranglerSchemaErrors(config)).toEqual([]); + expect(wranglerSchemaErrors({ ...config, placement: { mode: "bogus" } })).toContain("/placement/mode must be equal to one of the allowed values"); + }); + + test("a value.ref takes another Cloudflare-deployed app's publicUrl with its @path", async () => { + const sources = editFixture(TRIPS, (r) => { + children(child(r, "system.internal", "Trips")).push({ "app.service": { name: "api" } }); + children(child(r, "object.settings", "Notify")).push({ "field.string": { "name": "apiBase", "@envName": "NOTIFY_API_BASE" } }); + r["metadata.root"].children.push({ + "deployment.worker": { name: "apiProduction", "@app": "Trips.api", "@environment": "production", "@compatibilityDate": "2026-07-01", "@tokenSecret": "T", "@domains": ["api.example.com"] }, + }); + children(child(r, "deployment.worker", "webProduction")).push({ "value.ref": { name: "apiBase", "@setting": "Notify.apiBase", "@producedBy": "Trips.api", "@output": "publicUrl", "@path": "/v1" } }); + }); + const web = (await read(sources, { app: "Trips.web" })).deployments[0] as WorkerDeployment; + expect(web.vars.find((v) => v.name === "NOTIFY_API_BASE")).toEqual({ name: "NOTIFY_API_BASE", value: "https://api.example.com/v1", from: "value.ref apiBase" }); + }); + + test("a value.ref an app cannot supply is refused with what to ask it for instead", async () => { + const sources = editFixture(TRIPS, (r) => { + children(child(r, "system.internal", "Trips")).push({ + "app.service": { name: "api", "children": [{ "runtime.process": { name: "web", "@port": 8080 } }] }, + }); + children(child(r, "object.settings", "Notify")).push({ "field.string": { "name": "apiBase", "@envName": "NOTIFY_API_BASE" } }); + children(child(r, "deployment.worker", "webProduction")).push({ "value.ref": { name: "apiBase", "@setting": "Notify.apiBase", "@producedBy": "Trips.api", "@output": "port" } }); + }); + expect(await problems(sources)).toEqual([ + "deployment.worker acme::trips::webProduction value.ref apiBase: Cloudflare resolves no reference at deploy time; a value.ref can only take another Cloudflare-deployed app's host or publicUrl (from its @domains), not an app's port. Ask for its host or publicUrl, or give the setting a value.literal", + ]); + }); + + test("a Worker's @branch is held by no file and is listed; a Pages site's is carried by its upload", async () => { + const worker = await read(editFixture(ENVS, () => {})); + expect(worker.deployments.map((d) => d.unexpressed.find((f) => f.fact.startsWith("@branch")))).toEqual([ + { fact: "@branch `main`", how: "Deploys run from deploy/cloudflare/deploy.sh, not on a push to the branch, so no file holds it." }, + { fact: "@branch `staging`", how: "Deploys run from deploy/cloudflare/deploy.sh, not on a push to the branch, so no file holds it." }, + ]); + const pages = await read(editFixture(PAGES, () => {})); + expect(pages.deployments.every((d) => d.unexpressed.every((f) => !f.fact.startsWith("@branch")))).toBe(true); + }); + + test("a build-time value.literal a Pages site's deploy script exports is not listed as unexpressed", async () => { + const sources = editFixture(PAGES, (r) => { + children(child(r, "deployment.pages", "siteProduction")).push({ "value.literal": { name: "url", "@setting": "Site.url", "@literal": "https://production.docs.example.com" } }); + }); + const production = (await read(sources)).deployments[0] as PagesDeployment; + expect(production.buildVars).toEqual([{ name: "SITE_URL", value: "https://production.docs.example.com", from: "value.literal url" }]); + expect(production.unexpressed.map((f) => f.fact)).toEqual(["Build-time settings `SITE_URL`", "Custom domains `docs.example.com`"]); + }); + + test("the build-time settings row says whether the deploy script runs a build", async () => { + const fact = "Build-time settings `SITE_URL`"; + const withCommand = (await read(editFixture(PAGES, () => {}))).deployments[0]!; + expect(withCommand.unexpressed.find((f) => f.fact === fact)?.how).toBe( + "Read by the build, which runs on the deploying machine: deploy/cloudflare/deploy.sh exports each one the model gives a value (a value already in the environment wins) and runs the build there. They never reach Cloudflare as settings.", + ); + const committed = editFixture(PAGES, (r) => { + const [site] = children(child(r, "system.internal", "Docs")) as { "app.client"?: { children?: { "build.static"?: Record }[] } }[]; + const [pages] = site!["app.client"]!.children!; + delete pages!["build.static"]!["@command"]; + }); + expect((await read(committed)).deployments[0]!.unexpressed.find((f) => f.fact === fact)?.how).toBe( + "Read by whatever builds site, from the environment it runs in: deploy/cloudflare/deploy.sh runs no build (site declares no build command) and exports each one the model gives a value (a value already in the environment wins) for what it runs next. They never reach Cloudflare as settings.", + ); + const deploy = (await emit(await loadModels(committed))).get("deploy/cloudflare/deploy.sh")!; + expect(deploy.split("\n").filter((l) => l.includes("build"))).toEqual([ + "# 2. uploads the build to the environment's Pages project and branch, recording the commit.", + "# Build-time settings are read from this machine's environment by whatever builds site; deploy.sh runs no", + "# build (the app declares no build command), and exports the values the model gives first; a value already", + ]); + }); + + test("a model that deploys nothing to Cloudflare gets no files", async () => { + const sources = editFixture(TRIPS, (r) => { + r["metadata.root"].children = r["metadata.root"].children.filter((c) => c["deployment.worker"] === undefined); + }); + expect((await emit(await loadModels(sources))).size).toBe(0); + }); +}); + +describe("refusals", () => { + test("a binding for a resource the app does not need", async () => { + const sources = editFixture(TRIPS, (r) => { + children(child(r, "deployment.worker", "webProduction")).push({ "cloudflare.kv": { name: "sessions", "@namespaceId": "x" } }); + }); + expect(await problems(sources)).toEqual([ + 'deployment.worker acme::trips::webProduction cloudflare.kv sessions: web needs no resource.keyvalue named "sessions" (@needs); a binding is named after the resource it places', + ]); + }); + + test("a resource the app needs with no binding in some environment", async () => { + const sources = editFixture(TRIPS, (r) => { + const d = child(r, "deployment.worker", "webProduction"); + d["children"] = children(d).filter((c) => c["cloudflare.r2"] === undefined); + }); + expect(await problems(sources)).toEqual([ + 'deployment.worker acme::trips::webProduction: web needs resource.bucket "photos" and environment production has no cloudflare.r2 "photos" binding it; the Worker would fail when it reaches for it', + ]); + }); + + test("a required setting with no value, a value for a secret, a period Cloudflare refuses, both worker-first forms: all at once", async () => { + const sources = editFixture(TRIPS, (r) => { + const d = child(r, "deployment.worker", "webProduction"); + d["@workerFirstPaths"] = ["/api/*"]; + d["children"] = children(d).filter((c) => c["value.literal"]?.["name"] !== "teamDomain"); + children(d).push({ "value.literal": { name: "session", "@setting": "Auth.sessionSecret", "@literal": "x" } }); + for (const c of children(d)) if (c["cloudflare.ratelimit"]?.["name"] === "loginLockoutLimiter") c["cloudflare.ratelimit"]["@period"] = 900; + }); + const got = await problems(sources); + expect(got).toContain("deployment.worker acme::trips::webProduction value.literal session: Auth.sessionSecret is @secret; its value comes from the vault, never from a value node"); + expect(got).toContain( + "deployment.worker acme::trips::webProduction: acme::trips::Access.teamDomain (ACCESS_TEAM_DOMAIN) is required and has no value here: give it a value.literal on the deployment, a @default, or mark it @secret", + ); + expect(got).toContain("deployment.worker acme::trips::webProduction cloudflare.ratelimit loginLockoutLimiter: @period 900: the rate limiting binding accepts 10 or 60 seconds only"); + expect(got).toContain("deployment.worker acme::trips::webProduction: @workerFirst and @workerFirstPaths both set; say every request, or which paths"); + expect(got).toHaveLength(4); + }); + + test("@main set in one environment and not another: Wrangler would inherit it", async () => { + const sources = editFixture(ENVS, (r) => { + const base = child(r, "deployment.worker", "siteBase"); + child(r, "deployment.worker", "siteProduction")["@main"] = base["@main"]; + delete base["@main"]; + }); + expect(await problems(sources)).toEqual([ + "app.service acme::quiz::Quiz.site: @main is set in production and not in staging; Wrangler would fill the gap from the top level, so set it in every environment or none", + ]); + }); + + test("an inheritable @extra key set in one environment and not another: Wrangler would fill the gap", async () => { + const extra = JSON.stringify({ observability: { enabled: true } }); + const oneEnvironment = editFixture(ENVS, (r) => { + child(r, "deployment.worker", "siteProduction")["@extra"] = extra; + }); + expect(await problems(oneEnvironment)).toEqual([ + "app.service acme::quiz::Quiz.site: @extra observability is set in production and not in staging; Wrangler would fill the gap from the top level, so set it in every environment or none", + ]); + const everyEnvironment = editFixture(ENVS, (r) => { + child(r, "deployment.worker", "siteBase")["@extra"] = extra; + }); + expect((await read(everyEnvironment)).deployments.map((d) => (d as WorkerDeployment).extra)).toEqual([ + { observability: { enabled: true } }, + { observability: { enabled: true } }, + ]); + }); + + test("a build-time secret setting and a build-time value.ref, each refused by its setting", async () => { + const sources = editFixture(TRIPS, (r) => { + children(child(r, "object.settings", "Notify")).push( + { "field.string": { "name": "contentKey", "@envName": "CONTENT_API_KEY", "@secret": true, "@phase": "build" } }, + { "field.string": { "name": "apiBase", "@envName": "NOTIFY_API_BASE", "@phase": "build" } }, + ); + children(child(r, "deployment.worker", "webProduction")).push({ "value.ref": { name: "apiBase", "@setting": "Notify.apiBase", "@producedBy": "Trips.photos", "@output": "url" } }); + }); + expect(await problems(sources)).toEqual([ + "deployment.worker acme::trips::webProduction: acme::trips::Notify.contentKey (CONTENT_API_KEY) is @secret and @phase build; the scripts copy a secret to a Worker or to a Pages project, never to a build on this machine. Mark it @phase runtime if the Worker reads it; otherwise build by hand under keys-axi run and deploy with --no-build", + "deployment.worker acme::trips::webProduction value.ref apiBase: Notify.apiBase is @phase build, and a build on the deploying machine has no reference to resolve; give it a value.literal or a @default", + ]); + }); + + test("an @extra key the generator writes itself", async () => { + const sources = editFixture(TRIPS, (r) => { + child(r, "deployment.worker", "webProduction")["@extra"] = JSON.stringify({ vars: { X: "1" } }); + }); + expect(await problems(sources)).toEqual([ + "deployment.worker acme::trips::webProduction: @extra sets vars, which the generator writes from the model; declare those facts in the model", + ]); + }); + + test("@jobs naming something that is not a scheduled app.job", async () => { + const sources = editFixture(TRIPS, (r) => { + child(r, "deployment.worker", "webProduction")["@jobs"] = ["Trips.web"]; + }); + expect(await problems(sources)).toEqual(['deployment.worker acme::trips::webProduction: @jobs "Trips.web" does not resolve to an app.job (write System.job)']); + }); + + test("no top-level environment: several environments, none named production", async () => { + const sources = editFixture(ENVS, (r) => { + child(r, "environment.standing", "production")["name"] = "live"; + child(r, "deployment.worker", "siteProduction")["@environment"] = "live"; + for (const c of children(child(r, "vault.infisical", "keys"))) if (c["scope.env"]?.["name"] === "production") c["scope.env"]["name"] = "live"; + }); + expect(await problems(sources)).toEqual([ + "app.service acme::quiz::Quiz.site deploys to live, staging, and none is named production: pass { topLevel } to the generators to say which environment `wrangler deploy` with no --env deploys", + ]); + const app = await read(sources, { topLevel: "live" }); + expect(app.deployments.map((d) => d.environment)).toEqual(["live", "staging"]); + }); + + test("two environments that would deploy over one Worker", async () => { + const sources = editFixture(ENVS, (r) => { + r["metadata.root"].children.push( + { "environment.standing": { name: "qa" } }, + { "deployment.worker": { name: "siteQa", extends: "siteBase", "@environment": "qa", "@script": "quiz-staging" } }, + ); + children(child(r, "vault.infisical", "keys")).push({ "scope.env": { name: "qa", "@project": "quiz" } }); + }); + expect(await problems(sources)).toEqual(['deployment.worker acme::quiz::siteQa: deploys Worker "quiz-staging", as acme::quiz::siteStaging does; give one a different @script']); + }); + + test("a deploy-token vault with no scope for an environment and no @defaultScope", async () => { + const sources = editFixture(ENVS, (r) => { + delete child(r, "vault.infisical", "deployKeys")["@defaultScope"]; + }); + const got = await problems(sources); + expect(got).toEqual([ + 'deployment.worker acme::quiz::siteProduction: vault acme::quiz::deployKeys has no scope.env named "production" and no @defaultScope, so this environment has no place in it', + 'deployment.worker acme::quiz::siteStaging: vault acme::quiz::deployKeys has no scope.env named "staging" and no @defaultScope, so this environment has no place in it', + ]); + }); + + test("a deploy token read from the @secrets vault: both deployments read it there, and that vault's problem is reported once", async () => { + const fromSecrets = (r: Root): void => { + delete child(r, "deployment.worker", "siteBase")["@tokenVault"]; + }; + const tokens = (await read(editFixture(ENVS, fromSecrets))).deployments.map((d) => [d.token.secret, d.token.place.key, `${d.token.place.scope.project}/${d.token.place.scope.env}`]); + expect(tokens).toEqual([ + ["ACME_WORKERS_TOKEN", "acme::quiz::keys", "quiz/prod"], + ["ACME_WORKERS_TOKEN", "acme::quiz::keys", "quiz/staging"], + ]); + const noStaging = editFixture(ENVS, (r) => { + fromSecrets(r); + const keys = child(r, "vault.infisical", "keys"); + keys["children"] = children(keys).filter((c) => c["scope.env"]?.["name"] !== "staging"); + }); + expect(await problems(noStaging)).toEqual([ + 'deployment.worker acme::quiz::siteStaging: vault acme::quiz::keys has no scope.env named "staging" and no @defaultScope, so this environment has no place in it', + ]); + }); + + test("one app deployed both as a Worker and as a Pages site", async () => { + const sources = editFixture(ENVS, (r) => { + r["metadata.root"].children.push( + { "environment.standing": { name: "docs" } }, + { "deployment.pages": { name: "sitePages", "@app": "Quiz.site", "@environment": "docs", "@project": "quiz", "@tokenVault": "deployKeys", "@tokenSecret": "T" } }, + ); + }); + expect(await problems(sources)).toEqual([ + "app.service acme::quiz::Quiz.site is deployed both as a Worker and as a Pages site; deploy one app one way (a Worker with static assets replaces a Pages site)", + ]); + }); + + test("two Cloudflare apps in one model: the generators need { app }", async () => { + const both = [...editFixture(ENVS, () => {}), ...(await import("./model.js")).fixtureSources(TRIPS)]; + const got = await problems(both); + expect(got).toEqual([ + "the model deploys 2 apps to Cloudflare (app.service acme::quiz::Quiz.site, app.service acme::trips::Trips.web); one wrangler.jsonc and one set of scripts are for one app, so pass { app } to the generators", + ]); + expect((await read(both, { app: "Trips.web" })).name).toBe("web"); + }); +}); + +describe("a Pages site's environments", () => { + const secretRow = "Secret values: `SEARCH_API_KEY`"; + + test("a deployment serves Pages production when its branch is the production branch, else preview", async () => { + const app = await read(editFixture(PAGES_SECRETS, () => {})); + expect(app.deployments.map((d) => [d.environment, d.branch, (d as PagesDeployment).pagesEnvironment])).toEqual([ + ["production", "main", "production"], + ["preview", "preview", "preview"], + ]); + expect(app.deployments.map((d) => d.unexpressed.find((f) => f.fact === secretRow)?.how)).toEqual([ + "Never in a file. deploy/cloudflare/sync-secrets.sh copies them from the vault scope `acme-help/prod`; deploy/cloudflare/doctor.sh checks the names are in the vault and on the Pages project's production environment.", + "Never in a file. deploy/cloudflare/sync-secrets.sh copies them from the vault scope `acme-help-preview/preview`; deploy/cloudflare/doctor.sh checks the names are in the vault and on the Pages project's preview environment.", + ]); + }); + + test("a deployment that reads a secret is refused when the model does not say which branch is production", async () => { + const withoutProduction = (r: Root): void => { + r["metadata.root"].children = r["metadata.root"].children.filter((c) => c["deployment.pages"]?.["@environment"] !== "production"); + }; + const noProduction = editFixture(PAGES_SECRETS, withoutProduction); + expect(await problems(noProduction)).toEqual([ + 'deployment.pages acme::help::sitePreview: site reads 1 secret setting(s) (SEARCH_API_KEY) and the model does not say whether this deployment serves the Pages project\'s production or its preview environment, each of which keeps its own: no deployment.pages of site in an environment named "production" declares a @branch, the project\'s production branch', + ]); + const noBranch = editFixture(PAGES_SECRETS, (r) => { + delete child(r, "deployment.pages", "siteProduction")["@branch"]; + }); + expect(await problems(noBranch)).toEqual([ + "deployment.pages acme::help::siteProduction: site reads 1 secret setting(s) (SEARCH_API_KEY) and the model does not say whether this deployment serves the Pages project's production or its preview environment, each of which keeps its own: it has no @branch", + 'deployment.pages acme::help::sitePreview: site reads 1 secret setting(s) (SEARCH_API_KEY) and the model does not say whether this deployment serves the Pages project\'s production or its preview environment, each of which keeps its own: no deployment.pages of site in an environment named "production" declares a @branch, the project\'s production branch', + ]); + // With no secret to place, a deployment needs no Pages environment. + const noSecrets = editFixture(PAGES_SECRETS, (r) => { + withoutProduction(r); + delete child(r, "deployment.pages", "siteBase")["@secrets"]; + for (const c of children(child(r, "object.settings", "Search"))) delete c["field.string"]!["@secret"]; + }); + expect((await read(noSecrets)).deployments.map((d) => (d as PagesDeployment).pagesEnvironment)).toEqual([undefined]); + }); + + test("two deployments that read secrets from differing vault scopes: refused when they serve one Pages project's environment, and free to serve the same one in two projects", async () => { + const withStaging = (vault: (keys: Record, scopes: Node[]) => void, staging: Record = {}): ReturnType => + editFixture(PAGES_SECRETS, (r) => { + const keys = child(r, "vault.infisical", "keys"); + vault(keys, children(keys)); + r["metadata.root"].children.push( + { "environment.standing": { "name": "staging" } }, + { "deployment.pages": { name: "siteStaging", extends: "siteBase", "@environment": "staging", "@branch": "staging", ...staging } }, + ); + }); + const served = (app: Awaited>) => + app.deployments.map((d) => [d.environment, (d as PagesDeployment).pagesEnvironment, d.vault === undefined ? undefined : `${d.vault.scope.project}/${d.vault.scope.env}`]); + // One scope for both: the vault has no scope named preview, so that environment falls to the @defaultScope, which is the staging environment's own scope. + const oneScope = withStaging((keys, scopes) => { + keys["@defaultScope"] = "staging"; + for (const c of scopes) if (c["scope.env"]?.["@env"] === "preview") c["scope.env"] = { name: "staging", "@project": "acme-help-staging", "@env": "staging" }; + }); + expect(served(await read(oneScope))).toEqual([ + ["production", "production", "acme-help/prod"], + ["preview", "preview", "acme-help-staging/staging"], + ["staging", "preview", "acme-help-staging/staging"], + ]); + const sync = (await emit(await loadModels(oneScope))).get("deploy/cloudflare/sync-secrets.sh")!; + expect(sync.match(/ staging\)\n copy (.*)/)?.[1]).toBe("acme-help-staging staging SEARCH_API_KEY help-site preview"); + const ownScope = (scopes: Node[]): void => { + scopes.push({ "scope.env": { name: "staging", "@project": "acme-help-staging", "@env": "staging" } }); + }; + expect(await problems(withStaging((_keys, scopes) => ownScope(scopes)))).toEqual([ + "deployment.pages acme::help::siteStaging: serves the preview environment of Pages project help-site, as acme::help::sitePreview does, and reads its secrets from vault acme::help::keys scope staging (acme-help-staging/staging), not from vault acme::help::keys scope preview (acme-help-preview/preview); Pages keeps one value per name in a project environment, so the last deploy overwrites the other's secrets: give both deployments one vault scope", + ]); + // Two projects keep separate secrets, so the same Pages environment in each is no clash. + const ownProject = withStaging((_keys, scopes) => ownScope(scopes), { "@branch": "main", "@project": "help-site-staging" }); + expect(served(await read(ownProject))).toEqual([ + ["production", "production", "acme-help/prod"], + ["preview", "preview", "acme-help-preview/preview"], + ["staging", "production", "acme-help-staging/staging"], + ]); + expect((await emit(await loadModels(ownProject))).get("deploy/cloudflare/sync-secrets.sh")!.match(/ staging\)\n copy (.*)/)?.[1]).toBe("acme-help-staging staging SEARCH_API_KEY help-site-staging production"); + }); + + test("a value for a secret, for a setting the app does not read, or for no setting is refused on a Pages site as on a Worker; a valid one is listed", async () => { + const value = (name: string, setting: string): Node => ({ "value.literal": { name, "@setting": setting, "@literal": "abc" } }); + const [valid, ...refused] = [value("base", "Search.baseUrl"), value("key", "Search.apiKey"), value("other", "Other.url"), value("nope", "Search.nope")]; + const withValues = (values: readonly Node[]): ReturnType => + editFixture(PAGES_SECRETS, (r) => { + r["metadata.root"].children.push({ "object.settings": { name: "Other", "children": [{ "field.string": { "name": "url", "@envName": "OTHER_URL" } }] } }); + children(child(r, "object.settings", "Search")).push({ "field.string": { "name": "baseUrl", "@envName": "SEARCH_BASE_URL" } }); + children(child(r, "deployment.pages", "siteProduction")).push(...values); + }); + const where = "deployment.pages acme::help::siteProduction value.literal"; + expect(await problems(withValues([valid!, ...refused]))).toEqual([ + `${where} key: Search.apiKey is @secret; its value comes from the vault, never from a value node`, + `${where} other: Other.url is not a setting of the groups site reads (@settings)`, + `${where} nope: @setting "Search.nope" names no setting (Group.field) of an object.settings in the model`, + ]); + const production = (await read(withValues([valid!]))).deployments[0] as PagesDeployment; + expect(production.unexpressed.map((f) => f.fact)).toEqual([ + "Secret values: `SEARCH_API_KEY`", + "Non-secret settings `SEARCH_BASE_URL` (value nodes `base`)", + "Custom domains `help.example.com`", + ]); + }); +}); diff --git a/packs/cloudflare/typescript/test/model.ts b/packs/cloudflare/typescript/test/model.ts new file mode 100644 index 000000000..ecf7cd42e --- /dev/null +++ b/packs/cloudflare/typescript/test/model.ts @@ -0,0 +1,75 @@ +// Loads a conformance fixture's input/ with the pack and every pack it requires composed, and +// runs the pack's generators over it. +import { readdirSync, readFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { defineConfig, runGen } from "@metaobjectsdev/codegen-ts"; +import { MetaDataLoader, InMemoryStringSource, composeRegistry, coreProviders, type MetaRoot } from "@metaobjectsdev/metadata"; +import { configProvider } from "@metaobjectsdev/pack-config"; +import { provider as deliveryProvider } from "@metaobjectsdev/pack-delivery"; +import { provider as systemsProvider } from "@metaobjectsdev/pack-systems"; +import { cloudflareFiles, provider as cloudflareProvider, type CloudflareGeneratorOptions } from "../src/index.js"; + +const CORPUS = join(import.meta.dir, "../../fixtures/conformance"); + +export interface Source { + readonly id: string; + readonly json: string; +} + +/** One source per model, or one per file of a fixture's input/ directory. */ +export async function loadModels(sources: readonly Source[]): Promise { + const registry = composeRegistry([...coreProviders, systemsProvider, deliveryProvider, configProvider, cloudflareProvider]); + const res = await new MetaDataLoader({ registry, strict: true }).load( + sources.map((s) => new InMemoryStringSource(s.json, { id: s.id, format: "json" })), + ); + if (res.errors.length > 0) throw new Error(res.errors.map((e) => e.message).join("\n")); + return res.root; +} + +export function fixtureSources(scenario: string): Source[] { + const dir = join(CORPUS, scenario, "input"); + return readdirSync(dir) + .filter((f) => f.endsWith(".json")) + .sort() + .map((f) => ({ id: f, json: readFileSync(join(dir, f), "utf8") })); +} + +export function loadFixture(scenario: string): Promise { + return loadModels(fixtureSources(scenario)); +} + +/** + * Every file the pack's generators write for `root`, by its path relative to the output + * directory: a dry run, nothing written. + */ +export async function emit(root: MetaRoot, opts: CloudflareGeneratorOptions = {}): Promise> { + const out = join(process.env.DEV_SCRATCH ?? tmpdir(), "pack-cloudflare-out"); + const res = await runGen({ + config: defineConfig({ outDir: out, extStyle: "none", dbImport: "../db", dialect: "sqlite", generators: cloudflareFiles(opts) }), + metadata: root, + projectRoot: dirname(out), + dryRun: true, + }); + const files = new Map(); + for (const [abs, content] of res.rendered ?? []) files.set(abs.slice(out.length + 1), content); + return files; +} + +const emitted = new Map>>(); + +/** A fixture's generated files with the default options, loaded and emitted once per test file. */ +export function emitFixture(scenario: string): Promise> { + let files = emitted.get(scenario); + if (files === undefined) emitted.set(scenario, (files = loadFixture(scenario).then((root) => emit(root)))); + return files; +} + +/** A fixture's input with `edit` applied to its one file's JSON: for the refusal tests. */ +export function editFixture(scenario: string, edit: (root: { "metadata.root": { children: Record>[] } }) => void): Source[] { + const [only, ...rest] = fixtureSources(scenario); + if (only === undefined || rest.length > 0) throw new Error(`${scenario}: editFixture needs a fixture with one input file`); + const json = JSON.parse(only.json); + edit(json); + return [{ id: only.id, json: JSON.stringify(json) }]; +} diff --git a/packs/cloudflare/typescript/test/scripts.test.ts b/packs/cloudflare/typescript/test/scripts.test.ts new file mode 100644 index 000000000..313962e3e --- /dev/null +++ b/packs/cloudflare/typescript/test/scripts.test.ts @@ -0,0 +1,348 @@ +// The generated scripts run for real here. Each tool a script calls that talks to the outside +// is replaced by a stub first on PATH, and each stub writes what it was given under $STUB_DIR: +// keys-axi logs ` --project

--env --only ` per call; `ls --json` +// lists the names the fake vault holds, less $STUB_MISSING; `run` gives every +// `--only` name a value of its own (`value-of-`; empty for $STUB_EMPTY), but +// $STUB_MISSING, then runs the command +// npx logs its arguments, its environment and its stdin; `secret list` and +// `pages secret list` list the names as wrangler prints them +// curl fails when $STUB_CURL_FAIL is 1 +// jq is the real one: the doctor reads the stubs' JSON through it. +import { afterAll, describe, expect, test } from "bun:test"; +import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { editFixture, emit, emitFixture, loadModels } from "./model.js"; + +const LIST = `held() { + while IFS= read -r n; do + [ -n "$n" ] || continue + [ "$n" = "\${STUB_MISSING:-}" ] || "$@" + done < "$STUB_NAMES" +}`; + +const STUBS: Readonly> = { + "keys-axi": `#!/usr/bin/env bash +${LIST} +sub="$1" +project="" scope="" names=() +while [ "$#" -gt 0 ]; do + case "$1" in + --project) project="$2"; shift 2 ;; + --env) scope="$2"; shift 2 ;; + --only) shift; while [ "$#" -gt 0 ] && [ "$1" != "--" ]; do names+=("$1"); shift; done ;; + --) shift; break ;; + *) shift ;; + esac +done +echo "$sub --project $project --env $scope --only \${names[*]}" >> "$STUB_DIR/keys-axi.log" +if [ "$sub" = ls ]; then + out='{"secrets":[' sep="" + name() { out="$out$sep{\\"name\\":\\"$n\\"}"; sep=","; } + held name + echo "$out]}" + exit 0 +fi +for n in "\${names[@]}"; do + [ "$n" = "\${STUB_MISSING:-}" ] || export "$n=$([ "$n" = "\${STUB_EMPTY:-}" ] || echo "value-of-$n")" +done +exec "$@" +`, + npx: `#!/usr/bin/env bash +${LIST} +echo "npx $*" >> "$STUB_DIR/npx.log" +env | sort > "$STUB_DIR/npx.env" +cat >> "$STUB_DIR/npx.stdin" +case "$*" in + *" secret list"*" --format json") + out="[" sep="" + one() { out="$out$sep{\\"name\\":\\"$n\\",\\"type\\":\\"secret\\"}"; sep=","; } + held one + echo "$out]" ;; + *" pages secret list "*) + # \`wrangler pages secret list\` as wrangler 4.168.0 prints it (\`pagesSecretListCommand\` in + # packages/wrangler/src/pages/secret/index.ts), with its colour dropped because it is piped + project="" environment=production + while [ "$#" -gt 1 ]; do + case "$1" in --project-name) project="$2" ;; --env) environment="$2" ;; esac + shift + done + echo "The \\"$environment\\" environment of your Pages project \\"$project\\" has access to the following secrets:" + one() { echo " - $n: Value Encrypted"; } + held one ;; +esac +`, + curl: `#!/usr/bin/env bash +[ "\${STUB_CURL_FAIL:-0}" = 1 ] && exit 22 +exit 0 +`, +}; + +/** One run of a generated script: its exit, its output, and what the stubs were given. */ +interface Run { + readonly status: number | null; + readonly stdout: string; + readonly stderr: string; + /** Every call of `tool`, each as it logged itself. */ + readonly calls: (tool: "npx" | "keys-axi") => string[]; + /** Each `keys-axi run` as the vault project, the vault environment and the names it was asked for. */ + readonly vaultRuns: () => string[][]; + /** The environment the last npx call ran in. */ + readonly npxEnv: () => Record; + /** Everything piped into every npx call, in order. */ + readonly npxStdin: () => string; +} + +const staged: string[] = []; +afterAll(() => { + for (const dir of staged) rmSync(dir, { recursive: true, force: true }); +}); + +/** A directory holding `files` at their paths, the stubs in `bin/` and a fake vault of `names`. */ +async function stage(files: ReadonlyMap, names: readonly string[]): Promise { + const dir = mkdtempSync(join(process.env.DEV_SCRATCH ?? tmpdir(), "pack-cloudflare-scripts-")); + staged.push(dir); + for (const [path, content] of files) { + mkdirSync(dirname(join(dir, path)), { recursive: true }); + writeFileSync(join(dir, path), content, { mode: 0o755 }); + } + mkdirSync(join(dir, "bin")); + for (const [tool, script] of Object.entries(STUBS)) writeFileSync(join(dir, "bin", tool), script, { mode: 0o755 }); + writeFileSync(join(dir, "names"), `${names.join("\n")}\n`); + return dir; +} + +function run(dir: string, script: string, args: readonly string[], env: Record = {}): Run { + const stubDir = join(dir, "stub"); + rmSync(stubDir, { recursive: true, force: true }); + mkdirSync(stubDir, { recursive: true }); + mkdirSync(join(dir, "tmp"), { recursive: true }); + const res = spawnSync("bash", [join(dir, script), ...args], { + encoding: "utf8", + input: "", + env: { + PATH: `${join(dir, "bin")}:${process.env.PATH ?? ""}`, + HOME: dir, + TMPDIR: join(dir, "tmp"), + STUB_DIR: stubDir, + STUB_NAMES: join(dir, "names"), + CLOUDFLARE_EMAIL: "someone@example.com", + CLOUDFLARE_API_KEY: "the-global-key", + CLOUDFLARE_API_TOKEN: "the-shells-token", + ...env, + }, + }); + const written = (file: string): string => { + try { + return readFileSync(join(stubDir, file), "utf8"); + } catch { + return ""; + } + }; + const lines = (file: string): string[] => + written(file) + .split("\n") + .filter((l) => l !== ""); + return { + status: res.status, + stdout: res.stdout, + stderr: res.stderr, + calls: (tool) => lines(`${tool}.log`), + vaultRuns: () => + lines("keys-axi.log") + .filter((l) => l.startsWith("run ")) + .map((l) => /^run --project (\S+) --env (\S+) --only (.*)$/.exec(l)!.slice(1)), + npxEnv: () => + Object.fromEntries( + lines("npx.env").map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)]), + ), + npxStdin: () => written("npx.stdin"), + }; +} + +const TRIPS = "cloudflare-worker-cron-ratelimits"; +const PAGES_SECRETS = "cloudflare-pages-secrets"; +const RUNNER = "deploy/cloudflare/wrangler.sh"; +const SYNC = "deploy/cloudflare/sync-secrets.sh"; +const DOCTOR = "deploy/cloudflare/doctor.sh"; +const ACCOUNT_ID = "CLOUDFLARE_ACCOUNT_ID"; +/** The trips fixture's deploy token, in its own vault scope, and its five Worker secrets. */ +const TRIPS_TOKEN = "ACME_WORKERS_TOKEN"; +const TRIPS_SECRETS = ["SESSION_SECRET", "RESEND_API_KEY", "PASSPHRASE_PEPPER", "RECOVERY_ENC_KEY", "RECOVERY_HMAC_KEY"]; +/** The doctor reads JSON with jq, which the stubs do not replace. */ +const HAS_JQ = spawnSync("jq", ["--version"]).status === 0; +const doctorTest = HAS_JQ ? test : test.skip; +const findings = (r: Run): string[] => r.stdout.split("\n").filter((l) => l.startsWith("FAIL")); + +describe("deploy/cloudflare/wrangler.sh", () => { + test("runs the pinned wrangler as the vault's token, with the global key and the shell's token gone", async () => { + const dir = await stage(await emitFixture(TRIPS), [TRIPS_TOKEN, ACCOUNT_ID]); + const r = run(dir, RUNNER, ["production", "deploy", "--config", "wrangler.jsonc"]); + expect({ status: r.status, stderr: r.stderr }).toEqual({ status: 0, stderr: "" }); + expect(r.calls("npx")).toEqual(["npx --yes wrangler@4.168.0 deploy --config wrangler.jsonc"]); + expect(r.vaultRuns()).toEqual([["acme-deploy", "dev", `${TRIPS_TOKEN} ${ACCOUNT_ID}`]]); + const env = r.npxEnv(); + expect({ token: env["CLOUDFLARE_API_TOKEN"], account: env[ACCOUNT_ID] }).toEqual({ + token: `value-of-${TRIPS_TOKEN}`, + account: `value-of-${ACCOUNT_ID}`, + }); + expect(env[TRIPS_TOKEN]).toBeUndefined(); + expect(env["CLOUDFLARE_EMAIL"]).toBeUndefined(); + expect(env["CLOUDFLARE_API_KEY"]).toBeUndefined(); + }); + + test("stops before wrangler, naming what the vault scope lacks", async () => { + const dir = await stage(await emitFixture(TRIPS), [ACCOUNT_ID]); + const noToken = run(dir, RUNNER, ["production", "deploy"], { STUB_MISSING: TRIPS_TOKEN }); + expect({ status: noToken.status, npx: noToken.calls("npx"), stderr: noToken.stderr }).toEqual({ + status: 1, + npx: [], + stderr: `wrangler.sh: the deploy token ${TRIPS_TOKEN} is empty or is not in the vault scope\n`, + }); + const noAccount = run(dir, RUNNER, ["production", "deploy"], { STUB_MISSING: ACCOUNT_ID }); + expect({ status: noAccount.status, npx: noAccount.calls("npx") }).toEqual({ status: 1, npx: [] }); + expect(noAccount.stderr).toContain(`${ACCOUNT_ID} is not in the vault scope`); + }); + + test("stops before wrangler when the vault holds the deploy token empty: Wrangler would otherwise run as a logged-in account", async () => { + const dir = await stage(await emitFixture(TRIPS), [TRIPS_TOKEN, ACCOUNT_ID]); + const stopped = { status: 1, npx: [], stderr: `wrangler.sh: the deploy token ${TRIPS_TOKEN} is empty or is not in the vault scope\n` }; + const runner = run(dir, RUNNER, ["production", "deploy"], { STUB_EMPTY: TRIPS_TOKEN }); + expect({ status: runner.status, npx: runner.calls("npx"), stderr: runner.stderr }).toEqual(stopped); + const deploy = run(dir, "deploy/cloudflare/deploy.sh", ["production", "--no-build", "--no-secrets"], { STUB_EMPTY: TRIPS_TOKEN }); + expect({ status: deploy.status, npx: deploy.calls("npx"), stderr: deploy.stderr }).toEqual(stopped); + }); + + test("keeps the vault's token when the vault entry is itself named CLOUDFLARE_API_TOKEN", async () => { + const sources = editFixture(TRIPS, (r) => { + for (const c of r["metadata.root"].children) if (c["deployment.worker"] !== undefined) c["deployment.worker"]!["@tokenSecret"] = "CLOUDFLARE_API_TOKEN"; + }); + const dir = await stage(await emit(await loadModels(sources)), ["CLOUDFLARE_API_TOKEN", ACCOUNT_ID]); + const r = run(dir, RUNNER, ["production", "deploy"]); + expect({ status: r.status, stderr: r.stderr }).toEqual({ status: 0, stderr: "" }); + expect(r.npxEnv()["CLOUDFLARE_API_TOKEN"]).toBe("value-of-CLOUDFLARE_API_TOKEN"); + }); +}); + +describe("deploy/cloudflare/sync-secrets.sh", () => { + test("pipes each secret from its vault scope to `wrangler secret put`: the value on no command line and in no output", async () => { + const dir = await stage(await emitFixture(TRIPS), [TRIPS_TOKEN, ACCOUNT_ID, ...TRIPS_SECRETS]); + const r = run(dir, SYNC, ["production"]); + expect({ status: r.status, stderr: r.stderr }).toEqual({ status: 0, stderr: "" }); + expect(r.calls("npx")).toEqual(TRIPS_SECRETS.map((n) => `npx --yes wrangler@4.168.0 secret put ${n} --config wrangler.jsonc`)); + expect(r.npxStdin()).toBe(TRIPS_SECRETS.map((n) => `value-of-${n}`).join("")); + expect(r.vaultRuns()).toEqual( + TRIPS_SECRETS.flatMap((n) => [ + ["trips", "prod", n], + ["acme-deploy", "dev", `${TRIPS_TOKEN} ${ACCOUNT_ID}`], + ]), + ); + expect(r.stdout).toBe(TRIPS_SECRETS.map((n) => `copied ${n} to Cloudflare (production)\n`).join("")); + for (const text of [r.stdout, r.stderr, ...r.calls("npx"), ...r.calls("keys-axi")]) expect(text).not.toContain("value-of-"); + }); + + test("stops at the first secret the vault scope lacks, before wrangler", async () => { + const dir = await stage(await emitFixture(TRIPS), [TRIPS_TOKEN, ACCOUNT_ID, TRIPS_SECRETS[0]!]); + const r = run(dir, SYNC, ["production"], { STUB_MISSING: TRIPS_SECRETS[1]! }); + expect({ status: r.status, stderr: r.stderr, npx: r.calls("npx"), stdout: r.stdout }).toEqual({ + status: 1, + stderr: `sync-secrets: ${TRIPS_SECRETS[1]!} is not in the vault scope\n`, + npx: [`npx --yes wrangler@4.168.0 secret put ${TRIPS_SECRETS[0]} --config wrangler.jsonc`], + stdout: `copied ${TRIPS_SECRETS[0]} to Cloudflare (production)\n`, + }); + }); +}); + +describe("deploy/cloudflare/doctor.sh, for a Worker", () => { + doctorTest("checks the token, each secret, the build and each domain by name, and a failing check fails the run", async () => { + const dir = await stage(await emitFixture(TRIPS), [TRIPS_TOKEN, ACCOUNT_ID, ...TRIPS_SECRETS]); + const ok = run(dir, DOCTOR, ["production"]); + expect({ status: ok.status, stderr: ok.stderr, stdout: ok.stdout }).toEqual({ + status: 0, + stderr: "", + stdout: [ + `ok ${TRIPS_TOKEN} is in the vault (acme-deploy/dev)`, + `ok ${ACCOUNT_ID} is in the vault (acme-deploy/dev)`, + ...TRIPS_SECRETS.map((n) => `ok ${n} is in the vault (trips/prod)`), + ...TRIPS_SECRETS.map((n) => `ok ${n} is set on the Worker`), + "ok wrangler.jsonc builds (production)", + "ok https://trips.example.com/ answers", + "ok https://www.trips.example.com/ answers", + "", + ].join("\n"), + }); + expect(ok.calls("npx")).toEqual([ + "npx --yes wrangler@4.168.0 secret list --config wrangler.jsonc --format json", + expect.stringMatching(/^npx --yes wrangler@4\.168\.0 deploy --dry-run --outdir \S+ --config wrangler\.jsonc$/), + ]); + const down = run(dir, DOCTOR, ["production"], { STUB_CURL_FAIL: "1" }); + expect({ status: down.status, findings: findings(down) }).toEqual({ + status: 1, + findings: ["FAIL https://trips.example.com/ does not answer 2xx", "FAIL https://www.trips.example.com/ does not answer 2xx"], + }); + }); +}); + +describe("a Pages site's secrets", () => { + const TOKEN = "ACME_PAGES_TOKEN"; + const VAULT = [TOKEN, ACCOUNT_ID, "SEARCH_API_KEY"]; + + test.each([ + ["production", "acme-help", "prod", "production"], + ["preview", "acme-help-preview", "preview", "preview"], + ] as const)("sync-secrets.sh %s copies from vault scope %s/%s to the Pages %s environment", async (environment, project, scope, pagesEnvironment) => { + const dir = await stage(await emitFixture(PAGES_SECRETS), VAULT); + const r = run(dir, SYNC, [environment]); + expect(r.calls("npx")).toEqual([`npx --yes wrangler@4.168.0 pages secret put SEARCH_API_KEY --project-name help-site --env ${pagesEnvironment}`]); + expect(r.npxStdin()).toBe("value-of-SEARCH_API_KEY"); + expect(r.vaultRuns()).toEqual([ + [project, scope, "SEARCH_API_KEY"], + ["acme-deploy", "dev", `${TOKEN} ${ACCOUNT_ID}`], + ]); + expect(r.stdout).toBe(`copied SEARCH_API_KEY to Pages project help-site, ${pagesEnvironment} environment (${environment})\n`); + const dry = run(dir, SYNC, [environment, "--dry-run"]); + expect({ stdout: dry.stdout, npx: dry.calls("npx"), keysAxi: dry.calls("keys-axi") }).toEqual({ + stdout: `would copy SEARCH_API_KEY from ${project}/${scope} to Pages project help-site, ${pagesEnvironment} environment (${environment})\n`, + npx: [], + keysAxi: [], + }); + }); + + doctorTest("doctor.sh checks the secrets against the Pages environment the deployment serves, and fails by name", async () => { + const dir = await stage(await emitFixture(PAGES_SECRETS), VAULT); + const ok = run(dir, DOCTOR, ["preview"]); + expect({ status: ok.status, stderr: ok.stderr, stdout: ok.stdout }).toEqual({ + status: 0, + stderr: "", + stdout: [ + `ok ${TOKEN} is in the vault (acme-deploy/dev)`, + `ok ${ACCOUNT_ID} is in the vault (acme-deploy/dev)`, + "ok SEARCH_API_KEY is in the vault (acme-help-preview/preview)", + "ok SEARCH_API_KEY is set on Pages project help-site, preview environment", + "", + ].join("\n"), + }); + expect(ok.calls("npx")).toEqual(["npx --yes wrangler@4.168.0 pages secret list --project-name help-site --env preview"]); + const missing = run(dir, DOCTOR, ["preview"], { STUB_MISSING: "SEARCH_API_KEY" }); + expect({ status: missing.status, findings: findings(missing) }).toEqual({ + status: 1, + findings: [ + "FAIL SEARCH_API_KEY is not in the vault (acme-help-preview/preview)", + "FAIL SEARCH_API_KEY is declared and not set on Pages project help-site, preview environment (run deploy/cloudflare/sync-secrets.sh)", + ], + }); + }); + + doctorTest("doctor.sh passes a token name to the vault as one literal word, whatever it holds", async () => { + const token = "ACME PAGES *TOKEN"; + const sources = editFixture(PAGES_SECRETS, (r) => { + for (const c of r["metadata.root"].children) if (c["deployment.pages"]?.["name"] === "siteBase") c["deployment.pages"]!["@tokenSecret"] = token; + }); + const dir = await stage(await emit(await loadModels(sources)), [token, ACCOUNT_ID, "SEARCH_API_KEY"]); + const r = run(dir, DOCTOR, ["preview"]); + expect(r.stdout).toContain(`ok ${token} is in the vault (acme-deploy/dev)\n`); + expect(r.stdout).not.toContain("FAIL ACME "); + expect(r.stdout).not.toContain("FAIL PAGES "); + }); +}); diff --git a/packs/cloudflare/typescript/test/wrangler-schema.ts b/packs/cloudflare/typescript/test/wrangler-schema.ts new file mode 100644 index 000000000..ee39b5cd2 --- /dev/null +++ b/packs/cloudflare/typescript/test/wrangler-schema.ts @@ -0,0 +1,14 @@ +// Wrangler's own verdict on a configuration, for the tests that write one. The schema is +// vendored in wrangler-schema/ (its README says from which version and how to move it). +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import Ajv from "ajv"; + +const schema = JSON.parse(readFileSync(join(import.meta.dir, "wrangler-schema/config-schema.json"), "utf8")); +// strict: false — the schema carries Wrangler's own `allowTrailingCommas` keyword. +const validate = new Ajv({ strict: false, allErrors: true }).compile(schema); + +/** Each error Wrangler's schema reports for `config`, at its path: [] when it accepts the configuration. */ +export function wranglerSchemaErrors(config: unknown): string[] { + return validate(config) ? [] : (validate.errors ?? []).map((e) => `${e.instancePath} ${e.message}`); +} diff --git a/packs/cloudflare/typescript/test/wrangler-schema/README.md b/packs/cloudflare/typescript/test/wrangler-schema/README.md new file mode 100644 index 000000000..bcd85f085 --- /dev/null +++ b/packs/cloudflare/typescript/test/wrangler-schema/README.md @@ -0,0 +1,13 @@ +# Wrangler's configuration schema, vendored for the tests + +`config-schema.json` is the JSON Schema the `wrangler` npm package ships as +`config-schema.json`, from **wrangler 4.168.0** (the version the generated scripts pin, +`WRANGLER_VERSION` in `src/constants.ts`). Its `description`, `markdownDescription` and +`examples` keys are removed to keep it small; nothing else is changed. + +Wrangler is licensed MIT OR Apache-2.0 (Cloudflare, Inc.). The tests validate every +generated `wrangler.jsonc` against it, so a key the generator writes that Wrangler does not +accept fails the build here, not on a deploy. + +To move to a newer Wrangler: bump `WRANGLER_VERSION`, replace this file from that version's +package with the same three keys removed, and run the tests. diff --git a/packs/cloudflare/typescript/test/wrangler-schema/config-schema.json b/packs/cloudflare/typescript/test/wrangler-schema/config-schema.json new file mode 100644 index 000000000..266a9cc32 --- /dev/null +++ b/packs/cloudflare/typescript/test/wrangler-schema/config-schema.json @@ -0,0 +1 @@ +{"$schema":"http://json-schema.org/draft-07/schema#","definitions":{"RawConfig":{"type":"object","additionalProperties":false,"properties":{"$schema":{"type":"string"},"env":{"type":"object","additionalProperties":{"$ref":"#/definitions/RawEnvironment"},"default":{}},"durable_objects":{"$ref":"#/definitions/RawDurableObjectsConfig"},"name":{"type":"string"},"account_id":{"type":"string"},"compatibility_date":{"type":"string"},"compatibility_flags":{"type":"array","items":{"type":"string"},"default":[]},"main":{"type":"string"},"find_additional_modules":{"type":"boolean"},"preserve_file_names":{"type":"boolean"},"base_dir":{"type":"string"},"workers_dev":{"type":"boolean","default":true},"preview_urls":{"type":"boolean","default":false},"routes":{"type":"array","items":{"$ref":"#/definitions/Route"}},"route":{"$ref":"#/definitions/Route"},"tsconfig":{"type":"string"},"jsx_factory":{"type":"string","default":"React.createElement"},"jsx_fragment":{"type":"string","default":"React.Fragment"},"migrations":{"type":"array","items":{"$ref":"#/definitions/DurableObjectMigration"},"default":[]},"exports":{"$ref":"#/definitions/Exports","default":{}},"triggers":{"type":"object","properties":{"crons":{"type":"array","items":{"type":"string"}},"events":{"type":"array","items":{"$ref":"#/definitions/ArtifactsEventTrigger"}}},"additionalProperties":false,"default":{"crons":[]}},"limits":{"$ref":"#/definitions/UserLimits"},"rules":{"type":"array","items":{"$ref":"#/definitions/Rule"}},"build":{"type":"object","properties":{"command":{"type":"string"},"cwd":{"type":"string"},"watch_dir":{"anyOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]}},"additionalProperties":false,"default":{"watch_dir":"./src"}},"no_bundle":{"type":"boolean"},"minify":{"type":"boolean"},"keep_names":{"type":"boolean","default":true},"first_party_worker":{"type":"boolean"},"logfwdr":{"type":"object","properties":{"bindings":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"destination":{"type":"string"}},"required":["name","destination"],"additionalProperties":false}}},"required":["bindings"],"additionalProperties":false,"default":{"bindings":[]}},"logpush":{"type":"boolean"},"upload_source_maps":{"type":"boolean"},"placement":{"anyOf":[{"type":"object","properties":{"mode":{"type":"string","enum":["off","smart"]},"hint":{"type":"string"}},"required":["mode"],"additionalProperties":false},{"type":"object","properties":{"mode":{"type":"string","const":"targeted"},"region":{"type":"string"}},"required":["region"],"additionalProperties":false},{"type":"object","properties":{"mode":{"type":"string","const":"targeted"},"host":{"type":"string"}},"required":["host"],"additionalProperties":false},{"type":"object","properties":{"mode":{"type":"string","const":"targeted"},"hostname":{"type":"string"}},"required":["hostname"],"additionalProperties":false}]},"assets":{"$ref":"#/definitions/Assets"},"observability":{"$ref":"#/definitions/Observability"},"access":{"$ref":"#/definitions/Access"},"cache":{"$ref":"#/definitions/CacheOptions"},"compliance_region":{"type":"string","enum":["public","fedramp_high"]},"python_modules":{"type":"object","properties":{"exclude":{"type":"array","items":{"type":"string"},"default":["***.pyc"]}},"required":["exclude"],"additionalProperties":false},"previews":{"$ref":"#/definitions/PreviewsConfig"},"define":{"type":"object","additionalProperties":{"type":"string"},"default":{}},"vars":{"type":"object","additionalProperties":{"anyOf":[{"type":"string"},{"$ref":"#/definitions/Json"}]},"default":{}},"secrets":{"type":"object","properties":{"required":{"type":"array","items":{"type":"string"}}},"additionalProperties":false},"workflows":{"type":"array","items":{"$ref":"#/definitions/WorkflowBinding"},"default":[]},"cloudchamber":{"$ref":"#/definitions/CloudchamberConfig","default":{}},"containers":{"type":"array","items":{"$ref":"#/definitions/ContainerApp"},"default":[]},"kv_namespaces":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"id":{"type":"string"},"preview_id":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false},"default":[]},"send_email":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"destination_address":{"type":"string"},"allowed_destination_addresses":{"type":"array","items":{"type":"string"}},"allowed_sender_addresses":{"type":"array","items":{"type":"string"}},"remote":{"type":"boolean"}},"required":["name"],"additionalProperties":false},"default":[]},"queues":{"type":"object","properties":{"producers":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"queue":{"type":"string"},"delivery_delay":{"type":"number"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false}},"consumers":{"type":"array","items":{"type":"object","properties":{"queue":{"type":"string"},"type":{"type":"string","const":"worker"},"max_batch_size":{"type":"number"},"max_batch_timeout":{"type":"number"},"max_retries":{"type":"number"},"dead_letter_queue":{"type":"string"},"max_concurrency":{"type":["number","null"]},"visibility_timeout_ms":{"type":"number"},"retry_delay":{"type":"number"}},"required":["queue"],"additionalProperties":false}}},"additionalProperties":false,"default":{"consumers":[],"producers":[]}},"connect":{"type":"array","items":{"anyOf":[{"type":"object","additionalProperties":false,"properties":{"protocol":{"type":"string","const":"tcp"},"port":{"type":"number"},"address":{"type":"string"}},"required":["port","protocol"]},{"type":"object","additionalProperties":false,"properties":{"protocol":{"type":"string","const":"udp"},"idle_timeout_ms":{"type":"number"},"max_pending_bytes":{"type":"number"},"port":{"type":"number"},"address":{"type":"string"}},"required":["port","protocol"]}]},"default":[]},"r2_buckets":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"bucket_name":{"type":"string"},"preview_bucket_name":{"type":"string"},"jurisdiction":{"type":"string"},"remote":{"type":"boolean"},"local_dev":{"type":"object","properties":{"experimental_s3_credentials":{"$ref":"#/definitions/LocalS3Credentials"}},"additionalProperties":false}},"required":["binding"],"additionalProperties":false},"default":[]},"d1_databases":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"database_name":{"type":"string"},"database_id":{"type":"string"},"jurisdiction":{"type":"string"},"preview_database_id":{"type":"string"},"migrations_table":{"type":"string"},"migrations_dir":{"type":"string"},"migrations_pattern":{"type":"string"},"database_internal_env":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false},"default":[]},"vectorize":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"index_name":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","index_name"],"additionalProperties":false},"default":[]},"ai_search_namespaces":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"namespace":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","namespace"],"additionalProperties":false},"default":[]},"ai_search":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"instance_name":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","instance_name"],"additionalProperties":false},"default":[]},"agent_memory":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"namespace":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","namespace"],"additionalProperties":false},"default":[]},"hyperdrive":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"id":{"type":"string"},"localConnectionString":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","id"],"additionalProperties":false},"default":[]},"services":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"service":{"type":"string"},"entrypoint":{"type":"string"},"props":{"type":"object","additionalProperties":{}},"remote":{"type":"boolean"}},"required":["binding","service"],"additionalProperties":false},"default":[]},"analytics_engine_datasets":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"dataset":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false},"default":[]},"browser":{"type":"object","properties":{"binding":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false,"default":{}},"analytics":{"type":"object","properties":{"binding":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false,"default":{}},"ai":{"type":"object","properties":{"binding":{"type":"string"},"staging":{"type":"boolean"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false,"default":{}},"images":{"type":"object","properties":{"binding":{"type":"string"},"remote":{"type":"boolean"},"url_transformations":{"type":"object","properties":{"enabled":{"type":"boolean"},"allowed_origins":{"type":"array","items":{"type":"string"}}},"required":["enabled"],"additionalProperties":false}},"additionalProperties":false,"default":{}},"media":{"type":"object","properties":{"binding":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false,"default":{}},"stream":{"type":"object","properties":{"binding":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false,"default":{}},"version_metadata":{"type":"object","properties":{"binding":{"type":"string"}},"required":["binding"],"additionalProperties":false},"unsafe":{"type":"object","properties":{"bindings":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"type":{"type":"string"},"dev":{"type":"object","properties":{"plugin":{"type":"object","properties":{"package":{"type":"string"},"name":{"type":"string"}},"required":["package","name"],"additionalProperties":false},"options":{"type":"object","additionalProperties":{}}},"required":["plugin"],"additionalProperties":false}},"required":["name","type"],"additionalProperties":{}}},"metadata":{"type":"object","additionalProperties":{}},"capnp":{"anyOf":[{"type":"object","properties":{"base_path":{"type":"string"},"source_schemas":{"type":"array","items":{"type":"string"}}},"required":["base_path","source_schemas"],"additionalProperties":false},{"type":"object","properties":{"compiled_schema":{"type":"string"}},"required":["compiled_schema"],"additionalProperties":false}]}},"additionalProperties":false,"default":{}},"mtls_certificates":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"certificate_id":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","certificate_id"],"additionalProperties":false},"default":[]},"tail_consumers":{"type":"array","items":{"$ref":"#/definitions/TailConsumer"},"default":[]},"streaming_tail_consumers":{"type":"array","items":{"$ref":"#/definitions/StreamingTailConsumer"},"default":[]},"dispatch_namespaces":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"namespace":{"type":"string"},"outbound":{"$ref":"#/definitions/DispatchNamespaceOutbound"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false},"default":[]},"pipelines":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"stream":{"type":"string"},"pipeline":{"type":"string","deprecated":"Use `stream` instead."},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false},"default":[]},"k2":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"stream":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","stream"],"additionalProperties":false},"default":[]},"secrets_store_secrets":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"store_id":{"type":"string"},"secret_name":{"type":"string"}},"required":["binding","store_id","secret_name"],"additionalProperties":false},"default":[]},"artifacts":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"namespace":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","namespace"],"additionalProperties":false},"default":[]},"unsafe_hello_world":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"enable_timer":{"type":"boolean"}},"required":["binding"],"additionalProperties":false},"default":[]},"flagship":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"app_id":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false},"default":[]},"ratelimits":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"namespace_id":{"type":"string"},"simple":{"type":"object","properties":{"limit":{"type":"number"},"period":{"type":"number","enum":[10,60]}},"required":["limit","period"],"additionalProperties":false}},"required":["name","namespace_id","simple"],"additionalProperties":false},"default":[]},"worker_loaders":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"}},"required":["binding"],"additionalProperties":false},"default":[]},"vpc_services":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"service_id":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","service_id"],"additionalProperties":false},"default":[]},"vpc_networks":{"type":"array","items":{"anyOf":[{"type":"object","properties":{"binding":{"type":"string"},"tunnel_id":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","tunnel_id"],"additionalProperties":false},{"type":"object","properties":{"binding":{"type":"string"},"network_id":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","network_id"],"additionalProperties":false}]},"default":[]},"pages_build_output_dir":{"type":"string"},"send_metrics":{"type":"boolean"},"dependencies_instrumentation":{"type":"object","properties":{"enabled":{"type":"boolean"},"exclude_packages":{"type":"array","items":{"type":"string"}}},"required":["enabled"],"additionalProperties":false},"dev":{"$ref":"#/definitions/RawDevConfig"},"site":{"type":"object","properties":{"bucket":{"type":"string"},"entry-point":{"type":"string","deprecated":"DO NOT use this (it's a holdover from Wrangler v1.x). Either use the top level `main` field, or pass the path to your entry file as a command line argument."},"include":{"type":"array","items":{"type":"string"},"default":[]},"exclude":{"type":"array","items":{"type":"string"},"default":[]}},"required":["bucket"],"additionalProperties":false},"wasm_modules":{"type":"object","additionalProperties":{"type":"string"}},"text_blobs":{"type":"object","additionalProperties":{"type":"string"}},"data_blobs":{"type":"object","additionalProperties":{"type":"string"}},"alias":{"type":"object","additionalProperties":{"type":"string"}},"keep_vars":{"type":"boolean","default":false},"addresses":{"type":"array","items":{"type":"string"}}}},"RawEnvironment":{"type":"object","additionalProperties":false,"properties":{"durable_objects":{"$ref":"#/definitions/RawDurableObjectsConfig"},"name":{"type":"string"},"account_id":{"type":"string"},"compatibility_date":{"type":"string"},"compatibility_flags":{"type":"array","items":{"type":"string"},"default":[]},"main":{"type":"string"},"find_additional_modules":{"type":"boolean"},"preserve_file_names":{"type":"boolean"},"base_dir":{"type":"string"},"workers_dev":{"type":"boolean","default":true},"preview_urls":{"type":"boolean","default":false},"routes":{"type":"array","items":{"$ref":"#/definitions/Route"}},"route":{"$ref":"#/definitions/Route"},"tsconfig":{"type":"string"},"jsx_factory":{"type":"string","default":"React.createElement"},"jsx_fragment":{"type":"string","default":"React.Fragment"},"migrations":{"type":"array","items":{"$ref":"#/definitions/DurableObjectMigration"},"default":[]},"exports":{"$ref":"#/definitions/Exports","default":{}},"triggers":{"type":"object","properties":{"crons":{"type":"array","items":{"type":"string"}},"events":{"type":"array","items":{"$ref":"#/definitions/ArtifactsEventTrigger"}}},"additionalProperties":false,"default":{"crons":[]}},"limits":{"$ref":"#/definitions/UserLimits"},"rules":{"type":"array","items":{"$ref":"#/definitions/Rule"}},"build":{"type":"object","properties":{"command":{"type":"string"},"cwd":{"type":"string"},"watch_dir":{"anyOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]}},"additionalProperties":false,"default":{"watch_dir":"./src"}},"no_bundle":{"type":"boolean"},"minify":{"type":"boolean"},"keep_names":{"type":"boolean","default":true},"first_party_worker":{"type":"boolean"},"logfwdr":{"type":"object","properties":{"bindings":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"destination":{"type":"string"}},"required":["name","destination"],"additionalProperties":false}}},"required":["bindings"],"additionalProperties":false,"default":{"bindings":[]}},"logpush":{"type":"boolean"},"upload_source_maps":{"type":"boolean"},"placement":{"anyOf":[{"type":"object","properties":{"mode":{"type":"string","enum":["off","smart"]},"hint":{"type":"string"}},"required":["mode"],"additionalProperties":false},{"type":"object","properties":{"mode":{"type":"string","const":"targeted"},"region":{"type":"string"}},"required":["region"],"additionalProperties":false},{"type":"object","properties":{"mode":{"type":"string","const":"targeted"},"host":{"type":"string"}},"required":["host"],"additionalProperties":false},{"type":"object","properties":{"mode":{"type":"string","const":"targeted"},"hostname":{"type":"string"}},"required":["hostname"],"additionalProperties":false}]},"assets":{"$ref":"#/definitions/Assets"},"observability":{"$ref":"#/definitions/Observability"},"access":{"$ref":"#/definitions/Access"},"cache":{"$ref":"#/definitions/CacheOptions"},"compliance_region":{"type":"string","enum":["public","fedramp_high"]},"python_modules":{"type":"object","properties":{"exclude":{"type":"array","items":{"type":"string"},"default":["***.pyc"]}},"required":["exclude"],"additionalProperties":false},"previews":{"$ref":"#/definitions/PreviewsConfig"},"define":{"type":"object","additionalProperties":{"type":"string"},"default":{}},"vars":{"type":"object","additionalProperties":{"anyOf":[{"type":"string"},{"$ref":"#/definitions/Json"}]},"default":{}},"secrets":{"type":"object","properties":{"required":{"type":"array","items":{"type":"string"}}},"additionalProperties":false},"workflows":{"type":"array","items":{"$ref":"#/definitions/WorkflowBinding"},"default":[]},"cloudchamber":{"$ref":"#/definitions/CloudchamberConfig","default":{}},"containers":{"type":"array","items":{"$ref":"#/definitions/ContainerApp"},"default":[]},"kv_namespaces":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"id":{"type":"string"},"preview_id":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false},"default":[]},"send_email":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"destination_address":{"type":"string"},"allowed_destination_addresses":{"type":"array","items":{"type":"string"}},"allowed_sender_addresses":{"type":"array","items":{"type":"string"}},"remote":{"type":"boolean"}},"required":["name"],"additionalProperties":false},"default":[]},"queues":{"type":"object","properties":{"producers":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"queue":{"type":"string"},"delivery_delay":{"type":"number"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false}},"consumers":{"type":"array","items":{"type":"object","properties":{"queue":{"type":"string"},"type":{"type":"string","const":"worker"},"max_batch_size":{"type":"number"},"max_batch_timeout":{"type":"number"},"max_retries":{"type":"number"},"dead_letter_queue":{"type":"string"},"max_concurrency":{"type":["number","null"]},"visibility_timeout_ms":{"type":"number"},"retry_delay":{"type":"number"}},"required":["queue"],"additionalProperties":false}}},"additionalProperties":false,"default":{"consumers":[],"producers":[]}},"connect":{"type":"array","items":{"anyOf":[{"type":"object","additionalProperties":false,"properties":{"protocol":{"type":"string","const":"tcp"},"port":{"type":"number"},"address":{"type":"string"}},"required":["port","protocol"]},{"type":"object","additionalProperties":false,"properties":{"protocol":{"type":"string","const":"udp"},"idle_timeout_ms":{"type":"number"},"max_pending_bytes":{"type":"number"},"port":{"type":"number"},"address":{"type":"string"}},"required":["port","protocol"]}]},"default":[]},"r2_buckets":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"bucket_name":{"type":"string"},"preview_bucket_name":{"type":"string"},"jurisdiction":{"type":"string"},"remote":{"type":"boolean"},"local_dev":{"type":"object","properties":{"experimental_s3_credentials":{"$ref":"#/definitions/LocalS3Credentials"}},"additionalProperties":false}},"required":["binding"],"additionalProperties":false},"default":[]},"d1_databases":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"database_name":{"type":"string"},"database_id":{"type":"string"},"jurisdiction":{"type":"string"},"preview_database_id":{"type":"string"},"migrations_table":{"type":"string"},"migrations_dir":{"type":"string"},"migrations_pattern":{"type":"string"},"database_internal_env":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false},"default":[]},"vectorize":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"index_name":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","index_name"],"additionalProperties":false},"default":[]},"ai_search_namespaces":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"namespace":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","namespace"],"additionalProperties":false},"default":[]},"ai_search":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"instance_name":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","instance_name"],"additionalProperties":false},"default":[]},"agent_memory":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"namespace":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","namespace"],"additionalProperties":false},"default":[]},"hyperdrive":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"id":{"type":"string"},"localConnectionString":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","id"],"additionalProperties":false},"default":[]},"services":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"service":{"type":"string"},"entrypoint":{"type":"string"},"props":{"type":"object","additionalProperties":{}},"remote":{"type":"boolean"}},"required":["binding","service"],"additionalProperties":false},"default":[]},"analytics_engine_datasets":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"dataset":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false},"default":[]},"browser":{"type":"object","properties":{"binding":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false,"default":{}},"analytics":{"type":"object","properties":{"binding":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false,"default":{}},"ai":{"type":"object","properties":{"binding":{"type":"string"},"staging":{"type":"boolean"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false,"default":{}},"images":{"type":"object","properties":{"binding":{"type":"string"},"remote":{"type":"boolean"},"url_transformations":{"type":"object","properties":{"enabled":{"type":"boolean"},"allowed_origins":{"type":"array","items":{"type":"string"}}},"required":["enabled"],"additionalProperties":false}},"additionalProperties":false,"default":{}},"media":{"type":"object","properties":{"binding":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false,"default":{}},"stream":{"type":"object","properties":{"binding":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false,"default":{}},"version_metadata":{"type":"object","properties":{"binding":{"type":"string"}},"required":["binding"],"additionalProperties":false},"unsafe":{"type":"object","properties":{"bindings":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"type":{"type":"string"},"dev":{"type":"object","properties":{"plugin":{"type":"object","properties":{"package":{"type":"string"},"name":{"type":"string"}},"required":["package","name"],"additionalProperties":false},"options":{"type":"object","additionalProperties":{}}},"required":["plugin"],"additionalProperties":false}},"required":["name","type"],"additionalProperties":{}}},"metadata":{"type":"object","additionalProperties":{}},"capnp":{"anyOf":[{"type":"object","properties":{"base_path":{"type":"string"},"source_schemas":{"type":"array","items":{"type":"string"}}},"required":["base_path","source_schemas"],"additionalProperties":false},{"type":"object","properties":{"compiled_schema":{"type":"string"}},"required":["compiled_schema"],"additionalProperties":false}]}},"additionalProperties":false,"default":{}},"mtls_certificates":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"certificate_id":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","certificate_id"],"additionalProperties":false},"default":[]},"tail_consumers":{"type":"array","items":{"$ref":"#/definitions/TailConsumer"},"default":[]},"streaming_tail_consumers":{"type":"array","items":{"$ref":"#/definitions/StreamingTailConsumer"},"default":[]},"dispatch_namespaces":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"namespace":{"type":"string"},"outbound":{"$ref":"#/definitions/DispatchNamespaceOutbound"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false},"default":[]},"pipelines":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"stream":{"type":"string"},"pipeline":{"type":"string","deprecated":"Use `stream` instead."},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false},"default":[]},"k2":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"stream":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","stream"],"additionalProperties":false},"default":[]},"secrets_store_secrets":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"store_id":{"type":"string"},"secret_name":{"type":"string"}},"required":["binding","store_id","secret_name"],"additionalProperties":false},"default":[]},"artifacts":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"namespace":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","namespace"],"additionalProperties":false},"default":[]},"unsafe_hello_world":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"enable_timer":{"type":"boolean"}},"required":["binding"],"additionalProperties":false},"default":[]},"flagship":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"app_id":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false},"default":[]},"ratelimits":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"namespace_id":{"type":"string"},"simple":{"type":"object","properties":{"limit":{"type":"number"},"period":{"type":"number","enum":[10,60]}},"required":["limit","period"],"additionalProperties":false}},"required":["name","namespace_id","simple"],"additionalProperties":false},"default":[]},"worker_loaders":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"}},"required":["binding"],"additionalProperties":false},"default":[]},"vpc_services":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"service_id":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","service_id"],"additionalProperties":false},"default":[]},"vpc_networks":{"type":"array","items":{"anyOf":[{"type":"object","properties":{"binding":{"type":"string"},"tunnel_id":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","tunnel_id"],"additionalProperties":false},{"type":"object","properties":{"binding":{"type":"string"},"network_id":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","network_id"],"additionalProperties":false}]},"default":[]}}},"RawDurableObjectsConfig":{"type":"object","additionalProperties":false,"properties":{"bindings":{"$ref":"#/definitions/DurableObjectBindings"},"code_update_strategy":{"$ref":"#/definitions/DurableObjectCodeUpdateStrategy"}}},"DurableObjectBindings":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"class_name":{"type":"string"},"script_name":{"type":"string"},"environment":{"type":"string"}},"required":["name","class_name"],"additionalProperties":false}},"DurableObjectCodeUpdateStrategy":{"type":"object","properties":{"mode":{"type":"string","enum":["immediate","deferred"]},"max_delay":{"type":"number","minimum":0,"maximum":86400,"multipleOf":0.001,"default":300}},"required":["mode"],"additionalProperties":false},"Route":{"anyOf":[{"type":"string"},{"$ref":"#/definitions/ZoneIdRoute"},{"$ref":"#/definitions/ZoneNameRoute"},{"$ref":"#/definitions/CustomDomainRoute"}]},"ZoneIdRoute":{"type":"object","properties":{"pattern":{"type":"string"},"zone_id":{"type":"string"},"custom_domain":{"type":"boolean"}},"required":["pattern","zone_id"],"additionalProperties":false},"ZoneNameRoute":{"type":"object","properties":{"pattern":{"type":"string"},"zone_name":{"type":"string"},"custom_domain":{"type":"boolean"}},"required":["pattern","zone_name"],"additionalProperties":false},"CustomDomainRoute":{"type":"object","properties":{"pattern":{"type":"string"},"custom_domain":{"type":"boolean"},"enabled":{"type":"boolean"},"previews_enabled":{"type":"boolean"}},"required":["pattern","custom_domain"],"additionalProperties":false},"DurableObjectMigration":{"type":"object","properties":{"tag":{"type":"string"},"new_classes":{"type":"array","items":{"type":"string"}},"new_sqlite_classes":{"type":"array","items":{"type":"string"}},"renamed_classes":{"type":"array","items":{"type":"object","properties":{"from":{"type":"string"},"to":{"type":"string"}},"required":["from","to"],"additionalProperties":false}},"transferred_classes":{"type":"array","items":{"type":"object","properties":{"from":{"type":"string"},"from_script":{"type":"string"},"to":{"type":"string"}},"required":["from","from_script","to"],"additionalProperties":false}},"deleted_classes":{"type":"array","items":{"type":"string"}}},"required":["tag"],"additionalProperties":false},"Exports":{"type":"object","additionalProperties":{"$ref":"#/definitions/ConfiguredExport"}},"ConfiguredExport":{"anyOf":[{"$ref":"#/definitions/DurableObjectExport"},{"$ref":"#/definitions/WorkerEntrypointExport"},{"$ref":"#/definitions/WorkflowExport"}]},"DurableObjectExport":{"anyOf":[{"type":"object","properties":{"type":{"type":"string","const":"durable-object"},"state":{"type":"string","const":"created"},"storage":{"$ref":"#/definitions/DurableObjectExportStorage"},"container":{"type":"string"}},"required":["type","storage"],"additionalProperties":false},{"type":"object","properties":{"type":{"type":"string","const":"durable-object"},"state":{"type":"string","const":"deleted"}},"required":["type","state"],"additionalProperties":false},{"type":"object","properties":{"type":{"type":"string","const":"durable-object"},"state":{"type":"string","const":"renamed"},"renamed_to":{"type":"string"}},"required":["type","state","renamed_to"],"additionalProperties":false},{"type":"object","properties":{"type":{"type":"string","const":"durable-object"},"state":{"type":"string","const":"transferred"},"transferred_to":{"type":"string"}},"required":["type","state","transferred_to"],"additionalProperties":false},{"type":"object","properties":{"type":{"type":"string","const":"durable-object"},"state":{"type":"string","const":"expecting-transfer"},"storage":{"$ref":"#/definitions/DurableObjectExportStorage"},"transfer_from":{"type":"string"},"container":{"type":"string"}},"required":["type","state","storage","transfer_from"],"additionalProperties":false}]},"DurableObjectExportStorage":{"type":"string","enum":["sqlite","legacy-kv"]},"WorkerEntrypointExport":{"type":"object","properties":{"type":{"type":"string","const":"worker"},"cache":{"type":"object","properties":{"enabled":{"type":"boolean"}},"required":["enabled"],"additionalProperties":false}},"required":["type"],"additionalProperties":false},"WorkflowExport":{"type":"object","properties":{"limits":{"type":"object","properties":{"steps":{"type":"number"}},"additionalProperties":false},"concurrency":{"type":"object","properties":{"limit":{"type":"number"}},"additionalProperties":false},"schedules":{"anyOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]},"default_retention":{"type":"object","properties":{"success_retention":{"type":["number","string"]},"error_retention":{"type":["number","string"]}},"additionalProperties":false},"jurisdiction":{"$ref":"#/definitions/WorkflowJurisdiction"},"type":{"type":"string","const":"workflow"},"name":{"type":"string"}},"required":["type","name"],"additionalProperties":false},"WorkflowJurisdiction":{"type":"string","enum":["eu","fedramp","us"]},"ArtifactsEventTrigger":{"type":"object","properties":{"type":{"$ref":"#/definitions/ArtifactsEventType"},"filter":{"type":"object","properties":{"namespace":{"type":"string"},"repo_name":{"type":"string"}},"additionalProperties":false},"targets":{"type":"array","items":{"type":"object","properties":{"type":{"type":"string","const":"workflow"},"workflow_name":{"type":"string"}},"required":["type","workflow_name"],"additionalProperties":false}}},"required":["type","targets"],"additionalProperties":false},"ArtifactsEventType":{"type":"string","enum":["cf.artifacts.repo.created","cf.artifacts.repo.deleted","cf.artifacts.repo.forked","cf.artifacts.repo.imported","cf.artifacts.repo.pushed","cf.artifacts.repo.cloned","cf.artifacts.repo.fetched","cf.artifacts.repo.token.created","cf.artifacts.repo.token.revoked"]},"UserLimits":{"type":"object","properties":{"cpu_ms":{"type":"number"},"subrequests":{"type":"number"}},"additionalProperties":false},"Rule":{"type":"object","properties":{"type":{"$ref":"#/definitions/ConfigModuleRuleType"},"globs":{"type":"array","items":{"type":"string"}},"fallthrough":{"type":"boolean"}},"required":["type","globs"],"additionalProperties":false},"ConfigModuleRuleType":{"type":"string","enum":["ESModule","CommonJS","CompiledWasm","Text","Data","PythonModule","PythonRequirement"]},"Assets":{"type":"object","properties":{"directory":{"type":"string"},"binding":{"type":"string"},"html_handling":{"type":"string","enum":["auto-trailing-slash","force-trailing-slash","drop-trailing-slash","none"]},"not_found_handling":{"type":"string","enum":["single-page-application","404-page","none"]},"base_path":{"type":"string"},"run_worker_first":{"anyOf":[{"type":"array","items":{"type":"string"}},{"type":"boolean"}]}},"additionalProperties":false},"Observability":{"type":"object","properties":{"enabled":{"type":"boolean"},"head_sampling_rate":{"type":"number"},"redact_query_string":{"type":"boolean","default":false},"issues":{"type":"object","properties":{"enabled":{"type":"boolean"}},"additionalProperties":false},"logs":{"type":"object","properties":{"enabled":{"type":"boolean"},"head_sampling_rate":{"type":"number"},"invocation_logs":{"type":"boolean"},"persist":{"type":"boolean","default":true},"destinations":{"type":"array","items":{"type":"string"},"default":[]}},"additionalProperties":false},"traces":{"type":"object","properties":{"enabled":{"type":"boolean"},"head_sampling_rate":{"type":"number"},"persist":{"type":"boolean","default":true},"destinations":{"type":"array","items":{"type":"string"},"default":[]}},"additionalProperties":false}},"additionalProperties":false},"Access":{"type":"object","properties":{"dev":{"type":"object","properties":{"aud":{"type":"string"},"identity":{"type":"object","additionalProperties":{}}},"required":["aud"],"additionalProperties":false}},"additionalProperties":false},"CacheOptions":{"type":"object","properties":{"enabled":{"type":"boolean"},"cross_version_cache":{"type":"boolean"}},"required":["enabled"],"additionalProperties":false},"PreviewsConfig":{"type":"object","properties":{"logpush":{"$ref":"#/definitions/interface-769040647-14884-25493-769040647-0-636602004818536"},"observability":{"$ref":"#/definitions/interface-769040647-14884-25493-769040647-0-636602004818536"},"limits":{"$ref":"#/definitions/interface-769040647-14884-25493-769040647-0-636602004818536"},"placement":{"$ref":"#/definitions/interface-769040647-14884-25493-769040647-0-636602004818536"},"cache":{"$ref":"#/definitions/interface-769040647-14884-25493-769040647-0-636602004818536"},"define":{"type":"object","additionalProperties":{"type":"string"},"default":{}},"vars":{"type":"object","additionalProperties":{"anyOf":[{"type":"string"},{"$ref":"#/definitions/Json"}]},"default":{}},"secrets":{"type":"object","properties":{"required":{"type":"array","items":{"type":"string"}}},"additionalProperties":false},"workflows":{"type":"array","items":{"$ref":"#/definitions/WorkflowBinding"},"default":[]},"cloudchamber":{"$ref":"#/definitions/CloudchamberConfig","default":{}},"containers":{"type":"array","items":{"$ref":"#/definitions/ContainerApp"},"default":[]},"kv_namespaces":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"id":{"type":"string"},"preview_id":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false},"default":[]},"send_email":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"destination_address":{"type":"string"},"allowed_destination_addresses":{"type":"array","items":{"type":"string"}},"allowed_sender_addresses":{"type":"array","items":{"type":"string"}},"remote":{"type":"boolean"}},"required":["name"],"additionalProperties":false},"default":[]},"queues":{"type":"object","properties":{"producers":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"queue":{"type":"string"},"delivery_delay":{"type":"number"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false}},"consumers":{"type":"array","items":{"type":"object","properties":{"queue":{"type":"string"},"type":{"type":"string","const":"worker"},"max_batch_size":{"type":"number"},"max_batch_timeout":{"type":"number"},"max_retries":{"type":"number"},"dead_letter_queue":{"type":"string"},"max_concurrency":{"type":["number","null"]},"visibility_timeout_ms":{"type":"number"},"retry_delay":{"type":"number"}},"required":["queue"],"additionalProperties":false}}},"additionalProperties":false,"default":{"consumers":[],"producers":[]}},"connect":{"type":"array","items":{"anyOf":[{"type":"object","additionalProperties":false,"properties":{"protocol":{"type":"string","const":"tcp"},"port":{"type":"number"},"address":{"type":"string"}},"required":["port","protocol"]},{"type":"object","additionalProperties":false,"properties":{"protocol":{"type":"string","const":"udp"},"idle_timeout_ms":{"type":"number"},"max_pending_bytes":{"type":"number"},"port":{"type":"number"},"address":{"type":"string"}},"required":["port","protocol"]}]},"default":[]},"r2_buckets":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"bucket_name":{"type":"string"},"preview_bucket_name":{"type":"string"},"jurisdiction":{"type":"string"},"remote":{"type":"boolean"},"local_dev":{"type":"object","properties":{"experimental_s3_credentials":{"$ref":"#/definitions/LocalS3Credentials"}},"additionalProperties":false}},"required":["binding"],"additionalProperties":false},"default":[]},"d1_databases":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"database_name":{"type":"string"},"database_id":{"type":"string"},"jurisdiction":{"type":"string"},"preview_database_id":{"type":"string"},"migrations_table":{"type":"string"},"migrations_dir":{"type":"string"},"migrations_pattern":{"type":"string"},"database_internal_env":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false},"default":[]},"vectorize":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"index_name":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","index_name"],"additionalProperties":false},"default":[]},"ai_search_namespaces":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"namespace":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","namespace"],"additionalProperties":false},"default":[]},"ai_search":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"instance_name":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","instance_name"],"additionalProperties":false},"default":[]},"agent_memory":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"namespace":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","namespace"],"additionalProperties":false},"default":[]},"hyperdrive":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"id":{"type":"string"},"localConnectionString":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","id"],"additionalProperties":false},"default":[]},"services":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"service":{"type":"string"},"entrypoint":{"type":"string"},"props":{"type":"object","additionalProperties":{}},"remote":{"type":"boolean"}},"required":["binding","service"],"additionalProperties":false},"default":[]},"analytics_engine_datasets":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"dataset":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false},"default":[]},"browser":{"type":"object","properties":{"binding":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false,"default":{}},"analytics":{"type":"object","properties":{"binding":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false,"default":{}},"ai":{"type":"object","properties":{"binding":{"type":"string"},"staging":{"type":"boolean"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false,"default":{}},"media":{"type":"object","properties":{"binding":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false,"default":{}},"stream":{"type":"object","properties":{"binding":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false,"default":{}},"version_metadata":{"type":"object","properties":{"binding":{"type":"string"}},"required":["binding"],"additionalProperties":false},"unsafe":{"type":"object","properties":{"bindings":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"type":{"type":"string"},"dev":{"type":"object","properties":{"plugin":{"type":"object","properties":{"package":{"type":"string"},"name":{"type":"string"}},"required":["package","name"],"additionalProperties":false},"options":{"type":"object","additionalProperties":{}}},"required":["plugin"],"additionalProperties":false}},"required":["name","type"],"additionalProperties":{}}},"metadata":{"type":"object","additionalProperties":{}},"capnp":{"anyOf":[{"type":"object","properties":{"base_path":{"type":"string"},"source_schemas":{"type":"array","items":{"type":"string"}}},"required":["base_path","source_schemas"],"additionalProperties":false},{"type":"object","properties":{"compiled_schema":{"type":"string"}},"required":["compiled_schema"],"additionalProperties":false}]}},"additionalProperties":false,"default":{}},"mtls_certificates":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"certificate_id":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","certificate_id"],"additionalProperties":false},"default":[]},"tail_consumers":{"type":"array","items":{"$ref":"#/definitions/TailConsumer"},"default":[]},"streaming_tail_consumers":{"type":"array","items":{"$ref":"#/definitions/StreamingTailConsumer"},"default":[]},"dispatch_namespaces":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"namespace":{"type":"string"},"outbound":{"$ref":"#/definitions/DispatchNamespaceOutbound"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false},"default":[]},"pipelines":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"stream":{"type":"string"},"pipeline":{"type":"string","deprecated":"Use `stream` instead."},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false},"default":[]},"k2":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"stream":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","stream"],"additionalProperties":false},"default":[]},"secrets_store_secrets":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"store_id":{"type":"string"},"secret_name":{"type":"string"}},"required":["binding","store_id","secret_name"],"additionalProperties":false},"default":[]},"artifacts":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"namespace":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","namespace"],"additionalProperties":false},"default":[]},"unsafe_hello_world":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"enable_timer":{"type":"boolean"}},"required":["binding"],"additionalProperties":false},"default":[]},"flagship":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"app_id":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false},"default":[]},"ratelimits":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"namespace_id":{"type":"string"},"simple":{"type":"object","properties":{"limit":{"type":"number"},"period":{"type":"number","enum":[10,60]}},"required":["limit","period"],"additionalProperties":false}},"required":["name","namespace_id","simple"],"additionalProperties":false},"default":[]},"worker_loaders":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"}},"required":["binding"],"additionalProperties":false},"default":[]},"vpc_services":{"type":"array","items":{"type":"object","properties":{"binding":{"type":"string"},"service_id":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","service_id"],"additionalProperties":false},"default":[]},"vpc_networks":{"type":"array","items":{"anyOf":[{"type":"object","properties":{"binding":{"type":"string"},"tunnel_id":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","tunnel_id"],"additionalProperties":false},{"type":"object","properties":{"binding":{"type":"string"},"network_id":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding","network_id"],"additionalProperties":false}]},"default":[]},"durable_objects":{"type":"object","properties":{"bindings":{"$ref":"#/definitions/DurableObjectBindings"}},"required":["bindings"],"additionalProperties":false},"images":{"type":"object","properties":{"binding":{"type":"string"},"remote":{"type":"boolean"}},"required":["binding"],"additionalProperties":false}},"additionalProperties":false},"interface-769040647-14884-25493-769040647-0-636602004818536":{"type":"object","properties":{"name":{"type":"string"},"account_id":{"type":"string"},"compatibility_date":{"type":"string"},"compatibility_flags":{"type":"array","items":{"type":"string"},"default":[]},"main":{"type":"string"},"find_additional_modules":{"type":"boolean"},"preserve_file_names":{"type":"boolean"},"base_dir":{"type":"string"},"workers_dev":{"type":"boolean","default":true},"preview_urls":{"type":"boolean","default":false},"routes":{"type":"array","items":{"$ref":"#/definitions/Route"}},"route":{"$ref":"#/definitions/Route"},"tsconfig":{"type":"string"},"jsx_factory":{"type":"string","default":"React.createElement"},"jsx_fragment":{"type":"string","default":"React.Fragment"},"migrations":{"type":"array","items":{"$ref":"#/definitions/DurableObjectMigration"},"default":[]},"exports":{"$ref":"#/definitions/Exports","default":{}},"triggers":{"type":"object","properties":{"crons":{"type":"array","items":{"type":"string"}},"events":{"type":"array","items":{"$ref":"#/definitions/ArtifactsEventTrigger"}}},"additionalProperties":false,"default":{"crons":[]}},"limits":{"$ref":"#/definitions/UserLimits"},"rules":{"type":"array","items":{"$ref":"#/definitions/Rule"}},"build":{"type":"object","properties":{"command":{"type":"string"},"cwd":{"type":"string"},"watch_dir":{"anyOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]}},"additionalProperties":false,"default":{"watch_dir":"./src"}},"no_bundle":{"type":"boolean"},"minify":{"type":"boolean"},"keep_names":{"type":"boolean","default":true},"first_party_worker":{"type":"boolean"},"logfwdr":{"type":"object","properties":{"bindings":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"destination":{"type":"string"}},"required":["name","destination"],"additionalProperties":false}}},"required":["bindings"],"additionalProperties":false,"default":{"bindings":[]}},"logpush":{"type":"boolean"},"upload_source_maps":{"type":"boolean"},"placement":{"anyOf":[{"type":"object","properties":{"mode":{"type":"string","enum":["off","smart"]},"hint":{"type":"string"}},"required":["mode"],"additionalProperties":false},{"type":"object","properties":{"mode":{"type":"string","const":"targeted"},"region":{"type":"string"}},"required":["region"],"additionalProperties":false},{"type":"object","properties":{"mode":{"type":"string","const":"targeted"},"host":{"type":"string"}},"required":["host"],"additionalProperties":false},{"type":"object","properties":{"mode":{"type":"string","const":"targeted"},"hostname":{"type":"string"}},"required":["hostname"],"additionalProperties":false}]},"assets":{"$ref":"#/definitions/Assets"},"observability":{"$ref":"#/definitions/Observability"},"access":{"$ref":"#/definitions/Access"},"cache":{"$ref":"#/definitions/CacheOptions"},"compliance_region":{"type":"string","enum":["public","fedramp_high"]},"python_modules":{"type":"object","properties":{"exclude":{"type":"array","items":{"type":"string"},"default":["***.pyc"]}},"required":["exclude"],"additionalProperties":false},"previews":{"$ref":"#/definitions/PreviewsConfig"}},"required":["compatibility_flags","jsx_factory","jsx_fragment","migrations","exports","triggers","rules","build","logfwdr","python_modules"],"additionalProperties":false},"Json":{"anyOf":[{"type":"string"},{"type":"number"},{"type":"boolean"},{"type":"null"},{"type":"array","items":{"$ref":"#/definitions/Json"}},{"type":"object","additionalProperties":{"$ref":"#/definitions/Json"}}]},"WorkflowBinding":{"type":"object","properties":{"binding":{"type":"string"},"name":{"type":"string"},"class_name":{"type":"string"},"script_name":{"type":"string"},"limits":{"type":"object","properties":{"steps":{"type":"number"}},"additionalProperties":false},"concurrency":{"type":"object","properties":{"limit":{"type":"number"}},"additionalProperties":false},"schedules":{"anyOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]},"default_retention":{"type":"object","properties":{"success_retention":{"type":["number","string"]},"error_retention":{"type":["number","string"]}},"additionalProperties":false},"jurisdiction":{"$ref":"#/definitions/WorkflowJurisdiction"}},"required":["binding","name","class_name"],"additionalProperties":false},"CloudchamberConfig":{"type":"object","properties":{"image":{"type":"string"},"location":{"type":"string"},"instance_type":{"type":"string","enum":["dev","basic","standard","lite","standard-1","standard-2","standard-3","standard-4"]},"vcpu":{"type":"number"},"memory":{"type":"string"},"ipv4":{"type":"boolean"}},"additionalProperties":false},"ContainerApp":{"type":"object","properties":{"name":{"type":"string"},"max_instances":{"type":"number"},"image":{"type":"string"},"images":{"type":"object","additionalProperties":{"$ref":"#/definitions/DurableObjectContainerImage"}},"image_build_context":{"type":"string"},"image_vars":{"type":"object","additionalProperties":{"type":"string"}},"class_name":{"type":"string"},"observability":{"$ref":"#/definitions/ContainerObservability"},"scheduling_policy":{"type":"string","enum":["default","durable_object","moon","regional"],"default":"default"},"instance_type":{"anyOf":[{"type":"string","const":"dev"},{"type":"string","const":"basic"},{"type":"string","const":"standard"},{"type":"string","const":"lite"},{"type":"string","const":"standard-1"},{"type":"string","const":"standard-2"},{"type":"string","const":"standard-3"},{"type":"string","const":"standard-4"},{"type":"object","properties":{"vcpu":{"type":"number"},"memory_mib":{"type":"number"},"disk_mb":{"type":"number"}},"additionalProperties":false}],"default":"dev"},"ssh":{"type":"object","properties":{"enabled":{"type":"boolean","default":false},"port":{"type":"number"}},"required":["enabled"],"additionalProperties":false},"authorized_keys":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"public_key":{"type":"string"}},"required":["name","public_key"],"additionalProperties":false}},"trusted_user_ca_keys":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"public_key":{"type":"string"}},"required":["public_key"],"additionalProperties":false}},"constraints":{"type":"object","properties":{"regions":{"type":"array","items":{"type":"string","enum":["ENAM","WNAM","EEUR","WEUR","APAC","SAM","ME","OC","AFR"]}},"jurisdiction":{"type":"string","enum":["eu","fedramp","us"]}},"additionalProperties":false},"rollout_step_percentage":{"anyOf":[{"type":"number"},{"type":"array","items":{"type":"number"}}],"default":[10,100]},"rollout_active_grace_period":{"type":"number","default":0}},"additionalProperties":false},"DurableObjectContainerImage":{"anyOf":[{"type":"object","properties":{"dockerfile":{"type":"string"},"build_context":{"type":"string"},"build_vars":{"type":"object","additionalProperties":{"type":"string"}}},"required":["dockerfile"],"additionalProperties":false},{"type":"object","properties":{"image":{"type":"string"}},"required":["image"],"additionalProperties":false}]},"ContainerObservability":{"type":"object","properties":{"enabled":{"type":"boolean"},"logs":{"type":"object","properties":{"enabled":{"type":"boolean"}},"additionalProperties":false},"target_instance_percentage":{"type":"number"},"target_instance_count":{"type":"number"}},"additionalProperties":false},"LocalS3Credentials":{"type":"object","properties":{"accessKeyId":{"type":"string"},"secretAccessKey":{"type":"string"}},"required":["accessKeyId","secretAccessKey"],"additionalProperties":false},"TailConsumer":{"type":"object","properties":{"service":{"type":"string"},"environment":{"type":"string"}},"required":["service"],"additionalProperties":false},"StreamingTailConsumer":{"type":"object","properties":{"service":{"type":"string"}},"required":["service"],"additionalProperties":false},"DispatchNamespaceOutbound":{"type":"object","properties":{"service":{"type":"string"},"environment":{"type":"string"},"parameters":{"type":"array","items":{"type":"string"}}},"required":["service"],"additionalProperties":false},"RawDevConfig":{"type":"object","properties":{"ip":{"type":"string","default":"localhost"},"port":{"type":"number","default":8787},"inspector_port":{"type":"number","default":9229},"inspector_ip":{"type":"string","default":"127.0.0.1"},"local_protocol":{"type":"string","enum":["http","https"],"default":"http"},"upstream_protocol":{"type":"string","enum":["https","http"],"default":"https"},"host":{"type":"string"},"enable_containers":{"type":"boolean","default":true},"container_engine":{"$ref":"#/definitions/ContainerEngine"},"generate_types":{"type":"boolean","default":false}},"additionalProperties":false},"ContainerEngine":{"anyOf":[{"type":"object","properties":{"localDocker":{"$ref":"#/definitions/DockerConfiguration"}},"required":["localDocker"],"additionalProperties":false},{"type":"string"}]},"DockerConfiguration":{"type":"object","properties":{"socketPath":{"type":"string"},"containerEgressInterceptorImage":{"type":"string"}},"required":["socketPath"],"additionalProperties":false}},"allowTrailingCommas":true,"allOf":[{"$ref":"#/definitions/RawConfig"}]} diff --git a/packs/cloudflare/typescript/tsconfig.json b/packs/cloudflare/typescript/tsconfig.json new file mode 100644 index 000000000..66c8af379 --- /dev/null +++ b/packs/cloudflare/typescript/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../../server/typescript/tsconfig.base.json", + "compilerOptions": { + "noEmit": true, + "customConditions": ["bun"] + }, + "include": ["src/**/*", "test/**/*"] +}