webpack/lib/json/JsonData.js

75 lines
1.8 KiB
JavaScript
Raw Normal View History

/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { register } = require("../util/serialization");
2023-04-29 02:03:16 +08:00
/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {import("../util/Hash")} Hash */
2025-04-04 21:38:51 +08:00
/** @typedef {import("./JsonModulesPlugin").JsonValue} JsonValue */
2023-04-29 02:03:16 +08:00
class JsonData {
2023-04-29 02:03:16 +08:00
/**
2025-04-04 21:38:51 +08:00
* @param {Buffer | JsonValue} data JSON data
2023-04-29 02:03:16 +08:00
*/
constructor(data) {
2023-04-29 02:03:16 +08:00
/** @type {Buffer | undefined} */
this._buffer = undefined;
2025-04-04 21:38:51 +08:00
/** @type {JsonValue | undefined} */
this._data = undefined;
if (Buffer.isBuffer(data)) {
this._buffer = data;
} else {
this._data = data;
}
}
2023-04-29 02:03:16 +08:00
/**
2025-04-04 21:38:51 +08:00
* @returns {JsonValue | undefined} Raw JSON data
2023-04-29 02:03:16 +08:00
*/
get() {
if (this._data === undefined && this._buffer !== undefined) {
this._data = JSON.parse(this._buffer.toString());
}
return this._data;
}
2022-05-13 21:32:24 +08:00
2023-04-29 02:03:16 +08:00
/**
* @param {Hash} hash hash to be updated
2023-06-02 03:44:37 +08:00
* @returns {void} the updated hash
2023-04-29 02:03:16 +08:00
*/
2022-05-13 21:32:24 +08:00
updateHash(hash) {
if (this._buffer === undefined && this._data !== undefined) {
this._buffer = Buffer.from(JSON.stringify(this._data));
}
2023-06-02 03:44:37 +08:00
if (this._buffer) hash.update(this._buffer);
2022-05-13 21:32:24 +08:00
}
}
register(JsonData, "webpack/lib/json/JsonData", null, {
2023-04-29 02:03:16 +08:00
/**
* @param {JsonData} obj JSONData object
* @param {ObjectSerializerContext} context context
*/
serialize(obj, { write }) {
if (obj._buffer === undefined && obj._data !== undefined) {
obj._buffer = Buffer.from(JSON.stringify(obj._data));
}
write(obj._buffer);
},
2023-04-29 02:03:16 +08:00
/**
* @param {ObjectDeserializerContext} context context
* @returns {JsonData} deserialized JSON data
*/
deserialize({ read }) {
return new JsonData(read());
}
});
module.exports = JsonData;