literal.js 2.0 KB

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