@samebase/alchemy-convex 0.47.0 → 0.48.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/lib/index.js CHANGED
@@ -1,14 +1,37 @@
1
- import { A as Credentials, C as parseDeployOutput, D as ManagementApiLive, E as ManagementApi, M as DEPLOY_KEY_ENV, N as fromConfig, O as readLocalDeployment, P as fromValues, S as VariablesOwnedBySomeoneElse, T as ConvexApiError, _ as CodePushFailed, a as Project, b as EnvironmentNeedsDeployKey, c as ProjectProvider, d as AmbiguousDeployment, f as Deployment, g as ProductionDeploymentNotFound, h as DeploymentResource, i as CreatedProjectNotFound, j as CredentialsError, k as ACCESS_TOKEN_ENV, l as ProjectTeamChange, m as DeploymentProvider, n as state, o as ProjectDeploymentChange, p as DeploymentIdentityChange, r as AmbiguousProject, s as ProjectNotFound, t as STORE_PROJECT_NAME, u as AbsoluteRootDir, v as ConvexAppNotFound, w as push, x as PushTargetMismatch, y as ConvexCliNotFound } from "./State-Dd88J2_z.js";
1
+ import { newKey, newKeyId } from "./sealedSecret.js";
2
+ import { createRequire } from "node:module";
2
3
  import { toPath } from "alchemy/FQN";
3
4
  import { Stack } from "alchemy/Stack";
4
5
  import * as Effect from "effect/Effect";
5
6
  import * as Schema from "effect/Schema";
7
+ import { access, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
8
+ import { homedir, tmpdir } from "node:os";
9
+ import { dirname, join, posix, relative, resolve, win32 } from "node:path";
10
+ import * as Config from "effect/Config";
11
+ import * as Context from "effect/Context";
6
12
  import * as Layer from "effect/Layer";
13
+ import * as Option from "effect/Option";
14
+ import * as Redacted from "effect/Redacted";
15
+ import * as Result from "effect/Result";
7
16
  import { Resource } from "alchemy";
8
- import { isResolved } from "alchemy/Diff";
17
+ import { AdoptPolicy, OwnedBySomeoneElse, Unowned } from "alchemy/AdoptPolicy";
18
+ import { diffBindings, isResolved } from "alchemy/Diff";
9
19
  import * as Provider from "alchemy/Provider";
10
20
  import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
21
+ import { AlchemyContext } from "alchemy/AlchemyContext";
22
+ import { readFileSync } from "node:fs";
23
+ import { parseEnv, stripVTControlCharacters } from "node:util";
24
+ import { createDeploymentClient, createManagementClient } from "@convex-dev/platform";
25
+ import * as Schedule from "effect/Schedule";
26
+ import { createHash } from "node:crypto";
27
+ import { hashDirectory } from "alchemy/Command/Memo";
28
+ import * as Clock from "effect/Clock";
29
+ import * as ChildProcess from "effect/process/ChildProcess";
30
+ import * as Stream from "effect/Stream";
11
31
  import { RUN_RECORD_KEY, RunRecordError, runRecord, withRunRecord } from "@samebase/alchemy-kit/run-record";
32
+ import { fileURLToPath } from "node:url";
33
+ import * as Scope from "effect/Scope";
34
+ import { STATE_STORE_VERSION, State, StateStoreError, encodeState, reviveState } from "alchemy/State";
12
35
  //#region src/Component.ts
13
36
  /**
14
37
  * Associate a native namespace with an installed component. `component` is the
@@ -34,6 +57,1112 @@ const bindComponent = (options) => Effect.gen(function* () {
34
57
  });
35
58
  });
36
59
  //#endregion
60
+ //#region src/Credentials.ts
61
+ var Credentials = class extends Context.Service()("@samebase/alchemy-convex/Credentials") {};
62
+ /** Environment variable for the access token, read by {@link fromConfig}. */
63
+ const ACCESS_TOKEN_ENV = "CONVEX_ACCESS_TOKEN";
64
+ /** Environment variable for the deploy key, read by {@link fromConfig}. The Convex CLI reads the same name. */
65
+ const DEPLOY_KEY_ENV = "CONVEX_DEPLOY_KEY";
66
+ /** The Convex CLI stores its device login here after `npx convex login`. */
67
+ const convexCliConfigPath = () => join(homedir(), ".convex", "config.json");
68
+ const CliConfig = Schema.Struct({ accessToken: Schema.String });
69
+ var CredentialsError = class extends Schema.TaggedError()("CredentialsError", { reason: Schema.String }) {};
70
+ /**
71
+ * Token the Convex CLI saved on this machine. It works on the Management API
72
+ * for the teams the logged-in user belongs to. Fails when nobody is logged in.
73
+ */
74
+ const readConvexCliLogin = Effect.gen(function* () {
75
+ const path = convexCliConfigPath();
76
+ const text = yield* Effect.tryPromise({
77
+ try: () => readFile(path, "utf8"),
78
+ catch: () => new CredentialsError({ reason: `This step needs the Convex Management API. Set ${ACCESS_TOKEN_ENV} to a team access token, or run \`npx convex login\`. There is no Convex CLI login at ${path}.` })
79
+ });
80
+ const parsed = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(CliConfig))(text).pipe(Effect.mapError(() => new CredentialsError({ reason: `${path} has no accessToken` })));
81
+ return {
82
+ accessToken: Redacted.make(parsed.accessToken),
83
+ source: "convex-cli-login"
84
+ };
85
+ });
86
+ /**
87
+ * Default resolution through the stack ConfigProvider (process env, `.env`,
88
+ * stack secrets): `CONVEX_ACCESS_TOKEN`, then the Convex CLI login on this
89
+ * machine, for the access token; `CONVEX_DEPLOY_KEY` for the deploy key. A
90
+ * developer who ran `npx convex login` needs nothing. CI sets only the
91
+ * deploy key when the stack pushes to deployments that exist, and the access
92
+ * token when the stack also creates projects or deployments.
93
+ */
94
+ const fromConfig = () => Layer.effect(Credentials, Effect.gen(function* () {
95
+ const resolved = yield* Effect.cached(Config.Redacted(ACCESS_TOKEN_ENV).pipe(Effect.map((token) => ({
96
+ accessToken: token,
97
+ source: "env"
98
+ })), Effect.catch(() => readConvexCliLogin), Effect.result));
99
+ const deployKey = yield* Effect.cached(Config.option(Config.Redacted(DEPLOY_KEY_ENV)).pipe(Effect.map(Option.getOrUndefined), Effect.orDie));
100
+ return {
101
+ accessToken: resolved.pipe(Effect.flatMap(Effect.fromResult), Effect.orDie),
102
+ hasAccessToken: resolved.pipe(Effect.map(Result.isSuccess)),
103
+ deployKey
104
+ };
105
+ }));
106
+ /** Explicit values, for tests or callers that already hold them. */
107
+ const fromValues = (values) => Layer.succeed(Credentials, {
108
+ accessToken: values.accessToken === void 0 ? Effect.die(new CredentialsError({ reason: "This step needs the Convex Management API, and fromValues got no accessToken." })) : Effect.succeed({
109
+ accessToken: values.accessToken,
110
+ source: "explicit"
111
+ }),
112
+ hasAccessToken: Effect.succeed(values.accessToken !== void 0),
113
+ deployKey: Effect.succeed(values.deployKey)
114
+ });
115
+ //#endregion
116
+ //#region src/Adoption.ts
117
+ /** True when the resource `fqn` may take over an object that is not in state. */
118
+ const shouldAdopt = (fqn) => Effect.gen(function* () {
119
+ const stack = yield* Effect.serviceOption(Stack);
120
+ const own = Option.isSome(stack) ? stack.value.resources[fqn]?.Adopt : void 0;
121
+ if (own !== void 0) return own;
122
+ const policy = yield* Effect.serviceOption(AdoptPolicy);
123
+ if (Option.isSome(policy)) return policy.value;
124
+ const context = yield* Effect.serviceOption(AlchemyContext);
125
+ return Option.isSome(context) && context.value.adopt;
126
+ });
127
+ //#endregion
128
+ //#region src/ManagementApi.ts
129
+ /**
130
+ * One error for every control-plane and deployment call. Resources branch on
131
+ * `status` (404 means absent for read and delete), so the class is load
132
+ * bearing, not decorative.
133
+ */
134
+ var ConvexApiError = class extends Schema.TaggedError()("ConvexApiError", {
135
+ operation: Schema.String,
136
+ status: Schema.Number,
137
+ code: Schema.optionalKey(Schema.String),
138
+ message: Schema.String
139
+ }) {};
140
+ const ErrorBody = Schema.Struct({
141
+ code: Schema.optionalKey(Schema.String),
142
+ message: Schema.optionalKey(Schema.String)
143
+ });
144
+ const toApiError = (operation, result) => {
145
+ const body = Schema.decodeUnknownSync(Schema.NullishOr(ErrorBody))(result.error ?? null);
146
+ const code = body?.code;
147
+ return new ConvexApiError({
148
+ operation,
149
+ status: result.response.status,
150
+ ...code === void 0 ? {} : { code },
151
+ message: body?.message ?? `${operation} failed with HTTP ${result.response.status}`
152
+ });
153
+ };
154
+ /** The part of a Convex token after the first "|", or the whole value when it has none. */
155
+ const tokenPart = (value) => value.slice(value.indexOf("|") + 1);
156
+ var ManagementApi = class extends Context.Service()("@samebase/alchemy-convex/ManagementApi") {};
157
+ const attempt = (operation, run) => Effect.tryPromise({
158
+ try: run,
159
+ catch: (cause) => new ConvexApiError({
160
+ operation,
161
+ status: 0,
162
+ message: cause instanceof Error ? cause.message : String(cause)
163
+ })
164
+ });
165
+ /** Reads `data` or fails with the HTTP status and the API's own code and message. */
166
+ const settle = (operation, run) => attempt(operation, run).pipe(Effect.flatMap((result) => result.response.ok && result.data !== void 0 ? Effect.succeed(result.data) : Effect.fail(toApiError(operation, result))));
167
+ /** For endpoints that answer with an empty body, such as delete calls. */
168
+ const settleVoid = (operation, run) => attempt(operation, run).pipe(Effect.flatMap((result) => result.response.ok ? Effect.void : Effect.fail(toApiError(operation, result))));
169
+ /**
170
+ * True when an idempotent write can succeed on a new attempt:
171
+ *
172
+ * - A Convex write conflict. Two parallel update_environment_variables calls
173
+ * on one deployment gave HTTP 503 `OptimisticConcurrencyControlFailure`,
174
+ * "Data read or written in this mutation changed while it was being run",
175
+ * in a live run. The platform codes `OCC` and `WriteConflict` and the
176
+ * message "... changed while this mutation was being run ..." mean the same.
177
+ * - Any other 5xx answer. Two parallel delete_preview_deploy_key calls on one
178
+ * project gave HTTP 500 `InternalServerError`, "Your request couldn't be
179
+ * completed. Try again later.", in a live run. The next attempt succeeded.
180
+ */
181
+ const isRetryableWriteError = (error) => error.code === "OptimisticConcurrencyControlFailure" || error.code === "OCC" || error.code === "WriteConflict" || /changed while (it|this mutation) was being run/.test(error.message) || error.status >= 500;
182
+ /**
183
+ * Runs an idempotent write again after a retryable Convex error: at most
184
+ * four more attempts, with exponential backoff from 100 ms and jitter. Other
185
+ * errors fail at once, and so does the last retryable error. Use it only for
186
+ * a write that has the same result when it runs twice, such as setting a
187
+ * value or deleting by id. Never for a create that does not check first.
188
+ */
189
+ const retryIdempotentWrite = (effect) => effect.pipe(Effect.retry({
190
+ while: (error) => error instanceof ConvexApiError && isRetryableWriteError(error),
191
+ times: 4,
192
+ schedule: Schedule.exponential("100 millis").pipe(Schedule.jittered)
193
+ }));
194
+ /** Turns a 404 into `undefined` so read and delete stay idempotent. */
195
+ const absentAsUndefined = (effect) => effect.pipe(Effect.catchIf((error) => error.status === 404, () => Effect.succeed(void 0)));
196
+ /** GET /deployments/{name}: the project of the deployment. */
197
+ const DeploymentProject = Schema.Struct({ projectId: Schema.Number });
198
+ /** GET /projects/{id}: the team of the project. */
199
+ const ProjectTeam = Schema.Struct({ teamId: Schema.Number });
200
+ /** A folder's `.convex/local/default/config.json`, as the Convex CLI writes it. */
201
+ const LocalConfig = Schema.Struct({
202
+ deploymentName: Schema.String,
203
+ ports: Schema.Struct({
204
+ cloud: Schema.Number,
205
+ site: Schema.Number
206
+ }),
207
+ adminKey: Schema.String,
208
+ /** The project of a logged-in local deployment. An anonymous one has none. */
209
+ cloudProjectId: Schema.Number
210
+ });
211
+ /**
212
+ * The logged-in local deployment of `rootDir`, which `npx convex deployment create
213
+ * <team>:<project>:local` makes: undefined when the folder has none, or only an anonymous one, which
214
+ * belongs to no project.
215
+ */
216
+ const readLocalDeployment = (rootDir = ".") => {
217
+ let raw;
218
+ try {
219
+ raw = JSON.parse(readFileSync(join(rootDir, ".convex", "local", "default", "config.json"), "utf8"));
220
+ } catch {
221
+ return;
222
+ }
223
+ const config = Option.getOrUndefined(Schema.decodeUnknownOption(LocalConfig)(raw));
224
+ if (config === void 0 || !config.deploymentName.startsWith("local-")) return void 0;
225
+ return {
226
+ name: config.deploymentName,
227
+ url: `http://127.0.0.1:${config.ports.cloud}`,
228
+ siteUrl: `http://127.0.0.1:${config.ports.site}`,
229
+ projectId: config.cloudProjectId,
230
+ adminKey: Redacted.make(config.adminKey)
231
+ };
232
+ };
233
+ /**
234
+ * The deployment that the Convex CLI selected: CONVEX_DEPLOYMENT in the environment or in
235
+ * `.env.local` of the working directory, as `npx convex dev` writes it. A cloud deployment
236
+ * (`dev:happy-animal-123`) by its name; a logged-in local deployment (`local:local-team-app`) by the
237
+ * project in the working directory's `.convex/local/default`, when that is the selected one.
238
+ * Undefined when neither has it, and for an anonymous deployment, which is in no project.
239
+ */
240
+ const selectedDeployment = () => {
241
+ const fromEnv = process.env["CONVEX_DEPLOYMENT"];
242
+ const value = fromEnv !== void 0 && fromEnv !== "" ? fromEnv : (() => {
243
+ try {
244
+ return parseEnv(readFileSync(".env.local", "utf8"))["CONVEX_DEPLOYMENT"];
245
+ } catch {
246
+ return;
247
+ }
248
+ })();
249
+ const localName = /^local:(local-[^:]+)$/.exec(value ?? "")?.[1];
250
+ if (localName !== void 0) {
251
+ const local = readLocalDeployment();
252
+ return local?.name === localName ? {
253
+ kind: "local",
254
+ projectId: local.projectId
255
+ } : void 0;
256
+ }
257
+ const name = /^(?:(?:dev|prod|preview):)?([^:]+)$/.exec(value ?? "")?.[1];
258
+ return name === void 0 || name.startsWith("anonymous-") ? void 0 : {
259
+ kind: "cloud",
260
+ name
261
+ };
262
+ };
263
+ /** GET /token_details: the team of a team token, or the project of a project token. */
264
+ const TokenDetails = Schema.Union([Schema.Struct({
265
+ type: Schema.Literal("teamToken"),
266
+ teamId: Schema.Number
267
+ }), Schema.Struct({
268
+ type: Schema.Literal("projectToken"),
269
+ projectId: Schema.Number
270
+ })]);
271
+ /** The service for one way to get the bearer token. */
272
+ const makeService = (source) => {
273
+ const credentials = source.pipe(Effect.map((resolved) => ({
274
+ ...resolved,
275
+ accessToken: Redacted.make(Redacted.value(resolved.accessToken).trim())
276
+ })));
277
+ const client = Effect.cached(credentials.pipe(Effect.map((resolved) => createManagementClient(Redacted.value(resolved.accessToken))))).pipe(Effect.flatten);
278
+ const request = (operation, run) => client.pipe(Effect.flatMap((c) => settle(operation, () => run(c))));
279
+ const requestVoid = (operation, run) => client.pipe(Effect.flatMap((c) => settleVoid(operation, () => run(c))));
280
+ const deploymentRequest = (operation, deploymentUrlOrName, deployKey, run) => settle(operation, () => run(createDeploymentClient(deploymentUrlOrName, Redacted.value(deployKey))));
281
+ 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)))));
282
+ const teamId = Effect.runSync(Effect.cached(Effect.gen(function* () {
283
+ const details = yield* tokenDetails;
284
+ if (details?.type === "teamToken") return details.teamId;
285
+ if (details?.type === "projectToken") return yield* new ConvexApiError({
286
+ operation: "resolve team",
287
+ status: 403,
288
+ message: `the access token belongs to project ${details.projectId}, and a project token cannot create projects. Use a team access token.`
289
+ });
290
+ const selected = selectedDeployment();
291
+ if (selected === void 0) return yield* new ConvexApiError({
292
+ operation: "resolve team",
293
+ status: 0,
294
+ 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`."
295
+ });
296
+ 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;
297
+ const project = yield* request("get project", (c) => c.GET("/projects/{project_id}", { params: { path: { project_id: projectId } } }));
298
+ return Schema.decodeUnknownSync(ProjectTeam)(project).teamId;
299
+ })));
300
+ const isCredentialToken = (secret) => credentials.pipe(Effect.map((resolved) => tokenPart(Redacted.value(resolved.accessToken)) === tokenPart(secret)));
301
+ const isOAuthCredential = credentials.pipe(Effect.map((resolved) => /^(team|project):/.test(Redacted.value(resolved.accessToken))));
302
+ const withToken = (token) => makeService(Effect.succeed({
303
+ accessToken: token,
304
+ source: "explicit"
305
+ }));
306
+ return {
307
+ request,
308
+ requestVoid,
309
+ deploymentRequest,
310
+ teamId,
311
+ isCredentialToken,
312
+ isOAuthCredential,
313
+ withToken
314
+ };
315
+ };
316
+ const ManagementApiLive = () => Layer.effect(ManagementApi, Effect.gen(function* () {
317
+ const credentials = yield* Credentials;
318
+ return makeService(credentials.accessToken);
319
+ }));
320
+ //#endregion
321
+ //#region src/Push.ts
322
+ const sourceOf = (source) => typeof source === "string" ? {
323
+ path: source,
324
+ command: void 0,
325
+ include: void 0
326
+ } : {
327
+ path: source.path,
328
+ command: source.command,
329
+ include: source.include
330
+ };
331
+ /** Lifetime of a push key. Long enough for a slow push with index backfills. */
332
+ const PUSH_KEY_LIFETIME_MS = 72e5;
333
+ /** The only actions a key for `convex deploy` gets. */
334
+ const PUSH_KEY_ACTIONS = [
335
+ "deployment:deploy",
336
+ "deployment:env:view",
337
+ "deployment:env:write"
338
+ ];
339
+ /** POST /deployments/{deployment_name}/create_deploy_key */
340
+ const CreatedDeployKey = Schema.Struct({ deployKey: Schema.String });
341
+ /** GET https://<deployment>.convex.cloud/api/v1/list_environment_variables */
342
+ const EnvironmentVariableList = Schema.Struct({ environmentVariables: Schema.Record(Schema.String, Schema.String) });
343
+ /** No `convex` package resolves from the app directory. */
344
+ var ConvexCliNotFound = class extends Schema.TaggedError()("ConvexCliNotFound", { cwd: Schema.String }) {
345
+ get message() {
346
+ return `Convex.Deployment found no installed convex package from ${this.cwd}, and it does not download one. Install convex in the app (npm install convex), or set rootDir to the directory of the app.`;
347
+ }
348
+ };
349
+ /** The app directory (`rootDir`) has no package.json. */
350
+ var ConvexAppNotFound = class extends Schema.TaggedError()("ConvexAppNotFound", {
351
+ /** The app directory, resolved against the working directory of the deploy. */
352
+ rootDir: Schema.String }) {
353
+ get message() {
354
+ return `Convex.Deployment found no package.json in ${this.rootDir}. Set rootDir to the directory of the Convex app, relative to the directory where the deploy runs, such as "apps/web".`;
355
+ }
356
+ };
357
+ /** The Convex CLI failed, or exited 0 without the deployment URL. The output tail never contains the key. */
358
+ var CodePushFailed = class extends Schema.TaggedError()("CodePushFailed", {
359
+ /** Exit code of the CLI. Undefined when it did not start or a signal stopped it. */
360
+ exitCode: Schema.UndefinedOr(Schema.Number),
361
+ /** The last lines of the CLI output, with the deploy key and the `Redacted` values of `env` removed. */
362
+ outputTail: Schema.String
363
+ }) {
364
+ get message() {
365
+ return this.exitCode === 0 ? `convex deploy exited 0 but printed no "Deployed Convex functions to <url>" line. Last output, with the deploy key removed:\n${this.outputTail}` : `convex deploy failed${this.exitCode === void 0 ? "" : ` with exit code ${this.exitCode}`}. Last output, with the deploy key removed:\n${this.outputTail}`;
366
+ }
367
+ };
368
+ /** The CLI pushed to another deployment than the one of the resource. Checked after the push. */
369
+ var PushTargetMismatch = class extends Schema.TaggedError()("PushTargetMismatch", {
370
+ expected: Schema.String,
371
+ actual: Schema.String
372
+ }) {
373
+ get message() {
374
+ return `The Convex CLI pushed the functions to deployment ${this.actual}, but Convex.Deployment expected ${this.expected}. Check that convex.json does not select another deployment.`;
375
+ }
376
+ };
377
+ /** Variables in `env` exist on the deployment with other values, and adoption is off. */
378
+ var VariablesOwnedBySomeoneElse = class extends Schema.TaggedError()("VariablesOwnedBySomeoneElse", {
379
+ deployment: Schema.String,
380
+ names: Schema.Array(Schema.String)
381
+ }) {
382
+ get message() {
383
+ return `Environment variables ${this.names.join(", ")} already exist on deployment ${this.deployment} with other values. Re-run with --adopt to take them over and overwrite them, or remove them from env.`;
384
+ }
385
+ };
386
+ /** A preview deploy key cannot set variables: the deployment API takes only a deploy key of the deployment. */
387
+ var EnvironmentNeedsDeployKey = class extends Schema.TaggedError()("EnvironmentNeedsDeployKey", { deployment: Schema.String }) {
388
+ get message() {
389
+ return `Convex.Deployment cannot set or remove env variables on preview deployment ${this.deployment} with a preview deploy key: Convex lets that key create, push to, and delete preview deployments, but not change their variables. Set CONVEX_ACCESS_TOKEN for this stage, or set the values as project default environment variables for preview deployments in the Convex dashboard.`;
390
+ }
391
+ };
392
+ /**
393
+ * What a deploy key targets, from its prefix: `<type>:<deployment>|<secret>`
394
+ * (or `<deployment>|<secret>` in old keys) for one deployment, and
395
+ * `preview:<team>:<project>|<secret>` for the preview deployments of a
396
+ * project. Same rules as convex 1.46 `cli/lib/deployment.js`.
397
+ */
398
+ const keyTargetOf = (key) => {
399
+ const bar = key.indexOf("|");
400
+ if (bar <= 0 || /[\s#'"`]/.test(key)) return { kind: "other" };
401
+ const [first, second, third, ...rest] = key.slice(0, bar).split(":");
402
+ if (rest.length > 0) return { kind: "other" };
403
+ if (first === "preview" && second && third) return {
404
+ kind: "preview",
405
+ team: second,
406
+ project: third
407
+ };
408
+ if (third !== void 0) return { kind: "other" };
409
+ if (second) return {
410
+ kind: "deployment",
411
+ deployment: second
412
+ };
413
+ if (first && second === void 0) return {
414
+ kind: "deployment",
415
+ deployment: first
416
+ };
417
+ return { kind: "other" };
418
+ };
419
+ /**
420
+ * The CLI prints this line with `logFinishedStep` after the push succeeds, to
421
+ * stderr (convex 1.46 `cli/lib/deploy2.js`). The host is
422
+ * `<deployment>.convex.cloud` or `<deployment>.<region>.convex.cloud`.
423
+ */
424
+ const DEPLOYED_LINE = /Deployed Convex functions to (https:\/\/([a-z0-9]+(?:-[a-z0-9]+)*)(?:\.[a-z0-9]+(?:-[a-z0-9]+)*)?\.convex\.cloud)\/?(?=\s|$)/m;
425
+ /** Reads the deployment URL from `convex deploy` output. ANSI escape codes are removed first. */
426
+ const parseDeployOutput = (text) => {
427
+ const match = DEPLOYED_LINE.exec(stripVTControlCharacters(text));
428
+ const url = match?.[1];
429
+ const deploymentName = match?.[2];
430
+ return url === void 0 || deploymentName === void 0 ? void 0 : {
431
+ url,
432
+ deploymentName
433
+ };
434
+ };
435
+ /** The last non-empty lines of `text`, without escape codes and with every secret replaced. */
436
+ const outputTail = (text, secrets) => secrets.reduce((redacted, secret) => redacted.split(secret).join("[REDACTED]"), stripVTControlCharacters(text)).split(/\r?\n|\r/).filter((line) => line.trim() !== "").slice(-20).join("\n");
437
+ const valueOf$1 = (value) => Redacted.isRedacted(value) ? Redacted.value(value) : value;
438
+ /**
439
+ * The app directory: `rootDir` resolved against the working directory of the
440
+ * deploy. It must have a package.json. There is no search above it.
441
+ */
442
+ const appDirectoryOf = (rootDir) => {
443
+ const directory = resolve(rootDir);
444
+ return Effect.tryPromise({
445
+ try: () => access(join(directory, "package.json")).then(() => directory),
446
+ catch: () => new ConvexAppNotFound({ rootDir: directory })
447
+ });
448
+ };
449
+ /** `source` is not the functions directory that the Convex CLI pushes from the app directory. */
450
+ var SourceMismatch = class extends Schema.TaggedError()("SourceMismatch", {
451
+ /** The app directory, resolved. */
452
+ rootDir: Schema.String,
453
+ source: Schema.String,
454
+ functions: Schema.String
455
+ }) {
456
+ get message() {
457
+ return `Convex.Deployment source is ${this.source}, but the Convex CLI pushes ${this.functions} from the app directory ${this.rootDir} (the "functions" field of convex.json, or convex/ by default). Set rootDir to the directory of the Convex app, and source to its functions directory relative to rootDir, such as "./convex".`;
458
+ }
459
+ };
460
+ const ConvexJson = Schema.Struct({ functions: Schema.optionalKey(Schema.String) });
461
+ /** Fails with {@link SourceMismatch} when `path` is not the functions directory of the app in `cwd`. */
462
+ const checkFunctionsDirectory = (cwd, path) => Effect.gen(function* () {
463
+ const text = yield* Effect.promise(() => readFile(join(cwd, "convex.json"), "utf8").catch(() => void 0));
464
+ const configured = text === void 0 ? void 0 : Schema.decodeUnknownSync(Schema.fromJsonString(ConvexJson))(text).functions;
465
+ const functions = resolve(cwd, configured ?? "convex");
466
+ if (functions !== path) return yield* new SourceMismatch({
467
+ rootDir: cwd,
468
+ source: path,
469
+ functions
470
+ });
471
+ });
472
+ const CliManifest = Schema.Struct({ bin: Schema.Union([Schema.String, Schema.Record(Schema.String, Schema.String)]) });
473
+ /** `[node, <convex bin>]` for the `convex` package that `cwd` resolves. Never downloads. */
474
+ const installedCli = (cwd) => Effect.tryPromise({
475
+ try: async () => {
476
+ const manifestPath = createRequire(join(cwd, "package.json")).resolve("convex/package.json");
477
+ const { bin } = Schema.decodeUnknownSync(Schema.fromJsonString(CliManifest))(await readFile(manifestPath, "utf8"));
478
+ const entry = typeof bin === "string" ? bin : bin["convex"];
479
+ if (entry === void 0) throw new Error("the convex package has no convex bin");
480
+ return [process.execPath, resolve(dirname(manifestPath), entry)];
481
+ },
482
+ catch: () => new ConvexCliNotFound({ cwd })
483
+ });
484
+ /**
485
+ * The content identity of a push: the files of the app directory that git
486
+ * does not ignore (or `path`, the manifests, and the `include` globs), the
487
+ * nearest lockfile, the target deployment, and the `env` names and values.
488
+ * A change in a workspace package outside the app directory is not seen.
489
+ */
490
+ const pushHash = (options) => Effect.gen(function* () {
491
+ const source = options.source === void 0 ? void 0 : sourceOf(options.source);
492
+ const files = source === void 0 ? void 0 : yield* appDirectoryOf(options.rootDir).pipe(Effect.flatMap((cwd) => {
493
+ const functions = relative(cwd, resolve(cwd, source.path)).split("\\").join("/");
494
+ return hashDirectory({
495
+ cwd,
496
+ memo: source.include !== void 0 ? {
497
+ include: [
498
+ `${functions}/**`,
499
+ "package.json",
500
+ "convex.json",
501
+ ...source.include
502
+ ],
503
+ lockfile: true
504
+ } : functions === ".." || functions.startsWith("../") ? {
505
+ include: ["**/*", `${functions}/**`],
506
+ lockfile: true
507
+ } : {}
508
+ });
509
+ }));
510
+ const env = Object.entries(options.env).map(([name, value]) => [name, valueOf$1(value)]).sort(([a], [b]) => a < b ? -1 : 1);
511
+ return createHash("sha256").update(JSON.stringify({
512
+ files,
513
+ deployment: options.deployment,
514
+ env
515
+ })).digest("hex");
516
+ });
517
+ /**
518
+ * Runs `use` with an env file that holds the key, in a new temporary
519
+ * directory, and removes the directory afterwards: on success, on failure,
520
+ * and on interruption.
521
+ */
522
+ const withKeyFile = (key, use) => Effect.acquireUseRelease(Effect.promise(() => mkdtemp(join(tmpdir(), "alchemy-convex-"))), (home) => Effect.promise(() => writeFile(join(home, "deploy.env"), `CONVEX_DEPLOY_KEY=${key}\n`, { mode: 384 })).pipe(Effect.andThen(use({
523
+ envFile: join(home, "deploy.env"),
524
+ home
525
+ }))), (home) => Effect.promise(() => rm(home, {
526
+ recursive: true,
527
+ force: true
528
+ })));
529
+ /** This process's variables without `CONVEX_*`, with `home` as the home directory. */
530
+ const cliEnvironment = (home) => ({
531
+ ...Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.toUpperCase().startsWith("CONVEX_"))),
532
+ HOME: home,
533
+ USERPROFILE: home,
534
+ XDG_CONFIG_HOME: home
535
+ });
536
+ /**
537
+ * A deploy key of `deployment` that expires after PUSH_KEY_LIFETIME_MS, with
538
+ * only `allowedActions`, or every action when that is undefined. Delete it
539
+ * with {@link deleteDeployKey} when the work is done. An OAuth credential sends
540
+ * only the name: Convex refuses both limits and returns the OAuth token.
541
+ */
542
+ const createDeployKey = (api, deployment, name, allowedActions) => Effect.gen(function* () {
543
+ const now = yield* Clock.currentTimeMillis;
544
+ const oauth = yield* api.isOAuthCredential;
545
+ const created = yield* api.request("create deploy key", (client) => client.POST("/deployments/{deployment_name}/create_deploy_key", {
546
+ params: { path: { deployment_name: deployment } },
547
+ body: oauth ? { name } : {
548
+ name,
549
+ ...allowedActions === void 0 ? {} : { allowedActions: [...allowedActions] },
550
+ expiresAt: now + PUSH_KEY_LIFETIME_MS
551
+ }
552
+ }));
553
+ return Redacted.make(Schema.decodeUnknownSync(CreatedDeployKey)(created).deployKey);
554
+ });
555
+ /**
556
+ * Deletes a key that {@link createDeployKey} made. The delete is skipped for
557
+ * a key that is the OAuth credential. A failed delete is logged: the key
558
+ * expires anyway.
559
+ */
560
+ const deleteDeployKey = (api, deployment, key) => Effect.gen(function* () {
561
+ if (yield* api.isCredentialToken(Redacted.value(key))) return;
562
+ yield* absentAsUndefined(retryIdempotentWrite(api.requestVoid("delete deploy key", (client) => client.POST("/deployments/{deployment_name}/delete_deploy_key", {
563
+ params: { path: { deployment_name: deployment } },
564
+ body: { id: Redacted.value(key) }
565
+ }))));
566
+ }).pipe(Effect.catch((error) => Effect.logWarning(`Convex.Deployment could not delete its key on ${deployment} (${error.message}). The key expires on its own within ${PUSH_KEY_LIFETIME_MS / 6e4} minutes.`)));
567
+ /**
568
+ * Creates a deploy key for one push, runs `use` with it, and deletes it
569
+ * afterwards, also after a failure. `allowedActions` is PUSH_KEY_ACTIONS for
570
+ * `convex deploy`, or undefined for a push command, which can do more than a
571
+ * push, such as the uploads of convex-hosting through `convex run`.
572
+ */
573
+ const withPushKey = (api, deployment, allowedActions, use) => Effect.acquireUseRelease(createDeployKey(api, deployment, "alchemy-push", allowedActions), use, (key) => deleteDeployKey(api, deployment, key));
574
+ /** Every variable of the deployment with its value. */
575
+ const listVariables = (url, key) => settle("list environment variables", () => createDeploymentClient(url, Redacted.value(key)).GET("/list_environment_variables")).pipe(Effect.map((body) => Schema.decodeUnknownSync(EnvironmentVariableList)(body).environmentVariables));
576
+ /** One call that sets variables, or removes those whose value is null. */
577
+ const writeVariables = (url, key, changes) => settleVoid("update environment variables", () => createDeploymentClient(url, Redacted.value(key)).POST("/update_environment_variables", { body: { changes: changes.map(({ name, value }) => ({
578
+ name,
579
+ value
580
+ })) } }));
581
+ /**
582
+ * The app directory and the program of a push. Fails before any change when
583
+ * `rootDir` has no package.json, when `source` is not the functions directory
584
+ * of the app, or when the app has no installed Convex CLI and no push command.
585
+ */
586
+ const checkSource = (rootDir, input) => Effect.gen(function* () {
587
+ const source = sourceOf(input);
588
+ const cwd = yield* appDirectoryOf(rootDir);
589
+ yield* checkFunctionsDirectory(cwd, resolve(cwd, source.path));
590
+ return {
591
+ cwd,
592
+ program: source.command ?? (yield* installedCli(cwd))
593
+ };
594
+ });
595
+ /**
596
+ * Sets the `env` variables and pushes the functions of `source` to one
597
+ * deployment with `key`: a deploy key of the deployment, or a preview deploy
598
+ * key of its project with `previewName`. A name of `previousEnvNames` that
599
+ * left `env` is removed after a successful push, or, without `source`, in the
600
+ * same write as the new values. Returns the URL that the CLI printed, or
601
+ * undefined without `source`.
602
+ */
603
+ const push = (spawner, key, options) => Effect.gen(function* () {
604
+ const source = options.source === void 0 ? void 0 : sourceOf(options.source);
605
+ const resolved = options.source === void 0 ? void 0 : yield* checkSource(options.rootDir, options.source);
606
+ const cwd = resolved?.cwd;
607
+ const program = resolved?.program;
608
+ const env = Object.entries(options.env).sort(([a], [b]) => a < b ? -1 : 1);
609
+ const removed = options.previousEnvNames.filter((name) => !Object.hasOwn(options.env, name));
610
+ const removedBeforePush = source === void 0 ? removed : [];
611
+ const written = env.length === 0 && removedBeforePush.length === 0 ? {
612
+ current: {},
613
+ changes: []
614
+ } : yield* retryIdempotentWrite(Effect.gen(function* () {
615
+ const current = yield* listVariables(options.url, key);
616
+ if (!options.adopt) {
617
+ const taken = env.filter(([name, value]) => !options.previousEnvNames.includes(name) && Object.hasOwn(current, name) && current[name] !== valueOf$1(value)).map(([name]) => name);
618
+ if (taken.length > 0) return yield* new VariablesOwnedBySomeoneElse({
619
+ deployment: options.deployment,
620
+ names: taken
621
+ });
622
+ }
623
+ const changes = [...env.filter(([name, value]) => current[name] !== valueOf$1(value)).map(([name, value]) => ({
624
+ name,
625
+ value: valueOf$1(value)
626
+ })), ...removedBeforePush.filter((name) => Object.hasOwn(current, name)).map((name) => ({
627
+ name,
628
+ value: null
629
+ }))];
630
+ if (changes.length > 0) yield* writeVariables(options.url, key, changes);
631
+ return {
632
+ current,
633
+ changes
634
+ };
635
+ }));
636
+ /** After a successful push: removes the names that left `env`, as the variables are now. */
637
+ const removeAfterPush = removedBeforePush.length === removed.length ? Effect.void : retryIdempotentWrite(Effect.gen(function* () {
638
+ const current = yield* listVariables(options.url, key);
639
+ const changes = removed.filter((name) => Object.hasOwn(current, name)).map((name) => ({
640
+ name,
641
+ value: null
642
+ }));
643
+ if (changes.length > 0) yield* writeVariables(options.url, key, changes);
644
+ }));
645
+ /**
646
+ * After a failed push, the variables go back to their earlier values, so
647
+ * that the deployment matches the hash in state. A failed rollback is
648
+ * logged: the push error is the one to report.
649
+ */
650
+ const rollback = written.changes.length === 0 ? Effect.void : retryIdempotentWrite(writeVariables(options.url, key, written.changes.map(({ name }) => ({
651
+ name,
652
+ value: Object.hasOwn(written.current, name) ? written.current[name] ?? null : null
653
+ })))).pipe(Effect.catch((error) => Effect.logWarning(`Convex.Deployment could not set the env variables of ${options.deployment} back after the failed push (${error.message}). Run the deploy again.`)));
654
+ if (source === void 0 || cwd === void 0 || program === void 0) return void 0;
655
+ const url = yield* runPush(spawner, key, {
656
+ ...options,
657
+ cwd,
658
+ program,
659
+ command: source.command
660
+ }).pipe(Effect.onError(() => rollback));
661
+ yield* removeAfterPush;
662
+ return url;
663
+ });
664
+ /** Runs the installed CLI or the push command once, and checks the deployment that it names. */
665
+ const runPush = (spawner, key, options) => Effect.gen(function* () {
666
+ const { cwd, program } = options;
667
+ const secret = Redacted.value(key);
668
+ const secrets = [
669
+ secret,
670
+ secret.slice(secret.indexOf("|") + 1),
671
+ ...Object.values(options.env).flatMap((value) => Redacted.isRedacted(value) ? [Redacted.value(value)] : [])
672
+ ].filter((value) => value.length >= 8);
673
+ const result = yield* withKeyFile(secret, ({ envFile, home }) => Effect.gen(function* () {
674
+ const [command, ...programArgs] = program;
675
+ const args = options.command === void 0 ? [
676
+ ...programArgs,
677
+ "deploy",
678
+ ...options.previewName === void 0 ? [] : ["--preview-name", options.previewName],
679
+ "--env-file",
680
+ envFile
681
+ ] : programArgs;
682
+ const child = yield* spawner.spawn(ChildProcess.make(command, args, {
683
+ cwd,
684
+ env: {
685
+ ...cliEnvironment(home),
686
+ ...options.command === void 0 ? {} : { CONVEX_DEPLOY_KEY: secret }
687
+ },
688
+ extendEnv: false,
689
+ stdin: "ignore",
690
+ stdout: "pipe",
691
+ stderr: "pipe"
692
+ }));
693
+ const [exitCode, stdout, stderr] = yield* Effect.all([
694
+ child.exitCode,
695
+ Stream.mkString(Stream.decodeText(child.stdout)),
696
+ Stream.mkString(Stream.decodeText(child.stderr))
697
+ ], { concurrency: "unbounded" });
698
+ return {
699
+ exitCode: Number(exitCode),
700
+ output: `${stdout}\n${stderr}`
701
+ };
702
+ }).pipe(Effect.scoped)).pipe(Effect.mapError((error) => new CodePushFailed({
703
+ exitCode: void 0,
704
+ outputTail: outputTail(error.message, secrets)
705
+ })));
706
+ const deployed = parseDeployOutput(result.output);
707
+ if (result.exitCode !== 0 || deployed === void 0) return yield* new CodePushFailed({
708
+ exitCode: result.exitCode,
709
+ outputTail: outputTail(result.output, secrets)
710
+ });
711
+ if (deployed.deploymentName !== options.deployment) return yield* new PushTargetMismatch({
712
+ expected: options.deployment,
713
+ actual: deployed.deploymentName
714
+ });
715
+ return deployed.url;
716
+ });
717
+ //#endregion
718
+ //#region src/Deployment.ts
719
+ /** The resource class. Stacks call {@link Deployment}, which writes `rootDir` into the props. */
720
+ const DeploymentResource = Resource("Convex.Deployment", { defaultRemovalPolicy: "retain" });
721
+ /** `rootDir` in POSIX form, without "./" and a trailing slash, such as `apps/web` or ".". */
722
+ const normalizeRootDir = (rootDir) => {
723
+ const normalized = posix.normalize(rootDir.replaceAll("\\", "/"));
724
+ return normalized.length > 1 && normalized.endsWith("/") ? normalized.slice(0, -1) : normalized;
725
+ };
726
+ /** `rootDir` is an absolute path. The declaration stops with it as a defect, before the plan. */
727
+ var AbsoluteRootDir = class extends Schema.TaggedError()("AbsoluteRootDir", { rootDir: Schema.String }) {
728
+ get message() {
729
+ return `Convex.Deployment rootDir ${this.rootDir} is an absolute path. State keeps rootDir for every machine that runs the stack, so set it relative to the directory where the deploy runs, such as "apps/web".`;
730
+ }
731
+ };
732
+ /**
733
+ * `Convex.Deployment("id", props)`. The props go to state with `rootDir` in
734
+ * POSIX form, and with "." when it is not set, so that every row names the
735
+ * app directory of its deployment. An absolute `rootDir` stops the
736
+ * declaration, so it never reaches the plan or state. The check dies,
737
+ * because the program of `Alchemy.Stack` can fail only with a ConfigError.
738
+ * `win32.isAbsolute` also answers true for a POSIX absolute path. The other
739
+ * fields keep it usable where Alchemy takes a resource class, such as
740
+ * `Provider.collection`.
741
+ */
742
+ const Deployment = Object.assign((id, props) => {
743
+ const rootDir = props.rootDir ?? ".";
744
+ return win32.isAbsolute(rootDir) ? Effect.die(new AbsoluteRootDir({ rootDir })) : DeploymentResource(id, {
745
+ ...props,
746
+ rootDir: normalizeRootDir(rootDir)
747
+ });
748
+ }, {
749
+ Type: DeploymentResource.Type,
750
+ Props: DeploymentResource.Props,
751
+ Self: DeploymentResource.Self,
752
+ Provider: DeploymentResource.Provider,
753
+ Aliases: DeploymentResource.Aliases,
754
+ ref: (id, options) => DeploymentResource.ref(id, options)
755
+ });
756
+ /** The props name another deployment than the one in state. */
757
+ var DeploymentIdentityChange = class extends Schema.TaggedError()("DeploymentIdentityChange", {
758
+ /** Name of the deployment in state, such as `happy-animal-123`. */
759
+ deployment: Schema.String,
760
+ field: Schema.Literals([
761
+ "projectId",
762
+ "type",
763
+ "name"
764
+ ]),
765
+ current: Schema.String,
766
+ requested: Schema.String
767
+ }) {
768
+ get message() {
769
+ return `Convex.Deployment cannot change the ${this.field} of deployment ${this.deployment} from ${this.current} to ${this.requested}. Set ${this.field} back to ${this.current}. For another deployment, create a new resource with a new logical id.`;
770
+ }
771
+ };
772
+ /** The project has no default production deployment for a `prod` resource to take over. */
773
+ var ProductionDeploymentNotFound = class extends Schema.TaggedError()("ProductionDeploymentNotFound", { projectId: Schema.Number }) {
774
+ get message() {
775
+ return `Project ${this.projectId} has no default production deployment, and Convex.Deployment does not create one. Create it in the Convex dashboard, or with \`npx convex deployment create --type prod --default\` in the project, then run the deploy again.`;
776
+ }
777
+ };
778
+ /** More than one deployment of the project has the name, so the lookup cannot choose one. */
779
+ var AmbiguousDeployment = class extends Schema.TaggedError()("AmbiguousDeployment", {
780
+ projectId: Schema.Number,
781
+ type: Schema.Literals(["dev", "preview"]),
782
+ name: Schema.String,
783
+ deployments: Schema.Array(Schema.String)
784
+ }) {
785
+ get message() {
786
+ return `Project ${this.projectId} has ${this.deployments.length} ${this.type} deployments named "${this.name}" (${this.deployments.join(", ")}). Convex.Deployment does not choose one. Delete the extra deployments in the Convex dashboard, or use another name.`;
787
+ }
788
+ };
789
+ /**
790
+ * The URL of a Convex cloud deployment: `https://<name>.convex.cloud`, or
791
+ * `https://<name>.<region>.convex.cloud` outside US East.
792
+ */
793
+ const CLOUD_URL = /^https:\/\/[a-z0-9]+(?:-[a-z0-9]+)*(?:\.[a-z0-9]+(?:-[a-z0-9]+)*)?\.convex\.cloud$/;
794
+ /**
795
+ * The HTTP actions URL of a deployment: the client URL with `.convex.site`
796
+ * for `.convex.cloud`, as Convex sets CONVEX_SITE_URL. Custom domains are
797
+ * not covered.
798
+ */
799
+ const siteUrlOf = (url) => url.replace(/\.convex\.cloud$/, ".convex.site");
800
+ /** One row of list_deployments, GET /deployments/{name}, and create_deployment. Only the fields the provider uses. */
801
+ const DeploymentRow$1 = Schema.Struct({
802
+ name: Schema.String,
803
+ projectId: Schema.Number,
804
+ deploymentType: Schema.String,
805
+ isDefault: Schema.Boolean,
806
+ reference: Schema.String,
807
+ /** Set in list_deployments and create_deployment rows only: GET /deployments/{name} answers null. */
808
+ previewIdentifier: Schema.optionalKey(Schema.NullOr(Schema.String)),
809
+ deploymentUrl: Schema.String.check(Schema.isPattern(CLOUD_URL)),
810
+ /** Absent or null until the first push: list_deployments leaves it out for a new deployment. */
811
+ lastDeployTime: Schema.optionalKey(Schema.NullOr(Schema.Number))
812
+ });
813
+ const DeploymentRows$1 = Schema.Array(DeploymentRow$1);
814
+ /** GET https://<deployment>/api/v1/deployment_info, for a cloud deployment. Only the fields the provider uses. */
815
+ const DeploymentInfo = Schema.Struct({
816
+ kind: Schema.Literal("cloud"),
817
+ projectId: Schema.Number,
818
+ deploymentType: Schema.String,
819
+ reference: Schema.optionalKey(Schema.NullOr(Schema.String))
820
+ });
821
+ /** GET https://<deployment>/api/v1/get_canonical_urls */
822
+ const CanonicalUrls = Schema.Struct({
823
+ convexCloudUrl: Schema.String,
824
+ convexSiteUrl: Schema.String
825
+ });
826
+ const targetOf = (row, type, previewName) => ({
827
+ projectId: row.projectId,
828
+ type,
829
+ name: row.name,
830
+ reference: row.reference,
831
+ previewName: type === "preview" ? previewName : void 0,
832
+ url: row.deploymentUrl,
833
+ siteUrl: siteUrlOf(row.deploymentUrl)
834
+ });
835
+ /** True when the deployment has received a push. */
836
+ const isDeployed = (row) => row.lastDeployTime !== void 0 && row.lastDeployTime !== null;
837
+ /** The `name` prop of a deployment: the dev reference or the preview name. */
838
+ const nameOf = (target) => target.type === "dev" ? target.reference : target.type === "preview" ? target.previewName : void 0;
839
+ /**
840
+ * Fails with {@link DeploymentIdentityChange} when the props name another
841
+ * deployment than `current`: the attributes in state, or a live deployment.
842
+ */
843
+ const checkIdentity = (current, news) => {
844
+ const change = (field, from, to) => Effect.fail(new DeploymentIdentityChange({
845
+ deployment: current.name,
846
+ field,
847
+ current: from,
848
+ requested: to
849
+ }));
850
+ if (current.projectId !== news.project.projectId) return change("projectId", String(current.projectId), String(news.project.projectId));
851
+ if (current.type !== news.type) return change("type", current.type, news.type);
852
+ const currentName = nameOf(current);
853
+ const named = news.type === "dev" && current.name === news.name;
854
+ if (news.type !== "prod" && currentName !== news.name && !named) return change("name", currentName ?? "(none)", news.name);
855
+ return Effect.void;
856
+ };
857
+ const addressOf = (props) => ({
858
+ projectId: props.project.projectId,
859
+ type: props.type,
860
+ name: props.type === "prod" ? void 0 : props.name
861
+ });
862
+ /** True when an update writes or removes variables: `env` has names, or state has names to remove. */
863
+ const changesEnv = (news, output) => Object.keys(news.env ?? {}).length > 0 || envNamesOf(output).length > 0;
864
+ /** The `env` names in state. State from 0.3 has none. */
865
+ const envNamesOf = (output) => output?.envNames ?? [];
866
+ /** The address of the deployment in state. */
867
+ const addressInState = (output) => ({
868
+ projectId: output.projectId,
869
+ type: output.type,
870
+ name: nameOf(output)
871
+ });
872
+ const ProjectSlugs = Schema.Struct({
873
+ slug: Schema.String,
874
+ teamSlug: Schema.String
875
+ });
876
+ /** True for an answer that says this credential cannot read the object. */
877
+ const isRefused = (error) => error.status === 400 || error.status === 401 || error.status === 403 || error.status === 404;
878
+ const DeploymentProvider = () => Provider.effect(DeploymentResource, Effect.gen(function* () {
879
+ const api = yield* ManagementApi;
880
+ const credentials = yield* Credentials;
881
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
882
+ /** The live deployment, or undefined after a 404. GET /deployments/{name} answers no preview identifier. */
883
+ const getByName = (management, name) => absentAsUndefined(management.request("get deployment", (client) => client.GET("/deployments/{deployment_name}", { params: { path: { deployment_name: name } } }))).pipe(Effect.map((body) => body === void 0 ? void 0 : Schema.decodeUnknownSync(DeploymentRow$1)(body)));
884
+ const listDeployments = (management, projectId, type, isDefault) => management.request("list deployments", (client) => client.GET("/projects/{project_id}/list_deployments", { params: {
885
+ path: { project_id: projectId },
886
+ query: {
887
+ deploymentType: type,
888
+ ...isDefault === void 0 ? {} : { isDefault }
889
+ }
890
+ } })).pipe(Effect.map((body) => Schema.decodeUnknownSync(DeploymentRows$1)(body)));
891
+ /** The row of the project's default production deployment, or undefined. */
892
+ const productionRow = (management, projectId) => listDeployments(management, projectId, "prod", true).pipe(Effect.map((rows) => rows.find((candidate) => candidate.deploymentType === "prod" && candidate.isDefault)));
893
+ /** The project's default production deployment, or undefined. */
894
+ const production = (management, projectId) => productionRow(management, projectId).pipe(Effect.map((row) => row === void 0 ? void 0 : targetOf(row, "prod", void 0)));
895
+ /**
896
+ * The one dev deployment with this reference or this Convex name, or the
897
+ * one preview deployment with this preview name, or undefined. The name
898
+ * form takes the dev deployment that `npx convex dev` made, such as the
899
+ * one `.env.local` selects, which has a reference the stack never chose.
900
+ */
901
+ const findByName = (management, projectId, type, name) => Effect.gen(function* () {
902
+ const matches = (yield* listDeployments(management, projectId, type)).filter((row) => row.deploymentType === type && (type === "dev" ? row.reference === name || row.name === name : row.previewIdentifier === name));
903
+ if (matches.length > 1) return yield* new AmbiguousDeployment({
904
+ projectId,
905
+ type,
906
+ name,
907
+ deployments: matches.map((row) => row.name)
908
+ });
909
+ return matches[0];
910
+ });
911
+ /** The deployment that the address names, through the Management API, or undefined. */
912
+ const lookup = (management, address) => address.type === "prod" || address.name === void 0 ? production(management, address.projectId) : findByName(management, address.projectId, address.type, address.name).pipe(Effect.map((row) => row === void 0 ? void 0 : targetOf(row, address.type, address.name)));
913
+ /** The deployment of a deploy key, when it is the deployment that the address names. */
914
+ const deployKeyTarget = (key, deployment, address) => Effect.gen(function* () {
915
+ const info = Schema.decodeUnknownSync(DeploymentInfo)(yield* api.deploymentRequest("get deployment info", deployment, key, (client) => client.GET("/deployment_info")));
916
+ const reference = info.reference ?? "";
917
+ if (info.projectId !== address.projectId || info.deploymentType !== address.type || address.type === "dev" && reference !== address.name && deployment !== address.name) return;
918
+ const urls = Schema.decodeUnknownSync(CanonicalUrls)(yield* api.deploymentRequest("get canonical urls", deployment, key, (client) => client.GET("/get_canonical_urls")));
919
+ return {
920
+ projectId: info.projectId,
921
+ type: address.type,
922
+ name: deployment,
923
+ reference,
924
+ previewName: void 0,
925
+ url: urls.convexCloudUrl,
926
+ siteUrl: urls.convexSiteUrl
927
+ };
928
+ }).pipe(Effect.catchIf(isRefused, () => Effect.succeed(void 0)));
929
+ /** True when the preview deploy key belongs to the project. */
930
+ const previewKeyFits = (management, slugs, projectId) => management.request("get project", (client) => client.GET("/projects/{project_id}", { params: { path: { project_id: projectId } } })).pipe(Effect.map((body) => {
931
+ const project = Schema.decodeUnknownSync(ProjectSlugs)(body);
932
+ return project.slug === slugs.project && project.teamSlug === slugs.team;
933
+ }), Effect.catchIf(isRefused, () => Effect.succeed(false)));
934
+ /**
935
+ * The narrowest credential that reaches the deployment. See {@link Access}.
936
+ * When `changesEnv`, a preview deploy key gives way to the access token,
937
+ * because it cannot change variables.
938
+ */
939
+ const accessFor = (address, changesEnv) => Effect.gen(function* () {
940
+ const key = yield* credentials.deployKey;
941
+ if (key !== void 0) {
942
+ const target = keyTargetOf(Redacted.value(key));
943
+ if (target.kind === "deployment" && address.type !== "preview") {
944
+ const found = yield* deployKeyTarget(key, target.deployment, address);
945
+ if (found !== void 0) return {
946
+ kind: "deployKey",
947
+ key,
948
+ target: found
949
+ };
950
+ }
951
+ if (target.kind === "preview" && address.type === "preview") {
952
+ const scoped = api.withToken(key);
953
+ if (!(changesEnv && (yield* credentials.hasAccessToken)) && (yield* previewKeyFits(scoped, target, address.projectId))) return {
954
+ kind: "previewKey",
955
+ key,
956
+ api: scoped
957
+ };
958
+ }
959
+ }
960
+ return {
961
+ kind: "token",
962
+ api
963
+ };
964
+ });
965
+ /** The live deployment of a resource in state, or undefined when it is gone. */
966
+ const live = (access, output) => Effect.gen(function* () {
967
+ if (access.kind === "deployKey") return access.target;
968
+ if (output.type === "prod") return yield* absentAsUndefined(production(access.api, output.projectId));
969
+ const row = yield* getByName(access.api, output.name);
970
+ return row === void 0 ? void 0 : targetOf(row, output.type, output.previewName);
971
+ });
972
+ /** The content identity of `source` and `env` on a deployment, or undefined when there is nothing to push. */
973
+ const wantedHash = (news, rootDir, deployment) => news.source === void 0 && Object.keys(news.env ?? {}).length === 0 ? Effect.succeed(void 0) : pushHash({
974
+ rootDir,
975
+ source: news.source,
976
+ deployment,
977
+ env: news.env ?? {}
978
+ });
979
+ return {
980
+ stables: [
981
+ "projectId",
982
+ "type",
983
+ "previewName"
984
+ ],
985
+ diff: Effect.fn(function* ({ news, olds, output, oldBindings, newBindings }) {
986
+ if (!isResolved(news) || output === void 0) return void 0;
987
+ yield* checkIdentity(output, news);
988
+ if (!isResolved(newBindings)) return void 0;
989
+ const rootDir = news.rootDir ?? ".";
990
+ if (news.source !== void 0) yield* checkSource(rootDir, news.source);
991
+ if (olds.rootDir !== rootDir) return { action: "update" };
992
+ const access = yield* accessFor(addressOf(news), changesEnv(news, output));
993
+ const current = yield* live(access, output);
994
+ if (current?.name !== output.name) return { action: "update" };
995
+ if ((yield* wantedHash(news, rootDir, output.name)) !== output.hash) return { action: "update" };
996
+ if (diffBindings(oldBindings, newBindings).every((binding) => binding.action === "noop")) return { action: "noop" };
997
+ return {
998
+ action: "update",
999
+ stables: [
1000
+ "hash",
1001
+ "envNames",
1002
+ ...[
1003
+ "projectId",
1004
+ "type",
1005
+ "previewName",
1006
+ "name",
1007
+ "reference",
1008
+ "url",
1009
+ "siteUrl"
1010
+ ].filter((key) => current[key] === output[key])
1011
+ ]
1012
+ };
1013
+ }),
1014
+ read: Effect.fn(function* ({ olds, output }) {
1015
+ if (output !== void 0) {
1016
+ const access = yield* accessFor(addressInState(output), false);
1017
+ const current = yield* live(access, output);
1018
+ return current === void 0 ? void 0 : {
1019
+ ...output,
1020
+ ...current
1021
+ };
1022
+ }
1023
+ const address = addressOf(olds);
1024
+ const access = yield* accessFor(address, false);
1025
+ if (access.kind === "deployKey") return Unowned({
1026
+ ...access.target,
1027
+ hash: void 0,
1028
+ envNames: []
1029
+ });
1030
+ if (olds.type === "prod") {
1031
+ const row = yield* productionRow(access.api, address.projectId);
1032
+ if (row === void 0) return void 0;
1033
+ const attributes = {
1034
+ ...targetOf(row, "prod", void 0),
1035
+ hash: void 0,
1036
+ envNames: []
1037
+ };
1038
+ return isDeployed(row) ? Unowned(attributes) : attributes;
1039
+ }
1040
+ const found = yield* lookup(access.api, address);
1041
+ if (found === void 0) return void 0;
1042
+ return Unowned({
1043
+ ...found,
1044
+ hash: void 0,
1045
+ envNames: []
1046
+ });
1047
+ }),
1048
+ reconcile: Effect.fn(function* ({ fqn, news, output }) {
1049
+ if (output !== void 0) yield* checkIdentity(output, news);
1050
+ const rootDir = news.rootDir ?? ".";
1051
+ if (news.source !== void 0) yield* checkSource(rootDir, news.source);
1052
+ const address = addressOf(news);
1053
+ const access = yield* accessFor(address, changesEnv(news, output));
1054
+ const env = news.env ?? {};
1055
+ if (access.kind === "previewKey" && changesEnv(news, output)) return yield* new EnvironmentNeedsDeployKey({ deployment: output?.name ?? address.name ?? "(new)" });
1056
+ const adopt = yield* shouldAdopt(fqn);
1057
+ const refuse = (name) => new OwnedBySomeoneElse({
1058
+ message: `Project ${address.projectId} already has ${news.type} deployment ${name}${news.type === "prod" ? " with code" : ` named "${news.name}"`}. Re-run with --adopt to take it over${news.type === "prod" ? "" : ", or use another name"}.`,
1059
+ resourceType: DeploymentResource.Type,
1060
+ physicalName: name
1061
+ });
1062
+ const { target, created } = yield* Effect.gen(function* () {
1063
+ if (access.kind === "deployKey") {
1064
+ if (output === void 0 && !adopt) return yield* refuse(access.target.name);
1065
+ return {
1066
+ target: access.target,
1067
+ created: false
1068
+ };
1069
+ }
1070
+ if (news.type === "prod") {
1071
+ const row = yield* productionRow(access.api, address.projectId);
1072
+ if (row === void 0) return yield* new ProductionDeploymentNotFound({ projectId: address.projectId });
1073
+ if (output === void 0 && isDeployed(row) && !adopt) return yield* refuse(row.name);
1074
+ return {
1075
+ target: targetOf(row, "prod", void 0),
1076
+ created: false
1077
+ };
1078
+ }
1079
+ if (output !== void 0) {
1080
+ const row = yield* getByName(access.api, output.name);
1081
+ if (row !== void 0) {
1082
+ if (row.deploymentType !== output.type) return yield* new DeploymentIdentityChange({
1083
+ deployment: row.name,
1084
+ field: "type",
1085
+ current: row.deploymentType,
1086
+ requested: news.type
1087
+ });
1088
+ const current = targetOf(row, output.type, output.previewName);
1089
+ yield* checkIdentity(current, news);
1090
+ return {
1091
+ target: current,
1092
+ created: false
1093
+ };
1094
+ }
1095
+ }
1096
+ const existing = yield* lookup(access.api, address);
1097
+ if (existing !== void 0) {
1098
+ if (!adopt) return yield* refuse(existing.name);
1099
+ return {
1100
+ target: existing,
1101
+ created: false
1102
+ };
1103
+ }
1104
+ const row = yield* access.api.request("create deployment", (client) => client.POST("/projects/{project_id}/create_deployment", {
1105
+ params: { path: { project_id: address.projectId } },
1106
+ body: {
1107
+ type: news.type,
1108
+ reference: news.name
1109
+ }
1110
+ }));
1111
+ return {
1112
+ target: targetOf(Schema.decodeUnknownSync(DeploymentRow$1)(row), news.type, news.name),
1113
+ created: true
1114
+ };
1115
+ });
1116
+ const previousEnvNames = output?.name === target.name ? envNamesOf(output) : [];
1117
+ const before = yield* wantedHash(news, rootDir, target.name);
1118
+ if (before === void 0 && previousEnvNames.length === 0) return {
1119
+ ...target,
1120
+ hash: void 0,
1121
+ envNames: []
1122
+ };
1123
+ if (output?.name === target.name && before === output.hash) return {
1124
+ ...target,
1125
+ hash: output.hash,
1126
+ envNames: previousEnvNames
1127
+ };
1128
+ const options = {
1129
+ deployment: target.name,
1130
+ url: target.url,
1131
+ rootDir,
1132
+ source: news.source,
1133
+ env,
1134
+ previousEnvNames,
1135
+ adopt
1136
+ };
1137
+ yield* (access.kind === "deployKey" ? push(spawner, access.key, {
1138
+ ...options,
1139
+ previewName: void 0
1140
+ }) : access.kind === "previewKey" ? push(spawner, access.key, {
1141
+ ...options,
1142
+ previewName: target.previewName
1143
+ }) : withPushKey(access.api, target.name, typeof news.source === "object" && news.source.command !== void 0 ? void 0 : PUSH_KEY_ACTIONS, (key) => push(spawner, key, {
1144
+ ...options,
1145
+ previewName: void 0
1146
+ }))).pipe(Effect.onError(() => created && access.kind !== "deployKey" ? absentAsUndefined(retryIdempotentWrite(access.api.requestVoid("delete deployment", (client) => client.POST("/deployments/{deployment_name}/delete", { params: { path: { deployment_name: target.name } } })))).pipe(Effect.catch((error) => Effect.logWarning(`Convex.Deployment could not delete ${target.name} after the failed push (${error.message}). The next run takes it over only with --adopt.`))) : Effect.void));
1147
+ return {
1148
+ ...target,
1149
+ hash: yield* wantedHash(news, rootDir, target.name),
1150
+ envNames: Object.keys(env).sort()
1151
+ };
1152
+ }),
1153
+ delete: Effect.fn(function* ({ output }) {
1154
+ const keep = Effect.logWarning(`Convex.Deployment does not delete production deployment ${output.name}: it belongs to project ${output.projectId}. To delete it, delete the project with RemovalPolicy.destroy() on Convex.Project.`);
1155
+ if (output.type === "prod") return yield* keep;
1156
+ const access = yield* accessFor(addressInState(output), false);
1157
+ const management = access.kind === "deployKey" ? api : access.api;
1158
+ const row = yield* getByName(management, output.name);
1159
+ if (row === void 0) return;
1160
+ if (row.deploymentType === "prod") return yield* keep;
1161
+ yield* absentAsUndefined(retryIdempotentWrite(management.requestVoid("delete deployment", (client) => client.POST("/deployments/{deployment_name}/delete", { params: { path: { deployment_name: output.name } } }))));
1162
+ })
1163
+ };
1164
+ }));
1165
+ //#endregion
37
1166
  //#region src/LocalDeployment.ts
38
1167
  /** The folder has no logged-in local deployment. */
39
1168
  var LocalDeploymentNotFound = class extends Schema.TaggedError()("LocalDeploymentNotFound", { rootDir: Schema.String }) {
@@ -85,6 +1214,305 @@ const LocalDeploymentProvider = () => Provider.effect(LocalDeployment, Effect.ge
85
1214
  };
86
1215
  }));
87
1216
  //#endregion
1217
+ //#region src/Project.ts
1218
+ const Project = Resource("Convex.Project", { defaultRemovalPolicy: "retain" });
1219
+ /** The credential is of another team than the project. Convex cannot move a project. */
1220
+ var ProjectTeamChange = class extends Schema.TaggedError()("ProjectTeamChange", {
1221
+ projectId: Schema.Number,
1222
+ teamId: Schema.Number,
1223
+ requestedTeamId: Schema.Number
1224
+ }) {
1225
+ get message() {
1226
+ 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.`;
1227
+ }
1228
+ };
1229
+ /**
1230
+ * The props change `deploymentType` or `deploymentRegion` of an existing
1231
+ * project. Convex uses them only when it creates the project.
1232
+ */
1233
+ var ProjectDeploymentChange = class extends Schema.TaggedError()("ProjectDeploymentChange", {
1234
+ projectId: Schema.Number,
1235
+ field: Schema.Literals(["deploymentType", "deploymentRegion"]),
1236
+ current: Schema.UndefinedOr(Schema.String),
1237
+ requested: Schema.UndefinedOr(Schema.String)
1238
+ }) {
1239
+ get message() {
1240
+ const show = (value) => value === void 0 ? "(not set)" : value;
1241
+ return `Convex.Project cannot change ${this.field} of project ${this.projectId} from ${show(this.current)} to ${show(this.requested)}: Convex uses it only when it creates a project. Set ${this.field} back to ${show(this.current)}. For a new deployment, create a new resource with a new logical id and move the data yourself.`;
1242
+ }
1243
+ };
1244
+ /** More than one project in the team has the name, so the lookup cannot choose one. */
1245
+ var AmbiguousProject = class extends Schema.TaggedError()("AmbiguousProject", {
1246
+ teamId: Schema.Number,
1247
+ name: Schema.String,
1248
+ projectIds: Schema.Array(Schema.Number)
1249
+ }) {
1250
+ get message() {
1251
+ return `Team ${this.teamId} has ${this.projectIds.length} projects named "${this.name}" (ids ${this.projectIds.join(", ")}). Convex.Project does not choose one. Rename the projects in the Convex dashboard so that only one has this name, or use a different name.`;
1252
+ }
1253
+ };
1254
+ /** Convex answered a create call but then did not return the project. */
1255
+ var CreatedProjectNotFound = class extends Schema.TaggedError()("CreatedProjectNotFound", { projectId: Schema.Number }) {
1256
+ get message() {
1257
+ return `Convex created project ${this.projectId} but GET /projects/${this.projectId} did not return it. Run the deploy again with --adopt to take over project ${this.projectId}.`;
1258
+ }
1259
+ };
1260
+ /** No project in the team has the slug. A `slug` resource never creates one. */
1261
+ var ProjectNotFound = class extends Schema.TaggedError()("ProjectNotFound", {
1262
+ teamId: Schema.Number,
1263
+ slug: Schema.String
1264
+ }) {
1265
+ get message() {
1266
+ 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.`;
1267
+ }
1268
+ };
1269
+ /** The props change the slug of a `slug` resource: that is another project. */
1270
+ var ProjectSlugChange = class extends Schema.TaggedError()("ProjectSlugChange", {
1271
+ projectId: Schema.Number,
1272
+ slug: Schema.String,
1273
+ requestedSlug: Schema.String
1274
+ }) {
1275
+ get message() {
1276
+ return `Convex.Project ${this.projectId} has the slug "${this.slug}", and the props ask for "${this.requestedSlug}", which is another project. Set slug back to "${this.slug}". For the other project, create a new resource with a new logical id.`;
1277
+ }
1278
+ };
1279
+ /** Fields of GET /projects/{id}, PATCH /projects/{id}, and GET /teams/{team}/projects rows that the provider uses. */
1280
+ const ProjectDetails = Schema.Struct({
1281
+ id: Schema.Number,
1282
+ name: Schema.String,
1283
+ slug: Schema.String,
1284
+ teamId: Schema.Number,
1285
+ teamSlug: Schema.String,
1286
+ prodDeploymentName: Schema.NullOr(Schema.String)
1287
+ });
1288
+ /** GET /teams/{team_id}/projects: one page of projects. */
1289
+ const ProjectPage = Schema.Struct({
1290
+ items: Schema.Array(ProjectDetails),
1291
+ pagination: Schema.Struct({
1292
+ hasMore: Schema.Boolean,
1293
+ nextCursor: Schema.optionalKey(Schema.NullOr(Schema.String))
1294
+ })
1295
+ });
1296
+ /** POST /teams/{team_id}/create_project. Only the id: everything else comes from GET /projects/{id}. */
1297
+ const CreatedProject = Schema.Struct({ projectId: Schema.Number });
1298
+ const DeploymentRow = Schema.Struct({
1299
+ name: Schema.String,
1300
+ deploymentType: Schema.String,
1301
+ isDefault: Schema.Boolean,
1302
+ deploymentUrl: Schema.String,
1303
+ /** Absent or null until the first push. */
1304
+ lastDeployTime: Schema.optionalKey(Schema.NullOr(Schema.Number))
1305
+ });
1306
+ const DeploymentRows = Schema.Array(DeploymentRow);
1307
+ /**
1308
+ * Fails with {@link ProjectDeploymentChange} when a create-time prop
1309
+ * changed. An omitted `deploymentType` means `prod`.
1310
+ */
1311
+ const checkCreateTimeProps = (projectId, olds, news) => {
1312
+ const oldType = olds.deploymentType ?? "prod";
1313
+ const newType = news.deploymentType ?? "prod";
1314
+ if (oldType !== newType) return Effect.fail(new ProjectDeploymentChange({
1315
+ projectId,
1316
+ field: "deploymentType",
1317
+ current: oldType,
1318
+ requested: newType
1319
+ }));
1320
+ if (olds.deploymentRegion !== news.deploymentRegion) return Effect.fail(new ProjectDeploymentChange({
1321
+ projectId,
1322
+ field: "deploymentRegion",
1323
+ current: olds.deploymentRegion,
1324
+ requested: news.deploymentRegion
1325
+ }));
1326
+ return Effect.void;
1327
+ };
1328
+ /** The row of the project's default production deployment, or undefined. */
1329
+ 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)));
1330
+ /** GET /projects/{id}, or undefined after a 404. */
1331
+ const getProjectById = (api, projectId) => absentAsUndefined(api.request("get project", (client) => client.GET("/projects/{project_id}", { params: { path: { project_id: projectId } } }))).pipe(Effect.map((body) => body === void 0 ? void 0 : Schema.decodeUnknownSync(ProjectDetails)(body)));
1332
+ /**
1333
+ * Every project in the team with exactly this name, in the order of the
1334
+ * listing. Reads every page. `q` narrows the listing on the server, and the
1335
+ * exact match here decides. Pattern from Confect
1336
+ * `packages/alchemy/src/ConvexClient.ts` and `Project.ts`
1337
+ * (https://github.com/rjdellecese/confect, ISC license).
1338
+ */
1339
+ const listProjectsByName = (api, teamId, name) => Effect.gen(function* () {
1340
+ const matches = [];
1341
+ const seenCursors = /* @__PURE__ */ new Set();
1342
+ let cursor;
1343
+ for (;;) {
1344
+ const body = yield* api.request("list projects", (client) => client.GET("/teams/{team_id}/projects", { params: {
1345
+ path: { team_id: teamId },
1346
+ query: {
1347
+ q: name,
1348
+ ...cursor === void 0 ? {} : { cursor }
1349
+ }
1350
+ } }));
1351
+ const page = Schema.decodeUnknownSync(ProjectPage)(body);
1352
+ matches.push(...page.items.filter((row) => row.name === name));
1353
+ if (!page.pagination.hasMore) break;
1354
+ const next = page.pagination.nextCursor;
1355
+ if (next === void 0 || next === null || seenCursors.has(next)) return yield* new ConvexApiError({
1356
+ operation: "list projects",
1357
+ status: 0,
1358
+ code: "InvalidPagination",
1359
+ message: `The project listing of team ${teamId} reports more pages but gives no new cursor. Convex.Project stops so that it does not miss a project named "${name}".`
1360
+ });
1361
+ seenCursors.add(next);
1362
+ cursor = next;
1363
+ }
1364
+ return matches;
1365
+ });
1366
+ /** The one project in the team with exactly this name, or undefined. More than one is an error. */
1367
+ const findProjectByName = (api, teamId, name) => listProjectsByName(api, teamId, name).pipe(Effect.flatMap((matches) => matches.length > 1 ? new AmbiguousProject({
1368
+ teamId,
1369
+ name,
1370
+ projectIds: matches.map((row) => row.id)
1371
+ }) : Effect.succeed(matches[0])));
1372
+ /**
1373
+ * POST /teams/{team_id}/create_project, then GET /projects/{id}. The identity
1374
+ * comes from the create response, never from a name lookup.
1375
+ */
1376
+ const createProject = (api, teamId, props) => Effect.gen(function* () {
1377
+ const created = yield* api.request("create project", (client) => client.POST("/teams/{team_id}/create_project", {
1378
+ params: { path: { team_id: teamId } },
1379
+ body: {
1380
+ projectName: props.name,
1381
+ deploymentType: props.deploymentType,
1382
+ ...props.deploymentRegion === void 0 ? {} : { deploymentRegion: props.deploymentRegion }
1383
+ }
1384
+ }));
1385
+ const { projectId } = Schema.decodeUnknownSync(CreatedProject)(created);
1386
+ const details = yield* getProjectById(api, projectId);
1387
+ if (details === void 0) return yield* new CreatedProjectNotFound({ projectId });
1388
+ return details;
1389
+ });
1390
+ const ProjectProvider = () => Provider.effect(Project, Effect.gen(function* () {
1391
+ const api = yield* ManagementApi;
1392
+ const attributesOf = (details) => prodDeploymentOf(api, details.id).pipe(Effect.map((prod) => ({
1393
+ projectId: details.id,
1394
+ slug: details.slug,
1395
+ name: details.name,
1396
+ teamId: details.teamId,
1397
+ prodDeploymentName: prod?.name ?? details.prodDeploymentName ?? void 0,
1398
+ prodDeploymentUrl: prod?.deploymentUrl
1399
+ })));
1400
+ const getById = (projectId) => getProjectById(api, projectId);
1401
+ /** The project with this slug in the team, or undefined. */
1402
+ const getBySlug = (teamId, slug) => absentAsUndefined(api.request("get project by slug", (client) => client.GET("/teams/{team_id_or_slug}/projects/{project_slug}", { params: { path: {
1403
+ team_id_or_slug: String(teamId),
1404
+ project_slug: slug
1405
+ } } }))).pipe(Effect.map((body) => body === void 0 ? void 0 : Schema.decodeUnknownSync(ProjectDetails)(body)));
1406
+ const findByName = (teamId, name) => findProjectByName(api, teamId, name);
1407
+ /**
1408
+ * Brings an existing project to the desired name. The team cannot
1409
+ * change, so a project in another team fails.
1410
+ */
1411
+ const converge = (details, teamId, name) => Effect.gen(function* () {
1412
+ if (details.teamId !== teamId) return yield* new ProjectTeamChange({
1413
+ projectId: details.id,
1414
+ teamId: details.teamId,
1415
+ requestedTeamId: teamId
1416
+ });
1417
+ if (details.name === name) return yield* attributesOf(details);
1418
+ const updated = yield* api.request("update project", (client) => client.PATCH("/projects/{project_id}", {
1419
+ params: { path: { project_id: details.id } },
1420
+ body: { name }
1421
+ }));
1422
+ return yield* attributesOf(Schema.decodeUnknownSync(ProjectDetails)(updated));
1423
+ });
1424
+ return {
1425
+ stables: [
1426
+ "projectId",
1427
+ "slug",
1428
+ "teamId"
1429
+ ],
1430
+ diff: Effect.fn(function* ({ olds, news, output }) {
1431
+ if (!isResolved(news)) return void 0;
1432
+ if (output === void 0) return void 0;
1433
+ const teamId = yield* api.teamId;
1434
+ if (teamId !== output.teamId) return yield* new ProjectTeamChange({
1435
+ projectId: output.projectId,
1436
+ teamId: output.teamId,
1437
+ requestedTeamId: teamId
1438
+ });
1439
+ if (news.slug !== void 0) {
1440
+ if (news.slug !== output.slug) return yield* new ProjectSlugChange({
1441
+ projectId: output.projectId,
1442
+ slug: output.slug,
1443
+ requestedSlug: news.slug
1444
+ });
1445
+ return { action: "noop" };
1446
+ }
1447
+ return olds.name === news.name ? void 0 : { action: "update" };
1448
+ }),
1449
+ read: Effect.fn(function* ({ olds, output }) {
1450
+ if (output !== void 0) {
1451
+ const details = yield* getById(output.projectId);
1452
+ return details === void 0 ? void 0 : yield* attributesOf(details);
1453
+ }
1454
+ const teamId = yield* api.teamId;
1455
+ const existing = olds.slug !== void 0 ? yield* getBySlug(teamId, olds.slug) : yield* findByName(teamId, olds.name);
1456
+ return existing === void 0 ? void 0 : Unowned(yield* attributesOf(existing));
1457
+ }),
1458
+ reconcile: Effect.fn(function* ({ fqn, olds, news, output }) {
1459
+ const teamId = yield* api.teamId;
1460
+ if (news.slug !== void 0) {
1461
+ const details = output === void 0 ? yield* getBySlug(teamId, news.slug) : yield* getById(output.projectId);
1462
+ if (details === void 0) return yield* new ProjectNotFound({
1463
+ teamId,
1464
+ slug: news.slug
1465
+ });
1466
+ if (details.slug !== news.slug) return yield* new ProjectSlugChange({
1467
+ projectId: details.id,
1468
+ slug: details.slug,
1469
+ requestedSlug: news.slug
1470
+ });
1471
+ if (details.teamId !== teamId) return yield* new ProjectTeamChange({
1472
+ projectId: details.id,
1473
+ teamId: details.teamId,
1474
+ requestedTeamId: teamId
1475
+ });
1476
+ if (output === void 0 && !(yield* shouldAdopt(fqn))) return yield* new OwnedBySomeoneElse({
1477
+ message: `Convex project ${details.id} ("${news.slug}") exists and is not in this stack's state. Re-run with --adopt to take it over.`,
1478
+ resourceType: Project.Type,
1479
+ physicalName: news.slug
1480
+ });
1481
+ return yield* attributesOf(details);
1482
+ }
1483
+ if (output !== void 0) {
1484
+ if (olds !== void 0 && olds.name !== void 0) yield* checkCreateTimeProps(output.projectId, olds, news);
1485
+ if (output.teamId !== teamId) return yield* new ProjectTeamChange({
1486
+ projectId: output.projectId,
1487
+ teamId: output.teamId,
1488
+ requestedTeamId: teamId
1489
+ });
1490
+ const details = yield* getById(output.projectId);
1491
+ if (details !== void 0) return yield* converge(details, teamId, news.name);
1492
+ } else {
1493
+ const existing = yield* findByName(teamId, news.name);
1494
+ if (existing !== void 0) {
1495
+ if (!(yield* shouldAdopt(fqn))) return yield* new OwnedBySomeoneElse({
1496
+ message: `Convex project ${existing.id} in team ${teamId} already has the name "${news.name}". Re-run with --adopt to take it over, or use a different name.`,
1497
+ resourceType: Project.Type,
1498
+ physicalName: news.name
1499
+ });
1500
+ return yield* converge(existing, teamId, news.name);
1501
+ }
1502
+ }
1503
+ const details = yield* createProject(api, teamId, {
1504
+ name: news.name,
1505
+ deploymentType: news.deploymentType ?? "prod",
1506
+ deploymentRegion: news.deploymentRegion
1507
+ });
1508
+ return yield* converge(details, teamId, news.name);
1509
+ }),
1510
+ delete: Effect.fn(function* ({ output }) {
1511
+ yield* absentAsUndefined(api.requestVoid("delete project", (client) => client.POST("/projects/{project_id}/delete", { params: { path: { project_id: output.projectId } } })));
1512
+ })
1513
+ };
1514
+ }));
1515
+ //#endregion
88
1516
  //#region src/Providers.ts
89
1517
  var Providers = class extends Provider.ProviderCollection()("Convex") {};
90
1518
  /**
@@ -98,6 +1526,265 @@ const providers = (credentials = fromConfig()) => Layer.effect(Providers, Provid
98
1526
  LocalDeployment
99
1527
  ])).pipe(Layer.provide(Layer.mergeAll(ProjectProvider(), DeploymentProvider(), LocalDeploymentProvider())), Layer.provide(ManagementApiLive()), Layer.provide(credentials), Layer.orDie);
100
1528
  //#endregion
1529
+ //#region src/store/convex/sealing.ts
1530
+ /** The variable of the store deployment that holds the key `keyId`. */
1531
+ const stateKeyName = (keyId) => `STATE_KEY_${keyId}`;
1532
+ //#endregion
1533
+ //#region src/State.ts
1534
+ /** The name of the state project in each team. */
1535
+ const STORE_PROJECT_NAME = "alchemy-state-store";
1536
+ /** The actions of the key of one run on the store: its writes are actions that seal. */
1537
+ const STORE_KEY_ACTIONS = [...["deployment:functions:runInternalQueries", "deployment:functions:runInternalMutations"], "deployment:functions:runInternalActions"];
1538
+ /** The body of POST /api/function, with HTTP 200 for a function error too. */
1539
+ const Reply = Schema.Union([Schema.Struct({
1540
+ status: Schema.Literal("success"),
1541
+ value: Schema.Unknown
1542
+ }), Schema.Struct({
1543
+ status: Schema.Literal("error"),
1544
+ errorMessage: Schema.String
1545
+ })]);
1546
+ /** The error reply of /api/function for a function that the deployment does not have (recorded). */
1547
+ const MISSING_FUNCTION = /Could not find function for '/;
1548
+ /** HTTP 401 or 403 from the function API: the key is gone or expired (recorded: 403 without a key). */
1549
+ const isUnauthorized = (error) => error.http?.status === 401 || error.http?.status === 403;
1550
+ const failure = (message) => new StateStoreError({ message: `Convex state: ${message}` });
1551
+ /** No reply, HTTP 429, or HTTP 5xx: a new attempt can succeed. Every call of the store is idempotent. */
1552
+ const isTransient = (error) => error.http !== void 0 && (error.http.status === void 0 || error.http.status === 429 || error.http.status >= 500);
1553
+ const post = (url, headers, body) => Effect.tryPromise({
1554
+ try: () => fetch(url, {
1555
+ method: "POST",
1556
+ headers: {
1557
+ "Content-Type": "application/json",
1558
+ ...headers
1559
+ },
1560
+ body: JSON.stringify(body)
1561
+ }),
1562
+ catch: () => new StateStoreError({
1563
+ message: `Convex state: POST ${url} failed`,
1564
+ http: {}
1565
+ })
1566
+ }).pipe(Effect.flatMap((response) => response.ok || response.status === 560 ? Effect.tryPromise({
1567
+ try: () => response.json(),
1568
+ catch: () => failure(`${url} gave no JSON`)
1569
+ }) : Effect.fail(new StateStoreError({
1570
+ message: `Convex state: POST ${url} failed with HTTP ${response.status}`,
1571
+ http: { status: response.status }
1572
+ }))), Effect.retry({
1573
+ while: isTransient,
1574
+ schedule: Schedule.exponential("100 millis").pipe(Schedule.jittered),
1575
+ times: 5
1576
+ }));
1577
+ const decode = (schema, what) => (value) => Schema.decodeUnknownEffect(schema)(value).pipe(Effect.mapError(() => failure(`bad ${what}`)));
1578
+ /** The reply of `state:sealing`. */
1579
+ const Sealing = Schema.Struct({
1580
+ current: Schema.NullOr(Schema.String),
1581
+ sealed: Schema.Boolean
1582
+ });
1583
+ /** The reply of `state:reseal`. */
1584
+ const Resealed = Schema.Struct({ failed: Schema.Array(Schema.String) });
1585
+ const makeFunctionApi = (url, key) => ({ call: (path, args) => post(`${url}/api/function`, { Authorization: `Convex ${Redacted.value(key)}` }, {
1586
+ path,
1587
+ args,
1588
+ format: "json"
1589
+ }).pipe(Effect.flatMap(decode(Reply, `reply of ${path}`))) });
1590
+ /** The value of a reply, or the Convex message, which names the function and the cause, such as a missing key action. */
1591
+ const valueOf = (reply) => reply.status === "success" ? Effect.succeed(reply.value) : Effect.fail(failure(reply.errorMessage.trim()));
1592
+ /** The functions of the store with Alchemy's encoding: the JSON text of encodeState. */
1593
+ const remoteOf = (api) => {
1594
+ const run = (name, args) => api.call(`state:${name}`, args).pipe(Effect.flatMap(valueOf));
1595
+ const strings = (name, args) => run(name, args).pipe(Effect.flatMap(decode(Schema.Array(Schema.String), name)));
1596
+ const optional = (name, args) => run(name, args).pipe(Effect.flatMap(decode(Schema.NullOr(Schema.String), name)));
1597
+ const encode = (value) => JSON.stringify(encodeState(value));
1598
+ return {
1599
+ listStacks: () => strings("stacks", {}),
1600
+ listStages: (stack) => strings("stages", { stack }),
1601
+ list: (r) => strings("list", {
1602
+ stack: r.stack,
1603
+ stage: r.stage
1604
+ }),
1605
+ get: (r) => optional("get", {
1606
+ stack: r.stack,
1607
+ stage: r.stage,
1608
+ fqn: r.fqn
1609
+ }).pipe(Effect.map((text) => text === null ? void 0 : JSON.parse(text, reviveState))),
1610
+ getReplacedResources: (r) => strings("replaced", {
1611
+ stack: r.stack,
1612
+ stage: r.stage
1613
+ }).pipe(Effect.map((texts) => texts.map((text) => JSON.parse(text, reviveState)))),
1614
+ getOutput: (r) => optional("getOutput", {
1615
+ stack: r.stack,
1616
+ stage: r.stage
1617
+ }).pipe(Effect.map((text) => text === null ? void 0 : JSON.parse(text, reviveState))),
1618
+ set: (r) => run("set", {
1619
+ stack: r.stack,
1620
+ stage: r.stage,
1621
+ fqn: r.fqn,
1622
+ value: encode(r.value)
1623
+ }),
1624
+ delete: (r) => run("remove", {
1625
+ stack: r.stack,
1626
+ stage: r.stage,
1627
+ fqn: r.fqn
1628
+ }),
1629
+ deleteStack: (r) => run("removeStack", {
1630
+ stack: r.stack,
1631
+ stage: r.stage
1632
+ }),
1633
+ setOutput: (r) => run("setOutput", {
1634
+ stack: r.stack,
1635
+ stage: r.stage,
1636
+ value: encode(r.value)
1637
+ })
1638
+ };
1639
+ };
1640
+ /** The version that the store answers, or undefined when the deployment has no `state:version`. */
1641
+ const storeVersion = (api) => api.call("state:version", {}).pipe(Effect.flatMap((reply) => reply.status === "error" && MISSING_FUNCTION.test(reply.errorMessage) ? Effect.succeed(void 0) : valueOf(reply).pipe(Effect.flatMap(decode(Schema.Number, "store version")))));
1642
+ /**
1643
+ * The functions directory of the store app, `src/store/convex` of this
1644
+ * package. This file is `src/State.ts` in a checkout and a chunk in `lib/`
1645
+ * in the installed package, which ships `src` too, so the directory is
1646
+ * `../src/store/convex` from either place. Its `convex.config.ts` mounts the
1647
+ * alchemyState component of `src/store/component`, inside the same push root.
1648
+ */
1649
+ const storeDirectory = () => join(dirname(fileURLToPath(import.meta.url)), "..", "src", "store", "convex");
1650
+ /**
1651
+ * Pushes `store` to the production deployment of the state project with the
1652
+ * installed Convex CLI: no typecheck, no codegen, the key only in the
1653
+ * environment of the CLI.
1654
+ */
1655
+ const pushStore = (options, deployment) => Effect.gen(function* () {
1656
+ const cli = yield* installedCli(join(options.store, ".."));
1657
+ yield* Effect.logInfo(`Convex state: pushing the store version 7 to ${deployment.name}`);
1658
+ yield* withPushKey(options.api, deployment.name, PUSH_KEY_ACTIONS, (key) => push(options.spawner, key, {
1659
+ deployment: deployment.name,
1660
+ url: deployment.deploymentUrl,
1661
+ rootDir: join(options.store, ".."),
1662
+ source: {
1663
+ path: options.store,
1664
+ command: [
1665
+ ...cli,
1666
+ "deploy",
1667
+ "--typecheck",
1668
+ "disable",
1669
+ "--codegen",
1670
+ "disable"
1671
+ ]
1672
+ },
1673
+ env: {},
1674
+ previousEnvNames: [],
1675
+ adopt: false,
1676
+ previewName: void 0
1677
+ }));
1678
+ });
1679
+ /**
1680
+ * Finishes the sealing of the store, whatever an earlier run left: a new key when the store has
1681
+ * none, then a reseal unless one finished under the current key. A run reads this each time, so a
1682
+ * run that stopped after a push cannot leave rows in clear text. This client makes a key once, and
1683
+ * it never reads a key back.
1684
+ */
1685
+ const ensureSealed = (options, deployment, functions) => Effect.gen(function* () {
1686
+ const { current, sealed } = yield* functions.call("state:sealing", {}).pipe(Effect.flatMap(valueOf), Effect.flatMap(decode(Sealing, "state:sealing")));
1687
+ if (current === null) {
1688
+ const keyId = newKeyId();
1689
+ yield* withPushKey(options.api, deployment.name, PUSH_KEY_ACTIONS, (key) => writeVariables(deployment.deploymentUrl, key, [{
1690
+ name: stateKeyName(keyId),
1691
+ value: newKey()
1692
+ }]));
1693
+ yield* functions.call("state:chooseKey", { keyId }).pipe(Effect.flatMap(valueOf));
1694
+ }
1695
+ if (sealed) return;
1696
+ const { failed } = yield* functions.call("state:reseal", {}).pipe(Effect.flatMap(valueOf), Effect.flatMap(decode(Resealed, "state:reseal")));
1697
+ if (failed.length > 0) yield* Effect.logWarning(`Convex state: the store could not seal ${failed.join(", ")}. The next run tries again.`);
1698
+ });
1699
+ /**
1700
+ * Creates the state project of the team. Two first runs can both create one:
1701
+ * the run whose project is not the oldest deletes its own, which holds
1702
+ * nothing yet, and uses the oldest, so that every run ends on one store.
1703
+ */
1704
+ const createStoreProject = (api, teamId) => Effect.gen(function* () {
1705
+ yield* Effect.logInfo(`Convex state: creating the project ${STORE_PROJECT_NAME} in team ${teamId}`);
1706
+ const created = yield* createProject(api, teamId, {
1707
+ name: STORE_PROJECT_NAME,
1708
+ deploymentType: "prod",
1709
+ deploymentRegion: void 0
1710
+ });
1711
+ const oldest = (yield* listProjectsByName(api, teamId, STORE_PROJECT_NAME)).reduce((a, b) => b.id < a.id ? b : a, created);
1712
+ if (oldest.id === created.id) return created;
1713
+ yield* Effect.logInfo(`Convex state: another run created ${STORE_PROJECT_NAME} ${oldest.id} first; project ${created.id} is deleted again.`);
1714
+ yield* absentAsUndefined(retryIdempotentWrite(api.requestVoid("delete project", (client) => client.POST("/projects/{project_id}/delete", { params: { path: { project_id: created.id } } }))));
1715
+ return oldest;
1716
+ });
1717
+ /**
1718
+ * The StateService over the `alchemy-state-store` project of the team: found or
1719
+ * created, its store pushed when it is missing or older, and read and
1720
+ * written with the keys of this run.
1721
+ */
1722
+ const makeConvexState = (options) => Effect.gen(function* () {
1723
+ const { api } = options;
1724
+ const teamId = yield* api.teamId;
1725
+ const project = (yield* findProjectByName(api, teamId, "alchemy-state-store")) ?? (yield* createStoreProject(api, teamId));
1726
+ const deployment = yield* prodDeploymentOf(api, project.id);
1727
+ if (deployment === void 0) return yield* new ProductionDeploymentNotFound({ projectId: project.id });
1728
+ const keys = [];
1729
+ yield* Scope.addFinalizer(options.scope, Effect.suspend(() => Effect.forEach(keys, (key) => deleteDeployKey(api, deployment.name, key), { discard: true })));
1730
+ const mint = createDeployKey(api, deployment.name, STORE_PROJECT_NAME, STORE_KEY_ACTIONS).pipe(Effect.map((key) => {
1731
+ keys.push(key);
1732
+ return makeFunctionApi(deployment.deploymentUrl, key);
1733
+ }), Effect.mapError((error) => failure(`no key for ${deployment.name}: ${error.message}`)));
1734
+ let current = yield* mint;
1735
+ const functions = { call: (path, args) => current.call(path, args).pipe(Effect.catchIf(isUnauthorized, () => mint.pipe(Effect.flatMap((next) => {
1736
+ current = next;
1737
+ return next.call(path, args);
1738
+ })))) };
1739
+ let version = yield* storeVersion(functions);
1740
+ if (version === void 0 || version < 7) {
1741
+ 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.`);
1742
+ version = yield* storeVersion(functions);
1743
+ if (version === void 0 || version < 7) {
1744
+ yield* pushStore(options, deployment);
1745
+ version = yield* storeVersion(functions);
1746
+ }
1747
+ }
1748
+ if (version !== 7) return yield* failure(`${deployment.name} answers store version ${version ?? "none"}, and this package needs store version 7.`);
1749
+ yield* ensureSealed(options, deployment, functions);
1750
+ const remote = remoteOf(functions);
1751
+ return {
1752
+ id: "convex",
1753
+ getVersion: () => Effect.succeed(STATE_STORE_VERSION),
1754
+ listStacks: remote.listStacks,
1755
+ listStages: remote.listStages,
1756
+ list: remote.list,
1757
+ get: remote.get,
1758
+ getReplacedResources: remote.getReplacedResources,
1759
+ getOutput: remote.getOutput,
1760
+ set: (request) => remote.set(request).pipe(Effect.as(request.value)),
1761
+ delete: (request) => remote.delete(request).pipe(Effect.asVoid),
1762
+ deleteStack: (request) => remote.deleteStack(request).pipe(Effect.asVoid),
1763
+ setOutput: (request) => remote.setOutput(request).pipe(Effect.as(request.value))
1764
+ };
1765
+ });
1766
+ /**
1767
+ * Alchemy state in the `alchemy-state-store` project of the team of the credential: the team token
1768
+ * in CONVEX_ACCESS_TOKEN, which names its team, or the Convex CLI login, with the team of the
1769
+ * deployment that the CLI selected (CONVEX_DEPLOYMENT, see ManagementApi.teamId). The first use of
1770
+ * the run finds or creates the project and pushes the store when it is missing or older.
1771
+ * `alchemy plan` on another stack never touches Convex.
1772
+ */
1773
+ const state = () => Layer.effect(State, Effect.gen(function* () {
1774
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1775
+ const scope = yield* Scope.Scope;
1776
+ const context = yield* Effect.context();
1777
+ return yield* Effect.cached(Effect.gen(function* () {
1778
+ const api = yield* ManagementApi.pipe(Effect.provide(ManagementApiLive().pipe(Layer.provide(fromConfig()))));
1779
+ return yield* makeConvexState({
1780
+ api,
1781
+ spawner,
1782
+ scope,
1783
+ store: storeDirectory()
1784
+ });
1785
+ }).pipe(Effect.provideContext(context), Effect.orDie));
1786
+ }));
1787
+ //#endregion
101
1788
  export { ACCESS_TOKEN_ENV, AbsoluteRootDir, AmbiguousDeployment, AmbiguousProject, CodePushFailed, ConvexApiError, ConvexAppNotFound, ConvexCliNotFound, CreatedProjectNotFound, Credentials, CredentialsError, DEPLOY_KEY_ENV, Deployment, DeploymentIdentityChange, EnvironmentNeedsDeployKey, LocalDeployment, LocalDeploymentNotFound, ManagementApi, ProductionDeploymentNotFound, Project, ProjectDeploymentChange, ProjectNotFound, ProjectTeamChange, Providers, PushTargetMismatch, RUN_RECORD_KEY, RunRecordError, STORE_PROJECT_NAME, VariablesOwnedBySomeoneElse, bindComponent, fromConfig, fromValues, parseDeployOutput, providers, runRecord, state, withRunRecord };
102
1789
 
103
1790
  //# sourceMappingURL=index.js.map