import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; export interface RuleMappingItem { index: number; sourceRuleId: string; sourceRuleCode: string | number; targetRuleId: string; targetRuleCode: string | number; description: string; scope: string; strictness: string; } export interface RuleMappingSnapshot { syncedAt: string; source: { id: string; name: string; latestPublishedVersionNumber?: number | null; latestPublishedVersionName?: string | null; }; target: { id: string; name: string; publishedVersionNumber: number; publishedVersionName?: string | null; rulesCount: number; }; versionMapping: { sourceProdVersionNumber: number | null; sourceProdVersionName: string | null; targetTestVersionNumber: number; targetTestVersionName: string | null; }; ruleMapping: RuleMappingItem[]; } export function getMappingsDir(): string { const custom = process.env.SEAL_USE_MAPPINGS_DIR?.trim(); if (custom) return custom; return join(homedir(), ".config", "seal-use", "mappings"); } export function saveRuleMappingSnapshot(snapshot: RuleMappingSnapshot): string { const dir = getMappingsDir(); mkdirSync(dir, { recursive: true, mode: 0o700 }); const versionFile = join(dir, `${snapshot.target.id}-v${snapshot.target.publishedVersionNumber}.json`); const latestFile = join(dir, `${snapshot.target.id}-latest.json`); const content = JSON.stringify(snapshot, null, 2); writeFileSync(versionFile, content, { encoding: "utf-8", mode: 0o600 }); writeFileSync(latestFile, content, { encoding: "utf-8", mode: 0o600 }); return versionFile; } export function loadRuleMappingSnapshot( targetCorpId: string, versionSelector?: string | number ): RuleMappingSnapshot | null { const dir = getMappingsDir(); let filename: string; if (!versionSelector || versionSelector === "latest") { filename = `${targetCorpId}-latest.json`; } else { const vStr = String(versionSelector).replace(/^v/i, ""); filename = `${targetCorpId}-v${vStr}.json`; } const filePath = join(dir, filename); if (!existsSync(filePath)) { return null; } try { const raw = readFileSync(filePath, "utf-8"); return JSON.parse(raw) as RuleMappingSnapshot; } catch { return null; } } function stripLeadingZeros(val: string): string { return val.replace(/^0+(?=\d)/, ""); } export function filterRuleMapping( mapping: RuleMappingItem[], codeOrId?: string ): RuleMappingItem[] { if (!codeOrId) return mapping; const target = stripLeadingZeros(codeOrId.trim().toLowerCase().replace(/^#/, "")); return mapping.filter((item) => { const srcCode = String(item.sourceRuleCode).toLowerCase().replace(/^#/, ""); const tgtCode = String(item.targetRuleCode).toLowerCase().replace(/^#/, ""); const tgtShort = stripLeadingZeros(tgtCode.replace(/^rule-/, "")); const srcShort = stripLeadingZeros(srcCode.replace(/^rule-/, "")); return ( srcCode === target || tgtCode === target || srcShort === target || tgtShort === target || item.sourceRuleId.toLowerCase() === target || item.targetRuleId.toLowerCase() === target ); }); } export function computeNextSyncIteration( prodCorpName: string, prodVersionNumber: number | undefined, testVersions: Array<{ versionName?: string | null }> ): number { let maxIteration = 0; const prefixRegex = prodVersionNumber !== undefined ? new RegExp(`\\[Prod v${prodVersionNumber}\\s*·\\s*#(\\d+)(?:[^\\]]*)\\]`) : /\[Prod draft\s*·\s*#(\d+)(?:[^\]]*)\]/; for (const tv of testVersions) { if (!tv.versionName) continue; const match = tv.versionName.match(prefixRegex); if (match && match[1]) { const num = parseInt(match[1], 10); if (!isNaN(num) && num > maxIteration) { maxIteration = num; } } } if (maxIteration > 0) { return maxIteration + 1; } // If no structured tag exists at all, check legacy un-numbered sync versions const anyStructuredTag = testVersions.some( (tv) => tv.versionName && /\[Prod v\d+/.test(tv.versionName) ); if (!anyStructuredTag) { const legacySyncCount = testVersions.filter( (tv) => tv.versionName && tv.versionName.includes(`Sync from ${prodCorpName}`) ).length; if (legacySyncCount > 0) { return legacySyncCount + 1; } } return 1; } export function formatSyncVersionName( prodCorpName: string, prodVersionNumber: number | undefined, iteration: number, targetTestVersionNumber?: number ): string { const prodLabel = prodVersionNumber !== undefined ? `Prod v${prodVersionNumber}` : "Prod draft"; const testLabel = targetTestVersionNumber !== undefined ? ` -> Test v${targetTestVersionNumber}` : ""; return `Sync from ${prodCorpName} [${prodLabel} · #${iteration}${testLabel}]`; }