@kaloma-ai/framework-api 0.0.0-stage → 0.6.0

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,84 @@
1
+ import { D as Db, C as Config } from './app-UFeIdPnm.js';
2
+ export { A as AppAuthz, a as AppDeps, b as AuditFn, c as Auth, d as AuthEnv, e as Authz, f as AuthzError, B as BACKUP_STORAGE, g as Brand, h as BrandService, i as Catalog, j as ConnectionError, k as ConnectionKind, l as ConnectionSlot, m as ConnectionStatus, n as ConnectionView, o as Connections, p as DEFAULT_STORAGE, E as EMAIL_CONNECTION, q as Email, r as EmailSender, F as FieldDef, s as FileStorage, H as HealthDeps, L as Llm, t as LlmCallOptions, u as LlmGetOptions, v as LoadedBrand, O as Operations, P as PermissionDef, R as RoleDef, S as SessionUser, w as SettingDef, x as SettingType, y as SettingView, z as Settings, G as SmtpSettings, I as StoredFile, U as Usage, J as assertDefaultDeny, K as brandRoutes, M as buildCatalog, N as consoleEmailSender, Q as contrastOn, T as createApp, V as createAuth, W as createAuthz, X as createBrandService, Y as createConnections, Z as createDb, _ as createEmailSender, $ as createLocalFileStorage, a0 as createOperations, a1 as createSettings, a2 as findUndeclaredRoutes, a3 as frameworkPermissions, a4 as frameworkSettings, a5 as getCompanyId, a6 as healthRoutes, a7 as loadBrand, a8 as loadConfig, a9 as publicRoute, aa as requirePermission, ab as requireSession, ac as sessionMiddleware, ad as smtpSender } from './app-UFeIdPnm.js';
3
+ import 'hono/types';
4
+ import 'hono';
5
+ import 'zod';
6
+ import 'drizzle-orm/postgres-js';
7
+ import 'postgres';
8
+ import 'node:stream';
9
+ import 'ai';
10
+ import 'drizzle-orm/pg-core';
11
+
12
+ /** The folder with the framework's own migrations, inside the installed package (`src/` and `dist/` sit next to `drizzle/`). */
13
+ declare function frameworkMigrationsDir(): string;
14
+ /**
15
+ * Applies pending migrations from a folder generated by drizzle-kit. Safe to run on every start.
16
+ * The app's own migrations use their own `table`, so they never interfere with the framework's.
17
+ *
18
+ * Drizzle only runs migrations newer than the newest one it has applied, so a migration with an older
19
+ * timestamp (two branches merged, a hotfix released late) would be skipped without a word. After migrating,
20
+ * every migration in the folder must be recorded as applied, otherwise this throws and the API does not start.
21
+ */
22
+ declare function runMigrations(db: Db, migrationsFolder: string, table?: string): Promise<void>;
23
+
24
+ /**
25
+ * Settings that make a real deployment unsafe or useless. Errors stop the app from starting;
26
+ * warnings are printed. Only applies in production (NODE_ENV=production, which the Docker image sets).
27
+ */
28
+ declare function productionProblems(config: Config): {
29
+ errors: string[];
30
+ warnings: string[];
31
+ };
32
+
33
+ /** The framework release this app runs (from the package version). Shown by /api/health, the Status page and in backups. */
34
+ declare const FRAMEWORK_VERSION: string;
35
+
36
+ interface GroupMember {
37
+ id: string;
38
+ name: string;
39
+ email: string;
40
+ }
41
+ interface GroupView {
42
+ id: string;
43
+ name: string;
44
+ description: string;
45
+ members: GroupMember[];
46
+ }
47
+ interface GroupRef {
48
+ id: string;
49
+ name: string;
50
+ }
51
+ interface MembersChange {
52
+ group: GroupView;
53
+ added: GroupMember[];
54
+ removed: GroupMember[];
55
+ }
56
+ interface Groups {
57
+ list(): Promise<GroupView[]>;
58
+ create(name: string, description?: string): Promise<GroupView>;
59
+ update(id: string, changes: {
60
+ name?: string;
61
+ description?: string;
62
+ }): Promise<GroupView>;
63
+ remove(id: string): Promise<GroupView>;
64
+ /** Replaces the members of a group with exactly these users. */
65
+ setMembers(id: string, userIds: string[]): Promise<MembersChange>;
66
+ /**
67
+ * The users in any of these groups, without duplicates. People who cannot sign in (deactivated or
68
+ * expired) are left out unless `includeInactive` is set, so notifications and assignments skip them.
69
+ */
70
+ memberIds(groupIds: string[], options?: {
71
+ includeInactive?: boolean;
72
+ }): Promise<string[]>;
73
+ /** The groups one user belongs to. */
74
+ forUser(userId: string): Promise<GroupRef[]>;
75
+ /** The groups of every user, for lists that show them. */
76
+ byUser(): Promise<Map<string, GroupRef[]>>;
77
+ }
78
+ /** Organizational groups. They say who belongs together; roles say what people may do. */
79
+ declare function createGroups({ db }: {
80
+ db: Db;
81
+ }): Groups;
82
+
83
+ export { Config, Db, FRAMEWORK_VERSION, createGroups, frameworkMigrationsDir, productionProblems, runMigrations };
84
+ export type { GroupMember, GroupRef, GroupView, Groups };
package/dist/index.js ADDED
@@ -0,0 +1,100 @@
1
+ import {
2
+ AuthzError,
3
+ BACKUP_STORAGE,
4
+ ConnectionError,
5
+ DEFAULT_STORAGE,
6
+ EMAIL_CONNECTION,
7
+ FRAMEWORK_VERSION,
8
+ assertDefaultDeny,
9
+ brandRoutes,
10
+ buildCatalog,
11
+ consoleEmailSender,
12
+ contrastOn,
13
+ createApp,
14
+ createAuth,
15
+ createAuthz,
16
+ createBrandService,
17
+ createConnections,
18
+ createDb,
19
+ createEmailSender,
20
+ createGroups,
21
+ createLocalFileStorage,
22
+ createOperations,
23
+ createSettings,
24
+ findUndeclaredRoutes,
25
+ frameworkMigrationsDir,
26
+ frameworkPermissions,
27
+ frameworkSettings,
28
+ getCompanyId,
29
+ healthRoutes,
30
+ loadBrand,
31
+ loadConfig,
32
+ publicRoute,
33
+ requirePermission,
34
+ requireSession,
35
+ runMigrations,
36
+ sessionMiddleware,
37
+ smtpSender
38
+ } from "./chunk-T6RJSNTZ.js";
39
+ import "./chunk-R6W6GTUR.js";
40
+
41
+ // src/production.ts
42
+ var LOCAL_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
43
+ var PLACEHOLDER = /replace-with|change-me|changeme|example|secret|password/i;
44
+ function productionProblems(config) {
45
+ const errors = [];
46
+ const warnings = [];
47
+ if (config.NODE_ENV !== "production") return { errors, warnings };
48
+ if (PLACEHOLDER.test(config.AUTH_SECRET) || new Set(config.AUTH_SECRET).size < 8) {
49
+ errors.push("AUTH_SECRET is a placeholder or too simple. Generate one with: openssl rand -hex 32");
50
+ }
51
+ const url = new URL(config.PUBLIC_URL);
52
+ if (url.protocol !== "https:" && !LOCAL_HOSTS.has(url.hostname)) {
53
+ errors.push(`PUBLIC_URL must be https for a real address (got ${config.PUBLIC_URL}): sessions and passwords would travel unencrypted.`);
54
+ }
55
+ if (config.EMAIL_TRANSPORT === "console" && !LOCAL_HOSTS.has(url.hostname)) {
56
+ warnings.push("EMAIL_TRANSPORT=console: invitations, password resets and reminders are only printed in the log. Set EMAIL_TRANSPORT=smtp, or set up Email on the Connections page after the first sign-in.");
57
+ }
58
+ if (config.ALERT_EMAILS.length === 0) warnings.push("ALERT_EMAILS is empty: nobody is told about failed backups or outages.");
59
+ if (!config.BACKUP_ENABLED) warnings.push("BACKUP_ENABLED=false: there are no automatic backups.");
60
+ return { errors, warnings };
61
+ }
62
+ export {
63
+ AuthzError,
64
+ BACKUP_STORAGE,
65
+ ConnectionError,
66
+ DEFAULT_STORAGE,
67
+ EMAIL_CONNECTION,
68
+ FRAMEWORK_VERSION,
69
+ assertDefaultDeny,
70
+ brandRoutes,
71
+ buildCatalog,
72
+ consoleEmailSender,
73
+ contrastOn,
74
+ createApp,
75
+ createAuth,
76
+ createAuthz,
77
+ createBrandService,
78
+ createConnections,
79
+ createDb,
80
+ createEmailSender,
81
+ createGroups,
82
+ createLocalFileStorage,
83
+ createOperations,
84
+ createSettings,
85
+ findUndeclaredRoutes,
86
+ frameworkMigrationsDir,
87
+ frameworkPermissions,
88
+ frameworkSettings,
89
+ getCompanyId,
90
+ healthRoutes,
91
+ loadBrand,
92
+ loadConfig,
93
+ productionProblems,
94
+ publicRoute,
95
+ requirePermission,
96
+ requireSession,
97
+ runMigrations,
98
+ sessionMiddleware,
99
+ smtpSender
100
+ };
@@ -0,0 +1,130 @@
1
+ import * as drizzle_orm_pg_core from 'drizzle-orm/pg-core';
2
+
3
+ declare const user: drizzle_orm_pg_core.PgTableWithColumns<{
4
+ name: "user";
5
+ schema: undefined;
6
+ columns: {
7
+ id: drizzle_orm_pg_core.PgColumn<{
8
+ name: "id";
9
+ tableName: "user";
10
+ dataType: "string";
11
+ columnType: "PgText";
12
+ data: string;
13
+ driverParam: string;
14
+ notNull: true;
15
+ hasDefault: false;
16
+ isPrimaryKey: true;
17
+ isAutoincrement: false;
18
+ hasRuntimeDefault: false;
19
+ enumValues: [string, ...string[]];
20
+ baseColumn: never;
21
+ identity: undefined;
22
+ generated: undefined;
23
+ }, {}, {}>;
24
+ name: drizzle_orm_pg_core.PgColumn<{
25
+ name: "name";
26
+ tableName: "user";
27
+ dataType: "string";
28
+ columnType: "PgText";
29
+ data: string;
30
+ driverParam: string;
31
+ notNull: true;
32
+ hasDefault: false;
33
+ isPrimaryKey: false;
34
+ isAutoincrement: false;
35
+ hasRuntimeDefault: false;
36
+ enumValues: [string, ...string[]];
37
+ baseColumn: never;
38
+ identity: undefined;
39
+ generated: undefined;
40
+ }, {}, {}>;
41
+ email: drizzle_orm_pg_core.PgColumn<{
42
+ name: "email";
43
+ tableName: "user";
44
+ dataType: "string";
45
+ columnType: "PgText";
46
+ data: string;
47
+ driverParam: string;
48
+ notNull: true;
49
+ hasDefault: false;
50
+ isPrimaryKey: false;
51
+ isAutoincrement: false;
52
+ hasRuntimeDefault: false;
53
+ enumValues: [string, ...string[]];
54
+ baseColumn: never;
55
+ identity: undefined;
56
+ generated: undefined;
57
+ }, {}, {}>;
58
+ emailVerified: drizzle_orm_pg_core.PgColumn<{
59
+ name: "email_verified";
60
+ tableName: "user";
61
+ dataType: "boolean";
62
+ columnType: "PgBoolean";
63
+ data: boolean;
64
+ driverParam: boolean;
65
+ notNull: true;
66
+ hasDefault: true;
67
+ isPrimaryKey: false;
68
+ isAutoincrement: false;
69
+ hasRuntimeDefault: false;
70
+ enumValues: undefined;
71
+ baseColumn: never;
72
+ identity: undefined;
73
+ generated: undefined;
74
+ }, {}, {}>;
75
+ image: drizzle_orm_pg_core.PgColumn<{
76
+ name: "image";
77
+ tableName: "user";
78
+ dataType: "string";
79
+ columnType: "PgText";
80
+ data: string;
81
+ driverParam: string;
82
+ notNull: false;
83
+ hasDefault: false;
84
+ isPrimaryKey: false;
85
+ isAutoincrement: false;
86
+ hasRuntimeDefault: false;
87
+ enumValues: [string, ...string[]];
88
+ baseColumn: never;
89
+ identity: undefined;
90
+ generated: undefined;
91
+ }, {}, {}>;
92
+ createdAt: drizzle_orm_pg_core.PgColumn<{
93
+ name: "created_at";
94
+ tableName: "user";
95
+ dataType: "date";
96
+ columnType: "PgTimestamp";
97
+ data: Date;
98
+ driverParam: string;
99
+ notNull: true;
100
+ hasDefault: true;
101
+ isPrimaryKey: false;
102
+ isAutoincrement: false;
103
+ hasRuntimeDefault: false;
104
+ enumValues: undefined;
105
+ baseColumn: never;
106
+ identity: undefined;
107
+ generated: undefined;
108
+ }, {}, {}>;
109
+ updatedAt: drizzle_orm_pg_core.PgColumn<{
110
+ name: "updated_at";
111
+ tableName: "user";
112
+ dataType: "date";
113
+ columnType: "PgTimestamp";
114
+ data: Date;
115
+ driverParam: string;
116
+ notNull: true;
117
+ hasDefault: true;
118
+ isPrimaryKey: false;
119
+ isAutoincrement: false;
120
+ hasRuntimeDefault: false;
121
+ enumValues: undefined;
122
+ baseColumn: never;
123
+ identity: undefined;
124
+ generated: undefined;
125
+ }, {}, {}>;
126
+ };
127
+ dialect: "pg";
128
+ }>;
129
+
130
+ export { user };
package/dist/schema.js ADDED
@@ -0,0 +1,6 @@
1
+ import {
2
+ user
3
+ } from "./chunk-R6W6GTUR.js";
4
+ export {
5
+ user
6
+ };
@@ -0,0 +1,73 @@
1
+ import { Operations, Settings, FileStorage, Connections, BrandService, Config, EmailSender, createApp, Auth, Authz, Email, AppAuthz, SettingDef, ConnectionSlot } from './index.js';
2
+ import * as drizzle_orm_postgres_js from 'drizzle-orm/postgres-js';
3
+ import postgres__default from 'postgres';
4
+ import 'hono/types';
5
+ import 'hono';
6
+ import 'zod';
7
+ import 'node:stream';
8
+ import 'ai';
9
+ import 'drizzle-orm/pg-core';
10
+
11
+ declare const testDatabaseUrl: string | undefined;
12
+ /**
13
+ * Creates a throwaway database on the server in TEST_DATABASE_URL, migrates it,
14
+ * and returns a client plus a cleanup function.
15
+ */
16
+ declare function createTestDatabase(): Promise<{
17
+ url: string;
18
+ drop(): Promise<void>;
19
+ db: drizzle_orm_postgres_js.PostgresJsDatabase<Record<string, never>> & {
20
+ $client: postgres__default.Sql<{}>;
21
+ };
22
+ client: postgres__default.Sql<{}>;
23
+ close: () => Promise<void>;
24
+ }>;
25
+
26
+ declare const ORIGIN = "http://localhost:8080";
27
+ declare const PASSWORD = "a-long-enough-password";
28
+ declare const ADMIN = "boss@example.com";
29
+ /** Written out (not inferred) so the published type declarations stay small. */
30
+ interface Harness {
31
+ testDb: Awaited<ReturnType<typeof createTestDatabase>>;
32
+ ops: Operations;
33
+ settings: Settings;
34
+ storage: FileStorage;
35
+ connections: Connections;
36
+ brand: BrandService;
37
+ backupDir: string;
38
+ config: Config;
39
+ email: EmailSender;
40
+ app: ReturnType<typeof createApp>;
41
+ auth: Auth;
42
+ authz: Authz;
43
+ outbox: Email[];
44
+ call(path: string, opts?: {
45
+ method?: string;
46
+ body?: unknown;
47
+ cookie?: string;
48
+ apiKey?: string;
49
+ }): Promise<Response>;
50
+ cookieOf(res: Response): string;
51
+ lastLink(to: string): {
52
+ mail: Email;
53
+ path: string;
54
+ url: string;
55
+ };
56
+ signUp(address: string, name?: string, invitationId?: string): Promise<Response>;
57
+ verifyAndSignIn(address: string): Promise<string>;
58
+ setUpAdmin(): Promise<string>;
59
+ addUser(adminCookie: string, address: string, roles: string[]): Promise<{
60
+ cookie: string;
61
+ id: string;
62
+ }>;
63
+ }
64
+ /** A full app on a throwaway Postgres database, with helpers to drive it like a browser or an agent. */
65
+ declare function createHarness(appAuthz?: AppAuthz, options?: {
66
+ appMigrations?: string;
67
+ settings?: SettingDef[];
68
+ connections?: ConnectionSlot[];
69
+ fetch?: typeof fetch;
70
+ }): Promise<Harness>;
71
+
72
+ export { ADMIN, ORIGIN, PASSWORD, createHarness, testDatabaseUrl };
73
+ export type { Harness };
@@ -0,0 +1,209 @@
1
+ import {
2
+ buildCatalog,
3
+ createApp,
4
+ createAuth,
5
+ createAuthz,
6
+ createBrandService,
7
+ createConnections,
8
+ createDb,
9
+ createLocalFileStorage,
10
+ createOperations,
11
+ createSettings,
12
+ frameworkMigrationsDir,
13
+ frameworkSettings,
14
+ loadBrand,
15
+ loadConfig,
16
+ resetCompanyCache,
17
+ runMigrations
18
+ } from "./chunk-T6RJSNTZ.js";
19
+ import "./chunk-R6W6GTUR.js";
20
+
21
+ // src/test/harness.ts
22
+ import { mkdtempSync, writeFileSync } from "fs";
23
+ import { tmpdir } from "os";
24
+ import { join } from "path";
25
+ import { expect } from "vitest";
26
+ import { sql } from "drizzle-orm";
27
+
28
+ // src/test/scriptedEmail.ts
29
+ var scriptedMail = [];
30
+ var scriptedEmail = {
31
+ kind: "email",
32
+ key: "scripted",
33
+ label: "Scripted (tests)",
34
+ fields: [{ key: "fail", label: "Fail", type: "boolean" }],
35
+ create: ({ config }) => ({
36
+ async send(email) {
37
+ if (config.fail === true) throw new Error("The scripted mail server refused the message");
38
+ scriptedMail.push(email);
39
+ }
40
+ })
41
+ };
42
+
43
+ // src/test/scriptedLlm.ts
44
+ import { MockLanguageModelV4 } from "ai/test";
45
+ var scriptedLlm = {
46
+ kind: "llm",
47
+ key: "scripted",
48
+ label: "Scripted (tests)",
49
+ fields: [
50
+ { key: "model", label: "Model", type: "text", required: true },
51
+ { key: "reply", label: "Reply", type: "text" },
52
+ { key: "personalDataApproved", label: "Approved for personal data", type: "boolean" }
53
+ ],
54
+ create: ({ config }) => {
55
+ const reply = String(config.reply ?? "OK");
56
+ const usage = {
57
+ inputTokens: { total: 10, noCache: 10, cacheRead: void 0, cacheWrite: void 0 },
58
+ outputTokens: { total: 20, text: 20, reasoning: void 0 }
59
+ };
60
+ return new MockLanguageModelV4({
61
+ doGenerate: async () => {
62
+ if (reply === "FAIL") throw new Error("The scripted model failed");
63
+ return { content: [{ type: "text", text: reply }], finishReason: { unified: "stop", raw: void 0 }, usage, warnings: [] };
64
+ },
65
+ doStream: async () => ({
66
+ stream: new ReadableStream({
67
+ start(controller) {
68
+ controller.enqueue({ type: "text-start", id: "t" });
69
+ for (const part of reply.split(" ")) controller.enqueue({ type: "text-delta", id: "t", delta: `${part} ` });
70
+ controller.enqueue({ type: "text-end", id: "t" });
71
+ controller.enqueue({ type: "finish", finishReason: { unified: "stop", raw: void 0 }, usage });
72
+ controller.close();
73
+ }
74
+ })
75
+ })
76
+ });
77
+ }
78
+ };
79
+
80
+ // src/test/testDb.ts
81
+ import postgres from "postgres";
82
+ var testDatabaseUrl = process.env.TEST_DATABASE_URL;
83
+ async function createTestDatabase() {
84
+ const adminUrl = new URL(testDatabaseUrl);
85
+ const name = `appai_test_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
86
+ const admin = postgres(adminUrl.toString(), { max: 1 });
87
+ await admin.unsafe(`create database "${name}"`);
88
+ const url = new URL(adminUrl);
89
+ url.pathname = `/${name}`;
90
+ const database = createDb(url.toString());
91
+ await runMigrations(database.db, frameworkMigrationsDir());
92
+ return {
93
+ ...database,
94
+ url: url.toString(),
95
+ async drop() {
96
+ await database.close();
97
+ await admin.unsafe(`drop database "${name}" with (force)`);
98
+ await admin.end();
99
+ }
100
+ };
101
+ }
102
+
103
+ // src/test/harness.ts
104
+ var ORIGIN = "http://localhost:8080";
105
+ var PASSWORD = "a-long-enough-password";
106
+ var ADMIN = "boss@example.com";
107
+ async function createHarness(appAuthz, options = {}) {
108
+ resetCompanyCache();
109
+ const testDb = await createTestDatabase();
110
+ if (options.appMigrations) await runMigrations(testDb.db, options.appMigrations, "__app_migrations");
111
+ const outbox = [];
112
+ const email = { send: async (e) => void outbox.push(e) };
113
+ const config = loadConfig({
114
+ DATABASE_URL: testDb.url,
115
+ AUTH_SECRET: "t".repeat(40),
116
+ INITIAL_ADMIN_EMAIL: ADMIN,
117
+ NODE_ENV: "test"
118
+ });
119
+ const loadedBrand = loadBrand("/nonexistent", "test");
120
+ const settings = createSettings({ db: testDb.db, definitions: [...frameworkSettings(loadedBrand), ...options.settings ?? []] });
121
+ await settings.load();
122
+ const filesDir = mkdtempSync(join(tmpdir(), "appai-files-"));
123
+ const storage = createLocalFileStorage(filesDir);
124
+ const connections = createConnections({ db: testDb.db, config: { ...config, FILES_DIR: filesDir }, slots: options.connections, providers: [scriptedLlm, scriptedEmail], fetch: options.fetch });
125
+ const brand = createBrandService({ loaded: loadedBrand, settings, storage });
126
+ const appName = () => settings.get("app.name");
127
+ const authz = createAuthz({ db: testDb.db, catalog: buildCatalog(appAuthz), externalAccessDays: config.EXTERNAL_ACCESS_DAYS });
128
+ const auth = createAuth({ db: testDb.db, config, email, authz, appName });
129
+ const dir = mkdtempSync(join(tmpdir(), "appai-backups-"));
130
+ const ops = createOperations({
131
+ db: testDb.db,
132
+ config: { ...config, BACKUP_DIR: dir, ALERT_EMAILS: ["ops@example.com"] },
133
+ email,
134
+ appName,
135
+ settings,
136
+ connections,
137
+ // pg_dump is not installed on every developer machine: the tests use a stand-in.
138
+ dump: async (_url, file) => writeFileSync(file, "dump")
139
+ });
140
+ const app = createApp({
141
+ appName,
142
+ db: testDb.db,
143
+ auth,
144
+ authz,
145
+ email,
146
+ publicUrl: config.PUBLIC_URL,
147
+ brand,
148
+ settings,
149
+ storage,
150
+ connections,
151
+ ops,
152
+ checkDatabase: async () => {
153
+ await testDb.db.execute(sql`select 1`);
154
+ }
155
+ });
156
+ let requests = 0;
157
+ const nextAddress = () => `10.${++requests >> 16 & 255}.${requests >> 8 & 255}.${requests & 255}`;
158
+ async function call(path, opts = {}) {
159
+ return app.request(path, {
160
+ method: opts.method ?? (opts.body ? "POST" : "GET"),
161
+ headers: {
162
+ origin: ORIGIN,
163
+ "x-forwarded-for": nextAddress(),
164
+ ...opts.body ? { "content-type": "application/json" } : {},
165
+ ...opts.cookie ? { cookie: opts.cookie } : {},
166
+ ...opts.apiKey ? { "x-api-key": opts.apiKey } : {}
167
+ },
168
+ body: opts.body ? JSON.stringify(opts.body) : void 0
169
+ });
170
+ }
171
+ const cookieOf = (res) => res.headers.getSetCookie().map((c) => c.split(";")[0]).join("; ");
172
+ const lastLink = (to) => {
173
+ const mail = [...outbox].reverse().find((m) => m.to === to);
174
+ if (!mail) throw new Error(`no email for ${to}`);
175
+ const url = mail.text.match(/https?:\/\/\S+/)[0];
176
+ return { mail, path: url.replace(ORIGIN, ""), url };
177
+ };
178
+ async function signUp(address, name = "Someone", invitationId) {
179
+ const callbackURL = invitationId ? `/accept-invitation?invitation=${invitationId}` : "/";
180
+ return call("/api/auth/sign-up/email", { body: { email: address, password: PASSWORD, name, callbackURL } });
181
+ }
182
+ async function verifyAndSignIn(address) {
183
+ const res = await call(lastLink(address).path);
184
+ expect(res.status).toBeLessThan(400);
185
+ const signIn = await call("/api/auth/sign-in/email", { body: { email: address, password: PASSWORD } });
186
+ expect(signIn.status).toBe(200);
187
+ return cookieOf(signIn);
188
+ }
189
+ async function setUpAdmin() {
190
+ expect((await signUp(ADMIN, "Boss")).status).toBe(200);
191
+ return verifyAndSignIn(ADMIN);
192
+ }
193
+ async function addUser(adminCookie, address, roles) {
194
+ const invite = await call("/api/users/invitations", { cookie: adminCookie, body: { email: address, roles } });
195
+ expect(invite.status, await invite.clone().text()).toBe(201);
196
+ const { id } = await invite.json();
197
+ expect((await signUp(address, address.split("@")[0], id)).status).toBe(200);
198
+ const cookie = await verifyAndSignIn(address);
199
+ return { cookie, id };
200
+ }
201
+ return { testDb, ops, settings, storage, connections, brand, backupDir: dir, config, email, app, auth, authz, outbox, call, cookieOf, lastLink, signUp, verifyAndSignIn, setUpAdmin, addUser };
202
+ }
203
+ export {
204
+ ADMIN,
205
+ ORIGIN,
206
+ PASSWORD,
207
+ createHarness,
208
+ testDatabaseUrl
209
+ };