oblaka-iac 0.0.15 → 0.0.17
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/package.json +1 -1
- package/src/api.ts +76 -0
- package/src/auth.ts +212 -0
- package/src/client.ts +3 -5
- package/src/commands/deploy.ts +24 -10
- package/src/commands/input.ts +4 -0
- package/src/commands/load-definition.ts +11 -0
- package/src/commands/resource-processor.ts +25 -4
- package/src/commands/run.ts +6 -3
- package/src/index.ts +4 -0
package/package.json
CHANGED
package/src/api.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import * as fs from 'node:fs/promises'
|
|
2
|
+
import * as path from 'node:path'
|
|
3
|
+
import { CloudflareDeployExecutor } from './commands/deploy'
|
|
4
|
+
import type { Input } from './commands/input'
|
|
5
|
+
import type { ConfigWriter, GeneratedConfig } from './commands/resource-processor'
|
|
6
|
+
import type { Worker } from './resources'
|
|
7
|
+
|
|
8
|
+
export type Definition = Worker
|
|
9
|
+
|
|
10
|
+
export interface DeployOptions {
|
|
11
|
+
accountId: string
|
|
12
|
+
apiToken: string
|
|
13
|
+
env?: string
|
|
14
|
+
stateNamespace?: string
|
|
15
|
+
stateNamespaceId?: string
|
|
16
|
+
dryRun?: boolean
|
|
17
|
+
remote?: boolean
|
|
18
|
+
cwd?: string
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface DeployResult {
|
|
22
|
+
wranglerConfigs: GeneratedConfig[]
|
|
23
|
+
wranglerConfig: GeneratedConfig['config'] | undefined
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Programmatically provision the resources of an already-constructed oblaka definition
|
|
28
|
+
* (the result of `define()` / `new Worker(...)`) against Cloudflare.
|
|
29
|
+
*
|
|
30
|
+
* Unlike the CLI, this skips loading the recipe file and works directly on the in-memory
|
|
31
|
+
* definition. It always returns the generated wrangler config(s); `wrangler.jsonc` is written
|
|
32
|
+
* to disk only when `remote` is set and `dryRun` is not (mirroring the CLI deploy behavior).
|
|
33
|
+
*
|
|
34
|
+
* State is stored in the `cf-state` KV namespace under a per-env key (the `env` value).
|
|
35
|
+
*
|
|
36
|
+
* Note: this does not run `wrangler deploy` — it only provisions resources and returns the
|
|
37
|
+
* config the caller needs to feed to `wrangler deploy` themselves.
|
|
38
|
+
*/
|
|
39
|
+
export const deploy = async (definition: Definition | undefined, options: DeployOptions): Promise<DeployResult> => {
|
|
40
|
+
const env = options.env || 'local'
|
|
41
|
+
const cwd = options.cwd ?? process.cwd()
|
|
42
|
+
const remote = options.remote ?? false
|
|
43
|
+
const dryRun = options.dryRun ?? false
|
|
44
|
+
|
|
45
|
+
const input: Input = {
|
|
46
|
+
main: '',
|
|
47
|
+
env,
|
|
48
|
+
stateNamespace: options.stateNamespace || 'cf-state',
|
|
49
|
+
stateNamespaceId: options.stateNamespaceId,
|
|
50
|
+
accountId: options.accountId,
|
|
51
|
+
apiToken: options.apiToken,
|
|
52
|
+
dryRun,
|
|
53
|
+
remote,
|
|
54
|
+
destroy: false,
|
|
55
|
+
validate: false,
|
|
56
|
+
outStatePath: undefined,
|
|
57
|
+
// Programmatic deploy always supplies an explicit apiToken, so wrangler's
|
|
58
|
+
// OAuth token provider (and its persistence) is never exercised.
|
|
59
|
+
persistToken: false,
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const shouldWrite = remote && !dryRun
|
|
63
|
+
const configWriter: ConfigWriter = async (configPath, content) => {
|
|
64
|
+
if (!shouldWrite) {
|
|
65
|
+
return
|
|
66
|
+
}
|
|
67
|
+
await fs.writeFile(path.resolve(cwd, configPath), content)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const wranglerConfigs = await CloudflareDeployExecutor.execute({ input, definition, configWriter })
|
|
71
|
+
|
|
72
|
+
return {
|
|
73
|
+
wranglerConfigs,
|
|
74
|
+
wranglerConfig: wranglerConfigs[0]?.config,
|
|
75
|
+
}
|
|
76
|
+
}
|
package/src/auth.ts
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import * as fs from 'node:fs'
|
|
2
|
+
import * as os from 'node:os'
|
|
3
|
+
import * as path from 'node:path'
|
|
4
|
+
|
|
5
|
+
// Cloudflare's REST API accepts an OAuth access token as a Bearer token, exactly
|
|
6
|
+
// like an API token. So to support `wrangler login`-style auth we only need to
|
|
7
|
+
// read (and refresh) the credentials wrangler already stores on disk and hand
|
|
8
|
+
// the access token to CloudflareClient. The constants below mirror wrangler so
|
|
9
|
+
// the refresh flow stays compatible with the same default.toml.
|
|
10
|
+
|
|
11
|
+
const DEFAULT_CLIENT_ID = '54d11594-84e4-41aa-b438-e81b8fa78ee7'
|
|
12
|
+
const EXPIRY_BUFFER_MS = 10_000
|
|
13
|
+
|
|
14
|
+
export interface WranglerCredentials {
|
|
15
|
+
oauthToken: string
|
|
16
|
+
refreshToken: string
|
|
17
|
+
/** ISO timestamp of when `oauthToken` expires. */
|
|
18
|
+
expirationTime: string
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** The subset of fields a token refresh produces and writes back. */
|
|
22
|
+
type RefreshedCredentials = Pick<WranglerCredentials, 'oauthToken' | 'refreshToken' | 'expirationTime'>
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Mirrors wrangler's `getGlobalWranglerConfigPath()`: prefer the legacy
|
|
26
|
+
* `~/.wrangler` directory when it exists, otherwise the platform XDG config dir.
|
|
27
|
+
*/
|
|
28
|
+
export function getWranglerConfigPath(): string {
|
|
29
|
+
const legacy = path.join(os.homedir(), '.wrangler')
|
|
30
|
+
const dir = isDirectory(legacy) ? legacy : xdgWranglerDir()
|
|
31
|
+
return path.join(dir, 'config', 'default.toml')
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function isDirectory(p: string): boolean {
|
|
35
|
+
try {
|
|
36
|
+
return fs.statSync(p).isDirectory()
|
|
37
|
+
} catch {
|
|
38
|
+
return false
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function xdgWranglerDir(): string {
|
|
43
|
+
const home = os.homedir()
|
|
44
|
+
const name = '.wrangler'
|
|
45
|
+
if (process.platform === 'win32') {
|
|
46
|
+
const appData = process.env.APPDATA ?? path.join(home, 'AppData', 'Roaming')
|
|
47
|
+
return path.join(appData, 'xdg.config', name)
|
|
48
|
+
}
|
|
49
|
+
if (process.platform === 'darwin') {
|
|
50
|
+
return path.join(process.env.XDG_CONFIG_HOME ?? path.join(home, 'Library', 'Preferences'), name)
|
|
51
|
+
}
|
|
52
|
+
return path.join(process.env.XDG_CONFIG_HOME ?? path.join(home, '.config'), name)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function parseWranglerCredentials(toml: string): WranglerCredentials | null {
|
|
56
|
+
const str = (key: string) => toml.match(new RegExp(`^\\s*${key}\\s*=\\s*"([^"]*)"`, 'm'))?.[1]
|
|
57
|
+
const oauthToken = str('oauth_token')
|
|
58
|
+
const refreshToken = str('refresh_token')
|
|
59
|
+
const expirationTime = str('expiration_time')
|
|
60
|
+
if (!oauthToken || !refreshToken || !expirationTime) {
|
|
61
|
+
return null
|
|
62
|
+
}
|
|
63
|
+
return { oauthToken, refreshToken, expirationTime }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function readWranglerCredentials(configPath = getWranglerConfigPath()): WranglerCredentials | null {
|
|
67
|
+
let contents: string
|
|
68
|
+
try {
|
|
69
|
+
contents = fs.readFileSync(configPath, 'utf8')
|
|
70
|
+
} catch {
|
|
71
|
+
return null
|
|
72
|
+
}
|
|
73
|
+
return parseWranglerCredentials(contents)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function hasWranglerCredentials(configPath?: string): boolean {
|
|
77
|
+
return readWranglerCredentials(configPath) !== null
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Replaces a `key = "value"` line in place, or appends it if absent, leaving
|
|
81
|
+
* every other line (scopes, comments, future wrangler fields) untouched. */
|
|
82
|
+
function upsertTomlString(contents: string, key: string, value: string): string {
|
|
83
|
+
const line = `${key} = "${value}"`
|
|
84
|
+
const re = new RegExp(`^(\\s*)${key}\\s*=.*$`, 'm')
|
|
85
|
+
if (re.test(contents)) {
|
|
86
|
+
return contents.replace(re, `$1${line}`)
|
|
87
|
+
}
|
|
88
|
+
const prefix = contents.length === 0 || contents.endsWith('\n') ? contents : `${contents}\n`
|
|
89
|
+
return `${prefix}${line}\n`
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function writeWranglerCredentials(configPath: string, creds: RefreshedCredentials): void {
|
|
93
|
+
// Update the three fields in place so any other keys wrangler stores
|
|
94
|
+
// (scopes, comments, fields added in future versions) are preserved.
|
|
95
|
+
let contents = ''
|
|
96
|
+
try {
|
|
97
|
+
contents = fs.readFileSync(configPath, 'utf8')
|
|
98
|
+
} catch {}
|
|
99
|
+
contents = upsertTomlString(contents, 'oauth_token', creds.oauthToken)
|
|
100
|
+
contents = upsertTomlString(contents, 'expiration_time', creds.expirationTime)
|
|
101
|
+
contents = upsertTomlString(contents, 'refresh_token', creds.refreshToken)
|
|
102
|
+
|
|
103
|
+
// Write to a sibling temp file then rename so a crash can't leave wrangler's
|
|
104
|
+
// credentials file half-written.
|
|
105
|
+
const tmp = `${configPath}.${process.pid}.tmp`
|
|
106
|
+
fs.writeFileSync(tmp, contents, { mode: 0o600 })
|
|
107
|
+
fs.renameSync(tmp, configPath)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
interface TokenEndpointResponse {
|
|
111
|
+
access_token: string
|
|
112
|
+
expires_in: number
|
|
113
|
+
refresh_token?: string
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
interface RefreshDeps {
|
|
117
|
+
fetch?: typeof fetch
|
|
118
|
+
tokenUrl?: string
|
|
119
|
+
clientId?: string
|
|
120
|
+
now?: () => number
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export async function refreshAccessToken(
|
|
124
|
+
refreshToken: string,
|
|
125
|
+
deps: RefreshDeps = {},
|
|
126
|
+
): Promise<RefreshedCredentials> {
|
|
127
|
+
const doFetch = deps.fetch ?? fetch
|
|
128
|
+
const tokenUrl = deps.tokenUrl ?? tokenUrlFromEnv()
|
|
129
|
+
const clientId = deps.clientId ?? (process.env.WRANGLER_CLIENT_ID || DEFAULT_CLIENT_ID)
|
|
130
|
+
const now = deps.now ?? Date.now
|
|
131
|
+
|
|
132
|
+
const response = await doFetch(tokenUrl, {
|
|
133
|
+
method: 'POST',
|
|
134
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
135
|
+
body: new URLSearchParams({
|
|
136
|
+
grant_type: 'refresh_token',
|
|
137
|
+
refresh_token: refreshToken,
|
|
138
|
+
client_id: clientId,
|
|
139
|
+
}).toString(),
|
|
140
|
+
})
|
|
141
|
+
if (!response.ok) {
|
|
142
|
+
throw new Error(
|
|
143
|
+
`Failed to refresh Cloudflare OAuth token (${response.status}). Run \`wrangler login\` to re-authenticate.`,
|
|
144
|
+
)
|
|
145
|
+
}
|
|
146
|
+
const data = (await response.json()) as TokenEndpointResponse
|
|
147
|
+
if (!data.access_token || typeof data.expires_in !== 'number') {
|
|
148
|
+
throw new Error('Cloudflare OAuth token endpoint returned an unexpected response. Run `wrangler login` to re-authenticate.')
|
|
149
|
+
}
|
|
150
|
+
return {
|
|
151
|
+
oauthToken: data.access_token,
|
|
152
|
+
// Cloudflare may rotate the refresh token; fall back to the existing one.
|
|
153
|
+
refreshToken: data.refresh_token ?? refreshToken,
|
|
154
|
+
expirationTime: new Date(now() + data.expires_in * 1000).toISOString(),
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function tokenUrlFromEnv(): string {
|
|
159
|
+
if (process.env.WRANGLER_TOKEN_URL) {
|
|
160
|
+
return process.env.WRANGLER_TOKEN_URL
|
|
161
|
+
}
|
|
162
|
+
const domain = process.env.WRANGLER_AUTH_DOMAIN || 'dash.cloudflare.com'
|
|
163
|
+
return `https://${domain}/oauth2/token`
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export interface WranglerTokenProviderOptions {
|
|
167
|
+
configPath?: string
|
|
168
|
+
now?: () => number
|
|
169
|
+
fetch?: typeof fetch
|
|
170
|
+
/** Persist the refreshed token back to default.toml (default true). */
|
|
171
|
+
persist?: boolean
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Returns a token provider backed by wrangler's stored OAuth credentials. It
|
|
176
|
+
* returns the access token while valid, refreshing (and persisting) it once it
|
|
177
|
+
* is within the expiry buffer. The result is cached in memory for the process.
|
|
178
|
+
*/
|
|
179
|
+
export function createWranglerTokenProvider(options: WranglerTokenProviderOptions = {}): () => Promise<string> {
|
|
180
|
+
const configPath = options.configPath ?? getWranglerConfigPath()
|
|
181
|
+
const now = options.now ?? Date.now
|
|
182
|
+
const persist = options.persist ?? true
|
|
183
|
+
let cached: { token: string; expiresAt: number } | null = null
|
|
184
|
+
|
|
185
|
+
return async () => {
|
|
186
|
+
if (cached && cached.expiresAt - EXPIRY_BUFFER_MS > now()) {
|
|
187
|
+
return cached.token
|
|
188
|
+
}
|
|
189
|
+
const creds = readWranglerCredentials(configPath)
|
|
190
|
+
if (!creds) {
|
|
191
|
+
throw new Error(
|
|
192
|
+
`No Cloudflare credentials found. Set CLOUDFLARE_API_TOKEN, or run \`wrangler login\` (looked in ${configPath}).`,
|
|
193
|
+
)
|
|
194
|
+
}
|
|
195
|
+
const expiresAt = Date.parse(creds.expirationTime)
|
|
196
|
+
if (Number.isFinite(expiresAt) && expiresAt - EXPIRY_BUFFER_MS > now()) {
|
|
197
|
+
cached = { token: creds.oauthToken, expiresAt }
|
|
198
|
+
return creds.oauthToken
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const refreshed = await refreshAccessToken(creds.refreshToken, { fetch: options.fetch, now })
|
|
202
|
+
if (persist) {
|
|
203
|
+
try {
|
|
204
|
+
writeWranglerCredentials(configPath, refreshed)
|
|
205
|
+
} catch (error) {
|
|
206
|
+
console.warn(`Warning: refreshed Cloudflare OAuth token but could not persist it to ${configPath}: ${error}`)
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
cached = { token: refreshed.oauthToken, expiresAt: Date.parse(refreshed.expirationTime) }
|
|
210
|
+
return refreshed.oauthToken
|
|
211
|
+
}
|
|
212
|
+
}
|
package/src/client.ts
CHANGED
|
@@ -4,7 +4,7 @@ export class CloudflareClient {
|
|
|
4
4
|
constructor(
|
|
5
5
|
private readonly config: {
|
|
6
6
|
accountId: string
|
|
7
|
-
|
|
7
|
+
getToken: () => Promise<string>
|
|
8
8
|
},
|
|
9
9
|
) {
|
|
10
10
|
this.baseUrl = `https://api.cloudflare.com/client/v4/accounts/${config.accountId}`
|
|
@@ -16,13 +16,11 @@ export class CloudflareClient {
|
|
|
16
16
|
body?: any
|
|
17
17
|
headers?: Record<string, string>
|
|
18
18
|
}): Promise<T> {
|
|
19
|
-
|
|
20
|
-
throw new Error('API token is not set')
|
|
21
|
-
}
|
|
19
|
+
const token = await this.config.getToken()
|
|
22
20
|
const response = await fetch(`${this.baseUrl}${url}`, {
|
|
23
21
|
method,
|
|
24
22
|
headers: {
|
|
25
|
-
Authorization: `Bearer ${
|
|
23
|
+
Authorization: `Bearer ${token}`,
|
|
26
24
|
...(body ? { 'Content-Type': 'application/json' } : {}),
|
|
27
25
|
...headers,
|
|
28
26
|
},
|
package/src/commands/deploy.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import * as fs from 'node:fs/promises'
|
|
2
|
+
import { createWranglerTokenProvider } from '../auth'
|
|
2
3
|
import { CloudflareClient } from '../client'
|
|
3
|
-
import { destroyers } from '../resources'
|
|
4
|
+
import { destroyers, type Worker } from '../resources'
|
|
4
5
|
import { KVStateStorage, type State } from '../state'
|
|
5
6
|
import type { Resource } from '../types'
|
|
6
7
|
import type { Input } from './input'
|
|
7
|
-
import type { ResourceApplier } from './resource-processor'
|
|
8
|
+
import type { ConfigWriter, GeneratedConfig, ResourceApplier } from './resource-processor'
|
|
8
9
|
import { ResourceProcessor } from './resource-processor'
|
|
9
10
|
import { atomic, registerShutdownHandler } from './utils/pm'
|
|
10
11
|
|
|
@@ -12,19 +13,26 @@ export class CloudflareDeployExecutor implements ResourceApplier {
|
|
|
12
13
|
private remaining: Set<string>
|
|
13
14
|
private totalChanged = 0
|
|
14
15
|
|
|
15
|
-
public static async execute({ input }: {
|
|
16
|
+
public static async execute({ input, definition, configWriter }: {
|
|
16
17
|
input: Input
|
|
17
|
-
|
|
18
|
+
definition: Worker | undefined
|
|
19
|
+
configWriter?: ConfigWriter
|
|
20
|
+
}): Promise<GeneratedConfig[]> {
|
|
21
|
+
// An explicit API token wins; otherwise fall back to wrangler's stored
|
|
22
|
+
// OAuth credentials (`wrangler login`).
|
|
23
|
+
const getToken = input.apiToken
|
|
24
|
+
? async () => input.apiToken
|
|
25
|
+
: createWranglerTokenProvider({ persist: input.persistToken })
|
|
18
26
|
const cfClient = new CloudflareClient({
|
|
19
27
|
accountId: input.accountId,
|
|
20
|
-
|
|
28
|
+
getToken,
|
|
21
29
|
})
|
|
22
30
|
|
|
23
31
|
const stateStore = new KVStateStorage(cfClient, input.stateNamespace, input.stateNamespaceId)
|
|
24
32
|
const stateKey = { env: input.env }
|
|
25
33
|
const state = await stateStore.get(stateKey)
|
|
26
34
|
|
|
27
|
-
const executor = new CloudflareDeployExecutor(input, state, cfClient)
|
|
35
|
+
const executor = new CloudflareDeployExecutor(input, state, cfClient, configWriter)
|
|
28
36
|
|
|
29
37
|
const unregisterShutdown = registerShutdownHandler(async () => {
|
|
30
38
|
if (input.dryRun) {
|
|
@@ -33,8 +41,9 @@ export class CloudflareDeployExecutor implements ResourceApplier {
|
|
|
33
41
|
await stateStore.set(stateKey, state)
|
|
34
42
|
})
|
|
35
43
|
|
|
44
|
+
let generated: GeneratedConfig[]
|
|
36
45
|
try {
|
|
37
|
-
await executor.run()
|
|
46
|
+
generated = await executor.run(definition)
|
|
38
47
|
} finally {
|
|
39
48
|
unregisterShutdown()
|
|
40
49
|
await atomic(async () => {
|
|
@@ -48,19 +57,22 @@ export class CloudflareDeployExecutor implements ResourceApplier {
|
|
|
48
57
|
if (input.outStatePath) {
|
|
49
58
|
await fs.writeFile(input.outStatePath, JSON.stringify(state, null, '\t'))
|
|
50
59
|
}
|
|
60
|
+
|
|
61
|
+
return generated
|
|
51
62
|
}
|
|
52
63
|
|
|
53
64
|
private constructor(
|
|
54
65
|
private readonly input: Input,
|
|
55
66
|
private readonly state: State,
|
|
56
67
|
private readonly client: CloudflareClient,
|
|
68
|
+
private readonly configWriter?: ConfigWriter,
|
|
57
69
|
) {
|
|
58
70
|
this.remaining = new Set(Object.keys(state.resources || {}))
|
|
59
71
|
}
|
|
60
72
|
|
|
61
|
-
private async run() {
|
|
62
|
-
const resourceProcessor = new ResourceProcessor(this)
|
|
63
|
-
await resourceProcessor.
|
|
73
|
+
private async run(definition: Worker | undefined): Promise<GeneratedConfig[]> {
|
|
74
|
+
const resourceProcessor = new ResourceProcessor(this, this.configWriter)
|
|
75
|
+
const generated = await resourceProcessor.process({ definition, env: this.input.env })
|
|
64
76
|
|
|
65
77
|
this.log(`Changed ${this.totalChanged} resources`)
|
|
66
78
|
|
|
@@ -89,6 +101,8 @@ export class CloudflareDeployExecutor implements ResourceApplier {
|
|
|
89
101
|
this.log(`Destroyed ${resource}:${id}`)
|
|
90
102
|
}
|
|
91
103
|
}
|
|
104
|
+
|
|
105
|
+
return generated
|
|
92
106
|
}
|
|
93
107
|
|
|
94
108
|
private log(message: string) {
|
package/src/commands/input.ts
CHANGED
|
@@ -15,6 +15,7 @@ export const input = (() => {
|
|
|
15
15
|
destroy: { type: 'boolean' },
|
|
16
16
|
validate: { type: 'boolean' },
|
|
17
17
|
'out-state': { type: 'string' },
|
|
18
|
+
'no-persist-token': { type: 'boolean' },
|
|
18
19
|
},
|
|
19
20
|
})
|
|
20
21
|
|
|
@@ -36,6 +37,9 @@ export const input = (() => {
|
|
|
36
37
|
destroy: values.destroy ?? false,
|
|
37
38
|
validate: values.validate ?? false,
|
|
38
39
|
outStatePath: values['out-state'],
|
|
40
|
+
// When using OAuth, persist the refreshed token back to wrangler's config
|
|
41
|
+
// unless the user opts out (e.g. read-only credentials dir).
|
|
42
|
+
persistToken: !(values['no-persist-token'] ?? false),
|
|
39
43
|
}
|
|
40
44
|
})()
|
|
41
45
|
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import * as path from 'node:path'
|
|
2
|
+
import type { Worker } from '../resources'
|
|
3
|
+
import type { DefineFn } from '../types'
|
|
4
|
+
|
|
5
|
+
export const loadDefinition = async ({ main, env }: {
|
|
6
|
+
main: string
|
|
7
|
+
env: string
|
|
8
|
+
}): Promise<Worker | undefined> => {
|
|
9
|
+
const defineFn = (await import(path.resolve(main))).default as DefineFn
|
|
10
|
+
return defineFn({ env })
|
|
11
|
+
}
|
|
@@ -18,23 +18,36 @@ export class ResourceProcessor {
|
|
|
18
18
|
public async run({ main, env }: {
|
|
19
19
|
main: string
|
|
20
20
|
env: string
|
|
21
|
-
}) {
|
|
21
|
+
}): Promise<GeneratedConfig[]> {
|
|
22
22
|
const defineFn = (await import(path.resolve(main))).default as DefineFn
|
|
23
23
|
const definition = defineFn({ env })
|
|
24
|
+
return this.process({ definition, env })
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
public async process({ definition, env }: {
|
|
28
|
+
definition: Worker | undefined
|
|
29
|
+
env: string
|
|
30
|
+
}): Promise<GeneratedConfig[]> {
|
|
31
|
+
const generated: GeneratedConfig[] = []
|
|
24
32
|
|
|
25
33
|
if (definition) {
|
|
26
34
|
this.workers.push(definition)
|
|
27
35
|
}
|
|
28
36
|
|
|
29
37
|
while (this.workers.length) {
|
|
30
|
-
await this.processWorker(env)
|
|
38
|
+
const result = await this.processWorker(env)
|
|
39
|
+
if (result) {
|
|
40
|
+
generated.push(result)
|
|
41
|
+
}
|
|
31
42
|
}
|
|
43
|
+
|
|
44
|
+
return generated
|
|
32
45
|
}
|
|
33
46
|
|
|
34
|
-
private async processWorker(env: string): Promise<
|
|
47
|
+
private async processWorker(env: string): Promise<GeneratedConfig | undefined> {
|
|
35
48
|
const worker = this.workers.shift()
|
|
36
49
|
if (!worker) {
|
|
37
|
-
return
|
|
50
|
+
return undefined
|
|
38
51
|
}
|
|
39
52
|
const configPath = path.join(worker.options.dir, 'wrangler.jsonc')
|
|
40
53
|
const existingConfig = jsoncParser.parse((await tryReadFile(configPath)) || '{}') as Config
|
|
@@ -87,9 +100,17 @@ export class ResourceProcessor {
|
|
|
87
100
|
|
|
88
101
|
const content = `/**\n * File is auto generated DO NOT EDIT\n */\n${JSON.stringify(config, null, '\t')}\n`
|
|
89
102
|
await this.configWriter(configPath, content)
|
|
103
|
+
|
|
104
|
+
return { path: configPath, config, content }
|
|
90
105
|
}
|
|
91
106
|
}
|
|
92
107
|
|
|
108
|
+
export interface GeneratedConfig {
|
|
109
|
+
path: string
|
|
110
|
+
config: Config
|
|
111
|
+
content: string
|
|
112
|
+
}
|
|
113
|
+
|
|
93
114
|
export type ConfigWriter = (path: string, content: string) => Promise<void>
|
|
94
115
|
|
|
95
116
|
const defaultConfigWriter: ConfigWriter = (path, content) => fs.writeFile(path, content)
|
package/src/commands/run.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
+
import { hasWranglerCredentials } from '../auth'
|
|
2
3
|
import { CloudflareConfigureExecutor } from './configure'
|
|
3
4
|
import { CloudflareDeployExecutor } from './deploy'
|
|
4
5
|
import { input } from './input'
|
|
6
|
+
import { loadDefinition } from './load-definition'
|
|
5
7
|
import { registerSignalHandler } from './utils/pm'
|
|
6
8
|
import { CloudflareValidateExecutor } from './validate'
|
|
7
9
|
|
|
@@ -14,11 +16,12 @@ if (input.validate) {
|
|
|
14
16
|
console.error('Missing --account-id or CLOUDFLARE_ACCOUNT_ID environment variable')
|
|
15
17
|
process.exit(1)
|
|
16
18
|
}
|
|
17
|
-
if (!input.apiToken) {
|
|
18
|
-
console.error('Missing --api-token
|
|
19
|
+
if (!input.apiToken && !hasWranglerCredentials()) {
|
|
20
|
+
console.error('Missing credentials: set --api-token / CLOUDFLARE_API_TOKEN, or run `wrangler login` for OAuth')
|
|
19
21
|
process.exit(1)
|
|
20
22
|
}
|
|
21
|
-
await
|
|
23
|
+
const definition = await loadDefinition({ main: input.main, env: input.env })
|
|
24
|
+
await CloudflareDeployExecutor.execute({ input, definition })
|
|
22
25
|
} else {
|
|
23
26
|
await CloudflareConfigureExecutor.execute({ input })
|
|
24
27
|
}
|
package/src/index.ts
CHANGED
|
@@ -2,6 +2,10 @@ import type { DefineFn } from './types'
|
|
|
2
2
|
|
|
3
3
|
export * from './resources'
|
|
4
4
|
|
|
5
|
+
export { deploy } from './api'
|
|
6
|
+
export type { Definition, DeployOptions, DeployResult } from './api'
|
|
7
|
+
export type { GeneratedConfig } from './commands/resource-processor'
|
|
8
|
+
|
|
5
9
|
export const define = (cb: DefineFn) => {
|
|
6
10
|
return cb
|
|
7
11
|
}
|