ssr.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. exports.uniSSRPlugin = void 0;
  7. const debug_1 = __importDefault(require("debug"));
  8. const crypto_1 = __importDefault(require("crypto"));
  9. const estree_walker_1 = require("estree-walker");
  10. const pluginutils_1 = require("@rollup/pluginutils");
  11. const magic_string_1 = __importDefault(require("magic-string"));
  12. const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
  13. const debugSSR = (0, debug_1.default)('uni:ssr');
  14. const KEYED_FUNC_RE = /(ssrRef|shallowSsrRef)/;
  15. function uniSSRPlugin(config, options) {
  16. const filter = (0, pluginutils_1.createFilter)(options.include, options.exclude);
  17. return {
  18. name: 'uni:ssr:ref',
  19. transform(code, id) {
  20. if (!filter(id))
  21. return null;
  22. if (!KEYED_FUNC_RE.test(code)) {
  23. return;
  24. }
  25. debugSSR('try', id);
  26. const ast = this.parse(code);
  27. const s = new magic_string_1.default(code);
  28. (0, estree_walker_1.walk)(ast, {
  29. enter(node) {
  30. if (!(0, uni_cli_shared_1.isCallExpression)(node)) {
  31. return;
  32. }
  33. const { callee, arguments: args } = node;
  34. if (args.length !== 1) {
  35. return;
  36. }
  37. const name = (0, uni_cli_shared_1.isIdentifier)(callee)
  38. ? callee.name
  39. : (0, uni_cli_shared_1.isMemberExpression)(callee) && (0, uni_cli_shared_1.isIdentifier)(callee.property)
  40. ? callee.property.name
  41. : '';
  42. if (name !== 'ssrRef' && name !== 'shallowSsrRef') {
  43. return;
  44. }
  45. const { end } = node;
  46. const key = id + '-' + node.end;
  47. debugSSR(key, name);
  48. s.appendLeft(end - 1, ", '" + createKey(`${id}-${end}`) + "'");
  49. },
  50. });
  51. return {
  52. code: s.toString(),
  53. map: (0, uni_cli_shared_1.withSourcemap)(config) ? s.generateMap().toString() : null,
  54. };
  55. },
  56. };
  57. }
  58. exports.uniSSRPlugin = uniSSRPlugin;
  59. function createKey(source) {
  60. const hash = crypto_1.default.createHash('md5');
  61. hash.update(source);
  62. return hash.digest('base64').toString();
  63. }