2022-07-01 20:17:40 +01:00
|
|
|
/*
|
2024-09-06 17:56:18 +01:00
|
|
|
Copyright 2022-2024 New Vector Ltd.
|
2022-07-01 20:17:40 +01:00
|
|
|
|
2025-01-17 11:44:49 +00:00
|
|
|
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
|
2024-09-06 17:56:18 +01:00
|
|
|
Please see LICENSE files in the repository root for full details.
|
2022-07-01 20:17:40 +01:00
|
|
|
*/
|
|
|
|
|
|
2024-10-30 18:06:03 +00:00
|
|
|
import crypto from "node:crypto";
|
2024-02-19 15:22:40 +00:00
|
|
|
import fs from "node:fs";
|
|
|
|
|
import path from "node:path";
|
2022-07-01 20:17:40 +01:00
|
|
|
|
|
|
|
|
export async function randomArray(size: number): Promise<string> {
|
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
|
crypto.randomBytes(size, (err, buf) => {
|
|
|
|
|
if (err) {
|
|
|
|
|
reject(err);
|
|
|
|
|
} else {
|
2022-12-15 11:00:58 +00:00
|
|
|
resolve(buf.toString("base64").replace(/=+$/g, ""));
|
2022-07-01 20:17:40 +01:00
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
}
|
2024-02-19 15:22:40 +00:00
|
|
|
|
|
|
|
|
type JsonValue = null | string | number;
|
|
|
|
|
type JsonArray = Array<JsonValue | JsonObject | JsonArray>;
|
2025-05-22 11:40:28 +01:00
|
|
|
export interface JsonObject {
|
2024-02-19 15:22:40 +00:00
|
|
|
[key: string]: JsonObject | JsonArray | JsonValue;
|
|
|
|
|
}
|
2025-03-31 16:09:57 +01:00
|
|
|
export type Json = JsonArray | JsonObject;
|
2024-02-19 15:22:40 +00:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Synchronously load a JSON file from the local filesystem.
|
|
|
|
|
* Unlike `require`, will never execute any javascript in a loaded file.
|
|
|
|
|
* @param paths - An array of path segments which will be joined using the system's path delimiter.
|
|
|
|
|
*/
|
|
|
|
|
export function loadJsonFile<T extends Json>(...paths: string[]): T {
|
2025-04-14 11:22:11 +01:00
|
|
|
const joinedPaths = path.join(...paths);
|
|
|
|
|
|
|
|
|
|
if (!fs.existsSync(joinedPaths)) {
|
2025-04-15 11:58:55 +01:00
|
|
|
console.log(`Skipping nonexistent file: ${joinedPaths}`);
|
2025-04-14 11:22:11 +01:00
|
|
|
return {} as T;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const file = fs.readFileSync(joinedPaths, { encoding: "utf-8" });
|
2024-02-19 15:22:40 +00:00
|
|
|
return JSON.parse(file);
|
|
|
|
|
}
|