verbaly 0.33.0 → 0.35.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.
package/dist/index.d.cts CHANGED
@@ -21,6 +21,7 @@ declare function normalizeLink(link: RichLink): {
21
21
  rel?: string;
22
22
  };
23
23
  declare function safeAttribute(name: string, value: string): string | undefined;
24
+ declare const VOID_TAGS: string[];
24
25
  declare const RICH_TAGS: string[];
25
26
  declare function bindDom<D extends DictionaryInput>(instance: Verbaly<D>, options?: BindDomOptions): () => void;
26
27
  //#endregion
@@ -29,10 +30,17 @@ interface ResolveLocaleOptions {
29
30
  supported: string[];
30
31
  fallback?: string;
31
32
  storageKey?: string | false;
33
+ path?: string | false;
32
34
  }
33
35
  declare const LOCALE_STORAGE_KEY = "verbaly-locale";
34
36
  declare function localeDirection(locale: string): 'ltr' | 'rtl';
35
37
  declare function localeName(locale: string, displayIn?: string): string;
38
+ interface LocalePathOptions {
39
+ supported: string[];
40
+ sourceLocale?: string;
41
+ path?: string;
42
+ }
43
+ declare function localePath(locale: string, options: LocalePathOptions): string;
36
44
  declare function resolveLocale(options: ResolveLocaleOptions): string;
37
45
  declare function negotiateLocale(header: string | null | undefined, supported: string[], fallback?: string): string;
38
46
  interface RequestLocaleOptions {
@@ -76,5 +84,5 @@ type TagNode = string | {
76
84
  };
77
85
  declare function parseTags(text: string): TagNode[];
78
86
  //#endregion
79
- export { type BindDomOptions, type DictionaryInput, type FlatKeys, type Formatter, type KeysOf, LOCALE_STORAGE_KEY, type LocaleLoader, type MessageAt, type MessageNode, type MessageTree, type MessageValue, type ParamNames, type ParamNode, type Params, RICH_TAGS, type RequestLocaleOptions, type ResolveInfo, type ResolveLocaleOptions, type ResolveStatus, type RichLink, type SwitchLocaleOptions, type TArgs, type TFunction, type TagNode, type Verbaly, type VerbalyOptions, bindDom, createVerbaly, flatten, localeDirection, localeName, negotiateLocale, normalizeLink, parse, parseTags, persistLocale, resolveLocale, resolveRequestLocale, safeAttribute, safeHref, switchLocale };
87
+ export { type BindDomOptions, type DictionaryInput, type FlatKeys, type Formatter, type KeysOf, LOCALE_STORAGE_KEY, type LocaleLoader, type LocalePathOptions, type MessageAt, type MessageNode, type MessageTree, type MessageValue, type ParamNames, type ParamNode, type Params, RICH_TAGS, type RequestLocaleOptions, type ResolveInfo, type ResolveLocaleOptions, type ResolveStatus, type RichLink, type SwitchLocaleOptions, type TArgs, type TFunction, type TagNode, VOID_TAGS, type Verbaly, type VerbalyOptions, bindDom, createVerbaly, flatten, localeDirection, localeName, localePath, negotiateLocale, normalizeLink, parse, parseTags, persistLocale, resolveLocale, resolveRequestLocale, safeAttribute, safeHref, switchLocale };
80
88
  //# sourceMappingURL=index.d.cts.map
package/dist/index.d.ts CHANGED
@@ -21,6 +21,7 @@ declare function normalizeLink(link: RichLink): {
21
21
  rel?: string;
22
22
  };
23
23
  declare function safeAttribute(name: string, value: string): string | undefined;
24
+ declare const VOID_TAGS: string[];
24
25
  declare const RICH_TAGS: string[];
25
26
  declare function bindDom<D extends DictionaryInput>(instance: Verbaly<D>, options?: BindDomOptions): () => void;
26
27
  //#endregion
@@ -29,10 +30,17 @@ interface ResolveLocaleOptions {
29
30
  supported: string[];
30
31
  fallback?: string;
31
32
  storageKey?: string | false;
33
+ path?: string | false;
32
34
  }
33
35
  declare const LOCALE_STORAGE_KEY = "verbaly-locale";
34
36
  declare function localeDirection(locale: string): 'ltr' | 'rtl';
35
37
  declare function localeName(locale: string, displayIn?: string): string;
38
+ interface LocalePathOptions {
39
+ supported: string[];
40
+ sourceLocale?: string;
41
+ path?: string;
42
+ }
43
+ declare function localePath(locale: string, options: LocalePathOptions): string;
36
44
  declare function resolveLocale(options: ResolveLocaleOptions): string;
37
45
  declare function negotiateLocale(header: string | null | undefined, supported: string[], fallback?: string): string;
38
46
  interface RequestLocaleOptions {
@@ -76,5 +84,5 @@ type TagNode = string | {
76
84
  };
77
85
  declare function parseTags(text: string): TagNode[];
78
86
  //#endregion
79
- export { type BindDomOptions, type DictionaryInput, type FlatKeys, type Formatter, type KeysOf, LOCALE_STORAGE_KEY, type LocaleLoader, type MessageAt, type MessageNode, type MessageTree, type MessageValue, type ParamNames, type ParamNode, type Params, RICH_TAGS, type RequestLocaleOptions, type ResolveInfo, type ResolveLocaleOptions, type ResolveStatus, type RichLink, type SwitchLocaleOptions, type TArgs, type TFunction, type TagNode, type Verbaly, type VerbalyOptions, bindDom, createVerbaly, flatten, localeDirection, localeName, negotiateLocale, normalizeLink, parse, parseTags, persistLocale, resolveLocale, resolveRequestLocale, safeAttribute, safeHref, switchLocale };
87
+ export { type BindDomOptions, type DictionaryInput, type FlatKeys, type Formatter, type KeysOf, LOCALE_STORAGE_KEY, type LocaleLoader, type LocalePathOptions, type MessageAt, type MessageNode, type MessageTree, type MessageValue, type ParamNames, type ParamNode, type Params, RICH_TAGS, type RequestLocaleOptions, type ResolveInfo, type ResolveLocaleOptions, type ResolveStatus, type RichLink, type SwitchLocaleOptions, type TArgs, type TFunction, type TagNode, VOID_TAGS, type Verbaly, type VerbalyOptions, bindDom, createVerbaly, flatten, localeDirection, localeName, localePath, negotiateLocale, normalizeLink, parse, parseTags, persistLocale, resolveLocale, resolveRequestLocale, safeAttribute, safeHref, switchLocale };
80
88
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,12 +1,25 @@
1
+ //#region src/warn.ts
2
+ const warned = /* @__PURE__ */ new Set();
3
+ function warnOnce(message) {
4
+ if (warned.has(message)) return;
5
+ warned.add(message);
6
+ console.warn(`[verbaly] ${message}`);
7
+ }
8
+ //#endregion
1
9
  //#region src/flatten.ts
2
10
  function flatten(tree, prefix = "", out = {}) {
11
+ if (!isGroup(tree)) return out;
3
12
  for (const [key, value] of Object.entries(tree)) {
4
13
  const path = prefix ? `${prefix}.${key}` : key;
5
14
  if (typeof value === "string") out[path] = value;
6
- else flatten(value, path, out);
15
+ else if (isGroup(value)) flatten(value, path, out);
16
+ else warnOnce(`catalog value at "${path}" is not text, so the key renders as itself`);
7
17
  }
8
18
  return out;
9
19
  }
20
+ function isGroup(value) {
21
+ return typeof value === "object" && value !== null && !Array.isArray(value);
22
+ }
10
23
  //#endregion
11
24
  //#region src/intl.ts
12
25
  const CACHE_CAP = 200;
@@ -50,7 +63,7 @@ function displayNames(locale) {
50
63
  function formatNodes(nodes, ctx) {
51
64
  let out = "";
52
65
  for (const node of nodes) if (node.kind === "text") out += node.value;
53
- else if (node.kind === "hash") out += autoFormat(ctx.hashValue, ctx.locale);
66
+ else if (node.kind === "hash") out += autoFormat(ctx.hashValue, ctx.locale, ctx);
54
67
  else out += formatParam(node, ctx);
55
68
  return out;
56
69
  }
@@ -75,7 +88,15 @@ function formatParam(node, ctx) {
75
88
  });
76
89
  }
77
90
  if (node.format) return applyFormat(value, node, ctx);
78
- return autoFormat(value, ctx.locale);
91
+ return autoFormat(value, ctx.locale, ctx);
92
+ }
93
+ function describe(value) {
94
+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? "an invalid Date" : "a Date";
95
+ if (Array.isArray(value)) return "an array";
96
+ if (value === null) return "null";
97
+ if (value === void 0) return "undefined";
98
+ const type = typeof value;
99
+ return type === "object" ? "an object" : `a ${type}`;
79
100
  }
80
101
  function pickVariant(variants, value, locale, ordinal) {
81
102
  const raw = String(value);
@@ -108,20 +129,17 @@ function applyFormat(value, node, ctx) {
108
129
  currency: arg
109
130
  }).format(Number(value));
110
131
  } catch {
111
- warnOnce(`invalid currency "${arg}"`);
112
- return String(value);
132
+ return degrade(`does not know the currency "${arg}"`);
113
133
  }
114
134
  case "date": try {
115
135
  return dateTimeFormat(locale, arg ? { dateStyle: arg } : void 0).format(toDate(value));
116
136
  } catch {
117
- warnOnce(`invalid date "${arg ?? value}"`);
118
- return String(value);
137
+ return degrade(`cannot format ${describe(value)}${arg ? ` with style "${arg}"` : ""}`);
119
138
  }
120
139
  case "time": try {
121
140
  return dateTimeFormat(locale, { timeStyle: arg ?? "short" }).format(toDate(value));
122
141
  } catch {
123
- warnOnce(`invalid time "${arg ?? value}"`);
124
- return String(value);
142
+ return degrade(`cannot format ${describe(value)} with style "${arg ?? "short"}"`);
125
143
  }
126
144
  case "relative":
127
145
  if (typeof value === "number" && !arg) return degrade("needs an argument like /day");
@@ -129,7 +147,7 @@ function applyFormat(value, node, ctx) {
129
147
  return formatRelative(value, node, ctx);
130
148
  case "list":
131
149
  if (!Array.isArray(value)) return degrade("needs an array");
132
- return listFormat(locale, arg === "or" ? "disjunction" : arg === "unit" ? "unit" : "conjunction").format(value.map((item) => autoFormat(item, locale)));
150
+ return listFormat(locale, arg === "or" ? "disjunction" : arg === "unit" ? "unit" : "conjunction").format(value.map((item) => autoFormat(item, locale, ctx)));
133
151
  case "unit":
134
152
  if (!arg) return degrade("needs an argument like /kilometer");
135
153
  try {
@@ -138,12 +156,9 @@ function applyFormat(value, node, ctx) {
138
156
  unit: arg
139
157
  }).format(Number(value));
140
158
  } catch {
141
- warnOnce(`invalid unit "${arg}"`);
142
- return String(value);
159
+ return degrade(`does not know the unit "${arg}"`);
143
160
  }
144
- default:
145
- warnOnce(`unknown format "${format}"`);
146
- return String(value);
161
+ default: return degrade("is not a format verbaly knows");
147
162
  }
148
163
  }
149
164
  const REL_UNITS = [
@@ -169,22 +184,16 @@ function formatRelative(value, node, ctx) {
169
184
  const [unit, per] = REL_UNITS.find(([, s]) => Math.abs(diffSec) >= s) ?? ["second", 1];
170
185
  return fmt.format(Math.round(diffSec / per), unit);
171
186
  } catch {
172
- warnOnce(`{${node.name}:relative}${where(ctx)} cannot format "${value}" as "${arg}"`);
187
+ warnOnce(`{${node.name}:relative}${where(ctx)} cannot format ${describe(value)} as "${arg}"`);
173
188
  return String(value);
174
189
  }
175
190
  }
176
- const warned = /* @__PURE__ */ new Set();
177
- function warnOnce(msg) {
178
- if (warned.has(msg)) return;
179
- warned.add(msg);
180
- console.warn(`[verbaly] ${msg}`);
181
- }
182
- function autoFormat(value, locale) {
191
+ function autoFormat(value, locale, ctx) {
183
192
  if (value === null || value === void 0) return "";
184
193
  if (typeof value === "number") return numberFormat(locale).format(value);
185
194
  if (value instanceof Date) {
186
195
  if (Number.isNaN(value.getTime())) {
187
- warnOnce("invalid date value");
196
+ warnOnce(`an invalid Date${ctx ? where(ctx) : ""} renders as plain text`);
188
197
  return String(value);
189
198
  }
190
199
  return dateTimeFormat(locale).format(value);
@@ -227,8 +236,26 @@ function localeName(locale, displayIn = locale) {
227
236
  return locale;
228
237
  }
229
238
  }
239
+ function localePath(locale, options) {
240
+ const { supported, sourceLocale } = options;
241
+ const full = options.path ?? currentPath() ?? "/";
242
+ const cut = full.search(/[?#]/);
243
+ const path = cut < 0 ? full : full.slice(0, cut);
244
+ const rest = cut < 0 ? "" : full.slice(cut);
245
+ const segments = path.split("/").filter(Boolean);
246
+ if (segments[0] && matchSupported(segments[0], supported)) segments.shift();
247
+ if (locale !== sourceLocale) segments.unshift(locale);
248
+ const trailing = segments.length && path.endsWith("/") ? "/" : "";
249
+ return `/${segments.join("/")}${trailing}${rest}`;
250
+ }
230
251
  function resolveLocale(options) {
231
252
  const { supported, fallback = supported[0] ?? "en", storageKey = LOCALE_STORAGE_KEY } = options;
253
+ const path = options.path ?? currentPath();
254
+ if (path) {
255
+ const segment = path.split("/").find(Boolean);
256
+ const match = segment && matchSupported(segment, supported);
257
+ if (match) return match;
258
+ }
232
259
  if (storageKey) {
233
260
  const stored = getStorage()?.getItem(storageKey);
234
261
  const match = stored && matchSupported(stored, supported);
@@ -301,6 +328,9 @@ function persistLocale(locale, storageKey = LOCALE_STORAGE_KEY) {
301
328
  document.documentElement.dir = localeDirection(locale);
302
329
  }
303
330
  }
331
+ function currentPath() {
332
+ return typeof document !== "undefined" && typeof location !== "undefined" ? location.pathname : void 0;
333
+ }
304
334
  function preferredLanguages() {
305
335
  if (typeof document === "undefined" || typeof navigator === "undefined") return [];
306
336
  return navigator.languages?.length ? navigator.languages : [navigator.language];
@@ -626,7 +656,6 @@ function createVerbaly(options = {}) {
626
656
  const loaders = options.loaders ?? {};
627
657
  const loaded = /* @__PURE__ */ new Set();
628
658
  const inFlight = /* @__PURE__ */ new Map();
629
- const warned = /* @__PURE__ */ new Set();
630
659
  const fallbacks = options.fallback ? Array.isArray(options.fallback) ? options.fallback : [options.fallback] : [];
631
660
  let locale = options.locale ?? detectLocale();
632
661
  let version = 0;
@@ -653,10 +682,7 @@ function createVerbaly(options = {}) {
653
682
  if (hit === void 0) {
654
683
  const replacement = options.onMissing?.(key, locale);
655
684
  const value = typeof replacement === "string" ? replacement : key;
656
- if (typeof replacement !== "string" && !options.onMissing && !warned.has(key)) {
657
- warned.add(key);
658
- console.warn(`[verbaly] missing key "${key}" (${locale})`);
659
- }
685
+ if (typeof replacement !== "string" && !options.onMissing) warnOnce(`missing key "${key}" (${locale})`);
660
686
  options.onResolve?.({
661
687
  key,
662
688
  locale,
@@ -733,10 +759,7 @@ function createVerbaly(options = {}) {
733
759
  t,
734
760
  setLocale(next) {
735
761
  loadLocale(next).catch(() => {
736
- if (!warned.has(`load:${next}`)) {
737
- warned.add(`load:${next}`);
738
- console.warn(`[verbaly] failed to load catalog for "${next}"`);
739
- }
762
+ warnOnce(`failed to load catalog for "${next}"`);
740
763
  });
741
764
  if (next === locale) return;
742
765
  locale = next;
@@ -824,7 +847,7 @@ const URL_ATTR = /^(href|src|xlink:href|action|formaction)$/;
824
847
  const BLOCKED_ATTR = /^(style|srcdoc)$/;
825
848
  function safeHref(href) {
826
849
  if (UNSAFE_HREF.test(href)) {
827
- console.warn(`[verbaly] blocked unsafe href: ${href}`);
850
+ warnOnce(`blocked unsafe href: ${href}`);
828
851
  return;
829
852
  }
830
853
  return href;
@@ -843,6 +866,22 @@ function safeAttribute(name, value) {
843
866
  if (URL_ATTR.test(lower)) return safeHref(value);
844
867
  return value;
845
868
  }
869
+ const VOID_TAGS = [
870
+ "area",
871
+ "base",
872
+ "br",
873
+ "col",
874
+ "embed",
875
+ "hr",
876
+ "img",
877
+ "input",
878
+ "link",
879
+ "meta",
880
+ "param",
881
+ "source",
882
+ "track",
883
+ "wbr"
884
+ ];
846
885
  const RICH_TAGS = [
847
886
  "em",
848
887
  "strong",
@@ -917,15 +956,20 @@ function bindDom(instance, options = {}) {
917
956
  el.append(a);
918
957
  } else if (richTags.has(node.name)) {
919
958
  const child = el.ownerDocument.createElement(node.name);
920
- renderRich(child, node.children, links);
959
+ if (!VOID_TAGS.includes(node.name)) renderRich(child, node.children, links);
921
960
  el.append(child);
922
961
  } else renderRich(el, node.children, links);
923
962
  }
924
963
  }
964
+ let trustServerHtml = true;
965
+ function holdBack(key, current) {
966
+ if (!trustServerHtml || !current?.trim()) return false;
967
+ return instance.inspect(key)?.from !== instance.locale;
968
+ }
925
969
  function render(el) {
926
970
  const args = cachedArgs(el);
927
971
  const key = el.getAttribute(attr);
928
- if (key) {
972
+ if (key && !holdBack(key, el.textContent)) {
929
973
  const text = t(key, args);
930
974
  if (el.hasAttribute(richAttr)) {
931
975
  el.textContent = "";
@@ -936,6 +980,7 @@ function bindDom(instance, options = {}) {
936
980
  const attrMap = fromCache(attrsCache, el, rawAttrs, () => parseArgs(rawAttrs));
937
981
  if (attrMap) for (const [name, attrKey] of Object.entries(attrMap)) {
938
982
  if (typeof attrKey !== "string") continue;
983
+ if (holdBack(attrKey, el.getAttribute(name))) continue;
939
984
  const value = safeAttribute(name, t(attrKey, args));
940
985
  if (value !== void 0) el.setAttribute(name, value);
941
986
  }
@@ -945,7 +990,9 @@ function bindDom(instance, options = {}) {
945
990
  if (scope instanceof Element && scope.matches(selector)) render(scope);
946
991
  for (const el of scope.querySelectorAll(selector)) render(el);
947
992
  }
993
+ warnOnLangMismatch(instance.locale);
948
994
  renderAll(root);
995
+ trustServerHtml = false;
949
996
  const unsubscribe = instance.subscribe(() => renderAll(root));
950
997
  const observer = new MutationObserver((records) => {
951
998
  for (const record of records) if (record.type === "attributes" && record.target instanceof Element) render(record.target);
@@ -970,16 +1017,21 @@ function bindDom(instance, options = {}) {
970
1017
  observer.disconnect();
971
1018
  };
972
1019
  }
1020
+ function warnOnLangMismatch(locale) {
1021
+ const lang = document.documentElement.lang;
1022
+ if (!lang || narrowLocales(lang).includes(locale) || narrowLocales(locale).includes(lang)) return;
1023
+ warnOnce(`the page is <html lang="${lang}"> and this instance is in "${locale}", so bindDom is about to translate it away: resolve the locale from the url (resolveLocale reads it) before binding`);
1024
+ }
973
1025
  function parseArgs(raw) {
974
1026
  if (!raw) return void 0;
975
1027
  try {
976
1028
  return JSON.parse(raw);
977
1029
  } catch {
978
- console.warn(`[verbaly] invalid args JSON: ${raw}`);
1030
+ warnOnce(`invalid args JSON: ${raw}`);
979
1031
  return;
980
1032
  }
981
1033
  }
982
1034
  //#endregion
983
- export { LOCALE_STORAGE_KEY, RICH_TAGS, bindDom, createVerbaly, flatten, localeDirection, localeName, negotiateLocale, normalizeLink, parse, parseTags, persistLocale, resolveLocale, resolveRequestLocale, safeAttribute, safeHref, switchLocale };
1035
+ export { LOCALE_STORAGE_KEY, RICH_TAGS, VOID_TAGS, bindDom, createVerbaly, flatten, localeDirection, localeName, localePath, negotiateLocale, normalizeLink, parse, parseTags, persistLocale, resolveLocale, resolveRequestLocale, safeAttribute, safeHref, switchLocale };
984
1036
 
985
1037
  //# sourceMappingURL=index.js.map