@otwdesign/db-next 0.0.0-stage → 1.4.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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,2 @@
1
+ OTW DB
2
+ Copyright 2026 OTW SRL
package/README.md CHANGED
@@ -1,3 +1,88 @@
1
- # Temporary Holding Version
1
+ # @otwdesign/db-next
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
+ OTW DB in a Next.js app, on Vercel or anywhere: a database manager at `/db`, with a sign-in of its
4
+ own. In the app's directory:
5
+
6
+ ```sh
7
+ npx @otwdesign/db-next init
8
+ ```
9
+
10
+ It writes one route file and installs this package. It never writes over a file; `--dry-run`
11
+ says what it would do, `--path /admin/db` puts it elsewhere.
12
+
13
+ It makes no password and writes none: it lists the variables to set, and the password is yours to
14
+ choose. Use one of 16 characters or more, from your password manager or `openssl rand -base64 32`,
15
+ and set it as `DB_ADMIN_PASSWORD`: in `.env.local` on your machine (a file git must not have), and
16
+ in your host's settings where the app runs. Until it's set, nobody signs in with a password.
17
+
18
+ next.config's `basePath` is taken when it's written once, as a plain quoted path
19
+ (`basePath: '/docs'`). Written any other way (from a variable, built from parts), `init` says so
20
+ and leaves it to you: `createDbRoute({ basePath: '/docs/db' })`.
21
+
22
+ ```ts
23
+ // app/db/[[...path]]/route.ts
24
+ import { createDbRoute } from '@otwdesign/db-next'
25
+
26
+ export const runtime = 'nodejs'
27
+ export const dynamic = 'force-dynamic'
28
+ export const { GET, POST } = createDbRoute()
29
+ ```
30
+
31
+ ```dotenv
32
+ DB_ADMIN_PASSWORD=… # whoever has it gets in; 16 characters at least
33
+ DB_ADMIN_USERS=you@example.com,ana@example.com # the app's signed-in users who need no password
34
+ DB_ADMIN_MAIN_URL=postgres://… # or the app's own DATABASE_URL, read-only
35
+ ```
36
+
37
+ Set the same variables on your host (`vercel env add DB_ADMIN_PASSWORD`), and open `/db`.
38
+
39
+ ## Who gets in
40
+
41
+ - **The password:** `/db/sign-in` asks for it and sets a session for 12 hours. Changing the
42
+ password ends every session; signing out forgets it in that browser. One under 16 characters
43
+ is refused. Wrong passwords are answered one at a time, half a second apart, and past a few
44
+ waiting, sign-ins are turned away for a moment: a guesser gets two tries a second, however many
45
+ connections it opens (and someone sending wrong passwords without pause can keep the form
46
+ busy; the app's own users, below, get in regardless). The session's key is made from the
47
+ password the slow way, so a cookie forged from a guess costs its maker as much as a sign-in.
48
+ - **The app's own users:** those listed in `DB_ADMIN_USERS`, by email (or id), get in without the
49
+ password once they're signed in to the app. The audit log has who it was. With the list set and
50
+ no password, nobody else gets in.
51
+ - An app on **Supabase Auth** needs no code: the session `@supabase/ssr` keeps is read, and
52
+ Supabase is asked whose it is. Only a confirmed email counts. List people who have an
53
+ account, and keep Confirm email on in Supabase.
54
+ - Any other sign-in says who is signed in:
55
+
56
+ ```ts
57
+ import { auth } from '@/auth' // Auth.js, Clerk, your own
58
+
59
+ export const { GET, POST } = createDbRoute({
60
+ user: async () => (await auth())?.user?.email,
61
+ })
62
+ ```
63
+
64
+ - **Your own rule,** instead of both: `createDbRoute({ authorize, signInUrl: '/login' })`, where
65
+ `authorize(request)` returns `{ id }` or `null`.
66
+
67
+ Middleware that signs people in on every route must leave `/db` out of its matcher.
68
+
69
+ ## Which databases
70
+
71
+ `DB_ADMIN_<NAME>_URL` (with `_ACCESS`, `_LABEL`, `_TAG`), as in the
72
+ [whole guide](https://github.com/OTWSRL/otw-db#readme). With none set, the app's own database,
73
+ read-only unless `DB_ADMIN_APP_ACCESS=write`: `DATABASE_URL_UNPOOLED`, `POSTGRES_URL_NON_POOLING`,
74
+ `DATABASE_URL` or `POSTGRES_URL`, the first that's set. The tool keeps a session, which a
75
+ transaction pooler doesn't, so the address that goes round the pooler comes first.
76
+
77
+ On **Supabase**, an app that only uses Supabase's API holds no address of its database: copy the
78
+ Session pooler connection string from Supabase's Connect dialog into `DB_ADMIN_MAIN_URL`.
79
+
80
+ ## On Vercel
81
+
82
+ This package brings `pg` and `pg-cursor` and imports them where Next's file tracing sees them, so
83
+ they're in the deployed function. MySQL and MariaDB work where the whole of `node_modules` is
84
+ deployed (`next start` on a server), not yet in a Vercel function.
85
+
86
+ `createDbRoute(options)` also takes `basePath` (with next.config's `basePath` in front, as the
87
+ browser has it), `connections`, and what `createDbAdmin` takes: `audit`, `limits`, `origins`,
88
+ `backups`.
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../dist/cli.js'
3
+
4
+ await main()
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ /** The `otw-db-next` command. */
2
+ export declare function main(argv?: string[], cwd?: string): Promise<void>;
package/dist/cli.js ADDED
@@ -0,0 +1,85 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { apply, detect, plan, report } from "./init.js";
3
+ const HELP = `otw-db-next: OTW DB in a Next.js app
4
+
5
+ Usage: npx @otwdesign/db-next init [--path /db] [--dry-run] [--no-install]
6
+
7
+ Run it in the app's directory. It writes one route file (app/db/[[...path]]/route.ts), installs
8
+ @otwdesign/db-next, and says which variables to set: the password is yours to choose, and it
9
+ writes none. It never writes over a file.
10
+
11
+ --path /admin/db where the tool goes; /db unless you say
12
+ --dry-run say what it would do, and do nothing
13
+ --no-install write the files, install nothing
14
+ `;
15
+ /** What was typed, as options; null when it's none this command has. */
16
+ function options(argv) {
17
+ try {
18
+ return parseArgs({
19
+ args: argv,
20
+ allowPositionals: true,
21
+ options: {
22
+ path: { type: 'string' },
23
+ 'dry-run': { type: 'boolean' },
24
+ 'no-install': { type: 'boolean' },
25
+ help: { type: 'boolean', short: 'h' },
26
+ },
27
+ });
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ }
33
+ /** The `otw-db-next` command. */
34
+ export async function main(argv = process.argv.slice(2), cwd = process.cwd()) {
35
+ const given = options(argv);
36
+ if (!given) {
37
+ process.stdout.write(HELP);
38
+ process.exitCode = 1;
39
+ return;
40
+ }
41
+ const { values, positionals } = given;
42
+ if (values.help || positionals[0] !== 'init' || positionals.length > 1) {
43
+ process.stdout.write(HELP);
44
+ if (!values.help)
45
+ process.exitCode = 1;
46
+ return;
47
+ }
48
+ let detected;
49
+ let planned;
50
+ try {
51
+ detected = detect(cwd);
52
+ planned = plan(detected, {
53
+ ...(values.path === undefined ? {} : { path: values.path }),
54
+ install: !values['no-install'],
55
+ });
56
+ }
57
+ catch (error) {
58
+ // The code Node gives, and none of its own words: those carry paths as the folder has them.
59
+ const code = error.code ?? 'an error';
60
+ process.stderr.write(`Couldn’t read this folder (${code}). Nothing was written.\n`);
61
+ process.exitCode = 1;
62
+ return;
63
+ }
64
+ if (planned.refused) {
65
+ process.stderr.write(`${planned.refused}\n`);
66
+ process.exitCode = 1;
67
+ return;
68
+ }
69
+ let outcome;
70
+ try {
71
+ outcome = values['dry-run'] ? undefined : apply(detected, planned);
72
+ }
73
+ catch (error) {
74
+ // In a line: the code Node gives, and the path only as this command made it.
75
+ const failed = error;
76
+ const at = planned.files[0]?.path ?? 'the route file';
77
+ process.stderr.write(`Couldn’t write the route file (${failed.code ?? 'it failed'}): ${at}\n`);
78
+ process.exitCode = 1;
79
+ return;
80
+ }
81
+ process.stdout.write(report(detected, planned, values['dry-run'] === true, outcome));
82
+ if (outcome?.installFailed)
83
+ process.exitCode = 1;
84
+ }
85
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAA;AACrC,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,WAAW,CAAA;AAEvD,MAAM,IAAI,GAAG;;;;;;;;;;;CAWZ,CAAA;AAED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AC,CAAA;QAC9F,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAA;QACpB,OAAM;IACR,CAAC;IACD,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,EAAE,OAAO,EAAE,MAAM,CAAC,SAAS,CAAC,KAAK,IAAI,EAAE,OAAO,CAAC,CAAC,CAAA;IACpF,IAAI,OAAO,EAAE,aAAa;QAAE,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAA;AAClD,CAAC"}
@@ -0,0 +1,17 @@
1
+ import { type ConnectionConfig } from '@otwdesign/db-core';
2
+ type Env = Readonly<Record<string, string | undefined>>;
3
+ /**
4
+ * Where an app's own PostgreSQL is, by the names hosts and their database integrations give it,
5
+ * the ones that don't go through a transaction pooler first: Neon's DATABASE_URL_UNPOOLED,
6
+ * Vercel Postgres's and Supabase's POSTGRES_URL_NON_POOLING. The tool reads through cursors and
7
+ * sets things for a session, which a pooler that hands each statement to another connection
8
+ * doesn't keep.
9
+ */
10
+ export declare const OWN_DATABASE: readonly ["DATABASE_URL_UNPOOLED", "POSTGRES_URL_NON_POOLING", "DATABASE_URL", "POSTGRES_URL"];
11
+ /**
12
+ * The connections of an app: those it names (`DB_ADMIN_<NAME>_URL`), or, when it names none, its
13
+ * own database, read-only unless `DB_ADMIN_APP_ACCESS=write`. An address the tool can't open
14
+ * (Prisma's `prisma://`, MongoDB's) is passed over, not refused: it's the app's, set for the app.
15
+ */
16
+ export declare function appConnections(env?: Env): ConnectionConfig[];
17
+ export {};
@@ -0,0 +1,45 @@
1
+ import { connectionsFromEnv, driverKind } from '@otwdesign/db-core';
2
+ /**
3
+ * Where an app's own PostgreSQL is, by the names hosts and their database integrations give it,
4
+ * the ones that don't go through a transaction pooler first: Neon's DATABASE_URL_UNPOOLED,
5
+ * Vercel Postgres's and Supabase's POSTGRES_URL_NON_POOLING. The tool reads through cursors and
6
+ * sets things for a session, which a pooler that hands each statement to another connection
7
+ * doesn't keep.
8
+ */
9
+ export const OWN_DATABASE = [
10
+ 'DATABASE_URL_UNPOOLED',
11
+ 'POSTGRES_URL_NON_POOLING',
12
+ 'DATABASE_URL',
13
+ 'POSTGRES_URL',
14
+ ];
15
+ /**
16
+ * The connections of an app: those it names (`DB_ADMIN_<NAME>_URL`), or, when it names none, its
17
+ * own database, read-only unless `DB_ADMIN_APP_ACCESS=write`. An address the tool can't open
18
+ * (Prisma's `prisma://`, MongoDB's) is passed over, not refused: it's the app's, set for the app.
19
+ */
20
+ export function appConnections(env = process.env) {
21
+ const named = connectionsFromEnv(env);
22
+ if (named.length)
23
+ return named;
24
+ for (const variable of OWN_DATABASE) {
25
+ const url = env[variable]?.trim();
26
+ if (!url)
27
+ continue;
28
+ try {
29
+ driverKind(url);
30
+ }
31
+ catch {
32
+ continue;
33
+ }
34
+ return [
35
+ {
36
+ name: 'app',
37
+ label: 'This app',
38
+ url,
39
+ access: env.DB_ADMIN_APP_ACCESS?.trim() === 'write' ? 'write' : 'read',
40
+ },
41
+ ];
42
+ }
43
+ return [];
44
+ }
45
+ //# sourceMappingURL=connections.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connections.js","sourceRoot":"","sources":["../src/connections.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,UAAU,EAAyB,MAAM,oBAAoB,CAAA;AAI1F;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG;IAC1B,uBAAuB;IACvB,0BAA0B;IAC1B,cAAc;IACd,cAAc;CACN,CAAA;AAEV;;;;GAIG;AACH,MAAM,UAAU,cAAc,CAAC,MAAW,OAAO,CAAC,GAAG;IACnD,MAAM,KAAK,GAAG,kBAAkB,CAAC,GAAG,CAAC,CAAA;IACrC,IAAI,KAAK,CAAC,MAAM;QAAE,OAAO,KAAK,CAAA;IAC9B,KAAK,MAAM,QAAQ,IAAI,YAAY,EAAE,CAAC;QACpC,MAAM,GAAG,GAAG,GAAG,CAAC,QAAQ,CAAC,EAAE,IAAI,EAAE,CAAA;QACjC,IAAI,CAAC,GAAG;YAAE,SAAQ;QAClB,IAAI,CAAC;YACH,UAAU,CAAC,GAAG,CAAC,CAAA;QACjB,CAAC;QAAC,MAAM,CAAC;YACP,SAAQ;QACV,CAAC;QACD,OAAO;YACL;gBACE,IAAI,EAAE,KAAK;gBACX,KAAK,EAAE,UAAU;gBACjB,GAAG;gBACH,MAAM,EAAE,GAAG,CAAC,mBAAmB,EAAE,IAAI,EAAE,KAAK,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM;aACvE;SACF,CAAA;IACH,CAAC;IACD,OAAO,EAAE,CAAA;AACX,CAAC"}
@@ -0,0 +1,5 @@
1
+ export { appConnections, OWN_DATABASE } from './connections.ts';
2
+ export { createDbRoute, type DbRoute, type DbRouteOptions } from './route.ts';
3
+ export { MIN_PASSWORD, SESSION_COOKIE } from './session.ts';
4
+ export { supabaseUser, type SignedIn, type SupabaseUser } from './supabase.ts';
5
+ export { listedUsers } from './users.ts';
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { appConnections, OWN_DATABASE } from "./connections.js";
2
+ export { createDbRoute } from "./route.js";
3
+ export { MIN_PASSWORD, SESSION_COOKIE } from "./session.js";
4
+ export { supabaseUser } from "./supabase.js";
5
+ export { listedUsers } from "./users.js";
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAA;AAC/D,OAAO,EAAE,aAAa,EAAqC,MAAM,YAAY,CAAA;AAC7E,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,cAAc,CAAA;AAC3D,OAAO,EAAE,YAAY,EAAoC,MAAM,eAAe,CAAA;AAC9E,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA"}
package/dist/init.d.ts ADDED
@@ -0,0 +1,90 @@
1
+ export type PackageManager = 'npm' | 'pnpm' | 'yarn' | 'bun';
2
+ /** What `init` found in the app's directory. */
3
+ export interface Detected {
4
+ /** The app's directory, absolute. */
5
+ dir: string;
6
+ /** `next` is among its dependencies. */
7
+ next: boolean;
8
+ /** `src` when the app keeps `app/` or `pages/` there, else empty. */
9
+ src: '' | 'src';
10
+ typescript: boolean;
11
+ manager: PackageManager;
12
+ /** `basePath` from next.config, such as `/docs`; empty without one. */
13
+ nextBasePath: string;
14
+ /** next.config sets a `basePath` that isn't a plain path, so it wasn't taken. */
15
+ basePathUnread: boolean;
16
+ /** Its middleware (or proxy, as Next 16 calls it), relative to the app; null without one. */
17
+ middleware: string | null;
18
+ /**
19
+ * Files that are there and weren't read: not a file, or larger than any such file is. What
20
+ * they'd have said isn't known, which isn't the same as their saying nothing.
21
+ */
22
+ unread: string[];
23
+ /** DB_ADMIN_PASSWORD is set in `.env`, a file apps usually keep in git. */
24
+ passwordInDotEnv: boolean;
25
+ /** The names already set in `.env.local` and `.env`. */
26
+ envNames: ReadonlySet<string>;
27
+ /** The tool's own names those files mention at all, set or in a comment an earlier run left. */
28
+ envMentions: ReadonlySet<string>;
29
+ /** The app uses Supabase: its packages, or its address in the env. */
30
+ supabase: boolean;
31
+ /**
32
+ * The Node major package.json holds the app to (`20`, `20.x`, `^18.17`), when it holds it to
33
+ * one: the number, never the text, which is someone's and gets printed.
34
+ */
35
+ nodeMajor: number | null;
36
+ /** `@otwdesign/db-next` is a dependency already. */
37
+ installed: boolean;
38
+ }
39
+ export interface InitFlags {
40
+ /** Where the tool goes, such as `/db` (the default) or `/admin/db`. */
41
+ path?: string;
42
+ /** Install nothing: the files only. */
43
+ install?: boolean;
44
+ }
45
+ /** What `init` would do: files to write, a command, and what to say and leave to the person. */
46
+ export interface InitPlan {
47
+ /** Why nothing can be done; when set, the rest is empty. */
48
+ refused: string | null;
49
+ files: {
50
+ path: string;
51
+ content: string;
52
+ }[];
53
+ /**
54
+ * The variables still to set, as lines for the person to add to their environment: `init`
55
+ * writes none of them. The password is theirs to choose and to place, and a file in a folder
56
+ * someone else may have prepared is no place for a tool to put a secret.
57
+ */
58
+ env: string[];
59
+ /** The command that installs the package; null with `--no-install`, or when it's there. */
60
+ install: {
61
+ command: string;
62
+ args: string[];
63
+ } | null;
64
+ /** What the person should know, or do next. */
65
+ notes: string[];
66
+ /** Where the tool will be, as the browser has it. */
67
+ url: string;
68
+ }
69
+ /** Looks at the app in `dir`. */
70
+ export declare function detect(dir: string): Detected;
71
+ /**
72
+ * The route file: all of the tool's setup an app holds. The comments are for whoever opens it
73
+ * months later and wonders where the password and the databases come from.
74
+ */
75
+ export declare function routeFile(basePath: string): string;
76
+ /** What to do in the app `detect` found. Writes nothing. */
77
+ export declare function plan(detected: Detected, flags?: InitFlags): InitPlan;
78
+ /** How `apply` went. */
79
+ export interface InitOutcome {
80
+ /** Why the package wasn't installed, when installing it was tried and failed. */
81
+ installFailed: string | null;
82
+ }
83
+ /**
84
+ * Does what the plan says, in the app's directory. `run` installs; a test stands in for it. An
85
+ * install that fails (no network, a registry that says no) is reported, not thrown: the files
86
+ * are written by then, and what's left to do must still be said.
87
+ */
88
+ export declare function apply(detected: Detected, planned: InitPlan, run?: (command: string, args: string[], cwd: string) => void): InitOutcome;
89
+ /** What was done, or would be, for the terminal. */
90
+ export declare function report(detected: Detected, planned: InitPlan, dryRun: boolean, outcome?: InitOutcome): string;