|
| 1 | +import { CreatePlan, DestroyPlan, Resource, ResourceSettings, SpawnStatus, getPty, z } from '@codifycli/plugin-core'; |
| 2 | +import { OS } from '@codifycli/schemas'; |
| 3 | +import fs from 'node:fs/promises'; |
| 4 | +import os from 'node:os'; |
| 5 | +import path from 'node:path'; |
| 6 | + |
| 7 | +import { quote, readProjectFiles, wrapCommand } from '../project-install/package-managers.js'; |
| 8 | +import { exampleDeployExistingSite, exampleDeployNewSite } from './examples.js'; |
| 9 | +import { |
| 10 | + SCAFFOLD_TEMPLATES, |
| 11 | + buildDeployCommand, |
| 12 | + buildScaffoldCommand, |
| 13 | + defaultBuildCommand, |
| 14 | + hasWranglerConfig, |
| 15 | + interpretDeploymentsList, |
| 16 | + today, |
| 17 | +} from './wrangler-utils.js'; |
| 18 | + |
| 19 | +export const schema = z |
| 20 | + .object({ |
| 21 | + workerName: z |
| 22 | + .string() |
| 23 | + .regex(/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/) |
| 24 | + .describe('Name of the Worker. The site is served at https://<workerName>.<your-subdomain>.workers.dev. Lowercase letters, numbers and dashes, up to 63 characters, and it can\'t start or end with a dash.'), |
| 25 | + directory: z |
| 26 | + .string() |
| 27 | + .describe('The project directory to deploy from.'), |
| 28 | + framework: z |
| 29 | + .enum(SCAFFOLD_TEMPLATES) |
| 30 | + .optional() |
| 31 | + .describe('Scaffold a new project with create-cloudflare when the directory doesn\'t exist yet. Use "static" for plain HTML, CSS and JavaScript with no build step. Leave this out for existing projects.'), |
| 32 | + assets: z |
| 33 | + .string() |
| 34 | + .optional() |
| 35 | + .describe('Folder of static files to upload, relative to the directory (e.g. "./dist"). Only needed for plain static sites without a wrangler config.'), |
| 36 | + buildCommand: z |
| 37 | + .string() |
| 38 | + .optional() |
| 39 | + .describe('Command that builds the site before it is deployed, run in the directory. Defaults to the "build" script in package.json (run with the package manager the lockfile points to), if there is one. Set to "" to skip the build.'), |
| 40 | + accountId: z |
| 41 | + .string() |
| 42 | + .optional() |
| 43 | + .describe('Cloudflare account ID to deploy to. Only needed when your login can access more than one account.'), |
| 44 | + }) |
| 45 | + .meta({ $comment: 'https://codifycli.com/docs/resources/cloudflare/cloudflare-worker' }) |
| 46 | + .describe('Deploy a site or app to Cloudflare Workers on a free workers.dev URL. It is deployed once, when no Worker with this name exists: later changes are shipped with `wrangler deploy`. A brand-new account is asked to pick its workers.dev subdomain during the first deploy.'); |
| 47 | + |
| 48 | +export type CloudflareWorkerConfig = z.infer<typeof schema>; |
| 49 | + |
| 50 | +const defaultConfig: Partial<CloudflareWorkerConfig> = { |
| 51 | + workerName: '<Replace me here!>', |
| 52 | + directory: '<Replace me here!>', |
| 53 | +}; |
| 54 | + |
| 55 | +export class CloudflareWorkerResource extends Resource<CloudflareWorkerConfig> { |
| 56 | + getSettings(): ResourceSettings<CloudflareWorkerConfig> { |
| 57 | + return { |
| 58 | + id: 'cloudflare-worker', |
| 59 | + defaultConfig, |
| 60 | + exampleConfigs: { |
| 61 | + example1: exampleDeployNewSite, |
| 62 | + example2: exampleDeployExistingSite, |
| 63 | + }, |
| 64 | + operatingSystems: [OS.Darwin, OS.Linux], |
| 65 | + schema, |
| 66 | + dependencies: ['wrangler', 'wrangler-auth', 'git-repository', 'git-repositories', 'project-install', 'project-installs'], |
| 67 | + parameterSettings: { |
| 68 | + // Only the Worker on Cloudflare is tracked. The rest describes how to deploy it the first time. |
| 69 | + directory: { type: 'directory', setting: true }, |
| 70 | + framework: { type: 'string', setting: true }, |
| 71 | + assets: { type: 'string', setting: true }, |
| 72 | + buildCommand: { type: 'string', setting: true }, |
| 73 | + accountId: { type: 'string', setting: true }, |
| 74 | + }, |
| 75 | + importAndDestroy: { |
| 76 | + requiredParameters: ['workerName'], |
| 77 | + }, |
| 78 | + allowMultiple: { |
| 79 | + identifyingParameters: ['workerName'], |
| 80 | + }, |
| 81 | + }; |
| 82 | + } |
| 83 | + |
| 84 | + async refresh(parameters: Partial<CloudflareWorkerConfig>): Promise<Partial<CloudflareWorkerConfig> | null> { |
| 85 | + const $ = getPty(); |
| 86 | + const { workerName: name, directory, accountId } = parameters; |
| 87 | + if (!name) { |
| 88 | + return null; |
| 89 | + } |
| 90 | + |
| 91 | + // Run from the project so an account_id in its wrangler config is used, otherwise somewhere without a config. |
| 92 | + // The refresh shell ignores the env option and is shared between commands, so both go inline, in a subshell. |
| 93 | + const cwd = directory && await isDirectory(directory) ? directory : os.homedir(); |
| 94 | + const accountPrefix = accountId ? `CLOUDFLARE_ACCOUNT_ID=${quote(accountId)} ` : ''; |
| 95 | + const { data, status } = await $.spawnSafe( |
| 96 | + `(cd ${quote(cwd)} && ${accountPrefix}wrangler deployments list --name ${quote(name)} --json)`, |
| 97 | + ); |
| 98 | + |
| 99 | + const lookup = interpretDeploymentsList(status === SpawnStatus.SUCCESS, data); |
| 100 | + if (lookup === 'multiple-accounts') { |
| 101 | + throw new Error(`cloudflare-worker "${name}": your Cloudflare login can access more than one account. Set accountId to the account to deploy to (run \`wrangler whoami\` to list them).`); |
| 102 | + } |
| 103 | + |
| 104 | + // 'unknown' is usually "not logged in yet" or "wrangler not installed yet" during the first plan. Deploying is |
| 105 | + // the right call then too: the deploy reports any real problem. |
| 106 | + return lookup === 'exists' ? { workerName: name } : null; |
| 107 | + } |
| 108 | + |
| 109 | + async create(plan: CreatePlan<CloudflareWorkerConfig>): Promise<void> { |
| 110 | + const { workerName: name, directory, framework, assets, buildCommand, accountId } = plan.desiredConfig; |
| 111 | + const $ = getPty(); |
| 112 | + const env = accountEnv(accountId); |
| 113 | + |
| 114 | + if (!await isDirectory(directory)) { |
| 115 | + if (!framework) { |
| 116 | + throw new Error(`cloudflare-worker "${name}": ${directory} doesn't exist. Clone the project first (git-repository) or set framework to scaffold a new one.`); |
| 117 | + } |
| 118 | + |
| 119 | + const parent = path.dirname(directory); |
| 120 | + await fs.mkdir(parent, { recursive: true }); |
| 121 | + // create-cloudflare and the framework CLIs it runs can ask questions, so the terminal is attached. |
| 122 | + await $.spawn(buildScaffoldCommand(path.basename(directory), framework), { |
| 123 | + cwd: parent, |
| 124 | + interactive: true, |
| 125 | + stdin: true, |
| 126 | + }); |
| 127 | + } |
| 128 | + |
| 129 | + const files = await readProjectFiles(directory); |
| 130 | + if (!files) { |
| 131 | + throw new Error(`cloudflare-worker "${name}": unable to read ${directory}.`); |
| 132 | + } |
| 133 | + |
| 134 | + const build = buildCommand ?? defaultBuildCommand(files); |
| 135 | + if (build) { |
| 136 | + await $.spawn(wrapCommand(build, directory, 'npm', files), { interactive: true, env }); |
| 137 | + } |
| 138 | + |
| 139 | + // Prefer the wrangler version the project pins (create-cloudflare adds one) over the global one. |
| 140 | + const localWrangler = path.join(directory, 'node_modules', '.bin', 'wrangler'); |
| 141 | + const wranglerBinary = await fileExists(localWrangler) ? quote(localWrangler) : 'wrangler'; |
| 142 | + |
| 143 | + // Attached to the terminal: on a new account wrangler asks to register the workers.dev subdomain, and it may ask |
| 144 | + // to confirm the config it generates for projects that don't have one. |
| 145 | + await $.spawn(buildDeployCommand({ |
| 146 | + assets, |
| 147 | + compatibilityDate: assets && !hasWranglerConfig(files) ? today() : undefined, |
| 148 | + name, |
| 149 | + wranglerBinary, |
| 150 | + }), { cwd: directory, interactive: true, stdin: true, env }); |
| 151 | + } |
| 152 | + |
| 153 | + async destroy(plan: DestroyPlan<CloudflareWorkerConfig>): Promise<void> { |
| 154 | + const $ = getPty(); |
| 155 | + const { workerName: name, accountId } = plan.currentConfig; |
| 156 | + |
| 157 | + // Deletes the Worker on Cloudflare only. The local project is left alone. --force skips wrangler's own |
| 158 | + // confirmation (the Codify plan was already confirmed). |
| 159 | + await $.spawn(`wrangler delete ${quote(name)} --force`, { |
| 160 | + cwd: os.homedir(), |
| 161 | + interactive: true, |
| 162 | + env: accountEnv(accountId), |
| 163 | + }); |
| 164 | + } |
| 165 | +} |
| 166 | + |
| 167 | +function accountEnv(accountId?: string): Record<string, string> | undefined { |
| 168 | + return accountId ? { CLOUDFLARE_ACCOUNT_ID: accountId } : undefined; |
| 169 | +} |
| 170 | + |
| 171 | +async function isDirectory(p: string): Promise<boolean> { |
| 172 | + try { |
| 173 | + return (await fs.stat(p)).isDirectory(); |
| 174 | + } catch { |
| 175 | + return false; |
| 176 | + } |
| 177 | +} |
| 178 | + |
| 179 | +async function fileExists(p: string): Promise<boolean> { |
| 180 | + try { |
| 181 | + await fs.access(p); |
| 182 | + return true; |
| 183 | + } catch { |
| 184 | + return false; |
| 185 | + } |
| 186 | +} |
0 commit comments