@samebase/alchemy-convex 0.30.0 → 0.32.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.
@@ -80,13 +80,6 @@ export interface ManagementApiService {
80
80
  * Convex CLI selected (CONVEX_DEPLOYMENT). Read once for each service.
81
81
  */
82
82
  readonly teamId: Effect.Effect<number, ConvexApiError>;
83
- /**
84
- * Team id for a numeric id or a slug, for Convex.HubClient, which names the
85
- * team of the hub. With a team access token, a slug is checked against the
86
- * `teamSlug` of the team's projects, so a token of another team fails; with
87
- * the Convex CLI login, a slug goes to the dashboard's team list.
88
- */
89
- readonly resolveTeamId: (team: string | number) => Effect.Effect<number, ConvexApiError>;
90
83
  /**
91
84
  * True when a deploy key that Convex returned carries the token of the
92
85
  * Management API credential itself. With an OAuth token, create_deploy_key
@@ -199,14 +192,6 @@ export const absentAsUndefined = <A, R>(
199
192
  ),
200
193
  );
201
194
 
202
- const TeamRow = Schema.Struct({ id: Schema.Number, slug: Schema.String });
203
- const TeamRows = Schema.Array(TeamRow);
204
-
205
- /** The first page of GET /teams/{team_id}/projects: every row carries the slug of the team. */
206
- const ProjectSlugRows = Schema.Struct({
207
- items: Schema.Array(Schema.Struct({ teamSlug: Schema.String })),
208
- });
209
-
210
195
  /** GET /deployments/{name}: the project of the deployment. */
211
196
  const DeploymentProject = Schema.Struct({ projectId: Schema.Number });
212
197
 
@@ -346,27 +331,18 @@ const makeService = (source: Effect.Effect<ResolvedCredentials>): ManagementApiS
346
331
  ),
347
332
  );
348
333
 
349
- /** The slug of the team, from the first project of its listing, or undefined for a team without one. Read once. */
350
- const teamSlug = (teamId: number) =>
351
- request("list projects", (c) =>
352
- c.GET("/teams/{team_id}/projects", { params: { path: { team_id: teamId } } }),
353
- ).pipe(
354
- Effect.map((body) => Schema.decodeUnknownSync(ProjectSlugRows)(body).items[0]?.teamSlug),
355
- );
356
-
357
- const projectTokenError = (projectId: number) =>
358
- new ConvexApiError({
359
- operation: "resolve team",
360
- status: 403,
361
- message: `the access token belongs to project ${projectId}, and a project token cannot create projects. Use a team access token.`,
362
- });
363
-
364
334
  const teamId: ManagementApiService["teamId"] = Effect.runSync(
365
335
  Effect.cached(
366
336
  Effect.gen(function* () {
367
337
  const details = yield* tokenDetails;
368
338
  if (details?.type === "teamToken") return details.teamId;
369
- if (details?.type === "projectToken") return yield* projectTokenError(details.projectId);
339
+ if (details?.type === "projectToken") {
340
+ return yield* new ConvexApiError({
341
+ operation: "resolve team",
342
+ status: 403,
343
+ message: `the access token belongs to project ${details.projectId}, and a project token cannot create projects. Use a team access token.`,
344
+ });
345
+ }
370
346
  // The Convex CLI login names no team, but the deployment that `npx convex dev` selected
371
347
  // belongs to a project, and the project to a team.
372
348
  const selected = selectedDeployment();
@@ -396,65 +372,6 @@ const makeService = (source: Effect.Effect<ResolvedCredentials>): ManagementApiS
396
372
  ),
397
373
  );
398
374
 
399
- // The Management API addresses teams by numeric id. The only slug lookup
400
- // it offers is per project, so a slug falls back to the dashboard's team
401
- // list, which is unofficial. Pass the numeric team id to skip this.
402
- const resolveTeamId: ManagementApiService["resolveTeamId"] = (team) =>
403
- Effect.gen(function* () {
404
- if (typeof team === "number") return team;
405
- if (/^\d+$/.test(team)) return Number(team);
406
- const details = yield* tokenDetails;
407
- if (details?.type === "teamToken") {
408
- // The Management API has no team-by-id call, so the slug of the
409
- // team comes from any of its projects. A team without a project
410
- // cannot be checked: the numeric id, or no team, is the fix.
411
- const slug = yield* teamSlug(details.teamId);
412
- if (slug === undefined) {
413
- return yield* new ConvexApiError({
414
- operation: "resolve team",
415
- status: 0,
416
- message: `team "${team}" cannot be checked against the access token: team ${details.teamId} has no project yet. Set team to ${details.teamId}.`,
417
- });
418
- }
419
- if (slug !== team) {
420
- return yield* new ConvexApiError({
421
- operation: "resolve team",
422
- status: 403,
423
- message: `the access token belongs to team ${details.teamId} ("${slug}"), and team is "${team}". Use a token of "${team}", or set team to ${details.teamId}.`,
424
- });
425
- }
426
- return details.teamId;
427
- }
428
- if (details?.type === "projectToken") return yield* projectTokenError(details.projectId);
429
- const resolved = yield* credentials;
430
- const rows = yield* Effect.tryPromise({
431
- try: async () => {
432
- const response = await fetch("https://api.convex.dev/api/dashboard/teams", {
433
- headers: { Authorization: `Bearer ${Redacted.value(resolved.accessToken)}` },
434
- });
435
- if (!response.ok) {
436
- throw new Error(`team lookup for "${team}" failed with HTTP ${response.status}`);
437
- }
438
- return Schema.decodeUnknownSync(TeamRows)(await response.json());
439
- },
440
- catch: (cause) =>
441
- new ConvexApiError({
442
- operation: "resolve team",
443
- status: 0,
444
- message: cause instanceof Error ? cause.message : String(cause),
445
- }),
446
- });
447
- const match = rows.find((row) => row.slug === team);
448
- if (match === undefined) {
449
- return yield* new ConvexApiError({
450
- operation: "resolve team",
451
- status: 404,
452
- message: `no team with slug "${team}" for this token`,
453
- });
454
- }
455
- return match.id;
456
- });
457
-
458
375
  const isCredentialToken: ManagementApiService["isCredentialToken"] = (secret) =>
459
376
  credentials.pipe(
460
377
  Effect.map(
@@ -474,7 +391,6 @@ const makeService = (source: Effect.Effect<ResolvedCredentials>): ManagementApiS
474
391
  requestVoid,
475
392
  deploymentRequest,
476
393
  teamId,
477
- resolveTeamId,
478
394
  isCredentialToken,
479
395
  isOAuthCredential,
480
396
  withToken,
package/src/Providers.ts CHANGED
@@ -4,7 +4,6 @@ import * as Provider from "alchemy/Provider";
4
4
  import * as Layer from "effect/Layer";
5
5
  import { type Credentials, fromConfig } from "./Credentials.ts";
6
6
  import { DeploymentProvider, DeploymentResource } from "./Deployment.ts";
7
- import { HubClient, HubClientProvider } from "./HubClient.ts";
8
7
  import { LocalDeployment, LocalDeploymentProvider } from "./LocalDeployment.ts";
9
8
  import { ManagementApiLive } from "./ManagementApi.ts";
10
9
  import { Project, ProjectProvider } from "./Project.ts";
@@ -20,14 +19,13 @@ export class Providers extends Provider.ProviderCollection<Providers>()("Convex"
20
19
  export const providers = (credentials: Layer.Layer<Credentials> = fromConfig()) =>
21
20
  Layer.effect(
22
21
  Providers,
23
- Provider.collection([Project, DeploymentResource, LocalDeployment, HubClient, SharedHubClient]),
22
+ Provider.collection([Project, DeploymentResource, LocalDeployment, SharedHubClient]),
24
23
  ).pipe(
25
24
  Layer.provide(
26
25
  Layer.mergeAll(
27
26
  ProjectProvider(),
28
27
  DeploymentProvider(),
29
28
  LocalDeploymentProvider(),
30
- HubClientProvider(),
31
29
  SharedHubClientProvider(),
32
30
  ),
33
31
  ),
package/src/RunRecord.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  // the Samebase research of 2026-10-21), so a state layer adds this record to
4
4
  // the output document under the reserved key `samebase.run`. The record
5
5
  // depends on no store: it comes from the GitHub Actions variables, or from
6
- // git on a laptop, and holds no secret. See docs/design/convex-state.md.
6
+ // git in the checkout that runs the stack, and holds no secret. See docs/design/convex-state.md.
7
7
  import { execFile } from "node:child_process";
8
8
  import { readFile, realpath } from "node:fs/promises";
9
9
  import { relative, sep } from "node:path";
@@ -27,13 +27,18 @@ export interface RunRecord {
27
27
  readonly stackFile: string;
28
28
  /** The branch that was deployed: the head branch of a pull request, else the pushed branch. */
29
29
  readonly branch: string;
30
- /** The pull request whose head was deployed, or null for a push and for a laptop. */
30
+ /** The pull request whose head was deployed, or null for a push and for a checkout. */
31
31
  readonly pullRequest: number | null;
32
32
  /** The commit that was deployed: the head of the pull request, else GITHUB_SHA, else git HEAD. */
33
33
  readonly headCommit: string;
34
- /** The GitHub Actions run and attempt, or null for a laptop. */
34
+ /** The GitHub Actions run and attempt, or null for a checkout. */
35
35
  readonly runUrl: string | null;
36
- readonly source: "github-actions" | "laptop";
36
+ /**
37
+ * Where the record came from: the variables of a GitHub Actions run, or git in a checkout outside
38
+ * GitHub Actions, such as a developer's machine, a sandbox, or another CI. It says nothing of the
39
+ * stage: a checkout can deploy `prod`.
40
+ */
41
+ readonly source: "github-actions" | "checkout";
37
42
  /** ISO 8601, when the record was written. */
38
43
  readonly recordedAt: string;
39
44
  }
@@ -172,7 +177,7 @@ const fromGit = (where: RunEnvironment) =>
172
177
  pullRequest: null,
173
178
  headCommit: yield* git(cwd, ["rev-parse", "HEAD"]),
174
179
  runUrl: null,
175
- source: "laptop",
180
+ source: "checkout",
176
181
  recordedAt: yield* now,
177
182
  };
178
183
  return record;
@@ -1,6 +1,6 @@
1
1
  // Convex.SharedHubClient: one deployment of an app as a client of the central identity hub, for an
2
- // app that deploys in its own GitHub Actions run, on any host, and on a laptop as a stage of the same
3
- // stack.
2
+ // app that deploys in its own GitHub Actions run, on any host, and in development as a stage of the
3
+ // same stack.
4
4
  //
5
5
  // A run in GitHub Actions asks the hub for a new client with a GitHub OIDC token, so the stack needs
6
6
  // no key and no Samebase account. The token names the repository. The hub reads
@@ -11,9 +11,10 @@
11
11
  // token.
12
12
  //
13
13
  // The answer to a production registration also holds the app's initial access token (RFC 7591
14
- // section 1.2) and the repository id. The state of stage `prod` keeps them. A laptop runs the stack
15
- // as a stage `dev-<name>`: it reads them with `SharedHubClient.read`, and a client with
16
- // `deploymentType: "development"` asks the hub with the token in place of the GitHub token (RFC 133).
14
+ // section 1.2) and the repository id. The state of stage `prod` keeps them. A development checkout
15
+ // runs the stack as a stage `dev-<name>`: it reads them with `SharedHubClient.read`, and a client
16
+ // with `deploymentType: "development"` asks the hub with the token in place of the GitHub token
17
+ // (RFC 133).
17
18
  //
18
19
  // A push removes a variable that a deploy stops passing, so a failure here must not drop working
19
20
  // variables or stop the deploy. A renewal that fails keeps the saved values. Only a client that
@@ -331,15 +332,15 @@ const newClient = (props: SharedHubClientProps) => {
331
332
  const token = Redacted.value(props.initialAccessToken);
332
333
  return token === ""
333
334
  ? Effect.logInfo(
334
- "Convex.SharedHubClient: deploy to main once for Google sign-in on this laptop.",
335
+ "Convex.SharedHubClient: deploy to main once for Google sign-in in development.",
335
336
  ).pipe(Effect.as(off))
336
337
  : request(Effect.succeed(token));
337
338
  }
338
339
 
339
340
  const requestUrl = process.env["ACTIONS_ID_TOKEN_REQUEST_URL"];
340
341
  const requestToken = process.env["ACTIONS_ID_TOKEN_REQUEST_TOKEN"];
341
- // A laptop, or another CI. In a workflow, `id-token: write` gives both, so a workflow without them
342
- // is a mistake to show, not a normal run.
342
+ // A development machine, or another CI. In a workflow, `id-token: write` gives both, so a
343
+ // workflow without them is a mistake to show, not a normal run.
343
344
  if (!requestUrl || !requestToken) {
344
345
  return (
345
346
  process.env["GITHUB_ACTIONS"] === "true"
@@ -401,14 +402,15 @@ const SavedRow = Schema.Struct({
401
402
 
402
403
  /**
403
404
  * The attributes of the client `id` in another stage of this stack, such as
404
- * `read("HubClient", { stage: "prod" })` in the stage of a laptop, as Outputs: the
405
+ * `read("HubClient", { stage: "prod" })` in a development stage, as Outputs: the
405
406
  * `initialAccessToken` and the `repository` of the production client. Without that row, the off
406
407
  * attributes, with `deploymentType: "production"`.
407
408
  *
408
409
  * `SharedHubClient.ref` is not enough: Alchemy fails the plan with `InvalidReferenceError` when the
409
- * row is missing, and a laptop before the first deploy to main has none. This read runs when the
410
- * plan resolves it, with the State service of the running stack and its `get`, so it never creates
411
- * or upgrades a store. The store revives each secret as `Redacted`, as it does for every read.
410
+ * row is missing, and a development stage before the first deploy to main has none. This read runs
411
+ * when the plan resolves it, with the State service of the running stack and its `get`, so it never
412
+ * creates or upgrades a store. The store revives each secret as `Redacted`, as it does for every
413
+ * read.
412
414
  */
413
415
  const read = (id: string, options: { readonly stage: string }) =>
414
416
  Output.fromEffect(
package/src/cli.ts CHANGED
@@ -1,82 +1,33 @@
1
1
  #!/usr/bin/env node
2
- // The commands of the package:
2
+ // The command of the package:
3
3
  //
4
- // alchemy-convex hub-client --team <team> --app <app> --callback-path <path> [--env-prefix HUB]
5
4
  // alchemy-convex stack-comment
6
5
  //
7
- // hub-client runs in the directory of a Convex app at each dev start, and renews the client of the
8
- // identity hub of the team that the development deployment of that directory has, or gives it a new
9
- // one: see registerDevelopmentClient. stack-comment runs as a step of a pull request workflow after
10
- // the deploys, and keeps one comment with the stacks of the repository: see src/StackComment.ts. It
11
- // needs GITHUB_TOKEN, and reads the store of the team of the token. Both use CONVEX_ACCESS_TOKEN or
12
- // the Convex CLI login.
13
- import { execFileSync } from "node:child_process";
6
+ // stack-comment runs as a step of a pull request workflow after the deploys, and keeps one comment
7
+ // with the stacks of the repository: see src/StackComment.ts. It needs GITHUB_TOKEN, and reads the
8
+ // store of the team of CONVEX_ACCESS_TOKEN or of the Convex CLI login.
14
9
  import { parseArgs } from "node:util";
15
10
  import * as NodeServices from "@effect/platform-node/NodeServices";
16
11
  import * as Effect from "effect/Effect";
17
12
  import * as Layer from "effect/Layer";
18
- import { fromConfig } from "./Credentials.ts";
19
- import { registerDevelopmentClient } from "./HubClient.ts";
20
- import { ManagementApiLive } from "./ManagementApi.ts";
21
- import { installedCli } from "./Push.ts";
22
13
  import { updateStackComment } from "./StackComment.ts";
23
14
  import { state } from "./State.ts";
24
15
 
25
- const { positionals, values } = parseArgs({
26
- allowPositionals: true,
27
- options: {
28
- team: { type: "string" },
29
- app: { type: "string" },
30
- "callback-path": { type: "string" },
31
- "env-prefix": { type: "string" },
32
- },
33
- });
34
- const { team, app, "callback-path": callbackPath, "env-prefix": envPrefix } = values;
16
+ const { positionals } = parseArgs({ allowPositionals: true, options: {} });
35
17
  const USAGE = `Usage:
36
- alchemy-convex hub-client --team <team> --app <app> --callback-path <path> [--env-prefix HUB]
37
18
  alchemy-convex stack-comment`;
38
19
 
39
- const hubClient = (hub: { team: string; app: string; callbackPath: string; envPrefix?: string }) =>
40
- Effect.gen(function* () {
41
- const [command, ...prefix] = yield* installedCli(process.cwd());
42
- const callbackUrl = yield* registerDevelopmentClient({
43
- ...hub,
44
- convex: (args, input) =>
45
- execFileSync(command, [...prefix, ...args], {
46
- encoding: "utf8",
47
- input,
48
- stdio: ["pipe", "pipe", "inherit"],
49
- }).trim(),
50
- });
51
- console.log(
52
- callbackUrl === undefined
53
- ? "Hub client renewed."
54
- : `Hub client registered for ${callbackUrl}.`,
55
- );
56
- }).pipe(Effect.provide(ManagementApiLive().pipe(Layer.provide(fromConfig()))));
57
-
58
20
  const stackComment = updateStackComment.pipe(
59
21
  Effect.tap((url) => Effect.sync(() => console.log(url))),
60
22
  Effect.provide(state().pipe(Layer.provide(NodeServices.layer))),
61
23
  );
62
24
 
63
- const subcommand = positionals.join(" ");
64
- const program: Effect.Effect<unknown, unknown> | undefined =
65
- // stack-comment reads the store of the team of the credential, so a --team would be ignored.
66
- subcommand === "stack-comment" && team === undefined
67
- ? stackComment
68
- : subcommand === "hub-client" &&
69
- team !== undefined &&
70
- app !== undefined &&
71
- callbackPath !== undefined
72
- ? hubClient({ team, app, callbackPath, ...(envPrefix === undefined ? {} : { envPrefix }) })
73
- : undefined;
74
- if (program === undefined) {
25
+ if (positionals.join(" ") !== "stack-comment") {
75
26
  console.error(USAGE);
76
27
  process.exit(1);
77
28
  }
78
29
 
79
- await Effect.runPromise(program).catch((error: unknown) => {
30
+ await Effect.runPromise(stackComment).catch((error: unknown) => {
80
31
  console.error(error instanceof Error ? error.message : String(error));
81
32
  process.exit(1);
82
33
  });
package/src/index.ts CHANGED
@@ -18,14 +18,6 @@ export {
18
18
  type DeploymentProps,
19
19
  ProductionDeploymentNotFound,
20
20
  } from "./Deployment.ts";
21
- export {
22
- HUB_PROJECT_NAME,
23
- HubClient,
24
- type HubClientAttributes,
25
- HubClientFailed,
26
- type HubClientProps,
27
- type HubDeploymentType,
28
- } from "./HubClient.ts";
29
21
  export {
30
22
  LocalDeployment,
31
23
  type LocalDeploymentAttributes,
@@ -72,7 +72,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
72
72
  recordedAt: string;
73
73
  repository: string;
74
74
  runUrl: string | null;
75
- source: "github-actions" | "laptop";
75
+ source: "github-actions" | "checkout";
76
76
  stackFile: string;
77
77
  version: 1;
78
78
  };
@@ -131,7 +131,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
131
131
  recordedAt: string;
132
132
  repository: string;
133
133
  runUrl: string | null;
134
- source: "github-actions" | "laptop";
134
+ source: "github-actions" | "checkout";
135
135
  stackFile: string;
136
136
  version: 1;
137
137
  } | null;
@@ -153,7 +153,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
153
153
  recordedAt: string;
154
154
  repository: string;
155
155
  runUrl: string | null;
156
- source: "github-actions" | "laptop";
156
+ source: "github-actions" | "checkout";
157
157
  stackFile: string;
158
158
  version: 1;
159
159
  } | null;
@@ -232,7 +232,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
232
232
  recordedAt: string;
233
233
  repository: string;
234
234
  runUrl: string | null;
235
- source: "github-actions" | "laptop";
235
+ source: "github-actions" | "checkout";
236
236
  stackFile: string;
237
237
  version: 1;
238
238
  } | null;
@@ -254,7 +254,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
254
254
  recordedAt: string;
255
255
  repository: string;
256
256
  runUrl: string | null;
257
- source: "github-actions" | "laptop";
257
+ source: "github-actions" | "checkout";
258
258
  stackFile: string;
259
259
  version: 1;
260
260
  } | null;
@@ -8,7 +8,7 @@ export const runRecord = v.object({
8
8
  pullRequest: v.union(v.number(), v.null()),
9
9
  headCommit: v.string(),
10
10
  runUrl: v.union(v.string(), v.null()),
11
- source: v.union(v.literal("github-actions"), v.literal("laptop")),
11
+ source: v.union(v.literal("github-actions"), v.literal("checkout")),
12
12
  recordedAt: v.string(),
13
13
  });
14
14
 
@@ -16,7 +16,7 @@ type RunRecord = Infer<typeof runRecord>;
16
16
 
17
17
  /**
18
18
  * True when a write with `next` must replace `current`, the record of the stage. Records that differ
19
- * only in `recordedAt`, the time of one write, name the same run. Two laptop deploys of one commit
19
+ * only in `recordedAt`, the time of one write, name the same run. Two checkout deploys of one commit
20
20
  * have no `runUrl`, so they are the same run too. A write without a record (`null`) clears one.
21
21
  */
22
22
  export const runChanged = (current: RunRecord | undefined, next: RunRecord | null) => {
@@ -12,4 +12,5 @@
12
12
  // 4: the store is a component (same functions).
13
13
  // 5: rows hold their secrets sealed: `set` and `setOutput` are actions, with `sealing`, `chooseKey`,
14
14
  // `rotateKey`, and `reseal` (0.19.0).
15
- export const STORE_VERSION = 5;
15
+ // 6: a run record's `source` is `github-actions` or `checkout`, no longer `laptop` (0.32.0).
16
+ export const STORE_VERSION = 6;