@parlajs/compiler 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +21 -2
  3. package/build/build.d.ts +18 -0
  4. package/build/build.d.ts.map +1 -0
  5. package/build/build.js +10 -0
  6. package/build/cli.d.ts +3 -0
  7. package/build/cli.d.ts.map +1 -0
  8. package/build/cli.js +8 -0
  9. package/build/command.d.ts +13 -0
  10. package/build/command.d.ts.map +1 -0
  11. package/build/command.js +156 -0
  12. package/build/compile/code.d.ts +13 -0
  13. package/build/compile/code.d.ts.map +1 -0
  14. package/build/compile/code.js +42 -0
  15. package/build/compile/compile.d.ts +11 -0
  16. package/build/compile/compile.d.ts.map +1 -0
  17. package/build/compile/compile.js +244 -0
  18. package/build/compile/error.d.ts +4 -0
  19. package/build/compile/error.d.ts.map +1 -0
  20. package/build/compile/error.js +3 -0
  21. package/build/compile/info.d.ts +49 -0
  22. package/build/compile/info.d.ts.map +1 -0
  23. package/build/compile/info.js +22 -0
  24. package/build/compile/scope.d.ts +7 -0
  25. package/build/compile/scope.d.ts.map +1 -0
  26. package/build/compile/scope.js +14 -0
  27. package/build/compile/single.d.ts +11 -0
  28. package/build/compile/single.d.ts.map +1 -0
  29. package/build/compile/single.js +36 -0
  30. package/build/compile/variants.d.ts +16 -0
  31. package/build/compile/variants.d.ts.map +1 -0
  32. package/build/compile/variants.js +48 -0
  33. package/build/config/checks.d.ts +21 -0
  34. package/build/config/checks.d.ts.map +1 -0
  35. package/build/config/checks.js +97 -0
  36. package/build/config/config.d.ts +71 -0
  37. package/build/config/config.d.ts.map +1 -0
  38. package/build/config/config.js +7 -0
  39. package/build/config/fallbacks.d.ts +6 -0
  40. package/build/config/fallbacks.d.ts.map +1 -0
  41. package/build/config/fallbacks.js +13 -0
  42. package/build/config/import.d.ts +31 -0
  43. package/build/config/import.d.ts.map +1 -0
  44. package/build/config/import.js +115 -0
  45. package/build/config/load.d.ts +13 -0
  46. package/build/config/load.d.ts.map +1 -0
  47. package/build/config/load.js +59 -0
  48. package/build/diagnostics.d.ts +31 -0
  49. package/build/diagnostics.d.ts.map +1 -0
  50. package/build/diagnostics.js +41 -0
  51. package/build/generate/checks.d.ts +9 -0
  52. package/build/generate/checks.d.ts.map +1 -0
  53. package/build/generate/checks.js +93 -0
  54. package/build/generate/chunk.d.ts +11 -0
  55. package/build/generate/chunk.d.ts.map +1 -0
  56. package/build/generate/chunk.js +57 -0
  57. package/build/generate/digits.d.ts +8 -0
  58. package/build/generate/digits.d.ts.map +1 -0
  59. package/build/generate/digits.js +57 -0
  60. package/build/generate/files.d.ts +7 -0
  61. package/build/generate/files.d.ts.map +1 -0
  62. package/build/generate/files.js +59 -0
  63. package/build/generate/locale.d.ts +21 -0
  64. package/build/generate/locale.d.ts.map +1 -0
  65. package/build/generate/locale.js +108 -0
  66. package/build/generate/modules.d.ts +27 -0
  67. package/build/generate/modules.d.ts.map +1 -0
  68. package/build/generate/modules.js +61 -0
  69. package/build/generate/namespace.d.ts +19 -0
  70. package/build/generate/namespace.d.ts.map +1 -0
  71. package/build/generate/namespace.js +65 -0
  72. package/build/generate/namespaces.d.ts +5 -0
  73. package/build/generate/namespaces.d.ts.map +1 -0
  74. package/build/generate/namespaces.js +41 -0
  75. package/build/generate/read.d.ts +21 -0
  76. package/build/generate/read.d.ts.map +1 -0
  77. package/build/generate/read.js +115 -0
  78. package/build/index.d.ts +9 -0
  79. package/build/index.d.ts.map +1 -0
  80. package/build/index.js +7 -0
  81. package/build/init/detect.d.ts +43 -0
  82. package/build/init/detect.d.ts.map +1 -0
  83. package/build/init/detect.js +69 -0
  84. package/build/init/init.d.ts +12 -0
  85. package/build/init/init.d.ts.map +1 -0
  86. package/build/init/init.js +126 -0
  87. package/build/options/date.d.ts +3 -0
  88. package/build/options/date.d.ts.map +1 -0
  89. package/build/options/date.js +77 -0
  90. package/build/options/literal.d.ts +10 -0
  91. package/build/options/literal.d.ts.map +1 -0
  92. package/build/options/literal.js +11 -0
  93. package/build/options/names.d.ts +5 -0
  94. package/build/options/names.d.ts.map +1 -0
  95. package/build/options/names.js +56 -0
  96. package/build/options/number.d.ts +3 -0
  97. package/build/options/number.d.ts.map +1 -0
  98. package/build/options/number.js +17 -0
  99. package/build/options/options.d.ts +7 -0
  100. package/build/options/options.d.ts.map +1 -0
  101. package/build/options/options.js +66 -0
  102. package/build/plurals.d.ts +6 -0
  103. package/build/plurals.d.ts.map +1 -0
  104. package/build/plurals.js +50 -0
  105. package/build/types/names.d.ts +9 -0
  106. package/build/types/names.d.ts.map +1 -0
  107. package/build/types/names.js +109 -0
  108. package/build/types/namespace.d.ts +17 -0
  109. package/build/types/namespace.d.ts.map +1 -0
  110. package/build/types/namespace.js +113 -0
  111. package/build/types/signature.d.ts +8 -0
  112. package/build/types/signature.d.ts.map +1 -0
  113. package/build/types/signature.js +87 -0
  114. package/build/vite.d.ts +9 -0
  115. package/build/vite.d.ts.map +1 -0
  116. package/build/vite.js +125 -0
  117. package/build/watch.d.ts +12 -0
  118. package/build/watch.d.ts.map +1 -0
  119. package/build/watch.js +93 -0
  120. package/package.json +84 -3
  121. package/src/build.ts +31 -0
  122. package/src/cli.ts +9 -0
  123. package/src/command.ts +195 -0
  124. package/src/compile/code.ts +51 -0
  125. package/src/compile/compile.ts +289 -0
  126. package/src/compile/error.ts +3 -0
  127. package/src/compile/info.ts +63 -0
  128. package/src/compile/scope.ts +14 -0
  129. package/src/compile/single.ts +46 -0
  130. package/src/compile/variants.ts +68 -0
  131. package/src/config/checks.ts +140 -0
  132. package/src/config/config.ts +83 -0
  133. package/src/config/fallbacks.ts +18 -0
  134. package/src/config/import.ts +146 -0
  135. package/src/config/load.ts +75 -0
  136. package/src/diagnostics.ts +98 -0
  137. package/src/generate/checks.ts +103 -0
  138. package/src/generate/chunk.ts +73 -0
  139. package/src/generate/digits.ts +74 -0
  140. package/src/generate/files.ts +83 -0
  141. package/src/generate/locale.ts +145 -0
  142. package/src/generate/modules.ts +94 -0
  143. package/src/generate/namespace.ts +119 -0
  144. package/src/generate/namespaces.ts +59 -0
  145. package/src/generate/read.ts +159 -0
  146. package/src/index.ts +27 -0
  147. package/src/init/detect.ts +103 -0
  148. package/src/init/init.ts +158 -0
  149. package/src/options/date.ts +87 -0
  150. package/src/options/literal.ts +21 -0
  151. package/src/options/names.ts +64 -0
  152. package/src/options/number.ts +20 -0
  153. package/src/options/options.ts +75 -0
  154. package/src/plurals.ts +68 -0
  155. package/src/types/names.ts +115 -0
  156. package/src/types/namespace.ts +148 -0
  157. package/src/types/signature.ts +111 -0
  158. package/src/vite.ts +143 -0
  159. package/src/watch.ts +115 -0
@@ -0,0 +1,103 @@
1
+ import { existsSync } from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ import { readPackageJson } from '../config/load.ts';
5
+
6
+ interface Framework {
7
+ readonly name: string;
8
+ readonly adapter: string;
9
+ /** The framework's Vite plugin, as `vite.config.ts` calls it. */
10
+ readonly plugin: string;
11
+ /** How a component loads a namespace. */
12
+ readonly load: string;
13
+ readonly docs: string;
14
+ }
15
+
16
+ const DOCS = 'https://parlajs.github.io/parla';
17
+
18
+ const adapter = (name: string, plugin: string): Framework => ({
19
+ name,
20
+ adapter: `@parlajs/${name.toLowerCase()}`,
21
+ plugin,
22
+ load: 'useParla([common])',
23
+ docs: `${DOCS}/adapters/${name.toLowerCase()}/`,
24
+ });
25
+
26
+ const FRAMEWORKS: ReadonlyArray<readonly [string, Framework]> = [
27
+ ['react', adapter('React', 'react()')],
28
+ ['vue', adapter('Vue', 'vue()')],
29
+ ['svelte', adapter('Svelte', 'svelte()')],
30
+ ['solid-js', adapter('Solid', 'solid()')],
31
+ ];
32
+
33
+ const CORE: Framework = {
34
+ name: 'no framework',
35
+ adapter: '@parlajs/core',
36
+ plugin: '',
37
+ load: 'await parla.load([common])',
38
+ docs: `${DOCS}/core/loading/`,
39
+ };
40
+
41
+ const ADD = {
42
+ pnpm: { add: 'pnpm add', dev: 'pnpm add -D' },
43
+ npm: { add: 'npm install', dev: 'npm install -D' },
44
+ yarn: { add: 'yarn add', dev: 'yarn add -D' },
45
+ bun: { add: 'bun add', dev: 'bun add -d' },
46
+ } as const;
47
+
48
+ type Manager = keyof typeof ADD;
49
+
50
+ const LOCKFILES: ReadonlyArray<readonly [string, Manager]> = [
51
+ ['pnpm-lock.yaml', 'pnpm'],
52
+ ['yarn.lock', 'yarn'],
53
+ ['bun.lock', 'bun'],
54
+ ['bun.lockb', 'bun'],
55
+ ['package-lock.json', 'npm'],
56
+ ];
57
+
58
+ export interface Project {
59
+ readonly dependencies: ReadonlySet<string>;
60
+ readonly framework: Framework;
61
+ readonly vite: boolean;
62
+ /** Whether Node reads the package's `.ts` files as ES modules. */
63
+ readonly esm: boolean;
64
+ readonly manager: Manager;
65
+ readonly add: (typeof ADD)[Manager];
66
+ }
67
+
68
+ const isManager = (name: string | undefined): name is Manager => name !== undefined && name in ADD;
69
+
70
+ /** The nearest lockfile's manager, as a workspace keeps one at its root; else the one running us. */
71
+ export function detectManager(cwd: string): Manager {
72
+ for (let dir = cwd; ; dir = path.dirname(dir)) {
73
+ const found = LOCKFILES.find(([file]) => existsSync(path.join(dir, file)));
74
+ if (found) {
75
+ return found[1];
76
+ }
77
+ if (path.dirname(dir) === dir) {
78
+ break;
79
+ }
80
+ }
81
+ const agent = process.env['npm_config_user_agent']?.split('/')[0];
82
+ return isManager(agent) ? agent : 'npm';
83
+ }
84
+
85
+ /** What `parla init` reads from the folder instead of asking. */
86
+ export function detectProject(cwd: string): Project | undefined {
87
+ const pkg = readPackageJson(cwd);
88
+ if (!pkg) {
89
+ return undefined;
90
+ }
91
+ const dependencies = new Set(
92
+ Object.keys({ ...pkg.peerDependencies, ...pkg.devDependencies, ...pkg.dependencies }),
93
+ );
94
+ const manager = detectManager(cwd);
95
+ return {
96
+ dependencies,
97
+ framework: FRAMEWORKS.find(([name]) => dependencies.has(name))?.[1] ?? CORE,
98
+ vite: dependencies.has('vite'),
99
+ esm: pkg.type === 'module',
100
+ manager,
101
+ add: ADD[manager],
102
+ };
103
+ }
@@ -0,0 +1,158 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ import { checkLocales } from '../config/checks.ts';
5
+ import { ConfigError } from '../config/config.ts';
6
+ import { CONFIG_FILES } from '../config/load.ts';
7
+
8
+ import { detectProject } from './detect.ts';
9
+ import type { Project } from './detect.ts';
10
+
11
+ interface InitOptions {
12
+ /** `mf2` or `icu`. */
13
+ readonly format?: string | undefined;
14
+ /** Comma-separated, the source locale first. */
15
+ readonly locales?: string | undefined;
16
+ /** The folder of the catalogs, relative to the config. */
17
+ readonly catalogs?: string | undefined;
18
+ }
19
+
20
+ const FORMATS: Record<string, { readonly package: string; readonly hello: string }> = {
21
+ mf2: { package: '@parlajs/format-mf2', hello: 'Hello, {$name}!' },
22
+ icu: { package: '@parlajs/format-icu', hello: 'Hello, {name}!' },
23
+ };
24
+
25
+ const OUT_DIR = 'src/parla';
26
+ const IGNORED = /^(?:\*\*\/|\/)?src\/parla\/?$/;
27
+
28
+ interface Choices {
29
+ /** The config's file name. */
30
+ readonly config: string;
31
+ readonly format: string;
32
+ readonly locales: ReadonlyArray<string>;
33
+ readonly catalogs: string;
34
+ }
35
+
36
+ /** The options, checked before anything is written. */
37
+ function choose(
38
+ { format = 'mf2', locales = 'en', catalogs = 'locales' }: InitOptions,
39
+ config: string,
40
+ ): Choices {
41
+ if (!Object.hasOwn(FORMATS, format)) {
42
+ throw new ConfigError(`--format is mf2 or icu, not "${format}"`);
43
+ }
44
+ const list = locales.split(',').map((l) => l.trim());
45
+ checkLocales({ locales: list, sourceLocale: list[0] ?? '', fallbacks: {} });
46
+ const dir = catalogs.replace(/\/+$/, '');
47
+ // The path lands in a string literal of the config.
48
+ if (!/^[\w.-][\w./-]*$/.test(dir) || dir.split('/').includes('..')) {
49
+ throw new ConfigError(`--catalogs takes a relative folder of letters, digits, ".", "_" or "-"`);
50
+ }
51
+ const inside = path.posix.relative(OUT_DIR, path.posix.normalize(dir));
52
+ if (inside !== '..' && !inside.startsWith('../')) {
53
+ throw new ConfigError(`--catalogs cannot be in ${OUT_DIR}, which holds generated files only`);
54
+ }
55
+ return { config, format, locales: list, catalogs: dir };
56
+ }
57
+
58
+ const configModule = ({ format, locales, catalogs }: Choices): string =>
59
+ `import { defineConfig } from '@parlajs/compiler';
60
+ import { ${format} } from '${FORMATS[format]?.package}';
61
+
62
+ export default defineConfig({
63
+ locales: [${locales.map((l) => `'${l}'`).join(', ')}],
64
+ sourceLocale: '${locales[0]}',
65
+ outDir: '${OUT_DIR}',
66
+ formats: { ${format} },
67
+ namespaces: { common: { format: '${format}', path: '${catalogs}/{locale}/common.json' } },
68
+ });
69
+ `;
70
+
71
+ /** Adds `src/parla/` to `.gitignore`, unless it is there. */
72
+ function ignore(cwd: string): string {
73
+ const file = path.join(cwd, '.gitignore');
74
+ const text = existsSync(file) ? readFileSync(file, 'utf8') : undefined;
75
+ if (text?.split(/\r?\n/).some((line) => IGNORED.test(line.trim()))) {
76
+ return '';
77
+ }
78
+ const before = text === undefined || text === '' || text.endsWith('\n') ? '' : '\n';
79
+ writeFileSync(file, `${text ?? ''}${before}${OUT_DIR}/\n`);
80
+ return ` ${text === undefined ? 'created' : 'updated'} .gitignore: ${OUT_DIR}/`;
81
+ }
82
+
83
+ /** Writes the config, a catalog per locale and the ignore line; never one that exists. */
84
+ function write(cwd: string, choices: Choices): Array<string> {
85
+ writeFileSync(path.join(cwd, choices.config), configModule(choices));
86
+ const lines = [` created ${choices.config}`];
87
+ const hello = `${JSON.stringify({ hello: FORMATS[choices.format]?.hello }, null, 2)}\n`;
88
+ for (const locale of choices.locales) {
89
+ const file = `${choices.catalogs}/${locale}/common.json`;
90
+ const target = path.join(cwd, file);
91
+ if (existsSync(target)) {
92
+ lines.push(` kept ${file}`);
93
+ } else {
94
+ mkdirSync(path.dirname(target), { recursive: true });
95
+ writeFileSync(target, hello);
96
+ lines.push(` created ${file}`);
97
+ }
98
+ }
99
+ return [...lines, ignore(cwd)].filter(Boolean);
100
+ }
101
+
102
+ /** What is left to the user: installing, the Vite plugin, the first call. */
103
+ function next(project: Project, { format }: Choices): Array<string> {
104
+ const { framework, add, dependencies } = project;
105
+ const missing = (list: Array<string>): string =>
106
+ list.filter((name) => !dependencies.has(name)).join(' ');
107
+ const runtime = missing([...new Set([framework.adapter, '@parlajs/core'])]);
108
+ const dev = missing(['@parlajs/compiler', FORMATS[format]?.package ?? '']);
109
+ const plugins = framework.plugin ? `parla(), ${framework.plugin}` : 'parla()';
110
+ return [
111
+ '',
112
+ 'Next',
113
+ ...(runtime ? [` ${add.add} ${runtime}`] : []),
114
+ ...(dev ? [` ${add.dev} ${dev}`] : []),
115
+ '',
116
+ ...(project.vite
117
+ ? [
118
+ ' vite.config.ts',
119
+ " import { parla } from '@parlajs/compiler/vite';",
120
+ ` plugins: [${plugins}]`,
121
+ ]
122
+ : [
123
+ ' parla build before the bundler',
124
+ ' parla build --watch beside its dev server',
125
+ ]),
126
+ ...(framework.name === 'Svelte'
127
+ ? [
128
+ ' svelte.config.js, for useParla',
129
+ ' compilerOptions: { experimental: { async: true } }',
130
+ ]
131
+ : []),
132
+ '',
133
+ " import { common } from './parla/namespaces/common.js';",
134
+ ` ${framework.load} → t.common.hello({ name: 'Ada' })`,
135
+ ` ${framework.docs}`,
136
+ ];
137
+ }
138
+
139
+ /** Runs `parla init` in `cwd`: what it wrote and what is left to do. */
140
+ export function init(cwd: string, options: InitOptions): Array<string> {
141
+ const project = detectProject(cwd);
142
+ if (!project) {
143
+ throw new ConfigError(`No package.json in ${cwd}: run parla init in the app's folder`);
144
+ }
145
+ // Node reads a `.ts` as CommonJS unless the package says `"type": "module"`.
146
+ const choices = choose(options, CONFIG_FILES[project.esm ? 0 : 1]);
147
+ const existing = CONFIG_FILES.find((name) => existsSync(path.join(cwd, name)));
148
+ if (existing) {
149
+ throw new ConfigError(`${existing} exists: edit it instead`);
150
+ }
151
+ const { framework, vite, manager } = project;
152
+ const header = [framework.name, vite ? 'Vite' : 'no Vite', manager, choices.format];
153
+ return [
154
+ `parla init: ${[...header, choices.locales.join(', ')].join(' · ')}`,
155
+ ...write(cwd, choices),
156
+ ...next(project, choices),
157
+ ];
158
+ }
@@ -0,0 +1,87 @@
1
+ import { chosen, literal } from './literal.ts';
2
+ import type { Options } from './literal.ts';
3
+ import { FIELDS, SETTINGS } from './names.ts';
4
+
5
+ const DATE_FIELDS: ReadonlySet<string> = new Set([
6
+ 'weekday',
7
+ 'day-weekday',
8
+ 'month-day',
9
+ 'month-day-weekday',
10
+ 'year-month-day',
11
+ 'year-month-day-weekday',
12
+ ]);
13
+
14
+ const LENGTHS: ReadonlySet<string> = new Set(['long', 'medium', 'short']);
15
+
16
+ const PRECISIONS = ['hour', 'minute', 'second'];
17
+
18
+ /** MF2's fields, length and precision, as `Intl`'s fields. */
19
+ function semanticFields(name: string, options: Options): Options {
20
+ const { fields, dateFields, length, dateLength, precision, timePrecision, timeZoneStyle } =
21
+ options;
22
+ const out: Options = {};
23
+ if (name !== 'time') {
24
+ const size = length ?? dateLength;
25
+ const isLong = size ? chosen('length', { value: size, allowed: LENGTHS }) : 'medium';
26
+ const asked = fields ?? dateFields;
27
+ const set = asked ? chosen('fields', { value: asked, allowed: DATE_FIELDS }) : 'year-month-day';
28
+ const months: Record<string, string> = { long: 'long', medium: 'short', short: 'numeric' };
29
+ for (const field of set.split('-')) {
30
+ let value = 'numeric';
31
+ if (field === 'month') {
32
+ value = months[isLong] ?? value;
33
+ } else if (field === 'weekday') {
34
+ value = isLong === 'long' ? 'long' : 'short';
35
+ }
36
+ out[field] = literal(value);
37
+ }
38
+ }
39
+ if (name !== 'date') {
40
+ const asked = precision ?? timePrecision;
41
+ const until = asked
42
+ ? chosen('precision', { value: asked, allowed: new Set(PRECISIONS) })
43
+ : 'minute';
44
+ for (const field of PRECISIONS.slice(0, PRECISIONS.indexOf(until) + 1)) {
45
+ out[field] = literal('numeric');
46
+ }
47
+ if (timeZoneStyle) {
48
+ out['timeZoneName'] = timeZoneStyle;
49
+ }
50
+ }
51
+ return out;
52
+ }
53
+
54
+ const STYLES = ['style', 'dateStyle', 'timeStyle'];
55
+
56
+ const SEMANTIC = ['fields', 'dateFields', 'precision', 'timePrecision', 'timeZoneStyle'];
57
+
58
+ export function dateOptions(name: string, options: Options): Options {
59
+ const out = Object.fromEntries(
60
+ Object.entries(options).filter(([k]) => SETTINGS.includes(k) || FIELDS.includes(k)),
61
+ );
62
+ if (SEMANTIC.some((k) => options[k])) {
63
+ const style = STYLES.find((k) => options[k]);
64
+ if (style) {
65
+ throw new Error(`${style} cannot be combined with fields or a precision: use length`);
66
+ }
67
+ return { ...out, ...semanticFields(name, options) };
68
+ }
69
+ const { style, length, dateLength, dateStyle, timeStyle } = options;
70
+ if (style || length || dateLength || dateStyle || timeStyle) {
71
+ const size = style ?? length;
72
+ if (name === 'time') {
73
+ return { ...out, timeStyle: size ?? literal('short') };
74
+ }
75
+ out['dateStyle'] = dateStyle ?? dateLength ?? size ?? literal('medium');
76
+ return name === 'date' ? out : { ...out, timeStyle: timeStyle ?? literal('short') };
77
+ }
78
+ if (FIELDS.some((k) => options[k])) {
79
+ return out;
80
+ }
81
+ // Settings alone: the runtime adds the default style only to a call without options.
82
+ return {
83
+ ...out,
84
+ ...(name === 'time' ? {} : { dateStyle: literal('medium') }),
85
+ ...(name === 'date' ? {} : { timeStyle: literal('short') }),
86
+ };
87
+ }
@@ -0,0 +1,21 @@
1
+ import type { Model } from 'messageformat';
2
+
3
+ export type Value = Model.Literal | Model.VariableRef;
4
+
5
+ export type Options = Record<string, Value>;
6
+
7
+ export const literal = (value: string): Model.Literal => ({ type: 'literal', value });
8
+
9
+ /** A literal's value, which must be one of `allowed`; a variable cannot name fields at build time. */
10
+ export function chosen(
11
+ name: string,
12
+ { value, allowed }: { value: Value; allowed: ReadonlySet<string> },
13
+ ): string {
14
+ if (value.type !== 'literal') {
15
+ throw new Error(`${name} must be a literal`);
16
+ }
17
+ if (!allowed.has(value.value)) {
18
+ throw new Error(`${name} must be one of ${[...allowed].join(', ')}, not "${value.value}"`);
19
+ }
20
+ return value.value;
21
+ }
@@ -0,0 +1,64 @@
1
+ const DIGITS = [
2
+ 'minimumIntegerDigits',
3
+ 'minimumSignificantDigits',
4
+ 'maximumSignificantDigits',
5
+ 'roundingIncrement',
6
+ 'roundingMode',
7
+ 'roundingPriority',
8
+ 'trailingZeroDisplay',
9
+ ];
10
+
11
+ const COMMON = ['signDisplay', 'useGrouping', 'numberingSystem', 'select', 'offset', 'scale'];
12
+
13
+ const FRACTION = ['minimumFractionDigits', 'maximumFractionDigits'];
14
+
15
+ const COMPACT = ['notation', 'compactDisplay'];
16
+
17
+ const FORMAT = [...COMMON, ...DIGITS, ...FRACTION, ...COMPACT];
18
+
19
+ export const SETTINGS = ['calendar', 'numberingSystem', 'timeZone', 'hour12', 'hourCycle'];
20
+
21
+ export const FIELDS = [
22
+ 'weekday',
23
+ 'era',
24
+ 'year',
25
+ 'month',
26
+ 'day',
27
+ 'dayPeriod',
28
+ 'hour',
29
+ 'minute',
30
+ 'second',
31
+ 'fractionalSecondDigits',
32
+ 'timeZoneName',
33
+ ];
34
+
35
+ export const NUMBERS: Readonly<Record<string, ReadonlySet<string>>> = {
36
+ number: new Set([...FORMAT, 'style']),
37
+ integer: new Set([...COMMON, 'minimumIntegerDigits', 'maximumSignificantDigits', ...COMPACT]),
38
+ currency: new Set([
39
+ ...FORMAT,
40
+ 'fractionDigits',
41
+ 'currency',
42
+ 'currencyDisplay',
43
+ 'currencySign',
44
+ 'unitDisplay',
45
+ ]),
46
+ percent: new Set([...FORMAT, 'currencySign']),
47
+ unit: new Set([...FORMAT, 'unit', 'unitDisplay', 'currencyDisplay']),
48
+ };
49
+
50
+ export const DATES: Readonly<Record<string, ReadonlySet<string>>> = {
51
+ date: new Set([...SETTINGS, ...FIELDS, 'style', 'length', 'fields']),
52
+ time: new Set([...SETTINGS, ...FIELDS, 'style', 'length', 'precision', 'timeZoneStyle']),
53
+ datetime: new Set([
54
+ ...SETTINGS,
55
+ ...FIELDS,
56
+ 'style',
57
+ 'dateStyle',
58
+ 'timeStyle',
59
+ 'dateFields',
60
+ 'dateLength',
61
+ 'timePrecision',
62
+ 'timeZoneStyle',
63
+ ]),
64
+ };
@@ -0,0 +1,20 @@
1
+ import { chosen, literal } from './literal.ts';
2
+ import type { Options } from './literal.ts';
3
+
4
+ const SELECTS: ReadonlySet<string> = new Set(['plural', 'cardinal', 'ordinal', 'exact']);
5
+
6
+ export function numberOptions(options: Options): Options {
7
+ const { fractionDigits, ...out } = options;
8
+ if (fractionDigits && !(fractionDigits.type === 'literal' && fractionDigits.value === 'auto')) {
9
+ out['minimumFractionDigits'] = fractionDigits;
10
+ out['maximumFractionDigits'] = fractionDigits;
11
+ }
12
+ const { select, useGrouping } = out;
13
+ if (select?.type === 'literal') {
14
+ chosen('select', { value: select, allowed: SELECTS });
15
+ }
16
+ if (useGrouping?.type === 'literal' && useGrouping.value === 'never') {
17
+ out['useGrouping'] = literal('false');
18
+ }
19
+ return out;
20
+ }
@@ -0,0 +1,75 @@
1
+ import type { Model } from 'messageformat';
2
+
3
+ import { dateOptions } from './date.ts';
4
+ import type { Options } from './literal.ts';
5
+ import { DATES, NUMBERS } from './names.ts';
6
+ import { numberOptions } from './number.ts';
7
+
8
+ // An `Intl` object per message made a build 7 times slower.
9
+ const checked = new Set<string>();
10
+
11
+ /** Throws what `Intl` would at run time, where every option is a literal. */
12
+ function check(name: string, options: Options): void {
13
+ const key = name + JSON.stringify(options);
14
+ if (checked.has(key)) {
15
+ return;
16
+ }
17
+ const given: Record<string, unknown> = {};
18
+ for (const [k, v] of Object.entries(options)) {
19
+ if (v.type !== 'literal') {
20
+ return;
21
+ }
22
+ given[k] = v.value === 'false' || v.value === 'true' ? v.value === 'true' : v.value;
23
+ }
24
+ if (Object.hasOwn(NUMBERS, name)) {
25
+ const style = name === 'number' || name === 'integer' ? {} : { style: name };
26
+ // oxlint-disable-next-line no-new -- only its errors matter
27
+ new Intl.NumberFormat('en', { ...given, ...style } as Intl.NumberFormatOptions);
28
+ } else {
29
+ // oxlint-disable-next-line no-new -- only its errors matter
30
+ new Intl.DateTimeFormat('en', given);
31
+ }
32
+ checked.add(key);
33
+ }
34
+
35
+ /** Which of a variable's options a function applied to it takes over. */
36
+ export function inheritedOptions(from: Model.FunctionRef, to: string): Options {
37
+ const own = NUMBERS[to];
38
+ const entries = Object.entries(from.options ?? {});
39
+ if (own && Object.hasOwn(NUMBERS, from.name)) {
40
+ // `offset` is a plural's: only its own `#` subtracts it.
41
+ return Object.fromEntries(
42
+ entries.filter(([k]) => own.has(k) && k !== 'style' && k !== 'offset'),
43
+ );
44
+ }
45
+ if (from.name === to) {
46
+ return Object.fromEntries(entries);
47
+ }
48
+ return Object.hasOwn(DATES, to) && Object.hasOwn(DATES, from.name)
49
+ ? Object.fromEntries(
50
+ entries.filter(([k]) => k === 'calendar' || k === 'timeZone' || k === 'hour12'),
51
+ )
52
+ : {};
53
+ }
54
+
55
+ /** A built-in function's options as `Intl` takes them; throws for one it cannot honour. */
56
+ export function intlOptions({ name, options = {} }: Model.FunctionRef): Options {
57
+ const known = NUMBERS[name] ?? DATES[name] ?? new Set<string>();
58
+ const entries = Object.entries(options).filter(([k]) => k !== 'u:id');
59
+ for (const [key] of entries) {
60
+ if (!known.has(key)) {
61
+ throw new Error(`:${name} has no option "${key}"`);
62
+ }
63
+ }
64
+ if (entries.length === 0 && name !== 'currency' && name !== 'unit') {
65
+ return {};
66
+ }
67
+ const given = Object.fromEntries(entries);
68
+ try {
69
+ const out = Object.hasOwn(NUMBERS, name) ? numberOptions(given) : dateOptions(name, given);
70
+ check(name, out);
71
+ return out;
72
+ } catch (error) {
73
+ throw new Error(`:${name}: ${(error as Error).message}`, { cause: error });
74
+ }
75
+ }
package/src/plurals.ts ADDED
@@ -0,0 +1,68 @@
1
+ import type { MessageInfo } from './compile/info.ts';
2
+
3
+ // Italian's `many` is for millions: asking every catalog for it would be noise.
4
+ const COMMON = Array.from({ length: 1000 }, (_, n) => n);
5
+ const CATEGORIES: ReadonlySet<string> = new Set(['zero', 'one', 'two', 'few', 'many', 'other']);
6
+
7
+ interface Rules {
8
+ readonly rules: Intl.PluralRules;
9
+ /** The numbers below 1000 of each category. */
10
+ readonly numbers: ReadonlyMap<string, ReadonlyArray<string>>;
11
+ }
12
+
13
+ const known = new Map<string, Rules | undefined>();
14
+
15
+ function makeRules(locale: string, type: Intl.PluralRuleType): Rules | undefined {
16
+ if (Intl.PluralRules.supportedLocalesOf(locale).length === 0) {
17
+ // It would answer for the machine's own locale.
18
+ return undefined;
19
+ }
20
+ const rules = new Intl.PluralRules(locale, { type });
21
+ return { rules, numbers: Map.groupBy(COMMON.map(String), (n) => rules.select(Number(n))) };
22
+ }
23
+
24
+ /** `undefined` for a locale whose plurals `Intl` does not know. */
25
+ function rulesOf(locale: string, type: Intl.PluralRuleType): Rules | undefined {
26
+ const key = `${locale} ${type}`;
27
+ if (!known.has(key)) {
28
+ known.set(key, makeRules(locale, type));
29
+ }
30
+ return known.get(key);
31
+ }
32
+
33
+ const same = new Map<string, boolean>();
34
+
35
+ /** Whether a message's plurals read the same under both locales' rules. */
36
+ export function samePlurals(a: string, b: string): boolean {
37
+ const key = `${a} ${b}`;
38
+ let answer = same.get(key);
39
+ if (answer === undefined) {
40
+ answer = (['cardinal', 'ordinal'] as const).every((type) => {
41
+ const [one, two] = [rulesOf(a, type)?.rules, rulesOf(b, type)?.rules];
42
+ return (
43
+ one !== undefined &&
44
+ two !== undefined &&
45
+ [...COMMON, 0.1, 0.5, 1.5, 2.5, 1e6].every((n) => one.select(n) === two.select(n))
46
+ );
47
+ });
48
+ same.set(key, answer);
49
+ }
50
+ return answer;
51
+ }
52
+
53
+ const hasCategory = (keys: ReadonlySet<string>): boolean =>
54
+ [...keys].some((key) => CATEGORIES.has(key));
55
+
56
+ /** The categories `locale` uses for everyday numbers that a plural leaves to its catch-all. */
57
+ export function missingPlurals(locale: string, { plurals }: MessageInfo): Array<string> {
58
+ const missing = new Set<string>();
59
+ // A catch-all alone is a choice: Italian's "file" is its own plural.
60
+ for (const { type, keys } of plurals.filter((p) => hasCategory(p.keys))) {
61
+ for (const [category, numbers] of rulesOf(locale, type)?.numbers ?? []) {
62
+ if (category !== 'other' && !keys.has(category) && !numbers.every((n) => keys.has(n))) {
63
+ missing.add(category);
64
+ }
65
+ }
66
+ }
67
+ return [...missing];
68
+ }