@samebase/alchemy-convex 0.28.0 → 0.30.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/README.md CHANGED
@@ -44,8 +44,8 @@ export default Alchemy.Stack(
44
44
  const backend =
45
45
  stage === "prod"
46
46
  ? yield* Convex.Deployment("Backend", {
47
- // An existing project. A new one: { team: "my-team", name: "my-app" }.
48
- project: yield* Convex.Project("Project", { team: "my-team", slug: "my-app" }),
47
+ // An existing project of the team of the token. A new one: { name: "my-app" }.
48
+ project: yield* Convex.Project("Project", { slug: "my-app" }),
49
49
  type: "prod",
50
50
  source: "./convex",
51
51
  env: { AUTH_SECRET: Config.Redacted("AUTH_SECRET") },
@@ -81,7 +81,7 @@ relative to it:
81
81
 
82
82
  ```ts
83
83
  Effect.gen(function* () {
84
- const project = yield* Convex.Project("Project", { team: "my-team", slug: "my-app" });
84
+ const project = yield* Convex.Project("Project", { slug: "my-app" });
85
85
  const backend = yield* Convex.Deployment("Backend", {
86
86
  project,
87
87
  type: "prod",
@@ -166,26 +166,29 @@ values explicitly: `Convex.providers(Convex.fromValues({ accessToken, deployKey
166
166
 
167
167
  ## State in Convex
168
168
 
169
- `state: Convex.state({ team })` keeps the Alchemy state of every stack and stage of a Convex team in
170
- one project of that team, `alchemy-state-store`, the same name as the Cloudflare state store of
171
- Alchemy, so a repository holds one secret and a stack can create and destroy its own project.
169
+ `state: Convex.state()` keeps the Alchemy state of every stack and stage of a Convex team in one
170
+ project of that team, `alchemy-state-store`, the same name as the Cloudflare state store of Alchemy,
171
+ so a repository holds one secret and a stack can create and destroy its own project.
172
172
  [docs/design/convex-state.md](docs/design/convex-state.md) records the decisions and the
173
173
  measurements.
174
174
 
175
175
  ```ts
176
176
  export default Alchemy.Stack(
177
177
  process.env["GITHUB_REPOSITORY"] ?? "my-org/my-app", // the stack name: the repository
178
- { providers: Convex.providers(), state: Convex.state({ team: "my-team" }) },
178
+ { providers: Convex.providers(), state: Convex.state() },
179
179
  Effect.gen(function* () {
180
180
  /* ... */
181
181
  }),
182
182
  );
183
183
  ```
184
184
 
185
- Every run needs the team token in `CONVEX_ACCESS_TOKEN`, or the Convex CLI login on a laptop. A team
186
- access token names its team, so `Convex.state()` needs no `team` with one; a `team` slug that is set
187
- must be the slug of that team, checked against its projects, and a token of another team fails the
188
- run. The Convex CLI login needs the slug or the id. The first run of a team creates the project
185
+ Every run needs the team token in `CONVEX_ACCESS_TOKEN`, or the Convex CLI login on a laptop. The
186
+ state and the projects are in the team of that credential. A team access token and an OAuth token of
187
+ a team name their team. The Convex CLI login names no team, so the run uses the team of the
188
+ deployment that the Convex CLI selected: `CONVEX_DEPLOYMENT` in the environment or in `.env.local`,
189
+ which `npx convex dev` writes. A logged-in local deployment gives the team of its project, from the
190
+ folder's `.convex/local/default/config.json`. An anonymous deployment is in no team, so the run
191
+ stops and asks for a deployment of a project. The first run of a team creates the project
189
192
  `alchemy-state-store` and pushes the store functions to its production deployment with the Convex
190
193
  CLI of the app; a later version of this package pushes a newer store when it finds an older one. A
191
194
  store that is newer than the package fails the run with both versions, so the repositories of a team
@@ -264,11 +267,11 @@ call.
264
267
 
265
268
  ## Resources
266
269
 
267
- - `Convex.Project`: `{ team, name, deploymentRegion?, deploymentType? }` creates a project with its
268
- default deployment, or takes over one with that exact name with `--adopt`. A changed `name`
269
- renames the project in place. `{ team, slug }` is an existing project, found by its slug and taken
270
- over with `--adopt`; it never creates or renames a project. Outputs `projectId`, `slug`, `name`,
271
- `teamId`, `prodDeploymentName`, `prodDeploymentUrl`.
270
+ - `Convex.Project`: `{ name, deploymentRegion?, deploymentType? }` creates a project with its
271
+ default deployment in the team of the credential, or takes over one with that exact name with
272
+ `--adopt`. A changed `name` renames the project in place. `{ slug }` is an existing project of
273
+ that team, found by its slug and taken over with `--adopt`; it never creates or renames a project.
274
+ Outputs `projectId`, `slug`, `name`, `teamId`, `prodDeploymentName`, `prodDeploymentUrl`.
272
275
  - `Convex.Deployment`: `{ project, type: "prod" }` or `{ project, type: "dev" | "preview", name }`,
273
276
  each with optional `rootDir`, `source`, and `env`. Outputs `name` (such as `happy-animal-123`),
274
277
  `url`, `siteUrl`, `type`, `projectId`, `reference`, `previewName`, `hash`, and `envNames`.
@@ -342,6 +345,10 @@ call.
342
345
  values, `status` is `off`, and `issuer`, `clientId`, and `clientSecret` are the `no-hub` values
343
346
  of a checkout without a hub. A production or preview run without a GitHub OIDC token, such as on
344
347
  a laptop, does the same, and logs no warning.
348
+ - `required: true` makes the run fail unless the hub confirms the client in this run: a refusal, a
349
+ hub that does not answer a registration or a renewal, or a suspended client fails it. Set it
350
+ where sign-in is the product, so a deploy never ships guest sign-in, or a client that the hub
351
+ stopped, with a green run. A failed run saves nothing, and the next run asks the hub again.
345
352
  - `status` is `suspended` when the hub suspended the client. The state keeps the client and its
346
353
  values, so the client works again when the hub lifts the suspension.
347
354
  - `Convex.SharedHubClient.variables(client)` gives `issuer`, `clientId`, and `clientSecret` for
@@ -355,6 +362,20 @@ call.
355
362
  because the production deployment can stay.
356
363
  - `HUB_URL` replaces `https://auth.samebase.com`, the hub that the run asks at `/hub-clients`.
357
364
 
365
+ - `Convex.LocalDeployment`: `{ rootDir?, env }` writes the `env` of the logged-in local deployment
366
+ of the folder `rootDir` (the working directory without it), which
367
+ `npx convex deployment create <team>:<project>:local --select` makes and `npx convex dev` runs.
368
+ Each folder, such as each git worktree, has its own, with its own data. The resource reads the
369
+ deployment's name, ports, and admin key from `.convex/local/default/config.json`, and writes with
370
+ the admin key. It never creates, pushes, or deletes: run the stack while `convex dev` runs. A name
371
+ that leaves `env` is removed. A destroy changes nothing. Outputs `name`, `url`, `siteUrl`, and
372
+ `envNames`.
373
+ - `Convex.LocalDeployment.of(rootDir?)` gives `name`, `url`, and `siteUrl` when the stack's
374
+ program runs, so a client can take the local `siteUrl` for its callback. It throws when the
375
+ folder has no logged-in local deployment, also for an anonymous one.
376
+ - With a `local:` deployment selected in `.env.local`, the Convex CLI login takes the team of the
377
+ project in `config.json`.
378
+
358
379
  A development deployment of a team app (`Convex.HubClient`) has no stack, so the package has a
359
380
  command for it. Run it in the directory of the app, before the first push and at each dev start,
360
381
  with `CONVEX_ACCESS_TOKEN` or the Convex CLI login. It renews the client that `HUB_CLIENT_ID` names,
@@ -461,8 +482,8 @@ repository `owner/name`. A stack without the stage of the pull request has no ca
461
482
 
462
483
  - `Convex.Project` and `Convex.Deployment` have the removal policy `retain`. `alchemy destroy`
463
484
  forgets them and Convex keeps them. Add `RemovalPolicy.destroy()` to delete with the resource.
464
- - A project is never replaced. A change of `team`, `slug`, `deploymentType`, or `deploymentRegion`
465
- stops the deploy with a typed error that names the fix.
485
+ - A project is never replaced. A change of `slug`, `deploymentType`, or `deploymentRegion`, or a
486
+ credential of another team, stops the deploy with a typed error that names the fix.
466
487
  - A deployment keeps its `project`, `type`, and `name`; a change stops the deploy with
467
488
  `DeploymentIdentityChange`. A production deployment is never deleted, also not with
468
489
  `RemovalPolicy.destroy()`, and also not a dev deployment that became one.
@@ -494,8 +515,6 @@ repository `owner/name`. A stack without the stage of the pull request has no ca
494
515
  deployment must answer there.
495
516
  - A run that stops between a deployment create and the state write leaves a deployment that state
496
517
  does not know. The next run stops with `OwnedBySomeoneElse`; run it with `--adopt`.
497
- - Team slugs for `{ team, name }` resolve through an unofficial dashboard endpoint. Pass the numeric
498
- team id to avoid it. `{ team, slug }` uses the official endpoint.
499
518
  - Not covered: deployment regions and classes, custom domains, log streams, teams and members,
500
519
  components, snapshots.
501
520
 
@@ -512,11 +531,11 @@ pnpm run test:live # real API calls, see below
512
531
 
513
532
  Unit tests run against recorded Management API payloads in `test/fixtures/management/` and a fake
514
533
  Convex CLI. Live tests run only with `ALCHEMY_CONVEX_LIVE=1`, which `pnpm run test:live` sets. They
515
- need a Convex login or `CONVEX_ACCESS_TOKEN` that can create projects in `ALCHEMY_CONVEX_LIVE_TEAM`.
516
- Each test creates a project whose name starts with `ALCHEMY_CONVEX_LIVE_PREFIX` (default
517
- `tmp-alchemy-convex-`), deletes it at the end, also after a failure, and refuses to delete a
518
- project, or a deployment of a project, without that prefix. A file argument runs one live file only,
519
- for example `pnpm run test:live test/live/plane.live.test.ts`.
534
+ need a team access token of `ALCHEMY_CONVEX_LIVE_TEAM` in `CONVEX_ACCESS_TOKEN`: the projects are in
535
+ the team of the token. Each test creates a project whose name starts with
536
+ `ALCHEMY_CONVEX_LIVE_PREFIX` (default `tmp-alchemy-convex-`), deletes it at the end, also after a
537
+ failure, and refuses to delete a project, or a deployment of a project, without that prefix. A file
538
+ argument runs one live file only, for example `pnpm run test:live test/live/plane.live.test.ts`.
520
539
 
521
540
  Releases: change `version` in `package.json` in a pull request. After the merge,
522
541
  `.github/workflows/release.yml` publishes that version from `main` with npm trusted publishing.
@@ -18,10 +18,11 @@ import { diffBindings, isResolved } from "alchemy/Diff";
18
18
  import * as Provider from "alchemy/Provider";
19
19
  import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
20
20
  import { AlchemyContext } from "alchemy/AlchemyContext";
21
+ import { readFileSync } from "node:fs";
22
+ import { parseEnv, promisify, stripVTControlCharacters } from "node:util";
21
23
  import { createDeploymentClient, createManagementClient } from "@convex-dev/platform";
22
24
  import * as Schedule from "effect/Schedule";
23
25
  import { createHash } from "node:crypto";
24
- import { promisify, stripVTControlCharacters } from "node:util";
25
26
  import { hashDirectory } from "alchemy/Command/Memo";
26
27
  import * as Clock from "effect/Clock";
27
28
  import * as ChildProcess from "effect/process/ChildProcess";
@@ -173,6 +174,73 @@ const TeamRow = Schema.Struct({
173
174
  const TeamRows = Schema.Array(TeamRow);
174
175
  /** The first page of GET /teams/{team_id}/projects: every row carries the slug of the team. */
175
176
  const ProjectSlugRows = Schema.Struct({ items: Schema.Array(Schema.Struct({ teamSlug: Schema.String })) });
177
+ /** GET /deployments/{name}: the project of the deployment. */
178
+ const DeploymentProject = Schema.Struct({ projectId: Schema.Number });
179
+ /** GET /projects/{id}: the team of the project. */
180
+ const ProjectTeam = Schema.Struct({ teamId: Schema.Number });
181
+ /** A folder's `.convex/local/default/config.json`, as the Convex CLI writes it. */
182
+ const LocalConfig = Schema.Struct({
183
+ deploymentName: Schema.String,
184
+ ports: Schema.Struct({
185
+ cloud: Schema.Number,
186
+ site: Schema.Number
187
+ }),
188
+ adminKey: Schema.String,
189
+ /** The project of a logged-in local deployment. An anonymous one has none. */
190
+ cloudProjectId: Schema.Number
191
+ });
192
+ /**
193
+ * The logged-in local deployment of `rootDir`, which `npx convex deployment create
194
+ * <team>:<project>:local` makes: undefined when the folder has none, or only an anonymous one, which
195
+ * belongs to no project.
196
+ */
197
+ const readLocalDeployment = (rootDir = ".") => {
198
+ let raw;
199
+ try {
200
+ raw = JSON.parse(readFileSync(join(rootDir, ".convex", "local", "default", "config.json"), "utf8"));
201
+ } catch {
202
+ return;
203
+ }
204
+ const config = Option.getOrUndefined(Schema.decodeUnknownOption(LocalConfig)(raw));
205
+ if (config === void 0 || !config.deploymentName.startsWith("local-")) return void 0;
206
+ return {
207
+ name: config.deploymentName,
208
+ url: `http://127.0.0.1:${config.ports.cloud}`,
209
+ siteUrl: `http://127.0.0.1:${config.ports.site}`,
210
+ projectId: config.cloudProjectId,
211
+ adminKey: Redacted.make(config.adminKey)
212
+ };
213
+ };
214
+ /**
215
+ * The deployment that the Convex CLI selected: CONVEX_DEPLOYMENT in the environment or in
216
+ * `.env.local` of the working directory, as `npx convex dev` writes it. A cloud deployment
217
+ * (`dev:happy-animal-123`) by its name; a logged-in local deployment (`local:local-team-app`) by the
218
+ * project in the working directory's `.convex/local/default`, when that is the selected one.
219
+ * Undefined when neither has it, and for an anonymous deployment, which is in no project.
220
+ */
221
+ const selectedDeployment = () => {
222
+ const fromEnv = process.env["CONVEX_DEPLOYMENT"];
223
+ const value = fromEnv !== void 0 && fromEnv !== "" ? fromEnv : (() => {
224
+ try {
225
+ return parseEnv(readFileSync(".env.local", "utf8"))["CONVEX_DEPLOYMENT"];
226
+ } catch {
227
+ return;
228
+ }
229
+ })();
230
+ const localName = /^local:(local-[^:]+)$/.exec(value ?? "")?.[1];
231
+ if (localName !== void 0) {
232
+ const local = readLocalDeployment();
233
+ return local?.name === localName ? {
234
+ kind: "local",
235
+ projectId: local.projectId
236
+ } : void 0;
237
+ }
238
+ const name = /^(?:(?:dev|prod|preview):)?([^:]+)$/.exec(value ?? "")?.[1];
239
+ return name === void 0 || name.startsWith("anonymous-") ? void 0 : {
240
+ kind: "cloud",
241
+ name
242
+ };
243
+ };
176
244
  /** GET /token_details: the team of a team token, or the project of a project token. */
177
245
  const TokenDetails = Schema.Union([Schema.Struct({
178
246
  type: Schema.Literal("teamToken"),
@@ -194,17 +262,35 @@ const makeService = (source) => {
194
262
  const tokenDetails = Effect.runSync(Effect.cached(request("get token details", (c) => c.GET("/token_details")).pipe(Effect.map((body) => Schema.decodeUnknownSync(TokenDetails)(body)), Effect.catchIf((error) => error.status === 403, () => Effect.succeed(void 0)))));
195
263
  /** The slug of the team, from the first project of its listing, or undefined for a team without one. Read once. */
196
264
  const teamSlug = (teamId) => request("list projects", (c) => c.GET("/teams/{team_id}/projects", { params: { path: { team_id: teamId } } })).pipe(Effect.map((body) => Schema.decodeUnknownSync(ProjectSlugRows)(body).items[0]?.teamSlug));
265
+ const projectTokenError = (projectId) => new ConvexApiError({
266
+ operation: "resolve team",
267
+ status: 403,
268
+ message: `the access token belongs to project ${projectId}, and a project token cannot create projects. Use a team access token.`
269
+ });
270
+ const teamId = Effect.runSync(Effect.cached(Effect.gen(function* () {
271
+ const details = yield* tokenDetails;
272
+ if (details?.type === "teamToken") return details.teamId;
273
+ if (details?.type === "projectToken") return yield* projectTokenError(details.projectId);
274
+ const selected = selectedDeployment();
275
+ if (selected === void 0) return yield* new ConvexApiError({
276
+ operation: "resolve team",
277
+ status: 0,
278
+ message: "the Convex CLI login names no team, and no deployment of a project is selected. Run `npx convex dev` once with a cloud deployment, or create a local one with `npx convex deployment create <team>:<project>:local --select`."
279
+ });
280
+ const projectId = selected.kind === "local" ? selected.projectId : Schema.decodeUnknownSync(DeploymentProject)(yield* request("get deployment", (c) => c.GET("/deployments/{deployment_name}", { params: { path: { deployment_name: selected.name } } }))).projectId;
281
+ const project = yield* request("get project", (c) => c.GET("/projects/{project_id}", { params: { path: { project_id: projectId } } }));
282
+ return Schema.decodeUnknownSync(ProjectTeam)(project).teamId;
283
+ })));
197
284
  const resolveTeamId = (team) => Effect.gen(function* () {
198
285
  if (typeof team === "number") return team;
199
- if (team !== void 0 && /^\d+$/.test(team)) return Number(team);
286
+ if (/^\d+$/.test(team)) return Number(team);
200
287
  const details = yield* tokenDetails;
201
288
  if (details?.type === "teamToken") {
202
- if (team === void 0) return details.teamId;
203
289
  const slug = yield* teamSlug(details.teamId);
204
290
  if (slug === void 0) return yield* new ConvexApiError({
205
291
  operation: "resolve team",
206
292
  status: 0,
207
- message: `team "${team}" cannot be checked against the access token: team ${details.teamId} has no project yet. Set team to ${details.teamId}, or leave it out.`
293
+ message: `team "${team}" cannot be checked against the access token: team ${details.teamId} has no project yet. Set team to ${details.teamId}.`
208
294
  });
209
295
  if (slug !== team) return yield* new ConvexApiError({
210
296
  operation: "resolve team",
@@ -213,16 +299,7 @@ const makeService = (source) => {
213
299
  });
214
300
  return details.teamId;
215
301
  }
216
- if (details?.type === "projectToken") return yield* new ConvexApiError({
217
- operation: "resolve team",
218
- status: 403,
219
- message: `the access token belongs to project ${details.projectId}, and a project token cannot create projects. Use a team access token.`
220
- });
221
- if (team === void 0) return yield* new ConvexApiError({
222
- operation: "resolve team",
223
- status: 0,
224
- message: "set team to the slug or the id of the Convex team: this access token does not name a team."
225
- });
302
+ if (details?.type === "projectToken") return yield* projectTokenError(details.projectId);
226
303
  const resolved = yield* credentials;
227
304
  const match = (yield* Effect.tryPromise({
228
305
  try: async () => {
@@ -253,6 +330,7 @@ const makeService = (source) => {
253
330
  request,
254
331
  requestVoid,
255
332
  deploymentRequest,
333
+ teamId,
256
334
  resolveTeamId,
257
335
  isCredentialToken,
258
336
  isOAuthCredential,
@@ -1097,14 +1175,14 @@ const DeploymentProvider = () => Provider.effect(DeploymentResource, Effect.gen(
1097
1175
  //#endregion
1098
1176
  //#region src/Project.ts
1099
1177
  const Project = Resource("Convex.Project", { defaultRemovalPolicy: "retain" });
1100
- /** The props change the team of an existing project. Convex cannot move a project. */
1178
+ /** The credential is of another team than the project. Convex cannot move a project. */
1101
1179
  var ProjectTeamChange = class extends Schema.TaggedError()("ProjectTeamChange", {
1102
1180
  projectId: Schema.Number,
1103
1181
  teamId: Schema.Number,
1104
1182
  requestedTeamId: Schema.Number
1105
1183
  }) {
1106
1184
  get message() {
1107
- return `Convex.Project cannot move project ${this.projectId} from team ${this.teamId} to team ${this.requestedTeamId}. Set team back to ${this.teamId}. To use the other team, create a new resource with a new logical id and move the data yourself.`;
1185
+ return `Convex.Project cannot move project ${this.projectId} from team ${this.teamId} to team ${this.requestedTeamId}, the team of the credential. Use a token of team ${this.teamId}, or with the Convex CLI login, select a deployment of team ${this.teamId}. To use the other team, create a new resource with a new logical id and move the data yourself.`;
1108
1186
  }
1109
1187
  };
1110
1188
  /**
@@ -1140,11 +1218,11 @@ var CreatedProjectNotFound = class extends Schema.TaggedError()("CreatedProjectN
1140
1218
  };
1141
1219
  /** No project in the team has the slug. A `slug` resource never creates one. */
1142
1220
  var ProjectNotFound = class extends Schema.TaggedError()("ProjectNotFound", {
1143
- team: Schema.String,
1221
+ teamId: Schema.Number,
1144
1222
  slug: Schema.String
1145
1223
  }) {
1146
1224
  get message() {
1147
- return `Team ${this.team} has no project with the slug "${this.slug}", and a Convex.Project with a slug never creates one. Check the slug in the project URL of the Convex dashboard, or use name to create a project.`;
1225
+ return `Team ${this.teamId} has no project with the slug "${this.slug}", and a Convex.Project with a slug never creates one. Check the slug in the project URL of the Convex dashboard, or use name to create a project.`;
1148
1226
  }
1149
1227
  };
1150
1228
  /** The props change the slug of a `slug` resource: that is another project. */
@@ -1206,8 +1284,6 @@ const checkCreateTimeProps = (projectId, olds, news) => {
1206
1284
  }));
1207
1285
  return Effect.void;
1208
1286
  };
1209
- /** True when `team`, a slug or a numeric id, names the team of the project. */
1210
- const isTeamOf = (details, team) => typeof team === "number" || /^\d+$/.test(team) ? details.teamId === Number(team) : details.teamSlug === team;
1211
1287
  /** The row of the project's default production deployment, or undefined. */
1212
1288
  const prodDeploymentOf = (api, projectId) => api.request("list deployments", (client) => client.GET("/projects/{project_id}/list_deployments", { params: { path: { project_id: projectId } } })).pipe(Effect.map((rows) => Schema.decodeUnknownSync(DeploymentRows)(rows).find((row) => row.deploymentType === "prod" && row.isDefault)));
1213
1289
  /** GET /projects/{id}, or undefined after a 404. */
@@ -1281,9 +1357,9 @@ const ProjectProvider = () => Provider.effect(Project, Effect.gen(function* () {
1281
1357
  prodDeploymentUrl: prod?.deploymentUrl
1282
1358
  })));
1283
1359
  const getById = (projectId) => getProjectById(api, projectId);
1284
- /** The project with this slug in the team, or undefined. Official endpoint; the team can be a slug. */
1285
- const getBySlug = (team, slug) => absentAsUndefined(api.request("get project by slug", (client) => client.GET("/teams/{team_id_or_slug}/projects/{project_slug}", { params: { path: {
1286
- team_id_or_slug: String(team),
1360
+ /** The project with this slug in the team, or undefined. */
1361
+ const getBySlug = (teamId, slug) => absentAsUndefined(api.request("get project by slug", (client) => client.GET("/teams/{team_id_or_slug}/projects/{project_slug}", { params: { path: {
1362
+ team_id_or_slug: String(teamId),
1287
1363
  project_slug: slug
1288
1364
  } } }))).pipe(Effect.map((body) => body === void 0 ? void 0 : Schema.decodeUnknownSync(ProjectDetails)(body)));
1289
1365
  const findByName = (teamId, name) => findProjectByName(api, teamId, name);
@@ -1313,45 +1389,37 @@ const ProjectProvider = () => Provider.effect(Project, Effect.gen(function* () {
1313
1389
  diff: Effect.fn(function* ({ olds, news, output }) {
1314
1390
  if (!isResolved(news)) return void 0;
1315
1391
  if (output === void 0) return void 0;
1316
- if ("slug" in news) {
1392
+ const teamId = yield* api.teamId;
1393
+ if (teamId !== output.teamId) return yield* new ProjectTeamChange({
1394
+ projectId: output.projectId,
1395
+ teamId: output.teamId,
1396
+ requestedTeamId: teamId
1397
+ });
1398
+ if (news.slug !== void 0) {
1317
1399
  if (news.slug !== output.slug) return yield* new ProjectSlugChange({
1318
1400
  projectId: output.projectId,
1319
1401
  slug: output.slug,
1320
1402
  requestedSlug: news.slug
1321
1403
  });
1322
- if (olds.team !== news.team) {
1323
- const details = yield* getById(output.projectId);
1324
- if (details !== void 0 && !isTeamOf(details, news.team)) return yield* new ProjectTeamChange({
1325
- projectId: output.projectId,
1326
- teamId: output.teamId,
1327
- requestedTeamId: yield* api.resolveTeamId(news.team)
1328
- });
1329
- }
1330
1404
  return { action: "noop" };
1331
1405
  }
1332
- if (olds.team !== news.team) {
1333
- const requestedTeamId = yield* api.resolveTeamId(news.team);
1334
- if (requestedTeamId !== output.teamId) return yield* new ProjectTeamChange({
1335
- projectId: output.projectId,
1336
- teamId: output.teamId,
1337
- requestedTeamId
1338
- });
1339
- }
1340
- return "name" in olds && olds.name === news.name ? void 0 : { action: "update" };
1406
+ return olds.name === news.name ? void 0 : { action: "update" };
1341
1407
  }),
1342
1408
  read: Effect.fn(function* ({ olds, output }) {
1343
1409
  if (output !== void 0) {
1344
1410
  const details = yield* getById(output.projectId);
1345
1411
  return details === void 0 ? void 0 : yield* attributesOf(details);
1346
1412
  }
1347
- const existing = "slug" in olds ? yield* getBySlug(olds.team, olds.slug) : yield* findByName(yield* api.resolveTeamId(olds.team), olds.name);
1413
+ const teamId = yield* api.teamId;
1414
+ const existing = olds.slug !== void 0 ? yield* getBySlug(teamId, olds.slug) : yield* findByName(teamId, olds.name);
1348
1415
  return existing === void 0 ? void 0 : Unowned(yield* attributesOf(existing));
1349
1416
  }),
1350
1417
  reconcile: Effect.fn(function* ({ fqn, olds, news, output }) {
1351
- if ("slug" in news) {
1352
- const details = output === void 0 ? yield* getBySlug(news.team, news.slug) : yield* getById(output.projectId);
1418
+ const teamId = yield* api.teamId;
1419
+ if (news.slug !== void 0) {
1420
+ const details = output === void 0 ? yield* getBySlug(teamId, news.slug) : yield* getById(output.projectId);
1353
1421
  if (details === void 0) return yield* new ProjectNotFound({
1354
- team: String(news.team),
1422
+ teamId,
1355
1423
  slug: news.slug
1356
1424
  });
1357
1425
  if (details.slug !== news.slug) return yield* new ProjectSlugChange({
@@ -1359,10 +1427,10 @@ const ProjectProvider = () => Provider.effect(Project, Effect.gen(function* () {
1359
1427
  slug: details.slug,
1360
1428
  requestedSlug: news.slug
1361
1429
  });
1362
- if (!isTeamOf(details, news.team)) return yield* new ProjectTeamChange({
1430
+ if (details.teamId !== teamId) return yield* new ProjectTeamChange({
1363
1431
  projectId: details.id,
1364
1432
  teamId: details.teamId,
1365
- requestedTeamId: yield* api.resolveTeamId(news.team)
1433
+ requestedTeamId: teamId
1366
1434
  });
1367
1435
  if (output === void 0 && !(yield* shouldAdopt(fqn))) return yield* new OwnedBySomeoneElse({
1368
1436
  message: `Convex project ${details.id} ("${news.slug}") exists and is not in this stack's state. Re-run with --adopt to take it over.`,
@@ -1371,9 +1439,8 @@ const ProjectProvider = () => Provider.effect(Project, Effect.gen(function* () {
1371
1439
  });
1372
1440
  return yield* attributesOf(details);
1373
1441
  }
1374
- const teamId = yield* api.resolveTeamId(news.team);
1375
1442
  if (output !== void 0) {
1376
- if (olds !== void 0 && "name" in olds) yield* checkCreateTimeProps(output.projectId, olds, news);
1443
+ if (olds !== void 0 && olds.name !== void 0) yield* checkCreateTimeProps(output.projectId, olds, news);
1377
1444
  if (output.teamId !== teamId) return yield* new ProjectTeamChange({
1378
1445
  projectId: output.projectId,
1379
1446
  teamId: output.teamId,
@@ -1715,8 +1782,8 @@ const ensureSealed = (options, deployment, functions) => Effect.gen(function* ()
1715
1782
  * the run whose project is not the oldest deletes its own, which holds
1716
1783
  * nothing yet, and uses the oldest, so that every run ends on one store.
1717
1784
  */
1718
- const createStoreProject = (api, teamId, team) => Effect.gen(function* () {
1719
- yield* Effect.logInfo(`Convex state: creating the project ${STORE_PROJECT_NAME} in team ${team}`);
1785
+ const createStoreProject = (api, teamId) => Effect.gen(function* () {
1786
+ yield* Effect.logInfo(`Convex state: creating the project ${STORE_PROJECT_NAME} in team ${teamId}`);
1720
1787
  const created = yield* createProject(api, teamId, {
1721
1788
  name: STORE_PROJECT_NAME,
1722
1789
  deploymentType: "prod",
@@ -1735,9 +1802,8 @@ const createStoreProject = (api, teamId, team) => Effect.gen(function* () {
1735
1802
  */
1736
1803
  const makeConvexState = (options) => Effect.gen(function* () {
1737
1804
  const { api } = options;
1738
- const teamId = yield* api.resolveTeamId(options.team);
1739
- const team = options.team ?? teamId;
1740
- const project = (yield* findProjectByName(api, teamId, "alchemy-state-store")) ?? (yield* createStoreProject(api, teamId, team));
1805
+ const teamId = yield* api.teamId;
1806
+ const project = (yield* findProjectByName(api, teamId, "alchemy-state-store")) ?? (yield* createStoreProject(api, teamId));
1741
1807
  const deployment = yield* prodDeploymentOf(api, project.id);
1742
1808
  if (deployment === void 0) return yield* new ProductionDeploymentNotFound({ projectId: project.id });
1743
1809
  const keys = [];
@@ -1753,7 +1819,7 @@ const makeConvexState = (options) => Effect.gen(function* () {
1753
1819
  })))) };
1754
1820
  let version = yield* storeVersion(functions);
1755
1821
  if (version === void 0 || version < 5) {
1756
- if (version === void 0 && deployment.lastDeployTime) return yield* failure(`project ${STORE_PROJECT_NAME} (${project.id}) of team ${team} has code that is not the state store, and Convex.state does not push over it. Rename that project in the Convex dashboard.`);
1822
+ if (version === void 0 && deployment.lastDeployTime) return yield* failure(`project ${STORE_PROJECT_NAME} (${project.id}) of team ${teamId} has code that is not the state store, and Convex.state does not push over it. Rename that project in the Convex dashboard.`);
1757
1823
  version = yield* storeVersion(functions);
1758
1824
  if (version === void 0 || version < 5) {
1759
1825
  yield* pushStore(options, deployment);
@@ -1802,14 +1868,13 @@ const makeConvexState = (options) => Effect.gen(function* () {
1802
1868
  };
1803
1869
  });
1804
1870
  /**
1805
- * Alchemy state in the `alchemy-state-store` project of `team`, with the team token
1806
- * in CONVEX_ACCESS_TOKEN or the Convex CLI login. A team access token names
1807
- * its team, so `team` is optional with one; the Convex CLI login needs the
1808
- * slug or the id. The first use of the run finds or creates the project and
1809
- * pushes the store when it is missing or older. `alchemy plan` on another
1810
- * stack never touches Convex.
1871
+ * Alchemy state in the `alchemy-state-store` project of the team of the credential: the team token
1872
+ * in CONVEX_ACCESS_TOKEN, which names its team, or the Convex CLI login, with the team of the
1873
+ * deployment that the CLI selected (CONVEX_DEPLOYMENT, see ManagementApi.teamId). The first use of
1874
+ * the run finds or creates the project and pushes the store when it is missing or older.
1875
+ * `alchemy plan` on another stack never touches Convex.
1811
1876
  */
1812
- const state = (options = {}) => Layer.effect(State, Effect.gen(function* () {
1877
+ const state = () => Layer.effect(State, Effect.gen(function* () {
1813
1878
  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1814
1879
  const scope = yield* Scope.Scope;
1815
1880
  const context = yield* Effect.context();
@@ -1820,7 +1885,6 @@ const state = (options = {}) => Layer.effect(State, Effect.gen(function* () {
1820
1885
  env: process.env
1821
1886
  }).pipe(Effect.catch((error) => Effect.logWarning(`Convex state: the stage outputs of this run carry no record. ${error.message}`).pipe(Effect.as(void 0))));
1822
1887
  return yield* makeConvexState({
1823
- team: options.team,
1824
1888
  api,
1825
1889
  spawner,
1826
1890
  scope,
@@ -1990,6 +2054,6 @@ const registerDevelopmentClient = (options) => Effect.gen(function* () {
1990
2054
  return callbackUrl;
1991
2055
  });
1992
2056
  //#endregion
1993
- export { PushTargetMismatch as A, DEPLOY_KEY_ENV as B, DeploymentProvider as C, ConvexAppNotFound as D, CodePushFailed as E, ManagementApi as F, fromValues as H, ManagementApiLive as I, ACCESS_TOKEN_ENV as L, installedCli as M, parseDeployOutput as N, ConvexCliNotFound as O, ConvexApiError as P, Credentials as R, DeploymentIdentityChange as S, ProductionDeploymentNotFound as T, fromConfig as V, ProjectProvider as _, registerDevelopmentClient as a, AmbiguousDeployment as b, RUN_RECORD_KEY as c, withRunRecord as d, AmbiguousProject as f, ProjectNotFound as g, ProjectDeploymentChange as h, HubClientProvider as i, VariablesOwnedBySomeoneElse as j, EnvironmentNeedsDeployKey as k, RunRecordError as l, Project as m, HubClient as n, STORE_PROJECT_NAME as o, CreatedProjectNotFound as p, HubClientFailed as r, state as s, HUB_PROJECT_NAME as t, runRecord as u, ProjectTeamChange as v, DeploymentResource as w, Deployment as x, AbsoluteRootDir as y, CredentialsError as z };
2057
+ export { PushTargetMismatch as A, Credentials as B, DeploymentProvider as C, ConvexAppNotFound as D, CodePushFailed as E, ConvexApiError as F, DEPLOY_KEY_ENV as H, ManagementApi as I, ManagementApiLive as L, installedCli as M, parseDeployOutput as N, ConvexCliNotFound as O, push as P, readLocalDeployment as R, DeploymentIdentityChange as S, ProductionDeploymentNotFound as T, fromConfig as U, CredentialsError as V, fromValues as W, ProjectProvider as _, registerDevelopmentClient as a, AmbiguousDeployment as b, RUN_RECORD_KEY as c, withRunRecord as d, AmbiguousProject as f, ProjectNotFound as g, ProjectDeploymentChange as h, HubClientProvider as i, VariablesOwnedBySomeoneElse as j, EnvironmentNeedsDeployKey as k, RunRecordError as l, Project as m, HubClient as n, STORE_PROJECT_NAME as o, CreatedProjectNotFound as p, HubClientFailed as r, state as s, HUB_PROJECT_NAME as t, runRecord as u, ProjectTeamChange as v, DeploymentResource as w, Deployment as x, AbsoluteRootDir as y, ACCESS_TOKEN_ENV as z };
1994
2058
 
1995
- //# sourceMappingURL=HubClient-BcegkjaP.js.map
2059
+ //# sourceMappingURL=HubClient-X0-FgJ8v.js.map