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