@fabrika/provider-cloudflare 0.0.1

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/src/control.ts ADDED
@@ -0,0 +1,231 @@
1
+ import type {
2
+ ControlProvider,
3
+ JsonValue,
4
+ ProviderCodec,
5
+ ProviderDeployInput,
6
+ ProviderEnvelope,
7
+ ProviderRegistration,
8
+ ProviderRegistrationInput,
9
+ ProviderSource,
10
+ ProviderTerminalOutcome,
11
+ } from '@fabrika/provider-contract'
12
+ import { cloudflareArtifactCodec } from './codec'
13
+
14
+ /** Persisted Cloudflare target data. Installation credentials never enter this envelope. */
15
+ export interface CloudflareStoredTarget {
16
+ readonly stateNamespace?: string
17
+ }
18
+
19
+ const optionalString = (payload: ProviderEnvelope['payload'], key: string): string | undefined => {
20
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) {
21
+ throw new Error('Cloudflare target must be an object')
22
+ }
23
+ const value = payload[key]
24
+ if (value === undefined) {
25
+ return undefined
26
+ }
27
+ if (typeof value !== 'string' || value === '') {
28
+ throw new Error(`Cloudflare target ${key} must be a non-empty string when present`)
29
+ }
30
+ return value
31
+ }
32
+
33
+ export const cloudflareStoredTargetCodec: ProviderCodec<CloudflareStoredTarget> = {
34
+ version: 1,
35
+ encode: (target): JsonValue => {
36
+ if (target.stateNamespace === undefined) {
37
+ return {}
38
+ }
39
+ return { stateNamespace: target.stateNamespace }
40
+ },
41
+ decode: (payload) => {
42
+ const stateNamespace = optionalString(payload, 'stateNamespace')
43
+ return stateNamespace === undefined ? {} : { stateNamespace }
44
+ },
45
+ }
46
+
47
+ /** Cloudflare-specific request carried from the control plane to the deploy runner. */
48
+ export interface CloudflareRunnerJob {
49
+ readonly runId: string
50
+ readonly repoUrl: string
51
+ readonly ref: string
52
+ readonly env: string
53
+ readonly workerDir?: string
54
+ readonly configPath?: string
55
+ readonly stateNamespace?: string
56
+ readonly domain?: string
57
+ /** Every origin IAM may hand this app a session at, projected by the control plane (ADR-0021). */
58
+ readonly returnOrigins?: readonly string[]
59
+ readonly dryRun?: boolean
60
+ readonly credentials: {
61
+ readonly CLOUDFLARE_ACCOUNT_ID: string
62
+ readonly CLOUDFLARE_API_TOKEN: string
63
+ readonly FABRIKA_IAM_URL?: string
64
+ readonly FABRIKA_IAM_PROVISIONING_KEY?: string
65
+ }
66
+ readonly secrets?: Readonly<Record<string, string>>
67
+ readonly vars?: Readonly<Record<string, string>>
68
+ readonly managedEnvironment?: Readonly<Record<string, string>>
69
+ readonly artifactUpload?: {
70
+ readonly url: string
71
+ readonly bearer: string
72
+ readonly appId: string
73
+ readonly environment: string
74
+ readonly serviceKey: string
75
+ readonly release: string
76
+ readonly runId: string
77
+ }
78
+ }
79
+
80
+ const isStringArray = (value: unknown): boolean => Array.isArray(value) && value.every((entry) => typeof entry === 'string' && entry !== '')
81
+
82
+ const isStringRecord = (value: unknown): boolean =>
83
+ typeof value === 'object'
84
+ && value !== null
85
+ && !Array.isArray(value)
86
+ && Object.values(value).every((entry) => typeof entry === 'string')
87
+
88
+ const isArtifactUpload = (value: unknown): boolean =>
89
+ typeof value === 'object'
90
+ && value !== null
91
+ && !Array.isArray(value)
92
+ && ['url', 'bearer', 'appId', 'environment', 'serviceKey', 'release', 'runId'].every((key) => {
93
+ const field = Reflect.get(value, key)
94
+ return typeof field === 'string' && field !== ''
95
+ })
96
+
97
+ /** Minimal structural validation for the Worker-to-runner JSON boundary. */
98
+ export const isCloudflareRunnerJob = (value: unknown): value is CloudflareRunnerJob => {
99
+ if (
100
+ typeof value !== 'object'
101
+ || value === null
102
+ || !('runId' in value && typeof value.runId === 'string')
103
+ || !('repoUrl' in value && typeof value.repoUrl === 'string')
104
+ || !('ref' in value && typeof value.ref === 'string')
105
+ || !('env' in value && typeof value.env === 'string')
106
+ || !('credentials' in value && typeof value.credentials === 'object' && value.credentials !== null)
107
+ ) {
108
+ return false
109
+ }
110
+ const credentials = value.credentials
111
+ const requiredCredentials = 'CLOUDFLARE_ACCOUNT_ID' in credentials
112
+ && typeof credentials.CLOUDFLARE_ACCOUNT_ID === 'string'
113
+ && credentials.CLOUDFLARE_ACCOUNT_ID !== ''
114
+ && 'CLOUDFLARE_API_TOKEN' in credentials
115
+ && typeof credentials.CLOUDFLARE_API_TOKEN === 'string'
116
+ && credentials.CLOUDFLARE_API_TOKEN !== ''
117
+ if (!requiredCredentials) {
118
+ return false
119
+ }
120
+ if (
121
+ ('FABRIKA_IAM_URL' in credentials && credentials.FABRIKA_IAM_URL !== undefined && typeof credentials.FABRIKA_IAM_URL !== 'string')
122
+ || ('FABRIKA_IAM_PROVISIONING_KEY' in credentials
123
+ && credentials.FABRIKA_IAM_PROVISIONING_KEY !== undefined
124
+ && typeof credentials.FABRIKA_IAM_PROVISIONING_KEY !== 'string')
125
+ || ('workerDir' in value && value.workerDir !== undefined && typeof value.workerDir !== 'string')
126
+ || ('configPath' in value && value.configPath !== undefined && typeof value.configPath !== 'string')
127
+ || ('stateNamespace' in value && value.stateNamespace !== undefined && typeof value.stateNamespace !== 'string')
128
+ || ('domain' in value && value.domain !== undefined && typeof value.domain !== 'string')
129
+ || ('returnOrigins' in value && value.returnOrigins !== undefined && !isStringArray(value.returnOrigins))
130
+ || ('dryRun' in value && value.dryRun !== undefined && typeof value.dryRun !== 'boolean')
131
+ || ('secrets' in value && value.secrets !== undefined && !isStringRecord(value.secrets))
132
+ || ('vars' in value && value.vars !== undefined && !isStringRecord(value.vars))
133
+ || ('managedEnvironment' in value && value.managedEnvironment !== undefined && !isStringRecord(value.managedEnvironment))
134
+ || ('artifactUpload' in value && value.artifactUpload !== undefined && !isArtifactUpload(value.artifactUpload))
135
+ ) {
136
+ return false
137
+ }
138
+ return true
139
+ }
140
+
141
+ export interface ResolvedCloudflareSource {
142
+ readonly repoUrl: string
143
+ readonly ref: string
144
+ }
145
+
146
+ export interface CloudflareControlOptions {
147
+ readonly accountId: string
148
+ readonly apiToken: string
149
+ readonly propustkaUrl?: string
150
+ readonly propustkaProvisioningKey?: string
151
+ resolveSource(source: ProviderSource): Promise<ResolvedCloudflareSource>
152
+ startRun(job: CloudflareRunnerJob): Promise<ProviderTerminalOutcome>
153
+ cancelRun(runId: string): Promise<void>
154
+ }
155
+
156
+ const decodeEnvelope = <T>(kind: string, envelope: ProviderEnvelope, codec: ProviderCodec<T>): T => {
157
+ if (envelope.provider !== 'cloudflare') {
158
+ throw new Error(`${kind} belongs to provider "${envelope.provider}", expected "cloudflare"`)
159
+ }
160
+ if (envelope.version !== codec.version) {
161
+ throw new Error(`${kind} schema version ${envelope.version} is not supported by provider "cloudflare"`)
162
+ }
163
+ return codec.decode(envelope.payload)
164
+ }
165
+
166
+ const encodeEnvelope = <T>(codec: ProviderCodec<T>, value: T): ProviderEnvelope => ({
167
+ provider: 'cloudflare',
168
+ version: codec.version,
169
+ payload: codec.encode(value),
170
+ })
171
+
172
+ const normalizeRegistration = (input: ProviderRegistrationInput): ProviderRegistration => {
173
+ if (input.app.id !== input.environment.appId) {
174
+ throw new Error(`Cloudflare environment belongs to app "${input.environment.appId}", expected "${input.app.id}"`)
175
+ }
176
+ const target = decodeEnvelope('target', input.environment.target, cloudflareStoredTargetCodec)
177
+ const artifact = decodeEnvelope('artifact', input.environment.artifact, cloudflareArtifactCodec)
178
+ return {
179
+ app: input.app,
180
+ environment: {
181
+ ...input.environment,
182
+ target: encodeEnvelope(cloudflareStoredTargetCodec, target),
183
+ artifact: encodeEnvelope(cloudflareArtifactCodec, artifact),
184
+ },
185
+ }
186
+ }
187
+
188
+ const buildJob = async (options: CloudflareControlOptions, input: ProviderDeployInput): Promise<CloudflareRunnerJob> => {
189
+ const source = await options.resolveSource(input.app.source)
190
+ const storedTarget = decodeEnvelope('target', input.environment.target, cloudflareStoredTargetCodec)
191
+ const artifact = decodeEnvelope('artifact', input.environment.artifact, cloudflareArtifactCodec)
192
+ const managedEnvironment: Record<string, string> = {}
193
+ for (const [name, value] of Object.entries(input.managedEnvironment)) {
194
+ if (value !== null) managedEnvironment[name] = value
195
+ }
196
+ return {
197
+ runId: input.runId,
198
+ repoUrl: source.repoUrl,
199
+ ref: source.ref,
200
+ env: input.environment.env,
201
+ credentials: {
202
+ CLOUDFLARE_ACCOUNT_ID: options.accountId,
203
+ CLOUDFLARE_API_TOKEN: options.apiToken,
204
+ ...(options.propustkaUrl === undefined ? {} : { FABRIKA_IAM_URL: options.propustkaUrl }),
205
+ ...(options.propustkaProvisioningKey === undefined
206
+ ? {}
207
+ : { FABRIKA_IAM_PROVISIONING_KEY: options.propustkaProvisioningKey }),
208
+ },
209
+ ...(input.app.source.workerDir === undefined ? {} : { workerDir: input.app.source.workerDir }),
210
+ configPath: artifact.configPath,
211
+ ...(storedTarget.stateNamespace === undefined ? {} : { stateNamespace: storedTarget.stateNamespace }),
212
+ ...(input.environment.domain === undefined ? {} : { domain: input.environment.domain }),
213
+ ...(input.returnOrigins === undefined ? {} : { returnOrigins: input.returnOrigins }),
214
+ ...(input.dryRun ? { dryRun: true } : {}),
215
+ ...(Object.keys(input.secrets).length === 0 ? {} : { secrets: input.secrets }),
216
+ ...(Object.keys(input.vars).length === 0 ? {} : { vars: input.vars }),
217
+ ...(Object.keys(managedEnvironment).length === 0 ? {} : { managedEnvironment }),
218
+ ...(input.artifactUpload === undefined ? {} : { artifactUpload: input.artifactUpload }),
219
+ }
220
+ }
221
+
222
+ /** Build the Cloudflare control capability over its runner and source-resolution ports. */
223
+ export const createCloudflareControlProvider = (options: CloudflareControlOptions): ControlProvider => ({
224
+ id: 'cloudflare',
225
+ normalizeRegistration,
226
+ deploy: async (input) => {
227
+ await input.events.externalId(input.runId)
228
+ return options.startRun(await buildJob(options, input))
229
+ },
230
+ cancel: (input) => options.cancelRun(input.runId),
231
+ })
package/src/index.ts ADDED
@@ -0,0 +1,26 @@
1
+ export * from 'oblaka-iac'
2
+ export { type CloudflareAppConfig, type CloudflareAppConfigInput, defineApp, isCloudflareAppConfig, type ResourceContext } from './authoring'
3
+ export { parseCloudflareArgs, platformComponents } from './cli-args'
4
+ export type { ParsedCloudflareArgs, PlatformComponent } from './cli-args'
5
+ export { type CloudflareArtifact, cloudflareArtifact, cloudflareArtifactCodec, type CloudflareTarget, cloudflareTargetCodec } from './codec'
6
+ export {
7
+ type CloudflareCollaborators,
8
+ type CloudflareConfigLoader,
9
+ type CommandResult,
10
+ type CommandRunner,
11
+ type CommandSpec,
12
+ defaultCloudflareCollaborators,
13
+ type LoadedCloudflareConfig,
14
+ type OblakaProvisioner,
15
+ type ProvisionInput,
16
+ type SchemaReconciler,
17
+ } from './collaborators'
18
+ export { deployCloudflareConfig, loadCloudflareCommandConfig } from './command'
19
+ export type { CloudflareCommandDeployOptions, LoadedCloudflareCommandConfig } from './command'
20
+ export { cloudflareStoredTargetCodec, createCloudflareControlProvider, isCloudflareRunnerJob } from './control'
21
+ export type { CloudflareControlOptions, CloudflareRunnerJob, CloudflareStoredTarget, ResolvedCloudflareSource } from './control'
22
+ export { buildPlan, findMigratableDatabases } from './plan'
23
+ export type { CloudflareJobSpec, CloudflarePlan, CloudflarePlanInput, CloudflareStepKind, MigratableDatabase } from './plan'
24
+ export { cloudflareProvider, createCloudflareProvider } from './provider'
25
+ export { createCloudflareProxyWorker } from './proxy'
26
+ export type { CloudflareProxyWorkerOptions } from './proxy'
package/src/plan.ts ADDED
@@ -0,0 +1,92 @@
1
+ import type { ProviderDeployPlan, ProviderJobSpec } from '@fabrika/provider-contract'
2
+ import { Worker } from 'oblaka-iac'
3
+ import type { CloudflareAppConfig } from './authoring'
4
+
5
+ export type CloudflareStepKind = 'build' | 'provision-resources' | 'migrate' | 'deploy-worker' | 'reconcile-schema' | 'sync-secrets'
6
+
7
+ export interface CloudflareJobSpec extends ProviderJobSpec {
8
+ readonly kind: CloudflareStepKind
9
+ }
10
+
11
+ export interface CloudflarePlan extends ProviderDeployPlan {
12
+ readonly steps: readonly CloudflareJobSpec[]
13
+ }
14
+
15
+ export interface MigratableDatabase {
16
+ readonly binding: string
17
+ readonly name: string
18
+ }
19
+
20
+ const migratableDatabaseName = (value: unknown): string | null => {
21
+ if (typeof value !== 'object' || value === null || !('options' in value)) {
22
+ return null
23
+ }
24
+ const { options } = value
25
+ if (typeof options !== 'object' || options === null) {
26
+ return null
27
+ }
28
+ if (!('migrationsDir' in options) || typeof options.migrationsDir !== 'string' || options.migrationsDir === '') {
29
+ return null
30
+ }
31
+ return 'name' in options && typeof options.name === 'string' ? options.name : null
32
+ }
33
+
34
+ export const findMigratableDatabases = (worker: Worker): MigratableDatabase[] => {
35
+ const databases: MigratableDatabase[] = []
36
+ const visit = (current: Worker, prefix: string): void => {
37
+ for (const [binding, value] of Object.entries(current.options.bindings ?? {})) {
38
+ const qualifiedBinding = prefix === '' ? binding : `${prefix}.${binding}`
39
+ const name = migratableDatabaseName(value)
40
+ if (name !== null) {
41
+ databases.push({ binding: qualifiedBinding, name })
42
+ }
43
+ if (value instanceof Worker) {
44
+ visit(value, qualifiedBinding)
45
+ }
46
+ }
47
+ }
48
+ visit(worker, '')
49
+ return databases
50
+ }
51
+
52
+ export interface CloudflarePlanInput {
53
+ readonly appId: string
54
+ readonly env: string
55
+ readonly propustkaUrl?: string
56
+ }
57
+
58
+ export const buildPlan = (
59
+ config: CloudflareAppConfig,
60
+ input: CloudflarePlanInput,
61
+ worker: Worker,
62
+ ): CloudflarePlan => {
63
+ const steps: CloudflareJobSpec[] = []
64
+ let previous: string | undefined
65
+
66
+ const add = (spec: Omit<CloudflareJobSpec, 'dependsOn'>): void => {
67
+ steps.push(previous === undefined ? spec : { ...spec, dependsOn: [previous] })
68
+ previous = spec.id
69
+ }
70
+
71
+ if (config.pipeline?.build !== undefined) {
72
+ add({ id: 'build', kind: 'build', description: `Build the Worker (\`${config.pipeline.build}\`)` })
73
+ }
74
+
75
+ add({ id: 'provision-resources', kind: 'provision-resources', description: 'Provision Cloudflare resources via oblaka' })
76
+
77
+ for (const database of findMigratableDatabases(worker)) {
78
+ add({ id: `migrate:${database.binding}`, kind: 'migrate', description: `Apply D1 migrations for \`${database.binding}\` (${database.name})` })
79
+ }
80
+
81
+ add({ id: 'deploy-worker', kind: 'deploy-worker', description: 'Deploy the Worker (`wrangler deploy`)' })
82
+
83
+ if (config.schema !== undefined && input.propustkaUrl !== undefined) {
84
+ add({ id: 'reconcile-schema', kind: 'reconcile-schema', description: 'Reconcile authz schema into IAM' })
85
+ }
86
+
87
+ if (config.pipeline?.secrets !== undefined && config.pipeline.secrets.length > 0) {
88
+ add({ id: 'sync-secrets', kind: 'sync-secrets', description: `Sync ${config.pipeline.secrets.length} secret(s) via \`wrangler secret put\`` })
89
+ }
90
+
91
+ return { appId: input.appId, env: input.env, steps }
92
+ }
@@ -0,0 +1,253 @@
1
+ import { createProvider, type ProviderDeploySession, type TypedProviderRun } from '@fabrika/provider-contract'
2
+ import { dirname, resolve } from 'node:path'
3
+ import { type GeneratedConfig, Worker } from 'oblaka-iac'
4
+ import type { CloudflareAppConfig } from './authoring'
5
+ import { type CloudflareArtifact, cloudflareArtifactCodec, type CloudflareTarget, cloudflareTargetCodec } from './codec'
6
+ import { type CloudflareCollaborators, defaultCloudflareCollaborators } from './collaborators'
7
+ import { buildPlan, type CloudflareJobSpec, findMigratableDatabases } from './plan'
8
+
9
+ const CANCELLED = 'deploy cancelled'
10
+
11
+ const workerDir = (config: CloudflareAppConfig, cwd: string): string => resolve(cwd, config.pipeline?.workerDir ?? '.')
12
+
13
+ const wranglerEnv = (target: CloudflareTarget): Record<string, string> => ({
14
+ CLOUDFLARE_API_TOKEN: target.apiToken,
15
+ CLOUDFLARE_ACCOUNT_ID: target.accountId,
16
+ })
17
+
18
+ const commandError = (label: string, result: { exitCode: number; stdout: string; stderr: string }): Error => {
19
+ const detail = (result.stderr.trim() || result.stdout.trim() || '(no output)').slice(0, 2000)
20
+ return new Error(`${label} failed (exit ${result.exitCode}): ${detail}`)
21
+ }
22
+
23
+ const assertRunning = (signal: AbortSignal): void => {
24
+ if (signal.aborted) {
25
+ throw new Error(CANCELLED)
26
+ }
27
+ }
28
+
29
+ type CloudflareRun = TypedProviderRun<CloudflareTarget, CloudflareArtifact>
30
+
31
+ const withManagedEnvironment = (config: CloudflareAppConfig, authored: Worker, run: CloudflareRun): Worker => {
32
+ const managed = run.managedEnvironment
33
+ const present: Record<string, string> = {}
34
+ const declared = new Set(config.pipeline?.vars ?? [])
35
+ const application = applicationWorker(authored)
36
+ for (const [name, value] of Object.entries(managed)) {
37
+ if (declared.has(name) || application.options.vars?.[name] !== undefined || run.vars[name] !== undefined) {
38
+ throw new Error(`cloudflare: application variable \`${name}\` is managed by Fabrika`)
39
+ }
40
+ if (value !== null) present[name] = value
41
+ }
42
+ if (Object.keys(present).length === 0) return authored
43
+ const configured = new Worker({
44
+ ...application.options,
45
+ vars: {
46
+ ...(application.options.vars ?? {}),
47
+ ...present,
48
+ },
49
+ })
50
+ return replaceApplicationWorker(authored, configured)
51
+ }
52
+
53
+ const applicationWorker = (worker: Worker): Worker => {
54
+ const child = worker.options.bindings?.['APP']
55
+ return child instanceof Worker ? applicationWorker(child) : worker
56
+ }
57
+
58
+ const replaceApplicationWorker = (worker: Worker, replacement: Worker): Worker => {
59
+ const child = worker.options.bindings?.['APP']
60
+ if (!(child instanceof Worker)) return replacement
61
+ return new Worker({
62
+ ...worker.options,
63
+ bindings: {
64
+ ...(worker.options.bindings ?? {}),
65
+ APP: replaceApplicationWorker(child, replacement),
66
+ },
67
+ })
68
+ }
69
+
70
+ const databaseOwnerDir = (worker: Worker, binding: string, rootDir: string): string => {
71
+ const parts = binding.split('.')
72
+ let current = worker
73
+ for (let index = 0; index < parts.length - 1; index++) {
74
+ const part = parts[index]
75
+ if (part === undefined) return rootDir
76
+ const child = current.options.bindings?.[part]
77
+ if (!(child instanceof Worker)) return rootDir
78
+ current = child
79
+ }
80
+ return resolve(rootDir, current.options.dir)
81
+ }
82
+
83
+ const migrationBinding = (binding: string): string => {
84
+ const parts = binding.split('.')
85
+ return parts[parts.length - 1] ?? binding
86
+ }
87
+
88
+ interface StepEnv {
89
+ readonly config: CloudflareAppConfig
90
+ readonly run: CloudflareRun
91
+ readonly worker: Worker
92
+ readonly dir: string
93
+ readonly cf: CloudflareCollaborators
94
+ generatedConfigs: readonly GeneratedConfig[]
95
+ }
96
+
97
+ const runStep = async (spec: CloudflareJobSpec, env: StepEnv): Promise<void> => {
98
+ const { config, run, worker, dir, cf } = env
99
+ const { target, signal, dryRun } = run
100
+
101
+ switch (spec.kind) {
102
+ case 'build': {
103
+ const build = config.pipeline?.build
104
+ if (build === undefined) return
105
+ if (dryRun) {
106
+ run.events.log(` [dry-run] would run build: \`${build}\` in ${dir}`)
107
+ return
108
+ }
109
+ assertRunning(signal)
110
+ const result = await cf.runCommand({ command: 'sh', args: ['-c', build], cwd: dir, signal })
111
+ if (result.exitCode !== 0) throw commandError(`build (\`${build}\`)`, result)
112
+ return
113
+ }
114
+ case 'provision-resources': {
115
+ assertRunning(signal)
116
+ const result = await cf.provision({
117
+ definition: worker,
118
+ accountId: target.accountId,
119
+ apiToken: target.apiToken,
120
+ env: run.env,
121
+ cwd: dir,
122
+ stateNamespace: target.stateNamespace ?? `${config.id}-state`,
123
+ dryRun,
124
+ })
125
+ env.generatedConfigs = result.wranglerConfigs
126
+ const names = result.wranglerConfigs.map((item) => item.config.name ?? '(unnamed)').join(', ')
127
+ run.events.log(dryRun ? ` [dry-run] provisioned (plan-only): ${names}` : ` provisioned: ${names}`)
128
+ return
129
+ }
130
+ case 'migrate': {
131
+ const binding = spec.id.slice('migrate:'.length)
132
+ const database = findMigratableDatabases(worker).find((item) => item.binding === binding)
133
+ if (database === undefined) throw new Error(`migrate: no migratable D1 database for binding \`${binding}\``)
134
+ const commandBinding = migrationBinding(database.binding)
135
+ const migrationDir = databaseOwnerDir(worker, database.binding, dir)
136
+ if (dryRun) {
137
+ run.events.log(` [dry-run] would run: wrangler d1 migrations apply ${commandBinding} --remote in ${migrationDir}`)
138
+ return
139
+ }
140
+ assertRunning(signal)
141
+ const result = await cf.runCommand({
142
+ command: 'wrangler',
143
+ args: ['d1', 'migrations', 'apply', commandBinding, '--remote'],
144
+ cwd: migrationDir,
145
+ env: wranglerEnv(target),
146
+ signal,
147
+ })
148
+ if (result.exitCode !== 0) throw commandError(`wrangler d1 migrations apply ${commandBinding}`, result)
149
+ return
150
+ }
151
+ case 'deploy-worker': {
152
+ const configs = env.generatedConfigs
153
+ if (configs.length === 0) {
154
+ if (dryRun) {
155
+ run.events.log(` [dry-run] would run: wrangler deploy in ${dir}`)
156
+ return
157
+ }
158
+ assertRunning(signal)
159
+ const result = await cf.runCommand({ command: 'wrangler', args: ['deploy'], cwd: dir, env: wranglerEnv(target), signal })
160
+ if (result.exitCode !== 0) throw commandError('wrangler deploy', result)
161
+ return
162
+ }
163
+ for (const generated of configs) {
164
+ const generatedDir = dirname(resolve(dir, generated.path))
165
+ if (dryRun) {
166
+ run.events.log(` [dry-run] would run: wrangler deploy in ${generatedDir}`)
167
+ continue
168
+ }
169
+ assertRunning(signal)
170
+ const result = await cf.runCommand({ command: 'wrangler', args: ['deploy'], cwd: generatedDir, env: wranglerEnv(target), signal })
171
+ if (result.exitCode !== 0) throw commandError('wrangler deploy', result)
172
+ }
173
+ return
174
+ }
175
+ case 'reconcile-schema': {
176
+ if (config.schema === undefined || target.propustkaUrl === undefined) return
177
+ // Return origins ride this step because `apps.setReturnOrigins` 404s for an app IAM has never
178
+ // heard of, and the schema reconcile is what registers it. Separate call, same moment.
179
+ const returnOrigins = run.returnOrigins !== undefined && run.returnOrigins.length > 0 ? run.returnOrigins : undefined
180
+ if (dryRun) {
181
+ run.events.log(` [dry-run] would reconcile schema for \`${config.id}\` against ${target.propustkaUrl}`)
182
+ if (returnOrigins !== undefined) {
183
+ run.events.log(` [dry-run] would register return origins for \`${config.id}\`: ${returnOrigins.join(', ')}`)
184
+ }
185
+ return
186
+ }
187
+ assertRunning(signal)
188
+ await cf.reconcileSchema({
189
+ url: target.propustkaUrl,
190
+ app: config.id,
191
+ schema: config.schema,
192
+ ...(returnOrigins === undefined ? {} : { returnOrigins }),
193
+ adminKey: target.adminKey,
194
+ signal,
195
+ })
196
+ return
197
+ }
198
+ case 'sync-secrets': {
199
+ const secretsDir = resolve(dir, applicationWorker(worker).options.dir)
200
+ for (const name of config.pipeline?.secrets ?? []) {
201
+ const value = run.secrets[name]
202
+ if (value === undefined) throw new Error(`sync-secrets: missing value for secret \`${name}\` (not in run.secrets)`)
203
+ if (dryRun) {
204
+ run.events.log(` [dry-run] would run: wrangler secret put ${name} (value piped from run.secrets)`)
205
+ continue
206
+ }
207
+ assertRunning(signal)
208
+ const result = await cf.runCommand({
209
+ command: 'wrangler',
210
+ args: ['secret', 'put', name],
211
+ cwd: secretsDir,
212
+ env: wranglerEnv(target),
213
+ stdin: value,
214
+ signal,
215
+ })
216
+ if (result.exitCode !== 0) throw commandError(`wrangler secret put ${name}`, result)
217
+ }
218
+ return
219
+ }
220
+ }
221
+ }
222
+
223
+ export const createCloudflareProvider = (cf: CloudflareCollaborators = defaultCloudflareCollaborators) =>
224
+ createProvider({
225
+ id: 'cloudflare',
226
+ target: cloudflareTargetCodec,
227
+ artifact: cloudflareArtifactCodec,
228
+ open: async (run): Promise<ProviderDeploySession> => {
229
+ const loaded = await cf.loadConfig(run.cwd, run.artifact.configPath)
230
+ if (loaded.config.id !== run.appId) {
231
+ throw new Error(`Cloudflare config declares app "${loaded.config.id}", expected "${run.appId}"`)
232
+ }
233
+ const worker = withManagedEnvironment(
234
+ loaded.config,
235
+ loaded.config.resources({ env: run.env, domain: run.domain }),
236
+ run,
237
+ )
238
+ const dir = workerDir(loaded.config, loaded.cwd)
239
+ const plan = buildPlan(loaded.config, { appId: run.appId, env: run.env, propustkaUrl: run.target.propustkaUrl }, worker)
240
+ const byId = new Map(plan.steps.map((step): [string, CloudflareJobSpec] => [step.id, step]))
241
+ const env: StepEnv = { config: loaded.config, run, worker, dir, cf, generatedConfigs: [] }
242
+ return {
243
+ plan,
244
+ execute: async (stepId): Promise<void> => {
245
+ const spec = byId.get(stepId)
246
+ if (spec === undefined) throw new Error(`cloudflare: no step \`${stepId}\` in this plan`)
247
+ await runStep(spec, env)
248
+ },
249
+ }
250
+ },
251
+ })
252
+
253
+ export const cloudflareProvider = createCloudflareProvider()