spotcraft 0.0.0-stage → 0.2.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,8 @@
1
+ Spotcraft
2
+ Copyright 2026 Ivan Vinski
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
5
+
6
+ The agent skills vendored in .claude/skills/ are third-party works under their own
7
+ licenses (MIT, Apache-2.0, MPL-2.0); each skill folder carries its LICENSE, and
8
+ skills-lock.json records the source and license of every one.
package/README.md CHANGED
@@ -1,3 +1,53 @@
1
- # Temporary Holding Version
1
+ # spotcraft
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
+ The `spotcraft` command. For now it has one job: `spotcraft dev` runs, on your machine, the same
4
+ Postgres and app database setup an app gets on a Spotcraft apps server
5
+ ([ADR 0017](https://github.com/vindotski/spotcraft/blob/main/docs/decisions/0017-local-stack.md)). It needs Docker.
6
+
7
+ ```bash
8
+ npm install --save-dev spotcraft # same version as the Spotcraft you deploy to
9
+ npx spotcraft dev start # start the local Postgres and set up this app's database
10
+ npx spotcraft dev env --write # add DATABASE_URL and AUTH_SECRET to .env (only if missing)
11
+ ```
12
+
13
+ | Command | What |
14
+ | ------------------- | ------------------------------------------------------------------------------------- |
15
+ | `dev start` | starts the local Postgres if needed, sets up this app's database, prints its settings |
16
+ | `dev stop` | stops the local Postgres; the data stays |
17
+ | `dev status` | whether it runs, and this app's `auth` schema version |
18
+ | `dev env [--write]` | prints `DATABASE_URL` and `AUTH_SECRET`; `--write` adds missing ones to `.env` |
19
+ | `dev reset [--yes]` | deletes this app's database and creates it empty again (asks first) |
20
+ | `dev migrate` | brings this app's database up to date after upgrading the CLI |
21
+
22
+ How an app uses it with the kit: [Guest accounts with the backend kit](https://github.com/vindotski/spotcraft/blob/main/docs/guides/backend-kit.md).
23
+
24
+ The app name comes from `--name`, or from the `name` in `package.json` made into an app name
25
+ (`@acme/Blog_API` → `blog-api`). Its database is `app_<name>`, with dashes as underscores.
26
+
27
+ ## Same as the server
28
+
29
+ - **One Postgres for every app on the machine.** It's a Compose project, `spotcraft-dev`, with
30
+ the data in the `spotcraft-dev_data` volume. Each app gets its own role and database,
31
+ created with the kit's `provision`, the same code the agent uses. So one app can't open
32
+ another's database here either.
33
+ - **The same image and login rules** as the apps server: the pinned Postgres image, and the
34
+ superuser only over the container's socket. **The same admin role**: `spotcraft_agent`, set up
35
+ with the deploy script's SQL. Tests fail if the CLI's copies of the image, the rules or that
36
+ SQL drift from `infra/`.
37
+ - **The same `auth` schema**: the CLI's version matches the Spotcraft it deploys to (one
38
+ version for the project).
39
+
40
+ ## Local only
41
+
42
+ Postgres listens on `127.0.0.1:54340` only. The port isn't 54322, which Supabase uses. The
43
+ passwords are fixed (`local-<name>-password` for an app), so `DATABASE_URL` stays the same
44
+ across runs and in `.env`. That's fine for throwaway data on your own machine and nowhere else.
45
+ `AUTH_SECRET` is random; `env --write` keeps the one already in `.env`.
46
+
47
+ To remove everything: `docker compose -p spotcraft-dev down -v`.
48
+
49
+ ## Developing
50
+
51
+ In the workspace, run it from source with `pnpm --filter spotcraft spotcraft dev …`. Note
52
+ that pnpm runs it in `packages/cli`, so pass `--name`. `pnpm --filter spotcraft build`
53
+ writes `dist/` (the `spotcraft` bin); it uses the kit's build, so build the kit first.
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export declare function main(argv: string[]): Promise<number>;
package/dist/cli.js ADDED
@@ -0,0 +1,158 @@
1
+ #!/usr/bin/env node
2
+ import { createInterface } from 'node:readline/promises';
3
+ import { parseArgs } from 'node:util';
4
+ import { appDatabaseName, authSchemaVersion, provision, purge } from '@spotcraft/kit/provision';
5
+ import { AUTH_SCHEMA_VERSION } from '@spotcraft/kit/schema';
6
+ import pg from 'pg';
7
+ import { appName, localEnv, writeMissing } from "./project.js";
8
+ import { adminUrl, appPassword, databaseUrl, down, isRunning, PORT, StackError, up, } from "./stack.js";
9
+ const HELP = `Usage: spotcraft dev <command> [--name <app>]
10
+
11
+ Runs the same Postgres and app database setup as a Spotcraft apps server, on this machine.
12
+
13
+ Commands:
14
+ start start the local Postgres and set up this app's database
15
+ stop stop the local Postgres (the data stays)
16
+ status show whether it runs and this app's database
17
+ env [--write] print DATABASE_URL and AUTH_SECRET; --write adds missing ones to .env
18
+ reset [--yes] delete this app's database and start it empty
19
+ migrate bring this app's database up to date after upgrading
20
+
21
+ The app name comes from --name or package.json. Needs Docker.
22
+ `;
23
+ const print = (line = '') => process.stdout.write(`${line}\n`);
24
+ async function ensureRunning() {
25
+ if (!(await isRunning()))
26
+ throw new StackError('The local Postgres is not running; run `spotcraft dev start`');
27
+ }
28
+ /** The auth schema version of the app's database, or undefined if it doesn't exist. */
29
+ async function appDatabaseVersion(name) {
30
+ const admin = new pg.Client({ connectionString: adminUrl() });
31
+ await admin.connect();
32
+ try {
33
+ const found = await admin.query('SELECT 1 FROM pg_database WHERE datname = $1', [
34
+ appDatabaseName(name),
35
+ ]);
36
+ if (!found.rowCount)
37
+ return undefined;
38
+ }
39
+ finally {
40
+ await admin.end();
41
+ }
42
+ const db = new pg.Client({ connectionString: databaseUrl(name) });
43
+ await db.connect();
44
+ try {
45
+ return await authSchemaVersion(db);
46
+ }
47
+ finally {
48
+ await db.end();
49
+ }
50
+ }
51
+ async function confirm(question) {
52
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
53
+ try {
54
+ return /^y(es)?$/i.test((await rl.question(`${question} [y/N] `)).trim());
55
+ }
56
+ finally {
57
+ rl.close();
58
+ }
59
+ }
60
+ export async function main(argv) {
61
+ const { values, positionals } = parseArgs({
62
+ args: argv,
63
+ allowPositionals: true,
64
+ options: {
65
+ name: { type: 'string' },
66
+ write: { type: 'boolean', default: false },
67
+ yes: { type: 'boolean', default: false },
68
+ help: { type: 'boolean', short: 'h', default: false },
69
+ },
70
+ });
71
+ const [group, command] = positionals;
72
+ if (values.help || group !== 'dev' || !command) {
73
+ print(HELP);
74
+ return values.help ? 0 : 1;
75
+ }
76
+ const cwd = process.cwd();
77
+ switch (command) {
78
+ case 'start': {
79
+ const name = await appName(cwd, values.name);
80
+ await up();
81
+ await provision(adminUrl(), { name, password: appPassword(name) });
82
+ print(`Local Postgres on 127.0.0.1:${PORT}; database ${appDatabaseName(name)} is ready.`);
83
+ print();
84
+ for (const [key, value] of await localEnv(cwd, databaseUrl(name)))
85
+ print(`${key}=${value}`);
86
+ print();
87
+ print('Add these to .env with: spotcraft dev env --write');
88
+ return 0;
89
+ }
90
+ case 'stop':
91
+ await down();
92
+ print('Local Postgres stopped; the data stays.');
93
+ return 0;
94
+ case 'status': {
95
+ const name = await appName(cwd, values.name);
96
+ if (!(await isRunning())) {
97
+ print('Local Postgres: stopped (spotcraft dev start)');
98
+ return 0;
99
+ }
100
+ // Running but never set up (e.g. started by hand) reads as "no database yet".
101
+ const version = await appDatabaseVersion(name).catch(() => undefined);
102
+ print(`Local Postgres: running on 127.0.0.1:${PORT}`);
103
+ if (version === undefined)
104
+ print(`${appDatabaseName(name)}: none yet (spotcraft dev start)`);
105
+ else {
106
+ const note = version < AUTH_SCHEMA_VERSION ? ' (spotcraft dev migrate)' : '';
107
+ print(`${appDatabaseName(name)}: auth schema ${version} of ${AUTH_SCHEMA_VERSION}${note}`);
108
+ }
109
+ return 0;
110
+ }
111
+ case 'env': {
112
+ const name = await appName(cwd, values.name);
113
+ const env = await localEnv(cwd, databaseUrl(name));
114
+ if (!values.write) {
115
+ for (const [key, value] of env)
116
+ print(`${key}=${value}`);
117
+ return 0;
118
+ }
119
+ const { added, kept } = await writeMissing(cwd, env);
120
+ if (added.length)
121
+ print(`Added to .env: ${added.join(', ')}`);
122
+ if (kept.length)
123
+ print(`Already in .env, left as they are: ${kept.join(', ')}`);
124
+ return 0;
125
+ }
126
+ case 'reset': {
127
+ const name = await appName(cwd, values.name);
128
+ await ensureRunning();
129
+ const db = appDatabaseName(name);
130
+ if (!values.yes &&
131
+ !(await confirm(`Delete every row in the local ${db} and start it empty?`))) {
132
+ print('Nothing changed.');
133
+ return 1;
134
+ }
135
+ await purge(adminUrl(), name);
136
+ await provision(adminUrl(), { name, password: appPassword(name) });
137
+ print(`${db} is empty again.`);
138
+ return 0;
139
+ }
140
+ case 'migrate': {
141
+ const name = await appName(cwd, values.name);
142
+ await ensureRunning();
143
+ await provision(adminUrl(), { name, password: appPassword(name) });
144
+ print(`${appDatabaseName(name)}: auth schema ${AUTH_SCHEMA_VERSION}.`);
145
+ return 0;
146
+ }
147
+ default:
148
+ print(HELP);
149
+ return 1;
150
+ }
151
+ }
152
+ // Run when executed (not when a test imports it).
153
+ if (import.meta.main) {
154
+ main(process.argv.slice(2)).then((code) => process.exit(code), (error) => {
155
+ process.stderr.write(`spotcraft: ${error instanceof Error ? error.message : String(error)}\n`);
156
+ process.exit(1);
157
+ });
158
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The app's name: `--name`, or else the `name` in package.json, made into a Spotcraft app
3
+ * name (`@acme/Blog_API` → `blog-api`). Throws when neither gives a valid one.
4
+ */
5
+ export declare function appName(dir: string, flag?: string): Promise<string>;
6
+ /** KEY=value lines of a .env file (comments and blank lines skipped). */
7
+ export declare function parseEnv(text: string): Map<string, string>;
8
+ /** The local settings an app needs; AUTH_SECRET is kept if .env already has one. */
9
+ export declare function localEnv(dir: string, databaseUrl: string): Promise<Map<string, string>>;
10
+ /**
11
+ * Adds the variables .env doesn't have yet, at the end, and leaves every existing line alone.
12
+ * Returns which were added and which were already there (possibly with another value).
13
+ */
14
+ export declare function writeMissing(dir: string, values: Map<string, string>): Promise<{
15
+ added: string[];
16
+ kept: string[];
17
+ }>;
@@ -0,0 +1,82 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { readFile, writeFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { appDatabaseName } from '@spotcraft/kit/provision';
5
+ /**
6
+ * The app's name: `--name`, or else the `name` in package.json, made into a Spotcraft app
7
+ * name (`@acme/Blog_API` → `blog-api`). Throws when neither gives a valid one.
8
+ */
9
+ export async function appName(dir, flag) {
10
+ let candidate = flag;
11
+ if (!candidate) {
12
+ let pkg;
13
+ try {
14
+ pkg = JSON.parse(await readFile(join(dir, 'package.json'), 'utf8'));
15
+ }
16
+ catch {
17
+ throw new Error('No package.json here; pass the app name with --name');
18
+ }
19
+ if (typeof pkg.name !== 'string')
20
+ throw new Error('package.json has no name; pass --name');
21
+ candidate = pkg.name
22
+ .replace(/^@[^/]+\//, '')
23
+ .toLowerCase()
24
+ .replace(/[^a-z0-9-]+/g, '-')
25
+ .replace(/^[^a-z]+|-+$/g, '')
26
+ .slice(0, 32)
27
+ .replace(/-+$/, '');
28
+ }
29
+ try {
30
+ appDatabaseName(candidate);
31
+ }
32
+ catch {
33
+ throw new Error(`"${candidate}" is not a Spotcraft app name (lower-case letters, digits and dashes, 2–32 characters); pass --name`);
34
+ }
35
+ return candidate;
36
+ }
37
+ /** KEY=value lines of a .env file (comments and blank lines skipped). */
38
+ export function parseEnv(text) {
39
+ const entries = new Map();
40
+ for (const line of text.split(/\r?\n/)) {
41
+ const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/.exec(line);
42
+ if (match)
43
+ entries.set(match[1], match[2].trim());
44
+ }
45
+ return entries;
46
+ }
47
+ async function readEnvFile(path) {
48
+ try {
49
+ return await readFile(path, 'utf8');
50
+ }
51
+ catch (error) {
52
+ if (error.code === 'ENOENT')
53
+ return '';
54
+ throw error;
55
+ }
56
+ }
57
+ /** The local settings an app needs; AUTH_SECRET is kept if .env already has one. */
58
+ export async function localEnv(dir, databaseUrl) {
59
+ const existing = parseEnv(await readEnvFile(join(dir, '.env')));
60
+ return new Map([
61
+ ['DATABASE_URL', databaseUrl],
62
+ ['AUTH_SECRET', existing.get('AUTH_SECRET') || randomBytes(32).toString('hex')],
63
+ ]);
64
+ }
65
+ /**
66
+ * Adds the variables .env doesn't have yet, at the end, and leaves every existing line alone.
67
+ * Returns which were added and which were already there (possibly with another value).
68
+ */
69
+ export async function writeMissing(dir, values) {
70
+ const path = join(dir, '.env');
71
+ const text = await readEnvFile(path);
72
+ const existing = parseEnv(text);
73
+ const added = [...values.keys()].filter((key) => !existing.has(key));
74
+ const kept = [...values.keys()].filter((key) => existing.has(key));
75
+ if (added.length > 0) {
76
+ const lines = added.map((key) => `${key}=${values.get(key)}`);
77
+ const separator = text === '' || text.endsWith('\n') ? '' : '\n';
78
+ const header = '# Local stack (npx spotcraft dev env --write)\n';
79
+ await writeFile(path, `${text}${separator}${header}${lines.join('\n')}\n`);
80
+ }
81
+ return { added, kept };
82
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The local stack: one Postgres for every app repository on this machine, set up like the
3
+ * apps server's (ADR 0017). Tests keep the values below equal to the server's files.
4
+ */
5
+ export declare const PROJECT = "spotcraft-dev";
6
+ export declare const CONTAINER = "spotcraft-dev-postgres-1";
7
+ export declare const PORT = 54340;
8
+ /** The apps server's Postgres image (infra/apps-server/compose.yaml). */
9
+ export declare const POSTGRES_IMAGE = "postgres:18.6-trixie@sha256:e3d24f6906d0760bf4da0dae872415391ededefad23fd471c47dc53b0ddf3c42";
10
+ /** The apps server's login rules (infra/apps-server/pg_hba.conf). */
11
+ export declare const PG_HBA = "# TYPE DATABASE USER ADDRESS METHOD\nlocal all postgres peer\nlocal all all reject\nhost all postgres all reject\nhost all all all scram-sha-256\n";
12
+ /** The agent's role, exactly as the deploy script sets it up (infra/remote-deploy.sh). */
13
+ export declare const ADMIN_SQL = "SELECT NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'spotcraft_agent') AS missing \\gset\n\\if :missing\n CREATE ROLE spotcraft_agent LOGIN CREATEDB CREATEROLE PASSWORD :'pw';\n\\else\n ALTER ROLE spotcraft_agent LOGIN CREATEDB CREATEROLE NOSUPERUSER PASSWORD :'pw';\n\\endif\n-- Roles the agent creates (one per app) are ones it may SET ROLE to, which Postgres requires\n-- to make them a database's owner; it doesn't inherit their rights.\nALTER ROLE spotcraft_agent SET createrole_self_grant = 'set';\n-- Apps get CONNECT on their own database only; the built-in ones are the agent's.\nREVOKE CONNECT ON DATABASE postgres, template1 FROM PUBLIC;\nGRANT CONNECT ON DATABASE postgres TO spotcraft_agent;\n";
14
+ export declare const appPassword: (name: string) => string;
15
+ export declare const adminUrl: () => string;
16
+ /** What the app gets, as on the server but on localhost. */
17
+ export declare function databaseUrl(name: string): string;
18
+ /** The Compose file, as JSON (valid YAML), passed to Docker on stdin. */
19
+ export declare function composeFile(): string;
20
+ export interface RunResult {
21
+ code: number;
22
+ stdout: string;
23
+ stderr: string;
24
+ }
25
+ /** Runs a command without a shell, optionally feeding `input` on stdin. */
26
+ export declare function run(file: string, args: string[], input?: string): Promise<RunResult>;
27
+ export type Runner = typeof run;
28
+ export declare class StackError extends Error {
29
+ }
30
+ /** Starts Postgres (if needed), waits until it is healthy, and sets up the agent's role. */
31
+ export declare function up(runner?: Runner): Promise<void>;
32
+ /** Stops Postgres; the data stays in its volume. */
33
+ export declare function down(runner?: Runner): Promise<void>;
34
+ /** Whether the local Postgres container is running. */
35
+ export declare function isRunning(runner?: Runner): Promise<boolean>;
package/dist/stack.js ADDED
@@ -0,0 +1,138 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { appDatabaseName } from '@spotcraft/kit/provision';
3
+ /**
4
+ * The local stack: one Postgres for every app repository on this machine, set up like the
5
+ * apps server's (ADR 0017). Tests keep the values below equal to the server's files.
6
+ */
7
+ export const PROJECT = 'spotcraft-dev';
8
+ export const CONTAINER = `${PROJECT}-postgres-1`;
9
+ export const PORT = 54340;
10
+ /** The apps server's Postgres image (infra/apps-server/compose.yaml). */
11
+ export const POSTGRES_IMAGE = 'postgres:18.6-trixie@sha256:e3d24f6906d0760bf4da0dae872415391ededefad23fd471c47dc53b0ddf3c42';
12
+ /** The apps server's login rules (infra/apps-server/pg_hba.conf). */
13
+ export const PG_HBA = `# TYPE DATABASE USER ADDRESS METHOD
14
+ local all postgres peer
15
+ local all all reject
16
+ host all postgres all reject
17
+ host all all all scram-sha-256
18
+ `;
19
+ /** The agent's role, exactly as the deploy script sets it up (infra/remote-deploy.sh). */
20
+ export const ADMIN_SQL = `SELECT NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'spotcraft_agent') AS missing \\gset
21
+ \\if :missing
22
+ CREATE ROLE spotcraft_agent LOGIN CREATEDB CREATEROLE PASSWORD :'pw';
23
+ \\else
24
+ ALTER ROLE spotcraft_agent LOGIN CREATEDB CREATEROLE NOSUPERUSER PASSWORD :'pw';
25
+ \\endif
26
+ -- Roles the agent creates (one per app) are ones it may SET ROLE to, which Postgres requires
27
+ -- to make them a database's owner; it doesn't inherit their rights.
28
+ ALTER ROLE spotcraft_agent SET createrole_self_grant = 'set';
29
+ -- Apps get CONNECT on their own database only; the built-in ones are the agent's.
30
+ REVOKE CONNECT ON DATABASE postgres, template1 FROM PUBLIC;
31
+ GRANT CONNECT ON DATABASE postgres TO spotcraft_agent;
32
+ `;
33
+ // Fixed local passwords keep DATABASE_URL the same across runs (and in .env). Acceptable only
34
+ // because the port is bound to 127.0.0.1 and the data is throwaway.
35
+ const SUPERUSER_PASSWORD = 'spotcraft-dev-superuser';
36
+ const ADMIN_PASSWORD = 'spotcraft-dev-admin-password';
37
+ export const appPassword = (name) => `local-${name}-password`;
38
+ export const adminUrl = () => `postgres://spotcraft_agent:${ADMIN_PASSWORD}@127.0.0.1:${PORT}/postgres`;
39
+ /** What the app gets, as on the server but on localhost. */
40
+ export function databaseUrl(name) {
41
+ const db = appDatabaseName(name);
42
+ return `postgres://${db}:${appPassword(name)}@127.0.0.1:${PORT}/${db}`;
43
+ }
44
+ /** The Compose file, as JSON (valid YAML), passed to Docker on stdin. */
45
+ export function composeFile() {
46
+ return JSON.stringify({
47
+ name: PROJECT,
48
+ services: {
49
+ postgres: {
50
+ image: POSTGRES_IMAGE,
51
+ restart: 'unless-stopped',
52
+ environment: { POSTGRES_PASSWORD: SUPERUSER_PASSWORD },
53
+ command: [
54
+ 'postgres',
55
+ '-c',
56
+ 'hba_file=/etc/postgresql/pg_hba.conf',
57
+ '-c',
58
+ 'password_encryption=scram-sha-256',
59
+ ],
60
+ configs: [{ source: 'pg_hba', target: '/etc/postgresql/pg_hba.conf' }],
61
+ ports: [`127.0.0.1:${PORT}:5432`],
62
+ volumes: ['data:/var/lib/postgresql'],
63
+ healthcheck: {
64
+ test: ['CMD', 'pg_isready', '-q', '-h', '/var/run/postgresql', '-U', 'postgres'],
65
+ interval: '2s',
66
+ timeout: '5s',
67
+ retries: 30,
68
+ },
69
+ },
70
+ },
71
+ volumes: { data: {} },
72
+ configs: { pg_hba: { content: PG_HBA } },
73
+ });
74
+ }
75
+ /** Runs a command without a shell, optionally feeding `input` on stdin. */
76
+ export function run(file, args, input) {
77
+ return new Promise((resolve) => {
78
+ const child = spawn(file, args, { stdio: ['pipe', 'pipe', 'pipe'] });
79
+ let stdout = '';
80
+ let stderr = '';
81
+ child.stdout.on('data', (chunk) => {
82
+ stdout += chunk;
83
+ });
84
+ child.stderr.on('data', (chunk) => {
85
+ stderr += chunk;
86
+ });
87
+ child.on('error', (error) => resolve({ code: 127, stdout, stderr: error.message }));
88
+ child.on('close', (code) => resolve({ code: code ?? 1, stdout, stderr }));
89
+ child.stdin.end(input ?? '');
90
+ });
91
+ }
92
+ export class StackError extends Error {
93
+ }
94
+ /** Docker Compose for the local stack; the file comes on stdin. */
95
+ async function compose(runner, args) {
96
+ return runner('docker', ['compose', '-p', PROJECT, '-f', '-', ...args], composeFile());
97
+ }
98
+ function fail(what, result) {
99
+ throw new StackError(`${what}\n${`${result.stderr}${result.stdout}`.trim()}`);
100
+ }
101
+ /** Starts Postgres (if needed), waits until it is healthy, and sets up the agent's role. */
102
+ export async function up(runner = run) {
103
+ const docker = await runner('docker', ['version', '--format', '{{.Server.Version}}']);
104
+ if (docker.code !== 0)
105
+ fail('Docker is not running (the local stack needs it).', docker);
106
+ const started = await compose(runner, ['up', '-d', '--wait', '--wait-timeout', '120']);
107
+ if (started.code !== 0)
108
+ fail('Could not start the local Postgres.', started);
109
+ // As the OS user `postgres`: the superuser only logs in over the socket with `peer`.
110
+ const role = await runner('docker', [
111
+ 'exec',
112
+ '-i',
113
+ '-u',
114
+ 'postgres',
115
+ CONTAINER,
116
+ 'psql',
117
+ '-q',
118
+ '-v',
119
+ 'ON_ERROR_STOP=1',
120
+ '-U',
121
+ 'postgres',
122
+ '-d',
123
+ 'postgres',
124
+ ], `\\set pw ${ADMIN_PASSWORD}\n${ADMIN_SQL}`);
125
+ if (role.code !== 0)
126
+ fail("Could not set up the agent's role.", role);
127
+ }
128
+ /** Stops Postgres; the data stays in its volume. */
129
+ export async function down(runner = run) {
130
+ const stopped = await compose(runner, ['stop']);
131
+ if (stopped.code !== 0)
132
+ fail('Could not stop the local Postgres.', stopped);
133
+ }
134
+ /** Whether the local Postgres container is running. */
135
+ export async function isRunning(runner = run) {
136
+ const state = await runner('docker', ['inspect', '--format', '{{.State.Running}}', CONTAINER]);
137
+ return state.code === 0 && state.stdout.trim() === 'true';
138
+ }
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "spotcraft",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "The spotcraft command: run the Spotcraft apps server's database setup locally",
5
+ "keywords": [
6
+ "spotcraft",
7
+ "cli",
8
+ "postgres",
9
+ "local-development"
10
+ ],
11
+ "homepage": "https://spotcraft.dev",
12
+ "bugs": {
13
+ "url": "https://github.com/vindotski/spotcraft/issues"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/vindotski/spotcraft.git",
18
+ "directory": "packages/cli"
19
+ },
20
+ "license": "Apache-2.0",
21
+ "type": "module",
22
+ "engines": {
23
+ "node": ">=24"
24
+ },
25
+ "files": [
26
+ "LICENSE",
27
+ "NOTICE",
28
+ "dist"
29
+ ],
30
+ "bin": {
31
+ "spotcraft": "./dist/cli.js"
32
+ },
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "scripts": {
37
+ "build": "tsc -p tsconfig.build.json",
38
+ "typecheck": "tsc",
39
+ "test": "node --conditions=spotcraft-source --test 'test/**/*.test.ts'",
40
+ "spotcraft": "node --conditions=spotcraft-source src/cli.ts",
41
+ "prepack": "node -e \"const fs = require('node:fs'); if (!fs.existsSync('dist')) throw new Error('Build first: pnpm --recursive run build'); for (const f of ['LICENSE', 'NOTICE']) fs.copyFileSync('../../' + f, f)\""
42
+ },
43
+ "dependencies": {
44
+ "@spotcraft/kit": "0.2.0",
45
+ "pg": "^8.23.1"
46
+ },
47
+ "devDependencies": {
48
+ "@types/node": "catalog:",
49
+ "@types/pg": "^8.23.1",
50
+ "typescript": "catalog:"
51
+ }
52
+ }