#!/usr/bin/env node /** * Fetches the Konflux UI analytics schema from segment-bridge and generates * TypeScript type definitions into a single file using json-schema-to-typescript. * * Usage: node scripts/generate-analytics-types.mjs */ import { compile } from 'json-schema-to-typescript'; import { readFile, writeFile, mkdir, rm } from 'node:fs/promises'; import { existsSync } from 'node:fs'; import { join } from 'node:path'; // Pinned commit hash for stable schema reference. Update this when adopting new schema changes. const SCHEMA_COMMIT = '6a9a81249ff8222b39ca30256b62facb889fd44b'; const SCHEMA_URL = `https://raw.githubusercontent.com/konflux-ci/segment-bridge/${SCHEMA_COMMIT}/schema/ui.json`; const LOCAL_SCHEMA_PATHS = [ join(import.meta.dirname, '..', '..', 'segment-bridge', 'schema', 'ui.json'), join(import.meta.dirname, '..', '..', '..', 'segment-bridge', 'schema', 'ui.json'), ]; const OUTPUT_DIR = join(import.meta.dirname, '..', 'src', 'analytics', 'gen'); const OUTPUT_FILE = join(OUTPUT_DIR, 'analytics-types.ts'); const HEADER = `/** * ⚠️ AUTO-GENERATED FILE — DO NOT EDIT MANUALLY ⚠️ * * This file was generated from the Konflux analytics schema. * Schema: https://github.com/konflux-ci/segment-bridge/blob/${SCHEMA_COMMIT}/schema/ui.json * Docs: docs/analytics.md * * To regenerate, run: yarn generate:analytics-types * * LLM INSTRUCTIONS: If asked to modify analytics types, always regenerate * from schema instead of editing this file directly. */`; const SHA256_HASH_IMPORT = "import type { SHA256Hash } from '../obfuscate';"; async function fetchSchema() { const localSchemaPath = LOCAL_SCHEMA_PATHS.find(existsSync); if (process.env.ANALYTICS_SCHEMA_LOCAL === '1' && localSchemaPath) { console.log(' Using local schema (ANALYTICS_SCHEMA_LOCAL=1):', localSchemaPath); return JSON.parse(await readFile(localSchemaPath, 'utf-8')); } try { const res = await fetch(SCHEMA_URL); if (res.ok) return res.json(); } catch { // Fall through to local file } if (localSchemaPath) { console.log(' Remote fetch failed, using local schema:', localSchemaPath); return JSON.parse(await readFile(localSchemaPath, 'utf-8')); } throw new Error( `Failed to fetch schema from ${SCHEMA_URL} and no local fallback found at ${LOCAL_SCHEMA_PATHS.join(' or ')}`, ); } async function main() { console.log('Fetching schema from:', SCHEMA_URL); const schema = await fetchSchema(); await rm(OUTPUT_DIR, { recursive: true, force: true }); await mkdir(OUTPUT_DIR, { recursive: true }); // Enrich descriptions for fields with x-obfuscation-salt before compiling for (const def of Object.values(schema.$defs || {})) { for (const schemaEntry of def.allOf || []) { for (const [, fieldDef] of Object.entries(schemaEntry.properties || {})) { const salt = fieldDef['x-obfuscation-salt']; if (salt) { const base = (fieldDef.description || '').replace(/\.?\s*$/, ''); fieldDef.description = `${base}. Obfuscated via ${fieldDef['x-obfuscation'] || 'sha256'} with \`${salt}\` as salt.`; } } } } const ts = await compile(schema, 'KonfluxUISegmentEvents', { bannerComment: '', additionalProperties: false, }); // Collect event defs that have x-event-name const defs = schema.$defs || {}; const eventDefs = Object.entries(defs).filter(([, def]) => def['x-event-name']); const toPascalCase = (s) => s .split('_') .map((w) => w[0].toUpperCase() + w.slice(1)) .join(''); // Generate TrackEvents enum from x-event-name fields in $defs const enumEntries = eventDefs.map(([key, def]) => ` ${key} = '${def['x-event-name']}',`); const enumBlock = [ '', '/**', ' * Event names for Segment track() calls.', ' * Values match the x-event-name field in the schema.', ' */', 'export enum TrackEvents {', ...enumEntries, '}', '', ].join('\n'); // Generate EventPropertiesMap — maps each TrackEvents value to its event-specific // properties with CommonFields excluded (they are merged via commonProperties). const mapEntries = eventDefs.map(([key, def]) => { const hasEventProperties = (def.allOf || []).some( (schemaEntry) => Object.keys(schemaEntry.properties || {}).length > 0, ); const propertiesType = hasEventProperties ? `Omit<${toPascalCase(key)}, keyof CommonFields>` : 'Record'; return ` [TrackEvents.${key}]: ${propertiesType};`; }); const mapBlock = [ '', '/**', ' * Maps each TrackEvents value to its event-specific properties callers must supply.', ' * CommonFields are excluded — they are merged automatically from commonProperties.', ' */', 'export type EventPropertiesMap = {', ...mapEntries, '};', '', ].join('\n'); let output = `${HEADER}\n\n${ts}${enumBlock}${mapBlock}`; if (output.includes('SHA256Hash')) { output = `${HEADER}\n\n${SHA256_HASH_IMPORT}\n\n${ts}${enumBlock}${mapBlock}`; } await writeFile(OUTPUT_FILE, output); console.log(' Generated: analytics-types.ts'); } main().catch((err) => { console.error(err); process.exit(1); });