@rexezuge/tooling 1.14.0 → 1.15.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.
- package/README.md +42 -30
- package/dist/eslint-rules.d.ts.map +1 -1
- package/dist/eslint-rules.js +1 -1
- package/dist/eslint-rules.js.map +2 -2
- package/dist/eslint-strict.d.ts +2 -1
- package/dist/eslint-strict.d.ts.map +1 -1
- package/dist/eslint-strict.js +2 -1
- package/dist/eslint-strict.js.map +3 -3
- package/dist/manifest-validate.d.ts.map +1 -1
- package/dist/manifest-validate.js +1 -1
- package/dist/manifest-validate.js.map +3 -3
- package/dist/manifest.d.ts +21 -0
- package/dist/manifest.d.ts.map +1 -1
- package/dist/manifest.js.map +2 -2
- package/dist/scripts/backup/destinations.d.ts +40 -0
- package/dist/scripts/backup/destinations.d.ts.map +1 -0
- package/dist/scripts/backup/destinations.js +1 -0
- package/dist/scripts/backup/destinations.js.map +7 -0
- package/dist/scripts/backup/encrypt-backup.d.ts +5 -2
- package/dist/scripts/backup/encrypt-backup.d.ts.map +1 -1
- package/dist/scripts/backup/encrypt-backup.js +2 -3
- package/dist/scripts/backup/encrypt-backup.js.map +3 -3
- package/dist/scripts/backup/naming.d.ts +1 -1
- package/dist/scripts/backup/naming.d.ts.map +1 -1
- package/dist/scripts/backup/naming.js +1 -1
- package/dist/scripts/backup/naming.js.map +3 -3
- package/dist/scripts/prepare-wrangler-config.d.ts.map +1 -1
- package/dist/scripts/prepare-wrangler-config.js +1 -1
- package/dist/scripts/prepare-wrangler-config.js.map +3 -3
- package/dist/scripts/wrangler-config/resources.d.ts +11 -2
- 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/vitest-aliases.d.ts +7 -1
- package/dist/vitest-aliases.d.ts.map +1 -1
- package/dist/vitest-aliases.js +1 -1
- package/dist/vitest-aliases.js.map +3 -3
- package/dist/vitest-integration.d.ts.map +1 -1
- package/dist/vitest-integration.js +1 -1
- package/dist/vitest-integration.js.map +3 -3
- package/dist/vitest-repo.js +1 -1
- package/dist/vitest-repo.js.map +3 -3
- package/dist/vitest-web.js +1 -1
- package/dist/vitest-web.js.map +3 -3
- package/dist/vitest.d.ts +1 -1
- package/dist/vitest.d.ts.map +1 -1
- package/dist/vitest.js +1 -1
- package/dist/vitest.js.map +3 -3
- package/package.json +3 -3
- package/presets/tsconfig/web.json +2 -2
- package/schema/manifest.schema.json +28 -1
- package/src/eslint-rules.ts +4 -0
- package/src/eslint-strict.test.ts +29 -0
- package/src/eslint-strict.ts +36 -4
- package/src/github/dependabot.yml +14 -4
- package/src/github/workflows/backup-d1.yml +15 -0
- package/src/github/workflows/backup-main.yml +9 -126
- package/src/github/workflows/continuous-deployment.yml +11 -180
- package/src/github/workflows/continuous-integration.yml +9 -249
- package/src/github/workflows/scheduled-version-update.yml +8 -31
- package/src/github/workflows/upstream-sync.yml +8 -49
- package/src/manifest-validate.ts +31 -2
- package/src/manifest.test.ts +22 -0
- package/src/manifest.ts +22 -0
- package/src/presets.test.ts +5 -1
- package/src/scripts/backup/backup-rules.test.ts +22 -0
- package/src/scripts/backup/destinations.ts +59 -0
- package/src/scripts/backup/encrypt-backup.ts +58 -48
- package/src/scripts/backup/naming.ts +2 -2
- package/src/scripts/prepare-wrangler-config.ts +9 -1
- package/src/scripts/wrangler-config/resources.test.ts +10 -0
- package/src/scripts/wrangler-config/resources.ts +21 -4
- package/src/vitest-aliases.test.ts +33 -0
- package/src/vitest-aliases.ts +37 -7
- package/src/vitest-integration.ts +2 -5
- package/src/vitest-repo.ts +2 -2
- package/src/vitest-web.ts +2 -2
- package/src/vitest.ts +3 -3
- package/src/github/actions/retry-step/action.yml +0 -55
- package/src/github/actions/setup-env/action.yml +0 -20
package/dist/manifest.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manifest.d.ts","sourceRoot":"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C,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC;AAE/G;;EAEE;AACF,qBAAa,aAAc,SAAQ,KAAK;IACtC,QAAQ,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC;gBACvB,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,MAAM,EAAE;CAKtD;AAED;;EAEE;AACF,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,GAAE,MAA0B,GAAG,cAAc,CAY9F;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,cAAc,GAAG,IAAI,CAIhE;AAED;;;;GAIG;AACH,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,MAAM,GAAG,gBAAgB,GAAG,SAAS,CAGrF"}
|
package/dist/manifest.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/manifest.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * The family manifest: `.rexezuge.jsonc` at a repo root.\n *\n * One declarative file states what a repo *is* (its scope, the platform features\n * it uses, its dependency layers) and how strict it holds itself (coverage\n * floors, god-file limits). The tooling factories read it instead of each\n * encoding consumer directory names, so the kit stays free of repo layouts and a\n * repo's layout stays out of its lint config.\n *\n * The charter applies to the file itself. The **closed** side is the schema:\n * unknown keys are refused (a typo is an error, not a silent no-op), and\n * `quality.godFiles` may only be lowered below the family default, never raised.\n * The **open** side is `extensions`: a free-form object, namespaced by the key\n * that owns it, that the kit never reads.\n *\n * `manifest.schema.json` (shipped beside this module) describes the same shape\n * for editor completion via `$schema`; a test keeps the two in step.\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { parse as parseJsonc, printParseErrorCode } from 'jsonc-parser';\nimport type { ParseError } from 'jsonc-parser';\nimport { validateManifest } from './manifest-validate.ts';\n\nexport { FAMILY_GOD_FILE_LIMITS, validateManifest } from './manifest-validate.ts';\n\n/**\nThe file name, resolved against a repo root.\n*/\nexport const MANIFEST_FILENAME = '.rexezuge.jsonc';\n\nexport interface ManifestD1 {\n readonly binding: string;\n readonly database: string;\n readonly migrationsDir?: string;\n}\n\nexport interface ManifestWeb {\n /**\n The SPA is served by Cloudflare Pages.\n */\n readonly pages: boolean;\n /**\n The SPA shell is embedded into the worker (`spa-shell` scripts).\n */\n readonly spaShell: boolean;\n}\n\nexport interface ManifestFeatures {\n readonly d1?: ManifestD1;\n readonly web?: ManifestWeb;\n readonly background?: boolean;\n readonly backupD1?: boolean;\n /**\n Durable Object class names.\n */\n readonly durableObjects?: readonly string[];\n /**\n Queue names.\n */\n readonly queues?: readonly string[];\n /**\n Workflow class names.\n */\n readonly workflows?: readonly string[];\n readonly email?: boolean;\n readonly android?: boolean;\n}\n\n/**\n * One dependency layer: a directory, and the other layers it may import.\n *\n * Everything not named in `mayImport` / `typeOnly` is banned, by package name\n * (`<scope>/<basename of dir>`, or `package`). `mayImport: []` isolates the layer\n * from the whole scope (`<scope>/*`).\n */\nexport interface ManifestLayer {\n readonly name: string;\n /**\n Repo-relative directory, no globs: `packages/backend-data`.\n */\n readonly dir: string;\n /**\n Package suffix when it is not the directory's basename.\n */\n readonly package?: string;\n /**\n Names of layers this layer may import.\n */\n readonly mayImport: readonly string[];\n /**\n Names of layers importable as `import type` only.\n */\n readonly typeOnly?: readonly string[];\n /**\n Extra external specifiers this layer may not import, e.g. `aws4fetch`.\n */\n readonly forbid?: readonly string[];\n /**\n Message for `forbid`; defaults to a generic one.\n */\n readonly forbidMessage?: string;\n /**\n May import `hono`/`chanfana` (and hand-build error envelopes).\n */\n readonly http?: boolean;\n /**\n Browser code: may use `console`, and lints with browser globals.\n */\n readonly browser?: boolean;\n}\n\nexport interface ManifestCoverage {\n readonly lines: number;\n readonly branches: number;\n readonly functions: number;\n readonly statements: number;\n}\n\nexport interface ManifestQuality {\n readonly coverage?: ManifestCoverage;\n readonly godFiles?: { readonly soft: number; readonly hard: number };\n}\n\nexport interface FamilyManifest {\n readonly $schema?: string;\n readonly name: string;\n /**\n npm scope with the `@`, e.g. `@mail-meow`.\n */\n readonly scope: string;\n readonly features?: ManifestFeatures;\n readonly layers?: readonly ManifestLayer[];\n readonly quality?: ManifestQuality;\n /**\n Repo-specific settings, namespaced by key. Never read by the kit.\n */\n readonly extensions?: Readonly<Record<string, Readonly<Record<string, unknown>>>>;\n}\n\nexport type ManifestValidation =\n { readonly ok: true; readonly manifest: FamilyManifest } | { readonly ok: false; readonly errors: string[] };\n\n/**\nThrown by {@link loadManifest} and {@link parseManifest}; `errors` has one line per problem.\n*/\nexport class ManifestError extends Error {\n readonly errors: readonly string[];\n constructor(source: string, errors: readonly string[]) {\n super(`${source} is not a valid family manifest:\\n${errors.map((line) => ` - ${line}`).join('\\n')}`);\n this.name = 'ManifestError';\n this.errors = errors;\n }\n}\n\n/**\nParse JSONC text and validate it. Throws {@link ManifestError}.\n*/\nexport function parseManifest(text: string, source: string = MANIFEST_FILENAME): FamilyManifest {\n const syntax: ParseError[] = [];\n const value: unknown = parseJsonc(text, syntax, { allowTrailingComma: true });\n if (syntax.length > 0) {\n throw new ManifestError(\n source,\n syntax.map((error) => `syntax error at offset ${error.offset}: ${printParseErrorCode(error.error)}`),\n );\n }\n const result = validateManifest(value);\n if (!result.ok) throw new ManifestError(source, result.errors);\n return result.manifest;\n}\n\n/**\n * Load `<root>/.rexezuge.jsonc`. Returns `null` when the file is absent (the\n * repo has not adopted a manifest) and throws {@link ManifestError} when it is\n * present but invalid: a broken manifest must fail the gate, not fall back.\n */\nexport function loadManifest(root: string): FamilyManifest | null {\n const file = path.join(root, MANIFEST_FILENAME);\n if (!existsSync(file)) return null;\n return parseManifest(readFileSync(file, 'utf8'), file);\n}\n\n/**\n * The manifest's coverage floor for a vitest config, or `undefined` when the\n * repo has no manifest or declares none. `root` is what the factories take: a\n * directory path or a `file:` URL (`new URL('.', import.meta.url).href`).\n */\nexport function manifestCoverageThresholds(root: string): ManifestCoverage | undefined {\n const dir = root.startsWith('file:') ? fileURLToPath(root) : root;\n return loadManifest(dir)?.quality?.coverage;\n}\n"],
|
|
5
|
-
"mappings": "+EAmBA,OAAS,cAAAA,EAAY,gBAAAC,MAAoB,UACzC,OAAOC,MAAU,YACjB,OAAS,iBAAAC,MAAqB,WAC9B,OAAS,SAASC,EAAY,uBAAAC,MAA2B,eAEzD,OAAS,oBAAAC,MAAwB,yBAEjC,OAAS,0BAAAC,EAAwB,oBAAAD,MAAwB,yBAKlD,MAAME,EAAoB,
|
|
4
|
+
"sourcesContent": ["/**\n * The family manifest: `.rexezuge.jsonc` at a repo root.\n *\n * One declarative file states what a repo *is* (its scope, the platform features\n * it uses, its dependency layers) and how strict it holds itself (coverage\n * floors, god-file limits). The tooling factories read it instead of each\n * encoding consumer directory names, so the kit stays free of repo layouts and a\n * repo's layout stays out of its lint config.\n *\n * The charter applies to the file itself. The **closed** side is the schema:\n * unknown keys are refused (a typo is an error, not a silent no-op), and\n * `quality.godFiles` may only be lowered below the family default, never raised.\n * The **open** side is `extensions`: a free-form object, namespaced by the key\n * that owns it, that the kit never reads.\n *\n * `manifest.schema.json` (shipped beside this module) describes the same shape\n * for editor completion via `$schema`; a test keeps the two in step.\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { parse as parseJsonc, printParseErrorCode } from 'jsonc-parser';\nimport type { ParseError } from 'jsonc-parser';\nimport { validateManifest } from './manifest-validate.ts';\n\nexport { FAMILY_GOD_FILE_LIMITS, validateManifest } from './manifest-validate.ts';\n\n/**\nThe file name, resolved against a repo root.\n*/\nexport const MANIFEST_FILENAME = '.rexezuge.jsonc';\n\nexport interface ManifestD1 {\n readonly binding: string;\n readonly database: string;\n readonly migrationsDir?: string;\n}\n\nexport interface ManifestKv {\n /**\n KV binding names the deployment needs (UPPER_SNAKE). `prepare-wrangler` adds any a hand-written config lacks and provisions\n their namespaces; a repo that declares none gets no KV binding and no namespace.\n */\n readonly bindings: readonly string[];\n /**\n Binding to namespace name, for a namespace that predates the kit's `<worker>-<binding>` convention. Keys must be listed in `bindings`.\n */\n readonly namespaceNames?: Readonly<Record<string, string>>;\n}\n\nexport interface ManifestWeb {\n /**\n The SPA is served by Cloudflare Pages.\n */\n readonly pages: boolean;\n /**\n The SPA shell is embedded into the worker (`spa-shell` scripts).\n */\n readonly spaShell: boolean;\n /**\n A **root** `package.json` script that builds the SPA, for a repo whose build has wrappers (`verify:tailwind && build`).\n CI and CD run `pnpm run <script>` instead of `pnpm --filter <scope>/web run build`.\n */\n readonly buildScript?: string;\n /**\n The Cloudflare Pages project, when it is not `<name>-web`. Wins over the `CLOUDFLARE_PAGES_PROJECT_NAME` variable.\n */\n readonly pagesProject?: string;\n}\n\nexport interface ManifestFeatures {\n readonly d1?: ManifestD1;\n readonly kv?: ManifestKv;\n readonly web?: ManifestWeb;\n readonly background?: boolean;\n readonly backupD1?: boolean;\n /**\n Durable Object class names.\n */\n readonly durableObjects?: readonly string[];\n /**\n Queue names.\n */\n readonly queues?: readonly string[];\n /**\n Workflow class names.\n */\n readonly workflows?: readonly string[];\n readonly email?: boolean;\n readonly android?: boolean;\n}\n\n/**\n * One dependency layer: a directory, and the other layers it may import.\n *\n * Everything not named in `mayImport` / `typeOnly` is banned, by package name\n * (`<scope>/<basename of dir>`, or `package`). `mayImport: []` isolates the layer\n * from the whole scope (`<scope>/*`).\n */\nexport interface ManifestLayer {\n readonly name: string;\n /**\n Repo-relative directory, no globs: `packages/backend-data`.\n */\n readonly dir: string;\n /**\n Package suffix when it is not the directory's basename.\n */\n readonly package?: string;\n /**\n Names of layers this layer may import.\n */\n readonly mayImport: readonly string[];\n /**\n Names of layers importable as `import type` only.\n */\n readonly typeOnly?: readonly string[];\n /**\n Extra external specifiers this layer may not import, e.g. `aws4fetch`.\n */\n readonly forbid?: readonly string[];\n /**\n Message for `forbid`; defaults to a generic one.\n */\n readonly forbidMessage?: string;\n /**\n May import `hono`/`chanfana` (and hand-build error envelopes).\n */\n readonly http?: boolean;\n /**\n Browser code: may use `console`, and lints with browser globals.\n */\n readonly browser?: boolean;\n}\n\nexport interface ManifestCoverage {\n readonly lines: number;\n readonly branches: number;\n readonly functions: number;\n readonly statements: number;\n}\n\nexport interface ManifestQuality {\n readonly coverage?: ManifestCoverage;\n readonly godFiles?: { readonly soft: number; readonly hard: number };\n}\n\nexport interface FamilyManifest {\n readonly $schema?: string;\n readonly name: string;\n /**\n npm scope with the `@`, e.g. `@mail-meow`.\n */\n readonly scope: string;\n readonly features?: ManifestFeatures;\n readonly layers?: readonly ManifestLayer[];\n readonly quality?: ManifestQuality;\n /**\n Repo-specific settings, namespaced by key. Never read by the kit.\n */\n readonly extensions?: Readonly<Record<string, Readonly<Record<string, unknown>>>>;\n}\n\nexport type ManifestValidation =\n { readonly ok: true; readonly manifest: FamilyManifest } | { readonly ok: false; readonly errors: string[] };\n\n/**\nThrown by {@link loadManifest} and {@link parseManifest}; `errors` has one line per problem.\n*/\nexport class ManifestError extends Error {\n readonly errors: readonly string[];\n constructor(source: string, errors: readonly string[]) {\n super(`${source} is not a valid family manifest:\\n${errors.map((line) => ` - ${line}`).join('\\n')}`);\n this.name = 'ManifestError';\n this.errors = errors;\n }\n}\n\n/**\nParse JSONC text and validate it. Throws {@link ManifestError}.\n*/\nexport function parseManifest(text: string, source: string = MANIFEST_FILENAME): FamilyManifest {\n const syntax: ParseError[] = [];\n const value: unknown = parseJsonc(text, syntax, { allowTrailingComma: true });\n if (syntax.length > 0) {\n throw new ManifestError(\n source,\n syntax.map((error) => `syntax error at offset ${error.offset}: ${printParseErrorCode(error.error)}`),\n );\n }\n const result = validateManifest(value);\n if (!result.ok) throw new ManifestError(source, result.errors);\n return result.manifest;\n}\n\n/**\n * Load `<root>/.rexezuge.jsonc`. Returns `null` when the file is absent (the\n * repo has not adopted a manifest) and throws {@link ManifestError} when it is\n * present but invalid: a broken manifest must fail the gate, not fall back.\n */\nexport function loadManifest(root: string): FamilyManifest | null {\n const file = path.join(root, MANIFEST_FILENAME);\n if (!existsSync(file)) return null;\n return parseManifest(readFileSync(file, 'utf8'), file);\n}\n\n/**\n * The manifest's coverage floor for a vitest config, or `undefined` when the\n * repo has no manifest or declares none. `root` is what the factories take: a\n * directory path or a `file:` URL (`new URL('.', import.meta.url).href`).\n */\nexport function manifestCoverageThresholds(root: string): ManifestCoverage | undefined {\n const dir = root.startsWith('file:') ? fileURLToPath(root) : root;\n return loadManifest(dir)?.quality?.coverage;\n}\n"],
|
|
5
|
+
"mappings": "+EAmBA,OAAS,cAAAA,EAAY,gBAAAC,MAAoB,UACzC,OAAOC,MAAU,YACjB,OAAS,iBAAAC,MAAqB,WAC9B,OAAS,SAASC,EAAY,uBAAAC,MAA2B,eAEzD,OAAS,oBAAAC,MAAwB,yBAEjC,OAAS,0BAAAC,EAAwB,oBAAAD,MAAwB,yBAKlD,MAAME,EAAoB,kBA2I3B,MAAOC,UAAsB,KAAK,CA1KxC,MA0KwC,CAAAC,EAAA,sBAC7B,OACT,YAAYC,EAAgBC,EAAyB,CACnD,MAAM,GAAGD,CAAM;EAAqCC,EAAO,IAAKC,GAAS,OAAOA,CAAI,EAAE,EAAE,KAAK;CAAI,CAAC,EAAE,EACpG,KAAK,KAAO,gBACZ,KAAK,OAASD,CAChB,EAMI,SAAUE,EAAcC,EAAcJ,EAAiBH,EAAiB,CAC5E,MAAMQ,EAAuB,CAAA,EACvBC,EAAiBb,EAAWW,EAAMC,EAAQ,CAAE,mBAAoB,EAAI,CAAE,EAC5E,GAAIA,EAAO,OAAS,EAClB,MAAM,IAAIP,EACRE,EACAK,EAAO,IAAKE,GAAU,0BAA0BA,EAAM,MAAM,KAAKb,EAAoBa,EAAM,KAAK,CAAC,EAAE,CAAC,EAGxG,MAAMC,EAASb,EAAiBW,CAAK,EACrC,GAAI,CAACE,EAAO,GAAI,MAAM,IAAIV,EAAcE,EAAQQ,EAAO,MAAM,EAC7D,OAAOA,EAAO,QAChB,CAZgBT,EAAAI,EAAA,iBAmBV,SAAUM,EAAaC,EAAY,CACvC,MAAMC,EAAOpB,EAAK,KAAKmB,EAAMb,CAAiB,EAC9C,OAAKR,EAAWsB,CAAI,EACbR,EAAcb,EAAaqB,EAAM,MAAM,EAAGA,CAAI,EADvB,IAEhC,CAJgBZ,EAAAU,EAAA,gBAWV,SAAUG,EAA2BF,EAAY,CACrD,MAAMG,EAAMH,EAAK,WAAW,OAAO,EAAIlB,EAAckB,CAAI,EAAIA,EAC7D,OAAOD,EAAaI,CAAG,GAAG,SAAS,QACrC,CAHgBd,EAAAa,EAAA",
|
|
6
6
|
"names": ["existsSync", "readFileSync", "path", "fileURLToPath", "parseJsonc", "printParseErrorCode", "validateManifest", "FAMILY_GOD_FILE_LIMITS", "MANIFEST_FILENAME", "ManifestError", "__name", "source", "errors", "line", "parseManifest", "text", "syntax", "value", "error", "result", "loadManifest", "root", "file", "manifestCoverageThresholds", "dir"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where backups land, and which listed objects the retention prune may delete.
|
|
3
|
+
*
|
|
4
|
+
* Provenance: the `s3-prune.ts` and `webdav-target.ts` that Mail-Meow, Edge-Sonic and AWS-AccessBridge each carry,
|
|
5
|
+
* converged with the repo-specific prefix lifted into a parameter (the manifest's `name`). Pure, so the safety rules
|
|
6
|
+
* are asserted without a bucket or a WebDAV host.
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Every backup of one repo lives under `<name>/production`, so a prune can never touch an unrelated object.
|
|
10
|
+
*/
|
|
11
|
+
export declare function backupPrefix(name: string): string;
|
|
12
|
+
export interface BackupListingEntry {
|
|
13
|
+
/**
|
|
14
|
+
`YYYY-MM-DD` as reported by `aws s3 ls`.
|
|
15
|
+
*/
|
|
16
|
+
fileDate: string;
|
|
17
|
+
fileName: string;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* True only for files this workflow produced. The prune is the one destructive operation in the backup, so it refuses
|
|
21
|
+
* anything that is not a backup artifact. `.gz` is kept so objects written before the switch to xz still age out.
|
|
22
|
+
*/
|
|
23
|
+
export declare function isBackupArtifact(fileName: string): boolean;
|
|
24
|
+
/**
|
|
25
|
+
* Parse one `aws s3 ls` row: `<date> <time> <size> <key>`.
|
|
26
|
+
*/
|
|
27
|
+
export declare function parseS3ListRow(line: string): BackupListingEntry | undefined;
|
|
28
|
+
/**
|
|
29
|
+
* Decide whether a listed object should be pruned. Dates are `YYYY-MM-DD`, so lexicographic and chronological order agree.
|
|
30
|
+
*/
|
|
31
|
+
export declare function shouldDeleteBackup(entry: BackupListingEntry, cutoffDate: string): boolean;
|
|
32
|
+
/**
|
|
33
|
+
* The rclone remote name the WebDAV upload configures from the environment.
|
|
34
|
+
*/
|
|
35
|
+
export declare const WEBDAV_REMOTE = "webdav";
|
|
36
|
+
/**
|
|
37
|
+
* Where backups land on the remote, e.g. `webdav:my-app/production`. An empty base path falls back to `name`.
|
|
38
|
+
*/
|
|
39
|
+
export declare function webdavTargetDir(basePath: string, name: string): string;
|
|
40
|
+
//# sourceMappingURL=destinations.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"destinations.d.ts","sourceRoot":"","sources":["../../../src/scripts/backup/destinations.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH;;GAEG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEjD;AAED,MAAM,WAAW,kBAAkB;IACjC;;MAEE;IACF,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAI1D;AAED;;GAEG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,kBAAkB,GAAG,SAAS,CAG3E;AAED;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,kBAAkB,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAEzF;AAED;;GAEG;AACH,eAAO,MAAM,aAAa,WAAW,CAAC;AAEtC;;GAEG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAEtE"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var i=Object.defineProperty;var n=(t,e)=>i(t,"name",{value:e,configurable:!0});function u(t){return`${t}/production`}n(u,"backupPrefix");function r(t){return t.endsWith(".sql.xz")||t.endsWith(".sql.xz.enc")||t.endsWith(".sql.gz")||t.endsWith(".sql.gz.enc")}n(r,"isBackupArtifact");function c(t){const e=t.trim().split(/\s+/);return e.length<4?void 0:{fileDate:e[0],fileName:e.slice(3).join(" ")}}n(c,"parseS3ListRow");function p(t,e){return r(t.fileName)&&t.fileDate<e}n(p,"shouldDeleteBackup");const o="webdav";function d(t,e){return`${o}:${t||e}/production`}n(d,"webdavTargetDir");export{o as WEBDAV_REMOTE,u as backupPrefix,r as isBackupArtifact,c as parseS3ListRow,p as shouldDeleteBackup,d as webdavTargetDir};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/scripts/backup/destinations.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Where backups land, and which listed objects the retention prune may delete.\n *\n * Provenance: the `s3-prune.ts` and `webdav-target.ts` that Mail-Meow, Edge-Sonic and AWS-AccessBridge each carry,\n * converged with the repo-specific prefix lifted into a parameter (the manifest's `name`). Pure, so the safety rules\n * are asserted without a bucket or a WebDAV host.\n */\n\n/**\n * Every backup of one repo lives under `<name>/production`, so a prune can never touch an unrelated object.\n */\nexport function backupPrefix(name: string): string {\n return `${name}/production`;\n}\n\nexport interface BackupListingEntry {\n /**\n `YYYY-MM-DD` as reported by `aws s3 ls`.\n */\n fileDate: string;\n fileName: string;\n}\n\n/**\n * True only for files this workflow produced. The prune is the one destructive operation in the backup, so it refuses\n * anything that is not a backup artifact. `.gz` is kept so objects written before the switch to xz still age out.\n */\nexport function isBackupArtifact(fileName: string): boolean {\n return (\n fileName.endsWith('.sql.xz') || fileName.endsWith('.sql.xz.enc') || fileName.endsWith('.sql.gz') || fileName.endsWith('.sql.gz.enc')\n );\n}\n\n/**\n * Parse one `aws s3 ls` row: `<date> <time> <size> <key>`.\n */\nexport function parseS3ListRow(line: string): BackupListingEntry | undefined {\n const fields = line.trim().split(/\\s+/);\n return fields.length < 4 ? undefined : { fileDate: fields[0], fileName: fields.slice(3).join(' ') };\n}\n\n/**\n * Decide whether a listed object should be pruned. Dates are `YYYY-MM-DD`, so lexicographic and chronological order agree.\n */\nexport function shouldDeleteBackup(entry: BackupListingEntry, cutoffDate: string): boolean {\n return isBackupArtifact(entry.fileName) && entry.fileDate < cutoffDate;\n}\n\n/**\n * The rclone remote name the WebDAV upload configures from the environment.\n */\nexport const WEBDAV_REMOTE = 'webdav';\n\n/**\n * Where backups land on the remote, e.g. `webdav:my-app/production`. An empty base path falls back to `name`.\n */\nexport function webdavTargetDir(basePath: string, name: string): string {\n return `${WEBDAV_REMOTE}:${basePath || name}/production`;\n}\n"],
|
|
5
|
+
"mappings": "+EAWM,SAAUA,EAAaC,EAAY,CACvC,MAAO,GAAGA,CAAI,aAChB,CAFgBC,EAAAF,EAAA,gBAgBV,SAAUG,EAAiBC,EAAgB,CAC/C,OACEA,EAAS,SAAS,SAAS,GAAKA,EAAS,SAAS,aAAa,GAAKA,EAAS,SAAS,SAAS,GAAKA,EAAS,SAAS,aAAa,CAEvI,CAJgBF,EAAAC,EAAA,oBASV,SAAUE,EAAeC,EAAY,CACzC,MAAMC,EAASD,EAAK,KAAI,EAAG,MAAM,KAAK,EACtC,OAAOC,EAAO,OAAS,EAAI,OAAY,CAAE,SAAUA,EAAO,CAAC,EAAG,SAAUA,EAAO,MAAM,CAAC,EAAE,KAAK,GAAG,CAAC,CACnG,CAHgBL,EAAAG,EAAA,kBAQV,SAAUG,EAAmBC,EAA2BC,EAAkB,CAC9E,OAAOP,EAAiBM,EAAM,QAAQ,GAAKA,EAAM,SAAWC,CAC9D,CAFgBR,EAAAM,EAAA,sBAOT,MAAMG,EAAgB,SAKvB,SAAUC,EAAgBC,EAAkBZ,EAAY,CAC5D,MAAO,GAAGU,CAAa,IAAIE,GAAYZ,CAAI,aAC7C,CAFgBC,EAAAU,EAAA",
|
|
6
|
+
"names": ["backupPrefix", "name", "__name", "isBackupArtifact", "fileName", "parseS3ListRow", "line", "fields", "shouldDeleteBackup", "entry", "cutoffDate", "WEBDAV_REMOTE", "webdavTargetDir", "basePath"]
|
|
7
|
+
}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
#!/usr/bin/env tsx
|
|
2
1
|
/**
|
|
3
2
|
* Compress and encrypt the exported D1 dump.
|
|
4
3
|
*
|
|
@@ -31,5 +30,9 @@
|
|
|
31
30
|
* BACKUP_ENCRYPTION_KEY=… pnpm exec tsx scripts/backup/encrypt-backup.ts
|
|
32
31
|
* ```
|
|
33
32
|
*/
|
|
34
|
-
|
|
33
|
+
/**
|
|
34
|
+
* Compress and encrypt `backup.sql` in the working directory, remove the plaintext, and publish the file name as the
|
|
35
|
+
* `file` step output. Calls `fail` (exits 1) on any problem, so no unencrypted dump is left for an upload job.
|
|
36
|
+
*/
|
|
37
|
+
export declare function main(): Promise<void>;
|
|
35
38
|
//# sourceMappingURL=encrypt-backup.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"encrypt-backup.d.ts","sourceRoot":"","sources":["../../../src/scripts/backup/encrypt-backup.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"encrypt-backup.d.ts","sourceRoot":"","sources":["../../../src/scripts/backup/encrypt-backup.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAuBH;;;GAGG;AACH,wBAAsB,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAwD1C"}
|
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
`,"utf8"),m(t,{force:!0}),console.log(`Backup encrypted: ${o} (${n.byteLength} compressed bytes)`),y("file",o);
|
|
1
|
+
var p=Object.defineProperty;var c=(n,o)=>p(n,"name",{value:o,configurable:!0});import{encryptSecret as m}from"@rexezuge/d1";import{execFileSync as f}from"node:child_process";import{existsSync as l,readFileSync as u,rmSync as y,writeFileSync as d}from"node:fs";import E from"node:path";import{fail as r,setOutput as S}from"../lib/github-actions.js";import{isEntrypoint as g}from"../lib/entrypoint.js";import{backupFileName as x}from"./naming.js";const t="backup.sql",$=["-T0","-6"];async function b(){process.env.BACKUP_ENCRYPTION_KEY||r("BACKUP_ENCRYPTION_KEY is not set. Refusing to export an unencrypted database."),l(t)||r(`Expected ${t} from the export step, but it does not exist.`);const n=process.env.BACKUP_ENCRYPTION_KEY,o=x(new Date);let i;try{i=u(t,"utf8")}catch(e){r(`Could not read ${t}: ${e instanceof Error?e.message:String(e)}`)}i===""&&r(`${t} is empty. An empty dump is not a backup, and uploading one is a false sense of safety.`);let s;try{s=f("xz",[...$,"--keep","--stdout",t],{maxBuffer:512*1024*1024})}catch(e){r(`xz failed on ${t}: ${e instanceof Error?e.message:String(e)}`)}let a;try{a=await m(s.toString("base64"),n)}catch(e){r(`Could not encrypt the dump: ${e instanceof Error?e.message:String(e)}`)}d(o,`${JSON.stringify({...a,source:E.basename(t)},null,2)}
|
|
2
|
+
`,"utf8"),y(t,{force:!0}),console.log(`Backup encrypted: ${o} (${s.byteLength} compressed bytes)`),S("file",o)}c(b,"main"),g(import.meta.url)&&await b();export{b as main};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/scripts/backup/encrypt-backup.ts"],
|
|
4
|
-
"sourcesContent": ["
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": ["encryptSecret", "execFileSync", "existsSync", "readFileSync", "rmSync", "writeFileSync", "path", "fail", "setOutput", "backupFileName", "SOURCE_FILE", "XZ_ARGS", "key", "file", "plaintext", "error", "compressed", "envelope"]
|
|
4
|
+
"sourcesContent": ["/**\n * Compress and encrypt the exported D1 dump.\n *\n * Provenance: Edge-Sonic's `scripts/backup/encrypt-backup.ts`, converged with the\n * AES-GCM envelope every repo in the family already uses for its secrets. This is\n * the one backup script that ported cleanly and changed *for the better* on the way\n * in: the source shelled out to `openssl enc -aes-256-cbc -pbkdf2`, which is a\n * password-derived key with a KDF whose cost is a constant somebody chose once,\n * and which is not authenticated — a flipped byte in the ciphertext is undetectable.\n *\n * The kit's version uses `@rexezuge/d1`'s `encryptSecret`, the same WebCrypto\n * AES-256-GCM primitive the workers use, over a base64 32-byte key — the same key\n * format `resolveReplicationKey` reads. One definition of \"what an encryption key\n * looks like\" across the deploy path and the backup path is the point: a second\n * implementation is how a deploy ends up generating something the worker cannot\n * read, and here it would be how a backup ends up unreadable by the restore path.\n *\n * Fail-closed: without `BACKUP_ENCRYPTION_KEY` the script refuses to run and\n * deletes nothing, so an unencrypted dump can never reach the artifact store the\n * upload jobs read from.\n *\n * The passphrase is read from the environment rather than passed as an argument,\n * because command-line arguments are visible to any process on the runner via `ps`.\n *\n * Emits the resulting file name as the `file` step output.\n *\n * Usage, from the repo root (after `wrangler d1 export … --output=backup.sql`):\n *\n * ```bash\n * BACKUP_ENCRYPTION_KEY=… pnpm exec tsx scripts/backup/encrypt-backup.ts\n * ```\n */\n\nimport { encryptSecret } from '@rexezuge/d1';\nimport { execFileSync } from 'node:child_process';\nimport { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { fail, setOutput } from '../lib/github-actions.ts';\nimport { isEntrypoint } from '../lib/entrypoint.ts';\nimport { backupFileName } from './naming.ts';\n\n/**\nThe dump the export step leaves in the working directory.\n*/\nconst SOURCE_FILE = 'backup.sql';\n\n/**\n * xz preset 6, chosen for ratio over speed: this runs once a day against a dump\n * that is mostly SQL text and JSON blobs, and LZMA typically beats gzip by 20-30%\n * there. `-T0` uses every available thread, which matters because xz is markedly\n * slower than gzip and the job is wall-clock bound.\n */\nconst XZ_ARGS = ['-T0', '-6'];\n\n/**\n * Compress and encrypt `backup.sql` in the working directory, remove the plaintext, and publish the file name as the\n * `file` step output. Calls `fail` (exits 1) on any problem, so no unencrypted dump is left for an upload job.\n */\nexport async function main(): Promise<void> {\n if (!process.env['BACKUP_ENCRYPTION_KEY']) {\n fail('BACKUP_ENCRYPTION_KEY is not set. Refusing to export an unencrypted database.');\n }\n\n if (!existsSync(SOURCE_FILE)) {\n fail(`Expected ${SOURCE_FILE} from the export step, but it does not exist.`);\n }\n\n const key = process.env['BACKUP_ENCRYPTION_KEY'];\n const file = backupFileName(new Date());\n\n let plaintext: string;\n try {\n plaintext = readFileSync(SOURCE_FILE, 'utf8');\n } catch (error: unknown) {\n fail(`Could not read ${SOURCE_FILE}: ${error instanceof Error ? error.message : String(error)}`);\n }\n\n if (plaintext === '') {\n fail(`${SOURCE_FILE} is empty. An empty dump is not a backup, and uploading one is a false sense of safety.`);\n }\n\n /**\n * Compress first, then encrypt.\n *\n * The order matters: compression over ciphertext buys nothing, and encrypting the\n * compressed bytes means the plaintext is never re-materialised on disk at full\n * size. Unlike gzip, xz leaves its input in place, so the plaintext SQL has to be\n * removed explicitly here or it survives into the artifact store.\n */\n let compressed: Buffer;\n try {\n // `xz` is resolved from PATH deliberately: the script runs wherever the\n // operator compresses backups, and pinning an absolute path would break\n // every platform but one.\n // eslint-disable-next-line sonarjs/no-os-command-from-path\n compressed = execFileSync('xz', [...XZ_ARGS, '--keep', '--stdout', SOURCE_FILE], { maxBuffer: 512 * 1024 * 1024 });\n } catch (error: unknown) {\n fail(`xz failed on ${SOURCE_FILE}: ${error instanceof Error ? error.message : String(error)}`);\n }\n\n let envelope: { ciphertext: string; iv: string };\n try {\n envelope = await encryptSecret(compressed.toString('base64'), key);\n } catch (error: unknown) {\n // A key that is not 32 base64 bytes, or not valid base64 at all, fails here\n // rather than producing a file nothing can open.\n fail(`Could not encrypt the dump: ${error instanceof Error ? error.message : String(error)}`);\n }\n\n writeFileSync(file, `${JSON.stringify({ ...envelope, source: path.basename(SOURCE_FILE) }, null, 2)}\\n`, 'utf8');\n rmSync(SOURCE_FILE, { force: true });\n\n console.log(`Backup encrypted: ${file} (${compressed.byteLength} compressed bytes)`);\n setOutput('file', file);\n}\n\nif (isEntrypoint(import.meta.url)) {\n await main();\n}\n"],
|
|
5
|
+
"mappings": "+EAiCA,OAAS,iBAAAA,MAAqB,eAC9B,OAAS,gBAAAC,MAAoB,qBAC7B,OAAS,cAAAC,EAAY,gBAAAC,EAAc,UAAAC,EAAQ,iBAAAC,MAAqB,UAChE,OAAOC,MAAU,YACjB,OAAS,QAAAC,EAAM,aAAAC,MAAiB,2BAChC,OAAS,gBAAAC,MAAoB,uBAC7B,OAAS,kBAAAC,MAAsB,cAK/B,MAAMC,EAAc,aAQdC,EAAU,CAAC,MAAO,IAAI,EAM5B,eAAsBC,GAAI,CACnB,QAAQ,IAAI,uBACfN,EAAK,+EAA+E,EAGjFL,EAAWS,CAAW,GACzBJ,EAAK,YAAYI,CAAW,+CAA+C,EAG7E,MAAMG,EAAM,QAAQ,IAAI,sBAClBC,EAAOL,EAAe,IAAI,IAAM,EAEtC,IAAIM,EACJ,GAAI,CACFA,EAAYb,EAAaQ,EAAa,MAAM,CAC9C,OAASM,EAAgB,CACvBV,EAAK,kBAAkBI,CAAW,KAAKM,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CAAC,EAAE,CACjG,CAEID,IAAc,IAChBT,EAAK,GAAGI,CAAW,yFAAyF,EAW9G,IAAIO,EACJ,GAAI,CAKFA,EAAajB,EAAa,KAAM,CAAC,GAAGW,EAAS,SAAU,WAAYD,CAAW,EAAG,CAAE,UAAW,IAAM,KAAO,IAAI,CAAE,CACnH,OAASM,EAAgB,CACvBV,EAAK,gBAAgBI,CAAW,KAAKM,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CAAC,EAAE,CAC/F,CAEA,IAAIE,EACJ,GAAI,CACFA,EAAW,MAAMnB,EAAckB,EAAW,SAAS,QAAQ,EAAGJ,CAAG,CACnE,OAASG,EAAgB,CAGvBV,EAAK,+BAA+BU,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CAAC,EAAE,CAC9F,CAEAZ,EAAcU,EAAM,GAAG,KAAK,UAAU,CAAE,GAAGI,EAAU,OAAQb,EAAK,SAASK,CAAW,CAAC,EAAI,KAAM,CAAC,CAAC;EAAM,MAAM,EAC/GP,EAAOO,EAAa,CAAE,MAAO,EAAI,CAAE,EAEnC,QAAQ,IAAI,qBAAqBI,CAAI,KAAKG,EAAW,UAAU,oBAAoB,EACnFV,EAAU,OAAQO,CAAI,CACxB,CAxDsBK,EAAAP,EAAA,QA0DlBJ,EAAa,YAAY,GAAG,GAC9B,MAAMI,EAAI",
|
|
6
|
+
"names": ["encryptSecret", "execFileSync", "existsSync", "readFileSync", "rmSync", "writeFileSync", "path", "fail", "setOutput", "isEntrypoint", "backupFileName", "SOURCE_FILE", "XZ_ARGS", "main", "key", "file", "plaintext", "error", "compressed", "envelope", "__name"]
|
|
7
7
|
}
|
|
@@ -42,5 +42,5 @@ export declare function retentionCutoff(now: Date, days: number): string;
|
|
|
42
42
|
* `Number()` rather than `parseInt()`: `parseInt('30d')` yields 30, which would
|
|
43
43
|
* silently accept a mistyped value and prune against the wrong window.
|
|
44
44
|
*/
|
|
45
|
-
export declare function requireRetentionDays(): number;
|
|
45
|
+
export declare function requireRetentionDays(env?: NodeJS.ProcessEnv): number;
|
|
46
46
|
//# sourceMappingURL=naming.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"naming.d.ts","sourceRoot":"","sources":["../../../src/scripts/backup/naming.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH;;;;;;;;GAQG;AACH,eAAO,MAAM,kBAAkB,iBAAiB,CAAC;AAEjD;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,IAAI,GAAG,MAAM,CAG9C;AAED;;EAEE;AACF,wBAAgB,cAAc,CAAC,IAAI,EAAE,IAAI,GAAG,MAAM,CAEjD;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAE/D;AAED;;;;;;;;;GASG;AACH,wBAAgB,oBAAoB,
|
|
1
|
+
{"version":3,"file":"naming.d.ts","sourceRoot":"","sources":["../../../src/scripts/backup/naming.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH;;;;;;;;GAQG;AACH,eAAO,MAAM,kBAAkB,iBAAiB,CAAC;AAEjD;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,IAAI,GAAG,MAAM,CAG9C;AAED;;EAEE;AACF,wBAAgB,cAAc,CAAC,IAAI,EAAE,IAAI,GAAG,MAAM,CAEjD;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAE/D;AAED;;;;;;;;;GASG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,GAAE,MAAM,CAAC,UAAwB,GAAG,MAAM,CAOjF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var o=Object.defineProperty;var r=(e,t)=>o(e,"name",{value:t,configurable:!0});const i="backup_prod_";function c(e){const t=e.toISOString();return`${t.slice(0,10)}_${t.slice(11,19).replaceAll(":","-")}`}r(c,"backupStamp");function u(e){return`${i}${c(e)}.sql.xz.enc`}r(u,"backupFileName");function p(e,t){return new Date(e.getTime()-t*24*60*60*1e3).toISOString().slice(0,10)}r(p,"retentionCutoff");function a(e=process.env){const t=e.BACKUP_RETENTION_DAYS,n=Number(t);if(!Number.isFinite(n)||n<=0)throw new Error(`BACKUP_RETENTION_DAYS must be a positive number, got ${JSON.stringify(t)}.`);return n}r(a,"requireRetentionDays");export{i as BACKUP_FILE_PREFIX,u as backupFileName,c as backupStamp,a as requireRetentionDays,p as retentionCutoff};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/scripts/backup/naming.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Backup artifact naming and retention-window handling.\n *\n * Provenance: Edge-Sonic's `scripts/backup/naming.ts` and `retention.ts`,\n * converged into one module because the two answer the same question from either\n * side — what a file is called, and which of them are still worth keeping — and a\n * consumer only ever imports one.\n */\n\n/**\n * The filename prefix.\n *\n * Exported rather than inlined, because the workflow uploads with\n * `<prefix>_*.sql.xz.enc` and `if-no-files-found: error`. That glob and this prefix\n * are one fact written in two places — the failure mode being a rename here that\n * silently stops every upload while each upload job still reports success, since\n * the upload jobs skip on `needs` rather than failing.\n */\nexport const BACKUP_FILE_PREFIX = 'backup_prod_';\n\n/**\n * `2026-10-01_04-15-00` — sortable, filename-safe, and UTC.\n *\n * UTC rather than local: a retention window computed across a DST boundary is one\n * day wide in one direction, and a backup pruned a day early is a backup that was\n * never needed.\n */\nexport function backupStamp(date: Date): string {\n const iso = date.toISOString();\n return `${iso.slice(0, 10)}_${iso.slice(11, 19).replaceAll(':', '-')}`;\n}\n\n/**\nThe full artifact name: `<prefix><stamp>.sql.xz.enc`.\n*/\nexport function backupFileName(date: Date): string {\n return `${BACKUP_FILE_PREFIX}${backupStamp(date)}.sql.xz.enc`;\n}\n\n/**\n * `YYYY-MM-DD`, `days` before `now`.\n */\nexport function retentionCutoff(now: Date, days: number): string {\n return new Date(now.getTime() - days * 24 * 60 * 60 * 1000).toISOString().slice(0, 10);\n}\n\n/**\n * Read `BACKUP_RETENTION_DAYS` from the environment, rejecting bad values.\n *\n * Rejected rather than defaulted: silently falling back would either prune\n * everything or keep backups forever, and both are worse than a failed run that\n * names the problem.\n *\n * `Number()` rather than `parseInt()`: `parseInt('30d')` yields 30, which would\n * silently accept a mistyped value and prune against the wrong window.\n */\nexport function requireRetentionDays(): number {\n const raw =
|
|
5
|
-
"mappings": "+EAkBO,MAAMA,EAAqB,eAS5B,SAAUC,EAAYC,EAAU,CACpC,MAAMC,EAAMD,EAAK,YAAW,EAC5B,MAAO,GAAGC,EAAI,MAAM,EAAG,EAAE,CAAC,IAAIA,EAAI,MAAM,GAAI,EAAE,EAAE,WAAW,IAAK,GAAG,CAAC,EACtE,CAHgBC,EAAAH,EAAA,eAQV,SAAUI,EAAeH,EAAU,CACvC,MAAO,GAAGF,CAAkB,GAAGC,EAAYC,CAAI,CAAC,aAClD,CAFgBE,EAAAC,EAAA,kBAOV,SAAUC,EAAgBC,EAAWC,EAAY,CACrD,OAAO,IAAI,KAAKD,EAAI,QAAO,EAAKC,EAAO,GAAK,GAAK,GAAK,GAAI,EAAE,YAAW,EAAG,MAAM,EAAG,EAAE,CACvF,CAFgBJ,EAAAE,EAAA,mBAcV,SAAUG,
|
|
6
|
-
"names": ["BACKUP_FILE_PREFIX", "backupStamp", "date", "iso", "__name", "backupFileName", "retentionCutoff", "now", "days", "requireRetentionDays", "raw"]
|
|
4
|
+
"sourcesContent": ["/**\n * Backup artifact naming and retention-window handling.\n *\n * Provenance: Edge-Sonic's `scripts/backup/naming.ts` and `retention.ts`,\n * converged into one module because the two answer the same question from either\n * side — what a file is called, and which of them are still worth keeping — and a\n * consumer only ever imports one.\n */\n\n/**\n * The filename prefix.\n *\n * Exported rather than inlined, because the workflow uploads with\n * `<prefix>_*.sql.xz.enc` and `if-no-files-found: error`. That glob and this prefix\n * are one fact written in two places — the failure mode being a rename here that\n * silently stops every upload while each upload job still reports success, since\n * the upload jobs skip on `needs` rather than failing.\n */\nexport const BACKUP_FILE_PREFIX = 'backup_prod_';\n\n/**\n * `2026-10-01_04-15-00` — sortable, filename-safe, and UTC.\n *\n * UTC rather than local: a retention window computed across a DST boundary is one\n * day wide in one direction, and a backup pruned a day early is a backup that was\n * never needed.\n */\nexport function backupStamp(date: Date): string {\n const iso = date.toISOString();\n return `${iso.slice(0, 10)}_${iso.slice(11, 19).replaceAll(':', '-')}`;\n}\n\n/**\nThe full artifact name: `<prefix><stamp>.sql.xz.enc`.\n*/\nexport function backupFileName(date: Date): string {\n return `${BACKUP_FILE_PREFIX}${backupStamp(date)}.sql.xz.enc`;\n}\n\n/**\n * `YYYY-MM-DD`, `days` before `now`.\n */\nexport function retentionCutoff(now: Date, days: number): string {\n return new Date(now.getTime() - days * 24 * 60 * 60 * 1000).toISOString().slice(0, 10);\n}\n\n/**\n * Read `BACKUP_RETENTION_DAYS` from the environment, rejecting bad values.\n *\n * Rejected rather than defaulted: silently falling back would either prune\n * everything or keep backups forever, and both are worse than a failed run that\n * names the problem.\n *\n * `Number()` rather than `parseInt()`: `parseInt('30d')` yields 30, which would\n * silently accept a mistyped value and prune against the wrong window.\n */\nexport function requireRetentionDays(env: NodeJS.ProcessEnv = process.env): number {\n const raw = env['BACKUP_RETENTION_DAYS'];\n const days = Number(raw);\n if (!Number.isFinite(days) || days <= 0) {\n throw new Error(`BACKUP_RETENTION_DAYS must be a positive number, got ${JSON.stringify(raw)}.`);\n }\n return days;\n}\n"],
|
|
5
|
+
"mappings": "+EAkBO,MAAMA,EAAqB,eAS5B,SAAUC,EAAYC,EAAU,CACpC,MAAMC,EAAMD,EAAK,YAAW,EAC5B,MAAO,GAAGC,EAAI,MAAM,EAAG,EAAE,CAAC,IAAIA,EAAI,MAAM,GAAI,EAAE,EAAE,WAAW,IAAK,GAAG,CAAC,EACtE,CAHgBC,EAAAH,EAAA,eAQV,SAAUI,EAAeH,EAAU,CACvC,MAAO,GAAGF,CAAkB,GAAGC,EAAYC,CAAI,CAAC,aAClD,CAFgBE,EAAAC,EAAA,kBAOV,SAAUC,EAAgBC,EAAWC,EAAY,CACrD,OAAO,IAAI,KAAKD,EAAI,QAAO,EAAKC,EAAO,GAAK,GAAK,GAAK,GAAI,EAAE,YAAW,EAAG,MAAM,EAAG,EAAE,CACvF,CAFgBJ,EAAAE,EAAA,mBAcV,SAAUG,EAAqBC,EAAyB,QAAQ,IAAG,CACvE,MAAMC,EAAMD,EAAI,sBACVF,EAAO,OAAOG,CAAG,EACvB,GAAI,CAAC,OAAO,SAASH,CAAI,GAAKA,GAAQ,EACpC,MAAM,IAAI,MAAM,wDAAwD,KAAK,UAAUG,CAAG,CAAC,GAAG,EAEhG,OAAOH,CACT,CAPgBJ,EAAAK,EAAA",
|
|
6
|
+
"names": ["BACKUP_FILE_PREFIX", "backupStamp", "date", "iso", "__name", "backupFileName", "retentionCutoff", "now", "days", "requireRetentionDays", "env", "raw"]
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prepare-wrangler-config.d.ts","sourceRoot":"","sources":["../../src/scripts/prepare-wrangler-config.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"prepare-wrangler-config.d.ts","sourceRoot":"","sources":["../../src/scripts/prepare-wrangler-config.ts"],"names":[],"mappings":"AAwCA;;;;GAIG;AACH,wBAAgB,IAAI,IAAI,MAAM,EAAE,CAqB/B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var i=Object.defineProperty;var o=(r,e)=>i(r,"name",{value:e,configurable:!0});import{setOutput as t}from"./lib/github-actions.js";import{applyTopLevelPatch as
|
|
1
|
+
var i=Object.defineProperty;var o=(r,e)=>i(r,"name",{value:e,configurable:!0});import{loadManifest as n}from"../manifest.js";import{setOutput as t}from"./lib/github-actions.js";import{applyTopLevelPatch as a,applyVarsPatch as s,ensureMinimumConfigVersion as p,prepareConfigFile as m}from"./wrangler-config/patches.js";import{provisionWranglerResources as c}from"./wrangler-config/resources.js";import{isEntrypoint as f}from"./lib/entrypoint.js";function u(){m(),p(),a(),s();const r=n(process.cwd())?.features?.kv,e=c({namespaceNames:{...r?.namespaceNames},requiredKvBindings:r?.bindings??[]});return t("created",e.join(",")),console.log("Wrangler configuration is ready."),e}o(u,"main"),f(import.meta.url)&&u();export{u as main};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/scripts/prepare-wrangler-config.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Materialize `wrangler.jsonc` and provision what it refers to.\n *\n * Provenance: Durable-DAV's `scripts/prepare-wrangler-config.ts` and Edge-Sonic's\n * `scripts/deploy/prepare-wrangler-config.ts`, converged. The five ordered calls\n * live in `wrangler-config/`: read or copy the config, refuse one older than the\n * template requires, apply the caller's patches, then create whatever resources it\n * names and write their real ids over the placeholders. This file is only the\n * order; it has nothing else to do.\n *\n * Run by the deploy job before `wrangler deploy`, and by the backup workflow\n * before `wrangler d1 export` — so the database a backup covers is resolved from\n * the same config the deploy targets, with no second `D1_DATABASE_ID` secret to\n * keep in sync.\n *\n * The one thing it does beyond calling is publish what\n * `provisionWranglerResources` created, which the backup workflow reads to refuse\n * exporting a database that did not exist until this run.\n *\n * Usage, from the repo root:\n *\n * ```bash\n * pnpm exec tsx scripts/prepare-wrangler-config.ts\n * ```\n *\n * Environment:\n *\n * - `WRANGLER_JSONC` — the whole config, as a repository variable. When set it is\n * written verbatim instead of copying the template.\n * - `WRANGLER_PATCH_JSON` — top-level keys merged into the config.\n * - `WRANGLER_VARS_PATCH_JSON` — `vars` entries merged into the config.\n */\nimport { setOutput } from './lib/github-actions.ts';\nimport { applyTopLevelPatch, applyVarsPatch, ensureMinimumConfigVersion, prepareConfigFile } from './wrangler-config/patches.ts';\nimport { provisionWranglerResources } from './wrangler-config/resources.ts';\nimport { isEntrypoint } from './lib/entrypoint.ts';\n\n/**\n * Materialize and provision. Reads `process.env` and `process.cwd()` (the config paths\n * resolve when `wrangler-config/types.ts` is first imported, so a caller changing\n * directory must do so before importing this module). Returns the created resources.\n */\nexport function main(): string[] {\n prepareConfigFile();\n ensureMinimumConfigVersion();\n applyTopLevelPatch();\n applyVarsPatch();\n const created = provisionWranglerResources();\n\n // Published as a step output rather than only printed. The backup workflow needs\n // to know whether the D1 database *existed* or was created moments ago: a fresh one\n // holds no user data, and uploading that empty dump every night is a false sense\n // of safety. The alternative — re-reading the placeholder id out of\n // `wrangler.jsonc` — is unreachable, because `provisionWranglerResources` patches\n // the placeholder away before the reader ever runs.\n setOutput('created', created.join(','));\n console.log('Wrangler configuration is ready.');\n return created;\n}\n\nif (isEntrypoint(import.meta.url)) {\n main();\n}\n"],
|
|
5
|
-
"mappings": "+
|
|
6
|
-
"names": ["setOutput", "applyTopLevelPatch", "applyVarsPatch", "ensureMinimumConfigVersion", "prepareConfigFile", "provisionWranglerResources", "isEntrypoint", "main", "created", "__name"]
|
|
4
|
+
"sourcesContent": ["/**\n * Materialize `wrangler.jsonc` and provision what it refers to.\n *\n * Provenance: Durable-DAV's `scripts/prepare-wrangler-config.ts` and Edge-Sonic's\n * `scripts/deploy/prepare-wrangler-config.ts`, converged. The five ordered calls\n * live in `wrangler-config/`: read or copy the config, refuse one older than the\n * template requires, apply the caller's patches, then create whatever resources it\n * names and write their real ids over the placeholders. This file is only the\n * order; it has nothing else to do.\n *\n * Run by the deploy job before `wrangler deploy`, and by the backup workflow\n * before `wrangler d1 export` — so the database a backup covers is resolved from\n * the same config the deploy targets, with no second `D1_DATABASE_ID` secret to\n * keep in sync.\n *\n * The one thing it does beyond calling is publish what\n * `provisionWranglerResources` created, which the backup workflow reads to refuse\n * exporting a database that did not exist until this run.\n *\n * Usage, from the repo root:\n *\n * ```bash\n * pnpm exec tsx scripts/prepare-wrangler-config.ts\n * ```\n *\n * Environment:\n *\n * - `WRANGLER_JSONC` — the whole config, as a repository variable. When set it is\n * written verbatim instead of copying the template.\n * - `WRANGLER_PATCH_JSON` — top-level keys merged into the config.\n * - `WRANGLER_VARS_PATCH_JSON` — `vars` entries merged into the config.\n *\n * KV bindings come from the manifest's `features.kv` (none declared: none added).\n */\nimport { loadManifest } from '../manifest.ts';\nimport { setOutput } from './lib/github-actions.ts';\nimport { applyTopLevelPatch, applyVarsPatch, ensureMinimumConfigVersion, prepareConfigFile } from './wrangler-config/patches.ts';\nimport { provisionWranglerResources } from './wrangler-config/resources.ts';\nimport { isEntrypoint } from './lib/entrypoint.ts';\n\n/**\n * Materialize and provision. Reads `process.env` and `process.cwd()` (the config paths\n * resolve when `wrangler-config/types.ts` is first imported, so a caller changing\n * directory must do so before importing this module). Returns the created resources.\n */\nexport function main(): string[] {\n prepareConfigFile();\n ensureMinimumConfigVersion();\n applyTopLevelPatch();\n applyVarsPatch();\n // KV is manifest-driven: a repo that declares no `features.kv` gets no KV binding and no namespace (no phantom CACHE).\n const kv = loadManifest(process.cwd())?.features?.kv;\n const created = provisionWranglerResources({\n namespaceNames: { ...kv?.namespaceNames },\n requiredKvBindings: kv?.bindings ?? [],\n });\n\n // Published as a step output rather than only printed. The backup workflow needs\n // to know whether the D1 database *existed* or was created moments ago: a fresh one\n // holds no user data, and uploading that empty dump every night is a false sense\n // of safety. The alternative — re-reading the placeholder id out of\n // `wrangler.jsonc` — is unreachable, because `provisionWranglerResources` patches\n // the placeholder away before the reader ever runs.\n setOutput('created', created.join(','));\n console.log('Wrangler configuration is ready.');\n return created;\n}\n\nif (isEntrypoint(import.meta.url)) {\n main();\n}\n"],
|
|
5
|
+
"mappings": "+EAkCA,OAAS,gBAAAA,MAAoB,iBAC7B,OAAS,aAAAC,MAAiB,0BAC1B,OAAS,sBAAAC,EAAoB,kBAAAC,EAAgB,8BAAAC,EAA4B,qBAAAC,MAAyB,+BAClG,OAAS,8BAAAC,MAAkC,iCAC3C,OAAS,gBAAAC,MAAoB,sBAOvB,SAAUC,GAAI,CAClBH,EAAiB,EACjBD,EAA0B,EAC1BF,EAAkB,EAClBC,EAAc,EAEd,MAAMM,EAAKT,EAAa,QAAQ,IAAG,CAAE,GAAG,UAAU,GAC5CU,EAAUJ,EAA2B,CACzC,eAAgB,CAAE,GAAGG,GAAI,cAAc,EACvC,mBAAoBA,GAAI,UAAY,CAAA,EACrC,EAQD,OAAAR,EAAU,UAAWS,EAAQ,KAAK,GAAG,CAAC,EACtC,QAAQ,IAAI,kCAAkC,EACvCA,CACT,CArBgBC,EAAAH,EAAA,QAuBZD,EAAa,YAAY,GAAG,GAC9BC,EAAI",
|
|
6
|
+
"names": ["loadManifest", "setOutput", "applyTopLevelPatch", "applyVarsPatch", "ensureMinimumConfigVersion", "prepareConfigFile", "provisionWranglerResources", "isEntrypoint", "main", "kv", "created", "__name"]
|
|
7
7
|
}
|
|
@@ -37,6 +37,7 @@ export declare function listKVNamespaces(): KVNamespace[];
|
|
|
37
37
|
/**
|
|
38
38
|
* The namespace name a binding's namespace is created under.
|
|
39
39
|
*
|
|
40
|
+
* Takes either {@link ProvisionOptions} or (legacy) the bare binding → namespace map. `requiredKvBindings` defaults to the map's keys.
|
|
40
41
|
* `namespaceNames` is the binding → namespace map, defaulting to the kit's
|
|
41
42
|
* `DEFAULT_KV_NAMESPACE_NAMES`. A consumer whose namespaces predate that convention
|
|
42
43
|
* passes its own, so provisioning finds the namespace that already holds the data
|
|
@@ -48,13 +49,21 @@ export declare function ensureKVNamespace(config: WranglerConfig, binding: strin
|
|
|
48
49
|
The bindings a deployment always needs, whether or not a custom config lists them.
|
|
49
50
|
*/
|
|
50
51
|
export declare function getRequiredKvBindings(namespaceNames?: Record<string, string>): string[];
|
|
52
|
+
/**
|
|
53
|
+
What `prepare-wrangler` provisions beyond the placeholders a config already carries: the manifest-declared KV bindings
|
|
54
|
+
(`features.kv`). Nothing declared means no KV binding is added.
|
|
55
|
+
*/
|
|
56
|
+
export interface ProvisionOptions {
|
|
57
|
+
readonly namespaceNames?: Record<string, string>;
|
|
58
|
+
readonly requiredKvBindings?: readonly string[];
|
|
59
|
+
}
|
|
51
60
|
/**
|
|
52
61
|
* Add the always-needed KV bindings a hand-written config left out.
|
|
53
62
|
*
|
|
54
63
|
* A config supplied through `WRANGLER_JSONC` is edited by hand and drifts; without
|
|
55
64
|
* this the worker starts with an unbound `CACHE` and fails on the first read.
|
|
56
65
|
*/
|
|
57
|
-
export declare function ensureRequiredKvBindings(content: string, config: WranglerConfig, namespaceNames?: Record<string, string
|
|
66
|
+
export declare function ensureRequiredKvBindings(content: string, config: WranglerConfig, namespaceNames?: Record<string, string>, requiredBindings?: readonly string[]): string;
|
|
58
67
|
/**
|
|
59
68
|
The stores in a `secrets-store store list` table.
|
|
60
69
|
*/
|
|
@@ -88,5 +97,5 @@ export declare function ensureVectorizeIndex(indexName: string, dimensions: numb
|
|
|
88
97
|
* that appears here, since one created moments ago holds no user data and an empty
|
|
89
98
|
* dump uploaded on schedule is a false sense of safety.
|
|
90
99
|
*/
|
|
91
|
-
export declare function provisionWranglerResources(
|
|
100
|
+
export declare function provisionWranglerResources(options?: ProvisionOptions | Record<string, string>): string[];
|
|
92
101
|
//# sourceMappingURL=resources.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resources.d.ts","sourceRoot":"","sources":["../../../src/scripts/wrangler-config/resources.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAIH,OAAO,EAOL,KAAK,UAAU,EACf,KAAK,WAAW,EAChB,KAAK,WAAW,EAChB,KAAK,cAAc,EACpB,MAAM,YAAY,CAAC;AAIpB;;EAEE;AACF,MAAM,WAAW,WAAW;IAC1B,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,OAAO,CAAC;CAClB;AAED;;EAEE;AACF,wBAAgB,OAAO,CAAC,QAAQ,EAAE,UAAU,GAAG,MAAM,GAAG,SAAS,CAEhE;AAED,wBAAgB,eAAe,IAAI,UAAU,EAAE,CAE9C;AAED;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAAC,YAAY,EAAE,MAAM,GAAG,WAAW,CAclE;AAED,wBAAgB,gBAAgB,IAAI,WAAW,EAAE,CAEhD;AAED
|
|
1
|
+
{"version":3,"file":"resources.d.ts","sourceRoot":"","sources":["../../../src/scrip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,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAA8B,EACnE,gBAAgB,GAAE,SAAS,MAAM,EAA0C,GAC1E,MAAM,CAYR;AAED;;EAEE;AACF,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,WAAW,EAAE,CAmBpE;AAED,wBAAgB,gBAAgB,IAAI,WAAW,EAAE,CAQhD;AAED,wBAAgB,iBAAiB,IAAI,MAAM,CAmB1C;AAED;;EAEE;AACF,wBAAgB,WAAW,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAUtD;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,cAAc,GAAG,MAAM,EAAE,CAc7D;AAED,wBAAgB,oBAAoB,CAAC,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,IAAI,CAQhF;AAuED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,0BAA0B,CAAC,OAAO,GAAE,gBAAgB,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAA8B,GAAG,MAAM,EAAE,CAuCpI"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var D=Object.defineProperty;var c=(e,t)=>D(e,"name",{value:t,configurable:!0});import{parse as p}from"jsonc-parser";import{parseWranglerTableRows as E}from"../lib/wrangler-table.js";import{DEFAULT_HEX_ID as g,DEFAULT_KV_NAMESPACE_NAMES as l,DEFAULT_SECRET_STORE_NAME as u,DEFAULT_UUID as w,DEFAULT_WORKER_NAME as h,VECTORIZE_DIMENSIONS as q}from"./types.js";import{parseJsonArray as _,runWrangler as d}from"./cli.js";import{readConfig as I,writeConfig as K,writeConfigValue as m}from"./patches.js";function V(e){return e.uuid??e.database_id??e.id}c(V,"getD1Id");function $(){return _(d(["d1","list","--json"]),"wrangler d1 list --json")}c($,"listD1Databases");function U(e){let t=$().find(o=>o.name===e),a=!1;t===void 0&&(console.log(`Creating D1 database: ${e}`),d(["d1","create",e]),t=$().find(o=>o.name===e),a=!0);const n=t===void 0?void 0:V(t);if(n===void 0||n==="")throw new Error(`Unable to discover D1 database ID for ${e}.`);return{id:n,created:a}}c(U,"ensureD1Database");function v(){return _(d(["kv","namespace","list"]),"wrangler kv namespace list")}c(v,"listKVNamespaces");function x(e,t,a=l){return a[t]??`${e.name??h}-${t.toLowerCase()}`}c(x,"getKVNamespaceName");function A(e,t,a=l){const n=x(e,t,a),o=new Set([n,`${e.name??h}-${t}`,t]);let r=v().find(i=>{const f=i.title??i.name;return i.id!==void 0&&f!==void 0&&o.has(f)}),s=!1;if(r===void 0&&(console.log(`Creating KV namespace: ${n}`),d(["kv","namespace","create",n]),r=v().find(i=>i.id!==void 0&&(i.title??i.name)===n),s=!0),r?.id===void 0)throw new Error(`Unable to discover KV namespace ID for ${n}.`);return{id:r.id,created:s}}c(A,"ensureKVNamespace");function S(e=l){return Object.keys(e)}c(S,"getRequiredKvBindings");function C(e,t,a=l,n=S(a)){const o=new Set((t.kv_namespaces??[]).map(i=>i.binding).filter(i=>i!==void 0)),r=n.filter(i=>!o.has(i));if(r.length===0)return e;const s=[...t.kv_namespaces??[]];for(const i of r)console.log(`Adding missing KV namespace binding: ${i}`),s.push({binding:i,id:g});return m(e,["kv_namespaces"],s)}c(C,"ensureRequiredKvBindings");function k(e){const t=[];for(const a of E(e)){const n=a.at(0),o=a.at(1);n!==void 0&&o!==void 0&&/^[a-f0-9]{32}$/i.test(o)&&t.push({name:n,id:o})}return t}c(k,"parseSecretStoresTable");function b(){const e=d(["secrets-store","store","list","--remote"]);try{return _(e,"wrangler secrets-store store list --remote")}catch{return k(e)}}c(b,"listSecretStores");function T(){const e=b(),t=e.find(s=>s.name===u)??e.at(0);if(t!==void 0)return t.id;console.log(`Creating Secrets Store: ${u}`);const a=d(["secrets-store","store","create",u,"--remote"]),n=/ID:\s*([a-f0-9]{32})/i.exec(a)?.[1];if(n!==void 0)return n;const o=b(),r=o.find(s=>s.name===u)??o.at(0);if(r?.id===void 0)throw new Error(`Unable to discover Secrets Store ID for ${u}.`);return r.id}c(T,"ensureSecretStore");function N(e){try{return d(["queues","info",e]),console.log(`Queue ${e} already exists.`),!1}catch{return console.log(`Creating queue: ${e}`),d(["queues","create",e]),!0}}c(N,"ensureQueue");function R(e){const t=[],a=new Set;for(const n of e.queues?.producers??[])n.queue===""||a.has(n.queue)||(a.add(n.queue),t.push(n.queue));for(const n of e.queues?.consumers??[])n.queue===""||a.has(n.queue)||(a.add(n.queue),t.push(n.queue));return t}c(R,"queueNamesIn");function y(e,t){try{d(["vectorize","info",e]),console.log(`Vectorize index ${e} already exists.`)}catch{console.log(`Creating Vectorize index: ${e} with ${t} dimensions`),d(["vectorize","create",e,`--dimensions=${t}`,"--metric=cosine"])}}c(y,"ensureVectorizeIndex");function z(e,t,a){let n=e;for(const[o,r]of t.d1_databases?.entries()??[]){if(r.database_id!==w)continue;if(r.database_name===void 0||r.database_name==="")throw new Error(`D1 database binding ${r.binding??o} has a placeholder database_id but no database_name.`);const s=U(r.database_name);s.created&&a.push(`d1:${r.database_name}`),console.log(`Using D1 database ${r.database_name}: ${s.id}`),n=m(n,["d1_databases",o,"database_id"],s.id)}return n}c(z,"provisionD1Databases");function L(e,t,a,n){let o=e;for(const[r,s]of t.kv_namespaces?.entries()??[]){if(s.id!==g)continue;if(s.binding===void 0||s.binding==="")throw new Error(`KV namespace at index ${r} has a placeholder id but no binding.`);const i=A(t,s.binding,n),f=x(t,s.binding,n);i.created&&a.push(`kv:${f}`),console.log(`Using KV namespace ${f}: ${i.id}`),o=m(o,["kv_namespaces",r,"id"],i.id)}return o}c(L,"provisionKvNamespaces");function O(e,t,a){const n=(t.secrets_store_secrets??[]).map((s,i)=>({secret:s,index:i})).filter(({secret:s})=>s.store_id===g);if(n.length===0)return e;const o=b().some(s=>s.name===u),r=T();return o||a.push(`secrets-store:${u}`),console.log(`Using Secrets Store: ${r}`),n.reduce((s,{index:i})=>m(s,["secrets_store_secrets",i,"store_id"],r),e)}c(O,"provisionSecretStore");function F(e){return"namespaceNames"in e||"requiredKvBindings"in e}c(F,"isProvisionOptions");function H(e=l){const{namespaceNames:t,requiredKvBindings:a}=F(e)?e:{namespaceNames:e},n=t??{},o=[];let{content:r,config:s}=I();r=C(r,s,n,a??S(n)),s=p(r),r=z(r,s,o),s=p(r),r=L(r,s,o,n),s=p(r),r=O(r,s,o),K(r),s=p(r);for(const i of R(s))N(i)&&o.push(`queue:${i}`);for(const i of s.vectorize??[])y(i.index_name,q);return o}c(H,"provisionWranglerResources");export{U as ensureD1Database,A as ensureKVNamespace,N as ensureQueue,C as ensureRequiredKvBindings,T as ensureSecretStore,y as ensureVectorizeIndex,V as getD1Id,x as getKVNamespaceName,S as getRequiredKvBindings,$ as listD1Databases,v as listKVNamespaces,b as listSecretStores,k as parseSecretStoresTable,H as provisionWranglerResources,R as queueNamesIn};
|
|
@@ -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/**\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,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", "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"]
|
|
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 * Takes either {@link ProvisionOptions} or (legacy) the bare binding → namespace map. `requiredKvBindings` defaults to the map's keys.\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/**\nWhat `prepare-wrangler` provisions beyond the placeholders a config already carries: the manifest-declared KV bindings\n(`features.kv`). Nothing declared means no KV binding is added.\n*/\nexport interface ProvisionOptions {\n readonly namespaceNames?: Record<string, string>;\n readonly requiredKvBindings?: readonly string[];\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 requiredBindings: readonly string[] = getRequiredKvBindings(namespaceNames),\n): string {\n const existing = new Set((config.kv_namespaces ?? []).map((namespace) => namespace.binding).filter((binding) => binding !== undefined));\n const missing = requiredBindings.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\nfunction isProvisionOptions(value: ProvisionOptions | Record<string, string>): value is ProvisionOptions {\n return 'namespaceNames' in value || 'requiredKvBindings' in value;\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(options: ProvisionOptions | Record<string, string> = DEFAULT_KV_NAMESPACE_NAMES): string[] {\n const { namespaceNames, requiredKvBindings }: ProvisionOptions = isProvisionOptions(options) ? options : { namespaceNames: options };\n const names = namespaceNames ?? {};\n const created: string[] = [];\n let { content, config } = readConfig();\n\n content = ensureRequiredKvBindings(content, config, names, requiredKvBindings ?? getRequiredKvBindings(names));\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, names);\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,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AAU,CAAE,eAAgBA,CAAO,EAC5HpB,EAAQ3B,GAAkB,CAAA,EAC1BN,EAAoB,CAAA,EAC1B,GAAI,CAAE,QAAAc,EAAS,OAAAV,CAAM,EAAKd,EAAU,EAEpCwB,EAAUD,EAAyBC,EAASV,EAAQ6B,EAAOqB,GAAsB1C,EAAsBqB,CAAK,CAAC,EAC7G7B,EAASxB,EAAMkC,CAAO,EAOtBA,EAAU0B,EAAqB1B,EAASV,EAAQJ,CAAO,EACvDI,EAASxB,EAAMkC,CAAO,EAEtBA,EAAU8B,EAAsB9B,EAASV,EAAQJ,EAASiC,CAAK,EAC/D7B,EAASxB,EAAMkC,CAAO,EAEtBA,EAAU+B,EAAqB/B,EAASV,EAAQJ,CAAO,EAEvDT,EAAYuB,CAAO,EAEnBV,EAASxB,EAAMkC,CAAO,EACtB,UAAWiB,KAAaC,EAAa5B,CAAM,EACrC0B,EAAYC,CAAS,GACvB/B,EAAQ,KAAK,SAAS+B,CAAS,EAAE,EAOrC,UAAW1B,KAAWD,EAAO,WAAa,CAAA,EACxCiC,EAAqBhC,EAAQ,WAAYlB,CAAoB,EAG/D,OAAOa,CACT,CAvCgBL,EAAAyD,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", "requiredBindings", "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", "isProvisionOptions", "value", "provisionWranglerResources", "options", "requiredKvBindings"]
|
|
7
7
|
}
|
package/dist/vitest-aliases.d.ts
CHANGED
|
@@ -22,6 +22,10 @@ export interface VitestAlias {
|
|
|
22
22
|
* source repo, so they are not listed — a repo that needs them passes
|
|
23
23
|
* `packages` explicitly or appends `aliases`.
|
|
24
24
|
*
|
|
25
|
+
* `contracts` is the shared endpoint-contracts package the API and the SPA both import. A repo with a manifest
|
|
26
|
+
* that declares `layers` does not use this list at all: its aliases come from `layers[].package` / `dir`
|
|
27
|
+
* (see {@link WorkspaceAliasesOptions.packages}).
|
|
28
|
+
*
|
|
25
29
|
* A superset is safe: an alias for a package the consumer does not have never
|
|
26
30
|
* matches a specifier, and Vite only resolves the replacement when something
|
|
27
31
|
* imports it.
|
|
@@ -81,7 +85,9 @@ export interface WorkspaceAliasesOptions {
|
|
|
81
85
|
readonly root: string;
|
|
82
86
|
/**
|
|
83
87
|
* Workspace package directory names under `packages/` plus `background`
|
|
84
|
-
* (which lives under `apps/`).
|
|
88
|
+
* (which lives under `apps/`). When omitted: the manifest's `layers` if `<root>/.rexezuge.jsonc` declares any
|
|
89
|
+
* (each layer `dir` is aliased as `<scope>/<package or basename of dir>`), else {@link DEFAULT_WORKSPACE_PACKAGES}.
|
|
90
|
+
* An explicit list always wins.
|
|
85
91
|
*/
|
|
86
92
|
readonly packages?: readonly string[];
|
|
87
93
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vitest-aliases.d.ts","sourceRoot":"","sources":["../src/vitest-aliases.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"vitest-aliases.d.ts","sourceRoot":"","sources":["../src/vitest-aliases.ts"],"names":[],"mappings":"AAMA;;;;;;;GAOG;AACH,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC;IAC/B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;CAC9B;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,0BAA0B,EAAE,SAAS,MAAM,EAavD,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,wBAAwB,EAAE,SAAS,MAAM,EAAwC,CAAC;AAE/F;;;;;;;;;;GAUG;AACH,eAAO,MAAM,eAAe,EAAE,SAAS,MAAM,EAA6B,CAAC;AAE3E;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,UAAU,EAAE,SAAS,MAAM,EAAgE,CAAC;AAEzG;;GAEG;AACH,MAAM,WAAW,uBAAuB;IACtC;;;OAGG;IACH,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB;;;;OAIG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB;;;;;OAKG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACtC;;OAEG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACnC;;OAEG;IACH,QAAQ,CAAC,YAAY,CAAC,EAAE,SAAS,WAAW,EAAE,CAAC;CAChD;AAoCD;;;;;;;;;;;GAWG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,uBAAuB,GAAG,WAAW,EAAE,CAoBhF"}
|
package/dist/vitest-aliases.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var k=Object.defineProperty;var s=(r,t)=>k(r,"name",{value:t,configurable:!0});import{existsSync as g}from"node:fs";import{createRequire as b}from"node:module";import x from"node:path";import{fileURLToPath as d}from"node:url";import{loadManifest as w}from"./manifest.js";const A=["shared","contracts","backend-errors","backend-runtime","backend-data","provider-clients","webdav","dav-store","git-protocol","git-service","backend-services","background"],$=["workers","sockets","workflows"],U=[/(^|[/\\])@rexezuge\//],D=["react","react-dom","react/jsx-runtime","lucide-react"];function E(){try{return b(import.meta.url).resolve("@rexezuge/testing/cloudflare-workers")}catch{return null}}s(E,"kitWorkersMock");function h(r,t){try{const e=w(d(t))?.layers;return e===void 0||e.length===0?null:e.map(o=>({find:`${r}/${o.package??x.posix.basename(o.dir)}`,dir:`${o.dir}/src`}))}catch{return null}}s(h,"manifestTargets");function l(r,t){return t.map(e=>({find:`${r}/${e}`,dir:e==="background"?"apps/background/src":`packages/${e}/src`}))}s(l,"defaultTargets");function K(r){const{scope:t,root:e}=r,o=r.packages===void 0?h(t,e)??l(t,A):l(t,r.packages),p=r.mocks??$,n=s(c=>d(new URL(c,e)),"at"),a=Array.from(o,c=>({find:c.find,replacement:n(c.dir)}));for(const c of p){const i=n(`test/mocks/cloudflare-${c}.ts`),m=c==="workers"&&!g(i)?E():null;a.push({find:`cloudflare:${c}`,replacement:m??i})}const u=n("apps/api/src"),f=n("apps/web/src");return a.push({find:/^@\//,replacement:`${u}/`},{find:/^~\//,replacement:`${f}/`},...r.extraAliases??[]),a}s(K,"workspaceAliases");export{$ as DEFAULT_CLOUDFLARE_MOCKS,A as DEFAULT_WORKSPACE_PACKAGES,D as KIT_DEDUPE,U as KIT_NO_EXTERNAL,K as workspaceAliases};
|