@fgv/ts-json-base 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js ADDED
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) 2023 Erik Fortune
4
+ *
5
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ * of this software and associated documentation files (the "Software"), to deal
7
+ * in the Software without restriction, including without limitation the rights
8
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ * copies of the Software, and to permit persons to whom the Software is
10
+ * furnished to do so, subject to the following conditions:
11
+ *
12
+ * The above copyright notice and this permission notice shall be included in all
13
+ * copies or substantial portions of the Software.
14
+ *
15
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ * SOFTWARE.
22
+ */
23
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
24
+ if (k2 === undefined) k2 = k;
25
+ var desc = Object.getOwnPropertyDescriptor(m, k);
26
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
27
+ desc = { enumerable: true, get: function() { return m[k]; } };
28
+ }
29
+ Object.defineProperty(o, k2, desc);
30
+ }) : (function(o, m, k, k2) {
31
+ if (k2 === undefined) k2 = k;
32
+ o[k2] = m[k];
33
+ }));
34
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
35
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
36
+ }) : function(o, v) {
37
+ o["default"] = v;
38
+ });
39
+ var __importStar = (this && this.__importStar) || function (mod) {
40
+ if (mod && mod.__esModule) return mod;
41
+ var result = {};
42
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
43
+ __setModuleDefault(result, mod);
44
+ return result;
45
+ };
46
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
47
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
48
+ };
49
+ Object.defineProperty(exports, "__esModule", { value: true });
50
+ exports.JsonFile = void 0;
51
+ const JsonFile = __importStar(require("./packlets/json-file"));
52
+ exports.JsonFile = JsonFile;
53
+ __exportStar(require("./packlets/json"), exports);
54
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,+DAAiD;AAGxC,4BAAQ;AADjB,kDAAgC","sourcesContent":["/*\n * Copyright (c) 2023 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport * as JsonFile from './packlets/json-file';\n\nexport * from './packlets/json';\nexport { JsonFile };\n\n"]}
@@ -0,0 +1,85 @@
1
+ import { Result } from '@fgv/ts-utils';
2
+ /**
3
+ * Primitive (terminal) values allowed in by JSON.
4
+ * @public
5
+ */
6
+ export type JsonPrimitive = boolean | number | string | null;
7
+ /**
8
+ * A {@link JsonObject | JsonObject} is a string-keyed object
9
+ * containing only valid {@link JsonValue | JSON values}.
10
+ * @public
11
+ */
12
+ export interface JsonObject {
13
+ [key: string]: JsonValue;
14
+ }
15
+ /**
16
+ * A {@link JsonValue | JsonValue} is one of: a {@link JsonPrimitive | JsonPrimitive},
17
+ * a {@link JsonObject | JsonObject} or an {@link JsonArray | JsonArray}.
18
+ * @public
19
+ */
20
+ export type JsonValue = JsonPrimitive | JsonObject | JsonArray;
21
+ /**
22
+ * A {@link JsonArray | JsonArray} is an array containing only valid {@link JsonValue | JsonValues}.
23
+ * @public
24
+ */
25
+ export interface JsonArray extends Array<JsonValue> {
26
+ }
27
+ /**
28
+ * Classes of {@link JsonValue | JsonValue}.
29
+ * @public
30
+ */
31
+ export type JsonValueType = 'primitive' | 'object' | 'array';
32
+ /**
33
+ * Test if an `unknown` is a {@link JsonValue | JsonValue}.
34
+ * @param from - The `unknown` to be tested
35
+ * @returns `true` if the supplied parameter is a valid {@link JsonPrimitive | JsonPrimitive},
36
+ * `false` otherwise.
37
+ * @public
38
+ */
39
+ export declare function isJsonPrimitive(from: unknown): from is JsonPrimitive;
40
+ /**
41
+ * Test if an `unknown` is potentially a {@link JsonObject | JsonObject}.
42
+ * @param from - The `unknown` to be tested.
43
+ * @returns `true` if the supplied parameter is a non-array, non-special object,
44
+ * `false` otherwise.
45
+ * @public
46
+ */
47
+ export declare function isJsonObject(from: unknown): from is JsonObject;
48
+ /**
49
+ * Test if an `unknown` is potentially a {@link JsonArray | JsonArray}.
50
+ * @param from - The `unknown` to be tested.
51
+ * @returns `true` if the supplied parameter is an array object,
52
+ * `false` otherwise.
53
+ * @public
54
+ */
55
+ export declare function isJsonArray(from: unknown): from is JsonArray;
56
+ /**
57
+ * Identifies whether some `unknown` value is a {@link JsonPrimitive | primitive},
58
+ * {@link JsonObject | object} or {@link JsonArray | array}. Fails for any value
59
+ * that cannot be converted to JSON (e.g. a function) _but_ this is a shallow test -
60
+ * it does not test the properties of an object or elements in an array.
61
+ * @param from - The `unknown` value to be tested
62
+ * @public
63
+ */
64
+ export declare function classifyJsonValue(from: unknown): Result<JsonValueType>;
65
+ /**
66
+ * Picks a nested field from a supplied {@link JsonObject | JsonObject}.
67
+ * @param src - The {@link JsonObject | object} from which the field is to be picked.
68
+ * @param path - Dot-separated path of the member to be picked.
69
+ * @returns `Success` with the property if the path is valid, `Failure`
70
+ * with an error message otherwise.
71
+ * @public
72
+ */
73
+ export declare function pickJsonValue(src: JsonObject, path: string): Result<JsonValue>;
74
+ /**
75
+ * Picks a nested {@link JsonObject | JsonObject} from a supplied
76
+ * {@link JsonObject | JsonObject}.
77
+ * @param src - The {@link JsonObject | object} from which the field is
78
+ * to be picked.
79
+ * @param path - Dot-separated path of the member to be picked.
80
+ * @returns `Success` with the property if the path is valid and the value
81
+ * is an object. Returns `Failure` with details if an error occurs.
82
+ * @public
83
+ */
84
+ export declare function pickJsonObject(src: JsonObject, path: string): Result<JsonObject>;
85
+ //# sourceMappingURL=common.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"common.d.ts","sourceRoot":"","sources":["../../../src/packlets/json/common.ts"],"names":[],"mappings":"AAsBA,OAAO,EAAE,MAAM,EAAiB,MAAM,eAAe,CAAC;AAItD;;;GAGG;AAEH,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC;AAE7D;;;;GAIG;AAEH,MAAM,WAAW,UAAU;IACzB,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAC;CAC1B;AAED;;;;GAIG;AACH,MAAM,MAAM,SAAS,GAAG,aAAa,GAAG,UAAU,GAAG,SAAS,CAAC;AAE/D;;;GAGG;AAEH,MAAM,WAAW,SAAU,SAAQ,KAAK,CAAC,SAAS,CAAC;CAAG;AAEtD;;;GAGG;AACH,MAAM,MAAM,aAAa,GAAG,WAAW,GAAG,QAAQ,GAAG,OAAO,CAAC;AAE7D;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,IAAI,aAAa,CAEpE;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,IAAI,UAAU,CAI9D;AAED;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,IAAI,SAAS,CAE5D;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,OAAO,GAAG,MAAM,CAAC,aAAa,CAAC,CAStE;AAED;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC,SAAS,CAAC,CAa9E;AAED;;;;;;;;;GASG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC,UAAU,CAAC,CAOhF"}
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) 2020 Erik Fortune
4
+ *
5
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ * of this software and associated documentation files (the "Software"), to deal
7
+ * in the Software without restriction, including without limitation the rights
8
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ * copies of the Software, and to permit persons to whom the Software is
10
+ * furnished to do so, subject to the following conditions:
11
+ *
12
+ * The above copyright notice and this permission notice shall be included in all
13
+ * copies or substantial portions of the Software.
14
+ *
15
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ * SOFTWARE.
22
+ */
23
+ Object.defineProperty(exports, "__esModule", { value: true });
24
+ exports.pickJsonObject = exports.pickJsonValue = exports.classifyJsonValue = exports.isJsonArray = exports.isJsonObject = exports.isJsonPrimitive = void 0;
25
+ const ts_utils_1 = require("@fgv/ts-utils");
26
+ /**
27
+ * Test if an `unknown` is a {@link JsonValue | JsonValue}.
28
+ * @param from - The `unknown` to be tested
29
+ * @returns `true` if the supplied parameter is a valid {@link JsonPrimitive | JsonPrimitive},
30
+ * `false` otherwise.
31
+ * @public
32
+ */
33
+ function isJsonPrimitive(from) {
34
+ return typeof from === 'boolean' || typeof from === 'number' || typeof from === 'string' || from === null;
35
+ }
36
+ exports.isJsonPrimitive = isJsonPrimitive;
37
+ /**
38
+ * Test if an `unknown` is potentially a {@link JsonObject | JsonObject}.
39
+ * @param from - The `unknown` to be tested.
40
+ * @returns `true` if the supplied parameter is a non-array, non-special object,
41
+ * `false` otherwise.
42
+ * @public
43
+ */
44
+ function isJsonObject(from) {
45
+ return (typeof from === 'object' && !Array.isArray(from) && !(from instanceof RegExp) && !(from instanceof Date));
46
+ }
47
+ exports.isJsonObject = isJsonObject;
48
+ /**
49
+ * Test if an `unknown` is potentially a {@link JsonArray | JsonArray}.
50
+ * @param from - The `unknown` to be tested.
51
+ * @returns `true` if the supplied parameter is an array object,
52
+ * `false` otherwise.
53
+ * @public
54
+ */
55
+ function isJsonArray(from) {
56
+ return typeof from === 'object' && Array.isArray(from);
57
+ }
58
+ exports.isJsonArray = isJsonArray;
59
+ /**
60
+ * Identifies whether some `unknown` value is a {@link JsonPrimitive | primitive},
61
+ * {@link JsonObject | object} or {@link JsonArray | array}. Fails for any value
62
+ * that cannot be converted to JSON (e.g. a function) _but_ this is a shallow test -
63
+ * it does not test the properties of an object or elements in an array.
64
+ * @param from - The `unknown` value to be tested
65
+ * @public
66
+ */
67
+ function classifyJsonValue(from) {
68
+ if (isJsonPrimitive(from)) {
69
+ return (0, ts_utils_1.succeed)('primitive');
70
+ }
71
+ else if (isJsonObject(from)) {
72
+ return (0, ts_utils_1.succeed)('object');
73
+ }
74
+ else if (isJsonArray(from)) {
75
+ return (0, ts_utils_1.succeed)('array');
76
+ }
77
+ return (0, ts_utils_1.fail)(`Invalid JSON: ${from}`);
78
+ }
79
+ exports.classifyJsonValue = classifyJsonValue;
80
+ /**
81
+ * Picks a nested field from a supplied {@link JsonObject | JsonObject}.
82
+ * @param src - The {@link JsonObject | object} from which the field is to be picked.
83
+ * @param path - Dot-separated path of the member to be picked.
84
+ * @returns `Success` with the property if the path is valid, `Failure`
85
+ * with an error message otherwise.
86
+ * @public
87
+ */
88
+ function pickJsonValue(src, path) {
89
+ let result = src;
90
+ for (const part of path.split('.')) {
91
+ if (result && isJsonObject(result)) {
92
+ result = result[part];
93
+ if (result === undefined) {
94
+ return (0, ts_utils_1.fail)(`${path}: child '${part}' does not exist`);
95
+ }
96
+ }
97
+ else {
98
+ return (0, ts_utils_1.fail)(`${path}: child '${part}' does not exist`);
99
+ }
100
+ }
101
+ return (0, ts_utils_1.succeed)(result);
102
+ }
103
+ exports.pickJsonValue = pickJsonValue;
104
+ /**
105
+ * Picks a nested {@link JsonObject | JsonObject} from a supplied
106
+ * {@link JsonObject | JsonObject}.
107
+ * @param src - The {@link JsonObject | object} from which the field is
108
+ * to be picked.
109
+ * @param path - Dot-separated path of the member to be picked.
110
+ * @returns `Success` with the property if the path is valid and the value
111
+ * is an object. Returns `Failure` with details if an error occurs.
112
+ * @public
113
+ */
114
+ function pickJsonObject(src, path) {
115
+ return pickJsonValue(src, path).onSuccess((v) => {
116
+ if (!isJsonObject(v)) {
117
+ return (0, ts_utils_1.fail)(`${path}: not an object`);
118
+ }
119
+ return (0, ts_utils_1.succeed)(v);
120
+ });
121
+ }
122
+ exports.pickJsonObject = pickJsonObject;
123
+ //# sourceMappingURL=common.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"common.js","sourceRoot":"","sources":["../../../src/packlets/json/common.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAEH,4CAAsD;AAyCtD;;;;;;GAMG;AACH,SAAgB,eAAe,CAAC,IAAa;IAC3C,OAAO,OAAO,IAAI,KAAK,SAAS,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI,CAAC;AAC5G,CAAC;AAFD,0CAEC;AAED;;;;;;GAMG;AACH,SAAgB,YAAY,CAAC,IAAa;IACxC,OAAO,CACL,OAAO,IAAI,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,YAAY,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,YAAY,IAAI,CAAC,CACzG,CAAC;AACJ,CAAC;AAJD,oCAIC;AAED;;;;;;GAMG;AACH,SAAgB,WAAW,CAAC,IAAa;IACvC,OAAO,OAAO,IAAI,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;AACzD,CAAC;AAFD,kCAEC;AAED;;;;;;;GAOG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C,YAAY,CAAC,CAAC,CAAC,EAAE,CAAC;YACrB,OAAO,IAAA,eAAI,EAAC,GAAG,IAAI,iBAAiB,CAAC,CAAC;QACxC,CAAC;QACD,OAAO,IAAA,kBAAO,EAAC,CAAC,CAAC,CAAC;IACpB,CAAC,CAAC,CAAC;AACL,CAAC;AAPD,wCAOC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Result, fail, succeed } from '@fgv/ts-utils';\n\n/* eslint-disable no-use-before-define */\n\n/**\n * Primitive (terminal) values allowed in by JSON.\n * @public\n */\n// eslint-disable-next-line @rushstack/no-new-null\nexport type JsonPrimitive = boolean | number | string | null;\n\n/**\n * A {@link JsonObject | JsonObject} is a string-keyed object\n * containing only valid {@link JsonValue | JSON values}.\n * @public\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport interface JsonObject {\n [key: string]: JsonValue;\n}\n\n/**\n * A {@link JsonValue | JsonValue} is one of: a {@link JsonPrimitive | JsonPrimitive},\n * a {@link JsonObject | JsonObject} or an {@link JsonArray | JsonArray}.\n * @public\n */\nexport type JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * A {@link JsonArray | JsonArray} is an array containing only valid {@link JsonValue | JsonValues}.\n * @public\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-interface, @typescript-eslint/naming-convention\nexport interface JsonArray extends Array<JsonValue> {}\n\n/**\n * Classes of {@link JsonValue | JsonValue}.\n * @public\n */\nexport type JsonValueType = 'primitive' | 'object' | 'array';\n\n/**\n * Test if an `unknown` is a {@link JsonValue | JsonValue}.\n * @param from - The `unknown` to be tested\n * @returns `true` if the supplied parameter is a valid {@link JsonPrimitive | JsonPrimitive},\n * `false` otherwise.\n * @public\n */\nexport function isJsonPrimitive(from: unknown): from is JsonPrimitive {\n return typeof from === 'boolean' || typeof from === 'number' || typeof from === 'string' || from === null;\n}\n\n/**\n * Test if an `unknown` is potentially a {@link JsonObject | JsonObject}.\n * @param from - The `unknown` to be tested.\n * @returns `true` if the supplied parameter is a non-array, non-special object,\n * `false` otherwise.\n * @public\n */\nexport function isJsonObject(from: unknown): from is JsonObject {\n return (\n typeof from === 'object' && !Array.isArray(from) && !(from instanceof RegExp) && !(from instanceof Date)\n );\n}\n\n/**\n * Test if an `unknown` is potentially a {@link JsonArray | JsonArray}.\n * @param from - The `unknown` to be tested.\n * @returns `true` if the supplied parameter is an array object,\n * `false` otherwise.\n * @public\n */\nexport function isJsonArray(from: unknown): from is JsonArray {\n return typeof from === 'object' && Array.isArray(from);\n}\n\n/**\n * Identifies whether some `unknown` value is a {@link JsonPrimitive | primitive},\n * {@link JsonObject | object} or {@link JsonArray | array}. Fails for any value\n * that cannot be converted to JSON (e.g. a function) _but_ this is a shallow test -\n * it does not test the properties of an object or elements in an array.\n * @param from - The `unknown` value to be tested\n * @public\n */\nexport function classifyJsonValue(from: unknown): Result<JsonValueType> {\n if (isJsonPrimitive(from)) {\n return succeed('primitive');\n } else if (isJsonObject(from)) {\n return succeed('object');\n } else if (isJsonArray(from)) {\n return succeed('array');\n }\n return fail(`Invalid JSON: ${from}`);\n}\n\n/**\n * Picks a nested field from a supplied {@link JsonObject | JsonObject}.\n * @param src - The {@link JsonObject | object} from which the field is to be picked.\n * @param path - Dot-separated path of the member to be picked.\n * @returns `Success` with the property if the path is valid, `Failure`\n * with an error message otherwise.\n * @public\n */\nexport function pickJsonValue(src: JsonObject, path: string): Result<JsonValue> {\n let result: JsonValue = src;\n for (const part of path.split('.')) {\n if (result && isJsonObject(result)) {\n result = result[part];\n if (result === undefined) {\n return fail(`${path}: child '${part}' does not exist`);\n }\n } else {\n return fail(`${path}: child '${part}' does not exist`);\n }\n }\n return succeed(result);\n}\n\n/**\n * Picks a nested {@link JsonObject | JsonObject} from a supplied\n * {@link JsonObject | JsonObject}.\n * @param src - The {@link JsonObject | object} from which the field is\n * to be picked.\n * @param path - Dot-separated path of the member to be picked.\n * @returns `Success` with the property if the path is valid and the value\n * is an object. Returns `Failure` with details if an error occurs.\n * @public\n */\nexport function pickJsonObject(src: JsonObject, path: string): Result<JsonObject> {\n return pickJsonValue(src, path).onSuccess((v) => {\n if (!isJsonObject(v)) {\n return fail(`${path}: not an object`);\n }\n return succeed(v);\n });\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export * from './common';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/packlets/json/index.ts"],"names":[],"mappings":"AAsBA,cAAc,UAAU,CAAC"}
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) 2020 Erik Fortune
4
+ *
5
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ * of this software and associated documentation files (the "Software"), to deal
7
+ * in the Software without restriction, including without limitation the rights
8
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ * copies of the Software, and to permit persons to whom the Software is
10
+ * furnished to do so, subject to the following conditions:
11
+ *
12
+ * The above copyright notice and this permission notice shall be included in all
13
+ * copies or substantial portions of the Software.
14
+ *
15
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ * SOFTWARE.
22
+ */
23
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
24
+ if (k2 === undefined) k2 = k;
25
+ var desc = Object.getOwnPropertyDescriptor(m, k);
26
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
27
+ desc = { enumerable: true, get: function() { return m[k]; } };
28
+ }
29
+ Object.defineProperty(o, k2, desc);
30
+ }) : (function(o, m, k, k2) {
31
+ if (k2 === undefined) k2 = k;
32
+ o[k2] = m[k];
33
+ }));
34
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
35
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
36
+ };
37
+ Object.defineProperty(exports, "__esModule", { value: true });
38
+ __exportStar(require("./common"), exports);
39
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/json/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;;;;;;;;;;;;;;AAEH,2CAAyB","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nexport * from './common';\n"]}
@@ -0,0 +1,83 @@
1
+ import { Converter, Result } from '@fgv/ts-utils';
2
+ import { JsonValue } from '../json';
3
+ /**
4
+ * Convenience function to read type-safe JSON from a file
5
+ * @param srcPath - Path of the file to read
6
+ * @returns `Success` with a {@link JsonValue | JsonValue} or `Failure`
7
+ * with a message if an error occurs.
8
+ * @public
9
+ */
10
+ export declare function readJsonFileSync(srcPath: string): Result<JsonValue>;
11
+ /**
12
+ * Convenience function to read a JSON file and apply a supplied converter.
13
+ * @param srcPath - Path of the file to read.
14
+ * @param converter - `Converter` used to convert the file contents
15
+ * @returns `Success` with a result of type `<T>`, or `Failure`
16
+ * with a message if an error occurs.
17
+ * @public
18
+ */
19
+ export declare function convertJsonFileSync<T>(srcPath: string, converter: Converter<T>): Result<T>;
20
+ /**
21
+ * Options for directory conversion.
22
+ * TODO: add filtering, allowed and excluded.
23
+ * @public
24
+ */
25
+ export interface IDirectoryConvertOptions<T, TC = unknown> {
26
+ /**
27
+ * The converter used to convert incoming JSON objects.
28
+ */
29
+ converter: Converter<T, TC>;
30
+ }
31
+ /**
32
+ * Return value for one item in a directory conversion.
33
+ * @public
34
+ */
35
+ export interface IReadDirectoryItem<T> {
36
+ /**
37
+ * Relative name of the file that was processed
38
+ */
39
+ filename: string;
40
+ /**
41
+ * The payload of the file.
42
+ */
43
+ item: T;
44
+ }
45
+ /**
46
+ * Reads all JSON files from a directory and apply a supplied converter.
47
+ * @param srcPath - The path of the folder to be read.
48
+ * @param options - {@link Files.IDirectoryConvertOptions | Options} to control
49
+ * conversion and filtering
50
+ * @public
51
+ */
52
+ export declare function convertJsonDirectorySync<T>(srcPath: string, options: IDirectoryConvertOptions<T>): Result<IReadDirectoryItem<T>[]>;
53
+ /**
54
+ * Function to transform the name of a some entity, given an original name
55
+ * and the contents of the entity.
56
+ * @public
57
+ */
58
+ export type ItemNameTransformFunction<T> = (name: string, item: T) => Result<string>;
59
+ /**
60
+ * Options controlling conversion of a directory.
61
+ * @public
62
+ */
63
+ export interface IDirectoryToMapConvertOptions<T, TC = unknown> extends IDirectoryConvertOptions<T, TC> {
64
+ transformName?: ItemNameTransformFunction<T>;
65
+ }
66
+ /**
67
+ * Reads and converts all JSON files from a directory, returning a
68
+ * `Map<string, T>` indexed by file base name (i.e. minus the extension)
69
+ * with an optional name transformation applied if present.
70
+ * @param srcPath - The path of the folder to be read.
71
+ * @param options - {@link Files.IDirectoryToMapConvertOptions | Options} to control conversion,
72
+ * filtering and naming.
73
+ * @public
74
+ */
75
+ export declare function convertJsonDirectoryToMapSync<T, TC = unknown>(srcPath: string, options: IDirectoryToMapConvertOptions<T, TC>): Result<Map<string, T>>;
76
+ /**
77
+ * Convenience function to write type-safe JSON to a file.
78
+ * @param srcPath - Path of the file to write.
79
+ * @param value - The {@link JsonValue | JsonValue} to be written.
80
+ * @public
81
+ */
82
+ export declare function writeJsonFileSync(srcPath: string, value: JsonValue): Result<boolean>;
83
+ //# sourceMappingURL=file.d.ts.map
@@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E,yBAAyB,CAAC,CAAC,CAAC,CAAC;CAC9C;AAWD;;;;;;;;GAQG;AACH,wBAAgB,6BAA6B,CAAC,CAAC,EAAE,EAAE,GAAG,OAAO,EAC3D,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,6BAA6B,CAAC,CAAC,EAAE,EAAE,CAAC,GAC5C,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,CAcxB;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,CAMpF"}
@@ -0,0 +1,162 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) 2020 Erik Fortune
4
+ *
5
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ * of this software and associated documentation files (the "Software"), to deal
7
+ * in the Software without restriction, including without limitation the rights
8
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ * copies of the Software, and to permit persons to whom the Software is
10
+ * furnished to do so, subject to the following conditions:
11
+ *
12
+ * The above copyright notice and this permission notice shall be included in all
13
+ * copies or substantial portions of the Software.
14
+ *
15
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ * SOFTWARE.
22
+ */
23
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
24
+ if (k2 === undefined) k2 = k;
25
+ var desc = Object.getOwnPropertyDescriptor(m, k);
26
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
27
+ desc = { enumerable: true, get: function() { return m[k]; } };
28
+ }
29
+ Object.defineProperty(o, k2, desc);
30
+ }) : (function(o, m, k, k2) {
31
+ if (k2 === undefined) k2 = k;
32
+ o[k2] = m[k];
33
+ }));
34
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
35
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
36
+ }) : function(o, v) {
37
+ o["default"] = v;
38
+ });
39
+ var __importStar = (this && this.__importStar) || function (mod) {
40
+ if (mod && mod.__esModule) return mod;
41
+ var result = {};
42
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
43
+ __setModuleDefault(result, mod);
44
+ return result;
45
+ };
46
+ Object.defineProperty(exports, "__esModule", { value: true });
47
+ exports.writeJsonFileSync = exports.convertJsonDirectoryToMapSync = exports.convertJsonDirectorySync = exports.convertJsonFileSync = exports.readJsonFileSync = void 0;
48
+ const ts_utils_1 = require("@fgv/ts-utils");
49
+ const fs = __importStar(require("fs"));
50
+ const path = __importStar(require("path"));
51
+ /**
52
+ * Convenience function to read type-safe JSON from a file
53
+ * @param srcPath - Path of the file to read
54
+ * @returns `Success` with a {@link JsonValue | JsonValue} or `Failure`
55
+ * with a message if an error occurs.
56
+ * @public
57
+ */
58
+ function readJsonFileSync(srcPath) {
59
+ return (0, ts_utils_1.captureResult)(() => {
60
+ const fullPath = path.resolve(srcPath);
61
+ const body = fs.readFileSync(fullPath, 'utf8').toString();
62
+ return JSON.parse(body);
63
+ });
64
+ }
65
+ exports.readJsonFileSync = readJsonFileSync;
66
+ /**
67
+ * Convenience function to read a JSON file and apply a supplied converter.
68
+ * @param srcPath - Path of the file to read.
69
+ * @param converter - `Converter` used to convert the file contents
70
+ * @returns `Success` with a result of type `<T>`, or `Failure`
71
+ * with a message if an error occurs.
72
+ * @public
73
+ */
74
+ function convertJsonFileSync(srcPath, converter) {
75
+ return readJsonFileSync(srcPath).onSuccess((json) => {
76
+ return converter.convert(json);
77
+ });
78
+ }
79
+ exports.convertJsonFileSync = convertJsonFileSync;
80
+ /**
81
+ * Reads all JSON files from a directory and apply a supplied converter.
82
+ * @param srcPath - The path of the folder to be read.
83
+ * @param options - {@link Files.IDirectoryConvertOptions | Options} to control
84
+ * conversion and filtering
85
+ * @public
86
+ */
87
+ function convertJsonDirectorySync(srcPath, options) {
88
+ return (0, ts_utils_1.captureResult)(() => {
89
+ const fullPath = path.resolve(srcPath);
90
+ if (!fs.statSync(fullPath).isDirectory()) {
91
+ throw new Error(`${fullPath}: Not a directory`);
92
+ }
93
+ const files = fs.readdirSync(fullPath, { withFileTypes: true });
94
+ const results = files
95
+ .map((fi) => {
96
+ if (fi.isFile() && path.extname(fi.name) === '.json') {
97
+ const filePath = path.resolve(fullPath, fi.name);
98
+ return convertJsonFileSync(filePath, options.converter)
99
+ .onSuccess((payload) => {
100
+ return (0, ts_utils_1.succeed)({
101
+ filename: fi.name,
102
+ item: payload
103
+ });
104
+ })
105
+ .onFailure((message) => {
106
+ return (0, ts_utils_1.fail)(`${fi.name}: ${message}`);
107
+ });
108
+ }
109
+ return undefined;
110
+ })
111
+ .filter((r) => r !== undefined);
112
+ return (0, ts_utils_1.mapResults)(results).orThrow();
113
+ });
114
+ }
115
+ exports.convertJsonDirectorySync = convertJsonDirectorySync;
116
+ /**
117
+ * Function to transform the name of some entity, given only a previous name. This
118
+ * default implementation always returns `Success` with the value that was passed in.
119
+ * @param n - The name to be transformed.
120
+ * @returns - `Success` with the string that was passed in.
121
+ * @public
122
+ */
123
+ const defaultNameTransformer = (n) => (0, ts_utils_1.succeed)(n);
124
+ /**
125
+ * Reads and converts all JSON files from a directory, returning a
126
+ * `Map<string, T>` indexed by file base name (i.e. minus the extension)
127
+ * with an optional name transformation applied if present.
128
+ * @param srcPath - The path of the folder to be read.
129
+ * @param options - {@link Files.IDirectoryToMapConvertOptions | Options} to control conversion,
130
+ * filtering and naming.
131
+ * @public
132
+ */
133
+ function convertJsonDirectoryToMapSync(srcPath, options) {
134
+ return convertJsonDirectorySync(srcPath, options).onSuccess((items) => {
135
+ var _a;
136
+ const transformName = (_a = options.transformName) !== null && _a !== void 0 ? _a : defaultNameTransformer;
137
+ return (0, ts_utils_1.mapResults)(items.map((item) => {
138
+ const basename = path.basename(item.filename, '.json');
139
+ return transformName(basename, item.item).onSuccess((name) => {
140
+ return (0, ts_utils_1.succeed)([name, item.item]);
141
+ });
142
+ })).onSuccess((items) => {
143
+ return (0, ts_utils_1.succeed)(new Map(items));
144
+ });
145
+ });
146
+ }
147
+ exports.convertJsonDirectoryToMapSync = convertJsonDirectoryToMapSync;
148
+ /**
149
+ * Convenience function to write type-safe JSON to a file.
150
+ * @param srcPath - Path of the file to write.
151
+ * @param value - The {@link JsonValue | JsonValue} to be written.
152
+ * @public
153
+ */
154
+ function writeJsonFileSync(srcPath, value) {
155
+ return (0, ts_utils_1.captureResult)(() => {
156
+ const fullPath = path.resolve(srcPath);
157
+ fs.writeFileSync(fullPath, JSON.stringify(value, undefined, 2));
158
+ return true;
159
+ });
160
+ }
161
+ exports.writeJsonFileSync = writeJsonFileSync;
162
+ //# sourceMappingURL=file.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file.js","sourceRoot":"","sources":["../../../src/packlets/json-file/file.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,4CAA4F;AAC5F,uCAAyB;AACzB,2CAA6B;AAI7B;;;;;;GAMG;AACH,SAAgB,gBAAgB,CAAC,OAAe;IAC9C,OAAO,IAAA,wBAAa,EAAC,GAAG,EAAE;QACxB,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QACvC,MAAM,IAAI,GAAG,EAAE,CAAC,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CAAC,CAAC,CAAC;YACjD,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CACH,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,OAAO,IAAA,kBAAO,EAAC,IAAI,GAAG,CAAY,KAAK,CAAC,CAAC,CAAC;QAC5C,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AAjBD,sEAiBC;AAED;;;;;GAKG;AACH,SAAgB,iBAAiB,CAAC,OAAe,EAAE,KAAgB;IACjE,OAAO,IAAA,wBAAa,EAAC,GAAG,EAAE;QACxB,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QACvC,EAAE,CAAC,aAAa,CAAC,QAAQ,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,CAAC;QAChE,OAAO,IAAI,CAAC;IACd,CAAC,CAAC,CAAC;AACL,CAAC;AAND,8CAMC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Converter, Result, captureResult, fail, mapResults, succeed } from '@fgv/ts-utils';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nimport { JsonValue } from '../json';\n\n/**\n * Convenience function to read type-safe JSON from a file\n * @param srcPath - Path of the file to read\n * @returns `Success` with a {@link JsonValue | JsonValue} or `Failure`\n * with a message if an error occurs.\n * @public\n */\nexport function readJsonFileSync(srcPath: string): Result<JsonValue> {\n return captureResult(() => {\n const fullPath = path.resolve(srcPath);\n const body = fs.readFileSync(fullPath, 'utf8').toString();\n return JSON.parse(body) as JsonValue;\n });\n}\n\n/**\n * Convenience function to read a JSON file and apply a supplied converter.\n * @param srcPath - Path of the file to read.\n * @param converter - `Converter` used to convert the file contents\n * @returns `Success` with a result of type `<T>`, or `Failure`\n * with a message if an error occurs.\n * @public\n */\nexport function convertJsonFileSync<T>(srcPath: string, converter: Converter<T>): Result<T> {\n return readJsonFileSync(srcPath).onSuccess((json) => {\n return converter.convert(json);\n });\n}\n\n/**\n * Options for directory conversion.\n * TODO: add filtering, allowed and excluded.\n * @public\n */\nexport interface IDirectoryConvertOptions<T, TC = unknown> {\n /**\n * The converter used to convert incoming JSON objects.\n */\n converter: Converter<T, TC>;\n}\n\n/**\n * Return value for one item in a directory conversion.\n * @public\n */\nexport interface IReadDirectoryItem<T> {\n /**\n * Relative name of the file that was processed\n */\n filename: string;\n\n /**\n * The payload of the file.\n */\n item: T;\n}\n\n/**\n * Reads all JSON files from a directory and apply a supplied converter.\n * @param srcPath - The path of the folder to be read.\n * @param options - {@link Files.IDirectoryConvertOptions | Options} to control\n * conversion and filtering\n * @public\n */\nexport function convertJsonDirectorySync<T>(\n srcPath: string,\n options: IDirectoryConvertOptions<T>\n): Result<IReadDirectoryItem<T>[]> {\n return captureResult<IReadDirectoryItem<T>[]>(() => {\n const fullPath = path.resolve(srcPath);\n if (!fs.statSync(fullPath).isDirectory()) {\n throw new Error(`${fullPath}: Not a directory`);\n }\n const files = fs.readdirSync(fullPath, { withFileTypes: true });\n const results = files\n .map((fi) => {\n if (fi.isFile() && path.extname(fi.name) === '.json') {\n const filePath = path.resolve(fullPath, fi.name);\n return convertJsonFileSync(filePath, options.converter)\n .onSuccess((payload) => {\n return succeed({\n filename: fi.name,\n item: payload\n });\n })\n .onFailure((message) => {\n return fail(`${fi.name}: ${message}`);\n });\n }\n return undefined;\n })\n .filter((r): r is Result<IReadDirectoryItem<T>> => r !== undefined);\n return mapResults(results).orThrow();\n });\n}\n\n/**\n * Function to transform the name of a some entity, given an original name\n * and the contents of the entity.\n * @public\n */\nexport type ItemNameTransformFunction<T> = (name: string, item: T) => Result<string>;\n\n/**\n * Options controlling conversion of a directory.\n * @public\n */\nexport interface IDirectoryToMapConvertOptions<T, TC = unknown> extends IDirectoryConvertOptions<T, TC> {\n transformName?: ItemNameTransformFunction<T>;\n}\n\n/**\n * Function to transform the name of some entity, given only a previous name. This\n * default implementation always returns `Success` with the value that was passed in.\n * @param n - The name to be transformed.\n * @returns - `Success` with the string that was passed in.\n * @public\n */\nconst defaultNameTransformer = (n: string): Result<string> => succeed(n);\n\n/**\n * Reads and converts all JSON files from a directory, returning a\n * `Map<string, T>` indexed by file base name (i.e. minus the extension)\n * with an optional name transformation applied if present.\n * @param srcPath - The path of the folder to be read.\n * @param options - {@link Files.IDirectoryToMapConvertOptions | Options} to control conversion,\n * filtering and naming.\n * @public\n */\nexport function convertJsonDirectoryToMapSync<T, TC = unknown>(\n srcPath: string,\n options: IDirectoryToMapConvertOptions<T, TC>\n): Result<Map<string, T>> {\n return convertJsonDirectorySync(srcPath, options).onSuccess((items) => {\n const transformName = options.transformName ?? defaultNameTransformer;\n return mapResults(\n items.map((item) => {\n const basename = path.basename(item.filename, '.json');\n return transformName(basename, item.item).onSuccess((name) => {\n return succeed<[string, T]>([name, item.item]);\n });\n })\n ).onSuccess((items) => {\n return succeed(new Map<string, T>(items));\n });\n });\n}\n\n/**\n * Convenience function to write type-safe JSON to a file.\n * @param srcPath - Path of the file to write.\n * @param value - The {@link JsonValue | JsonValue} to be written.\n * @public\n */\nexport function writeJsonFileSync(srcPath: string, value: JsonValue): Result<boolean> {\n return captureResult(() => {\n const fullPath = path.resolve(srcPath);\n fs.writeFileSync(fullPath, JSON.stringify(value, undefined, 2));\n return true;\n });\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export * from './file';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/packlets/json-file/index.ts"],"names":[],"mappings":"AAsBA,cAAc,QAAQ,CAAC"}