This repository was archived by the owner on Mar 1, 2026. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathaction-utils.ts
More file actions
201 lines (181 loc) · 6.55 KB
/
action-utils.ts
File metadata and controls
201 lines (181 loc) · 6.55 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
import { loadDocument } from '@zenstackhq/language';
import { 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';
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) {
const loadResult = await loadDocument(schemaFile);
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));
});
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.join(cwd, target) as FindUpResult<Multiple>;
}
if (target) {
result.push(path.join(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(import.meta.url);
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);
}