verbaly 0.11.0 → 0.13.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.cjs CHANGED
@@ -1,862 +1,823 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- RICH_TAGS: () => RICH_TAGS,
24
- bindDom: () => bindDom,
25
- createVerbaly: () => createVerbaly,
26
- flatten: () => flatten,
27
- parse: () => parse,
28
- parseTags: () => parseTags,
29
- persistLocale: () => persistLocale,
30
- resolveLocale: () => resolveLocale,
31
- safeHref: () => safeHref
32
- });
33
- module.exports = __toCommonJS(index_exports);
34
-
35
- // src/flatten.ts
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/flatten.ts
36
3
  function flatten(tree, prefix = "", out = {}) {
37
- for (const [key, value] of Object.entries(tree)) {
38
- const path = prefix ? `${prefix}.${key}` : key;
39
- if (typeof value === "string") out[path] = value;
40
- else flatten(value, path, out);
41
- }
42
- return out;
43
- }
44
-
45
- // src/intl.ts
46
- var CACHE_CAP = 200;
47
- var nfCache = /* @__PURE__ */ new Map();
48
- var dtfCache = /* @__PURE__ */ new Map();
49
- var prCache = /* @__PURE__ */ new Map();
50
- var rtfCache = /* @__PURE__ */ new Map();
51
- var lfCache = /* @__PURE__ */ new Map();
4
+ for (const [key, value] of Object.entries(tree)) {
5
+ const path = prefix ? `${prefix}.${key}` : key;
6
+ if (typeof value === "string") out[path] = value;
7
+ else flatten(value, path, out);
8
+ }
9
+ return out;
10
+ }
11
+ //#endregion
12
+ //#region src/intl.ts
13
+ const CACHE_CAP = 200;
14
+ const nfCache = /* @__PURE__ */ new Map();
15
+ const dtfCache = /* @__PURE__ */ new Map();
16
+ const prCache = /* @__PURE__ */ new Map();
17
+ const rtfCache = /* @__PURE__ */ new Map();
18
+ const lfCache = /* @__PURE__ */ new Map();
52
19
  function cached(cache, key, make) {
53
- let hit = cache.get(key);
54
- if (!hit) {
55
- if (cache.size >= CACHE_CAP) cache.delete(cache.keys().next().value);
56
- hit = make();
57
- cache.set(key, hit);
58
- }
59
- return hit;
20
+ let hit = cache.get(key);
21
+ if (!hit) {
22
+ if (cache.size >= CACHE_CAP) cache.delete(cache.keys().next().value);
23
+ hit = make();
24
+ cache.set(key, hit);
25
+ }
26
+ return hit;
60
27
  }
61
28
  function numberFormat(locale, options) {
62
- const key = locale + (options ? JSON.stringify(options) : "");
63
- return cached(nfCache, key, () => new Intl.NumberFormat(locale, options));
29
+ const key = locale + (options ? JSON.stringify(options) : "");
30
+ return cached(nfCache, key, () => new Intl.NumberFormat(locale, options));
64
31
  }
65
32
  function dateTimeFormat(locale, options) {
66
- const key = locale + (options ? JSON.stringify(options) : "");
67
- return cached(dtfCache, key, () => new Intl.DateTimeFormat(locale, options));
33
+ const key = locale + (options ? JSON.stringify(options) : "");
34
+ return cached(dtfCache, key, () => new Intl.DateTimeFormat(locale, options));
68
35
  }
69
36
  function pluralRules(locale, type = "cardinal") {
70
- return cached(prCache, locale + type, () => new Intl.PluralRules(locale, { type }));
37
+ return cached(prCache, locale + type, () => new Intl.PluralRules(locale, { type }));
71
38
  }
72
39
  function relativeTimeFormat(locale) {
73
- return cached(rtfCache, locale, () => new Intl.RelativeTimeFormat(locale, { numeric: "auto" }));
40
+ return cached(rtfCache, locale, () => new Intl.RelativeTimeFormat(locale, { numeric: "auto" }));
74
41
  }
75
42
  function listFormat(locale, type) {
76
- return cached(lfCache, locale + type, () => new Intl.ListFormat(locale, { type }));
43
+ return cached(lfCache, locale + type, () => new Intl.ListFormat(locale, { type }));
77
44
  }
78
-
79
- // src/format.ts
45
+ //#endregion
46
+ //#region src/format.ts
80
47
  function formatNodes(nodes, ctx) {
81
- let out = "";
82
- for (const node of nodes) {
83
- if (node.kind === "text") out += node.value;
84
- else if (node.kind === "hash") out += autoFormat(ctx.hashValue, ctx.locale);
85
- else out += formatParam(node, ctx);
86
- }
87
- return out;
48
+ let out = "";
49
+ for (const node of nodes) if (node.kind === "text") out += node.value;
50
+ else if (node.kind === "hash") out += autoFormat(ctx.hashValue, ctx.locale);
51
+ else out += formatParam(node, ctx);
52
+ return out;
88
53
  }
89
54
  function formatParam(node, ctx) {
90
- const value = ctx.params?.[node.name];
91
- if (value === void 0) return `{${node.name}}`;
92
- if (node.variants) {
93
- const chosen = pickVariant(node.variants, value, ctx.locale, node.ordinal);
94
- if (!chosen) return "";
95
- return formatNodes(chosen, { ...ctx, hashValue: value });
96
- }
97
- if (node.format) return applyFormat(value, node.format, node.arg, ctx);
98
- return autoFormat(value, ctx.locale);
55
+ const value = ctx.params?.[node.name];
56
+ if (value === void 0) return `{${node.name}}`;
57
+ if (node.variants) {
58
+ const chosen = pickVariant(node.variants, value, ctx.locale, node.ordinal);
59
+ if (!chosen) return "";
60
+ return formatNodes(chosen, {
61
+ ...ctx,
62
+ hashValue: value
63
+ });
64
+ }
65
+ if (node.format) return applyFormat(value, node.format, node.arg, ctx);
66
+ return autoFormat(value, ctx.locale);
99
67
  }
100
68
  function pickVariant(variants, value, locale, ordinal) {
101
- const raw = String(value);
102
- if (typeof value === "number") {
103
- for (const [key, nodes] of variants) if (key === `=${raw}`) return nodes;
104
- const category = pluralRules(locale, ordinal ? "ordinal" : "cardinal").select(value);
105
- for (const [key, nodes] of variants) if (key === category) return nodes;
106
- } else {
107
- for (const [key, nodes] of variants) if (key === raw) return nodes;
108
- }
109
- for (const [key, nodes] of variants) if (key === "other") return nodes;
110
- return void 0;
69
+ const raw = String(value);
70
+ if (typeof value === "number") {
71
+ for (const [key, nodes] of variants) if (key === `=${raw}`) return nodes;
72
+ const category = pluralRules(locale, ordinal ? "ordinal" : "cardinal").select(value);
73
+ for (const [key, nodes] of variants) if (key === category) return nodes;
74
+ } else for (const [key, nodes] of variants) if (key === raw) return nodes;
75
+ for (const [key, nodes] of variants) if (key === "other") return nodes;
111
76
  }
112
77
  function applyFormat(value, format, arg, ctx) {
113
- const custom = ctx.formatters[format];
114
- if (custom) return custom(value, ctx.locale, arg);
115
- const { locale } = ctx;
116
- switch (format) {
117
- case "number":
118
- return numberFormat(locale).format(Number(value));
119
- case "integer":
120
- return numberFormat(locale, { maximumFractionDigits: 0 }).format(Number(value));
121
- case "percent":
122
- return numberFormat(locale, { style: "percent" }).format(Number(value));
123
- case "currency":
124
- if (!arg) return String(value);
125
- return numberFormat(locale, { style: "currency", currency: arg }).format(Number(value));
126
- case "date":
127
- return dateTimeFormat(
128
- locale,
129
- arg ? { dateStyle: arg } : void 0
130
- ).format(toDate(value));
131
- case "time":
132
- return dateTimeFormat(locale, {
133
- timeStyle: arg ?? "short"
134
- }).format(toDate(value));
135
- case "relative":
136
- return formatRelative(value, arg, locale);
137
- case "list": {
138
- if (!Array.isArray(value)) return String(value);
139
- const type = arg === "or" ? "disjunction" : arg === "unit" ? "unit" : "conjunction";
140
- return listFormat(locale, type).format(value.map((item) => autoFormat(item, locale)));
141
- }
142
- case "unit":
143
- if (!arg) return String(value);
144
- try {
145
- return numberFormat(locale, { style: "unit", unit: arg }).format(Number(value));
146
- } catch {
147
- warnOnce(`invalid unit "${arg}"`);
148
- return String(value);
149
- }
150
- default:
151
- warnOnce(`unknown format "${format}"`);
152
- return String(value);
153
- }
154
- }
155
- var REL_UNITS = [
156
- ["year", 31536e3],
157
- ["month", 2592e3],
158
- ["week", 604800],
159
- ["day", 86400],
160
- ["hour", 3600],
161
- ["minute", 60],
162
- ["second", 1]
78
+ const custom = ctx.formatters[format];
79
+ if (custom) return custom(value, ctx.locale, arg);
80
+ const { locale } = ctx;
81
+ switch (format) {
82
+ case "number": return numberFormat(locale).format(Number(value));
83
+ case "integer": return numberFormat(locale, { maximumFractionDigits: 0 }).format(Number(value));
84
+ case "percent": return numberFormat(locale, { style: "percent" }).format(Number(value));
85
+ case "currency":
86
+ if (!arg) return String(value);
87
+ return numberFormat(locale, {
88
+ style: "currency",
89
+ currency: arg
90
+ }).format(Number(value));
91
+ case "date": return dateTimeFormat(locale, arg ? { dateStyle: arg } : void 0).format(toDate(value));
92
+ case "time": return dateTimeFormat(locale, { timeStyle: arg ?? "short" }).format(toDate(value));
93
+ case "relative": return formatRelative(value, arg, locale);
94
+ case "list":
95
+ if (!Array.isArray(value)) return String(value);
96
+ return listFormat(locale, arg === "or" ? "disjunction" : arg === "unit" ? "unit" : "conjunction").format(value.map((item) => autoFormat(item, locale)));
97
+ case "unit":
98
+ if (!arg) return String(value);
99
+ try {
100
+ return numberFormat(locale, {
101
+ style: "unit",
102
+ unit: arg
103
+ }).format(Number(value));
104
+ } catch {
105
+ warnOnce(`invalid unit "${arg}"`);
106
+ return String(value);
107
+ }
108
+ default:
109
+ warnOnce(`unknown format "${format}"`);
110
+ return String(value);
111
+ }
112
+ }
113
+ const REL_UNITS = [
114
+ ["year", 31536e3],
115
+ ["month", 2592e3],
116
+ ["week", 604800],
117
+ ["day", 86400],
118
+ ["hour", 3600],
119
+ ["minute", 60],
120
+ ["second", 1]
163
121
  ];
164
122
  function formatRelative(value, arg, locale) {
165
- try {
166
- if (typeof value === "number" && arg) {
167
- return relativeTimeFormat(locale).format(value, arg);
168
- }
169
- if (value instanceof Date) {
170
- const diffSec = (value.getTime() - Date.now()) / 1e3;
171
- if (arg) {
172
- const per2 = REL_UNITS.find(([unit2]) => unit2 === arg)?.[1];
173
- if (!per2) throw new RangeError(arg);
174
- return relativeTimeFormat(locale).format(
175
- Math.round(diffSec / per2),
176
- arg
177
- );
178
- }
179
- const [unit, per] = REL_UNITS.find(([, s]) => Math.abs(diffSec) >= s) ?? ["second", 1];
180
- return relativeTimeFormat(locale).format(Math.round(diffSec / per), unit);
181
- }
182
- } catch {
183
- warnOnce(`invalid relative unit "${arg}"`);
184
- }
185
- return String(value);
186
- }
187
- var warned = /* @__PURE__ */ new Set();
123
+ try {
124
+ if (typeof value === "number" && arg) return relativeTimeFormat(locale).format(value, arg);
125
+ if (value instanceof Date) {
126
+ const diffSec = (value.getTime() - Date.now()) / 1e3;
127
+ if (arg) {
128
+ const per = REL_UNITS.find(([unit]) => unit === arg)?.[1];
129
+ if (!per) throw new RangeError(arg);
130
+ return relativeTimeFormat(locale).format(Math.round(diffSec / per), arg);
131
+ }
132
+ const [unit, per] = REL_UNITS.find(([, s]) => Math.abs(diffSec) >= s) ?? ["second", 1];
133
+ return relativeTimeFormat(locale).format(Math.round(diffSec / per), unit);
134
+ }
135
+ } catch {
136
+ warnOnce(`invalid relative unit "${arg}"`);
137
+ }
138
+ return String(value);
139
+ }
140
+ const warned = /* @__PURE__ */ new Set();
188
141
  function warnOnce(msg) {
189
- if (warned.has(msg)) return;
190
- warned.add(msg);
191
- console.warn(`[verbaly] ${msg}`);
142
+ if (warned.has(msg)) return;
143
+ warned.add(msg);
144
+ console.warn(`[verbaly] ${msg}`);
192
145
  }
193
146
  function autoFormat(value, locale) {
194
- if (value === null || value === void 0) return "";
195
- if (typeof value === "number") return numberFormat(locale).format(value);
196
- if (value instanceof Date) return dateTimeFormat(locale).format(value);
197
- return String(value);
147
+ if (value === null || value === void 0) return "";
148
+ if (typeof value === "number") return numberFormat(locale).format(value);
149
+ if (value instanceof Date) return dateTimeFormat(locale).format(value);
150
+ return String(value);
198
151
  }
199
152
  function toDate(value) {
200
- return value instanceof Date ? value : new Date(value);
153
+ return value instanceof Date ? value : new Date(value);
201
154
  }
202
-
203
- // src/icu.ts
204
- var ICU_ARG = /\{\s*[a-zA-Z0-9_]+\s*,\s*(?:plural|selectordinal|select|number|date|time)\b/;
155
+ //#endregion
156
+ //#region src/icu.ts
157
+ const ICU_ARG = /\{\s*[a-zA-Z0-9_]+\s*,\s*(?:plural|selectordinal|select|number|date|time)\b/;
205
158
  function isIcu(message) {
206
- return ICU_ARG.test(message);
159
+ return ICU_ARG.test(message);
207
160
  }
208
161
  function parseIcu(message) {
209
- let i = 0;
210
- const at = () => message.charAt(i);
211
- const skipWs = () => {
212
- while (i < message.length && /\s/.test(at())) i++;
213
- };
214
- const readIdent = () => {
215
- let s = "";
216
- while (i < message.length && /[a-zA-Z0-9_]/.test(at())) s += message[i++];
217
- return s;
218
- };
219
- function parseBody(inPlural) {
220
- const nodes = [];
221
- let buf = "";
222
- const flush = () => {
223
- if (buf) nodes.push({ kind: "text", value: buf });
224
- buf = "";
225
- };
226
- while (i < message.length) {
227
- const ch = at();
228
- if (ch === "}") break;
229
- if (ch === "{") {
230
- flush();
231
- nodes.push(parseArg());
232
- } else if (ch === "#" && inPlural) {
233
- flush();
234
- nodes.push({ kind: "hash" });
235
- i++;
236
- } else if (ch === "'") {
237
- buf += readQuoted();
238
- } else {
239
- buf += ch;
240
- i++;
241
- }
242
- }
243
- flush();
244
- return nodes;
245
- }
246
- function readQuoted() {
247
- i++;
248
- if (at() === "'") {
249
- i++;
250
- return "'";
251
- }
252
- const next = at();
253
- if (next !== "{" && next !== "}" && next !== "#") return "'";
254
- let out = "";
255
- while (i < message.length) {
256
- if (at() === "'") {
257
- if (message.charAt(i + 1) === "'") {
258
- out += "'";
259
- i += 2;
260
- continue;
261
- }
262
- i++;
263
- return out;
264
- }
265
- out += message[i++];
266
- }
267
- return out;
268
- }
269
- function parseArg() {
270
- i++;
271
- skipWs();
272
- const name = readIdent();
273
- skipWs();
274
- if (at() === "}") {
275
- i++;
276
- return { kind: "param", name };
277
- }
278
- if (at() === ",") i++;
279
- skipWs();
280
- const type = readIdent();
281
- const node = { kind: "param", name };
282
- if (type === "number" || type === "date" || type === "time") {
283
- skipWs();
284
- let style = "";
285
- if (at() === ",") {
286
- i++;
287
- skipWs();
288
- while (i < message.length && at() !== "}" && at() !== ",") style += message[i++];
289
- style = style.trim();
290
- }
291
- if (type === "number") {
292
- node.format = style === "integer" ? "integer" : style === "percent" ? "percent" : style === "currency" ? "currency" : "number";
293
- } else {
294
- node.format = type;
295
- if (style) node.arg = style;
296
- }
297
- skipToClose();
298
- return node;
299
- }
300
- if (type === "plural" || type === "selectordinal" || type === "select") {
301
- if (type === "selectordinal") node.ordinal = true;
302
- const variants = [];
303
- skipWs();
304
- if (at() === ",") i++;
305
- skipWs();
306
- if (type !== "select" && message.startsWith("offset:", i)) {
307
- i += 7;
308
- skipWs();
309
- while (i < message.length && /[0-9]/.test(at())) i++;
310
- skipWs();
311
- }
312
- while (i < message.length && at() !== "}") {
313
- const selector = readSelector();
314
- skipWs();
315
- if (at() !== "{") break;
316
- i++;
317
- const body = parseBody(type !== "select");
318
- if (at() === "}") i++;
319
- variants.push([selector, body]);
320
- skipWs();
321
- }
322
- if (at() === "}") i++;
323
- node.variants = variants;
324
- return node;
325
- }
326
- skipToClose();
327
- return node;
328
- }
329
- function readSelector() {
330
- if (at() === "=") {
331
- let s2 = "=";
332
- i++;
333
- while (i < message.length && /[0-9]/.test(at())) s2 += message[i++];
334
- return s2;
335
- }
336
- let s = "";
337
- while (i < message.length && !/[\s{]/.test(at())) s += message[i++];
338
- return s;
339
- }
340
- function skipToClose() {
341
- while (i < message.length && at() !== "}") i++;
342
- if (at() === "}") i++;
343
- }
344
- return parseBody(false);
345
- }
346
-
347
- // src/parse.ts
348
- var astCache = /* @__PURE__ */ new Map();
349
- var AST_CACHE_MAX = 2e3;
162
+ let i = 0;
163
+ const at = () => message.charAt(i);
164
+ const skipWs = () => {
165
+ while (i < message.length && /\s/.test(at())) i++;
166
+ };
167
+ const readIdent = () => {
168
+ let s = "";
169
+ while (i < message.length && /[a-zA-Z0-9_]/.test(at())) s += message[i++];
170
+ return s;
171
+ };
172
+ function parseBody(inPlural) {
173
+ const nodes = [];
174
+ let buf = "";
175
+ const flush = () => {
176
+ if (buf) nodes.push({
177
+ kind: "text",
178
+ value: buf
179
+ });
180
+ buf = "";
181
+ };
182
+ while (i < message.length) {
183
+ const ch = at();
184
+ if (ch === "}") break;
185
+ if (ch === "{") {
186
+ flush();
187
+ nodes.push(parseArg());
188
+ } else if (ch === "#" && inPlural) {
189
+ flush();
190
+ nodes.push({ kind: "hash" });
191
+ i++;
192
+ } else if (ch === "'") buf += readQuoted();
193
+ else {
194
+ buf += ch;
195
+ i++;
196
+ }
197
+ }
198
+ flush();
199
+ return nodes;
200
+ }
201
+ function readQuoted() {
202
+ i++;
203
+ if (at() === "'") {
204
+ i++;
205
+ return "'";
206
+ }
207
+ const next = at();
208
+ if (next !== "{" && next !== "}" && next !== "#") return "'";
209
+ let out = "";
210
+ while (i < message.length) {
211
+ if (at() === "'") {
212
+ if (message.charAt(i + 1) === "'") {
213
+ out += "'";
214
+ i += 2;
215
+ continue;
216
+ }
217
+ i++;
218
+ return out;
219
+ }
220
+ out += message[i++];
221
+ }
222
+ return out;
223
+ }
224
+ function parseArg() {
225
+ i++;
226
+ skipWs();
227
+ const name = readIdent();
228
+ skipWs();
229
+ if (at() === "}") {
230
+ i++;
231
+ return {
232
+ kind: "param",
233
+ name
234
+ };
235
+ }
236
+ if (at() === ",") i++;
237
+ skipWs();
238
+ const type = readIdent();
239
+ const node = {
240
+ kind: "param",
241
+ name
242
+ };
243
+ if (type === "number" || type === "date" || type === "time") {
244
+ skipWs();
245
+ let style = "";
246
+ if (at() === ",") {
247
+ i++;
248
+ skipWs();
249
+ while (i < message.length && at() !== "}" && at() !== ",") style += message[i++];
250
+ style = style.trim();
251
+ }
252
+ if (type === "number") node.format = style === "integer" ? "integer" : style === "percent" ? "percent" : style === "currency" ? "currency" : "number";
253
+ else {
254
+ node.format = type;
255
+ if (style) node.arg = style;
256
+ }
257
+ skipToClose();
258
+ return node;
259
+ }
260
+ if (type === "plural" || type === "selectordinal" || type === "select") {
261
+ if (type === "selectordinal") node.ordinal = true;
262
+ const variants = [];
263
+ skipWs();
264
+ if (at() === ",") i++;
265
+ skipWs();
266
+ if (type !== "select" && message.startsWith("offset:", i)) {
267
+ i += 7;
268
+ skipWs();
269
+ while (i < message.length && /[0-9]/.test(at())) i++;
270
+ skipWs();
271
+ }
272
+ while (i < message.length && at() !== "}") {
273
+ const selector = readSelector();
274
+ skipWs();
275
+ if (at() !== "{") break;
276
+ i++;
277
+ const body = parseBody(type !== "select");
278
+ if (at() === "}") i++;
279
+ variants.push([selector, body]);
280
+ skipWs();
281
+ }
282
+ if (at() === "}") i++;
283
+ node.variants = variants;
284
+ return node;
285
+ }
286
+ skipToClose();
287
+ return node;
288
+ }
289
+ function readSelector() {
290
+ if (at() === "=") {
291
+ let s = "=";
292
+ i++;
293
+ while (i < message.length && /[0-9]/.test(at())) s += message[i++];
294
+ return s;
295
+ }
296
+ let s = "";
297
+ while (i < message.length && !/[\s{]/.test(at())) s += message[i++];
298
+ return s;
299
+ }
300
+ function skipToClose() {
301
+ while (i < message.length && at() !== "}") i++;
302
+ if (at() === "}") i++;
303
+ }
304
+ return parseBody(false);
305
+ }
306
+ //#endregion
307
+ //#region src/parse.ts
308
+ const astCache = /* @__PURE__ */ new Map();
309
+ const AST_CACHE_MAX = 2e3;
350
310
  function parse(message) {
351
- let cached2 = astCache.get(message);
352
- if (!cached2) {
353
- if (astCache.size >= AST_CACHE_MAX) astCache.clear();
354
- cached2 = isIcu(message) ? parseIcu(message) : parseMessage(message, false);
355
- astCache.set(message, cached2);
356
- }
357
- return cached2;
311
+ let cached = astCache.get(message);
312
+ if (!cached) {
313
+ if (astCache.size >= AST_CACHE_MAX) astCache.clear();
314
+ cached = isIcu(message) ? parseIcu(message) : parseMessage(message, false);
315
+ astCache.set(message, cached);
316
+ }
317
+ return cached;
358
318
  }
359
319
  function parseMessage(input, inVariant) {
360
- const nodes = [];
361
- let buf = "";
362
- let i = 0;
363
- const flush = () => {
364
- if (buf) nodes.push({ kind: "text", value: buf });
365
- buf = "";
366
- };
367
- while (i < input.length) {
368
- const ch = input[i];
369
- if (ch === "{") {
370
- if (input[i + 1] === "{") {
371
- buf += "{";
372
- i += 2;
373
- continue;
374
- }
375
- const close = findClose(input, i);
376
- if (close < 0) {
377
- buf += input.slice(i);
378
- break;
379
- }
380
- flush();
381
- nodes.push(parsePlaceholder(input.slice(i + 1, close)));
382
- i = close + 1;
383
- } else if (ch === "}" && input[i + 1] === "}") {
384
- buf += "}";
385
- i += 2;
386
- } else if (inVariant && ch === "#") {
387
- if (input[i + 1] === "#") {
388
- buf += "#";
389
- i += 2;
390
- } else {
391
- flush();
392
- nodes.push({ kind: "hash" });
393
- i += 1;
394
- }
395
- } else {
396
- buf += ch;
397
- i += 1;
398
- }
399
- }
400
- flush();
401
- return nodes;
320
+ const nodes = [];
321
+ let buf = "";
322
+ let i = 0;
323
+ const flush = () => {
324
+ if (buf) nodes.push({
325
+ kind: "text",
326
+ value: buf
327
+ });
328
+ buf = "";
329
+ };
330
+ while (i < input.length) {
331
+ const ch = input[i];
332
+ if (ch === "{") {
333
+ if (input[i + 1] === "{") {
334
+ buf += "{";
335
+ i += 2;
336
+ continue;
337
+ }
338
+ const close = findClose(input, i);
339
+ if (close < 0) {
340
+ buf += input.slice(i);
341
+ break;
342
+ }
343
+ flush();
344
+ nodes.push(parsePlaceholder(input.slice(i + 1, close)));
345
+ i = close + 1;
346
+ } else if (ch === "}" && input[i + 1] === "}") {
347
+ buf += "}";
348
+ i += 2;
349
+ } else if (inVariant && ch === "#") if (input[i + 1] === "#") {
350
+ buf += "#";
351
+ i += 2;
352
+ } else {
353
+ flush();
354
+ nodes.push({ kind: "hash" });
355
+ i += 1;
356
+ }
357
+ else {
358
+ buf += ch;
359
+ i += 1;
360
+ }
361
+ }
362
+ flush();
363
+ return nodes;
402
364
  }
403
365
  function findClose(input, open) {
404
- let depth = 0;
405
- let i = open;
406
- while (i < input.length) {
407
- const ch = input[i];
408
- if (ch === "{") {
409
- if (input[i + 1] === "{") {
410
- i += 2;
411
- continue;
412
- }
413
- depth += 1;
414
- } else if (ch === "}") {
415
- if (input[i + 1] === "}") {
416
- i += 2;
417
- continue;
418
- }
419
- depth -= 1;
420
- if (depth === 0) return i;
421
- }
422
- i += 1;
423
- }
424
- return -1;
366
+ let depth = 0;
367
+ let i = open;
368
+ while (i < input.length) {
369
+ const ch = input[i];
370
+ if (ch === "{") {
371
+ if (input[i + 1] === "{") {
372
+ i += 2;
373
+ continue;
374
+ }
375
+ depth += 1;
376
+ } else if (ch === "}") {
377
+ if (input[i + 1] === "}") {
378
+ i += 2;
379
+ continue;
380
+ }
381
+ depth -= 1;
382
+ if (depth === 0) return i;
383
+ }
384
+ i += 1;
385
+ }
386
+ return -1;
425
387
  }
426
388
  function parsePlaceholder(inner) {
427
- const segments = splitTop(inner);
428
- const head = (segments[0] ?? "").trim();
429
- if (!head) return { kind: "text", value: `{${inner}}` };
430
- const colon = head.indexOf(":");
431
- const name = (colon < 0 ? head : head.slice(0, colon)).trim();
432
- if (!name) return { kind: "text", value: `{${inner}}` };
433
- const node = { kind: "param", name };
434
- if (colon >= 0) {
435
- const fmtRaw = head.slice(colon + 1).trim();
436
- const slash = fmtRaw.indexOf("/");
437
- node.format = (slash < 0 ? fmtRaw : fmtRaw.slice(0, slash)).trim();
438
- if (slash >= 0) node.arg = fmtRaw.slice(slash + 1).trim();
439
- }
440
- if (segments.length > 1) {
441
- node.variants = [];
442
- for (const seg of segments.slice(1)) {
443
- const sep = seg.indexOf(":");
444
- if (sep < 0) continue;
445
- const key = seg.slice(0, sep).trim();
446
- const body = seg.slice(sep + 1).trim();
447
- if (key) node.variants.push([key, parseMessage(body, true)]);
448
- }
449
- }
450
- return node;
389
+ const segments = splitTop(inner);
390
+ const head = (segments[0] ?? "").trim();
391
+ if (!head) return {
392
+ kind: "text",
393
+ value: `{${inner}}`
394
+ };
395
+ const colon = head.indexOf(":");
396
+ const name = (colon < 0 ? head : head.slice(0, colon)).trim();
397
+ if (!name) return {
398
+ kind: "text",
399
+ value: `{${inner}}`
400
+ };
401
+ const node = {
402
+ kind: "param",
403
+ name
404
+ };
405
+ if (colon >= 0) {
406
+ const fmtRaw = head.slice(colon + 1).trim();
407
+ const slash = fmtRaw.indexOf("/");
408
+ node.format = (slash < 0 ? fmtRaw : fmtRaw.slice(0, slash)).trim();
409
+ if (slash >= 0) node.arg = fmtRaw.slice(slash + 1).trim();
410
+ }
411
+ if (segments.length > 1) {
412
+ node.variants = [];
413
+ for (const seg of segments.slice(1)) {
414
+ const sep = seg.indexOf(":");
415
+ if (sep < 0) continue;
416
+ const key = seg.slice(0, sep).trim();
417
+ const body = seg.slice(sep + 1).trim();
418
+ if (key) node.variants.push([key, parseMessage(body, true)]);
419
+ }
420
+ }
421
+ return node;
451
422
  }
452
423
  function splitTop(input) {
453
- const parts = [];
454
- let buf = "";
455
- let depth = 0;
456
- let i = 0;
457
- while (i < input.length) {
458
- const ch = input[i];
459
- if (ch === "{") {
460
- if (input[i + 1] === "{") {
461
- buf += "{{";
462
- i += 2;
463
- continue;
464
- }
465
- depth += 1;
466
- buf += ch;
467
- } else if (ch === "}") {
468
- if (input[i + 1] === "}") {
469
- buf += "}}";
470
- i += 2;
471
- continue;
472
- }
473
- depth -= 1;
474
- buf += ch;
475
- } else if (ch === "|" && depth === 0) {
476
- if (input[i + 1] === "|") {
477
- buf += "|";
478
- i += 2;
479
- continue;
480
- }
481
- parts.push(buf);
482
- buf = "";
483
- } else {
484
- buf += ch;
485
- }
486
- i += 1;
487
- }
488
- parts.push(buf);
489
- return parts;
490
- }
491
-
492
- // src/instance.ts
424
+ const parts = [];
425
+ let buf = "";
426
+ let depth = 0;
427
+ let i = 0;
428
+ while (i < input.length) {
429
+ const ch = input[i];
430
+ if (ch === "{") {
431
+ if (input[i + 1] === "{") {
432
+ buf += "{{";
433
+ i += 2;
434
+ continue;
435
+ }
436
+ depth += 1;
437
+ buf += ch;
438
+ } else if (ch === "}") {
439
+ if (input[i + 1] === "}") {
440
+ buf += "}}";
441
+ i += 2;
442
+ continue;
443
+ }
444
+ depth -= 1;
445
+ buf += ch;
446
+ } else if (ch === "|" && depth === 0) {
447
+ if (input[i + 1] === "|") {
448
+ buf += "|";
449
+ i += 2;
450
+ continue;
451
+ }
452
+ parts.push(buf);
453
+ buf = "";
454
+ } else buf += ch;
455
+ i += 1;
456
+ }
457
+ parts.push(buf);
458
+ return parts;
459
+ }
460
+ //#endregion
461
+ //#region src/instance.ts
493
462
  function createVerbaly(options = {}) {
494
- const dict = {};
495
- const listeners = /* @__PURE__ */ new Set();
496
- const formatters = options.formatters ?? {};
497
- const loaders = options.loaders ?? {};
498
- const loaded = /* @__PURE__ */ new Set();
499
- const inFlight = /* @__PURE__ */ new Map();
500
- const warned2 = /* @__PURE__ */ new Set();
501
- const fallbacks = options.fallback ? Array.isArray(options.fallback) ? options.fallback : [options.fallback] : [];
502
- let locale = options.locale ?? detectLocale();
503
- let version = 0;
504
- let chainCache = null;
505
- if (options.messages) {
506
- for (const [loc, tree] of Object.entries(options.messages)) {
507
- dict[loc] = flatten(tree);
508
- }
509
- }
510
- function chain() {
511
- if (chainCache) return chainCache;
512
- const result = [];
513
- const parts = locale.split("-");
514
- while (parts.length > 0) {
515
- result.push(parts.join("-"));
516
- parts.pop();
517
- }
518
- for (const fb of fallbacks) if (!result.includes(fb)) result.push(fb);
519
- chainCache = result;
520
- return result;
521
- }
522
- function lookup(key) {
523
- for (const loc of chain()) {
524
- const msg = dict[loc]?.[key];
525
- if (msg !== void 0) return msg;
526
- }
527
- return void 0;
528
- }
529
- function translate(key, params) {
530
- const msg = lookup(key);
531
- if (msg === void 0) {
532
- const replacement = options.onMissing?.(key, locale);
533
- if (typeof replacement === "string") return replacement;
534
- if (!options.onMissing && !warned2.has(key)) {
535
- warned2.add(key);
536
- console.warn(`[verbaly] missing key "${key}" (${locale})`);
537
- }
538
- return key;
539
- }
540
- return formatNodes(parse(msg), { locale, params, formatters });
541
- }
542
- function tagged(strings, values) {
543
- let out = strings[0] ?? "";
544
- for (let i = 0; i < values.length; i++) {
545
- out += autoFormat(values[i], locale) + (strings[i + 1] ?? "");
546
- }
547
- return out;
548
- }
549
- function notify() {
550
- version += 1;
551
- for (const fn of listeners) fn();
552
- }
553
- const t = ((first, ...rest) => {
554
- if (isTemplateStrings(first)) return tagged(first, rest);
555
- return translate(first, rest[0]);
556
- });
557
- t.id = () => (strings, ...values) => tagged(strings, values);
558
- function pendingLoader(target) {
559
- const parts = target.split("-");
560
- while (parts.length > 0) {
561
- const candidate = parts.join("-");
562
- if (loaders[candidate] && !loaded.has(candidate)) return candidate;
563
- if (loaders[candidate]) return void 0;
564
- parts.pop();
565
- }
566
- return void 0;
567
- }
568
- function loadLocale(target) {
569
- const pending = pendingLoader(target);
570
- if (!pending) return Promise.resolve();
571
- const running = inFlight.get(pending);
572
- if (running) return running;
573
- const load = loaders[pending]().then((mod) => {
574
- loaded.add(pending);
575
- inFlight.delete(pending);
576
- addMessages(
577
- pending,
578
- "default" in mod ? mod.default : mod
579
- );
580
- }).catch((error) => {
581
- inFlight.delete(pending);
582
- throw error;
583
- });
584
- inFlight.set(pending, load);
585
- return load;
586
- }
587
- function addMessages(loc, messages) {
588
- dict[loc] = { ...dict[loc], ...flatten(messages) };
589
- notify();
590
- }
591
- return {
592
- get locale() {
593
- return locale;
594
- },
595
- get locales() {
596
- return [.../* @__PURE__ */ new Set([...Object.keys(dict), ...Object.keys(loaders)])];
597
- },
598
- get version() {
599
- return version;
600
- },
601
- t,
602
- setLocale(next) {
603
- if (pendingLoader(next)) {
604
- void loadLocale(next).catch(() => {
605
- if (!warned2.has(`load:${next}`)) {
606
- warned2.add(`load:${next}`);
607
- console.warn(`[verbaly] failed to load catalog for "${next}"`);
608
- }
609
- });
610
- }
611
- if (next === locale) return;
612
- locale = next;
613
- chainCache = null;
614
- notify();
615
- },
616
- loadLocale,
617
- addMessages,
618
- subscribe(listener) {
619
- listeners.add(listener);
620
- return () => {
621
- listeners.delete(listener);
622
- };
623
- },
624
- has(key) {
625
- return lookup(key) !== void 0;
626
- }
627
- };
463
+ const dict = {};
464
+ const listeners = /* @__PURE__ */ new Set();
465
+ const formatters = options.formatters ?? {};
466
+ const loaders = options.loaders ?? {};
467
+ const loaded = /* @__PURE__ */ new Set();
468
+ const inFlight = /* @__PURE__ */ new Map();
469
+ const warned = /* @__PURE__ */ new Set();
470
+ const fallbacks = options.fallback ? Array.isArray(options.fallback) ? options.fallback : [options.fallback] : [];
471
+ let locale = options.locale ?? detectLocale();
472
+ let version = 0;
473
+ let chainCache = null;
474
+ if (options.messages) for (const [loc, tree] of Object.entries(options.messages)) dict[loc] = flatten(tree);
475
+ function chain() {
476
+ if (chainCache) return chainCache;
477
+ const result = [];
478
+ const parts = locale.split("-");
479
+ while (parts.length > 0) {
480
+ result.push(parts.join("-"));
481
+ parts.pop();
482
+ }
483
+ for (const fb of fallbacks) if (!result.includes(fb)) result.push(fb);
484
+ chainCache = result;
485
+ return result;
486
+ }
487
+ function lookup(key) {
488
+ for (const loc of chain()) {
489
+ const msg = dict[loc]?.[key];
490
+ if (msg !== void 0) return msg;
491
+ }
492
+ }
493
+ function translate(key, params) {
494
+ const msg = lookup(key);
495
+ if (msg === void 0) {
496
+ const replacement = options.onMissing?.(key, locale);
497
+ if (typeof replacement === "string") return replacement;
498
+ if (!options.onMissing && !warned.has(key)) {
499
+ warned.add(key);
500
+ console.warn(`[verbaly] missing key "${key}" (${locale})`);
501
+ }
502
+ return key;
503
+ }
504
+ return formatNodes(parse(msg), {
505
+ locale,
506
+ params,
507
+ formatters
508
+ });
509
+ }
510
+ function tagged(strings, values) {
511
+ let out = strings[0] ?? "";
512
+ for (let i = 0; i < values.length; i++) out += autoFormat(values[i], locale) + (strings[i + 1] ?? "");
513
+ return out;
514
+ }
515
+ function notify() {
516
+ version += 1;
517
+ for (const fn of listeners) fn();
518
+ }
519
+ const t = ((first, ...rest) => {
520
+ if (isTemplateStrings(first)) return tagged(first, rest);
521
+ return translate(first, rest[0]);
522
+ });
523
+ t.id = () => (strings, ...values) => tagged(strings, values);
524
+ function pendingLoader(target) {
525
+ const parts = target.split("-");
526
+ while (parts.length > 0) {
527
+ const candidate = parts.join("-");
528
+ if (loaders[candidate] && !loaded.has(candidate)) return candidate;
529
+ if (loaders[candidate]) return void 0;
530
+ parts.pop();
531
+ }
532
+ }
533
+ function loadLocale(target) {
534
+ const pending = pendingLoader(target);
535
+ if (!pending) return Promise.resolve();
536
+ const running = inFlight.get(pending);
537
+ if (running) return running;
538
+ const load = loaders[pending]().then((mod) => {
539
+ loaded.add(pending);
540
+ inFlight.delete(pending);
541
+ addMessages(pending, "default" in mod ? mod.default : mod);
542
+ }).catch((error) => {
543
+ inFlight.delete(pending);
544
+ throw error;
545
+ });
546
+ inFlight.set(pending, load);
547
+ return load;
548
+ }
549
+ function addMessages(loc, messages) {
550
+ dict[loc] = {
551
+ ...dict[loc],
552
+ ...flatten(messages)
553
+ };
554
+ notify();
555
+ }
556
+ return {
557
+ get locale() {
558
+ return locale;
559
+ },
560
+ get locales() {
561
+ return [.../* @__PURE__ */ new Set([...Object.keys(dict), ...Object.keys(loaders)])];
562
+ },
563
+ get version() {
564
+ return version;
565
+ },
566
+ t,
567
+ setLocale(next) {
568
+ if (pendingLoader(next)) loadLocale(next).catch(() => {
569
+ if (!warned.has(`load:${next}`)) {
570
+ warned.add(`load:${next}`);
571
+ console.warn(`[verbaly] failed to load catalog for "${next}"`);
572
+ }
573
+ });
574
+ if (next === locale) return;
575
+ locale = next;
576
+ chainCache = null;
577
+ notify();
578
+ },
579
+ loadLocale,
580
+ addMessages,
581
+ subscribe(listener) {
582
+ listeners.add(listener);
583
+ return () => {
584
+ listeners.delete(listener);
585
+ };
586
+ },
587
+ has(key) {
588
+ return lookup(key) !== void 0;
589
+ }
590
+ };
628
591
  }
629
592
  function isTemplateStrings(value) {
630
- return Array.isArray(value) && "raw" in value;
593
+ return Array.isArray(value) && "raw" in value;
631
594
  }
632
595
  function detectLocale() {
633
- return typeof navigator !== "undefined" && navigator.language ? navigator.language : "en";
596
+ return typeof navigator !== "undefined" && navigator.language ? navigator.language : "en";
634
597
  }
635
-
636
- // src/tags.ts
637
- var TAG = /<(\/?)([a-zA-Z][\w-]*)(\/?)>/g;
598
+ //#endregion
599
+ //#region src/tags.ts
600
+ const TAG = /<(\/?)([a-zA-Z][\w-]*)(\/?)>/g;
638
601
  function parseTags(text) {
639
- const re = new RegExp(TAG.source, "g");
640
- const root = [];
641
- const stack = [];
642
- const top = () => stack.length ? stack[stack.length - 1].children : root;
643
- const pushText = (s) => {
644
- if (s) top().push(s);
645
- };
646
- let last = 0;
647
- let m;
648
- while ((m = re.exec(text)) !== null) {
649
- const [full, closing, name, selfClose] = m;
650
- pushText(text.slice(last, m.index));
651
- last = m.index + full.length;
652
- if (selfClose) {
653
- top().push({ name, children: [] });
654
- } else if (closing) {
655
- if (stack.length && stack[stack.length - 1].name === name) {
656
- const node = stack.pop();
657
- top().push(node);
658
- } else {
659
- pushText(full);
660
- }
661
- } else {
662
- stack.push({ name, children: [] });
663
- }
664
- }
665
- pushText(text.slice(last));
666
- while (stack.length) {
667
- const node = stack.pop();
668
- top().push(...node.children);
669
- }
670
- return root;
671
- }
672
-
673
- // src/dom.ts
674
- var UNSAFE_HREF = /^\s*(javascript|data|vbscript):/i;
602
+ const re = new RegExp(TAG.source, "g");
603
+ const root = [];
604
+ const stack = [];
605
+ const top = () => stack.length ? stack[stack.length - 1].children : root;
606
+ const pushText = (s) => {
607
+ if (s) top().push(s);
608
+ };
609
+ let last = 0;
610
+ let m;
611
+ while ((m = re.exec(text)) !== null) {
612
+ const [full, closing, name, selfClose] = m;
613
+ pushText(text.slice(last, m.index));
614
+ last = m.index + full.length;
615
+ if (selfClose) top().push({
616
+ name,
617
+ children: []
618
+ });
619
+ else if (closing) if (stack.length && stack[stack.length - 1].name === name) {
620
+ const node = stack.pop();
621
+ top().push(node);
622
+ } else pushText(full);
623
+ else stack.push({
624
+ name,
625
+ children: []
626
+ });
627
+ }
628
+ pushText(text.slice(last));
629
+ while (stack.length) {
630
+ const node = stack.pop();
631
+ top().push(...node.children);
632
+ }
633
+ return root;
634
+ }
635
+ //#endregion
636
+ //#region src/dom.ts
637
+ const UNSAFE_HREF = /^\s*(javascript|data|vbscript):/i;
675
638
  function safeHref(href) {
676
- if (UNSAFE_HREF.test(href)) {
677
- console.warn(`[verbaly] blocked unsafe href: ${href}`);
678
- return void 0;
679
- }
680
- return href;
681
- }
682
- var RICH_TAGS = [
683
- "em",
684
- "strong",
685
- "code",
686
- "b",
687
- "i",
688
- "u",
689
- "s",
690
- "small",
691
- "mark",
692
- "sub",
693
- "sup",
694
- "span",
695
- "kbd",
696
- "abbr",
697
- "br",
698
- "wbr"
639
+ if (UNSAFE_HREF.test(href)) {
640
+ console.warn(`[verbaly] blocked unsafe href: ${href}`);
641
+ return;
642
+ }
643
+ return href;
644
+ }
645
+ const RICH_TAGS = [
646
+ "em",
647
+ "strong",
648
+ "code",
649
+ "b",
650
+ "i",
651
+ "u",
652
+ "s",
653
+ "small",
654
+ "mark",
655
+ "sub",
656
+ "sup",
657
+ "span",
658
+ "kbd",
659
+ "abbr",
660
+ "br",
661
+ "wbr"
699
662
  ];
700
663
  function bindDom(instance, options = {}) {
701
- if (typeof document === "undefined") {
702
- throw new Error("[verbaly] bindDom requires a DOM");
703
- }
704
- const t = instance.t;
705
- const root = options.root ?? document.body;
706
- const attr = options.attribute ?? "data-verbaly";
707
- const argsAttr = `${attr}-args`;
708
- const attrsAttr = `${attr}-attr`;
709
- const richAttr = `${attr}-rich`;
710
- const linksAttr = `${attr}-links`;
711
- const richTags = new Set(options.richTags ?? RICH_TAGS);
712
- const globalLinks = options.richLinks;
713
- const argsCache = /* @__PURE__ */ new WeakMap();
714
- const linksCache = /* @__PURE__ */ new WeakMap();
715
- function cachedArgs(el) {
716
- const raw = el.getAttribute(argsAttr);
717
- const hit = argsCache.get(el);
718
- if (hit && hit.raw === raw) return hit.params;
719
- const params = parseArgs(raw);
720
- argsCache.set(el, { raw, params });
721
- return params;
722
- }
723
- function cachedLinks(el) {
724
- const raw = el.getAttribute(linksAttr);
725
- if (!raw) return globalLinks;
726
- const hit = linksCache.get(el);
727
- if (hit && hit.raw === raw) return hit.links;
728
- const own = parseArgs(raw);
729
- const links = own ? globalLinks ? { ...globalLinks, ...own } : own : globalLinks;
730
- linksCache.set(el, { raw, links });
731
- return links;
732
- }
733
- function renderRich(el, nodes, links) {
734
- for (const node of nodes) {
735
- if (typeof node === "string") {
736
- el.append(node);
737
- } else if (links?.[node.name] !== void 0) {
738
- const link = links[node.name];
739
- const { href, target, rel } = typeof link === "string" ? { href: link } : link;
740
- const a = el.ownerDocument.createElement("a");
741
- const safe = safeHref(href);
742
- if (safe !== void 0) a.setAttribute("href", safe);
743
- if (target) a.setAttribute("target", target);
744
- if (rel) a.setAttribute("rel", rel);
745
- renderRich(a, node.children, links);
746
- el.append(a);
747
- } else if (richTags.has(node.name)) {
748
- const child = el.ownerDocument.createElement(node.name);
749
- renderRich(child, node.children, links);
750
- el.append(child);
751
- } else {
752
- renderRich(el, node.children, links);
753
- }
754
- }
755
- }
756
- function render(el) {
757
- const args = cachedArgs(el);
758
- const key = el.getAttribute(attr);
759
- if (key) {
760
- const text = t(key, args);
761
- if (el.hasAttribute(richAttr)) {
762
- el.textContent = "";
763
- renderRich(el, parseTags(text), cachedLinks(el));
764
- } else {
765
- el.textContent = text;
766
- }
767
- }
768
- const attrMap = parseArgs(el.getAttribute(attrsAttr));
769
- if (attrMap) {
770
- for (const [name, attrKey] of Object.entries(attrMap)) {
771
- if (typeof attrKey !== "string" || name.toLowerCase().startsWith("on")) continue;
772
- el.setAttribute(name, t(attrKey, args));
773
- }
774
- }
775
- }
776
- const selector = `[${attr}], [${attrsAttr}]`;
777
- function renderAll(scope) {
778
- if (scope instanceof Element && scope.matches(selector)) render(scope);
779
- for (const el of scope.querySelectorAll(selector)) render(el);
780
- }
781
- renderAll(root);
782
- const unsubscribe = instance.subscribe(() => renderAll(root));
783
- const observer = new MutationObserver((records) => {
784
- for (const record of records) {
785
- if (record.type === "attributes" && record.target instanceof Element) {
786
- render(record.target);
787
- } else if (record.type === "childList") {
788
- for (const node of record.addedNodes) {
789
- if (node instanceof Element) renderAll(node);
790
- }
791
- }
792
- }
793
- });
794
- observer.observe(root instanceof Document ? root.documentElement : root, {
795
- childList: true,
796
- subtree: true,
797
- attributes: true,
798
- attributeFilter: [attr, argsAttr, attrsAttr, richAttr, linksAttr]
799
- });
800
- return () => {
801
- unsubscribe();
802
- observer.disconnect();
803
- };
664
+ if (typeof document === "undefined") throw new Error("[verbaly] bindDom requires a DOM");
665
+ const t = instance.t;
666
+ const root = options.root ?? document.body;
667
+ const attr = options.attribute ?? "data-verbaly";
668
+ const argsAttr = `${attr}-args`;
669
+ const attrsAttr = `${attr}-attr`;
670
+ const richAttr = `${attr}-rich`;
671
+ const linksAttr = `${attr}-links`;
672
+ const richTags = new Set(options.richTags ?? RICH_TAGS);
673
+ const globalLinks = options.richLinks;
674
+ const argsCache = /* @__PURE__ */ new WeakMap();
675
+ const linksCache = /* @__PURE__ */ new WeakMap();
676
+ function cachedArgs(el) {
677
+ const raw = el.getAttribute(argsAttr);
678
+ const hit = argsCache.get(el);
679
+ if (hit && hit.raw === raw) return hit.params;
680
+ const params = parseArgs(raw);
681
+ argsCache.set(el, {
682
+ raw,
683
+ params
684
+ });
685
+ return params;
686
+ }
687
+ function cachedLinks(el) {
688
+ const raw = el.getAttribute(linksAttr);
689
+ if (!raw) return globalLinks;
690
+ const hit = linksCache.get(el);
691
+ if (hit && hit.raw === raw) return hit.links;
692
+ const own = parseArgs(raw);
693
+ const links = own ? globalLinks ? {
694
+ ...globalLinks,
695
+ ...own
696
+ } : own : globalLinks;
697
+ linksCache.set(el, {
698
+ raw,
699
+ links
700
+ });
701
+ return links;
702
+ }
703
+ function renderRich(el, nodes, links) {
704
+ for (const node of nodes) if (typeof node === "string") el.append(node);
705
+ else if (links?.[node.name] !== void 0) {
706
+ const link = links[node.name];
707
+ const { href, target, rel } = typeof link === "string" ? { href: link } : link;
708
+ const a = el.ownerDocument.createElement("a");
709
+ const safe = safeHref(href);
710
+ if (safe !== void 0) a.setAttribute("href", safe);
711
+ if (target) a.setAttribute("target", target);
712
+ if (rel) a.setAttribute("rel", rel);
713
+ renderRich(a, node.children, links);
714
+ el.append(a);
715
+ } else if (richTags.has(node.name)) {
716
+ const child = el.ownerDocument.createElement(node.name);
717
+ renderRich(child, node.children, links);
718
+ el.append(child);
719
+ } else renderRich(el, node.children, links);
720
+ }
721
+ function render(el) {
722
+ const args = cachedArgs(el);
723
+ const key = el.getAttribute(attr);
724
+ if (key) {
725
+ const text = t(key, args);
726
+ if (el.hasAttribute(richAttr)) {
727
+ el.textContent = "";
728
+ renderRich(el, parseTags(text), cachedLinks(el));
729
+ } else el.textContent = text;
730
+ }
731
+ const attrMap = parseArgs(el.getAttribute(attrsAttr));
732
+ if (attrMap) for (const [name, attrKey] of Object.entries(attrMap)) {
733
+ if (typeof attrKey !== "string" || name.toLowerCase().startsWith("on")) continue;
734
+ el.setAttribute(name, t(attrKey, args));
735
+ }
736
+ }
737
+ const selector = `[${attr}], [${attrsAttr}]`;
738
+ function renderAll(scope) {
739
+ if (scope instanceof Element && scope.matches(selector)) render(scope);
740
+ for (const el of scope.querySelectorAll(selector)) render(el);
741
+ }
742
+ renderAll(root);
743
+ const unsubscribe = instance.subscribe(() => renderAll(root));
744
+ const observer = new MutationObserver((records) => {
745
+ for (const record of records) if (record.type === "attributes" && record.target instanceof Element) render(record.target);
746
+ else if (record.type === "childList") {
747
+ for (const node of record.addedNodes) if (node instanceof Element) renderAll(node);
748
+ }
749
+ });
750
+ observer.observe(root instanceof Document ? root.documentElement : root, {
751
+ childList: true,
752
+ subtree: true,
753
+ attributes: true,
754
+ attributeFilter: [
755
+ attr,
756
+ argsAttr,
757
+ attrsAttr,
758
+ richAttr,
759
+ linksAttr
760
+ ]
761
+ });
762
+ return () => {
763
+ unsubscribe();
764
+ observer.disconnect();
765
+ };
804
766
  }
805
767
  function parseArgs(raw) {
806
- if (!raw) return void 0;
807
- try {
808
- return JSON.parse(raw);
809
- } catch {
810
- console.warn(`[verbaly] invalid args JSON: ${raw}`);
811
- return void 0;
812
- }
813
- }
814
-
815
- // src/locale.ts
816
- var DEFAULT_KEY = "verbaly-locale";
768
+ if (!raw) return void 0;
769
+ try {
770
+ return JSON.parse(raw);
771
+ } catch {
772
+ console.warn(`[verbaly] invalid args JSON: ${raw}`);
773
+ return;
774
+ }
775
+ }
776
+ //#endregion
777
+ //#region src/locale.ts
778
+ const DEFAULT_KEY = "verbaly-locale";
817
779
  function resolveLocale(options) {
818
- const { supported, fallback = supported[0] ?? "en", storageKey = DEFAULT_KEY } = options;
819
- if (storageKey) {
820
- const stored = getStorage()?.getItem(storageKey);
821
- const match = stored && matchSupported(stored, supported);
822
- if (match) return match;
823
- }
824
- for (const lang of preferredLanguages()) {
825
- const match = matchSupported(lang, supported);
826
- if (match) return match;
827
- }
828
- return fallback;
780
+ const { supported, fallback = supported[0] ?? "en", storageKey = DEFAULT_KEY } = options;
781
+ if (storageKey) {
782
+ const stored = getStorage()?.getItem(storageKey);
783
+ const match = stored && matchSupported(stored, supported);
784
+ if (match) return match;
785
+ }
786
+ for (const lang of preferredLanguages()) {
787
+ const match = matchSupported(lang, supported);
788
+ if (match) return match;
789
+ }
790
+ return fallback;
829
791
  }
830
792
  function matchSupported(lang, supported) {
831
- if (supported.includes(lang)) return lang;
832
- const base = lang.split("-")[0];
833
- return supported.includes(base) ? base : void 0;
793
+ if (supported.includes(lang)) return lang;
794
+ const base = lang.split("-")[0];
795
+ return supported.includes(base) ? base : void 0;
834
796
  }
835
797
  function persistLocale(locale, storageKey = DEFAULT_KEY) {
836
- if (storageKey) getStorage()?.setItem(storageKey, locale);
837
- if (typeof document !== "undefined") document.documentElement.lang = locale;
798
+ if (storageKey) getStorage()?.setItem(storageKey, locale);
799
+ if (typeof document !== "undefined") document.documentElement.lang = locale;
838
800
  }
839
801
  function preferredLanguages() {
840
- if (typeof navigator === "undefined") return [];
841
- return navigator.languages?.length ? navigator.languages : [navigator.language];
802
+ if (typeof navigator === "undefined") return [];
803
+ return navigator.languages?.length ? navigator.languages : [navigator.language];
842
804
  }
843
805
  function getStorage() {
844
- try {
845
- return typeof localStorage === "undefined" ? null : localStorage;
846
- } catch {
847
- return null;
848
- }
849
- }
850
- // Annotate the CommonJS export names for ESM import in node:
851
- 0 && (module.exports = {
852
- RICH_TAGS,
853
- bindDom,
854
- createVerbaly,
855
- flatten,
856
- parse,
857
- parseTags,
858
- persistLocale,
859
- resolveLocale,
860
- safeHref
861
- });
806
+ try {
807
+ return typeof localStorage === "undefined" ? null : localStorage;
808
+ } catch {
809
+ return null;
810
+ }
811
+ }
812
+ //#endregion
813
+ exports.RICH_TAGS = RICH_TAGS;
814
+ exports.bindDom = bindDom;
815
+ exports.createVerbaly = createVerbaly;
816
+ exports.flatten = flatten;
817
+ exports.parse = parse;
818
+ exports.parseTags = parseTags;
819
+ exports.persistLocale = persistLocale;
820
+ exports.resolveLocale = resolveLocale;
821
+ exports.safeHref = safeHref;
822
+
862
823
  //# sourceMappingURL=index.cjs.map