JsonData.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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("../util/fs").JsonValue} JsonValue */
  11. class JsonData {
  12. /**
  13. * Creates an instance of JsonData.
  14. * @param {Buffer | JsonValue} data JSON data
  15. */
  16. constructor(data) {
  17. /** @type {Buffer | undefined} */
  18. this._buffer = undefined;
  19. /** @type {JsonValue | undefined} */
  20. this._data = undefined;
  21. if (Buffer.isBuffer(data)) {
  22. this._buffer = data;
  23. } else {
  24. this._data = data;
  25. }
  26. }
  27. /**
  28. * Returns raw JSON data.
  29. * @returns {JsonValue | undefined} Raw JSON data
  30. */
  31. get() {
  32. if (this._data === undefined && this._buffer !== undefined) {
  33. this._data = JSON.parse(this._buffer.toString());
  34. }
  35. return this._data;
  36. }
  37. /**
  38. * Updates the hash with the data contributed by this instance.
  39. * @param {Hash} hash hash to be updated
  40. * @returns {void} the updated hash
  41. */
  42. updateHash(hash) {
  43. if (this._buffer === undefined && this._data !== undefined) {
  44. this._buffer = Buffer.from(JSON.stringify(this._data));
  45. }
  46. if (this._buffer) hash.update(this._buffer);
  47. }
  48. }
  49. register(JsonData, "webpack/lib/json/JsonData", null, {
  50. /**
  51. * Serializes this instance into the provided serializer context.
  52. * @param {JsonData} obj JSONData object
  53. * @param {ObjectSerializerContext} context context
  54. */
  55. serialize(obj, { write }) {
  56. if (obj._buffer === undefined && obj._data !== undefined) {
  57. obj._buffer = Buffer.from(JSON.stringify(obj._data));
  58. }
  59. write(obj._buffer);
  60. },
  61. /**
  62. * Restores this instance from the provided deserializer context.
  63. * @param {ObjectDeserializerContext} context context
  64. * @returns {JsonData} deserialized JSON data
  65. */
  66. deserialize({ read }) {
  67. return new JsonData(read());
  68. }
  69. });
  70. module.exports = JsonData;