canonify
Version:
**NOTE: This is effictively a fork of [@truestamp/canonify](https://www.npmjs.com/package/@truestamp/canonify) to fix an issue with exporting types. Since a repo could not be found, a fork/PR was not possible. All copyrights/attribution has been left in p
61 lines (59 loc) • 2.25 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
canonify: () => canonify
});
module.exports = __toCommonJS(src_exports);
function hasComma(num) {
return num === 0 ? "" : ",";
}
function canonify(object) {
if (object === null || typeof object === "undefined" || typeof object === "boolean" || typeof object === "number" || typeof object === "string") {
return JSON.stringify(object);
}
if (typeof object === "bigint") {
throw new TypeError("BigInt value can't be serialized in JSON");
}
if (typeof object === "function" || typeof object === "symbol") {
return canonify(void 0);
}
if (object.toJSON instanceof Function) {
return canonify(object.toJSON());
}
if (Array.isArray(object)) {
const values2 = object.reduce((t, cv, ci) => {
const value = cv === void 0 || typeof cv === "symbol" || typeof cv === "function" ? null : cv;
return `${t}${hasComma(ci)}${canonify(value)}`;
}, "");
return `[${values2}]`;
}
const values = Object.keys(object).sort().reduce((t, cv) => {
if (object[cv] === void 0 || typeof object[cv] === "symbol" || typeof object[cv] === "function") {
return t;
}
return `${t}${hasComma(t.length)}${canonify(cv)}:${canonify(object[cv])}`;
}, "");
return `{${values}}`;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
canonify
});