Skip to content

An open source design system that's fully customizable and agent ready

TypeScript
3.6 KB
Raw Blame
// Copyright (c) Meta Platforms, Inc. and affiliates.

/**
 * Generates the languages whose stand-alone month names start with a capital.
 *
 * CLDR records capitalization per context in `contextTransforms`: a language
 * whose `month-standalone-except-narrow` stand-alone value is
 * `titlecase-firstword` capitalizes a month name that stands alone, such as a
 * calendar heading, though `Intl.DateTimeFormat` formats it for running text.
 * The runtime package consumes only the checked-in TypeScript output; raw CLDR
 * data stays in root development dependencies and is read only by this script.
 */

import fs from 'node:fs';
import path from 'node:path';
import {createRequire} from 'node:module';
import {fileURLToPath, pathToFileURL} from 'node:url';
import {format, resolveConfig} from 'prettier';
import {getShippedLocales} from './generate-cldr-weekdays.mjs';

const require = createRequire(import.meta.url);
const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = path.resolve(SCRIPT_DIR, '..');
const OUTPUT_FILE = path.join(
  REPO_ROOT,
  'packages',
  'core',
  'src',
  'utils',
  'standaloneMonthCapitals.generated.ts',
);
const CLDR_MISC_ROOT = path.dirname(
  require.resolve('cldr-misc-full/package.json'),
);
const CLDR_MISC_PACKAGE = JSON.parse(
  fs.readFileSync(path.join(CLDR_MISC_ROOT, 'package.json'), 'utf8'),
);

/** Whether CLDR titlecases a stand-alone month name in `language`. */
export function hasStandaloneMonthCapital(language) {
  const file = path.join(
    CLDR_MISC_ROOT,
    'main',
    language,
    'contextTransforms.json',
  );
  if (!fs.existsSync(file)) {
    return false;
  }
  const transforms = JSON.parse(fs.readFileSync(file, 'utf8')).main?.[language]
    ?.contextTransforms;
  return (
    transforms?.['month-standalone-except-narrow']?.['stand-alone'] ===
    'titlecase-firstword'
  );
}

/** The shipped languages that capitalize a stand-alone month name, sorted. */
export function generateMonthCapitalLanguages() {
  const languages = new Set(
    getShippedLocales().map(locale => new Intl.Locale(locale).language),
  );
  return [...languages].filter(hasStandaloneMonthCapital).sort();
}

export async function renderGeneratedFile() {
  const languages = generateMonthCapitalLanguages();
  const source = `// Copyright (c) Meta Platforms, Inc. and affiliates.\n\n/**\n * @generated by scripts/generate-cldr-month-capitals.mjs from Unicode CLDR ${CLDR_MISC_PACKAGE.version}.\n * Do not edit by hand. Run \`pnpm generate:cldr-month-capitals\` instead.\n */\n\n/** Shipped languages whose stand-alone month names start with a capital. */\nexport const standaloneMonthCapitalLanguages: ReadonlySet<string> = new Set(${JSON.stringify(languages)});\n`;
  const prettierConfig = await resolveConfig(OUTPUT_FILE);
  return format(source, {...prettierConfig, filepath: OUTPUT_FILE});
}

async function main() {
  const check = process.argv.slice(2).includes('--check');
  const expected = await renderGeneratedFile();
  if (check) {
    const actual = fs.existsSync(OUTPUT_FILE)
      ? fs.readFileSync(OUTPUT_FILE, 'utf8')
      : '';
    if (actual !== expected) {
      console.error(
        '✗ Calendar CLDR month capitalization data is stale. Run `pnpm generate:cldr-month-capitals` and commit the result.',
      );
      process.exitCode = 1;
      return;
    }
    console.log('✓ Calendar CLDR month capitalization data is current');
    return;
  }
  fs.writeFileSync(OUTPUT_FILE, expected);
  console.log(`Generated ${path.relative(REPO_ROOT, OUTPUT_FILE)}`);
}

if (
  process.argv[1] &&
  import.meta.url === pathToFileURL(process.argv[1]).href
) {
  await main();
}