@verbaly/compiler 0.9.0 → 0.10.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.js CHANGED
@@ -673,12 +673,345 @@ function isModuleNotFound2(error, name) {
673
673
  return error instanceof Error && error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes(name);
674
674
  }
675
675
 
676
- // src/transform.ts
676
+ // src/pseudo.ts
677
+ var PSEUDO_LOCALE = "en-XA";
678
+ var ACCENTS = {
679
+ a: "\xE1",
680
+ b: "\u0180",
681
+ c: "\xE7",
682
+ d: "\u0111",
683
+ e: "\xE9",
684
+ f: "\u0192",
685
+ g: "\u011F",
686
+ h: "\u0125",
687
+ i: "\xED",
688
+ j: "\u0135",
689
+ k: "\u0137",
690
+ l: "\u013A",
691
+ m: "\u0271",
692
+ n: "\xF1",
693
+ o: "\xF3",
694
+ p: "\xFE",
695
+ q: "\u01EB",
696
+ r: "\u0155",
697
+ s: "\u0161",
698
+ t: "\u0163",
699
+ u: "\xFA",
700
+ v: "\u1E7D",
701
+ w: "\u0175",
702
+ x: "\u1E8B",
703
+ y: "\xFD",
704
+ z: "\u017E",
705
+ A: "\xC1",
706
+ B: "\u0181",
707
+ C: "\xC7",
708
+ D: "\u0110",
709
+ E: "\xC9",
710
+ F: "\u0191",
711
+ G: "\u011E",
712
+ H: "\u0124",
713
+ I: "\xCD",
714
+ J: "\u0134",
715
+ K: "\u0136",
716
+ L: "\u0139",
717
+ M: "\u1E3E",
718
+ N: "\xD1",
719
+ O: "\xD3",
720
+ P: "\xDE",
721
+ Q: "\u01EA",
722
+ R: "\u0154",
723
+ S: "\u0160",
724
+ T: "\u0162",
725
+ U: "\xDA",
726
+ V: "\u1E7C",
727
+ W: "\u0174",
728
+ X: "\u1E8C",
729
+ Y: "\xDD",
730
+ Z: "\u017D"
731
+ };
732
+ var TAG_AT = /<\/?[a-zA-Z][\w-]*\/?>/y;
733
+ function pseudoLocalize(message) {
734
+ let out = "";
735
+ let letters = 0;
736
+ let i = 0;
737
+ while (i < message.length) {
738
+ const two = message.slice(i, i + 2);
739
+ if (two === "{{" || two === "}}" || two === "||" || two === "##") {
740
+ out += two;
741
+ i += 2;
742
+ continue;
743
+ }
744
+ const ch = message[i];
745
+ if (ch === "{") {
746
+ const end = matchBrace(message, i);
747
+ out += message.slice(i, end);
748
+ i = end;
749
+ continue;
750
+ }
751
+ if (ch === "<") {
752
+ TAG_AT.lastIndex = i;
753
+ const m = TAG_AT.exec(message);
754
+ if (m) {
755
+ out += m[0];
756
+ i += m[0].length;
757
+ continue;
758
+ }
759
+ }
760
+ const mapped = ACCENTS[ch];
761
+ if (mapped) {
762
+ out += mapped;
763
+ letters += 1;
764
+ } else {
765
+ out += ch;
766
+ }
767
+ i += 1;
768
+ }
769
+ const pad = "~".repeat(Math.ceil(letters / 3));
770
+ return `\u27E6${out}${pad ? " " + pad : ""}\u27E7`;
771
+ }
772
+ function matchBrace(message, start) {
773
+ let depth = 0;
774
+ for (let i = start; i < message.length; i++) {
775
+ const two = message.slice(i, i + 2);
776
+ if (two === "{{" || two === "}}") {
777
+ i += 1;
778
+ continue;
779
+ }
780
+ const ch = message[i];
781
+ if (ch === "{") depth += 1;
782
+ else if (ch === "}") {
783
+ depth -= 1;
784
+ if (depth === 0) return i + 1;
785
+ }
786
+ }
787
+ return message.length;
788
+ }
789
+ function pseudoCatalogs(cfg, catalogs, locale = PSEUDO_LOCALE) {
790
+ const source = catalogs[cfg.sourceLocale] ?? {};
791
+ const target = {};
792
+ for (const [key, msg] of Object.entries(source)) {
793
+ target[key] = msg ? pseudoLocalize(msg) : "";
794
+ }
795
+ catalogs[locale] = target;
796
+ return Object.keys(target).filter((key) => target[key]);
797
+ }
798
+
799
+ // src/render.ts
800
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "fs";
801
+ import { dirname, join as join4, relative } from "path";
677
802
  import MagicString from "magic-string";
803
+ import { glob as glob2 } from "tinyglobby";
804
+ import { createVerbaly, parseTags, RICH_TAGS } from "verbaly";
805
+ var VOID_TAGS = /* @__PURE__ */ new Set([
806
+ "area",
807
+ "base",
808
+ "br",
809
+ "col",
810
+ "embed",
811
+ "hr",
812
+ "img",
813
+ "input",
814
+ "link",
815
+ "meta",
816
+ "param",
817
+ "source",
818
+ "track",
819
+ "wbr"
820
+ ]);
821
+ var START_TAG = /<([a-zA-Z][a-zA-Z0-9-]*)((?:"[^"]*"|'[^']*'|[^"'>])*)>/g;
822
+ var ATTR = /([^\s=/"'<>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
823
+ function renderHtml(html, options) {
824
+ const attr = options.attribute ?? "data-verbaly";
825
+ const argsAttr = `${attr}-args`;
826
+ const attrsAttr = `${attr}-attr`;
827
+ const richAttr = `${attr}-rich`;
828
+ const richTags = new Set(options.richTags ?? RICH_TAGS);
829
+ const sourceLocale = options.sourceLocale ?? "en";
830
+ const messages = {};
831
+ for (const [locale, catalog] of Object.entries(options.catalogs)) {
832
+ const clean = {};
833
+ for (const [key, msg] of Object.entries(catalog)) if (msg) clean[key] = msg;
834
+ messages[locale] = clean;
835
+ }
836
+ const v = createVerbaly({ locale: options.locale, fallback: sourceLocale, messages });
837
+ const t = v.t;
838
+ const ms = new MagicString(html);
839
+ const missing = /* @__PURE__ */ new Set();
840
+ const skip = protectedRanges(html);
841
+ const inSkip = (index) => skip.some(([from, to]) => index >= from && index < to);
842
+ START_TAG.lastIndex = 0;
843
+ let m;
844
+ while ((m = START_TAG.exec(html)) !== null) {
845
+ if (inSkip(m.index)) continue;
846
+ const [full, rawName, attrChunk] = m;
847
+ const tagName = rawName.toLowerCase();
848
+ const openEnd = m.index + full.length;
849
+ const chunkStart = m.index + 1 + rawName.length;
850
+ if (tagName === "html" && options.setLang !== false) {
851
+ setAttribute(ms, html, chunkStart, openEnd, attrChunk, "lang", options.locale);
852
+ continue;
853
+ }
854
+ const attrs = parseAttrs(attrChunk);
855
+ const key = attrs.get(attr);
856
+ const attrMapRaw = attrs.get(attrsAttr);
857
+ if (key === void 0 && attrMapRaw === void 0) continue;
858
+ const args = parseArgs(attrs.get(argsAttr));
859
+ if (key) {
860
+ if (!v.has(key)) {
861
+ missing.add(key);
862
+ } else if (!VOID_TAGS.has(tagName) && !attrChunk.trimEnd().endsWith("/")) {
863
+ const close = findClose(html, tagName, openEnd, inSkip);
864
+ if (close) {
865
+ const text = t(key, args);
866
+ const content = attrs.has(richAttr) ? richToHtml(parseTags(text), richTags) : escapeHtml(text);
867
+ if (html.slice(openEnd, close.contentEnd) !== content) {
868
+ if (openEnd === close.contentEnd) ms.appendLeft(openEnd, content);
869
+ else ms.overwrite(openEnd, close.contentEnd, content);
870
+ }
871
+ }
872
+ }
873
+ }
874
+ if (attrMapRaw !== void 0) {
875
+ const map = parseArgs(attrMapRaw);
876
+ if (map) {
877
+ for (const [name, attrKey] of Object.entries(map)) {
878
+ if (typeof attrKey !== "string" || name.toLowerCase().startsWith("on")) continue;
879
+ if (!v.has(attrKey)) {
880
+ missing.add(attrKey);
881
+ continue;
882
+ }
883
+ setAttribute(ms, html, chunkStart, openEnd, attrChunk, name, t(attrKey, args));
884
+ }
885
+ }
886
+ }
887
+ }
888
+ return { html: ms.toString(), missing: [...missing] };
889
+ }
890
+ async function renderSite(cfg, options = {}) {
891
+ const site = join4(cfg.root, options.site ?? "dist");
892
+ const locales = options.locales ?? cfg.locales;
893
+ const catalogs = loadCatalogs(cfg);
894
+ const files = await glob2("**/*.html", {
895
+ cwd: site,
896
+ absolute: true,
897
+ ignore: locales.map((locale) => `${locale}/**`)
898
+ });
899
+ const missing = {};
900
+ for (const file of files) {
901
+ const html = readFileSync4(file, "utf8");
902
+ const rel = relative(site, file);
903
+ for (const locale of locales) {
904
+ const result = renderHtml(html, {
905
+ locale,
906
+ catalogs,
907
+ sourceLocale: cfg.sourceLocale,
908
+ attribute: options.attribute,
909
+ richTags: options.richTags
910
+ });
911
+ for (const key of result.missing) {
912
+ const list = missing[locale] ??= [];
913
+ if (!list.includes(key)) list.push(key);
914
+ }
915
+ const out = locale === cfg.sourceLocale ? file : join4(site, locale, rel);
916
+ mkdirSync2(dirname(out), { recursive: true });
917
+ writeFileSync3(out, result.html);
918
+ }
919
+ }
920
+ return { files: files.length, locales: [...locales], missing };
921
+ }
922
+ function parseAttrs(chunk) {
923
+ const attrs = /* @__PURE__ */ new Map();
924
+ ATTR.lastIndex = 0;
925
+ let m;
926
+ while ((m = ATTR.exec(chunk)) !== null) {
927
+ attrs.set(m[1].toLowerCase(), m[2] ?? m[3] ?? m[4] ?? "");
928
+ }
929
+ return attrs;
930
+ }
931
+ function parseArgs(raw) {
932
+ if (!raw) return void 0;
933
+ try {
934
+ return JSON.parse(decodeEntities(raw));
935
+ } catch {
936
+ console.warn(`[verbaly] invalid args JSON: ${raw}`);
937
+ return void 0;
938
+ }
939
+ }
940
+ function protectedRanges(html) {
941
+ const ranges = [];
942
+ const re = /<!--[\s\S]*?-->|<script\b[\s\S]*?<\/script\s*>|<style\b[\s\S]*?<\/style\s*>/gi;
943
+ let m;
944
+ while ((m = re.exec(html)) !== null) {
945
+ const openEnd = m[0].startsWith("<!--") ? m.index : html.indexOf(">", m.index) + 1;
946
+ ranges.push([openEnd, m.index + m[0].length]);
947
+ }
948
+ return ranges;
949
+ }
950
+ function findClose(html, tagName, from, inSkip) {
951
+ const re = new RegExp(
952
+ `<${tagName}(?=[\\s/>])(?:"[^"]*"|'[^']*'|[^"'>])*>|</${tagName}\\s*>`,
953
+ "gi"
954
+ );
955
+ re.lastIndex = from;
956
+ let depth = 1;
957
+ let m;
958
+ while ((m = re.exec(html)) !== null) {
959
+ if (inSkip(m.index)) continue;
960
+ if (m[0][1] === "/") {
961
+ depth -= 1;
962
+ if (depth === 0) return { contentEnd: m.index };
963
+ } else if (!m[0].endsWith("/>")) {
964
+ depth += 1;
965
+ }
966
+ }
967
+ return null;
968
+ }
969
+ function setAttribute(ms, html, chunkStart, openEnd, attrChunk, name, value) {
970
+ const escaped = escapeAttr(value);
971
+ const existing = new RegExp(`(\\s${name}\\s*=\\s*)("[^"]*"|'[^']*'|[^\\s>]+)`, "i").exec(
972
+ attrChunk
973
+ );
974
+ if (existing) {
975
+ const valueStart = chunkStart + existing.index + existing[1].length;
976
+ const valueEnd = valueStart + existing[2].length;
977
+ if (html.slice(valueStart, valueEnd) !== `"${escaped}"`) {
978
+ ms.overwrite(valueStart, valueEnd, `"${escaped}"`);
979
+ }
980
+ return;
981
+ }
982
+ const selfClosing = html.slice(openEnd - 2, openEnd) === "/>";
983
+ const insertAt = openEnd - (selfClosing ? 2 : 1);
984
+ ms.appendLeft(insertAt, ` ${name}="${escaped}"`);
985
+ }
986
+ function richToHtml(nodes, allowed) {
987
+ let out = "";
988
+ for (const node of nodes) {
989
+ if (typeof node === "string") {
990
+ out += escapeHtml(node);
991
+ } else if (allowed.has(node.name)) {
992
+ out += `<${node.name}>${richToHtml(node.children, allowed)}</${node.name}>`;
993
+ } else {
994
+ out += richToHtml(node.children, allowed);
995
+ }
996
+ }
997
+ return out;
998
+ }
999
+ function escapeHtml(text) {
1000
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1001
+ }
1002
+ function escapeAttr(text) {
1003
+ return escapeHtml(text).replace(/"/g, "&quot;");
1004
+ }
1005
+ function decodeEntities(text) {
1006
+ return text.replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
1007
+ }
1008
+
1009
+ // src/transform.ts
1010
+ import MagicString2 from "magic-string";
678
1011
  function transformCode(code, file, analysis) {
679
1012
  const { tagged } = analysis ?? analyze(code, file);
680
1013
  if (tagged.length === 0) return null;
681
- const s = new MagicString(code);
1014
+ const s = new MagicString2(code);
682
1015
  for (const msg of tagged) {
683
1016
  const seen = /* @__PURE__ */ new Set();
684
1017
  const entries = msg.params.filter((p) => !seen.has(p.name) && seen.add(p.name));
@@ -760,6 +1093,7 @@ function sameMembers(a, b) {
760
1093
  }
761
1094
  export {
762
1095
  MessageRegistry,
1096
+ PSEUDO_LOCALE,
763
1097
  VIRTUAL_ID,
764
1098
  analyze,
765
1099
  catalogPath,
@@ -775,8 +1109,12 @@ export {
775
1109
  loadConfig,
776
1110
  loadConfigFile,
777
1111
  pruneCatalogs,
1112
+ pseudoCatalogs,
1113
+ pseudoLocalize,
778
1114
  readCatalog,
1115
+ renderHtml,
779
1116
  renderParamType,
1117
+ renderSite,
780
1118
  resolveConfig,
781
1119
  serializeCatalog,
782
1120
  stableKey,