forked from microsoft/FluidFramework
-
Notifications
You must be signed in to change notification settings - Fork 3
/
utils.ts
101 lines (90 loc) · 2.43 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*!
* Copyright (c) Microsoft Corporation and contributors. All rights reserved.
* Licensed under the MIT License.
*/
import * as fs from "fs";
import { IFluidFileConverter } from "./codeLoaderBundle.js";
/**
* Is the given snapshot in JSON format
* @param content - snapshot file content
* @internal
*/
export function isJsonSnapshot(content: Buffer): boolean {
return content.toString(undefined, 0, 1) === "{";
}
/**
* Get the ODSP snapshot file content
* Works on both JSON and binary snapshot formats
* @param filePath - path to the ODSP snapshot file
* @internal
*/
export function getSnapshotFileContent(filePath: string): string | Buffer {
// TODO: read file stream
const content = fs.readFileSync(filePath);
return isJsonSnapshot(content) ? content.toString() : content;
}
/**
* Validate provided command line arguments
* @internal
*/
export function validateCommandLineArgs(
codeLoader?: string,
fluidFileConverter?: IFluidFileConverter,
): string | undefined {
if (codeLoader && fluidFileConverter !== undefined) {
return '"codeLoader" and "fluidFileConverter" cannot both be provided. See README for details.';
}
if (!codeLoader && fluidFileConverter === undefined) {
return '"codeLoader" must be provided if there is no explicit "fluidFileConverter". See README for details.';
}
return undefined;
}
/**
* @internal
*/
export function getArgsValidationError(
inputFile: string,
outputFile: string,
timeout?: number,
): string | undefined {
// Validate input file
if (!inputFile) {
return "Input file name argument is missing.";
} else if (!fs.existsSync(inputFile)) {
return "Input file does not exist.";
}
// Validate output file
if (!outputFile) {
return "Output file argument is missing.";
} else if (fs.existsSync(outputFile)) {
return `Output file already exists [${outputFile}].`;
}
if (timeout !== undefined && (isNaN(timeout) || timeout < 0)) {
return "Invalid timeout";
}
return undefined;
}
/**
* @internal
*/
export async function timeoutPromise<T = void>(
executor: (
resolve: (value: T | PromiseLike<T>) => void,
reject: (reason?: any) => void,
) => void,
timeout: number,
): Promise<T> {
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error(`Timed out (${timeout}ms)`)), timeout);
executor(
(value) => {
clearTimeout(timer);
resolve(value);
},
(reason) => {
clearTimeout(timer);
reject(reason);
},
);
});
}