meowjsx 0.3.0-alpha.1 → 0.3.0-alpha.3

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.
package/README.md CHANGED
@@ -97,6 +97,12 @@ meowjsx (this package: core + JSX contract)
97
97
  - `./signal`: `signal`, `batch`, `mapSignal`, `derived`, `isSignal`, `unwrap`, and the
98
98
  `ReadableSignal`, `WritableSignal`, `Signal` and `MaybeSignal` types. This DOM-free entry loads
99
99
  the reactive implementation without creating a runtime or renderer.
100
+ - `./i18n`: `createI18n`, `t`, `defineMessages`, `I18nProvider`, `useI18n` and the `Catalog`,
101
+ `Message`, `MessageDescriptor` and `I18n` types; see [Internationalization](#internationalization).
102
+ DOM-free (ECMAScript and `Intl` only) and not re-exported from the root.
103
+ - `./i18n/audit`: `extractMessages`, `messageArguments`, `auditCatalog` and `CLOSEST_SIMILARITY`;
104
+ see [Audit](#audit). Pure functions over strings: no IO, no DOM, and no import of the runtime or
105
+ renderer.
100
106
  - `./renderer`: `RenderStrategy<TNode>`, `createRenderer()`, `Renderer`/`Rendered`/
101
107
  `RendererOptions`, `ComponentObserver`/`ObservedComponent` and other target-seam types. `createRenderer()` injects component lifecycle,
102
108
  render hooks, overrides and `key`/`componentPart` identity; the target only implements node and attribute placement.
@@ -212,6 +218,159 @@ Signals, Context or types leaves the runtime and renderer out.
212
218
  - `bun test packages/meowjsx/tests/unit`: Signal, VNode, plugin, metadata, part/ref bindings, fake target seam and Web host tests.
213
219
  - `tests/types/` checks core and Web type cases separately; the core type environment does not include the DOM.
214
220
 
221
+ ## Internationalization
222
+
223
+ `meowjsx/i18n` translates by source sentence: the literal text is the message identity, so a
224
+ single-language application needs no provider, catalog or key.
225
+
226
+ ```tsx
227
+ import { t } from "meowjsx/i18n";
228
+
229
+ function Header() {
230
+ return (
231
+ <nav aria-label={t("Primary navigation")}>
232
+ <a href="/posts/">{t("Posts")}</a>
233
+ <span>{t("{count, plural, one {# min read} other {# mins read}}", { count })}</span>
234
+ </nav>
235
+ );
236
+ }
237
+ ```
238
+
239
+ ```tsx
240
+ import { createI18n, I18nProvider } from "meowjsx/i18n";
241
+
242
+ const i18n = createI18n({ source: "en", locale: "fr", catalogs: { fr: { Posts: "Articles" } } });
243
+ render(
244
+ <I18nProvider value={i18n}>
245
+ <App />
246
+ </I18nProvider>,
247
+ container,
248
+ );
249
+ i18n.locale.value = "en"; // mounted text and attributes update in place
250
+ ```
251
+
252
+ - `t(source, params?, options?)` returns a `ReadableSignal<string>` that follows the locale, the
253
+ catalogs and any Signal parameter. A mounted child, attribute or `className` binds to it; static
254
+ HTML reads it once. `options.context` is part of the identity; `options.note` is ignored at run time.
255
+ - The message Signal throws from `toString` and `Symbol.toPrimitive`, so `` `${t("Posts")}` `` and
256
+ `t("a") + "b"` fail loudly. Read `.value` for a string, or pass variables through
257
+ `t("Hello, {name}", { name })`.
258
+ - `source` must be written as a literal: a value of type `string` or a template literal with a
259
+ runtime part is a type error. Required parameter names are inferred only when the literal has no
260
+ `,` inside braces, no nested brace, no space inside a name and no apostrophe; otherwise
261
+ parameters are loose.
262
+ - Messages support `{name}`, `{count, plural, =0 {...} one {...} other {...}}` and `#` (the
263
+ locale-formatted number). An apostrophe is literal unless it directly precedes `{`, `}` or `#`,
264
+ where it starts a quoted section ending at the next apostrophe (`''` is a literal apostrophe), so
265
+ `l'{name}` does not interpolate; write `l’{name}`. A placeholder with no parameter stays visible
266
+ as written, and a template that does not parse throws an error naming it.
267
+ - `{kind, select, a {...} b {...} other {...}}` picks the branch whose selector equals the value
268
+ (`other` otherwise). `{n, selectordinal, one {#st} two {#nd} few {#rd} other {#th}}` selects
269
+ with the locale's ordinal rules (`Intl.PluralRules` with `type: "ordinal"`) and accepts `=N`
270
+ and `#` like `plural`. `other` is required in all three; branches may nest arguments, and a `#`
271
+ in a `select` branch inside a `plural` is the plural's number. Any other argument type
272
+ (`number`, `date`) is a parse error.
273
+ - A catalog is a flat object from source to translation, or to an object from context to
274
+ translation with `""` for no context. An empty string counts as missing; only own properties are
275
+ read. Lookup tries the locale, then its parents (`zh-Hant-TW`, `zh-Hant`, `zh`), then the source
276
+ text. A locale equal to, or a child of, `source` uses the source text without a miss;
277
+ otherwise `onMissing({ source, context?, locale })` is called once per source, context and locale.
278
+ - `createI18n` returns a plain object: `locale` (writable Signal of a canonical tag; an invalid tag
279
+ throws), `direction` (`"ltr"` or `"rtl"`, derived from the locale's script because Bun has no
280
+ `getTextInfo`), `t`, `number(value, options?)` and `date(value, options?)` (Signals of strings;
281
+ `date` uses the instance `timeZone` unless the options set one), `addCatalog` and
282
+ `setLocale(locale)`. `setLocale` loads through `load` first when the locale has no catalog, then
283
+ writes `locale`, and with concurrent calls only the last one writes. Bind `lang` and `dir` on your
284
+ own element; the entry never touches the document.
285
+ - The module-level `t` reads the nearest `I18nProvider` and works only while a component function
286
+ body runs, binding the message to that instance for good. Without a provider it renders the
287
+ source text, with the plural rules of `"en"`. In a handler, a `derived` body, an effect, a `keyed`
288
+ callback, after `await`, at module top level or in a plain function it throws; use `i18n.t`
289
+ there, which has the same signature and works anywhere.
290
+ - `defineMessages(table)` declares messages away from their use, at module top level or in a table
291
+ keyed by a status or error code. Each entry is a literal source or `{ source, context?, note? }`;
292
+ the result is a frozen object of frozen descriptors with the same keys, and no lookup happens.
293
+ `t` and `i18n.t` accept a literal, a descriptor, or a Signal of a descriptor as the first
294
+ argument. With a Signal, the message follows both the locale and the descriptor, so
295
+ `t(derived(() => labels[status.value]))` called in the component body works. A descriptor's own
296
+ `context` wins over `options.context`; parameters of a descriptor are not inferred. A value of
297
+ type `string` is still a type error for `t` and for a table entry.
298
+ - `t.rich(source, parts, params?, options?)` (also `i18n.t.rich`) returns a `ReadableSignal<Child>`
299
+ for a message with named tag pairs: `t.rich("Read <link>the guide</link>", { link: (children) =>
300
+ <a href="/guide/">{children}</a> })`. A tag is `<name>` ... `</name>` with no attributes and no
301
+ self-closing form; `parts` maps each tag name in the literal to `(children: Child) => Child`
302
+ and a missing part is a type error. Arguments, plurals and selects work inside and outside
303
+ tags, and a translation may move or reorder tags. The result is an array of strings and part
304
+ results that the renderer and `renderToHtml` accept. A tag in the message (or in its
305
+ translation) with no matching part throws an error naming the tag and the source when the
306
+ Signal is read. `<` is only interpreted by `t.rich`: in `t` it is ordinary text, and in `t.rich`
307
+ a `<` that does not start `<name>` or `</name>` is text. Parts run when the Signal is evaluated,
308
+ outside the component body, so they should not call the ambient `t`. The ambient `t.rich` has the
309
+ same in-component-body rule as `t` and the rich Signal refuses string conversion like a message.
310
+ - `i18n.lookup(text, options?)` translates a string that is not a literal, such as site
311
+ configuration copy, through the same catalogs, the same fallback chain and the same `onMissing`
312
+ reporting, and returns a message Signal. The text and its translation are **literal**: no
313
+ placeholder, plural or apostrophe is interpreted, because such copy may contain braces and
314
+ apostrophes. It is an instance method only; there is no ambient `lookup`. The scanner cannot see
315
+ these strings, so their owner passes the same set to `auditCatalog` as extra messages.
316
+
317
+ ### Audit
318
+
319
+ `meowjsx/i18n/audit` turns "did every string get translated" into a list. It runs at build time
320
+ and imports nothing but the message parser the run time also uses, so the audit and the run time
321
+ cannot disagree about what a template contains.
322
+
323
+ - `extractMessages(code, file)` returns `{ messages, dynamic, aliases }`. It is a scanner, not a
324
+ TypeScript parser: it lexes enough TS and TSX to skip comments, string and template literals
325
+ (including `${}` nesting), regex literals and JSX text, then reads only the argument list of
326
+ each call to `t(`, `.t(`, `t.rich(`, `.t.rich(`, `.lookup(` and `defineMessages(`. Matching is by
327
+ name, so an unrelated `.t(` also appears; filter by file. A first argument that is one string
328
+ literal (single or double quoted, or a template without substitutions, with escapes decoded) is
329
+ a message `{ source, context?, note?, kind: "t" | "rich" | "defined", key?, literal?, file, line,
330
+ column, placeholders, tags }`. `context` and `note` come from an options object literal (third
331
+ argument of `t`, fourth of `t.rich`, second of `lookup`); a `context` that is not a literal
332
+ makes the call dynamic. `defineMessages` members with a literal source, or an object literal
333
+ with a literal `source`, are messages of kind `"defined"` with their `key`. A `.lookup("...")`
334
+ call with a literal is a message with `literal: true`.
335
+ - Everything else is reported in `dynamic` as `{ file, line, column, callee, argument, reason }`
336
+ and never skipped: template literals with substitutions, concatenations, identifiers, member
337
+ accesses (the scanner does not try to prove one is a descriptor), calls, other expressions,
338
+ every non-literal `.lookup(...)`, and unreadable `defineMessages` members. `reason` is one of
339
+ `missing-argument`, `template-literal`, `concatenation`, `identifier`, `member-access`, `call`,
340
+ `expression`, `lookup`, `context`, `options`, `not-an-object-literal` and `unreadable-member`.
341
+ `aliases` lists `import { t as x } from "meowjsx/i18n"` (and the same for `defineMessages`),
342
+ and calls through the alias are scanned. Line and column are 1-based and point at the callee
343
+ name, or at the member key for `defineMessages`. An unterminated construct ends the scan of that
344
+ region without throwing.
345
+ - `messageArguments(source, { rich? })` returns `{ names, tags }` from the shared parser and
346
+ throws when the template does not parse.
347
+ - `auditCatalog(messages, catalog, locale, { extra?, extraLiteral? })` compares messages with one
348
+ locale's catalog (source to string, or to an object from context to string, `""` for none) and
349
+ returns `{ locale, missing, unused, invalid }`:
350
+ - `missing`: `{ source, context?, note?, file?, line? }` for a message with no translation or an
351
+ empty one;
352
+ - `unused`: `{ source, context?, translation, closest? }` for a non-empty catalog entry that no
353
+ message refers to. `closest` is the first missing item with the highest normalized
354
+ edit-distance similarity (case-insensitive, `1 - distance / longer length`) of at least
355
+ `CLOSEST_SIMILARITY` (0.6), so an edited sentence carries its old translation as a starting
356
+ point;
357
+ - `invalid`: `{ source, context?, translation, reason }` when the source or the translation does
358
+ not parse, when the set of argument names differs (this also catches `l'{name}`, where the
359
+ apostrophe swallows the placeholder), or, for messages of kind `"rich"`, when the set of tag
360
+ names differs. Plural categories are not validated against `locale`; it is recorded in the
361
+ result.
362
+ - `extra` adds messages the scanner cannot see; with `extraLiteral` (default `true`) they are
363
+ literal text, as `lookup` treats them, and only their presence is checked.
364
+
365
+ ```ts
366
+ import { auditCatalog, extractMessages } from "meowjsx/i18n/audit";
367
+
368
+ const { messages, dynamic } = extractMessages(await readSource(file), file);
369
+ const { missing, unused, invalid } = auditCatalog(messages, catalog, "fr", {
370
+ extra: [{ source: site.description }],
371
+ });
372
+ ```
373
+
215
374
  ## Web module
216
375
 
217
376
  ```ts
@@ -13,4 +13,18 @@ export declare function isContextProvider(component: Function): boolean;
13
13
  export declare function createContext<T>(defaultValue: T): ContextValue<T>;
14
14
  export declare function useContext<T>(context: ContextValue<T>): T;
15
15
  export declare function withContextScope<T>(scope: ContextScope | undefined, run: () => T): T;
16
+ /**
17
+ * Whether a component function body is executing synchronously right now. This
18
+ * is a different fact from "no Provider above": `useContext` returns the default
19
+ * in both cases. Handlers, derived and effect bodies, keyed callbacks, code after
20
+ * `await` and module top level are all outside a component body.
21
+ */
22
+ export declare function isInComponentBody(): boolean;
23
+ /** Run one component function body with its Context scope and the in-body fact set. */
24
+ export declare function runComponentBody<T>(scope: ContextScope | undefined, run: () => T): T;
25
+ /**
26
+ * Run user code that a component body may trigger synchronously but that is not
27
+ * itself the body: derived reads, effects, flushed subscribers, keyed callbacks.
28
+ */
29
+ export declare function outsideComponentBody<T>(run: () => T): T;
16
30
  export declare function contextScopeForProvider(component: Function, value: unknown, parent: ContextScope | undefined): ContextScope | undefined;
@@ -1,5 +1,6 @@
1
1
  const providers = new WeakMap();
2
2
  let activeScope;
3
+ let componentBodyRunning = false;
3
4
  export function isContextProvider(component) {
4
5
  return providers.has(component);
5
6
  }
@@ -23,6 +24,41 @@ export function withContextScope(scope, run) {
23
24
  activeScope = previous;
24
25
  }
25
26
  }
27
+ /**
28
+ * Whether a component function body is executing synchronously right now. This
29
+ * is a different fact from "no Provider above": `useContext` returns the default
30
+ * in both cases. Handlers, derived and effect bodies, keyed callbacks, code after
31
+ * `await` and module top level are all outside a component body.
32
+ */
33
+ export function isInComponentBody() {
34
+ return componentBodyRunning;
35
+ }
36
+ /** Run one component function body with its Context scope and the in-body fact set. */
37
+ export function runComponentBody(scope, run) {
38
+ const previous = componentBodyRunning;
39
+ componentBodyRunning = true;
40
+ try {
41
+ return withContextScope(scope, run);
42
+ }
43
+ finally {
44
+ componentBodyRunning = previous;
45
+ }
46
+ }
47
+ /**
48
+ * Run user code that a component body may trigger synchronously but that is not
49
+ * itself the body: derived reads, effects, flushed subscribers, keyed callbacks.
50
+ */
51
+ export function outsideComponentBody(run) {
52
+ if (!componentBodyRunning)
53
+ return run();
54
+ componentBodyRunning = false;
55
+ try {
56
+ return run();
57
+ }
58
+ finally {
59
+ componentBodyRunning = true;
60
+ }
61
+ }
26
62
  export function contextScopeForProvider(component, value, parent) {
27
63
  const key = providers.get(component);
28
64
  if (!key)
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Build-time audit for `meowjsx/i18n`. Pure functions over strings: no IO, no DOM, no
3
+ * runtime or renderer. `extractMessages` is a scanner, not a TypeScript parser: it lexes
4
+ * enough of TS/TSX to skip comments, strings, templates, regex literals and JSX text, finds
5
+ * the call sites of the message functions and reads only their argument lists. What it
6
+ * cannot read is returned in `dynamic`, never skipped.
7
+ */
8
+ export type ExtractedKind = "t" | "rich" | "defined";
9
+ export interface ExtractedMessage {
10
+ readonly source: string;
11
+ readonly context?: string;
12
+ readonly note?: string;
13
+ readonly kind: ExtractedKind;
14
+ /** The table key of a `defineMessages` member. */
15
+ readonly key?: string;
16
+ /** Set for a `.lookup("...")` call: the text is literal, not an ICU template. */
17
+ readonly literal?: true;
18
+ readonly file: string;
19
+ /** 1-based position of the callee name, or of the member for `defineMessages`. */
20
+ readonly line: number;
21
+ readonly column: number;
22
+ /** Argument names the template uses. Empty when the source does not parse or is literal. */
23
+ readonly placeholders: string[];
24
+ /** Rich tag names; non-empty only for kind "rich". */
25
+ readonly tags: string[];
26
+ }
27
+ /**
28
+ * Why a call could not be read: `missing-argument`, `template-literal` (substitutions),
29
+ * `concatenation`, `identifier`, `member-access`, `call`, `expression`, `lookup` (a
30
+ * non-literal `.lookup(...)` argument, always reported), `context` (a context that is not a
31
+ * literal), `options` (an options argument that is not an object literal),
32
+ * `not-an-object-literal` and `unreadable-member` (`defineMessages`).
33
+ */
34
+ export interface DynamicCall {
35
+ readonly file: string;
36
+ readonly line: number;
37
+ readonly column: number;
38
+ readonly callee: string;
39
+ /** A short excerpt of the argument source. */
40
+ readonly argument: string;
41
+ readonly reason: string;
42
+ }
43
+ /** `import { t as x } from "meowjsx/i18n"`. */
44
+ export interface AliasReport {
45
+ readonly file: string;
46
+ readonly line: number;
47
+ readonly column: number;
48
+ readonly imported: string;
49
+ readonly local: string;
50
+ readonly module: string;
51
+ }
52
+ export interface Extraction {
53
+ messages: ExtractedMessage[];
54
+ dynamic: DynamicCall[];
55
+ aliases: AliasReport[];
56
+ }
57
+ export declare function extractMessages(code: string, file: string): Extraction;
58
+ /**
59
+ * Argument names and rich tag names of a message, from the parser the run time uses.
60
+ * `rich: true` reads `<name>...</name>` tags. Throws an `Error` when the template does not
61
+ * parse.
62
+ */
63
+ export declare function messageArguments(source: string, options?: {
64
+ readonly rich?: boolean;
65
+ }): {
66
+ names: string[];
67
+ tags: string[];
68
+ };
69
+ /** Flat map from source to a translation, or to a map from context (`""` = none). */
70
+ export type AuditCatalog = {
71
+ readonly [source: string]: string | {
72
+ readonly [context: string]: string;
73
+ };
74
+ };
75
+ /** A message to audit; every `ExtractedMessage` satisfies this. */
76
+ export interface AuditMessage {
77
+ readonly source: string;
78
+ readonly context?: string;
79
+ readonly note?: string;
80
+ readonly kind?: ExtractedKind;
81
+ /** The text is literal, not an ICU template: its braces and apostrophes are not parsed. */
82
+ readonly literal?: boolean;
83
+ readonly file?: string;
84
+ readonly line?: number;
85
+ }
86
+ export interface MissingItem {
87
+ source: string;
88
+ context?: string;
89
+ note?: string;
90
+ file?: string;
91
+ line?: number;
92
+ }
93
+ export interface UnusedItem {
94
+ source: string;
95
+ context?: string;
96
+ translation: string;
97
+ closest?: {
98
+ source: string;
99
+ context?: string;
100
+ };
101
+ }
102
+ export interface InvalidItem {
103
+ source: string;
104
+ context?: string;
105
+ translation: string;
106
+ reason: string;
107
+ }
108
+ export interface AuditResult {
109
+ /** The locale audited; recorded, not used to validate plural categories. */
110
+ locale: string;
111
+ missing: MissingItem[];
112
+ unused: UnusedItem[];
113
+ invalid: InvalidItem[];
114
+ }
115
+ export interface AuditOptions {
116
+ /** Messages the scanner cannot see, such as the copy passed to `i18n.lookup`. */
117
+ readonly extra?: readonly AuditMessage[];
118
+ /** Whether `extra` entries are literal text (default `true`, as `lookup` treats them). */
119
+ readonly extraLiteral?: boolean;
120
+ }
121
+ /** `closest` needs at least this normalized edit-distance similarity (1 is identical). */
122
+ export declare const CLOSEST_SIMILARITY = 0.6;
123
+ /**
124
+ * Compares the messages the code uses with one locale's catalog and returns the work list.
125
+ * `catalog` maps a source to a translation, or to a map from context to translation.
126
+ */
127
+ export declare function auditCatalog(messages: readonly AuditMessage[], catalog: AuditCatalog, locale: string, options?: AuditOptions): AuditResult;