@lokascript/i18n 2.11.0 → 3.0.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.
Files changed (42) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/browser.cjs +5 -1690
  3. package/dist/browser.cjs.map +1 -1
  4. package/dist/browser.d.cts +2 -2
  5. package/dist/browser.d.ts +2 -2
  6. package/dist/browser.js +6 -1685
  7. package/dist/browser.js.map +1 -1
  8. package/dist/dictionaries/index.cjs +5 -1
  9. package/dist/dictionaries/index.cjs.map +1 -1
  10. package/dist/dictionaries/index.js +5 -1
  11. package/dist/dictionaries/index.js.map +1 -1
  12. package/dist/{transformer-CsOeqayN.d.cts → index-BykxjYST.d.cts} +1 -232
  13. package/dist/{transformer-DWCTG1DQ.d.ts → index-DuIef8O7.d.ts} +1 -232
  14. package/dist/index.cjs +16 -1878
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.d.cts +35 -35
  17. package/dist/index.d.ts +35 -35
  18. package/dist/index.js +17 -1873
  19. package/dist/index.js.map +1 -1
  20. package/dist/lokascript-i18n.min.js +1 -1
  21. package/dist/lokascript-i18n.min.js.map +1 -1
  22. package/dist/lokascript-i18n.mjs +49 -2680
  23. package/dist/lokascript-i18n.mjs.map +1 -1
  24. package/dist/plugins/vite.cjs +5 -1
  25. package/dist/plugins/vite.cjs.map +1 -1
  26. package/dist/plugins/vite.js +5 -1
  27. package/dist/plugins/vite.js.map +1 -1
  28. package/dist/plugins/webpack.cjs +5 -1
  29. package/dist/plugins/webpack.cjs.map +1 -1
  30. package/dist/plugins/webpack.js +5 -1
  31. package/dist/plugins/webpack.js.map +1 -1
  32. package/package.json +4 -4
  33. package/src/browser.ts +0 -7
  34. package/src/compatibility/browser-tests/grammar-demo.spec.ts +22 -8
  35. package/src/constants.ts +1 -0
  36. package/src/dictionaries/bn.ts +5 -1
  37. package/src/grammar/index.ts +15 -9
  38. package/src/grammar/profiles.test.ts +440 -0
  39. package/src/index.ts +0 -7
  40. package/src/lexicon-parity.test.ts +77 -0
  41. package/src/grammar/grammar.test.ts +0 -2751
  42. package/src/grammar/transformer.ts +0 -2737
package/dist/browser.js CHANGED
@@ -1,37 +1,4 @@
1
1
  // src/constants.ts
2
- var ENGLISH_MODIFIER_ROLES = {
3
- to: "destination",
4
- into: "destination",
5
- from: "source",
6
- with: "style",
7
- by: "quantity",
8
- as: "method",
9
- on: "event",
10
- over: "duration",
11
- for: "duration"
12
- };
13
- var COMMAND_PRIMARY_ROLES = {
14
- set: "destination",
15
- on: "event",
16
- trigger: "event",
17
- send: "event",
18
- wait: "duration",
19
- fetch: "source",
20
- get: "source",
21
- if: "condition",
22
- unless: "condition",
23
- while: "condition",
24
- repeat: "loopType",
25
- go: "destination",
26
- scroll: "destination",
27
- tell: "destination",
28
- default: "destination",
29
- swap: "destination",
30
- // morph deliberately absent: its schema primaryRole is `patient` (the
31
- // element being morphed — aligned with the transformer's patient marking
32
- // in the session-9 role-layout swap), and patient is the default.
33
- bind: "destination"
34
- };
35
2
  var ENGLISH_MODIFIERS = /* @__PURE__ */ new Set([
36
3
  "to",
37
4
  "from",
@@ -264,69 +231,6 @@ var ENGLISH_EXPRESSION_KEYWORDS = /* @__PURE__ */ new Set([
264
231
  "starts with",
265
232
  "ends with"
266
233
  ]);
267
- var CONDITIONAL_KEYWORDS = /* @__PURE__ */ new Set([
268
- // English
269
- "if",
270
- "unless",
271
- "when",
272
- "where",
273
- // Japanese
274
- "\u3082\u3057",
275
- "\u6642\u306B",
276
- "\u3068\u304D\u306B",
277
- "\u3069\u3053\u3067",
278
- // Chinese
279
- "\u5982\u679C",
280
- "\u5F53",
281
- // Arabic
282
- "\u0625\u0630\u0627",
283
- "\u0639\u0646\u062F\u0645\u0627",
284
- "\u062D\u064A\u062B",
285
- // Spanish
286
- "si",
287
- "cuando",
288
- "donde",
289
- // German
290
- "wenn",
291
- "wann",
292
- "wo",
293
- // French
294
- "quand",
295
- "lorsque",
296
- "o\xF9",
297
- // Portuguese
298
- "quando",
299
- "onde",
300
- // Turkish
301
- "e\u011Fer",
302
- "zaman",
303
- "nerede",
304
- // Indonesian
305
- "ketika",
306
- "saat",
307
- "dimana",
308
- // Korean
309
- "\uB54C",
310
- "\uC5B4\uB514\uC11C",
311
- // Quechua
312
- "maypi",
313
- // Swahili
314
- "wakati",
315
- "wapi"
316
- ]);
317
- var THEN_KEYWORDS = /* @__PURE__ */ new Set([
318
- "then",
319
- "\u305D\u308C\u304B\u3089",
320
- "\u90A3\u4E48",
321
- "\u062B\u0645",
322
- "entonces",
323
- "alors",
324
- "dann",
325
- "sonra",
326
- "lalu",
327
- "chayqa",
328
- "kisha"
329
- ]);
330
234
 
331
235
  // src/parser/create-provider.ts
332
236
  function createKeywordProvider(dictionary, locale, options = {}) {
@@ -4825,7 +4729,11 @@ var bengaliDictionary = {
4825
4729
  random: "\u098F\u09B2\u09CB\u09AE\u09C7\u09B2\u09CB",
4826
4730
  length: "\u09A6\u09C8\u09B0\u09CD\u0998\u09CD\u09AF",
4827
4731
  index: "\u09B8\u09C2\u099A\u0995",
4828
- empty: "\u0996\u09BE\u09B2\u09BF-\u0995\u09B0\u09C1\u09A8",
4732
+ // The EXPRESSION `empty` is the state predicate (`if my value is empty`),
4733
+ // not the command: `খালি-করুন` is the imperative "empty it!" and belongs to
4734
+ // the `empty` COMMAND, which keeps it. Kept in step with the semantic
4735
+ // lexicon by `lexicon-parity.test.ts`.
4736
+ empty: "\u0996\u09BE\u09B2\u09BF",
4829
4737
  "starts with": "\u09A6\u09BF\u09AF\u09BC\u09C7_\u09B6\u09C1\u09B0\u09C1",
4830
4738
  "ends with": "\u09A6\u09BF\u09AF\u09BC\u09C7_\u09B6\u09C7\u09B7",
4831
4739
  "ignoring case": "\u0995\u09C7\u09B8_\u0989\u09AA\u09C7\u0995\u09CD\u09B7\u09BE",
@@ -7836,1593 +7744,6 @@ function getSupportedDirectPairs() {
7836
7744
  });
7837
7745
  }
7838
7746
 
7839
- // src/dictionaries/index.ts
7840
- var en2 = en;
7841
- var es2 = es;
7842
- var ja2 = ja;
7843
- var ko2 = ko;
7844
- var zh2 = zh;
7845
- var fr2 = fr;
7846
- var de2 = de;
7847
- var ar2 = ar;
7848
- var tr2 = tr;
7849
- var id2 = id;
7850
- var pt2 = pt;
7851
- var qu2 = qu;
7852
- var sw2 = sw;
7853
- var it2 = it;
7854
- var vi2 = vi;
7855
- var pl2 = pl;
7856
- var ru = russianDictionary;
7857
- var uk = ukrainianDictionary;
7858
- var hi = hindiDictionary;
7859
- var bn2 = bengaliDictionary;
7860
- var th2 = thaiDictionary;
7861
- var ms2 = malayDictionary;
7862
- var tl2 = tagalogDictionary;
7863
- var he2 = he;
7864
- var dictionaries = {
7865
- en: en2,
7866
- es: es2,
7867
- ko: ko2,
7868
- zh: zh2,
7869
- fr: fr2,
7870
- de: de2,
7871
- ja: ja2,
7872
- ar: ar2,
7873
- tr: tr2,
7874
- id: id2,
7875
- qu: qu2,
7876
- sw: sw2,
7877
- pt: pt2,
7878
- it: it2,
7879
- vi: vi2,
7880
- pl: pl2,
7881
- ru,
7882
- uk,
7883
- hi,
7884
- bn: bn2,
7885
- th: th2,
7886
- ms: ms2,
7887
- tl: tl2,
7888
- he: he2
7889
- };
7890
-
7891
- // src/types.ts
7892
- var DICTIONARY_CATEGORIES = [
7893
- "commands",
7894
- "modifiers",
7895
- "events",
7896
- "logical",
7897
- "temporal",
7898
- "values",
7899
- "attributes",
7900
- "expressions"
7901
- ];
7902
- function findInDictionary(dict, localizedWord) {
7903
- const normalized = localizedWord.toLowerCase();
7904
- for (const category of DICTIONARY_CATEGORIES) {
7905
- const entries = dict[category];
7906
- for (const [english, localized] of Object.entries(entries)) {
7907
- if (localized.toLowerCase() === normalized) {
7908
- return { category, englishKey: english };
7909
- }
7910
- }
7911
- }
7912
- return void 0;
7913
- }
7914
- function translateFromEnglish(dict, englishWord) {
7915
- const normalized = englishWord.toLowerCase();
7916
- for (const category of DICTIONARY_CATEGORIES) {
7917
- const entries = dict[category];
7918
- const translated = entries[normalized];
7919
- if (translated) {
7920
- return translated;
7921
- }
7922
- }
7923
- return void 0;
7924
- }
7925
-
7926
- // src/grammar/transformer.ts
7927
- function getCommandKeywordsForLocale(locale) {
7928
- const keywords = new Set(ENGLISH_COMMANDS);
7929
- const dict = dictionaries[locale];
7930
- if (dict?.commands) {
7931
- Object.values(dict.commands).forEach((cmd) => {
7932
- if (typeof cmd === "string") {
7933
- keywords.add(cmd.toLowerCase());
7934
- }
7935
- });
7936
- }
7937
- return keywords;
7938
- }
7939
- var EN_COPULAS = ["is", "are", "was", "were", "am", "be"];
7940
- function getCopulasForLocale(locale) {
7941
- const copulas = new Set(EN_COPULAS);
7942
- if (locale !== "en") {
7943
- for (const form of EN_COPULAS) {
7944
- copulas.add(translateWord(form, "en", locale).toLowerCase());
7945
- }
7946
- }
7947
- return copulas;
7948
- }
7949
- function isPredicateAdjectivePosition(tokens, i, copulas) {
7950
- const prev = tokens[i - 1]?.toLowerCase();
7951
- return !!prev && copulas.has(prev);
7952
- }
7953
- function getForLoopWordsForLocale(locale) {
7954
- const forWords = /* @__PURE__ */ new Set(["for"]);
7955
- const inWords = /* @__PURE__ */ new Set(["in"]);
7956
- if (locale !== "en") {
7957
- forWords.add(translateWord("for", "en", locale).toLowerCase());
7958
- inWords.add(translateWord("in", "en", locale).toLowerCase());
7959
- }
7960
- return { forWords, inWords };
7961
- }
7962
- function isLoopHeadFor(tokens, i, inWords, commandKeywords) {
7963
- for (let j = i + 1; j < tokens.length; j++) {
7964
- const lt = tokens[j].toLowerCase();
7965
- if (inWords.has(lt)) return true;
7966
- if (commandKeywords.has(lt)) return false;
7967
- }
7968
- return false;
7969
- }
7970
- function repairHebrewFrontedAccusative(text) {
7971
- const ACC = "\u05D0\u05EA";
7972
- const verbs = getCommandKeywordsForLocale("he");
7973
- const tokens = text.split(/\s+/);
7974
- let changed = false;
7975
- for (let i = 0; i + 1 < tokens.length; i++) {
7976
- if (tokens[i] === ACC && verbs.has(tokens[i + 1].toLowerCase())) {
7977
- [tokens[i], tokens[i + 1]] = [tokens[i + 1], tokens[i]];
7978
- changed = true;
7979
- i++;
7980
- }
7981
- }
7982
- return changed ? tokens.join(" ") : text;
7983
- }
7984
- function extractBlockStructure(input, sourceLocale) {
7985
- const tokens = input.split(/\s+/);
7986
- const head = tokens[0]?.toLowerCase();
7987
- if (!head || !BLOCK_HEAD_KEYWORDS.has(head)) return null;
7988
- let depth = 1;
7989
- let endIdx = -1;
7990
- for (let i = 1; i < tokens.length; i++) {
7991
- const t = tokens[i].toLowerCase();
7992
- if (BLOCK_HEAD_KEYWORDS.has(t)) depth++;
7993
- else if (t === "end") {
7994
- depth--;
7995
- if (depth === 0) {
7996
- endIdx = i;
7997
- break;
7998
- }
7999
- }
8000
- }
8001
- if (endIdx !== -1 && endIdx !== tokens.length - 1) return null;
8002
- const inner = endIdx !== -1 ? tokens.slice(1, endIdx) : tokens.slice(1);
8003
- const base = { headKeyword: tokens[0], body: "" };
8004
- if (endIdx !== -1) base.tailKeyword = tokens[endIdx];
8005
- if (head === "live") {
8006
- return { ...base, body: inner.join(" ") };
8007
- }
8008
- if (head === "when") {
8009
- const idx = inner.findIndex((t) => t.toLowerCase() === "changes");
8010
- if (idx >= 0) {
8011
- return {
8012
- ...base,
8013
- prefixExpr: inner.slice(0, idx).join(" "),
8014
- connector: inner[idx],
8015
- body: inner.slice(idx + 1).join(" ")
8016
- };
8017
- }
8018
- return null;
8019
- }
8020
- const commands = getCommandKeywordsForLocale(sourceLocale);
8021
- const copulas = getCopulasForLocale(sourceLocale);
8022
- let bodyStart = -1;
8023
- for (let i = 0; i < inner.length; i++) {
8024
- if (commands.has(inner[i].toLowerCase()) && !isPredicateAdjectivePosition(inner, i, copulas)) {
8025
- bodyStart = i;
8026
- break;
8027
- }
8028
- }
8029
- if (bodyStart <= 0) return null;
8030
- return {
8031
- ...base,
8032
- prefixExpr: inner.slice(0, bodyStart).join(" "),
8033
- body: inner.slice(bodyStart).join(" ")
8034
- };
8035
- }
8036
- function splitCompoundStatement(input, sourceLocale) {
8037
- const lines = input.split(/\n/).map((line) => line.trim()).filter((line) => line.length > 0);
8038
- const parts = [];
8039
- for (const line of lines) {
8040
- const lineParts = splitOnThen(line, sourceLocale);
8041
- for (const part of lineParts) {
8042
- const commandParts = splitOnCommandBoundaries(part, sourceLocale);
8043
- parts.push(...commandParts);
8044
- }
8045
- }
8046
- return parts;
8047
- }
8048
- function splitCompoundStatementWithMetadata(input, sourceLocale) {
8049
- const rawLines = input.split("\n");
8050
- const lineMetadata = [];
8051
- const parts = [];
8052
- const partToLineIndex = [];
8053
- for (let lineIndex = 0; lineIndex < rawLines.length; lineIndex++) {
8054
- const rawLine = rawLines[lineIndex];
8055
- const indentMatch = rawLine.match(/^(\s*)/);
8056
- const originalIndent = indentMatch ? indentMatch[1] : "";
8057
- const trimmed = rawLine.trim();
8058
- lineMetadata.push({
8059
- content: trimmed,
8060
- originalIndent,
8061
- isBlank: trimmed.length === 0
8062
- });
8063
- if (trimmed.length > 0) {
8064
- const lineParts = splitOnThen(trimmed, sourceLocale);
8065
- for (const part of lineParts) {
8066
- const commandParts = splitOnCommandBoundaries(part, sourceLocale);
8067
- for (const cmdPart of commandParts) {
8068
- parts.push(cmdPart);
8069
- partToLineIndex.push(lineIndex);
8070
- }
8071
- }
8072
- }
8073
- }
8074
- return { parts, lineMetadata, partToLineIndex };
8075
- }
8076
- function normalizeIndentation(lineMetadata) {
8077
- const indentedLines = lineMetadata.filter((m) => !m.isBlank && m.originalIndent.length > 0);
8078
- if (indentedLines.length === 0) {
8079
- return lineMetadata.map(() => "");
8080
- }
8081
- const indentLengths = indentedLines.map((m) => {
8082
- const normalized = m.originalIndent.replace(/\t/g, " ");
8083
- return normalized.length;
8084
- });
8085
- const minIndent = Math.min(...indentLengths);
8086
- const baseUnit = minIndent > 0 ? minIndent : 4;
8087
- return lineMetadata.map((meta) => {
8088
- if (meta.isBlank) {
8089
- return "";
8090
- }
8091
- if (meta.originalIndent.length === 0) {
8092
- return "";
8093
- }
8094
- const normalized = meta.originalIndent.replace(/\t/g, " ");
8095
- const level = Math.round(normalized.length / baseUnit);
8096
- return " ".repeat(level);
8097
- });
8098
- }
8099
- function reconstructWithLineStructure(transformedParts, lineMetadata, partToLineIndex, targetThen) {
8100
- const nonBlankCount = lineMetadata.filter((m) => !m.isBlank).length;
8101
- if (nonBlankCount <= 1 && transformedParts.length <= 1) {
8102
- const normalizedIndents2 = normalizeIndentation(lineMetadata);
8103
- const result2 = [];
8104
- for (let i = 0; i < lineMetadata.length; i++) {
8105
- if (lineMetadata[i].isBlank) {
8106
- result2.push("");
8107
- } else if (transformedParts.length > 0) {
8108
- result2.push(normalizedIndents2[i] + transformedParts[0]);
8109
- }
8110
- }
8111
- return result2.join("\n");
8112
- }
8113
- const normalizedIndents = normalizeIndentation(lineMetadata);
8114
- const partsPerLine = /* @__PURE__ */ new Map();
8115
- for (let i = 0; i < transformedParts.length; i++) {
8116
- const lineIdx = partToLineIndex[i];
8117
- if (!partsPerLine.has(lineIdx)) {
8118
- partsPerLine.set(lineIdx, []);
8119
- }
8120
- partsPerLine.get(lineIdx).push(transformedParts[i]);
8121
- }
8122
- const result = [];
8123
- for (let i = 0; i < lineMetadata.length; i++) {
8124
- const meta = lineMetadata[i];
8125
- const indent = normalizedIndents[i];
8126
- if (meta.isBlank) {
8127
- result.push("");
8128
- } else {
8129
- const lineParts = partsPerLine.get(i) || [];
8130
- if (lineParts.length > 0) {
8131
- const lineContent = lineParts.join(` ${targetThen} `);
8132
- result.push(indent + lineContent);
8133
- }
8134
- }
8135
- }
8136
- return result.join("\n");
8137
- }
8138
- var BOUNDARY_MODIFIERS = /* @__PURE__ */ new Set([
8139
- "to",
8140
- "into",
8141
- "from",
8142
- "with",
8143
- "by",
8144
- "as",
8145
- "at",
8146
- "in",
8147
- "on",
8148
- "of",
8149
- "over"
8150
- ]);
8151
- var boundaryModifiersCache = /* @__PURE__ */ new Map();
8152
- function getBoundaryModifiersForLocale(locale) {
8153
- const cached = boundaryModifiersCache.get(locale);
8154
- if (cached) return cached;
8155
- const modifiers = new Set(BOUNDARY_MODIFIERS);
8156
- const profile = getProfile(locale);
8157
- profile?.markers.forEach((marker) => {
8158
- const form = marker.form.replace(/^-|-$/g, "").toLowerCase();
8159
- if (form) modifiers.add(form);
8160
- marker.alternatives?.forEach((alt) => {
8161
- const altForm = alt.replace(/^-|-$/g, "").toLowerCase();
8162
- if (altForm) modifiers.add(altForm);
8163
- });
8164
- });
8165
- boundaryModifiersCache.set(locale, modifiers);
8166
- return modifiers;
8167
- }
8168
- var ON_TARGET_COMMANDS = /* @__PURE__ */ new Set(["toggle", "add", "remove", "trigger", "send"]);
8169
- function commandVerbOf(tokens, commandKeywords) {
8170
- for (const token of tokens) {
8171
- const lt = token.toLowerCase();
8172
- if (commandKeywords.has(lt) && !BOUNDARY_MODIFIERS.has(lt) && !EVENT_KEYWORDS.has(lt)) {
8173
- return lt;
8174
- }
8175
- }
8176
- return null;
8177
- }
8178
- var BLOCK_HEAD_KEYWORDS = /* @__PURE__ */ new Set(["live", "when", "unless"]);
8179
- var BLOCK_BODY_KEYWORDS = /* @__PURE__ */ new Set(["if", "repeat", "unless", "while", "for"]);
8180
- var UNLESS_GUARD_OBJECT_MARKING_LOCALES = /* @__PURE__ */ new Set(["he", "zh"]);
8181
- function splitOnCommandBoundaries(input, sourceLocale) {
8182
- const commandKeywords = getCommandKeywordsForLocale(sourceLocale);
8183
- const boundaryModifiers = getBoundaryModifiersForLocale(sourceLocale);
8184
- const { forWords, inWords } = getForLoopWordsForLocale(sourceLocale);
8185
- const tokens = input.split(/\s+/);
8186
- if (tokens.length === 0) return [input];
8187
- const parts = [];
8188
- let currentPart = [];
8189
- const firstTokenLower = tokens[0]?.toLowerCase();
8190
- const isEventHandler = EVENT_KEYWORDS.has(firstTokenLower);
8191
- let seenFirstCommand = !isEventHandler;
8192
- let blockDepth = 0;
8193
- for (let i = 0; i < tokens.length; i++) {
8194
- const token = tokens[i];
8195
- const lowerToken = token.toLowerCase();
8196
- if (BLOCK_HEAD_KEYWORDS.has(lowerToken)) {
8197
- blockDepth++;
8198
- } else if (lowerToken === "end" && blockDepth > 0) {
8199
- blockDepth--;
8200
- }
8201
- if (commandKeywords.has(lowerToken) && currentPart.length > 0) {
8202
- const prevToken = currentPart[currentPart.length - 1];
8203
- const prevLower = prevToken.toLowerCase();
8204
- if (!seenFirstCommand) {
8205
- seenFirstCommand = true;
8206
- currentPart.push(token);
8207
- continue;
8208
- }
8209
- if (blockDepth > 0) {
8210
- currentPart.push(token);
8211
- continue;
8212
- }
8213
- if (forWords.has(lowerToken) && !isLoopHeadFor(tokens, i, inWords, commandKeywords)) {
8214
- currentPart.push(token);
8215
- continue;
8216
- }
8217
- if (BOUNDARY_MODIFIERS.has(lowerToken)) {
8218
- const verb = commandVerbOf(currentPart, commandKeywords);
8219
- if (verb && ON_TARGET_COMMANDS.has(verb)) {
8220
- currentPart.push(token);
8221
- continue;
8222
- }
8223
- if (lowerToken === "on" && verb === "set") {
8224
- const nextTok = tokens[i + 1];
8225
- const nextLower = nextTok?.toLowerCase();
8226
- const scopeLike = !!nextTok && (/^[#.<@[]/.test(nextTok) || nextLower === "me" || nextLower === "it" || nextLower === "you");
8227
- if (scopeLike) {
8228
- currentPart.push(token);
8229
- continue;
8230
- }
8231
- }
8232
- }
8233
- if (!boundaryModifiers.has(prevLower) && !commandKeywords.has(prevLower)) {
8234
- parts.push(currentPart.join(" "));
8235
- currentPart = [token];
8236
- continue;
8237
- }
8238
- }
8239
- currentPart.push(token);
8240
- }
8241
- if (currentPart.length > 0) {
8242
- parts.push(currentPart.join(" "));
8243
- }
8244
- return parts.filter((p) => p.length > 0);
8245
- }
8246
- function splitOnThen(input, sourceLocale) {
8247
- const thenKeywords = Array.from(THEN_KEYWORDS);
8248
- const sourceDict = sourceLocale === "en" ? null : dictionaries[sourceLocale];
8249
- if (sourceDict?.modifiers?.then) {
8250
- thenKeywords.push(sourceDict.modifiers.then);
8251
- }
8252
- if (sourceDict?.logical?.then) {
8253
- thenKeywords.push((sourceDict?.logical).then);
8254
- }
8255
- const escapedKeywords = thenKeywords.map((k) => k.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
8256
- const pattern = new RegExp(`\\s+(${escapedKeywords.join("|")})\\s+`, "gi");
8257
- const parts = input.split(pattern).filter((part) => {
8258
- const lowerPart = part.toLowerCase().trim();
8259
- return lowerPart && !thenKeywords.some((k) => k.toLowerCase() === lowerPart);
8260
- });
8261
- return parts.map((p) => p.trim()).filter((p) => p.length > 0);
8262
- }
8263
- function getTargetThenKeyword(targetLocale) {
8264
- if (targetLocale === "en") return "then";
8265
- const targetDict = dictionaries[targetLocale];
8266
- if (!targetDict) return "then";
8267
- return targetDict.modifiers?.then || targetDict.logical?.then || "then";
8268
- }
8269
- function deriveEventKeywordsFromProfiles() {
8270
- const keywords = /* @__PURE__ */ new Set();
8271
- keywords.add("on");
8272
- for (const profile of Object.values(profiles)) {
8273
- for (const marker of profile.markers) {
8274
- if (marker.role === "event") {
8275
- const form = marker.form.replace(/^-|-$/g, "").toLowerCase();
8276
- if (form) keywords.add(form);
8277
- marker.alternatives?.forEach((alt) => {
8278
- const altForm = alt.replace(/^-|-$/g, "").toLowerCase();
8279
- if (altForm) keywords.add(altForm);
8280
- });
8281
- }
8282
- }
8283
- }
8284
- return keywords;
8285
- }
8286
- var EVENT_KEYWORDS = deriveEventKeywordsFromProfiles();
8287
- var EVENT_CONJUNCTIONS = /* @__PURE__ */ new Set(["or"]);
8288
- var BODY_MODIFIER_KEYWORDS = /* @__PURE__ */ new Set([
8289
- "async",
8290
- "once",
8291
- "debounced",
8292
- "debounce",
8293
- "throttled",
8294
- "throttle"
8295
- ]);
8296
- function generateModifierMap(profile) {
8297
- const map = {};
8298
- profile.markers.forEach((marker) => {
8299
- const form = marker.form.replace(/^-|-$/g, "").toLowerCase();
8300
- if (form) {
8301
- map[form] = marker.role;
8302
- }
8303
- marker.alternatives?.forEach((alt) => {
8304
- const altForm = alt.replace(/^-|-$/g, "").toLowerCase();
8305
- if (altForm) {
8306
- map[altForm] = marker.role;
8307
- }
8308
- });
8309
- });
8310
- for (const [key, role] of Object.entries(ENGLISH_MODIFIER_ROLES)) {
8311
- if (!(key in map)) {
8312
- map[key] = role;
8313
- }
8314
- }
8315
- return map;
8316
- }
8317
- function buildArgumentModifierMap(profile, actionVerb) {
8318
- const map = generateModifierMap(profile);
8319
- const verb = actionVerb?.toLowerCase();
8320
- if (profile.wordOrder !== "SVO" || !verb || !ON_TARGET_COMMANDS.has(verb)) {
8321
- return map;
8322
- }
8323
- const remapped = {};
8324
- for (const [form, role] of Object.entries(map)) {
8325
- remapped[form] = role === "event" ? "destination" : role;
8326
- }
8327
- return remapped;
8328
- }
8329
- function parseStatement(input, sourceLocale = "en") {
8330
- const profile = getProfile(sourceLocale);
8331
- if (!profile) return null;
8332
- const tokens = tokenize(input, profile);
8333
- const statementType = identifyStatementType(tokens, profile);
8334
- switch (statementType) {
8335
- case "event-handler":
8336
- return parseEventHandler(tokens, profile);
8337
- case "command":
8338
- return parseCommand(tokens, profile);
8339
- case "conditional":
8340
- return parseConditional(tokens);
8341
- default:
8342
- return null;
8343
- }
8344
- }
8345
- var ATTACHED_SUFFIXES = {
8346
- // Chinese: 时 (time/when) often attaches to events like 点击时 (when clicking)
8347
- zh: ["\u65F6", "\u7684", "\u5730", "\u5F97"],
8348
- // Japanese: Some particles may attach in casual writing
8349
- ja: [],
8350
- // Korean: Particles sometimes written without spaces
8351
- ko: []
8352
- };
8353
- var ATTACHED_PREFIXES = {
8354
- // Chinese: 当 (when) sometimes written attached
8355
- zh: ["\u5F53"],
8356
- // Arabic: Prepositions that attach
8357
- ar: ["\u0628\u0640", "\u0643\u0640", "\u0648"]
8358
- };
8359
- function splitAttachedAffixes(tokens, locale) {
8360
- const suffixes = ATTACHED_SUFFIXES[locale] || [];
8361
- const prefixes = ATTACHED_PREFIXES[locale] || [];
8362
- if (suffixes.length === 0 && prefixes.length === 0) {
8363
- return tokens;
8364
- }
8365
- const result = [];
8366
- for (const token of tokens) {
8367
- if (/^[#.<@]/.test(token) || /^\d+/.test(token)) {
8368
- result.push(token);
8369
- continue;
8370
- }
8371
- let processed = token;
8372
- let prefix = "";
8373
- let suffix = "";
8374
- for (const p of prefixes) {
8375
- if (processed.startsWith(p) && processed.length > p.length) {
8376
- prefix = p;
8377
- processed = processed.slice(p.length);
8378
- break;
8379
- }
8380
- }
8381
- for (const s of suffixes) {
8382
- if (processed.endsWith(s) && processed.length > s.length) {
8383
- suffix = s;
8384
- processed = processed.slice(0, -s.length);
8385
- break;
8386
- }
8387
- }
8388
- if (prefix) result.push(prefix);
8389
- if (processed) result.push(processed);
8390
- if (suffix) result.push(suffix);
8391
- }
8392
- return result;
8393
- }
8394
- function tokenize(input, profile) {
8395
- const tokens = [];
8396
- let current = "";
8397
- let inSelector = false;
8398
- let selectorDepth = 0;
8399
- let bracketDepth = 0;
8400
- let parenDepth = 0;
8401
- for (let i = 0; i < input.length; i++) {
8402
- const char = input[i];
8403
- if (char === "<") {
8404
- inSelector = true;
8405
- selectorDepth++;
8406
- } else if (char === ">" && inSelector) {
8407
- selectorDepth--;
8408
- if (selectorDepth === 0) inSelector = false;
8409
- }
8410
- if (char === "[") {
8411
- bracketDepth++;
8412
- } else if (char === "]" && bracketDepth > 0) {
8413
- bracketDepth--;
8414
- }
8415
- if (char === "(") {
8416
- parenDepth++;
8417
- } else if (char === ")" && parenDepth > 0) {
8418
- parenDepth--;
8419
- }
8420
- if (/\s/.test(char) && !inSelector && bracketDepth === 0 && parenDepth === 0) {
8421
- if (current) {
8422
- tokens.push(current);
8423
- current = "";
8424
- }
8425
- } else {
8426
- current += char;
8427
- }
8428
- }
8429
- if (current) {
8430
- tokens.push(current);
8431
- }
8432
- return splitAttachedAffixes(tokens, profile.code);
8433
- }
8434
- function identifyStatementType(tokens, profile) {
8435
- if (tokens.length === 0) return "unknown";
8436
- const firstToken = tokens[0].toLowerCase();
8437
- const eventMarker = profile.markers.find((m) => m.role === "event" && m.position === "preposition");
8438
- if (eventMarker && firstToken === eventMarker.form.toLowerCase()) {
8439
- return "event-handler";
8440
- }
8441
- if (EVENT_KEYWORDS.has(firstToken)) {
8442
- return "event-handler";
8443
- }
8444
- if (CONDITIONAL_KEYWORDS.has(firstToken)) {
8445
- return "conditional";
8446
- }
8447
- return "command";
8448
- }
8449
- function parseEventHandler(tokens, profile) {
8450
- const roles = /* @__PURE__ */ new Map();
8451
- let startIndex = EVENT_KEYWORDS.has(tokens[0]?.toLowerCase()) ? 1 : 0;
8452
- if (tokens[startIndex]) {
8453
- const eventTokens = [tokens[startIndex]];
8454
- startIndex++;
8455
- while (tokens[startIndex] && EVENT_CONJUNCTIONS.has(tokens[startIndex].toLowerCase()) && tokens[startIndex + 1]) {
8456
- eventTokens.push(tokens[startIndex], tokens[startIndex + 1]);
8457
- startIndex += 2;
8458
- }
8459
- roles.set("event", {
8460
- role: "event",
8461
- value: eventTokens.join(" ")
8462
- });
8463
- }
8464
- if (tokens[startIndex] && tokens[startIndex].toLowerCase() === "from" && tokens[startIndex + 1]) {
8465
- startIndex++;
8466
- const sourceValue = [];
8467
- while (tokens[startIndex]) {
8468
- if (ENGLISH_COMMANDS.has(tokens[startIndex].toLowerCase())) break;
8469
- sourceValue.push(tokens[startIndex]);
8470
- startIndex++;
8471
- }
8472
- if (sourceValue.length > 0) {
8473
- const value = sourceValue.join(" ");
8474
- roles.set("source", {
8475
- role: "source",
8476
- value,
8477
- isSelector: /^[#.<@]/.test(value)
8478
- });
8479
- }
8480
- }
8481
- if (tokens[startIndex]) {
8482
- roles.set("action", {
8483
- role: "action",
8484
- value: tokens[startIndex]
8485
- });
8486
- startIndex++;
8487
- }
8488
- if (tokens[startIndex]) {
8489
- const modifierMap = buildArgumentModifierMap(profile, roles.get("action")?.value);
8490
- let currentRole = "patient";
8491
- let currentValue = [];
8492
- for (let i = startIndex; i < tokens.length; i++) {
8493
- const token = tokens[i];
8494
- const mappedRole = modifierMap[token.toLowerCase()];
8495
- if (mappedRole) {
8496
- if (currentValue.length > 0) {
8497
- const value = currentValue.join(" ");
8498
- roles.set(currentRole, {
8499
- role: currentRole,
8500
- value,
8501
- isSelector: /^[#.<@]/.test(value)
8502
- });
8503
- }
8504
- currentRole = mappedRole;
8505
- currentValue = [];
8506
- } else {
8507
- currentValue.push(token);
8508
- }
8509
- }
8510
- if (currentValue.length > 0) {
8511
- const value = currentValue.join(" ");
8512
- roles.set(currentRole, {
8513
- role: currentRole,
8514
- value,
8515
- isSelector: /^[#.<@]/.test(value)
8516
- });
8517
- }
8518
- }
8519
- return {
8520
- type: "event-handler",
8521
- roles,
8522
- original: tokens.join(" ")
8523
- };
8524
- }
8525
- function parseCommand(tokens, profile) {
8526
- const roles = /* @__PURE__ */ new Map();
8527
- if (tokens.length === 0) {
8528
- return { type: "command", roles, original: "" };
8529
- }
8530
- roles.set("action", {
8531
- role: "action",
8532
- value: tokens[0]
8533
- });
8534
- const modifierMap = buildArgumentModifierMap(profile, tokens[0]);
8535
- let currentRole = "patient";
8536
- let currentValue = [];
8537
- for (let i = 1; i < tokens.length; i++) {
8538
- const token = tokens[i];
8539
- const mappedRole = modifierMap[token.toLowerCase()];
8540
- if (mappedRole) {
8541
- if (currentValue.length > 0) {
8542
- const value = currentValue.join(" ");
8543
- roles.set(currentRole, {
8544
- role: currentRole,
8545
- value,
8546
- isSelector: /^[#.<@]/.test(value)
8547
- });
8548
- }
8549
- currentRole = mappedRole;
8550
- currentValue = [];
8551
- } else {
8552
- currentValue.push(token);
8553
- }
8554
- }
8555
- if (currentValue.length > 0) {
8556
- const value = currentValue.join(" ");
8557
- roles.set(currentRole, {
8558
- role: currentRole,
8559
- value,
8560
- isSelector: /^[#.<@]/.test(value)
8561
- });
8562
- }
8563
- return {
8564
- type: "command",
8565
- roles,
8566
- original: tokens.join(" ")
8567
- };
8568
- }
8569
- var LITERAL_PRIMARY_ROLES = /* @__PURE__ */ new Set([
8570
- "duration",
8571
- "quantity"
8572
- ]);
8573
- function applyPrimaryRole(parsed, targetProfile) {
8574
- if (parsed.type !== "command") return;
8575
- const action = parsed.roles.get("action")?.value;
8576
- if (!action) return;
8577
- const primaryRole = COMMAND_PRIMARY_ROLES[action.toLowerCase()];
8578
- if (!primaryRole || !LITERAL_PRIMARY_ROLES.has(primaryRole)) return;
8579
- const patientEl = parsed.roles.get("patient");
8580
- if (!patientEl || parsed.roles.has(primaryRole)) return;
8581
- if (targetProfile.markers.some((m) => m.role === primaryRole)) return;
8582
- parsed.roles.delete("patient");
8583
- parsed.roles.set(primaryRole, { ...patientEl, role: primaryRole });
8584
- }
8585
- function parseConditional(tokens, _profile) {
8586
- const roles = /* @__PURE__ */ new Map();
8587
- roles.set("action", {
8588
- role: "action",
8589
- value: tokens[0]
8590
- });
8591
- const thenIndex = tokens.findIndex((t) => THEN_KEYWORDS.has(t.toLowerCase()));
8592
- if (thenIndex > 1) {
8593
- const conditionValue = tokens.slice(1, thenIndex).join(" ");
8594
- roles.set("condition", {
8595
- role: "condition",
8596
- value: conditionValue
8597
- });
8598
- } else if (thenIndex === -1 && tokens.length > 1) {
8599
- roles.set("condition", {
8600
- role: "condition",
8601
- value: tokens.slice(1).join(" ")
8602
- });
8603
- }
8604
- return {
8605
- type: "conditional",
8606
- roles,
8607
- original: tokens.join(" ")
8608
- };
8609
- }
8610
- function translateWord(word, sourceLocale, targetLocale) {
8611
- if (/^[#.<@]/.test(word)) {
8612
- return word;
8613
- }
8614
- if (/^\d+/.test(word)) {
8615
- return word;
8616
- }
8617
- if (/\s/.test(word) && word.startsWith("(")) {
8618
- return word.split(/\s+/).map((w) => translateWord(w, sourceLocale, targetLocale)).join(" ");
8619
- }
8620
- if (word.length > 1 && (word.startsWith("(") || word.endsWith(")"))) {
8621
- const m = word.match(/^(\(*)([^()]+)(\)*)$/);
8622
- if (m && (m[1] || m[3])) {
8623
- return m[1] + translateWord(m[2], sourceLocale, targetLocale) + m[3];
8624
- }
8625
- }
8626
- const sourceDict = sourceLocale === "en" ? null : dictionaries[sourceLocale];
8627
- const targetDict = dictionaries[targetLocale];
8628
- if (!targetDict) return word;
8629
- let englishWord = word;
8630
- if (sourceDict) {
8631
- const found = findInDictionary(sourceDict, word);
8632
- if (found) {
8633
- englishWord = found.englishKey;
8634
- }
8635
- }
8636
- const translated = translateFromEnglish(targetDict, englishWord);
8637
- return translated ?? word;
8638
- }
8639
- var POSSESSIVE_MARKERS = {
8640
- en: { type: "suffix", marker: "'s" },
8641
- es: { type: "preposition", marker: "de" },
8642
- pt: { type: "preposition", marker: "de" },
8643
- fr: { type: "preposition", marker: "de" },
8644
- de: { type: "preposition", marker: "von" },
8645
- ja: { type: "suffix", marker: "\u306E" },
8646
- ko: { type: "suffix", marker: "\uC758" },
8647
- zh: { type: "suffix", marker: "\u7684" },
8648
- ar: { type: "preposition", marker: "\u0644\u0640" },
8649
- // Spaced genitive particle (not the glued `'ın`), so the tokenizer can split
8650
- // it off the selector — consistent with Turkish's other spaced case markers.
8651
- tr: { type: "particle", marker: "\u0131n" },
8652
- id: { type: "preposition", marker: "dari" },
8653
- // Latin-script genitive: must be a *spaced* particle (`#picker pa`), since a
8654
- // glued `#pickerpa` can't be split from the selector by the tokenizer the
8655
- // way a non-Latin suffix (の/의/র) can.
8656
- qu: { type: "particle", marker: "pa" },
8657
- // Bengali SOV postposition genitive, like ja/ko — a spaced suffix the
8658
- // tokenizer splits off as a particle. Previously absent, so it fell back to
8659
- // the English `'s` marker and its possessive property paths never parsed.
8660
- // (Hindi `का` is intentionally omitted: its `bind` lacks a verb-final
8661
- // grammar rule, so fixing its possessive alone yields a wrong `on` parse —
8662
- // tracked as separate follow-up.)
8663
- bn: { type: "suffix", marker: "\u09B0" },
8664
- sw: { type: "preposition", marker: "ya" }
8665
- };
8666
- function translatePossessive(token, sourceLocale, targetLocale) {
8667
- const possessiveMatch = token.match(/^(.+)'s$/i);
8668
- if (!possessiveMatch) {
8669
- return token;
8670
- }
8671
- const owner = possessiveMatch[1];
8672
- const targetMarker = POSSESSIVE_MARKERS[targetLocale] || POSSESSIVE_MARKERS.en;
8673
- const pronounPossessives = {
8674
- me: "my",
8675
- it: "its",
8676
- you: "your"
8677
- };
8678
- const lowerOwner = owner.toLowerCase();
8679
- if (pronounPossessives[lowerOwner]) {
8680
- const possessiveForm = pronounPossessives[lowerOwner];
8681
- return translateWord(possessiveForm, "en", targetLocale);
8682
- }
8683
- const translatedOwner = translateWord(owner, sourceLocale, targetLocale);
8684
- switch (targetMarker.type) {
8685
- case "suffix":
8686
- return `${translatedOwner}${targetMarker.marker}`;
8687
- case "particle":
8688
- return `${translatedOwner} ${targetMarker.marker}`;
8689
- case "preposition":
8690
- return `__POSS__${targetMarker.marker}__${translatedOwner}__POSS__`;
8691
- default:
8692
- return `${translatedOwner}'s`;
8693
- }
8694
- }
8695
- var POSSESSIVE_DOT_REGEX = /^(my|its|your|me|it|you)(\??\..+)$/i;
8696
- var POSSESSIVE_DOT_PRONOUNS = {
8697
- me: "my",
8698
- it: "its",
8699
- you: "your",
8700
- my: "my",
8701
- its: "its",
8702
- your: "your"
8703
- };
8704
- function translatePossessiveDotNotation(value, sourceLocale, targetLocale) {
8705
- const match = value.match(POSSESSIVE_DOT_REGEX);
8706
- if (!match) return null;
8707
- const possessiveWord = match[1].toLowerCase();
8708
- const propertySuffix = match[2];
8709
- const possessiveKey = POSSESSIVE_DOT_PRONOUNS[possessiveWord] || possessiveWord;
8710
- const translated = translateWord(possessiveKey, sourceLocale, targetLocale);
8711
- if (translated.includes(" ")) return null;
8712
- if (translated !== possessiveKey) {
8713
- return translated + propertySuffix;
8714
- }
8715
- if (possessiveWord !== possessiveKey) {
8716
- const alt = translateWord(possessiveWord, sourceLocale, targetLocale);
8717
- if (alt !== possessiveWord && !alt.includes(" ")) {
8718
- return alt + propertySuffix;
8719
- }
8720
- }
8721
- return null;
8722
- }
8723
- function translateMultiWordValue(value, sourceLocale, targetLocale) {
8724
- if (value.includes("[")) {
8725
- const guards = [];
8726
- const masked = value.replace(/\[[^\]]*\]/g, (match) => {
8727
- guards.push(match);
8728
- return `\uE000${guards.length - 1}\uE001`;
8729
- });
8730
- if (guards.length > 0) {
8731
- const translated2 = translateMultiWordValue(masked, sourceLocale, targetLocale);
8732
- return translated2.replace(/(\d+)/g, (_, n) => guards[Number(n)]);
8733
- }
8734
- }
8735
- if (!value.includes(" ")) {
8736
- if (value.includes("'s")) {
8737
- return translatePossessive(value, sourceLocale, targetLocale);
8738
- }
8739
- const dotResult = translatePossessiveDotNotation(value, sourceLocale, targetLocale);
8740
- if (dotResult !== null) return dotResult;
8741
- return translateWord(value, sourceLocale, targetLocale);
8742
- }
8743
- const words = value.split(/\s+/);
8744
- const translated = [];
8745
- let i = 0;
8746
- while (i < words.length) {
8747
- const word = words[i];
8748
- if (word.includes("'s")) {
8749
- const possessiveResult = translatePossessive(word, sourceLocale, targetLocale);
8750
- const prepMatch = possessiveResult.match(/^__POSS__(.+)__(.+)__POSS__$/);
8751
- if (prepMatch && i + 1 < words.length) {
8752
- const marker = prepMatch[1];
8753
- const owner = prepMatch[2];
8754
- const property = words[i + 1];
8755
- const translatedProperty = translateWord(property, sourceLocale, targetLocale);
8756
- translated.push(`${translatedProperty} ${marker} ${owner}`);
8757
- i += 2;
8758
- continue;
8759
- } else if (prepMatch) {
8760
- const marker = prepMatch[1];
8761
- const owner = prepMatch[2];
8762
- translated.push(`${marker} ${owner}`);
8763
- i++;
8764
- continue;
8765
- }
8766
- translated.push(possessiveResult);
8767
- i++;
8768
- continue;
8769
- }
8770
- if (/^[#.<@]/.test(word) || /^\d+/.test(word)) {
8771
- translated.push(word);
8772
- i++;
8773
- continue;
8774
- }
8775
- if (/^["'].*["']$/.test(word)) {
8776
- translated.push(word);
8777
- i++;
8778
- continue;
8779
- }
8780
- const dotResult = translatePossessiveDotNotation(word, sourceLocale, targetLocale);
8781
- if (dotResult !== null) {
8782
- translated.push(dotResult);
8783
- i++;
8784
- continue;
8785
- }
8786
- translated.push(translateWord(word, sourceLocale, targetLocale));
8787
- i++;
8788
- }
8789
- return translated.join(" ");
8790
- }
8791
- function translateElements(parsed, sourceLocale, targetLocale) {
8792
- for (const [_role, element] of parsed.roles) {
8793
- if (element.value.includes("'s")) {
8794
- element.translated = translateMultiWordValue(element.value, sourceLocale, targetLocale);
8795
- } else if (!element.isSelector && !element.isLiteral) {
8796
- element.translated = translateMultiWordValue(element.value, sourceLocale, targetLocale);
8797
- } else {
8798
- element.translated = element.value;
8799
- }
8800
- }
8801
- }
8802
- var CARET_SCOPE_OPEN = "\uE000";
8803
- var CARET_SCOPE_CLOSE = "\uE001";
8804
- var CARET_SCOPE_RE = /(\^[A-Za-z_][\w-]*)(\s+on\s+(?:[#.][\w-]+|<[^>]*\/>|\[[^\]]+\]))/g;
8805
- function maskCaretScopes(input) {
8806
- const scopes = [];
8807
- const masked = input.replace(CARET_SCOPE_RE, (_m, varTok, scope) => {
8808
- const idx = scopes.length;
8809
- scopes.push(scope);
8810
- return `${varTok}${CARET_SCOPE_OPEN}${idx}${CARET_SCOPE_CLOSE}`;
8811
- });
8812
- return scopes.length > 0 ? { masked, scopes } : null;
8813
- }
8814
- function restoreCaretScopes(input, scopes) {
8815
- return input.replace(
8816
- new RegExp(`${CARET_SCOPE_OPEN}(\\d+)${CARET_SCOPE_CLOSE}`, "g"),
8817
- (_m, n) => scopes[Number(n)] ?? ""
8818
- );
8819
- }
8820
- var VIEW_TAIL_OPEN = "\uE002";
8821
- var VIEW_TAIL_CLOSE = "\uE003";
8822
- var VIEW_TAIL_RE = /\busing\s+view\b(?:\s+(?!then\b)[A-Za-z][\w-]*)?/gi;
8823
- var VIEW_TAIL_TOKEN_RE = new RegExp(`^${VIEW_TAIL_OPEN}(\\d+)${VIEW_TAIL_CLOSE}$`);
8824
- function maskViewTransitionTails(input) {
8825
- const tails = [];
8826
- const masked = input.replace(VIEW_TAIL_RE, (match) => {
8827
- const idx = tails.length;
8828
- tails.push(match);
8829
- return `${VIEW_TAIL_OPEN}${idx}${VIEW_TAIL_CLOSE}`;
8830
- });
8831
- return tails.length > 0 ? { masked, tails } : null;
8832
- }
8833
- function restoreViewTransitionTails(input, tails) {
8834
- return input.replace(
8835
- new RegExp(`${VIEW_TAIL_OPEN}(\\d+)${VIEW_TAIL_CLOSE}`, "g"),
8836
- (_m, n) => tails[Number(n)] ?? ""
8837
- );
8838
- }
8839
- var GrammarTransformer = class {
8840
- constructor(sourceLocale = "en", targetLocale) {
8841
- const source = getProfile(sourceLocale);
8842
- const target = getProfile(targetLocale);
8843
- if (!source) throw new Error(`Unknown source locale: ${sourceLocale}`);
8844
- if (!target) throw new Error(`Unknown target locale: ${targetLocale}`);
8845
- this.sourceProfile = source;
8846
- this.targetProfile = target;
8847
- }
8848
- /**
8849
- * Transform a hyperscript statement from source to target language.
8850
- * Handles compound statements with "then" by splitting, transforming each part,
8851
- * and rejoining with the target language's "then" keyword.
8852
- *
8853
- * For multi-line input, preserves line structure (indentation, blank lines).
8854
- */
8855
- transform(input) {
8856
- const out = this.transformInternal(input);
8857
- return this.targetProfile.code === "he" ? repairHebrewFrontedAccusative(out) : out;
8858
- }
8859
- transformInternal(input) {
8860
- const viewTails = maskViewTransitionTails(input);
8861
- if (viewTails) {
8862
- return restoreViewTransitionTails(this.transformInternal(viewTails.masked), viewTails.tails);
8863
- }
8864
- const caret = maskCaretScopes(input);
8865
- if (caret) {
8866
- return restoreCaretScopes(this.transform(caret.masked), caret.scopes);
8867
- }
8868
- const targetThen = getTargetThenKeyword(this.targetProfile.code);
8869
- if (!input.includes("\n")) {
8870
- const jsBlock = this.tryTransformJsBlock(input);
8871
- if (jsBlock !== null) return jsBlock;
8872
- const eventModifier = this.tryTransformEventWithModifierBody(input);
8873
- if (eventModifier !== null) return eventModifier;
8874
- const eventBlock = this.tryTransformEventWithBlockBody(input);
8875
- if (eventBlock !== null) return eventBlock;
8876
- const eventGuard = this.tryTransformEventWithUnlessGuard(input);
8877
- if (eventGuard !== null) return eventGuard;
8878
- }
8879
- const hasMultiLineStructure = input.includes("\n");
8880
- if (hasMultiLineStructure) {
8881
- const { parts: parts2, lineMetadata, partToLineIndex } = splitCompoundStatementWithMetadata(
8882
- input,
8883
- this.sourceProfile.code
8884
- );
8885
- const transformedParts = parts2.map((part) => this.transformSingle(part));
8886
- return reconstructWithLineStructure(
8887
- transformedParts,
8888
- lineMetadata,
8889
- partToLineIndex,
8890
- targetThen
8891
- );
8892
- }
8893
- const parts = splitCompoundStatement(input, this.sourceProfile.code);
8894
- if (parts.length > 1) {
8895
- const transformedParts = parts.map((part) => this.transformSingle(part));
8896
- return transformedParts.join(` ${targetThen} `);
8897
- }
8898
- return this.transformSingle(input);
8899
- }
8900
- /**
8901
- * Transform a single hyperscript statement (no compound "then" chains).
8902
- */
8903
- transformSingle(input) {
8904
- const block = extractBlockStructure(input, this.sourceProfile.code);
8905
- if (block) {
8906
- return this.transformBlock(block);
8907
- }
8908
- const strippedEnd = this.transformWithTrailingEnd(input);
8909
- if (strippedEnd !== null) {
8910
- return strippedEnd;
8911
- }
8912
- const setScope = this.transformSetWithScope(input);
8913
- if (setScope !== null) {
8914
- return setScope;
8915
- }
8916
- const viewTail = this.transformWithViewTransitionTail(input);
8917
- if (viewTail !== null) {
8918
- return viewTail;
8919
- }
8920
- const parsed = parseStatement(input, this.sourceProfile.code);
8921
- if (!parsed) {
8922
- return input;
8923
- }
8924
- applyPrimaryRole(parsed, this.targetProfile);
8925
- translateElements(parsed, this.sourceProfile.code, this.targetProfile.code);
8926
- const rule = this.findRule(parsed);
8927
- if (rule?.transform.custom) {
8928
- return rule.transform.custom(parsed, this.targetProfile);
8929
- }
8930
- const roleOrder = rule?.transform.roleOrder || this.targetProfile.canonicalOrder;
8931
- const reordered = reorderRoles(parsed.roles, roleOrder);
8932
- const shouldInsertMarkers = rule?.transform.insertMarkers ?? true;
8933
- if (shouldInsertMarkers) {
8934
- const result = insertMarkers(
8935
- reordered,
8936
- this.targetProfile.markers,
8937
- this.targetProfile.adpositionType
8938
- );
8939
- return joinTokens(result);
8940
- }
8941
- return joinTokens(reordered.map((e) => e.translated || e.value));
8942
- }
8943
- /**
8944
- * Clause carrying a masked `using view transition` tail: strip the opaque
8945
- * token, transform the clause alone, and re-append the token at the very end.
8946
- *
8947
- * The tail is a clause-final modifier in every word order the corpus emits:
8948
- * the semantic side matches it as the literal `using view` marker plus a value
8949
- * word, and the SOV/VSO event-handler patterns admit it as an optional
8950
- * TRAILING group (after the with-marked operand). So the target position is
8951
- * "end of the transformed clause" for all 24 languages — no per-profile
8952
- * placement decision, which is what makes this a passthrough rather than a
8953
- * role.
8954
- *
8955
- * Returns null when the clause carries no masked tail, or when the token is
8956
- * not clause-final (nothing to reposition — leaving it in place still restores
8957
- * verbatim English).
8958
- */
8959
- transformWithViewTransitionTail(input) {
8960
- const trimmed = input.trim();
8961
- const tokens = trimmed.split(/\s+/);
8962
- if (tokens.length < 2) {
8963
- return null;
8964
- }
8965
- if (!VIEW_TAIL_TOKEN_RE.test(tokens[tokens.length - 1])) {
8966
- return null;
8967
- }
8968
- const tail = tokens[tokens.length - 1];
8969
- const head = tokens.slice(0, -1).join(" ");
8970
- return `${this.transformSingle(head)} ${tail}`;
8971
- }
8972
- /**
8973
- * `<command …> end` fragments: transform the command without its stranded
8974
- * terminator, then re-append the translated terminator as a standalone
8975
- * trailing token. Fragments that open a block of their own (`if … end`,
8976
- * `repeat … end`, `js … end`) bail — their terminator belongs to them and
8977
- * their dedicated paths handle it.
8978
- */
8979
- transformWithTrailingEnd(input) {
8980
- const src = this.sourceProfile.code;
8981
- const tokens = input.trim().split(/\s+/);
8982
- if (tokens.length < 2) {
8983
- return null;
8984
- }
8985
- const sourceEnd = translateWord("end", "en", src).toLowerCase();
8986
- if (tokens[tokens.length - 1].toLowerCase() !== sourceEnd) {
8987
- return null;
8988
- }
8989
- const openers = new Set(
8990
- ["if", "repeat", "unless", "while", "when", "live", "js"].map(
8991
- (k) => translateWord(k, "en", src).toLowerCase()
8992
- )
8993
- );
8994
- if (tokens.slice(0, -1).some((t) => openers.has(t.toLowerCase()))) {
8995
- return null;
8996
- }
8997
- const inner = this.transformSingle(tokens.slice(0, -1).join(" "));
8998
- const endT = translateWord(tokens[tokens.length - 1], src, this.targetProfile.code);
8999
- return `${inner} ${endT}`;
9000
- }
9001
- /**
9002
- * Detect and transform an inline JS block (`[on <event>] js <raw js> end`).
9003
- *
9004
- * The `js ... end` body is raw JavaScript: it must not be tokenized,
9005
- * translated, or word-order reordered. We mask the whole block with a single
9006
- * opaque placeholder, run the surrounding statement (the event-handler head,
9007
- * if any) through the normal reorder pipeline so the placeholder lands in the
9008
- * correct action position, then substitute the translated `js`/`end` keywords
9009
- * around the verbatim body.
9010
- *
9011
- * Returns `null` (fall through to the normal path) when there is no js block,
9012
- * no matching `end`, or trailing content after `end` (kept tight on purpose).
9013
- */
9014
- tryTransformJsBlock(input) {
9015
- const src = this.sourceProfile.code;
9016
- const dst = this.targetProfile.code;
9017
- const sourceJs = translateWord("js", "en", src);
9018
- const sourceEnd = translateWord("end", "en", src).toLowerCase();
9019
- const tokens = input.split(/\s+/).filter((t) => t.length > 0);
9020
- const escapedJs = sourceJs.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
9021
- const jsRe = new RegExp(`^${escapedJs}(\\(.*\\))?$`, "i");
9022
- const jsIdx = tokens.findIndex((t) => jsRe.test(t));
9023
- if (jsIdx === -1) return null;
9024
- let endIdx = -1;
9025
- for (let i = jsIdx + 1; i < tokens.length; i++) {
9026
- if (tokens[i].toLowerCase() === sourceEnd) {
9027
- endIdx = i;
9028
- break;
9029
- }
9030
- }
9031
- if (endIdx === -1) return null;
9032
- if (endIdx !== tokens.length - 1) return null;
9033
- const jsToken = tokens[jsIdx];
9034
- const jsParen = jsToken.match(jsRe)?.[1] ?? "";
9035
- const jsKeywordRaw = jsParen ? jsToken.slice(0, jsToken.length - jsParen.length) : jsToken;
9036
- const body = tokens.slice(jsIdx + 1, endIdx).join(" ");
9037
- const targetJs = translateWord(jsKeywordRaw, src, dst) + jsParen;
9038
- const targetEnd = translateWord(tokens[endIdx], src, dst);
9039
- const replacement = [targetJs, body, targetEnd].filter((s) => s.length > 0).join(" ");
9040
- const before = tokens.slice(0, jsIdx);
9041
- if (before.length === 0) return replacement;
9042
- const placeholder = "JSBLOCKPLACEHOLDER";
9043
- const reordered = this.transformSingle([...before, placeholder].join(" "));
9044
- if (!reordered.includes(placeholder)) return null;
9045
- return reordered.replace(placeholder, replacement);
9046
- }
9047
- /**
9048
- * Transform an event handler whose body is a block command
9049
- * (`on <event> [from <src>] {if|repeat|unless|while|for} … end`).
9050
- *
9051
- * `parseEventHandler` would treat the block keyword as the action and sweep the
9052
- * condition/body into role values, then reorder them — shredding the block
9053
- * (`if event.shiftKey call submitAndContinue() end` → scattered tokens). Instead
9054
- * we mask the whole block as an opaque action placeholder, reorder the event
9055
- * head normally, transform the block as a self-contained unit, and restitch.
9056
- *
9057
- * Returns `null` (fall through) when the input isn't an event handler, has no
9058
- * block-keyword body, or has no closing `end`.
9059
- */
9060
- tryTransformEventWithBlockBody(input) {
9061
- const tokens = tokenize(input, this.sourceProfile);
9062
- if (tokens.length === 0) return null;
9063
- if (!EVENT_KEYWORDS.has(tokens[0]?.toLowerCase())) return null;
9064
- let blockIdx = -1;
9065
- for (let i = 1; i < tokens.length; i++) {
9066
- if (BLOCK_BODY_KEYWORDS.has(tokens[i].toLowerCase())) {
9067
- blockIdx = i;
9068
- break;
9069
- }
9070
- }
9071
- if (blockIdx <= 0) return null;
9072
- if (tokens[tokens.length - 1].toLowerCase() !== "end") return null;
9073
- const eventHead = tokens.slice(0, blockIdx);
9074
- const blockTokens = tokens.slice(blockIdx);
9075
- if (this.targetProfile.wordOrder === "VSO" && eventHead.some((t) => t.toLowerCase() === "from")) {
9076
- return null;
9077
- }
9078
- const placeholder = "EVENTBLOCKPLACEHOLDER";
9079
- const headOut = this.transformSingle([...eventHead, placeholder].join(" "));
9080
- if (!headOut.includes(placeholder)) return null;
9081
- const blockOut = this.transformBlockBody(blockTokens);
9082
- const eventClause = headOut.replace(placeholder, "").replace(/\s+/g, " ").trim();
9083
- return [eventClause, blockOut].filter((s) => s.length > 0).join(" ");
9084
- }
9085
- /**
9086
- * Transform an event handler whose body is an inline `unless` guard with NO
9087
- * `end` (`on <event> unless <cond> <body>` — the `unless-condition` shape).
9088
- *
9089
- * Object-marking SVO targets (he, zh). `parseEventHandler` reads `unless` as the
9090
- * action and sweeps the whole `<cond> <body>` tail into a single `patient` blob;
9091
- * the target then prefixes that blob with its object marker — Hebrew's accusative
9092
- * את (`… אלא את I match .disabled מתג .selected`) or Chinese's BA particle 把
9093
- * (`… 除非 把 I match .disabled 切换 .selected`) — and the inner toggle loses its
9094
- * own marker. The semantic parser can't recover the guard from that: the marker
9095
- * ahead of the condition blocks the `unless` pattern AND the now-markerless body
9096
- * command fails its object-marked toggle pattern, so the body collapses (`unless`
9097
- * dropped). Marker-less languages (de/it/ar/pl) tolerate the same role-blob and
9098
- * stay faithful, so this is an object-marker artifact, not a general parse gap.
9099
- *
9100
- * The standalone `unless <cond> <body>` path already produces the correct shape
9101
- * (`extractBlockStructure` → `transformBlock`: condition kept marker-free, body
9102
- * command keeps its marker — he `אלא I match .disabled מתג את .selected`, zh
9103
- * `除非 I match .disabled 切换 把 .selected`). So we split the event head off,
9104
- * transform the guard through that path, and emit the event clause first (he and
9105
- * zh are both SVO — event leads). Returns `null` (fall through) when the input
9106
- * isn't an object-marking event handler with an un-terminated inline `unless`
9107
- * guard.
9108
- */
9109
- tryTransformEventWithUnlessGuard(input) {
9110
- if (!UNLESS_GUARD_OBJECT_MARKING_LOCALES.has(this.targetProfile.code)) return null;
9111
- const tokens = tokenize(input, this.sourceProfile);
9112
- if (tokens.length === 0) return null;
9113
- if (!EVENT_KEYWORDS.has(tokens[0]?.toLowerCase())) return null;
9114
- let guardIdx = -1;
9115
- for (let i = 1; i < tokens.length; i++) {
9116
- if (tokens[i].toLowerCase() === "unless") {
9117
- guardIdx = i;
9118
- break;
9119
- }
9120
- }
9121
- if (guardIdx <= 0) return null;
9122
- if (tokens[tokens.length - 1].toLowerCase() === "end") return null;
9123
- const eventHead = tokens.slice(0, guardIdx);
9124
- const guard = tokens.slice(guardIdx).join(" ");
9125
- const guardOut = this.transform(guard);
9126
- if (!guardOut) return null;
9127
- const placeholder = "EVENTGUARDPLACEHOLDER";
9128
- const headOut = this.transformSingle([...eventHead, placeholder].join(" "));
9129
- if (!headOut.includes(placeholder)) return null;
9130
- const eventClause = headOut.replace(placeholder, "").replace(/\s+/g, " ").trim();
9131
- return [eventClause, guardOut].filter((s) => s.length > 0).join(" ");
9132
- }
9133
- /**
9134
- * Transform an event handler whose body leads with a command-modifier
9135
- * (`on <event> [from <src>] {async|once|debounced [at N]|throttled [at N]} <body>`).
9136
- *
9137
- * `parseEventHandler` reads the first token after the event as the **action**, so
9138
- * a leading modifier is mistaken for the verb and the real verb (`fetch`/`add`) is
9139
- * swept into the patient. For SOV targets the reorder then surfaces that verb
9140
- * **first** (`取得 /api/data を クリック …`), and the semantic parser matches the
9141
- * leading `<verb> <patient>` with the low-priority `*-generated-verb-first`
9142
- * command pattern — returning a bare command and discarding the event + the rest
9143
- * of the body (degenerate parse).
9144
- *
9145
- * Instead, lift the modifier out, transform the modifier-free handler through the
9146
- * normal path (which keeps the body in canonical patient-first SOV order so the
9147
- * event sits mid-stream and the existing SOV event-extraction recovers it), then
9148
- * re-emit the modifier as a **leading English literal**. The semantic parser
9149
- * strips a leading `once`/`debounced`/`throttled` (`extractStandaloneModifiers`)
9150
- * and an `async` anywhere (`stripAsyncModifier`) before parsing, so the modifier
9151
- * is consumed as handler metadata rather than shadowing the body.
9152
- *
9153
- * Returns `null` (fall through) when the input isn't an event handler or the body
9154
- * doesn't lead with a modifier — leaving simple/Mode-B handlers byte-identical.
9155
- */
9156
- tryTransformEventWithModifierBody(input) {
9157
- if (this.targetProfile.wordOrder !== "SOV") return null;
9158
- const tokens = tokenize(input, this.sourceProfile);
9159
- if (tokens.length === 0) return null;
9160
- if (!EVENT_KEYWORDS.has(tokens[0]?.toLowerCase())) return null;
9161
- let i = 1;
9162
- if (!tokens[i]) return null;
9163
- i++;
9164
- while (tokens[i] && EVENT_CONJUNCTIONS.has(tokens[i].toLowerCase()) && tokens[i + 1]) {
9165
- i += 2;
9166
- }
9167
- if (tokens[i]?.toLowerCase() === "from" && tokens[i + 1]) {
9168
- i++;
9169
- while (tokens[i] && !ENGLISH_COMMANDS.has(tokens[i].toLowerCase()) && !BODY_MODIFIER_KEYWORDS.has(tokens[i].toLowerCase())) {
9170
- i++;
9171
- }
9172
- }
9173
- const modWord = tokens[i]?.toLowerCase();
9174
- if (!modWord || !BODY_MODIFIER_KEYWORDS.has(modWord)) return null;
9175
- const modStart = i;
9176
- let modEnd = i + 1;
9177
- if (modWord !== "async" && modWord !== "once") {
9178
- if (tokens[modEnd]?.toLowerCase() === "at") modEnd++;
9179
- if (tokens[modEnd] && /^\d+(ms|s|m)?$/.test(tokens[modEnd])) modEnd++;
9180
- }
9181
- const modifierPhrase = tokens.slice(modStart, modEnd).join(" ");
9182
- const rebuilt = [...tokens.slice(0, modStart), ...tokens.slice(modEnd)].join(" ");
9183
- if (tokens.length - (modEnd - modStart) <= 2) return null;
9184
- const bodyOut = this.transform(rebuilt);
9185
- return [modifierPhrase, bodyOut].filter((s) => s.length > 0).join(" ");
9186
- }
9187
- /**
9188
- * Transform a `set <stuff> on <scope>` clause (S1 tabs-aria). The trailing
9189
- * `on <scope>` is the element(s) the attribute is set on — kept attached by
9190
- * splitOnCommandBoundaries. The semantic parser captures it as a `scope` role
9191
- * via the passthrough literal `on` (setSchema's scope markerOverride is `on`
9192
- * in every language), so `on` is emitted verbatim and only the scope *value*
9193
- * is translated (selectors pass through; `me`/`it`/`you` translate to the
9194
- * native reference, which the parser also accepts).
9195
- *
9196
- * Positioning matches where the set patterns expect the scope: at the clause
9197
- * end for verb-first orders (SVO/VSO), and immediately before the clause-final
9198
- * verb for SOV (the generated SOV pattern is `{dest} {patient} on {scope}
9199
- * {verb}`). Returns null (fall through) when there is no trailing `on <scope>`.
9200
- *
9201
- * Source is English in the sync-translations pipeline, so the `set` verb and
9202
- * `on` marker are matched as English literals.
9203
- */
9204
- transformSetWithScope(input) {
9205
- const src = this.sourceProfile.code;
9206
- const dst = this.targetProfile.code;
9207
- const m = input.match(/^(.*\bset\b.*\S)\s+on\s+([#.<@[]\S*|me|it|you)\s*$/i);
9208
- if (!m) return null;
9209
- const head = m[1];
9210
- const scopeRaw = m[2];
9211
- const headOut = this.transformSingle(head);
9212
- const scopeT = /^[#.<@[]/.test(scopeRaw) ? scopeRaw : translateWord(scopeRaw, src, dst);
9213
- if (this.targetProfile.wordOrder === "SOV") {
9214
- const verb = translateWord("set", "en", dst);
9215
- const firstTok = input.trim().split(/\s+/)[0]?.toLowerCase();
9216
- const isEventHandler = !!firstTok && EVENT_KEYWORDS.has(firstTok);
9217
- const toks = headOut.split(/\s+/).filter(Boolean);
9218
- if (!isEventHandler) {
9219
- const vIdx = toks.indexOf(verb);
9220
- if (vIdx >= 0) {
9221
- toks.splice(vIdx, 1);
9222
- toks.push("on", scopeT, verb);
9223
- return toks.join(" ");
9224
- }
9225
- } else if (toks.length > 0 && toks[toks.length - 1] === verb) {
9226
- toks.splice(toks.length - 1, 0, "on", scopeT);
9227
- return toks.join(" ");
9228
- }
9229
- return `${headOut} on ${scopeT}`;
9230
- }
9231
- return `${headOut} on ${scopeT}`;
9232
- }
9233
- /**
9234
- * Transform a self-contained block command (`{head} {clause?} {body} {end}`),
9235
- * where head ∈ {if, repeat, unless, …}. The clause (condition / `until event …`)
9236
- * runs up to the first command verb and is translated word-by-word; the body is
9237
- * recursively transformed (so its inner commands reorder for the target); the
9238
- * head/tail keywords are translated. The block is never word-order reordered as
9239
- * a whole — delimiters stay at the edges regardless of target word order.
9240
- */
9241
- transformBlockBody(blockTokens) {
9242
- const src = this.sourceProfile.code;
9243
- const dst = this.targetProfile.code;
9244
- const head = blockTokens[0];
9245
- const hasEnd = blockTokens[blockTokens.length - 1]?.toLowerCase() === "end";
9246
- const tail = hasEnd ? blockTokens[blockTokens.length - 1] : "";
9247
- const inner = blockTokens.slice(1, hasEnd ? -1 : void 0);
9248
- const commands = getCommandKeywordsForLocale(src);
9249
- const copulas = getCopulasForLocale(src);
9250
- let bodyStart = inner.findIndex(
9251
- (t, i) => commands.has(t.toLowerCase()) && !isPredicateAdjectivePosition(inner, i, copulas)
9252
- );
9253
- if (bodyStart < 0) bodyStart = inner.length;
9254
- const clause = inner.slice(0, bodyStart).join(" ");
9255
- const bodyTokens = inner.slice(bodyStart);
9256
- const headT = translateWord(head, src, dst);
9257
- const tailT = tail ? translateWord(tail, src, dst) : "";
9258
- const clauseT = clause ? translateMultiWordValue(clause, src, dst) : "";
9259
- const bodyT = this.transformConditionalBody(bodyTokens);
9260
- const POSITIONAL_BRANCH_HEADS = /* @__PURE__ */ new Set(["first", "last", "next", "previous", "closest"]);
9261
- const thenT = this.targetProfile.wordOrder === "SOV" && clauseT && POSITIONAL_BRANCH_HEADS.has(bodyTokens[1]?.toLowerCase()) && inner[bodyStart - 1]?.toLowerCase() !== "then" ? translateWord("then", src, dst) : "";
9262
- return [headT, clauseT, thenT, bodyT, tailT].filter((s) => s.length > 0).join(" ");
9263
- }
9264
- /**
9265
- * Transform an `if`/`unless` block body, splitting it at a top-level `else` into
9266
- * a then-branch and an else-branch so each is reordered as a self-contained unit
9267
- * and the `else` keyword itself is translated. Without this, the body is reordered
9268
- * as one stream: `else` rides along glued to the preceding clause (and, when that
9269
- * clause begins with a selector, is marked a selector and left *untranslated*),
9270
- * and a spurious `then` is inserted around it — both of which break the target
9271
- * text and the downstream parse. The split is depth-aware so an `else` belonging
9272
- * to a nested block is not mistaken for this block's separator. Bodies without an
9273
- * `else` transform exactly as before.
9274
- */
9275
- transformConditionalBody(bodyTokens) {
9276
- const src = this.sourceProfile.code;
9277
- const dst = this.targetProfile.code;
9278
- const sourceElse = translateWord("else", "en", src).toLowerCase();
9279
- let depth = 0;
9280
- let elseIdx = -1;
9281
- for (let i = 0; i < bodyTokens.length; i++) {
9282
- const t = bodyTokens[i].toLowerCase();
9283
- if (BLOCK_BODY_KEYWORDS.has(t)) depth++;
9284
- else if (t === "end" && depth > 0) depth--;
9285
- else if (t === sourceElse && depth === 0) {
9286
- elseIdx = i;
9287
- break;
9288
- }
9289
- }
9290
- if (elseIdx === -1) {
9291
- const body = bodyTokens.join(" ");
9292
- return body ? this.transform(body) : "";
9293
- }
9294
- const thenBranch = bodyTokens.slice(0, elseIdx).join(" ");
9295
- const elseBranch = bodyTokens.slice(elseIdx + 1).join(" ");
9296
- const elseT = translateWord(bodyTokens[elseIdx], src, dst);
9297
- return [
9298
- thenBranch ? this.transform(thenBranch) : "",
9299
- elseT,
9300
- elseBranch ? this.transform(elseBranch) : ""
9301
- ].filter((s) => s.length > 0).join(" ");
9302
- }
9303
- /**
9304
- * Translate a reactive block by translating the head/tail/connector
9305
- * via the dictionary, recursively transforming the body through the
9306
- * regular pipeline, and rejoining in source-language position order.
9307
- * Block-syntactic tokens are never reordered: they're delimiters, not
9308
- * arguments, and authors expect them at start/end positions
9309
- * regardless of target word order.
9310
- */
9311
- transformBlock(block) {
9312
- const src = this.sourceProfile.code;
9313
- const dst = this.targetProfile.code;
9314
- const head = translateWord(block.headKeyword, src, dst);
9315
- const tail = block.tailKeyword ? translateWord(block.tailKeyword, src, dst) : "";
9316
- const connector = block.connector ? translateWord(block.connector, src, dst) : "";
9317
- const prefix = block.prefixExpr ? translateMultiWordValue(block.prefixExpr, src, dst) : "";
9318
- const body = this.transform(block.body);
9319
- return [head, prefix, connector, body, tail].filter((s) => s.length > 0).join(" ");
9320
- }
9321
- /**
9322
- * Find the best matching rule for this statement
9323
- */
9324
- findRule(parsed) {
9325
- if (!this.targetProfile.rules) return void 0;
9326
- const matchingRules = this.targetProfile.rules.filter((rule) => this.matchesRule(parsed, rule)).sort((a, b) => b.priority - a.priority);
9327
- return matchingRules[0];
9328
- }
9329
- /**
9330
- * Check if a parsed statement matches a rule
9331
- */
9332
- matchesRule(parsed, rule) {
9333
- const { match } = rule;
9334
- for (const role of match.requiredRoles) {
9335
- if (!parsed.roles.has(role)) {
9336
- return false;
9337
- }
9338
- }
9339
- if (match.commands && match.commands.length > 0) {
9340
- const action = parsed.roles.get("action");
9341
- if (!action) return false;
9342
- const actionValue = action.value.toLowerCase();
9343
- if (!match.commands.some((cmd) => cmd.toLowerCase() === actionValue)) {
9344
- return false;
9345
- }
9346
- }
9347
- if (match.predicate && !match.predicate(parsed)) {
9348
- return false;
9349
- }
9350
- return true;
9351
- }
9352
- };
9353
- function toLocale(input, targetLocale) {
9354
- const transformer = new GrammarTransformer("en", targetLocale);
9355
- return transformer.transform(input);
9356
- }
9357
- function toEnglish(input, sourceLocale) {
9358
- const transformer = new GrammarTransformer(sourceLocale, "en");
9359
- return transformer.transform(input);
9360
- }
9361
- function translate(input, sourceLocale, targetLocale) {
9362
- if (sourceLocale === targetLocale) return input;
9363
- if (sourceLocale === "en") return toLocale(input, targetLocale);
9364
- if (targetLocale === "en") return toEnglish(input, sourceLocale);
9365
- if (hasDirectMapping(sourceLocale, targetLocale)) {
9366
- return translateDirect(input, sourceLocale, targetLocale);
9367
- }
9368
- const english = toEnglish(input, sourceLocale);
9369
- return toLocale(english, targetLocale);
9370
- }
9371
- function translateDirect(input, sourceLocale, targetLocale) {
9372
- const mapping = getDirectMapping(sourceLocale, targetLocale);
9373
- if (!mapping) {
9374
- return toLocale(toEnglish(input, sourceLocale), targetLocale);
9375
- }
9376
- const tokens = input.split(/\s+/);
9377
- const translated = tokens.map((token) => {
9378
- if (token.startsWith("#") || token.startsWith(".") || token.startsWith("@")) {
9379
- return token;
9380
- }
9381
- if (token.startsWith('"') || token.startsWith("'")) {
9382
- return token;
9383
- }
9384
- const directTranslation = mapping.words[token];
9385
- if (directTranslation) {
9386
- return directTranslation;
9387
- }
9388
- const suffixMatch = token.match(/^(.+?)(-.+)$/);
9389
- if (suffixMatch) {
9390
- const [, base, suffix] = suffixMatch;
9391
- const translatedBase = mapping.words[base] || base;
9392
- return translatedBase + suffix;
9393
- }
9394
- return token;
9395
- });
9396
- return translated.join(" ");
9397
- }
9398
- var examples = {
9399
- english: {
9400
- eventHandler: "on click increment #count",
9401
- putInto: "put my value into #output",
9402
- toggle: "toggle .active",
9403
- wait: "wait 2 seconds"
9404
- },
9405
- // Expected outputs (approximate, for reference)
9406
- japanese: {
9407
- eventHandler: "#count \u3092 \u30AF\u30EA\u30C3\u30AF \u3067 \u5897\u52A0",
9408
- putInto: "\u79C1\u306E \u5024 \u3092 #output \u306B \u7F6E\u304F",
9409
- toggle: ".active \u3092 \u5207\u308A\u66FF\u3048",
9410
- wait: "2\u79D2 \u5F85\u3064"
9411
- },
9412
- chinese: {
9413
- eventHandler: "\u5F53 \u70B9\u51FB \u65F6 \u589E\u52A0 #count",
9414
- putInto: "\u628A \u6211\u7684\u503C \u653E \u5230 #output",
9415
- toggle: "\u5207\u6362 .active",
9416
- wait: "\u7B49\u5F85 2\u79D2"
9417
- },
9418
- arabic: {
9419
- eventHandler: "\u0632\u0650\u062F #count \u0639\u0646\u062F \u0627\u0644\u0646\u0642\u0631",
9420
- putInto: "\u0636\u0639 \u0642\u064A\u0645\u062A\u064A \u0641\u064A #output",
9421
- toggle: "\u0628\u062F\u0651\u0644 .active",
9422
- wait: "\u0627\u0646\u062A\u0638\u0631 \u062B\u0627\u0646\u064A\u062A\u064A\u0646"
9423
- }
9424
- };
9425
-
9426
- export { ENGLISH_COMMANDS, ENGLISH_KEYWORDS, GrammarTransformer, LANGUAGE_FAMILY_DEFAULTS, LocaleManager, UNIVERSAL_ENGLISH_KEYWORDS, UNIVERSAL_PATTERNS, ar, ar as arDictionary, arKeywords, arabicProfile, bn, bn as bnDictionary, bnKeywords, chineseProfile, createEnglishProvider, createKeywordProvider, de, de as deDictionary, deKeywords, detectBrowserLocale, directMappings, en, englishProfile, es, es as esDictionary, esKeywords, fr, fr as frDictionary, frKeywords, frenchProfile, germanProfile, getDirectMapping, getProfile, getSupportedDirectPairs, getSupportedLocales, examples as grammarExamples, hasDirectMapping, he, he as heDictionary, heKeywords, hebrewProfile, hindiDictionary as hiDictionary, hiKeywords, hindiDictionary, id, id as idDictionary, idKeywords, indonesianProfile, insertMarkers, it, it as itDictionary, itKeywords, ja, ja as jaDictionary, jaKeywords, japaneseProfile, joinTokens, ko, ko as koDictionary, koKeywords, koreanProfile, malayProfile, ms, ms as msDictionary, msKeywords, parseStatement, pl, pl as plDictionary, plKeywords, portugueseProfile, profiles, pt, pt as ptDictionary, ptKeywords, qu, qu as quDictionary, quKeywords, quechuaProfile, reorderRoles, russianDictionary as ruDictionary, ruKeywords, russianDictionary, spanishProfile, sw, sw as swDictionary, swKeywords, swahiliProfile, th, th as thDictionary, thKeywords, tl, tl as tlDictionary, tlKeywords, toEnglish, toLocale, tr, tr as trDictionary, trKeywords, transformStatement, translate, translateWordDirect, turkishProfile, ukrainianDictionary as ukDictionary, ukKeywords, ukrainianDictionary, vi, vi as viDictionary, viKeywords, zh, zh as zhDictionary, zhKeywords };
7747
+ export { ENGLISH_COMMANDS, ENGLISH_KEYWORDS, LANGUAGE_FAMILY_DEFAULTS, LocaleManager, UNIVERSAL_ENGLISH_KEYWORDS, UNIVERSAL_PATTERNS, ar, ar as arDictionary, arKeywords, arabicProfile, bn, bn as bnDictionary, bnKeywords, chineseProfile, createEnglishProvider, createKeywordProvider, de, de as deDictionary, deKeywords, detectBrowserLocale, directMappings, en, englishProfile, es, es as esDictionary, esKeywords, fr, fr as frDictionary, frKeywords, frenchProfile, germanProfile, getDirectMapping, getProfile, getSupportedDirectPairs, getSupportedLocales, hasDirectMapping, he, he as heDictionary, heKeywords, hebrewProfile, hindiDictionary as hiDictionary, hiKeywords, hindiDictionary, id, id as idDictionary, idKeywords, indonesianProfile, insertMarkers, it, it as itDictionary, itKeywords, ja, ja as jaDictionary, jaKeywords, japaneseProfile, joinTokens, ko, ko as koDictionary, koKeywords, koreanProfile, malayProfile, ms, ms as msDictionary, msKeywords, pl, pl as plDictionary, plKeywords, portugueseProfile, profiles, pt, pt as ptDictionary, ptKeywords, qu, qu as quDictionary, quKeywords, quechuaProfile, reorderRoles, russianDictionary as ruDictionary, ruKeywords, russianDictionary, spanishProfile, sw, sw as swDictionary, swKeywords, swahiliProfile, th, th as thDictionary, thKeywords, tl, tl as tlDictionary, tlKeywords, tr, tr as trDictionary, trKeywords, transformStatement, translateWordDirect, turkishProfile, ukrainianDictionary as ukDictionary, ukKeywords, ukrainianDictionary, vi, vi as viDictionary, viKeywords, zh, zh as zhDictionary, zhKeywords };
9427
7748
  //# sourceMappingURL=browser.js.map
9428
7749
  //# sourceMappingURL=browser.js.map