oblaka-iac 0.0.4 → 0.0.7

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oblaka-iac",
3
- "version": "0.0.4",
3
+ "version": "0.0.7",
4
4
  "main": "./src/index.ts",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -20,7 +20,8 @@
20
20
  "format:check": "dprint check",
21
21
  "lint": "biome check ./src",
22
22
  "lint:fix": "biome check --write ./src",
23
- "typecheck": "tsc --noEmit"
23
+ "typecheck": "tsc --noEmit",
24
+ "test": "bun test"
24
25
  },
25
26
  "devDependencies": {
26
27
  "@biomejs/biome": "^2.4.6",
@@ -20,7 +20,7 @@ export class CloudflareDeployExecutor implements ResourceApplier {
20
20
  apiToken: input.apiToken,
21
21
  })
22
22
 
23
- const stateStore = new KVStateStorage(cfClient, input.stateNamespace)
23
+ const stateStore = new KVStateStorage(cfClient, input.stateNamespace, input.stateNamespaceId)
24
24
  const stateKey = { env: input.env }
25
25
  const state = await stateStore.get(stateKey)
26
26
 
@@ -1,25 +1,41 @@
1
- import { parseArgs } from './utils/args'
1
+ import { parseArgs } from 'node:util'
2
2
 
3
- const requireString = (value: string | boolean | undefined, name: string): string => {
4
- if (typeof value === 'string') {
5
- return value
3
+ export const input = (() => {
4
+ const { values, positionals } = parseArgs({
5
+ args: process.argv.slice(2),
6
+ allowPositionals: true,
7
+ options: {
8
+ env: { type: 'string' },
9
+ 'state-namespace': { type: 'string' },
10
+ 'state-namespace-id': { type: 'string' },
11
+ 'account-id': { type: 'string' },
12
+ 'api-token': { type: 'string' },
13
+ 'dry-run': { type: 'boolean' },
14
+ remote: { type: 'boolean' },
15
+ destroy: { type: 'boolean' },
16
+ validate: { type: 'boolean' },
17
+ 'out-state': { type: 'string' },
18
+ },
19
+ })
20
+
21
+ const main = positionals[0]
22
+ if (!main) {
23
+ console.error('Missing config entrypoint argument')
24
+ process.exit(1)
6
25
  }
7
- throw new Error(`Missing required string argument: ${name}`)
8
- }
9
26
 
10
- export const input = (() => {
11
- const { named, positional } = parseArgs(process.argv.slice(2))
12
27
  return {
13
- main: requireString(positional[0], 'config entrypoint'),
14
- env: requireString(named.env || process.env.CLOUDFLARE_ENV || 'local', 'environment'),
15
- stateNamespace: requireString(named['state-namespace'] || 'cf-state', 'state namespace'),
16
- configPath: requireString(named.config || 'wrangler.jsonc', 'config path'),
17
- accountId: requireString(named['account-id'] || process.env.CLOUDFLARE_ACCOUNT_ID || '', 'account id'),
18
- apiToken: requireString(named['api-token'] || process.env.CLOUDFLARE_API_TOKEN || '', 'api token'),
19
- dryRun: !!named['dry-run'],
20
- remote: !!named.remote,
21
- destroy: !!named.destroy,
22
- outStatePath: named['out-state'] === true ? 'out-state.json' : named['out-state'],
28
+ main,
29
+ env: values.env || process.env.CLOUDFLARE_ENV || 'local',
30
+ stateNamespace: values['state-namespace'] || 'cf-state',
31
+ stateNamespaceId: values['state-namespace-id'],
32
+ accountId: values['account-id'] || process.env.CLOUDFLARE_ACCOUNT_ID || '',
33
+ apiToken: values['api-token'] || process.env.CLOUDFLARE_API_TOKEN || '',
34
+ dryRun: values['dry-run'] ?? false,
35
+ remote: values.remote ?? false,
36
+ destroy: values.destroy ?? false,
37
+ validate: values.validate ?? false,
38
+ outStatePath: values['out-state'],
23
39
  }
24
40
  })()
25
41
 
@@ -3,6 +3,7 @@ import * as fs from 'node:fs/promises'
3
3
  import * as path from 'node:path'
4
4
  import { Worker } from '../resources'
5
5
  import type { Config, DefineFn, Resource } from '../types'
6
+ import { getNextMigrationTag } from '../utils/migrations'
6
7
  import { tryReadFile } from './utils/fs'
7
8
 
8
9
  export class ResourceProcessor {
@@ -10,6 +11,7 @@ export class ResourceProcessor {
10
11
 
11
12
  constructor(
12
13
  private readonly resourceHandler: ResourceApplier,
14
+ private readonly configWriter: ConfigWriter = defaultConfigWriter,
13
15
  ) {
14
16
  }
15
17
 
@@ -36,7 +38,7 @@ export class ResourceProcessor {
36
38
  }
37
39
  const configPath = path.join(worker.options.dir, 'wrangler.jsonc')
38
40
  const existingConfig = jsoncParser.parse((await tryReadFile(configPath)) || '{}') as Config
39
- const { bindings, dir, ...workerConfig } = worker?.options ?? {}
41
+ const { bindings, dir, deleteDurableObjectsOnRemoval, ...workerConfig } = worker.options
40
42
 
41
43
  let config: Config = {
42
44
  ...workerConfig,
@@ -54,10 +56,44 @@ export class ResourceProcessor {
54
56
  config = binding.configureBinding({ config, binding: bindingName, state, env })
55
57
  }
56
58
 
57
- await fs.writeFile(configPath, `/**\n * File is auto generated DO NOT EDIT\n */\n${JSON.stringify(config, null, '\t')}\n`)
59
+ if (deleteDurableObjectsOnRemoval !== false) {
60
+ const oldClasses = new Set((existingConfig.durable_objects?.bindings ?? []).map((b: { class_name: string }) => b.class_name))
61
+ const newClasses = new Set((config.durable_objects?.bindings ?? []).map((b: { class_name: string }) => b.class_name))
62
+ const deletedClasses = [...oldClasses].filter(c => !newClasses.has(c))
63
+
64
+ if (deletedClasses.length > 0) {
65
+ const deletedClassesSet = new Set(deletedClasses)
66
+ config = {
67
+ ...config,
68
+ migrations: [
69
+ ...(config.migrations ?? [])
70
+ .flatMap(m => {
71
+ if (!m.new_sqlite_classes) return [m]
72
+ const filtered = m.new_sqlite_classes.filter((c: string) => !deletedClassesSet.has(c))
73
+ if (filtered.length === 0) {
74
+ const { new_sqlite_classes: _, ...rest } = m
75
+ return Object.keys(rest).length > 1 ? [rest as typeof m] : []
76
+ }
77
+ return [{ ...m, new_sqlite_classes: filtered }]
78
+ }),
79
+ {
80
+ tag: getNextMigrationTag(config),
81
+ deleted_classes: deletedClasses,
82
+ },
83
+ ],
84
+ }
85
+ }
86
+ }
87
+
88
+ const content = `/**\n * File is auto generated DO NOT EDIT\n */\n${JSON.stringify(config, null, '\t')}\n`
89
+ await this.configWriter(configPath, content)
58
90
  }
59
91
  }
60
92
 
93
+ export type ConfigWriter = (path: string, content: string) => Promise<void>
94
+
95
+ const defaultConfigWriter: ConfigWriter = (path, content) => fs.writeFile(path, content)
96
+
61
97
  export interface ResourceApplier {
62
98
  applyResource<T>(resource: Resource<T>): Promise<T | undefined>
63
99
  }
@@ -3,10 +3,21 @@ import { CloudflareConfigureExecutor } from './configure'
3
3
  import { CloudflareDeployExecutor } from './deploy'
4
4
  import { input } from './input'
5
5
  import { registerSignalHandler } from './utils/pm'
6
+ import { CloudflareValidateExecutor } from './validate'
6
7
 
7
8
  registerSignalHandler()
8
9
 
9
- if (input.remote) {
10
+ if (input.validate) {
11
+ await CloudflareValidateExecutor.execute({ input })
12
+ } else if (input.remote) {
13
+ if (!input.accountId) {
14
+ console.error('Missing --account-id or CLOUDFLARE_ACCOUNT_ID environment variable')
15
+ process.exit(1)
16
+ }
17
+ if (!input.apiToken) {
18
+ console.error('Missing --api-token or CLOUDFLARE_API_TOKEN environment variable')
19
+ process.exit(1)
20
+ }
10
21
  await CloudflareDeployExecutor.execute({ input })
11
22
  } else {
12
23
  await CloudflareConfigureExecutor.execute({ input })
@@ -0,0 +1,44 @@
1
+ import type { Input } from './input'
2
+ import { ResourceProcessor } from './resource-processor'
3
+ import { tryReadFile } from './utils/fs'
4
+
5
+ export class CloudflareValidateExecutor {
6
+ public static async execute({ input }: {
7
+ input: Input
8
+ }) {
9
+ const executor = new CloudflareValidateExecutor(input)
10
+ await executor.run()
11
+ }
12
+
13
+ private constructor(
14
+ private readonly input: Input,
15
+ ) {
16
+ }
17
+
18
+ private async run() {
19
+ const mismatches: string[] = []
20
+
21
+ const resourceProcessor = new ResourceProcessor(
22
+ { applyResource: () => Promise.resolve(undefined) },
23
+ async (configPath, content) => {
24
+ const existing = await tryReadFile(configPath)
25
+ if (existing === undefined) {
26
+ mismatches.push(`${configPath}: file does not exist, run the generator first`)
27
+ } else if (existing !== content) {
28
+ mismatches.push(`${configPath}: content is outdated, run the generator to update`)
29
+ }
30
+ },
31
+ )
32
+ await resourceProcessor.run({ main: this.input.main, env: this.input.env })
33
+
34
+ if (mismatches.length > 0) {
35
+ console.error('Validation failed:')
36
+ for (const m of mismatches) {
37
+ console.error(` - ${m}`)
38
+ }
39
+ process.exit(1)
40
+ }
41
+
42
+ console.log('Validation passed: all generated configs are up to date.')
43
+ }
44
+ }
@@ -40,7 +40,9 @@ export class Container implements BindableResource<ContainerState> {
40
40
  }
41
41
 
42
42
  configureBinding(args: { config: Config; binding: string; state?: ContainerState; env: string }): Config {
43
- const hasMigration = args.config?.migrations?.find(it => it.new_sqlite_classes?.includes(this.options.className))
43
+ const hasMigration = args.config?.migrations?.find((it: { new_sqlite_classes?: string[] }) =>
44
+ it.new_sqlite_classes?.includes(this.options.className)
45
+ )
44
46
 
45
47
  return {
46
48
  ...args.config,
@@ -24,7 +24,9 @@ export class DurableObject implements BindableResource<DurableObjectState> {
24
24
  }
25
25
 
26
26
  configureBinding(args: { config: Config; state?: DurableObjectState; binding: string; env: string }): Config {
27
- const hasMigration = args.config?.migrations?.find(it => it.new_sqlite_classes?.includes(this.options.className))
27
+ const hasMigration = args.config?.migrations?.find((it: { new_sqlite_classes?: string[] }) =>
28
+ it.new_sqlite_classes?.includes(this.options.className)
29
+ )
28
30
 
29
31
  return {
30
32
  ...args.config,
@@ -12,6 +12,7 @@ export class Worker implements BindableResource<WorkerState> {
12
12
  name: string
13
13
  compatibility_flags: CompatibilityFlags[]
14
14
  bindings: Record<string, AnyBindable>
15
+ deleteDurableObjectsOnRemoval?: boolean
15
16
  }
16
17
  & Partial<
17
18
  Pick<
package/src/state.ts CHANGED
@@ -20,18 +20,20 @@ export class KVStateStorage implements StateStorage {
20
20
  constructor(
21
21
  private readonly cfClient: CloudflareClient,
22
22
  private readonly namespace: string,
23
+ namespaceId?: string,
23
24
  ) {
25
+ this.id = namespaceId
24
26
  }
25
27
 
26
28
  private async resolveKvId(): Promise<string> {
27
29
  if (this.id) {
28
30
  return this.id
29
31
  }
30
- const id = await this.cfClient.fetch<{ title: string; id: string }[]>({
31
- url: `/storage/kv/namespaces`,
32
+ const namespaces = await this.cfClient.fetch<{ title: string; id: string }[]>({
33
+ url: `/storage/kv/namespaces?per_page=1000`,
32
34
  method: 'GET',
33
35
  })
34
- const existing = id.find(i => i.title === this.namespace)
36
+ const existing = namespaces.find(i => i.title === this.namespace)
35
37
  if (existing) {
36
38
  this.id = existing.id
37
39
  return existing.id
@@ -1,20 +0,0 @@
1
- export const parseArgs = (args: string[]): { named: { [key: string]: string | true }; positional: string[] } => {
2
- const named: { [key: string]: string | true } = {}
3
- const positional: string[] = []
4
- for (let i = 0; i < args.length; i++) {
5
- const arg = args[i]
6
- if (arg.startsWith('--')) {
7
- const key = arg.slice(2)
8
- const value = args[i + 1]
9
- if (value && !value.startsWith('--')) {
10
- named[key] = value
11
- i++
12
- } else {
13
- named[key] = true
14
- }
15
- } else {
16
- positional.push(arg)
17
- }
18
- }
19
- return { named, positional }
20
- }