This repository has been archived by the owner on Jan 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 477
/
ExpSchema.ts
80 lines (71 loc) · 2.39 KB
/
ExpSchema.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
import * as ConfigUtils from '@expo/config';
import Schemer from '@expo/schemer';
import fs from 'fs';
import path from 'path';
import Api from '../Api';
export type Schema = any;
export type AssetSchema = { schema: Schema; fieldPath: string };
let _xdlSchemaJson: { [sdkVersion: string]: Schema } = {};
export async function validatorFromProjectRoot(projectRoot: string): Promise<Schemer> {
const { exp } = await ConfigUtils.readConfigJsonAsync(projectRoot);
if (!exp.sdkVersion) throw new Error(`Couldn't read local manifest`);
const schema = await getSchemaAsync(exp.sdkVersion);
const validator = new Schemer(schema);
return validator;
}
export async function getSchemaAsync(sdkVersion: string): Promise<Schema> {
let json = await _getSchemaJSONAsync(sdkVersion);
return json.schema;
}
// Array of schema nodes that refer to assets along with their field
// path (eg. 'notification.icon')
export async function getAssetSchemasAsync(sdkVersion: string): Promise<AssetSchema[]> {
const schema = await getSchemaAsync(sdkVersion);
const assetSchemas: AssetSchema[] = [];
const visit = (node: Schema, fieldPath: string) => {
if (node.meta && node.meta.asset) {
assetSchemas.push({ schema: node, fieldPath });
}
const properties = node.properties;
if (properties) {
Object.keys(properties).forEach(property =>
visit(properties[property], `${fieldPath}${fieldPath.length > 0 ? '.' : ''}${property}`)
);
}
};
visit(schema, '');
return assetSchemas;
}
async function _getSchemaJSONAsync(sdkVersion: string): Promise<{ schema: Schema }> {
if (process.env.LOCAL_XDL_SCHEMA) {
if (process.env.EXPONENT_UNIVERSE_DIR) {
return JSON.parse(
fs
.readFileSync(
path.join(
process.env.EXPONENT_UNIVERSE_DIR,
'server',
'www',
'xdl-schemas',
'UNVERSIONED-schema.json'
)
)
.toString()
);
} else {
throw new Error(`LOCAL_XDL_SCHEMA is set but EXPONENT_UNIVERSE_DIR is not.`);
}
}
if (!_xdlSchemaJson[sdkVersion]) {
try {
_xdlSchemaJson[sdkVersion] = await Api.xdlSchemaAsync(sdkVersion);
} catch (e) {
if (e.code && e.code === 'INVALID_JSON') {
throw new Error(`Couldn't read schema from server`);
} else {
throw e;
}
}
}
return _xdlSchemaJson[sdkVersion];
}