@theholocron/holocron-plugin-cloudflare 5.0.0-alpha.4 → 5.0.0-alpha.400

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
@@ -2,8 +2,9 @@
2
2
 
3
3
  # `@theholocron/holocron-plugin-cloudflare`
4
4
 
5
- Cloudflare plugin for [Holocron](../cli). Implements the `dns` and `deployment`
6
- capabilities against the [Cloudflare v4 API](https://developers.cloudflare.com/api/).
5
+ Cloudflare plugin for [Holocron](../cli). Implements the `dns`, `deployment`,
6
+ `workers` and `tunnels` capabilities against the
7
+ [Cloudflare v4 API](https://developers.cloudflare.com/api/).
7
8
 
8
9
  ## Install
9
10
 
@@ -40,12 +41,15 @@ Generate a scoped API token at **dash.cloudflare.com/profile/api-tokens**.
40
41
  // Cloudflare Pages deployments (requires accountId)
41
42
  // accountId falls back to CLOUDFLARE_ACCOUNT_ID env var when omitted
42
43
  "deployment": "cloudflare",
44
+
45
+ // Workers deployment (also requires accountId)
46
+ "workers": "cloudflare",
43
47
  },
44
48
  }
45
49
 
46
50
  ```
47
51
 
48
- Both capabilities can be enabled together:
52
+ Any combination of capabilities can be enabled together:
49
53
 
50
54
  <!-- prettier-ignore -->
51
55
  ```jsonc
@@ -53,12 +57,16 @@ Both capabilities can be enabled together:
53
57
  "providers": {
54
58
  "dns": "cloudflare",
55
59
  "deployment": "cloudflare",
60
+ "workers": "cloudflare",
56
61
  },
57
62
  }
58
63
 
59
64
  ```
60
65
 
61
- The `deployment` capability is only exposed when `accountId` is resolvable — either passed explicitly in options or set via the `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).
62
70
 
63
71
  ## `dns` capability
64
72
 
@@ -72,7 +80,7 @@ Zone ids are cached per plugin instance for the lifetime of the process.
72
80
 
73
81
  ## `deployment` capability
74
82
 
75
- 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.
76
84
 
77
85
  | Method | What it does |
78
86
  | ----------------------- | ----------------------------------------------------------------------------------------------------------------------- |
@@ -83,9 +91,38 @@ Manages [Cloudflare Pages](https://developers.cloudflare.com/pages/) projects. U
83
91
  | `triggerDeployment` | Triggers a new Pages deployment from the latest production branch commit. |
84
92
  | `updateProjectSettings` | Updates project-level settings (currently a no-op; CF Pages REST API has no direct settings endpoint for these fields). |
85
93
 
94
+ ## `workers` capability
95
+
96
+ Deploys and manages [Workers](https://developers.cloudflare.com/workers/) scripts.
97
+
98
+ | Method | What it does |
99
+ | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
100
+ | `upsertProxy` | Deploys a generated reverse-proxy Worker forwarding `hostname/*` to `config.target`, injecting `config.headers`. Used by `setup` to wire wiki custom-domain proxies when the wiki provider requires one in addition to the CNAME. |
101
+ | `deployScript` | Deploys (or updates) an arbitrary Worker script — the caller's own code, not a generated proxy — with optional secret bindings and route patterns. For a consumer that isn't a reverse-proxy, e.g. a webhook receiver. |
102
+
103
+ Both methods are idempotent: re-running with the same inputs makes no
104
+ route-write call when nothing changed. Zone ids are cached per plugin
105
+ instance for the lifetime of the process — the `workers` capability's own
106
+ cache, separate from `dns`'s.
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
+
86
123
  ### Preview deployment setup
87
124
 
88
- 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:
89
126
 
90
127
  1. `ensureProject` — creates `<org>-preview` if it doesn't exist
91
128
  2. `ensureCustomDomain` — attaches `*.<domain>` to the project
package/dist/index.d.mts CHANGED
@@ -1,15 +1,19 @@
1
- import { AuthError, Deployment, DeploymentProject, DeploymentProjectSettings, DeploymentRecord, DeploymentTarget, DeploymentTrigger, Dns, DnsRecord, ResolveTokenInput, WikiProxyConfig, Workers } from "@theholocron/cli";
2
- import { CloudflareClient, CloudflareClientOptions, CloudflareClientOptions as CloudflareClientOptions$1, 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 {
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
+ import { CloudflareClient, CloudflareClient as CloudflareClient$1, CloudflareClientOptions, createCloudflareClient } from "@theholocron/cloudflare-client";
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
- ensureCustomDomain(projectId: string, hostname: string): Promise<void>;
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,56 +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
- interface ZonesClient {
57
- list(query?: {
58
- name?: string;
59
- per_page?: number;
60
- }): Promise<Array<{
61
- id: string;
62
- }>>;
71
+ /** The Cloudflare implementation of the `tunnels` capability, backed by Cloudflare Tunnel in one account. */
72
+ export declare class CloudflareTunnels implements Tunnels {
73
+ private readonly client;
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
+ }>;
63
89
  }
64
- declare class CloudflareWorkers implements Workers {
65
- private readonly zones;
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;
66
93
  private readonly accountId;
94
+ /** The capability this class provides, always `"workers"`. */
67
95
  readonly key: "workers";
96
+ /** The provider name, `"cloudflare"`. */
68
97
  readonly providerName = "cloudflare";
69
98
  private readonly zoneCache;
70
- private readonly baseUrl;
71
- private readonly fetchImpl;
72
- /** Memoized token thunk — resolved on the first authenticated request. */
73
- private readonly token;
74
- constructor(zones: () => ZonesClient, accountId: string, opts: {
75
- token: () => string;
76
- } & Pick<CloudflareClientOptions$1, "baseUrl" | "fetch">);
99
+ constructor(client: () => Pick<CloudflareClient$1, "workers" | "zones">, accountId: string);
77
100
  upsertProxy(hostname: string, config: WikiProxyConfig): Promise<void>;
78
- private putScript;
79
- private listRoutes;
80
- private createRoute;
81
- private updateRoute;
82
- private cfRequest;
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
+ }>;
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>;
114
+ /** Idempotent create-or-update for one route pattern — shared by both public methods. */
115
+ private upsertRoute;
83
116
  private resolveZone;
84
117
  }
85
- //#endregion
86
- //#region src/verify-token.d.ts
87
- interface VerifyTokenSuccess {
88
- ok: true;
89
- subject: string;
90
- }
91
- interface VerifyTokenFailure {
92
- ok: false;
93
- message: string;
94
- }
95
- type VerifyTokenResult = VerifyTokenSuccess | VerifyTokenFailure;
96
118
  interface VerifyTokenOptions {
97
119
  baseUrl?: string;
98
120
  fetch?: typeof fetch;
99
121
  }
100
- declare function verifyToken(token: string, opts?: VerifyTokenOptions): Promise<VerifyTokenResult>;
101
- //#endregion
102
- //#region src/index.d.ts
103
- 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 {
104
126
  /**
105
127
  * Cloudflare account ID. Required for Pages (deployment) operations;
106
128
  * optional for DNS-only use.
@@ -108,27 +130,41 @@ interface CloudflarePluginOptions extends ResolveTokenInput {
108
130
  accountId?: string;
109
131
  /** Override base URL for tests. */
110
132
  baseUrl?: string;
133
+ /** The `fetch` to use instead of the global one, for tests. */
111
134
  fetch?: typeof fetch;
112
135
  }
113
- 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. */
114
139
  options: CloudflarePluginOptions;
115
140
  /** Memoized client — the token is resolved on first use, not at plugin load. */
116
141
  client: () => CloudflareClient;
117
142
  /** Memoized token resolver — shared by the client and the Workers capability. */
118
143
  token: () => string;
119
144
  }
120
- declare function createContext(options?: CloudflarePluginOptions): PluginContext;
121
- declare function dns(ctx: PluginContext): Dns;
122
- declare function deployment(ctx: PluginContext): Deployment;
123
- declare function workersCapability(ctx: PluginContext): Workers;
124
- 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): {
125
157
  name: string;
158
+ probes: {
159
+ connection: import("@theholocron/cli").Probe;
160
+ };
126
161
  capabilities: {
127
162
  deployment?: (() => Deployment) | undefined;
128
163
  workers?: (() => Workers) | undefined;
164
+ tunnels?: (() => Tunnels) | undefined;
129
165
  dns: () => Dns;
130
166
  };
131
167
  };
132
- declare const AUTH_HINT: string;
133
- //#endregion
134
- 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);
@@ -74,8 +86,9 @@ var CloudflareDeployment = class {
74
86
  return deploymentIds.length;
75
87
  }
76
88
  async ensureCustomDomain(projectId, hostname) {
77
- if ((await this.client().pages.listDomains(this.accountId, projectId)).some((d) => d.name === hostname)) return;
89
+ if ((await this.client().pages.listDomains(this.accountId, projectId)).some((d) => d.name === hostname)) return null;
78
90
  await this.client().pages.addDomain(this.accountId, projectId, hostname);
91
+ return null;
79
92
  }
80
93
  async getProjectByName(name) {
81
94
  try {
@@ -113,20 +126,24 @@ function normalizeStatus(status) {
113
126
  default: return "error";
114
127
  }
115
128
  }
116
- //#endregion
117
- //#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. */
118
131
  var CloudflareDns = class {
119
132
  client;
133
+ /** The capability this class provides, always `"dns"`. */
120
134
  key = "dns";
135
+ /** The provider name, `"cloudflare"`. */
121
136
  providerName = "cloudflare";
122
137
  zoneCache = /* @__PURE__ */ new Map();
123
138
  constructor(client) {
124
139
  this.client = client;
125
140
  }
141
+ /** Lists the DNS records in the zone that holds the domain. */
126
142
  async listRecords(domain) {
127
143
  const zoneId = await this.resolveZone(domain);
128
144
  return (await this.client().dns.list(zoneId)).map(mapRecord);
129
145
  }
146
+ /** Updates the first record of the same type and name, or creates the record when there is none; returns the stored record. */
130
147
  async upsertRecord(domain, record) {
131
148
  const client = this.client();
132
149
  const zoneId = await this.resolveZone(domain);
@@ -149,10 +166,18 @@ var CloudflareDns = class {
149
166
  ...record.proxied !== void 0 ? { proxied: record.proxied } : {}
150
167
  }));
151
168
  }
169
+ /** Deletes the DNS record with this id from the zone that holds the domain. */
152
170
  async deleteRecord(domain, id) {
153
171
  const zoneId = await this.resolveZone(domain);
154
172
  await this.client().dns.delete(zoneId, id);
155
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
+ }
156
181
  /**
157
182
  * Walk from full domain up to apex to find the Cloudflare zone.
158
183
  * E.g. "api.staging.example.com" tries:
@@ -181,93 +206,134 @@ function mapRecord(raw) {
181
206
  type: raw.type,
182
207
  name: raw.name,
183
208
  content: raw.content,
184
- ttl: raw.ttl
209
+ ttl: raw.ttl,
210
+ ...raw.proxied !== void 0 ? { proxied: raw.proxied } : {}
185
211
  };
186
212
  }
187
- //#endregion
188
- //#region src/capabilities/workers.ts
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
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];
228
+ }
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. */
189
272
  var CloudflareWorkers = class {
190
- zones;
273
+ client;
191
274
  accountId;
275
+ /** The capability this class provides, always `"workers"`. */
192
276
  key = "workers";
277
+ /** The provider name, `"cloudflare"`. */
193
278
  providerName = "cloudflare";
194
279
  zoneCache = /* @__PURE__ */ new Map();
195
- baseUrl;
196
- fetchImpl;
197
- /** Memoized token thunk — resolved on the first authenticated request. */
198
- token;
199
- constructor(zones, accountId, opts) {
200
- this.zones = zones;
280
+ constructor(client, accountId) {
281
+ this.client = client;
201
282
  this.accountId = accountId;
202
- this.token = opts.token;
203
- this.baseUrl = opts.baseUrl ?? "https://api.cloudflare.com/client/v4";
204
- this.fetchImpl = opts.fetch ?? globalThis.fetch;
205
283
  }
206
284
  async upsertProxy(hostname, config) {
207
285
  const scriptName = hostnameToScriptName(hostname);
208
286
  const script = generateProxyScript(config);
209
- await this.putScript(scriptName, script);
210
- const zoneId = await this.resolveZone(hostname);
211
- const pattern = `${hostname}/*`;
212
- const existing = (await this.listRoutes(zoneId)).find((r) => r.pattern === pattern);
213
- if (existing) {
214
- if (existing.script !== scriptName) await this.updateRoute(zoneId, existing.id, pattern, scriptName);
215
- } else await this.createRoute(zoneId, pattern, scriptName);
216
- }
217
- async putScript(scriptName, script) {
218
- const form = new FormData();
219
- form.append("metadata", new Blob([JSON.stringify({
220
- main_module: "index.js",
221
- compatibility_date: "2025-08-31"
222
- })], { type: "application/json" }));
223
- form.append("index.js", new Blob([script], { type: "application/javascript+module" }), "index.js");
224
- const path = `/accounts/${this.accountId}/workers/scripts/${encodeURIComponent(scriptName)}`;
225
- const res = await this.fetchImpl(`${this.baseUrl}${path}`, {
226
- method: "PUT",
227
- headers: { authorization: `Bearer ${this.token()}` },
228
- body: form
229
- });
230
- if (!res.ok) {
231
- const body = await res.text().catch(() => "");
232
- throw new ProviderApiError(`Cloudflare PUT ${path} → ${res.status}`, res.status, body);
233
- }
287
+ await this.client().workers.putScript(this.accountId, scriptName, script);
288
+ await this.upsertRoute(`${hostname}/*`, scriptName);
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
+ };
234
296
  }
235
- listRoutes(zoneId) {
236
- return this.cfRequest("GET", `/zones/${zoneId}/workers/routes`);
297
+ async deployScript(name, config) {
298
+ await this.client().workers.putScript(this.accountId, name, config.code);
299
+ for (const [secretName, value] of Object.entries(config.secrets ?? {})) await this.client().workers.putSecret(this.accountId, name, secretName, value);
300
+ for (const pattern of config.routes ?? []) await this.upsertRoute(pattern, name);
301
+ return { scriptName: name };
237
302
  }
238
- createRoute(zoneId, pattern, script) {
239
- return this.cfRequest("POST", `/zones/${zoneId}/workers/routes`, {
240
- pattern,
241
- script
242
- });
303
+ async setSecret(script, name, value) {
304
+ await this.client().workers.putSecret(this.accountId, script, name, value);
243
305
  }
244
- updateRoute(zoneId, routeId, pattern, script) {
245
- return this.cfRequest("PUT", `/zones/${zoneId}/workers/routes/${routeId}`, {
246
- pattern,
247
- script
248
- });
306
+ async secretNames(script) {
307
+ return (await this.client().workers.listSecrets(this.accountId, script)).map((secret) => secret.name);
249
308
  }
250
- async cfRequest(method, path, body) {
251
- const headers = {
252
- authorization: `Bearer ${this.token()}`,
253
- accept: "application/json"
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: []
254
319
  };
255
- const init = {
256
- method,
257
- headers
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)
258
327
  };
259
- if (body !== void 0) {
260
- headers["content-type"] = "application/json";
261
- init.body = JSON.stringify(body);
262
- }
263
- const res = await this.fetchImpl(`${this.baseUrl}${path}`, init);
264
- if (!res.ok) {
265
- const text = await res.text().catch(() => "");
266
- throw new ProviderApiError(`Cloudflare ${method} ${path} → ${res.status}`, res.status, text);
267
- }
268
- const envelope = await res.json();
269
- if (!envelope.success) throw new ProviderApiError(`Cloudflare ${method} ${path} returned success:false`, 0, JSON.stringify(envelope.errors));
270
- return envelope.result;
328
+ }
329
+ /** Idempotent create-or-update for one route pattern — shared by both public methods. */
330
+ async upsertRoute(pattern, scriptName) {
331
+ const hostname = pattern.split("/")[0];
332
+ const zoneId = await this.resolveZone(hostname);
333
+ const existing = (await this.client().workers.listRoutes(zoneId)).find((r) => r.pattern === pattern);
334
+ if (existing) {
335
+ if (existing.script !== scriptName) await this.client().workers.updateRoute(zoneId, existing.id, pattern, scriptName);
336
+ } else await this.client().workers.createRoute(zoneId, pattern, scriptName);
271
337
  }
272
338
  async resolveZone(domain) {
273
339
  const cached = this.zoneCache.get(domain);
@@ -275,7 +341,7 @@ var CloudflareWorkers = class {
275
341
  const parts = domain.split(".");
276
342
  for (let i = 0; i < parts.length - 1; i++) {
277
343
  const candidate = parts.slice(i).join(".");
278
- const zones = await this.zones().list({ name: candidate });
344
+ const zones = await this.client().zones.list({ name: candidate });
279
345
  if (zones.length > 0) {
280
346
  this.zoneCache.set(domain, zones[0].id);
281
347
  return zones[0].id;
@@ -302,8 +368,8 @@ function generateProxyScript(config) {
302
368
  `};`
303
369
  ].join("\n");
304
370
  }
305
- //#endregion
306
- //#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. */
307
373
  async function verifyToken(token, opts = {}) {
308
374
  const client = createCloudflareClient({
309
375
  token,
@@ -318,21 +384,26 @@ async function verifyToken(token, opts = {}) {
318
384
  };
319
385
  } catch {}
320
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
+ };
321
392
  return {
322
393
  ok: true,
323
- 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)`}`
324
395
  };
325
396
  } catch (err) {
326
397
  return {
327
398
  ok: false,
328
- message: err instanceof Error ? err.message : String(err)
399
+ message: errorMessage(err)
329
400
  };
330
401
  }
331
402
  }
332
- //#endregion
333
- //#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. */
334
405
  function createContext(options = {}) {
335
- const accountId = options.accountId ?? process.env.CLOUDFLARE_ACCOUNT_ID;
406
+ const accountId = options.accountId ?? resolveValue(["CLOUDFLARE_ACCOUNT_ID"], options.env, { prefix: PREFIX });
336
407
  const opts = {
337
408
  ...options,
338
409
  accountId
@@ -350,34 +421,50 @@ function createContext(options = {}) {
350
421
  })
351
422
  };
352
423
  }
424
+ /** Builds the `dns` capability for a context. */
353
425
  function dns(ctx) {
354
426
  return new CloudflareDns(ctx.client);
355
427
  }
428
+ /** Builds the `deployment` capability for a context; throws when no account id is set. */
356
429
  function deployment(ctx) {
357
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");
358
431
  return new CloudflareDeployment(ctx.client, ctx.options.accountId);
359
432
  }
433
+ /** Builds the `workers` capability for a context; throws when no account id is set. */
360
434
  function workersCapability(ctx) {
361
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");
362
- return new CloudflareWorkers(() => ctx.client().zones, ctx.options.accountId, {
363
- token: ctx.token,
364
- baseUrl: ctx.options.baseUrl,
365
- fetch: ctx.options.fetch
366
- });
436
+ return new CloudflareWorkers(ctx.client, ctx.options.accountId);
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);
367
442
  }
443
+ /** Creates the Cloudflare plugin: `dns` always, plus `deployment`, `workers` and `tunnels` when an account id is set, and a `connection` probe. */
368
444
  function createPlugin(options = {}) {
369
445
  const ctx = createContext(options);
370
446
  return {
371
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
+ }) },
372
458
  capabilities: {
373
459
  dns: () => dns(ctx),
374
460
  ...ctx.options.accountId ? {
375
461
  deployment: () => deployment(ctx),
376
- workers: () => workersCapability(ctx)
462
+ workers: () => workersCapability(ctx),
463
+ tunnels: () => tunnelsCapability(ctx)
377
464
  } : {}
378
465
  }
379
466
  };
380
467
  }
381
- 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>";
382
- //#endregion
383
- 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.4",
3
+ "version": "5.0.0-alpha.400",
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,28 +29,35 @@
29
29
  "files": [
30
30
  "dist"
31
31
  ],
32
+ "dependencies": {
33
+ "@theholocron/env-utils": "^1.17.0-alpha.3"
34
+ },
32
35
  "devDependencies": {
33
- "@theholocron/cloudflare-client": "^1.14.2",
34
- "@theholocron/eslint-config": "^8.0.0",
35
- "@theholocron/tsconfig": "^8.0.0",
36
- "@theholocron/tsdown-config": "^8.0.0",
37
- "@theholocron/vitest-config": "^8.0.0",
38
36
  "@types/node": "^26",
39
- "@vitest/coverage-v8": "^4.1.11",
40
- "@vitest/eslint-plugin": "^1.6.27",
41
- "chalk": "^6.0.0",
42
- "eslint": "^10.8.1",
43
- "eslint-plugin-n": "^18.3.0",
44
- "globals": "^17.11.0",
45
- "tsdown": "^0.22.14",
46
- "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",
47
45
  "typescript": "^5.9.3",
48
- "vitest": "^4.1.11",
49
- "@theholocron/cli": "5.0.0-alpha.4"
46
+ "vitest": "^5.1.0",
47
+ "@theholocron/eslint-config": "^8.9.0-alpha.15",
48
+ "@theholocron/http-client": "^1.58.0-alpha.27",
49
+ "@theholocron/kyber": "5.0.0-alpha.400",
50
+ "@theholocron/cloudflare-client": "^1.58.0-alpha.27",
51
+ "@theholocron/misc-utils": "^1.17.0-alpha.3",
52
+ "@theholocron/tsdown-config": "^8.9.0-alpha.15",
53
+ "@theholocron/tsconfig": "^8.9.0-alpha.15",
54
+ "@theholocron/cli": "5.0.0-alpha.400",
55
+ "@theholocron/vitest-config": "^8.9.0-alpha.15"
50
56
  },
51
57
  "peerDependencies": {
52
- "@theholocron/cloudflare-client": "^1.14.2",
53
- "@theholocron/cli": "5.0.0-alpha.4"
58
+ "@theholocron/cloudflare-client": "^1.53.1",
59
+ "@theholocron/misc-utils": "^1.16.0",
60
+ "@theholocron/cli": "5.0.0-alpha.400"
54
61
  },
55
62
  "peerDependenciesMeta": {
56
63
  "@theholocron/cloudflare-client": {}
@@ -62,11 +69,11 @@
62
69
  "access": "public"
63
70
  },
64
71
  "scripts": {
65
- "delivery.build": "tsdown",
66
- "sourceQuality.staticAnalysis": "holocron run sourceQuality.staticAnalysis --",
72
+ "build": "tsdown",
73
+ "lint:code": "eslint .",
74
+ "test:unit": "vitest run --coverage",
67
75
  "test:watch": "vitest",
68
- "validate": "tsx scripts/validate.mjs",
69
- "verification.typeSafety": "holocron run verification.typeSafety --",
70
- "verification.unitTests": "holocron run verification.unitTests --"
76
+ "typecheck": "tsc --noEmit",
77
+ "validate:plugin": "tsx scripts/validate.mjs"
71
78
  }
72
79
  }