@phala/dstack-sdk
Version:
dstack SDK
72 lines • 2.58 kB
JavaScript
;
// SPDX-FileCopyrightText: © 2025 Phala Network <dstack@phala.network>
//
// SPDX-License-Identifier: Apache-2.0
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getComposeHash = getComposeHash;
const crypto_1 = __importDefault(require("crypto"));
/**
* Recursively sorts object keys lexicographically.
* This is crucial for deterministic JSON.stringify in JavaScript.
* @param obj The object to sort.
* @returns A new object with sorted keys, or the original value if not an object.
*/
function sortObject(obj) {
if (obj === undefined || obj === null) {
return obj;
}
if (Array.isArray(obj)) {
return obj.map(sortObject);
}
else if (obj && typeof obj === "object" && obj.constructor === Object) {
return Object.keys(obj)
.sort()
.reduce((result, key) => {
const value = obj[key];
result[key] = sortObject(value);
return result;
}, {});
}
return obj;
}
function preprocessAppCompose(dic) {
const obj = { ...dic };
if (obj.runner === "bash" && "docker_compose_file" in obj) {
delete obj.docker_compose_file;
}
else if (obj.runner === "docker-compose" && "bash_script" in obj) {
delete obj.bash_script;
}
if ("pre_launch_script" in obj && !obj.pre_launch_script) {
delete obj.pre_launch_script;
}
return obj;
}
/**
* Deterministic JSON serialization following cross-language standards.
* - Recursively sorts object keys lexicographically
* - Compact output (no spaces)
* - Handles special values (NaN, Infinity) by converting them to null
* - UTF-8 encoding (default in JavaScript)
*/
function toDeterministicJson(dic) {
const ordered = sortObject(dic);
return JSON.stringify(ordered, (key, value) => {
// Convert NaN and Infinity to null for deterministic output
if (typeof value === 'number' && (isNaN(value) || !isFinite(value))) {
return null;
}
return value;
}); // Omit the 'space' argument for compact output
}
function getComposeHash(app_compose, normalize = false) {
if (normalize) {
app_compose = preprocessAppCompose(app_compose);
}
const manifest_str = toDeterministicJson(app_compose);
return crypto_1.default.createHash("sha256").update(manifest_str, "utf8").digest("hex");
}
//# sourceMappingURL=get-compose-hash.js.map