Skip to content

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

12.3 KB
Raw Blame
#!/usr/bin/env node
/**
 * Generates FieldKey, FieldType and ItemType constants for Swift and Kotlin from TypeScript source.
 * All type definitions are dynamically extracted from the TypeScript source files.
 */

const fs = require('fs');
const path = require('path');

// Paths
const REPO_ROOT = path.join(__dirname, '../../..');
const TS_SOURCE = path.join(REPO_ROOT, 'core/models/src/vault/FieldKey.ts');
const TS_ITEM_SOURCE = path.join(REPO_ROOT, 'core/models/src/vault/Item.ts');
const SWIFT_OUTPUT = path.join(REPO_ROOT, 'apps/mobile-app/ios/VaultModels/FieldKey.swift');
const SWIFT_FIELD_TYPE_OUTPUT = path.join(REPO_ROOT, 'apps/mobile-app/ios/VaultModels/FieldType.swift');
const SWIFT_ITEM_TYPE_OUTPUT = path.join(REPO_ROOT, 'apps/mobile-app/ios/VaultModels/ItemType.swift');
const KOTLIN_OUTPUT = path.join(REPO_ROOT, 'apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/FieldKey.kt');
const KOTLIN_FIELD_TYPE_OUTPUT = path.join(REPO_ROOT, 'apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/FieldType.kt');
const KOTLIN_ITEM_TYPE_OUTPUT = path.join(REPO_ROOT, 'apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/ItemType.kt');

/**
 * Parse the TypeScript FieldKey.ts file and extract constants
 */
function parseTypeScriptFieldKeys(tsContent) {
  const fieldKeys = {};

  // Extract field comments
  const lines = tsContent.split(/\r?\n/);
  let currentComment = '';

  for (let i = 0; i < lines.length; i++) {
    const line = lines[i].trim();

    // Capture JSDoc comments
    if (line.startsWith('/**') || line.startsWith('*')) {
      const commentMatch = line.match(/\*\s*(.+)/);
      if (commentMatch && !commentMatch[1].startsWith('/')) {
        currentComment = commentMatch[1].trim();
      }
    }

    // Match field definition
    const fieldMatch = line.match(/^(\w+):\s*'([^']+)',?$/);
    if (fieldMatch) {
      const [, name, value] = fieldMatch;
      fieldKeys[name] = {
        value,
        comment: currentComment
      };
      currentComment = '';
    }
  }

  return fieldKeys;
}

/**
 * Parse FieldTypes from TypeScript Item.ts source
 * Returns an array of field type names in order
 */
function parseFieldTypes(tsContent) {
  const fieldTypes = [];

  // Find the FieldTypes constant
  const match = tsContent.match(/export const FieldTypes\s*=\s*\{([^}]+)\}/s);
  if (!match) {
    console.warn('Warning: Could not find FieldTypes in source');
    return fieldTypes;
  }

  const body = match[1];
  // Match each type: Text: 'Text',
  const typeRegex = /(\w+):\s*'(\w+)'/g;
  let typeMatch;

  while ((typeMatch = typeRegex.exec(body)) !== null) {
    fieldTypes.push(typeMatch[1]);
  }

  return fieldTypes;
}

/**
 * Parse ItemTypes from TypeScript Item.ts source
 * Returns an array of item type names in order
 */
function parseItemTypes(tsContent) {
  const itemTypes = [];

  // Find the ItemTypes constant
  const match = tsContent.match(/export const ItemTypes\s*=\s*\{([^}]+)\}/s);
  if (!match) {
    console.warn('Warning: Could not find ItemTypes in source');
    return itemTypes;
  }

  const body = match[1];
  // Match each type: Login: 'Login',
  const typeRegex = /(\w+):\s*'(\w+)'/g;
  let typeMatch;

  while ((typeMatch = typeRegex.exec(body)) !== null) {
    itemTypes.push(typeMatch[1]);
  }

  return itemTypes;
}

/**
 * Generate Swift enum
 */
function generateSwift(fieldKeys) {
  const header = `// <auto-generated />
// This file is auto-generated from core/models/src/vault/FieldKey.ts
// Do not edit this file directly. Run 'npm run generate:models' to regenerate.

import Foundation

/// System field keys for the field-based data model.
/// These keys map to FieldDefinition.FieldKey values.
public struct FieldKey {`;

  const fields = Object.entries(fieldKeys)
    .map(([name, { value, comment }]) => {
      // Convert PascalCase to camelCase for Swift
      const swiftName = name.charAt(0).toLowerCase() + name.slice(1);
      return `    /// ${comment}
    public static let ${swiftName} = "${value}"`;
    })
    .join('\n\n');

  const footer = `
}
`;

  return header + '\n' + fields + footer;
}

/**
 * Generate Kotlin object
 */
function generateKotlin(fieldKeys) {
  const header = `// <auto-generated />
// This file is auto-generated from core/models/src/vault/FieldKey.ts
// Do not edit this file directly. Run 'npm run generate:models' to regenerate.

package net.aliasvault.app.vaultstore.models

/**
 * System field keys for the field-based data model.
 * These keys map to FieldDefinition.FieldKey values.
 */
object FieldKey {`;

  const fields = Object.entries(fieldKeys)
    .map(([name, { value, comment }]) => {
      // Convert to SCREAMING_SNAKE_CASE for Kotlin constants
      const kotlinName = name.replace(/([A-Z])/g, '_$1').toUpperCase().replace(/^_/, '');
      // Ensure comment ends with a period for Kotlin detekt
      const kotlinComment = comment.endsWith('.') ? comment : `${comment}.`;
      return `    /**
     * ${kotlinComment}
     */
    const val ${kotlinName} = "${value}"`;
    })
    .join('\n\n');

  const footer = `
}
`;

  return header + '\n' + fields + footer;
}

/**
 * Generate Swift struct for FieldType
 */
function generateSwiftFieldType(fieldTypes) {
  const header = `// <auto-generated />
// This file is auto-generated from core/models/src/vault/Item.ts
// Do not edit this file directly. Run 'npm run generate:models' to regenerate.

import Foundation

/// Field types for rendering and validation.
public struct FieldType {`;

  const fields = fieldTypes
    .map(type => {
      // Convert PascalCase to camelCase for Swift
      const swiftName = type.charAt(0).toLowerCase() + type.slice(1);
      return `    /// ${type} field type.
    public static let ${swiftName} = "${type}"`;
    })
    .join('\n\n');

  const allTypes = `

    /// All available field types.
    public static let all = [${fieldTypes.map(t => t.charAt(0).toLowerCase() + t.slice(1)).join(', ')}]

    /// Checks if a string value is a valid field type.
    public static func isValid(_ value: String?) -> Bool {
        guard let value = value else { return false }
        return all.contains(value)
    }`;

  const footer = `
}
`;

  return header + '\n' + fields + allTypes + footer;
}

/**
 * Generate Swift struct for ItemType
 */
function generateSwiftItemType(itemTypes) {
  const header = `// <auto-generated />
// This file is auto-generated from core/models/src/vault/Item.ts
// Do not edit this file directly. Run 'npm run generate:models' to regenerate.

import Foundation

/// Item types supported by the vault.
public struct ItemType {`;

  const fields = itemTypes
    .map(type => {
      // Convert PascalCase to camelCase for Swift
      const swiftName = type.charAt(0).toLowerCase() + type.slice(1);
      return `    /// ${type} item type.
    public static let ${swiftName} = "${type}"`;
    })
    .join('\n\n');

  const allTypes = `

    /// All available item types.
    public static let all = [${itemTypes.map(t => t.charAt(0).toLowerCase() + t.slice(1)).join(', ')}]

    /// Checks if a string value is a valid item type.
    public static func isValid(_ value: String?) -> Bool {
        guard let value = value else { return false }
        return all.contains(value)
    }`;

  const footer = `
}
`;

  return header + '\n' + fields + allTypes + footer;
}

/**
 * Generate Kotlin object for FieldType
 */
function generateKotlinFieldType(fieldTypes) {
  const header = `// <auto-generated />
// This file is auto-generated from core/models/src/vault/Item.ts
// Do not edit this file directly. Run 'npm run generate:models' to regenerate.

package net.aliasvault.app.vaultstore.models

/**
 * Field types for rendering and validation.
 */
object FieldType {`;

  const fields = fieldTypes
    .map(type => {
      // Convert to SCREAMING_SNAKE_CASE for Kotlin constants
      const kotlinName = type.replace(/([A-Z])/g, '_$1').toUpperCase().replace(/^_/, '');
      return `    /**
     * ${type} field type.
     */
    const val ${kotlinName} = "${type}"`;
    })
    .join('\n\n');

  const allTypes = `

    /**
     * All available field types.
     */
    val all = listOf(${fieldTypes.map(t => t.replace(/([A-Z])/g, '_$1').toUpperCase().replace(/^_/, '')).join(', ')})

    /**
     * Checks if a string value is a valid field type.
     */
    fun isValid(value: String?): Boolean {
        return value in all
    }`;

  const footer = `
}
`;

  return header + '\n' + fields + allTypes + footer;
}

/**
 * Generate Kotlin object for ItemType
 */
function generateKotlinItemType(itemTypes) {
  const header = `// <auto-generated />
// This file is auto-generated from core/models/src/vault/Item.ts
// Do not edit this file directly. Run 'npm run generate:models' to regenerate.

package net.aliasvault.app.vaultstore.models

/**
 * Item types supported by the vault.
 */
object ItemType {`;

  const fields = itemTypes
    .map(type => {
      // Convert to SCREAMING_SNAKE_CASE for Kotlin constants
      const kotlinName = type.replace(/([A-Z])/g, '_$1').toUpperCase().replace(/^_/, '');
      return `    /**
     * ${type} item type.
     */
    const val ${kotlinName} = "${type}"`;
    })
    .join('\n\n');

  const allTypes = `

    /**
     * All available item types.
     */
    val all = listOf(${itemTypes.map(t => t.replace(/([A-Z])/g, '_$1').toUpperCase().replace(/^_/, '')).join(', ')})

    /**
     * Checks if a string value is a valid item type.
     */
    fun isValid(value: String?): Boolean {
        return value in all
    }`;

  const footer = `
}
`;

  return header + '\n' + fields + allTypes + footer;
}

/**
 * Ensure directory exists
 */
function ensureDir(filePath) {
  const dir = path.dirname(filePath);
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
}

/**
 * Main execution
 */
function main() {
  // Read TypeScript FieldKey source
  if (!fs.existsSync(TS_SOURCE)) {
    throw new Error(`Source file not found: ${TS_SOURCE}`);
  }

  const tsContent = fs.readFileSync(TS_SOURCE, 'utf8');
  const fieldKeys = parseTypeScriptFieldKeys(tsContent);

  if (Object.keys(fieldKeys).length === 0) {
    throw new Error('No field keys found in source file');
  }

  // Read TypeScript Item.ts source for FieldTypes and ItemTypes
  if (!fs.existsSync(TS_ITEM_SOURCE)) {
    throw new Error(`Source file not found: ${TS_ITEM_SOURCE}`);
  }

  const tsItemContent = fs.readFileSync(TS_ITEM_SOURCE, 'utf8');
  const fieldTypes = parseFieldTypes(tsItemContent);
  const itemTypes = parseItemTypes(tsItemContent);

  if (fieldTypes.length === 0) {
    throw new Error('No field types found in Item.ts source file');
  }

  if (itemTypes.length === 0) {
    throw new Error('No item types found in Item.ts source file');
  }

  console.log(`Parsed ${Object.keys(fieldKeys).length} field keys`);
  console.log(`Parsed ${fieldTypes.length} field types: ${fieldTypes.join(', ')}`);
  console.log(`Parsed ${itemTypes.length} item types: ${itemTypes.join(', ')}`);

  // Generate Swift FieldKey
  ensureDir(SWIFT_OUTPUT);
  const swiftContent = generateSwift(fieldKeys);
  fs.writeFileSync(SWIFT_OUTPUT, swiftContent, 'utf8');
  console.log(`Generated: ${SWIFT_OUTPUT}`);

  // Generate Swift FieldType
  ensureDir(SWIFT_FIELD_TYPE_OUTPUT);
  const swiftFieldTypeContent = generateSwiftFieldType(fieldTypes);
  fs.writeFileSync(SWIFT_FIELD_TYPE_OUTPUT, swiftFieldTypeContent, 'utf8');
  console.log(`Generated: ${SWIFT_FIELD_TYPE_OUTPUT}`);

  // Generate Swift ItemType
  ensureDir(SWIFT_ITEM_TYPE_OUTPUT);
  const swiftItemTypeContent = generateSwiftItemType(itemTypes);
  fs.writeFileSync(SWIFT_ITEM_TYPE_OUTPUT, swiftItemTypeContent, 'utf8');
  console.log(`Generated: ${SWIFT_ITEM_TYPE_OUTPUT}`);

  // Generate Kotlin FieldKey
  ensureDir(KOTLIN_OUTPUT);
  const kotlinContent = generateKotlin(fieldKeys);
  fs.writeFileSync(KOTLIN_OUTPUT, kotlinContent, 'utf8');
  console.log(`Generated: ${KOTLIN_OUTPUT}`);

  // Generate Kotlin FieldType
  ensureDir(KOTLIN_FIELD_TYPE_OUTPUT);
  const kotlinFieldTypeContent = generateKotlinFieldType(fieldTypes);
  fs.writeFileSync(KOTLIN_FIELD_TYPE_OUTPUT, kotlinFieldTypeContent, 'utf8');
  console.log(`Generated: ${KOTLIN_FIELD_TYPE_OUTPUT}`);

  // Generate Kotlin ItemType
  ensureDir(KOTLIN_ITEM_TYPE_OUTPUT);
  const kotlinItemTypeContent = generateKotlinItemType(itemTypes);
  fs.writeFileSync(KOTLIN_ITEM_TYPE_OUTPUT, kotlinItemTypeContent, 'utf8');
  console.log(`Generated: ${KOTLIN_ITEM_TYPE_OUTPUT}`);

  console.log('\nCode generation complete!');
}

main();