All files / generator common.ts

100% Statements 187/187
96.29% Branches 130/135
100% Functions 32/32
100% Lines 175/175

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527                                                                                7x                     7x           425x 423x                                                     7x   48x 46x                           46x     28x 24x 17x             7x   10x 9x     7x 6x 2x             7x               7x                         32x 32x 32x 6x 4x                   9x   9x 9x     9x   9x 9x 9x 8x   9x   9x 9x 4x   9x 2x   9x 4x     9x 9x 4x 4x 7x   4x   9x 9x                       6x   8x     8x 8x 6x   8x 8x                           12x   9x     12x 4x 7x     7x 7x         8x 8x 8x 8x 18x         8x 1x     7x 12x   12x 12x 12x 18x   7x 7x                   6x 1x     5x   6x 6x 6x 12x   5x 5x             6x   9x 9x 8x   9x 9x                     5x   7x                         15x 15x   15x   15x     15x     15x 15x 15x     15x 3x       15x 15x 15x   15x 15x 15x 15x 2x   15x 15x 14x   15x   15x 5x 5x 5x     15x 5x 5x 9x   5x     15x 4x 4x         4x 4x 4x 3x   4x 3x 3x 5x   3x   4x       15x     15x 15x                 2x 1x   1x     2x                           36x   22x   2x   5x   1x   1x   2x   1x   1x     1x         1x                         61x 26x 27x         35x   4x   5x 2x   3x     6x         1x   3x   5x   3x   5x   2x   3x   3x     5x         1x      
/**
 * Common utilities for CV/Resume generators
 * Shared between English and Japanese CV generators
 */
 
import type { PaperSize } from '../types/config.js';
import type { CVMetadata } from '../types/metadata.js';
import type {
  CertificationEntry,
  CompetencyEntry,
  ContentBlock,
  EducationEntry,
  ExperienceEntry,
  LanguageEntry,
  MixedContentPart,
  ParsedSection,
  SectionContent,
  SkillEntry,
  SkillsOptions,
} from '../types/sections.js';
import { inlineMarkdownToHtml, markdownToHtml } from './markdown.js';
 
/**
 * Input for CV generation
 */
export interface CVInput {
  readonly metadata: CVMetadata;
  readonly sections: readonly ParsedSection[];
  /** Source line range of the frontmatter block (for sync scroll on cv-header) */
  readonly frontmatterSourceLines?: {
    readonly startLine: number;
    readonly endLine: number;
  };
}
 
/**
 * Page size dimensions in mm
 * CV uses portrait orientation (width < height)
 */
export const PAGE_SIZES: Record<PaperSize, { width: number; height: number }> =
  {
    a3: { width: 297, height: 420 },
    a4: { width: 210, height: 297 },
    b4: { width: 257, height: 364 },
    b5: { width: 182, height: 257 },
    letter: { width: 215.9, height: 279.4 },
  };
 
/**
 * Default number of columns for skills grid
 */
export const DEFAULT_SKILLS_COLUMNS = 3;
 
/**
 * Escape HTML special characters
 */
export function escapeHtml(text: string): string {
  if (text == null) return '';
  return text
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;');
}
 
/**
 * Date formatter interface for language-specific formatting
 */
export interface DateFormatter {
  formatDate(date: Date | undefined): string;
  formatEndDate(end: Date | 'present' | undefined): string;
}
 
/**
 * Locale options for language-specific formatting
 */
export interface LocaleOptions {
  dateFormatter: DateFormatter;
  itemSeparator: string;
}
 
/**
 * English date formatter
 */
export const enDateFormatter: DateFormatter = {
  formatDate(date: Date | undefined): string {
    if (!date) return '';
    const months = [
      'Jan',
      'Feb',
      'Mar',
      'Apr',
      'May',
      'Jun',
      'Jul',
      'Aug',
      'Sep',
      'Oct',
      'Nov',
      'Dec',
    ];
    return `${months[date.getMonth()]} ${date.getFullYear()}`;
  },
  formatEndDate(end: Date | 'present' | undefined): string {
    if (!end) return '';
    if (end === 'present') return 'Present';
    return this.formatDate(end);
  },
};
 
/**
 * Japanese date formatter
 */
export const jaDateFormatter: DateFormatter = {
  formatDate(date: Date | undefined): string {
    if (!date) return '';
    return `${date.getFullYear()}年${date.getMonth() + 1}月`;
  },
  formatEndDate(end: Date | 'present' | undefined): string {
    if (!end) return '';
    if (end === 'present') return '現在';
    return this.formatDate(end);
  },
};
 
/**
 * English locale options
 */
export const enLocale: LocaleOptions = {
  dateFormatter: enDateFormatter,
  itemSeparator: ', ',
};
 
/**
 * Japanese locale options
 */
export const jaLocale: LocaleOptions = {
  dateFormatter: jaDateFormatter,
  itemSeparator: ', ',
};
 
/**
 * Format date range using the provided formatter
 */
export function formatDateRange(
  start: Date | undefined,
  end: Date | 'present' | undefined,
  formatter: DateFormatter,
): string {
  const startStr = formatter.formatDate(start);
  const endStr = formatter.formatEndDate(end);
  if (startStr && endStr) return `${startStr} - ${endStr}`;
  if (startStr) return startStr;
  return '';
}
 
/**
 * Render education section
 */
export function renderEducation(
  entries: readonly EducationEntry[],
  formatter: DateFormatter,
): string {
  return entries
    .map((entry) => {
      const dateRange = formatDateRange(entry.start, entry.end, formatter);
      const sourceLineAttr = entry.sourceLines
        ? ` data-source-line="${entry.sourceLines.startLine}" data-source-end-line="${entry.sourceLines.endLine}"`
        : '';
      let html = `<div class="entry"${sourceLineAttr}>`;
 
      html += '<div class="entry-header">';
      html += `<span class="entry-title">${escapeHtml(entry.school)}</span>`;
      if (dateRange) {
        html += `<span class="entry-date">${escapeHtml(dateRange)}</span>`;
      }
      html += '</div>';
 
      const subtitleParts: string[] = [];
      if (entry.degree) {
        subtitleParts.push(escapeHtml(entry.degree));
      }
      if (entry.location) {
        subtitleParts.push(escapeHtml(entry.location));
      }
      if (subtitleParts.length > 0) {
        html += `<div class="entry-subtitle">${subtitleParts.join(' — ')}</div>`;
      }
 
      const nonEmptyDetails = entry.details?.filter((d) => d && d.trim()) ?? [];
      if (nonEmptyDetails.length > 0) {
        html += '<ul>';
        for (const detail of nonEmptyDetails) {
          html += `<li>${inlineMarkdownToHtml(detail)}</li>`;
        }
        html += '</ul>';
      }
      html += '</div>';
      return html;
    })
    .join('\n');
}
 
/**
 * Render certifications section
 */
export function renderCertifications(
  entries: readonly CertificationEntry[],
  formatter: DateFormatter,
): string {
  return entries
    .map((entry) => {
      const sourceLineAttr = entry.sourceLines
        ? ` data-source-line="${entry.sourceLines.startLine}" data-source-end-line="${entry.sourceLines.endLine}"`
        : '';
      let html = `<div class="cert-item"${sourceLineAttr}>• ${escapeHtml(entry.name)}`;
      if (entry.date) {
        html += ` (${escapeHtml(formatter.formatDate(entry.date))})`;
      }
      html += '</div>';
      return html;
    })
    .join('\n');
}
 
/**
 * Render skills section - supports grid and categorized formats
 */
export function renderSkills(
  entries: readonly SkillEntry[],
  options: SkillsOptions,
  locale: LocaleOptions,
): string {
  const isCategorized =
    options.format === 'categorized' ||
    entries.some(
      (e) => e.category && (e.description || (e.items && e.items.length > 0)),
    );
 
  if (isCategorized && entries.some((e) => e.category)) {
    return entries
      .filter((e) => e.category)
      .map((entry) => {
        const content =
          entry.description || (entry.items?.join(locale.itemSeparator) ?? '');
        return `<div class="skill-category">• <span class="skill-category-name">${escapeHtml(entry.category)}:</span> ${escapeHtml(content)}</div>`;
      })
      .join('\n');
  }
 
  const allItems: string[] = [];
  for (const entry of entries) {
    Eif (entry.items) {
      for (const item of entry.items) {
        allItems.push(item);
      }
    }
  }
 
  if (allItems.length === 0) {
    return '';
  }
 
  const columns = options.columns ?? DEFAULT_SKILLS_COLUMNS;
  const colsClass = columns === 3 ? 'skills-grid--cols-3' : '';
  const colsStyle =
    columns !== 3 ? `grid-template-columns: repeat(${columns}, 1fr);` : '';
  let html = `<div class="skills-grid ${colsClass}"${colsStyle ? ` style="${colsStyle}"` : ''}>`;
  for (const item of allItems) {
    html += `<div class="skill-item">• ${escapeHtml(item)}</div>`;
  }
  html += '</div>';
  return html;
}
 
/**
 * Render skills from list content as grid
 */
export function renderSkillsList(
  items: readonly string[],
  columns: number = DEFAULT_SKILLS_COLUMNS,
): string {
  if (items.length === 0) {
    return '';
  }
 
  const colsClass = columns === 3 ? 'skills-grid--cols-3' : '';
  const colsStyle =
    columns !== 3 ? `grid-template-columns: repeat(${columns}, 1fr);` : '';
  let html = `<div class="skills-grid ${colsClass}"${colsStyle ? ` style="${colsStyle}"` : ''}>`;
  for (const item of items) {
    html += `<div class="skill-item">• ${escapeHtml(item)}</div>`;
  }
  html += '</div>';
  return html;
}
 
/**
 * Render languages section
 */
export function renderLanguages(entries: readonly LanguageEntry[]): string {
  return entries
    .map((entry) => {
      let html = `<span class="lang-item">${escapeHtml(entry.language)}`;
      if (entry.level) {
        html += ` (${escapeHtml(entry.level)})`;
      }
      html += '</span>';
      return html;
    })
    .join(' • ');
}
 
/**
 * Render core competencies section
 */
export function renderCompetencies(
  entries: readonly CompetencyEntry[],
): string {
  return entries
    .map((entry) => {
      return `<div class="competency-entry"><span class="competency-header">${escapeHtml(entry.header)}:</span> ${inlineMarkdownToHtml(entry.description)}</div>`;
    })
    .join('\n');
}
 
/**
 * Render experience section
 */
export function renderExperience(
  entries: readonly ExperienceEntry[],
  formatter: DateFormatter,
  options?: { includeTeam?: boolean; includeProjects?: boolean },
): string {
  const includeTeam = options?.includeTeam ?? true;
  const includeProjects = options?.includeProjects ?? true;
 
  return entries
    .map((entry) => {
      const sourceLineAttr = entry.sourceLines
        ? ` data-source-line="${entry.sourceLines.startLine}" data-source-end-line="${entry.sourceLines.endLine}"`
        : '';
      let html = `<div class="entry"${sourceLineAttr}>`;
 
      // Company header
      html += '<div class="entry-header">';
      html += `<span class="entry-title">${escapeHtml(entry.company)}</span>`;
      html += '</div>';
 
      // Location
      if (entry.location) {
        html += `<div class="entry-location">${escapeHtml(entry.location)}</div>`;
      }
 
      // Roles
      for (const role of entry.roles) {
        const dateRange = formatDateRange(role.start, role.end, formatter);
        html += '<div class="role">';
 
        html += '<div class="role-header">';
        html += '<span class="role-title">';
        html += escapeHtml(role.title);
        if (includeTeam && role.team) {
          html += `<span class="role-team"> — ${escapeHtml(role.team)}</span>`;
        }
        html += '</span>';
        if (dateRange) {
          html += `<span class="entry-date">${escapeHtml(dateRange)}</span>`;
        }
        html += '</div>';
 
        if (role.summary && role.summary.length > 0) {
          html += '<div class="entry-summary">';
          html += role.summary.map((s) => inlineMarkdownToHtml(s)).join(' ');
          html += '</div>';
        }
 
        if (role.highlights && role.highlights.length > 0) {
          html += '<ul>';
          for (const highlight of role.highlights) {
            html += `<li>${inlineMarkdownToHtml(highlight)}</li>`;
          }
          html += '</ul>';
        }
 
        if (includeProjects && role.projects && role.projects.length > 0) {
          for (const project of role.projects) {
            const projDateRange = formatDateRange(
              project.start,
              project.end,
              formatter,
            );
            html += '<div class="project">';
            html += `<span class="project-name">${escapeHtml(project.name)}</span>`;
            if (projDateRange) {
              html += ` <span class="entry-date">(${escapeHtml(projDateRange)})</span>`;
            }
            if (project.bullets && project.bullets.length > 0) {
              html += '<ul>';
              for (const bullet of project.bullets) {
                html += `<li>${inlineMarkdownToHtml(bullet)}</li>`;
              }
              html += '</ul>';
            }
            html += '</div>';
          }
        }
 
        html += '</div>';
      }
 
      html += '</div>';
      return html;
    })
    .join('\n');
}
 
/**
 * Render mixed content part (legacy)
 */
function renderMixedContentPart(part: MixedContentPart): string {
  if (part.type === 'paragraph') {
    return markdownToHtml(part.text);
  }
  return (
    '<ul>' +
    part.items
      .map((item) => `<li>${inlineMarkdownToHtml(item)}</li>`)
      .join('\n') +
    '</ul>'
  );
}
 
/**
 * Render a single content block
 */
export function renderContentBlock(
  block: ContentBlock,
  _sectionId: string,
  locale: LocaleOptions,
): string {
  switch (block.type) {
    case 'markdown':
      return markdownToHtml(block.content);
    case 'education':
      return renderEducation(block.entries, locale.dateFormatter);
    case 'experience':
      return renderExperience(block.entries, locale.dateFormatter);
    case 'certifications':
      return renderCertifications(block.entries, locale.dateFormatter);
    case 'skills':
      return renderSkills(block.entries, block.options, locale);
    case 'competencies':
      return renderCompetencies(block.entries);
    case 'languages':
      return renderLanguages(block.entries);
    case 'table':
      return (
        '<ul>' +
        block.rows
          .map((row) => `<li>${inlineMarkdownToHtml(row.content)}</li>`)
          .join('\n') +
        '</ul>'
      );
    default:
      return '';
  }
}
 
/**
 * Render section content - supports both legacy and composite formats
 */
export function renderSectionContent(
  content: SectionContent,
  sectionId: string,
  locale: LocaleOptions,
): string {
  // Handle composite content (new format)
  if (content.type === 'composite') {
    return content.blocks
      .map((block) => renderContentBlock(block, sectionId, locale))
      .join('\n');
  }
 
  // Handle legacy content types
  switch (content.type) {
    case 'text':
      return markdownToHtml(content.text);
    case 'list':
      if (sectionId === 'skills') {
        return renderSkillsList(content.items);
      }
      return (
        '<ul>' +
        content.items
          .map((item) => `<li>${inlineMarkdownToHtml(item)}</li>`)
          .join('\n') +
        '</ul>'
      );
    case 'mixed':
      return content.parts.map(renderMixedContentPart).join('\n');
    case 'education':
      return renderEducation(content.entries, locale.dateFormatter);
    case 'experience':
      return renderExperience(content.entries, locale.dateFormatter);
    case 'certifications':
      return renderCertifications(content.entries, locale.dateFormatter);
    case 'skills':
      return renderSkills(content.entries, content.options, locale);
    case 'competencies':
      return renderCompetencies(content.entries);
    case 'languages':
      return renderLanguages(content.entries);
    case 'table':
      return (
        '<ul>' +
        content.rows
          .map((row) => `<li>${inlineMarkdownToHtml(row.content)}</li>`)
          .join('\n') +
        '</ul>'
      );
    default:
      return '';
  }
}