Skip to content

Commit 8abe7a3

Browse files
committed
Add wrangler, wrangler-auth and cloudflare-worker resources
wrangler installs the Cloudflare CLI globally with npm (checks for Node.js 22.12+). wrangler-auth logs in through the browser, with device code and OS keychain options. cloudflare-worker deploys a project to a workers.dev URL once, when no Worker with that name exists, optionally scaffolding it with create-cloudflare first, and deletes the Worker on destroy. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016QnBk4EcmhRfUY4BYKFpK7
1 parent 35ac7ad commit 8abe7a3

8 files changed

Lines changed: 721 additions & 0 deletions

File tree

‎src/index.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,9 @@ import { Virtualenv } from './resources/python/virtualenv/virtualenv.js';
4848
import { VirtualenvProject } from './resources/python/virtualenv/virtualenv-project.js';
4949
import { RbenvResource } from './resources/ruby/rbenv/rbenv.js';
5050
import { RustResource } from './resources/rust/rust-resource.js';
51+
import { CloudflareWorkerResource } from './resources/cloudflare/cloudflare-worker.js';
52+
import { WranglerResource } from './resources/cloudflare/wrangler.js';
53+
import { WranglerAuthResource } from './resources/cloudflare/wrangler-auth.js';
5154
import { ActionResource } from './resources/scripting/action.js';
5255
import { AliasResource } from './resources/shell/alias/alias-resource.js';
5356
import { AliasesResource } from './resources/shell/aliases/aliases-resource.js';
@@ -177,6 +180,9 @@ runPlugin(Plugin.create(
177180
new GithubCliSshKeyResource(),
178181
new ProjectInstallResource(),
179182
new ProjectInstallsResource(),
183+
new WranglerResource(),
184+
new WranglerAuthResource(),
185+
new CloudflareWorkerResource(),
180186
],
181187
{ minSupportedCliVersion: MIN_SUPPORTED_CLI_VERSION }
182188
))
Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
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+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import { ExampleConfig } from '@codifycli/plugin-core';
2+
3+
export const exampleDeployNewSite: ExampleConfig = {
4+
title: 'Deploy a new Astro site to Cloudflare',
5+
description: 'Install Node.js and wrangler, log in to Cloudflare in the browser, scaffold an Astro site and deploy it to a free workers.dev URL. No domain needed.',
6+
configs: [
7+
{ type: 'nvm', nodeVersions: ['lts'], global: 'lts' },
8+
{ type: 'wrangler' },
9+
{ type: 'wrangler-auth' },
10+
{
11+
type: 'cloudflare-worker',
12+
workerName: 'my-site',
13+
directory: '~/projects/my-site',
14+
framework: 'astro',
15+
},
16+
],
17+
};
18+
19+
export const exampleDeployExistingSite: ExampleConfig = {
20+
title: 'Deploy an existing site from GitHub',
21+
description: 'Clone a site, install its dependencies and deploy it to Cloudflare. wrangler detects the framework and adds a Cloudflare config when the project has none.',
22+
configs: [
23+
{ type: 'nvm', nodeVersions: ['lts'], global: 'lts' },
24+
{ type: 'wrangler' },
25+
{ type: 'wrangler-auth' },
26+
{ type: 'git-repository', repository: 'https://github.com/<Replace me here!>.git', directory: '~/projects/my-site' },
27+
{ type: 'project-install', directory: '~/projects/my-site' },
28+
{ type: 'cloudflare-worker', workerName: 'my-site', directory: '~/projects/my-site' },
29+
],
30+
};
31+
32+
export const exampleWranglerBasic: ExampleConfig = {
33+
title: 'Install wrangler with Node.js',
34+
description: 'Install the Node.js LTS with nvm (wrangler needs Node.js 22.12 or newer), then install the wrangler CLI globally.',
35+
configs: [
36+
{ type: 'nvm', nodeVersions: ['lts'], global: 'lts' },
37+
{ type: 'wrangler' },
38+
],
39+
};
40+
41+
export const exampleWranglerAuthDevice: ExampleConfig = {
42+
title: 'Log in to Cloudflare from a VM or SSH session',
43+
description: 'Use the device code flow, which works where the browser can\'t reach the machine, and keep the credentials in the OS keychain.',
44+
configs: [
45+
{ type: 'wrangler' },
46+
{ type: 'wrangler-auth', device: true, useKeyring: true },
47+
],
48+
};
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import { CreatePlan, DestroyPlan, Resource, ResourceSettings, SpawnStatus, getPty, z } from '@codifycli/plugin-core';
2+
import { OS } from '@codifycli/schemas';
3+
4+
import { exampleDeployNewSite, exampleWranglerAuthDevice } from './examples.js';
5+
import { parseWhoami } from './wrangler-utils.js';
6+
7+
export const schema = z
8+
.object({
9+
device: z
10+
.boolean()
11+
.optional()
12+
.describe('Log in with a device code instead of the localhost callback. Use this in VMs, containers and SSH sessions where the browser can\'t reach the machine. Defaults to false.'),
13+
useKeyring: z
14+
.boolean()
15+
.optional()
16+
.describe('Store the OAuth credentials in the OS keychain instead of a plaintext file. Defaults to false.'),
17+
})
18+
.meta({ $comment: 'https://codifycli.com/docs/resources/cloudflare/wrangler-auth' })
19+
.describe('Log wrangler in to Cloudflare through the browser. New users can sign up for a free account on the same page. Being logged in through the CLOUDFLARE_API_TOKEN environment variable also counts.');
20+
21+
export type WranglerAuthConfig = z.infer<typeof schema>;
22+
23+
export class WranglerAuthResource extends Resource<WranglerAuthConfig> {
24+
getSettings(): ResourceSettings<WranglerAuthConfig> {
25+
return {
26+
id: 'wrangler-auth',
27+
defaultConfig: {},
28+
exampleConfigs: {
29+
example1: exampleDeployNewSite,
30+
example2: exampleWranglerAuthDevice,
31+
},
32+
operatingSystems: [OS.Darwin, OS.Linux],
33+
schema,
34+
dependencies: ['wrangler'],
35+
parameterSettings: {
36+
device: { type: 'boolean', setting: true },
37+
useKeyring: { type: 'boolean', setting: true },
38+
},
39+
};
40+
}
41+
42+
async refresh(): Promise<Partial<WranglerAuthConfig> | null> {
43+
const $ = getPty();
44+
const { data, status } = await $.spawnSafe('wrangler whoami --json');
45+
if (status !== SpawnStatus.SUCCESS) {
46+
return null;
47+
}
48+
49+
return parseWhoami(data) ? {} : null;
50+
}
51+
52+
async create(plan: CreatePlan<WranglerAuthConfig>): Promise<void> {
53+
const $ = getPty();
54+
const { device, useKeyring } = plan.desiredConfig;
55+
56+
const flags = [device ? ' --device' : '', useKeyring ? ' --use-keyring' : ''].join('');
57+
await $.spawn(`wrangler login${flags}`, { interactive: true, stdin: true });
58+
}
59+
60+
async destroy(_plan: DestroyPlan<WranglerAuthConfig>): Promise<void> {
61+
const $ = getPty();
62+
await $.spawn('wrangler logout', { interactive: true });
63+
}
64+
}

0 commit comments

Comments
 (0)