@simetrajs/designer 0.3.0-next.11 → 0.3.0-next.12

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.
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env node
2
+ import { t as UsageError } from "./usage-error-BGPr8yRj.js";
3
+ import { FUNCTIONS_FILE_SUFFIX, SQL_DEBT_FILE } from "simetra/model";
4
+ import { dirname, join, relative, resolve, sep } from "node:path";
5
+ import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
6
+ // src/io/metadata-dir.ts
7
+ /**
8
+ * Файли, які читає компілятор; усе інше в теці його не стосується. Перелік
9
+ * боргу — один файл у корені теки: без нього ратчет бачив би порожній перелік
10
+ * і звітував кожну одиницю боргу.
11
+ */
12
+ const METADATA_SUFFIXES = [
13
+ ".meta.json",
14
+ ".sql",
15
+ ".module.ts",
16
+ FUNCTIONS_FILE_SUFFIX
17
+ ];
18
+ const isMetadataFile = (key) => key === SQL_DEBT_FILE || METADATA_SUFFIXES.some((suffix) => key.endsWith(suffix));
19
+ /**
20
+ * Єдине місце читання диска для дверей CLI: компілятор (T1) працює над мапою
21
+ * «шлях → текст» і не знає про файлову систему.
22
+ */
23
+ async function readMetadataDir(dir) {
24
+ let isDirectory;
25
+ try {
26
+ isDirectory = (await stat(dir)).isDirectory();
27
+ } catch (error) {
28
+ const code = error.code;
29
+ if (code === "ENOENT" || code === "ENOTDIR") throw new UsageError(`metadata directory not found: ${dir}`);
30
+ throw error;
31
+ }
32
+ if (!isDirectory) throw new UsageError(`Not a directory: ${dir}`);
33
+ const entries = await readdir(dir, {
34
+ recursive: true,
35
+ withFileTypes: true
36
+ });
37
+ const files = /* @__PURE__ */ new Map();
38
+ for (const entry of entries) {
39
+ if (!entry.isFile()) continue;
40
+ const full = join(entry.parentPath, entry.name);
41
+ const key = relative(dir, full).split(sep).join("/");
42
+ if (!isMetadataFile(key)) continue;
43
+ files.set(key, await readFile(full, "utf8"));
44
+ }
45
+ return files;
46
+ }
47
+ /**
48
+ * Єдине місце запису; `content: null` видаляє файл і прибирає порожні теки.
49
+ * Видалення йдуть першими: на регістронезалежній ФС перейменування лише
50
+ * регістру — це видалення старого шляху й запис нового, що вказують на той
51
+ * самий файл, і зворотний порядок стер би щойно записане.
52
+ */
53
+ async function writeChanges(dir, changes) {
54
+ const root = resolve(dir);
55
+ const targets = /* @__PURE__ */ new Map();
56
+ for (const change of changes) {
57
+ const target = resolve(root, change.path);
58
+ if (!target.startsWith(root + sep)) throw new UsageError(`Path escapes the target directory: ${change.path}`);
59
+ targets.set(change, target);
60
+ }
61
+ const ordered = [...changes.filter((c) => c.content === null), ...changes.filter((c) => c.content !== null)];
62
+ for (const change of ordered) {
63
+ const target = targets.get(change);
64
+ if (change.content === null) {
65
+ await rm(target, { force: true });
66
+ await pruneEmptyDirs(dirname(target), root);
67
+ } else {
68
+ await mkdir(dirname(target), { recursive: true });
69
+ await writeFile(target, change.content, "utf8");
70
+ }
71
+ }
72
+ }
73
+ async function pruneEmptyDirs(from, root) {
74
+ let current = from;
75
+ while (current !== root && current.startsWith(root + sep)) {
76
+ let entries;
77
+ try {
78
+ entries = await readdir(current);
79
+ } catch {
80
+ return;
81
+ }
82
+ if (entries.length > 0) return;
83
+ await rm(current, { recursive: true });
84
+ current = dirname(current);
85
+ }
86
+ }
87
+ export { readMetadataDir as n, writeChanges as r, isMetadataFile as t };
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  // package.json
3
- var version = "0.3.0-next.11";
3
+ var version = "0.3.0-next.12";
4
4
  export { version as t };
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export { t as createApplyDatabase, n as createPgDeltaEngine } from "./schema-engine-CjU4PSK9.js";
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import { a as ShadowTemplateMissingError, i as ShadowServerMismatchError, n as ShadowCreateRefusedError, r as ShadowServerError, s as withShadowDrop, t as ShadowBaseUnsupportedError } from "./errors-D1P2kKbL.js";
3
- import { PLATFORM_ROLES, PROVIDER_API_ROLES, PROVIDER_SCHEMAS, quoteIdent } from "simetra/model";
4
- import { ApplyConnectionLost, ApplyDbError, ENGINE_PREAMBLE_ALLOWED, ENGINE_SESSION_TIMEOUTS, PROVIDER_ASSUMED_SCHEMAS, PROVIDER_EVENT_TRIGGERS, PROVIDER_PUBLIC_SCHEMA_GRANTS, PROVIDER_SHADOW_TEMPLATES, PROVIDER_UNMANAGED_EXTENSIONS, censusDiagnostics, copiesShadowFromTemplate, providerTriggerInBoundarySql, renderProviderSeed, tableKey, unmodeledClasses } from "simetra/schema";
5
3
  import pg from "pg";
6
- import { loadSqlParser, localize, readSqlUnits, unitIdentity } from "simetra/compiler";
4
+ import { ApplyConnectionLost, ApplyDbError, ENGINE_PREAMBLE_ALLOWED, ENGINE_SESSION_TIMEOUTS, PROVIDER_ASSUMED_SCHEMAS, PROVIDER_EVENT_TRIGGERS, PROVIDER_PUBLIC_SCHEMA_GRANTS, PROVIDER_SHADOW_TEMPLATES, PROVIDER_UNMANAGED_EXTENSIONS, censusDiagnostics, copiesShadowFromTemplate, providerTriggerInBoundarySql, renderProviderSeed, tableKey, unmodeledClasses } from "simetra/schema";
5
+ import { PLATFORM_ROLES, PROVIDER_API_ROLES, PROVIDER_SCHEMAS, quoteIdent } from "simetra/model";
7
6
  import { FactBase, SchemaFrontendError, ShadowLoadError, ShadowProvisionError, apply, encodeId, isShadowProvisionError, plan, planSchemaFiles, provisionCoLocatedShadow, resolveProfile, supabasePolicy, supabaseProfile, validatePolicy, withDatabaseName } from "@supabase/pg-delta";
8
7
  import { resolveView } from "@supabase/pg-delta/policy";
8
+ import { loadSqlParser, localize, readSqlUnits, unitIdentity } from "simetra/compiler";
9
9
  // src/schema-engine/census-read.ts
10
10
  /**
11
11
  * Простий запит до каталогу, що лише рахує об'єкти за класами в межі
@@ -3311,4 +3311,4 @@ function createApplyDatabase(o) {
3311
3311
  }
3312
3312
  };
3313
3313
  }
3314
- export { createApplyDatabase, createPgDeltaEngine };
3314
+ export { createPgDeltaEngine as n, createApplyDatabase as t };
@@ -0,0 +1,304 @@
1
+
2
+ import pg from "pg";
3
+ import "simetra/schema";
4
+ import { CommandResult, Operation, ReadQuery, ReadResultOf } from "simetra/model";
5
+ import "simetra/compiler";
6
+ import { CommandRunOptions, CommandRuntime, CommandRuntimeOptions, Workspace } from "simetra/server";
7
+ /**
8
+ * Error thrown by the `@simetrajs/designer/testing` entry. `code` is a stable
9
+ * `testing.*` identifier to branch on; the message is for humans.
10
+ */
11
+ export declare class TestingError extends Error {
12
+ readonly code: string;
13
+ constructor(code: string, message: string);
14
+ }
15
+ /**
16
+ * Refuses a connection string whose host is not this machine (loopback or a
17
+ * unix socket), before any connection is opened. The host is the one `pg`
18
+ * would use (a `host` query parameter, a repeated one, `PGHOST`). Throws
19
+ * {@link TestingError} `testing.not-local`; an unparsable string is refused
20
+ * the same way, without quoting it.
21
+ */
22
+ export declare function assertLocalHost(dsn: string): void;
23
+ /**
24
+ * A connected client to check: its `host` and one query on that very
25
+ * connection. `pg.Client` and a client taken from `pg.Pool` fit.
26
+ */
27
+ interface DevelopmentClient {
28
+ readonly host?: string | undefined;
29
+ query(text: string, values?: unknown[]): Promise<{
30
+ rows: unknown[];
31
+ }>;
32
+ }
33
+ /**
34
+ * Refuses unless `client` is connected to this machine and the database
35
+ * carries the database-level flag `simetra.environment = 'development'`. The
36
+ * flag is read from the catalog on the same connection, so a session option
37
+ * (`options=-c …`) or a role setting does not pass. Without `database` the
38
+ * current database of the connection is checked; with it, the named database
39
+ * of the same cluster (for a database one cannot connect to, such as a
40
+ * template). Throws {@link TestingError} `testing.not-local` before any query,
41
+ * or `testing.not-development`.
42
+ */
43
+ export declare function assertDevelopmentDatabase(client: DevelopmentClient, options?: {
44
+ database?: string;
45
+ }): Promise<void>;
46
+ /** The session cookie attributes of a Better Auth instance the entry reads. */
47
+ interface TestingAuthCookieAttributes {
48
+ readonly domain?: string;
49
+ readonly path?: string;
50
+ readonly secure?: boolean;
51
+ readonly httpOnly?: boolean;
52
+ readonly sameSite?: string;
53
+ }
54
+ /**
55
+ * The part of a Better Auth context (`await auth.$context`) the testing entry
56
+ * uses: schema migration, the database adapter, password hashing, the
57
+ * session cookie and its signing secret.
58
+ */
59
+ interface TestingAuthContext {
60
+ runMigrations(): Promise<void>;
61
+ readonly secret: string;
62
+ /** The instance's static `baseURL` origin; empty when it is dynamic. */
63
+ readonly baseURL: string;
64
+ readonly adapter: {
65
+ create(data: {
66
+ model: "user";
67
+ data: {
68
+ name: string;
69
+ email: string;
70
+ emailVerified: boolean;
71
+ createdAt: Date;
72
+ updatedAt: Date;
73
+ };
74
+ }): Promise<{
75
+ id: string;
76
+ email: string;
77
+ }>;
78
+ };
79
+ readonly internalAdapter: {
80
+ linkAccount(account: {
81
+ userId: string;
82
+ providerId: string;
83
+ accountId: string;
84
+ password: string;
85
+ }): Promise<unknown>;
86
+ createSession(userId: string): Promise<{
87
+ token: string;
88
+ expiresAt: Date;
89
+ }>;
90
+ };
91
+ readonly password: {
92
+ hash(password: string): Promise<string>;
93
+ };
94
+ readonly authCookies: {
95
+ readonly sessionToken: {
96
+ readonly name: string;
97
+ readonly attributes: TestingAuthCookieAttributes;
98
+ };
99
+ };
100
+ }
101
+ /**
102
+ * The part of an application's Better Auth instance the testing entry reads:
103
+ * `options.database` and `options.secondaryStorage` (to prove where it
104
+ * writes) and `$context`.
105
+ */
106
+ interface TestingAuth {
107
+ readonly options: {
108
+ readonly database?: unknown;
109
+ readonly secondaryStorage?: unknown;
110
+ };
111
+ readonly $context: Promise<TestingAuthContext>;
112
+ }
113
+ /**
114
+ * Builds the application's Better Auth instance on the given pool. The
115
+ * instance must use that very pool as `database` and have no
116
+ * `secondaryStorage`; otherwise the entry refuses with `testing.auth-pool`.
117
+ * `prepareRunTemplate` builds the instance before migrating its tables,
118
+ * so a test factory may set `advanced.database.validateSchema: false` (or a
119
+ * `logger`) to avoid Better Auth's one-off schema-mismatch log.
120
+ */
121
+ type TestingAuthFactory = (pool: pg.Pool) => TestingAuth;
122
+ /** Passwords of the cluster login roles (`db:setup` of the developer). */
123
+ interface TestingLogins {
124
+ owner: string;
125
+ auth: string;
126
+ runtime: string;
127
+ signals: string;
128
+ }
129
+ /** Connection strings of the four login roles to one run database. */
130
+ type RunDatabaseUrls = TestingLogins;
131
+ /** The run template made by {@link prepareRunTemplate}. */
132
+ interface RunTemplate {
133
+ /** Database name; pass it to {@link createRunDatabase} as `template`. */
134
+ name: string;
135
+ /** Unmarks the template and drops it. */
136
+ drop(): Promise<void>;
137
+ }
138
+ /** A run database copied from the run template. */
139
+ interface RunDatabase {
140
+ name: string;
141
+ urls: RunDatabaseUrls;
142
+ /** Ends the connections to the database and drops it. */
143
+ drop(): Promise<void>;
144
+ }
145
+ /**
146
+ * Prepares the run template once per test run (Vitest `globalSetup`): a new
147
+ * database from the provider's shadow template, flagged as a development
148
+ * database, with the Better Auth schema migrated by the application's `auth`
149
+ * factory and the model of `project` (the metadata directory, as the CLI
150
+ * `--dir`) applied as `simetra_owner`; then sealed as a template. `adminUrl`
151
+ * is a superuser of the development cluster on its maintenance database, which
152
+ * must carry the development flag. Throws {@link TestingError}:
153
+ * `testing.login-missing`, `testing.invalid-tag`, `testing.not-local`,
154
+ * `testing.not-development`, `testing.auth-pool`, `testing.apply-failed`; a
155
+ * failure after the database is created drops it.
156
+ *
157
+ * The instance is built before its tables are migrated, so Better Auth logs a
158
+ * schema mismatch once per call; a test factory may set
159
+ * `advanced.database.validateSchema: false` or a `logger` to silence it.
160
+ */
161
+ export declare function prepareRunTemplate(o: {
162
+ adminUrl: string;
163
+ project: string;
164
+ auth: TestingAuthFactory;
165
+ tag?: string;
166
+ logins?: TestingLogins;
167
+ }): Promise<RunTemplate>;
168
+ /**
169
+ * Copies the run template `template` (its name from
170
+ * {@link prepareRunTemplate}) into a new run database for one test file or
171
+ * test, flagged as a development database, with `CONNECT` for the identity,
172
+ * runtime and signals logins. `urls` are the connection strings of the four
173
+ * login roles to it. Both the maintenance database of `adminUrl` and the
174
+ * template must carry the development flag. Throws {@link TestingError}:
175
+ * `testing.login-missing`, `testing.invalid-tag`, `testing.not-local`,
176
+ * `testing.not-development`, and `testing.template-not-applied` when the copy
177
+ * holds no applied model (the copy is dropped).
178
+ */
179
+ export declare function createRunDatabase(o: {
180
+ adminUrl: string;
181
+ template: string;
182
+ tag?: string;
183
+ logins?: TestingLogins;
184
+ }): Promise<RunDatabase>;
185
+ /** A user made by {@link createTestUser}. */
186
+ interface TestUser {
187
+ id: string;
188
+ /** The stored email (Better Auth lowercases it). */
189
+ email: string;
190
+ /** The password of the user's credential account. */
191
+ password: string;
192
+ }
193
+ /** A session cookie in the form of Playwright `storageState` cookies. */
194
+ interface TestSessionCookie {
195
+ name: string;
196
+ value: string;
197
+ domain: string;
198
+ path: string;
199
+ /** Unix time in seconds. */
200
+ expires: number;
201
+ httpOnly: boolean;
202
+ secure: boolean;
203
+ sameSite: "Strict" | "Lax" | "None";
204
+ }
205
+ /** A session made by {@link createTestSession}. */
206
+ interface TestSession {
207
+ /** For Playwright `storageState({ cookies })` or `context.addCookies`. */
208
+ cookies: TestSessionCookie[];
209
+ /** The `Cookie` request header, e.g. for `auth.api.getSession`. */
210
+ cookieHeader: string;
211
+ }
212
+ /**
213
+ * Creates a user with `emailVerified: true` and a password credential account
214
+ * through the application's Better Auth instance, built by `auth` on the
215
+ * identity pool of `db` after the run database is checked as a development
216
+ * database; no open `/sign-up` path is called. The user row is written with
217
+ * the instance's database adapter, so the application's user-create hooks
218
+ * (`user.validateUserInfo`, `databaseHooks.user.create`) do not run for it.
219
+ * The database provisions the user's Users row. `password` defaults to a
220
+ * random one, `name` to `email`. Throws {@link TestingError}:
221
+ * `testing.not-local`, `testing.not-development`, `testing.auth-pool`.
222
+ */
223
+ export declare function createTestUser(db: Pick<RunDatabase, "urls">, o: {
224
+ auth: TestingAuthFactory;
225
+ email: string;
226
+ password?: string;
227
+ name?: string;
228
+ }): Promise<TestUser>;
229
+ /**
230
+ * Creates a session for `user` through the application's Better Auth
231
+ * instance, built by `auth` on the identity pool of `db` after the run
232
+ * database is checked as a development database, and returns its signed
233
+ * session cookie. No `/sign-in/*` path is called, so the sign-in rate limit
234
+ * is not consumed and stays enabled. The cookie domain is the session
235
+ * cookie's `domain` attribute, else the host of the instance's `baseURL`.
236
+ * Throws {@link TestingError}: `testing.not-local`, `testing.not-development`,
237
+ * `testing.auth-pool`, and `testing.auth-base-url` when the instance has no
238
+ * static `baseURL` and the cookie no `domain` (nothing is written then).
239
+ */
240
+ export declare function createTestSession(db: Pick<RunDatabase, "urls">, o: {
241
+ auth: TestingAuthFactory;
242
+ user: Pick<TestUser, "id">;
243
+ }): Promise<TestSession>;
244
+ /**
245
+ * Adds `user` as a member of the scope `scope` of the scope kind `scopeKind`
246
+ * past the invitation flow and assigns the named `roles` of that scope kind's
247
+ * level to the member, in one maintenance-mode transaction as the migrator
248
+ * `simetra_owner`. `project` is the metadata directory of the applied model
249
+ * (as the CLI `--dir`); `values` are the attributes of the member row, checked
250
+ * as the rights-maintenance tool checks `member`. Returns the member id.
251
+ * Throws {@link TestingError}: `testing.not-local`,
252
+ * `testing.not-development` (nothing written), `testing.apply-failed` when the
253
+ * metadata does not compile, and the engine's refusal codes as they are
254
+ * (`maintenance.member-exists`, `maintenance.role-level`,
255
+ * `maintenance.invalid-member`, `maintenance.model-mismatch`, …).
256
+ */
257
+ export declare function addMember(db: Pick<RunDatabase, "urls">, o: {
258
+ project: string;
259
+ scopeKind: string;
260
+ scope: string;
261
+ user: {
262
+ id: string;
263
+ };
264
+ values?: Record<string, unknown>;
265
+ roles: readonly string[];
266
+ }): Promise<string>;
267
+ /** Operations on behalf of one user, see {@link TestRuntime.as}. */
268
+ interface TestUserRuntime {
269
+ /** `CommandRuntime.run` with the user's session. */
270
+ run(input: Operation | readonly Operation[], options?: CommandRunOptions): Promise<CommandResult>;
271
+ /** `CommandRuntime.read` with the user's session. */
272
+ read<Q extends ReadQuery>(query: Q): Promise<ReadResultOf<Q>>;
273
+ /** `CommandRuntime.workspaces` with the user's session, in process. */
274
+ workspaces(): Promise<Workspace[]>;
275
+ }
276
+ /** The command runtime of a run database, made by {@link createTestRuntime}. */
277
+ interface TestRuntime {
278
+ readonly runtime: CommandRuntime;
279
+ /**
280
+ * The runtime on behalf of `user` (for example a `TestUser`): claims
281
+ * `{ sub, is_anonymous: false }`, `sub` lowercased as the template's
282
+ * session adapter does.
283
+ */
284
+ as(user: {
285
+ id: string;
286
+ }): TestUserRuntime;
287
+ /** Ends the runtime pool; call it before dropping the run database. */
288
+ close(): Promise<void>;
289
+ }
290
+ /**
291
+ * Creates the command runtime (`createCommandRuntime` of `simetra/server`)
292
+ * of the run database `db` on a pool of its runtime login, in process.
293
+ * `catalog` is the runtime catalog (`runtime-catalog.json`) of the applied
294
+ * model. Before the runtime is created the run database is checked as a
295
+ * development database on a connection of that pool. Throws
296
+ * {@link TestingError} `testing.not-local` or `testing.not-development`; the
297
+ * runtime's own refusals (`CommandFailure`) pass as they are.
298
+ */
299
+ export declare function createTestRuntime(o: {
300
+ db: Pick<RunDatabase, "urls">;
301
+ catalog: unknown;
302
+ objectModules?: CommandRuntimeOptions["objectModules"];
303
+ }): Promise<TestRuntime>;
304
+ export type { DevelopmentClient, RunDatabase, RunDatabaseUrls, RunTemplate, TestRuntime, TestSession, TestSessionCookie, TestUser, TestUserRuntime, TestingAuth, TestingAuthContext, TestingAuthCookieAttributes, TestingAuthFactory, TestingLogins };