@samebase/alchemy-convex 0.29.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.
@@ -5,11 +5,13 @@
5
5
  // typed error, resolves credentials lazily, and validates the fields the
6
6
  // provider relies on at runtime.
7
7
  import { readFileSync } from "node:fs";
8
+ import { join } from "node:path";
8
9
  import { parseEnv } from "node:util";
9
10
  import { createDeploymentClient, createManagementClient } from "@convex-dev/platform";
10
11
  import * as Context from "effect/Context";
11
12
  import * as Effect from "effect/Effect";
12
13
  import * as Layer from "effect/Layer";
14
+ import * as Option from "effect/Option";
13
15
  import * as Redacted from "effect/Redacted";
14
16
  import * as Schedule from "effect/Schedule";
15
17
  import * as Schema from "effect/Schema";
@@ -211,13 +213,63 @@ const DeploymentProject = Schema.Struct({ projectId: Schema.Number });
211
213
  /** GET /projects/{id}: the team of the project. */
212
214
  const ProjectTeam = Schema.Struct({ teamId: Schema.Number });
213
215
 
216
+ /** A folder's `.convex/local/default/config.json`, as the Convex CLI writes it. */
217
+ const LocalConfig = Schema.Struct({
218
+ deploymentName: Schema.String,
219
+ ports: Schema.Struct({ cloud: Schema.Number, site: Schema.Number }),
220
+ adminKey: Schema.String,
221
+ /** The project of a logged-in local deployment. An anonymous one has none. */
222
+ cloudProjectId: Schema.Number,
223
+ });
224
+
225
+ export interface LocalDeploymentInfo {
226
+ /** Such as `local-nicu-samebase_com-1`. */
227
+ readonly name: string;
228
+ /** The client URL, `http://127.0.0.1:<cloud port>`. */
229
+ readonly url: string;
230
+ /** The HTTP actions URL, `http://127.0.0.1:<site port>`, the local `CONVEX_SITE_URL`. */
231
+ readonly siteUrl: string;
232
+ /** The Convex project that the deployment belongs to. */
233
+ readonly projectId: number;
234
+ readonly adminKey: Redacted.Redacted<string>;
235
+ }
236
+
214
237
  /**
215
- * The cloud 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 (`dev:happy-animal-123`),
217
- * without the type prefix. Undefined when neither has it, and for a local or anonymous deployment
218
- * (`local:local-team-app`, `anonymous:anonymous-app`), which runs on this machine and is in no team.
238
+ * The logged-in local deployment of `rootDir`, which `npx convex deployment create
239
+ * <team>:<project>:local` makes: undefined when the folder has none, or only an anonymous one, which
240
+ * belongs to no project.
219
241
  */
220
- const selectedDeployment = () => {
242
+ export const readLocalDeployment = (rootDir = "."): LocalDeploymentInfo | undefined => {
243
+ let raw: unknown;
244
+ try {
245
+ raw = JSON.parse(
246
+ readFileSync(join(rootDir, ".convex", "local", "default", "config.json"), "utf8"),
247
+ );
248
+ } catch {
249
+ return undefined;
250
+ }
251
+ const config = Option.getOrUndefined(Schema.decodeUnknownOption(LocalConfig)(raw));
252
+ if (config === undefined || !config.deploymentName.startsWith("local-")) return undefined;
253
+ return {
254
+ name: config.deploymentName,
255
+ url: `http://127.0.0.1:${config.ports.cloud}`,
256
+ siteUrl: `http://127.0.0.1:${config.ports.site}`,
257
+ projectId: config.cloudProjectId,
258
+ adminKey: Redacted.make(config.adminKey),
259
+ };
260
+ };
261
+
262
+ /**
263
+ * The deployment that the Convex CLI selected: CONVEX_DEPLOYMENT in the environment or in
264
+ * `.env.local` of the working directory, as `npx convex dev` writes it. A cloud deployment
265
+ * (`dev:happy-animal-123`) by its name; a logged-in local deployment (`local:local-team-app`) by the
266
+ * project in the working directory's `.convex/local/default`, when that is the selected one.
267
+ * Undefined when neither has it, and for an anonymous deployment, which is in no project.
268
+ */
269
+ const selectedDeployment = ():
270
+ | { readonly kind: "cloud"; readonly name: string }
271
+ | { readonly kind: "local"; readonly projectId: number }
272
+ | undefined => {
221
273
  const fromEnv = process.env["CONVEX_DEPLOYMENT"];
222
274
  const value =
223
275
  fromEnv !== undefined && fromEnv !== ""
@@ -229,8 +281,13 @@ const selectedDeployment = () => {
229
281
  return undefined;
230
282
  }
231
283
  })();
284
+ const localName = /^local:(local-[^:]+)$/.exec(value ?? "")?.[1];
285
+ if (localName !== undefined) {
286
+ const local = readLocalDeployment();
287
+ return local?.name === localName ? { kind: "local", projectId: local.projectId } : undefined;
288
+ }
232
289
  const name = /^(?:(?:dev|prod|preview):)?([^:]+)$/.exec(value ?? "")?.[1];
233
- return name === undefined || name.startsWith("anonymous-") ? undefined : name;
290
+ return name === undefined || name.startsWith("anonymous-") ? undefined : { kind: "cloud", name };
234
291
  };
235
292
 
236
293
  /** GET /token_details: the team of a team token, or the project of a project token. */
@@ -318,15 +375,19 @@ const makeService = (source: Effect.Effect<ResolvedCredentials>): ManagementApiS
318
375
  operation: "resolve team",
319
376
  status: 0,
320
377
  message:
321
- "the Convex CLI login names no team, and no cloud deployment is selected. Run `npx convex dev` once with a cloud deployment.",
378
+ "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`.",
322
379
  });
323
380
  }
324
- const deployment = yield* request("get deployment", (c) =>
325
- c.GET("/deployments/{deployment_name}", {
326
- params: { path: { deployment_name: selected } },
327
- }),
328
- );
329
- const { projectId } = Schema.decodeUnknownSync(DeploymentProject)(deployment);
381
+ const projectId =
382
+ selected.kind === "local"
383
+ ? selected.projectId
384
+ : Schema.decodeUnknownSync(DeploymentProject)(
385
+ yield* request("get deployment", (c) =>
386
+ c.GET("/deployments/{deployment_name}", {
387
+ params: { path: { deployment_name: selected.name } },
388
+ }),
389
+ ),
390
+ ).projectId;
330
391
  const project = yield* request("get project", (c) =>
331
392
  c.GET("/projects/{project_id}", { params: { path: { project_id: projectId } } }),
332
393
  );
package/src/Providers.ts CHANGED
@@ -5,6 +5,7 @@ import * as Layer from "effect/Layer";
5
5
  import { type Credentials, fromConfig } from "./Credentials.ts";
6
6
  import { DeploymentProvider, DeploymentResource } from "./Deployment.ts";
7
7
  import { HubClient, HubClientProvider } from "./HubClient.ts";
8
+ import { LocalDeployment, LocalDeploymentProvider } from "./LocalDeployment.ts";
8
9
  import { ManagementApiLive } from "./ManagementApi.ts";
9
10
  import { Project, ProjectProvider } from "./Project.ts";
10
11
  import { SharedHubClient, SharedHubClientProvider } from "./SharedHubClient.ts";
@@ -19,12 +20,13 @@ export class Providers extends Provider.ProviderCollection<Providers>()("Convex"
19
20
  export const providers = (credentials: Layer.Layer<Credentials> = fromConfig()) =>
20
21
  Layer.effect(
21
22
  Providers,
22
- Provider.collection([Project, DeploymentResource, HubClient, SharedHubClient]),
23
+ Provider.collection([Project, DeploymentResource, LocalDeployment, HubClient, SharedHubClient]),
23
24
  ).pipe(
24
25
  Layer.provide(
25
26
  Layer.mergeAll(
26
27
  ProjectProvider(),
27
28
  DeploymentProvider(),
29
+ LocalDeploymentProvider(),
28
30
  HubClientProvider(),
29
31
  SharedHubClientProvider(),
30
32
  ),
@@ -53,6 +53,13 @@ interface CommonProps {
53
53
  readonly redirectUri: string;
54
54
  /** Recorded on the hub's client, such as the commit. The hub records "unknown" without it. */
55
55
  readonly softwareVersion?: string;
56
+ /**
57
+ * The run fails unless the hub confirms the client in this run: it fails when the hub refuses or
58
+ * does not answer a registration or a renewal, and when it suspended the client. Without it, such
59
+ * a run gives the off values or keeps the saved client, so the app deploys anyway. Set it where
60
+ * sign-in is the product. A failed run saves nothing, so the next run asks the hub again.
61
+ */
62
+ readonly required?: boolean;
56
63
  }
57
64
 
58
65
  /**
@@ -343,8 +350,13 @@ const newClient = (props: SharedHubClientProps) => {
343
350
  return request(readOidcToken(requestUrl, requestToken));
344
351
  };
345
352
 
346
- /** The client after a read on the hub, or undefined when the hub says that the client is gone. */
347
- const renew = (saved: SharedHubClientAttributes) =>
353
+ /**
354
+ * The client after a read on the hub, or undefined when the hub says that the client is gone. A
355
+ * read with no usable answer keeps the saved client, except for a required one: a required client
356
+ * passes a run only when the hub confirms it in that run, so a suspension that an earlier run saw,
357
+ * and did not save because that run failed, cannot pass a run that the hub does not answer.
358
+ */
359
+ const renew = (saved: SharedHubClientAttributes, required: boolean) =>
348
360
  Effect.gen(function* () {
349
361
  const { status } = yield* send(
350
362
  "The identity hub",
@@ -369,9 +381,15 @@ const renew = (saved: SharedHubClientAttributes) =>
369
381
  }
370
382
  }).pipe(
371
383
  Effect.catchTag("SharedHubClientFailed", (error) =>
372
- Effect.logWarning(
373
- `Convex.SharedHubClient: ${saved.redirectUri} keeps the saved client: ${error.reason}.`,
374
- ).pipe(Effect.as(saved)),
384
+ required
385
+ ? Effect.fail(
386
+ new SharedHubClientFailed({
387
+ reason: `${saved.redirectUri} is required, and the hub did not confirm its client: ${error.reason}`,
388
+ }),
389
+ )
390
+ : Effect.logWarning(
391
+ `Convex.SharedHubClient: ${saved.redirectUri} keeps the saved client: ${error.reason}.`,
392
+ ).pipe(Effect.as(saved)),
375
393
  ),
376
394
  );
377
395
 
@@ -479,9 +497,15 @@ export const SharedHubClientProvider = () =>
479
497
  }
480
498
  const renewed =
481
499
  saved?.redirectUri === news.redirectUri && saved.deploymentType === news.deploymentType
482
- ? yield* renew(saved)
500
+ ? yield* renew(saved, news.required === true)
483
501
  : undefined;
484
- return renewed ?? (yield* newClient(news));
502
+ const client = renewed ?? (yield* newClient(news));
503
+ if (news.required === true && client.status !== "on") {
504
+ return yield* new SharedHubClientFailed({
505
+ reason: `${news.app} on ${news.redirectUri} is required and has no working client (${client.status}). The warning above names the reason`,
506
+ });
507
+ }
508
+ return client;
485
509
  }),
486
510
 
487
511
  // A failed delete does not stop a destroy: the removal date of a preview or development client
package/src/index.ts CHANGED
@@ -26,6 +26,12 @@ export {
26
26
  type HubClientProps,
27
27
  type HubDeploymentType,
28
28
  } from "./HubClient.ts";
29
+ export {
30
+ LocalDeployment,
31
+ type LocalDeploymentAttributes,
32
+ LocalDeploymentNotFound,
33
+ type LocalDeploymentProps,
34
+ } from "./LocalDeployment.ts";
29
35
  export { ConvexApiError, ManagementApi } from "./ManagementApi.ts";
30
36
  export {
31
37
  AmbiguousProject,