-
-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathaction-utils.ts
More file actions
286 lines (253 loc) · 9.32 KB
/
action-utils.ts
File metadata and controls
286 lines (253 loc) · 9.32 KB
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
import { type ZModelServices, loadDocument } from '@zenstackhq/language';
import { type Model, isDataSource } from '@zenstackhq/language/ast';
import { PrismaSchemaGenerator } from '@zenstackhq/sdk';
import colors from 'colors';
import fs from 'node:fs';
import { createRequire } from 'node:module';
import path from 'node:path';
import { CliError } from '../cli-error';
import terminalLink from 'terminal-link';
import { z } from 'zod';
export function getSchemaFile(file?: string) {
if (file) {
if (!fs.existsSync(file)) {
throw new CliError(`Schema file not found: ${file}`);
}
return file;
}
const pkgJsonConfig = getPkgJsonConfig(process.cwd());
if (pkgJsonConfig.schema) {
if (!fs.existsSync(pkgJsonConfig.schema)) {
throw new CliError(`Schema file not found: ${pkgJsonConfig.schema}`);
}
if (fs.statSync(pkgJsonConfig.schema).isDirectory()) {
const schemaPath = path.join(pkgJsonConfig.schema, 'schema.zmodel');
if (!fs.existsSync(schemaPath)) {
throw new CliError(`Schema file not found: ${schemaPath}`);
}
return schemaPath;
} else {
return pkgJsonConfig.schema;
}
}
if (fs.existsSync('./schema.zmodel')) {
return './schema.zmodel';
} else if (fs.existsSync('./zenstack/schema.zmodel')) {
return './zenstack/schema.zmodel';
} else {
throw new CliError(
'Schema file not found in default locations ("./schema.zmodel" or "./zenstack/schema.zmodel").',
);
}
}
export async function loadSchemaDocument(
schemaFile: string,
opts?: { mergeImports?: boolean; returnServices?: false },
): Promise<Model>;
export async function loadSchemaDocument(
schemaFile: string,
opts: { returnServices: true; mergeImports?: boolean },
): Promise<{ model: Model; services: ZModelServices }>;
export async function loadSchemaDocument(
schemaFile: string,
opts: { returnServices?: boolean; mergeImports?: boolean } = {},
) {
const returnServices = opts.returnServices ?? false;
const mergeImports = opts.mergeImports ?? true;
const loadResult = await loadDocument(schemaFile, [], mergeImports);
if (!loadResult.success) {
loadResult.errors.forEach((err) => {
console.error(colors.red(err));
});
throw new CliError('Schema contains errors. See above for details.');
}
loadResult.warnings.forEach((warn) => {
console.warn(colors.yellow(warn));
});
if (returnServices) return { model: loadResult.model, services: loadResult.services };
return loadResult.model;
}
export function handleSubProcessError(err: unknown) {
if (err instanceof Error && 'status' in err && typeof err.status === 'number') {
process.exit(err.status);
} else {
process.exit(1);
}
}
export async function generateTempPrismaSchema(zmodelPath: string, folder?: string) {
const model = await loadSchemaDocument(zmodelPath);
if (!model.declarations.some(isDataSource)) {
throw new CliError('Schema must define a datasource');
}
const prismaSchema = await new PrismaSchemaGenerator(model).generate();
if (!folder) {
folder = path.dirname(zmodelPath);
}
const prismaSchemaFile = path.resolve(folder, '~schema.prisma');
fs.writeFileSync(prismaSchemaFile, prismaSchema);
return prismaSchemaFile;
}
export function getPkgJsonConfig(startPath: string) {
const result: { schema: string | undefined; output: string | undefined; seed: string | undefined } = {
schema: undefined,
output: undefined,
seed: undefined,
};
const pkgJsonFile = findUp(['package.json'], startPath, false);
if (!pkgJsonFile) {
return result;
}
let pkgJson: any = undefined;
try {
pkgJson = JSON.parse(fs.readFileSync(pkgJsonFile, 'utf8'));
} catch {
return result;
}
if (pkgJson.zenstack && typeof pkgJson.zenstack === 'object') {
result.schema =
pkgJson.zenstack.schema && typeof pkgJson.zenstack.schema === 'string'
? path.resolve(path.dirname(pkgJsonFile), pkgJson.zenstack.schema)
: undefined;
result.output =
pkgJson.zenstack.output && typeof pkgJson.zenstack.output === 'string'
? path.resolve(path.dirname(pkgJsonFile), pkgJson.zenstack.output)
: undefined;
result.seed =
typeof pkgJson.zenstack.seed === 'string' && pkgJson.zenstack.seed ? pkgJson.zenstack.seed : undefined;
}
return result;
}
type FindUpResult<Multiple extends boolean> = Multiple extends true ? string[] | undefined : string | undefined;
function findUp<Multiple extends boolean = false>(
names: string[],
cwd: string = process.cwd(),
multiple: Multiple = false as Multiple,
result: string[] = [],
): FindUpResult<Multiple> {
if (!names.some((name) => !!name)) {
return undefined;
}
const target = names.find((name) => fs.existsSync(path.join(cwd, name)));
if (multiple === false && target) {
return path.resolve(cwd, target) as FindUpResult<Multiple>;
}
if (target) {
result.push(path.resolve(cwd, target));
}
const up = path.resolve(cwd, '..');
if (up === cwd) {
return (multiple && result.length > 0 ? result : undefined) as FindUpResult<Multiple>;
}
return findUp(names, up, multiple, result);
}
export async function requireDataSourceUrl(schemaFile: string) {
const zmodel = await loadSchemaDocument(schemaFile);
const dataSource = zmodel.declarations.find(isDataSource);
if (!dataSource?.fields.some((f) => f.name === 'url')) {
throw new CliError('The schema\'s "datasource" must have a "url" field to use this command.');
}
}
export function getOutputPath(options: { output?: string }, schemaFile: string) {
if (options.output) {
return options.output;
}
const pkgJsonConfig = getPkgJsonConfig(process.cwd());
if (pkgJsonConfig.output) {
return pkgJsonConfig.output;
} else {
return path.dirname(schemaFile);
}
}
export async function getZenStackPackages(
searchPath: string,
): Promise<Array<{ pkg: string; version: string | undefined }>> {
const pkgJsonFile = findUp(['package.json'], searchPath, false);
if (!pkgJsonFile) {
return [];
}
let pkgJson: {
dependencies?: Record<string, unknown>;
devDependencies?: Record<string, unknown>;
};
try {
pkgJson = JSON.parse(fs.readFileSync(pkgJsonFile, 'utf8'));
} catch {
return [];
}
const packages = Array.from(
new Set(
[...Object.keys(pkgJson.dependencies ?? {}), ...Object.keys(pkgJson.devDependencies ?? {})].filter((p) =>
p.startsWith('@zenstackhq/'),
),
),
).sort();
const require = createRequire(pkgJsonFile);
const result = packages.map((pkg) => {
try {
const depPkgJson = require(`${pkg}/package.json`);
if (depPkgJson.private) {
return undefined;
}
return { pkg, version: depPkgJson.version as string };
} catch {
return { pkg, version: undefined };
}
});
return result.filter((p) => !!p);
}
const FETCH_CLI_MAX_TIME = 1000;
const CLI_CONFIG_ENDPOINT = 'https://zenstack.dev/config/cli-v3.json';
const usageTipsSchema = z.object({
notifications: z.array(z.object({ title: z.string(), url: z.url().optional(), active: z.boolean() })),
});
/**
* Starts the usage tips fetch in the background. Returns a callback that, when invoked check if the fetch
* is complete. If not complete, it will wait until the max time is reached. After that, if fetch is still
* not complete, just return.
*/
export function startUsageTipsFetch() {
let fetchedData: z.infer<typeof usageTipsSchema> | undefined = undefined;
let fetchComplete = false;
const start = Date.now();
const controller = new AbortController();
fetch(CLI_CONFIG_ENDPOINT, {
headers: { accept: 'application/json' },
signal: controller.signal,
})
.then(async (res) => {
if (!res.ok) return;
const data = await res.json();
const parseResult = usageTipsSchema.safeParse(data);
if (parseResult.success) {
fetchedData = parseResult.data;
}
})
.catch(() => {
// noop
})
.finally(() => {
fetchComplete = true;
});
return async () => {
const elapsed = Date.now() - start;
if (!fetchComplete && elapsed < FETCH_CLI_MAX_TIME) {
// wait for the timeout
await new Promise((resolve) => setTimeout(resolve, FETCH_CLI_MAX_TIME - elapsed));
}
if (!fetchComplete) {
controller.abort();
return;
}
if (!fetchedData) return;
const activeItems = fetchedData.notifications.filter((item) => item.active);
// show a random active item
if (activeItems.length > 0) {
const item = activeItems[Math.floor(Math.random() * activeItems.length)]!;
if (item.url) {
console.log(terminalLink(item.title, item.url));
} else {
console.log(item.title);
}
}
};
}