literal.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = literalTemplate;
  6. var _options = require("./options");
  7. var _parse = _interopRequireDefault(require("./parse"));
  8. var _populate = _interopRequireDefault(require("./populate"));
  9. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  10. function literalTemplate(formatter, tpl, opts) {
  11. const {
  12. metadata,
  13. names
  14. } = buildLiteralData(formatter, tpl, opts);
  15. return arg => {
  16. const defaultReplacements = arg.reduce((acc, replacement, i) => {
  17. acc[names[i]] = replacement;
  18. return acc;
  19. }, {});
  20. return arg => {
  21. const replacements = (0, _options.normalizeReplacements)(arg);
  22. if (replacements) {
  23. Object.keys(replacements).forEach(key => {
  24. if (Object.prototype.hasOwnProperty.call(defaultReplacements, key)) {
  25. throw new Error("Unexpected replacement overlap.");
  26. }
  27. });
  28. }
  29. return formatter.unwrap((0, _populate.default)(metadata, replacements ? Object.assign(replacements, defaultReplacements) : defaultReplacements));
  30. };
  31. };
  32. }
  33. function buildLiteralData(formatter, tpl, opts) {
  34. let names;
  35. let nameSet;
  36. let metadata;
  37. let prefix = "";
  38. do {
  39. prefix += "$";
  40. const result = buildTemplateCode(tpl, prefix);
  41. names = result.names;
  42. nameSet = new Set(names);
  43. metadata = (0, _parse.default)(formatter, formatter.code(result.code), {
  44. parser: opts.parser,
  45. placeholderWhitelist: new Set(result.names.concat(opts.placeholderWhitelist ? Array.from(opts.placeholderWhitelist) : [])),
  46. placeholderPattern: opts.placeholderPattern,
  47. preserveComments: opts.preserveComments,
  48. syntacticPlaceholders: opts.syntacticPlaceholders
  49. });
  50. } while (metadata.placeholders.some(placeholder => placeholder.isDuplicate && nameSet.has(placeholder.name)));
  51. return {
  52. metadata,
  53. names
  54. };
  55. }
  56. function buildTemplateCode(tpl, prefix) {
  57. const names = [];
  58. let code = tpl[0];
  59. for (let i = 1; i < tpl.length; i++) {
  60. const value = `${prefix}${i - 1}`;
  61. names.push(value);
  62. code += value + tpl[i];
  63. }
  64. return {
  65. names,
  66. code
  67. };
  68. }