JsonData.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { register } = require("../util/serialization");
  7. /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  8. /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  9. /** @typedef {import("../util/Hash")} Hash */
  10. /** @typedef {import("./JsonModulesPlugin").RawJsonData} RawJsonData */
  11. class JsonData {
  12. /**
  13. * @param {Buffer | RawJsonData} data JSON data
  14. */
  15. constructor(data) {
  16. /** @type {Buffer | undefined} */
  17. this._buffer = undefined;
  18. /** @type {RawJsonData | undefined} */
  19. this._data = undefined;
  20. if (Buffer.isBuffer(data)) {
  21. this._buffer = data;
  22. } else {
  23. this._data = data;
  24. }
  25. }
  26. /**
  27. * @returns {RawJsonData|undefined} Raw JSON data
  28. */
  29. get() {
  30. if (this._data === undefined && this._buffer !== undefined) {
  31. this._data = JSON.parse(this._buffer.toString());
  32. }
  33. return this._data;
  34. }
  35. /**
  36. * @param {Hash} hash hash to be updated
  37. * @returns {void} the updated hash
  38. */
  39. updateHash(hash) {
  40. if (this._buffer === undefined && this._data !== undefined) {
  41. this._buffer = Buffer.from(JSON.stringify(this._data));
  42. }
  43. if (this._buffer) hash.update(this._buffer);
  44. }
  45. }
  46. register(JsonData, "webpack/lib/json/JsonData", null, {
  47. /**
  48. * @param {JsonData} obj JSONData object
  49. * @param {ObjectSerializerContext} context context
  50. */
  51. serialize(obj, { write }) {
  52. if (obj._buffer === undefined && obj._data !== undefined) {
  53. obj._buffer = Buffer.from(JSON.stringify(obj._data));
  54. }
  55. write(obj._buffer);
  56. },
  57. /**
  58. * @param {ObjectDeserializerContext} context context
  59. * @returns {JsonData} deserialized JSON data
  60. */
  61. deserialize({ read }) {
  62. return new JsonData(read());
  63. }
  64. });
  65. module.exports = JsonData;