@rexezuge/tooling 1.16.0 → 1.17.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 +4 -1
- package/dist/eslint.d.ts.map +1 -1
- package/dist/eslint.js +1 -1
- package/dist/eslint.js.map +2 -2
- 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 +16 -0
- package/dist/manifest.d.ts.map +1 -1
- package/dist/manifest.js.map +2 -2
- package/dist/scripts/init-secrets.d.ts.map +1 -1
- package/dist/scripts/init-secrets.js +2 -2
- package/dist/scripts/init-secrets.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/patches.d.ts.map +1 -1
- package/dist/scripts/wrangler-config/patches.js +3 -3
- package/dist/scripts/wrangler-config/patches.js.map +3 -3
- package/dist/scripts/wrangler-config/types.d.ts +13 -3
- package/dist/scripts/wrangler-config/types.d.ts.map +1 -1
- package/dist/scripts/wrangler-config/types.js +1 -1
- package/dist/scripts/wrangler-config/types.js.map +3 -3
- package/package.json +3 -3
- package/schema/manifest.schema.json +18 -0
- package/src/eslint.test.ts +9 -0
- package/src/eslint.ts +13 -6
- package/src/manifest-validate.ts +42 -1
- package/src/manifest.test.ts +12 -0
- package/src/manifest.ts +17 -0
- package/src/scripts/init-secrets.ts +21 -11
- package/src/scripts/prepare-wrangler-config.ts +25 -12
- package/src/scripts/prepare-wrangler.test.ts +50 -0
- package/src/scripts/wrangler-config/patches.ts +7 -7
- package/src/scripts/wrangler-config/types.ts +26 -3
package/README.md
CHANGED
|
@@ -118,9 +118,12 @@ repo's layout stays out of its lint config.
|
|
|
118
118
|
| `layers[]` | `name`, `dir` (no globs), `mayImport[]` (layer names; `[]` isolates the layer from the whole scope), optional `typeOnly[]`, `package`, `forbid[]` + `forbidMessage`, `http`, `browser`. Replaces the canonical layer table. |
|
|
119
119
|
| `quality.coverage` | `{lines, branches, functions, statements}`. The default `thresholds` of `defineUnitVitestConfig` / `defineRepoVitestConfig` (an explicit `thresholds` option wins). |
|
|
120
120
|
| `quality.godFiles` | `{soft, hard}`, read by `check-god-files`. **May only be lowered**: the validator refuses a value above the family 300 / 400. |
|
|
121
|
+
| `features.workers` | `[{template, config?}]`: the workers `prepare-wrangler` / `init-secrets` handle. Absent: `apps/api/wrangler.template.jsonc` to `wrangler.jsonc`. Paths are repo-relative; `config` is unique. |
|
|
121
122
|
| `extensions` | The open side. One object per owner namespace, free-form, never read by the kit. |
|
|
122
123
|
|
|
123
|
-
`features.
|
|
124
|
+
`features.workers` makes the template path manifest-driven: each `{ template, config? }` entry is copied to its `config` (default `wrangler.jsonc`) and
|
|
125
|
+
provisioned in turn, and `init-secrets` visits the same configs. List each `config` in `worker-cd.yml`'s `worker-configs` input so it is deployed too.
|
|
126
|
+
`WRANGLER_JSONC` holds one config, so it is refused when several workers are declared. `features.kv` drives `prepare-wrangler`'s KV provisioning: it adds the listed bindings a hand-written config lacks and creates their namespaces
|
|
124
127
|
(`<worker>-<binding lower-cased>`, or the name `namespaceNames` gives for a namespace that predates that convention). **No `features.kv`, no KV binding and no
|
|
125
128
|
namespace**: a repo without a cache no longer gets a phantom `CACHE`. A placeholder KV id the config itself carries is still resolved. `features.web.buildScript`
|
|
126
129
|
names a **root** `package.json` script that builds the SPA (a wrapper such as `verify:tailwind && build`); CI and CD run `pnpm run <script>` instead of
|
package/dist/eslint.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"eslint.d.ts","sourceRoot":"","sources":["../src/eslint.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkDG;AASH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAEpD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAMjE,YAAY,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAsCjE;;;;;;;;;;GAUG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,qBAAqB,GAAG,UAAU,CAAC,WAAW,
|
|
1
|
+
{"version":3,"file":"eslint.d.ts","sourceRoot":"","sources":["../src/eslint.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkDG;AASH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAEpD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAMjE,YAAY,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAsCjE;;;;;;;;;;GAUG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,qBAAqB,GAAG,UAAU,CAAC,WAAW,CAmJ3F"}
|
package/dist/eslint.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var l=Object.defineProperty;var t=(s,e)=>l(s,"name",{value:e,configurable:!0});import
|
|
1
|
+
var l=Object.defineProperty;var t=(s,e)=>l(s,"name",{value:e,configurable:!0});import i from"globals";import a from"typescript-eslint";import m from"eslint-plugin-unicorn";import{configs as g}from"eslint-plugin-sonarjs";import d from"eslint-plugin-regexp";import u from"eslint-config-prettier";import R from"eslint-plugin-prettier";import{DEFAULT_PROJECT_DIRS as j,layerBans as x,restrictedDynamicImports as D,restrictedImports as w}from"./eslint-boundaries.js";import{manifestBrowserDirs as C,manifestHttpDirs as S,manifestLayerBans as E}from"./eslint-manifest.js";import{strictConfigs as L}from"./eslint-strict.js";import{loadManifest as b}from"./manifest.js";import{SONARJS_RULES as y,TEST_RULES as h,TYPESCRIPT_RULES as O,UNICORN_RULES as T}from"./eslint-rules.js";function W(s){return s}t(W,"asConfig");function Y(s){return s}t(Y,"asRules");function $(s){const e=s.manifest===!1?null:s.manifest??b(s.tsconfigRootDir??process.cwd()),n=s.scope??e?.scope;if(n===void 0)throw new Error("defineRepoLintConfig: pass `scope`, or add a `.rexezuge.jsonc` manifest that declares it.");const f=s.projectDirs??j,c=[...e?.layers===void 0?x(n).filter(o=>f.some(p=>o.dir.startsWith(p))):E(e),...s.extraLayers??[]],r=C(e);return a.config({ignores:["eslint.config.mjs","eslint.config.js","scripts/**","worker-configuration.d.ts","local/**","app/dist/**","apps/web/dist/**","apps/*/dist/**","src/generated/**","apps/api/src/generated/**","coverage/**","coverage-integration/**","coverage-web/**","node_modules/**",...s.extraIgnores??[]]},{files:["**/*.{js,mjs,cjs,ts,mts,cts,tsx,jsx}"],languageOptions:{globals:i.node}},{files:["**/*.{ts,mts,cts,tsx}"],extends:a.configs.recommendedTypeChecked,languageOptions:{parserOptions:{projectService:!0,tsconfigRootDir:s.tsconfigRootDir??process.cwd()}}},{files:["**/*.{ts,mts,cts,tsx}"],rules:O},m.configs["flat/recommended"]??m.configs.recommended,g.recommended,{rules:T},{rules:y},d.configs["flat/recommended"],u,{plugins:{prettier:R},rules:{"prettier/prettier":"error"}},...w(c),...D(c),...L({httpDirs:[...S(e),...s.httpDirs??[]],browserDirs:r}),...r.length===0?[]:[{files:r.map(o=>`${o}/**/*.{ts,tsx,js,jsx,mts,cts,mjs,cjs}`),languageOptions:{globals:{...i.node,...i.browser}}}],{files:["test/**/*.{ts,tsx,mts,cts}","**/*.test.{ts,tsx,mts,cts}","**/*.spec.{ts,tsx,mts,cts}"],rules:h})}t($,"defineRepoLintConfig");export{$ as defineRepoLintConfig};
|
package/dist/eslint.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/eslint.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * The converged ESLint flat config for a monorepo in the Rexezuge family.\n *\n * Provenance: the base is Durable-DAV's `eslint.config.mjs` (the most\n * elaborate of the nine repos, with the layered `no-restricted-imports` boundary\n * rules). Merged in from the stacks that share the same plugin set:\n *\n * - **Edge-Sonic** — `test/**` is *not* ignored (it is linted like everything else,\n * with a narrow override block for Vitest idioms), and `unicorn/prefer-ternary`\n * is off. Edge-Sonic is also the source for the dynamic-`import()` boundary\n * guard and its `apps/web` layer block.\n * - **Mail-Meow** — `prettier/prettier` is an **error**, not a warning.\n * - **AWS-AccessBridge** — the `apps/api` DAO/service boundary uses\n * `allowTypeImports` where the source repos do not. It is also the source for\n * the anchored skip patterns and the symlink-safe walk that came out of its own\n * backlog.\n * - **CalDAV-Bridge, Mail-Otter, Durable-DAV-Router, Edge-Git, Agent-Router** —\n * the `provider-clients` / `webdav`+`dav-store` / `git-protocol`+`git-service`\n * layers and the per-client `apps/api` alternatives in the boundary table.\n *\n * Canonical decisions, and why each one:\n *\n * 1. **`prettier/prettier: 'error'`.** Three of the four source repos had it at\n * `warn`, which under `eslint --quiet` is unenforceable — a gate nobody can see\n * is a gate that has never run. Formatting drift is therefore a hard failure.\n * 2. **The layered boundary rules are parameterized by `scope`.** Every source\n * repo wrote the same blocks with a different npm scope hardcoded; the\n * factory takes `scope` (`'@myapp'`) and generates the `@myapp/*` patterns.\n * The table itself lives in {@link ./eslint-boundaries.ts} and covers the\n * family superset — a repo without a domain package never triggers its ban,\n * so no repo needs `extraLayers` for a known package.\n * 3. **`test/**` is linted, not ignored.** Durable-DAV/AWS/Mail-Meow ignored it;\n * Edge-Sonic does not, and records why: ~200 KB of test code had accumulated\n * violations that nothing reported.\n * 4. **`apps/web` is a layer in its own right**, banned from every `@scope/*`\n * package. Edge-Sonic is the only source with that block; the others had none,\n * which is how their layer table's \"may import: the browser\" was a convention\n * rather than a gate. A backend package imported by the SPA compiles and then\n * fails at bundle time, with the error pointing at the bundler.\n * 5. **jsdom + node globals for web files.** The sources ran `globals.node` only;\n * `apps/web` needs browser globals as well, and the vitest config for the SPA\n * runs under jsdom, so the lint environment matches the test environment.\n * 6. **`eslint-plugin-react-hooks` is NOT imported here.** The kit stays\n * zero-dependency, and the plugin belongs to the app that has JSX. A consumer\n * appends it — the README shows the four lines.\n *\n * The rule bodies live in {@link ./eslint-rules.ts} and the boundary table in\n * {@link ./eslint-boundaries.ts}; this file is the assembly. A repo that needs a\n * boundary the canonical table does not name passes `extraLayers` — see\n * {@link RepoLintConfigOptions}.\n */\n\nimport globals from 'globals';\nimport tseslint from 'typescript-eslint';\nimport unicorn from 'eslint-plugin-unicorn';\nimport { configs as sonarjsConfigs } from 'eslint-plugin-sonarjs';\nimport pluginRegexp from 'eslint-plugin-regexp';\nimport eslintConfigPrettier from 'eslint-config-prettier';\nimport prettier from 'eslint-plugin-prettier';\nimport type { FlatConfig } from 'typescript-eslint';\nimport { DEFAULT_PROJECT_DIRS, layerBans, restrictedDynamicImports, restrictedImports } from './eslint-boundaries.ts';\nimport type { RepoLintConfigOptions } from './eslint-options.ts';\nimport { manifestBrowserDirs, manifestHttpDirs, manifestLayerBans } from './eslint-manifest.ts';\nimport { strictConfigs } from './eslint-strict.ts';\nimport { loadManifest } from './manifest.ts';\nimport { SONARJS_RULES, TEST_RULES, TYPESCRIPT_RULES, UNICORN_RULES } from './eslint-rules.ts';\n\nexport type { RepoLintConfigOptions } from './eslint-options.ts';\n\n/**\n * One argument to `tseslint.config()`.\n */\ntype ConfigInput = Parameters<typeof tseslint.config>[number];\n\n/**\n * A plugin preset or config object as the source repos pass it.\n */\ntype MaybeConfig = FlatConfig.Config | readonly FlatConfig.Config[];\n\n/**\n * Bridge a third-party preset into `tseslint.config()`.\n *\n * `sonarjs`' `recommended` preset is typed as a union that includes the legacy\n * config shape, which `tseslint.config()` does not accept — but ESLint accepts it\n * at runtime, which is the only thing that matters here. One checked assertion,\n * rather than forking the plugin's own types.\n */\nfunction asConfig(config: MaybeConfig): ConfigInput {\n return config as ConfigInput;\n}\n\n/**\n * Bridge a rule block onto `tseslint.config()`'s `rules` field.\n *\n * The blocks in `eslint-rules.ts` are written as ESLint expects them —\n * `'off' | 'warn' | 'error' | [level, ...options]` — but spelled as data so a\n * rule's reason comment sits beside the rule itself. ESLint's own `RuleEntry`\n * union is narrower than the data shape, and widening every entry to that union\n * would buy nothing; one assertion here, with the reason, is the cheaper and\n * more honest of the two.\n */\nfunction asRules(block: Readonly<Record<string, unknown>>): FlatConfig.Config['rules'] {\n return block as FlatConfig.Config['rules'];\n}\n\n/**\n * Build the repo's flat config.\n *\n * Consumed from the repo root as three lines:\n *\n * ```js\n * // eslint.config.mjs\n * import { defineRepoLintConfig } from '@rexezuge/tooling/eslint';\n * export default defineRepoLintConfig({ scope: '@myapp' });\n * ```\n */\nexport function defineRepoLintConfig(options: RepoLintConfigOptions): FlatConfig.ConfigArray {\n const manifest = options.manifest === false ? null : (options.manifest ?? loadManifest(options.tsconfigRootDir ?? process.cwd()));\n const scope = options.scope ?? manifest?.scope;\n if (scope === undefined) throw new Error('defineRepoLintConfig: pass `scope`, or add a `.rexezuge.jsonc` manifest that declares it.');\n const projectDirs = options.projectDirs ?? DEFAULT_PROJECT_DIRS;\n const layerRows =\n manifest?.layers === undefined\n ? layerBans(scope).filter((layer) => projectDirs.some((dir) => layer.dir.startsWith(dir)))\n : manifestLayerBans(manifest);\n const bans = [...layerRows, ...(options.extraLayers ?? [])];\n const browserDirs = manifestBrowserDirs(manifest);\n\n return tseslint.config(\n {\n ignores: [\n 'eslint.config.mjs',\n 'eslint.config.js',\n 'scripts/**',\n 'worker-configuration.d.ts',\n 'local/**',\n 'app/dist/**',\n 'apps/web/dist/**',\n 'apps/*/dist/**',\n 'src/generated/**',\n 'apps/api/src/generated/**',\n 'coverage/**',\n 'coverage-integration/**',\n 'coverage-web/**',\n 'node_modules/**',\n ...(options.extraIgnores ?? []),\n ],\n },\n\n // Base: globals for all JS/TS source files. Node is the floor because the\n // scripts and the workers both run on it; the web block below adds browser\n // globals rather than replacing them, so a shared file that touches both\n // (there are several in `shared/`) still lints.\n {\n files: ['**/*.{js,mjs,cjs,ts,mts,cts,tsx,jsx}'],\n languageOptions: {\n globals: globals.node,\n },\n },\n\n // Type-aware TS rules, scoped to TS files only.\n {\n files: ['**/*.{ts,mts,cts,tsx}'],\n extends: tseslint.configs.recommendedTypeChecked,\n languageOptions: {\n parserOptions: {\n projectService: true,\n tsconfigRootDir: options.tsconfigRootDir ?? process.cwd(),\n },\n },\n },\n\n // --- typescript-eslint overrides (identical in all four source stacks) ---\n {\n files: ['**/*.{ts,mts,cts,tsx}'],\n rules: asRules(TYPESCRIPT_RULES),\n },\n\n // --- Unicorn + SonarJS presets, then the family's off-block ---\n //\n // Both presets come first on purpose: UNICORN_RULES carries `sonarjs/*`\n // offs as well as `unicorn/*` ones (it is the family's single\n // \"deliberately does not follow\" block), and a preset applied after it\n // would re-enable them. That is exactly what shipped — the sonarjs preset\n // sat between the block and the rules it relaxed, so `void-use`,\n // `different-types-comparison`, `use-type-alias`, `redundant-type-aliases`,\n // `no-nested-assignment` and `no-all-duplicated-branches` linted as errors\n // in every consumer. The two presets do not share rule names, so their\n // relative order decides nothing.\n //\n // The unicorn preset is read from whichever spelling the installed major\n // publishes. v78 dropped the `flat/`-prefixed aliases and exports the flat\n // configs directly, so `configs['flat/recommended']` is `undefined` there —\n // and a config object built around it is `undefined` too, which ESLint\n // rejects outright with \"Unexpected undefined config\". The fallback is\n // what makes the factory work on both majors rather than only the one the\n // kit was written against.\n asConfig(unicorn.configs['flat/recommended'] ?? unicorn.configs.recommended),\n asConfig(sonarjsConfigs.recommended),\n {\n rules: asRules(UNICORN_RULES),\n },\n\n // --- SonarJS advisories ---\n {\n rules: asRules(SONARJS_RULES),\n },\n\n // --- Regexp: static analysis for regular expressions ---\n asConfig(pluginRegexp.configs['flat/recommended']),\n\n // --- Prettier: formatting drift is a hard error ---\n //\n // Mail-Meow's decision, adopted repo-wide because the alternative is\n // unenforceable: `pnpm run lint` is `eslint --fix --quiet` in three of the\n // four source repos, and `--quiet` discards every warning, so a\n // `prettier/prettier` *warning* is a silent no-op. 242 files were in that\n // state in Edge-Sonic: the gate had never run.\n asConfig(eslintConfigPrettier),\n {\n plugins: { prettier },\n rules: {\n 'prettier/prettier': 'error',\n },\n },\n\n // --- Import direction guardrails (parameterized by scope) ---\n ...restrictedImports(bans),\n ...restrictedDynamicImports(bans),\n\n // --- Strict side: family rules a repo waives per file, never wholesale ---\n ...strictConfigs({ httpDirs: [...manifestHttpDirs(manifest), ...(options.httpDirs ?? [])], browserDirs }),\n\n // --- Web: browser globals, matching the jsdom test environment ---\n //\n // The sources linted `apps/web` under `globals.node` only, so `window`,\n // `document` and `localStorage` read as undefined globals. The vitest web\n // config runs those suites under jsdom; the lint environment should agree\n // with the environment the code is executed in, or the rule is reporting\n // something untrue about how the file behaves.\n {\n files: browserDirs.map((dir) => `${dir}/**/*.{ts,tsx,js,jsx,mts,cts,mjs,cjs}`),\n languageOptions: {\n globals: { ...globals.node, ...globals.browser },\n },\n },\n\n // --- Test suite ---\n //\n // `test/**` is deliberately NOT in the ignores list above. See TEST_RULES\n // for the override block and the reasoning behind it.\n {\n files: ['test/**/*.{ts,tsx,mts,cts}', '**/*.test.{ts,tsx,mts,cts}', '**/*.spec.{ts,tsx,mts,cts}'],\n rules: asRules(TEST_RULES),\n },\n );\n}\n"],
|
|
5
|
-
"mappings": "+EAoDA,OAAOA,MAAa,UACpB,OAAOC,MAAc,oBACrB,OAAOC,MAAa,wBACpB,OAAS,WAAWC,MAAsB,wBAC1C,OAAOC,MAAkB,uBACzB,OAAOC,MAA0B,yBACjC,OAAOC,MAAc,yBAErB,OAAS,wBAAAC,EAAsB,aAAAC,EAAW,4BAAAC,EAA0B,qBAAAC,MAAyB,yBAE7F,OAAS,uBAAAC,EAAqB,oBAAAC,EAAkB,qBAAAC,MAAyB,uBACzE,OAAS,iBAAAC,MAAqB,qBAC9B,OAAS,gBAAAC,MAAoB,gBAC7B,OAAS,iBAAAC,EAAe,cAAAC,EAAY,oBAAAC,EAAkB,iBAAAC,MAAq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B,UAKzB,GAAGI,EAAkBoB,CAAI,EACzB,GAAGrB,EAAyBqB,CAAI,EAGhC,GAAGhB,EAAc,CAAE,SAAU,CAAC,GAAGF,EAAiBe,CAAQ,EAAG,GAAID,EAAQ,UAAY,CAAA,CAAG,EAAG,YAAAO,CAAW,CAAE,
|
|
4
|
+
"sourcesContent": ["/**\n * The converged ESLint flat config for a monorepo in the Rexezuge family.\n *\n * Provenance: the base is Durable-DAV's `eslint.config.mjs` (the most\n * elaborate of the nine repos, with the layered `no-restricted-imports` boundary\n * rules). Merged in from the stacks that share the same plugin set:\n *\n * - **Edge-Sonic** — `test/**` is *not* ignored (it is linted like everything else,\n * with a narrow override block for Vitest idioms), and `unicorn/prefer-ternary`\n * is off. Edge-Sonic is also the source for the dynamic-`import()` boundary\n * guard and its `apps/web` layer block.\n * - **Mail-Meow** — `prettier/prettier` is an **error**, not a warning.\n * - **AWS-AccessBridge** — the `apps/api` DAO/service boundary uses\n * `allowTypeImports` where the source repos do not. It is also the source for\n * the anchored skip patterns and the symlink-safe walk that came out of its own\n * backlog.\n * - **CalDAV-Bridge, Mail-Otter, Durable-DAV-Router, Edge-Git, Agent-Router** —\n * the `provider-clients` / `webdav`+`dav-store` / `git-protocol`+`git-service`\n * layers and the per-client `apps/api` alternatives in the boundary table.\n *\n * Canonical decisions, and why each one:\n *\n * 1. **`prettier/prettier: 'error'`.** Three of the four source repos had it at\n * `warn`, which under `eslint --quiet` is unenforceable — a gate nobody can see\n * is a gate that has never run. Formatting drift is therefore a hard failure.\n * 2. **The layered boundary rules are parameterized by `scope`.** Every source\n * repo wrote the same blocks with a different npm scope hardcoded; the\n * factory takes `scope` (`'@myapp'`) and generates the `@myapp/*` patterns.\n * The table itself lives in {@link ./eslint-boundaries.ts} and covers the\n * family superset — a repo without a domain package never triggers its ban,\n * so no repo needs `extraLayers` for a known package.\n * 3. **`test/**` is linted, not ignored.** Durable-DAV/AWS/Mail-Meow ignored it;\n * Edge-Sonic does not, and records why: ~200 KB of test code had accumulated\n * violations that nothing reported.\n * 4. **`apps/web` is a layer in its own right**, banned from every `@scope/*`\n * package. Edge-Sonic is the only source with that block; the others had none,\n * which is how their layer table's \"may import: the browser\" was a convention\n * rather than a gate. A backend package imported by the SPA compiles and then\n * fails at bundle time, with the error pointing at the bundler.\n * 5. **jsdom + node globals for web files.** The sources ran `globals.node` only;\n * `apps/web` needs browser globals as well, and the vitest config for the SPA\n * runs under jsdom, so the lint environment matches the test environment.\n * 6. **`eslint-plugin-react-hooks` is NOT imported here.** The kit stays\n * zero-dependency, and the plugin belongs to the app that has JSX. A consumer\n * appends it — the README shows the four lines.\n *\n * The rule bodies live in {@link ./eslint-rules.ts} and the boundary table in\n * {@link ./eslint-boundaries.ts}; this file is the assembly. A repo that needs a\n * boundary the canonical table does not name passes `extraLayers` — see\n * {@link RepoLintConfigOptions}.\n */\n\nimport globals from 'globals';\nimport tseslint from 'typescript-eslint';\nimport unicorn from 'eslint-plugin-unicorn';\nimport { configs as sonarjsConfigs } from 'eslint-plugin-sonarjs';\nimport pluginRegexp from 'eslint-plugin-regexp';\nimport eslintConfigPrettier from 'eslint-config-prettier';\nimport prettier from 'eslint-plugin-prettier';\nimport type { FlatConfig } from 'typescript-eslint';\nimport { DEFAULT_PROJECT_DIRS, layerBans, restrictedDynamicImports, restrictedImports } from './eslint-boundaries.ts';\nimport type { RepoLintConfigOptions } from './eslint-options.ts';\nimport { manifestBrowserDirs, manifestHttpDirs, manifestLayerBans } from './eslint-manifest.ts';\nimport { strictConfigs } from './eslint-strict.ts';\nimport { loadManifest } from './manifest.ts';\nimport { SONARJS_RULES, TEST_RULES, TYPESCRIPT_RULES, UNICORN_RULES } from './eslint-rules.ts';\n\nexport type { RepoLintConfigOptions } from './eslint-options.ts';\n\n/**\n * One argument to `tseslint.config()`.\n */\ntype ConfigInput = Parameters<typeof tseslint.config>[number];\n\n/**\n * A plugin preset or config object as the source repos pass it.\n */\ntype MaybeConfig = FlatConfig.Config | readonly FlatConfig.Config[];\n\n/**\n * Bridge a third-party preset into `tseslint.config()`.\n *\n * `sonarjs`' `recommended` preset is typed as a union that includes the legacy\n * config shape, which `tseslint.config()` does not accept — but ESLint accepts it\n * at runtime, which is the only thing that matters here. One checked assertion,\n * rather than forking the plugin's own types.\n */\nfunction asConfig(config: MaybeConfig): ConfigInput {\n return config as ConfigInput;\n}\n\n/**\n * Bridge a rule block onto `tseslint.config()`'s `rules` field.\n *\n * The blocks in `eslint-rules.ts` are written as ESLint expects them —\n * `'off' | 'warn' | 'error' | [level, ...options]` — but spelled as data so a\n * rule's reason comment sits beside the rule itself. ESLint's own `RuleEntry`\n * union is narrower than the data shape, and widening every entry to that union\n * would buy nothing; one assertion here, with the reason, is the cheaper and\n * more honest of the two.\n */\nfunction asRules(block: Readonly<Record<string, unknown>>): FlatConfig.Config['rules'] {\n return block as FlatConfig.Config['rules'];\n}\n\n/**\n * Build the repo's flat config.\n *\n * Consumed from the repo root as three lines:\n *\n * ```js\n * // eslint.config.mjs\n * import { defineRepoLintConfig } from '@rexezuge/tooling/eslint';\n * export default defineRepoLintConfig({ scope: '@myapp' });\n * ```\n */\nexport function defineRepoLintConfig(options: RepoLintConfigOptions): FlatConfig.ConfigArray {\n const manifest = options.manifest === false ? null : (options.manifest ?? loadManifest(options.tsconfigRootDir ?? process.cwd()));\n const scope = options.scope ?? manifest?.scope;\n if (scope === undefined) throw new Error('defineRepoLintConfig: pass `scope`, or add a `.rexezuge.jsonc` manifest that declares it.');\n const projectDirs = options.projectDirs ?? DEFAULT_PROJECT_DIRS;\n const layerRows =\n manifest?.layers === undefined\n ? layerBans(scope).filter((layer) => projectDirs.some((dir) => layer.dir.startsWith(dir)))\n : manifestLayerBans(manifest);\n const bans = [...layerRows, ...(options.extraLayers ?? [])];\n const browserDirs = manifestBrowserDirs(manifest);\n\n return tseslint.config(\n {\n ignores: [\n 'eslint.config.mjs',\n 'eslint.config.js',\n 'scripts/**',\n 'worker-configuration.d.ts',\n 'local/**',\n 'app/dist/**',\n 'apps/web/dist/**',\n 'apps/*/dist/**',\n 'src/generated/**',\n 'apps/api/src/generated/**',\n 'coverage/**',\n 'coverage-integration/**',\n 'coverage-web/**',\n 'node_modules/**',\n ...(options.extraIgnores ?? []),\n ],\n },\n\n // Base: globals for all JS/TS source files. Node is the floor because the\n // scripts and the workers both run on it; the web block below adds browser\n // globals rather than replacing them, so a shared file that touches both\n // (there are several in `shared/`) still lints.\n {\n files: ['**/*.{js,mjs,cjs,ts,mts,cts,tsx,jsx}'],\n languageOptions: {\n globals: globals.node,\n },\n },\n\n // Type-aware TS rules, scoped to TS files only.\n {\n files: ['**/*.{ts,mts,cts,tsx}'],\n extends: tseslint.configs.recommendedTypeChecked,\n languageOptions: {\n parserOptions: {\n projectService: true,\n tsconfigRootDir: options.tsconfigRootDir ?? process.cwd(),\n },\n },\n },\n\n // --- typescript-eslint overrides (identical in all four source stacks) ---\n {\n files: ['**/*.{ts,mts,cts,tsx}'],\n rules: asRules(TYPESCRIPT_RULES),\n },\n\n // --- Unicorn + SonarJS presets, then the family's off-block ---\n //\n // Both presets come first on purpose: UNICORN_RULES carries `sonarjs/*`\n // offs as well as `unicorn/*` ones (it is the family's single\n // \"deliberately does not follow\" block), and a preset applied after it\n // would re-enable them. That is exactly what shipped — the sonarjs preset\n // sat between the block and the rules it relaxed, so `void-use`,\n // `different-types-comparison`, `use-type-alias`, `redundant-type-aliases`,\n // `no-nested-assignment` and `no-all-duplicated-branches` linted as errors\n // in every consumer. The two presets do not share rule names, so their\n // relative order decides nothing.\n //\n // The unicorn preset is read from whichever spelling the installed major\n // publishes. v78 dropped the `flat/`-prefixed aliases and exports the flat\n // configs directly, so `configs['flat/recommended']` is `undefined` there —\n // and a config object built around it is `undefined` too, which ESLint\n // rejects outright with \"Unexpected undefined config\". The fallback is\n // what makes the factory work on both majors rather than only the one the\n // kit was written against.\n asConfig(unicorn.configs['flat/recommended'] ?? unicorn.configs.recommended),\n asConfig(sonarjsConfigs.recommended),\n {\n rules: asRules(UNICORN_RULES),\n },\n\n // --- SonarJS advisories ---\n {\n rules: asRules(SONARJS_RULES),\n },\n\n // --- Regexp: static analysis for regular expressions ---\n asConfig(pluginRegexp.configs['flat/recommended']),\n\n // --- Prettier: formatting drift is a hard error ---\n //\n // Mail-Meow's decision, adopted repo-wide because the alternative is\n // unenforceable: `pnpm run lint` is `eslint --fix --quiet` in three of the\n // four source repos, and `--quiet` discards every warning, so a\n // `prettier/prettier` *warning* is a silent no-op. 242 files were in that\n // state in Edge-Sonic: the gate had never run.\n asConfig(eslintConfigPrettier),\n {\n plugins: { prettier },\n rules: {\n 'prettier/prettier': 'error',\n },\n },\n\n // --- Import direction guardrails (parameterized by scope) ---\n ...restrictedImports(bans),\n ...restrictedDynamicImports(bans),\n\n // --- Strict side: family rules a repo waives per file, never wholesale ---\n ...strictConfigs({ httpDirs: [...manifestHttpDirs(manifest), ...(options.httpDirs ?? [])], browserDirs }),\n\n // --- Web: browser globals, matching the jsdom test environment ---\n //\n // The sources linted `apps/web` under `globals.node` only, so `window`,\n // `document` and `localStorage` read as undefined globals. The vitest web\n // config runs those suites under jsdom; the lint environment should agree\n // with the environment the code is executed in, or the rule is reporting\n // something untrue about how the file behaves.\n //\n // Omitted when the repo has no browser dirs: a block with `files: []` is\n // rejected by ESLint (\"Expected value to be a non-empty array\").\n ...(browserDirs.length === 0\n ? []\n : [\n {\n files: browserDirs.map((dir) => `${dir}/**/*.{ts,tsx,js,jsx,mts,cts,mjs,cjs}`),\n languageOptions: {\n globals: { ...globals.node, ...globals.browser },\n },\n },\n ]),\n\n // --- Test suite ---\n //\n // `test/**` is deliberately NOT in the ignores list above. See TEST_RULES\n // for the override block and the reasoning behind it.\n {\n files: ['test/**/*.{ts,tsx,mts,cts}', '**/*.test.{ts,tsx,mts,cts}', '**/*.spec.{ts,tsx,mts,cts}'],\n rules: asRules(TEST_RULES),\n },\n );\n}\n"],
|
|
5
|
+
"mappings": "+EAoDA,OAAOA,MAAa,UACpB,OAAOC,MAAc,o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AO,CAAC,uBAAuB,EAC/B,QAASC,EAAS,QAAQ,uBAC1B,gBAAiB,CACf,cAAe,CACb,eAAgB,GAChB,gBAAiByB,EAAQ,iBAAmB,QAAQ,IAAG,KAM7D,CACE,MAAO,CAAC,uBAAuB,EAC/B,MAAeR,GAsBRhB,EAAQ,QAAQ,kBAAkB,GAAKA,EAAQ,QAAQ,YACvDC,EAAe,YACxB,CACE,MAAegB,GAIjB,CACE,MAAeH,GAIRZ,EAAa,QAAQ,kBAAkB,EASvCC,EACT,CACE,QAAS,CAAE,SAAAC,CAAQ,EACnB,MAAO,CACL,oBAAqB,UAKzB,GAAGI,EAAkBoB,CAAI,EACzB,GAAGrB,EAAyBqB,CAAI,EAGhC,GAAGhB,EAAc,CAAE,SAAU,CAAC,GAAGF,EAAiBe,CAAQ,EAAG,GAAID,EAAQ,UAAY,CAAA,CAAG,EAAG,YAAAO,CAAW,CAAE,EAYxG,GAAIA,EAAY,SAAW,EACvB,CAAA,EACA,CACE,CACE,MAAOA,EAAY,IAAKD,GAAQ,GAAGA,CAAG,uCAAuC,EAC7E,gBAAiB,CACf,QAAS,CAAE,GAAGhC,EAAQ,KAAM,GAAGA,EAAQ,OAAO,KASxD,CACE,MAAO,CAAC,6BAA8B,6BAA8B,4BAA4B,EAChG,MAAeiB,EAChB,CAEL,CAnJgBK,EAAAG,EAAA",
|
|
6
6
|
"names": ["globals", "tseslint", "unicorn", "sonarjsConfigs", "pluginRegexp", "eslintConfigPrettier", "prettier", "DEFAULT_PROJECT_DIRS", "layerBans", "restrictedDynamicImports", "restrictedImports", "manifestBrowserDirs", "manifestHttpDirs", "manifestLayerBans", "strictConfigs", "loadManifest", "SONARJS_RULES", "TEST_RULES", "TYPESCRIPT_RULES", "UNICORN_RULES", "asConfig", "config", "__name", "asRules", "block", "defineRepoLintConfig", "options", "manifest", "scope", "projectDirs", "bans", "layer", "dir", "browserDirs"]
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manifest-validate.d.ts","sourceRoot":"","sources":["../src/manifest-validate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAkB,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAExE;;EAEE;AACF,eAAO,MAAM,sBAAsB;;;CAAoC,CAAC;
|
|
1
|
+
{"version":3,"file":"manifest-validate.d.ts","sourceRoot":"","sources":["../src/manifest-validate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAkB,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAExE;;EAEE;AACF,eAAO,MAAM,sBAAsB;;;CAAoC,CAAC;AAwPxE;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,kBAAkB,CAcnE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var g=Object.defineProperty;var f=(s,t)=>g(s,"name",{value:t,configurable:!0});const y={soft:300,hard:400},u=f(s=>typeof s=="object"&&s!==null&&!Array.isArray(s),"isObj"),m=/^@[a-z0-9][a-z0-9-]*$/,l=/^[a-z][a-z0-9-]*$/,c=["lines","branches","functions","statements"];class p{static{f(this,"Check")}errors=[];fail(t,e){this.errors.push(`${t}: ${e}`)}keys(t,e,i){for(const n of Object.keys(e))i.includes(n)||this.fail(`${t}.${n}`,`unknown key (allowed: ${i.join(", ")})`)}obj(t,e){return u(e)?e:(this.fail(t,"must be an object"),null)}str(t,e,i,n){return typeof e!="string"||e===""?(this.fail(t,"must be a non-empty string"),!1):i&&!i.test(e)?(this.fail(t,`${JSON.stringify(e)} is invalid${n?` (${n})`:""}`),!1):!0}bool(t,e){typeof e!="boolean"&&this.fail(t,"must be a boolean")}strings(t,e){return!Array.isArray(e)||e.some(i=>typeof i!="string"||i==="")?(this.fail(t,"must be an array of non-empty strings"),!1):!0}}const k=/^[A-Z][A-Z0-9_]*$/;function h(s,t){const e=s.obj("features.kv",t);if(!e)return;s.keys("features.kv",e,["bindings","namespaceNames"]);const i=s.strings("features.kv.bindings",e.bindings)?e.bindings:[];for(const o of i)s.str("features.kv.bindings",o,k,"an UPPER_SNAKE binding name");if(e.namespaceNames===void 0)return;const n=s.obj("features.kv.namespaceNames",e.namespaceNames);if(n)for(const[o,a]of Object.entries(n)){const r=`features.kv.namespaceNames.${o}`;i.includes(o)||s.fail(r,"is not listed in features.kv.bindings"),s.str(r,a)}}f(h,"checkKv");function b(s,t,e){return s.str(t,e)?/[*?{}]/.test(e)||e.startsWith("/")||e.split("/").includes("..")?(s.fail(t,`${JSON.stringify(e)} must be a repo-relative file path without globs or '..'`),!1):!0:!1}f(b,"checkRepoPath");function $(s,t){if(!Array.isArray(t)||t.length===0){s.fail("features.workers","must be a non-empty array");return}const e=new Set;t.forEach((i,n)=>{const o=`features.workers[${n}]`,a=s.obj(o,i);if(!a)return;s.keys(o,a,["template","config"]),b(s,`${o}.template`,a.template);const r=a.config===void 0?"wrangler.jsonc":a.config;a.config!==void 0&&!b(s,`${o}.config`,a.config)||(e.has(r)&&s.fail(`${o}.config`,`${JSON.stringify(r)} is written by another worker`),e.add(r))})}f($,"checkWorkers");function w(s,t){const e=s.obj("features",t);if(e){if(s.keys("features",e,["d1","kv","workers","web","background","backupD1","durableObjects","queues","workflows","email","android"]),e.d1!==void 0){const i=s.obj("features.d1",e.d1);i&&(s.keys("features.d1",i,["binding","database","migrationsDir"]),s.str("features.d1.binding",i.binding,/^[A-Z][A-Z0-9_]*$/,"an UPPER_SNAKE binding name"),s.str("features.d1.database",i.database),i.migrationsDir!==void 0&&s.str("features.d1.migrationsDir",i.migrationsDir))}if(e.kv!==void 0&&h(s,e.kv),e.workers!==void 0&&$(s,e.workers),e.web!==void 0){const i=s.obj("features.web",e.web);i&&(s.keys("features.web",i,["pages","spaShell","buildScript","pagesProject"]),s.bool("features.web.pages",i.pages),s.bool("features.web.spaShell",i.spaShell),i.buildScript!==void 0&&s.str("features.web.buildScript",i.buildScript,/^[\w:.-]+$/,"a root package.json script name"),i.pagesProject!==void 0&&s.str("features.web.pagesProject",i.pagesProject,/^[a-z0-9][a-z0-9-]{0,57}$/,"lower-case letters, digits and hyphens, at most 58"))}for(const i of["background","backupD1","email","android"])e[i]!==void 0&&s.bool(`features.${i}`,e[i]);for(const i of["durableObjects","queues","workflows"])e[i]!==void 0&&s.strings(`features.${i}`,e[i])}}f(w,"checkFeatures");function j(s,t,e){s.keys(t,e,["name","dir","package","mayImport","typeOnly","forbid","forbidMessage","http","browser"]),s.str(`${t}.name`,e.name,l,"lower-case letters, digits and hyphens"),s.str(`${t}.dir`,e.dir)&&(/[*?{}]/.test(e.dir)||e.dir.startsWith("/")||e.dir.split("/").includes(".."))&&s.fail(`${t}.dir`,`${JSON.stringify(e.dir)} must be a repo-relative directory without globs`),e.package!==void 0&&s.str(`${t}.package`,e.package),e.forbidMessage!==void 0&&s.str(`${t}.forbidMessage`,e.forbidMessage);for(const i of["mayImport","typeOnly","forbid"])(e[i]!==void 0||i==="mayImport")&&s.strings(`${t}.${i}`,e[i]);for(const i of["http","browser"])e[i]!==void 0&&s.bool(`${t}.${i}`,e[i])}f(j,"checkLayer");function S(s,t){if(!Array.isArray(t)){s.fail("layers","must be an array of layers");return}const e=new Set,i=new Set;t.forEach((n,o)=>{const a=`layers[${o}]`,r=s.obj(a,n);r&&(j(s,a,r),typeof r.name=="string"&&(e.has(r.name)&&s.fail(`${a}.name`,`duplicate layer name ${JSON.stringify(r.name)}`),e.add(r.name)),typeof r.dir=="string"&&(i.has(r.dir)&&s.fail(`${a}.dir`,`duplicate layer dir ${JSON.stringify(r.dir)}`),i.add(r.dir)))}),t.forEach((n,o)=>{if(u(n))for(const a of["mayImport","typeOnly"]){const r=n[a];if(Array.isArray(r))for(const d of r)typeof d=="string"&&!e.has(d)&&s.fail(`layers[${o}].${a}`,`unknown layer ${JSON.stringify(d)}`),a==="typeOnly"&&Array.isArray(n.mayImport)&&n.mayImport.includes(d)&&s.fail(`layers[${o}].typeOnly`,`${JSON.stringify(d)} is already in mayImport`)}})}f(S,"checkLayers");function O(s,t){const e=s.obj("quality",t);e&&(s.keys("quality",e,["coverage","godFiles"]),e.coverage!==void 0&&N(s,e.coverage),e.godFiles!==void 0&&A(s,e.godFiles))}f(O,"checkQuality");function A(s,t){const e=s.obj("quality.godFiles",t);if(e){s.keys("quality.godFiles",e,["soft","hard"]);for(const i of["soft","hard"]){const n=e[i],o=y[i];!Number.isInteger(n)||n<1?s.fail(`quality.godFiles.${i}`,"must be a positive integer"):n>o&&s.fail(`quality.godFiles.${i}`,`${String(n)} is above the family limit ${o}: god-file limits may only be lowered`)}typeof e.soft=="number"&&typeof e.hard=="number"&&e.soft>e.hard&&s.fail("quality.godFiles.soft","must not exceed quality.godFiles.hard")}}f(A,"checkGodFiles");function N(s,t){const e=s.obj("quality.coverage",t);if(e){s.keys("quality.coverage",e,c);for(const i of c){const n=e[i];(typeof n!="number"||!(n>=0&&n<=100))&&s.fail(`quality.coverage.${i}`,"must be a number from 0 to 100")}}}f(N,"checkCoverage");function q(s,t){const e=s.obj("extensions",t);if(e)for(const[i,n]of Object.entries(e))l.test(i)||s.fail(`extensions.${i}`,"namespace must be lower-case letters, digits and hyphens"),u(n)||s.fail(`extensions.${i}`,"must be an object (extensions are namespaced: one object per owner)")}f(q,"checkExtensions");function I(s){const t=new p,e=t.obj("manifest",s);return e&&(t.keys("manifest",e,["$schema","name","scope","features","layers","quality","extensions"]),e.$schema!==void 0&&t.str("$schema",e.$schema),t.str("name",e.name),t.str("scope",e.scope,m,'an npm scope such as "@mail-meow"'),e.features!==void 0&&w(t,e.features),e.layers!==void 0&&S(t,e.layers),e.quality!==void 0&&O(t,e.quality),e.extensions!==void 0&&q(t,e.extensions)),t.errors.length>0?{ok:!1,errors:t.errors}:{ok:!0,manifest:s}}f(I,"validateManifest");export{y as FAMILY_GOD_FILE_LIMITS,I as validateManifest};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/manifest-validate.ts"],
|
|
4
|
-
"sourcesContent": ["import type { FamilyManifest, ManifestValidation } from './manifest.ts';\n\n/**\nFamily default god-file limits: a manifest may only lower them.\n*/\nexport const FAMILY_GOD_FILE_LIMITS = { soft: 300, hard: 400 } as const;\n\ntype Obj = Record<string, unknown>;\n\nconst isObj = (value: unknown): value is Obj => typeof value === 'object' && value !== null && !Array.isArray(value);\nconst SCOPE_RE = /^@[a-z0-9][a-z0-9-]*$/;\nconst NAME_RE = /^[a-z][a-z0-9-]*$/;\nconst COVERAGE_KEYS = ['lines', 'branches', 'functions', 'statements'] as const;\n\n/**\nCollects errors under a dotted path so every message names its field.\n*/\nclass Check {\n readonly errors: string[] = [];\n fail(at: string, message: string): void {\n this.errors.push(`${at}: ${message}`);\n }\n /**\n Refuse unknown keys: the closed side.\n */\n keys(at: string, value: Obj, allowed: readonly string[]): void {\n for (const key of Object.keys(value)) {\n if (!allowed.includes(key)) this.fail(`${at}.${key}`, `unknown key (allowed: ${allowed.join(', ')})`);\n }\n }\n obj(at: string, value: unknown): Obj | null {\n if (isObj(value)) return value;\n this.fail(at, 'must be an object');\n return null;\n }\n str(at: string, value: unknown, pattern?: RegExp, hint?: string): value is string {\n if (typeof value !== 'string' || value === '') {\n this.fail(at, 'must be a non-empty string');\n return false;\n }\n if (pattern && !pattern.test(value)) {\n this.fail(at, `${JSON.stringify(value)} is invalid${hint ? ` (${hint})` : ''}`);\n return false;\n }\n return true;\n }\n bool(at: string, value: unknown): void {\n if (typeof value !== 'boolean') this.fail(at, 'must be a boolean');\n }\n strings(at: string, value: unknown): value is string[] {\n if (!Array.isArray(value) || value.some((item) => typeof item !== 'string' || item === '')) {\n this.fail(at, 'must be an array of non-empty strings');\n return false;\n }\n return true;\n }\n}\n\nconst BINDING_RE = /^[A-Z][A-Z0-9_]*$/;\n\nfunction checkKv(c: Check, value: unknown): void {\n const kv = c.obj('features.kv', value);\n if (!kv) return;\n c.keys('features.kv', kv, ['bindings', 'namespaceNames']);\n const bindings = c.strings('features.kv.bindings', kv.bindings) ? kv.bindings : [];\n for (const binding of bindings) c.str('features.kv.bindings', binding, BINDING_RE, 'an UPPER_SNAKE binding name');\n if (kv.namespaceNames === undefined) return;\n const names = c.obj('features.kv.namespaceNames', kv.namespaceNames);\n if (!names) return;\n for (const [binding, name] of Object.entries(names)) {\n const at = `features.kv.namespaceNames.${binding}`;\n if (!bindings.includes(binding)) c.fail(at, 'is not listed in features.kv.bindings');\n c.str(at, name);\n }\n}\n\nfunction checkFeatures(c: Check, value: unknown): void {\n const features = c.obj('features', value);\n if (!features) return;\n c.keys('features', features, ['d1', 'kv', 'web', 'background', 'backupD1', 'durableObjects', 'queues', 'workflows', 'email', 'android']);\n if (features.d1 !== undefined) {\n const d1 = c.obj('features.d1', features.d1);\n if (d1) {\n c.keys('features.d1', d1, ['binding', 'database', 'migrationsDir']);\n c.str('features.d1.binding', d1.binding, /^[A-Z][A-Z0-9_]*$/, 'an UPPER_SNAKE binding name');\n c.str('features.d1.database', d1.database);\n if (d1.migrationsDir !== undefined) c.str('features.d1.migrationsDir', d1.migrationsDir);\n }\n }\n if (features.kv !== undefined) checkKv(c, features.kv);\n if (features.web !== undefined) {\n const web = c.obj('features.web', features.web);\n if (web) {\n c.keys('features.web', web, ['pages', 'spaShell', 'buildScript', 'pagesProject']);\n c.bool('features.web.pages', web.pages);\n c.bool('features.web.spaShell', web.spaShell);\n if (web.buildScript !== undefined)\n c.str('features.web.buildScript', web.buildScript, /^[\\w:.-]+$/, 'a root package.json script name');\n if (web.pagesProject !== undefined) {\n c.str(\n 'features.web.pagesProject',\n web.pagesProject,\n /^[a-z0-9][a-z0-9-]{0,57}$/,\n 'lower-case letters, digits and hyphens, at most 58',\n );\n }\n }\n }\n for (const flag of ['background', 'backupD1', 'email', 'android'] as const) {\n if (features[flag] !== undefined) c.bool(`features.${flag}`, features[flag]);\n }\n for (const list of ['durableObjects', 'queues', 'workflows'] as const) {\n if (features[list] !== undefined) c.strings(`features.${list}`, features[list]);\n }\n}\n\nfunction checkLayer(c: Check, at: string, layer: Obj): void {\n c.keys(at, layer, ['name', 'dir', 'package', 'mayImport', 'typeOnly', 'forbid', 'forbidMessage', 'http', 'browser']);\n c.str(`${at}.name`, layer.name, NAME_RE, 'lower-case letters, digits and hyphens');\n if (c.str(`${at}.dir`, layer.dir) && (/[*?{}]/.test(layer.dir) || layer.dir.startsWith('/') || layer.dir.split('/').includes('..'))) {\n c.fail(`${at}.dir`, `${JSON.stringify(layer.dir)} must be a repo-relative directory without globs`);\n }\n if (layer.package !== undefined) c.str(`${at}.package`, layer.package);\n if (layer.forbidMessage !== undefined) c.str(`${at}.forbidMessage`, layer.forbidMessage);\n for (const list of ['mayImport', 'typeOnly', 'forbid'] as const) {\n if (layer[list] !== undefined || list === 'mayImport') c.strings(`${at}.${list}`, layer[list]);\n }\n for (const flag of ['http', 'browser'] as const) if (layer[flag] !== undefined) c.bool(`${at}.${flag}`, layer[flag]);\n}\n\nfunction checkLayers(c: Check, value: unknown): void {\n if (!Array.isArray(value)) {\n c.fail('layers', 'must be an array of layers');\n return;\n }\n const names = new Set<string>();\n const dirs = new Set<string>();\n value.forEach((entry: unknown, index) => {\n const at = `layers[${index}]`;\n const layer = c.obj(at, entry);\n if (!layer) return;\n checkLayer(c, at, layer);\n if (typeof layer.name === 'string') {\n if (names.has(layer.name)) c.fail(`${at}.name`, `duplicate layer name ${JSON.stringify(layer.name)}`);\n names.add(layer.name);\n }\n if (typeof layer.dir !== 'string') {\n return;\n }\n\n if (dirs.has(layer.dir)) c.fail(`${at}.dir`, `duplicate layer dir ${JSON.stringify(layer.dir)}`);\n dirs.add(layer.dir);\n });\n value.forEach((entry: unknown, index) => {\n if (!isObj(entry)) return;\n for (const list of ['mayImport', 'typeOnly'] as const) {\n const refs = entry[list];\n if (!Array.isArray(refs)) continue;\n for (const ref of refs) {\n if (typeof ref === 'string' && !names.has(ref)) c.fail(`layers[${index}].${list}`, `unknown layer ${JSON.stringify(ref)}`);\n if (list === 'typeOnly' && Array.isArray(entry.mayImport) && entry.mayImport.includes(ref)) {\n c.fail(`layers[${index}].typeOnly`, `${JSON.stringify(ref)} is already in mayImport`);\n }\n }\n }\n });\n}\n\nfunction checkQuality(c: Check, value: unknown): void {\n const quality = c.obj('quality', value);\n if (!quality) return;\n c.keys('quality', quality, ['coverage', 'godFiles']);\n if (quality.coverage !== undefined) checkCoverage(c, quality.coverage);\n if (quality.godFiles !== undefined) checkGodFiles(c, quality.godFiles);\n}\n\nfunction checkGodFiles(c: Check, value: unknown): void {\n const god = c.obj('quality.godFiles', value);\n if (!god) return;\n c.keys('quality.godFiles', god, ['soft', 'hard']);\n for (const key of ['soft', 'hard'] as const) {\n const limit = god[key];\n const ceiling = FAMILY_GOD_FILE_LIMITS[key];\n if (!Number.isInteger(limit) || (limit as number) < 1) c.fail(`quality.godFiles.${key}`, 'must be a positive integer');\n else if ((limit as number) > ceiling) {\n c.fail(`quality.godFiles.${key}`, `${String(limit)} is above the family limit ${ceiling}: god-file limits may only be lowered`);\n }\n }\n if (typeof god.soft === 'number' && typeof god.hard === 'number' && god.soft > god.hard) {\n c.fail('quality.godFiles.soft', 'must not exceed quality.godFiles.hard');\n }\n}\n\nfunction checkCoverage(c: Check, value: unknown): void {\n const coverage = c.obj('quality.coverage', value);\n if (!coverage) return;\n c.keys('quality.coverage', coverage, COVERAGE_KEYS);\n for (const key of COVERAGE_KEYS) {\n const figure = coverage[key];\n if (typeof figure !== 'number' || !(figure >= 0 && figure <= 100)) c.fail(`quality.coverage.${key}`, 'must be a number from 0 to 100');\n }\n}\n\nfunction checkExtensions(c: Check, value: unknown): void {\n const extensions = c.obj('extensions', value);\n if (!extensions) return;\n for (const [key, entry] of Object.entries(extensions)) {\n if (!NAME_RE.test(key)) c.fail(`extensions.${key}`, 'namespace must be lower-case letters, digits and hyphens');\n if (!isObj(entry)) c.fail(`extensions.${key}`, 'must be an object (extensions are namespaced: one object per owner)');\n }\n}\n\n/**\n * Validate an already-parsed value. Returns every problem found, not just the\n * first, so one edit can fix them all.\n */\nexport function validateManifest(input: unknown): ManifestValidation {\n const c = new Check();\n const root = c.obj('manifest', input);\n if (root) {\n c.keys('manifest', root, ['$schema', 'name', 'scope', 'features', 'layers', 'quality', 'extensions']);\n if (root.$schema !== undefined) c.str('$schema', root.$schema);\n c.str('name', root.name);\n c.str('scope', root.scope, SCOPE_RE, 'an npm scope such as \"@mail-meow\"');\n if (root.features !== undefined) checkFeatures(c, root.features);\n if (root.layers !== undefined) checkLayers(c, root.layers);\n if (root.quality !== undefined) checkQuality(c, root.quality);\n if (root.extensions !== undefined) checkExtensions(c, root.extensions);\n }\n return c.errors.length > 0 ? { ok: false, errors: c.errors } : { ok: true, manifest: input as FamilyManifest };\n}\n"],
|
|
5
|
-
"mappings": "+EAKO,MAAMA,EAAyB,CAAE,KAAM,IAAK,KAAM,GAAG,EAItDC,EAAQC,EAACC,GAAiC,OAAOA,GAAU,UAAYA,IAAU,MAAQ,CAAC,MAAM,QAAQA,CAAK,EAArG,SACRC,EAAW,wBACXC,EAAU,oBACVC,EAAgB,CAAC,QAAS,WAAY,YAAa,YAAY,EAKrE,MAAMC,CAAK,CAfX,MAeW,CAAAL,EAAA,cACA,OAAmB,CAAA,EAC5B,KAAKM,EAAYC,EAAe,CAC9B,KAAK,OAAO,KAAK,GAAGD,CAAE,KAAKC,CAAO,EAAE,CACtC,CAIA,KAAKD,EAAYL,EAAYO,EAA0B,CACrD,UAAWC,KAAO,OAAO,KAAKR,CAAK,EAC5BO,EAAQ,SAASC,CAAG,GAAG,KAAK,KAAK,GAAGH,CAAE,IAAIG,CAAG,GAAI,yBAAyBD,EAAQ,KAAK,IAAI,CAAC,GAAG,CAExG,CACA,IAAIF,EAAYL,EAAc,CAC5B,OAAIF,EAAME,CAAK,EAAUA,GACzB,KAAK,KAAKK,EAAI,mBAAmB,EAC1B,KACT,CACA,IAAIA,EAAYL,EAAgBS,EAAkBC,EAAa,CAC7D,OAAI,OAAOV,GAAU,UAAYA,IAAU,IACzC,KAAK,KAAKK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", "at", "message", "allowed", "key", "pattern", "hint", "item", "BINDING_RE", "checkKv", "c", "kv", "bindings", "binding", "names", "name", "checkFeatures", "features", "d1", "web", "flag", "list", "checkLayer", "layer", "checkLayers", "dirs", "
|
|
4
|
+
"sourcesContent": ["import type { FamilyManifest, ManifestValidation } from './manifest.ts';\n\n/**\nFamily default god-file limits: a manifest may only lower them.\n*/\nexport const FAMILY_GOD_FILE_LIMITS = { soft: 300, hard: 400 } as const;\n\ntype Obj = Record<string, unknown>;\n\nconst isObj = (value: unknown): value is Obj => typeof value === 'object' && value !== null && !Array.isArray(value);\nconst SCOPE_RE = /^@[a-z0-9][a-z0-9-]*$/;\nconst NAME_RE = /^[a-z][a-z0-9-]*$/;\nconst COVERAGE_KEYS = ['lines', 'branches', 'functions', 'statements'] as const;\n\n/**\nCollects errors under a dotted path so every message names its field.\n*/\nclass Check {\n readonly errors: string[] = [];\n fail(at: string, message: string): void {\n this.errors.push(`${at}: ${message}`);\n }\n /**\n Refuse unknown keys: the closed side.\n */\n keys(at: string, value: Obj, allowed: readonly string[]): void {\n for (const key of Object.keys(value)) {\n if (!allowed.includes(key)) this.fail(`${at}.${key}`, `unknown key (allowed: ${allowed.join(', ')})`);\n }\n }\n obj(at: string, value: unknown): Obj | null {\n if (isObj(value)) return value;\n this.fail(at, 'must be an object');\n return null;\n }\n str(at: string, value: unknown, pattern?: RegExp, hint?: string): value is string {\n if (typeof value !== 'string' || value === '') {\n this.fail(at, 'must be a non-empty string');\n return false;\n }\n if (pattern && !pattern.test(value)) {\n this.fail(at, `${JSON.stringify(value)} is invalid${hint ? ` (${hint})` : ''}`);\n return false;\n }\n return true;\n }\n bool(at: string, value: unknown): void {\n if (typeof value !== 'boolean') this.fail(at, 'must be a boolean');\n }\n strings(at: string, value: unknown): value is string[] {\n if (!Array.isArray(value) || value.some((item) => typeof item !== 'string' || item === '')) {\n this.fail(at, 'must be an array of non-empty strings');\n return false;\n }\n return true;\n }\n}\n\nconst BINDING_RE = /^[A-Z][A-Z0-9_]*$/;\n\nfunction checkKv(c: Check, value: unknown): void {\n const kv = c.obj('features.kv', value);\n if (!kv) return;\n c.keys('features.kv', kv, ['bindings', 'namespaceNames']);\n const bindings = c.strings('features.kv.bindings', kv.bindings) ? kv.bindings : [];\n for (const binding of bindings) c.str('features.kv.bindings', binding, BINDING_RE, 'an UPPER_SNAKE binding name');\n if (kv.namespaceNames === undefined) return;\n const names = c.obj('features.kv.namespaceNames', kv.namespaceNames);\n if (!names) return;\n for (const [binding, name] of Object.entries(names)) {\n const at = `features.kv.namespaceNames.${binding}`;\n if (!bindings.includes(binding)) c.fail(at, 'is not listed in features.kv.bindings');\n c.str(at, name);\n }\n}\n\nfunction checkRepoPath(c: Check, at: string, value: unknown): value is string {\n if (!c.str(at, value)) return false;\n if (/[*?{}]/.test(value) || value.startsWith('/') || value.split('/').includes('..')) {\n c.fail(at, `${JSON.stringify(value)} must be a repo-relative file path without globs or '..'`);\n return false;\n }\n return true;\n}\n\nfunction checkWorkers(c: Check, value: unknown): void {\n if (!Array.isArray(value) || value.length === 0) {\n c.fail('features.workers', 'must be a non-empty array');\n return;\n }\n const configs = new Set<string>();\n value.forEach((entry: unknown, index) => {\n const at = `features.workers[${index}]`;\n const worker = c.obj(at, entry);\n if (!worker) return;\n c.keys(at, worker, ['template', 'config']);\n checkRepoPath(c, `${at}.template`, worker.template);\n const config = worker.config === undefined ? 'wrangler.jsonc' : worker.config;\n if (worker.config !== undefined && !checkRepoPath(c, `${at}.config`, worker.config)) return;\n if (configs.has(config as string)) c.fail(`${at}.config`, `${JSON.stringify(config)} is written by another worker`);\n configs.add(config as string);\n });\n}\n\nfunction checkFeatures(c: Check, value: unknown): void {\n const features = c.obj('features', value);\n if (!features) return;\n c.keys('features', features, [\n 'd1',\n 'kv',\n 'workers',\n 'web',\n 'background',\n 'backupD1',\n 'durableObjects',\n 'queues',\n 'workflows',\n 'email',\n 'android',\n ]);\n if (features.d1 !== undefined) {\n const d1 = c.obj('features.d1', features.d1);\n if (d1) {\n c.keys('features.d1', d1, ['binding', 'database', 'migrationsDir']);\n c.str('features.d1.binding', d1.binding, /^[A-Z][A-Z0-9_]*$/, 'an UPPER_SNAKE binding name');\n c.str('features.d1.database', d1.database);\n if (d1.migrationsDir !== undefined) c.str('features.d1.migrationsDir', d1.migrationsDir);\n }\n }\n if (features.kv !== undefined) checkKv(c, features.kv);\n if (features.workers !== undefined) checkWorkers(c, features.workers);\n if (features.web !== undefined) {\n const web = c.obj('features.web', features.web);\n if (web) {\n c.keys('features.web', web, ['pages', 'spaShell', 'buildScript', 'pagesProject']);\n c.bool('features.web.pages', web.pages);\n c.bool('features.web.spaShell', web.spaShell);\n if (web.buildScript !== undefined)\n c.str('features.web.buildScript', web.buildScript, /^[\\w:.-]+$/, 'a root package.json script name');\n if (web.pagesProject !== undefined) {\n c.str(\n 'features.web.pagesProject',\n web.pagesProject,\n /^[a-z0-9][a-z0-9-]{0,57}$/,\n 'lower-case letters, digits and hyphens, at most 58',\n );\n }\n }\n }\n for (const flag of ['background', 'backupD1', 'email', 'android'] as const) {\n if (features[flag] !== undefined) c.bool(`features.${flag}`, features[flag]);\n }\n for (const list of ['durableObjects', 'queues', 'workflows'] as const) {\n if (features[list] !== undefined) c.strings(`features.${list}`, features[list]);\n }\n}\n\nfunction checkLayer(c: Check, at: string, layer: Obj): void {\n c.keys(at, layer, ['name', 'dir', 'package', 'mayImport', 'typeOnly', 'forbid', 'forbidMessage', 'http', 'browser']);\n c.str(`${at}.name`, layer.name, NAME_RE, 'lower-case letters, digits and hyphens');\n if (c.str(`${at}.dir`, layer.dir) && (/[*?{}]/.test(layer.dir) || layer.dir.startsWith('/') || layer.dir.split('/').includes('..'))) {\n c.fail(`${at}.dir`, `${JSON.stringify(layer.dir)} must be a repo-relative directory without globs`);\n }\n if (layer.package !== undefined) c.str(`${at}.package`, layer.package);\n if (layer.forbidMessage !== undefined) c.str(`${at}.forbidMessage`, layer.forbidMessage);\n for (const list of ['mayImport', 'typeOnly', 'forbid'] as const) {\n if (layer[list] !== undefined || list === 'mayImport') c.strings(`${at}.${list}`, layer[list]);\n }\n for (const flag of ['http', 'browser'] as const) if (layer[flag] !== undefined) c.bool(`${at}.${flag}`, layer[flag]);\n}\n\nfunction checkLayers(c: Check, value: unknown): void {\n if (!Array.isArray(value)) {\n c.fail('layers', 'must be an array of layers');\n return;\n }\n const names = new Set<string>();\n const dirs = new Set<string>();\n value.forEach((entry: unknown, index) => {\n const at = `layers[${index}]`;\n const layer = c.obj(at, entry);\n if (!layer) return;\n checkLayer(c, at, layer);\n if (typeof layer.name === 'string') {\n if (names.has(layer.name)) c.fail(`${at}.name`, `duplicate layer name ${JSON.stringify(layer.name)}`);\n names.add(layer.name);\n }\n if (typeof layer.dir !== 'string') {\n return;\n }\n\n if (dirs.has(layer.dir)) c.fail(`${at}.dir`, `duplicate layer dir ${JSON.stringify(layer.dir)}`);\n dirs.add(layer.dir);\n });\n value.forEach((entry: unknown, index) => {\n if (!isObj(entry)) return;\n for (const list of ['mayImport', 'typeOnly'] as const) {\n const refs = entry[list];\n if (!Array.isArray(refs)) continue;\n for (const ref of refs) {\n if (typeof ref === 'string' && !names.has(ref)) c.fail(`layers[${index}].${list}`, `unknown layer ${JSON.stringify(ref)}`);\n if (list === 'typeOnly' && Array.isArray(entry.mayImport) && entry.mayImport.includes(ref)) {\n c.fail(`layers[${index}].typeOnly`, `${JSON.stringify(ref)} is already in mayImport`);\n }\n }\n }\n });\n}\n\nfunction checkQuality(c: Check, value: unknown): void {\n const quality = c.obj('quality', value);\n if (!quality) return;\n c.keys('quality', quality, ['coverage', 'godFiles']);\n if (quality.coverage !== undefined) checkCoverage(c, quality.coverage);\n if (quality.godFiles !== undefined) checkGodFiles(c, quality.godFiles);\n}\n\nfunction checkGodFiles(c: Check, value: unknown): void {\n const god = c.obj('quality.godFiles', value);\n if (!god) return;\n c.keys('quality.godFiles', god, ['soft', 'hard']);\n for (const key of ['soft', 'hard'] as const) {\n const limit = god[key];\n const ceiling = FAMILY_GOD_FILE_LIMITS[key];\n if (!Number.isInteger(limit) || (limit as number) < 1) c.fail(`quality.godFiles.${key}`, 'must be a positive integer');\n else if ((limit as number) > ceiling) {\n c.fail(`quality.godFiles.${key}`, `${String(limit)} is above the family limit ${ceiling}: god-file limits may only be lowered`);\n }\n }\n if (typeof god.soft === 'number' && typeof god.hard === 'number' && god.soft > god.hard) {\n c.fail('quality.godFiles.soft', 'must not exceed quality.godFiles.hard');\n }\n}\n\nfunction checkCoverage(c: Check, value: unknown): void {\n const coverage = c.obj('quality.coverage', value);\n if (!coverage) return;\n c.keys('quality.coverage', coverage, COVERAGE_KEYS);\n for (const key of COVERAGE_KEYS) {\n const figure = coverage[key];\n if (typeof figure !== 'number' || !(figure >= 0 && figure <= 100)) c.fail(`quality.coverage.${key}`, 'must be a number from 0 to 100');\n }\n}\n\nfunction checkExtensions(c: Check, value: unknown): void {\n const extensions = c.obj('extensions', value);\n if (!extensions) return;\n for (const [key, entry] of Object.entries(extensions)) {\n if (!NAME_RE.test(key)) c.fail(`extensions.${key}`, 'namespace must be lower-case letters, digits and hyphens');\n if (!isObj(entry)) c.fail(`extensions.${key}`, 'must be an object (extensions are namespaced: one object per owner)');\n }\n}\n\n/**\n * Validate an already-parsed value. Returns every problem found, not just the\n * first, so one edit can fix them all.\n */\nexport function validateManifest(input: unknown): ManifestValidation {\n const c = new Check();\n const root = c.obj('manifest', input);\n if (root) {\n c.keys('manifest', root, ['$schema', 'name', 'scope', 'features', 'layers', 'quality', 'extensions']);\n if (root.$schema !== undefined) c.str('$schema', root.$schema);\n c.str('name', root.name);\n c.str('scope', root.scope, SCOPE_RE, 'an npm scope such as \"@mail-meow\"');\n if (root.features !== undefined) checkFeatures(c, root.features);\n if (root.layers !== undefined) checkLayers(c, root.layers);\n if (root.quality !== undefined) checkQuality(c, root.quality);\n if (root.extensions !== undefined) checkExtensions(c, root.extensions);\n }\n return c.errors.length > 0 ? { ok: false, errors: c.errors } : { ok: true, manifest: input as Family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K,OAAO,EACxDA,EAAK,aAAe,QAAWJ,EAAgBlC,EAAGsC,EAAK,UAAU,GAEhEtC,EAAE,OAAO,OAAS,EAAI,CAAE,GAAI,GAAO,OAAQA,EAAE,MAAM,EAAK,CAAE,GAAI,GAAM,SAAUqC,CAAuB,CAC9G,CAdgBpD,EAAAmD,EAAA",
|
|
6
|
+
"names": ["FAMILY_GOD_FILE_LIMITS", "isObj", "__name", "value", "SCOPE_RE", "NAME_RE", "COVERAGE_KEYS", "Check", "at", "message", "allowed", "key", "pattern", "hint", "item", "BINDING_RE", "checkKv", "c", "kv", "bindings", "binding", "names", "name", "checkRepoPath", "checkWorkers", "configs", "entry", "index", "worker", "config", "checkFeatures", "features", "d1", "web", "flag", "list", "checkLayer", "layer", "checkLayers", "dirs", "refs", "ref", "checkQuality", "quality", "checkCoverage", "checkGodFiles", "god", "limit", "ceiling", "coverage", "figure", "checkExtensions", "extensions", "validateManifest", "input", "root"]
|
|
7
7
|
}
|
package/dist/manifest.d.ts
CHANGED
|
@@ -56,9 +56,25 @@ export interface ManifestWeb {
|
|
|
56
56
|
*/
|
|
57
57
|
readonly pagesProject?: string;
|
|
58
58
|
}
|
|
59
|
+
/**
|
|
60
|
+
* One worker `prepare-wrangler` materializes: the committed template and the config it writes. Declared as
|
|
61
|
+
* `features.workers`; absent means one worker (`apps/api/wrangler.template.jsonc` to `wrangler.jsonc`). List every
|
|
62
|
+
* entry's `config` in `worker-cd.yml`'s `worker-configs` input as well, so each one is also deployed.
|
|
63
|
+
*/
|
|
64
|
+
export interface ManifestWorker {
|
|
65
|
+
/**
|
|
66
|
+
Repo-relative path of the committed template.
|
|
67
|
+
*/
|
|
68
|
+
readonly template: string;
|
|
69
|
+
/**
|
|
70
|
+
Repo-relative path of the config written from it. Defaults to `wrangler.jsonc`; unique across `workers`.
|
|
71
|
+
*/
|
|
72
|
+
readonly config?: string;
|
|
73
|
+
}
|
|
59
74
|
export interface ManifestFeatures {
|
|
60
75
|
readonly d1?: ManifestD1;
|
|
61
76
|
readonly kv?: ManifestKv;
|
|
77
|
+
readonly workers?: readonly ManifestWorker[];
|
|
62
78
|
readonly web?: ManifestWeb;
|
|
63
79
|
readonly background?: boolean;
|
|
64
80
|
readonly backupD1?: boolean;
|
package/dist/manifest.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manifest.d.ts","sourceRoot":"","sources":["../src/manifest.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AASH,OAAO,EAAE,sBAAsB,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAElF;;EAEE;AACF,eAAO,MAAM,iBAAiB,oBAAoB,CAAC;AAEnD,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;CACjC;AAED,MAAM,WAAW,UAAU;IACzB;;;MAGE;IACF,QAAQ,CAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAC;IACrC;;MAEE;IACF,QAAQ,CAAC,cAAc,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;CAC5D;AAED,MAAM,WAAW,WAAW;IAC1B;;MAEE;IACF,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;IACxB;;MAEE;IACF,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC3B;;;MAGE;IACF,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B;;MAEE;IACF,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;CAChC;AAED,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,EAAE,CAAC,EAAE,UAAU,CAAC;IACzB,QAAQ,CAAC,EAAE,CAAC,EAAE,UAAU,CAAC;IACzB,QAAQ,CAAC,GAAG,CA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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 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,
|
|
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\n/**\n * One worker `prepare-wrangler` materializes: the committed template and the config it writes. Declared as\n * `features.workers`; absent means one worker (`apps/api/wrangler.template.jsonc` to `wrangler.jsonc`). List every\n * entry's `config` in `worker-cd.yml`'s `worker-configs` input as well, so each one is also deployed.\n */\nexport interface ManifestWorker {\n /**\n Repo-relative path of the committed template.\n */\n readonly template: string;\n /**\n Repo-relative path of the config written from it. Defaults to `wrangler.jsonc`; unique across `workers`.\n */\n readonly config?: string;\n}\n\nexport interface ManifestFeatures {\n readonly d1?: ManifestD1;\n readonly kv?: ManifestKv;\n readonly workers?: readonly ManifestWorker[];\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,iBAA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Jsonc", "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
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init-secrets.d.ts","sourceRoot":"","sources":["../../src/scripts/init-secrets.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;
|
|
1
|
+
{"version":3,"file":"init-secrets.d.ts","sourceRoot":"","sources":["../../src/scripts/init-secrets.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AA8LH,wBAAsB,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAU1C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var d=Object.defineProperty;var
|
|
2
|
-
${
|
|
1
|
+
var d=Object.defineProperty;var o=(e,r)=>d(e,"name",{value:r,configurable:!0});import{execFileSync as g}from"node:child_process";import{existsSync as p,readFileSync as u}from"node:fs";import{parse as m}from"jsonc-parser";import{isEntrypoint as w}from"./lib/entrypoint.js";import{fail as y}from"./lib/github-actions.js";import{isEmptySecretsStoreListing as h,parseWranglerNames as S}from"./lib/wrangler-table.js";import{loadManifest as E}from"../manifest.js";import{configPath as a,withWranglerPaths as $}from"./wrangler-config/types.js";const b="-encryption-key",_="-signing-secret";async function x(){const e=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),r=await crypto.subtle.exportKey("raw",e);let t="";for(const n of new Uint8Array(r))t+=String.fromCodePoint(n);return btoa(t)}o(x,"generateAESGCMKey");function C(){let e="";for(const r of crypto.getRandomValues(new Uint8Array(32)))e+=r.toString(16).padStart(2,"0");return Promise.resolve(e)}o(C,"generateSigningSecret");function f(e){if(e.endsWith(b))return x;if(e.endsWith(_))return C;throw new Error(`Unknown secret: ${e}. Name it '*-encryption-key' for a generated 32-byte AES-GCM key, or '*-signing-secret' for 32 random bytes, and teach this script the shape if neither fits.`)}o(f,"generatorFor");function k(e){try{return f(e),!0}catch{return!1}}o(k,"canProvisionSecret");function l(e,r){try{return g("pnpm",["exec","wrangler",...e],{encoding:"utf8",stdio:[r===void 0?"ignore":"pipe","pipe","pipe"],...r!==void 0&&{input:r}})}catch(t){const n=t,s=n.stdout?n.stdout.toString():"",i=n.stderr?n.stderr.toString():"";throw new Error(`Command failed: pnpm exec wrangler ${e.join(" ")}
|
|
2
|
+
${s}${i||n.message||""}`)}}o(l,"wrangler");function N(){if(!p(a()))throw new Error(`${a()} not found. Run scripts/prepare-wrangler-config.ts first \u2014 it is what creates the file this script reads.`);const e=m(u(a(),"utf8"));if(e.secrets_store_secrets===void 0&&Object.keys(e).length===0)throw new Error(`${a()} is empty or not valid JSONC. Run scripts/prepare-wrangler-config.ts to regenerate it.`);return e}o(N,"parseWranglerConfig");function F(e){const r=[];for(const[t,n]of(e.secrets_store_secrets??[]).entries()){const s=n.binding??`index ${t}`,i=n.store_id,c=n.secret_name;if(i===void 0||i===""||c===void 0||c==="")throw new Error(`secrets_store_secrets[${t}] ("${s}") needs both store_id and secret_name; store_id is normally filled in by scripts/prepare-wrangler-config.ts.`);if(!k(c))throw new Error(`No generator for secret "${c}" (binding "${s}").`);r.push({storeId:i,secretName:c})}return r}o(F,"planSecrets");function P(e){let r;try{r=l(["secrets-store","secret","list",e,"--remote"])}catch(t){if(h(t))return console.log(`Secrets Store ${e} is empty`),new Set;console.warn(`Unable to list secrets in store ${e}:`,t instanceof Error?t.message:"unknown error");return}return S(r)}o(P,"listSecretNames");function I(e,r,t){console.log(`Creating secret: ${r}`),l(["secrets-store","secret","create",e,"--name",r,"--scopes","workers","--remote"],t)}o(I,"createSecret");async function U(){console.log("Initializing Cloudflare secrets...");const e=E(process.cwd())?.features?.workers??[{}];let r=0;for(const t of e)r+=await $(t,z);if(r===0)throw new Error("wrangler.jsonc declares no secrets_store_secrets entries, so there is nothing to initialize.");console.log("Secret initialization complete")}o(U,"main");async function z(){const e=N(),r=F(e),t=new Map;for(const{storeId:n,secretName:s}of r){t.has(n)||t.set(n,P(n));const i=t.get(n);if(i===void 0)throw new Error(`Could not list secrets in store ${n}; refusing to create ${s} without confirming it is absent.`);if(i.has(s)){console.log(`Secret ${s} already exists; leaving it untouched.`);continue}I(n,s,await f(s)()),i.add(s)}return r.length}if(o(z,"initializeOne"),w(import.meta.url))try{await U()}catch(e){y(e instanceof Error?`Secret initialization failed: ${e.message}`:String(e))}export{U as main};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/scripts/init-secrets.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Create the Secrets Store entries declared in `wrangler.jsonc`, generating a fresh\n * value for each one that does not exist yet.\n *\n * Provenance: Edge-Sonic's `scripts/deploy/init-secrets.ts` and Durable-DAV's\n * `scripts/init-secrets.ts`, converged. Both record the same two defects that hid\n * a broken deploy for a whole release, and both fixes are carried over.\n *\n * ### Why this script exists at all\n *\n * A `secrets_store_secrets` binding fails the deploy unless the named secret\n * already exists inside the named store. Nothing creates it: Cloudflare will not\n * generate a value, and the template cannot carry one. So this script is the only\n * thing standing between a fresh account and a deploy that cannot succeed.\n *\n * ### The two defects that hid a broken deploy\n *\n * **The generator list was stale.** Durable-DAV's copy carried an allowlist of\n * exact names from the repository it was inherited from, all deleted when the repo\n * was renamed, so the very first iteration threw `Unknown secret` and never created\n * anything. So the rule here is the secret's **name shape**, not a list of names:\n * `*-encryption-key` gets a generated AES-GCM key and `*-signing-secret` gets 32\n * random bytes. Adding a secret to the template is then a one-line change needing\n * no matching edit here, which is the property the exact-name list did not have.\n *\n * **The throw was swallowed.** The original ended in `main().catch(console.error)`.\n * `console.error` returns `undefined` and never sets an exit status, so the process\n * exited **0** and CI marked the step green — the failure only surfaced one step\n * later, as an unexplainable `wrangler deploy` failure. Hence: the whole plan is\n * validated **before** any Cloudflare call, and a rejection reaches the runner as\n * a non-zero exit with a workflow annotation.\n *\n * ### Create-if-absent is a correctness property, not laziness\n *\n * An existing secret is left untouched. A replication encryption key seals every\n * remote target's credential; regenerating it on a redeploy would strand them all\n * as undecryptable. Rotation has to be a deliberate act with a re-encrypt path,\n * not a side effect of deploying.\n *\n * Requires a materialized `wrangler.jsonc` — run\n * `scripts/prepare-wrangler-config.ts` first. Fails rather than skipping when the\n * config is missing, because a step reporting \"Secret initialization complete\"\n * having created nothing is worse than a named error.\n */\n\nimport { execFileSync } from 'node:child_process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { parse } from 'jsonc-parser';\nimport { isEntrypoint } from './lib/entrypoint.ts';\nimport { fail } from './lib/github-actions.ts';\nimport { isEmptySecretsStoreListing, parseWranglerNames } from './lib/wrangler-table.ts';\nimport { CONFIG_PATH, type WranglerConfig } from './wrangler-config/types.ts';\n\n/**\n * The secret names the AES-GCM key generator produces, matched by **shape**.\n *\n * Keyed on the suffix because the alternative is the exact-name map that went\n * stale. See the header: a template naming `*-encryption-key` is then a one-line\n * change with no matching edit here, and a new secret breaks the deploy loudly\n * instead of silently.\n */\nconst ENCRYPTION_KEY_SUFFIX = '-encryption-key';\n\n/**\nThe secret names the random signing secret generator produces.\n*/\nconst SIGNING_SECRET_SUFFIX = '-signing-secret';\n\n/**\nA 256-bit AES-GCM key, base64-encoded — the shape the worker's crypto layer accepts.\n*/\nasync function generateAESGCMKey(): Promise<string> {\n const key = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt']);\n const exported = await crypto.subtle.exportKey('raw', key);\n // Chunked rather than spread: `String.fromCharCode(...bytes)` passes 32 arguments,\n // which is fine today and is a stack overflow the day the key is longer.\n let binary = '';\n for (const byte of new Uint8Array(exported)) {\n binary += String.fromCodePoint(byte);\n }\n return btoa(binary);\n}\n\n/**\nA 256-bit random signing secret for internal self-calls, hex-encoded.\n*/\nfunction generateSigningSecret(): Promise<string> {\n let hex = '';\n for (const byte of crypto.getRandomValues(new Uint8Array(32))) {\n hex += byte.toString(16).padStart(2, '0');\n }\n return Promise.resolve(hex);\n}\n\n/**\n * The generator for a secret name, chosen by the name's shape.\n *\n * A name matching neither is still refused rather than given a guess: the generator\n * is not the only thing that has to be right, and an unusable value that looks\n * provisioned is worse than a failure.\n */\nfunction generatorFor(secretName: string): () => Promise<string> {\n if (secretName.endsWith(ENCRYPTION_KEY_SUFFIX)) return generateAESGCMKey;\n if (secretName.endsWith(SIGNING_SECRET_SUFFIX)) return generateSigningSecret;\n throw new Error(\n `Unknown secret: ${secretName}. Name it '*-encryption-key' for a generated 32-byte AES-GCM key, ` +\n `or '*-signing-secret' for 32 random bytes, and teach this script the shape if neither fits.`,\n );\n}\n\n/**\nWhether this script can produce a value for `secretName`.\n*/\nfunction canProvisionSecret(secretName: string): boolean {\n try {\n generatorFor(secretName);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Runs a wrangler subcommand, optionally feeding `input` on stdin.\n *\n * Arguments are passed as an argv array rather than interpolated into a shell\n * string, so a value containing shell metacharacters cannot alter the command.\n */\nfunction wrangler(args: readonly string[], input?: string): string {\n try {\n // eslint-disable-next-line sonarjs/no-os-command-from-path\n return execFileSync('pnpm', ['exec', 'wrangler', ...args], {\n encoding: 'utf8',\n stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'],\n ...(input !== undefined && { input }),\n });\n } catch (error: unknown) {\n const maybeProcessError = error as { stdout?: string | Buffer; stderr?: string | Buffer; message?: string };\n const stdout: string = maybeProcessError.stdout ? maybeProcessError.stdout.toString() : '';\n const stderr: string = maybeProcessError.stderr ? maybeProcessError.stderr.toString() : '';\n throw new Error(`Command failed: pnpm exec wrangler ${args.join(' ')}\\n${stdout}${stderr || maybeProcessError.message || ''}`);\n }\n}\n\nfunction parseWranglerConfig(): WranglerConfig {\n if (!existsSync(CONFIG_PATH)) {\n throw new Error(\n `${CONFIG_PATH} not found. Run scripts/prepare-wrangler-config.ts first — it is what creates the file this script reads.`,\n );\n }\n // `parse` is error-tolerant and returns a partial object, so an empty result means\n // malformed JSON rather than \"no secrets declared\". Treating that as an empty list\n // would report success having created nothing.\n const config = parse(readFileSync(CONFIG_PATH, 'utf8')) as WranglerConfig;\n if (config.secrets_store_secrets === undefined && Object.keys(config).length === 0) {\n throw new Error(`${CONFIG_PATH} is empty or not valid JSONC. Run scripts/prepare-wrangler-config.ts to regenerate it.`);\n }\n return config;\n}\n\n/**\nOne secret to create, as the plan names it.\n*/\ninterface PlannedSecret {\n storeId: string;\n secretName: string;\n}\n\n/**\n * Turn the config's bindings into a validated work list.\n *\n * Every entry is checked *before* the first Cloudflare call, so an\n * unprovisionable secret fails the step in milliseconds instead of after some other\n * secret has already been created.\n */\nfunction planSecrets(config: WranglerConfig): PlannedSecret[] {\n const plan: PlannedSecret[] = [];\n for (const [index, secret] of (config.secrets_store_secrets ?? []).entries()) {\n const label = secret.binding ?? `index ${index}`;\n const storeId = secret.store_id;\n const secretName = secret.secret_name;\n if (storeId === undefined || storeId === '' || secretName === undefined || secretName === '') {\n throw new Error(\n `secrets_store_secrets[${index}] (\"${label}\") needs both store_id and secret_name; ` +\n 'store_id is normally filled in by scripts/prepare-wrangler-config.ts.',\n );\n }\n if (!canProvisionSecret(secretName)) {\n throw new Error(`No generator for secret \"${secretName}\" (binding \"${label}\").`);\n }\n plan.push({ storeId, secretName });\n }\n return plan;\n}\n\n/**\n * List the secret names present in a store.\n *\n * Returns `undefined` when the listing itself failed, which is deliberately\n * distinct from an empty set: a transient CLI failure must not be read as \"the\n * secret is missing\" and cause a duplicate insert over a live value. An empty store\n * *is* a confirmed absence, so it maps to an empty set rather than `undefined`.\n *\n * The name is taken exactly. `output.includes(secretName)` is not a membership test:\n * `my-replication-encryption-key-2` satisfies a search for\n * `my-replication-encryption-key`, so a store holding only the suffixed entry would\n * report the unsuffixed one as already present and it would never be created.\n */\nfunction listSecretNames(storeId: string): Set<string> | undefined {\n let output: string;\n try {\n output = wrangler(['secrets-store', 'secret', 'list', storeId, '--remote']);\n } catch (error: unknown) {\n if (isEmptySecretsStoreListing(error)) {\n console.log(`Secrets Store ${storeId} is empty`);\n return new Set();\n }\n console.warn(`Unable to list secrets in store ${storeId}:`, error instanceof Error ? error.message : 'unknown error');\n return undefined;\n }\n return parseWranglerNames(output);\n}\n\nfunction createSecret(storeId: string, secretName: string, secretValue: string): void {\n console.log(`Creating secret: ${secretName}`);\n // The value goes in on stdin, never as an argv entry: an argv is visible to every\n // process on the runner through `ps`, and the previous\n // `echo \"${value}\" | wrangler … ${name}` also broke on `\"`, `$`, backticks and\n // newlines.\n wrangler(['secrets-store', 'secret', 'create', storeId, '--name', secretName, '--scopes', 'workers', '--remote'], secretValue);\n}\n\nexport async function main(): Promise<void> {\n console.log('Initializing Cloudflare secrets...');\n const config = parseWranglerConfig();\n const plan = planSecrets(config);\n\n if (plan.length === 0) {\n throw new Error('wrangler.jsonc declares no secrets_store_secrets entries, so there is nothing to initialize.');\n }\n\n const listedByStore = new Map<string, Set<string> | undefined>();\n\n for (const { storeId, secretName } of plan) {\n if (!listedByStore.has(storeId)) {\n listedByStore.set(storeId, listSecretNames(storeId));\n }\n const existing = listedByStore.get(storeId);\n if (existing === undefined) {\n // Refuse to guess: creating a secret we could not read back risks overwriting\n // a live value with a freshly generated one.\n throw new Error(`Could not list secrets in store ${storeId}; refusing to create ${secretName} without confirming it is absent.`);\n }\n if (existing.has(secretName)) {\n console.log(`Secret ${secretName} already exists; leaving it untouched.`);\n continue;\n }\n createSecret(storeId, secretName, await generatorFor(secretName)());\n existing.add(secretName);\n }\n\n console.log('Secret initialization complete');\n}\n\n// Top-level await rather than `.catch(console.error)`, so a rejected `main` surfaces\n// as a stack trace with its cause intact and the process exits non-zero. Either way\n// the exit status has to be right: this runs in the deploy pipeline, and swallowing\n// the rejection reported a failed key bootstrap as a green step.\nif (isEntrypoint(import.meta.url)) {\n try {\n await main();\n } catch (error: unknown) {\n fail(error instanceof Error ? `Secret initialization failed: ${error.message}` : String(error));\n }\n}\n"],
|
|
5
|
-
"mappings": "+EA6CA,OAAS,gBAAAA,MAAoB,qBAC7B,OAAS,cAAAC,EAAY,gBAAAC,MAAoB,UACzC,OAAS,SAAAC,MAAa,eACtB,OAAS,gBAAAC,MAAoB,sBAC7B,OAAS,QAAAC,MAAY,0BACrB,OAAS,8BAAAC,EAA4B,sBAAAC,MAA0B,0BAC/D,OAAS,
|
|
6
|
-
"names": ["execFileSync", "existsSync", "readFileSync", "parse", "isEntrypoint", "fail", "isEmptySecretsStoreListing", "parseWranglerNames", "
|
|
4
|
+
"sourcesContent": ["/**\n * Create the Secrets Store entries declared in `wrangler.jsonc`, generating a fresh\n * value for each one that does not exist yet.\n *\n * Provenance: Edge-Sonic's `scripts/deploy/init-secrets.ts` and Durable-DAV's\n * `scripts/init-secrets.ts`, converged. Both record the same two defects that hid\n * a broken deploy for a whole release, and both fixes are carried over.\n *\n * ### Why this script exists at all\n *\n * A `secrets_store_secrets` binding fails the deploy unless the named secret\n * already exists inside the named store. Nothing creates it: Cloudflare will not\n * generate a value, and the template cannot carry one. So this script is the only\n * thing standing between a fresh account and a deploy that cannot succeed.\n *\n * ### The two defects that hid a broken deploy\n *\n * **The generator list was stale.** Durable-DAV's copy carried an allowlist of\n * exact names from the repository it was inherited from, all deleted when the repo\n * was renamed, so the very first iteration threw `Unknown secret` and never created\n * anything. So the rule here is the secret's **name shape**, not a list of names:\n * `*-encryption-key` gets a generated AES-GCM key and `*-signing-secret` gets 32\n * random bytes. Adding a secret to the template is then a one-line change needing\n * no matching edit here, which is the property the exact-name list did not have.\n *\n * **The throw was swallowed.** The original ended in `main().catch(console.error)`.\n * `console.error` returns `undefined` and never sets an exit status, so the process\n * exited **0** and CI marked the step green — the failure only surfaced one step\n * later, as an unexplainable `wrangler deploy` failure. Hence: the whole plan is\n * validated **before** any Cloudflare call, and a rejection reaches the runner as\n * a non-zero exit with a workflow annotation.\n *\n * ### Create-if-absent is a correctness property, not laziness\n *\n * An existing secret is left untouched. A replication encryption key seals every\n * remote target's credential; regenerating it on a redeploy would strand them all\n * as undecryptable. Rotation has to be a deliberate act with a re-encrypt path,\n * not a side effect of deploying.\n *\n * Requires a materialized `wrangler.jsonc` — run\n * `scripts/prepare-wrangler-config.ts` first. Fails rather than skipping when the\n * config is missing, because a step reporting \"Secret initialization complete\"\n * having created nothing is worse than a named error.\n */\n\nimport { execFileSync } from 'node:child_process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { parse } from 'jsonc-parser';\nimport { isEntrypoint } from './lib/entrypoint.ts';\nimport { fail } from './lib/github-actions.ts';\nimport { isEmptySecretsStoreListing, parseWranglerNames } from './lib/wrangler-table.ts';\nimport { loadManifest } from '../manifest.ts';\nimport { configPath, withWranglerPaths, type WranglerConfig } from './wrangler-config/types.ts';\n\n/**\n * The secret names the AES-GCM key generator produces, matched by **shape**.\n *\n * Keyed on the suffix because the alternative is the exact-name map that went\n * stale. See the header: a template naming `*-encryption-key` is then a one-line\n * change with no matching edit here, and a new secret breaks the deploy loudly\n * instead of silently.\n */\nconst ENCRYPTION_KEY_SUFFIX = '-encryption-key';\n\n/**\nThe secret names the random signing secret generator produces.\n*/\nconst SIGNING_SECRET_SUFFIX = '-signing-secret';\n\n/**\nA 256-bit AES-GCM key, base64-encoded — the shape the worker's crypto layer accepts.\n*/\nasync function generateAESGCMKey(): Promise<string> {\n const key = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt']);\n const exported = await crypto.subtle.exportKey('raw', key);\n // Chunked rather than spread: `String.fromCharCode(...bytes)` passes 32 arguments,\n // which is fine today and is a stack overflow the day the key is longer.\n let binary = '';\n for (const byte of new Uint8Array(exported)) {\n binary += String.fromCodePoint(byte);\n }\n return btoa(binary);\n}\n\n/**\nA 256-bit random signing secret for internal self-calls, hex-encoded.\n*/\nfunction generateSigningSecret(): Promise<string> {\n let hex = '';\n for (const byte of crypto.getRandomValues(new Uint8Array(32))) {\n hex += byte.toString(16).padStart(2, '0');\n }\n return Promise.resolve(hex);\n}\n\n/**\n * The generator for a secret name, chosen by the name's shape.\n *\n * A name matching neither is still refused rather than given a guess: the generator\n * is not the only thing that has to be right, and an unusable value that looks\n * provisioned is worse than a failure.\n */\nfunction generatorFor(secretName: string): () => Promise<string> {\n if (secretName.endsWith(ENCRYPTION_KEY_SUFFIX)) return generateAESGCMKey;\n if (secretName.endsWith(SIGNING_SECRET_SUFFIX)) return generateSigningSecret;\n throw new Error(\n `Unknown secret: ${secretName}. Name it '*-encryption-key' for a generated 32-byte AES-GCM key, ` +\n `or '*-signing-secret' for 32 random bytes, and teach this script the shape if neither fits.`,\n );\n}\n\n/**\nWhether this script can produce a value for `secretName`.\n*/\nfunction canProvisionSecret(secretName: string): boolean {\n try {\n generatorFor(secretName);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Runs a wrangler subcommand, optionally feeding `input` on stdin.\n *\n * Arguments are passed as an argv array rather than interpolated into a shell\n * string, so a value containing shell metacharacters cannot alter the command.\n */\nfunction wrangler(args: readonly string[], input?: string): string {\n try {\n // eslint-disable-next-line sonarjs/no-os-command-from-path\n return execFileSync('pnpm', ['exec', 'wrangler', ...args], {\n encoding: 'utf8',\n stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'],\n ...(input !== undefined && { input }),\n });\n } catch (error: unknown) {\n const maybeProcessError = error as { stdout?: string | Buffer; stderr?: string | Buffer; message?: string };\n const stdout: string = maybeProcessError.stdout ? maybeProcessError.stdout.toString() : '';\n const stderr: string = maybeProcessError.stderr ? maybeProcessError.stderr.toString() : '';\n throw new Error(`Command failed: pnpm exec wrangler ${args.join(' ')}\\n${stdout}${stderr || maybeProcessError.message || ''}`);\n }\n}\n\nfunction parseWranglerConfig(): WranglerConfig {\n if (!existsSync(configPath())) {\n throw new Error(\n `${configPath()} not found. Run scripts/prepare-wrangler-config.ts first — it is what creates the file this script reads.`,\n );\n }\n // `parse` is error-tolerant and returns a partial object, so an empty result means\n // malformed JSON rather than \"no secrets declared\". Treating that as an empty list\n // would report success having created nothing.\n const config = parse(readFileSync(configPath(), 'utf8')) as WranglerConfig;\n if (config.secrets_store_secrets === undefined && Object.keys(config).length === 0) {\n throw new Error(`${configPath()} is empty or not valid JSONC. Run scripts/prepare-wrangler-config.ts to regenerate it.`);\n }\n return config;\n}\n\n/**\nOne secret to create, as the plan names it.\n*/\ninterface PlannedSecret {\n storeId: string;\n secretName: string;\n}\n\n/**\n * Turn the config's bindings into a validated work list.\n *\n * Every entry is checked *before* the first Cloudflare call, so an\n * unprovisionable secret fails the step in milliseconds instead of after some other\n * secret has already been created.\n */\nfunction planSecrets(config: WranglerConfig): PlannedSecret[] {\n const plan: PlannedSecret[] = [];\n for (const [index, secret] of (config.secrets_store_secrets ?? []).entries()) {\n const label = secret.binding ?? `index ${index}`;\n const storeId = secret.store_id;\n const secretName = secret.secret_name;\n if (storeId === undefined || storeId === '' || secretName === undefined || secretName === '') {\n throw new Error(\n `secrets_store_secrets[${index}] (\"${label}\") needs both store_id and secret_name; ` +\n 'store_id is normally filled in by scripts/prepare-wrangler-config.ts.',\n );\n }\n if (!canProvisionSecret(secretName)) {\n throw new Error(`No generator for secret \"${secretName}\" (binding \"${label}\").`);\n }\n plan.push({ storeId, secretName });\n }\n return plan;\n}\n\n/**\n * List the secret names present in a store.\n *\n * Returns `undefined` when the listing itself failed, which is deliberately\n * distinct from an empty set: a transient CLI failure must not be read as \"the\n * secret is missing\" and cause a duplicate insert over a live value. An empty store\n * *is* a confirmed absence, so it maps to an empty set rather than `undefined`.\n *\n * The name is taken exactly. `output.includes(secretName)` is not a membership test:\n * `my-replication-encryption-key-2` satisfies a search for\n * `my-replication-encryption-key`, so a store holding only the suffixed entry would\n * report the unsuffixed one as already present and it would never be created.\n */\nfunction listSecretNames(storeId: string): Set<string> | undefined {\n let output: string;\n try {\n output = wrangler(['secrets-store', 'secret', 'list', storeId, '--remote']);\n } catch (error: unknown) {\n if (isEmptySecretsStoreListing(error)) {\n console.log(`Secrets Store ${storeId} is empty`);\n return new Set();\n }\n console.warn(`Unable to list secrets in store ${storeId}:`, error instanceof Error ? error.message : 'unknown error');\n return undefined;\n }\n return parseWranglerNames(output);\n}\n\nfunction createSecret(storeId: string, secretName: string, secretValue: string): void {\n console.log(`Creating secret: ${secretName}`);\n // The value goes in on stdin, never as an argv entry: an argv is visible to every\n // process on the runner through `ps`, and the previous\n // `echo \"${value}\" | wrangler … ${name}` also broke on `\"`, `$`, backticks and\n // newlines.\n wrangler(['secrets-store', 'secret', 'create', storeId, '--name', secretName, '--scopes', 'workers', '--remote'], secretValue);\n}\n\nexport async function main(): Promise<void> {\n console.log('Initializing Cloudflare secrets...');\n // One pass per manifest worker (`features.workers`), or the one default config.\n const workers = loadManifest(process.cwd())?.features?.workers ?? [{}];\n let planned = 0;\n for (const worker of workers) planned += await withWranglerPaths(worker, initializeOne);\n if (planned === 0) {\n throw new Error('wrangler.jsonc declares no secrets_store_secrets entries, so there is nothing to initialize.');\n }\n console.log('Secret initialization complete');\n}\n\n/**\n * Initialize the secrets one config declares; returns how many it declares.\n */\nasync function initializeOne(): Promise<number> {\n const config = parseWranglerConfig();\n const plan = planSecrets(config);\n\n const listedByStore = new Map<string, Set<string> | undefined>();\n\n for (const { storeId, secretName } of plan) {\n if (!listedByStore.has(storeId)) {\n listedByStore.set(storeId, listSecretNames(storeId));\n }\n const existing = listedByStore.get(storeId);\n if (existing === undefined) {\n // Refuse to guess: creating a secret we could not read back risks overwriting\n // a live value with a freshly generated one.\n throw new Error(`Could not list secrets in store ${storeId}; refusing to create ${secretName} without confirming it is absent.`);\n }\n if (existing.has(secretName)) {\n console.log(`Secret ${secretName} already exists; leaving it untouched.`);\n continue;\n }\n createSecret(storeId, secretName, await generatorFor(secretName)());\n existing.add(secretName);\n }\n return plan.length;\n}\n\n// Top-level await rather than `.catch(console.error)`, so a rejected `main` surfaces\n// as a stack trace with its cause intact and the process exits non-zero. Either way\n// the exit status has to be right: this runs in the deploy pipeline, and swallowing\n// the rejection reported a failed key bootstrap as a green step.\nif (isEntrypoint(import.meta.url)) {\n try {\n await main();\n } catch (error: unknown) {\n fail(error instanceof Error ? `Secret initialization failed: ${error.message}` : String(error));\n }\n}\n"],
|
|
5
|
+
"mappings": "+EA6CA,OAAS,gBAAAA,MAAoB,qBAC7B,OAAS,cAAAC,EAAY,gBAAAC,MAAoB,UACzC,OAAS,SAAAC,MAAa,eACtB,OAAS,gBAAAC,MAAoB,sBAC7B,OAAS,QAAAC,MAAY,0BACrB,OAAS,8BAAAC,EAA4B,sBAAAC,MAA0B,0BAC/D,OAAS,gBAAAC,MAAoB,iBAC7B,OAAS,cAAAC,EAAY,qBAAAC,MAA8C,6BAUnE,MAAMC,EAAwB,kBAKxBC,EAAwB,kBAK9B,eAAeC,GAAiB,CAC9B,MAAMC,EAAM,MAAM,OAAO,OAAO,YAAY,CAAE,KAAM,UAAW,OAAQ,GAAG,EAAI,GAAM,CAAC,UAAW,SAAS,CAAC,EACpGC,EAAW,MAAM,OAAO,OAAO,UAAU,MAAOD,CAAG,EAGzD,IAAIE,EAAS,GACb,UAAWC,KAAQ,IAAI,WAAWF,CAAQ,EACxCC,GAAU,OAAO,cAAcC,CAAI,EAErC,OAAO,KAAKD,CAAM,CACpB,CAVeE,EAAAL,EAAA,qBAef,SAASM,GAAqB,CAC5B,IAAIC,EAAM,GACV,UAAWH,KAAQ,OAAO,gBAAgB,IAAI,WAAW,EAAE,CAAC,EAC1DG,GAAOH,EAAK,SAAS,EAAE,EAAE,SAAS,EAAG,GAAG,EAE1C,OAAO,QAAQ,QAAQG,CAAG,CAC5B,CANSF,EAAAC,EAAA,yBAeT,SAASE,EAAaC,EAAkB,CACtC,GAAIA,EAAW,SAASX,CAAqB,EAAG,OAAOE,EACvD,GAAIS,EAAW,SAASV,CAAqB,EAAG,OAAOO,EACvD,MAAM,IAAI,M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CAVsB3B,EAAAyB,EAAA,QAetB,eAAeI,GAAa,CAC1B,MAAMf,EAASD,EAAmB,EAC5BG,EAAOD,EAAYD,CAAM,EAEzBgB,EAAgB,IAAI,IAE1B,SAAW,CAAE,QAAAV,EAAS,WAAAhB,CAAU,IAAMY,EAAM,CACrCc,EAAc,IAAIV,CAAO,GAC5BU,EAAc,IAAIV,EAASC,EAAgBD,CAAO,CAAC,EAErD,MAAMW,EAAWD,EAAc,IAAIV,CAAO,EAC1C,GAAIW,IAAa,OAGf,MAAM,IAAI,MAAM,mCAAmCX,CAAO,wBAAwBhB,CAAU,mCAAmC,EAEjI,GAAI2B,EAAS,IAAI3B,CAAU,EAAG,CAC5B,QAAQ,IAAI,UAAUA,CAAU,wCAAwC,EACxE,QACF,CACAmB,EAAaH,EAAShB,EAAY,MAAMD,EAAaC,CAAU,EAAC,CAAE,EAClE2B,EAAS,IAAI3B,CAAU,CACzB,CACA,OAAOY,EAAK,MACd,CAMA,GA9BehB,EAAA6B,EAAA,iBA8BX3C,EAAa,YAAY,GAAG,EAC9B,GAAI,CACF,MAAMuC,EAAI,CACZ,OAAShB,EAAgB,CACvBtB,EAAKsB,aAAiB,MAAQ,iCAAiCA,EAAM,OAAO,GAAK,OAAOA,CAAK,CAAC,CAChG",
|
|
6
|
+
"names": ["execFileSync", "existsSync", "readFileSync", "parse", "isEntrypoint", "fail", "isEmptySecretsStoreListing", "parseWranglerNames", "loadManifest", "configPath", "withWranglerPaths", "ENCRYPTION_KEY_SUFFIX", "SIGNING_SECRET_SUFFIX", "generateAESGCMKey", "key", "exported", "binary", "byte", "__name", "generateSigningSecret", "hex", "generatorFor", "secretName", "canProvisionSecret", "wrangler", "args", "input", "error", "maybeProcessError", "stdout", "stderr", "parseWranglerConfig", "config", "planSecrets", "plan", "index", "secret", "label", "storeId", "listSecretNames", "output", "createSecret", "secretValue", "main", "workers", "planned", "worker", "initializeOne", "listedByStore", "existing"]
|
|
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":"AA2CA;;;;GAIG;AACH,wBAAgB,IAAI,IAAI,MAAM,EAAE,CAkB/B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var s=Object.defineProperty;var o=(r,e)=>s(r,"name",{value:e,configurable:!0});import{loadManifest as i}from"../manifest.js";import{setOutput as a}from"./lib/github-actions.js";import{applyTopLevelPatch as p,applyVarsPatch as m,ensureMinimumConfigVersion as c,prepareConfigFile as f}from"./wrangler-config/patches.js";import{withWranglerPaths as u}from"./wrangler-config/types.js";import{provisionWranglerResources as l}from"./wrangler-config/resources.js";import{isEntrypoint as d}from"./lib/entrypoint.js";function g(){const r=i(process.cwd()),e=r?.features?.workers??[{}];if(e.length>1&&process.env.WRANGLER_JSONC?.trim())throw new Error("WRANGLER_JSONC holds one config, but features.workers declares several; use WRANGLER_PATCH_JSON instead.");const n=e.flatMap(t=>u(t,()=>w(r)));return a("created",[...new Set(n)].join(",")),console.log("Wrangler configuration is ready."),n}o(g,"main");function w(r){f(),c(),p(),m();const e=r?.features?.kv;return l({namespaceNames:{...e?.namespaceNames},requiredKvBindings:e?.bindings??[]})}o(w,"prepareOne"),d(import.meta.url)&&g();export{g 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 *\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
|
|
5
|
-
"mappings": "+
|
|
6
|
-
"names": ["loadManifest", "setOutput", "applyTopLevelPatch", "applyVarsPatch", "ensureMinimumConfigVersion", "prepareConfigFile", "provisionWranglerResources", "isEntrypoint", "main", "
|
|
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 * Templates come from the manifest's `features.workers` (`template`, and `config` to write; default\n * `apps/api/wrangler.template.jsonc` to `wrangler.jsonc`). KV bindings come from the manifest's `features.kv` (none declared: none added).\n */\nimport { loadManifest } from '../manifest.ts';\nimport type { FamilyManifest } from '../manifest.ts';\nimport { setOutput } from './lib/github-actions.ts';\nimport { applyTopLevelPatch, applyVarsPatch, ensureMinimumConfigVersion, prepareConfigFile } from './wrangler-config/patches.ts';\nimport { withWranglerPaths } from './wrangler-config/types.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 // Manifest-driven: each `features.workers` entry is prepared in turn; none declared is the one default worker.\n const manifest = loadManifest(process.cwd());\n const workers = manifest?.features?.workers ?? [{}];\n if (workers.length > 1 && process.env['WRANGLER_JSONC']?.trim()) {\n throw new Error('WRANGLER_JSONC holds one config, but features.workers declares several; use WRANGLER_PATCH_JSON instead.');\n }\n const created = workers.flatMap((worker) => withWranglerPaths(worker, () => prepareOne(manifest)));\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', [...new Set(created)].join(','));\n console.log('Wrangler configuration is ready.');\n return created;\n}\n\nfunction prepareOne(manifest: FamilyManifest | null): 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 = manifest?.features?.kv;\n return provisionWranglerResources({\n namespaceNames: { ...kv?.namespaceNames },\n requiredKvBindings: kv?.bindings ?? [],\n });\n}\n\nif (isEntrypoint(import.meta.url)) {\n main();\n}\n"],
|
|
5
|
+
"mappings": "+EAmCA,OAAS,gBAAAA,MAAoB,iBAE7B,OAAS,aAAAC,MAAiB,0BAC1B,OAAS,sBAAAC,EAAoB,kBAAAC,EAAgB,8BAAAC,EAA4B,qBAAAC,MAAyB,+BAClG,OAAS,qBAAAC,MAAyB,6BAClC,OAAS,8BAAAC,MAAkC,iCAC3C,OAAS,gBAAAC,MAAoB,sBAOvB,SAAUC,GAAI,CAElB,MAAMC,EAAWV,EAAa,QAAQ,IAAG,CAAE,EACrCW,EAAUD,GAAU,UAAU,SAAW,CAAC,CAAA,CAAE,EAClD,GAAIC,EAAQ,OAAS,GAAK,QAAQ,IAAI,gBAAmB,KAAI,EAC3D,MAAM,IAAI,MAAM,0GAA0G,EAE5H,MAAMC,EAAUD,EAAQ,QAASE,GAAWP,EAAkBO,EAAQ,IAAMC,EAAWJ,CAAQ,CAAC,CAAC,EAQjG,OAAAT,EAAU,UAAW,CAAC,GAAG,IAAI,IAAIW,CAAO,CAAC,EAAE,KAAK,GAAG,CAAC,EACpD,QAAQ,IAAI,kCAAkC,EACvCA,CACT,CAlBgBG,EAAAN,EAAA,QAoBhB,SAASK,EAAWJ,EAA+B,CACjDL,EAAiB,EACjBD,EAA0B,EAC1BF,EAAkB,EAClBC,EAAc,EAEd,MAAMa,EAAKN,GAAU,UAAU,GAC/B,OAAOH,EAA2B,CAChC,eAAgB,CAAE,GAAGS,GAAI,cAAc,EACvC,mBAAoBA,GAAI,UAAY,CAAA,EACrC,CACH,CAXSD,EAAAD,EAAA,cAaLN,EAAa,YAAY,GAAG,GAC9BC,EAAI",
|
|
6
|
+
"names": ["loadManifest", "setOutput", "applyTopLevelPatch", "applyVarsPatch", "ensureMinimumConfigVersion", "prepareConfigFile", "withWranglerPaths", "provisionWranglerResources", "isEntrypoint", "main", "manifest", "workers", "created", "worker", "prepareOne", "__name", "kv"]
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"patches.d.ts","sourceRoot":"","sources":["../../../src/scripts/wrangler-config/patches.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAKH,OAAO,
|
|
1
|
+
{"version":3,"file":"patches.d.ts","sourceRoot":"","sources":["../../../src/scripts/wrangler-config/patches.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAKH,OAAO,EAA4B,KAAK,cAAc,EAAE,MAAM,YAAY,CAAC;AAE3E;;EAEE;AACF,MAAM,WAAW,UAAU;IACzB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,cAAc,CAAC;CACxB;AAED,wBAAgB,UAAU,IAAI,UAAU,CAGvC;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,KAAK,EAAE,OAAO,GAAG,MAAM,CAGtG;AAED;;EAEE;AACF,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAEjD;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,CAExE;AAED;;EAEE;AACF,wBAAgB,cAAc,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,CAgBnE;AA0BD;;;GAGG;AACH,wBAAgB,iBAAiB,IAAI,IAAI,CASxC;AAED;;;;;;;GAOG;AACH,wBAAgB,0BAA0B,IAAI,IAAI,CAYjD;AAED,wBAAgB,kBAAkB,IAAI,IAAI,CAYzC;AAED,wBAAgB,cAAc,IAAI,IAAI,CAwBrC"}
|