Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

13.1 KB
Raw Blame
#!/usr/bin/env node
/**
 * Generates the icon catalogs for every platform from the SVG sources in core/assets/icons.
 */

const fs = require('fs');
const path = require('path');
const { readIconFolder, serializeIconSvg, serializeIconBody, toCamelCase } = require('./lib/svg-icons.cjs');

const REPO_ROOT = path.join(__dirname, '../../..');
const ICONS_DIR = path.join(REPO_ROOT, 'core/models/src/icons');
const ICON_SOURCES_DIR = path.join(REPO_ROOT, 'core/assets/icons');
const SOURCES_FILE = path.join(ICON_SOURCES_DIR, 'sources.json');

const GENERATED_HEADER = 'This file is auto-generated from core/assets/icons by core/models/scripts/generate-icons.cjs.';
const REGENERATE_HINT = "Do not edit this file directly. Run 'node core/models/scripts/generate-icons.cjs' to regenerate.";
const TS_HEADER = `/*\n * <auto-generated />\n * ${GENERATED_HEADER}\n * ${REGENERATE_HINT}\n */`;

/**
 * The item type and built-in logo catalogs, rendered as full SVG strings on every platform.
 */
const SVG_CATALOGS = [
  {
    key: 'item',
    constName: 'ItemTypeIconSvgs',
    className: 'ItemTypeIcons',
    keyTypeName: 'ItemTypeIconKey',
    description: ['Centralized SVG icon definitions for item types.', 'Single source of truth for all item type icons across platforms.'],
    rnMapName: 'itemTypeIconComponents',
    rnKeyTypeName: 'ItemTypeIconComponentKey',
    lookup: false,
    outputs: {
      ts: path.join(ICONS_DIR, 'ItemTypeIcons.ts'),
      swift: path.join(REPO_ROOT, 'apps/mobile-app/ios/VaultModels/ItemTypeIcons.swift'),
      kotlin: path.join(REPO_ROOT, 'apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/ItemTypeIcons.kt'),
      rn: path.join(REPO_ROOT, 'apps/mobile-app/components/items/ItemTypeIconComponents.tsx'),
    },
  },
  {
    key: 'builtin-logo',
    constName: 'BuiltinLogoSvgs',
    className: 'BuiltinLogos',
    keyTypeName: 'BuiltinLogoKey',
    description: ['The built-in logos a user can pick for an item, keyed by the Source a builtin logo row stores.', 'Single source of truth for all built-in logos across platforms.'],
    rnMapName: 'builtinLogoComponents',
    rnKeyTypeName: 'BuiltinLogoComponentKey',
    lookup: true,
    outputs: {
      ts: path.join(ICONS_DIR, 'BuiltinLogos.ts'),
      swift: path.join(REPO_ROOT, 'apps/mobile-app/ios/VaultModels/BuiltinLogos.swift'),
      kotlin: path.join(REPO_ROOT, 'apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/BuiltinLogos.kt'),
      rn: path.join(REPO_ROOT, 'apps/mobile-app/components/items/BuiltinLogoComponents.tsx'),
    },
  },
];

const UI_TS_OUTPUT = path.join(ICONS_DIR, 'UiIcons.ts');
const UI_CSHARP_OUTPUT = path.join(REPO_ROOT, 'apps/server/AliasVault.Admin/Main/Components/Icons/UiIcons.cs');

/**
 * Load one catalog in the order of sources.json, failing when a source file and its provenance entry don't line up.
 */
function loadCatalog(key, sources) {
  const icons = readIconFolder(path.join(ICON_SOURCES_DIR, key));
  const listed = Object.keys(sources[key] ?? {});
  const missingSource = Object.keys(icons).filter((name) => !listed.includes(name));
  const missingFile = listed.filter((name) => !(name in icons));
  if (missingSource.length || missingFile.length) {
    throw new Error(`Icon catalog "${key}" is out of sync with sources.json. Without a sources.json entry: ${missingSource.join(', ') || '-'}. Without an svg file: ${missingFile.join(', ') || '-'}.`);
  }
  for (const name of listed) {
    if (!sources[key][name].source) {
      throw new Error(`sources.json: ${key}/${name} has no "source"`);
    }
  }
  return Object.fromEntries(listed.map((name) => [name, icons[name]]));
}

/**
 * Quote a string for a single-quoted TypeScript literal.
 */
function tsString(value) {
  return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
}

/**
 * Format an attribute map as a TypeScript object literal with camelCase keys.
 */
function tsAttributes(attrs) {
  const entries = Object.entries(attrs).map(([name, value]) => {
    const prop = toCamelCase(name);
    return `${/^[a-zA-Z_$][\w$]*$/.test(prop) ? prop : tsString(prop)}: ${tsString(value)}`;
  });
  return `{ ${entries.join(', ')} }`;
}

/**
 * Generate core/models/src/icons/UiIcons.ts.
 */
function generateUiTypeScript(icons) {
  const entries = Object.entries(icons).map(([name, icon]) => {
    const { viewBox, ...attrs } = icon.attrs;
    const nodes = icon.nodes.map(([tag, nodeAttrs]) => `[${tsString(tag)}, ${tsAttributes(nodeAttrs)}]`).join(', ');
    return `  ${tsString(name)}: { viewBox: ${tsString(viewBox)}, attrs: ${tsAttributes(attrs)}, nodes: [${nodes}] },`;
  });

  return `${TS_HEADER}

/**
 * A shape element of a UI icon.
 */
export type UiIconTag = 'path' | 'circle' | 'rect' | 'line' | 'polyline' | 'polygon' | 'ellipse';

/**
 * A shape of a UI icon with its attributes, keyed by React prop name (camelCase).
 */
export type UiIconNode = readonly [tag: UiIconTag, attrs: Readonly<Record<string, string>>];

/**
 * A UI icon: the root <svg> attributes (camelCase) and its shapes.
 */
export type UiIconDefinition = {
  readonly viewBox: string;
  readonly attrs: Readonly<Record<string, string>>;
  readonly nodes: readonly UiIconNode[];
};

/**
 * The UI icons shared by all apps, keyed by name.
 */
export const UiIcons = {
${entries.join('\n')}
} as const satisfies Record<string, UiIconDefinition>;

export type UiIconName = keyof typeof UiIcons;
`;
}

/**
 * Generate the TypeScript string catalog for item type icons or built-in logos.
 */
function generateSvgCatalogTypeScript(icons, catalog) {
  const entries = Object.entries(icons).map(([name, icon]) => `  ${tsString(name)}: \`${serializeIconSvg(icon, { xmlns: true })}\`,`).join('\n\n');
  const helpers = catalog.lookup
    ? `
/**
 * Get the SVG string for a built-in logo key, or null when the key is unknown to this client
 * (a newer version may have added it). Callers fall back to their placeholder icon.
 */
export function getBuiltinLogoSvg(key: string): string | null {
  return Object.prototype.hasOwnProperty.call(${catalog.constName}, key) ? ${catalog.constName}[key as ${catalog.keyTypeName}] : null;
}

/**
 * Get all built-in logo keys, in the order they are offered to the user.
 */
export function getAllBuiltinLogoKeys(): ${catalog.keyTypeName}[] {
  return Object.keys(${catalog.constName}) as ${catalog.keyTypeName}[];
}
`
    : `
/**
 * Get SVG string for an item type icon.
 */
export function getItemTypeIconSvg(key: ${catalog.keyTypeName}): string {
  return ${catalog.constName}[key];
}

/**
 * Get all item type icon keys.
 */
export function getAllItemTypeIconKeys(): ${catalog.keyTypeName}[] {
  return Object.keys(${catalog.constName}) as ${catalog.keyTypeName}[];
}
`;

  return `${TS_HEADER}

/**
${catalog.description.map((line) => ` * ${line}`).join('\n')}
 */
export const ${catalog.constName} = {
${entries}
} as const;

export type ${catalog.keyTypeName} = keyof typeof ${catalog.constName};
${helpers}`;
}

/**
 * Generate a Swift struct for an item type icon or built-in logo catalog.
 */
function generateSwiftIcons(icons, catalog) {
  const fields = Object.entries(icons).map(([name, icon]) => `    /// ${name} icon SVG.
    public static let ${toCamelCase(name)} = """
${serializeIconSvg(icon, { xmlns: true })}
"""`).join('\n\n');

  const lookup = catalog.lookup ? `

    /// The SVG for an icon key, or nil when the key is unknown to this client.
    public static func svg(for key: String) -> String? {
        switch key {
${Object.keys(icons).map((name) => `        case "${name}": return ${toCamelCase(name)}`).join('\n')}
        default: return nil
        }
    }` : '';

  return `// <auto-generated />
// ${GENERATED_HEADER}
// ${REGENERATE_HINT}
// swiftlint:disable line_length

import Foundation

${catalog.description.map((line) => `/// ${line}`).join('\n')}
public struct ${catalog.className} {
${fields}${lookup}
}
`;
}

/**
 * Generate a Kotlin object for an item type icon or built-in logo catalog.
 */
function generateKotlinIcons(icons, catalog) {
  const constantName = (name) => name.replace(/-/g, '_').toUpperCase();
  const fields = Object.entries(icons).map(([name, icon]) => `    /**
     * ${name} icon SVG.
     */
    val ${constantName(name)} = """
${serializeIconSvg(icon, { xmlns: true })}
    """.trimIndent()`).join('\n\n');

  const lookup = catalog.lookup ? `

    /**
     * The SVG for an icon key, or null when the key is unknown to this client.
     */
    fun svgFor(key: String): String? = when (key) {
${Object.keys(icons).map((name) => `        "${name}" -> ${constantName(name)}`).join('\n')}
        else -> null
    }` : '';

  return `// <auto-generated />
// ${GENERATED_HEADER}
// ${REGENERATE_HINT}
@file:Suppress("MaxLineLength")

package net.aliasvault.app.vaultstore.models

/**
${catalog.description.map((line) => ` * ${line}`).join('\n')}
 */
object ${catalog.className} {
${fields}${lookup}
}
`;
}

/**
 * The react-native-svg component for each shape element.
 */
const RN_COMPONENTS = { path: 'Path', circle: 'Circle', rect: 'Rect', line: 'Line', polyline: 'Polyline', polygon: 'Polygon', ellipse: 'Ellipse' };

/**
 * Generate react-native-svg components for an item type icon or built-in logo catalog.
 */
function generateReactNativeIcons(icons, catalog) {
  const used = new Set();
  const components = Object.entries(icons).map(([name, icon]) => {
    const { viewBox, ...rootAttrs } = icon.attrs;
    const rootProps = Object.entries(rootAttrs).map(([attr, value]) => ` ${toCamelCase(attr)}="${value}"`).join('');
    const children = icon.nodes.map(([tag, attrs]) => {
      used.add(RN_COMPONENTS[tag]);
      return `    <${RN_COMPONENTS[tag]} ${Object.entries(attrs).map(([attr, value]) => `${toCamelCase(attr)}="${value}"`).join(' ')} />`;
    }).join('\n');
    return `export const ${toPascalCase(name)}Icon = ({ width = 32, height = 32 }: { width?: number; height?: number }): React.ReactElement => (
  <Svg width={width} height={height} viewBox="${viewBox}"${rootProps}>
${children}
  </Svg>
);`;
  }).join('\n\n');

  const imports = [...used].sort().join(', ');
  return `// <auto-generated />
// ${GENERATED_HEADER}
// ${REGENERATE_HINT}

import React from 'react';
import Svg, { ${imports} } from 'react-native-svg';

${components}

/**
 * Map of icon key to React Native SVG component.
 */
export const ${catalog.rnMapName} = {
${Object.keys(icons).map((name) => `  ${tsString(name)}: ${toPascalCase(name)}Icon,`).join('\n')}
};

export type ${catalog.rnKeyTypeName} = keyof typeof ${catalog.rnMapName};
`;
}

/**
 * Convert a kebab-case icon name to a PascalCase member name.
 */
function toPascalCase(name) {
  return name.split('-').map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join('');
}

/**
 * Quote a string for a C# verbatim string literal.
 */
function csString(value) {
  return `@"${value.replace(/"/g, '""')}"`;
}

/**
 * Generate the C# UI icon catalog for the admin portal.
 */
function generateUiCSharp(icons) {
  const members = Object.entries(icons).map(([name, icon]) => {
    const { viewBox, ...attrs } = icon.attrs;
    const attrList = Object.entries(attrs).map(([attr, value]) => `{ "${attr}", "${value}" }`).join(', ');
    return `    /// <summary>Gets the "${name}" icon.</summary>
    public static UiIconDefinition ${toPascalCase(name)} { get; } = new("${viewBox}", new Dictionary<string, object> { ${attrList} }, ${csString(serializeIconBody(icon))});`;
  }).join('\n\n');

  return `// <auto-generated />
// ${GENERATED_HEADER}
// ${REGENERATE_HINT}

namespace AliasVault.Admin.Main.Components.Icons;

using System.Collections.Generic;

/// <summary>
/// A UI icon: its viewBox, root svg attributes and inner shape markup.
/// </summary>
/// <param name="ViewBox">The svg viewBox.</param>
/// <param name="Attributes">The root svg attributes (fill, stroke and so on).</param>
/// <param name="Body">The inner shape markup.</param>
public sealed record UiIconDefinition(string ViewBox, IReadOnlyDictionary<string, object> Attributes, string Body);

/// <summary>
/// The UI icons shared by all apps.
/// </summary>
public static class UiIcons
{
${members}
}
`;
}

/**
 * Write a generated file when its content differs.
 */
function emit(file, content) {
  const current = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null;
  if (current === content) {
    return;
  }
  fs.mkdirSync(path.dirname(file), { recursive: true });
  fs.writeFileSync(file, content, 'utf8');
  console.log(`Generated: ${path.relative(REPO_ROOT, file)}`);
}

/**
 * Main execution.
 */
function main() {
  const sources = JSON.parse(fs.readFileSync(SOURCES_FILE, 'utf8'));

  const uiIcons = loadCatalog('ui', sources);
  emit(UI_TS_OUTPUT, generateUiTypeScript(uiIcons));
  emit(UI_CSHARP_OUTPUT, generateUiCSharp(uiIcons));

  for (const catalog of SVG_CATALOGS) {
    const icons = loadCatalog(catalog.key, sources);
    emit(catalog.outputs.ts, generateSvgCatalogTypeScript(icons, catalog));
    emit(catalog.outputs.swift, generateSwiftIcons(icons, catalog));
    emit(catalog.outputs.kotlin, generateKotlinIcons(icons, catalog));
    emit(catalog.outputs.rn, generateReactNativeIcons(icons, catalog));
  }

  console.log(`Icons: ${Object.keys(uiIcons).length} ui, ${Object.keys(sources.item).length} item, ${Object.keys(sources['builtin-logo']).length} built-in logo.`);
}

main();