@reddoorla/maintenance 0.76.0 → 0.79.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 +34 -7
- package/dist/{blux-RIJBRVCF.js → blux-2P4FGCUL.js} +5 -5
- package/dist/{blux-RIJBRVCF.js.map → blux-2P4FGCUL.js.map} +1 -1
- package/dist/{bump-deps-OQR3IXLN.js → bump-deps-XB2LJTVN.js} +3 -3
- package/dist/{chunk-RHPDQW6D.js → chunk-2SLED3NB.js} +1 -1
- package/dist/{chunk-RHPDQW6D.js.map → chunk-2SLED3NB.js.map} +1 -1
- package/dist/{chunk-3U3IGVAQ.js → chunk-3LWKIKZ2.js} +47 -9
- package/dist/chunk-3LWKIKZ2.js.map +1 -0
- package/dist/{chunk-HIN3P4ZN.js → chunk-4SOCPK7A.js} +10 -1
- package/dist/chunk-4SOCPK7A.js.map +1 -0
- package/dist/{chunk-CASCWQQX.js → chunk-73UFRZKY.js} +34 -19
- package/dist/chunk-73UFRZKY.js.map +1 -0
- package/dist/chunk-A3WDWNN5.js +70 -0
- package/dist/chunk-A3WDWNN5.js.map +1 -0
- package/dist/{chunk-D3DQFC32.js → chunk-ATJ6ZA2V.js} +2 -2
- package/dist/{chunk-ZO7WNY57.js → chunk-B5ZUQZFL.js} +2 -2
- package/dist/{chunk-PH3AGF4Z.js → chunk-DC5H7KEQ.js} +2 -2
- package/dist/{chunk-DYKG53IR.js → chunk-FAQIMC26.js} +9 -9
- package/dist/{chunk-4VAUSRSS.js → chunk-FVVGDIGX.js} +2 -2
- package/dist/{chunk-7MJBTV2R.js → chunk-FX7RAMGC.js} +2 -2
- package/dist/{chunk-PKVZMFEB.js → chunk-K5JZ5KLO.js} +2 -2
- package/dist/{chunk-CZAMYVOP.js → chunk-KPQXB5CR.js} +2 -2
- package/dist/{chunk-BTEBRTW4.js → chunk-LS6QPANO.js} +2 -2
- package/dist/{chunk-2X322ZES.js → chunk-MGJ72BA4.js} +2 -2
- package/dist/chunk-MNDIED4M.js +137 -0
- package/dist/chunk-MNDIED4M.js.map +1 -0
- package/dist/{chunk-ZYBOT5PM.js → chunk-NT4WIP7I.js} +2 -2
- package/dist/{chunk-JNXCDUYB.js → chunk-Q276MZ7E.js} +3 -4
- package/dist/chunk-Q276MZ7E.js.map +1 -0
- package/dist/{chunk-GYNRZCM6.js → chunk-QG6OSL4M.js} +2 -2
- package/dist/{chunk-IRRZG66U.js → chunk-QMXQUL5Z.js} +34 -18
- package/dist/chunk-QMXQUL5Z.js.map +1 -0
- package/dist/{chunk-YEGHUODU.js → chunk-VSHC4HOI.js} +96 -1
- package/dist/chunk-VSHC4HOI.js.map +1 -0
- package/dist/{chunk-JTRTG5CU.js → chunk-YIQ7IWE3.js} +2 -2
- package/dist/{chunk-XKOZUVK2.js → chunk-ZTPPCHDB.js} +1 -1
- package/dist/chunk-ZTPPCHDB.js.map +1 -0
- package/dist/cli/bin.js +32 -21
- package/dist/cli/bin.js.map +1 -1
- package/dist/cli/commands/audit.d.ts +1 -1
- package/dist/cli/commands/audit.js +7 -5
- package/dist/cli/commands/audit.js.map +1 -1
- package/dist/client-X5WUJWDE.js +11 -0
- package/dist/configs/eslint.js +10 -0
- package/dist/configs/eslint.js.map +1 -1
- package/dist/{convert-to-pnpm-OVMASATZ.js → convert-to-pnpm-FZHSLUQB.js} +3 -3
- package/dist/{db-3QW2XEXA.js → db-JSIZYT23.js} +3 -3
- package/dist/{digest-75FWSC74.js → digest-NQAQI34P.js} +11 -11
- package/dist/forms/index.js +6 -62
- package/dist/forms/index.js.map +1 -1
- package/dist/{github-signals-TF3VSNIN.js → github-signals-4LWQGD5V.js} +5 -5
- package/dist/{health-endpoint-JZGYCMTV.js → health-endpoint-LFVE26QS.js} +3 -3
- package/dist/index.d.ts +11 -3
- package/dist/index.js +32 -24
- package/dist/index.js.map +1 -1
- package/dist/{init-2KOISBCZ.js → init-Y5O33BUL.js} +14 -12
- package/dist/{init-2KOISBCZ.js.map → init-Y5O33BUL.js.map} +1 -1
- package/dist/{launch-K4EHKTXC.js → launch-3SYLX263.js} +8 -5
- package/dist/launch-3SYLX263.js.map +1 -0
- package/dist/migrate-LJUFGXQZ.js +7 -0
- package/dist/{onboard-PX36YDZA.js → onboard-RDGHVCNG.js} +3 -3
- package/dist/{orchestrate-CPR6KVS2.js → orchestrate-QOQXOJLI.js} +5 -5
- package/dist/{preflight-QRRMPI7K.js → preflight-2PWVVIRR.js} +6 -6
- package/dist/protection-audit-X3BHT2MB.js +140 -0
- package/dist/protection-audit-X3BHT2MB.js.map +1 -0
- package/dist/recipes/sync-configs.d.ts +1 -1
- package/dist/recipes/sync-configs.js +3 -3
- package/dist/{renovate-dispatch-6II2JVOX.js → renovate-dispatch-2VYCEH42.js} +2 -2
- package/dist/renovate-dispatch-2VYCEH42.js.map +1 -0
- package/dist/{report-SLGBDJ6O.js → report-IU4CLJS5.js} +3 -3
- package/dist/{self-updating-2YSVNMPP.js → self-updating-ALMUWJNX.js} +5 -4
- package/dist/{self-updating-2YSVNMPP.js.map → self-updating-ALMUWJNX.js.map} +1 -1
- package/dist/{selftest-RVASRO3Z.js → selftest-PJFABZDM.js} +5 -5
- package/dist/{smoke-suite-CSP23NZM.js → smoke-suite-SUEJFBYP.js} +3 -3
- package/dist/{submissions-MDKWJYMM.js → submissions-3I3GAQAX.js} +13 -5
- package/dist/submissions-3I3GAQAX.js.map +1 -0
- package/dist/{submissions-BNRGY3JQ.js → submissions-SURN7BV5.js} +3 -3
- package/dist/{svelte-codemods-V54KOBWU.js → svelte-codemods-IWO7X3F3.js} +3 -3
- package/dist/{sync-configs-UBCJRASZ.js → sync-configs-7XGHFC6P.js} +4 -4
- package/dist/{types-0jreMCF5.d.ts → types-DnEL3NRn.d.ts} +1 -1
- package/dist/{upgrade-WR6ICPAG.js → upgrade-AM4S7JF3.js} +3 -3
- package/package.json +1 -1
- package/dist/chunk-3U3IGVAQ.js.map +0 -1
- package/dist/chunk-CASCWQQX.js.map +0 -1
- package/dist/chunk-HIN3P4ZN.js.map +0 -1
- package/dist/chunk-IRRZG66U.js.map +0 -1
- package/dist/chunk-JNXCDUYB.js.map +0 -1
- package/dist/chunk-XKOZUVK2.js.map +0 -1
- package/dist/chunk-YEGHUODU.js.map +0 -1
- package/dist/client-NVVQK3HH.js +0 -11
- package/dist/launch-K4EHKTXC.js.map +0 -1
- package/dist/migrate-35DNNF3H.js +0 -7
- package/dist/renovate-dispatch-6II2JVOX.js.map +0 -1
- package/dist/submissions-MDKWJYMM.js.map +0 -1
- /package/dist/{bump-deps-OQR3IXLN.js.map → bump-deps-XB2LJTVN.js.map} +0 -0
- /package/dist/{chunk-D3DQFC32.js.map → chunk-ATJ6ZA2V.js.map} +0 -0
- /package/dist/{chunk-ZO7WNY57.js.map → chunk-B5ZUQZFL.js.map} +0 -0
- /package/dist/{chunk-PH3AGF4Z.js.map → chunk-DC5H7KEQ.js.map} +0 -0
- /package/dist/{chunk-DYKG53IR.js.map → chunk-FAQIMC26.js.map} +0 -0
- /package/dist/{chunk-4VAUSRSS.js.map → chunk-FVVGDIGX.js.map} +0 -0
- /package/dist/{chunk-7MJBTV2R.js.map → chunk-FX7RAMGC.js.map} +0 -0
- /package/dist/{chunk-PKVZMFEB.js.map → chunk-K5JZ5KLO.js.map} +0 -0
- /package/dist/{chunk-CZAMYVOP.js.map → chunk-KPQXB5CR.js.map} +0 -0
- /package/dist/{chunk-BTEBRTW4.js.map → chunk-LS6QPANO.js.map} +0 -0
- /package/dist/{chunk-2X322ZES.js.map → chunk-MGJ72BA4.js.map} +0 -0
- /package/dist/{chunk-ZYBOT5PM.js.map → chunk-NT4WIP7I.js.map} +0 -0
- /package/dist/{chunk-GYNRZCM6.js.map → chunk-QG6OSL4M.js.map} +0 -0
- /package/dist/{chunk-JTRTG5CU.js.map → chunk-YIQ7IWE3.js.map} +0 -0
- /package/dist/{client-NVVQK3HH.js.map → client-X5WUJWDE.js.map} +0 -0
- /package/dist/{convert-to-pnpm-OVMASATZ.js.map → convert-to-pnpm-FZHSLUQB.js.map} +0 -0
- /package/dist/{db-3QW2XEXA.js.map → db-JSIZYT23.js.map} +0 -0
- /package/dist/{digest-75FWSC74.js.map → digest-NQAQI34P.js.map} +0 -0
- /package/dist/{github-signals-TF3VSNIN.js.map → github-signals-4LWQGD5V.js.map} +0 -0
- /package/dist/{health-endpoint-JZGYCMTV.js.map → health-endpoint-LFVE26QS.js.map} +0 -0
- /package/dist/{migrate-35DNNF3H.js.map → migrate-LJUFGXQZ.js.map} +0 -0
- /package/dist/{onboard-PX36YDZA.js.map → onboard-RDGHVCNG.js.map} +0 -0
- /package/dist/{orchestrate-CPR6KVS2.js.map → orchestrate-QOQXOJLI.js.map} +0 -0
- /package/dist/{preflight-QRRMPI7K.js.map → preflight-2PWVVIRR.js.map} +0 -0
- /package/dist/{report-SLGBDJ6O.js.map → report-IU4CLJS5.js.map} +0 -0
- /package/dist/{selftest-RVASRO3Z.js.map → selftest-PJFABZDM.js.map} +0 -0
- /package/dist/{smoke-suite-CSP23NZM.js.map → smoke-suite-SUEJFBYP.js.map} +0 -0
- /package/dist/{submissions-BNRGY3JQ.js.map → submissions-SURN7BV5.js.map} +0 -0
- /package/dist/{svelte-codemods-V54KOBWU.js.map → svelte-codemods-IWO7X3F3.js.map} +0 -0
- /package/dist/{sync-configs-UBCJRASZ.js.map → sync-configs-7XGHFC6P.js.map} +0 -0
- /package/dist/{upgrade-WR6ICPAG.js.map → upgrade-AM4S7JF3.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/recipes/sync-configs.ts","../src/recipes/sync-configs/gitignore.ts"],"sourcesContent":["import { readFile, writeFile, mkdir } from \"node:fs/promises\";\nimport { join, dirname } from \"node:path\";\nimport type { RecipeResult, Site, ConfigName } from \"../types.js\";\nimport { ALL_TEMPLATES, templatesByName, type ConfigTemplate } from \"./sync-configs/templates.js\";\nimport {\n CANONICAL_GITIGNORE_ENTRIES,\n mergeGitignore,\n findTrackedArtifacts,\n} from \"./sync-configs/gitignore.js\";\nimport { listTrackedFiles, removeFromIndex } from \"../util/git.js\";\nimport { withRecipe } from \"./_with-recipe.js\";\n\nexport type SyncConfigsOptions = {\n which?: ConfigName[];\n};\n\nconst GITIGNORE_CONFIG: ConfigName = \"gitignore\";\nconst SVELTE_CONFIG: ConfigName = \"svelte\";\nconst NETLIFY_CONFIG: ConfigName = \"netlify\";\n\n/** A site's `svelte.config.js` is \"compliant\" — and left untouched by sync —\n * once it builds on the canonical helpers (createSvelteConfig + adapter-netlify).\n *\n * Unlike the other exact-match templates, svelte.config legitimately carries\n * site-specific `kit.alias` and `compilerOptions`; an exact overwrite would\n * clobber those on every sync (it silently dropped MSOT's $utils alias,\n * 2026-06-04). So once a config is on the canonical pattern we preserve it as-is\n * and only rewrite a genuinely off-pattern (or missing) config. `createSvelteConfig`\n * now provides the canonical `$lib` aliases itself, and a site's own `kit.alias`\n * overrides per key (and may add more), so a site's additive customization is safe\n * to preserve. */\nfunction isSvelteConfigCompliant(contents: string): boolean {\n return contents.includes(\"createSvelteConfig\") && contents.includes(\"@sveltejs/adapter-netlify\");\n}\n\n/** Any of the baseline security headers — the marker that a netlify.toml is\n * deliberately hardened (vs. e.g. a cache-control-only `[[headers]]` block). */\nconst SECURITY_HEADER_RE =\n /Strict-Transport-Security|Content-Security-Policy|X-Frame-Options|X-Content-Type-Options|Referrer-Policy|Permissions-Policy|Cross-Origin-Opener-Policy/i;\n\n/** A site's `netlify.toml` is \"compliant\" — and left untouched by sync — once it\n * carries a `[[headers]]` block AND a security header (HSTS/CSP/X-Frame-Options/…).\n *\n * Like svelte.config, netlify.toml legitimately holds site-specific config\n * (custom CSP, redirects, per-route headers). The canonical template ships the\n * baseline security headers, but an exact overwrite would CLOBBER a site's own\n * hardening — that bug stripped gallerysonder's headers on a routine sync\n * (2026-06-10). So a genuinely-hardened file is left alone, while a missing,\n * header-less (previously-stripped), OR merely cache-header file is non-compliant\n * and gets the canonical template, which backfills the security baseline. */\nfunction isNetlifyConfigCompliant(contents: string): boolean {\n return contents.includes(\"[[headers]]\") && SECURITY_HEADER_RE.test(contents);\n}\n\n/** Runtime enumeration of every `ConfigName`. Mirror of the union in\n * `src/types.ts`. Used by CLI `--only` validation; a missing entry would\n * silently accept typos. The type-test in `tests/types.test.ts` guards\n * against drift between this array and the union. */\nexport const ALL_CONFIG_NAMES: ConfigName[] = [\n \"lighthouse\",\n \"eslint\",\n \"prettier\",\n \"prettier-ignore\",\n \"playwright-a11y\",\n \"svelte\",\n \"gitignore\",\n \"renovate-action\",\n \"renovate-config\",\n \"netlify\",\n];\n\nexport function isConfigName(value: string): value is ConfigName {\n return (ALL_CONFIG_NAMES as string[]).includes(value);\n}\n\nasync function readMaybe(path: string): Promise<string | null> {\n try {\n return await readFile(path, \"utf-8\");\n } catch {\n return null;\n }\n}\n\nasync function planTemplateDiffs(\n cwd: string,\n templates: ConfigTemplate[],\n): Promise<ConfigTemplate[]> {\n const diffs: ConfigTemplate[] = [];\n for (const t of templates) {\n const existing = await readMaybe(join(cwd, t.path));\n if (existing === t.contents) continue;\n // svelte.config is compliance-checked, not exact-matched: an existing config\n // already on the canonical pattern is left alone so its aliases/compilerOptions\n // survive. A missing (null) or off-pattern config still gets the canonical template.\n if (t.config === SVELTE_CONFIG && existing !== null && isSvelteConfigCompliant(existing)) {\n continue;\n }\n // netlify.toml is likewise compliance-checked: a file that already carries\n // `[[headers]]` is hardened and left alone (an exact overwrite would strip\n // its security headers). A header-less / missing file gets the template.\n if (t.config === NETLIFY_CONFIG && existing !== null && isNetlifyConfigCompliant(existing)) {\n continue;\n }\n diffs.push(t);\n }\n return diffs;\n}\n\ntype GitignorePlan =\n { kind: \"noop\" } | { kind: \"apply\"; content: string; toUntrack: string[]; added: string[] };\n\nasync function planGitignore(cwd: string): Promise<GitignorePlan> {\n const existing = await readMaybe(join(cwd, \".gitignore\"));\n const merge = mergeGitignore(existing, CANONICAL_GITIGNORE_ENTRIES);\n const tracked = await listTrackedFiles(cwd);\n const toUntrack = findTrackedArtifacts(tracked, CANONICAL_GITIGNORE_ENTRIES);\n if (merge.added.length === 0 && toUntrack.length === 0) return { kind: \"noop\" };\n return { kind: \"apply\", content: merge.content, toUntrack, added: merge.added };\n}\n\nasync function applyGitignore(\n cwd: string,\n plan: Extract<GitignorePlan, { kind: \"apply\" }>,\n): Promise<void> {\n await writeFile(join(cwd, \".gitignore\"), plan.content, \"utf-8\");\n if (plan.toUntrack.length > 0) {\n await removeFromIndex(cwd, plan.toUntrack);\n }\n}\n\nexport async function syncConfigs(\n site: Site,\n opts: SyncConfigsOptions = {},\n): Promise<RecipeResult> {\n const requested = opts.which ?? ALL_TEMPLATES.map((t) => t.config).concat(GITIGNORE_CONFIG);\n const templateNames = requested.filter((c): c is ConfigName => c !== GITIGNORE_CONFIG);\n const templates = templatesByName(templateNames);\n const includeGitignore = requested.includes(GITIGNORE_CONFIG);\n\n return withRecipe({\n name: \"sync-configs\",\n site,\n plan: async () => {\n const templateDiffs = await planTemplateDiffs(site.path, templates);\n const gitignorePlan: GitignorePlan = includeGitignore\n ? await planGitignore(site.path)\n : { kind: \"noop\" };\n if (templateDiffs.length === 0 && gitignorePlan.kind === \"noop\") {\n return { kind: \"noop\", notes: \"all targeted configs already match\" };\n }\n return { kind: \"apply\", plan: { templateDiffs, gitignorePlan } };\n },\n apply: async ({ templateDiffs, gitignorePlan }, { commit }) => {\n for (const t of templateDiffs) {\n const dest = join(site.path, t.path);\n await mkdir(dirname(dest), { recursive: true });\n await writeFile(dest, t.contents, \"utf-8\");\n await commit(`chore: sync ${t.config} config from @reddoorla/maintenance`);\n }\n if (gitignorePlan.kind === \"apply\") {\n await applyGitignore(site.path, gitignorePlan);\n await commit(`chore: sync gitignore from @reddoorla/maintenance`);\n }\n return { kind: \"ok\" };\n },\n });\n}\n","/**\n * Comment line written above the appended block so future runs (and humans)\n * can recognize the managed section. Presence of this line is incidental —\n * the merge logic is keyed on each entry's normalized form, not on the marker.\n */\nexport const MANAGED_MARKER = \"# canonical entries from @reddoorla/maintenance sync-configs\";\n\n/**\n * Build artifacts, test outputs, deploy caches, and secrets that should never\n * be tracked across the reddoor fleet. Sites may keep additional site-specific\n * entries — they are preserved on merge.\n */\nexport const CANONICAL_GITIGNORE_ENTRIES: readonly string[] = [\n \"node_modules/\",\n \"build/\",\n \"dist/\",\n \".svelte-kit/\",\n \"coverage/\",\n \".vitest-cache/\",\n \"playwright-report/\",\n \"test-results/\",\n \".lighthouseci/\",\n \".tsbuildinfo\",\n \".env\",\n \".env.*\",\n \"!.env.example\",\n \".DS_Store\",\n \"*.log\",\n \".vercel/\",\n \".netlify/\",\n \".reddoor-a11y/\",\n // The a11y audit's transient spec dir, written inside the checkout and\n // normally cleaned, but a timeout-SIGKILL of the parent orphans it. Ignored\n // fleet-wide so it never dirties a self-updating repo's tree (2026-06-10 M-D).\n \".reddoor-a11y-spec-*/\",\n];\n\nexport type MergeResult = { content: string; added: string[] };\n\nfunction stripLeadingSlash(s: string): string {\n return s.startsWith(\"/\") ? s.slice(1) : s;\n}\n\nfunction stripTrailingSlash(s: string): string {\n return s.endsWith(\"/\") ? s.slice(0, -1) : s;\n}\n\n/**\n * Normalize for presence comparison only: strip leading `/`, trailing `/`,\n * and surrounding whitespace. `build`, `/build`, `build/`, and `/build/` all\n * collapse to the same key.\n */\nfunction normalizePresence(line: string): string {\n return stripTrailingSlash(stripLeadingSlash(line.trim()));\n}\n\nfunction presentSet(existing: string): Set<string> {\n const set = new Set<string>();\n for (const raw of existing.split(/\\r?\\n/)) {\n const trimmed = raw.trim();\n if (!trimmed) continue;\n if (trimmed.startsWith(\"#\")) continue;\n set.add(normalizePresence(trimmed));\n }\n return set;\n}\n\n/**\n * Merge `canonical` entries into `existing` .gitignore content.\n *\n * - Missing entries are appended under a managed marker comment.\n * - Existing entries (in any normalized variant — `/build`, `build/`, etc.)\n * are preserved as-is; we never rewrite the site's own lines.\n * - When every canonical entry is already present, returns the original\n * content unchanged with `added: []` — the recipe can treat that as noop.\n */\nexport function mergeGitignore(existing: string | null, canonical: readonly string[]): MergeResult {\n if (existing === null) {\n const body = [MANAGED_MARKER, ...canonical].join(\"\\n\") + \"\\n\";\n return { content: body, added: [...canonical] };\n }\n const present = presentSet(existing);\n const added: string[] = [];\n for (const entry of canonical) {\n const norm = normalizePresence(entry);\n if (!present.has(norm)) {\n added.push(entry);\n present.add(norm);\n }\n }\n if (added.length === 0) {\n return { content: existing, added: [] };\n }\n let base = existing;\n if (!base.endsWith(\"\\n\")) base += \"\\n\";\n const block = [\"\", MANAGED_MARKER, ...added].join(\"\\n\") + \"\\n\";\n return { content: base + block, added };\n}\n\n/**\n * Of the tracked paths, return those that fall under a canonical *directory*\n * entry — i.e., paths that the freshly-synced .gitignore now wants ignored\n * but which git currently has in the index.\n *\n * File-pattern entries (`.env`, `*.log`, `.DS_Store`) are intentionally\n * skipped: they may contain user-meaningful data, and `git rm --cached`\n * cannot scrub secrets from history anyway. Surfaced for manual review\n * instead of auto-removing.\n */\nexport function findTrackedArtifacts(\n tracked: readonly string[],\n canonical: readonly string[],\n): string[] {\n const dirEntries: string[] = [];\n for (const raw of canonical) {\n const t = raw.trim();\n if (!t) continue;\n if (t.startsWith(\"!\")) continue;\n if (/[*?[]/.test(t)) continue;\n const noLead = stripLeadingSlash(t);\n if (!noLead.endsWith(\"/\")) continue;\n const name = stripTrailingSlash(noLead);\n if (!name) continue;\n dirEntries.push(name);\n }\n const matched: string[] = [];\n for (const path of tracked) {\n for (const dir of dirEntries) {\n if (path === dir || path.startsWith(dir + \"/\")) {\n matched.push(path);\n break;\n }\n }\n }\n return matched;\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,SAAS,UAAU,WAAW,aAAa;AAC3C,SAAS,MAAM,eAAe;;;ACIvB,IAAM,iBAAiB;AAOvB,IAAM,8BAAiD;AAAA,EAC5D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,E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gB,aAAa;AAC/C,QAAM,mBAAmB,UAAU,SAAS,gBAAgB;AAE5D,SAAO,WAAW;AAAA,IAChB,MAAM;AAAA,IACN;AAAA,IACA,MAAM,YAAY;AAChB,YAAM,gBAAgB,MAAM,kBAAkB,KAAK,MAAM,SAAS;AAClE,YAAM,gBAA+B,mBACjC,MAAM,cAAc,KAAK,IAAI,IAC7B,EAAE,MAAM,OAAO;AACnB,UAAI,cAAc,WAAW,KAAK,cAAc,SAAS,QAAQ;AAC/D,eAAO,EAAE,MAAM,QAAQ,OAAO,qCAAqC;AAAA,MACrE;AACA,aAAO,EAAE,MAAM,SAAS,MAAM,EAAE,eAAe,cAAc,EAAE;AAAA,IACjE;AAAA,IACA,OAAO,OAAO,EAAE,eAAe,cAAc,GAAG,EAAE,OAAO,MAAM;AAC7D,iBAAW,KAAK,eAAe;AAC7B,cAAM,OAAO,KAAK,KAAK,MAAM,EAAE,IAAI;AACnC,cAAM,MAAM,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AAC9C,cAAM,UAAU,MAAM,EAAE,UAAU,OAAO;AACzC,cAAM,OAAO,eAAe,EAAE,MAAM,qCAAqC;AAAA,MAC3E;AACA,UAAI,cAAc,SAAS,SAAS;AAClC,cAAM,eAAe,KAAK,MAAM,aAAa;AAC7C,cAAM,OAAO,mDAAmD;AAAA,MAClE;AACA,aAAO,EAAE,MAAM,KAAK;AAAA,IACtB;AAAA,EACF,CAAC;AACH;","names":[]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
openDb,
|
|
3
3
|
readDbConfig
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-DC5H7KEQ.js";
|
|
5
5
|
|
|
6
6
|
// src/db/fleet-events.ts
|
|
7
7
|
async function recordFleetEvent(db, e) {
|
|
@@ -47,4 +47,4 @@ async function recordFleetEventsBestEffort(events, now, open = () => openDb(read
|
|
|
47
47
|
export {
|
|
48
48
|
recordFleetEventsBestEffort
|
|
49
49
|
};
|
|
50
|
-
//# sourceMappingURL=chunk-
|
|
50
|
+
//# sourceMappingURL=chunk-QG6OSL4M.js.map
|
|
@@ -1,12 +1,18 @@
|
|
|
1
|
+
import {
|
|
2
|
+
FLEET_RULESET_NAME,
|
|
3
|
+
desiredRuleset,
|
|
4
|
+
healRuleset,
|
|
5
|
+
rulesetGaps
|
|
6
|
+
} from "./chunk-MNDIED4M.js";
|
|
1
7
|
import {
|
|
2
8
|
templatesByName
|
|
3
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-73UFRZKY.js";
|
|
4
10
|
import {
|
|
5
11
|
readGitHubConfig
|
|
6
12
|
} from "./chunk-GASBX52O.js";
|
|
7
13
|
import {
|
|
8
14
|
makeGitHub
|
|
9
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-VSHC4HOI.js";
|
|
10
16
|
import {
|
|
11
17
|
siteLabel
|
|
12
18
|
} from "./chunk-XXTZBPUY.js";
|
|
@@ -26,7 +32,7 @@ import {
|
|
|
26
32
|
// src/recipes/self-updating/index.ts
|
|
27
33
|
import { mkdir, writeFile } from "fs/promises";
|
|
28
34
|
import { dirname, join } from "path";
|
|
29
|
-
var SELF_UPDATING_CONFIGS = ["
|
|
35
|
+
var SELF_UPDATING_CONFIGS = ["renovate-action", "renovate-config"];
|
|
30
36
|
var REQUIRED_CHECK = "ci / ci";
|
|
31
37
|
function resultOf(site, status, notes, commits = []) {
|
|
32
38
|
return { recipe: "self-updating", site: siteLabel(site), status, commits, notes };
|
|
@@ -74,9 +80,7 @@ async function selfUpdating(site, deps = {}) {
|
|
|
74
80
|
);
|
|
75
81
|
}
|
|
76
82
|
const cfg = readGitHubConfig();
|
|
77
|
-
const renovateToken = deps.renovateToken ?? cfg?.renovateToken;
|
|
78
83
|
if (!deps.github && !cfg) return resultOf(site, "failed", "GITHUB_TOKEN not set");
|
|
79
|
-
if (!renovateToken) return resultOf(site, "failed", "no RENOVATE_TOKEN available");
|
|
80
84
|
const github = deps.github ?? makeGitHub({ token: cfg.token });
|
|
81
85
|
const base = await github.defaultBranch(repo).catch(() => "main");
|
|
82
86
|
const actions = [];
|
|
@@ -109,24 +113,21 @@ async function selfUpdating(site, deps = {}) {
|
|
|
109
113
|
await mkdir(dirname(dest), { recursive: true });
|
|
110
114
|
await writeFile(dest, t.contents, "utf-8");
|
|
111
115
|
}
|
|
112
|
-
const sha = await commit(
|
|
113
|
-
site.path,
|
|
114
|
-
"ci: enable self-updating (CI + Renovate auto-merge)"
|
|
115
|
-
);
|
|
116
|
+
const sha = await commit(site.path, "ci: enable self-updating (Renovate auto-merge)");
|
|
116
117
|
if (sha) commits.push(sha);
|
|
117
118
|
await (deps.pushBranch ?? push)(site.path, maintBranch);
|
|
118
119
|
const pr = await github.openPullRequest(repo, {
|
|
119
120
|
head: maintBranch,
|
|
120
121
|
base,
|
|
121
|
-
title: "Enable self-updating (
|
|
122
|
-
body: "Adds
|
|
122
|
+
title: "Enable self-updating (Renovate)",
|
|
123
|
+
body: "Adds scheduled Renovate and Renovate-owned merges for patch/minor updates. (ci.yml is deliberately not managed here \u2014 its shape comes from the starter and its reusable-workflow pin from Renovate.)"
|
|
123
124
|
});
|
|
124
125
|
actions.push(`opened PR ${pr.url}`);
|
|
125
126
|
}
|
|
126
127
|
}
|
|
127
|
-
if (
|
|
128
|
-
await github.
|
|
129
|
-
actions.push("
|
|
128
|
+
if (await github.autoMergeEnabled(repo)) {
|
|
129
|
+
await github.disableRepoAutoMerge(repo);
|
|
130
|
+
actions.push("disabled auto-merge (platform auto-merge is not permitted fleet-wide)");
|
|
130
131
|
}
|
|
131
132
|
const existingContexts = await github.branchProtectionContexts(repo, base);
|
|
132
133
|
if (!existingContexts.includes(REQUIRED_CHECK)) {
|
|
@@ -134,9 +135,24 @@ async function selfUpdating(site, deps = {}) {
|
|
|
134
135
|
await github.protectBranch(repo, base, contexts);
|
|
135
136
|
actions.push(`required "${REQUIRED_CHECK}" check on ${base}`);
|
|
136
137
|
}
|
|
137
|
-
if (
|
|
138
|
-
await github.
|
|
139
|
-
|
|
138
|
+
if (await github.repoVisibility(repo) === "public") {
|
|
139
|
+
const check = await github.checkContextObserved(repo, base, REQUIRED_CHECK) ? REQUIRED_CHECK : null;
|
|
140
|
+
const existingRuleset = (await github.listRepoRulesets(repo)).find(
|
|
141
|
+
(r) => r.name === FLEET_RULESET_NAME
|
|
142
|
+
);
|
|
143
|
+
if (!existingRuleset) {
|
|
144
|
+
await github.createRuleset(repo, desiredRuleset(check));
|
|
145
|
+
actions.push(
|
|
146
|
+
check === null ? `created ruleset "${FLEET_RULESET_NAME}" (refs rules only \u2014 "${REQUIRED_CHECK}" not yet observed on ${base})` : `created ruleset "${FLEET_RULESET_NAME}"`
|
|
147
|
+
);
|
|
148
|
+
} else {
|
|
149
|
+
const full = await github.getRuleset(repo, existingRuleset.id);
|
|
150
|
+
const gaps = rulesetGaps(full, check);
|
|
151
|
+
if (gaps.length > 0) {
|
|
152
|
+
await github.updateRuleset(repo, existingRuleset.id, healRuleset(full, check));
|
|
153
|
+
actions.push(`healed ruleset drift: ${gaps.join("; ")}`);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
140
156
|
}
|
|
141
157
|
} catch (err) {
|
|
142
158
|
const done = actions.length ? ` (completed: ${actions.join("; ")})` : "";
|
|
@@ -159,4 +175,4 @@ async function selfUpdating(site, deps = {}) {
|
|
|
159
175
|
export {
|
|
160
176
|
selfUpdating
|
|
161
177
|
};
|
|
162
|
-
//# sourceMappingURL=chunk-
|
|
178
|
+
//# sourceMappingURL=chunk-QMXQUL5Z.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/recipes/self-updating/index.ts"],"sourcesContent":["import { mkdir, writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport type { RecipeResult, Site } from \"../../types.js\";\nimport { templatesByName } from \"../sync-configs/templates.js\";\nimport {\n getRemoteUrl,\n parseOwnerRepo,\n isOwnerRepo,\n push as gitPush,\n branchName,\n checkoutBranch,\n createBranch,\n currentBranch,\n commit as gitCommit,\n isWorkingTreeClean,\n} from \"../../util/git.js\";\nimport { siteLabel } from \"../../util/site.js\";\nimport { readGitHubConfig } from \"../../github/config.js\";\nimport { makeGitHub, type GitHub } from \"../../github/gh.js\";\nimport {\n FLEET_RULESET_NAME,\n desiredRuleset,\n healRuleset,\n rulesetGaps,\n} from \"../../github/rulesets.js\";\n\n// Deliberately NOT ci.yml: that file is per-site parameterized (netlify-site,\n// node-version, permissions), so an exact-match heal against a static template\n// would strip those values in a green auto-mergeable PR — the armed clobber\n// the 2026-08-02 architecture review found. The starter clone owns ci.yml's\n// shape; Renovate bumps its pinned reusable-workflow ref per repo (proven:\n// its github-actions manager already updates action pins on fleet sites, and\n// reddoorla/.github publishes the tags it tracks).\nconst SELF_UPDATING_CONFIGS = [\"renovate-action\", \"renovate-config\"] as const;\n\n// Reusable-workflow jobs report their check as \"<caller-job> / <reusable-job>\".\n// The thin `ci` caller (job `ci`) calls reddoorla/.github's reusable workflow (job `ci`),\n// so the required context is \"ci / ci\", NOT \"ci\". (Provisional — verified empirically on the\n// starter during M7.1 rollout; correct here if the live checks API reports a different string.)\nconst REQUIRED_CHECK = \"ci / ci\";\n\nexport type SelfUpdatingDeps = {\n github?: GitHub;\n pushBranch?: (cwd: string, branch: string) => Promise<void>;\n};\n\nfunction resultOf(\n site: Site,\n status: RecipeResult[\"status\"],\n notes: string,\n commits: string[] = [],\n): RecipeResult {\n return { recipe: \"self-updating\", site: siteLabel(site), status, commits, notes };\n}\n\n/** True when a file's current content matches the canonical template for drift\n * purposes. Normalizes line endings + trailing whitespace so a stray trailing\n * newline (or CRLF) can't read as drift and open a needless PR every nightly run;\n * any real content change still differs. */\nfunction sameConfigContents(current: string, canonical: string): boolean {\n const norm = (s: string) => s.replace(/\\r\\n/g, \"\\n\").replace(/\\s+$/, \"\");\n return norm(current) === norm(canonical);\n}\n\n/**\n * Resolve the `owner/repo` this recipe will mutate. An explicit `site.gitRepo`\n * (from Airtable) wins; otherwise derive it from the checkout's `origin`.\n *\n * Returns `null` when there is no repo to act on (no `gitRepo`, no origin) — a\n * benign \"nothing wired\" state. THROWS when a repo value IS present but doesn't\n * match the strict `owner/repo` shape: this recipe writes the broad GitHub\n * token as a repo secret (plus branch protection / auto-merge) at this\n * identity, so an attacker/typo-controlled value must be rejected here, before\n * the first `gh` call, rather than passed through to `gh`.\n */\nasync function resolveRepo(site: Site): Promise<string | null> {\n if (site.gitRepo) {\n if (!isOwnerRepo(site.gitRepo)) {\n throw new Error(\n `refusing to act on malformed repo identity: expected \"owner/repo\", got ${JSON.stringify(site.gitRepo)}`,\n );\n }\n return site.gitRepo;\n }\n let fromOrigin: string | null;\n try {\n fromOrigin = parseOwnerRepo(await getRemoteUrl(site.path));\n } catch {\n return null;\n }\n if (fromOrigin === null) return null;\n if (!isOwnerRepo(fromOrigin)) {\n throw new Error(\n `refusing to act on malformed repo identity from origin: ${JSON.stringify(fromOrigin)}`,\n );\n }\n return fromOrigin;\n}\n\nexport async function selfUpdating(site: Site, deps: SelfUpdatingDeps = {}): Promise<RecipeResult> {\n const templates = templatesByName([...SELF_UPDATING_CONFIGS]);\n\n let repo: string | null;\n try {\n repo = await resolveRepo(site);\n } catch (err) {\n // A malformed repo identity must abort before any `gh` write — surface it\n // as a recipe failure rather than letting the token reach an unintended repo.\n return resultOf(site, \"failed\", err instanceof Error ? err.message : String(err));\n }\n if (!repo) {\n return resultOf(\n site,\n \"failed\",\n \"no Git repo (set Airtable 'Git repo' or add an origin remote)\",\n );\n }\n\n const cfg = readGitHubConfig();\n if (!deps.github && !cfg) return resultOf(site, \"failed\", \"GITHUB_TOKEN not set\");\n const github = deps.github ?? makeGitHub({ token: cfg!.token });\n\n const base = await github.defaultBranch(repo).catch(() => \"main\");\n const actions: string[] = [];\n const commits: string[] = [];\n // Hoisted so the `finally` can restore the operator's branch even when a\n // failure (push/PR error) aborts AFTER we created + checked out the maint\n // branch. `maintBranch` stays null until createBranch succeeds, so the\n // restore is a no-op on every path that never left the operator's branch.\n let original: string | null = null;\n let maintBranch: string | null = null;\n\n try {\n // A. Renovate config on the default branch — compare CONTENT, not just\n // existence, so a present-but-STALE config (a pre-App workflow, a drifted\n // Renovate schedule window) is corrected rather than left silently\n // forever. The prior existence-only gate reported \"already self-updating\" for any\n // repo that merely HAD the files, however out of date — the very drift this\n // recipe exists to repair (e.g. the Renovate schedule-window regression).\n const drifted: string[] = [];\n for (const t of templates) {\n const current = await github.fileContentsOnBranch(repo, base, t.path);\n if (current === null || !sameConfigContents(current, t.contents)) drifted.push(t.path);\n }\n if (drifted.length > 0) {\n const existingPR = await github.findOpenSelfUpdatingPR(repo);\n if (existingPR) {\n actions.push(`self-updating PR already open: ${existingPR}`);\n } else {\n if (!(await isWorkingTreeClean(site.path))) {\n return resultOf(site, \"failed\", \"working tree not clean — commit or stash first\");\n }\n // Capture the operator's branch BEFORE creating the maint branch so the\n // `finally` can return them to it (#2). Best-effort capture: if it fails\n // we just skip the restore rather than guess.\n try {\n original = await currentBranch(site.path);\n } catch {\n original = null;\n }\n maintBranch = branchName(\"self-updating\");\n await createBranch(site.path, maintBranch);\n for (const t of templates) {\n const dest = join(site.path, t.path);\n await mkdir(dirname(dest), { recursive: true });\n await writeFile(dest, t.contents, \"utf-8\");\n }\n const sha = await gitCommit(site.path, \"ci: enable self-updating (Renovate auto-merge)\");\n if (sha) commits.push(sha);\n await (deps.pushBranch ?? gitPush)(site.path, maintBranch);\n const pr = await github.openPullRequest(repo, {\n head: maintBranch,\n base,\n title: \"Enable self-updating (Renovate)\",\n body: \"Adds scheduled Renovate and Renovate-owned merges for patch/minor updates. (ci.yml is deliberately not managed here — its shape comes from the starter and its reusable-workflow pin from Renovate.)\",\n });\n actions.push(`opened PR ${pr.url}`);\n // (Branch restore happens in the `finally` below — on success AND on a\n // failure that aborts after createBranch.)\n }\n }\n\n // B. Repo settings — check-then-ensure, each independent (self-healing).\n //\n // Platform auto-merge is DISABLED fleet-wide, and this block self-heals toward\n // OFF (it used to drive repos ON — do not \"fix\" it back).\n //\n // Why: GitHub's platform auto-merge is a per-PR flag that anyone with write\n // access can arm; the PR then merges itself later, unattended, once checks go\n // green. The org Renovate preset forbids auto-merging majors and was working\n // correctly — Renovate never armed them — but the preset has no authority over\n // a flag someone else set. On 2026-07-26 a bulk `gh pr merge --auto` sweep\n // armed it across 8 fleet repos, and the next morning two `actions/checkout`\n // MAJOR bumps merged with zero reviews (reddoor-starter#77,\n // reddoor-website#111) as soon as Renovate's own rebase cleared their\n // conflicts. Realized damage, not a hypothetical.\n //\n // The fix is to keep merges INSIDE Renovate's own run, where its `packageRules`\n // actually govern the decision. Renovate can only merge while it is running, so\n // the workflow cron (see sync-configs templates) is the merge cadence.\n //\n // Leaving the self-heal pointed at OFF makes this a drift ALARM: if someone\n // re-enables platform auto-merge, the next `self-updating` / `launch` run turns\n // it back off and records the action. `enableRepoAutoMerge` is retained in\n // `src/github/gh.ts` as the documented rollback path.\n if (await github.autoMergeEnabled(repo)) {\n await github.disableRepoAutoMerge(repo);\n actions.push(\"disabled auto-merge (platform auto-merge is not permitted fleet-wide)\");\n }\n const existingContexts = await github.branchProtectionContexts(repo, base);\n if (!existingContexts.includes(REQUIRED_CHECK)) {\n // protectBranch issues a full PUT that REPLACES required-status-check contexts.\n // Send the UNION of the branch's existing required contexts + our REQUIRED_CHECK\n // so we ADD the CI gate without silently dropping any other checks the repo\n // already requires. (When the branch has no protection yet, existingContexts is\n // [] and this is just [REQUIRED_CHECK] — the original behavior.) Dedupe defends\n // against REQUIRED_CHECK already appearing among the existing contexts.\n const contexts = [...new Set([...existingContexts, REQUIRED_CHECK])];\n await github.protectBranch(repo, base, contexts);\n actions.push(`required \"${REQUIRED_CHECK}\" check on ${base}`);\n }\n // Ruleset ensure — the layer that binds ADMINS. Classic protection above\n // keeps `enforce_admins: false`, which is exactly the hole the 2026-07-26\n // bulk `gh pr merge --auto` sweep walked through (two unreviewed MAJORS\n // merged). The 2026-08-01 audit then found the six NEWEST repos with no\n // ruleset at all — every hand-applied sweep regrows its gap at the next\n // onboard, so the recipe owns the invariant now. Spec + invariants:\n // docs/superpowers/specs/2026-08-02-ruleset-self-healing-design.md.\n //\n // Private repos are skipped BEFORE any attempt: rulesets there need a paid\n // plan, so trying would either fail every run or spam a phantom action\n // that flips this recipe to \"applied\" forever. Classic protection remains\n // their floor.\n if ((await github.repoVisibility(repo)) === \"public\") {\n // Evidence gate: only require \"ci / ci\" once that check-run has actually\n // been OBSERVED on the default branch. With an empty bypass list, a\n // required context that never fires would make the repo permanently\n // unmergeable by EVERYONE — e.g. a workflow_call-only ci.yml emits no\n // check runs. Unobserved ⇒ refs rules only; the check upgrades on a\n // later pass once real evidence exists.\n //\n // Residual risk, accepted: this proves the check fires on default-branch\n // PUSHES, not on pull_request events — a hand-edited push-only ci.yml\n // would pass the gate and then block every PR. ci.yml is deliberately\n // NOT healed by block A (per-site parameterized; see\n // SELF_UPDATING_CONFIGS), so this recipe cannot correct that drift —\n // the exposure is one bricked-PR repo, immediately visible on its next\n // PR. Un-brick path: edit the ruleset via API (ruleset ADMIN is not\n // ref-gated), then fix the ci.yml triggers by push.\n const check = (await github.checkContextObserved(repo, base, REQUIRED_CHECK))\n ? REQUIRED_CHECK\n : null;\n const existingRuleset = (await github.listRepoRulesets(repo)).find(\n (r) => r.name === FLEET_RULESET_NAME,\n );\n if (!existingRuleset) {\n await github.createRuleset(repo, desiredRuleset(check));\n actions.push(\n check === null\n ? `created ruleset \"${FLEET_RULESET_NAME}\" (refs rules only — \"${REQUIRED_CHECK}\" not yet observed on ${base})`\n : `created ruleset \"${FLEET_RULESET_NAME}\"`,\n );\n } else {\n const full = await github.getRuleset(repo, existingRuleset.id);\n const gaps = rulesetGaps(full, check);\n if (gaps.length > 0) {\n // PUT the healed payload (merge TOWARD the floor, never away — see\n // healRuleset). Recording the specific gaps makes this the drift\n // ALARM, same as the auto-merge-off action above.\n await github.updateRuleset(repo, existingRuleset.id, healRuleset(full, check));\n actions.push(`healed ruleset drift: ${gaps.join(\"; \")}`);\n }\n }\n }\n // (No per-repo RENOVATE_TOKEN planting anymore: Renovate authenticates as\n // the reddoor-renovate GitHub App, whose RENOVATE_APP_ID / _PRIVATE_KEY are\n // org-level with all-repos visibility — a new repo needs NOTHING set. The\n // old step was already redundant for new sites (the PAT was an org secret\n // too); existing per-repo copies are inert and left to rot harmlessly.\n // docs/runbooks/renovate-app-identity.md covers the migration + rollback.)\n } catch (err) {\n const done = actions.length ? ` (completed: ${actions.join(\"; \")})` : \"\";\n const message = err instanceof Error ? err.message : String(err);\n return resultOf(site, \"failed\", `${message}${done}`, commits);\n } finally {\n // Restore the operator's branch whenever we created + checked out a maint\n // branch — on SUCCESS and, critically, on FAILURE. Without this, a push/PR\n // error after createBranch strands the checkout on the maint branch with an\n // unpushed commit, and the retry then fails at createBranch (\"branch already\n // exists\"). Best-effort: a restore failure must not mask the real outcome.\n if (maintBranch !== null && original !== null && original !== maintBranch) {\n try {\n await checkoutBranch(site.path, original);\n } catch (err) {\n console.warn(\n `warning: could not restore branch ${original} after self-updating: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n }\n }\n\n return actions.length\n ? resultOf(site, \"applied\", actions.join(\"; \"), commits)\n : resultOf(site, \"noop\", \"already self-updating\", commits);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,OAAO,iBAAiB;AACjC,SAAS,SAAS,YAAY;AAgC9B,IAAM,wBAAwB,CAAC,mBAAmB,iBAAiB;AAMnE,IAAM,iBAAiB;AAOvB,SAAS,SACP,MACA,QACA,OACA,UAAoB,CAAC,GACP;AACd,SAAO,EAAE,QAAQ,iBAAiB,MAAM,UAAU,IAAI,GAAG,QAAQ,SAAS,MAAM;AAClF;AAMA,SAAS,mBAAmB,SAAiB,WAA4B;AACvE,QAAM,OAAO,CAAC,MAAc,EAAE,QAAQ,SAAS,IAAI,EAAE,QAAQ,QAAQ,EAAE;AACvE,SA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IAAI,OAAO;AAAA,EAC9D,UAAE;AAMA,QAAI,gBAAgB,QAAQ,aAAa,QAAQ,aAAa,aAAa;AACzE,UAAI;AACF,cAAM,eAAe,KAAK,MAAM,QAAQ;AAAA,MAC1C,SAAS,KAAK;AACZ,gBAAQ;AAAA,UACN,qCAAqC,QAAQ,yBAC3C,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CACjD;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO,QAAQ,SACX,SAAS,MAAM,WAAW,QAAQ,KAAK,IAAI,GAAG,OAAO,IACrD,SAAS,MAAM,QAAQ,yBAAyB,OAAO;AAC7D;","names":[]}
|
|
@@ -3,6 +3,9 @@ import {
|
|
|
3
3
|
} from "./chunk-HVOOCK6L.js";
|
|
4
4
|
|
|
5
5
|
// src/github/gh.ts
|
|
6
|
+
import { mkdtemp, rm, writeFile } from "fs/promises";
|
|
7
|
+
import { tmpdir } from "os";
|
|
8
|
+
import { join } from "path";
|
|
6
9
|
function assertUrlSegment(kind, value) {
|
|
7
10
|
const structural = /[\s?#%\\]|\.\./;
|
|
8
11
|
if (value.length === 0 || value.startsWith("/") || structural.test(value)) {
|
|
@@ -36,6 +39,16 @@ function makeGitHub(deps) {
|
|
|
36
39
|
if (r.code !== 0) throw new Error(`gh ${args[0]} failed (code ${r.code}): ${r.stderr.trim()}`);
|
|
37
40
|
return r.stdout;
|
|
38
41
|
}
|
|
42
|
+
async function ghJson(method, path, body) {
|
|
43
|
+
const dir = await mkdtemp(join(tmpdir(), "gh-json-"));
|
|
44
|
+
const file = join(dir, "body.json");
|
|
45
|
+
try {
|
|
46
|
+
await writeFile(file, JSON.stringify(body), "utf-8");
|
|
47
|
+
return await gh(["api", "-X", method, path, "--input", file]);
|
|
48
|
+
} finally {
|
|
49
|
+
await rm(dir, { recursive: true, force: true });
|
|
50
|
+
}
|
|
51
|
+
}
|
|
39
52
|
return {
|
|
40
53
|
async openPullRequest(repo, pr) {
|
|
41
54
|
const out = await gh([
|
|
@@ -57,6 +70,9 @@ function makeGitHub(deps) {
|
|
|
57
70
|
async enableRepoAutoMerge(repo) {
|
|
58
71
|
await gh(["api", "-X", "PATCH", `repos/${repo}`, "-F", "allow_auto_merge=true"]);
|
|
59
72
|
},
|
|
73
|
+
async disableRepoAutoMerge(repo) {
|
|
74
|
+
await gh(["api", "-X", "PATCH", `repos/${repo}`, "-F", "allow_auto_merge=false"]);
|
|
75
|
+
},
|
|
60
76
|
async protectBranch(repo, branch, requiredChecks) {
|
|
61
77
|
assertUrlSegment("branch", branch);
|
|
62
78
|
const args = [
|
|
@@ -247,6 +263,85 @@ function makeGitHub(deps) {
|
|
|
247
263
|
"-f",
|
|
248
264
|
`ref=${ref}`
|
|
249
265
|
]);
|
|
266
|
+
},
|
|
267
|
+
async listRepoRulesets(repo) {
|
|
268
|
+
const out = await gh([
|
|
269
|
+
"api",
|
|
270
|
+
`repos/${repo}/rulesets?per_page=100&includes_parents=false`,
|
|
271
|
+
"--jq",
|
|
272
|
+
'.[] | "\\(.id)\\t\\(.name)"'
|
|
273
|
+
]);
|
|
274
|
+
return out.split("\n").map((l) => l.trim()).filter((l) => l.includes(" ")).map((l) => {
|
|
275
|
+
const tab = l.indexOf(" ");
|
|
276
|
+
return { id: Number(l.slice(0, tab)), name: l.slice(tab + 1) };
|
|
277
|
+
}).filter((r) => Number.isSafeInteger(r.id));
|
|
278
|
+
},
|
|
279
|
+
async getRuleset(repo, id) {
|
|
280
|
+
const out = await gh(["api", `repos/${repo}/rulesets/${Math.trunc(id)}`]);
|
|
281
|
+
return JSON.parse(out);
|
|
282
|
+
},
|
|
283
|
+
async createRuleset(repo, payload) {
|
|
284
|
+
await ghJson("POST", `repos/${repo}/rulesets`, payload);
|
|
285
|
+
},
|
|
286
|
+
async updateRuleset(repo, id, payload) {
|
|
287
|
+
await ghJson("PUT", `repos/${repo}/rulesets/${Math.trunc(id)}`, payload);
|
|
288
|
+
},
|
|
289
|
+
async checkContextObserved(repo, ref, context) {
|
|
290
|
+
assertUrlSegment("branch", ref);
|
|
291
|
+
const r = await spawn(
|
|
292
|
+
"gh",
|
|
293
|
+
[
|
|
294
|
+
"api",
|
|
295
|
+
`repos/${repo}/commits/${ref}/check-runs?per_page=100`,
|
|
296
|
+
"--jq",
|
|
297
|
+
".check_runs[].name"
|
|
298
|
+
],
|
|
299
|
+
{ env, timeoutMs: 6e4 }
|
|
300
|
+
);
|
|
301
|
+
if (r.code !== 0) return false;
|
|
302
|
+
return r.stdout.split("\n").map((l) => l.trim()).includes(context);
|
|
303
|
+
},
|
|
304
|
+
async repoVisibility(repo) {
|
|
305
|
+
const out = await gh(["api", `repos/${repo}`, "--jq", ".visibility"]);
|
|
306
|
+
return out.trim();
|
|
307
|
+
},
|
|
308
|
+
async listOrgRepos(org) {
|
|
309
|
+
assertUrlSegment("path", org);
|
|
310
|
+
const out = await gh([
|
|
311
|
+
"api",
|
|
312
|
+
"--paginate",
|
|
313
|
+
`orgs/${org}/repos?per_page=100`,
|
|
314
|
+
"--jq",
|
|
315
|
+
'.[] | "\\(.name)\\t\\(.visibility)\\t\\(.archived)\\t\\(.security_and_analysis.secret_scanning.status // "unavailable")\\t\\(.security_and_analysis.secret_scanning_push_protection.status // "unavailable")"'
|
|
316
|
+
]);
|
|
317
|
+
return out.split("\n").map((l) => l.trim()).filter((l) => l.length > 0).map((l) => {
|
|
318
|
+
const [name = "", visibility = "", archived = "", ss = "", pp = ""] = l.split(" ");
|
|
319
|
+
return {
|
|
320
|
+
name,
|
|
321
|
+
visibility,
|
|
322
|
+
archived: archived === "true",
|
|
323
|
+
secretScanning: ss || "unavailable",
|
|
324
|
+
pushProtection: pp || "unavailable"
|
|
325
|
+
};
|
|
326
|
+
});
|
|
327
|
+
},
|
|
328
|
+
async workflowHealth(repo, filename) {
|
|
329
|
+
const wf = await spawn(
|
|
330
|
+
"gh",
|
|
331
|
+
["api", `repos/${repo}/actions/workflows/${filename}`, "--jq", ".state"],
|
|
332
|
+
{ env, timeoutMs: 6e4 }
|
|
333
|
+
);
|
|
334
|
+
if (wf.code !== 0) {
|
|
335
|
+
if (/HTTP 404/.test(wf.stderr)) return { present: false };
|
|
336
|
+
throw new Error(`workflowHealth(${repo}/${filename}) failed: ${wf.stderr.trim()}`);
|
|
337
|
+
}
|
|
338
|
+
const runs = await gh([
|
|
339
|
+
"api",
|
|
340
|
+
`repos/${repo}/actions/workflows/${filename}/runs?status=success&per_page=1`,
|
|
341
|
+
"--jq",
|
|
342
|
+
'.workflow_runs[0].created_at // ""'
|
|
343
|
+
]);
|
|
344
|
+
return { present: true, state: wf.stdout.trim(), lastSuccessAt: runs.trim() || null };
|
|
250
345
|
}
|
|
251
346
|
};
|
|
252
347
|
}
|
|
@@ -255,4 +350,4 @@ export {
|
|
|
255
350
|
assertUrlSegment,
|
|
256
351
|
makeGitHub
|
|
257
352
|
};
|
|
258
|
-
//# sourceMappingURL=chunk-
|
|
353
|
+
//# sourceMappingURL=chunk-VSHC4HOI.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/github/gh.ts"],"sourcesContent":["import { mkdtemp, rm, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { defaultSpawn, type SpawnFn } from \"../audits/util/spawn.js\";\nimport type { ExistingRuleset, RulesetPayload } from \"./rulesets.js\";\n\n/** Aggregate CI state of a PR's head commit, normalized from GitHub's rollup. */\nexport type CiState = \"passing\" | \"failing\" | \"pending\" | \"none\";\n\n/** GitHub's computed mergeability of a PR. `UNKNOWN` is transient — GitHub is\n * still computing it (e.g. right after a push) — so it should be read as \"not\n * known to conflict\", never as conflicting. */\nexport type PrMergeable = \"MERGEABLE\" | \"CONFLICTING\" | \"UNKNOWN\";\n\n/** A minimal open-PR summary with its head-commit CI rollup state + mergeability. */\nexport type PullRequestSummary = {\n number: number;\n title: string;\n url: string;\n headRef: string;\n ciState: CiState;\n mergeable: PrMergeable;\n};\n\n/**\n * Reject a value before it's interpolated into a `gh api` URL path. The\n * `owner/repo` split methods already validate shape; this is the defense-in-depth\n * guard for the `branch` and file-`path` segments. An unexpected value (`..`, a\n * leading `/`, whitespace, or a URL-structural char like `?#%` or a backslash)\n * could otherwise retarget the endpoint (escape the intended path, smuggle a\n * query string, or traverse). Conservative by design — legit branch names like\n * `maint/self-updating-x` and paths like `.github/workflows/ci.yml` pass.\n *\n * Both branch refs (`maint/self-updating-x`) and file paths\n * (`.github/workflows/ci.yml`) legitimately contain `/`, so a single slash is\n * allowed; what's rejected is `..`, a leading `/`, whitespace, or a\n * URL-structural char (`?`, `#`, `%`, backslash) that could escape or retarget\n * the endpoint.\n */\nexport function assertUrlSegment(kind: \"branch\" | \"path\", value: string): void {\n const structural = /[\\s?#%\\\\]|\\.\\./;\n if (value.length === 0 || value.startsWith(\"/\") || structural.test(value)) {\n throw new Error(\n `unsafe ${kind} for gh api path (illegal characters or traversal): ${JSON.stringify(value)}`,\n );\n }\n}\n\n/** Map GitHub's `statusCheckRollup.state` enum to our normalized CiState. */\nfunction mapRollupState(state: string | null | undefined): CiState {\n switch (state) {\n case \"SUCCESS\":\n return \"passing\";\n case \"FAILURE\":\n case \"ERROR\":\n return \"failing\";\n case \"PENDING\":\n case \"EXPECTED\":\n return \"pending\";\n default:\n return \"none\"; // null/undefined = no checks reported\n }\n}\n\n/** Coerce GitHub's `mergeable` enum to our PrMergeable. Anything unexpected\n * (including the literal `UNKNOWN` GitHub returns while still computing) maps to\n * `UNKNOWN` — i.e. \"not known to conflict\". Only an explicit `CONFLICTING` is. */\nfunction mapMergeable(state: string | null | undefined): PrMergeable {\n return state === \"MERGEABLE\" || state === \"CONFLICTING\" ? state : \"UNKNOWN\";\n}\n\nexport type GitHub = {\n openPullRequest: (\n repo: string,\n pr: { head: string; base: string; title: string; body: string },\n ) => Promise<{ url: string }>;\n /** Turn GitHub's platform auto-merge ON for a repo. Retained as the documented\n * ROLLBACK path — the fleet drives repos to auto-merge OFF (see\n * {@link disableRepoAutoMerge} and `recipes/self-updating`). */\n enableRepoAutoMerge: (repo: string) => Promise<void>;\n /** Turn GitHub's platform auto-merge OFF for a repo. This is the fleet default:\n * platform auto-merge is a per-PR flag anyone with write access can arm, and it\n * merges unattended outside Renovate's `packageRules`. Renovate merges from\n * inside its own run instead. */\n disableRepoAutoMerge: (repo: string) => Promise<void>;\n protectBranch: (repo: string, branch: string, requiredChecks: string[]) => Promise<void>;\n setRepoSecret: (repo: string, name: string, value: string) => Promise<void>;\n repoExists: (repo: string) => Promise<boolean>;\n defaultBranch: (repo: string) => Promise<string>;\n filesOnBranch: (repo: string, branch: string, paths: string[]) => Promise<string[]>;\n /** The raw contents of `path` on `branch`, or null when the file is absent (404).\n * Lets a caller detect a present-but-STALE file (content drift), where\n * `filesOnBranch` only sees existence. */\n fileContentsOnBranch: (repo: string, branch: string, path: string) => Promise<string | null>;\n branchProtectionContexts: (repo: string, branch: string) => Promise<string[]>;\n secretExists: (repo: string, name: string) => Promise<boolean>;\n autoMergeEnabled: (repo: string) => Promise<boolean>;\n findOpenSelfUpdatingPR: (repo: string) => Promise<string | null>;\n /** All open PRs on a repo with each head commit's normalized CI rollup state. */\n openPullRequests: (repo: string) => Promise<PullRequestSummary[]>;\n /** The default branch's latest-commit date + normalized CI rollup, one query. */\n defaultBranchStatus: (repo: string) => Promise<{ ciState: CiState; lastCommitAt: string | null }>;\n /** Renovate PRs (head `renovate/*`) merged at/after `sinceIso`. Used to record\n * `pr_automerged` fleet events. gh-shell (Actions only). */\n mergedRenovatePullRequests: (\n repo: string,\n sinceIso: string,\n ) => Promise<Array<{ number: number; title: string; url: string; mergedAt: string }>>;\n /** Fire a `workflow_dispatch` for `<workflow>` (a filename like `renovate.yml`)\n * on `ref`. Requires the token's `actions:write` scope; a 404 (no such\n * workflow) or 403 (missing scope) surfaces as a thrown error. */\n dispatchWorkflow: (repo: string, workflow: string, ref: string) => Promise<void>;\n /** REPO-sourced rulesets only (`includes_parents=false`): org-level rulesets\n * aren't ours to manage (and don't exist on the Free plan). */\n listRepoRulesets: (repo: string) => Promise<Array<{ id: number; name: string }>>;\n getRuleset: (repo: string, id: number) => Promise<ExistingRuleset>;\n createRuleset: (repo: string, payload: RulesetPayload) => Promise<void>;\n /** The update verb is PUT — `PATCH repos/{repo}/rulesets/{id}` returns 404\n * (verified live 2026-08-01), so a PATCH-based update would silently no-op\n * on every drifted repo while the recipe reported success. */\n updateRuleset: (repo: string, id: number, payload: RulesetPayload) => Promise<void>;\n /** True iff a check-run named `context` exists on `ref`'s HEAD commit. The\n * evidence gate for requiring a status check: with an empty bypass list, a\n * required context that never fires makes the repo permanently unmergeable\n * by everyone — so a context must be OBSERVED before it is required.\n * False-negatives (fresh repo, API hiccup) safely degrade to \"don't require\n * yet\"; false-positives are impossible (we name-match real runs). */\n checkContextObserved: (repo: string, ref: string, context: string) => Promise<boolean>;\n /** \"public\" | \"private\" (| \"internal\" on GHEC). Rulesets on private repos\n * need a paid plan, so callers gate on this rather than attempting. */\n repoVisibility: (repo: string) => Promise<string>;\n /** Every repo in the org (paginated) — the anti-hand-typed-list enumerator.\n * Sweeps driven by a hand-maintained or Airtable-scoped list have already\n * produced two false \"all clear\"s; enumerate from the API instead.\n * secretScanning/pushProtection come from the same listing (no extra call);\n * \"unavailable\" means the token couldn't read security_and_analysis (needs\n * admin/security read) — callers must treat that as unverified, not fine. */\n listOrgRepos: (org: string) => Promise<\n Array<{\n name: string;\n visibility: string;\n archived: boolean;\n secretScanning: string;\n pushProtection: string;\n }>\n >;\n /** Liveness of one workflow file: registered? state? when did it last\n * SUCCEED? Success, not mere existence of a run: a dead credential or\n * broken config still CREATES a run on every cron tick that fails in\n * seconds, keeping created_at perpetually fresh — counting those as alive\n * is exactly the silent-stop blindness this probe exists to catch.\n * A clean 404 is the answer `{present: false}` — any OTHER failure throws,\n * because \"couldn't check\" must never read as \"healthy\" downstream. */\n workflowHealth: (repo: string, filename: string) => Promise<WorkflowHealth>;\n};\n\nexport type WorkflowHealth =\n { present: false } | { present: true; state: string; lastSuccessAt: string | null };\n\nexport function makeGitHub(deps: { token: string; spawn?: SpawnFn }): GitHub {\n const spawn = deps.spawn ?? defaultSpawn;\n const env = { ...process.env, GH_TOKEN: deps.token };\n\n async function gh(args: string[]): Promise<string> {\n const r = await spawn(\"gh\", args, { env, timeoutMs: 60_000 });\n if (r.code !== 0) throw new Error(`gh ${args[0]} failed (code ${r.code}): ${r.stderr.trim()}`);\n return r.stdout;\n }\n\n /** `gh api` with a JSON request body. Ruleset payloads have nested arrays/\n * objects that `-f`/`-F` field flags cannot express, and the spawn wrapper\n * has no stdin — so the body rides a private temp file via `--input`. */\n async function ghJson(method: \"POST\" | \"PUT\", path: string, body: unknown): Promise<string> {\n const dir = await mkdtemp(join(tmpdir(), \"gh-json-\"));\n const file = join(dir, \"body.json\");\n try {\n await writeFile(file, JSON.stringify(body), \"utf-8\");\n return await gh([\"api\", \"-X\", method, path, \"--input\", file]);\n } finally {\n await rm(dir, { recursive: true, force: true });\n }\n }\n\n return {\n async openPullRequest(repo, pr) {\n const out = await gh([\n \"pr\",\n \"create\",\n \"--repo\",\n repo,\n \"--head\",\n pr.head,\n \"--base\",\n pr.base,\n \"--title\",\n pr.title,\n \"--body\",\n pr.body,\n ]);\n return { url: out.trim() };\n },\n async enableRepoAutoMerge(repo) {\n await gh([\"api\", \"-X\", \"PATCH\", `repos/${repo}`, \"-F\", \"allow_auto_merge=true\"]);\n },\n async disableRepoAutoMerge(repo) {\n await gh([\"api\", \"-X\", \"PATCH\", `repos/${repo}`, \"-F\", \"allow_auto_merge=false\"]);\n },\n async protectBranch(repo, branch, requiredChecks) {\n assertUrlSegment(\"branch\", branch);\n const args = [\n \"api\",\n \"-X\",\n \"PUT\",\n `repos/${repo}/branches/${branch}/protection`,\n \"-H\",\n \"Accept: application/vnd.github+json\",\n \"-F\",\n \"required_status_checks[strict]=true\",\n ...requiredChecks.flatMap((c) => [\"-f\", `required_status_checks[contexts][]=${c}`]),\n \"-F\",\n \"enforce_admins=true\",\n \"-F\",\n \"required_pull_request_reviews=null\",\n \"-F\",\n \"restrictions=null\",\n ];\n await gh(args);\n },\n async setRepoSecret(repo, name, value) {\n await gh([\"secret\", \"set\", name, \"--repo\", repo, \"--body\", value]);\n },\n async repoExists(repo) {\n const r = await spawn(\"gh\", [\"api\", `repos/${repo}`], { env, timeoutMs: 60_000 });\n return r.code === 0;\n },\n async defaultBranch(repo) {\n const out = await gh([\"api\", `repos/${repo}`, \"--jq\", \".default_branch\"]);\n return out.trim();\n },\n // filesOnBranch and branchProtectionContexts call `spawn` directly (not the\n // throwing `gh()` helper) because a 404 is an expected, meaningful answer —\n // \"file/protection absent\" — not an error. The remaining readers use `gh()`\n // since a non-200 there is a genuine failure (e.g. missing token scope).\n async filesOnBranch(repo, branch, paths) {\n assertUrlSegment(\"branch\", branch);\n const present: string[] = [];\n for (const p of paths) {\n assertUrlSegment(\"path\", p);\n const r = await spawn(\"gh\", [`api`, `repos/${repo}/contents/${p}?ref=${branch}`], {\n env,\n timeoutMs: 60_000,\n });\n if (r.code === 0) present.push(p);\n }\n return present;\n },\n async fileContentsOnBranch(repo, branch, path) {\n // Same spawn-directly rationale as filesOnBranch: a 404 (file absent) is an\n // expected answer (null), not an error. The `raw` media type returns the file\n // bytes verbatim (no base64 envelope) so the result compares directly against a\n // canonical template.\n assertUrlSegment(\"branch\", branch);\n assertUrlSegment(\"path\", path);\n const r = await spawn(\n \"gh\",\n [\n \"api\",\n `repos/${repo}/contents/${path}?ref=${branch}`,\n \"-H\",\n \"Accept: application/vnd.github.raw\",\n ],\n { env, timeoutMs: 60_000 },\n );\n if (r.code !== 0) return null; // 404 = file absent on this branch\n return r.stdout;\n },\n async branchProtectionContexts(repo, branch) {\n assertUrlSegment(\"branch\", branch);\n const r = await spawn(\n \"gh\",\n [\n \"api\",\n `repos/${repo}/branches/${branch}/protection`,\n \"--jq\",\n \".required_status_checks.contexts[]?\",\n ],\n { env, timeoutMs: 60_000 },\n );\n if (r.code !== 0) return []; // 404 = no protection configured\n return r.stdout\n .split(\"\\n\")\n .map((l) => l.trim())\n .filter((l) => l.length > 0);\n },\n async secretExists(repo, name) {\n // per_page=100: the REST default of 30 would false-negative on a repo with >30 secrets,\n // wrongly reporting an existing secret absent (→ a needless overwrite).\n const out = await gh([\n \"api\",\n `repos/${repo}/actions/secrets?per_page=100`,\n \"--jq\",\n \".secrets[].name\",\n ]);\n return out\n .split(\"\\n\")\n .map((l) => l.trim())\n .includes(name);\n },\n async autoMergeEnabled(repo) {\n const out = await gh([\"api\", `repos/${repo}`, \"--jq\", \".allow_auto_merge\"]);\n return out.trim() === \"true\";\n },\n async findOpenSelfUpdatingPR(repo) {\n // per_page=100: with the REST default of 30, a repo with >30 open PRs (plausible under\n // Renovate) could page past the existing self-updating PR and open a duplicate.\n const out = await gh([\n \"api\",\n `repos/${repo}/pulls?state=open&per_page=100`,\n \"--jq\",\n '.[] | select(.head.ref | startswith(\"maint/self-updating-\")) | .html_url',\n ]);\n const first = out\n .split(\"\\n\")\n .map((l) => l.trim())\n .find((l) => l.length > 0);\n return first ?? null;\n },\n async openPullRequests(repo) {\n const [owner, name, ...rest] = repo.split(\"/\");\n if (!owner || !name || rest.length > 0) {\n throw new Error(`openPullRequests: expected \"owner/repo\", got \"${repo}\"`);\n }\n const query =\n \"query($owner:String!,$name:String!){repository(owner:$owner,name:$name){\" +\n \"pullRequests(states:OPEN,first:100,orderBy:{field:CREATED_AT,direction:DESC}){nodes{number title url headRefName mergeable \" +\n \"commits(last:1){nodes{commit{statusCheckRollup{state}}}}}}}}\";\n const out = await gh([\n \"api\",\n \"graphql\",\n \"-f\",\n `query=${query}`,\n \"-F\",\n `owner=${owner}`,\n \"-F\",\n `name=${name}`,\n ]);\n const parsed = JSON.parse(out) as {\n data?: {\n repository?: {\n pullRequests?: {\n nodes?: Array<{\n number: number;\n title: string;\n url: string;\n headRefName: string;\n mergeable?: string;\n commits?: {\n nodes?: Array<{ commit?: { statusCheckRollup?: { state?: string } } }>;\n };\n }>;\n };\n };\n };\n };\n const nodes = parsed.data?.repository?.pullRequests?.nodes ?? [];\n return nodes.map((n) => ({\n number: n.number,\n title: n.title,\n url: n.url,\n headRef: n.headRefName,\n ciState: mapRollupState(n.commits?.nodes?.[0]?.commit?.statusCheckRollup?.state),\n mergeable: mapMergeable(n.mergeable),\n }));\n },\n async defaultBranchStatus(repo) {\n const [owner, name, ...rest] = repo.split(\"/\");\n if (!owner || !name || rest.length > 0) {\n throw new Error(`defaultBranchStatus: expected \"owner/repo\", got \"${repo}\"`);\n }\n const query =\n \"query($owner:String!,$name:String!){repository(owner:$owner,name:$name){\" +\n \"defaultBranchRef{target{... on Commit{committedDate statusCheckRollup{state}}}}}}\";\n const out = await gh([\n \"api\",\n \"graphql\",\n \"-f\",\n `query=${query}`,\n \"-F\",\n `owner=${owner}`,\n \"-F\",\n `name=${name}`,\n ]);\n const parsed = JSON.parse(out) as {\n data?: {\n repository?: {\n defaultBranchRef?: {\n target?: { committedDate?: string; statusCheckRollup?: { state?: string } | null };\n } | null;\n };\n };\n };\n const target = parsed.data?.repository?.defaultBranchRef?.target;\n return {\n ciState: mapRollupState(target?.statusCheckRollup?.state),\n lastCommitAt: target?.committedDate ?? null,\n };\n },\n async mergedRenovatePullRequests(repo, sinceIso) {\n const [owner, name, ...rest] = repo.split(\"/\");\n if (!owner || !name || rest.length > 0) {\n throw new Error(`mergedRenovatePullRequests: expected \"owner/repo\", got \"${repo}\"`);\n }\n // per_page=50: comfortably covers a week of Renovate merges on one repo. The\n // list endpoint returns merged_at + head.ref, so the filter is local.\n const out = await gh([\n \"api\",\n `repos/${owner}/${name}/pulls?state=closed&sort=updated&direction=desc&per_page=50`,\n ]);\n const arr = JSON.parse(out) as Array<{\n number: number;\n title: string;\n html_url: string;\n merged_at: string | null;\n head?: { ref?: string };\n }>;\n return arr\n .filter(\n (p) =>\n p.merged_at !== null &&\n p.merged_at >= sinceIso && // ISO8601 UTC strings sort lexicographically\n (p.head?.ref ?? \"\").startsWith(\"renovate/\"),\n )\n .map((p) => ({\n number: p.number,\n title: p.title,\n url: p.html_url,\n mergedAt: p.merged_at as string,\n }));\n },\n async dispatchWorkflow(repo, workflow, ref) {\n const [owner, name, ...rest] = repo.split(\"/\");\n if (!owner || !name || rest.length > 0) {\n throw new Error(`dispatchWorkflow: expected \"owner/repo\", got \"${repo}\"`);\n }\n // Every segment interpolates into the API path, so guard them all like the\n // other write methods do (defense in depth). `owner`/`name` are the most\n // operator-controlled (typed into Airtable's \"Git repo\"); `workflow` is a\n // constant today; `ref` is repo-sourced. A junk value like `repo?x=1` would\n // otherwise smuggle a query string past the bare two-part shape check.\n assertUrlSegment(\"path\", owner);\n assertUrlSegment(\"path\", name);\n assertUrlSegment(\"path\", workflow);\n assertUrlSegment(\"branch\", ref);\n await gh([\n \"api\",\n \"-X\",\n \"POST\",\n `repos/${owner}/${name}/actions/workflows/${workflow}/dispatches`,\n \"-f\",\n `ref=${ref}`,\n ]);\n },\n async listRepoRulesets(repo) {\n // includes_parents=false: only rulesets SOURCED on this repo are ours to\n // heal; an org-level ruleset (paid plans) must never be PUT from here.\n const out = await gh([\n \"api\",\n `repos/${repo}/rulesets?per_page=100&includes_parents=false`,\n \"--jq\",\n '.[] | \"\\\\(.id)\\\\t\\\\(.name)\"',\n ]);\n return out\n .split(\"\\n\")\n .map((l) => l.trim())\n .filter((l) => l.includes(\"\\t\")) // a tab-less line has no id/name split — never fabricate a NaN row from it\n .map((l) => {\n const tab = l.indexOf(\"\\t\");\n return { id: Number(l.slice(0, tab)), name: l.slice(tab + 1) };\n })\n .filter((r) => Number.isSafeInteger(r.id));\n },\n async getRuleset(repo, id) {\n const out = await gh([\"api\", `repos/${repo}/rulesets/${Math.trunc(id)}`]);\n return JSON.parse(out) as ExistingRuleset;\n },\n async createRuleset(repo, payload) {\n await ghJson(\"POST\", `repos/${repo}/rulesets`, payload);\n },\n async updateRuleset(repo, id, payload) {\n // PUT, not PATCH: PATCH on this endpoint 404s (verified live 2026-08-01),\n // which a naive implementation would surface as \"update failed\" at best —\n // or, with a lenient error path, as a silent no-op reported as healed.\n await ghJson(\"PUT\", `repos/${repo}/rulesets/${Math.trunc(id)}`, payload);\n },\n async checkContextObserved(repo, ref, context) {\n assertUrlSegment(\"branch\", ref);\n // spawn-direct (not the throwing gh()): a 404/409 — empty repo, no commits\n // on the ref yet — is an expected answer meaning \"no evidence\", not an\n // error. Any failure degrades to false, i.e. \"don't require the check\n // yet\", which is the safe direction (see checkContextObserved's contract).\n const r = await spawn(\n \"gh\",\n [\n \"api\",\n `repos/${repo}/commits/${ref}/check-runs?per_page=100`,\n \"--jq\",\n \".check_runs[].name\",\n ],\n { env, timeoutMs: 60_000 },\n );\n if (r.code !== 0) return false;\n return r.stdout\n .split(\"\\n\")\n .map((l) => l.trim())\n .includes(context);\n },\n async repoVisibility(repo) {\n const out = await gh([\"api\", `repos/${repo}`, \"--jq\", \".visibility\"]);\n return out.trim();\n },\n async listOrgRepos(org) {\n assertUrlSegment(\"path\", org);\n // --paginate: the org is >27 repos and the default page of 30 is exactly\n // the trap that produced the 2026-07-31 false \"queue is empty\".\n const out = await gh([\n \"api\",\n \"--paginate\",\n `orgs/${org}/repos?per_page=100`,\n \"--jq\",\n '.[] | \"\\\\(.name)\\\\t\\\\(.visibility)\\\\t\\\\(.archived)\\\\t\\\\(.security_and_analysis.secret_scanning.status // \"unavailable\")\\\\t\\\\(.security_and_analysis.secret_scanning_push_protection.status // \"unavailable\")\"',\n ]);\n return out\n .split(\"\\n\")\n .map((l) => l.trim())\n .filter((l) => l.length > 0)\n .map((l) => {\n const [name = \"\", visibility = \"\", archived = \"\", ss = \"\", pp = \"\"] = l.split(\"\\t\");\n return {\n name,\n visibility,\n archived: archived === \"true\",\n secretScanning: ss || \"unavailable\",\n pushProtection: pp || \"unavailable\",\n };\n });\n },\n async workflowHealth(repo, filename) {\n // spawn-direct for the workflow GET: 404 (file not registered as a\n // workflow) is an expected ANSWER, not an error. Everything else throws —\n // per the contract, an unreadable workflow must surface as unverified.\n const wf = await spawn(\n \"gh\",\n [\"api\", `repos/${repo}/actions/workflows/${filename}`, \"--jq\", \".state\"],\n { env, timeoutMs: 60_000 },\n );\n if (wf.code !== 0) {\n if (/HTTP 404/.test(wf.stderr)) return { present: false };\n throw new Error(`workflowHealth(${repo}/${filename}) failed: ${wf.stderr.trim()}`);\n }\n // status=success: filter to runs that actually CONCLUDED success. Without\n // it, a schedule whose every run fails (revoked App key, broken config)\n // reads as hours-fresh forever while zero updates flow.\n const runs = await gh([\n \"api\",\n `repos/${repo}/actions/workflows/${filename}/runs?status=success&per_page=1`,\n \"--jq\",\n '.workflow_runs[0].created_at // \"\"',\n ]);\n return { present: true, state: wf.stdout.trim(), lastSuccessAt: runs.trim() || null };\n },\n };\n}\n"],"mappings":";;;;;AAAA,SAAS,SAAS,IAAI,iBAAiB;AACvC,SAAS,cAAc;AACvB,SAAS,YAAY;AAqCd,SAAS,iBAAiB,MAAyB,OAAqB;AAC7E,QAAM,aAAa;AACnB,MAAI,MAAM,WAAW,KAAK,MAAM,WAAW,GAAG,KAAK,WAAW,KAAK,KAAK,GAAG;AACzE,UAAM,IAAI;AAAA,MACR,UAAU,IAAI,uDAAuD,KAAK,UAAU,KAAK,CAAC;AAAA,IAC5F;AAAA,EACF;AACF;AAGA,SAAS,eAAe,OAA2C;AACjE,UAAQ,OAAO;AAAA,IACb,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,IACT;AACE,aAAO;AAAA,EACX;AACF;AAKA,SAAS,aAAa,OAA+C;AACnE,SAAO,UAAU,eAAe,UAAU,gBAAgB,QAAQ;AACpE;AA0FO,SAAS,WAAW,MAAkD;AAC3E,QAAM,QAAQ,KAAK,SAAS;AAC5B,QAAM,MAAM,EAAE,GAAG,QAAQ,KAAK,UAAU,KAAK,MAAM;AAEnD,iBAAe,GAAG,MAAiC;A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,cAAM,IAAI,MAAM,kBAAkB,IAAI,IAAI,QAAQ,aAAa,GAAG,OAAO,KAAK,CAAC,EAAE;AAAA,MACnF;AAIA,YAAM,OAAO,MAAM,GAAG;AAAA,QACpB;AAAA,QACA,SAAS,IAAI,sBAAsB,QAAQ;AAAA,QAC3C;AAAA,QACA;AAAA,MACF,CAAC;AACD,aAAO,EAAE,SAAS,MAAM,OAAO,GAAG,OAAO,KAAK,GAAG,eAAe,KAAK,KAAK,KAAK,KAAK;AAAA,IACtF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
import {
|
|
6
6
|
isProbablyEmail,
|
|
7
7
|
parseAddresses
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-FVVGDIGX.js";
|
|
9
9
|
import {
|
|
10
10
|
gatingHealth,
|
|
11
11
|
isSendOverridden,
|
|
@@ -339,4 +339,4 @@ export {
|
|
|
339
339
|
preflight,
|
|
340
340
|
approveBlockers
|
|
341
341
|
};
|
|
342
|
-
//# sourceMappingURL=chunk-
|
|
342
|
+
//# sourceMappingURL=chunk-YIQ7IWE3.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/recipes/_with-recipe.ts"],"sourcesContent":["import type { RecipeName, RecipeResult, Site } from \"../types.js\";\nimport {\n branchName,\n checkoutBranch,\n commit as gitCommit,\n createBranch,\n currentBranch,\n deleteBranch,\n forceCheckoutBranch,\n isWorkingTreeClean,\n} from \"../util/git.js\";\nimport { siteLabel } from \"../util/site.js\";\n\n/** Outcome of the read-only planning phase. `noop` and `failed` short-circuit\n * without creating a branch; `apply` carries the recipe-specific plan data\n * forward to the apply phase. */\nexport type RecipePlan<P> =\n { kind: \"noop\"; notes?: string } | { kind: \"failed\"; notes: string } | { kind: \"apply\"; plan: P };\n\nexport type RecipeApplyCtx = {\n /** Stage all current changes and commit. Returns the SHA, or null if\n * nothing was staged. The wrapper accumulates SHAs into the final\n * RecipeResult. */\n commit: (message: string) => Promise<string | null>;\n /** Branch name that was created for this run. */\n branch: string;\n /** Site path — same as `site.path`. */\n cwd: string;\n};\n\nexport type RecipeApplyResult = { kind: \"ok\"; notes?: string } | { kind: \"failed\"; notes: string };\n\nexport type RecipeBody<P> = {\n name: RecipeName;\n site: Site;\n /** Inspect the site and decide: noop, failed, or proceed (with plan data\n * passed to apply). Runs before the working-tree clean check unless\n * `checkTreeFirst: true` is set, so most recipes can noop on a dirty\n * tree without throwing. */\n plan: () => Promise<RecipePlan<P>>;\n /** Make the actual changes. Use `ctx.commit(msg)` for each logical step;\n * the wrapper collects SHAs into `RecipeResult.commits`. Return\n * `{ kind: \"failed\", notes }` to abort partway and surface the failure. */\n apply: (plan: P, ctx: RecipeApplyCtx) => Promise<RecipeApplyResult>;\n /** Check working tree clean BEFORE `plan()` runs. Use only when plan\n * itself mutates the tree (e.g. `bump-deps` runs `pnpm install` in plan\n * for an accurate outdated probe). Default false — clean check happens\n * after plan only if plan returns proceed, allowing noop-on-dirty for\n * read-only plans (a tree with stray edits + no recipe work to do\n * should not throw). */\n checkTreeFirst?: boolean;\n};\n\n/** Wrap a recipe's plan/apply phases. Centralises the siteLabel /\n * clean-tree check / branch creation / commit accumulation / RecipeResult\n * construction boilerplate that every recipe used to re-implement. */\nexport async function withRecipe<P>(body: RecipeBody<P>): Promise<RecipeResult> {\n const label = siteLabel(body.site);\n\n if (body.checkTreeFirst && !(await isWorkingTreeClean(body.site.path))) {\n throw new Error(`refusing to run: working tree is not clean at ${body.site.path}`);\n }\n\n const planned = await body.plan();\n\n if (planned.kind === \"noop\") {\n return {\n recipe: body.name,\n site: label,\n status: \"noop\",\n commits: [],\n ...(planned.notes ? { notes: planned.notes } : {}),\n };\n }\n if (planned.kind === \"failed\") {\n return {\n recipe: body.name,\n site: label,\n status: \"failed\",\n commits: [],\n notes: planned.notes,\n };\n }\n\n if (!body.checkTreeFirst && !(await isWorkingTreeClean(body.site.path))) {\n throw new Error(`refusing to run: working tree is not clean at ${body.site.path}`);\n }\n\n // Capture the operator's branch BEFORE we create the recipe branch, so we can\n // return them to it afterwards (#2) and so the failure path (#3) knows which\n // branch to force-restore to. Best-effort: if we can't read it (detached HEAD,\n // git error) we proceed with `original = null` and skip any force operations\n // rather than guess — we must NEVER force-discard/delete a branch we're unsure\n // of.\n let original: string | null = null;\n try {\n original = await currentBranch(body.site.path);\n } catch {\n original = null;\n }\n\n const branch = branchName(body.name);\n await createBranch(body.site.path, branch);\n\n /**\n * Best-effort restore to the operator's original branch. Never throws — a\n * restore failure must not turn an otherwise-clean recipe result into a\n * failure (#2). Skipped when we couldn't capture the original branch.\n *\n * IMPORTANT (composition): this is invoked only on the NOOP-from-apply path\n * (the recipe created a branch but committed nothing — leaving the operator\n * parked on an empty maint branch is pure downside). It is deliberately NOT\n * invoked on the APPLIED path: the fleet onboarding pipeline composes recipes\n * by running them in sequence against the SAME checkout, each building on the\n * prior's committed files in the working tree (convert-to-pnpm's lockfile →\n * onboard's deps → sync-configs → svelte-codemods). Restoring to the base\n * branch after an applied recipe would strip those files from the working\n * tree and break composition (verified live across the fleet). selfUpdating,\n * which PUSHES its branch, does its own post-push restore since its local\n * branch is disposable.\n */\n const restoreOriginal = async (): Promise<void> => {\n if (original === null || original === branch) return;\n try {\n await checkoutBranch(body.site.path, original);\n } catch (err) {\n // Leave the operator on the recipe branch rather than fail the result.\n console.warn(\n `warning: could not restore branch ${original} after ${body.name}: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n };\n\n /**\n * Failure restore (#3): force the checkout back to the captured original\n * branch (discarding the recipe branch's uncommitted changes) and delete the\n * recipe branch, so a re-run starts clean. SAFETY: only ever force-checks-out\n * the captured `original` and only ever deletes `branch` (the recipe-created\n * branch); never deletes `original`, never runs `git clean`. If `original` is\n * unavailable we do nothing (the safe subset) — better to leave the operator\n * parked than to force anything we're unsure about. Best-effort: never throws.\n */\n const restoreAfterFailure = async (): Promise<void> => {\n if (original === null || original === branch) return;\n try {\n await forceCheckoutBranch(body.site.path, original);\n } catch (err) {\n console.warn(\n `warning: could not force-restore branch ${original} after failed ${body.name}: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n // If we couldn't get off the recipe branch, deleting it would fail anyway;\n // and we must never delete the branch we're still on.\n return;\n }\n try {\n await deleteBranch(body.site.path, branch);\n } catch (err) {\n console.warn(\n `warning: could not delete recipe branch ${branch} after failed ${body.name}: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n };\n\n const shas: string[] = [];\n let result: RecipeApplyResult;\n try {\n result = await body.apply(planned.plan, {\n cwd: body.site.path,\n branch,\n commit: async (msg) => {\n const sha = await gitCommit(body.site.path, msg);\n if (sha) shas.push(sha);\n return sha;\n },\n });\n } catch (err) {\n // Body threw mid-mutation: force-restore + delete the recipe branch so the\n // checkout is retriable, then re-throw (preserve the prior throw semantics —\n // callers like init treat an uncaught throw as an `error` step).\n await restoreAfterFailure();\n throw err;\n }\n\n if (result.kind === \"failed\") {\n await restoreAfterFailure();\n return {\n recipe: body.name,\n site: label,\n status: \"failed\",\n commits: shas,\n notes: result.notes,\n };\n }\n\n // NOOP-from-apply only: no commits to compose, so don't leave the operator\n // parked on an empty maint branch. The APPLIED path intentionally stays on the\n // maint branch so the onboarding pipeline can compose (see restoreOriginal).\n if (shas.length === 0) {\n await restoreOriginal();\n }\n\n const notes = result.notes ? `${result.notes}; branch: ${branch}` : `branch: ${branch}`;\n return {\n recipe: body.name,\n site: label,\n status: shas.length > 0 ? \"applied\" : \"noop\",\n commits: shas,\n notes,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwDA,eAAsB,WAAc,MAA4C;AAC9E,QAAM,QAAQ,UAAU,KAAK,IAAI;AAEjC,MAAI,KAAK,kBAAkB,CAAE,MAAM,mBAAmB,KAAK,KAAK,IAAI,GAAI;AACtE,UAAM,IAAI,MAAM,iDAAiD,KAAK,KAAK,IAAI,EAAE;AAAA,EACnF;AAEA,QAAM,UAAU,MAAM,KAAK,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