@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.
package/README.md CHANGED
@@ -182,20 +182,20 @@ export default Alchemy.Stack(
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. 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
192
- `alchemy-state-store` and pushes the store functions to its production deployment with the Convex
193
- CLI of the app; a later version of this package pushes a newer store when it finds an older one. A
194
- store that is newer than the package fails the run with both versions, so the repositories of a team
195
- upgrade the package together. Each run makes a deploy key of that deployment that can only run the
196
- store's internal functions, and deletes it at the end. Rows are in the tables `resources` and
197
- `outputs` of the component `alchemyState` in the dashboard, under the stack name. The store has no
198
- lock: run one deploy of a stage at a time, such as with a CI concurrency group. The store and its
185
+ Every run needs the team token in `CONVEX_ACCESS_TOKEN`, or the Convex CLI login on a development
186
+ machine. The state and the projects are in the team of that credential. A team access token and an
187
+ OAuth token of a team name their team. The Convex CLI login names no team, so the run uses the team
188
+ of the deployment that the Convex CLI selected: `CONVEX_DEPLOYMENT` in the environment or in
189
+ `.env.local`, which `npx convex dev` writes. A logged-in local deployment gives the team of its
190
+ project, from the folder's `.convex/local/default/config.json`. An anonymous deployment is in no
191
+ team, so the run stops and asks for a deployment of a project. The first run of a team creates the
192
+ project `alchemy-state-store` and pushes the store functions to its production deployment with the
193
+ Convex CLI of the app; a later version of this package pushes a newer store when it finds an older
194
+ one. A store that is newer than the package fails the run with both versions, so the repositories of
195
+ a team upgrade the package together. Each run makes a deploy key of that deployment that can only
196
+ run the store's internal functions, and deletes it at the end. Rows are in the tables `resources`
197
+ and `outputs` of the component `alchemyState` in the dashboard, under the stack name. The store has
198
+ no lock: run one deploy of a stage at a time, such as with a CI concurrency group. The store and its
199
199
  readers (Samebase) are released and upgraded together.
200
200
 
201
201
  Store version 3 supports native subscriptions. A trusted server checks repository access, then calls
@@ -236,8 +236,8 @@ To rotate the key, from a directory that selects the project `alchemy-state-stor
236
236
 
237
237
  Alchemy state holds no time, commit, branch, or run. `Convex.state()` adds them to the stage output:
238
238
  the document that `setOutput` stores is the stack's output plus the key `samebase.run`. On GitHub
239
- Actions the record comes from the run's variables and the event payload; on a laptop from git, which
240
- needs a branch and an `origin` remote. It holds no secret.
239
+ Actions the record comes from the run's variables and the event payload; on a development machine
240
+ from git, which needs a branch and an `origin` remote. It holds no secret.
241
241
 
242
242
  ```json
243
243
  {
@@ -257,13 +257,13 @@ needs a branch and an `origin` remote. It holds no secret.
257
257
  ```
258
258
 
259
259
  `stackFile` is the working directory of the run below the repository root plus `alchemy.run.ts`.
260
- `pullRequest` and `runUrl` are `null` for a push and for a laptop, where `source` is `laptop`. A
261
- value that the stack itself returns under `samebase.run` stays. A checkout that gives no record,
262
- such as a tarball without git or a detached HEAD, writes its outputs without one, and the log says
263
- why. Alchemy writes the output once after a full successful deploy, so a failed deploy leaves the
264
- previous record, and a deploy of selected resources writes none. A reader gets every stage of a
265
- stack, with its resources and output, from the store function `state:readStack({ stack })` in one
266
- call.
260
+ `pullRequest` and `runUrl` are `null` for a push and for a checkout outside GitHub Actions, where
261
+ `source` is `checkout`. A value that the stack itself returns under `samebase.run` stays. A checkout
262
+ that gives no record, such as a tarball without git or a detached HEAD, writes its outputs without
263
+ one, and the log says why. Alchemy writes the output once after a full successful deploy, so a
264
+ failed deploy leaves the previous record, and a deploy of selected resources writes none. A reader
265
+ gets every stage of a stack, with its resources and output, from the store function
266
+ `state:readStack({ stack })` in one call.
267
267
 
268
268
  ## Resources
269
269
 
@@ -304,24 +304,10 @@ call.
304
304
  as the build inputs `["src/**", "public/**", "vite.config.ts"]`. A minted key for a command has
305
305
  every action, because the command can do more than a push.
306
306
 
307
- - `Convex.HubClient`: `{ team, app, redirectUri, deploymentType, clientName, softwareVersion? }`
308
- registers one deployment as a client of the identity hub of the team. The hub is the production
309
- deployment of the project `identity-hub`. The resource finds it by name and runs its internal
310
- functions `identityBroker:renewClient` and `identityBroker:registerClient` with a short-lived key,
311
- so the stack needs no other credential and no hub address. The first client of an `app` creates
312
- the app. Outputs `issuer`, `clientId`, `clientSecret`, `redirectUri`, `deploymentType`, and
313
- `clientName`, which the `env` of the `Convex.Deployment` writes to the deployment.
314
- - Each deploy renews the client on the hub. A preview or development client expires 14 days after
315
- its last deploy or use, and a production client never expires. A client that the hub no longer
316
- has gets a new one in the same run.
317
- - Another `redirectUri` is a new client, and the old one goes.
318
- - A destroy deletes a preview or development client. It does nothing to a production client,
319
- because the production deployment can stay.
320
-
321
307
  - `Convex.SharedHubClient`:
322
308
  `{ app, redirectUri, deploymentType, initialAccessToken?, softwareVersion? }` gets a client of the
323
309
  central identity hub, for an app that deploys in its own GitHub Actions run, on any host, and for
324
- a laptop as a stage of the same stack. `deploymentType` is `production`, `preview`, or
310
+ development as a stage of the same stack. `deploymentType` is `production`, `preview`, or
325
311
  `development`. A production or preview client needs `permissions: id-token: write` in the
326
312
  workflow, and no key and no Samebase account. `app` is at most 64 characters. The origin of an
327
313
  https `redirectUri` must serve `/samebase-verification.json` with the numeric GitHub id of the
@@ -333,9 +319,9 @@ call.
333
319
  repository id, which the state keeps. A renewal keeps both. They are empty for a preview, for a
334
320
  development client, and for the off values.
335
321
  - A development client needs `initialAccessToken`, and only a development client takes it. The
336
- client asks the hub with this token in place of the GitHub OIDC token, so it works on a laptop.
337
- With an empty token, the client gets the off values, and the log says "deploy to main once for
338
- Google sign-in on this laptop". See "The development stage" below.
322
+ client asks the hub with this token in place of the GitHub OIDC token, so it works in
323
+ development. With an empty token, the client gets the off values, and the log says "deploy to
324
+ main once for Google sign-in in development". See "The development stage" below.
339
325
  - Each deploy reads the saved client on the hub with its own token. A client that is gone gets a
340
326
  new one, and a client on another `redirectUri` or of another `deploymentType` too.
341
327
  - A new client logs the link to the terms of the shared sign-in service. A refusal logs its
@@ -344,7 +330,7 @@ call.
344
330
  - No failure stops a deploy or a destroy. A failed renewal keeps the saved values. Without saved
345
331
  values, `status` is `off`, and `issuer`, `clientId`, and `clientSecret` are the `no-hub` values
346
332
  of a checkout without a hub. A production or preview run without a GitHub OIDC token, such as on
347
- a laptop, does the same, and logs no warning.
333
+ a development machine, does the same, and logs no warning.
348
334
  - `required: true` makes the run fail unless the hub confirms the client in this run: a refusal, a
349
335
  hub that does not answer a registration or a renewal, or a suspended client fails it. Set it
350
336
  where sign-in is the product, so a deploy never ships guest sign-in, or a client that the hub
@@ -357,7 +343,7 @@ call.
357
343
  - `Convex.SharedHubClient.read(id, { stage })` gives the attributes of the client `id` in another
358
344
  stage of the same stack, from the state store of the stack. When that stage has no row, it gives
359
345
  the off attributes and does not fail. `Convex.SharedHubClient.ref` fails when the row is
360
- missing, and a laptop before the first deploy to main has no `prod` row.
346
+ missing, and a development stage before the first deploy to main has no `prod` row.
361
347
  - A destroy deletes a preview or development client. It does nothing to a production client,
362
348
  because the production deployment can stay.
363
349
  - `HUB_URL` replaces `https://auth.samebase.com`, the hub that the run asks at `/hub-clients`.
@@ -376,29 +362,13 @@ call.
376
362
  - With a `local:` deployment selected in `.env.local`, the Convex CLI login takes the team of the
377
363
  project in `config.json`.
378
364
 
379
- A development deployment of a team app (`Convex.HubClient`) has no stack, so the package has a
380
- command for it. Run it in the directory of the app, before the first push and at each dev start,
381
- with `CONVEX_ACCESS_TOKEN` or the Convex CLI login. It renews the client that `HUB_CLIENT_ID` names,
382
- so the client expires 14 days after the last dev start or use. A deployment without all three
383
- variables, or whose client the hub no longer has, gets a new client, and the command writes
384
- `HUB_ISSUER`, `HUB_CLIENT_ID`, and `HUB_CLIENT_SECRET` to it.
385
-
386
- ```sh
387
- npx alchemy-convex hub-client --team my-team --app scout --callback-path /auth/hub/callback
388
- ```
389
-
390
- For a separate API-connection callback, register another client with
391
- `--callback-path /oauth/hub/callback --env-prefix RESOURCE_HUB`. This writes `RESOURCE_HUB_ISSUER`,
392
- `RESOURCE_HUB_CLIENT_ID`, and `RESOURCE_HUB_CLIENT_SECRET`, preserving the sign-in client's
393
- variables. Each callback remains one exact registered URI.
394
-
395
365
  ### The development stage
396
366
 
397
- A laptop gets its client from a stage `dev-<name>` of the app's stack, run on purpose, not at each
398
- dev start: `npx convex dev` has made and selected the dev deployment and pushed the code, and then
399
- `alchemy deploy --stage dev-<name>` gives that deployment its variables. The stage creates nothing
400
- and pushes nothing. It has three rows on the deployment that `.env.local` selects, taken over by its
401
- Convex name:
367
+ A development checkout gets its client from a stage `dev-<name>` of the app's stack, run on purpose,
368
+ not at each dev start: `npx convex dev` has made and selected the dev deployment and pushed the
369
+ code, and then `alchemy deploy --stage dev-<name>` gives that deployment its variables. The stage
370
+ creates nothing and pushes nothing. It has three rows on the deployment that `.env.local` selects,
371
+ taken over by its Convex name:
402
372
 
403
373
  ```ts
404
374
  // `selected` is the name in CONVEX_DEPLOYMENT of .env.local, such as happy-animal-123, and
@@ -442,8 +412,8 @@ The imports are `alchemy/AdoptPolicy` for `adopt` and `alchemy/Output` for `Outp
442
412
  `/samebase-verification.json`. `adopt` takes over the deployment and the variables that the dev
443
413
  start set before.
444
414
  3. "HubClient" asks the hub for a development client on the deployment's site URL with the token. A
445
- later run renews it. A sign-in renews it too, so a laptop in use never needs the stage again; a
446
- development client expires 14 days after its last run or sign-in.
415
+ later run renews it. A sign-in renews it too, so a development server in use never needs the
416
+ stage again; a development client expires 14 days after its last run or sign-in.
447
417
  4. "Site" writes the three variables. It removes only a name that leaves its own `env`, so
448
418
  `SAMEBASE_REPOSITORY_ID` stays.
449
419
 
@@ -27,10 +27,10 @@ import { hashDirectory } from "alchemy/Command/Memo";
27
27
  import * as Clock from "effect/Clock";
28
28
  import * as ChildProcess from "effect/process/ChildProcess";
29
29
  import * as Stream from "effect/Stream";
30
- import { fileURLToPath } from "node:url";
31
- import * as Scope from "effect/Scope";
32
30
  import { STATE_STORE_VERSION, State, StateStoreError, encodeState, reviveState } from "alchemy/State";
33
31
  import { execFile } from "node:child_process";
32
+ import { fileURLToPath } from "node:url";
33
+ import * as Scope from "effect/Scope";
34
34
  //#region src/Credentials.ts
35
35
  var Credentials = class extends Context.Service()("@samebase/alchemy-convex/Credentials") {};
36
36
  /** Environment variable for the access token, read by {@link fromConfig}. */
@@ -167,13 +167,6 @@ const retryIdempotentWrite = (effect) => effect.pipe(Effect.retry({
167
167
  }));
168
168
  /** Turns a 404 into `undefined` so read and delete stay idempotent. */
169
169
  const absentAsUndefined = (effect) => effect.pipe(Effect.catchIf((error) => error.status === 404, () => Effect.succeed(void 0)));
170
- const TeamRow = Schema.Struct({
171
- id: Schema.Number,
172
- slug: Schema.String
173
- });
174
- const TeamRows = Schema.Array(TeamRow);
175
- /** The first page of GET /teams/{team_id}/projects: every row carries the slug of the team. */
176
- const ProjectSlugRows = Schema.Struct({ items: Schema.Array(Schema.Struct({ teamSlug: Schema.String })) });
177
170
  /** GET /deployments/{name}: the project of the deployment. */
178
171
  const DeploymentProject = Schema.Struct({ projectId: Schema.Number });
179
172
  /** GET /projects/{id}: the team of the project. */
@@ -260,17 +253,14 @@ const makeService = (source) => {
260
253
  const requestVoid = (operation, run) => client.pipe(Effect.flatMap((c) => settleVoid(operation, () => run(c))));
261
254
  const deploymentRequest = (operation, deploymentUrlOrName, deployKey, run) => settle(operation, () => run(createDeploymentClient(deploymentUrlOrName, Redacted.value(deployKey))));
262
255
  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)))));
263
- /** The slug of the team, from the first project of its listing, or undefined for a team without one. Read once. */
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
256
  const teamId = Effect.runSync(Effect.cached(Effect.gen(function* () {
271
257
  const details = yield* tokenDetails;
272
258
  if (details?.type === "teamToken") return details.teamId;
273
- if (details?.type === "projectToken") return yield* projectTokenError(details.projectId);
259
+ if (details?.type === "projectToken") return yield* new ConvexApiError({
260
+ operation: "resolve team",
261
+ status: 403,
262
+ message: `the access token belongs to project ${details.projectId}, and a project token cannot create projects. Use a team access token.`
263
+ });
274
264
  const selected = selectedDeployment();
275
265
  if (selected === void 0) return yield* new ConvexApiError({
276
266
  operation: "resolve team",
@@ -281,45 +271,6 @@ const makeService = (source) => {
281
271
  const project = yield* request("get project", (c) => c.GET("/projects/{project_id}", { params: { path: { project_id: projectId } } }));
282
272
  return Schema.decodeUnknownSync(ProjectTeam)(project).teamId;
283
273
  })));
284
- const resolveTeamId = (team) => Effect.gen(function* () {
285
- if (typeof team === "number") return team;
286
- if (/^\d+$/.test(team)) return Number(team);
287
- const details = yield* tokenDetails;
288
- if (details?.type === "teamToken") {
289
- const slug = yield* teamSlug(details.teamId);
290
- if (slug === void 0) return yield* new ConvexApiError({
291
- operation: "resolve team",
292
- status: 0,
293
- message: `team "${team}" cannot be checked against the access token: team ${details.teamId} has no project yet. Set team to ${details.teamId}.`
294
- });
295
- if (slug !== team) return yield* new ConvexApiError({
296
- operation: "resolve team",
297
- status: 403,
298
- 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}.`
299
- });
300
- return details.teamId;
301
- }
302
- if (details?.type === "projectToken") return yield* projectTokenError(details.projectId);
303
- const resolved = yield* credentials;
304
- const match = (yield* Effect.tryPromise({
305
- try: async () => {
306
- const response = await fetch("https://api.convex.dev/api/dashboard/teams", { headers: { Authorization: `Bearer ${Redacted.value(resolved.accessToken)}` } });
307
- if (!response.ok) throw new Error(`team lookup for "${team}" failed with HTTP ${response.status}`);
308
- return Schema.decodeUnknownSync(TeamRows)(await response.json());
309
- },
310
- catch: (cause) => new ConvexApiError({
311
- operation: "resolve team",
312
- status: 0,
313
- message: cause instanceof Error ? cause.message : String(cause)
314
- })
315
- })).find((row) => row.slug === team);
316
- if (match === void 0) return yield* new ConvexApiError({
317
- operation: "resolve team",
318
- status: 404,
319
- message: `no team with slug "${team}" for this token`
320
- });
321
- return match.id;
322
- });
323
274
  const isCredentialToken = (secret) => credentials.pipe(Effect.map((resolved) => tokenPart(Redacted.value(resolved.accessToken)) === tokenPart(secret)));
324
275
  const isOAuthCredential = credentials.pipe(Effect.map((resolved) => /^(team|project):/.test(Redacted.value(resolved.accessToken))));
325
276
  const withToken = (token) => makeService(Effect.succeed({
@@ -331,7 +282,6 @@ const makeService = (source) => {
331
282
  requestVoid,
332
283
  deploymentRequest,
333
284
  teamId,
334
- resolveTeamId,
335
285
  isCredentialToken,
336
286
  isOAuthCredential,
337
287
  withToken
@@ -1563,7 +1513,7 @@ const fromGit = (where) => Effect.gen(function* () {
1563
1513
  pullRequest: null,
1564
1514
  headCommit: yield* git(cwd, ["rev-parse", "HEAD"]),
1565
1515
  runUrl: null,
1566
- source: "laptop",
1516
+ source: "checkout",
1567
1517
  recordedAt: yield* now
1568
1518
  };
1569
1519
  });
@@ -1598,14 +1548,8 @@ const stateKeyName = (keyId) => `STATE_KEY_${keyId}`;
1598
1548
  //#region src/State.ts
1599
1549
  /** The name of the state project in each team. */
1600
1550
  const STORE_PROJECT_NAME = "alchemy-state-store";
1601
- /**
1602
- * The actions of the key of one run: the internal queries and mutations of
1603
- * the store, nothing else. Measured: `deployment:data:view` and
1604
- * `deployment:data:write` do not run an internal function.
1605
- */
1606
- const RUN_KEY_ACTIONS = ["deployment:functions:runInternalQueries", "deployment:functions:runInternalMutations"];
1607
1551
  /** The actions of the key of one run on the store: its writes are actions that seal. */
1608
- const STORE_KEY_ACTIONS = [...RUN_KEY_ACTIONS, "deployment:functions:runInternalActions"];
1552
+ const STORE_KEY_ACTIONS = [...["deployment:functions:runInternalQueries", "deployment:functions:runInternalMutations"], "deployment:functions:runInternalActions"];
1609
1553
  /** The body of POST /api/function, with HTTP 200 for a function error too. */
1610
1554
  const Reply = Schema.Union([Schema.Struct({
1611
1555
  status: Schema.Literal("success"),
@@ -1735,7 +1679,7 @@ const storeDirectory = () => join(dirname(fileURLToPath(import.meta.url)), "..",
1735
1679
  */
1736
1680
  const pushStore = (options, deployment) => Effect.gen(function* () {
1737
1681
  const cli = yield* installedCli(join(options.store, ".."));
1738
- yield* Effect.logInfo(`Convex state: pushing the store version 5 to ${deployment.name}`);
1682
+ yield* Effect.logInfo(`Convex state: pushing the store version 6 to ${deployment.name}`);
1739
1683
  yield* withPushKey(options.api, deployment.name, PUSH_KEY_ACTIONS, (key) => push(options.spawner, key, {
1740
1684
  deployment: deployment.name,
1741
1685
  url: deployment.deploymentUrl,
@@ -1818,15 +1762,15 @@ const makeConvexState = (options) => Effect.gen(function* () {
1818
1762
  return next.call(path, args);
1819
1763
  })))) };
1820
1764
  let version = yield* storeVersion(functions);
1821
- if (version === void 0 || version < 5) {
1765
+ if (version === void 0 || version < 6) {
1822
1766
  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.`);
1823
1767
  version = yield* storeVersion(functions);
1824
- if (version === void 0 || version < 5) {
1768
+ if (version === void 0 || version < 6) {
1825
1769
  yield* pushStore(options, deployment);
1826
1770
  version = yield* storeVersion(functions);
1827
1771
  }
1828
1772
  }
1829
- if (version !== 5) return yield* failure(`${deployment.name} answers store version ${version ?? "none"}, and this package needs store version 5.`);
1773
+ if (version !== 6) return yield* failure(`${deployment.name} answers store version ${version ?? "none"}, and this package needs store version 6.`);
1830
1774
  yield* ensureSealed(options, deployment, functions);
1831
1775
  const remote = remoteOf(functions, options.run);
1832
1776
  /** The stack's output plus the record, when the run has one and the output has a place for it. */
@@ -1894,166 +1838,6 @@ const state = () => Layer.effect(State, Effect.gen(function* () {
1894
1838
  }).pipe(Effect.provideContext(context), Effect.orDie));
1895
1839
  }));
1896
1840
  //#endregion
1897
- //#region src/HubClient.ts
1898
- /** The name of the project of the hub in each team. */
1899
- const HUB_PROJECT_NAME = "identity-hub";
1900
- const HubClient = Resource("IdentityHub.Client");
1901
- /** The hub of the team could not do the call. The reason is the Convex message: it holds no secret. */
1902
- var HubClientFailed = class extends Schema.TaggedError()("HubClientFailed", {
1903
- team: Schema.Union([Schema.String, Schema.Number]),
1904
- reason: Schema.String
1905
- }) {
1906
- get message() {
1907
- return `Convex.HubClient: the hub of team ${this.team}: ${this.reason}.`;
1908
- }
1909
- };
1910
- /** The reply of `identityBroker:registerClient`. */
1911
- const Registered = Schema.Struct({
1912
- issuer: Schema.NonEmptyString,
1913
- clientId: Schema.NonEmptyString,
1914
- clientSecret: Schema.NonEmptyString
1915
- });
1916
- /** The reply of `identityBroker:renewClient`: false when the hub no longer has the client. */
1917
- const Renewed = Schema.Boolean;
1918
- /** Runs `use` with the function API of the hub of `team`, with a key of this call only. */
1919
- const withHub = (api, team, use) => Effect.gen(function* () {
1920
- const teamId = yield* api.resolveTeamId(team);
1921
- const project = yield* findProjectByName(api, teamId, HUB_PROJECT_NAME);
1922
- if (project === void 0) return yield* new HubClientFailed({
1923
- team,
1924
- reason: `no project ${HUB_PROJECT_NAME}, which holds the hub`
1925
- });
1926
- const deployment = yield* prodDeploymentOf(api, project.id);
1927
- if (deployment === void 0) return yield* new HubClientFailed({
1928
- team,
1929
- reason: `project ${HUB_PROJECT_NAME} has no production deployment`
1930
- });
1931
- return yield* withPushKey(api, deployment.name, RUN_KEY_ACTIONS, (key) => use(makeFunctionApi(deployment.deploymentUrl, key)));
1932
- });
1933
- /** One internal function of the hub: its value, or the Convex message as an error. */
1934
- const runHub = (functions, team, name, args) => functions.call(`identityBroker:${name}`, args).pipe(Effect.mapError((error) => new HubClientFailed({
1935
- team,
1936
- reason: error.message
1937
- })), Effect.flatMap((reply) => reply.status === "success" ? Effect.succeed(reply.value) : Effect.fail(new HubClientFailed({
1938
- team,
1939
- reason: reply.errorMessage.trim()
1940
- }))));
1941
- /**
1942
- * Registers one client, which expires unless it is a production client. An
1943
- * attempt that a lost reply repeats leaves one spare client on the hub, which
1944
- * signs nobody in, and which the hub deletes after 14 days.
1945
- */
1946
- const registerHubClient = (api, props) => withHub(api, props.team, (functions) => runHub(functions, props.team, "registerClient", {
1947
- appId: props.app,
1948
- redirectUri: props.redirectUri,
1949
- deploymentType: props.deploymentType,
1950
- clientName: props.clientName,
1951
- softwareVersion: props.softwareVersion ?? "unknown",
1952
- tokenEndpointAuthMethod: "client_secret_post",
1953
- expires: true
1954
- })).pipe(Effect.flatMap((value) => Schema.decodeUnknownEffect(Registered)(value).pipe(Effect.mapError(() => new HubClientFailed({
1955
- team: props.team,
1956
- reason: "registerClient gave no client"
1957
- })))), Effect.map(({ issuer, clientId, clientSecret }) => ({
1958
- issuer,
1959
- clientId,
1960
- clientSecret: Redacted.make(clientSecret)
1961
- })));
1962
- /**
1963
- * Renews one client: true while the hub has it. A preview or development client
1964
- * then expires 14 days after this call.
1965
- */
1966
- const renewHubClient = (api, team, clientId) => withHub(api, team, (functions) => runHub(functions, team, "renewClient", {
1967
- clientId,
1968
- expires: true
1969
- })).pipe(Effect.flatMap((value) => Schema.decodeUnknownEffect(Renewed)(value).pipe(Effect.mapError(() => new HubClientFailed({
1970
- team,
1971
- reason: "renewClient gave no answer"
1972
- })))));
1973
- /**
1974
- * Renews a client whose values the caller holds: false only when the hub answers that the client is
1975
- * gone. Any other failure, such as a hub or a Convex API that cannot answer, keeps the client and
1976
- * warns, so an outage never stops a deploy or a dev start; the next one renews it.
1977
- */
1978
- const renewOrKeep = (api, team, clientId) => renewHubClient(api, team, clientId).pipe(Effect.catch((error) => Effect.logWarning(`Convex.HubClient: ${clientId} keeps its saved values, because the hub could not renew it: ${error.message}`).pipe(Effect.as(true))));
1979
- const unregister = (api, team, clientId) => withHub(api, team, (functions) => runHub(functions, team, "deleteClient", { clientId }));
1980
- /** True when the client in state serves the redirect URI and deployment type of `props`. */
1981
- const registeredFor = (output, props) => output.redirectUri === props.redirectUri && output.deploymentType === props.deploymentType;
1982
- const HubClientProvider = () => Provider.effect(HubClient, Effect.gen(function* () {
1983
- const api = yield* ManagementApi;
1984
- return {
1985
- diff: ({ news }) => Effect.succeed(isResolved(news) ? { action: "update" } : void 0),
1986
- read: ({ output }) => Effect.succeed(output),
1987
- reconcile: Effect.fn(function* ({ news, output }) {
1988
- const saved = output !== void 0 && registeredFor(output, news) ? output : void 0;
1989
- if (saved !== void 0 && (yield* renewOrKeep(api, news.team, saved.clientId))) return saved;
1990
- const client = yield* registerHubClient(api, news);
1991
- if (output !== void 0 && saved === void 0) yield* unregister(api, news.team, output.clientId).pipe(Effect.catchTag("HubClientFailed", (error) => Effect.logWarning(`Client ${output.clientId} stays on the hub: ${error.message} Delete it with \`npx convex run --prod identityBroker:deleteClient\`.`)));
1992
- return {
1993
- ...client,
1994
- redirectUri: news.redirectUri,
1995
- deploymentType: news.deploymentType,
1996
- clientName: news.clientName
1997
- };
1998
- }),
1999
- delete: ({ olds, output }) => output.deploymentType === "production" ? Effect.void : unregister(api, olds.team, output.clientId).pipe(Effect.asVoid)
2000
- };
2001
- }));
2002
- /**
2003
- * `alchemy-convex hub-client`: a stack deploys production and previews, and this covers the
2004
- * development deployment, which no stack deploys. Run it at each dev start: it renews the client
2005
- * that the three variables name, so the client expires 14 days after the last dev start or use. A
2006
- * deployment without all three variables, or whose client the hub no longer has, such as one with
2007
- * the `no-hub` values, gets a new client. Answers the callback URL of a new client, or undefined
2008
- * for a renewal. The secret reaches the Convex CLI on standard input, never in its arguments.
2009
- */
2010
- const registerDevelopmentClient = (options) => Effect.gen(function* () {
2011
- const { convex } = options;
2012
- const api = yield* ManagementApi;
2013
- const envPrefix = options.envPrefix ?? "HUB";
2014
- const variables = [
2015
- `${envPrefix}_ISSUER`,
2016
- `${envPrefix}_CLIENT_ID`,
2017
- `${envPrefix}_CLIENT_SECRET`
2018
- ];
2019
- const names = convex([
2020
- "env",
2021
- "list",
2022
- "--names-only"
2023
- ]).split("\n");
2024
- if (variables.every((name) => names.includes(name))) {
2025
- const clientId = convex([
2026
- "env",
2027
- "get",
2028
- `${envPrefix}_CLIENT_ID`
2029
- ]);
2030
- if (yield* renewOrKeep(api, options.team, clientId)) return void 0;
2031
- }
2032
- const siteUrl = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.String))(convex([
2033
- "run",
2034
- "--inline-query",
2035
- "process.env.CONVEX_SITE_URL"
2036
- ])).pipe(Effect.mapError(() => new HubClientFailed({
2037
- team: options.team,
2038
- reason: "no CONVEX_SITE_URL to register"
2039
- })));
2040
- const callbackUrl = `${siteUrl.replace(/\/$/, "")}${options.callbackPath}`;
2041
- const client = yield* registerHubClient(api, {
2042
- team: options.team,
2043
- app: options.app,
2044
- redirectUri: callbackUrl,
2045
- deploymentType: "development",
2046
- clientName: "development",
2047
- softwareVersion: new URL(siteUrl).host
2048
- });
2049
- convex([
2050
- "env",
2051
- "set",
2052
- "--force"
2053
- ], `${envPrefix}_ISSUER='${client.issuer}'\n${envPrefix}_CLIENT_ID='${client.clientId}'\n${envPrefix}_CLIENT_SECRET='${Redacted.value(client.clientSecret)}'\n`);
2054
- return callbackUrl;
2055
- });
2056
- //#endregion
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 };
1841
+ export { ManagementApi as A, ConvexCliNotFound as C, parseDeployOutput as D, VariablesOwnedBySomeoneElse as E, CredentialsError as F, DEPLOY_KEY_ENV as I, fromConfig as L, readLocalDeployment as M, ACCESS_TOKEN_ENV as N, push as O, Credentials as P, fromValues as R, ConvexAppNotFound as S, PushTargetMismatch as T, DeploymentIdentityChange as _, runRecord as a, ProductionDeploymentNotFound as b, CreatedProjectNotFound as c, ProjectNotFound as d, ProjectProvider as f, Deployment as g, AmbiguousDeployment as h, RunRecordError as i, ManagementApiLive as j, ConvexApiError as k, Project as l, AbsoluteRootDir as m, state as n, withRunRecord as o, ProjectTeamChange as p, RUN_RECORD_KEY as r, AmbiguousProject as s, STORE_PROJECT_NAME as t, ProjectDeploymentChange as u, DeploymentProvider as v, EnvironmentNeedsDeployKey as w, CodePushFailed as x, DeploymentResource as y };
2058
1842
 
2059
- //# sourceMappingURL=HubClient-X0-FgJ8v.js.map
1843
+ //# sourceMappingURL=State-CuktZaOh.js.map