@parlajs/compiler 0.0.0-stage → 0.0.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 (171) 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/compile.d.ts +61 -0
  34. package/build/compile.d.ts.map +1 -0
  35. package/build/compile.js +385 -0
  36. package/build/config/checks.d.ts +21 -0
  37. package/build/config/checks.d.ts.map +1 -0
  38. package/build/config/checks.js +97 -0
  39. package/build/config/config.d.ts +71 -0
  40. package/build/config/config.d.ts.map +1 -0
  41. package/build/config/config.js +7 -0
  42. package/build/config/fallbacks.d.ts +6 -0
  43. package/build/config/fallbacks.d.ts.map +1 -0
  44. package/build/config/fallbacks.js +13 -0
  45. package/build/config/import.d.ts +31 -0
  46. package/build/config/import.d.ts.map +1 -0
  47. package/build/config/import.js +115 -0
  48. package/build/config/load.d.ts +13 -0
  49. package/build/config/load.d.ts.map +1 -0
  50. package/build/config/load.js +59 -0
  51. package/build/config.d.ts +77 -0
  52. package/build/config.d.ts.map +1 -0
  53. package/build/config.js +223 -0
  54. package/build/diagnostics.d.ts +31 -0
  55. package/build/diagnostics.d.ts.map +1 -0
  56. package/build/diagnostics.js +41 -0
  57. package/build/generate/checks.d.ts +9 -0
  58. package/build/generate/checks.d.ts.map +1 -0
  59. package/build/generate/checks.js +93 -0
  60. package/build/generate/chunk.d.ts +11 -0
  61. package/build/generate/chunk.d.ts.map +1 -0
  62. package/build/generate/chunk.js +57 -0
  63. package/build/generate/digits.d.ts +8 -0
  64. package/build/generate/digits.d.ts.map +1 -0
  65. package/build/generate/digits.js +57 -0
  66. package/build/generate/files.d.ts +7 -0
  67. package/build/generate/files.d.ts.map +1 -0
  68. package/build/generate/files.js +59 -0
  69. package/build/generate/locale.d.ts +21 -0
  70. package/build/generate/locale.d.ts.map +1 -0
  71. package/build/generate/locale.js +108 -0
  72. package/build/generate/modules.d.ts +27 -0
  73. package/build/generate/modules.d.ts.map +1 -0
  74. package/build/generate/modules.js +61 -0
  75. package/build/generate/namespace.d.ts +19 -0
  76. package/build/generate/namespace.d.ts.map +1 -0
  77. package/build/generate/namespace.js +65 -0
  78. package/build/generate/namespaces.d.ts +5 -0
  79. package/build/generate/namespaces.d.ts.map +1 -0
  80. package/build/generate/namespaces.js +41 -0
  81. package/build/generate/read.d.ts +21 -0
  82. package/build/generate/read.d.ts.map +1 -0
  83. package/build/generate/read.js +115 -0
  84. package/build/index.d.ts +9 -0
  85. package/build/index.d.ts.map +1 -0
  86. package/build/index.js +7 -0
  87. package/build/init/detect.d.ts +43 -0
  88. package/build/init/detect.d.ts.map +1 -0
  89. package/build/init/detect.js +69 -0
  90. package/build/init/init.d.ts +12 -0
  91. package/build/init/init.d.ts.map +1 -0
  92. package/build/init/init.js +126 -0
  93. package/build/options/date.d.ts +3 -0
  94. package/build/options/date.d.ts.map +1 -0
  95. package/build/options/date.js +77 -0
  96. package/build/options/literal.d.ts +10 -0
  97. package/build/options/literal.d.ts.map +1 -0
  98. package/build/options/literal.js +11 -0
  99. package/build/options/names.d.ts +5 -0
  100. package/build/options/names.d.ts.map +1 -0
  101. package/build/options/names.js +56 -0
  102. package/build/options/number.d.ts +3 -0
  103. package/build/options/number.d.ts.map +1 -0
  104. package/build/options/number.js +17 -0
  105. package/build/options/options.d.ts +7 -0
  106. package/build/options/options.d.ts.map +1 -0
  107. package/build/options/options.js +66 -0
  108. package/build/options.d.ts +9 -0
  109. package/build/options.d.ts.map +1 -0
  110. package/build/options.js +214 -0
  111. package/build/plurals.d.ts +6 -0
  112. package/build/plurals.d.ts.map +1 -0
  113. package/build/plurals.js +50 -0
  114. package/build/types/names.d.ts +9 -0
  115. package/build/types/names.d.ts.map +1 -0
  116. package/build/types/names.js +109 -0
  117. package/build/types/namespace.d.ts +17 -0
  118. package/build/types/namespace.d.ts.map +1 -0
  119. package/build/types/namespace.js +113 -0
  120. package/build/types/signature.d.ts +8 -0
  121. package/build/types/signature.d.ts.map +1 -0
  122. package/build/types/signature.js +87 -0
  123. package/build/types.d.ts +25 -0
  124. package/build/types.d.ts.map +1 -0
  125. package/build/types.js +250 -0
  126. package/build/vite.d.ts +9 -0
  127. package/build/vite.d.ts.map +1 -0
  128. package/build/vite.js +125 -0
  129. package/build/watch.d.ts +12 -0
  130. package/build/watch.d.ts.map +1 -0
  131. package/build/watch.js +93 -0
  132. package/package.json +84 -3
  133. package/src/build.ts +31 -0
  134. package/src/cli.ts +9 -0
  135. package/src/command.ts +195 -0
  136. package/src/compile/code.ts +51 -0
  137. package/src/compile/compile.ts +289 -0
  138. package/src/compile/error.ts +3 -0
  139. package/src/compile/info.ts +63 -0
  140. package/src/compile/scope.ts +14 -0
  141. package/src/compile/single.ts +46 -0
  142. package/src/compile/variants.ts +68 -0
  143. package/src/config/checks.ts +140 -0
  144. package/src/config/config.ts +83 -0
  145. package/src/config/fallbacks.ts +18 -0
  146. package/src/config/import.ts +146 -0
  147. package/src/config/load.ts +75 -0
  148. package/src/diagnostics.ts +98 -0
  149. package/src/generate/checks.ts +103 -0
  150. package/src/generate/chunk.ts +73 -0
  151. package/src/generate/digits.ts +74 -0
  152. package/src/generate/files.ts +83 -0
  153. package/src/generate/locale.ts +145 -0
  154. package/src/generate/modules.ts +94 -0
  155. package/src/generate/namespace.ts +119 -0
  156. package/src/generate/namespaces.ts +59 -0
  157. package/src/generate/read.ts +159 -0
  158. package/src/index.ts +27 -0
  159. package/src/init/detect.ts +103 -0
  160. package/src/init/init.ts +158 -0
  161. package/src/options/date.ts +87 -0
  162. package/src/options/literal.ts +21 -0
  163. package/src/options/names.ts +64 -0
  164. package/src/options/number.ts +20 -0
  165. package/src/options/options.ts +75 -0
  166. package/src/plurals.ts +68 -0
  167. package/src/types/names.ts +115 -0
  168. package/src/types/namespace.ts +148 -0
  169. package/src/types/signature.ts +111 -0
  170. package/src/vite.ts +143 -0
  171. package/src/watch.ts +115 -0
@@ -0,0 +1,108 @@
1
+ import { compileMessage } from '../compile/compile.js';
2
+ import { CompileError } from '../compile/error.js';
3
+ import { ModuleScope } from '../compile/scope.js';
4
+ import { fallbackChain } from '../config/fallbacks.js';
5
+ import { missingPlurals, samePlurals } from '../plurals.js';
6
+ import { inherits, mismatches, omissions } from './checks.js';
7
+ import { emitFactory, treeOf } from './chunk.js';
8
+ import { HEADER } from './modules.js';
9
+ /** The entry a locale compiles for `key`: its own, else the first of its chain that has it. */
10
+ function entryFor(key, { config, locale, own, catalogs, chain, gapsAllowed, reported, at }) {
11
+ const entry = own.get(key);
12
+ if (entry) {
13
+ return { entry, from: locale };
14
+ }
15
+ // the chain ends at the source locale, which has every key
16
+ const from = chain.find((l) => catalogs.get(l)?.has(key)) ?? config.sourceLocale;
17
+ if (!gapsAllowed && !reported.has(locale) && !reported.has(`${locale}\0${key}`)) {
18
+ at({
19
+ level: 'warning',
20
+ code: 'missing-translation',
21
+ key,
22
+ message: `untranslated, using "${from}"`,
23
+ });
24
+ }
25
+ return { entry: catalogs.get(from)?.get(key), from };
26
+ }
27
+ /** A translation's params, markup and plurals against the source message's. */
28
+ function compare(key, { compiled, ctx }) {
29
+ const { config, locale, own, sourceInfo, at } = ctx;
30
+ // A source message that fails to compile is reported for the source locale.
31
+ const ref = sourceInfo.get(key)?.info;
32
+ if (locale !== config.sourceLocale && own.has(key) && ref) {
33
+ for (const message of mismatches(compiled.info, ref)) {
34
+ at({ level: 'error', code: 'param-mismatch', key, message });
35
+ }
36
+ for (const message of omissions(compiled.info, ref)) {
37
+ at({ level: 'warning', code: 'missing-param', key, message });
38
+ }
39
+ }
40
+ const missing = own.has(key) ? missingPlurals(locale, compiled.info) : [];
41
+ if (missing.length > 0) {
42
+ const message = `has no plural form for ${missing.join(', ')}, which "${locale}" uses`;
43
+ at({ level: 'warning', code: 'missing-plural', key, message });
44
+ }
45
+ }
46
+ /** One locale's chunk of a namespace: every source key, translated or borrowed. */
47
+ export function compileLocale(locale, input) {
48
+ const { config, ns, catalogs, reported, sourceInfo, diagnostics } = input;
49
+ const source = catalogs.get(config.sourceLocale) ?? new Map();
50
+ const own = catalogs.get(locale) ?? new Map();
51
+ const at = (d) => {
52
+ diagnostics.push({ ...d, namespace: ns.name, locale, file: ns.file(locale) });
53
+ };
54
+ const ctx = {
55
+ ...input,
56
+ locale,
57
+ own,
58
+ chain: fallbackChain(config, locale),
59
+ gapsAllowed: inherits(config, locale),
60
+ at,
61
+ };
62
+ // A source that failed to parse may have the key.
63
+ if (!reported.has(config.sourceLocale)) {
64
+ for (const key of own.keys()) {
65
+ if (source.has(key) || reported.has(`${config.sourceLocale}\0${key}`)) {
66
+ continue;
67
+ }
68
+ at({
69
+ level: 'warning',
70
+ code: 'unknown-key',
71
+ key,
72
+ message: `not in "${config.sourceLocale}", so dropped: add it there or remove it`,
73
+ });
74
+ }
75
+ }
76
+ const scope = new ModuleScope();
77
+ const messages = [];
78
+ for (const [key, srcEntry] of source) {
79
+ const { entry = srcEntry, from } = entryFor(key, ctx);
80
+ let compiled;
81
+ try {
82
+ compiled = compileMessage(entry.model, {
83
+ scope,
84
+ custom: config.functions,
85
+ pluralsOf: from === locale || samePlurals(from, locale) ? undefined : from,
86
+ });
87
+ }
88
+ catch (error) {
89
+ if (!(error instanceof CompileError)) {
90
+ throw error;
91
+ }
92
+ // borrowed text is reported for the locale that wrote it
93
+ if (from === locale) {
94
+ at({ level: 'error', code: 'invalid-syntax', key, message: error.message });
95
+ }
96
+ continue;
97
+ }
98
+ if (locale === config.sourceLocale) {
99
+ sourceInfo.set(key, { info: compiled.info, source: srcEntry.source });
100
+ }
101
+ compare(key, { compiled, ctx });
102
+ // A message that never reads `p` takes no default, so a call without params allocates nothing.
103
+ const param = /\bp\b/.test(compiled.body) ? 'p = {}' : 'p';
104
+ messages.push([key, `(${param}) => ${compiled.body}`]);
105
+ }
106
+ const consts = scope.consts.length > 0 ? `${scope.consts.join('\n')}\n` : '';
107
+ return `${HEADER}${consts}export default ${emitFactory(treeOf(messages))};\n`;
108
+ }
@@ -0,0 +1,27 @@
1
+ import type { MessageInfo } from '../compile/info.ts';
2
+ import type { ResolvedConfig } from '../config/config.ts';
3
+ export declare const MARK = "// Generated by parla. Do not edit.\n";
4
+ export declare const HEADER = "// Generated by parla. Do not edit.\n/* eslint-disable */\n/* oxlint-disable */\n";
5
+ /**
6
+ * The namespace object's type: its messages, a kind that hands them the instance's node type when
7
+ * they have markup, and the locales it was built for.
8
+ */
9
+ export declare function namespaceDeclaration(config: ResolvedConfig, { namespace, iface, exported, messages, }: {
10
+ namespace: string;
11
+ iface: string;
12
+ exported: string;
13
+ messages: Map<string, {
14
+ info: MessageInfo;
15
+ source: string;
16
+ }>;
17
+ }): string;
18
+ /** What an app imports to load a namespace: its name and one chunk loader per locale. */
19
+ export declare function namespaceModule(namespace: string, { exported, locales }: {
20
+ exported: string;
21
+ locales: ReadonlyArray<string>;
22
+ }): string;
23
+ /** `catalog.js`, which an app passes to `createParla`. */
24
+ export declare function catalogModule(config: ResolvedConfig): string;
25
+ /** `catalog.d.ts`: the locales, and the registries it adds to the runtime. */
26
+ export declare function catalogDeclaration(config: ResolvedConfig): string;
27
+ //# sourceMappingURL=modules.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"modules.d.ts","sourceRoot":"","sources":["../../src/generate/modules.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAM1D,eAAO,MAAM,IAAI,0CAA0C,CAAC;AAG5D,eAAO,MAAM,MAAM,sFAAwD,CAAC;AAW5E;;;GAGG;AACH,wBAAgB,oBAAoB,CAClC,MAAM,EAAE,cAAc,EACtB,EACE,SAAS,EACT,KAAK,EACL,QAAQ,EACR,QAAQ,GACT,EAAE;IACD,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,GAAG,CAAC,MAAM,EAAE;QAAE,IAAI,EAAE,WAAW,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CAC9D,GACA,MAAM,CAcR;AAED,yFAAyF;AACzF,wBAAgB,eAAe,CAC7B,SAAS,EAAE,MAAM,EACjB,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,aAAa,CAAC,MAAM,CAAC,CAAA;CAAE,GAC1E,MAAM,CAQR;AAED,0DAA0D;AAC1D,wBAAgB,aAAa,CAAC,MAAM,EAAE,cAAc,GAAG,MAAM,CAc5D;AAED,8EAA8E;AAC9E,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,cAAc,GAAG,MAAM,CAOjE"}
@@ -0,0 +1,61 @@
1
+ import { fallbackChain } from '../config/fallbacks.js';
2
+ import { namespaceTypes } from '../types/namespace.js';
3
+ import { groupSeparator, hasPlainDigits } from './digits.js';
4
+ export const MARK = '// Generated by parla. Do not edit.\n';
5
+ // Not all linters skip what `.gitignore` lists, and oxlint may be set to ignore ESLint's directives.
6
+ export const HEADER = `${MARK}/* eslint-disable */\n/* oxlint-disable */\n`;
7
+ /** One registry augmentation, or nothing when it has no member. */
8
+ function registry(name, keys) {
9
+ const members = keys.map((k) => ` ${JSON.stringify(k)}: true;\n`).join('');
10
+ return members ? ` interface ${name} {\n${members} }\n` : '';
11
+ }
12
+ const localeType = (config) => config.locales.map((l) => JSON.stringify(l)).join(' | ');
13
+ /**
14
+ * The namespace object's type: its messages, a kind that hands them the instance's node type when
15
+ * they have markup, and the locales it was built for.
16
+ */
17
+ export function namespaceDeclaration(config, { namespace, iface, exported, messages, }) {
18
+ const types = namespaceTypes(messages, { name: iface, defaults: new Set(config.markup) });
19
+ const kind = iface.replace(/Messages$/, 'Kind');
20
+ const imported = ['Namespace', 'NamespaceKind', ...(types.usesText ? ['Text'] : [])];
21
+ return `${HEADER}import type { ${imported.join(', ')} } from '${config.runtime}';
22
+
23
+ ${types.code}
24
+
25
+ export interface ${kind} extends NamespaceKind {
26
+ readonly messages: ${iface}${types.generic ? "<this['node']>" : ''};
27
+ }
28
+
29
+ export declare const ${exported}: Namespace<${JSON.stringify(namespace)}, ${kind}, ${localeType(config)}>;
30
+ `;
31
+ }
32
+ /** What an app imports to load a namespace: its name and one chunk loader per locale. */
33
+ export function namespaceModule(namespace, { exported, locales }) {
34
+ const loaders = locales
35
+ .map((l) => ` ${JSON.stringify(l)}: () => import(${JSON.stringify(`../messages/${l}/${namespace}.js`)}),`)
36
+ .join('\n');
37
+ return `${HEADER}export const ${exported} = {\n name: ${JSON.stringify(namespace)},\n load: {\n${loaders}\n },\n};\n`;
38
+ }
39
+ /** `catalog.js`, which an app passes to `createParla`. */
40
+ export function catalogModule(config) {
41
+ const fallbacks = Object.fromEntries(config.locales.map((l) => [l, fallbackChain(config, l)]));
42
+ const plainDigits = Object.fromEntries(config.locales
43
+ .filter((l) => [l, ...(fallbacks[l] ?? [])].every((tag) => hasPlainDigits(tag)))
44
+ .map((l) => [l, groupSeparator(l, fallbacks[l] ?? []) ?? true]));
45
+ const members = Object.entries({
46
+ locales: config.locales,
47
+ sourceLocale: config.sourceLocale,
48
+ fallbacks,
49
+ plainDigits,
50
+ }).map(([key, value]) => ` ${key}: ${JSON.stringify(value)},\n`);
51
+ return `${HEADER}export const catalog = {\n${members.join('')}};\n`;
52
+ }
53
+ /** `catalog.d.ts`: the locales, and the registries it adds to the runtime. */
54
+ export function catalogDeclaration(config) {
55
+ const registries = [
56
+ registry('LocaleRegistry', config.locales),
57
+ registry('FunctionRegistry', Object.keys(config.functions)),
58
+ registry('MarkupRegistry', config.markup),
59
+ ].join('');
60
+ return `${HEADER}import type { Catalog } from '${config.runtime}';\n\nexport type Locale = ${localeType(config)};\n\nexport declare const catalog: Catalog & { readonly locales: readonly Locale[]; readonly sourceLocale: ${JSON.stringify(config.sourceLocale)} };\n\ndeclare module '${config.runtime}' {\n${registries}}\n`;
61
+ }
@@ -0,0 +1,19 @@
1
+ import type { ResolvedConfig, ResolvedNamespace } from '../config/config.ts';
2
+ import type { Diagnostic } from '../diagnostics.ts';
3
+ import type { CatalogText } from './read.ts';
4
+ /** What a build collects: its diagnostics, and the files to write by path under `outDir`. */
5
+ export interface Output {
6
+ readonly diagnostics: Array<Diagnostic>;
7
+ readonly files: Map<string, string>;
8
+ }
9
+ /** A namespace's chunk per locale, its object and its types, from its catalogs' `texts` per locale. */
10
+ export declare function buildNamespace(ns: ResolvedNamespace, { config, names: { iface, exported }, texts, out, }: {
11
+ config: ResolvedConfig;
12
+ names: {
13
+ readonly iface: string;
14
+ readonly exported: string;
15
+ };
16
+ texts: ReadonlyArray<CatalogText>;
17
+ out: Output;
18
+ }): void;
19
+ //# sourceMappingURL=namespace.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"namespace.d.ts","sourceRoot":"","sources":["../../src/generate/namespace.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAiB,cAAc,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAC5F,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAMpD,OAAO,KAAK,EAAE,WAAW,EAAS,MAAM,WAAW,CAAC;AAEpD,6FAA6F;AAC7F,MAAM,WAAW,MAAM;IACrB,QAAQ,CAAC,WAAW,EAAE,KAAK,CAAC,UAAU,CAAC,CAAC;IACxC,QAAQ,CAAC,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACrC;AAiDD,uGAAuG;AACvG,wBAAgB,cAAc,CAC5B,EAAE,EAAE,iBAAiB,EACrB,EACE,MAAM,EACN,KAAK,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,EAC1B,KAAK,EACL,GAAG,GACJ,EAAE;IACD,MAAM,EAAE,cAAc,CAAC;IACvB,KAAK,EAAE;QAAE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC;IAC7D,KAAK,EAAE,aAAa,CAAC,WAAW,CAAC,CAAC;IAClC,GAAG,EAAE,MAAM,CAAC;CACb,GACA,IAAI,CAuCN"}
@@ -0,0 +1,65 @@
1
+ import path from 'node:path';
2
+ import { inherits } from './checks.js';
3
+ import { compileLocale } from './locale.js';
4
+ import { namespaceDeclaration, namespaceModule } from './modules.js';
5
+ import { readCatalog } from './read.js';
6
+ function readCatalogs(ns, { config, adapter, texts, diagnostics, }) {
7
+ const catalogs = new Map();
8
+ const reported = new Set();
9
+ for (const [index, locale] of config.locales.entries()) {
10
+ const read = readCatalog(ns, {
11
+ locale,
12
+ adapter,
13
+ text: texts[index],
14
+ report: (d) => {
15
+ reported.add(d.key ? `${locale}\0${d.key}` : locale);
16
+ diagnostics.push({ ...d, namespace: ns.name, locale });
17
+ },
18
+ });
19
+ if (!read.exists && (locale === config.sourceLocale || !inherits(config, locale))) {
20
+ reported.add(locale);
21
+ diagnostics.push({
22
+ level: locale === config.sourceLocale ? 'error' : 'warning',
23
+ code: 'missing-file',
24
+ namespace: ns.name,
25
+ locale,
26
+ file: read.file,
27
+ message: 'no such file: create it',
28
+ });
29
+ }
30
+ catalogs.set(locale, read.entries);
31
+ }
32
+ return { catalogs, reported };
33
+ }
34
+ /** A namespace's chunk per locale, its object and its types, from its catalogs' `texts` per locale. */
35
+ export function buildNamespace(ns, { config, names: { iface, exported }, texts, out, }) {
36
+ const { diagnostics, files } = out;
37
+ if (exported !== ns.name) {
38
+ // two names for one namespace is what tools like codemods and x18n trip over
39
+ diagnostics.push({
40
+ level: 'warning',
41
+ code: 'namespace-name',
42
+ namespace: ns.name,
43
+ message: `exports as ${exported} while t keeps "${ns.name}": name it as an identifier and map the file in path`,
44
+ });
45
+ }
46
+ const adapter = config.formats[ns.format];
47
+ if (!adapter) {
48
+ diagnostics.push({
49
+ level: 'error',
50
+ code: 'unknown-format',
51
+ namespace: ns.name,
52
+ message: `format "${ns.format}" is not in formats (${Object.keys(config.formats).join(', ') || 'empty'})`,
53
+ });
54
+ return;
55
+ }
56
+ const read = readCatalogs(ns, { config, adapter, texts, diagnostics });
57
+ const sourceInfo = new Map();
58
+ // The source locale first, so every translation has its source message to compare against.
59
+ const locales = [config.sourceLocale, ...config.locales.filter((l) => l !== config.sourceLocale)];
60
+ for (const locale of locales) {
61
+ files.set(path.join('messages', locale, `${ns.name}.js`), compileLocale(locale, { ...read, config, ns, sourceInfo, diagnostics }));
62
+ }
63
+ files.set(path.join('namespaces', `${ns.name}.js`), namespaceModule(ns.name, { exported, locales: config.locales }));
64
+ files.set(path.join('namespaces', `${ns.name}.d.ts`), namespaceDeclaration(config, { namespace: ns.name, iface, exported, messages: sourceInfo }));
65
+ }
@@ -0,0 +1,5 @@
1
+ import type { ResolvedConfig } from '../config/config.ts';
2
+ import type { Output } from './namespace.ts';
3
+ /** Every namespace's output, the last build's where nothing the namespace reads has changed. */
4
+ export declare function buildNamespaces(config: ResolvedConfig, out: Output): void;
5
+ //# sourceMappingURL=namespaces.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"namespaces.d.ts","sourceRoot":"","sources":["../../src/generate/namespaces.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAiB,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAKzE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAgB7C,gGAAgG;AAChG,wBAAgB,eAAe,CAAC,MAAM,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,GAAG,IAAI,CAoCzE"}
@@ -0,0 +1,41 @@
1
+ import { exportNames, interfaceNames } from '../types/names.js';
2
+ import { buildNamespace } from './namespace.js';
3
+ import { readText } from './read.js';
4
+ // Per config file, its last build: a watcher's rebuild compiles only the namespaces that changed.
5
+ const builds = new Map();
6
+ /** Every namespace's output, the last build's where nothing the namespace reads has changed. */
7
+ export function buildNamespaces(config, out) {
8
+ const ifaces = interfaceNames(config.namespaces.map((ns) => ns.name));
9
+ const exports = exportNames(ifaces);
10
+ // Whatever else the config holds, so an option added later is not forgotten here.
11
+ const shared = JSON.stringify({
12
+ ...config,
13
+ formats: Object.keys(config.formats),
14
+ namespaces: 0,
15
+ watchFiles: 0,
16
+ watchFolders: 0,
17
+ });
18
+ const last = builds.get(config.configFile);
19
+ const kept = new Map();
20
+ for (const ns of config.namespaces) {
21
+ const names = { iface: ifaces.get(ns.name) ?? '', exported: exports.get(ns.name) ?? '' };
22
+ const files = config.locales.map((locale) => ns.file(locale));
23
+ const settings = JSON.stringify([shared, ns.format, names, files]);
24
+ const adapter = config.formats[ns.format];
25
+ const texts = files.map((file) => readText(file));
26
+ let built = last?.get(ns.name);
27
+ if (built?.settings !== settings ||
28
+ built.adapter !== adapter ||
29
+ texts.some((text, i) => text !== built?.texts[i])) {
30
+ const fresh = { diagnostics: [], files: new Map() };
31
+ buildNamespace(ns, { config, names, texts, out: fresh });
32
+ built = { settings, adapter, texts, ...fresh };
33
+ }
34
+ kept.set(ns.name, built);
35
+ out.diagnostics.push(...built.diagnostics);
36
+ for (const [file, content] of built.files) {
37
+ out.files.set(file, content);
38
+ }
39
+ }
40
+ builds.set(config.configFile, kept);
41
+ }
@@ -0,0 +1,21 @@
1
+ import type { Model } from 'messageformat';
2
+ import type { FormatAdapter, ResolvedNamespace } from '../config/config.ts';
3
+ import type { Unplaced } from '../diagnostics.ts';
4
+ export interface Entry {
5
+ source: string;
6
+ model: Model.Message;
7
+ }
8
+ /** A catalog's text: none where there is no file, an error where it cannot be read. */
9
+ export type CatalogText = string | Error | undefined;
10
+ export declare function readText(file: string): CatalogText;
11
+ export declare function readCatalog(ns: ResolvedNamespace, { locale, adapter, text, report: diag, }: {
12
+ locale: string;
13
+ adapter: FormatAdapter;
14
+ text: CatalogText;
15
+ report: (d: Unplaced) => void;
16
+ }): {
17
+ file: string;
18
+ entries: Map<string, Entry>;
19
+ exists: boolean;
20
+ };
21
+ //# sourceMappingURL=read.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"read.d.ts","sourceRoot":"","sources":["../../src/generate/read.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AAE3C,OAAO,KAAK,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAC5E,OAAO,KAAK,EAAmB,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAmEnE,MAAM,WAAW,KAAK;IACpB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,KAAK,CAAC,OAAO,CAAC;CACtB;AAED,uFAAuF;AACvF,MAAM,MAAM,WAAW,GAAG,MAAM,GAAG,KAAK,GAAG,SAAS,CAAC;AAErD,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW,CASlD;AAED,wBAAgB,WAAW,CACzB,EAAE,EAAE,iBAAiB,EACrB,EACE,MAAM,EACN,OAAO,EACP,IAAI,EACJ,MAAM,EAAE,IAAI,GACb,EAAE;IACD,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,aAAa,CAAC;IACvB,IAAI,EAAE,WAAW,CAAC;IAClB,MAAM,EAAE,CAAC,CAAC,EAAE,QAAQ,KAAK,IAAI,CAAC;CAC/B,GACA;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAAC,MAAM,EAAE,OAAO,CAAA;CAAE,CAsDhE"}
@@ -0,0 +1,115 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ /** Groups in groups past this would overflow the stack, here or in what reads the output. */
3
+ const MAX_DEPTH = 100;
4
+ /** `value`'s messages into `out` by dotted key. */
5
+ function flatten(value, { prefix, out, report, }) {
6
+ const invalid = (message) => {
7
+ report({ key: prefix, message, code: 'invalid-resource' });
8
+ };
9
+ if (prefix.split('.').length > MAX_DEPTH) {
10
+ invalid(`more than ${MAX_DEPTH} levels of keys`);
11
+ return;
12
+ }
13
+ if (typeof value === 'string') {
14
+ if (out.has(prefix)) {
15
+ report({
16
+ key: prefix,
17
+ message: `"${prefix}" is written twice, with dots and in a group`,
18
+ code: 'key-conflict',
19
+ });
20
+ }
21
+ out.set(prefix, value);
22
+ return;
23
+ }
24
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
25
+ for (const [k, v] of Object.entries(value)) {
26
+ flatten(v, { prefix: `${prefix}.${k}`, out, report });
27
+ }
28
+ return;
29
+ }
30
+ const kind = Array.isArray(value) ? 'array' : typeof value;
31
+ invalid(`expected a string or an object, got ${value === null ? 'null' : kind}`);
32
+ }
33
+ /** A catalog's messages by dotted key; nothing, reported, unless it is an object. */
34
+ function flattenRoot(tree, report) {
35
+ if (!tree || typeof tree !== 'object' || Array.isArray(tree)) {
36
+ const kind = Array.isArray(tree) ? 'array' : typeof tree;
37
+ const message = `expected an object of messages, got ${tree === null ? 'null' : kind}`;
38
+ report({ key: '', message, code: 'invalid-resource' });
39
+ return undefined;
40
+ }
41
+ const out = new Map();
42
+ // From the root, as a group named "" would otherwise pass for it.
43
+ for (const [key, value] of Object.entries(tree)) {
44
+ flatten(value, { prefix: key, out, report });
45
+ }
46
+ return out;
47
+ }
48
+ export function readText(file) {
49
+ if (!existsSync(file)) {
50
+ return undefined;
51
+ }
52
+ try {
53
+ return readFileSync(file, 'utf8');
54
+ }
55
+ catch (error) {
56
+ return error;
57
+ }
58
+ }
59
+ export function readCatalog(ns, { locale, adapter, text, report: diag, }) {
60
+ const file = ns.file(locale);
61
+ const entries = new Map();
62
+ if (text === undefined) {
63
+ return { file, entries, exists: false };
64
+ }
65
+ let tree;
66
+ try {
67
+ if (text instanceof Error) {
68
+ throw text;
69
+ }
70
+ tree = adapter.parseFile ? adapter.parseFile(text) : JSON.parse(text);
71
+ }
72
+ catch (error) {
73
+ diag({ level: 'error', code: 'invalid-resource', message: error.message, file });
74
+ return { file, entries, exists: true };
75
+ }
76
+ const flat = flattenRoot(tree, (problem) => {
77
+ diag({ level: 'error', ...problem, file });
78
+ });
79
+ if (!flat) {
80
+ return { file, entries, exists: true };
81
+ }
82
+ // Every prefix, not a sorted neighbour: `-` and others sort between `a` and `a.b`.
83
+ const groups = new Set();
84
+ for (const key of flat.keys()) {
85
+ for (let dot = key.indexOf('.'); dot !== -1; dot = key.indexOf('.', dot + 1)) {
86
+ groups.add(key.slice(0, dot));
87
+ }
88
+ }
89
+ for (const key of flat.keys()) {
90
+ if (groups.has(key)) {
91
+ diag({
92
+ level: 'error',
93
+ code: 'key-conflict',
94
+ key,
95
+ message: `"${key}" is both a message and a group`,
96
+ file,
97
+ });
98
+ }
99
+ }
100
+ for (const [key, source] of flat) {
101
+ try {
102
+ entries.set(key, { source, model: adapter.parse(source) });
103
+ }
104
+ catch (error) {
105
+ diag({
106
+ level: 'error',
107
+ code: 'invalid-syntax',
108
+ key,
109
+ message: error.message,
110
+ file,
111
+ });
112
+ }
113
+ }
114
+ return { file, entries, exists: true };
115
+ }
@@ -0,0 +1,9 @@
1
+ export { build, type BuildOptions, type BuildResult } from './build.ts';
2
+ export { compileMessage } from './compile/compile.ts';
3
+ export { CompileError } from './compile/error.ts';
4
+ export type { CompiledMessage, CustomFunctions, FunctionKind, MessageInfo, ParamKind, } from './compile/info.ts';
5
+ export { ModuleScope } from './compile/scope.ts';
6
+ export { ConfigError, defineConfig, type FormatAdapter, type NamespaceConfig, type ParlaConfig, type ResolvedConfig, type ResolvedNamespace, } from './config/config.ts';
7
+ export { loadConfig } from './config/load.ts';
8
+ export { formatDiagnostic, type Diagnostic, type ErrorDiagnostic, type WarningDiagnostic, } from './diagnostics.ts';
9
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,KAAK,YAAY,EAAE,KAAK,WAAW,EAAE,MAAM,YAAY,CAAC;AACxE,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,YAAY,EACV,eAAe,EACf,eAAe,EACf,YAAY,EACZ,WAAW,EACX,SAAS,GACV,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EACL,WAAW,EACX,YAAY,EACZ,KAAK,aAAa,EAClB,KAAK,eAAe,EACpB,KAAK,WAAW,EAChB,KAAK,cAAc,EACnB,KAAK,iBAAiB,GACvB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EACL,gBAAgB,EAChB,KAAK,UAAU,EACf,KAAK,eAAe,EACpB,KAAK,iBAAiB,GACvB,MAAM,kBAAkB,CAAC"}
package/build/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export { build } from './build.js';
2
+ export { compileMessage } from './compile/compile.js';
3
+ export { CompileError } from './compile/error.js';
4
+ export { ModuleScope } from './compile/scope.js';
5
+ export { ConfigError, defineConfig, } from './config/config.js';
6
+ export { loadConfig } from './config/load.js';
7
+ export { formatDiagnostic, } from './diagnostics.js';
@@ -0,0 +1,43 @@
1
+ interface Framework {
2
+ readonly name: string;
3
+ readonly adapter: string;
4
+ /** The framework's Vite plugin, as `vite.config.ts` calls it. */
5
+ readonly plugin: string;
6
+ /** How a component loads a namespace. */
7
+ readonly load: string;
8
+ readonly docs: string;
9
+ }
10
+ declare const ADD: {
11
+ readonly pnpm: {
12
+ readonly add: 'pnpm add';
13
+ readonly dev: 'pnpm add -D';
14
+ };
15
+ readonly npm: {
16
+ readonly add: 'npm install';
17
+ readonly dev: 'npm install -D';
18
+ };
19
+ readonly yarn: {
20
+ readonly add: 'yarn add';
21
+ readonly dev: 'yarn add -D';
22
+ };
23
+ readonly bun: {
24
+ readonly add: 'bun add';
25
+ readonly dev: 'bun add -d';
26
+ };
27
+ };
28
+ type Manager = keyof typeof ADD;
29
+ export interface Project {
30
+ readonly dependencies: ReadonlySet<string>;
31
+ readonly framework: Framework;
32
+ readonly vite: boolean;
33
+ /** Whether Node reads the package's `.ts` files as ES modules. */
34
+ readonly esm: boolean;
35
+ readonly manager: Manager;
36
+ readonly add: (typeof ADD)[Manager];
37
+ }
38
+ /** The nearest lockfile's manager, as a workspace keeps one at its root; else the one running us. */
39
+ export declare function detectManager(cwd: string): Manager;
40
+ /** What `parla init` reads from the folder instead of asking. */
41
+ export declare function detectProject(cwd: string): Project | undefined;
42
+ export {};
43
+ //# sourceMappingURL=detect.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"detect.d.ts","sourceRoot":"","sources":["../../src/init/detect.ts"],"names":[],"mappings":"AAKA,UAAU,SAAS;IACjB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,iEAAiE;IACjE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,yCAAyC;IACzC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACvB;AA2BD,QAAA,MAAM,GAAG;aACP,IAAI;iBAAI,GAAG,EAAE,UAAU;iBAAE,GAAG,EAAE,aAAa;;aAC3C,GAAG;iBAAI,GAAG,EAAE,aAAa;iBAAE,GAAG,EAAE,gBAAgB;;aAChD,IAAI;iBAAI,GAAG,EAAE,UAAU;iBAAE,GAAG,EAAE,aAAa;;aAC3C,GAAG;iBAAI,GAAG,EAAE,SAAS;iBAAE,GAAG,EAAE,YAAY;;CAChC,CAAC;AAEX,KAAK,OAAO,GAAG,MAAM,OAAO,GAAG,CAAC;AAUhC,MAAM,WAAW,OAAO;IACtB,QAAQ,CAAC,YAAY,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IAC3C,QAAQ,CAAC,SAAS,EAAE,SAAS,CAAC;IAC9B,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;IACvB,kEAAkE;IAClE,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;IACtB,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,QAAQ,CAAC,GAAG,EAAE,CAAC,OAAO,GAAG,CAAC,CAAC,OAAO,CAAC,CAAC;CACrC;AAID,qGAAqG;AACrG,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAYlD;AAED,iEAAiE;AACjE,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,GAAG,SAAS,CAiB9D"}
@@ -0,0 +1,69 @@
1
+ import { existsSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { readPackageJson } from '../config/load.js';
4
+ const DOCS = 'https://parlajs.github.io/parla';
5
+ const adapter = (name, plugin) => ({
6
+ name,
7
+ adapter: `@parlajs/${name.toLowerCase()}`,
8
+ plugin,
9
+ load: 'useParla([common])',
10
+ docs: `${DOCS}/adapters/${name.toLowerCase()}/`,
11
+ });
12
+ const FRAMEWORKS = [
13
+ ['react', adapter('React', 'react()')],
14
+ ['vue', adapter('Vue', 'vue()')],
15
+ ['svelte', adapter('Svelte', 'svelte()')],
16
+ ['solid-js', adapter('Solid', 'solid()')],
17
+ ];
18
+ const CORE = {
19
+ name: 'no framework',
20
+ adapter: '@parlajs/core',
21
+ plugin: '',
22
+ load: 'await parla.load([common])',
23
+ docs: `${DOCS}/core/loading/`,
24
+ };
25
+ const ADD = {
26
+ pnpm: { add: 'pnpm add', dev: 'pnpm add -D' },
27
+ npm: { add: 'npm install', dev: 'npm install -D' },
28
+ yarn: { add: 'yarn add', dev: 'yarn add -D' },
29
+ bun: { add: 'bun add', dev: 'bun add -d' },
30
+ };
31
+ const LOCKFILES = [
32
+ ['pnpm-lock.yaml', 'pnpm'],
33
+ ['yarn.lock', 'yarn'],
34
+ ['bun.lock', 'bun'],
35
+ ['bun.lockb', 'bun'],
36
+ ['package-lock.json', 'npm'],
37
+ ];
38
+ const isManager = (name) => name !== undefined && name in ADD;
39
+ /** The nearest lockfile's manager, as a workspace keeps one at its root; else the one running us. */
40
+ export function detectManager(cwd) {
41
+ for (let dir = cwd;; dir = path.dirname(dir)) {
42
+ const found = LOCKFILES.find(([file]) => existsSync(path.join(dir, file)));
43
+ if (found) {
44
+ return found[1];
45
+ }
46
+ if (path.dirname(dir) === dir) {
47
+ break;
48
+ }
49
+ }
50
+ const agent = process.env['npm_config_user_agent']?.split('/')[0];
51
+ return isManager(agent) ? agent : 'npm';
52
+ }
53
+ /** What `parla init` reads from the folder instead of asking. */
54
+ export function detectProject(cwd) {
55
+ const pkg = readPackageJson(cwd);
56
+ if (!pkg) {
57
+ return undefined;
58
+ }
59
+ const dependencies = new Set(Object.keys({ ...pkg.peerDependencies, ...pkg.devDependencies, ...pkg.dependencies }));
60
+ const manager = detectManager(cwd);
61
+ return {
62
+ dependencies,
63
+ framework: FRAMEWORKS.find(([name]) => dependencies.has(name))?.[1] ?? CORE,
64
+ vite: dependencies.has('vite'),
65
+ esm: pkg.type === 'module',
66
+ manager,
67
+ add: ADD[manager],
68
+ };
69
+ }
@@ -0,0 +1,12 @@
1
+ interface InitOptions {
2
+ /** `mf2` or `icu`. */
3
+ readonly format?: string | undefined;
4
+ /** Comma-separated, the source locale first. */
5
+ readonly locales?: string | undefined;
6
+ /** The folder of the catalogs, relative to the config. */
7
+ readonly catalogs?: string | undefined;
8
+ }
9
+ /** Runs `parla init` in `cwd`: what it wrote and what is left to do. */
10
+ export declare function init(cwd: string, options: InitOptions): Array<string>;
11
+ export {};
12
+ //# sourceMappingURL=init.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../src/init/init.ts"],"names":[],"mappings":"AAUA,UAAU,WAAW;IACnB,sBAAsB;IACtB,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACrC,gDAAgD;IAChD,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACtC,0DAA0D;IAC1D,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACxC;AAyHD,wEAAwE;AACxE,wBAAgB,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,GAAG,KAAK,CAAC,MAAM,CAAC,CAkBrE"}