@rexezuge/tooling 1.3.0 → 1.4.0

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.
Files changed (128) hide show
  1. package/dist/eslint-boundaries.d.ts +12 -4
  2. package/dist/eslint-boundaries.d.ts.map +1 -1
  3. package/dist/eslint-boundaries.js +1 -224
  4. package/dist/eslint-boundaries.js.map +7 -1
  5. package/dist/eslint-rules.js +1 -273
  6. package/dist/eslint-rules.js.map +7 -1
  7. package/dist/eslint.js +1 -194
  8. package/dist/eslint.js.map +7 -1
  9. package/dist/functions/pages-proxy.d.ts.map +1 -1
  10. package/dist/functions/pages-proxy.js +1 -131
  11. package/dist/functions/pages-proxy.js.map +7 -1
  12. package/dist/index.js +1 -31
  13. package/dist/index.js.map +7 -1
  14. package/dist/scripts/backup/d1-target.d.ts +15 -5
  15. package/dist/scripts/backup/d1-target.d.ts.map +1 -1
  16. package/dist/scripts/backup/d1-target.js +1 -31
  17. package/dist/scripts/backup/d1-target.js.map +7 -1
  18. package/dist/scripts/backup/destination-config.d.ts +24 -8
  19. package/dist/scripts/backup/destination-config.d.ts.map +1 -1
  20. package/dist/scripts/backup/destination-config.js +1 -57
  21. package/dist/scripts/backup/destination-config.js.map +7 -1
  22. package/dist/scripts/backup/encrypt-backup.js +2 -97
  23. package/dist/scripts/backup/encrypt-backup.js.map +7 -1
  24. package/dist/scripts/backup/naming.d.ts +3 -1
  25. package/dist/scripts/backup/naming.d.ts.map +1 -1
  26. package/dist/scripts/backup/naming.js +1 -58
  27. package/dist/scripts/backup/naming.js.map +7 -1
  28. package/dist/scripts/check-god-files.d.ts +40 -14
  29. package/dist/scripts/check-god-files.d.ts.map +1 -1
  30. package/dist/scripts/check-god-files.js +2 -271
  31. package/dist/scripts/check-god-files.js.map +7 -1
  32. package/dist/scripts/ensure-spa-shell-stub.js +1 -29
  33. package/dist/scripts/ensure-spa-shell-stub.js.map +7 -1
  34. package/dist/scripts/init-secrets.d.ts +0 -16
  35. package/dist/scripts/init-secrets.d.ts.map +1 -1
  36. package/dist/scripts/init-secrets.js +2 -239
  37. package/dist/scripts/init-secrets.js.map +7 -1
  38. package/dist/scripts/lib/cli-args.d.ts.map +1 -1
  39. package/dist/scripts/lib/cli-args.js +1 -116
  40. package/dist/scripts/lib/cli-args.js.map +7 -1
  41. package/dist/scripts/lib/github-actions.js +3 -38
  42. package/dist/scripts/lib/github-actions.js.map +7 -1
  43. package/dist/scripts/lib/wrangler-table.d.ts.map +1 -1
  44. package/dist/scripts/lib/wrangler-table.js +2 -99
  45. package/dist/scripts/lib/wrangler-table.js.map +7 -1
  46. package/dist/scripts/migrations-lock.js +1 -44
  47. package/dist/scripts/migrations-lock.js.map +7 -1
  48. package/dist/scripts/prepare-wrangler-config.js +1 -49
  49. package/dist/scripts/prepare-wrangler-config.js.map +7 -1
  50. package/dist/scripts/spa-shell.d.ts +12 -4
  51. package/dist/scripts/spa-shell.d.ts.map +1 -1
  52. package/dist/scripts/spa-shell.js +3 -160
  53. package/dist/scripts/spa-shell.js.map +7 -1
  54. package/dist/scripts/validate-locales.d.ts +13 -5
  55. package/dist/scripts/validate-locales.d.ts.map +1 -1
  56. package/dist/scripts/validate-locales.js +4 -350
  57. package/dist/scripts/validate-locales.js.map +7 -1
  58. package/dist/scripts/verify-migrations.d.ts +27 -9
  59. package/dist/scripts/verify-migrations.d.ts.map +1 -1
  60. package/dist/scripts/verify-migrations.js +2 -312
  61. package/dist/scripts/verify-migrations.js.map +7 -1
  62. package/dist/scripts/verify-spa-shell.js +1 -52
  63. package/dist/scripts/verify-spa-shell.js.map +7 -1
  64. package/dist/scripts/wrangler-config/cli.js +3 -51
  65. package/dist/scripts/wrangler-config/cli.js.map +7 -1
  66. package/dist/scripts/wrangler-config/patches.d.ts +9 -3
  67. package/dist/scripts/wrangler-config/patches.d.ts.map +1 -1
  68. package/dist/scripts/wrangler-config/patches.js +4 -141
  69. package/dist/scripts/wrangler-config/patches.js.map +7 -1
  70. package/dist/scripts/wrangler-config/resources.d.ts +18 -6
  71. package/dist/scripts/wrangler-config/resources.d.ts.map +1 -1
  72. package/dist/scripts/wrangler-config/resources.js +1 -290
  73. package/dist/scripts/wrangler-config/resources.js.map +7 -1
  74. package/dist/scripts/wrangler-config/types.d.ts +24 -8
  75. package/dist/scripts/wrangler-config/types.d.ts.map +1 -1
  76. package/dist/scripts/wrangler-config/types.js +1 -49
  77. package/dist/scripts/wrangler-config/types.js.map +7 -1
  78. package/dist/test/integration-migrations.d.ts +29 -12
  79. package/dist/test/integration-migrations.d.ts.map +1 -1
  80. package/dist/test/integration-migrations.js +2 -171
  81. package/dist/test/integration-migrations.js.map +7 -1
  82. package/dist/test/mocks/cloudflare-workers.js +1 -90
  83. package/dist/test/mocks/cloudflare-workers.js.map +7 -1
  84. package/dist/vite.d.ts +5 -3
  85. package/dist/vite.d.ts.map +1 -1
  86. package/dist/vite.js +3 -125
  87. package/dist/vite.js.map +7 -1
  88. package/dist/vitest-aliases.d.ts.map +1 -1
  89. package/dist/vitest-aliases.js +1 -81
  90. package/dist/vitest-aliases.js.map +7 -1
  91. package/dist/vitest-integration.js +1 -64
  92. package/dist/vitest-integration.js.map +7 -1
  93. package/dist/vitest-repo.js +1 -146
  94. package/dist/vitest-repo.js.map +7 -1
  95. package/dist/vitest-web.js +1 -109
  96. package/dist/vitest-web.js.map +7 -1
  97. package/dist/vitest.js +1 -133
  98. package/dist/vitest.js.map +7 -1
  99. package/package.json +3 -3
  100. package/src/eslint-boundaries.ts +13 -5
  101. package/src/eslint.test.ts +18 -8
  102. package/src/functions/pages-proxy.test.ts +1 -1
  103. package/src/functions/pages-proxy.ts +4 -2
  104. package/src/scripts/backup/backup-rules.test.ts +1 -1
  105. package/src/scripts/backup/d1-target.ts +15 -5
  106. package/src/scripts/backup/destination-config.ts +27 -9
  107. package/src/scripts/backup/encrypt-backup.ts +10 -8
  108. package/src/scripts/backup/naming.ts +3 -1
  109. package/src/scripts/check-god-files.test.ts +18 -18
  110. package/src/scripts/check-god-files.ts +60 -31
  111. package/src/scripts/init-secrets.ts +17 -7
  112. package/src/scripts/lib/cli-args.ts +6 -3
  113. package/src/scripts/lib/wrangler-table.ts +5 -3
  114. package/src/scripts/migrations-lock.ts +1 -1
  115. package/src/scripts/spa-shell.test.ts +17 -17
  116. package/src/scripts/spa-shell.ts +26 -14
  117. package/src/scripts/validate-locales.test.ts +17 -17
  118. package/src/scripts/validate-locales.ts +43 -25
  119. package/src/scripts/verify-migrations.test.ts +7 -7
  120. package/src/scripts/verify-migrations.ts +47 -24
  121. package/src/scripts/wrangler-config/patches.ts +12 -4
  122. package/src/scripts/wrangler-config/resources.ts +30 -14
  123. package/src/scripts/wrangler-config/types.ts +24 -8
  124. package/src/test/integration-migrations.test.ts +6 -6
  125. package/src/test/integration-migrations.ts +33 -14
  126. package/src/vite.test.ts +24 -13
  127. package/src/vite.ts +5 -5
  128. package/src/vitest-aliases.ts +1 -3
@@ -1 +1,7 @@
1
- {"version":3,"file":"resources.js","sourceRoot":"","sources":["../../../src/scripts/wrangler-config/resources.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAGH,OAAO,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AACrC,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAEL,cAAc,EACd,0BAA0B,EAC1B,yBAAyB,EACzB,YAAY,EACZ,mBAAmB,EACnB,oBAAoB,GAKrB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AACvD,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAQzE,0EAA0E;AAC1E,MAAM,UAAU,OAAO,CAAC,QAAoB;IAC1C,OAAO,QAAQ,CAAC,IAAI,IAAI,QAAQ,CAAC,WAAW,IAAI,QAAQ,CAAC,EAAE,CAAC;AAC9D,CAAC;AAED,MAAM,UAAU,eA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I,YAAY,CAAC,MAAM,CAAC,EAAE,CAAC;QAC7C,IAAI,WAAW,CAAC,SAAS,CAAC,EAAE,CAAC;YAC3B,OAAO,CAAC,IAAI,CAAC,SAAS,SAAS,EAAE,CAAC,CAAC;QACrC,CAAC;IACH,CAAC;IAED,gFAAgF;IAChF,8EAA8E;IAC9E,uBAAuB;IACvB,KAAK,MAAM,OAAO,IAAI,MAAM,CAAC,SAAS,IAAI,EAAE,EAAE,CAAC;QAC7C,oBAAoB,CAAC,OAAO,CAAC,UAAU,EAAE,oBAAoB,CAAC,CAAC;IACjE,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["/**\n * Creating the resources `wrangler.jsonc` names, and writing their real ids over\n * the placeholders.\n *\n * Provenance: ported from Edge-Sonic's `scripts/lib/wrangler-config/resources.ts`.\n *\n * The placeholder rule: a template carries an all-zero id meaning \"resolve me\",\n * and a config carrying one cannot be deployed. So provisioning walks the config,\n * creates what is missing, and patches the id in place. A placeholder with nothing\n * to create it *under* — a KV id with no binding, a D1 id with no name — is\n * refused rather than skipped, because a silently skipped placeholder is a deploy\n * that fails later with no link back to the reason.\n */\n\nimport { writeFileSync } from 'node:fs';\nimport { parse } from 'jsonc-parser';\nimport { parseWranglerTableRows } from '../lib/wrangler-table.ts';\nimport {\n CONFIG_PATH,\n DEFAULT_HEX_ID,\n DEFAULT_KV_NAMESPACE_NAMES,\n DEFAULT_SECRET_STORE_NAME,\n DEFAULT_UUID,\n DEFAULT_WORKER_NAME,\n VECTORIZE_DIMENSIONS,\n type D1Database,\n type KVNamespace,\n type SecretStore,\n type WranglerConfig,\n} from './types.ts';\nimport { parseJsonArray, runWrangler } from './cli.ts';\nimport { readConfig, writeConfig, writeConfigValue } from './patches.ts';\n\n/** What `ensure*` did, so a caller can act on the difference. */\nexport interface Provisioned {\n id: string;\n created: boolean;\n}\n\n/** The id a D1 database is reported under, whichever key the CLI used. */\nexport function getD1Id(database: D1Database): string | undefined {\n return database.uuid ?? database.database_id ?? database.id;\n}\n\nexport function listD1Databases(): D1Database[] {\n return parseJsonArray<D1Database>(runWrangler(['d1', 'list', '--json']), 'wrangler d1 list --json');\n}\n\n/**\n * The D1 database `binding` names, created when it does not exist.\n *\n * Whether it was created is reported, not inferred: a database created moments ago\n * holds no user data, so a backup workflow must refuse to upload its empty dump.\n * The caller cannot re-derive that from the config, because this very function\n * patches the placeholder away before the reader ever runs.\n */\nexport function ensureD1Database(databaseName: string): Provisioned {\n let database = listD1Databases().find((candidate) => candidate.name === databaseName);\n let created = false;\n if (database === undefined) {\n console.log(`Creating D1 database: ${databaseName}`);\n runWrangler(['d1', 'create', databaseName]);\n database = listD1Databases().find((candidate) => candidate.name === databaseName);\n created = true;\n }\n const databaseId = database === undefined ? undefined : getD1Id(database);\n if (databaseId === undefined || databaseId === '') {\n throw new Error(`Unable to discover D1 database ID for ${databaseName}.`);\n }\n return { id: databaseId, created };\n}\n\nexport function listKVNamespaces(): KVNamespace[] {\n return parseJsonArray<KVNamespace>(runWrangler(['kv', 'namespace', 'list']), 'wrangler kv namespace list');\n}\n\n/** The namespace name a binding's namespace is created under. */\nexport function getKVNamespaceName(config: WranglerConfig, binding: string): string {\n return DEFAULT_KV_NAMESPACE_NAMES[binding] ?? `${config.name ?? DEFAULT_WORKER_NAME}-${binding.toLowerCase()}`;\n}\n\nexport function ensureKVNamespace(config: WranglerConfig, binding: string): Provisioned {\n const namespaceName = getKVNamespaceName(config, binding);\n const candidateNames = new Set([namespaceName, `${config.name ?? DEFAULT_WORKER_NAME}-${binding}`, binding]);\n let namespace = listKVNamespaces().find((candidate) => {\n const candidateName = candidate.title ?? candidate.name;\n return candidate.id !== undefined && candidateName !== undefined && candidateNames.has(candidateName);\n });\n let created = false;\n if (namespace === undefined) {\n console.log(`Creating KV namespace: ${namespaceName}`);\n runWrangler(['kv', 'namespace', 'create', namespaceName]);\n namespace = listKVNamespaces().find((candidate) => candidate.id !== undefined && (candidate.title ?? candidate.name) === namespaceName);\n created = true;\n }\n if (namespace?.id === undefined) {\n throw new Error(`Unable to discover KV namespace ID for ${namespaceName}.`);\n }\n return { id: namespace.id, created };\n}\n\n/** The bindings a deployment always needs, whether or not a custom config lists them. */\nexport function getRequiredKvBindings(): string[] {\n return Object.keys(DEFAULT_KV_NAMESPACE_NAMES);\n}\n\n/**\n * Add the always-needed KV bindings a hand-written config left out.\n *\n * A config supplied through `WRANGLER_JSONC` is edited by hand and drifts; without\n * this the worker starts with an unbound `CACHE` and fails on the first read.\n */\nexport function ensureRequiredKvBindings(content: string, config: WranglerConfig): string {\n const existing = new Set((config.kv_namespaces ?? []).map((namespace) => namespace.binding).filter((binding) => binding !== undefined));\n const missing = getRequiredKvBindings().filter((binding) => !existing.has(binding));\n if (missing.length === 0) {\n return content;\n }\n const next = [...(config.kv_namespaces ?? [])];\n for (const binding of missing) {\n console.log(`Adding missing KV namespace binding: ${binding}`);\n next.push({ binding, id: DEFAULT_HEX_ID });\n }\n return writeConfigValue(content, ['kv_namespaces'], next);\n}\n\n/** The stores in a `secrets-store store list` table. */\nexport function parseSecretStoresTable(output: string): SecretStore[] {\n const stores: SecretStore[] = [];\n // Through the shared table parser rather than a second inline split: `wrangler`\n // renders through `cli-table3`, whose cells are separated by U+2502 and are *not*\n // space-aligned, so a parser written for aligned output silently matches nothing\n // — which reads as \"the store does not exist\" and makes provisioning create a\n // duplicate.\n for (const row of parseWranglerTableRows(output)) {\n const name = row[0];\n const id = row[1];\n // Store ids are 32 hex characters; a row without one is a header, a border, or\n // an unrelated column, and is skipped rather than stored with an undefined id.\n if (name !== undefined && id !== undefined && /^[a-f0-9]{32}$/i.test(id)) {\n stores.push({ name, id });\n }\n }\n return stores;\n}\n\nexport function listSecretStores(): SecretStore[] {\n const output = runWrangler(['secrets-store', 'store', 'list', '--remote']);\n try {\n return parseJsonArray<SecretStore>(output, 'wrangler secrets-store store list --remote');\n } catch {\n // The subcommand prints a table rather than JSON on some versions.\n return parseSecretStoresTable(output);\n }\n}\n\nexport function ensureSecretStore(): string {\n const stores = listSecretStores();\n const existing = stores.find((candidate) => candidate.name === DEFAULT_SECRET_STORE_NAME) ?? stores[0];\n if (existing !== undefined) {\n return existing.id;\n }\n console.log(`Creating Secrets Store: ${DEFAULT_SECRET_STORE_NAME}`);\n const output = runWrangler(['secrets-store', 'store', 'create', DEFAULT_SECRET_STORE_NAME, '--remote']);\n const createdStoreId = /ID:\\s*([a-f0-9]{32})/i.exec(output)?.[1];\n if (createdStoreId !== undefined) {\n return createdStoreId;\n }\n // The create output did not name the id, so read it back rather than guessing.\n const refreshed = listSecretStores();\n const store = refreshed.find((candidate) => candidate.name === DEFAULT_SECRET_STORE_NAME) ?? refreshed[0];\n if (store?.id === undefined) {\n throw new Error(`Unable to discover Secrets Store ID for ${DEFAULT_SECRET_STORE_NAME}.`);\n }\n return store.id;\n}\n\n/** Create a queue when it is absent, reporting whether it had to be created. */\nexport function ensureQueue(queueName: string): boolean {\n try {\n runWrangler(['queues', 'info', queueName]);\n console.log(`Queue ${queueName} already exists.`);\n return false;\n } catch {\n console.log(`Creating queue: ${queueName}`);\n runWrangler(['queues', 'create', queueName]);\n return true;\n }\n}\n\n/**\n * Queue names a deployment needs, in first-seen order.\n *\n * Producers and consumers name the same queue twice — one queue, two roles — and a\n * name appearing in both must be created once. Pure so it is testable without\n * wrangler.\n */\nexport function queueNamesIn(config: WranglerConfig): string[] {\n const names: string[] = [];\n const seen = new Set<string>();\n for (const producer of config.queues?.producers ?? []) {\n if (producer.queue === '' || seen.has(producer.queue)) continue;\n seen.add(producer.queue);\n names.push(producer.queue);\n }\n for (const consumer of config.queues?.consumers ?? []) {\n if (consumer.queue === '' || seen.has(consumer.queue)) continue;\n seen.add(consumer.queue);\n names.push(consumer.queue);\n }\n return names;\n}\n\nexport function ensureVectorizeIndex(indexName: string, dimensions: number): void {\n try {\n runWrangler(['vectorize', 'info', indexName]);\n console.log(`Vectorize index ${indexName} already exists.`);\n } catch {\n console.log(`Creating Vectorize index: ${indexName} with ${dimensions} dimensions`);\n runWrangler(['vectorize', 'create', indexName, `--dimensions=${dimensions}`, '--metric=cosine']);\n }\n}\n\n/** Replace each placeholder D1 `database_id` with a real one. */\nfunction provisionD1Databases(content: string, config: WranglerConfig, created: string[]): string {\n let patched = content;\n for (const [index, database] of config.d1_databases?.entries() ?? []) {\n if (database.database_id !== DEFAULT_UUID) continue;\n if (database.database_name === undefined || database.database_name === '') {\n throw new Error(`D1 database binding ${database.binding ?? index} has a placeholder database_id but no database_name.`);\n }\n const resolved = ensureD1Database(database.database_name);\n if (resolved.created) {\n created.push(`d1:${database.database_name}`);\n }\n console.log(`Using D1 database ${database.database_name}: ${resolved.id}`);\n patched = writeConfigValue(patched, ['d1_databases', index, 'database_id'], resolved.id);\n }\n return patched;\n}\n\n/** Replace each placeholder KV namespace id with a real one. */\nfunction provisionKvNamespaces(content: string, config: WranglerConfig, created: string[]): string {\n let patched = content;\n for (const [index, namespace] of config.kv_namespaces?.entries() ?? []) {\n if (namespace.id !== DEFAULT_HEX_ID) continue;\n if (namespace.binding === undefined || namespace.binding === '') {\n throw new Error(`KV namespace at index ${index} has a placeholder id but no binding.`);\n }\n const resolved = ensureKVNamespace(config, namespace.binding);\n const namespaceName = getKVNamespaceName(config, namespace.binding);\n if (resolved.created) {\n created.push(`kv:${namespaceName}`);\n }\n console.log(`Using KV namespace ${namespaceName}: ${resolved.id}`);\n patched = writeConfigValue(patched, ['kv_namespaces', index, 'id'], resolved.id);\n }\n return patched;\n}\n\n/**\n * Point every placeholder Secrets Store `store_id` at one store, creating it if\n * absent. `existed` is read **before** the create, because whether the store was\n * created is what the caller reports.\n */\nfunction provisionSecretStore(content: string, config: WranglerConfig, created: string[]): string {\n const placeholders = (config.secrets_store_secrets ?? [])\n .map((secret, index) => ({ secret, index }))\n .filter(({ secret }) => secret.store_id === DEFAULT_HEX_ID);\n if (placeholders.length === 0) {\n return content;\n }\n const existed = listSecretStores().some((store) => store.name === DEFAULT_SECRET_STORE_NAME);\n const storeId = ensureSecretStore();\n if (!existed) {\n created.push(`secrets-store:${DEFAULT_SECRET_STORE_NAME}`);\n }\n console.log(`Using Secrets Store: ${storeId}`);\n return placeholders.reduce(\n (patched, { index }) => writeConfigValue(patched, ['secrets_store_secrets', index, 'store_id'], storeId),\n content,\n );\n}\n\n/**\n * Create every resource the config names, and write the real ids over the\n * placeholders.\n *\n * Returns what it had to create, as `<kind>:<name>` — returned rather than logged,\n * because a caller acts on it: the backup workflow refuses to export a D1 database\n * that appears here, since one created moments ago holds no user data and an empty\n * dump uploaded on schedule is a false sense of safety.\n */\nexport function provisionWranglerResources(): string[] {\n const created: string[] = [];\n let { content, config } = readConfig();\n\n content = ensureRequiredKvBindings(content, config);\n config = parse(content) as WranglerConfig;\n\n // Each of the three below re-parses before it patches, because each writes into\n // the config text the previous one produced. They are separate functions because\n // they are separate resources with separate rules, and one loop holding all\n // three would read as a single resource list with the differences hidden in the\n // bodies.\n content = provisionD1Databases(content, config, created);\n config = parse(content) as WranglerConfig;\n\n content = provisionKvNamespaces(content, config, created);\n config = parse(content) as WranglerConfig;\n\n content = provisionSecretStore(content, config, created);\n\n writeConfig(content);\n\n config = parse(content) as WranglerConfig;\n for (const queueName of queueNamesIn(config)) {\n if (ensureQueue(queueName)) {\n created.push(`queue:${queueName}`);\n }\n }\n\n // Vectorize indexes are name-based, so nothing in the file is patched — but the\n // created names are still reported like every other resource, so a deploy log\n // shows what appeared.\n for (const binding of config.vectorize ?? []) {\n ensureVectorizeIndex(binding.index_name, VECTORIZE_DIMENSIONS);\n }\n\n return created;\n}\n"]}
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/scripts/wrangler-config/resources.ts"],
4
+ "sourcesContent": ["/**\n * Creating the resources `wrangler.jsonc` names, and writing their real ids over\n * the placeholders.\n *\n * Provenance: ported from Edge-Sonic's `scripts/lib/wrangler-config/resources.ts`.\n *\n * The placeholder rule: a template carries an all-zero id meaning \"resolve me\",\n * and a config carrying one cannot be deployed. So provisioning walks the config,\n * creates what is missing, and patches the id in place. A placeholder with nothing\n * to create it *under* — a KV id with no binding, a D1 id with no name — is\n * refused rather than skipped, because a silently skipped placeholder is a deploy\n * that fails later with no link back to the reason.\n */\n\nimport { parse } from 'jsonc-parser';\nimport { parseWranglerTableRows } from '../lib/wrangler-table.ts';\nimport {\n DEFAULT_HEX_ID,\n DEFAULT_KV_NAMESPACE_NAMES,\n DEFAULT_SECRET_STORE_NAME,\n DEFAULT_UUID,\n DEFAULT_WORKER_NAME,\n VECTORIZE_DIMENSIONS,\n type D1Database,\n type KVNamespace,\n type SecretStore,\n type WranglerConfig,\n} from './types.ts';\nimport { parseJsonArray, runWrangler } from './cli.ts';\nimport { readConfig, writeConfig, writeConfigValue } from './patches.ts';\n\n/**\nWhat `ensure*` did, so a caller can act on the difference.\n*/\nexport interface Provisioned {\n id: string;\n created: boolean;\n}\n\n/**\nThe id a D1 database is reported under, whichever key the CLI used.\n*/\nexport function getD1Id(database: D1Database): string | undefined {\n return database.uuid ?? database.database_id ?? database.id;\n}\n\nexport function listD1Databases(): D1Database[] {\n return parseJsonArray<D1Database>(runWrangler(['d1', 'list', '--json']), 'wrangler d1 list --json');\n}\n\n/**\n * The D1 database `binding` names, created when it does not exist.\n *\n * Whether it was created is reported, not inferred: a database created moments ago\n * holds no user data, so a backup workflow must refuse to upload its empty dump.\n * The caller cannot re-derive that from the config, because this very function\n * patches the placeholder away before the reader ever runs.\n */\nexport function ensureD1Database(databaseName: string): Provisioned {\n let database = listD1Databases().find((candidate) => candidate.name === databaseName);\n let created = false;\n if (database === undefined) {\n console.log(`Creating D1 database: ${databaseName}`);\n runWrangler(['d1', 'create', databaseName]);\n database = listD1Databases().find((candidate) => candidate.name === databaseName);\n created = true;\n }\n const databaseId = database === undefined ? undefined : getD1Id(database);\n if (databaseId === undefined || databaseId === '') {\n throw new Error(`Unable to discover D1 database ID for ${databaseName}.`);\n }\n return { id: databaseId, created };\n}\n\nexport function listKVNamespaces(): KVNamespace[] {\n return parseJsonArray<KVNamespace>(runWrangler(['kv', 'namespace', 'list']), 'wrangler kv namespace list');\n}\n\n/**\nThe namespace name a binding's namespace is created under.\n*/\nexport function getKVNamespaceName(config: WranglerConfig, binding: string): string {\n return DEFAULT_KV_NAMESPACE_NAMES[binding] ?? `${config.name ?? DEFAULT_WORKER_NAME}-${binding.toLowerCase()}`;\n}\n\nexport function ensureKVNamespace(config: WranglerConfig, binding: string): Provisioned {\n const namespaceName = getKVNamespaceName(config, binding);\n const candidateNames = new Set([namespaceName, `${config.name ?? DEFAULT_WORKER_NAME}-${binding}`, binding]);\n let namespace = listKVNamespaces().find((candidate) => {\n const candidateName = candidate.title ?? candidate.name;\n return candidate.id !== undefined && candidateName !== undefined && candidateNames.has(candidateName);\n });\n let created = false;\n if (namespace === undefined) {\n console.log(`Creating KV namespace: ${namespaceName}`);\n runWrangler(['kv', 'namespace', 'create', namespaceName]);\n namespace = listKVNamespaces().find((candidate) => candidate.id !== undefined && (candidate.title ?? candidate.name) === namespaceName);\n created = true;\n }\n if (namespace?.id === undefined) {\n throw new Error(`Unable to discover KV namespace ID for ${namespaceName}.`);\n }\n return { id: namespace.id, created };\n}\n\n/**\nThe bindings a deployment always needs, whether or not a custom config lists them.\n*/\nexport function getRequiredKvBindings(): string[] {\n return Object.keys(DEFAULT_KV_NAMESPACE_NAMES);\n}\n\n/**\n * Add the always-needed KV bindings a hand-written config left out.\n *\n * A config supplied through `WRANGLER_JSONC` is edited by hand and drifts; without\n * this the worker starts with an unbound `CACHE` and fails on the first read.\n */\nexport function ensureRequiredKvBindings(content: string, config: WranglerConfig): string {\n const existing = new Set((config.kv_namespaces ?? []).map((namespace) => namespace.binding).filter((binding) => binding !== undefined));\n const missing = getRequiredKvBindings().filter((binding) => !existing.has(binding));\n if (missing.length === 0) {\n return content;\n }\n const next = [...(config.kv_namespaces ?? [])];\n for (const binding of missing) {\n console.log(`Adding missing KV namespace binding: ${binding}`);\n next.push({ binding, id: DEFAULT_HEX_ID });\n }\n return writeConfigValue(content, ['kv_namespaces'], next);\n}\n\n/**\nThe stores in a `secrets-store store list` table.\n*/\nexport function parseSecretStoresTable(output: string): SecretStore[] {\n const stores: SecretStore[] = [];\n // Through the shared table parser rather than a second inline split: `wrangler`\n // renders through `cli-table3`, whose cells are separated by U+2502 and are *not*\n // space-aligned, so a parser written for aligned output silently matches nothing\n // — which reads as \"the store does not exist\" and makes provisioning create a\n // duplicate.\n for (const row of parseWranglerTableRows(output)) {\n // `.at()` rather than indexing: a short row is possible when the table\n // shape drifts, and the guards below are what skip it.\n const name = row.at(0);\n const id = row.at(1);\n // Store ids are 32 hex characters; a row without one is a header, a border, or\n // an unrelated column, and is skipped rather than stored with an undefined id.\n if (name !== undefined && id !== undefined && /^[a-f0-9]{32}$/i.test(id)) {\n stores.push({ name, id });\n }\n }\n return stores;\n}\n\nexport function listSecretStores(): SecretStore[] {\n const output = runWrangler(['secrets-store', 'store', 'list', '--remote']);\n try {\n return parseJsonArray<SecretStore>(output, 'wrangler secrets-store store list --remote');\n } catch {\n // The subcommand prints a table rather than JSON on some versions.\n return parseSecretStoresTable(output);\n }\n}\n\nexport function ensureSecretStore(): string {\n const stores = listSecretStores();\n const existing = stores.find((candidate) => candidate.name === DEFAULT_SECRET_STORE_NAME) ?? stores.at(0);\n if (existing !== undefined) {\n return existing.id;\n }\n console.log(`Creating Secrets Store: ${DEFAULT_SECRET_STORE_NAME}`);\n const output = runWrangler(['secrets-store', 'store', 'create', DEFAULT_SECRET_STORE_NAME, '--remote']);\n const createdStoreId = /ID:\\s*([a-f0-9]{32})/i.exec(output)?.[1];\n if (createdStoreId !== undefined) {\n return createdStoreId;\n }\n // The create output did not name the id, so read it back rather than guessing.\n const refreshed = listSecretStores();\n const store = refreshed.find((candidate) => candidate.name === DEFAULT_SECRET_STORE_NAME) ?? refreshed.at(0);\n if (store?.id === undefined) {\n throw new Error(`Unable to discover Secrets Store ID for ${DEFAULT_SECRET_STORE_NAME}.`);\n }\n return store.id;\n}\n\n/**\nCreate a queue when it is absent, reporting whether it had to be created.\n*/\nexport function ensureQueue(queueName: string): boolean {\n try {\n runWrangler(['queues', 'info', queueName]);\n console.log(`Queue ${queueName} already exists.`);\n return false;\n } catch {\n console.log(`Creating queue: ${queueName}`);\n runWrangler(['queues', 'create', queueName]);\n return true;\n }\n}\n\n/**\n * Queue names a deployment needs, in first-seen order.\n *\n * Producers and consumers name the same queue twice — one queue, two roles — and a\n * name appearing in both must be created once. Pure so it is testable without\n * wrangler.\n */\nexport function queueNamesIn(config: WranglerConfig): string[] {\n const names: string[] = [];\n const seen = new Set<string>();\n for (const producer of config.queues?.producers ?? []) {\n if (producer.queue === '' || seen.has(producer.queue)) continue;\n seen.add(producer.queue);\n names.push(producer.queue);\n }\n for (const consumer of config.queues?.consumers ?? []) {\n if (consumer.queue === '' || seen.has(consumer.queue)) continue;\n seen.add(consumer.queue);\n names.push(consumer.queue);\n }\n return names;\n}\n\nexport function ensureVectorizeIndex(indexName: string, dimensions: number): void {\n try {\n runWrangler(['vectorize', 'info', indexName]);\n console.log(`Vectorize index ${indexName} already exists.`);\n } catch {\n console.log(`Creating Vectorize index: ${indexName} with ${dimensions} dimensions`);\n runWrangler(['vectorize', 'create', indexName, `--dimensions=${dimensions}`, '--metric=cosine']);\n }\n}\n\n/**\nReplace each placeholder D1 `database_id` with a real one.\n*/\nfunction provisionD1Databases(content: string, config: WranglerConfig, created: string[]): string {\n let patched = content;\n for (const [index, database] of config.d1_databases?.entries() ?? []) {\n if (database.database_id !== DEFAULT_UUID) continue;\n if (database.database_name === undefined || database.database_name === '') {\n throw new Error(`D1 database binding ${database.binding ?? index} has a placeholder database_id but no database_name.`);\n }\n const resolved = ensureD1Database(database.database_name);\n if (resolved.created) {\n created.push(`d1:${database.database_name}`);\n }\n console.log(`Using D1 database ${database.database_name}: ${resolved.id}`);\n patched = writeConfigValue(patched, ['d1_databases', index, 'database_id'], resolved.id);\n }\n return patched;\n}\n\n/**\nReplace each placeholder KV namespace id with a real one.\n*/\nfunction provisionKvNamespaces(content: string, config: WranglerConfig, created: string[]): string {\n let patched = content;\n for (const [index, namespace] of config.kv_namespaces?.entries() ?? []) {\n if (namespace.id !== DEFAULT_HEX_ID) continue;\n if (namespace.binding === undefined || namespace.binding === '') {\n throw new Error(`KV namespace at index ${index} has a placeholder id but no binding.`);\n }\n const resolved = ensureKVNamespace(config, namespace.binding);\n const namespaceName = getKVNamespaceName(config, namespace.binding);\n if (resolved.created) {\n created.push(`kv:${namespaceName}`);\n }\n console.log(`Using KV namespace ${namespaceName}: ${resolved.id}`);\n patched = writeConfigValue(patched, ['kv_namespaces', index, 'id'], resolved.id);\n }\n return patched;\n}\n\n/**\n * Point every placeholder Secrets Store `store_id` at one store, creating it if\n * absent. `existed` is read **before** the create, because whether the store was\n * created is what the caller reports.\n */\nfunction provisionSecretStore(content: string, config: WranglerConfig, created: string[]): string {\n const placeholders = (config.secrets_store_secrets ?? [])\n .map((secret, index) => ({ secret, index }))\n .filter(({ secret }) => secret.store_id === DEFAULT_HEX_ID);\n if (placeholders.length === 0) {\n return content;\n }\n const existed = listSecretStores().some((store) => store.name === DEFAULT_SECRET_STORE_NAME);\n const storeId = ensureSecretStore();\n if (!existed) {\n created.push(`secrets-store:${DEFAULT_SECRET_STORE_NAME}`);\n }\n console.log(`Using Secrets Store: ${storeId}`);\n return placeholders.reduce(\n (patched, { index }) => writeConfigValue(patched, ['secrets_store_secrets', index, 'store_id'], storeId),\n content,\n );\n}\n\n/**\n * Create every resource the config names, and write the real ids over the\n * placeholders.\n *\n * Returns what it had to create, as `<kind>:<name>` — returned rather than logged,\n * because a caller acts on it: the backup workflow refuses to export a D1 database\n * that appears here, since one created moments ago holds no user data and an empty\n * dump uploaded on schedule is a false sense of safety.\n */\nexport function provisionWranglerResources(): string[] {\n const created: string[] = [];\n let { content, config } = readConfig();\n\n content = ensureRequiredKvBindings(content, config);\n config = parse(content) as WranglerConfig;\n\n // Each of the three below re-parses before it patches, because each writes into\n // the config text the previous one produced. They are separate functions because\n // they are separate resources with separate rules, and one loop holding all\n // three would read as a single resource list with the differences hidden in the\n // bodies.\n content = provisionD1Databases(content, config, created);\n config = parse(content) as WranglerConfig;\n\n content = provisionKvNamespaces(content, config, created);\n config = parse(content) as WranglerConfig;\n\n content = provisionSecretStore(content, config, created);\n\n writeConfig(content);\n\n config = parse(content) as WranglerConfig;\n for (const queueName of queueNamesIn(config)) {\n if (ensureQueue(queueName)) {\n created.push(`queue:${queueName}`);\n }\n }\n\n // Vectorize indexes are name-based, so nothing in the file is patched — but the\n // created names are still reported like every other resource, so a deploy log\n // shows what appeared.\n for (const binding of config.vectorize ?? []) {\n ensureVectorizeIndex(binding.index_name, VECTORIZE_DIMENSIONS);\n }\n\n return created;\n}\n"],
5
+ "mappings": "AAcA,OAAS,SAAAA,MAAa,eACtB,OAAS,0BAAAC,MAA8B,2BACvC,OACE,kBAAAC,EACA,8BAAAC,EACA,6BAAAC,EACA,gBAAAC,EACA,uBAAAC,EACA,wBAAAC,MAKK,aACP,OAAS,kBAAAC,EAAgB,eAAAC,MAAmB,WAC5C,OAAS,cAAAC,EAAY,eAAAC,EAAa,oBAAAC,MAAwB,eAapD,SAAUC,EAAQC,EAAoB,CAC1C,OAAOA,EAAS,MAAQA,EAAS,aAAeA,EAAS,EAC3D,CAEM,SAAUC,GAAe,CAC7B,OAAOP,EAA2BC,EAAY,CAAC,KAAM,OAAQ,QAAQ,CAAC,EAAG,yBAAyB,CACpG,CAUM,SAAUO,EAAiBC,EAAoB,CACnD,IAAIH,EAAWC,EAAe,EAAG,KAAMG,GAAcA,EAAU,OAASD,CAAY,EAChFE,EAAU,GACVL,IAAa,SACf,QAAQ,IAAI,yBAAyBG,CAAY,EAAE,EACnDR,EAAY,CAAC,KAAM,SAAUQ,CAAY,CAAC,EAC1CH,EAAWC,EAAe,EAAG,KAAMG,GAAcA,EAAU,OAASD,CAAY,EAChFE,EAAU,IAEZ,MAAMC,EAAaN,IAAa,OAAY,OAAYD,EAAQC,CAAQ,EACxE,GAA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T_SECRET_STORE_NAME", "DEFAULT_UUID", "DEFAULT_WORKER_NAME", "VECTORIZE_DIMENSIONS", "parseJsonArray", "runWrangler", "readConfig", "writeConfig", "writeConfigValue", "getD1Id", "database", "listD1Databases", "ensureD1Database", "databaseName", "candidate", "created", "databaseId", "listKVNamespaces", "getKVNamespaceName", "config", "binding", "ensureKVNamespace", "namespaceName", "candidateNames", "namespace", "candidateName", "getRequiredKvBindings", "ensureRequiredKvBindings", "content", "existing", "missing", "next", "parseSecretStoresTable", "output", "stores", "row", "name", "id", "listSecretStores", "ensureSecretStore", "createdStoreId", "refreshed", "store", "ensureQueue", "queueName", "queueNamesIn", "names", "seen", "producer", "consumer", "ensureVectorizeIndex", "indexName", "dimensions", "provisionD1Databases", "patched", "index", "resolved", "provisionKvNamespaces", "provisionSecretStore", "placeholders", "secret", "existed", "storeId", "provisionWranglerResources"]
7
+ }
@@ -11,9 +11,13 @@
11
11
  * / `WRANGLER_TEMPLATE_PATH` override them for a caller that is not in the repo
12
12
  * root, which is the one case the cwd default gets wrong.
13
13
  */
14
- /** The config the deploy targets. */
14
+ /**
15
+ The config the deploy targets.
16
+ */
15
17
  export declare const CONFIG_PATH: string;
16
- /** The committed template the config is materialized from. */
18
+ /**
19
+ The committed template the config is materialized from.
20
+ */
17
21
  export declare const TEMPLATE_PATH: string;
18
22
  /**
19
23
  * The id a template carries for a D1 database that does not exist yet.
@@ -23,9 +27,13 @@ export declare const TEMPLATE_PATH: string;
23
27
  * created holds no user data.
24
28
  */
25
29
  export declare const DEFAULT_UUID = "00000000-0000-0000-0000-000000000000";
26
- /** The placeholder for a KV namespace id and for a Secrets Store id. */
30
+ /**
31
+ The placeholder for a KV namespace id and for a Secrets Store id.
32
+ */
27
33
  export declare const DEFAULT_HEX_ID = "00000000000000000000000000000000";
28
- /** The Secrets Store name a deployment uses. */
34
+ /**
35
+ The Secrets Store name a deployment uses.
36
+ */
29
37
  export declare const DEFAULT_SECRET_STORE_NAME = "default";
30
38
  /**
31
39
  * Fallback when the config declares no `name`, used to derive resource names.
@@ -41,7 +49,9 @@ export declare const DEFAULT_WORKER_NAME: string;
41
49
  * with one names it here or leaves the derived `<worker>-<BINDING>` convention.
42
50
  */
43
51
  export declare const DEFAULT_KV_NAMESPACE_NAMES: Record<string, string>;
44
- /** Dimensions of a Vectorize index this kit provisions. */
52
+ /**
53
+ Dimensions of a Vectorize index this kit provisions.
54
+ */
45
55
  export declare const VECTORIZE_DIMENSIONS = 1024;
46
56
  /**
47
57
  * The parsed shape of a wrangler config.
@@ -82,20 +92,26 @@ export interface WranglerConfig {
82
92
  index_name: string;
83
93
  }>;
84
94
  }
85
- /** A D1 database as `wrangler d1 list --json` reports one. */
95
+ /**
96
+ A D1 database as `wrangler d1 list --json` reports one.
97
+ */
86
98
  export interface D1Database {
87
99
  name?: string;
88
100
  uuid?: string;
89
101
  id?: string;
90
102
  database_id?: string;
91
103
  }
92
- /** A KV namespace as `wrangler kv namespace list` reports one. */
104
+ /**
105
+ A KV namespace as `wrangler kv namespace list` reports one.
106
+ */
93
107
  export interface KVNamespace {
94
108
  title?: string;
95
109
  name?: string;
96
110
  id?: string;
97
111
  }
98
- /** A Secrets Store as `wrangler secrets-store store list` reports one. */
112
+ /**
113
+ A Secrets Store as `wrangler secrets-store store list` reports one.
114
+ */
99
115
  export interface SecretStore {
100
116
  name: string;
101
117
  id: string;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/scripts/wrangler-config/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAIH,qCAAqC;AACrC,eAAO,MAAM,WAAW,QAAoF,CAAC;AAE7G,8DAA8D;AAC9D,eAAO,MAAM,aAAa,QAAwG,CAAC;AAEnI;;;;;;GAMG;AACH,eAAO,MAAM,YAAY,yCAAyC,CAAC;AAEnE,wEAAwE;AACxE,eAAO,MAAM,cAAc,qCAAqC,CAAC;AAEjE,gDAAgD;AAChD,eAAO,MAAM,yBAAyB,YAAY,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wrangler config helpers.
3
- *
4
- * Provenance: ported from Edge-Sonic's `scripts/lib/wrangler-config/types.ts`.
5
- * Every script that reads or writes `wrangler.jsonc` resolves it here, so the
6
- * backup workflow cannot end up inspecting a different file than the deploy
7
- * materialized.
8
- *
9
- * The paths default to `process.cwd()`, which is the repo root in every consumer:
10
- * the scripts run as `pnpm exec tsx scripts/deploy/…` from there. `WRANGLER_CONFIG_PATH`
11
- * / `WRANGLER_TEMPLATE_PATH` override them for a caller that is not in the repo
12
- * root, which is the one case the cwd default gets wrong.
13
- */
14
- import path from 'node:path';
15
- /** The config the deploy targets. */
16
- export const CONFIG_PATH = process.env['WRANGLER_CONFIG_PATH'] ?? path.join(process.cwd(), 'wrangler.jsonc');
17
- /** The committed template the config is materialized from. */
18
- export const TEMPLATE_PATH = process.env['WRANGLER_TEMPLATE_PATH'] ?? path.join(process.cwd(), 'apps/api/wrangler.template.jsonc');
19
- /**
20
- * The id a template carries for a D1 database that does not exist yet.
21
- *
22
- * `provisionWranglerResources` replaces it with a real id; the backup scripts
23
- * refuse to export while it is still in place, because a database that was just
24
- * created holds no user data.
25
- */
26
- export const DEFAULT_UUID = '00000000-0000-0000-0000-000000000000';
27
- /** The placeholder for a KV namespace id and for a Secrets Store id. */
28
- export const DEFAULT_HEX_ID = '00000000000000000000000000000000';
29
- /** The Secrets Store name a deployment uses. */
30
- export const DEFAULT_SECRET_STORE_NAME = 'default';
31
- /**
32
- * Fallback when the config declares no `name`, used to derive resource names.
33
- *
34
- * Overridable per consumer with `WRANGLER_WORKER_NAME`, which keeps the default
35
- * honest rather than baking one repo's name into the kit.
36
- */
37
- export const DEFAULT_WORKER_NAME = process.env['WRANGLER_WORKER_NAME'] ?? 'my-worker';
38
- /**
39
- * KV bindings a deployment always needs, and the namespace each maps to.
40
- *
41
- * A consumer whose worker has no cache binding passes an empty map; a consumer
42
- * with one names it here or leaves the derived `<worker>-<BINDING>` convention.
43
- */
44
- export const DEFAULT_KV_NAMESPACE_NAMES = {
45
- CACHE: `${DEFAULT_WORKER_NAME}-cache`,
46
- };
47
- /** Dimensions of a Vectorize index this kit provisions. */
48
- export const VECTORIZE_DIMENSIONS = 1024;
49
- //# sourceMappingURL=types.js.map
1
+ import o from"node:path";const r=process.env.WRANGLER_CONFIG_PATH??o.join(process.cwd(),"wrangler.jsonc"),s=process.env.WRANGLER_TEMPLATE_PATH??o.join(process.cwd(),"apps/api/wrangler.template.jsonc"),t="00000000-0000-0000-0000-000000000000",A="00000000000000000000000000000000",_="default",E=process.env.WRANGLER_WORKER_NAME??"my-worker",c={CACHE:`${E}-cache`},p=1024;export{r as CONFIG_PATH,A as DEFAULT_HEX_ID,c as DEFAULT_KV_NAMESPACE_NAMES,_ as DEFAULT_SECRET_STORE_NAME,t as DEFAULT_UUID,E as DEFAULT_WORKER_NAME,s as TEMPLATE_PATH,p as VECTORIZE_DIMENSIONS};
@@ -1 +1,7 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/scripts/wrangler-config/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,IAAI,MAAM,WAAW,CAAC;AAE7B,qCAAqC;AACrC,MAAM,CAAC,MAAM,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,sBAAsB,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,gBAAgB,CAAC,CAAC;AAE7G,8DAA8D;AAC9D,MAAM,CAAC,MAAM,aAAa,GAAG,OAAO,CAAC,GAAG,CAAC,wBAAwB,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,kCAAkC,CAAC,CAAC;AAEnI;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,sCAAsC,CAAC;AAEnE,wEAAwE;AACxE,MAAM,CAAC,MAAM,cAAc,GAAG,kCAAkC,CAAC;AAEjE,gDAAgD;AAChD,MAAM,CAAC,MAAM,yBAAyB,GAAG,SAAS,CAAC;AAEnD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,OAAO,CAAC,GAAG,CAAC,sBAAsB,CAAC,IAAI,WAAW,CAAC;AAEtF;;;;;GAKG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAA2B;IAChE,KAAK,EAAE,GAAG,mBAAmB,QAAQ;CACtC,CAAC;AAEF,2DAA2D;AAC3D,MAAM,CAAC,MAAM,oBAAoB,GAAG,IAAI,CAAC","sourcesContent":["/**\n * Shared paths, placeholders and shape definitions for the wrangler config helpers.\n *\n * Provenance: ported from Edge-Sonic's `scripts/lib/wrangler-config/types.ts`.\n * Every script that reads or writes `wrangler.jsonc` resolves it here, so the\n * backup workflow cannot end up inspecting a different file than the deploy\n * materialized.\n *\n * The paths default to `process.cwd()`, which is the repo root in every consumer:\n * the scripts run as `pnpm exec tsx scripts/deploy/…` from there. `WRANGLER_CONFIG_PATH`\n * / `WRANGLER_TEMPLATE_PATH` override them for a caller that is not in the repo\n * root, which is the one case the cwd default gets wrong.\n */\n\nimport path from 'node:path';\n\n/** The config the deploy targets. */\nexport const CONFIG_PATH = process.env['WRANGLER_CONFIG_PATH'] ?? path.join(process.cwd(), 'wrangler.jsonc');\n\n/** The committed template the config is materialized from. */\nexport const TEMPLATE_PATH = process.env['WRANGLER_TEMPLATE_PATH'] ?? path.join(process.cwd(), 'apps/api/wrangler.template.jsonc');\n\n/**\n * The id a template carries for a D1 database that does not exist yet.\n *\n * `provisionWranglerResources` replaces it with a real id; the backup scripts\n * refuse to export while it is still in place, because a database that was just\n * created holds no user data.\n */\nexport const DEFAULT_UUID = '00000000-0000-0000-0000-000000000000';\n\n/** The placeholder for a KV namespace id and for a Secrets Store id. */\nexport const DEFAULT_HEX_ID = '00000000000000000000000000000000';\n\n/** The Secrets Store name a deployment uses. */\nexport const DEFAULT_SECRET_STORE_NAME = 'default';\n\n/**\n * Fallback when the config declares no `name`, used to derive resource names.\n *\n * Overridable per consumer with `WRANGLER_WORKER_NAME`, which keeps the default\n * honest rather than baking one repo's name into the kit.\n */\nexport const DEFAULT_WORKER_NAME = process.env['WRANGLER_WORKER_NAME'] ?? 'my-worker';\n\n/**\n * KV bindings a deployment always needs, and the namespace each maps to.\n *\n * A consumer whose worker has no cache binding passes an empty map; a consumer\n * with one names it here or leaves the derived `<worker>-<BINDING>` convention.\n */\nexport const DEFAULT_KV_NAMESPACE_NAMES: Record<string, string> = {\n CACHE: `${DEFAULT_WORKER_NAME}-cache`,\n};\n\n/** Dimensions of a Vectorize index this kit provisions. */\nexport const VECTORIZE_DIMENSIONS = 1024;\n\n/**\n * The parsed shape of a wrangler config.\n *\n * `vars` is widened with `null` on purpose: jsonc-parser yields `null` for an\n * explicit `vars: null`, and the vars-patch path must be able to reject that\n * rather than treat the field as absent.\n */\nexport interface WranglerConfig {\n name?: string;\n $version?: number;\n vars?: Record<string, unknown> | null;\n d1_databases?: Array<{\n binding?: string;\n database_id?: string;\n database_name?: string;\n }>;\n kv_namespaces?: Array<{\n binding?: string;\n id?: string;\n }>;\n secrets_store_secrets?: Array<{\n binding?: string;\n store_id?: string;\n secret_name?: string;\n }>;\n queues?: {\n producers?: Array<{ binding: string; queue: string }>;\n consumers?: Array<{ queue: string }>;\n };\n vectorize?: Array<{\n binding: string;\n index_name: string;\n }>;\n}\n\n/** A D1 database as `wrangler d1 list --json` reports one. */\nexport interface D1Database {\n name?: string;\n uuid?: string;\n id?: string;\n database_id?: string;\n}\n\n/** A KV namespace as `wrangler kv namespace list` reports one. */\nexport interface KVNamespace {\n title?: string;\n name?: string;\n id?: string;\n}\n\n/** A Secrets Store as `wrangler secrets-store store list` reports one. */\nexport interface SecretStore {\n name: string;\n id: string;\n}\n"]}
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/scripts/wrangler-config/types.ts"],
4
+ "sourcesContent": ["/**\n * Shared paths, placeholders and shape definitions for the wrangler config helpers.\n *\n * Provenance: ported from Edge-Sonic's `scripts/lib/wrangler-config/types.ts`.\n * Every script that reads or writes `wrangler.jsonc` resolves it here, so the\n * backup workflow cannot end up inspecting a different file than the deploy\n * materialized.\n *\n * The paths default to `process.cwd()`, which is the repo root in every consumer:\n * the scripts run as `pnpm exec tsx scripts/deploy/…` from there. `WRANGLER_CONFIG_PATH`\n * / `WRANGLER_TEMPLATE_PATH` override them for a caller that is not in the repo\n * root, which is the one case the cwd default gets wrong.\n */\n\nimport path from 'node:path';\n\n/**\nThe config the deploy targets.\n*/\nexport const CONFIG_PATH = process.env['WRANGLER_CONFIG_PATH'] ?? path.join(process.cwd(), 'wrangler.jsonc');\n\n/**\nThe committed template the config is materialized from.\n*/\nexport const TEMPLATE_PATH = process.env['WRANGLER_TEMPLATE_PATH'] ?? path.join(process.cwd(), 'apps/api/wrangler.template.jsonc');\n\n/**\n * The id a template carries for a D1 database that does not exist yet.\n *\n * `provisionWranglerResources` replaces it with a real id; the backup scripts\n * refuse to export while it is still in place, because a database that was just\n * created holds no user data.\n */\nexport const DEFAULT_UUID = '00000000-0000-0000-0000-000000000000';\n\n/**\nThe placeholder for a KV namespace id and for a Secrets Store id.\n*/\nexport const DEFAULT_HEX_ID = '00000000000000000000000000000000';\n\n/**\nThe Secrets Store name a deployment uses.\n*/\nexport const DEFAULT_SECRET_STORE_NAME = 'default';\n\n/**\n * Fallback when the config declares no `name`, used to derive resource names.\n *\n * Overridable per consumer with `WRANGLER_WORKER_NAME`, which keeps the default\n * honest rather than baking one repo's name into the kit.\n */\nexport const DEFAULT_WORKER_NAME = process.env['WRANGLER_WORKER_NAME'] ?? 'my-worker';\n\n/**\n * KV bindings a deployment always needs, and the namespace each maps to.\n *\n * A consumer whose worker has no cache binding passes an empty map; a consumer\n * with one names it here or leaves the derived `<worker>-<BINDING>` convention.\n */\nexport const DEFAULT_KV_NAMESPACE_NAMES: Record<string, string> = {\n CACHE: `${DEFAULT_WORKER_NAME}-cache`,\n};\n\n/**\nDimensions of a Vectorize index this kit provisions.\n*/\nexport const VECTORIZE_DIMENSIONS = 1024;\n\n/**\n * The parsed shape of a wrangler config.\n *\n * `vars` is widened with `null` on purpose: jsonc-parser yields `null` for an\n * explicit `vars: null`, and the vars-patch path must be able to reject that\n * rather than treat the field as absent.\n */\nexport interface WranglerConfig {\n name?: string;\n $version?: number;\n vars?: Record<string, unknown> | null;\n d1_databases?: Array<{\n binding?: string;\n database_id?: string;\n database_name?: string;\n }>;\n kv_namespaces?: Array<{\n binding?: string;\n id?: string;\n }>;\n secrets_store_secrets?: Array<{\n binding?: string;\n store_id?: string;\n secret_name?: string;\n }>;\n queues?: {\n producers?: Array<{ binding: string; queue: string }>;\n consumers?: Array<{ queue: string }>;\n };\n vectorize?: Array<{\n binding: string;\n index_name: string;\n }>;\n}\n\n/**\nA D1 database as `wrangler d1 list --json` reports one.\n*/\nexport interface D1Database {\n name?: string;\n uuid?: string;\n id?: string;\n database_id?: string;\n}\n\n/**\nA KV namespace as `wrangler kv namespace list` reports one.\n*/\nexport interface KVNamespace {\n title?: string;\n name?: string;\n id?: string;\n}\n\n/**\nA Secrets Store as `wrangler secrets-store store list` reports one.\n*/\nexport interface SecretStore {\n name: string;\n id: string;\n}\n"],
5
+ "mappings": "AAcA,OAAOA,MAAU,YAKV,MAAMC,EAAc,QAAQ,IAAI,sBAA2BD,EAAK,KAAK,QAAQ,IAAG,EAAI,gBAAgB,EAK9FE,EAAgB,QAAQ,IAAI,wBAA6BF,EAAK,KAAK,QAAQ,IAAG,EAAI,kCAAkC,EASpHG,EAAe,uCAKfC,EAAiB,mCAKjBC,EAA4B,UAQ5BC,EAAsB,QAAQ,IAAI,sBAA2B,YAQ7DC,EAAqD,CAChE,MAAO,GAAGD,CAAmB,UAMlBE,EAAuB",
6
+ "names": ["path", "CONFIG_PATH", "TEMPLATE_PATH", "DEFAULT_UUID", "DEFAULT_HEX_ID", "DEFAULT_SECRET_STORE_NAME", "DEFAULT_WORKER_NAME", "DEFAULT_KV_NAMESPACE_NAMES", "VECTORIZE_DIMENSIONS"]
7
+ }
@@ -64,14 +64,17 @@
64
64
  * the failure names the file) and a sequential `prepare().run()` loop otherwise
65
65
  * (AWS's shape: works on a binding with no batch support).
66
66
  */
67
- import { executableStatements, splitSql } from '@rexezuge/d1';
68
67
  /**
69
68
  * One migration file, as it is read.
70
69
  */
71
70
  export interface MigrationFile {
72
- /** Bare filename, e.g. `0007_replication.sql`. */
71
+ /**
72
+ Bare filename, e.g. `0007_replication.sql`.
73
+ */
73
74
  name: string;
74
- /** The file's full text. */
75
+ /**
76
+ The file's full text.
77
+ */
75
78
  sql: string;
76
79
  }
77
80
  /**
@@ -123,17 +126,29 @@ export interface MigrationHelperOptions {
123
126
  * A bound migration helper.
124
127
  */
125
128
  export interface MigrationHelper {
126
- /** Every migration, in apply order. */
129
+ /**
130
+ Every migration, in apply order.
131
+ */
127
132
  migrationFiles(): MigrationFile[];
128
- /** The filenames, in apply order. */
133
+ /**
134
+ The filenames, in apply order.
135
+ */
129
136
  migrationFileNames(): string[];
130
- /** The concatenation of every file, in apply order — what a fresh database becomes. */
137
+ /**
138
+ The concatenation of every file, in apply order — what a fresh database becomes.
139
+ */
131
140
  migrationSql(): string;
132
- /** One file's SQL, by name. "What does *this* file say", not "what does the set say". */
141
+ /**
142
+ One file's SQL, by name. "What does *this* file say", not "what does the set say".
143
+ */
133
144
  migrationSqlOf(name: string): string;
134
- /** Split one file into statements, comments included. */
145
+ /**
146
+ Split one file into statements, comments included.
147
+ */
135
148
  splitSql(sql: string): string[];
136
- /** The statements of one file that SQLite will actually execute. */
149
+ /**
150
+ The statements of one file that SQLite will actually execute.
151
+ */
137
152
  executableStatements(sql: string): string[];
138
153
  /**
139
154
  * Apply a range of migrations, at most once per database and range.
@@ -153,15 +168,17 @@ export interface MigrationHelper {
153
168
  * than four digits.
154
169
  */
155
170
  export declare function readMigrationFiles(dir: string): MigrationFile[];
156
- /** Re-exported for surface parity with the source repos — the rules live in @rexezuge/d1. */
157
- export { executableStatements, splitSql };
171
+ /**
172
+ Re-exported for surface parity with the source repos — the rules live in @rexezuge/d1.
173
+ */
158
174
  /**
159
175
  * Bind a migration directory into a helper.
160
176
  *
161
177
  * ```ts
162
- * const migrations = createMigrationHelper({ migrationsDir: path.join(REPO_ROOT, 'migrations') });
178
+ * const migrations = createMigrationHelper({ migrationsDir: join(REPO_ROOT, 'migrations') });
163
179
  * await migrations.applyMigrations(env.DB);
164
180
  * ```
165
181
  */
166
182
  export declare function createMigrationHelper(options: MigrationHelperOptions): MigrationHelper;
183
+ export { executableStatements, splitSql } from '@rexezuge/d1';
167
184
  //# sourceMappingURL=integration-migrations.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"integration-migrations.d.ts","sourceRoot":"","sources":["../../src/test/integration-migrations.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiEG;AAEH,OAAO,EAAE,oBAAoB,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAI9D;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,kDAAkD;IAClD,IAAI,EAAE,MAAM,CAAC;IACb,4BAA4B;IAC5B,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;GAEG;AACH,MAAM,WAAW,uBAAuB;IACtC,GAAG,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;CACzB;AAED;;;;;;GAMG;AACH,MAAM,WAAW,cAAc;IAC7B,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,uBAAuB,CAAC;IAC9C,KAAK,CAAC,CAAC,UAAU,EAAE,SAAS,uBAAuB,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CAC1E;AAED;;;;;GAKG;AACH,MAAM,WAAW,cAAc;IAC7B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,EAAE,CAAC,EAAE,MAAM,CAAC;CACb;AAED;;GAEG;AACH,MAAM,WAAW,sBAAsB;IACrC;;;;OAIG;IACH,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B;;;;;OAKG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,SAAS,aAAa,EAAE,CAAC;CAC3C;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,uCAAuC;IACvC,cAAc,IAAI,aAAa,EAAE,CAAC;IAClC,qCAAqC;IACrC,kBAAkB,IAAI,MAAM,EAAE,CAAC;IAC/B,uFAAuF;IACvF,YAAY,IAAI,MAAM,CAAC;IACvB,yFAAyF;IACzF,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC;IACrC,yDAAyD;IACzD,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAChC,oEAAoE;IACpE,oBAAoB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAC5C;;;;;;OAMG;IACH,eAAe,CAAC,EAAE,EAAE,cAAc,EAAE,KAAK,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC5E;AAED;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,GAAG,aAAa,EAAE,CAM/D;AAeD,6FAA6F;AAC7F,OAAO,EAAE,oBAAoB,EAAE,QAAQ,EAAE,CAAC;AAE1C;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,sBAAsB,GAAG,eAAe,CAsEtF"}
1
+ {"version":3,"file":"integration-migrations.d.ts","sourceRoot":"","sources":["../../src/test/integration-migrations.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiEG;AAMH;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B;;MAEE;IACF,IAAI,EAAE,MAAM,CAAC;IACb;;MAEE;IACF,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;GAEG;AACH,MAAM,WAAW,uBAAuB;IACtC,GAAG,IAAI,OAAO,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F;AAED,OAAO,EAAE,oBAAoB,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC"}
@@ -1,171 +1,2 @@
1
- /**
2
- * Applying the migration directory to a D1 binding — as a factory.
3
- *
4
- * Provenance: converged from `test/integration/helpers/migrations.ts` in six repos
5
- * (AWS-AccessBridge, ChordDHT-Tracker, Durable-DAV, Durable-DAV-Router, Edge-Git,
6
- * Mail-Meow) and `test/helpers/migrations.ts` in two more (CalDAV-Bridge,
7
- * Edge-Sonic). All eight are the same file: a SQL splitter plus a range-addressed
8
- * `applyMigrations`.
9
- *
10
- * ### Why it is a factory and not a module
11
- *
12
- * Every source file hardcodes where the migrations live, either as a
13
- * `__INTEGRATION_MIGRATION_FILES__` binding injected by the Vitest config's
14
- * `define`, or as a path derived from `import.meta.url`. The kit cannot know
15
- * either, so the directory is an argument and the injection stays available as an
16
- * option. One call to `createMigrationHelper({ migrationsDir })` gives the consumer
17
- * the same helper their repo already has.
18
- *
19
- * ### What each source contributes
20
- *
21
- * - **Durable-DAV** — the trigger-aware splitter. `CREATE TRIGGER … BEGIN … END;`
22
- * bodies contain semicolons that must not split, and a naive splitter produces
23
- * statements SQLite rejects mid-migration. The BEGIN/END depth is tracked only
24
- * outside strings and comments, and the word *before* `TRIGGER` disambiguates
25
- * `CREATE TRIGGER` from a table called `trigger`. Durable-DAV also applies one
26
- * file per `batch()` and names the offending statement in the error, which is
27
- * the difference between "0007 failed" and a line number.
28
- * - **AWS-AccessBridge** — the once-per-database guard. D1 records which
29
- * migrations have run; this helper does the same, because `ALTER TABLE … ADD
30
- * COLUMN` is not idempotent in SQLite and re-running the bundle fails with
31
- * "duplicate column name". A `WeakMap` keyed on the binding is the right scope
32
- * because each test file gets its own database. AWS also keeps `next` out of the
33
- * line-comment branch, which never reads it, and preserves newlines inside block
34
- * comments so an error's line numbers still point at the file.
35
- * - **Edge-Sonic** — reading the directory off disk rather than a `define`
36
- * binding, because a test that names one hardcoded file cannot tell **a new
37
- * migration** from **an edit to an old one**, so it goes on passing through a
38
- * schema change that never reached production.
39
- *
40
- * ### The splitter is not here
41
- *
42
- * The statement splitter — with all of Durable-DAV's trigger-aware rules and its
43
- * comment-level history — lives once, in `@rexezuge/d1`. `@rexezuge/identity`'s
44
- * migration applier delegates to the same module, so the splitter cannot drift
45
- * between the suite helper and the production applier. The re-exports below keep
46
- * this file's public surface identical to the source repos'.
47
- *
48
- * ### The lock is asserted, not reimplemented
49
- *
50
- * D1 records applied migrations by *filename*, so an applied migration is immutable
51
- * in fact while being an ordinary text file in appearance. That fact lives in
52
- * `migrations/migrations.lock.json`, and the rules that check it live once, in
53
- * `scripts/verify-migrations.ts` — the same module the CI gate runs. This helper
54
- * deliberately does not parse the lock itself: a second implementation of a thing
55
- * already written is free to disagree with the first, and the two disagreeing would
56
- * leave a suite green against a lock CI rejects.
57
- *
58
- * ### Generic over the binding
59
- *
60
- * `D1DatabaseLike` is structural — `prepare`, and `batch` when the runtime has it
61
- * — so a fake D1 in a unit test, a real D1 in the workerd integration suite, and
62
- * Miniflare's D1 all satisfy it without an import of `@cloudflare/workers-types`.
63
- * `batch` is used when present (Durable-DAV's shape: one round trip per file, and
64
- * the failure names the file) and a sequential `prepare().run()` loop otherwise
65
- * (AWS's shape: works on a binding with no batch support).
66
- */
67
- import { executableStatements, splitSql } from '@rexezuge/d1';
68
- import { readdirSync, readFileSync } from 'node:fs';
69
- import { join } from 'node:path';
70
- /**
71
- * Reads every `.sql` file in `dir`, in apply order.
72
- *
73
- * Sort is the filename sort D1 itself uses, rather than a numeric parse of the
74
- * prefix: wrangler hands the directory to SQLite in lexicographic order, so a
75
- * suite that reads it numerically disagrees with production on any prefix wider
76
- * than four digits.
77
- */
78
- export function readMigrationFiles(dir) {
79
- const entries = readdirSync(dir, { withFileTypes: true });
80
- return entries
81
- .filter((entry) => entry.isFile() && entry.name.endsWith('.sql'))
82
- .map((entry) => ({ name: entry.name, sql: readFileSync(join(dir, entry.name), 'utf8') }))
83
- .sort((left, right) => left.name.localeCompare(right.name));
84
- }
85
- /**
86
- * Strip leading `--` and block comments, which the splitter folds into the
87
- * statement it then reports on.
88
- */
89
- function stripLeadingComments(statement) {
90
- let out = statement;
91
- for (;;) {
92
- const next = out.replace(/^\s*(?:--[^\n]*\n|\/\*[\s\S]*?\*\/)\s*/, '');
93
- if (next === out)
94
- return out.trim();
95
- out = next;
96
- }
97
- }
98
- /** Re-exported for surface parity with the source repos — the rules live in @rexezuge/d1. */
99
- export { executableStatements, splitSql };
100
- /**
101
- * Bind a migration directory into a helper.
102
- *
103
- * ```ts
104
- * const migrations = createMigrationHelper({ migrationsDir: path.join(REPO_ROOT, 'migrations') });
105
- * await migrations.applyMigrations(env.DB);
106
- * ```
107
- */
108
- export function createMigrationHelper(options) {
109
- const files = options.files !== undefined ? [...options.files] : readMigrationFiles(options.migrationsDir);
110
- /**
111
- * Databases this helper has already migrated, keyed by the range applied.
112
- *
113
- * A `WeakMap` rather than a module-level `Set`, because the guard is per
114
- * binding: two databases in one suite each need the bundle applied once, and a
115
- * module-level set would silently skip the second.
116
- */
117
- const applied = new WeakMap();
118
- const indexOf = (name, fallback) => {
119
- if (name === undefined)
120
- return fallback;
121
- const found = files.findIndex((file) => file.name === name);
122
- if (found === -1) {
123
- throw new Error(`Unknown migration file: ${name}. Available: ${files.map((file) => file.name).join(', ')}`);
124
- }
125
- return found;
126
- };
127
- return {
128
- migrationFiles: () => files.map((file) => ({ ...file })),
129
- migrationFileNames: () => files.map((file) => file.name),
130
- migrationSql: () => files.map((file) => file.sql).join('\n'),
131
- migrationSqlOf: (name) => {
132
- const file = files.find((candidate) => candidate.name === name);
133
- if (file === undefined) {
134
- throw new Error(`Unknown migration file: ${name}. Available: ${files.map((candidate) => candidate.name).join(', ')}`);
135
- }
136
- return file.sql;
137
- },
138
- splitSql,
139
- executableStatements,
140
- applyMigrations: async (db, range) => {
141
- const start = indexOf(range?.from, 0);
142
- const end = indexOf(range?.to, files.length - 1);
143
- const key = `${start}:${end}`;
144
- if (applied.get(db) === key)
145
- return;
146
- const applicable = files.slice(start, end + 1);
147
- for (const file of applicable) {
148
- const statements = executableStatements(file.sql);
149
- if (statements.length === 0)
150
- continue;
151
- if (typeof db.batch === 'function') {
152
- try {
153
- await db.batch(statements.map((sql) => db.prepare(sql)));
154
- }
155
- catch (error) {
156
- // A batch reports only the file's single failure, so name the statement:
157
- // a migration error that says nothing about which of its nine statements
158
- // broke is a migration error nobody fixes.
159
- throw new Error(`${file.name}: batch of ${statements.length} statements failed at ${stripLeadingComments(statements.at(-1) ?? '').slice(0, 200)}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
160
- }
161
- continue;
162
- }
163
- for (const sql of statements) {
164
- await db.prepare(sql).run();
165
- }
166
- }
167
- applied.set(db, key);
168
- },
169
- };
170
- }
171
- //# sourceMappingURL=integration-migrations.js.map
1
+ import{executableStatements as p,splitSql as g}from"@rexezuge/d1";import{readdirSync as d,readFileSync as h}from"node:fs";import w from"node:path";function q(r){return d(r,{withFileTypes:!0}).filter(t=>t.isFile()&&t.name.endsWith(".sql")).map(t=>({name:t.name,sql:h(w.join(r,t.name),"utf8")})).sort((t,f)=>t.name.localeCompare(f.name))}function S(r){let n=r;for(;;){const t=n.replace(/^\s*(?:--[^\n]*\n|\/\*[\s\S]*?\*\/)\s*/,"");if(t===n)return n.trim();n=t}}function F(r){const n=r.files===void 0?q(r.migrationsDir):[...r.files],t=new WeakMap,f=(e,o)=>{if(e===void 0)return o;const i=n.findIndex(s=>s.name===e);if(i===-1)throw new Error(`Unknown migration file: ${e}. Available: ${n.map(s=>s.name).join(", ")}`);return i};return{migrationFiles:()=>n.map(e=>({...e})),migrationFileNames:()=>n.map(e=>e.name),migrationSql:()=>n.map(e=>e.sql).join(`
2
+ `),migrationSqlOf:e=>{const o=n.find(i=>i.name===e);if(o===void 0)throw new Error(`Unknown migration file: ${e}. Available: ${n.map(i=>i.name).join(", ")}`);return o.sql},splitSql:g,executableStatements:p,applyMigrations:async(e,o)=>{const i=f(o?.from,0),s=f(o?.to,n.length-1),m=`${i}:${s}`;if(t.get(e)===m)return;const u=n.slice(i,s+1);for(const c of u){const l=p(c.sql);if(l.length!==0){if(typeof e.batch=="function"){try{await e.batch(l.map(a=>e.prepare(a)))}catch(a){throw new Error(`${c.name}: batch of ${l.length} statements failed at ${S(l.at(-1)??"").slice(0,200)}: ${a instanceof Error?a.message:String(a)}`,{cause:a})}continue}for(const a of l)await e.prepare(a).run()}}t.set(e,m)}}}import{executableStatements as E,splitSql as M}from"@rexezuge/d1";export{F as createMigrationHelper,E as executableStatements,q as readMigrationFiles,M as splitSql};
@@ -1 +1,7 @@
1
- {"version":3,"file":"integration-migrations.js","sourceRoot":"","sources":["../../src/test/integration-migrations.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiEG;AAEH,OAAO,EAAE,oBAAoB,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAC9D,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACpD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAuFjC;;;;;;;GAOG;AACH,MAAM,UAAU,kBAAkB,CAAC,GAAW;IAC5C,MAAM,OAAO,GAAG,WAAW,CAAC,GAAG,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,CAAC;IAC1D,OAAO,OAAO;SACX,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,EAAE,IAAI,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;SAChE,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,GAAG,EAAE,YAAY,CAAC,IAAI,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,EAAE,CAAC,CAAC;SAC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C9B,CAAC;YACH,CAAC;YAED,OAAO,CAAC,GAAG,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC;QACvB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Applying the migration directory to a D1 binding — as a factory.\n *\n * Provenance: converged from `test/integration/helpers/migrations.ts` in six repos\n * (AWS-AccessBridge, ChordDHT-Tracker, Durable-DAV, Durable-DAV-Router, Edge-Git,\n * Mail-Meow) and `test/helpers/migrations.ts` in two more (CalDAV-Bridge,\n * Edge-Sonic). All eight are the same file: a SQL splitter plus a range-addressed\n * `applyMigrations`.\n *\n * ### Why it is a factory and not a module\n *\n * Every source file hardcodes where the migrations live, either as a\n * `__INTEGRATION_MIGRATION_FILES__` binding injected by the Vitest config's\n * `define`, or as a path derived from `import.meta.url`. The kit cannot know\n * either, so the directory is an argument and the injection stays available as an\n * option. One call to `createMigrationHelper({ migrationsDir })` gives the consumer\n * the same helper their repo already has.\n *\n * ### What each source contributes\n *\n * - **Durable-DAV** — the trigger-aware splitter. `CREATE TRIGGER … BEGIN … END;`\n * bodies contain semicolons that must not split, and a naive splitter produces\n * statements SQLite rejects mid-migration. The BEGIN/END depth is tracked only\n * outside strings and comments, and the word *before* `TRIGGER` disambiguates\n * `CREATE TRIGGER` from a table called `trigger`. Durable-DAV also applies one\n * file per `batch()` and names the offending statement in the error, which is\n * the difference between \"0007 failed\" and a line number.\n * - **AWS-AccessBridge** — the once-per-database guard. D1 records which\n * migrations have run; this helper does the same, because `ALTER TABLE … ADD\n * COLUMN` is not idempotent in SQLite and re-running the bundle fails with\n * \"duplicate column name\". A `WeakMap` keyed on the binding is the right scope\n * because each test file gets its own database. AWS also keeps `next` out of the\n * line-comment branch, which never reads it, and preserves newlines inside block\n * comments so an error's line numbers still point at the file.\n * - **Edge-Sonic** — reading the directory off disk rather than a `define`\n * binding, because a test that names one hardcoded file cannot tell **a new\n * migration** from **an edit to an old one**, so it goes on passing through a\n * schema change that never reached production.\n *\n * ### The splitter is not here\n *\n * The statement splitter — with all of Durable-DAV's trigger-aware rules and its\n * comment-level history — lives once, in `@rexezuge/d1`. `@rexezuge/identity`'s\n * migration applier delegates to the same module, so the splitter cannot drift\n * between the suite helper and the production applier. The re-exports below keep\n * this file's public surface identical to the source repos'.\n *\n * ### The lock is asserted, not reimplemented\n *\n * D1 records applied migrations by *filename*, so an applied migration is immutable\n * in fact while being an ordinary text file in appearance. That fact lives in\n * `migrations/migrations.lock.json`, and the rules that check it live once, in\n * `scripts/verify-migrations.ts` — the same module the CI gate runs. This helper\n * deliberately does not parse the lock itself: a second implementation of a thing\n * already written is free to disagree with the first, and the two disagreeing would\n * leave a suite green against a lock CI rejects.\n *\n * ### Generic over the binding\n *\n * `D1DatabaseLike` is structural — `prepare`, and `batch` when the runtime has it\n * — so a fake D1 in a unit test, a real D1 in the workerd integration suite, and\n * Miniflare's D1 all satisfy it without an import of `@cloudflare/workers-types`.\n * `batch` is used when present (Durable-DAV's shape: one round trip per file, and\n * the failure names the file) and a sequential `prepare().run()` loop otherwise\n * (AWS's shape: works on a binding with no batch support).\n */\n\nimport { executableStatements, splitSql } from '@rexezuge/d1';\nimport { readdirSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\n/**\n * One migration file, as it is read.\n */\nexport interface MigrationFile {\n /** Bare filename, e.g. `0007_replication.sql`. */\n name: string;\n /** The file's full text. */\n sql: string;\n}\n\n/**\n * The subset of a D1 prepared statement this helper uses.\n */\nexport interface D1PreparedStatementLike {\n run(): Promise<unknown>;\n}\n\n/**\n * The subset of a D1 binding this helper uses.\n *\n * `batch` is optional because not every binding that can prepare a statement can\n * batch one; where it exists it is the better path, and where it does not the\n * sequential loop is equivalent for a migration whose statements are independent.\n */\nexport interface D1DatabaseLike {\n prepare(sql: string): D1PreparedStatementLike;\n batch?(statements: readonly D1PreparedStatementLike[]): Promise<unknown>;\n}\n\n/**\n * A closed range of migration files, by filename.\n *\n * Both ends inclusive, because \"up to and including 0006\" is the natural way to\n * seed a pre-migration database and then apply the migration under test.\n */\nexport interface MigrationRange {\n from?: string;\n to?: string;\n}\n\n/**\n * What `createMigrationHelper` accepts.\n */\nexport interface MigrationHelperOptions {\n /**\n * Directory holding the `.sql` files. Read top-level only, matching wrangler's\n * default `${migrationsDir}/*.sql`, so the helper describes exactly the set\n * wrangler will run.\n */\n readonly migrationsDir: string;\n /**\n * Migration files to use instead of reading `migrationsDir`.\n *\n * The escape hatch for a harness that embeds the SQL at build time. Same shape\n * as the `__INTEGRATION_MIGRATION_FILES__` binding the source repos inject.\n */\n readonly files?: readonly MigrationFile[];\n}\n\n/**\n * A bound migration helper.\n */\nexport interface MigrationHelper {\n /** Every migration, in apply order. */\n migrationFiles(): MigrationFile[];\n /** The filenames, in apply order. */\n migrationFileNames(): string[];\n /** The concatenation of every file, in apply order — what a fresh database becomes. */\n migrationSql(): string;\n /** One file's SQL, by name. \"What does *this* file say\", not \"what does the set say\". */\n migrationSqlOf(name: string): string;\n /** Split one file into statements, comments included. */\n splitSql(sql: string): string[];\n /** The statements of one file that SQLite will actually execute. */\n executableStatements(sql: string): string[];\n /**\n * Apply a range of migrations, at most once per database and range.\n *\n * Per file rather than one batch for everything, so a test can stop between\n * files: the identity-upgrade test needs to seed the *pre-0004* shape and then\n * apply 0004 to it.\n */\n applyMigrations(db: D1DatabaseLike, range?: MigrationRange): Promise<void>;\n}\n\n/**\n * Reads every `.sql` file in `dir`, in apply order.\n *\n * Sort is the filename sort D1 itself uses, rather than a numeric parse of the\n * prefix: wrangler hands the directory to SQLite in lexicographic order, so a\n * suite that reads it numerically disagrees with production on any prefix wider\n * than four digits.\n */\nexport function readMigrationFiles(dir: string): MigrationFile[] {\n const entries = readdirSync(dir, { withFileTypes: true });\n return entries\n .filter((entry) => entry.isFile() && entry.name.endsWith('.sql'))\n .map((entry) => ({ name: entry.name, sql: readFileSync(join(dir, entry.name), 'utf8') }))\n .sort((left, right) => left.name.localeCompare(right.name));\n}\n\n/**\n * Strip leading `--` and block comments, which the splitter folds into the\n * statement it then reports on.\n */\nfunction stripLeadingComments(statement: string): string {\n let out = statement;\n for (;;) {\n const next = out.replace(/^\\s*(?:--[^\\n]*\\n|\\/\\*[\\s\\S]*?\\*\\/)\\s*/, '');\n if (next === out) return out.trim();\n out = next;\n }\n}\n\n/** Re-exported for surface parity with the source repos — the rules live in @rexezuge/d1. */\nexport { executableStatements, splitSql };\n\n/**\n * Bind a migration directory into a helper.\n *\n * ```ts\n * const migrations = createMigrationHelper({ migrationsDir: path.join(REPO_ROOT, 'migrations') });\n * await migrations.applyMigrations(env.DB);\n * ```\n */\nexport function createMigrationHelper(options: MigrationHelperOptions): MigrationHelper {\n const files = options.files !== undefined ? [...options.files] : readMigrationFiles(options.migrationsDir);\n\n /**\n * Databases this helper has already migrated, keyed by the range applied.\n *\n * A `WeakMap` rather than a module-level `Set`, because the guard is per\n * binding: two databases in one suite each need the bundle applied once, and a\n * module-level set would silently skip the second.\n */\n const applied = new WeakMap<D1DatabaseLike, string>();\n\n const indexOf = (name: string | undefined, fallback: number): number => {\n if (name === undefined) return fallback;\n const found = files.findIndex((file) => file.name === name);\n if (found === -1) {\n throw new Error(`Unknown migration file: ${name}. Available: ${files.map((file) => file.name).join(', ')}`);\n }\n return found;\n };\n\n return {\n migrationFiles: () => files.map((file) => ({ ...file })),\n migrationFileNames: () => files.map((file) => file.name),\n migrationSql: () => files.map((file) => file.sql).join('\\n'),\n migrationSqlOf: (name: string) => {\n const file = files.find((candidate) => candidate.name === name);\n if (file === undefined) {\n throw new Error(`Unknown migration file: ${name}. Available: ${files.map((candidate) => candidate.name).join(', ')}`);\n }\n return file.sql;\n },\n splitSql,\n executableStatements,\n applyMigrations: async (db: D1DatabaseLike, range?: MigrationRange): Promise<void> => {\n const start = indexOf(range?.from, 0);\n const end = indexOf(range?.to, files.length - 1);\n const key = `${start}:${end}`;\n if (applied.get(db) === key) return;\n const applicable = files.slice(start, end + 1);\n\n for (const file of applicable) {\n const statements = executableStatements(file.sql);\n if (statements.length === 0) continue;\n\n if (typeof db.batch === 'function') {\n try {\n await db.batch(statements.map((sql) => db.prepare(sql)));\n } catch (error: unknown) {\n // A batch reports only the file's single failure, so name the statement:\n // a migration error that says nothing about which of its nine statements\n // broke is a migration error nobody fixes.\n throw new Error(\n `${file.name}: batch of ${statements.length} statements failed at ${stripLeadingComments(statements.at(-1) ?? '').slice(0, 200)}: ${\n error instanceof Error ? error.message : String(error)\n }`,\n { cause: error },\n );\n }\n continue;\n }\n\n for (const sql of statements) {\n await db.prepare(sql).run();\n }\n }\n\n applied.set(db, key);\n },\n };\n}\n"]}
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/test/integration-migrations.ts"],
4
+ "sourcesContent": ["/**\n * Applying the migration directory to a D1 binding — as a factory.\n *\n * Provenance: converged from `test/integration/helpers/migrations.ts` in six repos\n * (AWS-AccessBridge, ChordDHT-Tracker, Durable-DAV, Durable-DAV-Router, Edge-Git,\n * Mail-Meow) and `test/helpers/migrations.ts` in two more (CalDAV-Bridge,\n * Edge-Sonic). All eight are the same file: a SQL splitter plus a range-addressed\n * `applyMigrations`.\n *\n * ### Why it is a factory and not a module\n *\n * Every source file hardcodes where the migrations live, either as a\n * `__INTEGRATION_MIGRATION_FILES__` binding injected by the Vitest config's\n * `define`, or as a path derived from `import.meta.url`. The kit cannot know\n * either, so the directory is an argument and the injection stays available as an\n * option. One call to `createMigrationHelper({ migrationsDir })` gives the consumer\n * the same helper their repo already has.\n *\n * ### What each source contributes\n *\n * - **Durable-DAV** — the trigger-aware splitter. `CREATE TRIGGER … BEGIN … END;`\n * bodies contain semicolons that must not split, and a naive splitter produces\n * statements SQLite rejects mid-migration. The BEGIN/END depth is tracked only\n * outside strings and comments, and the word *before* `TRIGGER` disambiguates\n * `CREATE TRIGGER` from a table called `trigger`. Durable-DAV also applies one\n * file per `batch()` and names the offending statement in the error, which is\n * the difference between \"0007 failed\" and a line number.\n * - **AWS-AccessBridge** — the once-per-database guard. D1 records which\n * migrations have run; this helper does the same, because `ALTER TABLE … ADD\n * COLUMN` is not idempotent in SQLite and re-running the bundle fails with\n * \"duplicate column name\". A `WeakMap` keyed on the binding is the right scope\n * because each test file gets its own database. AWS also keeps `next` out of the\n * line-comment branch, which never reads it, and preserves newlines inside block\n * comments so an error's line numbers still point at the file.\n * - **Edge-Sonic** — reading the directory off disk rather than a `define`\n * binding, because a test that names one hardcoded file cannot tell **a new\n * migration** from **an edit to an old one**, so it goes on passing through a\n * schema change that never reached production.\n *\n * ### The splitter is not here\n *\n * The statement splitter — with all of Durable-DAV's trigger-aware rules and its\n * comment-level history — lives once, in `@rexezuge/d1`. `@rexezuge/identity`'s\n * migration applier delegates to the same module, so the splitter cannot drift\n * between the suite helper and the production applier. The re-exports below keep\n * this file's public surface identical to the source repos'.\n *\n * ### The lock is asserted, not reimplemented\n *\n * D1 records applied migrations by *filename*, so an applied migration is immutable\n * in fact while being an ordinary text file in appearance. That fact lives in\n * `migrations/migrations.lock.json`, and the rules that check it live once, in\n * `scripts/verify-migrations.ts` — the same module the CI gate runs. This helper\n * deliberately does not parse the lock itself: a second implementation of a thing\n * already written is free to disagree with the first, and the two disagreeing would\n * leave a suite green against a lock CI rejects.\n *\n * ### Generic over the binding\n *\n * `D1DatabaseLike` is structural — `prepare`, and `batch` when the runtime has it\n * — so a fake D1 in a unit test, a real D1 in the workerd integration suite, and\n * Miniflare's D1 all satisfy it without an import of `@cloudflare/workers-types`.\n * `batch` is used when present (Durable-DAV's shape: one round trip per file, and\n * the failure names the file) and a sequential `prepare().run()` loop otherwise\n * (AWS's shape: works on a binding with no batch support).\n */\n\nimport { executableStatements, splitSql } from '@rexezuge/d1';\nimport { readdirSync, readFileSync } from 'node:fs';\nimport path from 'node:path';\n\n/**\n * One migration file, as it is read.\n */\nexport interface MigrationFile {\n /**\n Bare filename, e.g. `0007_replication.sql`.\n */\n name: string;\n /**\n The file's full text.\n */\n sql: string;\n}\n\n/**\n * The subset of a D1 prepared statement this helper uses.\n */\nexport interface D1PreparedStatementLike {\n run(): Promise<unknown>;\n}\n\n/**\n * The subset of a D1 binding this helper uses.\n *\n * `batch` is optional because not every binding that can prepare a statement can\n * batch one; where it exists it is the better path, and where it does not the\n * sequential loop is equivalent for a migration whose statements are independent.\n */\nexport interface D1DatabaseLike {\n prepare(sql: string): D1PreparedStatementLike;\n batch?(statements: readonly D1PreparedStatementLike[]): Promise<unknown>;\n}\n\n/**\n * A closed range of migration files, by filename.\n *\n * Both ends inclusive, because \"up to and including 0006\" is the natural way to\n * seed a pre-migration database and then apply the migration under test.\n */\nexport interface MigrationRange {\n from?: string;\n to?: string;\n}\n\n/**\n * What `createMigrationHelper` accepts.\n */\nexport interface MigrationHelperOptions {\n /**\n * Directory holding the `.sql` files. Read top-level only, matching wrangler's\n * default `${migrationsDir}/*.sql`, so the helper describes exactly the set\n * wrangler will run.\n */\n readonly migrationsDir: string;\n /**\n * Migration files to use instead of reading `migrationsDir`.\n *\n * The escape hatch for a harness that embeds the SQL at build time. Same shape\n * as the `__INTEGRATION_MIGRATION_FILES__` binding the source repos inject.\n */\n readonly files?: readonly MigrationFile[];\n}\n\n/**\n * A bound migration helper.\n */\nexport interface MigrationHelper {\n /**\n Every migration, in apply order.\n */\n migrationFiles(): MigrationFile[];\n /**\n The filenames, in apply order.\n */\n migrationFileNames(): string[];\n /**\n The concatenation of every file, in apply order — what a fresh database becomes.\n */\n migrationSql(): string;\n /**\n One file's SQL, by name. \"What does *this* file say\", not \"what does the set say\".\n */\n migrationSqlOf(name: string): string;\n /**\n Split one file into statements, comments included.\n */\n splitSql(sql: string): string[];\n /**\n The statements of one file that SQLite will actually execute.\n */\n executableStatements(sql: string): string[];\n /**\n * Apply a range of migrations, at most once per database and range.\n *\n * Per file rather than one batch for everything, so a test can stop between\n * files: the identity-upgrade test needs to seed the *pre-0004* shape and then\n * apply 0004 to it.\n */\n applyMigrations(db: D1DatabaseLike, range?: MigrationRange): Promise<void>;\n}\n\n/**\n * Reads every `.sql` file in `dir`, in apply order.\n *\n * Sort is the filename sort D1 itself uses, rather than a numeric parse of the\n * prefix: wrangler hands the directory to SQLite in lexicographic order, so a\n * suite that reads it numerically disagrees with production on any prefix wider\n * than four digits.\n */\nexport function readMigrationFiles(dir: string): MigrationFile[] {\n const entries = readdirSync(dir, { withFileTypes: true });\n return entries\n .filter((entry) => entry.isFile() && entry.name.endsWith('.sql'))\n .map((entry) => ({ name: entry.name, sql: readFileSync(path.join(dir, entry.name), 'utf8') }))\n .sort((left, right) => left.name.localeCompare(right.name));\n}\n\n/**\n * Strip leading `--` and block comments, which the splitter folds into the\n * statement it then reports on.\n */\nfunction stripLeadingComments(statement: string): string {\n let out = statement;\n for (;;) {\n const next = out.replace(/^\\s*(?:--[^\\n]*\\n|\\/\\*[\\s\\S]*?\\*\\/)\\s*/, '');\n if (next === out) return out.trim();\n out = next;\n }\n}\n\n/**\nRe-exported for surface parity with the source repos — the rules live in @rexezuge/d1.\n*/\n\n/**\n * Bind a migration directory into a helper.\n *\n * ```ts\n * const migrations = createMigrationHelper({ migrationsDir: join(REPO_ROOT, 'migrations') });\n * await migrations.applyMigrations(env.DB);\n * ```\n */\nexport function createMigrationHelper(options: MigrationHelperOptions): MigrationHelper {\n const files = options.files === undefined ? readMigrationFiles(options.migrationsDir) : [...options.files];\n\n /**\n * Databases this helper has already migrated, keyed by the range applied.\n *\n * A `WeakMap` rather than a module-level `Set`, because the guard is per\n * binding: two databases in one suite each need the bundle applied once, and a\n * module-level set would silently skip the second.\n */\n const applied = new WeakMap<D1DatabaseLike, string>();\n\n const indexOf = (name: string | undefined, fallback: number): number => {\n if (name === undefined) return fallback;\n const found = files.findIndex((file) => file.name === name);\n if (found === -1) {\n throw new Error(`Unknown migration file: ${name}. Available: ${files.map((file) => file.name).join(', ')}`);\n }\n return found;\n };\n\n return {\n migrationFiles: () => files.map((file) => ({ ...file })),\n migrationFileNames: () => files.map((file) => file.name),\n migrationSql: () => files.map((file) => file.sql).join('\\n'),\n migrationSqlOf: (name: string) => {\n const file = files.find((candidate) => candidate.name === name);\n if (file === undefined) {\n throw new Error(`Unknown migration file: ${name}. Available: ${files.map((candidate) => candidate.name).join(', ')}`);\n }\n return file.sql;\n },\n splitSql,\n executableStatements,\n applyMigrations: async (db: D1DatabaseLike, range?: MigrationRange): Promise<void> => {\n const start = indexOf(range?.from, 0);\n const end = indexOf(range?.to, files.length - 1);\n const key = `${start}:${end}`;\n if (applied.get(db) === key) return;\n const applicable = files.slice(start, end + 1);\n\n for (const file of applicable) {\n const statements = executableStatements(file.sql);\n if (statements.length === 0) continue;\n\n if (typeof db.batch === 'function') {\n try {\n await db.batch(statements.map((sql) => db.prepare(sql)));\n } catch (error: unknown) {\n // A batch reports only the file's single failure, so name the statement:\n // a migration error that says nothing about which of its nine statements\n // broke is a migration error nobody fixes.\n throw new Error(\n `${file.name}: batch of ${statements.length} statements failed at ${stripLeadingComments(statements.at(-1) ?? '').slice(0, 200)}: ${\n error instanceof Error ? error.message : String(error)\n }`,\n { cause: error },\n );\n }\n continue;\n }\n\n for (const sql of statements) {\n await db.prepare(sql).run();\n }\n }\n\n applied.set(db, key);\n },\n };\n}\n\nexport { executableStatements, splitSql } from '@rexezuge/d1';\n"],
5
+ "mappings": "AAmEA,OAAS,wBAAAA,EAAsB,YAAAC,MAAgB,eAC/C,OAAS,eAAAC,EAAa,gBAAAC,MAAoB,UAC1C,OAAOC,MAAU,YA+GX,SAAUC,EAAmBC,EAAW,CAE5C,OADgBJ,EAAYI,EAAK,CAAE,cAAe,EAAI,CAAE,EAErD,OAAQC,GAAUA,EAAM,OAAM,GAAMA,EAAM,KAAK,SAAS,MAAM,CAAC,EAC/D,IAAKA,IAAW,CAAE,KAAMA,EAAM,KAAM,IAAKJ,EAAaC,EAAK,KAAKE,EAAKC,EAAM,IAAI,EAAG,MAAM,CAAC,EAAG,EAC5F,KAAK,CAACC,EAAMC,IAAUD,EAAK,KAAK,cAAcC,EAAM,IAAI,CAAC,CAC9D,CAMA,SAASC,EAAqBC,EAAiB,CAC7C,IAAIC,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AAK,OAC7B,MAAMC,EAAab,EAAM,MAAMU,EAAOC,EAAM,CAAC,EAE7C,UAAWL,KAAQO,EAAY,CAC7B,MAAMC,EAAa9B,EAAqBsB,EAAK,GAAG,EAChD,GAAIQ,EAAW,SAAW,EAE1B,IAAI,OAAON,EAAG,OAAU,WAAY,CAClC,GAAI,CACF,MAAMA,EAAG,MAAMM,EAAW,IAAKC,GAAQP,EAAG,QAAQO,CAAG,CAAC,CAAC,CACzD,OAASC,EAAgB,CAIvB,MAAM,IAAI,MACR,GAAGV,EAAK,IAAI,cAAcQ,EAAW,MAAM,yBAAyBpB,EAAqBoB,EAAW,GAAG,EAAE,GAAK,EAAE,EAAE,MAAM,EAAG,GAAG,CAAC,KAC7HE,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CACvD,GACA,CAAE,MAAOA,CAAK,CAAE,CAEpB,CACA,QACF,CAEA,UAAWD,KAAOD,EAChB,MAAMN,EAAG,QAAQO,CAAG,EAAE,IAAG,EAE7B,CAEAd,EAAQ,IAAIO,EAAII,CAAG,CACrB,EAEJ,CAEA,OAAS,wBAAA5B,EAAsB,YAAAC,MAAgB",
6
+ "names": ["executableStatements", "splitSql", "readdirSync", "readFileSync", "path", "readMigrationFiles", "dir", "entry", "left", "right", "stripLeadingComments", "statement", "out", "next", "createMigrationHelper", "options", "files", "applied", "indexOf", "name", "fallback", "found", "file", "candidate", "db", "range", "start", "end", "key", "applicable", "statements", "sql", "error"]
7
+ }