message-compiler.global.js 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558
  1. /*!
  2. * message-compiler v11.1.3
  3. * (c) 2025 kazuya kawaguchi
  4. * Released under the MIT License.
  5. */
  6. var IntlifyMessageCompiler = (function (exports) {
  7. 'use strict';
  8. const LOCATION_STUB = {
  9. start: { line: 1, column: 1, offset: 0 },
  10. end: { line: 1, column: 1, offset: 0 }
  11. };
  12. function createPosition(line, column, offset) {
  13. return { line, column, offset };
  14. }
  15. function createLocation(start, end, source) {
  16. const loc = { start, end };
  17. if (source != null) {
  18. loc.source = source;
  19. }
  20. return loc;
  21. }
  22. /**
  23. * Original Utilities
  24. * written by kazuya kawaguchi
  25. */
  26. const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g;
  27. /* eslint-disable */
  28. function format(message, ...args) {
  29. if (args.length === 1 && isObject(args[0])) {
  30. args = args[0];
  31. }
  32. if (!args || !args.hasOwnProperty) {
  33. args = {};
  34. }
  35. return message.replace(RE_ARGS, (match, identifier) => {
  36. return args.hasOwnProperty(identifier) ? args[identifier] : '';
  37. });
  38. }
  39. const assign = Object.assign;
  40. const isString = (val) => typeof val === 'string';
  41. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  42. const isObject = (val) => val !== null && typeof val === 'object';
  43. function join(items, separator = '') {
  44. return items.reduce((str, item, index) => (index === 0 ? str + item : str + separator + item), '');
  45. }
  46. const CompileErrorCodes = {
  47. // tokenizer error codes
  48. EXPECTED_TOKEN: 1,
  49. INVALID_TOKEN_IN_PLACEHOLDER: 2,
  50. UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER: 3,
  51. UNKNOWN_ESCAPE_SEQUENCE: 4,
  52. INVALID_UNICODE_ESCAPE_SEQUENCE: 5,
  53. UNBALANCED_CLOSING_BRACE: 6,
  54. UNTERMINATED_CLOSING_BRACE: 7,
  55. EMPTY_PLACEHOLDER: 8,
  56. NOT_ALLOW_NEST_PLACEHOLDER: 9,
  57. INVALID_LINKED_FORMAT: 10,
  58. // parser error codes
  59. MUST_HAVE_MESSAGES_IN_PLURAL: 11,
  60. UNEXPECTED_EMPTY_LINKED_MODIFIER: 12,
  61. UNEXPECTED_EMPTY_LINKED_KEY: 13,
  62. UNEXPECTED_LEXICAL_ANALYSIS: 14,
  63. // generator error codes
  64. UNHANDLED_CODEGEN_NODE_TYPE: 15,
  65. // minifier error codes
  66. UNHANDLED_MINIFIER_NODE_TYPE: 16
  67. };
  68. // Special value for higher-order compilers to pick up the last code
  69. // to avoid collision of error codes.
  70. // This should always be kept as the last item.
  71. const COMPILE_ERROR_CODES_EXTEND_POINT = 17;
  72. /** @internal */
  73. const errorMessages = {
  74. // tokenizer error messages
  75. [CompileErrorCodes.EXPECTED_TOKEN]: `Expected token: '{0}'`,
  76. [CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER]: `Invalid token in placeholder: '{0}'`,
  77. [CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]: `Unterminated single quote in placeholder`,
  78. [CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE]: `Unknown escape sequence: \\{0}`,
  79. [CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE]: `Invalid unicode escape sequence: {0}`,
  80. [CompileErrorCodes.UNBALANCED_CLOSING_BRACE]: `Unbalanced closing brace`,
  81. [CompileErrorCodes.UNTERMINATED_CLOSING_BRACE]: `Unterminated closing brace`,
  82. [CompileErrorCodes.EMPTY_PLACEHOLDER]: `Empty placeholder`,
  83. [CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER]: `Not allowed nest placeholder`,
  84. [CompileErrorCodes.INVALID_LINKED_FORMAT]: `Invalid linked format`,
  85. // parser error messages
  86. [CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL]: `Plural must have messages`,
  87. [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER]: `Unexpected empty linked modifier`,
  88. [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY]: `Unexpected empty linked key`,
  89. [CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS]: `Unexpected lexical analysis in token: '{0}'`,
  90. // generator error messages
  91. [CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE]: `unhandled codegen node type: '{0}'`,
  92. // minimizer error messages
  93. [CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE]: `unhandled mimifier node type: '{0}'`
  94. };
  95. function createCompileError(code, loc, options = {}) {
  96. const { domain, messages, args } = options;
  97. const msg = format((messages || errorMessages)[code] || '', ...(args || []))
  98. ;
  99. const error = new SyntaxError(String(msg));
  100. error.code = code;
  101. if (loc) {
  102. error.location = loc;
  103. }
  104. error.domain = domain;
  105. return error;
  106. }
  107. /** @internal */
  108. function defaultOnError(error) {
  109. throw error;
  110. }
  111. // eslint-disable-next-line no-useless-escape
  112. const RE_HTML_TAG = /<\/?[\w\s="/.':;#-\/]+>/;
  113. const detectHtmlTag = (source) => RE_HTML_TAG.test(source);
  114. const CHAR_SP = ' ';
  115. const CHAR_CR = '\r';
  116. const CHAR_LF = '\n';
  117. const CHAR_LS = String.fromCharCode(0x2028);
  118. const CHAR_PS = String.fromCharCode(0x2029);
  119. function createScanner(str) {
  120. const _buf = str;
  121. let _index = 0;
  122. let _line = 1;
  123. let _column = 1;
  124. let _peekOffset = 0;
  125. const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF;
  126. const isLF = (index) => _buf[index] === CHAR_LF;
  127. const isPS = (index) => _buf[index] === CHAR_PS;
  128. const isLS = (index) => _buf[index] === CHAR_LS;
  129. const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index);
  130. const index = () => _index;
  131. const line = () => _line;
  132. const column = () => _column;
  133. const peekOffset = () => _peekOffset;
  134. const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset];
  135. const currentChar = () => charAt(_index);
  136. const currentPeek = () => charAt(_index + _peekOffset);
  137. function next() {
  138. _peekOffset = 0;
  139. if (isLineEnd(_index)) {
  140. _line++;
  141. _column = 0;
  142. }
  143. if (isCRLF(_index)) {
  144. _index++;
  145. }
  146. _index++;
  147. _column++;
  148. return _buf[_index];
  149. }
  150. function peek() {
  151. if (isCRLF(_index + _peekOffset)) {
  152. _peekOffset++;
  153. }
  154. _peekOffset++;
  155. return _buf[_index + _peekOffset];
  156. }
  157. function reset() {
  158. _index = 0;
  159. _line = 1;
  160. _column = 1;
  161. _peekOffset = 0;
  162. }
  163. function resetPeek(offset = 0) {
  164. _peekOffset = offset;
  165. }
  166. function skipToPeek() {
  167. const target = _index + _peekOffset;
  168. while (target !== _index) {
  169. next();
  170. }
  171. _peekOffset = 0;
  172. }
  173. return {
  174. index,
  175. line,
  176. column,
  177. peekOffset,
  178. charAt,
  179. currentChar,
  180. currentPeek,
  181. next,
  182. peek,
  183. reset,
  184. resetPeek,
  185. skipToPeek
  186. };
  187. }
  188. const EOF = undefined;
  189. const DOT = '.';
  190. const LITERAL_DELIMITER = "'";
  191. const ERROR_DOMAIN$3 = 'tokenizer';
  192. function createTokenizer(source, options = {}) {
  193. const location = options.location !== false;
  194. const _scnr = createScanner(source);
  195. const currentOffset = () => _scnr.index();
  196. const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index());
  197. const _initLoc = currentPosition();
  198. const _initOffset = currentOffset();
  199. const _context = {
  200. currentType: 13 /* TokenTypes.EOF */,
  201. offset: _initOffset,
  202. startLoc: _initLoc,
  203. endLoc: _initLoc,
  204. lastType: 13 /* TokenTypes.EOF */,
  205. lastOffset: _initOffset,
  206. lastStartLoc: _initLoc,
  207. lastEndLoc: _initLoc,
  208. braceNest: 0,
  209. inLinked: false,
  210. text: ''
  211. };
  212. const context = () => _context;
  213. const { onError } = options;
  214. function emitError(code, pos, offset, ...args) {
  215. const ctx = context();
  216. pos.column += offset;
  217. pos.offset += offset;
  218. if (onError) {
  219. const loc = location ? createLocation(ctx.startLoc, pos) : null;
  220. const err = createCompileError(code, loc, {
  221. domain: ERROR_DOMAIN$3,
  222. args
  223. });
  224. onError(err);
  225. }
  226. }
  227. function getToken(context, type, value) {
  228. context.endLoc = currentPosition();
  229. context.currentType = type;
  230. const token = { type };
  231. if (location) {
  232. token.loc = createLocation(context.startLoc, context.endLoc);
  233. }
  234. if (value != null) {
  235. token.value = value;
  236. }
  237. return token;
  238. }
  239. const getEndToken = (context) => getToken(context, 13 /* TokenTypes.EOF */);
  240. function eat(scnr, ch) {
  241. if (scnr.currentChar() === ch) {
  242. scnr.next();
  243. return ch;
  244. }
  245. else {
  246. emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
  247. return '';
  248. }
  249. }
  250. function peekSpaces(scnr) {
  251. let buf = '';
  252. while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) {
  253. buf += scnr.currentPeek();
  254. scnr.peek();
  255. }
  256. return buf;
  257. }
  258. function skipSpaces(scnr) {
  259. const buf = peekSpaces(scnr);
  260. scnr.skipToPeek();
  261. return buf;
  262. }
  263. function isIdentifierStart(ch) {
  264. if (ch === EOF) {
  265. return false;
  266. }
  267. const cc = ch.charCodeAt(0);
  268. return ((cc >= 97 && cc <= 122) || // a-z
  269. (cc >= 65 && cc <= 90) || // A-Z
  270. cc === 95 // _
  271. );
  272. }
  273. function isNumberStart(ch) {
  274. if (ch === EOF) {
  275. return false;
  276. }
  277. const cc = ch.charCodeAt(0);
  278. return cc >= 48 && cc <= 57; // 0-9
  279. }
  280. function isNamedIdentifierStart(scnr, context) {
  281. const { currentType } = context;
  282. if (currentType !== 2 /* TokenTypes.BraceLeft */) {
  283. return false;
  284. }
  285. peekSpaces(scnr);
  286. const ret = isIdentifierStart(scnr.currentPeek());
  287. scnr.resetPeek();
  288. return ret;
  289. }
  290. function isListIdentifierStart(scnr, context) {
  291. const { currentType } = context;
  292. if (currentType !== 2 /* TokenTypes.BraceLeft */) {
  293. return false;
  294. }
  295. peekSpaces(scnr);
  296. const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek();
  297. const ret = isNumberStart(ch);
  298. scnr.resetPeek();
  299. return ret;
  300. }
  301. function isLiteralStart(scnr, context) {
  302. const { currentType } = context;
  303. if (currentType !== 2 /* TokenTypes.BraceLeft */) {
  304. return false;
  305. }
  306. peekSpaces(scnr);
  307. const ret = scnr.currentPeek() === LITERAL_DELIMITER;
  308. scnr.resetPeek();
  309. return ret;
  310. }
  311. function isLinkedDotStart(scnr, context) {
  312. const { currentType } = context;
  313. if (currentType !== 7 /* TokenTypes.LinkedAlias */) {
  314. return false;
  315. }
  316. peekSpaces(scnr);
  317. const ret = scnr.currentPeek() === "." /* TokenChars.LinkedDot */;
  318. scnr.resetPeek();
  319. return ret;
  320. }
  321. function isLinkedModifierStart(scnr, context) {
  322. const { currentType } = context;
  323. if (currentType !== 8 /* TokenTypes.LinkedDot */) {
  324. return false;
  325. }
  326. peekSpaces(scnr);
  327. const ret = isIdentifierStart(scnr.currentPeek());
  328. scnr.resetPeek();
  329. return ret;
  330. }
  331. function isLinkedDelimiterStart(scnr, context) {
  332. const { currentType } = context;
  333. if (!(currentType === 7 /* TokenTypes.LinkedAlias */ ||
  334. currentType === 11 /* TokenTypes.LinkedModifier */)) {
  335. return false;
  336. }
  337. peekSpaces(scnr);
  338. const ret = scnr.currentPeek() === ":" /* TokenChars.LinkedDelimiter */;
  339. scnr.resetPeek();
  340. return ret;
  341. }
  342. function isLinkedReferStart(scnr, context) {
  343. const { currentType } = context;
  344. if (currentType !== 9 /* TokenTypes.LinkedDelimiter */) {
  345. return false;
  346. }
  347. const fn = () => {
  348. const ch = scnr.currentPeek();
  349. if (ch === "{" /* TokenChars.BraceLeft */) {
  350. return isIdentifierStart(scnr.peek());
  351. }
  352. else if (ch === "@" /* TokenChars.LinkedAlias */ ||
  353. ch === "|" /* TokenChars.Pipe */ ||
  354. ch === ":" /* TokenChars.LinkedDelimiter */ ||
  355. ch === "." /* TokenChars.LinkedDot */ ||
  356. ch === CHAR_SP ||
  357. !ch) {
  358. return false;
  359. }
  360. else if (ch === CHAR_LF) {
  361. scnr.peek();
  362. return fn();
  363. }
  364. else {
  365. // other characters
  366. return isTextStart(scnr, false);
  367. }
  368. };
  369. const ret = fn();
  370. scnr.resetPeek();
  371. return ret;
  372. }
  373. function isPluralStart(scnr) {
  374. peekSpaces(scnr);
  375. const ret = scnr.currentPeek() === "|" /* TokenChars.Pipe */;
  376. scnr.resetPeek();
  377. return ret;
  378. }
  379. function isTextStart(scnr, reset = true) {
  380. const fn = (hasSpace = false, prev = '') => {
  381. const ch = scnr.currentPeek();
  382. if (ch === "{" /* TokenChars.BraceLeft */) {
  383. return hasSpace;
  384. }
  385. else if (ch === "@" /* TokenChars.LinkedAlias */ || !ch) {
  386. return hasSpace;
  387. }
  388. else if (ch === "|" /* TokenChars.Pipe */) {
  389. return !(prev === CHAR_SP || prev === CHAR_LF);
  390. }
  391. else if (ch === CHAR_SP) {
  392. scnr.peek();
  393. return fn(true, CHAR_SP);
  394. }
  395. else if (ch === CHAR_LF) {
  396. scnr.peek();
  397. return fn(true, CHAR_LF);
  398. }
  399. else {
  400. return true;
  401. }
  402. };
  403. const ret = fn();
  404. reset && scnr.resetPeek();
  405. return ret;
  406. }
  407. function takeChar(scnr, fn) {
  408. const ch = scnr.currentChar();
  409. if (ch === EOF) {
  410. return EOF;
  411. }
  412. if (fn(ch)) {
  413. scnr.next();
  414. return ch;
  415. }
  416. return null;
  417. }
  418. function isIdentifier(ch) {
  419. const cc = ch.charCodeAt(0);
  420. return ((cc >= 97 && cc <= 122) || // a-z
  421. (cc >= 65 && cc <= 90) || // A-Z
  422. (cc >= 48 && cc <= 57) || // 0-9
  423. cc === 95 || // _
  424. cc === 36 // $
  425. );
  426. }
  427. function takeIdentifierChar(scnr) {
  428. return takeChar(scnr, isIdentifier);
  429. }
  430. function isNamedIdentifier(ch) {
  431. const cc = ch.charCodeAt(0);
  432. return ((cc >= 97 && cc <= 122) || // a-z
  433. (cc >= 65 && cc <= 90) || // A-Z
  434. (cc >= 48 && cc <= 57) || // 0-9
  435. cc === 95 || // _
  436. cc === 36 || // $
  437. cc === 45 // -
  438. );
  439. }
  440. function takeNamedIdentifierChar(scnr) {
  441. return takeChar(scnr, isNamedIdentifier);
  442. }
  443. function isDigit(ch) {
  444. const cc = ch.charCodeAt(0);
  445. return cc >= 48 && cc <= 57; // 0-9
  446. }
  447. function takeDigit(scnr) {
  448. return takeChar(scnr, isDigit);
  449. }
  450. function isHexDigit(ch) {
  451. const cc = ch.charCodeAt(0);
  452. return ((cc >= 48 && cc <= 57) || // 0-9
  453. (cc >= 65 && cc <= 70) || // A-F
  454. (cc >= 97 && cc <= 102)); // a-f
  455. }
  456. function takeHexDigit(scnr) {
  457. return takeChar(scnr, isHexDigit);
  458. }
  459. function getDigits(scnr) {
  460. let ch = '';
  461. let num = '';
  462. while ((ch = takeDigit(scnr))) {
  463. num += ch;
  464. }
  465. return num;
  466. }
  467. function readText(scnr) {
  468. let buf = '';
  469. while (true) {
  470. const ch = scnr.currentChar();
  471. if (ch === "{" /* TokenChars.BraceLeft */ ||
  472. ch === "}" /* TokenChars.BraceRight */ ||
  473. ch === "@" /* TokenChars.LinkedAlias */ ||
  474. ch === "|" /* TokenChars.Pipe */ ||
  475. !ch) {
  476. break;
  477. }
  478. else if (ch === CHAR_SP || ch === CHAR_LF) {
  479. if (isTextStart(scnr)) {
  480. buf += ch;
  481. scnr.next();
  482. }
  483. else if (isPluralStart(scnr)) {
  484. break;
  485. }
  486. else {
  487. buf += ch;
  488. scnr.next();
  489. }
  490. }
  491. else {
  492. buf += ch;
  493. scnr.next();
  494. }
  495. }
  496. return buf;
  497. }
  498. function readNamedIdentifier(scnr) {
  499. skipSpaces(scnr);
  500. let ch = '';
  501. let name = '';
  502. while ((ch = takeNamedIdentifierChar(scnr))) {
  503. name += ch;
  504. }
  505. if (scnr.currentChar() === EOF) {
  506. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  507. }
  508. return name;
  509. }
  510. function readListIdentifier(scnr) {
  511. skipSpaces(scnr);
  512. let value = '';
  513. if (scnr.currentChar() === '-') {
  514. scnr.next();
  515. value += `-${getDigits(scnr)}`;
  516. }
  517. else {
  518. value += getDigits(scnr);
  519. }
  520. if (scnr.currentChar() === EOF) {
  521. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  522. }
  523. return value;
  524. }
  525. function isLiteral(ch) {
  526. return ch !== LITERAL_DELIMITER && ch !== CHAR_LF;
  527. }
  528. function readLiteral(scnr) {
  529. skipSpaces(scnr);
  530. // eslint-disable-next-line no-useless-escape
  531. eat(scnr, `\'`);
  532. let ch = '';
  533. let literal = '';
  534. while ((ch = takeChar(scnr, isLiteral))) {
  535. if (ch === '\\') {
  536. literal += readEscapeSequence(scnr);
  537. }
  538. else {
  539. literal += ch;
  540. }
  541. }
  542. const current = scnr.currentChar();
  543. if (current === CHAR_LF || current === EOF) {
  544. emitError(CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER, currentPosition(), 0);
  545. // TODO: Is it correct really?
  546. if (current === CHAR_LF) {
  547. scnr.next();
  548. // eslint-disable-next-line no-useless-escape
  549. eat(scnr, `\'`);
  550. }
  551. return literal;
  552. }
  553. // eslint-disable-next-line no-useless-escape
  554. eat(scnr, `\'`);
  555. return literal;
  556. }
  557. function readEscapeSequence(scnr) {
  558. const ch = scnr.currentChar();
  559. switch (ch) {
  560. case '\\':
  561. case `\'`: // eslint-disable-line no-useless-escape
  562. scnr.next();
  563. return `\\${ch}`;
  564. case 'u':
  565. return readUnicodeEscapeSequence(scnr, ch, 4);
  566. case 'U':
  567. return readUnicodeEscapeSequence(scnr, ch, 6);
  568. default:
  569. emitError(CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE, currentPosition(), 0, ch);
  570. return '';
  571. }
  572. }
  573. function readUnicodeEscapeSequence(scnr, unicode, digits) {
  574. eat(scnr, unicode);
  575. let sequence = '';
  576. for (let i = 0; i < digits; i++) {
  577. const ch = takeHexDigit(scnr);
  578. if (!ch) {
  579. emitError(CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`);
  580. break;
  581. }
  582. sequence += ch;
  583. }
  584. return `\\${unicode}${sequence}`;
  585. }
  586. function isInvalidIdentifier(ch) {
  587. return (ch !== "{" /* TokenChars.BraceLeft */ &&
  588. ch !== "}" /* TokenChars.BraceRight */ &&
  589. ch !== CHAR_SP &&
  590. ch !== CHAR_LF);
  591. }
  592. function readInvalidIdentifier(scnr) {
  593. skipSpaces(scnr);
  594. let ch = '';
  595. let identifiers = '';
  596. while ((ch = takeChar(scnr, isInvalidIdentifier))) {
  597. identifiers += ch;
  598. }
  599. return identifiers;
  600. }
  601. function readLinkedModifier(scnr) {
  602. let ch = '';
  603. let name = '';
  604. while ((ch = takeIdentifierChar(scnr))) {
  605. name += ch;
  606. }
  607. return name;
  608. }
  609. function readLinkedRefer(scnr) {
  610. const fn = (buf) => {
  611. const ch = scnr.currentChar();
  612. if (ch === "{" /* TokenChars.BraceLeft */ ||
  613. ch === "@" /* TokenChars.LinkedAlias */ ||
  614. ch === "|" /* TokenChars.Pipe */ ||
  615. ch === "(" /* TokenChars.ParenLeft */ ||
  616. ch === ")" /* TokenChars.ParenRight */ ||
  617. !ch) {
  618. return buf;
  619. }
  620. else if (ch === CHAR_SP) {
  621. return buf;
  622. }
  623. else if (ch === CHAR_LF || ch === DOT) {
  624. buf += ch;
  625. scnr.next();
  626. return fn(buf);
  627. }
  628. else {
  629. buf += ch;
  630. scnr.next();
  631. return fn(buf);
  632. }
  633. };
  634. return fn('');
  635. }
  636. function readPlural(scnr) {
  637. skipSpaces(scnr);
  638. const plural = eat(scnr, "|" /* TokenChars.Pipe */);
  639. skipSpaces(scnr);
  640. return plural;
  641. }
  642. // TODO: We need refactoring of token parsing ...
  643. function readTokenInPlaceholder(scnr, context) {
  644. let token = null;
  645. const ch = scnr.currentChar();
  646. switch (ch) {
  647. case "{" /* TokenChars.BraceLeft */:
  648. if (context.braceNest >= 1) {
  649. emitError(CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER, currentPosition(), 0);
  650. }
  651. scnr.next();
  652. token = getToken(context, 2 /* TokenTypes.BraceLeft */, "{" /* TokenChars.BraceLeft */);
  653. skipSpaces(scnr);
  654. context.braceNest++;
  655. return token;
  656. case "}" /* TokenChars.BraceRight */:
  657. if (context.braceNest > 0 &&
  658. context.currentType === 2 /* TokenTypes.BraceLeft */) {
  659. emitError(CompileErrorCodes.EMPTY_PLACEHOLDER, currentPosition(), 0);
  660. }
  661. scnr.next();
  662. token = getToken(context, 3 /* TokenTypes.BraceRight */, "}" /* TokenChars.BraceRight */);
  663. context.braceNest--;
  664. context.braceNest > 0 && skipSpaces(scnr);
  665. if (context.inLinked && context.braceNest === 0) {
  666. context.inLinked = false;
  667. }
  668. return token;
  669. case "@" /* TokenChars.LinkedAlias */:
  670. if (context.braceNest > 0) {
  671. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  672. }
  673. token = readTokenInLinked(scnr, context) || getEndToken(context);
  674. context.braceNest = 0;
  675. return token;
  676. default: {
  677. let validNamedIdentifier = true;
  678. let validListIdentifier = true;
  679. let validLiteral = true;
  680. if (isPluralStart(scnr)) {
  681. if (context.braceNest > 0) {
  682. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  683. }
  684. token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
  685. // reset
  686. context.braceNest = 0;
  687. context.inLinked = false;
  688. return token;
  689. }
  690. if (context.braceNest > 0 &&
  691. (context.currentType === 4 /* TokenTypes.Named */ ||
  692. context.currentType === 5 /* TokenTypes.List */ ||
  693. context.currentType === 6 /* TokenTypes.Literal */)) {
  694. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  695. context.braceNest = 0;
  696. return readToken(scnr, context);
  697. }
  698. if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) {
  699. token = getToken(context, 4 /* TokenTypes.Named */, readNamedIdentifier(scnr));
  700. skipSpaces(scnr);
  701. return token;
  702. }
  703. if ((validListIdentifier = isListIdentifierStart(scnr, context))) {
  704. token = getToken(context, 5 /* TokenTypes.List */, readListIdentifier(scnr));
  705. skipSpaces(scnr);
  706. return token;
  707. }
  708. if ((validLiteral = isLiteralStart(scnr, context))) {
  709. token = getToken(context, 6 /* TokenTypes.Literal */, readLiteral(scnr));
  710. skipSpaces(scnr);
  711. return token;
  712. }
  713. if (!validNamedIdentifier && !validListIdentifier && !validLiteral) {
  714. // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ...
  715. token = getToken(context, 12 /* TokenTypes.InvalidPlace */, readInvalidIdentifier(scnr));
  716. emitError(CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER, currentPosition(), 0, token.value);
  717. skipSpaces(scnr);
  718. return token;
  719. }
  720. break;
  721. }
  722. }
  723. return token;
  724. }
  725. // TODO: We need refactoring of token parsing ...
  726. function readTokenInLinked(scnr, context) {
  727. const { currentType } = context;
  728. let token = null;
  729. const ch = scnr.currentChar();
  730. if ((currentType === 7 /* TokenTypes.LinkedAlias */ ||
  731. currentType === 8 /* TokenTypes.LinkedDot */ ||
  732. currentType === 11 /* TokenTypes.LinkedModifier */ ||
  733. currentType === 9 /* TokenTypes.LinkedDelimiter */) &&
  734. (ch === CHAR_LF || ch === CHAR_SP)) {
  735. emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
  736. }
  737. switch (ch) {
  738. case "@" /* TokenChars.LinkedAlias */:
  739. scnr.next();
  740. token = getToken(context, 7 /* TokenTypes.LinkedAlias */, "@" /* TokenChars.LinkedAlias */);
  741. context.inLinked = true;
  742. return token;
  743. case "." /* TokenChars.LinkedDot */:
  744. skipSpaces(scnr);
  745. scnr.next();
  746. return getToken(context, 8 /* TokenTypes.LinkedDot */, "." /* TokenChars.LinkedDot */);
  747. case ":" /* TokenChars.LinkedDelimiter */:
  748. skipSpaces(scnr);
  749. scnr.next();
  750. return getToken(context, 9 /* TokenTypes.LinkedDelimiter */, ":" /* TokenChars.LinkedDelimiter */);
  751. default:
  752. if (isPluralStart(scnr)) {
  753. token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
  754. // reset
  755. context.braceNest = 0;
  756. context.inLinked = false;
  757. return token;
  758. }
  759. if (isLinkedDotStart(scnr, context) ||
  760. isLinkedDelimiterStart(scnr, context)) {
  761. skipSpaces(scnr);
  762. return readTokenInLinked(scnr, context);
  763. }
  764. if (isLinkedModifierStart(scnr, context)) {
  765. skipSpaces(scnr);
  766. return getToken(context, 11 /* TokenTypes.LinkedModifier */, readLinkedModifier(scnr));
  767. }
  768. if (isLinkedReferStart(scnr, context)) {
  769. skipSpaces(scnr);
  770. if (ch === "{" /* TokenChars.BraceLeft */) {
  771. // scan the placeholder
  772. return readTokenInPlaceholder(scnr, context) || token;
  773. }
  774. else {
  775. return getToken(context, 10 /* TokenTypes.LinkedKey */, readLinkedRefer(scnr));
  776. }
  777. }
  778. if (currentType === 7 /* TokenTypes.LinkedAlias */) {
  779. emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
  780. }
  781. context.braceNest = 0;
  782. context.inLinked = false;
  783. return readToken(scnr, context);
  784. }
  785. }
  786. // TODO: We need refactoring of token parsing ...
  787. function readToken(scnr, context) {
  788. let token = { type: 13 /* TokenTypes.EOF */ };
  789. if (context.braceNest > 0) {
  790. return readTokenInPlaceholder(scnr, context) || getEndToken(context);
  791. }
  792. if (context.inLinked) {
  793. return readTokenInLinked(scnr, context) || getEndToken(context);
  794. }
  795. const ch = scnr.currentChar();
  796. switch (ch) {
  797. case "{" /* TokenChars.BraceLeft */:
  798. return readTokenInPlaceholder(scnr, context) || getEndToken(context);
  799. case "}" /* TokenChars.BraceRight */:
  800. emitError(CompileErrorCodes.UNBALANCED_CLOSING_BRACE, currentPosition(), 0);
  801. scnr.next();
  802. return getToken(context, 3 /* TokenTypes.BraceRight */, "}" /* TokenChars.BraceRight */);
  803. case "@" /* TokenChars.LinkedAlias */:
  804. return readTokenInLinked(scnr, context) || getEndToken(context);
  805. default: {
  806. if (isPluralStart(scnr)) {
  807. token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
  808. // reset
  809. context.braceNest = 0;
  810. context.inLinked = false;
  811. return token;
  812. }
  813. if (isTextStart(scnr)) {
  814. return getToken(context, 0 /* TokenTypes.Text */, readText(scnr));
  815. }
  816. break;
  817. }
  818. }
  819. return token;
  820. }
  821. function nextToken() {
  822. const { currentType, offset, startLoc, endLoc } = _context;
  823. _context.lastType = currentType;
  824. _context.lastOffset = offset;
  825. _context.lastStartLoc = startLoc;
  826. _context.lastEndLoc = endLoc;
  827. _context.offset = currentOffset();
  828. _context.startLoc = currentPosition();
  829. if (_scnr.currentChar() === EOF) {
  830. return getToken(_context, 13 /* TokenTypes.EOF */);
  831. }
  832. return readToken(_scnr, _context);
  833. }
  834. return {
  835. nextToken,
  836. currentOffset,
  837. currentPosition,
  838. context
  839. };
  840. }
  841. const ERROR_DOMAIN$2 = 'parser';
  842. // Backslash backslash, backslash quote, uHHHH, UHHHHHH.
  843. const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;
  844. function fromEscapeSequence(match, codePoint4, codePoint6) {
  845. switch (match) {
  846. case `\\\\`:
  847. return `\\`;
  848. // eslint-disable-next-line no-useless-escape
  849. case `\\\'`:
  850. // eslint-disable-next-line no-useless-escape
  851. return `\'`;
  852. default: {
  853. const codePoint = parseInt(codePoint4 || codePoint6, 16);
  854. if (codePoint <= 0xd7ff || codePoint >= 0xe000) {
  855. return String.fromCodePoint(codePoint);
  856. }
  857. // invalid ...
  858. // Replace them with U+FFFD REPLACEMENT CHARACTER.
  859. return '�';
  860. }
  861. }
  862. }
  863. function createParser(options = {}) {
  864. const location = options.location !== false;
  865. const { onError } = options;
  866. function emitError(tokenzer, code, start, offset, ...args) {
  867. const end = tokenzer.currentPosition();
  868. end.offset += offset;
  869. end.column += offset;
  870. if (onError) {
  871. const loc = location ? createLocation(start, end) : null;
  872. const err = createCompileError(code, loc, {
  873. domain: ERROR_DOMAIN$2,
  874. args
  875. });
  876. onError(err);
  877. }
  878. }
  879. function startNode(type, offset, loc) {
  880. const node = { type };
  881. if (location) {
  882. node.start = offset;
  883. node.end = offset;
  884. node.loc = { start: loc, end: loc };
  885. }
  886. return node;
  887. }
  888. function endNode(node, offset, pos, type) {
  889. if (location) {
  890. node.end = offset;
  891. if (node.loc) {
  892. node.loc.end = pos;
  893. }
  894. }
  895. }
  896. function parseText(tokenizer, value) {
  897. const context = tokenizer.context();
  898. const node = startNode(3 /* NodeTypes.Text */, context.offset, context.startLoc);
  899. node.value = value;
  900. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  901. return node;
  902. }
  903. function parseList(tokenizer, index) {
  904. const context = tokenizer.context();
  905. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  906. const node = startNode(5 /* NodeTypes.List */, offset, loc);
  907. node.index = parseInt(index, 10);
  908. tokenizer.nextToken(); // skip brach right
  909. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  910. return node;
  911. }
  912. function parseNamed(tokenizer, key) {
  913. const context = tokenizer.context();
  914. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  915. const node = startNode(4 /* NodeTypes.Named */, offset, loc);
  916. node.key = key;
  917. tokenizer.nextToken(); // skip brach right
  918. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  919. return node;
  920. }
  921. function parseLiteral(tokenizer, value) {
  922. const context = tokenizer.context();
  923. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  924. const node = startNode(9 /* NodeTypes.Literal */, offset, loc);
  925. node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence);
  926. tokenizer.nextToken(); // skip brach right
  927. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  928. return node;
  929. }
  930. function parseLinkedModifier(tokenizer) {
  931. const token = tokenizer.nextToken();
  932. const context = tokenizer.context();
  933. const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc
  934. const node = startNode(8 /* NodeTypes.LinkedModifier */, offset, loc);
  935. if (token.type !== 11 /* TokenTypes.LinkedModifier */) {
  936. // empty modifier
  937. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER, context.lastStartLoc, 0);
  938. node.value = '';
  939. endNode(node, offset, loc);
  940. return {
  941. nextConsumeToken: token,
  942. node
  943. };
  944. }
  945. // check token
  946. if (token.value == null) {
  947. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  948. }
  949. node.value = token.value || '';
  950. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  951. return {
  952. node
  953. };
  954. }
  955. function parseLinkedKey(tokenizer, value) {
  956. const context = tokenizer.context();
  957. const node = startNode(7 /* NodeTypes.LinkedKey */, context.offset, context.startLoc);
  958. node.value = value;
  959. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  960. return node;
  961. }
  962. function parseLinked(tokenizer) {
  963. const context = tokenizer.context();
  964. const linkedNode = startNode(6 /* NodeTypes.Linked */, context.offset, context.startLoc);
  965. let token = tokenizer.nextToken();
  966. if (token.type === 8 /* TokenTypes.LinkedDot */) {
  967. const parsed = parseLinkedModifier(tokenizer);
  968. linkedNode.modifier = parsed.node;
  969. token = parsed.nextConsumeToken || tokenizer.nextToken();
  970. }
  971. // asset check token
  972. if (token.type !== 9 /* TokenTypes.LinkedDelimiter */) {
  973. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  974. }
  975. token = tokenizer.nextToken();
  976. // skip brace left
  977. if (token.type === 2 /* TokenTypes.BraceLeft */) {
  978. token = tokenizer.nextToken();
  979. }
  980. switch (token.type) {
  981. case 10 /* TokenTypes.LinkedKey */:
  982. if (token.value == null) {
  983. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  984. }
  985. linkedNode.key = parseLinkedKey(tokenizer, token.value || '');
  986. break;
  987. case 4 /* TokenTypes.Named */:
  988. if (token.value == null) {
  989. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  990. }
  991. linkedNode.key = parseNamed(tokenizer, token.value || '');
  992. break;
  993. case 5 /* TokenTypes.List */:
  994. if (token.value == null) {
  995. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  996. }
  997. linkedNode.key = parseList(tokenizer, token.value || '');
  998. break;
  999. case 6 /* TokenTypes.Literal */:
  1000. if (token.value == null) {
  1001. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1002. }
  1003. linkedNode.key = parseLiteral(tokenizer, token.value || '');
  1004. break;
  1005. default: {
  1006. // empty key
  1007. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY, context.lastStartLoc, 0);
  1008. const nextContext = tokenizer.context();
  1009. const emptyLinkedKeyNode = startNode(7 /* NodeTypes.LinkedKey */, nextContext.offset, nextContext.startLoc);
  1010. emptyLinkedKeyNode.value = '';
  1011. endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc);
  1012. linkedNode.key = emptyLinkedKeyNode;
  1013. endNode(linkedNode, nextContext.offset, nextContext.startLoc);
  1014. return {
  1015. nextConsumeToken: token,
  1016. node: linkedNode
  1017. };
  1018. }
  1019. }
  1020. endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition());
  1021. return {
  1022. node: linkedNode
  1023. };
  1024. }
  1025. function parseMessage(tokenizer) {
  1026. const context = tokenizer.context();
  1027. const startOffset = context.currentType === 1 /* TokenTypes.Pipe */
  1028. ? tokenizer.currentOffset()
  1029. : context.offset;
  1030. const startLoc = context.currentType === 1 /* TokenTypes.Pipe */
  1031. ? context.endLoc
  1032. : context.startLoc;
  1033. const node = startNode(2 /* NodeTypes.Message */, startOffset, startLoc);
  1034. node.items = [];
  1035. let nextToken = null;
  1036. do {
  1037. const token = nextToken || tokenizer.nextToken();
  1038. nextToken = null;
  1039. switch (token.type) {
  1040. case 0 /* TokenTypes.Text */:
  1041. if (token.value == null) {
  1042. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1043. }
  1044. node.items.push(parseText(tokenizer, token.value || ''));
  1045. break;
  1046. case 5 /* TokenTypes.List */:
  1047. if (token.value == null) {
  1048. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1049. }
  1050. node.items.push(parseList(tokenizer, token.value || ''));
  1051. break;
  1052. case 4 /* TokenTypes.Named */:
  1053. if (token.value == null) {
  1054. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1055. }
  1056. node.items.push(parseNamed(tokenizer, token.value || ''));
  1057. break;
  1058. case 6 /* TokenTypes.Literal */:
  1059. if (token.value == null) {
  1060. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1061. }
  1062. node.items.push(parseLiteral(tokenizer, token.value || ''));
  1063. break;
  1064. case 7 /* TokenTypes.LinkedAlias */: {
  1065. const parsed = parseLinked(tokenizer);
  1066. node.items.push(parsed.node);
  1067. nextToken = parsed.nextConsumeToken || null;
  1068. break;
  1069. }
  1070. }
  1071. } while (context.currentType !== 13 /* TokenTypes.EOF */ &&
  1072. context.currentType !== 1 /* TokenTypes.Pipe */);
  1073. // adjust message node loc
  1074. const endOffset = context.currentType === 1 /* TokenTypes.Pipe */
  1075. ? context.lastOffset
  1076. : tokenizer.currentOffset();
  1077. const endLoc = context.currentType === 1 /* TokenTypes.Pipe */
  1078. ? context.lastEndLoc
  1079. : tokenizer.currentPosition();
  1080. endNode(node, endOffset, endLoc);
  1081. return node;
  1082. }
  1083. function parsePlural(tokenizer, offset, loc, msgNode) {
  1084. const context = tokenizer.context();
  1085. let hasEmptyMessage = msgNode.items.length === 0;
  1086. const node = startNode(1 /* NodeTypes.Plural */, offset, loc);
  1087. node.cases = [];
  1088. node.cases.push(msgNode);
  1089. do {
  1090. const msg = parseMessage(tokenizer);
  1091. if (!hasEmptyMessage) {
  1092. hasEmptyMessage = msg.items.length === 0;
  1093. }
  1094. node.cases.push(msg);
  1095. } while (context.currentType !== 13 /* TokenTypes.EOF */);
  1096. if (hasEmptyMessage) {
  1097. emitError(tokenizer, CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL, loc, 0);
  1098. }
  1099. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1100. return node;
  1101. }
  1102. function parseResource(tokenizer) {
  1103. const context = tokenizer.context();
  1104. const { offset, startLoc } = context;
  1105. const msgNode = parseMessage(tokenizer);
  1106. if (context.currentType === 13 /* TokenTypes.EOF */) {
  1107. return msgNode;
  1108. }
  1109. else {
  1110. return parsePlural(tokenizer, offset, startLoc, msgNode);
  1111. }
  1112. }
  1113. function parse(source) {
  1114. const tokenizer = createTokenizer(source, assign({}, options));
  1115. const context = tokenizer.context();
  1116. const node = startNode(0 /* NodeTypes.Resource */, context.offset, context.startLoc);
  1117. if (location && node.loc) {
  1118. node.loc.source = source;
  1119. }
  1120. node.body = parseResource(tokenizer);
  1121. if (options.onCacheKey) {
  1122. node.cacheKey = options.onCacheKey(source);
  1123. }
  1124. // assert whether achieved to EOF
  1125. if (context.currentType !== 13 /* TokenTypes.EOF */) {
  1126. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, source[context.offset] || '');
  1127. }
  1128. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1129. return node;
  1130. }
  1131. return { parse };
  1132. }
  1133. function getTokenCaption(token) {
  1134. if (token.type === 13 /* TokenTypes.EOF */) {
  1135. return 'EOF';
  1136. }
  1137. const name = (token.value || '').replace(/\r?\n/gu, '\\n');
  1138. return name.length > 10 ? name.slice(0, 9) + '…' : name;
  1139. }
  1140. function createTransformer(ast, options = {} // eslint-disable-line
  1141. ) {
  1142. const _context = {
  1143. ast,
  1144. helpers: new Set()
  1145. };
  1146. const context = () => _context;
  1147. const helper = (name) => {
  1148. _context.helpers.add(name);
  1149. return name;
  1150. };
  1151. return { context, helper };
  1152. }
  1153. function traverseNodes(nodes, transformer) {
  1154. for (let i = 0; i < nodes.length; i++) {
  1155. traverseNode(nodes[i], transformer);
  1156. }
  1157. }
  1158. function traverseNode(node, transformer) {
  1159. // TODO: if we need pre-hook of transform, should be implemented to here
  1160. switch (node.type) {
  1161. case 1 /* NodeTypes.Plural */:
  1162. traverseNodes(node.cases, transformer);
  1163. transformer.helper("plural" /* HelperNameMap.PLURAL */);
  1164. break;
  1165. case 2 /* NodeTypes.Message */:
  1166. traverseNodes(node.items, transformer);
  1167. break;
  1168. case 6 /* NodeTypes.Linked */: {
  1169. const linked = node;
  1170. traverseNode(linked.key, transformer);
  1171. transformer.helper("linked" /* HelperNameMap.LINKED */);
  1172. transformer.helper("type" /* HelperNameMap.TYPE */);
  1173. break;
  1174. }
  1175. case 5 /* NodeTypes.List */:
  1176. transformer.helper("interpolate" /* HelperNameMap.INTERPOLATE */);
  1177. transformer.helper("list" /* HelperNameMap.LIST */);
  1178. break;
  1179. case 4 /* NodeTypes.Named */:
  1180. transformer.helper("interpolate" /* HelperNameMap.INTERPOLATE */);
  1181. transformer.helper("named" /* HelperNameMap.NAMED */);
  1182. break;
  1183. }
  1184. // TODO: if we need post-hook of transform, should be implemented to here
  1185. }
  1186. // transform AST
  1187. function transform(ast, options = {} // eslint-disable-line
  1188. ) {
  1189. const transformer = createTransformer(ast);
  1190. transformer.helper("normalize" /* HelperNameMap.NORMALIZE */);
  1191. // traverse
  1192. ast.body && traverseNode(ast.body, transformer);
  1193. // set meta information
  1194. const context = transformer.context();
  1195. ast.helpers = Array.from(context.helpers);
  1196. }
  1197. function optimize(ast) {
  1198. const body = ast.body;
  1199. if (body.type === 2 /* NodeTypes.Message */) {
  1200. optimizeMessageNode(body);
  1201. }
  1202. else {
  1203. body.cases.forEach(c => optimizeMessageNode(c));
  1204. }
  1205. return ast;
  1206. }
  1207. function optimizeMessageNode(message) {
  1208. if (message.items.length === 1) {
  1209. const item = message.items[0];
  1210. if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {
  1211. message.static = item.value;
  1212. delete item.value; // optimization for size
  1213. }
  1214. }
  1215. else {
  1216. const values = [];
  1217. for (let i = 0; i < message.items.length; i++) {
  1218. const item = message.items[i];
  1219. if (!(item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */)) {
  1220. break;
  1221. }
  1222. if (item.value == null) {
  1223. break;
  1224. }
  1225. values.push(item.value);
  1226. }
  1227. if (values.length === message.items.length) {
  1228. message.static = join(values);
  1229. for (let i = 0; i < message.items.length; i++) {
  1230. const item = message.items[i];
  1231. if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {
  1232. delete item.value; // optimization for size
  1233. }
  1234. }
  1235. }
  1236. }
  1237. }
  1238. const ERROR_DOMAIN$1 = 'minifier';
  1239. /* eslint-disable @typescript-eslint/no-explicit-any */
  1240. function minify(node) {
  1241. node.t = node.type;
  1242. switch (node.type) {
  1243. case 0 /* NodeTypes.Resource */: {
  1244. const resource = node;
  1245. minify(resource.body);
  1246. resource.b = resource.body;
  1247. delete resource.body;
  1248. break;
  1249. }
  1250. case 1 /* NodeTypes.Plural */: {
  1251. const plural = node;
  1252. const cases = plural.cases;
  1253. for (let i = 0; i < cases.length; i++) {
  1254. minify(cases[i]);
  1255. }
  1256. plural.c = cases;
  1257. delete plural.cases;
  1258. break;
  1259. }
  1260. case 2 /* NodeTypes.Message */: {
  1261. const message = node;
  1262. const items = message.items;
  1263. for (let i = 0; i < items.length; i++) {
  1264. minify(items[i]);
  1265. }
  1266. message.i = items;
  1267. delete message.items;
  1268. if (message.static) {
  1269. message.s = message.static;
  1270. delete message.static;
  1271. }
  1272. break;
  1273. }
  1274. case 3 /* NodeTypes.Text */:
  1275. case 9 /* NodeTypes.Literal */:
  1276. case 8 /* NodeTypes.LinkedModifier */:
  1277. case 7 /* NodeTypes.LinkedKey */: {
  1278. const valueNode = node;
  1279. if (valueNode.value) {
  1280. valueNode.v = valueNode.value;
  1281. delete valueNode.value;
  1282. }
  1283. break;
  1284. }
  1285. case 6 /* NodeTypes.Linked */: {
  1286. const linked = node;
  1287. minify(linked.key);
  1288. linked.k = linked.key;
  1289. delete linked.key;
  1290. if (linked.modifier) {
  1291. minify(linked.modifier);
  1292. linked.m = linked.modifier;
  1293. delete linked.modifier;
  1294. }
  1295. break;
  1296. }
  1297. case 5 /* NodeTypes.List */: {
  1298. const list = node;
  1299. list.i = list.index;
  1300. delete list.index;
  1301. break;
  1302. }
  1303. case 4 /* NodeTypes.Named */: {
  1304. const named = node;
  1305. named.k = named.key;
  1306. delete named.key;
  1307. break;
  1308. }
  1309. default:
  1310. {
  1311. throw createCompileError(CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE, null, {
  1312. domain: ERROR_DOMAIN$1,
  1313. args: [node.type]
  1314. });
  1315. }
  1316. }
  1317. delete node.type;
  1318. }
  1319. /* eslint-enable @typescript-eslint/no-explicit-any */
  1320. // eslint-disable-next-line @typescript-eslint/triple-slash-reference
  1321. /// <reference types="source-map-js" />
  1322. const ERROR_DOMAIN = 'parser';
  1323. function createCodeGenerator(ast, options) {
  1324. const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options;
  1325. const location = options.location !== false;
  1326. const _context = {
  1327. filename,
  1328. code: '',
  1329. column: 1,
  1330. line: 1,
  1331. offset: 0,
  1332. map: undefined,
  1333. breakLineCode,
  1334. needIndent: _needIndent,
  1335. indentLevel: 0
  1336. };
  1337. if (location && ast.loc) {
  1338. _context.source = ast.loc.source;
  1339. }
  1340. const context = () => _context;
  1341. function push(code, node) {
  1342. _context.code += code;
  1343. }
  1344. function _newline(n, withBreakLine = true) {
  1345. const _breakLineCode = withBreakLine ? breakLineCode : '';
  1346. push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode);
  1347. }
  1348. function indent(withNewLine = true) {
  1349. const level = ++_context.indentLevel;
  1350. withNewLine && _newline(level);
  1351. }
  1352. function deindent(withNewLine = true) {
  1353. const level = --_context.indentLevel;
  1354. withNewLine && _newline(level);
  1355. }
  1356. function newline() {
  1357. _newline(_context.indentLevel);
  1358. }
  1359. const helper = (key) => `_${key}`;
  1360. const needIndent = () => _context.needIndent;
  1361. return {
  1362. context,
  1363. push,
  1364. indent,
  1365. deindent,
  1366. newline,
  1367. helper,
  1368. needIndent
  1369. };
  1370. }
  1371. function generateLinkedNode(generator, node) {
  1372. const { helper } = generator;
  1373. generator.push(`${helper("linked" /* HelperNameMap.LINKED */)}(`);
  1374. generateNode(generator, node.key);
  1375. if (node.modifier) {
  1376. generator.push(`, `);
  1377. generateNode(generator, node.modifier);
  1378. generator.push(`, _type`);
  1379. }
  1380. else {
  1381. generator.push(`, undefined, _type`);
  1382. }
  1383. generator.push(`)`);
  1384. }
  1385. function generateMessageNode(generator, node) {
  1386. const { helper, needIndent } = generator;
  1387. generator.push(`${helper("normalize" /* HelperNameMap.NORMALIZE */)}([`);
  1388. generator.indent(needIndent());
  1389. const length = node.items.length;
  1390. for (let i = 0; i < length; i++) {
  1391. generateNode(generator, node.items[i]);
  1392. if (i === length - 1) {
  1393. break;
  1394. }
  1395. generator.push(', ');
  1396. }
  1397. generator.deindent(needIndent());
  1398. generator.push('])');
  1399. }
  1400. function generatePluralNode(generator, node) {
  1401. const { helper, needIndent } = generator;
  1402. if (node.cases.length > 1) {
  1403. generator.push(`${helper("plural" /* HelperNameMap.PLURAL */)}([`);
  1404. generator.indent(needIndent());
  1405. const length = node.cases.length;
  1406. for (let i = 0; i < length; i++) {
  1407. generateNode(generator, node.cases[i]);
  1408. if (i === length - 1) {
  1409. break;
  1410. }
  1411. generator.push(', ');
  1412. }
  1413. generator.deindent(needIndent());
  1414. generator.push(`])`);
  1415. }
  1416. }
  1417. function generateResource(generator, node) {
  1418. if (node.body) {
  1419. generateNode(generator, node.body);
  1420. }
  1421. else {
  1422. generator.push('null');
  1423. }
  1424. }
  1425. function generateNode(generator, node) {
  1426. const { helper } = generator;
  1427. switch (node.type) {
  1428. case 0 /* NodeTypes.Resource */:
  1429. generateResource(generator, node);
  1430. break;
  1431. case 1 /* NodeTypes.Plural */:
  1432. generatePluralNode(generator, node);
  1433. break;
  1434. case 2 /* NodeTypes.Message */:
  1435. generateMessageNode(generator, node);
  1436. break;
  1437. case 6 /* NodeTypes.Linked */:
  1438. generateLinkedNode(generator, node);
  1439. break;
  1440. case 8 /* NodeTypes.LinkedModifier */:
  1441. generator.push(JSON.stringify(node.value), node);
  1442. break;
  1443. case 7 /* NodeTypes.LinkedKey */:
  1444. generator.push(JSON.stringify(node.value), node);
  1445. break;
  1446. case 5 /* NodeTypes.List */:
  1447. generator.push(`${helper("interpolate" /* HelperNameMap.INTERPOLATE */)}(${helper("list" /* HelperNameMap.LIST */)}(${node.index}))`, node);
  1448. break;
  1449. case 4 /* NodeTypes.Named */:
  1450. generator.push(`${helper("interpolate" /* HelperNameMap.INTERPOLATE */)}(${helper("named" /* HelperNameMap.NAMED */)}(${JSON.stringify(node.key)}))`, node);
  1451. break;
  1452. case 9 /* NodeTypes.Literal */:
  1453. generator.push(JSON.stringify(node.value), node);
  1454. break;
  1455. case 3 /* NodeTypes.Text */:
  1456. generator.push(JSON.stringify(node.value), node);
  1457. break;
  1458. default:
  1459. {
  1460. throw createCompileError(CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE, null, {
  1461. domain: ERROR_DOMAIN,
  1462. args: [node.type]
  1463. });
  1464. }
  1465. }
  1466. }
  1467. // generate code from AST
  1468. const generate = (ast, options = {}) => {
  1469. const mode = isString(options.mode) ? options.mode : 'normal';
  1470. const filename = isString(options.filename)
  1471. ? options.filename
  1472. : 'message.intl';
  1473. const sourceMap = !!options.sourceMap;
  1474. // prettier-ignore
  1475. const breakLineCode = options.breakLineCode != null
  1476. ? options.breakLineCode
  1477. : mode === 'arrow'
  1478. ? ';'
  1479. : '\n';
  1480. const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow';
  1481. const helpers = ast.helpers || [];
  1482. const generator = createCodeGenerator(ast, {
  1483. mode,
  1484. filename,
  1485. sourceMap,
  1486. breakLineCode,
  1487. needIndent
  1488. });
  1489. generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`);
  1490. generator.indent(needIndent);
  1491. if (helpers.length > 0) {
  1492. generator.push(`const { ${join(helpers.map(s => `${s}: _${s}`), ', ')} } = ctx`);
  1493. generator.newline();
  1494. }
  1495. generator.push(`return `);
  1496. generateNode(generator, ast);
  1497. generator.deindent(needIndent);
  1498. generator.push(`}`);
  1499. delete ast.helpers;
  1500. const { code, map } = generator.context();
  1501. return {
  1502. ast,
  1503. code,
  1504. map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any
  1505. };
  1506. };
  1507. function baseCompile(source, options = {}) {
  1508. const assignedOptions = assign({}, options);
  1509. const jit = !!assignedOptions.jit;
  1510. const enalbeMinify = !!assignedOptions.minify;
  1511. const enambeOptimize = assignedOptions.optimize == null ? true : assignedOptions.optimize;
  1512. // parse source codes
  1513. const parser = createParser(assignedOptions);
  1514. const ast = parser.parse(source);
  1515. if (!jit) {
  1516. // transform ASTs
  1517. transform(ast, assignedOptions);
  1518. // generate javascript codes
  1519. return generate(ast, assignedOptions);
  1520. }
  1521. else {
  1522. // optimize ASTs
  1523. enambeOptimize && optimize(ast);
  1524. // minimize ASTs
  1525. enalbeMinify && minify(ast);
  1526. // In JIT mode, no ast transform, no code generation.
  1527. return { ast, code: '' };
  1528. }
  1529. }
  1530. exports.COMPILE_ERROR_CODES_EXTEND_POINT = COMPILE_ERROR_CODES_EXTEND_POINT;
  1531. exports.CompileErrorCodes = CompileErrorCodes;
  1532. exports.ERROR_DOMAIN = ERROR_DOMAIN$2;
  1533. exports.LOCATION_STUB = LOCATION_STUB;
  1534. exports.baseCompile = baseCompile;
  1535. exports.createCompileError = createCompileError;
  1536. exports.createLocation = createLocation;
  1537. exports.createParser = createParser;
  1538. exports.createPosition = createPosition;
  1539. exports.defaultOnError = defaultOnError;
  1540. exports.detectHtmlTag = detectHtmlTag;
  1541. exports.errorMessages = errorMessages;
  1542. return exports;
  1543. })({});