@zenstackhq/testtools 3.0.0-beta.2 → 3.0.0-beta.21
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/dist/index.cjs +411 -17
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +35 -7
- package/dist/index.d.ts +35 -7
- package/dist/index.js +410 -16
- package/dist/index.js.map +1 -1
- package/dist/types.d.ts +16 -0
- package/package.json +18 -8
package/dist/index.d.cts
CHANGED
|
@@ -1,18 +1,46 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ClientOptions, ClientContract } from '@zenstackhq/orm';
|
|
2
|
+
import { SchemaDef } from '@zenstackhq/orm/schema';
|
|
3
|
+
import { LogEvent } from 'kysely';
|
|
4
|
+
import * as _zenstackhq_language_ast from '@zenstackhq/language/ast';
|
|
5
|
+
import { SchemaDef as SchemaDef$1 } from '@zenstackhq/schema';
|
|
2
6
|
|
|
3
|
-
declare function
|
|
7
|
+
declare function getTestDbProvider(): "sqlite" | "postgresql";
|
|
8
|
+
type CreateTestClientOptions<Schema extends SchemaDef> = Omit<ClientOptions<Schema>, 'dialect'> & {
|
|
9
|
+
provider?: 'sqlite' | 'postgresql';
|
|
10
|
+
schemaFile?: string;
|
|
11
|
+
dbName?: string;
|
|
12
|
+
usePrismaPush?: boolean;
|
|
13
|
+
extraSourceFiles?: Record<string, string>;
|
|
14
|
+
workDir?: string;
|
|
15
|
+
debug?: boolean;
|
|
16
|
+
dbFile?: string;
|
|
17
|
+
};
|
|
18
|
+
declare function createTestClient<Schema extends SchemaDef>(schema: Schema, options?: CreateTestClientOptions<Schema>): Promise<ClientContract<Schema>>;
|
|
19
|
+
declare function createTestClient<Schema extends SchemaDef>(schema: string, options?: CreateTestClientOptions<Schema>): Promise<any>;
|
|
20
|
+
declare function createPolicyTestClient<Schema extends SchemaDef>(schema: Schema, options?: CreateTestClientOptions<Schema>): Promise<ClientContract<Schema>>;
|
|
21
|
+
declare function createPolicyTestClient<Schema extends SchemaDef>(schema: string, options?: CreateTestClientOptions<Schema>): Promise<any>;
|
|
22
|
+
declare function testLogger(e: LogEvent): void;
|
|
4
23
|
|
|
5
|
-
declare function
|
|
24
|
+
declare function createTestProject(zmodelContent?: string): string;
|
|
25
|
+
|
|
26
|
+
declare function generateTsSchema(schemaText: string, provider?: 'sqlite' | 'postgresql', dbUrl?: string, extraSourceFiles?: Record<string, string>, withLiteSchema?: boolean): Promise<{
|
|
27
|
+
model: _zenstackhq_language_ast.Model;
|
|
6
28
|
workDir: string;
|
|
7
|
-
schema: SchemaDef;
|
|
29
|
+
schema: SchemaDef$1;
|
|
30
|
+
schemaLite: SchemaDef$1 | undefined;
|
|
8
31
|
}>;
|
|
9
32
|
declare function generateTsSchemaFromFile(filePath: string): Promise<{
|
|
33
|
+
model: _zenstackhq_language_ast.Model;
|
|
10
34
|
workDir: string;
|
|
11
|
-
schema: SchemaDef;
|
|
35
|
+
schema: SchemaDef$1;
|
|
36
|
+
schemaLite: SchemaDef$1 | undefined;
|
|
12
37
|
}>;
|
|
13
38
|
declare function generateTsSchemaInPlace(schemaPath: string): Promise<{
|
|
14
39
|
workDir: string;
|
|
15
|
-
schema: SchemaDef;
|
|
40
|
+
schema: SchemaDef$1;
|
|
41
|
+
schemaLite: SchemaDef$1 | undefined;
|
|
16
42
|
}>;
|
|
43
|
+
declare function loadSchema(schema: string, additionalSchemas?: Record<string, string>): Promise<_zenstackhq_language_ast.Model>;
|
|
44
|
+
declare function loadSchemaWithError(schema: string, error: string | RegExp): Promise<void>;
|
|
17
45
|
|
|
18
|
-
export { createTestProject, generateTsSchema, generateTsSchemaFromFile, generateTsSchemaInPlace };
|
|
46
|
+
export { type CreateTestClientOptions, createPolicyTestClient, createTestClient, createTestProject, generateTsSchema, generateTsSchemaFromFile, generateTsSchemaInPlace, getTestDbProvider, loadSchema, loadSchemaWithError, testLogger };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,18 +1,46 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ClientOptions, ClientContract } from '@zenstackhq/orm';
|
|
2
|
+
import { SchemaDef } from '@zenstackhq/orm/schema';
|
|
3
|
+
import { LogEvent } from 'kysely';
|
|
4
|
+
import * as _zenstackhq_language_ast from '@zenstackhq/language/ast';
|
|
5
|
+
import { SchemaDef as SchemaDef$1 } from '@zenstackhq/schema';
|
|
2
6
|
|
|
3
|
-
declare function
|
|
7
|
+
declare function getTestDbProvider(): "sqlite" | "postgresql";
|
|
8
|
+
type CreateTestClientOptions<Schema extends SchemaDef> = Omit<ClientOptions<Schema>, 'dialect'> & {
|
|
9
|
+
provider?: 'sqlite' | 'postgresql';
|
|
10
|
+
schemaFile?: string;
|
|
11
|
+
dbName?: string;
|
|
12
|
+
usePrismaPush?: boolean;
|
|
13
|
+
extraSourceFiles?: Record<string, string>;
|
|
14
|
+
workDir?: string;
|
|
15
|
+
debug?: boolean;
|
|
16
|
+
dbFile?: string;
|
|
17
|
+
};
|
|
18
|
+
declare function createTestClient<Schema extends SchemaDef>(schema: Schema, options?: CreateTestClientOptions<Schema>): Promise<ClientContract<Schema>>;
|
|
19
|
+
declare function createTestClient<Schema extends SchemaDef>(schema: string, options?: CreateTestClientOptions<Schema>): Promise<any>;
|
|
20
|
+
declare function createPolicyTestClient<Schema extends SchemaDef>(schema: Schema, options?: CreateTestClientOptions<Schema>): Promise<ClientContract<Schema>>;
|
|
21
|
+
declare function createPolicyTestClient<Schema extends SchemaDef>(schema: string, options?: CreateTestClientOptions<Schema>): Promise<any>;
|
|
22
|
+
declare function testLogger(e: LogEvent): void;
|
|
4
23
|
|
|
5
|
-
declare function
|
|
24
|
+
declare function createTestProject(zmodelContent?: string): string;
|
|
25
|
+
|
|
26
|
+
declare function generateTsSchema(schemaText: string, provider?: 'sqlite' | 'postgresql', dbUrl?: string, extraSourceFiles?: Record<string, string>, withLiteSchema?: boolean): Promise<{
|
|
27
|
+
model: _zenstackhq_language_ast.Model;
|
|
6
28
|
workDir: string;
|
|
7
|
-
schema: SchemaDef;
|
|
29
|
+
schema: SchemaDef$1;
|
|
30
|
+
schemaLite: SchemaDef$1 | undefined;
|
|
8
31
|
}>;
|
|
9
32
|
declare function generateTsSchemaFromFile(filePath: string): Promise<{
|
|
33
|
+
model: _zenstackhq_language_ast.Model;
|
|
10
34
|
workDir: string;
|
|
11
|
-
schema: SchemaDef;
|
|
35
|
+
schema: SchemaDef$1;
|
|
36
|
+
schemaLite: SchemaDef$1 | undefined;
|
|
12
37
|
}>;
|
|
13
38
|
declare function generateTsSchemaInPlace(schemaPath: string): Promise<{
|
|
14
39
|
workDir: string;
|
|
15
|
-
schema: SchemaDef;
|
|
40
|
+
schema: SchemaDef$1;
|
|
41
|
+
schemaLite: SchemaDef$1 | undefined;
|
|
16
42
|
}>;
|
|
43
|
+
declare function loadSchema(schema: string, additionalSchemas?: Record<string, string>): Promise<_zenstackhq_language_ast.Model>;
|
|
44
|
+
declare function loadSchemaWithError(schema: string, error: string | RegExp): Promise<void>;
|
|
17
45
|
|
|
18
|
-
export { createTestProject, generateTsSchema, generateTsSchemaFromFile, generateTsSchemaInPlace };
|
|
46
|
+
export { type CreateTestClientOptions, createPolicyTestClient, createTestClient, createTestProject, generateTsSchema, generateTsSchemaFromFile, generateTsSchemaInPlace, getTestDbProvider, loadSchema, loadSchemaWithError, testLogger };
|
package/dist/index.js
CHANGED
|
@@ -1,11 +1,31 @@
|
|
|
1
1
|
var __defProp = Object.defineProperty;
|
|
2
2
|
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
3
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
4
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
5
|
+
}) : x)(function(x) {
|
|
6
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
7
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
// src/client.ts
|
|
11
|
+
import { invariant as invariant2 } from "@zenstackhq/common-helpers";
|
|
12
|
+
import { ZenStackClient } from "@zenstackhq/orm";
|
|
13
|
+
import { PolicyPlugin } from "@zenstackhq/plugin-policy";
|
|
14
|
+
import { PrismaSchemaGenerator } from "@zenstackhq/sdk";
|
|
15
|
+
import SQLite from "better-sqlite3";
|
|
16
|
+
import { PostgresDialect, SqliteDialect } from "kysely";
|
|
17
|
+
import { execSync as execSync2 } from "child_process";
|
|
18
|
+
import { createHash } from "crypto";
|
|
19
|
+
import fs3 from "fs";
|
|
20
|
+
import path3 from "path";
|
|
21
|
+
import { Client as PGClient, Pool } from "pg";
|
|
22
|
+
import { expect as expect2 } from "vitest";
|
|
3
23
|
|
|
4
24
|
// src/project.ts
|
|
5
25
|
import fs from "fs";
|
|
6
26
|
import path from "path";
|
|
7
27
|
import tmp from "tmp";
|
|
8
|
-
function createTestProject() {
|
|
28
|
+
function createTestProject(zmodelContent) {
|
|
9
29
|
const { name: workDir } = tmp.dirSync({
|
|
10
30
|
unsafeCleanup: true
|
|
11
31
|
});
|
|
@@ -20,7 +40,7 @@ function createTestProject() {
|
|
|
20
40
|
const zenstackPackages = [
|
|
21
41
|
"language",
|
|
22
42
|
"sdk",
|
|
23
|
-
"
|
|
43
|
+
"orm",
|
|
24
44
|
"cli"
|
|
25
45
|
];
|
|
26
46
|
fs.mkdirSync(path.join(workDir, "node_modules/@zenstackhq"));
|
|
@@ -45,18 +65,35 @@ function createTestProject() {
|
|
|
45
65
|
"**/*.ts"
|
|
46
66
|
]
|
|
47
67
|
}, null, 4));
|
|
68
|
+
if (zmodelContent) {
|
|
69
|
+
fs.writeFileSync(path.join(workDir, "schema.zmodel"), zmodelContent);
|
|
70
|
+
}
|
|
48
71
|
return workDir;
|
|
49
72
|
}
|
|
50
73
|
__name(createTestProject, "createTestProject");
|
|
51
74
|
|
|
52
75
|
// src/schema.ts
|
|
53
|
-
import {
|
|
76
|
+
import { invariant } from "@zenstackhq/common-helpers";
|
|
54
77
|
import { TsSchemaGenerator } from "@zenstackhq/sdk";
|
|
55
|
-
import { glob } from "glob";
|
|
56
78
|
import { execSync } from "child_process";
|
|
79
|
+
import crypto from "crypto";
|
|
57
80
|
import fs2 from "fs";
|
|
81
|
+
import os from "os";
|
|
58
82
|
import path2 from "path";
|
|
59
83
|
import { match } from "ts-pattern";
|
|
84
|
+
import { expect } from "vitest";
|
|
85
|
+
|
|
86
|
+
// src/utils.ts
|
|
87
|
+
import { loadDocument } from "@zenstackhq/language";
|
|
88
|
+
function loadDocumentWithPlugins(filePath) {
|
|
89
|
+
const pluginModelFiles = [
|
|
90
|
+
__require.resolve("@zenstackhq/plugin-policy/plugin.zmodel")
|
|
91
|
+
];
|
|
92
|
+
return loadDocument(filePath, pluginModelFiles);
|
|
93
|
+
}
|
|
94
|
+
__name(loadDocumentWithPlugins, "loadDocumentWithPlugins");
|
|
95
|
+
|
|
96
|
+
// src/schema.ts
|
|
60
97
|
function makePrelude(provider, dbUrl) {
|
|
61
98
|
return match(provider).with("sqlite", () => {
|
|
62
99
|
return `
|
|
@@ -75,30 +112,40 @@ datasource db {
|
|
|
75
112
|
}).exhaustive();
|
|
76
113
|
}
|
|
77
114
|
__name(makePrelude, "makePrelude");
|
|
78
|
-
|
|
115
|
+
function replacePlaceholders(schemaText, provider, dbUrl) {
|
|
116
|
+
const url = dbUrl ?? (provider === "sqlite" ? "file:./test.db" : "postgres://postgres:postgres@localhost:5432/db");
|
|
117
|
+
return schemaText.replace(/\$DB_URL/g, url).replace(/\$PROVIDER/g, provider);
|
|
118
|
+
}
|
|
119
|
+
__name(replacePlaceholders, "replacePlaceholders");
|
|
120
|
+
async function generateTsSchema(schemaText, provider = "sqlite", dbUrl, extraSourceFiles, withLiteSchema) {
|
|
79
121
|
const workDir = createTestProject();
|
|
80
122
|
const zmodelPath = path2.join(workDir, "schema.zmodel");
|
|
81
123
|
const noPrelude = schemaText.includes("datasource ");
|
|
82
124
|
fs2.writeFileSync(zmodelPath, `${noPrelude ? "" : makePrelude(provider, dbUrl)}
|
|
83
125
|
|
|
84
|
-
${schemaText}`);
|
|
85
|
-
const
|
|
86
|
-
const result = await loadDocument(zmodelPath, pluginModelFiles);
|
|
126
|
+
${replacePlaceholders(schemaText, provider, dbUrl)}`);
|
|
127
|
+
const result = await loadDocumentWithPlugins(zmodelPath);
|
|
87
128
|
if (!result.success) {
|
|
88
129
|
throw new Error(`Failed to load schema from ${zmodelPath}: ${result.errors}`);
|
|
89
130
|
}
|
|
90
131
|
const generator = new TsSchemaGenerator();
|
|
91
|
-
await generator.generate(result.model,
|
|
132
|
+
await generator.generate(result.model, {
|
|
133
|
+
outDir: workDir,
|
|
134
|
+
lite: withLiteSchema
|
|
135
|
+
});
|
|
92
136
|
if (extraSourceFiles) {
|
|
93
137
|
for (const [fileName, content] of Object.entries(extraSourceFiles)) {
|
|
94
|
-
const filePath = path2.resolve(workDir, `${fileName}.ts`);
|
|
138
|
+
const filePath = path2.resolve(workDir, !fileName.endsWith(".ts") ? `${fileName}.ts` : fileName);
|
|
95
139
|
fs2.mkdirSync(path2.dirname(filePath), {
|
|
96
140
|
recursive: true
|
|
97
141
|
});
|
|
98
142
|
fs2.writeFileSync(filePath, content);
|
|
99
143
|
}
|
|
100
144
|
}
|
|
101
|
-
return
|
|
145
|
+
return {
|
|
146
|
+
...await compileAndLoad(workDir),
|
|
147
|
+
model: result.model
|
|
148
|
+
};
|
|
102
149
|
}
|
|
103
150
|
__name(generateTsSchema, "generateTsSchema");
|
|
104
151
|
async function compileAndLoad(workDir) {
|
|
@@ -107,9 +154,15 @@ async function compileAndLoad(workDir) {
|
|
|
107
154
|
stdio: "inherit"
|
|
108
155
|
});
|
|
109
156
|
const module = await import(path2.join(workDir, "schema.js"));
|
|
157
|
+
let moduleLite;
|
|
158
|
+
try {
|
|
159
|
+
moduleLite = await import(path2.join(workDir, "schema-lite.js"));
|
|
160
|
+
} catch {
|
|
161
|
+
}
|
|
110
162
|
return {
|
|
111
163
|
workDir,
|
|
112
|
-
schema: module.schema
|
|
164
|
+
schema: module.schema,
|
|
165
|
+
schemaLite: moduleLite?.schema
|
|
113
166
|
};
|
|
114
167
|
}
|
|
115
168
|
__name(compileAndLoad, "compileAndLoad");
|
|
@@ -120,20 +173,361 @@ function generateTsSchemaFromFile(filePath) {
|
|
|
120
173
|
__name(generateTsSchemaFromFile, "generateTsSchemaFromFile");
|
|
121
174
|
async function generateTsSchemaInPlace(schemaPath) {
|
|
122
175
|
const workDir = path2.dirname(schemaPath);
|
|
123
|
-
const
|
|
124
|
-
const result = await loadDocument(schemaPath, pluginModelFiles);
|
|
176
|
+
const result = await loadDocumentWithPlugins(schemaPath);
|
|
125
177
|
if (!result.success) {
|
|
126
178
|
throw new Error(`Failed to load schema from ${schemaPath}: ${result.errors}`);
|
|
127
179
|
}
|
|
128
180
|
const generator = new TsSchemaGenerator();
|
|
129
|
-
await generator.generate(result.model,
|
|
181
|
+
await generator.generate(result.model, {
|
|
182
|
+
outDir: workDir
|
|
183
|
+
});
|
|
130
184
|
return compileAndLoad(workDir);
|
|
131
185
|
}
|
|
132
186
|
__name(generateTsSchemaInPlace, "generateTsSchemaInPlace");
|
|
187
|
+
async function loadSchema(schema, additionalSchemas) {
|
|
188
|
+
if (!schema.includes("datasource ")) {
|
|
189
|
+
schema = `${makePrelude("sqlite")}
|
|
190
|
+
|
|
191
|
+
${schema}`;
|
|
192
|
+
}
|
|
193
|
+
const tempDir = fs2.mkdtempSync(path2.join(os.tmpdir(), "zenstack-schema"));
|
|
194
|
+
const tempFile = path2.join(tempDir, `schema.zmodel`);
|
|
195
|
+
fs2.writeFileSync(tempFile, schema);
|
|
196
|
+
if (additionalSchemas) {
|
|
197
|
+
for (const [fileName, content] of Object.entries(additionalSchemas)) {
|
|
198
|
+
let name = fileName;
|
|
199
|
+
if (!name.endsWith(".zmodel")) {
|
|
200
|
+
name += ".zmodel";
|
|
201
|
+
}
|
|
202
|
+
const filePath = path2.join(tempDir, name);
|
|
203
|
+
fs2.writeFileSync(filePath, content);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
const r = await loadDocumentWithPlugins(tempFile);
|
|
207
|
+
expect(r).toSatisfy((r2) => r2.success, `Failed to load schema: ${r.errors?.map((e) => e.toString()).join(", ")}`);
|
|
208
|
+
invariant(r.success);
|
|
209
|
+
return r.model;
|
|
210
|
+
}
|
|
211
|
+
__name(loadSchema, "loadSchema");
|
|
212
|
+
async function loadSchemaWithError(schema, error) {
|
|
213
|
+
if (!schema.includes("datasource ")) {
|
|
214
|
+
schema = `${makePrelude("sqlite")}
|
|
215
|
+
|
|
216
|
+
${schema}`;
|
|
217
|
+
}
|
|
218
|
+
const tempFile = path2.join(os.tmpdir(), `zenstack-schema-${crypto.randomUUID()}.zmodel`);
|
|
219
|
+
fs2.writeFileSync(tempFile, schema);
|
|
220
|
+
const r = await loadDocumentWithPlugins(tempFile);
|
|
221
|
+
expect(r.success).toBe(false);
|
|
222
|
+
invariant(!r.success);
|
|
223
|
+
if (typeof error === "string") {
|
|
224
|
+
expect(r).toSatisfy((r2) => r2.errors.some((e) => e.toString().toLowerCase().includes(error.toLowerCase())), `Expected error message to include "${error}" but got: ${r.errors.map((e) => e.toString()).join(", ")}`);
|
|
225
|
+
} else {
|
|
226
|
+
expect(r).toSatisfy((r2) => r2.errors.some((e) => error.test(e)), `Expected error message to match "${error}" but got: ${r.errors.map((e) => e.toString()).join(", ")}`);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
__name(loadSchemaWithError, "loadSchemaWithError");
|
|
230
|
+
|
|
231
|
+
// src/client.ts
|
|
232
|
+
function getTestDbProvider() {
|
|
233
|
+
const val = process.env["TEST_DB_PROVIDER"] ?? "sqlite";
|
|
234
|
+
if (![
|
|
235
|
+
"sqlite",
|
|
236
|
+
"postgresql"
|
|
237
|
+
].includes(val)) {
|
|
238
|
+
throw new Error(`Invalid TEST_DB_PROVIDER value: ${val}`);
|
|
239
|
+
}
|
|
240
|
+
return val;
|
|
241
|
+
}
|
|
242
|
+
__name(getTestDbProvider, "getTestDbProvider");
|
|
243
|
+
var TEST_PG_CONFIG = {
|
|
244
|
+
host: process.env["TEST_PG_HOST"] ?? "localhost",
|
|
245
|
+
port: process.env["TEST_PG_PORT"] ? parseInt(process.env["TEST_PG_PORT"]) : 5432,
|
|
246
|
+
user: process.env["TEST_PG_USER"] ?? "postgres",
|
|
247
|
+
password: process.env["TEST_PG_PASSWORD"] ?? "postgres"
|
|
248
|
+
};
|
|
249
|
+
async function createTestClient(schema, options) {
|
|
250
|
+
let workDir = options?.workDir;
|
|
251
|
+
let _schema;
|
|
252
|
+
const provider = options?.provider ?? getTestDbProvider() ?? "sqlite";
|
|
253
|
+
const dbName = options?.dbName ?? getTestDbName(provider);
|
|
254
|
+
const dbUrl = provider === "sqlite" ? `file:${dbName}` : `postgres://${TEST_PG_CONFIG.user}:${TEST_PG_CONFIG.password}@${TEST_PG_CONFIG.host}:${TEST_PG_CONFIG.port}/${dbName}`;
|
|
255
|
+
let model;
|
|
256
|
+
if (typeof schema === "string") {
|
|
257
|
+
const generated = await generateTsSchema(schema, provider, dbUrl, options?.extraSourceFiles, void 0);
|
|
258
|
+
workDir = generated.workDir;
|
|
259
|
+
model = generated.model;
|
|
260
|
+
_schema = {
|
|
261
|
+
...generated.schema,
|
|
262
|
+
provider: {
|
|
263
|
+
...generated.schema.provider,
|
|
264
|
+
type: provider
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
} else {
|
|
268
|
+
_schema = {
|
|
269
|
+
...schema,
|
|
270
|
+
provider: {
|
|
271
|
+
type: provider
|
|
272
|
+
}
|
|
273
|
+
};
|
|
274
|
+
workDir ??= createTestProject();
|
|
275
|
+
if (options?.schemaFile) {
|
|
276
|
+
let schemaContent = fs3.readFileSync(options.schemaFile, "utf-8");
|
|
277
|
+
if (dbUrl) {
|
|
278
|
+
schemaContent = schemaContent.replace(/datasource\s+db\s*{[^}]*}/m, `datasource db {
|
|
279
|
+
provider = '${provider}'
|
|
280
|
+
url = '${dbUrl}'
|
|
281
|
+
}`);
|
|
282
|
+
}
|
|
283
|
+
fs3.writeFileSync(path3.join(workDir, "schema.zmodel"), schemaContent);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
invariant2(workDir);
|
|
287
|
+
if (options?.debug) {
|
|
288
|
+
console.log(`Work directory: ${workDir}`);
|
|
289
|
+
}
|
|
290
|
+
if (options?.dbFile) {
|
|
291
|
+
if (provider !== "sqlite") {
|
|
292
|
+
throw new Error("dbFile option is only supported for sqlite provider");
|
|
293
|
+
}
|
|
294
|
+
fs3.copyFileSync(options.dbFile, path3.join(workDir, dbName));
|
|
295
|
+
}
|
|
296
|
+
const { plugins, ...rest } = options ?? {};
|
|
297
|
+
const _options = {
|
|
298
|
+
...rest
|
|
299
|
+
};
|
|
300
|
+
if (!options?.dbFile) {
|
|
301
|
+
if (options?.usePrismaPush) {
|
|
302
|
+
invariant2(typeof schema === "string" || options?.schemaFile, "a schema file must be provided when using prisma db push");
|
|
303
|
+
if (!model) {
|
|
304
|
+
const r = await loadDocumentWithPlugins(path3.join(workDir, "schema.zmodel"));
|
|
305
|
+
if (!r.success) {
|
|
306
|
+
throw new Error(r.errors.join("\n"));
|
|
307
|
+
}
|
|
308
|
+
model = r.model;
|
|
309
|
+
}
|
|
310
|
+
const prismaSchema = new PrismaSchemaGenerator(model);
|
|
311
|
+
const prismaSchemaText = await prismaSchema.generate();
|
|
312
|
+
fs3.writeFileSync(path3.resolve(workDir, "schema.prisma"), prismaSchemaText);
|
|
313
|
+
execSync2("npx prisma db push --schema ./schema.prisma --skip-generate --force-reset", {
|
|
314
|
+
cwd: workDir,
|
|
315
|
+
stdio: "ignore"
|
|
316
|
+
});
|
|
317
|
+
} else {
|
|
318
|
+
if (provider === "postgresql") {
|
|
319
|
+
invariant2(dbName, "dbName is required");
|
|
320
|
+
const pgClient = new PGClient(TEST_PG_CONFIG);
|
|
321
|
+
await pgClient.connect();
|
|
322
|
+
await pgClient.query(`DROP DATABASE IF EXISTS "${dbName}"`);
|
|
323
|
+
await pgClient.query(`CREATE DATABASE "${dbName}"`);
|
|
324
|
+
await pgClient.end();
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
if (provider === "postgresql") {
|
|
329
|
+
_options.dialect = new PostgresDialect({
|
|
330
|
+
pool: new Pool({
|
|
331
|
+
...TEST_PG_CONFIG,
|
|
332
|
+
database: dbName
|
|
333
|
+
})
|
|
334
|
+
});
|
|
335
|
+
} else {
|
|
336
|
+
_options.dialect = new SqliteDialect({
|
|
337
|
+
database: new SQLite(path3.join(workDir, dbName))
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
let client = new ZenStackClient(_schema, _options);
|
|
341
|
+
if (!options?.usePrismaPush && !options?.dbFile) {
|
|
342
|
+
await client.$pushSchema();
|
|
343
|
+
}
|
|
344
|
+
if (plugins) {
|
|
345
|
+
for (const plugin of plugins) {
|
|
346
|
+
client = client.$use(plugin);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
return client;
|
|
350
|
+
}
|
|
351
|
+
__name(createTestClient, "createTestClient");
|
|
352
|
+
async function createPolicyTestClient(schema, options) {
|
|
353
|
+
return createTestClient(schema, {
|
|
354
|
+
...options,
|
|
355
|
+
plugins: [
|
|
356
|
+
...options?.plugins ?? [],
|
|
357
|
+
new PolicyPlugin()
|
|
358
|
+
]
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
__name(createPolicyTestClient, "createPolicyTestClient");
|
|
362
|
+
function testLogger(e) {
|
|
363
|
+
console.log(e.query.sql, e.query.parameters);
|
|
364
|
+
}
|
|
365
|
+
__name(testLogger, "testLogger");
|
|
366
|
+
function getTestDbName(provider) {
|
|
367
|
+
if (provider === "sqlite") {
|
|
368
|
+
return "./test.db";
|
|
369
|
+
}
|
|
370
|
+
const testName = expect2.getState().currentTestName ?? "unnamed";
|
|
371
|
+
const testPath = expect2.getState().testPath ?? "";
|
|
372
|
+
const digest = createHash("md5").update(testName + testPath).digest("hex");
|
|
373
|
+
return "test_" + testName.toLowerCase().replace(/[^a-z0-9_]/g, "_").replace(/_+/g, "_").substring(0, 30) + digest.slice(0, 6);
|
|
374
|
+
}
|
|
375
|
+
__name(getTestDbName, "getTestDbName");
|
|
376
|
+
|
|
377
|
+
// src/vitest-ext.ts
|
|
378
|
+
import { ORMError, ORMErrorReason } from "@zenstackhq/orm";
|
|
379
|
+
import { expect as expect3 } from "vitest";
|
|
380
|
+
function isPromise(value) {
|
|
381
|
+
return typeof value.then === "function" && typeof value.catch === "function";
|
|
382
|
+
}
|
|
383
|
+
__name(isPromise, "isPromise");
|
|
384
|
+
function expectErrorReason(err, errorReason) {
|
|
385
|
+
if (err instanceof ORMError && err.reason === errorReason) {
|
|
386
|
+
return {
|
|
387
|
+
message: /* @__PURE__ */ __name(() => "", "message"),
|
|
388
|
+
pass: true
|
|
389
|
+
};
|
|
390
|
+
} else {
|
|
391
|
+
return {
|
|
392
|
+
message: /* @__PURE__ */ __name(() => `expected ORMError of reason ${errorReason}, got ${err}`, "message"),
|
|
393
|
+
pass: false
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
__name(expectErrorReason, "expectErrorReason");
|
|
398
|
+
function expectErrorMessages(expectedMessages, message) {
|
|
399
|
+
for (const m of expectedMessages) {
|
|
400
|
+
if (!message.toLowerCase().includes(m.toLowerCase())) {
|
|
401
|
+
return {
|
|
402
|
+
message: /* @__PURE__ */ __name(() => `expected message not found in error: ${m}, got message: ${message}`, "message"),
|
|
403
|
+
pass: false
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
return void 0;
|
|
408
|
+
}
|
|
409
|
+
__name(expectErrorMessages, "expectErrorMessages");
|
|
410
|
+
expect3.extend({
|
|
411
|
+
async toResolveTruthy(received) {
|
|
412
|
+
if (!isPromise(received)) {
|
|
413
|
+
return {
|
|
414
|
+
message: /* @__PURE__ */ __name(() => "a promise is expected", "message"),
|
|
415
|
+
pass: false
|
|
416
|
+
};
|
|
417
|
+
}
|
|
418
|
+
const r = await received;
|
|
419
|
+
return {
|
|
420
|
+
pass: !!r,
|
|
421
|
+
message: /* @__PURE__ */ __name(() => `Expected promise to resolve to a truthy value, but got ${r}`, "message")
|
|
422
|
+
};
|
|
423
|
+
},
|
|
424
|
+
async toResolveFalsy(received) {
|
|
425
|
+
if (!isPromise(received)) {
|
|
426
|
+
return {
|
|
427
|
+
message: /* @__PURE__ */ __name(() => "a promise is expected", "message"),
|
|
428
|
+
pass: false
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
const r = await received;
|
|
432
|
+
return {
|
|
433
|
+
pass: !r,
|
|
434
|
+
message: /* @__PURE__ */ __name(() => `Expected promise to resolve to a falsy value, but got ${r}`, "message")
|
|
435
|
+
};
|
|
436
|
+
},
|
|
437
|
+
async toResolveNull(received) {
|
|
438
|
+
if (!isPromise(received)) {
|
|
439
|
+
return {
|
|
440
|
+
message: /* @__PURE__ */ __name(() => "a promise is expected", "message"),
|
|
441
|
+
pass: false
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
const r = await received;
|
|
445
|
+
return {
|
|
446
|
+
pass: r === null,
|
|
447
|
+
message: /* @__PURE__ */ __name(() => `Expected promise to resolve to a null value, but got ${r}`, "message")
|
|
448
|
+
};
|
|
449
|
+
},
|
|
450
|
+
async toResolveWithLength(received, length) {
|
|
451
|
+
const r = await received;
|
|
452
|
+
return {
|
|
453
|
+
pass: Array.isArray(r) && r.length === length,
|
|
454
|
+
message: /* @__PURE__ */ __name(() => `Expected promise to resolve with an array with length ${length}, but got ${r}`, "message")
|
|
455
|
+
};
|
|
456
|
+
},
|
|
457
|
+
async toBeRejectedNotFound(received) {
|
|
458
|
+
if (!isPromise(received)) {
|
|
459
|
+
return {
|
|
460
|
+
message: /* @__PURE__ */ __name(() => "a promise is expected", "message"),
|
|
461
|
+
pass: false
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
try {
|
|
465
|
+
await received;
|
|
466
|
+
} catch (err) {
|
|
467
|
+
return expectErrorReason(err, ORMErrorReason.NOT_FOUND);
|
|
468
|
+
}
|
|
469
|
+
return {
|
|
470
|
+
message: /* @__PURE__ */ __name(() => `expected NotFoundError, got no error`, "message"),
|
|
471
|
+
pass: false
|
|
472
|
+
};
|
|
473
|
+
},
|
|
474
|
+
async toBeRejectedByPolicy(received, expectedMessages) {
|
|
475
|
+
if (!isPromise(received)) {
|
|
476
|
+
return {
|
|
477
|
+
message: /* @__PURE__ */ __name(() => "a promise is expected", "message"),
|
|
478
|
+
pass: false
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
try {
|
|
482
|
+
await received;
|
|
483
|
+
} catch (err) {
|
|
484
|
+
if (expectedMessages && err instanceof ORMError && err.reason === ORMErrorReason.REJECTED_BY_POLICY) {
|
|
485
|
+
const r = expectErrorMessages(expectedMessages, err.message || "");
|
|
486
|
+
if (r) {
|
|
487
|
+
return r;
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
return expectErrorReason(err, ORMErrorReason.REJECTED_BY_POLICY);
|
|
491
|
+
}
|
|
492
|
+
return {
|
|
493
|
+
message: /* @__PURE__ */ __name(() => `expected PolicyError, got no error`, "message"),
|
|
494
|
+
pass: false
|
|
495
|
+
};
|
|
496
|
+
},
|
|
497
|
+
async toBeRejectedByValidation(received, expectedMessages) {
|
|
498
|
+
if (!isPromise(received)) {
|
|
499
|
+
return {
|
|
500
|
+
message: /* @__PURE__ */ __name(() => "a promise is expected", "message"),
|
|
501
|
+
pass: false
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
try {
|
|
505
|
+
await received;
|
|
506
|
+
} catch (err) {
|
|
507
|
+
if (expectedMessages && err instanceof ORMError && err.reason === ORMErrorReason.INVALID_INPUT) {
|
|
508
|
+
const r = expectErrorMessages(expectedMessages, err.message || "");
|
|
509
|
+
if (r) {
|
|
510
|
+
return r;
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
return expectErrorReason(err, ORMErrorReason.INVALID_INPUT);
|
|
514
|
+
}
|
|
515
|
+
return {
|
|
516
|
+
message: /* @__PURE__ */ __name(() => `expected InputValidationError, got no error`, "message"),
|
|
517
|
+
pass: false
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
});
|
|
133
521
|
export {
|
|
522
|
+
createPolicyTestClient,
|
|
523
|
+
createTestClient,
|
|
134
524
|
createTestProject,
|
|
135
525
|
generateTsSchema,
|
|
136
526
|
generateTsSchemaFromFile,
|
|
137
|
-
generateTsSchemaInPlace
|
|
527
|
+
generateTsSchemaInPlace,
|
|
528
|
+
getTestDbProvider,
|
|
529
|
+
loadSchema,
|
|
530
|
+
loadSchemaWithError,
|
|
531
|
+
testLogger
|
|
138
532
|
};
|
|
139
533
|
//# sourceMappingURL=index.js.map
|