create-user-hub 0.2.1 → 0.3.1

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/README.md CHANGED
@@ -16,12 +16,12 @@ You get a TanStack Start + Convex app with Tailwind, shadcn (dark theme) and Vit
16
16
 
17
17
  - **Sign-in** from [`@user-hub/auth`](https://www.npmjs.com/package/@user-hub/auth): a signed-in home page, a facilitator-only page, sign-out, and notes saved per person.
18
18
  - **For coding agents:** `CLAUDE.md` (also as `AGENTS.md`) and the `user-hub-auth` skill in `.claude/skills`.
19
- - **`bun run setup`:** one command that creates your Convex project, registers the app with your hub and sets the values it needs.
19
+ - **`bun run setup`:** one command that creates your Convex project, registers the app with your hub in an event (a workshop: it asks which, or creates one) and sets the values it needs.
20
20
 
21
21
  ## Then
22
22
 
23
23
  ```sh
24
24
  cd my-app
25
- bun run setup # connects Convex and the hub, once
25
+ bun run setup # connects Convex and the hub, once (--event <slug> without a terminal)
26
26
  bun run dev # http://localhost:3000
27
27
  ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-user-hub",
3
- "version": "0.2.1",
3
+ "version": "0.3.1",
4
4
  "description": "Start a TanStack Start + Convex app with User Hub sign-in: bun create user-hub@latest my-app",
5
5
  "type": "module",
6
6
  "bin": {
@@ -4,6 +4,7 @@ HUB_URL=https://hub.example.com
4
4
  HUB_API_KEY=
5
5
 
6
6
  # Written by bun run setup and the Convex CLI:
7
- # CONVEX_DEPLOYMENT, VITE_CONVEX_URL, VITE_HUB_URL, HUB_APP_NAME (this app's
8
- # name in the hub, once registered), HUB_APP_DEV_URL (its development URL),
7
+ # CONVEX_DEPLOYMENT, VITE_CONVEX_URL, VITE_HUB_URL, HUB_EVENT (the slug of the
8
+ # hub event the app belongs to), HUB_APP_NAME (this app's name in the hub,
9
+ # once registered), HUB_APP_DEV_URL (its development URL),
9
10
  # HUB_APP_PROD_URL (once given)
@@ -4,7 +4,8 @@ A TanStack Start + Convex app whose sign-in comes from User Hub: people scan the
4
4
 
5
5
  ## How it is wired
6
6
 
7
- - `convex/hub.ts`: this app's key in the hub (`APP_KEY`), written by `bun run setup`.
7
+ - `convex/hub.ts`: this app's key in the hub (`APP_KEY`, made from its event's slug and its name), written by `bun run setup`.
8
+ - The app belongs to one hub **event** (a workshop): its slug is `HUB_EVENT` in `.env.local`, saved by `bun run setup`.
8
9
  - `convex/auth.config.ts`: `hubAuth({ app: APP_KEY })`; Convex trusts hub tokens through `HUB_ISSUER` and `HUB_JWKS` on the deployment.
9
10
  - `src/routes/__root.tsx`: `ConvexHubAuthProvider` and `HubSignedIn` inside `<body>`. Never move them outside `<html>` or into the router's `Wrap`.
10
11
  - People: `useHubUser()` in components; `requireHubUser(ctx)` / `requireFacilitator(ctx)` in Convex functions. Key data on the person's hub id; check roles on the server.
@@ -24,6 +25,6 @@ A TanStack Start + Convex app whose sign-in comes from User Hub: people scan the
24
25
 
25
26
  ## Commands
26
27
 
27
- `bun run setup` (once; signs the folder in first when run in a terminal and it is not), `bun run setup --prod <url>` (once deployed: registers the production URL so badge scans can reach the app; see the skill's "Production URL"), `bun run setup --dev <url>` (change where the hub opens the app for developers; first registered as `http://localhost:` plus the port in the `dev` script, kept on later runs; change the port in the `dev` script too), `bun run setup --unlisted` / `--listed` (keep the app out of the hub's badge app list, or put it back; new apps are listed), `bun run dev`, `bun run check` (`vp check`: format, lint and type-check), `bun run fix` (`vp check --fix`), `bun run typecheck`, `bun run build`, `just build` / `just push` (deploy Convex to production and build the Docker image against it; `IMAGE` sets the registry path; the container needs no env). Lint and format rules live in `vite.config.ts` (Vite+); `vp` is project-local, so run it through the scripts or `bunx vp`.
28
+ `bun run setup` (once; signs the folder in first when run in a terminal and it is not; in a terminal it asks which hub event the app is for, or creates one, and saves it as `HUB_EVENT`), `bun run setup --event <slug>` (the event without asking: an agent asks the human which event and passes it, `bunx hub-user events` lists them; never create an event unless the human asks, and then ask for its time zone too; with another event than `HUB_EVENT`, or `--name` with another name than `HUB_APP_NAME`, the app is registered anew with a new app key and the earlier registration is left as it was), `bun run setup --prod <url>` (once deployed: registers the production URL so badge scans can reach the app; see the skill's "Production URL"), `bun run setup --dev <url>` (change where the hub opens the app for developers; first registered as `http://localhost:` plus the port in the `dev` script, kept on later runs; change the port in the `dev` script too: it is defined only there, and `server.strictPort` in `vite.config.ts` makes the dev server stop when the port is taken rather than move to another one the hub does not know), `bun run setup --unlisted` / `--listed` (keep the app out of the hub's badge app list, or put it back; new apps are listed), `bun run dev`, `bun run check` (`vp check`: format, lint and type-check), `bun run fix` (`vp check --fix`), `bun run typecheck`, `bun run build`, `just build` / `just push` (deploy Convex to production and build the Docker image against it; `IMAGE` sets the registry path; the container needs no env). Lint and format rules live in `vite.config.ts` (Vite+); `vp` is project-local, so run it through the scripts or `bunx vp`.
28
29
 
29
- **Hub moved:** sign the folder in to the new hub (`bunx hub-user login --hub <new url>`, replacing `HUB_URL` and `HUB_API_KEY`), run `bun run setup` (it updates this app's registration and sets `HUB_ISSUER`/`HUB_JWKS` on Convex, production included once a production URL is known, and `VITE_HUB_URL`), then `just push`, because `VITE_HUB_URL` is built into the frontend.
30
+ **Hub moved:** sign the folder in to the new hub (`bunx hub-user login --hub <new url>`, replacing `HUB_URL` and `HUB_API_KEY`), run `bun run setup` (with `--event <slug>` when the new hub has no event with this app's `HUB_EVENT`; it updates this app's registration and sets `HUB_ISSUER`/`HUB_JWKS` on Convex, production included once a production URL is known, and `VITE_HUB_URL`), then `just push`, because `VITE_HUB_URL` is built into the frontend.
@@ -12,8 +12,8 @@ A TanStack Start + Convex app with User Hub sign-in: people scan their badge and
12
12
 
13
13
  Run it in this folder with the dependencies installed (`bun install` first in a fresh clone): `bunx hub-user` runs the CLI that comes with `@user-hub/auth`. Anywhere else it fetches an npm package called `hub-user`, which is not ours. Paste an API key from the hub's account page, or press Enter and approve the sign-in in your browser. It saves `HUB_URL` and `HUB_API_KEY` to `.env.local`. Skip this if you signed in when the app was created; `bun run setup` also asks when this folder is not signed in.
14
14
 
15
- 2. `bun run setup`: creates your Convex project, registers the app with the hub and sets everything up. If another app already has this name in the hub, it asks you for a new one (or run `bun run setup --name <name>`). New apps show in the hub's badge app list once they have a production URL; `bun run setup --unlisted` keeps this one out and `--listed` puts it back. Safe to run again. If the hub later says your account may not change this app (it belongs to another account), ask a hub admin, or register it under a new name: delete `HUB_APP_NAME` from `.env.local` and run `bun run setup --name <new name>`.
16
- 3. `bun run dev`, then open http://localhost:3000. You are sent to the hub to pick who to be, then back signed in. To use another port, change it in `package.json`'s `dev` script and run `bun run setup --dev http://localhost:<port>`; later runs of setup keep the development URL.
15
+ 2. `bun run setup`: creates your Convex project, registers the app with the hub and sets everything up. The hub runs many workshops, called events, and the app belongs to one: setup lists the active events and asks which (or creates a new one, asking for its name and time zone), then saves it as `HUB_EVENT` in `.env.local`. Without a terminal, pass it: `bun run setup --event <slug>` (`bunx hub-user events` lists the slugs). If the saved event was deleted from the hub, setup asks again (or, without a terminal, says to pass `--event`). If another app already has this name in the event, it asks you for a new one (or run `bun run setup --name <name>`). New apps show in the hub's badge app list once they have a production URL; `bun run setup --unlisted` keeps this one out and `--listed` puts it back. Safe to run again. `bun run setup --name <name>` or `--event <slug>` with another name or event than the saved ones (`HUB_APP_NAME`, `HUB_EVENT` in `.env.local`) registers the app anew, with a new app key; setup leaves the earlier registration as it was.
16
+ 3. `bun run dev`, then open http://localhost:3000. You are sent to the hub to pick who to be, then back signed in. If something else already uses that port, the dev server stops with an error instead of moving to another port, because the hub only sends you back to the registered URL. To use another port, change it in `package.json`'s `dev` script and run `bun run setup --dev http://localhost:<port>`; later runs of setup keep the development URL.
17
17
  4. Once the app is deployed: `bun run setup --prod https://your-app.example.com`, so badge scans can reach it. Setup asks for this the first time; press Enter to skip until you deploy.
18
18
 
19
19
  ## Deploy
@@ -27,7 +27,7 @@ Then serve the container (port 3000) at your production URL and make sure the hu
27
27
 
28
28
  ### Hub moved
29
29
 
30
- Sign this folder in to the new hub (`bunx hub-user login --hub <new url>`, which replaces `HUB_URL` and `HUB_API_KEY` in `.env.local`) and run `bun run setup`: it updates this app's registration with the new hub and sets `HUB_ISSUER`, `HUB_JWKS` (on the production Convex deployment too, once it has a production URL) and `VITE_HUB_URL`. Then `just push`, because `VITE_HUB_URL` is built into the frontend.
30
+ Sign this folder in to the new hub (`bunx hub-user login --hub <new url>`, which replaces `HUB_URL` and `HUB_API_KEY` in `.env.local`) and run `bun run setup` (it asks for the event again when the new hub has no event with the slug in `HUB_EVENT`, or pass `--event <slug>`): it updates this app's registration with the new hub and sets `HUB_ISSUER`, `HUB_JWKS` (on the production Convex deployment too, once it has a production URL) and `VITE_HUB_URL`. Then `just push`, because `VITE_HUB_URL` is built into the frontend.
31
31
 
32
32
  ## What's inside
33
33
 
@@ -16,32 +16,32 @@
16
16
  "dependencies": {
17
17
  "@base-ui/react": "^1.9.0",
18
18
  "@fontsource-variable/oxanium": "^5.3.0",
19
- "@tailwindcss/vite": "^4.3.3",
19
+ "@tailwindcss/vite": "^4.3.5",
20
20
  "@tanstack/react-router": "^1.170.46",
21
- "@tanstack/react-start": "^1.169.4",
22
- "@user-hub/auth": "^0.3.0",
21
+ "@tanstack/react-start": "^1.169.5",
22
+ "@user-hub/auth": "^0.4.0",
23
23
  "class-variance-authority": "^0.7.1",
24
- "cn": "^0.5.0",
25
- "convex": "^1.48.0",
26
- "lucide-react": "^1.61.0",
24
+ "cn": "^0.5.2",
25
+ "convex": "^1.51.0",
26
+ "lucide-react": "^1.75.0",
27
27
  "react": "^19.3.1",
28
28
  "react-dom": "^19.3.1",
29
- "shadcn": "^4.22.1",
30
- "tailwindcss": "^4.3.3",
29
+ "shadcn": "^4.23.0",
30
+ "tailwindcss": "^4.3.5",
31
31
  "tw-animate-css": "^1.4.0"
32
32
  },
33
33
  "devDependencies": {
34
34
  "@types/bun": "^1.4.4",
35
35
  "@types/react": "^19.3.0",
36
36
  "@types/react-dom": "^19.3.0",
37
- "@vitejs/plugin-react": "^6.1.2",
38
- "oxc-transform-react": "^0.155.0",
37
+ "@vitejs/plugin-react": "^6.3.0",
38
+ "oxc-transform-react": "^0.156.0",
39
39
  "typescript": "^7.0.2",
40
- "vite": "npm:@voidzero-dev/vite-plus-core@1.4.0",
41
- "vite-plus": "1.4.0"
40
+ "vite": "npm:@voidzero-dev/vite-plus-core@8.3.8000",
41
+ "vite-plus": "1.7.0"
42
42
  },
43
43
  "overrides": {
44
- "vite": "npm:@voidzero-dev/vite-plus-core@1.4.0",
45
- "vitest": "5.0.5"
44
+ "vite": "npm:@voidzero-dev/vite-plus-core@8.3.8000",
45
+ "vitest": "5.1.0"
46
46
  }
47
47
  }
@@ -1,28 +1,54 @@
1
- // Setup: creates the Convex project, registers this app with User Hub and
2
- // sets the values that make Convex trust the hub's tokens.
3
- // Run: bun run setup [--name <name>] [--prod <url>] [--dev <url>]
4
- // [--listed|--unlisted]. Safe to run again; run it with --prod once the app
5
- // is deployed so badge scans can reach it. --dev changes where the hub opens
6
- // the app for developers (first registered as http://localhost:<the port in
7
- // package.json's dev script>); later runs keep it. --unlisted keeps the app
8
- // out of the hub's badge app list (new apps are listed), --listed puts it
9
- // back; without either, the hub keeps the current setting.
1
+ // Setup: creates the Convex project, registers this app with User Hub in an
2
+ // event (a workshop) and sets the values that make Convex trust the hub's
3
+ // tokens.
4
+ // Run: bun run setup [--event <slug>] [--name <name>] [--prod <url>]
5
+ // [--dev <url>] [--listed|--unlisted]. Safe to run again; run it with --prod
6
+ // once the app is deployed so badge scans can reach it. --event picks the
7
+ // hub event the app belongs to (`bunx hub-user events` lists them); without
8
+ // it, the event saved in .env.local (HUB_EVENT) is used, and in a terminal
9
+ // setup asks for one the first time (or creates one). --name sets the app's
10
+ // name in the hub (default: the saved HUB_APP_NAME, else the package name).
11
+ // An event or name other than the saved ones registers the app anew, with a
12
+ // new key; the earlier registration is left as it was. --dev changes where the
13
+ // hub opens the app for developers (first registered as
14
+ // http://localhost:<the port in package.json's dev script>); later runs keep
15
+ // it. --unlisted keeps the app out of the hub's badge app list (new apps are
16
+ // listed), --listed puts it back; without either, the hub keeps the current
17
+ // setting.
10
18
  // Needs HUB_URL and HUB_API_KEY in .env.local (Bun loads it), which
11
19
  // `bunx hub-user login` saves; in a terminal, setup runs it when they are
12
20
  // missing or the hub refuses the key.
13
21
 
14
22
  import { existsSync, renameSync } from "node:fs";
15
- import { rename } from "node:fs/promises";
23
+ import { chmod, rename, rm, stat, writeFile } from "node:fs/promises";
16
24
 
17
25
  const ENV_FILE = ".env.local";
18
26
  const HUB_FILE = "convex/hub.ts";
19
27
  const AUTH_CONFIG = "convex/auth.config.ts";
20
28
  const AUTH_CONFIG_ASIDE = "convex/auth.config.ts.setup";
21
29
 
22
- // The value after --flag on the command line, if any.
23
- function flag(name: string) {
30
+ // The options that take a value, and the form to show when it is missing.
31
+ const VALUE_FLAGS = {
32
+ event: "--event <slug> (`bunx hub-user events` lists the slugs)",
33
+ name: '--name "<the app\'s name in the hub>"',
34
+ prod: "--prod https://your-app.example.com",
35
+ dev: "--dev http://localhost:<port>",
36
+ };
37
+
38
+ // The value after --flag on the command line, or undefined when the option
39
+ // is left out. Given without a value (nothing after it, or another flag), it
40
+ // stops setup: running on as if it were left out would quietly do something
41
+ // else, such as a listing-only update for `--prod --unlisted`.
42
+ function flag(name: keyof typeof VALUE_FLAGS) {
24
43
  const at = process.argv.indexOf(`--${name}`);
25
- return at > -1 ? process.argv[at + 1]?.trim() || undefined : undefined;
44
+ if (at === -1) return undefined;
45
+ const value = process.argv[at + 1]?.trim();
46
+ if (!value || value.startsWith("--")) {
47
+ fail(`--${name} needs a value:
48
+
49
+ bun run setup ${VALUE_FLAGS[name]}`);
50
+ }
51
+ return value;
26
52
  }
27
53
 
28
54
  function step(message: string) {
@@ -69,12 +95,34 @@ async function readEnv() {
69
95
  return (await file.exists()) ? await file.text() : "";
70
96
  }
71
97
 
72
- // Set or replace KEY=value in .env.local.
73
- async function writeEnv(key: string, value: string) {
98
+ // Set or replace KEY=value lines in .env.local, keeping every other line.
99
+ // Values that belong together (a registration's event and name) are saved in
100
+ // one write: the new content goes to a temporary file in the same folder
101
+ // (ignored by .env.* in .gitignore), which is then renamed over .env.local.
102
+ // A rename on the same filesystem replaces the file atomically, so a stopped
103
+ // run leaves the old file or the new one, never a mix. The renamed file keeps
104
+ // the temporary file's mode, so that gets .env.local's own mode first (600
105
+ // from hub-user login; 600 for a new file too, as it holds the API key).
106
+ async function writeEnv(values: Record<string, string>) {
107
+ const keys = Object.keys(values);
74
108
  const lines = (await readEnv())
75
109
  .split("\n")
76
- .filter((line) => line && !line.startsWith(`${key}=`));
77
- await Bun.write(ENV_FILE, `${[...lines, `${key}=${value}`].join("\n")}\n`);
110
+ .filter((line) => line && !keys.some((key) => line.startsWith(`${key}=`)));
111
+ const added = Object.entries(values).map(([key, value]) => `${key}=${value}`);
112
+ const mode = existsSync(ENV_FILE)
113
+ ? (await stat(ENV_FILE)).mode & 0o777
114
+ : 0o600;
115
+ const temporary = `${ENV_FILE}.${process.pid}.tmp`;
116
+ try {
117
+ await writeFile(temporary, `${[...lines, ...added].join("\n")}\n`, {
118
+ mode,
119
+ });
120
+ // The umask can narrow the mode a new file gets; set it exactly.
121
+ await chmod(temporary, mode);
122
+ await rename(temporary, ENV_FILE);
123
+ } finally {
124
+ await rm(temporary, { force: true });
125
+ }
78
126
  }
79
127
 
80
128
  // Signs this folder in to the hub with `hub-user login` (an API key or the
@@ -99,9 +147,9 @@ async function signIn() {
99
147
  }
100
148
 
101
149
  // What to run when this folder is not signed in and nobody can be asked.
102
- function loginHelp(problem: string) {
150
+ function loginHelp(problem: string, again = "bun run setup") {
103
151
  const hub = process.env.HUB_URL ? "" : " --hub https://<your hub>";
104
- return `${problem} Sign the folder in, then run bun run setup again:
152
+ return `${problem} Sign the folder in, then run ${again} again:
105
153
 
106
154
  bunx hub-user login${hub}
107
155
 
@@ -110,6 +158,134 @@ the sign-in in your browser. A coding agent runs it with --browser and shows
110
158
  you the link to open.`;
111
159
  }
112
160
 
161
+ // hub-user, signing the folder in again once (in a terminal) when the hub
162
+ // refuses the API key: hub-user exits with 4 then.
163
+ let signedInAgain = false;
164
+ async function signedInHubUser(...args: string[]) {
165
+ for (;;) {
166
+ const result = await hubUser(...args);
167
+ if (result.code !== 4) return result;
168
+ if (!process.stdin.isTTY || signedInAgain) {
169
+ fail(loginHelp("The hub did not accept this folder's API key."));
170
+ }
171
+ console.log("\n The hub did not accept this folder's API key.");
172
+ await signIn();
173
+ signedInAgain = true;
174
+ }
175
+ }
176
+
177
+ type HubEvent = {
178
+ slug: string;
179
+ name: string;
180
+ status: "active" | "ended";
181
+ timeZone: string;
182
+ };
183
+
184
+ // What to run when no event is known and nobody can be asked.
185
+ const EVENT_HELP = `Pass the hub event this app belongs to:
186
+
187
+ bun run setup --event <slug>
188
+
189
+ \`bunx hub-user events\` lists the events and their slugs.`;
190
+
191
+ // Creates an event, asking for its name and time zone. Undefined when the
192
+ // slug is taken, so the caller asks again.
193
+ async function createEvent(): Promise<HubEvent | undefined> {
194
+ const name = (prompt(" Name of the new event:") ?? "").trim();
195
+ if (!name) fail("No event name given. Run bun run setup again.");
196
+ // Asked rather than taken from this machine, which in a sandbox or CI is
197
+ // often UTC; the hub shows the event's schedule in this zone.
198
+ const here = Intl.DateTimeFormat().resolvedOptions().timeZone;
199
+ let timeZone: string;
200
+ for (;;) {
201
+ timeZone =
202
+ (
203
+ prompt(
204
+ ` The event's time zone, such as Europe/Berlin (Enter for ${here}):`,
205
+ ) ?? ""
206
+ ).trim() || here;
207
+ try {
208
+ new Intl.DateTimeFormat("en", { timeZone });
209
+ break;
210
+ } catch {
211
+ console.log(` "${timeZone}" is not a time zone. Use an IANA name.`);
212
+ }
213
+ }
214
+ const created = await signedInHubUser(
215
+ "events",
216
+ "create",
217
+ "--name",
218
+ name,
219
+ "--time-zone",
220
+ timeZone,
221
+ "--json",
222
+ );
223
+ // hub-user exits with 3 when an event with that slug exists.
224
+ if (created.code === 3) {
225
+ const { slug } = JSON.parse(created.output) as { slug?: string };
226
+ console.log(
227
+ `\n An event with the slug "${slug ?? name}" already exists. Pick it below, or give the new event another name.`,
228
+ );
229
+ return undefined;
230
+ }
231
+ if (!created.ok) {
232
+ process.stderr.write(created.errors);
233
+ fail("The hub did not create the event; see the error above.");
234
+ }
235
+ const event = JSON.parse(created.output) as HubEvent;
236
+ console.log(
237
+ ` Created the event "${event.name}" (slug ${event.slug}, time zone ${event.timeZone})`,
238
+ );
239
+ return event;
240
+ }
241
+
242
+ // Asks which of the hub's active events this app belongs to, or creates one.
243
+ async function chooseEvent(): Promise<HubEvent> {
244
+ for (;;) {
245
+ const listed = await signedInHubUser("events", "--json");
246
+ if (!listed.ok) {
247
+ process.stderr.write(listed.errors);
248
+ fail("Could not list the hub's events; see the error above.");
249
+ }
250
+ const active = (JSON.parse(listed.output) as HubEvent[]).filter(
251
+ (event) => event.status === "active",
252
+ );
253
+ if (active.length === 0) {
254
+ console.log(
255
+ "\n The hub has no active events yet. Create the one this app is for.",
256
+ );
257
+ const created = await createEvent();
258
+ if (created) return created;
259
+ continue;
260
+ }
261
+ console.log("\n Which hub event is this app for?");
262
+ for (const [index, event] of active.entries()) {
263
+ console.log(` ${index + 1}. ${event.name} (${event.slug})`);
264
+ }
265
+ console.log(` ${active.length + 1}. Create a new event`);
266
+ for (;;) {
267
+ const answer = prompt(` Number (1-${active.length + 1}):`);
268
+ if (answer === null) fail("No event chosen. Run bun run setup again.");
269
+ const choice = Number(answer.trim());
270
+ if (choice === active.length + 1) break;
271
+ const event = active[choice - 1];
272
+ if (Number.isInteger(choice) && event) return event;
273
+ console.log(` Type a number from 1 to ${active.length + 1}.`);
274
+ }
275
+ const created = await createEvent();
276
+ if (created) return created;
277
+ }
278
+ }
279
+
280
+ // Every option with a value, read before anything changes, so a missing value
281
+ // stops setup here.
282
+ const flags = {
283
+ event: flag("event"),
284
+ name: flag("name"),
285
+ prod: flag("prod"),
286
+ dev: flag("dev"),
287
+ };
288
+
113
289
  // Put back an auth config left aside by an interrupted run.
114
290
  if (existsSync(AUTH_CONFIG_ASIDE) && !existsSync(AUTH_CONFIG)) {
115
291
  renameSync(AUTH_CONFIG_ASIDE, AUTH_CONFIG);
@@ -120,6 +296,34 @@ if (!existsSync("node_modules/@user-hub/auth")) {
120
296
  fail("Install the dependencies first: bun install");
121
297
  }
122
298
 
299
+ // What .env.local remembers about this app's own registration in the hub.
300
+ // HUB_EVENT and HUB_APP_NAME are written together, only after a successful
301
+ // registration, so together they name the app's own entry; the URLs are the
302
+ // ones last sent.
303
+ const saved = {
304
+ event: process.env.HUB_EVENT?.trim() || undefined,
305
+ name: process.env.HUB_APP_NAME?.trim() || undefined,
306
+ devUrl: process.env.HUB_APP_DEV_URL?.trim() || undefined,
307
+ prodUrl: process.env.HUB_APP_PROD_URL?.trim() || undefined,
308
+ };
309
+
310
+ // Without a terminal nobody can be asked for the event, so say that first,
311
+ // with the sign-in steps when the folder is not signed in either: one failure
312
+ // tells the caller everything. In a terminal the event is asked after the
313
+ // sign-in, since listing the events needs it.
314
+ if (!process.stdin.isTTY && !flags.event && !saved.event) {
315
+ if (!process.env.HUB_URL || !process.env.HUB_API_KEY) {
316
+ fail(`${loginHelp(
317
+ "This folder is not signed in to the hub, and the app is not in a hub event yet.",
318
+ "bun run setup --event <slug>",
319
+ )}
320
+
321
+ \`bunx hub-user events\` lists the events and their slugs once the folder is
322
+ signed in.`);
323
+ }
324
+ fail(`This app is not in a hub event yet. ${EVENT_HELP}`);
325
+ }
326
+
123
327
  // Sign-in first: nothing below works without it, and a refused key is better
124
328
  // found before the Convex project and the questions.
125
329
  if (!process.env.HUB_URL || !process.env.HUB_API_KEY) {
@@ -144,6 +348,15 @@ if (!process.env.HUB_URL || !process.env.HUB_API_KEY) {
144
348
  }
145
349
  }
146
350
 
351
+ // The hub event (workshop) the app belongs to: --event, else the saved one,
352
+ // else asked here (a run without a terminal stopped above), before the Convex
353
+ // project is created.
354
+ let event = flags.event ?? saved.event;
355
+ if (!event) {
356
+ step("Choosing the hub event this app belongs to");
357
+ event = (await chooseEvent()).slug;
358
+ }
359
+
147
360
  // 1. Convex project. Its first push happens before the hub values exist, so
148
361
  // the auth config sits aside for that push only (Convex refuses an auth
149
362
  // config whose env vars are unset) and comes back straight after.
@@ -170,72 +383,82 @@ if (!/^CONVEX_DEPLOYMENT=/m.test(await readEnv())) {
170
383
  }
171
384
  }
172
385
 
173
- // 2. Register with the hub. The first time, --new makes sure this never takes
174
- // over another app with the same name: if the name is taken, ask for
175
- // another one. Once registered, the name is kept in .env.local
176
- // (HUB_APP_NAME) and later runs update this app's own registration.
386
+ // 2. Register with the hub, in the event. An app's key comes from its event
387
+ // and its name, so only the saved pair is this app's own registration,
388
+ // which later runs update. Any other pair (another event, another name) is
389
+ // a new app: registered with --new, so it never takes over another app of
390
+ // that name (if the name is taken, ask for another one), and with its URLs.
391
+ // Setup never removes the earlier registration.
177
392
  step("Registering this app with User Hub");
178
393
  const packageJson = (await Bun.file("package.json").json()) as {
179
394
  name: string;
180
395
  scripts: { dev?: string };
181
396
  };
182
- const packageName = packageJson.name;
183
- // HUB_APP_NAME is written only after a successful registration, so it marks
184
- // this app's own entry. `bun run setup --name <name>` picks a new name.
185
- const alreadyRegistered = Boolean(process.env.HUB_APP_NAME);
186
- let appName = process.env.HUB_APP_NAME ?? flag("name") ?? packageName;
397
+ let appName = flags.name ?? saved.name ?? packageJson.name;
398
+ // Read again on each attempt: the event and the name can change below.
399
+ const isOwnRegistration = () => event === saved.event && appName === saved.name;
187
400
 
188
401
  // Where badge scans send people. Asked once in a terminal; skipped until the
189
402
  // app is deployed, then added with --prod. HUB_APP_PROD_URL remembers it.
190
- let prodUrl = flag("prod");
191
- if (!prodUrl && !process.env.HUB_APP_PROD_URL && process.stdin.isTTY) {
403
+ let prodUrl = flags.prod;
404
+ if (!prodUrl && !saved.prodUrl && process.stdin.isTTY) {
192
405
  prodUrl =
193
406
  prompt(
194
407
  " Production URL, where badge scans send people (Enter to skip until you deploy):",
195
408
  )?.trim() || undefined;
196
409
  }
197
- // Where the hub opens the app for developers. Sent the first time and with
198
- // --dev; otherwise the hub keeps the registered one, which HUB_APP_DEV_URL
199
- // remembers (set by hand with hub-user register, it is not known here).
410
+ // Where the hub opens the app for developers: first
411
+ // http://localhost:<port of the dev script>, then whatever --dev sets.
200
412
  const devPort =
201
413
  /--port (\d+)/.exec(packageJson.scripts.dev ?? "")?.[1] ?? "3000";
202
- const devFlag = flag("dev");
203
- const sendDev = Boolean(devFlag) || !alreadyRegistered;
204
- const devUrl: string | undefined =
205
- devFlag ??
206
- process.env.HUB_APP_DEV_URL ??
207
- (sendDev ? `http://localhost:${devPort}` : undefined);
414
+ const devFlag = flags.dev;
415
+ // The URLs to send. The app's own registration gets only the ones given now
416
+ // (the hub keeps the rest); a new app starts without URLs, so it also gets
417
+ // the saved ones, or the default development URL.
418
+ function urlsToSend() {
419
+ if (isOwnRegistration()) return { dev: devFlag, prod: prodUrl };
420
+ return {
421
+ dev: devFlag ?? saved.devUrl ?? `http://localhost:${devPort}`,
422
+ prod: prodUrl ?? saved.prodUrl,
423
+ };
424
+ }
208
425
  // Passed on to hub-user as is; without either the hub keeps its setting.
209
426
  const listing = ["--listed", "--unlisted"].filter((arg) =>
210
427
  process.argv.includes(arg),
211
428
  );
212
429
  if (listing.length > 1) fail("Pass --listed or --unlisted, not both.");
430
+ let sent: ReturnType<typeof urlsToSend>;
213
431
  let registered: Awaited<ReturnType<typeof run>>;
214
- let signedInAgain = false;
215
432
  for (;;) {
216
- registered = await hubUser(
433
+ sent = urlsToSend();
434
+ registered = await signedInHubUser(
217
435
  "register",
436
+ "--event",
437
+ event,
218
438
  "--name",
219
439
  appName,
220
- ...(sendDev && devUrl ? ["--dev", devUrl] : []),
221
- ...(prodUrl ? ["--prod", prodUrl] : []),
440
+ ...(sent.dev ? ["--dev", sent.dev] : []),
441
+ ...(sent.prod ? ["--prod", sent.prod] : []),
222
442
  ...listing,
223
443
  "--json",
224
- ...(alreadyRegistered ? [] : ["--new"]),
444
+ ...(isOwnRegistration() ? [] : ["--new"]),
225
445
  );
226
- // hub-user exits with 4 when the hub refuses the API key (401).
227
- if (registered.code === 4) {
228
- if (!process.stdin.isTTY || signedInAgain) {
229
- fail(loginHelp("The hub did not accept this folder's API key."));
230
- }
231
- console.log("\n The hub did not accept this folder's API key.");
232
- await signIn();
233
- signedInAgain = true;
446
+ // hub-user exits with 5 when no event has that slug, for example a saved
447
+ // event that was deleted from the hub.
448
+ if (registered.code === 5) {
449
+ const gone = `The hub has no event with the slug "${event}"${event === saved.event ? " (saved in .env.local as HUB_EVENT; it may have been deleted)" : ""}.`;
450
+ if (!process.stdin.isTTY) fail(`${gone} ${EVENT_HELP}`);
451
+ console.log(`\n ${gone}`);
452
+ event = (await chooseEvent()).slug;
234
453
  continue;
235
454
  }
236
- // hub-user exits with 3 when --new finds the name taken.
455
+ // hub-user exits with 3 when --new finds the name taken, or when an app of
456
+ // another event has the same key.
237
457
  if (registered.code !== 3) break;
238
- console.log(`\n An app called "${appName}" already exists in the hub.`);
458
+ const { error } = JSON.parse(registered.output) as { error?: string };
459
+ console.log(
460
+ `\n ${error ?? `An app called "${appName}" already exists in the hub.`}`,
461
+ );
239
462
  if (!process.stdin.isTTY) {
240
463
  fail("Choose another name: bun run setup --name <new name>");
241
464
  }
@@ -245,25 +468,46 @@ for (;;) {
245
468
  if (!registered.ok) {
246
469
  process.stderr.write(registered.errors);
247
470
  fail(
248
- prodUrl
471
+ sent.prod
249
472
  ? "The hub refused the registration; see the error above. Check HUB_URL and that the production URL is a full https:// address."
250
473
  : "The hub refused the registration; see the error above. Check HUB_URL.",
251
474
  );
252
475
  }
253
- const { key, hubUrl, env, listed } = JSON.parse(registered.output) as {
476
+ const {
477
+ key,
478
+ hubUrl,
479
+ env,
480
+ listed,
481
+ event: registeredIn,
482
+ } = JSON.parse(registered.output) as {
254
483
  key: string;
255
484
  hubUrl: string;
485
+ event: { slug: string; name: string };
256
486
  env: { HUB_ISSUER: string; HUB_JWKS: string };
257
487
  // The stored setting; missing from hubs without the badge app list.
258
488
  listed?: boolean;
259
489
  };
260
- await writeEnv("HUB_APP_NAME", appName);
261
- if (prodUrl) await writeEnv("HUB_APP_PROD_URL", prodUrl);
262
- if (sendDev && devUrl) await writeEnv("HUB_APP_DEV_URL", devUrl);
263
- const production = prodUrl ?? process.env.HUB_APP_PROD_URL;
264
- console.log(` Registered as "${appName}", app key: ${key}`);
490
+ // One write: a stopped run must never leave the new event with the old name,
491
+ // which the next run would take for this app's own registration.
492
+ await writeEnv({
493
+ HUB_EVENT: event,
494
+ HUB_APP_NAME: appName,
495
+ ...(sent.prod && { HUB_APP_PROD_URL: sent.prod }),
496
+ ...(sent.dev && { HUB_APP_DEV_URL: sent.dev }),
497
+ });
498
+ // What the hub now has; a URL not sent is the registered one, if known here.
499
+ const devUrl = sent.dev ?? saved.devUrl;
500
+ const production = sent.prod ?? saved.prodUrl;
501
+ console.log(
502
+ ` Registered as "${appName}" in the event "${registeredIn.name}" (${registeredIn.slug}), app key: ${key}`,
503
+ );
504
+ if (saved.event && saved.name && !isOwnRegistration()) {
505
+ console.log(
506
+ ` This is a new registration; setup left the earlier one ("${saved.name}" in the event "${saved.event}") as it was.`,
507
+ );
508
+ }
265
509
  console.log(
266
- ` Development URL: ${devUrl ?? "the one registered in the hub"}${sendDev ? "" : " (kept; bun run setup --dev <url> changes it)"}`,
510
+ ` Development URL: ${devUrl ?? "the one registered in the hub"}${sent.dev ? "" : " (kept; bun run setup --dev <url> changes it)"}`,
267
511
  );
268
512
  // bun run dev must serve where the hub sends developers back to.
269
513
  const devUrlPort = devUrl ? URL.parse(devUrl)?.port : undefined;
@@ -294,7 +538,7 @@ for (const [variable, value] of Object.entries(env)) {
294
538
  fail(`Could not set ${variable} on Convex.`);
295
539
  }
296
540
  }
297
- await writeEnv("VITE_HUB_URL", hubUrl);
541
+ await writeEnv({ VITE_HUB_URL: hubUrl });
298
542
 
299
543
  // The production Convex deployment needs the same two values once the app is
300
544
  // deployed. It may not exist yet: then say how to set them later.
@@ -18,13 +18,19 @@ const ignorePatterns = [
18
18
 
19
19
  export default defineConfig({
20
20
  resolve: { tsconfigPaths: true },
21
+ // The port lives in package.json's dev script, where `bun run setup` reads
22
+ // it to register the development URL. The hub only sends people back to
23
+ // that URL, so stop with an error when the port is taken instead of moving
24
+ // to the next free one.
25
+ server: { strictPort: true },
21
26
  plugins: lazyPlugins(() => [
22
27
  tailwindcss(),
23
28
  tanstackStart(),
24
29
  // React Compiler, natively (oxc-transform-react) rather than through Babel.
25
30
  viteReact({ compiler: true }),
26
31
  ]),
27
- // `vp check`: format (Oxfmt), lint (Oxlint) and type-check (tsgolint).
32
+ // `vp check`: format (Oxfmt), lint (Oxlint) and type-check (tsrs, the Rust
33
+ // port of TypeScript 7, through Oxlint's type-aware mode).
28
34
  lint: {
29
35
  plugins: ["eslint", "typescript", "unicorn", "oxc"],
30
36
  categories: {