@softistx/janus-kit 0.0.0-stage → 0.6.16

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Steve Tsala
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,271 @@
1
- # Temporary Holding Version
1
+ # @softistx/janus-kit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [`@softistx/janus`](https://github.com/softistx/nxgt-janus/tree/develop/packages/janus) wired in one call:
4
+ users and permissions in PostgreSQL through
5
+ [`@softistx/janus-drizzle`](https://github.com/softistx/nxgt-janus/tree/develop/packages/janus-drizzle) or in MongoDB through
6
+ [`@softistx/janus-mongo`](https://github.com/softistx/nxgt-janus/tree/develop/packages/janus-mongo), sessions and one-time tokens in
7
+ Redis through [`@softistx/janus-redis`](https://github.com/softistx/nxgt-janus/tree/develop/packages/janus-redis), telemetry, a health check
8
+ and a close.
9
+
10
+ ```ts
11
+ import { janus, scryptHasher } from '@softistx/janus';
12
+ import { defineModel, permissions } from '@softistx/janus/permissions';
13
+ import { connectKit, defineConfig } from '@softistx/janus-kit/drizzle';
14
+ import { z } from 'zod';
15
+
16
+ export const kit = await connectKit(
17
+ defineConfig({
18
+ postgres: { url: process.env.JANUS_DATABASE_URL! }, // Janus's own database
19
+ redis: { url: process.env.REDIS_URL! }, // optional: sessions and tokens
20
+ telemetry: true, // optional: @softistx/janus-telemetry
21
+ auth: (adapters) =>
22
+ janus({
23
+ user: z.object({ email: z.email(), name: z.string() }),
24
+ password: { login: 'email' },
25
+ hasher: scryptHasher(),
26
+ ...adapters, // { store, relations }
27
+ }),
28
+ access: ({ relations, auth }) =>
29
+ permissions({
30
+ model: defineModel({
31
+ subjects: auth.types,
32
+ types: {
33
+ document: {
34
+ related: { owners: ['user'], viewers: ['user'] },
35
+ permits: { view: ['owners', 'viewers'] },
36
+ },
37
+ },
38
+ }),
39
+ store: relations,
40
+ }),
41
+ }),
42
+ );
43
+
44
+ const current = await kit.auth.authenticate(request); // null when signed out
45
+ if (current) await kit.access.can(current.user, 'view', { type: 'document', id: 'd1' });
46
+ const health = await kit.ping(); // { ok, postgres, redis } — never throws
47
+ await kit.close();
48
+ ```
49
+
50
+ **You still write `janus()` and `permissions()`**, in the two functions, so
51
+ every type they infer is inferred where you wrote them: `kit.auth.signIn`
52
+ takes your login field, `kit.access.can` your permissions. The kit hands them
53
+ the stores, opens and closes the connections, and checks at startup what
54
+ would otherwise fail at the first sign-in.
55
+
56
+ > **0.x.** A minor version may still change the surface; the changelog says how.
57
+
58
+ ## Install
59
+
60
+ Public on npmjs:
61
+
62
+ ```sh
63
+ bun add @softistx/janus-kit @softistx/janus @softistx/redis zod
64
+ bun add @softistx/janus-drizzle @softistx/drizzle drizzle-orm # for @softistx/janus-kit/drizzle
65
+ bun add @softistx/janus-mongo @softistx/mongo mongodb # for @softistx/janus-kit/mongo
66
+ bun add @softistx/janus-telemetry @softistx/telemetry # only for telemetry: true
67
+ bun add -d @types/bun # the kit's types name Bun's RedisOptions
68
+ ```
69
+
70
+ Required peers, whichever subpath:
71
+ - `@softistx/janus`;
72
+ - `@softistx/redis` `>=0.14.0 <1`, and `zod` 4 which it requires, even with
73
+ sessions in the database: the kit's types name its connection;
74
+ - `typescript` 6 or 7.
75
+
76
+ Peers of `@softistx/janus-kit/drizzle` — optional in `package.json`, so an
77
+ application on another subpath does not install them, but required by this
78
+ one:
79
+ - `@softistx/janus-drizzle`: your schema file imports `defineJanusTables` from it
80
+ to create the tables, and the kit's stores must query the same definition;
81
+ - `@softistx/drizzle` `>=0.8.0 <1` and `drizzle-orm` 1.0 (from `1.0.0-rc.4`), for
82
+ PostgreSQL.
83
+
84
+ Peers of `@softistx/janus-kit/mongo`, optional in the same way:
85
+ - `@softistx/janus-mongo`: `syncMongoAdapter` creates the collections, and the
86
+ kit's stores must query the same definitions;
87
+ - `@softistx/mongo` `>=0.27.0 <1` and `mongodb` 7.
88
+
89
+ The `@softistx/*` floors are tested, not claimed: in the Floors job, on every CI
90
+ run, the kit's mongo specs and its typecheck run on `@softistx/mongo` 0.27.0, and
91
+ its whole suite and typecheck on `@softistx/redis` 0.14.0, `@softistx/drizzle` 0.8.0
92
+ and `@softistx/telemetry` 0.3.0.
93
+
94
+ `@softistx/janus-telemetry` is an optional peer, loaded only when `telemetry` is
95
+ `true`; it requires `@softistx/telemetry` `>=0.3.0 <1` as its own peer. `@softistx/janus-redis` is a dependency: your code never imports it.
96
+
97
+ It runs on **Bun** only: the kit opens PostgreSQL over Bun's `SQL` and Redis
98
+ over Bun's `RedisClient`. It needs PostgreSQL 15 or later, or MongoDB as a
99
+ replica set, and Redis 7.0 or later. Like `@softistx/janus`, it expects `"moduleResolution": "bundler"`.
100
+
101
+ ## Subpaths
102
+
103
+ **One kit, one subpath per database.** The package has **no root entry**, so
104
+ the import names the database: `import … from '@softistx/janus-kit'` fails with
105
+ `TS2307`. Redis, telemetry, `ping` and `close` are the same whichever subpath
106
+ you use.
107
+
108
+ | Subpath | Database | The database key | What `connectKit` checks |
109
+ | --- | --- | --- | --- |
110
+ | `@softistx/janus-kit/drizzle` | PostgreSQL, through `@softistx/janus-drizzle` | `postgres` | Janus's five required tables exist (`social_links` and `passkeys` are opt-in: checked only when `postgres.tables` defines them; `api_keys` is checked only with `apiKeys: true`; `invitations` is never checked, the kit wires no invitation store) |
111
+ | `@softistx/janus-kit/mongo` | MongoDB, through `@softistx/janus-mongo` | `mongo` | Janus's six collections and their indexes exist (`socialLinks` and `passkeys` are opt-in in use, but synced with the rest; `apiKeys` is checked only with `apiKeys: true`); any other difference is a warning |
112
+
113
+ On MongoDB, the example above changes in its first lines only:
114
+
115
+ ```ts
116
+ import { connectKit, defineConfig } from '@softistx/janus-kit/mongo';
117
+
118
+ export const kit = await connectKit(
119
+ defineConfig({
120
+ mongo: { url: process.env.JANUS_MONGO_URL! }, // mongodb://…/janus — the path names the database
121
+ redis: { url: process.env.REDIS_URL! },
122
+ auth: (adapters) => janus({ /* … */ ...adapters }),
123
+ }),
124
+ );
125
+ kit.db; // the Db; (await kit.ping()).mongo
126
+ ```
127
+
128
+ ## API
129
+
130
+ Both subpaths export the same names; they differ in the database key and
131
+ what `db` is.
132
+
133
+ | Export | What it is |
134
+ | --- | --- |
135
+ | `defineConfig(config)` | Checks the configuration and answers it, frozen. It connects to nothing and reads no environment variable. What is wrong throws a `TypeError` here, where the application starts. |
136
+ | `connectKit(config)` | Checks the configuration again, opens the database and Redis, checks Janus's tables or collections, builds `auth` and `access`, and answers the kit. Fails with an `Error` naming what to do — a `TypeError` for a URL it cannot read — after closing what it opened. |
137
+ | `Kit` | What `connectKit` answers: `auth`; `access` when configured; `db`, the Drizzle instance or the MongoDB `Db`; `redis`, the connection or `undefined`; `ping(options?)`; `close()`; and `[Symbol.asyncDispose]`. |
138
+ | `KitConfig`, `RedisConfig`, and `PostgresConfig` from `/drizzle` or `MongoConfig` from `/mongo` | The configuration's types. |
139
+ | `Adapters`, `AccessWiring` | What `auth` and `access` are given: `{ store, relations }` (plus `apiKeyStore` with `apiKeys: true`), and `{ relations, auth }`. |
140
+ | `KitApiKeyStore` | The type of `adapters.apiKeyStore`: an `ApiKeyStore` with the `bound`, `userBound` and `expiryNotice` capabilities. |
141
+ | `Health`, `PingResult` | What `ping` answers: `{ ok, postgres, redis? }` or `{ ok, mongo, redis? }`, each `{ ok: true, latencyMs }` or `{ ok: false, error }`. |
142
+
143
+ ## The configuration
144
+
145
+ | Key | | |
146
+ | --- | --- | --- |
147
+ | `postgres` | required on `/drizzle` | `{ url }` of Janus's database, a `postgres://` or `postgresql://` URL, which the kit opens and closes; or `{ db }`, a Drizzle instance you opened, **never closed** by the kit. `tables`: what your schema file exports, when the tables are in a PostgreSQL schema of their own. |
148
+ | `mongo` | required on `/mongo` | `{ url, clientOptions? }` of Janus's database, a `mongodb://` or `mongodb+srv://` URL whose path names the database, which the kit opens with `serverSelectionTimeoutMS: 5_000` and closes; or `{ db }`, a `Db` you opened, **never closed** by the kit. |
149
+ | `redis` | optional | `{ url, prefix?, clientOptions? }`, which the kit opens with `enableOfflineQueue: false` and closes; or `{ connection, prefix? }`, which it never closes. Absent, sessions and tokens stay in the database. |
150
+ | `telemetry` | optional | `true` wraps `auth` with `instrumentJanus` and `access` with `instrumentPermissions`. |
151
+ | `apiKeys` | optional | `true` opts in to API keys, on both subpaths: the kit checks their table (`api_keys`) or collection (`apiKeys` and its indexes) and hands `auth` the store as `adapters.apiKeyStore`. Absent, nothing API-key related is checked, created or required. |
152
+ | `auth` | required | `(adapters) => janus({ …, ...adapters })`; with `apiKeys: true`, also `apiKeys: { store: adapters.apiKeyStore, prefix, lifetimes }`. |
153
+ | `access` | optional | `({ relations, auth }) => permissions({ model, store: relations })`. Absent, the kit has no `access`, and `kit.access` does not compile. |
154
+
155
+ `adapters` is `{ store, relations }`: users from the database, sessions and
156
+ tokens from Redis when it is wired, and the relation store, so deleting a user
157
+ deletes every tuple naming them. With `apiKeys: true` it also holds
158
+ `apiKeyStore`, which you give to `janus()` yourself, since the prefix and the
159
+ lifetimes are yours:
160
+
161
+ ```ts
162
+ const kit = await connectKit(
163
+ defineConfig({
164
+ postgres: { url: process.env.JANUS_DATABASE_URL! },
165
+ apiKeys: true,
166
+ auth: (adapters) =>
167
+ janus({
168
+ user, password: { login: 'email' }, hasher: scryptHasher(),
169
+ ...adapters,
170
+ apiKeys: { store: adapters.apiKeyStore, prefix: 'sl_', lifetimes: ['30d', '90d'] },
171
+ }),
172
+ }),
173
+ );
174
+ ```
175
+
176
+ [The configuration guide](docs/guide/configuration.md)
177
+ has each key in detail.
178
+
179
+ ## Traps
180
+
181
+ - **Versions up to 0.6.14 treat the optional peers as required.** Their package document lacks `peerDependenciesMeta` ([details](docs/troubleshooting.md#optional-peers-are-installed-as-required)), so Bun installs `@softistx/drizzle`, `@softistx/mongo`, `@softistx/janus-drizzle`, `@softistx/janus-mongo`, `@softistx/janus-telemetry`, `drizzle-orm` and `mongodb` even when you do not use them. `bun install --omit=peer` skips them, but it also skips the required peers: add those back with `bun add @softistx/janus @softistx/redis typescript`, plus the database stack you use: `@softistx/drizzle @softistx/janus-drizzle drizzle-orm` for PostgreSQL, or `@softistx/mongo @softistx/janus-mongo mongodb` for MongoDB (and `@softistx/janus-telemetry` if you use it).
182
+ - **Social login needs its store created first.** On MongoDB the kit refuses
183
+ to start until `syncMongoAdapter(db)` has created `socialLinks`. On
184
+ PostgreSQL it wires `social_links` only when `postgres.tables` defines it
185
+ (typed as `DrizzleAdapterOptions['tables']`); without it social login is off.
186
+ - **Passkeys need their store created first.** The same holds for the optional
187
+ `passkeys` slot: on MongoDB the kit refuses to start until
188
+ `syncMongoAdapter(db)` has created `passkeys`; on PostgreSQL it wires
189
+ `passkeys` only when `postgres.tables` defines it, and the migration (with the
190
+ `tokens_kind` check admitting `passkeyRegistration`) is applied first.
191
+ - **API keys are opt-in, and need their store created first.** With
192
+ `apiKeys: true` the kit refuses to start until the `api_keys` table is
193
+ migrated (PostgreSQL; `postgres.tables` must define `apiKeys`) or
194
+ `syncMongoApiKeys(db)` has created the `apiKeys` collection and its indexes
195
+ (MongoDB). Without the option none of this is checked, even when the table
196
+ or collection exists.
197
+ - **Janus's tables come from your migrations.** `connectKit` checks that the
198
+ five required ones (`users`, `logins`, `sessions`, `tokens`, `relations`)
199
+ exist, and `social_links` and `passkeys` too when `postgres.tables` defines
200
+ them (both are opt-in), and refuses to start otherwise, naming them. Create them with
201
+ drizzle-kit, from `defineJanusTables()`, as
202
+ [`@softistx/janus-drizzle`'s guide](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus-drizzle/docs/guide/database.md)
203
+ shows.
204
+ - **In a PostgreSQL schema of their own, pass `postgres.tables`.** Without it,
205
+ the kit looks for, and the stores query, `users` in the connection's
206
+ `search_path`: `public`, where your application may have a `users` of its
207
+ own.
208
+ - **Janus's collections come from `syncMongoAdapter`**, a deployment step.
209
+ `connectKit` compares them with `@softistx/janus-mongo`'s definitions, writing
210
+ nothing. A missing collection or index refuses to start: MongoDB would
211
+ create a missing collection on the first write **without the unique index
212
+ on logins**. A validator, an option or an index's options that differ only warn
213
+ (`JANUS_KIT_COLLECTIONS_DRIFTED`), so a rollback still starts.
214
+ - **`kit.auth.collectExpired()` answers `UNSUPPORTED` on `/mongo`**: a TTL
215
+ index removes lapsed sessions and tokens there. Schedule it on PostgreSQL
216
+ only, where it deletes both.
217
+ - **A MongoDB URL without a database in its path uses `test`**, the driver's
218
+ default. Name Janus's database in the URL: `mongodb://…/janus`.
219
+ - **A MongoDB that does not answer fails after 5 seconds**, measured: the
220
+ kit's `serverSelectionTimeoutMS`, where the driver's own is 30. A request
221
+ during a replica-set election can fail rather than wait; pass
222
+ `clientOptions: { serverSelectionTimeoutMS }` to wait longer.
223
+ - **A Redis that is down at startup takes about 31 seconds to fail**, measured:
224
+ Bun's client retries its first connection. At run time the kit's
225
+ `enableOfflineQueue: false` makes an outage fail at once.
226
+ - **What you hand in, you close.** A `db` or a `connection` from the
227
+ configuration is left open by `kit.close()`.
228
+ - **`@softistx/mongo` shares one client per URL**, as `@softistx/redis` does below:
229
+ connecting to Janus's MongoDB URL elsewhere with other options is refused.
230
+ - **`@softistx/redis` shares one client per URL.** If your application connects
231
+ to the same Redis URL with other options, `connectRedis` refuses the
232
+ second. Give Janus its own URL, another database number for instance, or
233
+ pass `{ connection }`.
234
+
235
+ ## Documentation
236
+
237
+ - [Guides](docs/README.md): every key of the configuration, the health check,
238
+ and closing
239
+ - [Troubleshooting](docs/troubleshooting.md): look up the error message you see
240
+ - [Roadmap](docs/roadmap.md): what is next, and what is not planned
241
+
242
+ ## Type safety, counted
243
+
244
+ Twenty plausible mistakes are refused by the compiler, each with a
245
+ `@ts-expect-error` case: twelve in `test/types/kit.ts`, over PostgreSQL,
246
+ - `kit.access` on a kit configured without `access`;
247
+ - a user type `auth` does not have;
248
+ - a permission the model does not have;
249
+ - both `postgres.url` and `postgres.db`;
250
+ - both `redis.url` and `redis.connection`;
251
+ - `redis.clientOptions` beside a `connection` already open;
252
+ - `postgres.schema` instead of the tables built in it;
253
+ - a configuration without `auth`;
254
+ - `postgres` with neither `url` nor `db`;
255
+ - `telemetry` as a string, as an environment variable reads;
256
+ - `adapters.apiKeyStore` without `apiKeys: true`;
257
+ - `adapters.apiKeyStore` with `apiKeys` only known to be a boolean;
258
+
259
+ and eight in `test/types/mongo.ts`, over MongoDB:
260
+ - `kit.access` on a kit configured without `access`;
261
+ - `ping()`'s `postgres` on a MongoDB kit, which answers `mongo`;
262
+ - both `mongo.url` and `mongo.db`;
263
+ - `mongo.clientOptions` beside a `Db` whose client is already open;
264
+ - the `postgres` key given to the MongoDB kit;
265
+ - `mongo` with neither `url` nor `db`;
266
+ - `adapters.apiKeyStore` without `apiKeys: true`;
267
+ - `adapters.apiKeyStore` with `apiKeys` only known to be a boolean.
268
+
269
+ ## Licence
270
+
271
+ MIT
@@ -0,0 +1,187 @@
1
+ // src/shared/config.ts
2
+ function checkShared(config, where, database) {
3
+ const { redis, telemetry, apiKeys, auth, access } = config;
4
+ if (redis !== undefined) {
5
+ if (typeof redis !== "object" || redis === null) {
6
+ throw new TypeError(`${where}: \`redis\` is { url } or { connection }, or absent to keep sessions in ${database.label}.`);
7
+ }
8
+ oneOf(where, "redis", redis, "url", "connection");
9
+ if (redis.url !== undefined)
10
+ nonEmpty(where, "redis.url", redis.url);
11
+ if (redis.connection !== undefined && redis.clientOptions !== undefined) {
12
+ throw new TypeError(`${where}: \`redis.clientOptions\` beside \`redis.connection\` — the connection is already open with its own. Pass the options where you opened it.`);
13
+ }
14
+ if (redis.prefix !== undefined) {
15
+ nonEmpty(where, "redis.prefix", redis.prefix);
16
+ }
17
+ }
18
+ if (telemetry !== undefined && typeof telemetry !== "boolean") {
19
+ throw new TypeError(`${where}: \`telemetry\` is true or false.`);
20
+ }
21
+ if (apiKeys !== undefined && typeof apiKeys !== "boolean") {
22
+ throw new TypeError(`${where}: \`apiKeys\` is true or false.`);
23
+ }
24
+ if (typeof auth !== "function") {
25
+ throw new TypeError(`${where}: \`auth\` is required — (adapters) => janus({ …, ...adapters }).`);
26
+ }
27
+ if (access !== undefined && typeof access !== "function") {
28
+ throw new TypeError(`${where}: \`access\` is ({ relations, auth }) => permissions({ model, store: relations }).`);
29
+ }
30
+ }
31
+ function checkObject(config, where) {
32
+ if (typeof config !== "object" || config === null) {
33
+ throw new TypeError(`${where}: pass the kit's configuration, an object.`);
34
+ }
35
+ }
36
+ function oneOf(where, name, value, first, second) {
37
+ const has = (key) => value[key] !== undefined;
38
+ if (has(first) === has(second)) {
39
+ throw new TypeError(has(first) ? `${where}: \`${name}\` has both ${first} and ${second}. Pass one.` : `${where}: \`${name}\` needs ${first} or ${second}.`);
40
+ }
41
+ }
42
+ function nonEmpty(where, name, value) {
43
+ if (typeof value !== "string" || value === "") {
44
+ throw new TypeError(`${where}: \`${name}\` is a non-empty string.`);
45
+ }
46
+ }
47
+
48
+ // src/shared/health.ts
49
+ async function probe(probes, timeoutMs) {
50
+ const entries = await Promise.all(Object.entries(probes).map(async ([name, run]) => [name, await run(timeoutMs)]));
51
+ const results = Object.fromEntries(entries);
52
+ return {
53
+ ok: entries.every(([, result]) => result.ok),
54
+ ...results
55
+ };
56
+ }
57
+ async function timed(run, timeoutMs) {
58
+ const started = performance.now();
59
+ let timer;
60
+ try {
61
+ await Promise.race([
62
+ run(),
63
+ new Promise((_, reject) => {
64
+ timer = setTimeout(() => reject(new Error(`ping: no answer in ${timeoutMs}ms`)), timeoutMs);
65
+ })
66
+ ]);
67
+ return { ok: true, latencyMs: performance.now() - started };
68
+ } catch (error) {
69
+ return { ok: false, error };
70
+ } finally {
71
+ clearTimeout(timer);
72
+ }
73
+ }
74
+
75
+ // src/shared/kit.ts
76
+ import { createRedisStores } from "@softistx/janus-redis";
77
+
78
+ // src/shared/uri-conflict.ts
79
+ function isUriConflict(cause) {
80
+ return cause instanceof Error && cause.code === "URI_CONFLICT";
81
+ }
82
+
83
+ // src/shared/kit.ts
84
+ async function assembleKit(config, open) {
85
+ const { closers, close, failStart } = lifecycle();
86
+ try {
87
+ const opened = await open(closers);
88
+ const redis = await openRedis(config.redis, closers, opened.database.label);
89
+ const adapters = {
90
+ store: redis === undefined ? opened.store : {
91
+ ...opened.store,
92
+ ...createRedisStores(redis, {
93
+ ...config.redis?.prefix === undefined ? {} : { prefix: config.redis.prefix }
94
+ })
95
+ },
96
+ relations: opened.relations,
97
+ ...opened.apiKeyStore === undefined ? {} : { apiKeyStore: opened.apiKeyStore }
98
+ };
99
+ const instrument = config.telemetry === true ? await loadTelemetry() : undefined;
100
+ let auth = config.auth(adapters);
101
+ if (instrument !== undefined)
102
+ auth = instrument.janus(auth);
103
+ let access;
104
+ if (config.access !== undefined) {
105
+ access = config.access({ relations: adapters.relations, auth });
106
+ if (instrument !== undefined)
107
+ access = instrument.permissions(access);
108
+ }
109
+ const probes = {
110
+ [opened.database.key]: opened.probe,
111
+ ...redis === undefined ? {} : { redis: (timeoutMs) => redis.ping({ timeoutMs }) }
112
+ };
113
+ const kit = {
114
+ auth,
115
+ ...config.access === undefined ? {} : { access },
116
+ db: opened.db,
117
+ redis,
118
+ ping: async (options) => await probe(probes, options?.timeoutMs ?? 2000),
119
+ close,
120
+ [Symbol.asyncDispose]: close
121
+ };
122
+ return Object.freeze(kit);
123
+ } catch (error) {
124
+ return await failStart(error);
125
+ }
126
+ }
127
+ function lifecycle() {
128
+ const closers = [];
129
+ const closeAll = async () => {
130
+ const failures = [];
131
+ for (const closeOne of closers.splice(0).reverse()) {
132
+ await closeOne().catch((error) => failures.push(error));
133
+ }
134
+ return failures;
135
+ };
136
+ let closing;
137
+ const close = () => {
138
+ closing ??= closeAll().then((failures) => {
139
+ if (failures.length === 1)
140
+ throw failures[0];
141
+ if (failures.length > 1) {
142
+ throw new AggregateError(failures, "kit.close: several connections failed to close");
143
+ }
144
+ });
145
+ return closing;
146
+ };
147
+ const failStart = async (error) => {
148
+ for (const failure of await closeAll()) {
149
+ process.emitWarning(`connectKit: a connection failed to close after the kit failed to start: ${String(failure)}`, { code: "JANUS_KIT_CLOSE_FAILED" });
150
+ }
151
+ throw error;
152
+ };
153
+ return { closers, close, failStart };
154
+ }
155
+ async function openRedis(redis, closers, label) {
156
+ if (redis === undefined)
157
+ return;
158
+ if (redis.url === undefined)
159
+ return redis.connection;
160
+ const { connectRedis } = await import("@softistx/redis");
161
+ const connection = await connectRedis(redis.url, {
162
+ enableOfflineQueue: false,
163
+ ...redis.clientOptions
164
+ }).catch((cause) => {
165
+ if (cause instanceof TypeError || isUriConflict(cause))
166
+ throw cause;
167
+ throw new Error(`connectKit: Redis did not answer. Check \`redis.url\`, or leave \`redis\` out to keep sessions in ${label}.`, { cause });
168
+ });
169
+ closers.push(() => connection.close());
170
+ return connection;
171
+ }
172
+ async function loadTelemetry() {
173
+ try {
174
+ const telemetry = await import("@softistx/janus-telemetry");
175
+ return {
176
+ janus: (auth) => telemetry.instrumentJanus(auth),
177
+ permissions: (access) => telemetry.instrumentPermissions(access)
178
+ };
179
+ } catch (cause) {
180
+ throw new Error("connectKit: `telemetry: true` needs @softistx/janus-telemetry — `bun add @softistx/janus-telemetry @softistx/telemetry`.", { cause });
181
+ }
182
+ }
183
+
184
+ export { checkShared, checkObject, oneOf, nonEmpty, timed, isUriConflict, assembleKit };
185
+
186
+ //# debugId=6A4496CC3953B85364756E2164756E21
187
+ //# sourceMappingURL=index-vw036wd3.js.map
@@ -0,0 +1,13 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/shared/config.ts", "../src/shared/health.ts", "../src/shared/kit.ts", "../src/shared/uri-conflict.ts"],
4
+ "sourcesContent": [
5
+ "import type {\n\tApiKeyBoundMethods,\n\tApiKeyExpiryNoticeMethods,\n\tApiKeyStore,\n\tApiKeyUserBoundMethods,\n\tJanusStores,\n} from '@softistx/janus';\nimport type { RelationStore } from '@softistx/janus/permissions';\nimport type { RedisConnection } from '@softistx/redis';\nimport type { RedisOptions } from 'bun';\n\n/**\n * Where sessions and one-time tokens are kept instead. The URL, which the kit\n * connects to with `enableOfflineQueue: false` unless `clientOptions` says\n * otherwise, and closes; or a connection you opened, which it never closes.\n */\nexport type RedisConfig =\n\t| {\n\t\t\treadonly url: string;\n\t\t\treadonly connection?: never;\n\t\t\t/** Bun's `RedisOptions`, over the kit's `{ enableOfflineQueue: false }`. */\n\t\t\treadonly clientOptions?: RedisOptions;\n\t\t\t/** What every key starts with: `janus:` by default. */\n\t\t\treadonly prefix?: string;\n\t }\n\t| {\n\t\t\treadonly connection: RedisConnection;\n\t\t\treadonly url?: never;\n\t\t\treadonly clientOptions?: never;\n\t\t\treadonly prefix?: string;\n\t };\n\n/** The API key store the kit builds when `apiKeys` is `true`, with every optional capability. */\nexport type KitApiKeyStore = ApiKeyStore &\n\tApiKeyBoundMethods &\n\tApiKeyUserBoundMethods &\n\tApiKeyExpiryNoticeMethods;\n\n/**\n * What `auth` is built from: spread it into `janus()`. With `apiKeys: true`\n * it also holds `apiKeyStore`, for `janus({ apiKeys: { store: adapters.apiKeyStore, … } })`.\n */\nexport type Adapters<WithApiKeys extends boolean = boolean> = BaseAdapters &\n\t([WithApiKeys] extends [true]\n\t\t? { readonly apiKeyStore: KitApiKeyStore }\n\t\t: unknown);\n\n/** What `auth` is built from, whatever the options. */\nexport interface BaseAdapters {\n\t/** Users from the database; sessions and tokens from Redis when it is wired. */\n\treadonly store: JanusStores;\n\t/** The relation store: deleting a user deletes every tuple naming them. */\n\treadonly relations: RelationStore;\n}\n\n/** What `access` is built from. */\nexport interface AccessWiring<A> {\n\treadonly relations: RelationStore;\n\t/** The instance `auth` returned: its `types` are the model's subjects. */\n\treadonly auth: A;\n}\n\n/**\n * The keys every kit shares, whatever the database. **`auth` and `access`\n * are yours to write**, so `janus()` and `defineModel()` infer every type\n * where you call them; the kit hands them the stores.\n */\nexport interface SharedConfig<\n\tA extends object,\n\tP extends object,\n\tWithApiKeys extends boolean = false,\n> {\n\treadonly redis?: RedisConfig;\n\t/**\n\t * `true` opts in to API keys: the kit checks their table (or collection and\n\t * indexes) and hands `auth` the store as `adapters.apiKeyStore`. Without it\n\t * nothing API-key related is checked, created or required.\n\t */\n\treadonly apiKeys?: WithApiKeys;\n\t/**\n\t * `true` wraps `auth` and `access` with `@softistx/janus-telemetry`'s\n\t * `instrumentJanus` and `instrumentPermissions`, an optional peer.\n\t */\n\treadonly telemetry?: boolean;\n\treadonly auth: (adapters: Adapters<WithApiKeys>) => A;\n\treadonly access?: (wiring: AccessWiring<A>) => P;\n}\n\n/** What the checks read: every shared key, whatever `auth` and `access` build. */\nexport interface UncheckedShared {\n\treadonly redis?: RedisConfig | undefined;\n\treadonly telemetry?: boolean | undefined;\n\treadonly apiKeys?: boolean | undefined;\n\treadonly auth: unknown;\n\treadonly access?: unknown;\n}\n\n/**\n * A database the kit wires, named once per module: `key`, the name `ping`\n * reports it under; `label`, the name a message gives it, as where sessions\n * stay without Redis.\n */\nexport interface Database<Key extends string> {\n\treadonly key: Key;\n\treadonly label: string;\n}\n\n/** The shared keys' checks, after the database's own. */\nexport function checkShared(\n\tconfig: UncheckedShared,\n\twhere: string,\n\tdatabase: Database<string>,\n): void {\n\tconst { redis, telemetry, apiKeys, auth, access } = config;\n\tif (redis !== undefined) {\n\t\tif (typeof redis !== 'object' || redis === null) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${where}: \\`redis\\` is { url } or { connection }, or absent to keep sessions in ${database.label}.`,\n\t\t\t);\n\t\t}\n\t\toneOf(where, 'redis', redis, 'url', 'connection');\n\t\tif (redis.url !== undefined) nonEmpty(where, 'redis.url', redis.url);\n\t\tif (redis.connection !== undefined && redis.clientOptions !== undefined) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${where}: \\`redis.clientOptions\\` beside \\`redis.connection\\` — the connection is already open with its own. Pass the options where you opened it.`,\n\t\t\t);\n\t\t}\n\t\tif (redis.prefix !== undefined) {\n\t\t\tnonEmpty(where, 'redis.prefix', redis.prefix);\n\t\t}\n\t}\n\tif (telemetry !== undefined && typeof telemetry !== 'boolean') {\n\t\tthrow new TypeError(`${where}: \\`telemetry\\` is true or false.`);\n\t}\n\tif (apiKeys !== undefined && typeof apiKeys !== 'boolean') {\n\t\tthrow new TypeError(`${where}: \\`apiKeys\\` is true or false.`);\n\t}\n\tif (typeof auth !== 'function') {\n\t\tthrow new TypeError(\n\t\t\t`${where}: \\`auth\\` is required — (adapters) => janus({ …, ...adapters }).`,\n\t\t);\n\t}\n\tif (access !== undefined && typeof access !== 'function') {\n\t\tthrow new TypeError(\n\t\t\t`${where}: \\`access\\` is ({ relations, auth }) => permissions({ model, store: relations }).`,\n\t\t);\n\t}\n}\n\n/** Refuses a configuration that is not an object at all. */\nexport function checkObject(config: unknown, where: string): void {\n\tif (typeof config !== 'object' || config === null) {\n\t\tthrow new TypeError(`${where}: pass the kit's configuration, an object.`);\n\t}\n}\n\n/** Exactly one of `first` and `second`. */\nexport function oneOf(\n\twhere: string,\n\tname: string,\n\tvalue: object,\n\tfirst: string,\n\tsecond: string,\n): void {\n\tconst has = (key: string) =>\n\t\t(value as Record<string, unknown>)[key] !== undefined;\n\tif (has(first) === has(second)) {\n\t\tthrow new TypeError(\n\t\t\thas(first)\n\t\t\t\t? `${where}: \\`${name}\\` has both ${first} and ${second}. Pass one.`\n\t\t\t\t: `${where}: \\`${name}\\` needs ${first} or ${second}.`,\n\t\t);\n\t}\n}\n\nexport function nonEmpty(where: string, name: string, value: unknown): void {\n\tif (typeof value !== 'string' || value === '') {\n\t\tthrow new TypeError(`${where}: \\`${name}\\` is a non-empty string.`);\n\t}\n}\n",
6
+ "/** What one round trip found. It never throws: a health check reports. */\nexport type PingResult =\n\t| { readonly ok: true; readonly latencyMs: number }\n\t| { readonly ok: false; readonly error: unknown };\n\n/**\n * The database, under its own name — `postgres`, `mongo` — and `redis` when\n * it is wired; `ok` when every one answered.\n */\nexport type HealthOf<Database extends string> = {\n\treadonly ok: boolean;\n\treadonly redis?: PingResult;\n} & { readonly [Name in Database]: PingResult };\n\nexport type Probe = (timeoutMs: number) => Promise<PingResult>;\n\n/** The database's probe under its own name, and Redis's when it is wired. */\nexport type Probes<Database extends string> = {\n\treadonly [Name in Database]: Probe;\n} & { readonly redis?: Probe };\n\n/** Every probe at once, each within `timeoutMs`. */\nexport async function probe<Database extends string>(\n\tprobes: Probes<Database>,\n\ttimeoutMs: number,\n): Promise<HealthOf<Database>> {\n\tconst entries = await Promise.all(\n\t\t(Object.entries(probes) as [string, Probe][]).map(\n\t\t\tasync ([name, run]) => [name, await run(timeoutMs)] as const,\n\t\t),\n\t);\n\tconst results = Object.fromEntries(entries) as Record<string, PingResult>;\n\treturn {\n\t\tok: entries.every(([, result]) => result.ok),\n\t\t...results,\n\t} as HealthOf<Database>;\n}\n\n/**\n * `run`, answered within `timeoutMs`, as `ping` reports it: a round trip that\n * throws or takes longer is `{ ok: false, error }`.\n */\nexport async function timed(\n\trun: () => Promise<unknown>,\n\ttimeoutMs: number,\n): Promise<PingResult> {\n\tconst started = performance.now();\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\ttry {\n\t\tawait Promise.race([\n\t\t\trun(),\n\t\t\tnew Promise<never>((_, reject) => {\n\t\t\t\ttimer = setTimeout(\n\t\t\t\t\t() => reject(new Error(`ping: no answer in ${timeoutMs}ms`)),\n\t\t\t\t\ttimeoutMs,\n\t\t\t\t);\n\t\t\t}),\n\t\t]);\n\t\treturn { ok: true, latencyMs: performance.now() - started };\n\t} catch (error) {\n\t\treturn { ok: false, error };\n\t} finally {\n\t\tclearTimeout(timer);\n\t}\n}\n",
7
+ "import type { JanusStores } from '@softistx/janus';\nimport type { RelationStore } from '@softistx/janus/permissions';\nimport { createRedisStores } from '@softistx/janus-redis';\nimport type { RedisConnection } from '@softistx/redis';\nimport type {\n\tAdapters,\n\tDatabase,\n\tKitApiKeyStore,\n\tRedisConfig,\n\tSharedConfig,\n} from './config';\nimport { type HealthOf, type Probe, type Probes, probe } from './health';\nimport { isUriConflict } from './uri-conflict';\n\n/**\n * What `connectKit` answers, whatever the database: `auth`, `access` when\n * configured, `db`, and the rest. `Key` is the name `ping` reports the\n * database under.\n */\nexport type KitOf<\n\tA extends object,\n\tP extends object,\n\tDb,\n\tKey extends string,\n> = {\n\t/** What your `auth` returned, instrumented when `telemetry` is on. */\n\treadonly auth: A;\n\t/** The database Janus's stores query. */\n\treadonly db: Db;\n\t/** The Redis connection, when `redis` is configured. */\n\treadonly redis: RedisConnection | undefined;\n\t/**\n\t * The database's and Redis's answers to a round trip, within `timeoutMs`\n\t * (2 s by default). **Never throws**: a health route always has something\n\t * to report.\n\t */\n\tping(options?: { readonly timeoutMs?: number }): Promise<HealthOf<Key>>;\n\t/**\n\t * Closes what the kit opened — Redis, then the database — and nothing it\n\t * was handed. Idempotent.\n\t */\n\tclose(): Promise<void>;\n} & ([P] extends [never]\n\t? unknown\n\t: {\n\t\t\t/** What your `access` returned, instrumented when `telemetry` is on. */\n\t\t\treadonly access: P;\n\t\t}) &\n\tAsyncDisposable;\n\n/** A close, pushed as soon as what it closes is open. */\nexport type Closers = (() => Promise<void>)[];\n\n/** What the database's module opened, and checked, for the kit to wire. */\nexport interface Opened<Db, Key extends string> {\n\treadonly database: Database<Key>;\n\treadonly db: Db;\n\t/** Its identity stores and relation store, built over `db`. */\n\treadonly store: JanusStores;\n\treadonly relations: RelationStore;\n\t/** The API key store, built only when `apiKeys` is `true`. */\n\treadonly apiKeyStore?: KitApiKeyStore;\n\treadonly probe: Probe;\n}\n\n/**\n * Everything after the database: Redis, telemetry, `auth` and `access`,\n * `ping`, `close`. `open` opens and checks the database, pushing its close\n * onto `closers` as soon as there is something to close; **whatever fails\n * closes what was opened** before the error is seen.\n */\nexport async function assembleKit<\n\tA extends object,\n\tP extends object,\n\tDb,\n\tKey extends string,\n\tWithApiKeys extends boolean = false,\n>(\n\tconfig: SharedConfig<A, P, WithApiKeys>,\n\topen: (closers: Closers) => Promise<Opened<Db, Key>>,\n): Promise<KitOf<A, P, Db, Key>> {\n\tconst { closers, close, failStart } = lifecycle();\n\ttry {\n\t\tconst opened = await open(closers);\n\t\tconst redis = await openRedis(config.redis, closers, opened.database.label);\n\t\tconst adapters = {\n\t\t\tstore:\n\t\t\t\tredis === undefined\n\t\t\t\t\t? opened.store\n\t\t\t\t\t: {\n\t\t\t\t\t\t\t...opened.store,\n\t\t\t\t\t\t\t...createRedisStores(redis, {\n\t\t\t\t\t\t\t\t...(config.redis?.prefix === undefined\n\t\t\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t\t\t: { prefix: config.redis.prefix }),\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t},\n\t\t\trelations: opened.relations,\n\t\t\t...(opened.apiKeyStore === undefined\n\t\t\t\t? {}\n\t\t\t\t: { apiKeyStore: opened.apiKeyStore }),\n\t\t\t// The type follows `config.apiKeys`; `apiKeyStore` is built only when it is true.\n\t\t} as Adapters<WithApiKeys>;\n\n\t\tconst instrument =\n\t\t\tconfig.telemetry === true ? await loadTelemetry() : undefined;\n\t\tlet auth = config.auth(adapters);\n\t\tif (instrument !== undefined) auth = instrument.janus(auth);\n\t\tlet access: P | undefined;\n\t\tif (config.access !== undefined) {\n\t\t\taccess = config.access({ relations: adapters.relations, auth });\n\t\t\tif (instrument !== undefined) access = instrument.permissions(access);\n\t\t}\n\n\t\tconst probes = {\n\t\t\t[opened.database.key]: opened.probe,\n\t\t\t...(redis === undefined\n\t\t\t\t? {}\n\t\t\t\t: { redis: (timeoutMs: number) => redis.ping({ timeoutMs }) }),\n\t\t} as Probes<Key>;\n\t\tconst kit = {\n\t\t\tauth,\n\t\t\t...(config.access === undefined ? {} : { access }),\n\t\t\tdb: opened.db,\n\t\t\tredis,\n\t\t\tping: async (options?: { readonly timeoutMs?: number }) =>\n\t\t\t\tawait probe(probes, options?.timeoutMs ?? 2_000),\n\t\t\tclose,\n\t\t\t[Symbol.asyncDispose]: close,\n\t\t};\n\t\treturn Object.freeze(kit) as unknown as KitOf<A, P, Db, Key>;\n\t} catch (error) {\n\t\treturn await failStart(error);\n\t}\n}\n\n/**\n * The closes, in reverse of the opens — Redis before the database. `close`\n * is the kit's, idempotent, rejecting with the one failure or an\n * `AggregateError`; `failStart` closes on the way out of a failed start and\n * rethrows the error that stopped it.\n */\nexport function lifecycle() {\n\tconst closers: Closers = [];\n\t/** Closes everything opened; answers what failed to close. */\n\tconst closeAll = async () => {\n\t\tconst failures: unknown[] = [];\n\t\tfor (const closeOne of closers.splice(0).reverse()) {\n\t\t\tawait closeOne().catch((error: unknown) => failures.push(error));\n\t\t}\n\t\treturn failures;\n\t};\n\tlet closing: Promise<void> | undefined;\n\tconst close = () => {\n\t\tclosing ??= closeAll().then((failures) => {\n\t\t\tif (failures.length === 1) throw failures[0];\n\t\t\tif (failures.length > 1) {\n\t\t\t\tthrow new AggregateError(\n\t\t\t\t\tfailures,\n\t\t\t\t\t'kit.close: several connections failed to close',\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\t\treturn closing;\n\t};\n\tconst failStart = async (error: unknown): Promise<never> => {\n\t\t// The error that stopped the kit is the one to see; a failure to\n\t\t// close on the way out is only reported.\n\t\tfor (const failure of await closeAll()) {\n\t\t\tprocess.emitWarning(\n\t\t\t\t`connectKit: a connection failed to close after the kit failed to start: ${String(failure)}`,\n\t\t\t\t{ code: 'JANUS_KIT_CLOSE_FAILED' },\n\t\t\t);\n\t\t}\n\t\tthrow error;\n\t};\n\treturn { closers, close, failStart };\n}\n\nasync function openRedis(\n\tredis: RedisConfig | undefined,\n\tclosers: Closers,\n\tlabel: string,\n): Promise<RedisConnection | undefined> {\n\tif (redis === undefined) return undefined;\n\tif (redis.url === undefined) return redis.connection;\n\tconst { connectRedis } = await import('@softistx/redis');\n\tconst connection = await connectRedis(redis.url, {\n\t\tenableOfflineQueue: false,\n\t\t...redis.clientOptions,\n\t}).catch((cause: unknown) => {\n\t\t// A refused configuration — this URL already connected with other\n\t\t// options — is not an outage: it passes through as it is. Before\n\t\t// @softistx/redis 0.24 it is a TypeError, from 0.24 a RedisError with\n\t\t// code URI_CONFLICT; the peer range accepts both.\n\t\tif (cause instanceof TypeError || isUriConflict(cause)) throw cause;\n\t\tthrow new Error(\n\t\t\t`connectKit: Redis did not answer. Check \\`redis.url\\`, or leave \\`redis\\` out to keep sessions in ${label}.`,\n\t\t\t{ cause },\n\t\t);\n\t});\n\tclosers.push(() => connection.close());\n\treturn connection;\n}\n\n/** `@softistx/janus-telemetry`, an optional peer: loaded only when asked for. */\nexport async function loadTelemetry() {\n\ttry {\n\t\tconst telemetry = await import('@softistx/janus-telemetry');\n\t\treturn {\n\t\t\tjanus: <A>(auth: A) =>\n\t\t\t\ttelemetry.instrumentJanus(\n\t\t\t\t\tauth as Parameters<typeof telemetry.instrumentJanus>[0],\n\t\t\t\t) as A,\n\t\t\tpermissions: <P>(access: P) =>\n\t\t\t\ttelemetry.instrumentPermissions(\n\t\t\t\t\taccess as Parameters<typeof telemetry.instrumentPermissions>[0],\n\t\t\t\t) as P,\n\t\t};\n\t} catch (cause) {\n\t\tthrow new Error(\n\t\t\t'connectKit: `telemetry: true` needs @softistx/janus-telemetry — `bun add @softistx/janus-telemetry @softistx/telemetry`.',\n\t\t\t{ cause },\n\t\t);\n\t}\n}\n",
8
+ "/**\n * The refusal of a URL already connected with other options, from\n * `@softistx/redis` 0.24+ and `@softistx/mongo` 0.30+ (code `URI_CONFLICT`).\n * Earlier versions refuse with a `TypeError`, which callers test beside this;\n * the peer ranges accept both. Matched on `code`, so neither package's error\n * class is imported.\n */\nexport function isUriConflict(cause: unknown): boolean {\n\treturn (\n\t\tcause instanceof Error &&\n\t\t(cause as { code?: unknown }).code === 'URI_CONFLICT'\n\t);\n}\n"
9
+ ],
10
+ "mappings": ";AA4GO,SAAS,WAAW,CAC1B,QACA,OACA,UACO;AAAA,EACP,QAAQ,OAAO,WAAW,SAAS,MAAM,WAAW;AAAA,EACpD,IAAI,UAAU,WAAW;AAAA,IACxB,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM;AAAA,MAChD,MAAM,IAAI,UACT,GAAG,gFAAgF,SAAS,QAC7F;AAAA,IACD;AAAA,IACA,MAAM,OAAO,SAAS,OAAO,OAAO,YAAY;AAAA,IAChD,IAAI,MAAM,QAAQ;AAAA,MAAW,SAAS,OAAO,aAAa,MAAM,GAAG;AAAA,IACnE,IAAI,MAAM,eAAe,aAAa,MAAM,kBAAkB,WAAW;AAAA,MACxE,MAAM,IAAI,UACT,GAAG,iJACJ;AAAA,IACD;AAAA,IACA,IAAI,MAAM,WAAW,WAAW;AAAA,MAC/B,SAAS,OAAO,gBAAgB,MAAM,MAAM;AAAA,IAC7C;AAAA,EACD;AAAA,EACA,IAAI,cAAc,aAAa,OAAO,cAAc,WAAW;AAAA,IAC9D,MAAM,IAAI,UAAU,GAAG,wCAAwC;AAAA,EAChE;AAAA,EACA,IAAI,YAAY,aAAa,OAAO,Y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D;AAAA,MACD;AAAA,KACA;AAAA,IACD,OAAO;AAAA;AAAA,EAER,MAAM,YAAY,OAAO,UAAmC;AAAA,IAG3D,WAAW,WAAW,MAAM,SAAS,GAAG;AAAA,MACvC,QAAQ,YACP,2EAA2E,OAAO,OAAO,KACzF,EAAE,MAAM,yBAAyB,CAClC;AAAA,IACD;AAAA,IACA,MAAM;AAAA;AAAA,EAEP,OAAO,EAAE,SAAS,OAAO,UAAU;AAAA;AAGpC,eAAe,SAAS,CACvB,OACA,SACA,OACuC;AAAA,EACvC,IAAI,UAAU;AAAA,IAAW;AAAA,EACzB,IAAI,MAAM,QAAQ;AAAA,IAAW,OAAO,MAAM;AAAA,EAC1C,QAAQ,iBAAiB,MAAM;AAAA,EAC/B,MAAM,aAAa,MAAM,aAAa,MAAM,KAAK;AAAA,IAChD,oBAAoB;AAAA,OACjB,MAAM;AAAA,EACV,CAAC,EAAE,MAAM,CAAC,UAAmB;AAAA,IAK5B,IAAI,iBAAiB,aAAa,cAAc,KAAK;AAAA,MAAG,MAAM;AAAA,IAC9D,MAAM,IAAI,MACT,qGAAqG,UACrG,EAAE,MAAM,CACT;AAAA,GACA;AAAA,EACD,QAAQ,KAAK,MAAM,WAAW,MAAM,CAAC;AAAA,EACrC,OAAO;AAAA;AAID,eAAe,aAAa,GAAG;AAAA,EACrC,IAAI;AAAA,IACH,MAAM,YAAY,MAAM;AAAA,IACxB,OAAO;AAAA,MACN,OAAO,CAAI,SACA,0BACT,IACD;AAAA,MACD,aAAa,CAAI,WACN,gCACT,MACD;AAAA,IACF;AAAA,IACC,OAAO,OAAO;AAAA,IACf,MAAM,IAAI,MACT,4HACA,EAAE,MAAM,CACT;AAAA;AAAA;",
11
+ "debugId": "6A4496CC3953B85364756E2164756E21",
12
+ "names": []
13
+ }
@@ -0,0 +1,49 @@
1
+ import type { PgDatabase } from '@softistx/drizzle/pg';
2
+ import type { DrizzleAdapterOptions } from '@softistx/janus-drizzle';
3
+ import { type Database, type SharedConfig, type UncheckedShared } from '../shared/config';
4
+ /** PostgreSQL, as `ping` and the messages name it. */
5
+ export declare const postgresDatabase: Database<'postgres'>;
6
+ /**
7
+ * Where users, logins, relations — and sessions and tokens, unless Redis
8
+ * holds them — are kept. **The URL of a database of Janus's own**, which the
9
+ * kit opens over Bun's `SQL` and closes; or a Drizzle instance you opened,
10
+ * which it never closes.
11
+ */
12
+ export type PostgresConfig = {
13
+ readonly url: string;
14
+ readonly db?: never;
15
+ /** What your schema file exports, when the tables are in a PostgreSQL schema of their own. */
16
+ readonly tables?: DrizzleAdapterOptions['tables'];
17
+ } | {
18
+ readonly db: PgDatabase;
19
+ readonly url?: never;
20
+ readonly tables?: DrizzleAdapterOptions['tables'];
21
+ };
22
+ /** The kit's configuration over PostgreSQL: `postgres`, then the shared keys. */
23
+ export interface KitConfig<A extends object, P extends object, WithApiKeys extends boolean = false> extends SharedConfig<A, P, WithApiKeys> {
24
+ readonly postgres: PostgresConfig;
25
+ }
26
+ /**
27
+ * The configuration, **checked once, where the application starts**. It
28
+ * connects to nothing and reads no environment variable: write
29
+ * `process.env.JANUS_DATABASE_URL!` where your other settings are read.
30
+ *
31
+ * ```ts
32
+ * export const config = defineConfig({
33
+ * postgres: { url: process.env.JANUS_DATABASE_URL! },
34
+ * redis: { url: process.env.REDIS_URL! },
35
+ * auth: (adapters) => janus({ user, password: { login: 'email' }, hasher: scryptHasher(), ...adapters }),
36
+ * });
37
+ * ```
38
+ */
39
+ export declare function defineConfig<A extends object, P extends object = never, const WithApiKeys extends boolean = false>(config: KitConfig<A, P, WithApiKeys>): KitConfig<A, P, WithApiKeys>;
40
+ /**
41
+ * The checks, run by `defineConfig` and again by `connectKit`: a configuration
42
+ * is often built in one file and connected in another, and one that skipped
43
+ * `defineConfig` must not reach Bun's `SQL`, which reads `DATABASE_URL` for a
44
+ * missing URL.
45
+ */
46
+ export declare function checkConfig(config: UncheckedShared & {
47
+ readonly postgres: PostgresConfig;
48
+ }, where: string): void;
49
+ //# sourceMappingURL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AC,EAAE,WAAW,CAAC,GAAG,SAAS,CAAC,CAAC,EAAE,CAAC,EAAE,WAAW,CAAC,CAGpE;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAC1B,MAAM,EAAE,eAAe,GAAG;IAAE,QAAQ,CAAC,QAAQ,EAAE,cAAc,CAAA;CAAE,EAC/D,KAAK,EAAE,MAAM,GACX,IAAI,CA+BN"}
@@ -0,0 +1,24 @@
1
+ import type { PgDatabase } from '@softistx/drizzle/pg';
2
+ import type { HealthOf } from '../shared/health';
3
+ import { type KitOf } from '../shared/kit';
4
+ import { type KitConfig } from './config';
5
+ /** What `ping` answers: `{ ok, postgres, redis? }`. */
6
+ export type Health = HealthOf<'postgres'>;
7
+ /** What `connectKit` answers: `auth`, `access` when configured, and the rest. */
8
+ export type Kit<A extends object, P extends object> = KitOf<A, P, PgDatabase, 'postgres'>;
9
+ /**
10
+ * Opens the connections, checks that Janus's tables are there, and builds
11
+ * `auth` and `access` over them.
12
+ *
13
+ * ```ts
14
+ * export const kit = await connectKit(config);
15
+ * const current = await kit.auth.authenticate(request);
16
+ * await kit.close(); // or `await using kit = await connectKit(config)`
17
+ * ```
18
+ *
19
+ * **It fails here, not at the first sign-in**: a database that does not
20
+ * answer, or one without the tables your migrations create, rejects with an
21
+ * `Error` naming what to do, after closing whatever it had opened.
22
+ */
23
+ export declare function connectKit<A extends object, P extends object = never, const WithApiKeys extends boolean = false>(config: KitConfig<A, P, WithApiKeys>): Promise<Kit<A, P>>;
24
+ //# sourceMappingURL=connect.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../../src/drizzle/connect.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAWvD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAEjD,OAAO,EAA6B,KAAK,KAAK,EAAE,MAAM,eAAe,CAAC;AACtE,OAAO,EAEN,KAAK,SAAS,EAGd,MAAM,UAAU,CAAC;AAElB,uDAAuD;AACvD,MAAM,MAAM,MAAM,GAAG,QAAQ,CAAC,UAAU,CAAC,CAAC;AAE1C,iFAAiF;AACjF,MAAM,MAAM,GAAG,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,MAAM,IAAI,KAAK,CAC1D,CAAC,EACD,CAAC,EACD,UAAU,EACV,UAAU,CACV,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,wBAAsB,UAAU,CAC/B,CAAC,SAAS,MAAM,EAChB,CAAC,SAAS,MAAM,GAAG,KAAK,EACxB,KAAK,CAAC,WAAW,SAAS,OAAO,GAAG,KAAK,EACxC,MAAM,EAAE,SAAS,CAAC,CAAC,EAAE,CAAC,EAAE,WAAW,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAkD1D"}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * `@softistx/janus-kit/drizzle` — `@softistx/janus` wired in one call, over
3
+ * PostgreSQL through `@softistx/janus-drizzle`.
4
+ *
5
+ * `defineConfig` checks where PostgreSQL and Redis are, and holds the two
6
+ * functions that build `auth` and `access`; `connectKit` opens the
7
+ * connections, checks that Janus's tables are there, and answers
8
+ * `{ auth, access, db, redis, ping, close }`. It defines **no error class**:
9
+ * a refusal of the configuration is a `TypeError`, a database that cannot be
10
+ * reached an `Error` with its `cause`.
11
+ */
12
+ export type { AccessWiring, Adapters, KitApiKeyStore, RedisConfig, } from '../shared/config';
13
+ export type { PingResult } from '../shared/health';
14
+ export { defineConfig, type KitConfig, type PostgresConfig } from './config';
15
+ export { connectKit, type Health, type Kit } from './connect';
16
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/drizzle/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,YAAY,EACX,YAAY,EACZ,QAAQ,EACR,cAAc,EACd,WAAW,GACX,MAAM,kBAAkB,CAAC;AAC1B,YAAY,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,YAAY,EAAE,KAAK,SAAS,EAAE,KAAK,cAAc,EAAE,MAAM,UAAU,CAAC;AAC7E,OAAO,EAAE,UAAU,EAAE,KAAK,MAAM,EAAE,KAAK,GAAG,EAAE,MAAM,WAAW,CAAC"}