@rexezuge/tooling 1.9.1 → 1.9.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/eslint.d.ts.map +1 -1
- package/dist/eslint.js +1 -1
- package/dist/eslint.js.map +2 -2
- package/dist/scripts/check-god-files.js +2 -2
- package/dist/scripts/check-god-files.js.map +3 -3
- package/dist/scripts/lib/entrypoint.d.ts +27 -0
- package/dist/scripts/lib/entrypoint.d.ts.map +1 -0
- package/dist/scripts/lib/entrypoint.js +1 -0
- package/dist/scripts/lib/entrypoint.js.map +7 -0
- package/dist/scripts/spa-shell.js +2 -2
- package/dist/scripts/spa-shell.js.map +3 -3
- package/dist/scripts/validate-locales.js +5 -5
- package/dist/scripts/validate-locales.js.map +3 -3
- package/dist/scripts/verify-migrations.js +2 -2
- package/dist/scripts/verify-migrations.js.map +3 -3
- package/dist/scripts/wrangler-config/patches.d.ts.map +1 -1
- package/dist/scripts/wrangler-config/patches.js +3 -3
- package/dist/scripts/wrangler-config/patches.js.map +3 -3
- package/dist/scripts/wrangler-config/resources.d.ts +17 -7
- package/dist/scripts/wrangler-config/resources.d.ts.map +1 -1
- package/dist/scripts/wrangler-config/resources.js +1 -1
- package/dist/scripts/wrangler-config/resources.js.map +3 -3
- package/dist/scripts/wrangler-config/types.d.ts +3 -2
- package/dist/scripts/wrangler-config/types.d.ts.map +1 -1
- package/dist/scripts/wrangler-config/types.js.map +2 -2
- package/dist/vite.d.ts +21 -0
- package/dist/vite.d.ts.map +1 -1
- package/dist/vite.js +3 -3
- package/dist/vite.js.map +2 -2
- package/package.json +3 -3
- package/src/eslint.ts +9 -1
- package/src/scripts/check-god-files.ts +2 -2
- package/src/scripts/lib/entrypoint.test.ts +60 -0
- package/src/scripts/lib/entrypoint.ts +39 -0
- package/src/scripts/spa-shell.ts +2 -2
- package/src/scripts/validate-locales.ts +2 -2
- package/src/scripts/verify-migrations.ts +2 -2
- package/src/scripts/wrangler-config/patches.ts +11 -2
- package/src/scripts/wrangler-config/resources.test.ts +49 -0
- package/src/scripts/wrangler-config/resources.ts +38 -16
- package/src/scripts/wrangler-config/types.ts +3 -2
- package/src/vite.ts +31 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
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": "+EAcA,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,CAFgBC,EAAAF,EAAA,WAIV,SAAUG,GAAe,CAC7B,OAAOR,EAA2BC,EAAY,CAAC,KAAM,OAAQ,QAAQ,CAAC,EAAG,yBAAyB,CACpG,CAFgBM,EAAAC,EAAA,mBAYV,SAAUC,EAAiBC,EAAoB,CACnD,IAAIJ,EAAWE,EAAe,EAAG,KAAMG,GAAcA,EAAU,OAASD,CAAY,EAChFE,EAAU,GACVN,IAAa,SACf,QAAQ,IAAI,yBAAyBI,CAAY,EAAE,EACnDT,EAAY,CAAC,KAAM,SAAUS,CAAY,CAAC,EAC1CJ,EAAWE,EAAe,EAAG,KAAMG,GAAcA,EAAU,OAASD,CAAY,EAChFE,EAAU,IAEZ,MAAMC,EAAaP,IAAa,OAAY,OAAYD,EAAQC,CAAQ,EACxE,GAAIO,IAAe,QAAaA,IAAe,GAC7C,MAAM,IAAI,MAAM,yCAAyCH,CAAY,GAAG,EAE1E,MAAO,CAAE,GAAIG,EAAY,QAAAD,CAAO,CAClC,CAdgBL,EAAAE,EAAA,oBAgBV,SAAUK,GAAgB,CAC9B,OAAOd,EAA4BC,EAAY,CAAC,KAAM,YAAa,MAAM,CAAC,EAAG,4BAA4B,CAC3G,CAFgBM,EAAAO,EAAA,
|
|
6
|
-
"names": ["parse", "parseWranglerTableRows", "DEFAULT_HEX_ID", "DEFAULT_KV_NAMESPACE_NAMES", "DEFAULT_SECRET_STORE_NAME", "DEFAULT_UUID", "DEFAULT_WORKER_NAME", "VECTORIZE_DIMENSIONS", "parseJsonArray", "runWrangler", "readConfig", "writeConfig", "writeConfigValue", "getD1Id", "database", "__name", "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"]
|
|
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/**\n * The namespace name a binding's namespace is created under.\n *\n * `namespaceNames` is the binding → namespace map, defaulting to the kit's\n * `DEFAULT_KV_NAMESPACE_NAMES`. A consumer whose namespaces predate that convention\n * passes its own, so provisioning finds the namespace that already holds the data\n * instead of creating an empty one beside it and binding the worker to the new one.\n */\nexport function getKVNamespaceName(\n config: WranglerConfig,\n binding: string,\n namespaceNames: Record<string, string> = DEFAULT_KV_NAMESPACE_NAMES,\n): string {\n return namespaceNames[binding] ?? `${config.name ?? DEFAULT_WORKER_NAME}-${binding.toLowerCase()}`;\n}\n\nexport function ensureKVNamespace(\n config: WranglerConfig,\n binding: string,\n namespaceNames: Record<string, string> = DEFAULT_KV_NAMESPACE_NAMES,\n): Provisioned {\n const namespaceName = getKVNamespaceName(config, binding, namespaceNames);\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(namespaceNames: Record<string, string> = DEFAULT_KV_NAMESPACE_NAMES): string[] {\n return Object.keys(namespaceNames);\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(\n content: string,\n config: WranglerConfig,\n namespaceNames: Record<string, string> = DEFAULT_KV_NAMESPACE_NAMES,\n): string {\n const existing = new Set((config.kv_namespaces ?? []).map((namespace) => namespace.binding).filter((binding) => binding !== undefined));\n const missing = getRequiredKvBindings(namespaceNames).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[], namespaceNames: Record<string, 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, namespaceNames);\n const namespaceName = getKVNamespaceName(config, namespace.binding, namespaceNames);\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 * `namespaceNames` is the binding → namespace map KV provisioning reconciles\n * against, defaulting to the kit's `DEFAULT_KV_NAMESPACE_NAMES`; a consumer whose\n * namespaces were named before that convention passes its own so the existing\n * namespace is found instead of a second empty one being created.\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(namespaceNames: Record<string, string> = DEFAULT_KV_NAMESPACE_NAMES): string[] {\n const created: string[] = [];\n let { content, config } = readConfig();\n\n content = ensureRequiredKvBindings(content, config, namespaceNames);\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, namespaceNames);\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": "+EAcA,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,CAFgBC,EAAAF,EAAA,WAIV,SAAUG,GAAe,CAC7B,OAAOR,EAA2BC,EAAY,CAAC,KAAM,OAAQ,QAAQ,CAAC,EAAG,yBAAyB,CACpG,CAFgBM,EAAAC,EAAA,mBAYV,SAAUC,EAAiBC,EAAoB,CACnD,IAAIJ,EAAWE,EAAe,EAAG,KAAMG,GAAcA,EAAU,OAASD,CAAY,EAChFE,EAAU,GACVN,IAAa,SACf,QAAQ,IAAI,yBAAyBI,CAAY,EAAE,EACnDT,EAAY,CAAC,KAAM,SAAUS,CAAY,CAAC,EAC1CJ,EAAWE,EAAe,EAAG,KAAMG,GAAcA,EAAU,OAASD,CAAY,EAChFE,EAAU,IAEZ,MAAMC,EAAaP,IAAa,OAAY,OAAYD,EAAQC,CAAQ,EACxE,GAAIO,IAAe,QAAaA,IAAe,GAC7C,MAAM,IAAI,MAAM,yCAAyCH,CAAY,GAAG,EAE1E,MAAO,CAAE,GAAIG,EAAY,QAAAD,CAAO,CAClC,CAdgBL,EAAAE,EAAA,oBAgBV,SAAUK,GAAgB,CAC9B,OAAOd,EAA4BC,EAAY,CAAC,KAAM,YAAa,M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AO,EACtB,UAAWgB,KAAaC,EAAa3B,CAAM,EACrCyB,EAAYC,CAAS,GACvB9B,EAAQ,KAAK,SAAS8B,CAAS,EAAE,EAOrC,UAAWzB,KAAWD,EAAO,WAAa,CAAA,EACxCgC,EAAqB/B,EAAQ,WAAYlB,CAAoB,EAG/D,OAAOa,CACT,CArCgBL,EAAAsD,EAAA",
|
|
6
|
+
"names": ["parse", "parseWranglerTableRows", "DEFAULT_HEX_ID", "DEFAULT_KV_NAMESPACE_NAMES", "DEFAULT_SECRET_STORE_NAME", "DEFAULT_UUID", "DEFAULT_WORKER_NAME", "VECTORIZE_DIMENSIONS", "parseJsonArray", "runWrangler", "readConfig", "writeConfig", "writeConfigValue", "getD1Id", "database", "__name", "listD1Databases", "ensureD1Database", "databaseName", "candidate", "created", "databaseId", "listKVNamespaces", "getKVNamespaceName", "config", "binding", "namespaceNames", "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
7
|
}
|
|
@@ -45,8 +45,9 @@ export declare const DEFAULT_WORKER_NAME: string;
|
|
|
45
45
|
/**
|
|
46
46
|
* KV bindings a deployment always needs, and the namespace each maps to.
|
|
47
47
|
*
|
|
48
|
-
*
|
|
49
|
-
*
|
|
48
|
+
* The default for `provisionWranglerResources`'s `namespaceNames` argument: a
|
|
49
|
+
* consumer whose worker has no cache binding passes an empty map, and one whose
|
|
50
|
+
* namespaces predate this convention passes its own map.
|
|
50
51
|
*/
|
|
51
52
|
export declare const DEFAULT_KV_NAMESPACE_NAMES: Record<string, string>;
|
|
52
53
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/scripts/wrangler-config/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAIH;;EAEE;AACF,eAAO,MAAM,WAAW,QAAoF,CAAC;AAE7G;;EAEE;AACF,eAAO,MAAM,aAAa,QAAwG,CAAC;AAEnI;;;;;;GAMG;AACH,eAAO,MAAM,YAAY,yCAAyC,CAAC;AAEnE;;EAEE;AACF,eAAO,MAAM,cAAc,qCAAqC,CAAC;AAEjE;;EAEE;AACF,eAAO,MAAM,yBAAyB,YAAY,CAAC;AAEnD;;;;;GAKG;AACH,eAAO,MAAM,mBAAmB,QAAqD,CAAC;AAEtF
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/scripts/wrangler-config/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAIH;;EAEE;AACF,eAAO,MAAM,WAAW,QAAoF,CAAC;AAE7G;;EAEE;AACF,eAAO,MAAM,aAAa,QAAwG,CAAC;AAEnI;;;;;;GAMG;AACH,eAAO,MAAM,YAAY,yCAAyC,CAAC;AAEnE;;EAEE;AACF,eAAO,MAAM,cAAc,qCAAqC,CAAC;AAEjE;;EAEE;AACF,eAAO,MAAM,yBAAyB,YAAY,CAAC;AAEnD;;;;;GAKG;AACH,eAAO,MAAM,mBAAmB,QAAqD,CAAC;AAEtF;;;;;;GAMG;AACH,eAAO,MAAM,0BAA0B,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAE7D,CAAC;AAEF;;EAEE;AACF,eAAO,MAAM,oBAAoB,OAAO,CAAC;AAEzC;;;;;;GAMG;AACH,MAAM,WAAW,cAAc;IAC7B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC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AE,MAAM,CAAC;CACZ"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
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 *
|
|
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,
|
|
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 * The default for `provisionWranglerResources`'s `namespaceNames` argument: a\n * consumer whose worker has no cache binding passes an empty map, and one whose\n * namespaces predate this convention passes its own map.\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,YAS7DC,EAAqD,CAChE,MAAO,GAAGD,CAAmB,UAMlBE,EAAuB",
|
|
6
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
7
|
}
|
package/dist/vite.d.ts
CHANGED
|
@@ -38,6 +38,16 @@ export interface ProxyEntry {
|
|
|
38
38
|
readonly bypass?: (request: {
|
|
39
39
|
headers: Record<string, string | string[] | undefined>;
|
|
40
40
|
}) => string | undefined;
|
|
41
|
+
/**
|
|
42
|
+
* Proxy WebSocket upgrades on this path.
|
|
43
|
+
*
|
|
44
|
+
* Vite's `server.proxy` needs `ws: true` for an entry that carries a
|
|
45
|
+
* WebSocket, and the entry has no other way to say so: without it the
|
|
46
|
+
* handshake is proxied as an ordinary request and the socket never opens.
|
|
47
|
+
* A consumer with a live-update or realtime endpoint therefore could not
|
|
48
|
+
* express its dev proxy through this table at all.
|
|
49
|
+
*/
|
|
50
|
+
readonly ws?: boolean;
|
|
41
51
|
}
|
|
42
52
|
/**
|
|
43
53
|
* Where the SPA's built `index.html` is copied to, and under what module name.
|
|
@@ -66,6 +76,17 @@ export interface SpaShellTarget {
|
|
|
66
76
|
*
|
|
67
77
|
* Defaults to `dist/index.html` under the same root. Vite's `closeBundle` runs
|
|
68
78
|
* after the bundle is written, so this is the file the build just produced.
|
|
79
|
+
*
|
|
80
|
+
* A **relative** path resolves against {@link SpaShellTarget.root}, exactly as
|
|
81
|
+
* {@link SpaShellTarget.path} does. It used to resolve against the process's
|
|
82
|
+
* working directory, which under `pnpm --filter … build` is the *package*
|
|
83
|
+
* directory rather than the repository root — so a consumer naming the file
|
|
84
|
+
* relative to the root it had just been given wrote nowhere, and the plugin
|
|
85
|
+
* reported "dist/index.html not found, skipping". That message is also what a
|
|
86
|
+
* genuinely fresh checkout prints on its first build, so the two are
|
|
87
|
+
* indistinguishable in the log, and the worker keeps serving the *previous*
|
|
88
|
+
* shell: the SPA ships yesterday's JavaScript with nothing in the build log
|
|
89
|
+
* to explain it.
|
|
69
90
|
*/
|
|
70
91
|
readonly distIndex?: string | URL;
|
|
71
92
|
}
|
package/dist/vite.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vite.d.ts","sourceRoot":"","sources":["../src/vite.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAKH,OAAO,EAAgB,KAAK,MAAM,EAAE,KAAK,cAAc,EAAE,MAAM,eAAe,CAAC;AAE/E;;GAEG;AACH,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,YAAY,CAAC,EAAE,OAAO,CAAC;IAChC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,CAAA;KAAE,KAAK,MAAM,GAAG,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"vite.d.ts","sourceRoot":"","sources":["../src/vite.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAKH,OAAO,EAAgB,KAAK,MAAM,EAAE,KAAK,cAAc,EAAE,MAAM,eAAe,CAAC;AAE/E;;GAEG;AACH,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QA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+1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
export const SPA_HTML: string = ${JSON.stringify(
|
|
3
|
-
`;p(m.dirname(r),{recursive:!0}),h(r,u)}}}t(
|
|
1
|
+
var f=Object.defineProperty;var t=(e,n)=>f(e,"name",{value:n,configurable:!0});import{existsSync as l,mkdirSync as p,readFileSync as c,writeFileSync as h}from"node:fs";import m from"node:path";import{fileURLToPath as i,pathToFileURL as x}from"node:url";import{defineConfig as y}from"vitest/config";function d(e){return e instanceof URL?e:e.startsWith("file:")?new URL(e):x(e)}t(d,"toUrl");function a(e){const n=d(e);return n.href.endsWith("/")?n:new URL(`${n.href}/`)}t(a,"toDirUrl");function U(e){return{name:"spa-shell-embed",closeBundle(){const n=a(e.root??process.cwd()),r=i(new URL(e.path,n)),o=e.distIndex===void 0?i(new URL("dist/index.html",n)):i(typeof e.distIndex=="string"&&!/^[a-z][a-z\d+\-.]*:/i.test(e.distIndex)?new URL(e.distIndex,n):d(e.distIndex));if(!l(o)){console.warn("spa-shell-embed: dist/index.html not found, skipping");return}const s=c(o,"utf8"),u=`// Auto-generated by Vite build plugin - DO NOT EDIT.
|
|
2
|
+
export const SPA_HTML: string = ${JSON.stringify(s)};
|
|
3
|
+
`;p(m.dirname(r),{recursive:!0}),h(r,u)}}}t(U,"spaShellEmbedPlugin");function g(e={}){const n=[...e.plugins??[]];return e.spaShell!==void 0&&n.push(U(e.spaShell)),y({...n.length>0&&{plugins:n},...e.proxy!==void 0&&{server:{proxy:{...e.proxy}}},build:{outDir:e.outDir??"dist",emptyOutDir:!0}})}t(g,"defineWebViteConfig");export{g as defineWebViteConfig,U as spaShellEmbedPlugin};
|
package/dist/vite.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/vite.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * The SPA's Vite config.\n *\n * Provenance: converged from the `apps/web/vite.config.ts` of the eight repos\n * that build a Vite SPA. They are one file with three variables: the plugin list\n * (`@vitejs/plugin-react` + `@tailwindcss/vite`), the dev-server proxy target,\n * and the `spa-shell-embed` plugin that copies `dist/index.html` into\n * `apps/api/src/generated/spa-shell.ts`.\n *\n * Canonical decisions:\n *\n * 1. **The plugins are passed in, not imported.** The kit stays zero-dependency:\n * `react`, `@vitejs/plugin-react` and `@tailwindcss/vite` belong to the app\n * that uses them, and importing them here would make the tooling package\n * undownloadable for a consumer without a React SPA.\n * 2. **The `spa-shell-embed` hook stays per-repo, and is passed in.** It is the\n * one genuinely repo-specific piece: each repo names its own worker and its\n * own generated-module path. What the kit provides is the *contract* — see\n * `spaShellEmbedPlugin`, which is the converged body of all eight copies.\n * 3. **`server.proxy` is data, not code.** The paths differ per repo\n * (`/user` + `/rest` in Edge-Sonic, `/api` in CalDAV-Bridge, `/tracker` in\n * ChordDHT-Tracker) but the shape never does, so it is an option with a\n * default.\n * 4. **`build.emptyOutDir: true`** is the default, because a stale asset in\n * `dist/` is served as a live bundle — the same half-refreshed build\n * `scripts/verify-spa-shell.ts` rejects.\n *\n * The consumer's `apps/web/vite.config.ts` becomes a handful of lines — see the\n * README.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport { defineConfig, type Plugin, type ViteUserConfig } from 'vitest/config';\n\n/**\n * One dev-server proxy entry, as Vite's `server.proxy` accepts it.\n */\nexport interface ProxyEntry {\n readonly target: string;\n readonly changeOrigin?: boolean;\n readonly bypass?: (request: { headers: Record<string, string | string[] | undefined> }) => string | undefined;\n}\n\n/**\n * Where the SPA's built `index.html` is copied to, and under what module name.\n */\nexport interface SpaShellTarget {\n /**\n * Path of the generated module, relative to the repository root.\n *\n * `apps/api/src/generated/spa-shell.ts` in every repo that embeds a shell; the\n * parameter exists because the path is the one thing that genuinely differs.\n */\n readonly path: string;\n /**\n * The repository root the path is resolved against, as a file URL or a path.\n *\n * Defaults to the directory the build runs in (`process.cwd()`), which is the\n * repo root when the build is `pnpm --filter @scope/web build`. Passed in by the\n * Vite config, not derived from `import.meta.url`: this plugin object is created\n * inside the kit's own module, so a URL relative to it points into\n * `node_modules/@rexezuge/tooling` and writes the shell somewhere no compiler\n * will ever look.\n */\n readonly root?: string | URL;\n /**\n * The built `index.html`, as a path or file URL.\n *\n * Defaults to `dist/index.html` under the same root. Vite's `closeBundle` runs\n * after the bundle is written, so this is the file the build just produced.\n */\n readonly distIndex?: string | URL;\n}\n\n/**\n * What `defineWebViteConfig` accepts.\n */\nexport interface WebViteConfigOptions {\n /**\n * The SPA's plugins — `react()`, `tailwindcss()`, and anything else the app\n * needs. Applied before the spa-shell plugin so the shell is written after the\n * bundle exists.\n */\n readonly plugins?: readonly Plugin[];\n /**\n * Dev-server proxy entries. Keyed by path prefix.\n */\n readonly proxy?: Readonly<Record<string, ProxyEntry>>;\n /**\n * Where the built shell is embedded. Omit to skip the embedding entirely.\n */\n readonly spaShell?: SpaShellTarget;\n /**\n * The build output directory.\n */\n readonly outDir?: string;\n /**\n * The directory this config is resolved from, as a file URL. Defaults to the\n * caller's location.\n */\n readonly root?: string;\n}\n\n/**\n * The `spa-shell-embed` plugin, converged from all eight copies.\n *\n * It exists because the API worker serves `SPA_HTML` from a module in its own\n * source tree, and both that module and `dist/` are gitignored — so a fresh\n * clone gets an empty stub from `postinstall` and every `GET /` returns a blank\n * page until someone runs a build. This plugin is what makes the build write the\n * real artefact, and `scripts/verify-spa-shell.ts` is what refuses to deploy\n * without it.\n *\n * Written as a factory rather than inlined so the exit conditions are in one\n * place: the `closeBundle` hook runs on every build, including the ones where\n * `dist/index.html` was never produced, and a plugin that throws there fails\n * builds that legitimately emit nothing.\n */\n/**\n * Normalise a path-or-URL option to a URL, so `new URL(...)` can be used on it.\n *\n * Small, and here because two options accept either form: a path is what a consumer\n * naturally writes in a config, and a URL is what `import.meta.url` hands them.\n * Accepting both is one line and saves a `fileURLToPath` at every call site.\n */\n/**\n * Normalise `string | URL` to a `URL`.\n *\n * A string that is **already a file URL** must be parsed, not converted:\n * `pathToFileURL('file:///srv/app')` treats its argument as a filesystem path\n * and produces `file:///<cwd>/file:/srv/app`, so every path built on top of it\n * silently resolves into a directory named after the scheme.\n *\n * The failure this prevented is not loud. `spaShellEmbedPlugin` then reports\n * \"dist/index.html not found, skipping\" — which is also what a genuinely fresh\n * checkout prints on its first build — and the consumer's worker keeps serving\n * the *previous* shell, so the SPA ships yesterday's JavaScript with no error\n * anywhere in the build log. Both `root` and `distIndex` are documented as\n * \"a file URL or a path\", and `new URL('.', import.meta.url).href` — the shape\n * every config file reaches for first — is a file-URL string, so this is the\n * path most callers take.\n */\nfunction toUrl(value: string | URL): URL {\n if (value instanceof URL) return value;\n return value.startsWith('file:') ? new URL(value) : pathToFileURL(value);\n}\n\n/**\n * The same, as a **directory** URL — with the trailing separator `new URL(rel, base)`\n * needs.\n *\n * `new URL('apps/api/x.ts', 'file:///repo')` resolves to `/apps/api/x.ts`, silently\n * dropping the base. The base has to end in a separator, and a path from\n * `process.cwd()` never does, so this is where the plugin would otherwise write the\n * shell into the filesystem root.\n */\nfunction toDirUrl(value: string | URL): URL {\n const url = toUrl(value);\n return url.href.endsWith('/') ? url : new URL(`${url.href}/`);\n}\n\nexport function spaShellEmbedPlugin(target: SpaShellTarget): Plugin & { closeBundle: () => void } {\n return {\n name: 'spa-shell-embed',\n closeBundle() {\n // Resolved from the directory the build runs in, never from this module's own\n // URL: the plugin object is created here but executes in the consumer's Vite\n // process, and `new URL(path, import.meta.url)` would resolve against\n // `node_modules/@rexezuge/tooling`. `process.cwd()` is the repo root for\n // `pnpm --filter @scope/web build`, which is how every consumer runs it.\n const root = toDirUrl(target.root ?? process.cwd());\n const outputPath = fileURLToPath(new URL(target.path, root));\n const indexPath =\n target.distIndex === undefined ? fileURLToPath(new URL('dist/index.html', root)) : fileURLToPath(toUrl(target.distIndex));\n\n if (!existsSync(indexPath)) {\n console.warn('spa-shell-embed: dist/index.html not found, skipping');\n return;\n }\n\n const html = readFileSync(indexPath, 'utf8');\n const output = `// Auto-generated by Vite build plugin - DO NOT EDIT.\\nexport const SPA_HTML: string = ${JSON.stringify(html)};\\n`;\n\n mkdirSync(path.dirname(outputPath), { recursive: true });\n writeFileSync(outputPath, output);\n },\n };\n}\n\n/**\n * Build the SPA's Vite config.\n *\n * ```ts\n * // apps/web/vite.config.ts\n * import react from '@vitejs/plugin-react';\n * import { defineWebViteConfig, spaShellEmbedPlugin } from '@rexezuge/tooling/vite';\n *\n * export default defineWebViteConfig({\n * plugins: [react()],\n * proxy: { '/user': { target: 'http://localhost:8787', changeOrigin: true } },\n * spaShell: { path: '../../apps/api/src/generated/spa-shell.ts' },\n * });\n * ```\n */\nexport function defineWebViteConfig(options: WebViteConfigOptions = {}): ViteUserConfig {\n const plugins: Plugin[] = [...(options.plugins ?? [])];\n if (options.spaShell !== undefined) {\n plugins.push(spaShellEmbedPlugin(options.spaShell));\n }\n\n return defineConfig({\n ...(plugins.length > 0 && { plugins }),\n ...(options.proxy !== undefined && { server: { proxy: { ...options.proxy } } }),\n build: {\n outDir: options.outDir ?? 'dist',\n emptyOutDir: true,\n },\n });\n}\n"],
|
|
5
|
-
"mappings": "+EA+BA,OAAS,cAAAA,EAAY,aAAAC,EAAW,gBAAAC,EAAc,iBAAAC,MAAqB,UACnE,OAAOC,MAAU,YACjB,OAAS,iBAAAC,EAAe,iBAAAC,MAAqB,WAC7C,OAAS,gBAAAC,MAAsD,
|
|
4
|
+
"sourcesContent": ["/**\n * The SPA's Vite config.\n *\n * Provenance: converged from the `apps/web/vite.config.ts` of the eight repos\n * that build a Vite SPA. They are one file with three variables: the plugin list\n * (`@vitejs/plugin-react` + `@tailwindcss/vite`), the dev-server proxy target,\n * and the `spa-shell-embed` plugin that copies `dist/index.html` into\n * `apps/api/src/generated/spa-shell.ts`.\n *\n * Canonical decisions:\n *\n * 1. **The plugins are passed in, not imported.** The kit stays zero-dependency:\n * `react`, `@vitejs/plugin-react` and `@tailwindcss/vite` belong to the app\n * that uses them, and importing them here would make the tooling package\n * undownloadable for a consumer without a React SPA.\n * 2. **The `spa-shell-embed` hook stays per-repo, and is passed in.** It is the\n * one genuinely repo-specific piece: each repo names its own worker and its\n * own generated-module path. What the kit provides is the *contract* — see\n * `spaShellEmbedPlugin`, which is the converged body of all eight copies.\n * 3. **`server.proxy` is data, not code.** The paths differ per repo\n * (`/user` + `/rest` in Edge-Sonic, `/api` in CalDAV-Bridge, `/tracker` in\n * ChordDHT-Tracker) but the shape never does, so it is an option with a\n * default.\n * 4. **`build.emptyOutDir: true`** is the default, because a stale asset in\n * `dist/` is served as a live bundle — the same half-refreshed build\n * `scripts/verify-spa-shell.ts` rejects.\n *\n * The consumer's `apps/web/vite.config.ts` becomes a handful of lines — see the\n * README.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport { defineConfig, type Plugin, type ViteUserConfig } from 'vitest/config';\n\n/**\n * One dev-server proxy entry, as Vite's `server.proxy` accepts it.\n */\nexport interface ProxyEntry {\n readonly target: string;\n readonly changeOrigin?: boolean;\n readonly bypass?: (request: { headers: Record<string, string | string[] | undefined> }) => string | undefined;\n /**\n * Proxy WebSocket upgrades on this path.\n *\n * Vite's `server.proxy` needs `ws: true` for an entry that carries a\n * WebSocket, and the entry has no other way to say so: without it the\n * handshake is proxied as an ordinary request and the socket never opens.\n * A consumer with a live-update or realtime endpoint therefore could not\n * express its dev proxy through this table at all.\n */\n readonly ws?: boolean;\n}\n\n/**\n * Where the SPA's built `index.html` is copied to, and under what module name.\n */\nexport interface SpaShellTarget {\n /**\n * Path of the generated module, relative to the repository root.\n *\n * `apps/api/src/generated/spa-shell.ts` in every repo that embeds a shell; the\n * parameter exists because the path is the one thing that genuinely differs.\n */\n readonly path: string;\n /**\n * The repository root the path is resolved against, as a file URL or a path.\n *\n * Defaults to the directory the build runs in (`process.cwd()`), which is the\n * repo root when the build is `pnpm --filter @scope/web build`. Passed in by the\n * Vite config, not derived from `import.meta.url`: this plugin object is created\n * inside the kit's own module, so a URL relative to it points into\n * `node_modules/@rexezuge/tooling` and writes the shell somewhere no compiler\n * will ever look.\n */\n readonly root?: string | URL;\n /**\n * The built `index.html`, as a path or file URL.\n *\n * Defaults to `dist/index.html` under the same root. Vite's `closeBundle` runs\n * after the bundle is written, so this is the file the build just produced.\n *\n * A **relative** path resolves against {@link SpaShellTarget.root}, exactly as\n * {@link SpaShellTarget.path} does. It used to resolve against the process's\n * working directory, which under `pnpm --filter … build` is the *package*\n * directory rather than the repository root — so a consumer naming the file\n * relative to the root it had just been given wrote nowhere, and the plugin\n * reported \"dist/index.html not found, skipping\". That message is also what a\n * genuinely fresh checkout prints on its first build, so the two are\n * indistinguishable in the log, and the worker keeps serving the *previous*\n * shell: the SPA ships yesterday's JavaScript with nothing in the build log\n * to explain it.\n */\n readonly distIndex?: string | URL;\n}\n\n/**\n * What `defineWebViteConfig` accepts.\n */\nexport interface WebViteConfigOptions {\n /**\n * The SPA's plugins — `react()`, `tailwindcss()`, and anything else the app\n * needs. Applied before the spa-shell plugin so the shell is written after the\n * bundle exists.\n */\n readonly plugins?: readonly Plugin[];\n /**\n * Dev-server proxy entries. Keyed by path prefix.\n */\n readonly proxy?: Readonly<Record<string, ProxyEntry>>;\n /**\n * Where the built shell is embedded. Omit to skip the embedding entirely.\n */\n readonly spaShell?: SpaShellTarget;\n /**\n * The build output directory.\n */\n readonly outDir?: string;\n /**\n * The directory this config is resolved from, as a file URL. Defaults to the\n * caller's location.\n */\n readonly root?: string;\n}\n\n/**\n * The `spa-shell-embed` plugin, converged from all eight copies.\n *\n * It exists because the API worker serves `SPA_HTML` from a module in its own\n * source tree, and both that module and `dist/` are gitignored — so a fresh\n * clone gets an empty stub from `postinstall` and every `GET /` returns a blank\n * page until someone runs a build. This plugin is what makes the build write the\n * real artefact, and `scripts/verify-spa-shell.ts` is what refuses to deploy\n * without it.\n *\n * Written as a factory rather than inlined so the exit conditions are in one\n * place: the `closeBundle` hook runs on every build, including the ones where\n * `dist/index.html` was never produced, and a plugin that throws there fails\n * builds that legitimately emit nothing.\n */\n/**\n * Normalise a path-or-URL option to a URL, so `new URL(...)` can be used on it.\n *\n * Small, and here because two options accept either form: a path is what a consumer\n * naturally writes in a config, and a URL is what `import.meta.url` hands them.\n * Accepting both is one line and saves a `fileURLToPath` at every call site.\n */\n/**\n * Normalise `string | URL` to a `URL`.\n *\n * A string that is **already a file URL** must be parsed, not converted:\n * `pathToFileURL('file:///srv/app')` treats its argument as a filesystem path\n * and produces `file:///<cwd>/file:/srv/app`, so every path built on top of it\n * silently resolves into a directory named after the scheme.\n *\n * The failure this prevented is not loud. `spaShellEmbedPlugin` then reports\n * \"dist/index.html not found, skipping\" — which is also what a genuinely fresh\n * checkout prints on its first build — and the consumer's worker keeps serving\n * the *previous* shell, so the SPA ships yesterday's JavaScript with no error\n * anywhere in the build log. Both `root` and `distIndex` are documented as\n * \"a file URL or a path\", and `new URL('.', import.meta.url).href` — the shape\n * every config file reaches for first — is a file-URL string, so this is the\n * path most callers take.\n */\nfunction toUrl(value: string | URL): URL {\n if (value instanceof URL) return value;\n return value.startsWith('file:') ? new URL(value) : pathToFileURL(value);\n}\n\n/**\n * The same, as a **directory** URL — with the trailing separator `new URL(rel, base)`\n * needs.\n *\n * `new URL('apps/api/x.ts', 'file:///repo')` resolves to `/apps/api/x.ts`, silently\n * dropping the base. The base has to end in a separator, and a path from\n * `process.cwd()` never does, so this is where the plugin would otherwise write the\n * shell into the filesystem root.\n */\nfunction toDirUrl(value: string | URL): URL {\n const url = toUrl(value);\n return url.href.endsWith('/') ? url : new URL(`${url.href}/`);\n}\n\nexport function spaShellEmbedPlugin(target: SpaShellTarget): Plugin & { closeBundle: () => void } {\n return {\n name: 'spa-shell-embed',\n closeBundle() {\n // Resolved from the directory the build runs in, never from this module's own\n // URL: the plugin object is created here but executes in the consumer's Vite\n // process, and `new URL(path, import.meta.url)` would resolve against\n // `node_modules/@rexezuge/tooling`. `process.cwd()` is the repo root for\n // `pnpm --filter @scope/web build`, which is how every consumer runs it.\n const root = toDirUrl(target.root ?? process.cwd());\n const outputPath = fileURLToPath(new URL(target.path, root));\n // A relative `distIndex` resolves against the root, like `path` does —\n // not against the process's working directory, which under\n // `pnpm --filter … build` is the package directory.\n const indexPath =\n target.distIndex === undefined\n ? fileURLToPath(new URL('dist/index.html', root))\n : fileURLToPath(\n typeof target.distIndex === 'string' && !/^[a-z][a-z\\d+\\-.]*:/i.test(target.distIndex)\n ? new URL(target.distIndex, root)\n : toUrl(target.distIndex),\n );\n\n if (!existsSync(indexPath)) {\n console.warn('spa-shell-embed: dist/index.html not found, skipping');\n return;\n }\n\n const html = readFileSync(indexPath, 'utf8');\n const output = `// Auto-generated by Vite build plugin - DO NOT EDIT.\\nexport const SPA_HTML: string = ${JSON.stringify(html)};\\n`;\n\n mkdirSync(path.dirname(outputPath), { recursive: true });\n writeFileSync(outputPath, output);\n },\n };\n}\n\n/**\n * Build the SPA's Vite config.\n *\n * ```ts\n * // apps/web/vite.config.ts\n * import react from '@vitejs/plugin-react';\n * import { defineWebViteConfig, spaShellEmbedPlugin } from '@rexezuge/tooling/vite';\n *\n * export default defineWebViteConfig({\n * plugins: [react()],\n * proxy: { '/user': { target: 'http://localhost:8787', changeOrigin: true } },\n * spaShell: { path: '../../apps/api/src/generated/spa-shell.ts' },\n * });\n * ```\n */\nexport function defineWebViteConfig(options: WebViteConfigOptions = {}): ViteUserConfig {\n const plugins: Plugin[] = [...(options.plugins ?? [])];\n if (options.spaShell !== undefined) {\n plugins.push(spaShellEmbedPlugin(options.spaShell));\n }\n\n return defineConfig({\n ...(plugins.length > 0 && { plugins }),\n ...(options.proxy !== undefined && { server: { proxy: { ...options.proxy } } }),\n build: {\n outDir: options.outDir ?? 'dist',\n emptyOutDir: true,\n },\n });\n}\n"],
|
|
5
|
+
"mappings": "+EA+BA,OAAS,cAAAA,E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AAC,GAAID,EAAQ,SAAW,CAAA,CAAG,EACrD,OAAIA,EAAQ,WAAa,QACvBC,EAAQ,KAAKT,EAAoBQ,EAAQ,QAAQ,CAAC,EAG7Cd,EAAa,CAClB,GAAIe,EAAQ,OAAS,GAAK,CAAE,QAAAA,CAAO,EACnC,GAAID,EAAQ,QAAU,QAAa,CAAE,OAAQ,CAAE,MAAO,CAAE,GAAGA,EAAQ,KAAK,CAAE,CAAE,EAC5E,MAAO,CACL,OAAQA,EAAQ,QAAU,OAC1B,YAAa,IAEhB,CACH,CAdgBX,EAAAU,EAAA",
|
|
6
6
|
"names": ["existsSync", "mkdirSync", "readFileSync", "writeFileSync", "path", "fileURLToPath", "pathToFileURL", "defineConfig", "toUrl", "value", "__name", "toDirUrl", "url", "spaShellEmbedPlugin", "target", "root", "outputPath", "indexPath", "html", "output", "defineWebViteConfig", "options", "plugins"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rexezuge/tooling",
|
|
3
|
-
"version": "1.9.
|
|
3
|
+
"version": "1.9.3",
|
|
4
4
|
"private": false,
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"src"
|
|
39
39
|
],
|
|
40
40
|
"dependencies": {
|
|
41
|
-
"@rexezuge/d1": "1.9.
|
|
41
|
+
"@rexezuge/d1": "1.9.3"
|
|
42
42
|
},
|
|
43
43
|
"peerDependencies": {
|
|
44
44
|
"eslint": "^10.0.0",
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"eslint-plugin-prettier": "^5.5.6",
|
|
47
47
|
"eslint-plugin-regexp": "^3.3.1",
|
|
48
48
|
"eslint-plugin-sonarjs": "^4.2.2",
|
|
49
|
-
"eslint-plugin-unicorn": "^76.0.0",
|
|
49
|
+
"eslint-plugin-unicorn": "^76.0.0 || ^78.0.0",
|
|
50
50
|
"globals": "^17.13.0",
|
|
51
51
|
"jsonc-parser": "^3.3.1",
|
|
52
52
|
"prettier": "^3.9.0",
|
package/src/eslint.ts
CHANGED
|
@@ -213,7 +213,15 @@ export function defineRepoLintConfig(options: RepoLintConfigOptions): FlatConfig
|
|
|
213
213
|
// `no-nested-assignment` and `no-all-duplicated-branches` linted as errors
|
|
214
214
|
// in every consumer. The two presets do not share rule names, so their
|
|
215
215
|
// relative order decides nothing.
|
|
216
|
-
|
|
216
|
+
//
|
|
217
|
+
// The unicorn preset is read from whichever spelling the installed major
|
|
218
|
+
// publishes. v78 dropped the `flat/`-prefixed aliases and exports the flat
|
|
219
|
+
// configs directly, so `configs['flat/recommended']` is `undefined` there —
|
|
220
|
+
// and a config object built around it is `undefined` too, which ESLint
|
|
221
|
+
// rejects outright with "Unexpected undefined config". The fallback is
|
|
222
|
+
// what makes the factory work on both majors rather than only the one the
|
|
223
|
+
// kit was written against.
|
|
224
|
+
asConfig(unicorn.configs['flat/recommended'] ?? unicorn.configs.recommended),
|
|
217
225
|
asConfig(sonarjsConfigs.recommended),
|
|
218
226
|
{
|
|
219
227
|
rules: asRules(UNICORN_RULES),
|
|
@@ -47,9 +47,9 @@
|
|
|
47
47
|
*/
|
|
48
48
|
|
|
49
49
|
import { readdirSync, readFileSync, statSync } from 'node:fs';
|
|
50
|
-
import { pathToFileURL } from 'node:url';
|
|
51
50
|
import path from 'node:path';
|
|
52
51
|
import { fail } from './lib/github-actions.ts';
|
|
52
|
+
import { isEntrypoint } from './lib/entrypoint.ts';
|
|
53
53
|
import { isSet, parseFlags, splitPositional, valueOf } from './lib/cli-args.ts';
|
|
54
54
|
|
|
55
55
|
/**
|
|
@@ -351,6 +351,6 @@ export function checkGodFilesCli(argv: readonly string[] = process.argv.slice(2)
|
|
|
351
351
|
// an unconditional call is the same guard Durable-DAV's init-secrets.ts uses, and
|
|
352
352
|
// it is what keeps the rule modules importable — which is the whole reason they are
|
|
353
353
|
// separate modules in the first place.
|
|
354
|
-
if (
|
|
354
|
+
if (isEntrypoint(import.meta.url)) {
|
|
355
355
|
process.exit(checkGodFilesCli(process.argv.slice(2)));
|
|
356
356
|
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { tmpdir } from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { describe, expect, it } from 'vitest';
|
|
5
|
+
import { isEntrypoint } from './entrypoint.ts';
|
|
6
|
+
|
|
7
|
+
function repo(): string {
|
|
8
|
+
return mkdtempSync(path.join(tmpdir(), 'entrypoint-'));
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
describe('isEntrypoint', () => {
|
|
12
|
+
it('matches when the entrypoint is the file itself', () => {
|
|
13
|
+
const file = path.join(repo(), 'script.mjs');
|
|
14
|
+
writeFileSync(file, '');
|
|
15
|
+
expect(isEntrypoint(`file://${file}`, file)).toBe(true);
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
it('matches through a symlink, which is how pnpm installs every package', () => {
|
|
19
|
+
// The regression. `process.argv[1]` is whatever the caller typed —
|
|
20
|
+
// `node_modules/@rexezuge/tooling/dist/scripts/x.js`, a symlink into the
|
|
21
|
+
// store — while `import.meta.url` is always the realpath, because the ESM
|
|
22
|
+
// resolver follows links. Comparing the two unresolved returns false, the
|
|
23
|
+
// guard never fires, and the script exits 0 having printed nothing.
|
|
24
|
+
//
|
|
25
|
+
// For a *gate* that is the worst shape a failure can take: `validate-locales`
|
|
26
|
+
// passed with a key missing from eleven bundles and `check-god-files` reported
|
|
27
|
+
// no file over the limit, both silently. Found by a consumer swapping in its
|
|
28
|
+
// own copy and finding the replacement stopped catching what the old one
|
|
29
|
+
// reported on the same tree.
|
|
30
|
+
const root = repo();
|
|
31
|
+
const store = path.join(root, 'store', 'tooling');
|
|
32
|
+
mkdirSync(path.join(store, 'dist'), { recursive: true });
|
|
33
|
+
const real = path.join(store, 'dist', 'script.mjs');
|
|
34
|
+
writeFileSync(real, '');
|
|
35
|
+
// The pnpm layout: `node_modules/@rexezuge/tooling` is a symlink to the store.
|
|
36
|
+
mkdirSync(path.join(root, 'node_modules'), { recursive: true });
|
|
37
|
+
symlinkSync(path.dirname(store), path.join(root, 'node_modules', '@rexezuge'), 'dir');
|
|
38
|
+
const entry = path.join(root, 'node_modules', '@rexezuge', 'tooling', 'dist', 'script.mjs');
|
|
39
|
+
expect(isEntrypoint(`file://${real}`, entry)).toBe(true);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('does not match the module a suite imported', () => {
|
|
43
|
+
// The reason the guard exists: these modules export their rules so the tests
|
|
44
|
+
// can import them, and during a test run `argv[1]` is the test file.
|
|
45
|
+
const root = repo();
|
|
46
|
+
const test = path.join(root, 'thing.test.ts');
|
|
47
|
+
const script = path.join(root, 'script.mjs');
|
|
48
|
+
writeFileSync(test, '');
|
|
49
|
+
writeFileSync(script, '');
|
|
50
|
+
expect(isEntrypoint(`file://${script}`, test)).toBe(false);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it('does not match when the entrypoint is absent, or does not resolve', () => {
|
|
54
|
+
// Exercised through the real default rather than by passing `undefined`:
|
|
55
|
+
// `isEntrypoint` reads `process.argv[1]`, and under a test run that is the
|
|
56
|
+
// test file, which is the case the guard exists to exclude anyway.
|
|
57
|
+
expect(isEntrypoint('file:///nope.mjs')).toBe(false);
|
|
58
|
+
expect(isEntrypoint('file:///nope.mjs', '/also/not/here.mjs')).toBe(false);
|
|
59
|
+
});
|
|
60
|
+
});
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { realpathSync } from 'node:fs';
|
|
2
|
+
import { pathToFileURL } from 'node:url';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Whether this module is the process's entrypoint.
|
|
6
|
+
*
|
|
7
|
+
* The comparison needs **both** sides resolved through `realpathSync`, and that
|
|
8
|
+
* is not a detail. `process.argv[1]` is whatever the caller typed — under pnpm
|
|
9
|
+
* that is `node_modules/@rexezuge/tooling/dist/scripts/…`, a **symlink** into the
|
|
10
|
+
* store — while `import.meta.url` is always the realpath, because the ESM
|
|
11
|
+
* resolver follows links. So the two never matched, the guard never fired, and
|
|
12
|
+
* every script below exited 0 having printed nothing.
|
|
13
|
+
*
|
|
14
|
+
* That is the worst shape a gate can fail in: it looks green. `check-god-files`
|
|
15
|
+
* reported no file over the limit for every repository that adopted it,
|
|
16
|
+
* `validate-locales` passed with a key missing from eleven bundles, and neither
|
|
17
|
+
* said a word. Found by AWS-AccessBridge swapping in its own `validate_locales`
|
|
18
|
+
* and finding that the replacement stopped catching the defect the old one
|
|
19
|
+
* reported on the same tree.
|
|
20
|
+
*
|
|
21
|
+
* It is worth a function rather than an inline comparison because four scripts
|
|
22
|
+
* carry the same guard, and a shared helper is what makes the fifth correct
|
|
23
|
+
* instead of a fourth copy of the same mistake.
|
|
24
|
+
*
|
|
25
|
+
* A missing or unreadable entrypoint is not the entrypoint, and the caller
|
|
26
|
+
* exports the rule functions precisely so the module stays importable — a suite
|
|
27
|
+
* imports these to test the rules, and there `process.argv[1]` is the test file.
|
|
28
|
+
*/
|
|
29
|
+
export function isEntrypoint(moduleUrl: string, argv1: string | undefined = process.argv[1]): boolean {
|
|
30
|
+
if (argv1 === undefined) {
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
try {
|
|
34
|
+
return moduleUrl === pathToFileURL(realpathSync(argv1)).href;
|
|
35
|
+
} catch {
|
|
36
|
+
// A path that does not resolve cannot be the file that is running.
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
}
|
package/src/scripts/spa-shell.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isEntrypoint } from './lib/entrypoint.ts';
|
|
1
2
|
/**
|
|
2
3
|
* The SPA shell pair: `ensure-spa-shell-stub` + `verify-spa-shell`.
|
|
3
4
|
*
|
|
@@ -14,7 +15,6 @@
|
|
|
14
15
|
* with nothing in the source tree saying so.
|
|
15
16
|
*/
|
|
16
17
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
17
|
-
import { pathToFileURL } from 'node:url';
|
|
18
18
|
import path from 'node:path';
|
|
19
19
|
|
|
20
20
|
interface SpaShellPaths {
|
|
@@ -188,6 +188,6 @@ export type { SpaShellPaths, VerifyResult };
|
|
|
188
188
|
// an unconditional call is the same guard Durable-DAV's init-secrets.ts uses, and
|
|
189
189
|
// it is what keeps the rule modules importable — which is the whole reason they are
|
|
190
190
|
// separate modules in the first place.
|
|
191
|
-
if (
|
|
191
|
+
if (isEntrypoint(import.meta.url)) {
|
|
192
192
|
process.exit(spaShellCli(process.argv.slice(2)));
|
|
193
193
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isEntrypoint } from './lib/entrypoint.ts';
|
|
1
2
|
/**
|
|
2
3
|
* Validate that every locale bundle carries exactly the base locale's keys.
|
|
3
4
|
*
|
|
@@ -36,7 +37,6 @@
|
|
|
36
37
|
* the kit ships and the SPA bundles the repos do.
|
|
37
38
|
*/
|
|
38
39
|
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
39
|
-
import { pathToFileURL } from 'node:url';
|
|
40
40
|
import path from 'node:path';
|
|
41
41
|
|
|
42
42
|
/**
|
|
@@ -771,6 +771,6 @@ export type { LocaleProblem, LocaleReport, LocaleShape };
|
|
|
771
771
|
// an unconditional call is the same guard Durable-DAV's init-secrets.ts uses, and
|
|
772
772
|
// it is what keeps the rule modules importable — which is the whole reason they are
|
|
773
773
|
// separate modules in the first place.
|
|
774
|
-
if (
|
|
774
|
+
if (isEntrypoint(import.meta.url)) {
|
|
775
775
|
process.exit(validateLocalesCli(process.argv.slice(2)));
|
|
776
776
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isEntrypoint } from './lib/entrypoint.ts';
|
|
1
2
|
/**
|
|
2
3
|
* Verify the migration set is complete, ordered, and locked; write the lock.
|
|
3
4
|
*
|
|
@@ -59,7 +60,6 @@
|
|
|
59
60
|
* bless a drift would be the operator blessing their own edit.
|
|
60
61
|
*/
|
|
61
62
|
import { createHash } from 'node:crypto';
|
|
62
|
-
import { pathToFileURL } from 'node:url';
|
|
63
63
|
import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
|
|
64
64
|
import path from 'node:path';
|
|
65
65
|
|
|
@@ -391,6 +391,6 @@ export type { MigrationEntry, MigrationLockFile, MigrationProblem, MigrationRepo
|
|
|
391
391
|
// an unconditional call is the same guard Durable-DAV's init-secrets.ts uses, and
|
|
392
392
|
// it is what keeps the rule modules importable — which is the whole reason they are
|
|
393
393
|
// separate modules in the first place.
|
|
394
|
-
if (
|
|
394
|
+
if (isEntrypoint(import.meta.url)) {
|
|
395
395
|
process.exit(verifyMigrationsCli(process.argv.slice(2)));
|
|
396
396
|
}
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
13
|
import { copyFileSync, readFileSync, writeFileSync } from 'node:fs';
|
|
14
|
+
import path from 'node:path';
|
|
14
15
|
import { applyEdits, modify, parse } from 'jsonc-parser';
|
|
15
16
|
import { CONFIG_PATH, TEMPLATE_PATH, type WranglerConfig } from './types.ts';
|
|
16
17
|
|
|
@@ -90,6 +91,14 @@ function parseJsonObject(raw: string | undefined, name: string, expected: string
|
|
|
90
91
|
return parsed as Record<string, unknown>;
|
|
91
92
|
}
|
|
92
93
|
|
|
94
|
+
/**
|
|
95
|
+
* A path as a log line should name it: relative to the working directory the
|
|
96
|
+
* script was invoked from, which is the repo root in every consumer.
|
|
97
|
+
*/
|
|
98
|
+
function displayPath(filePath: string): string {
|
|
99
|
+
return path.relative(process.cwd(), filePath) || filePath;
|
|
100
|
+
}
|
|
101
|
+
|
|
93
102
|
/**
|
|
94
103
|
* Materialize the config: the repository variable when it is set, otherwise the
|
|
95
104
|
* committed template.
|
|
@@ -102,7 +111,7 @@ export function prepareConfigFile(): void {
|
|
|
102
111
|
return;
|
|
103
112
|
}
|
|
104
113
|
copyFileSync(TEMPLATE_PATH, CONFIG_PATH);
|
|
105
|
-
console.log(
|
|
114
|
+
console.log(`WRANGLER_JSONC is empty; copied ${displayPath(TEMPLATE_PATH)} to ${displayPath(CONFIG_PATH)}.`);
|
|
106
115
|
}
|
|
107
116
|
|
|
108
117
|
/**
|
|
@@ -122,7 +131,7 @@ export function ensureMinimumConfigVersion(): void {
|
|
|
122
131
|
const currentVersion = config.$version;
|
|
123
132
|
if (typeof currentVersion !== 'number' || currentVersion < template.$minimumVersion) {
|
|
124
133
|
throw new Error(
|
|
125
|
-
`wrangler.jsonc version (${typeof currentVersion === 'number' ? currentVersion : 'missing'}) is below minimum template version (${template.$minimumVersion}). Regenerate it from
|
|
134
|
+
`wrangler.jsonc version (${typeof currentVersion === 'number' ? currentVersion : 'missing'}) is below minimum template version (${template.$minimumVersion}). Regenerate it from ${displayPath(TEMPLATE_PATH)}.`,
|
|
126
135
|
);
|
|
127
136
|
}
|
|
128
137
|
}
|