@theholocron/holocron-plugin-cloudflare 5.0.0-alpha.42 → 5.0.0-alpha.421

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  # `@theholocron/holocron-plugin-cloudflare`
4
4
 
5
5
  Cloudflare plugin for [Holocron](../cli). Implements the `dns`, `deployment`,
6
- and `workers` capabilities against the
6
+ `workers` and `tunnels` capabilities against the
7
7
  [Cloudflare v4 API](https://developers.cloudflare.com/api/).
8
8
 
9
9
  ## Install
@@ -63,9 +63,10 @@ Any combination of capabilities can be enabled together:
63
63
 
64
64
  ```
65
65
 
66
- The `deployment` and `workers` capabilities are only exposed when `accountId`
67
- is resolvable — either passed explicitly in options or set via the
68
- `CLOUDFLARE_ACCOUNT_ID` env var.
66
+ The `deployment`, `workers` and `tunnels` capabilities are only exposed when `accountId`
67
+ is resolvable — either passed explicitly in options or set as the
68
+ `HOLOCRON_CLOUDFLARE_ACCOUNT_ID` (or `CLOUDFLARE_ACCOUNT_ID`) env var or in a `credentials` provider's Environment (the option wins, then the
69
+ environment, then the provider).
69
70
 
70
71
  ## `dns` capability
71
72
 
@@ -79,7 +80,7 @@ Zone ids are cached per plugin instance for the lifetime of the process.
79
80
 
80
81
  ## `deployment` capability
81
82
 
82
- Manages [Cloudflare Pages](https://developers.cloudflare.com/pages/) projects. Used by `holocron setup` to provision per-PR preview deployments.
83
+ Manages [Cloudflare Pages](https://developers.cloudflare.com/pages/) projects. Used by `holocron repo setup` to provision per-PR preview deployments.
83
84
 
84
85
  | Method | What it does |
85
86
  | ----------------------- | ----------------------------------------------------------------------------------------------------------------------- |
@@ -104,9 +105,24 @@ route-write call when nothing changed. Zone ids are cached per plugin
104
105
  instance for the lifetime of the process — the `workers` capability's own
105
106
  cache, separate from `dns`'s.
106
107
 
108
+ ## `tunnels` capability
109
+
110
+ Named [Cloudflare Tunnels](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/): a stable
111
+ public hostname that reaches a port on this machine, for a webhook that has to find a development instance. It needs a
112
+ token with **Cloudflare Tunnel: Edit** (account).
113
+
114
+ | Method | What it does |
115
+ | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
116
+ | `ensureTunnel` | Finds the tunnel by name or makes it, and makes its configuration serve `hostname` at `service`. Other hostnames' rules are kept and the catch-all (`http_status:404`) stays last. Returns the tunnel id and the `CNAME` target (`<id>.cfargotunnel.com`). |
117
+ | `tunnelToken` | The token `cloudflared` runs the tunnel with. A credential: never printed or stored. |
118
+ | `whoami` | How many tunnels the token can see, for `holocron doctor`. |
119
+
120
+ `ensureTunnel` is idempotent: a tunnel that already serves the hostname is not rewritten. The DNS record for the
121
+ hostname is the `dns` provider's job.
122
+
107
123
  ### Preview deployment setup
108
124
 
109
- When `preview: true` (or `preview: { project, domain }`) is set in a repo's deploy config, `holocron setup` calls:
125
+ When `preview: true` (or `preview: { project, domain }`) is set in a repo's deploy config, `holocron repo setup` calls:
110
126
 
111
127
  1. `ensureProject` — creates `<org>-preview` if it doesn't exist
112
128
  2. `ensureCustomDomain` — attaches `*.<domain>` to the project
package/dist/index.d.mts CHANGED
@@ -1,15 +1,19 @@
1
- import { AuthError, DeployScriptConfig, DeployScriptResult, Deployment, DeploymentProject, DeploymentProjectSettings, DeploymentRecord, DeploymentTarget, DeploymentTrigger, Dns, DnsRecord, DnsRecordRequest, ResolveTokenInput, WikiProxyConfig, Workers } from "@theholocron/cli";
1
+ import { AuthError, DeployScriptConfig, DeployScriptResult, Deployment, DeploymentProject, DeploymentProjectSettings, DeploymentRecord, DeploymentTarget, DeploymentTrigger, Dns, DnsRecord, DnsRecordRequest, EnsuredTunnel, PluginToken, ResolveTokenInput, TunnelRoute, Tunnels, VerifyTokenFailure, VerifyTokenResult, VerifyTokenResult as VerifyTokenResult$1, VerifyTokenSuccess, WikiProxyConfig, WorkerScriptState, Workers } from "@theholocron/cli";
2
2
  import { CloudflareClient, CloudflareClient as CloudflareClient$1, CloudflareClientOptions, createCloudflareClient } from "@theholocron/cloudflare-client";
3
- //#region src/auth.d.ts
4
- declare const resolveToken: (input?: ResolveTokenInput) => string;
5
- //#endregion
6
- //#region src/capabilities/deployment.d.ts
7
- declare class CloudflareDeployment implements Deployment {
3
+ /** Resolves the Cloudflare API token from `--token`, `HOLOCRON_CLOUDFLARE_TOKEN`, `CLOUDFLARE_API_TOKEN` or the keyring, and throws an `AuthError` when none is set. */
4
+ export declare const resolveToken: import("@theholocron/cli").TokenResolver;
5
+ /** Every token this plugin takes, for `holocron doctor tokens`. */
6
+ export declare const tokens: PluginToken[];
7
+ /** The Cloudflare implementation of the `deployment` capability, backed by Cloudflare Pages projects in one account. */
8
+ export declare class CloudflareDeployment implements Deployment {
8
9
  private readonly client;
9
10
  private readonly accountId;
11
+ /** The capability this class provides, always `"deployment"`. */
10
12
  readonly key: "deployment";
13
+ /** The provider name, `"cloudflare"`. */
11
14
  readonly providerName = "cloudflare";
12
15
  constructor(client: () => CloudflareClient, accountId: string);
16
+ /** Lists the account's Pages projects. */
13
17
  listProjects(): Promise<DeploymentProject[]>;
14
18
  ensureProject(input: {
15
19
  name: string;
@@ -17,31 +21,44 @@ declare class CloudflareDeployment implements Deployment {
17
21
  repo?: string;
18
22
  rootDirectory?: string;
19
23
  }): Promise<DeploymentProject>;
24
+ /** Returns the project as it is now; Pages has no REST setting for the requested options, so `settings` is ignored. */
20
25
  updateProjectSettings(projectId: string, settings: DeploymentProjectSettings): Promise<DeploymentProject>;
26
+ /** Lists the names of the environment variables set for the production or preview target. */
21
27
  listEnvVars(projectId: string, target: DeploymentTarget): Promise<string[]>;
28
+ /** Sets a plain-text environment variable on the production or preview target, keeping the others. */
22
29
  setEnvVar(projectId: string, target: DeploymentTarget, name: string, value: string): Promise<void>;
23
30
  triggerDeployment(input: {
24
31
  projectId: string;
25
32
  branch: string;
26
33
  target?: DeploymentTrigger;
27
34
  }): Promise<DeploymentRecord>;
35
+ /** Fetches a deployment by an id of the form `projectName:deploymentId`; throws a 400 `ProviderApiError` for any other form. */
28
36
  getDeployment(deploymentId: string): Promise<DeploymentRecord>;
29
37
  listPreviewDeployments(projectId: string, branch: string): Promise<DeploymentRecord[]>;
30
38
  deletePreviewDeployments(projectId: string, deploymentIds: string[]): Promise<number>;
31
39
  ensureCustomDomain(projectId: string, hostname: string): Promise<DnsRecordRequest | null>;
32
40
  private getProjectByName;
33
41
  }
34
- //#endregion
35
- //#region src/capabilities/dns.d.ts
36
- declare class CloudflareDns implements Dns {
42
+ /** The Cloudflare implementation of the `dns` capability; finds a domain's zone by walking from the domain up to its apex. */
43
+ export declare class CloudflareDns implements Dns {
37
44
  private readonly client;
45
+ /** The capability this class provides, always `"dns"`. */
38
46
  readonly key: "dns";
47
+ /** The provider name, `"cloudflare"`. */
39
48
  readonly providerName = "cloudflare";
40
49
  private readonly zoneCache;
41
50
  constructor(client: () => CloudflareClient);
51
+ /** Lists the DNS records in the zone that holds the domain. */
42
52
  listRecords(domain: string): Promise<DnsRecord[]>;
53
+ /** Updates the first record of the same type and name, or creates the record when there is none; returns the stored record. */
43
54
  upsertRecord(domain: string, record: DnsRecord): Promise<DnsRecord>;
55
+ /** Deletes the DNS record with this id from the zone that holds the domain. */
44
56
  deleteRecord(domain: string, id: string): Promise<void>;
57
+ /** `holocron doctor` has no specific domain to check — lists every zone the token can see instead. */
58
+ whoami(): Promise<{
59
+ ok: boolean;
60
+ zones: number;
61
+ }>;
45
62
  /**
46
63
  * Walk from full domain up to apex to find the Cloudflare zone.
47
64
  * E.g. "api.staging.example.com" tries:
@@ -51,40 +68,61 @@ declare class CloudflareDns implements Dns {
51
68
  */
52
69
  private resolveZone;
53
70
  }
54
- //#endregion
55
- //#region src/capabilities/workers.d.ts
56
- declare class CloudflareWorkers implements Workers {
71
+ /** The Cloudflare implementation of the `tunnels` capability, backed by Cloudflare Tunnel in one account. */
72
+ export declare class CloudflareTunnels implements Tunnels {
57
73
  private readonly client;
58
74
  private readonly accountId;
75
+ /** The capability this class provides, always `"tunnels"`. */
76
+ readonly key: "tunnels";
77
+ /** The provider name, `"cloudflare"`. */
78
+ readonly providerName = "cloudflare";
79
+ constructor(client: () => Pick<CloudflareClient$1, "tunnels">, accountId: string);
80
+ /** Finds the tunnel by name or makes it, then rewrites its routes only when they do not already serve the hostname. */
81
+ ensureTunnel(route: TunnelRoute): Promise<EnsuredTunnel>;
82
+ /** The token `cloudflared` runs the tunnel with. */
83
+ tunnelToken(tunnelId: string): Promise<string>;
84
+ /** `holocron doctor` has no specific tunnel to check: lists the ones the token can see. */
85
+ whoami(): Promise<{
86
+ ok: boolean;
87
+ tunnels: number;
88
+ }>;
89
+ }
90
+ /** The Cloudflare implementation of the `workers` capability, backed by Workers scripts and routes in one account. */
91
+ export declare class CloudflareWorkers implements Workers {
92
+ private readonly client;
93
+ private readonly accountId;
94
+ /** The capability this class provides, always `"workers"`. */
59
95
  readonly key: "workers";
96
+ /** The provider name, `"cloudflare"`. */
60
97
  readonly providerName = "cloudflare";
61
98
  private readonly zoneCache;
62
99
  constructor(client: () => Pick<CloudflareClient$1, "workers" | "zones">, accountId: string);
63
100
  upsertProxy(hostname: string, config: WikiProxyConfig): Promise<void>;
101
+ /** `holocron doctor` has no specific script to check — lists every script the token can see instead. */
102
+ whoami(): Promise<{
103
+ ok: boolean;
104
+ scripts: number;
105
+ }>;
64
106
  deployScript(name: string, config: DeployScriptConfig): Promise<DeployScriptResult>;
107
+ setSecret(script: string, name: string, value: string): Promise<void>;
108
+ secretNames(script: string): Promise<string[]>;
109
+ /**
110
+ * Whether the script exists, which routes in the zone of `host` point at it, and the names of its secrets. Reads
111
+ * only, and asks Cloudflare for names, so no value is ever fetched.
112
+ */
113
+ inspectScript(name: string, host: string): Promise<WorkerScriptState>;
65
114
  /** Idempotent create-or-update for one route pattern — shared by both public methods. */
66
115
  private upsertRoute;
67
116
  private resolveZone;
68
117
  }
69
- //#endregion
70
- //#region src/verify-token.d.ts
71
- interface VerifyTokenSuccess {
72
- ok: true;
73
- subject: string;
74
- }
75
- interface VerifyTokenFailure {
76
- ok: false;
77
- message: string;
78
- }
79
- type VerifyTokenResult = VerifyTokenSuccess | VerifyTokenFailure;
80
118
  interface VerifyTokenOptions {
81
119
  baseUrl?: string;
82
120
  fetch?: typeof fetch;
83
121
  }
84
- declare function verifyToken(token: string, opts?: VerifyTokenOptions): Promise<VerifyTokenResult>;
85
- //#endregion
86
- //#region src/index.d.ts
87
- interface CloudflarePluginOptions extends ResolveTokenInput {
122
+ /** Checks a Cloudflare API token, first by the token-verify endpoint and otherwise by listing zones; resolves to a description of what it found, or the failure message. */
123
+ export declare function verifyToken(token: string, opts?: VerifyTokenOptions): Promise<VerifyTokenResult$1>;
124
+ /** Options for the Cloudflare plugin: how the API token is resolved, the account, and test overrides. */
125
+ export interface CloudflarePluginOptions extends ResolveTokenInput {
88
126
  /**
89
127
  * Cloudflare account ID. Required for Pages (deployment) operations;
90
128
  * optional for DNS-only use.
@@ -92,27 +130,41 @@ interface CloudflarePluginOptions extends ResolveTokenInput {
92
130
  accountId?: string;
93
131
  /** Override base URL for tests. */
94
132
  baseUrl?: string;
133
+ /** The `fetch` to use instead of the global one, for tests. */
95
134
  fetch?: typeof fetch;
96
135
  }
97
- interface PluginContext {
136
+ /** The shared state the Cloudflare plugin's capabilities and probes are built from. */
137
+ export interface PluginContext {
138
+ /** The options the plugin was created with, with `accountId` falling back to `CLOUDFLARE_ACCOUNT_ID` in the environment, then in the `credentials` providers' variables. */
98
139
  options: CloudflarePluginOptions;
99
140
  /** Memoized client — the token is resolved on first use, not at plugin load. */
100
141
  client: () => CloudflareClient;
101
142
  /** Memoized token resolver — shared by the client and the Workers capability. */
102
143
  token: () => string;
103
144
  }
104
- declare function createContext(options?: CloudflarePluginOptions): PluginContext;
105
- declare function dns(ctx: PluginContext): Dns;
106
- declare function deployment(ctx: PluginContext): Deployment;
107
- declare function workersCapability(ctx: PluginContext): Workers;
108
- declare function createPlugin(options?: CloudflarePluginOptions): {
145
+ /** Builds the plugin context from its options; the API token is resolved lazily on the first client use. */
146
+ export declare function createContext(options?: CloudflarePluginOptions): PluginContext;
147
+ /** Builds the `dns` capability for a context. */
148
+ export declare function dns(ctx: PluginContext): Dns;
149
+ /** Builds the `deployment` capability for a context; throws when no account id is set. */
150
+ export declare function deployment(ctx: PluginContext): Deployment;
151
+ /** Builds the `workers` capability for a context; throws when no account id is set. */
152
+ export declare function workersCapability(ctx: PluginContext): Workers;
153
+ /** Builds the `tunnels` capability for a context; throws when no account id is set. */
154
+ export declare function tunnelsCapability(ctx: PluginContext): Tunnels;
155
+ /** Creates the Cloudflare plugin: `dns` always, plus `deployment`, `workers` and `tunnels` when an account id is set, and a `connection` probe. */
156
+ export declare function createPlugin(options?: CloudflarePluginOptions): {
109
157
  name: string;
158
+ probes: {
159
+ connection: import("@theholocron/cli").Probe;
160
+ };
110
161
  capabilities: {
111
162
  deployment?: (() => Deployment) | undefined;
112
163
  workers?: (() => Workers) | undefined;
164
+ tunnels?: (() => Tunnels) | undefined;
113
165
  dns: () => Dns;
114
166
  };
115
167
  };
116
- declare const AUTH_HINT: string;
117
- //#endregion
118
- export { AUTH_HINT, AuthError, type CloudflareClient, type CloudflareClientOptions, CloudflareDeployment, CloudflareDns, CloudflarePluginOptions, CloudflareWorkers, PluginContext, type ResolveTokenInput, type VerifyTokenFailure, type VerifyTokenResult, type VerifyTokenSuccess, createCloudflareClient, createContext, createPlugin, deployment, dns, resolveToken, verifyToken, workersCapability };
168
+ /** One-line hint printed by `holocron auth set cloudflare` when no token is supplied or the supplied one is rejected. */
169
+ export declare const AUTH_HINT: string;
170
+ export { AuthError, type CloudflareClient, type CloudflareClientOptions, type ResolveTokenInput, type VerifyTokenFailure, type VerifyTokenResult, type VerifyTokenSuccess, createCloudflareClient };
package/dist/index.mjs CHANGED
@@ -1,23 +1,31 @@
1
- import { AuthError, ProviderApiError, createResolveToken } from "@theholocron/cli";
1
+ import { AuthError, ProviderApiError, connectionProbe, createResolveToken, resolveValue } from "@theholocron/cli";
2
+ import { PREFIX } from "@theholocron/env-utils/lookup";
2
3
  import { createCloudflareClient } from "@theholocron/cloudflare-client";
3
- //#region src/auth.ts
4
+ import { errorMessage } from "@theholocron/misc-utils";
5
+ // src/auth.ts
6
+ /** Resolves the Cloudflare API token from `--token`, `HOLOCRON_CLOUDFLARE_TOKEN`, `CLOUDFLARE_API_TOKEN` or the keyring, and throws an `AuthError` when none is set. */
4
7
  const resolveToken = createResolveToken({
5
8
  envName: "HOLOCRON_CLOUDFLARE_TOKEN",
6
9
  vendorEnvName: "CLOUDFLARE_API_TOKEN",
7
10
  keyringService: "cloudflare",
8
11
  errorMessage: "no Cloudflare API token found. Pass --token <TOKEN>, set HOLOCRON_CLOUDFLARE_TOKEN / CLOUDFLARE_API_TOKEN, or run: holocron auth set cloudflare <TOKEN>"
9
12
  });
10
- //#endregion
11
- //#region src/capabilities/deployment.ts
13
+ /** Every token this plugin takes, for `holocron doctor tokens`. */
14
+ const tokens = [resolveToken.token];
15
+ // src/capabilities/deployment.ts
16
+ /** The Cloudflare implementation of the `deployment` capability, backed by Cloudflare Pages projects in one account. */
12
17
  var CloudflareDeployment = class {
13
18
  client;
14
19
  accountId;
20
+ /** The capability this class provides, always `"deployment"`. */
15
21
  key = "deployment";
22
+ /** The provider name, `"cloudflare"`. */
16
23
  providerName = "cloudflare";
17
24
  constructor(client, accountId) {
18
25
  this.client = client;
19
26
  this.accountId = accountId;
20
27
  }
28
+ /** Lists the account's Pages projects. */
21
29
  async listProjects() {
22
30
  return (await this.client().pages.listProjects(this.accountId)).map(mapProject);
23
31
  }
@@ -29,14 +37,17 @@ var CloudflareDeployment = class {
29
37
  production_branch: "main"
30
38
  }));
31
39
  }
40
+ /** Returns the project as it is now; Pages has no REST setting for the requested options, so `settings` is ignored. */
32
41
  async updateProjectSettings(projectId, settings) {
33
42
  return mapProject(await this.client().pages.getProject(this.accountId, projectId));
34
43
  }
44
+ /** Lists the names of the environment variables set for the production or preview target. */
35
45
  async listEnvVars(projectId, target) {
36
46
  const project = await this.client().pages.getProject(this.accountId, projectId);
37
47
  const envConfig = target === "production" ? project.deployment_configs.production : project.deployment_configs.preview;
38
48
  return Object.keys(envConfig.env_vars);
39
49
  }
50
+ /** Sets a plain-text environment variable on the production or preview target, keeping the others. */
40
51
  async setEnvVar(projectId, target, name, value) {
41
52
  const cfg = (await this.client().pages.getProject(this.accountId, projectId)).deployment_configs;
42
53
  const scope = target === "production" ? "production" : "preview";
@@ -55,6 +66,7 @@ var CloudflareDeployment = class {
55
66
  async triggerDeployment(input) {
56
67
  return mapDeployment(await this.client().pages.createDeployment(this.accountId, input.projectId, input.branch), input.projectId, input.branch, input.target);
57
68
  }
69
+ /** Fetches a deployment by an id of the form `projectName:deploymentId`; throws a 400 `ProviderApiError` for any other form. */
58
70
  async getDeployment(deploymentId) {
59
71
  const sep = deploymentId.indexOf(":");
60
72
  if (sep === -1) throw new ProviderApiError(`Invalid Cloudflare Pages deployment id "${deploymentId}" — expected "projectName:deploymentId"`, 400, void 0);
@@ -114,20 +126,24 @@ function normalizeStatus(status) {
114
126
  default: return "error";
115
127
  }
116
128
  }
117
- //#endregion
118
- //#region src/capabilities/dns.ts
129
+ // src/capabilities/dns.ts
130
+ /** The Cloudflare implementation of the `dns` capability; finds a domain's zone by walking from the domain up to its apex. */
119
131
  var CloudflareDns = class {
120
132
  client;
133
+ /** The capability this class provides, always `"dns"`. */
121
134
  key = "dns";
135
+ /** The provider name, `"cloudflare"`. */
122
136
  providerName = "cloudflare";
123
137
  zoneCache = /* @__PURE__ */ new Map();
124
138
  constructor(client) {
125
139
  this.client = client;
126
140
  }
141
+ /** Lists the DNS records in the zone that holds the domain. */
127
142
  async listRecords(domain) {
128
143
  const zoneId = await this.resolveZone(domain);
129
144
  return (await this.client().dns.list(zoneId)).map(mapRecord);
130
145
  }
146
+ /** Updates the first record of the same type and name, or creates the record when there is none; returns the stored record. */
131
147
  async upsertRecord(domain, record) {
132
148
  const client = this.client();
133
149
  const zoneId = await this.resolveZone(domain);
@@ -150,10 +166,18 @@ var CloudflareDns = class {
150
166
  ...record.proxied !== void 0 ? { proxied: record.proxied } : {}
151
167
  }));
152
168
  }
169
+ /** Deletes the DNS record with this id from the zone that holds the domain. */
153
170
  async deleteRecord(domain, id) {
154
171
  const zoneId = await this.resolveZone(domain);
155
172
  await this.client().dns.delete(zoneId, id);
156
173
  }
174
+ /** `holocron doctor` has no specific domain to check — lists every zone the token can see instead. */
175
+ async whoami() {
176
+ return {
177
+ ok: true,
178
+ zones: (await this.client().zones.list()).length
179
+ };
180
+ }
157
181
  /**
158
182
  * Walk from full domain up to apex to find the Cloudflare zone.
159
183
  * E.g. "api.staging.example.com" tries:
@@ -182,15 +206,75 @@ function mapRecord(raw) {
182
206
  type: raw.type,
183
207
  name: raw.name,
184
208
  content: raw.content,
185
- ttl: raw.ttl
209
+ ttl: raw.ttl,
210
+ ...raw.proxied !== void 0 ? { proxied: raw.proxied } : {}
211
+ };
212
+ }
213
+ // src/capabilities/tunnels.ts
214
+ /** The rule a tunnel needs last: anything no other rule matches is answered with a 404 by the connector itself. */
215
+ const CATCH_ALL = { service: "http_status:404" };
216
+ /**
217
+ * The ingress rules with `hostname` served at `service`: the rule for the hostname is replaced where it is or added
218
+ * after the others, every other hostname's rule is kept, and the rule without a hostname closes the list.
219
+ */
220
+ function withRoute(current, hostname, service) {
221
+ const rule = {
222
+ hostname,
223
+ service
186
224
  };
225
+ const named = current.filter((r) => r.hostname !== void 0);
226
+ const at = named.findIndex((r) => r.hostname === hostname);
227
+ return [...at === -1 ? [...named, rule] : named.map((r, i) => i === at ? rule : r), current.find((r) => r.hostname === void 0) ?? CATCH_ALL];
187
228
  }
188
- //#endregion
189
- //#region src/capabilities/workers.ts
229
+ /** The Cloudflare implementation of the `tunnels` capability, backed by Cloudflare Tunnel in one account. */
230
+ var CloudflareTunnels = class {
231
+ client;
232
+ accountId;
233
+ /** The capability this class provides, always `"tunnels"`. */
234
+ key = "tunnels";
235
+ /** The provider name, `"cloudflare"`. */
236
+ providerName = "cloudflare";
237
+ constructor(client, accountId) {
238
+ this.client = client;
239
+ this.accountId = accountId;
240
+ }
241
+ /** Finds the tunnel by name or makes it, then rewrites its routes only when they do not already serve the hostname. */
242
+ async ensureTunnel(route) {
243
+ const { tunnels } = this.client();
244
+ const found = (await tunnels.list(this.accountId)).find((t) => t.name === route.name);
245
+ const tunnel = found ?? await tunnels.create(this.accountId, { name: route.name });
246
+ const current = (await tunnels.getConfig(this.accountId, tunnel.id)).config?.ingress ?? [];
247
+ const wanted = withRoute(current, route.hostname, route.service);
248
+ const configured = JSON.stringify(wanted) !== JSON.stringify(current);
249
+ if (configured) await tunnels.putConfig(this.accountId, tunnel.id, { ingress: wanted });
250
+ return {
251
+ id: tunnel.id,
252
+ name: tunnel.name,
253
+ created: found === void 0,
254
+ configured,
255
+ target: `${tunnel.id}.cfargotunnel.com`
256
+ };
257
+ }
258
+ /** The token `cloudflared` runs the tunnel with. */
259
+ tunnelToken(tunnelId) {
260
+ return this.client().tunnels.token(this.accountId, tunnelId);
261
+ }
262
+ /** `holocron doctor` has no specific tunnel to check: lists the ones the token can see. */
263
+ async whoami() {
264
+ return {
265
+ ok: true,
266
+ tunnels: (await this.client().tunnels.list(this.accountId)).length
267
+ };
268
+ }
269
+ };
270
+ // src/capabilities/workers.ts
271
+ /** The Cloudflare implementation of the `workers` capability, backed by Workers scripts and routes in one account. */
190
272
  var CloudflareWorkers = class {
191
273
  client;
192
274
  accountId;
275
+ /** The capability this class provides, always `"workers"`. */
193
276
  key = "workers";
277
+ /** The provider name, `"cloudflare"`. */
194
278
  providerName = "cloudflare";
195
279
  zoneCache = /* @__PURE__ */ new Map();
196
280
  constructor(client, accountId) {
@@ -203,12 +287,45 @@ var CloudflareWorkers = class {
203
287
  await this.client().workers.putScript(this.accountId, scriptName, script);
204
288
  await this.upsertRoute(`${hostname}/*`, scriptName);
205
289
  }
290
+ /** `holocron doctor` has no specific script to check — lists every script the token can see instead. */
291
+ async whoami() {
292
+ return {
293
+ ok: true,
294
+ scripts: (await this.client().workers.listScripts(this.accountId)).length
295
+ };
296
+ }
206
297
  async deployScript(name, config) {
207
298
  await this.client().workers.putScript(this.accountId, name, config.code);
208
299
  for (const [secretName, value] of Object.entries(config.secrets ?? {})) await this.client().workers.putSecret(this.accountId, name, secretName, value);
209
300
  for (const pattern of config.routes ?? []) await this.upsertRoute(pattern, name);
210
301
  return { scriptName: name };
211
302
  }
303
+ async setSecret(script, name, value) {
304
+ await this.client().workers.putSecret(this.accountId, script, name, value);
305
+ }
306
+ async secretNames(script) {
307
+ return (await this.client().workers.listSecrets(this.accountId, script)).map((secret) => secret.name);
308
+ }
309
+ /**
310
+ * Whether the script exists, which routes in the zone of `host` point at it, and the names of its secrets. Reads
311
+ * only, and asks Cloudflare for names, so no value is ever fetched.
312
+ */
313
+ async inspectScript(name, host) {
314
+ const client = this.client();
315
+ if (!(await client.workers.listScripts(this.accountId)).some((s) => s.id === name)) return {
316
+ exists: false,
317
+ routes: [],
318
+ bindingNames: []
319
+ };
320
+ const zoneId = await this.resolveZone(host);
321
+ const routes = await client.workers.listRoutes(zoneId);
322
+ const secrets = await client.workers.listSecrets(this.accountId, name);
323
+ return {
324
+ exists: true,
325
+ routes: routes.filter((r) => r.script === name).map((r) => r.pattern),
326
+ bindingNames: secrets.map((secret) => secret.name)
327
+ };
328
+ }
212
329
  /** Idempotent create-or-update for one route pattern — shared by both public methods. */
213
330
  async upsertRoute(pattern, scriptName) {
214
331
  const hostname = pattern.split("/")[0];
@@ -251,8 +368,8 @@ function generateProxyScript(config) {
251
368
  `};`
252
369
  ].join("\n");
253
370
  }
254
- //#endregion
255
- //#region src/verify-token.ts
371
+ // src/verify-token.ts
372
+ /** Checks a Cloudflare API token, first by the token-verify endpoint and otherwise by listing zones; resolves to a description of what it found, or the failure message. */
256
373
  async function verifyToken(token, opts = {}) {
257
374
  const client = createCloudflareClient({
258
375
  token,
@@ -267,21 +384,26 @@ async function verifyToken(token, opts = {}) {
267
384
  };
268
385
  } catch {}
269
386
  try {
387
+ const names = (await client.zones.list()).map((z) => z.name);
388
+ if (names.length === 0) return {
389
+ ok: true,
390
+ subject: "no zones visible"
391
+ };
270
392
  return {
271
393
  ok: true,
272
- subject: `zone: ${(await client.zones.list({ per_page: 1 }))[0]?.name ?? "unknown"}`
394
+ subject: `zones: ${names.length <= 5 ? names.join(", ") : `${names.slice(0, 5).join(", ")} (+${names.length - 5} more)`}`
273
395
  };
274
396
  } catch (err) {
275
397
  return {
276
398
  ok: false,
277
- message: err instanceof Error ? err.message : String(err)
399
+ message: errorMessage(err)
278
400
  };
279
401
  }
280
402
  }
281
- //#endregion
282
- //#region src/index.ts
403
+ // src/index.ts
404
+ /** Builds the plugin context from its options; the API token is resolved lazily on the first client use. */
283
405
  function createContext(options = {}) {
284
- const accountId = options.accountId ?? process.env.CLOUDFLARE_ACCOUNT_ID;
406
+ const accountId = options.accountId ?? resolveValue(["CLOUDFLARE_ACCOUNT_ID"], options.env, { prefix: PREFIX });
285
407
  const opts = {
286
408
  ...options,
287
409
  accountId
@@ -299,30 +421,50 @@ function createContext(options = {}) {
299
421
  })
300
422
  };
301
423
  }
424
+ /** Builds the `dns` capability for a context. */
302
425
  function dns(ctx) {
303
426
  return new CloudflareDns(ctx.client);
304
427
  }
428
+ /** Builds the `deployment` capability for a context; throws when no account id is set. */
305
429
  function deployment(ctx) {
306
430
  if (!ctx.options.accountId) throw new Error("Cloudflare accountId is required for Pages deployments — set accountId in the plugin options or CLOUDFLARE_ACCOUNT_ID env var");
307
431
  return new CloudflareDeployment(ctx.client, ctx.options.accountId);
308
432
  }
433
+ /** Builds the `workers` capability for a context; throws when no account id is set. */
309
434
  function workersCapability(ctx) {
310
435
  if (!ctx.options.accountId) throw new Error("Cloudflare accountId is required for Workers — set accountId in the plugin options or CLOUDFLARE_ACCOUNT_ID env var");
311
436
  return new CloudflareWorkers(ctx.client, ctx.options.accountId);
312
437
  }
438
+ /** Builds the `tunnels` capability for a context; throws when no account id is set. */
439
+ function tunnelsCapability(ctx) {
440
+ if (!ctx.options.accountId) throw new Error("Cloudflare accountId is required for Tunnels — set accountId in the plugin options or CLOUDFLARE_ACCOUNT_ID env var");
441
+ return new CloudflareTunnels(ctx.client, ctx.options.accountId);
442
+ }
443
+ /** Creates the Cloudflare plugin: `dns` always, plus `deployment`, `workers` and `tunnels` when an account id is set, and a `connection` probe. */
313
444
  function createPlugin(options = {}) {
314
445
  const ctx = createContext(options);
315
446
  return {
316
447
  name: "@theholocron/holocron-plugin-cloudflare",
448
+ probes: { connection: connectionProbe({
449
+ provider: "Cloudflare",
450
+ url: options.baseUrl ?? "https://api.cloudflare.com",
451
+ fetch: options.fetch,
452
+ token: () => resolveToken(options),
453
+ verify: (token) => verifyToken(token, {
454
+ baseUrl: options.baseUrl,
455
+ fetch: options.fetch
456
+ })
457
+ }) },
317
458
  capabilities: {
318
459
  dns: () => dns(ctx),
319
460
  ...ctx.options.accountId ? {
320
461
  deployment: () => deployment(ctx),
321
- workers: () => workersCapability(ctx)
462
+ workers: () => workersCapability(ctx),
463
+ tunnels: () => tunnelsCapability(ctx)
322
464
  } : {}
323
465
  }
324
466
  };
325
467
  }
326
- const AUTH_HINT = "create an API token at https://dash.cloudflare.com/profile/api-tokens with Zone:Read, DNS:Edit, Cloudflare Pages:Edit, Workers Scripts:Edit (account-level), and Workers Routes:Edit (zone-level) permissions, then run: holocron auth set cloudflare <TOKEN>";
327
- //#endregion
328
- export { AUTH_HINT, AuthError, CloudflareDeployment, CloudflareDns, CloudflareWorkers, createCloudflareClient, createContext, createPlugin, deployment, dns, resolveToken, verifyToken, workersCapability };
468
+ /** One-line hint printed by `holocron auth set cloudflare` when no token is supplied or the supplied one is rejected. */
469
+ const AUTH_HINT = "create an API token at https://dash.cloudflare.com/profile/api-tokens with Zone:Read, DNS:Edit, Cloudflare Pages:Edit, Workers Scripts:Edit (account-level), Workers Routes:Edit (zone-level) and, for tunnels, Cloudflare Tunnel:Edit (account-level) permissions, then run: holocron auth set cloudflare <TOKEN>";
470
+ export { AUTH_HINT, AuthError, CloudflareDeployment, CloudflareDns, CloudflareTunnels, CloudflareWorkers, createCloudflareClient, createContext, createPlugin, deployment, dns, resolveToken, tokens, tunnelsCapability, verifyToken, workersCapability };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/holocron-plugin-cloudflare",
3
- "version": "5.0.0-alpha.42",
3
+ "version": "5.0.0-alpha.421",
4
4
  "description": "Holocron plugin for Cloudflare. Implements the dns capability against Cloudflare's REST API — zone resolution, DNS record management.",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -8,12 +8,12 @@
8
8
  "holocron",
9
9
  "plugin"
10
10
  ],
11
- "homepage": "https://github.com/theholocron/holocron/tree/main/packages/holocron-plugin-cloudflare#readme",
11
+ "homepage": "https://docs.theholocron.dev/holocron/plugins/cloudflare/",
12
12
  "bugs": "https://github.com/theholocron/holocron/issues",
13
13
  "repository": {
14
14
  "type": "git",
15
15
  "url": "git+https://github.com/theholocron/holocron.git",
16
- "directory": "packages/holocron-plugin-cloudflare"
16
+ "directory": "plugins/holocron-plugin-cloudflare"
17
17
  },
18
18
  "license": "MIT",
19
19
  "author": "Newton Koumantzelis",
@@ -29,29 +29,35 @@
29
29
  "files": [
30
30
  "dist"
31
31
  ],
32
+ "dependencies": {
33
+ "@theholocron/env-utils": "^1.17.0-alpha.4"
34
+ },
32
35
  "devDependencies": {
33
- "@theholocron/cloudflare-client": "^1.24.0",
34
- "@theholocron/eslint-config": "^8.0.0",
35
- "@theholocron/http-client": "^1.24.0",
36
- "@theholocron/tsconfig": "^8.0.0",
37
- "@theholocron/tsdown-config": "^8.0.0",
38
- "@theholocron/vitest-config": "^8.0.0",
39
36
  "@types/node": "^26",
40
- "@vitest/coverage-v8": "^4.1.11",
41
- "@vitest/eslint-plugin": "^1.6.27",
42
- "chalk": "^6.0.0",
43
- "eslint": "^10.8.1",
44
- "eslint-plugin-n": "^18.3.0",
45
- "globals": "^17.11.0",
46
- "tsdown": "^0.22.14",
47
- "tsx": "4.23.12",
37
+ "@vitest/coverage-v8": "^5.1.0",
38
+ "@vitest/eslint-plugin": "^1.6.28",
39
+ "chalk": "^6.0.1",
40
+ "eslint": "^10.14.0",
41
+ "eslint-plugin-n": "^18.5.0",
42
+ "globals": "^17.14.0",
43
+ "tsdown": "^0.23.5",
44
+ "tsx": "4.23.15",
48
45
  "typescript": "^5.9.3",
49
- "vitest": "^4.1.11",
50
- "@theholocron/cli": "5.0.0-alpha.42"
46
+ "vitest": "^5.1.0",
47
+ "@theholocron/eslint-config": "^8.9.0-alpha.16",
48
+ "@theholocron/http-client": "^1.58.0-alpha.28",
49
+ "@theholocron/cloudflare-client": "^1.58.0-alpha.28",
50
+ "@theholocron/kyber": "5.0.0-alpha.421",
51
+ "@theholocron/tsconfig": "^8.9.0-alpha.16",
52
+ "@theholocron/tsdown-config": "^8.9.0-alpha.16",
53
+ "@theholocron/misc-utils": "^1.17.0-alpha.4",
54
+ "@theholocron/vitest-config": "^8.9.0-alpha.16",
55
+ "@theholocron/cli": "5.0.0-alpha.421"
51
56
  },
52
57
  "peerDependencies": {
53
- "@theholocron/cloudflare-client": "^1.24.0",
54
- "@theholocron/cli": "5.0.0-alpha.42"
58
+ "@theholocron/cloudflare-client": "^1.53.1",
59
+ "@theholocron/misc-utils": "^1.16.0",
60
+ "@theholocron/cli": "5.0.0-alpha.421"
55
61
  },
56
62
  "peerDependenciesMeta": {
57
63
  "@theholocron/cloudflare-client": {}
@@ -63,11 +69,11 @@
63
69
  "access": "public"
64
70
  },
65
71
  "scripts": {
66
- "delivery.build": "tsdown",
67
- "sourceQuality.staticAnalysis": "holocron run sourceQuality.staticAnalysis --",
72
+ "build": "tsdown",
73
+ "lint:code": "eslint .",
74
+ "test:unit": "vitest run --coverage",
68
75
  "test:watch": "vitest",
69
- "validate": "tsx scripts/validate.mjs",
70
- "verification.typeSafety": "holocron run verification.typeSafety --",
71
- "verification.unitTests": "holocron run verification.unitTests --"
76
+ "typecheck": "tsc --noEmit",
77
+ "validate:plugin": "tsx scripts/validate.mjs"
72
78
  }
73
79
  }