@ductape/cli 0.4.9 → 0.5.2

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.
@@ -56,11 +56,19 @@ export async function runApps(verb, opts, extraArgs) {
56
56
  result = await updateApp(ctx, id, body ?? {});
57
57
  break;
58
58
  }
59
- case 'delete':
60
- if (!id)
61
- throw new Error('delete requires --id <app_id>');
62
- result = await deleteApp(ctx, id);
59
+ case 'delete': {
60
+ let appId = opts.id;
61
+ if (!appId && tag) {
62
+ const app = (await getApp(ctx, { tag }));
63
+ if (!app?._id)
64
+ throw new Error(`App "${tag}" not found`);
65
+ appId = String(app._id);
66
+ }
67
+ if (!appId)
68
+ throw new Error('delete requires --id <app_id> or --tag <app_tag>');
69
+ result = await deleteApp(ctx, appId);
63
70
  break;
71
+ }
64
72
  default:
65
73
  throw new Error(`Unsupported: apps ${v}`);
66
74
  }
@@ -5,6 +5,11 @@ export declare function runCloudPreflight(opts: {
5
5
  file?: string;
6
6
  json?: boolean;
7
7
  }): Promise<void>;
8
+ /**
9
+ * Writes the AWS or Azure setup template to a file and leaves a short note in its place in the output, so a long YAML document does not scroll
10
+ * the useful part of the response away. --save-fargate-template does the same for the Fargate stack. Without either the response is printed as it came.
11
+ */
12
+ export declare function withSavedTemplate(result: unknown, file: string | undefined, fargateFile?: string, expressFile?: string): unknown;
8
13
  export declare function runCloud(target: CloudTarget, verb: string, opts: {
9
14
  id?: string;
10
15
  file?: string;
@@ -16,5 +21,8 @@ export declare function runCloud(target: CloudTarget, verb: string, opts: {
16
21
  connection?: IConnectionFlags;
17
22
  purpose?: string;
18
23
  dryRun?: boolean;
24
+ saveTemplate?: string;
25
+ saveFargateTemplate?: string;
26
+ saveExpressTemplate?: string;
19
27
  }, extraArgs: string[]): Promise<void>;
20
28
  export {};
@@ -1,3 +1,5 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
1
3
  import { readJsonBody } from '../lib/read-body.js';
2
4
  import { getSdkProxy, requireSession } from '../lib/proxy/context.js';
3
5
  import { printJson } from '../lib/output.js';
@@ -78,6 +80,43 @@ export async function runCloudPreflight(opts) {
78
80
  ready: unresolved.length === 0,
79
81
  }, Boolean(opts.json));
80
82
  }
83
+ /**
84
+ * Writes the AWS or Azure setup template to a file and leaves a short note in its place in the output, so a long YAML document does not scroll
85
+ * the useful part of the response away. --save-fargate-template does the same for the Fargate stack. Without either the response is printed as it came.
86
+ */
87
+ export function withSavedTemplate(result, file, fargateFile, expressFile) {
88
+ if (!file && !fargateFile && !expressFile)
89
+ return result;
90
+ const root = (result && typeof result === 'object' ? result : {});
91
+ const setup = (root.deploy_setup ?? root.connection?.deploy_setup);
92
+ // AWS gives a CloudFormation document (text); Azure gives a deployment template (an object, saved as JSON).
93
+ const aws = typeof setup?.cloudformationTemplate === 'string';
94
+ const azure = !aws && !!setup?.template && typeof setup.template === 'object';
95
+ if (!setup || (!aws && !azure))
96
+ throw new Error('This connection has no setup template. It is only available for an AWS or Azure connection made with --deploy that is not active yet.');
97
+ let noted = { ...setup };
98
+ if (file) {
99
+ const target = path.resolve(file);
100
+ fs.writeFileSync(target, aws ? setup.cloudformationTemplate : `${JSON.stringify(setup.template, null, 2)}\n`, { mode: 0o644 });
101
+ noted = aws ? { ...noted, cloudformationTemplate: `(saved to ${target})` } : { ...noted, template: `(saved to ${target})` };
102
+ }
103
+ if (fargateFile) {
104
+ if (typeof setup.fargate?.cloudformationTemplate !== 'string')
105
+ throw new Error('This connection has no Fargate setup template. It is only available for an AWS connection made with --deploy that is not active yet.');
106
+ const target = path.resolve(fargateFile);
107
+ fs.writeFileSync(target, setup.fargate.cloudformationTemplate, { mode: 0o644 });
108
+ noted = { ...noted, fargate: { ...setup.fargate, cloudformationTemplate: `(saved to ${target})` } };
109
+ }
110
+ if (expressFile) {
111
+ const express = setup.express;
112
+ if (typeof express?.cloudformationTemplate !== 'string')
113
+ throw new Error('This connection has no ECS Express setup template. It is only available for an AWS connection made with --deploy that is not active yet.');
114
+ const target = path.resolve(expressFile);
115
+ fs.writeFileSync(target, express.cloudformationTemplate, { mode: 0o644 });
116
+ noted = { ...noted, express: { ...express, cloudformationTemplate: `(saved to ${target})` } };
117
+ }
118
+ return root.deploy_setup ? { ...root, deploy_setup: noted } : { ...root, connection: { ...root.connection, deploy_setup: noted } };
119
+ }
81
120
  export async function runCloud(target, verb, opts, extraArgs) {
82
121
  if (target === 'connections' && verb.toLowerCase() === 'guide') {
83
122
  // Offline: prints the steps for connecting a provider, and contacts nothing.
@@ -158,5 +197,5 @@ export async function runCloud(target, verb, opts, extraArgs) {
158
197
  [method, params] = entry;
159
198
  }
160
199
  const result = await proxy.execute('cloud', method, params);
161
- printJson(result, Boolean(opts.json));
200
+ printJson(withSavedTemplate(result, opts.saveTemplate, opts.saveFargateTemplate, opts.saveExpressTemplate), Boolean(opts.json));
162
201
  }
@@ -9,9 +9,11 @@ export interface IBuildOptions {
9
9
  id?: string;
10
10
  product?: string;
11
11
  status?: string;
12
+ /** Only builds that ran through this cloud connection. */
13
+ connection?: string;
12
14
  }
13
15
  /**
14
16
  * Builds source in the customer's own cloud account. The source is packed here, uploaded straight to a bucket in that
15
17
  * account, and built there by the same cloud connection that will deploy it. Ductape holds only the checksum.
16
18
  */
17
- export declare function runDeployBuilds(operation: 'create' | 'status' | 'list', options: IBuildOptions): Promise<void>;
19
+ export declare function runDeployBuilds(operation: 'create' | 'status' | 'list' | 'cancel', options: IBuildOptions): Promise<void>;
@@ -5,12 +5,12 @@ import { requireWorkspaceContext, workspaceAuthQuery } from '../lib/workspace-co
5
5
  import { packSource, uploadSource } from '../lib/source-pack.js';
6
6
  import { actorHeaders } from './deploy-remote.js';
7
7
  const BASE = '/integrations/v1/deploy';
8
- const TERMINAL = new Set(['succeeded', 'failed', 'expired']);
8
+ const TERMINAL = new Set(['succeeded', 'failed', 'expired', 'cancelled']);
9
9
  const note = (message) => process.stderr.write(`${message}\n`);
10
10
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
11
11
  function readBuildFile(file) {
12
12
  if (!file)
13
- throw new Error('--file is required: a JSON file with productTag, functionName, version, connectionTag, region, contract, config and verification');
13
+ throw new Error('--file is required: a JSON file with product, function, version, connection, region, contract, config and verification');
14
14
  const resolved = path.resolve(file);
15
15
  try {
16
16
  const parsed = JSON.parse(fs.readFileSync(resolved, 'utf8'));
@@ -32,9 +32,11 @@ export async function runDeployBuilds(operation, options) {
32
32
  const extra = {};
33
33
  if (operation === 'list') {
34
34
  if (options.product)
35
- extra.productTag = options.product;
35
+ extra.product = options.product;
36
36
  if (options.status)
37
37
  extra.status = options.status;
38
+ if (options.connection)
39
+ extra.connection = options.connection;
38
40
  }
39
41
  const query = new URLSearchParams(workspaceAuthQuery(ctx, extra)).toString();
40
42
  const call = (method, route, body) => api.request(method, `${BASE}${route}?${query}`, body, actorHeaders());
@@ -42,6 +44,12 @@ export async function runDeployBuilds(operation, options) {
42
44
  console.log(JSON.stringify(await call('GET', '/builds'), null, 2));
43
45
  return;
44
46
  }
47
+ if (operation === 'cancel') {
48
+ if (!options.id)
49
+ throw new Error('A build id is required');
50
+ console.log(JSON.stringify(await call('POST', `/builds/${encodeURIComponent(options.id)}/cancel`, {}), null, 2));
51
+ return;
52
+ }
45
53
  if (operation === 'status') {
46
54
  if (!options.id)
47
55
  throw new Error('A build id is required');
@@ -1,4 +1,4 @@
1
- export type DeployRemoteOperation = 'releases.register' | 'plans.create' | 'plans.approve' | 'plans.apply' | 'deployments.list' | 'deployments.get' | 'deployments.journal' | 'functions.list' | 'versions.list' | 'versions.history' | 'versions.deprecate' | 'versions.undeprecate' | 'versions.retire';
1
+ export type DeployRemoteOperation = 'releases.register' | 'releases.list' | 'releases.get' | 'plans.create' | 'plans.approve' | 'plans.apply' | 'plans.list' | 'plans.get' | 'capabilities' | 'orphans' | 'stepup.start' | 'stepup.verify' | 'deployments.list' | 'deployments.get' | 'deployments.journal' | 'deployments.redeploy' | 'deployments.rollback' | 'deployments.traffic' | 'environments.list' | 'environments.policy' | 'environments.history' | 'functions.list' | 'versions.list' | 'versions.history' | 'versions.deprecate' | 'versions.undeprecate' | 'versions.retire';
2
2
  export interface IDeployRemoteArgs {
3
3
  file?: string;
4
4
  id?: string;
@@ -6,10 +6,47 @@ export interface IDeployRemoteArgs {
6
6
  function?: string;
7
7
  version?: string;
8
8
  env?: string;
9
+ /** "function" or "service": narrows a listing. */
10
+ kind?: string;
11
+ /** Only what was applied through this cloud connection. */
12
+ connection?: string;
9
13
  reason?: string;
10
14
  sunset?: string;
11
15
  replacement?: string;
16
+ requireApproval?: string;
17
+ allowAgentApply?: string;
18
+ /** A release to put back (rollback). */
19
+ releaseHash?: string;
20
+ /** The share of traffic, as a whole number (traffic). */
21
+ percent?: string;
22
+ /** A JSON file of runtime settings, replacing the ones the deployment has. */
23
+ runtimeFile?: string;
24
+ /** A JSON file describing what the provider holds, needed only while the control plane does not read the provider itself. */
25
+ observedFile?: string;
26
+ /** Narrows a listing of plans: blocked, pending_approval, approved, ready, applied or expired. */
27
+ stage?: string;
28
+ /** A function or service name, to narrow a listing of releases. */
29
+ name?: string;
30
+ /** The region to look in (orphans). */
31
+ region?: string;
32
+ /** Step-up: what a code is good for, or one of the shortcuts that builds it. */
33
+ scope?: string;
34
+ plan?: string;
35
+ retire?: boolean;
36
+ policy?: boolean;
37
+ /** The six-digit code from the person's email. */
38
+ code?: string;
39
+ /** The name of an environment variable that holds the grant a verified code earned, sent with the one change it was earned for. */
40
+ grantEnv?: string;
12
41
  }
42
+ /** What a step-up code is good for. Must match what the control plane asks for, so a code for one change cannot be spent on another. */
43
+ export declare const stepUpScopes: {
44
+ plan: (planHash: string) => string;
45
+ retire: (product: string, name: string, version: string) => string;
46
+ policy: (product: string, env: string) => string;
47
+ };
48
+ /** The header that carries a grant, read from the environment so it is never typed on a command line. */
49
+ export declare function grantHeaders(grantEnv: string | undefined, env?: Record<string, string | undefined>): Record<string, string>;
13
50
  /** Calls made on behalf of an agent say so, so the control plane never lets them approve or retire. */
14
51
  export declare function actorHeaders(): Record<string, string>;
15
52
  /** Talks to the deploy control plane in the active workspace. Prints the result as JSON. */
@@ -3,6 +3,23 @@ import path from 'node:path';
3
3
  import { ApiClient } from '../lib/api-client.js';
4
4
  import { requireWorkspaceContext, workspaceAuthQuery } from '../lib/workspace-context.js';
5
5
  const BASE = '/integrations/v1/deploy';
6
+ /** What a step-up code is good for. Must match what the control plane asks for, so a code for one change cannot be spent on another. */
7
+ export const stepUpScopes = {
8
+ plan: (planHash) => `plan:${planHash}`,
9
+ retire: (product, name, version) => `retire:${product}/${name}@${version}`,
10
+ policy: (product, env) => `policy:${product}/${env}`,
11
+ };
12
+ /** The header that carries a grant, read from the environment so it is never typed on a command line. */
13
+ export function grantHeaders(grantEnv, env = process.env) {
14
+ if (grantEnv === undefined)
15
+ return {};
16
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(grantEnv))
17
+ throw new Error('--grant-env takes the NAME of an environment variable, not the grant itself');
18
+ const value = env[grantEnv];
19
+ if (!value)
20
+ throw new Error(`${grantEnv} named by --grant-env is not set or is empty. Get a grant with: ductape deploy step-up verify`);
21
+ return { 'x-ductape-grant': value };
22
+ }
6
23
  /** Calls made on behalf of an agent say so, so the control plane never lets them approve or retire. */
7
24
  export function actorHeaders() {
8
25
  return process.env.DUCTAPE_ACTOR === 'agent' ? { 'x-ductape-actor': 'agent' } : {};
@@ -28,6 +45,11 @@ function readJsonFile(file, what) {
28
45
  throw new Error(`The ${what} at ${resolved} is not valid: ${error instanceof Error ? error.message : String(error)}`);
29
46
  }
30
47
  }
48
+ function checkedKind(kind) {
49
+ if (kind !== undefined && kind !== 'function' && kind !== 'service')
50
+ throw new Error('--kind must be "function" or "service"');
51
+ return kind;
52
+ }
31
53
  const need = (value, name) => {
32
54
  if (!value)
33
55
  throw new Error(`${name} is required`);
@@ -40,16 +62,60 @@ export async function runDeployRemote(operation, args) {
40
62
  const extra = {};
41
63
  if (operation === 'deployments.list') {
42
64
  if (args.product)
43
- extra.productTag = args.product;
65
+ extra.product = args.product;
66
+ if (args.env)
67
+ extra.env = args.env;
68
+ if (args.version)
69
+ extra.version = args.version;
70
+ if (checkedKind(args.kind))
71
+ extra.kind = args.kind;
72
+ if (args.connection)
73
+ extra.connection = args.connection;
74
+ }
75
+ if (operation === 'plans.list') {
76
+ if (args.product)
77
+ extra.product = args.product;
44
78
  if (args.env)
45
79
  extra.env = args.env;
80
+ if (args.stage)
81
+ extra.stage = args.stage;
82
+ }
83
+ if (operation === 'releases.list') {
84
+ if (args.product)
85
+ extra.product = args.product;
86
+ if (args.function)
87
+ extra.function = args.function;
46
88
  if (args.version)
47
89
  extra.version = args.version;
48
90
  }
49
- if (operation === 'functions.list' && args.product)
50
- extra.productTag = args.product;
91
+ if (operation === 'orphans' && args.region)
92
+ extra.region = args.region;
93
+ if (operation === 'functions.list') {
94
+ if (args.product)
95
+ extra.product = args.product;
96
+ if (checkedKind(args.kind))
97
+ extra.kind = args.kind;
98
+ }
51
99
  const query = new URLSearchParams(workspaceAuthQuery(ctx, extra)).toString();
52
- const call = (method, route, body) => api.request(method, `${BASE}${route}?${query}`, body, actorHeaders());
100
+ const grant = grantHeaders(operation === 'plans.approve' || operation === 'versions.retire' || operation === 'environments.policy' ? args.grantEnv : undefined);
101
+ const call = (method, route, body) => api.request(method, `${BASE}${route}?${query}`, body, { ...actorHeaders(), ...grant });
102
+ /** The scope a code is for, from --scope or from what is being changed, so nobody has to build the string by hand. */
103
+ const scopeOfCode = async () => {
104
+ if (args.scope)
105
+ return args.scope;
106
+ if (args.plan) {
107
+ const plan = await call('GET', `/plans/${need(args.plan, '--plan')}`);
108
+ const hash = plan?.planHash;
109
+ if (!hash)
110
+ throw new Error('That plan has no plan hash to ask for a code for');
111
+ return stepUpScopes.plan(hash);
112
+ }
113
+ if (args.retire)
114
+ return stepUpScopes.retire(args.product ?? need(undefined, '--product'), args.function ?? need(undefined, '--function'), args.version ?? need(undefined, '--fn-version'));
115
+ if (args.policy)
116
+ return stepUpScopes.policy(args.product ?? need(undefined, '--product'), args.env ?? need(undefined, '--env'));
117
+ throw new Error('Say what the code is for: --plan <planId>, --retire with --product --function --fn-version, --policy with --product --env, or --scope <scope>');
118
+ };
53
119
  const fn = (suffix = '') => `/functions/${need(args.product, '--product')}/${need(args.function, '--function')}/versions${suffix}`;
54
120
  const version = () => `/${need(args.version, '--version')}`;
55
121
  let result;
@@ -60,6 +126,36 @@ export async function runDeployRemote(operation, args) {
60
126
  case 'plans.create':
61
127
  result = await call('POST', '/plans', readJsonFile(args.file, 'plan request'));
62
128
  break;
129
+ case 'releases.list':
130
+ result = await call('GET', '/releases');
131
+ break;
132
+ case 'releases.get':
133
+ result = await call('GET', `/releases/${need(args.id, 'the release hash')}`);
134
+ break;
135
+ case 'plans.list':
136
+ result = await call('GET', '/plans');
137
+ break;
138
+ case 'plans.get':
139
+ result = await call('GET', `/plans/${need(args.id, 'the plan id')}`);
140
+ break;
141
+ case 'capabilities':
142
+ result = await call('GET', '/capabilities');
143
+ break;
144
+ case 'orphans':
145
+ result = await call('GET', `/connections/${need(args.id, 'the connection')}/orphans`);
146
+ break;
147
+ case 'stepup.start':
148
+ result = await call('POST', '/step-up/start', { scope: await scopeOfCode() });
149
+ break;
150
+ case 'stepup.verify': {
151
+ if (!args.code || !/^[0-9]{6}$/.test(args.code.trim()))
152
+ throw new Error('--code is the six-digit code from your email');
153
+ result = await call('POST', '/step-up/verify', { scope: await scopeOfCode(), code: args.code.trim() });
154
+ break;
155
+ }
156
+ case 'environments.history':
157
+ result = await call('GET', `/products/${need(args.product, '--product')}/environments/${need(args.env, '--env')}/policy-changes`);
158
+ break;
63
159
  case 'plans.approve':
64
160
  result = await call('POST', `/plans/${need(args.id, 'the plan id')}/approve`, {});
65
161
  break;
@@ -75,6 +171,42 @@ export async function runDeployRemote(operation, args) {
75
171
  case 'deployments.journal':
76
172
  result = await call('GET', `/deployments/${need(args.id, 'the deployment id')}/journal`);
77
173
  break;
174
+ case 'deployments.redeploy':
175
+ case 'deployments.rollback':
176
+ case 'deployments.traffic': {
177
+ const intent = operation.split('.')[1];
178
+ let percent;
179
+ if (args.percent !== undefined) {
180
+ percent = Number(args.percent);
181
+ if (!Number.isInteger(percent) || percent < 0 || percent > 100)
182
+ throw new Error('--percent must be a whole number from 0 to 100');
183
+ }
184
+ if (intent === 'traffic' && percent === undefined)
185
+ throw new Error('--percent is required');
186
+ result = await call('POST', `/deployments/${need(args.id, 'the deployment id')}/plans`, {
187
+ intent,
188
+ ...(args.releaseHash ? { releaseHash: args.releaseHash } : {}),
189
+ ...(percent !== undefined ? { trafficPercent: percent } : {}),
190
+ ...(args.runtimeFile ? { runtime: readJsonFile(args.runtimeFile, 'runtime settings') } : {}),
191
+ ...(args.observedFile ? { observed: readJsonFile(args.observedFile, 'observed state') } : {}),
192
+ });
193
+ break;
194
+ }
195
+ case 'environments.list':
196
+ result = await call('GET', `/products/${need(args.product, '--product')}/environments`);
197
+ break;
198
+ case 'environments.policy': {
199
+ const flag = (value, name) => {
200
+ if (value !== 'true' && value !== 'false')
201
+ throw new Error(`${name} is required and must be true or false`);
202
+ return value === 'true';
203
+ };
204
+ result = await call('PUT', `/products/${need(args.product, '--product')}/environments/${need(args.env, '--env')}/policy`, {
205
+ requireHumanApproval: flag(args.requireApproval, '--require-approval'),
206
+ allowAgentApply: flag(args.allowAgentApply, '--allow-agent-apply'),
207
+ });
208
+ break;
209
+ }
78
210
  case 'functions.list':
79
211
  result = await call('GET', '/functions');
80
212
  break;
@@ -0,0 +1,30 @@
1
+ /** The largest bundle the control plane accepts. Cloudflare's own limit on a Worker is smaller. */
2
+ export declare const MAX_BUNDLE_BYTES: number;
3
+ export interface IPublishWorkerArgs {
4
+ /** A JSON file: product, function, version, contract, config, verification. Nothing about an image. */
5
+ file?: string;
6
+ connection?: string;
7
+ /** A bundle that is already built: one ES module that exports a default fetch handler. */
8
+ bundle?: string;
9
+ /** Source to bundle with esbuild first. esbuild must be installed in the project. */
10
+ entry?: string;
11
+ }
12
+ interface IEsbuild {
13
+ build(options: Record<string, unknown>): Promise<{
14
+ outputFiles?: Array<{
15
+ contents: Uint8Array;
16
+ }>;
17
+ errors?: unknown[];
18
+ }>;
19
+ }
20
+ /**
21
+ * Bundles source into the one ES module a Worker is. Node built-ins stay external because the Worker runs them through nodejs_compat,
22
+ * and the output is deterministic for the same input, so the same source gives the same release.
23
+ */
24
+ export declare function bundleWorker(entry: string, cwd?: string, esbuild?: IEsbuild): Promise<Uint8Array>;
25
+ /**
26
+ * Publishes a Cloudflare Worker release: the bundle goes through the control plane, in memory, into the customer's own Workers KV, and a
27
+ * release is registered from its digest. The source never leaves this machine; only the bundle does, and it is not kept by Ductape.
28
+ */
29
+ export declare function runDeployWorker(args: IPublishWorkerArgs): Promise<void>;
30
+ export {};
@@ -0,0 +1,85 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import path from 'node:path';
5
+ import { ApiClient } from '../lib/api-client.js';
6
+ import { requireWorkspaceContext, workspaceAuthQuery } from '../lib/workspace-context.js';
7
+ import { actorHeaders } from './deploy-remote.js';
8
+ /** The largest bundle the control plane accepts. Cloudflare's own limit on a Worker is smaller. */
9
+ export const MAX_BUNDLE_BYTES = 10 * 1024 * 1024;
10
+ function loadEsbuild(cwd) {
11
+ for (const base of [path.join(cwd, 'package.json'), import.meta.url]) {
12
+ try {
13
+ return createRequire(base)('esbuild');
14
+ }
15
+ catch { /* try the next place */ }
16
+ }
17
+ throw new Error('--entry needs esbuild to make the bundle, and it is not installed in this project. Run: npm install --save-dev esbuild (or build the bundle yourself and pass it with --bundle)');
18
+ }
19
+ /**
20
+ * Bundles source into the one ES module a Worker is. Node built-ins stay external because the Worker runs them through nodejs_compat,
21
+ * and the output is deterministic for the same input, so the same source gives the same release.
22
+ */
23
+ export async function bundleWorker(entry, cwd = process.cwd(), esbuild = loadEsbuild(cwd)) {
24
+ const resolved = path.resolve(cwd, entry);
25
+ if (!fs.existsSync(resolved))
26
+ throw new Error(`The entry file ${resolved} does not exist`);
27
+ const result = await esbuild.build({
28
+ entryPoints: [resolved], bundle: true, write: false, format: 'esm', platform: 'neutral', target: 'es2022', mainFields: ['module', 'main'], conditions: ['workerd', 'worker', 'browser'],
29
+ external: ['node:*', 'cloudflare:*'], outfile: 'index.js', legalComments: 'none', logLevel: 'silent',
30
+ });
31
+ const out = result.outputFiles?.[0];
32
+ if (!out)
33
+ throw new Error('esbuild produced no output');
34
+ return out.contents;
35
+ }
36
+ function readJson(file) {
37
+ if (!file)
38
+ throw new Error('--file is required (a JSON file with product, function, version, contract, config and verification)');
39
+ const resolved = path.resolve(file);
40
+ let parsed;
41
+ try {
42
+ parsed = JSON.parse(fs.readFileSync(resolved, 'utf8'));
43
+ }
44
+ catch (error) {
45
+ throw new Error(`Cannot read the release description at ${resolved}: ${error instanceof Error ? error.message : String(error)}`);
46
+ }
47
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
48
+ throw new Error(`The release description at ${resolved} must be a JSON object`);
49
+ return parsed;
50
+ }
51
+ /**
52
+ * Publishes a Cloudflare Worker release: the bundle goes through the control plane, in memory, into the customer's own Workers KV, and a
53
+ * release is registered from its digest. The source never leaves this machine; only the bundle does, and it is not kept by Ductape.
54
+ */
55
+ export async function runDeployWorker(args) {
56
+ if (!args.connection)
57
+ throw new Error('--connection is required (a Cloudflare connection made with the deploy scope)');
58
+ if (!args.bundle === !args.entry)
59
+ throw new Error('Give exactly one of --bundle <file> (already built) or --entry <file> (bundled here with esbuild)');
60
+ const release = readJson(args.file);
61
+ for (const key of ['product', 'function', 'version', 'contract', 'verification'])
62
+ if (release[key] === undefined)
63
+ throw new Error(`The release description has no "${key}"`);
64
+ if ('imageDigest' in release || 'imageRepository' in release)
65
+ throw new Error('A Worker release has no image: remove imageDigest and imageRepository. The bundle is what is released.');
66
+ const bytes = args.entry ? await bundleWorker(args.entry) : new Uint8Array(fs.readFileSync(path.resolve(args.bundle)));
67
+ if (bytes.byteLength === 0)
68
+ throw new Error('The bundle is empty');
69
+ if (bytes.byteLength > MAX_BUNDLE_BYTES)
70
+ throw new Error(`The bundle is ${(bytes.byteLength / 1024 / 1024).toFixed(1)} MB; the limit is ${MAX_BUNDLE_BYTES / 1024 / 1024} MB`);
71
+ const digest = `sha256:${crypto.createHash('sha256').update(bytes).digest('hex')}`;
72
+ const ctx = requireWorkspaceContext();
73
+ const api = ApiClient.forProfile(ctx.profile, ctx.credentials);
74
+ const base = '/integrations/v1/deploy';
75
+ const query = (extra = {}) => new URLSearchParams(workspaceAuthQuery(ctx, extra)).toString();
76
+ console.error(`Bundle: ${(bytes.byteLength / 1024).toFixed(1)} KB, ${digest}. Storing it in your Cloudflare account through connection ${args.connection} (nothing is kept by Ductape).`);
77
+ const staged = await api.request('PUT', `${base}/releases/worker-bundles?${query({ connection: args.connection })}`, bytes, actorHeaders());
78
+ if (staged.digest !== digest)
79
+ throw new Error(`The control plane stored a bundle with digest ${staged.digest}, not ${digest}. Nothing was registered.`);
80
+ const registered = await api.request('POST', `${base}/releases/worker?${query()}`, {
81
+ connection: args.connection, product: release.product, function: release.function, version: release.version, contract: release.contract,
82
+ ...(release.config ? { config: release.config } : {}), verification: release.verification, bundleDigest: digest,
83
+ }, actorHeaders());
84
+ console.log(JSON.stringify({ ...registered, bundle: { digest, bytes: bytes.byteLength } }, null, 2));
85
+ }
@@ -0,0 +1,49 @@
1
+ import { classifyEntry, type IScanOptions, type IScanRow } from '../lib/env-scan.js';
2
+ /** The workspace's secrets, as far as this command needs them. The real one is the SDK proxy; a test passes its own. */
3
+ export interface ISecretStore {
4
+ /** The keys of the secrets the workspace already has. */
5
+ keys(): Promise<string[]>;
6
+ create(input: {
7
+ key: string;
8
+ value: string;
9
+ description: string;
10
+ envs?: string[];
11
+ }): Promise<void>;
12
+ update(key: string, input: {
13
+ value: string;
14
+ description?: string;
15
+ }): Promise<void>;
16
+ }
17
+ export interface IScanCommandOptions extends IScanOptions {
18
+ /** The file to read. Default: .env in `dir`. */
19
+ envFile?: string;
20
+ /** The project folder. Default: the current folder. */
21
+ dir?: string;
22
+ /** The environment slug the saved secrets are limited to. Without it they are available in every environment. */
23
+ env?: string;
24
+ /** Save them. Without it nothing is saved and the result says what would be. */
25
+ apply?: boolean;
26
+ json?: boolean;
27
+ }
28
+ /** The file to read: the one named, or `.env` in the project folder. When there is none, the ones that are there are named, never read. */
29
+ export declare function locateEnvFile(options: {
30
+ envFile?: string;
31
+ dir?: string;
32
+ }, cwd?: string): string;
33
+ export interface IScanOutcome {
34
+ rows: IScanRow[];
35
+ applied: boolean;
36
+ failures: Array<{
37
+ key: string;
38
+ message: string;
39
+ }>;
40
+ result: Record<string, unknown>;
41
+ }
42
+ /**
43
+ * Reads a .env file on this machine, decides which variables are secrets, and (only with `apply`) saves them to the workspace's secrets. A value
44
+ * goes from the file to the workspace and nowhere else: it is not printed, not logged and not in any result, and an error from the workspace is
45
+ * stripped of any value before it is shown.
46
+ */
47
+ export declare function scanEnvFile(options: IScanCommandOptions, store?: ISecretStore, cwd?: string): Promise<IScanOutcome>;
48
+ export declare function runSecretsScanEnv(options: IScanCommandOptions): Promise<void>;
49
+ export { classifyEntry };