@samebase/alchemy-convex 0.29.0 → 0.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -39
- package/lib/{HubClient-HeGoVOLO.js → State-t0BZggNl.js} +62 -234
- package/lib/State-t0BZggNl.js.map +1 -0
- package/lib/cli.js +5 -36
- package/lib/cli.js.map +1 -1
- package/lib/index.d.ts +40 -49
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +68 -9
- package/lib/index.js.map +1 -1
- package/package.json +1 -1
- package/src/LocalDeployment.ts +105 -0
- package/src/ManagementApi.ts +81 -104
- package/src/Providers.ts +3 -3
- package/src/SharedHubClient.ts +31 -7
- package/src/cli.ts +7 -56
- package/src/index.ts +5 -7
- package/lib/HubClient-HeGoVOLO.js.map +0 -1
- package/src/HubClient.ts +0 -310
package/README.md
CHANGED
|
@@ -186,16 +186,17 @@ Every run needs the team token in `CONVEX_ACCESS_TOKEN`, or the Convex CLI login
|
|
|
186
186
|
state and the projects are in the team of that credential. A team access token and an OAuth token of
|
|
187
187
|
a team name their team. The Convex CLI login names no team, so the run uses the team of the
|
|
188
188
|
deployment that the Convex CLI selected: `CONVEX_DEPLOYMENT` in the environment or in `.env.local`,
|
|
189
|
-
which `npx convex dev` writes. A local
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
189
|
+
which `npx convex dev` writes. A logged-in local deployment gives the team of its project, from the
|
|
190
|
+
folder's `.convex/local/default/config.json`. An anonymous deployment is in no team, so the run
|
|
191
|
+
stops and asks for a deployment of a project. The first run of a team creates the project
|
|
192
|
+
`alchemy-state-store` and pushes the store functions to its production deployment with the Convex
|
|
193
|
+
CLI of the app; a later version of this package pushes a newer store when it finds an older one. A
|
|
194
|
+
store that is newer than the package fails the run with both versions, so the repositories of a team
|
|
195
|
+
upgrade the package together. Each run makes a deploy key of that deployment that can only run the
|
|
196
|
+
store's internal functions, and deletes it at the end. Rows are in the tables `resources` and
|
|
197
|
+
`outputs` of the component `alchemyState` in the dashboard, under the stack name. The store has no
|
|
198
|
+
lock: run one deploy of a stage at a time, such as with a CI concurrency group. The store and its
|
|
199
|
+
readers (Samebase) are released and upgraded together.
|
|
199
200
|
|
|
200
201
|
Store version 3 supports native subscriptions. A trusted server checks repository access, then calls
|
|
201
202
|
internal `reader:authorize({ repository, subject })` with a deployment credential. It gives the
|
|
@@ -303,20 +304,6 @@ call.
|
|
|
303
304
|
as the build inputs `["src/**", "public/**", "vite.config.ts"]`. A minted key for a command has
|
|
304
305
|
every action, because the command can do more than a push.
|
|
305
306
|
|
|
306
|
-
- `Convex.HubClient`: `{ team, app, redirectUri, deploymentType, clientName, softwareVersion? }`
|
|
307
|
-
registers one deployment as a client of the identity hub of the team. The hub is the production
|
|
308
|
-
deployment of the project `identity-hub`. The resource finds it by name and runs its internal
|
|
309
|
-
functions `identityBroker:renewClient` and `identityBroker:registerClient` with a short-lived key,
|
|
310
|
-
so the stack needs no other credential and no hub address. The first client of an `app` creates
|
|
311
|
-
the app. Outputs `issuer`, `clientId`, `clientSecret`, `redirectUri`, `deploymentType`, and
|
|
312
|
-
`clientName`, which the `env` of the `Convex.Deployment` writes to the deployment.
|
|
313
|
-
- Each deploy renews the client on the hub. A preview or development client expires 14 days after
|
|
314
|
-
its last deploy or use, and a production client never expires. A client that the hub no longer
|
|
315
|
-
has gets a new one in the same run.
|
|
316
|
-
- Another `redirectUri` is a new client, and the old one goes.
|
|
317
|
-
- A destroy deletes a preview or development client. It does nothing to a production client,
|
|
318
|
-
because the production deployment can stay.
|
|
319
|
-
|
|
320
307
|
- `Convex.SharedHubClient`:
|
|
321
308
|
`{ app, redirectUri, deploymentType, initialAccessToken?, softwareVersion? }` gets a client of the
|
|
322
309
|
central identity hub, for an app that deploys in its own GitHub Actions run, on any host, and for
|
|
@@ -344,6 +331,10 @@ call.
|
|
|
344
331
|
values, `status` is `off`, and `issuer`, `clientId`, and `clientSecret` are the `no-hub` values
|
|
345
332
|
of a checkout without a hub. A production or preview run without a GitHub OIDC token, such as on
|
|
346
333
|
a laptop, does the same, and logs no warning.
|
|
334
|
+
- `required: true` makes the run fail unless the hub confirms the client in this run: a refusal, a
|
|
335
|
+
hub that does not answer a registration or a renewal, or a suspended client fails it. Set it
|
|
336
|
+
where sign-in is the product, so a deploy never ships guest sign-in, or a client that the hub
|
|
337
|
+
stopped, with a green run. A failed run saves nothing, and the next run asks the hub again.
|
|
347
338
|
- `status` is `suspended` when the hub suspended the client. The state keeps the client and its
|
|
348
339
|
values, so the client works again when the hub lifts the suspension.
|
|
349
340
|
- `Convex.SharedHubClient.variables(client)` gives `issuer`, `clientId`, and `clientSecret` for
|
|
@@ -357,21 +348,19 @@ call.
|
|
|
357
348
|
because the production deployment can stay.
|
|
358
349
|
- `HUB_URL` replaces `https://auth.samebase.com`, the hub that the run asks at `/hub-clients`.
|
|
359
350
|
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
`RESOURCE_HUB_CLIENT_ID`, and `RESOURCE_HUB_CLIENT_SECRET`, preserving the sign-in client's
|
|
374
|
-
variables. Each callback remains one exact registered URI.
|
|
351
|
+
- `Convex.LocalDeployment`: `{ rootDir?, env }` writes the `env` of the logged-in local deployment
|
|
352
|
+
of the folder `rootDir` (the working directory without it), which
|
|
353
|
+
`npx convex deployment create <team>:<project>:local --select` makes and `npx convex dev` runs.
|
|
354
|
+
Each folder, such as each git worktree, has its own, with its own data. The resource reads the
|
|
355
|
+
deployment's name, ports, and admin key from `.convex/local/default/config.json`, and writes with
|
|
356
|
+
the admin key. It never creates, pushes, or deletes: run the stack while `convex dev` runs. A name
|
|
357
|
+
that leaves `env` is removed. A destroy changes nothing. Outputs `name`, `url`, `siteUrl`, and
|
|
358
|
+
`envNames`.
|
|
359
|
+
- `Convex.LocalDeployment.of(rootDir?)` gives `name`, `url`, and `siteUrl` when the stack's
|
|
360
|
+
program runs, so a client can take the local `siteUrl` for its callback. It throws when the
|
|
361
|
+
folder has no logged-in local deployment, also for an anonymous one.
|
|
362
|
+
- With a `local:` deployment selected in `.env.local`, the Convex CLI login takes the team of the
|
|
363
|
+
project in `config.json`.
|
|
375
364
|
|
|
376
365
|
### The development stage
|
|
377
366
|
|
|
@@ -27,10 +27,10 @@ import { hashDirectory } from "alchemy/Command/Memo";
|
|
|
27
27
|
import * as Clock from "effect/Clock";
|
|
28
28
|
import * as ChildProcess from "effect/process/ChildProcess";
|
|
29
29
|
import * as Stream from "effect/Stream";
|
|
30
|
-
import { fileURLToPath } from "node:url";
|
|
31
|
-
import * as Scope from "effect/Scope";
|
|
32
30
|
import { STATE_STORE_VERSION, State, StateStoreError, encodeState, reviveState } from "alchemy/State";
|
|
33
31
|
import { execFile } from "node:child_process";
|
|
32
|
+
import { fileURLToPath } from "node:url";
|
|
33
|
+
import * as Scope from "effect/Scope";
|
|
34
34
|
//#region src/Credentials.ts
|
|
35
35
|
var Credentials = class extends Context.Service()("@samebase/alchemy-convex/Credentials") {};
|
|
36
36
|
/** Environment variable for the access token, read by {@link fromConfig}. */
|
|
@@ -167,22 +167,49 @@ const retryIdempotentWrite = (effect) => effect.pipe(Effect.retry({
|
|
|
167
167
|
}));
|
|
168
168
|
/** Turns a 404 into `undefined` so read and delete stay idempotent. */
|
|
169
169
|
const absentAsUndefined = (effect) => effect.pipe(Effect.catchIf((error) => error.status === 404, () => Effect.succeed(void 0)));
|
|
170
|
-
const TeamRow = Schema.Struct({
|
|
171
|
-
id: Schema.Number,
|
|
172
|
-
slug: Schema.String
|
|
173
|
-
});
|
|
174
|
-
const TeamRows = Schema.Array(TeamRow);
|
|
175
|
-
/** The first page of GET /teams/{team_id}/projects: every row carries the slug of the team. */
|
|
176
|
-
const ProjectSlugRows = Schema.Struct({ items: Schema.Array(Schema.Struct({ teamSlug: Schema.String })) });
|
|
177
170
|
/** GET /deployments/{name}: the project of the deployment. */
|
|
178
171
|
const DeploymentProject = Schema.Struct({ projectId: Schema.Number });
|
|
179
172
|
/** GET /projects/{id}: the team of the project. */
|
|
180
173
|
const ProjectTeam = Schema.Struct({ teamId: Schema.Number });
|
|
174
|
+
/** A folder's `.convex/local/default/config.json`, as the Convex CLI writes it. */
|
|
175
|
+
const LocalConfig = Schema.Struct({
|
|
176
|
+
deploymentName: Schema.String,
|
|
177
|
+
ports: Schema.Struct({
|
|
178
|
+
cloud: Schema.Number,
|
|
179
|
+
site: Schema.Number
|
|
180
|
+
}),
|
|
181
|
+
adminKey: Schema.String,
|
|
182
|
+
/** The project of a logged-in local deployment. An anonymous one has none. */
|
|
183
|
+
cloudProjectId: Schema.Number
|
|
184
|
+
});
|
|
185
|
+
/**
|
|
186
|
+
* The logged-in local deployment of `rootDir`, which `npx convex deployment create
|
|
187
|
+
* <team>:<project>:local` makes: undefined when the folder has none, or only an anonymous one, which
|
|
188
|
+
* belongs to no project.
|
|
189
|
+
*/
|
|
190
|
+
const readLocalDeployment = (rootDir = ".") => {
|
|
191
|
+
let raw;
|
|
192
|
+
try {
|
|
193
|
+
raw = JSON.parse(readFileSync(join(rootDir, ".convex", "local", "default", "config.json"), "utf8"));
|
|
194
|
+
} catch {
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
const config = Option.getOrUndefined(Schema.decodeUnknownOption(LocalConfig)(raw));
|
|
198
|
+
if (config === void 0 || !config.deploymentName.startsWith("local-")) return void 0;
|
|
199
|
+
return {
|
|
200
|
+
name: config.deploymentName,
|
|
201
|
+
url: `http://127.0.0.1:${config.ports.cloud}`,
|
|
202
|
+
siteUrl: `http://127.0.0.1:${config.ports.site}`,
|
|
203
|
+
projectId: config.cloudProjectId,
|
|
204
|
+
adminKey: Redacted.make(config.adminKey)
|
|
205
|
+
};
|
|
206
|
+
};
|
|
181
207
|
/**
|
|
182
|
-
* The
|
|
183
|
-
* `.env.local` of the working directory, as `npx convex dev` writes it
|
|
184
|
-
*
|
|
185
|
-
*
|
|
208
|
+
* The deployment that the Convex CLI selected: CONVEX_DEPLOYMENT in the environment or in
|
|
209
|
+
* `.env.local` of the working directory, as `npx convex dev` writes it. A cloud deployment
|
|
210
|
+
* (`dev:happy-animal-123`) by its name; a logged-in local deployment (`local:local-team-app`) by the
|
|
211
|
+
* project in the working directory's `.convex/local/default`, when that is the selected one.
|
|
212
|
+
* Undefined when neither has it, and for an anonymous deployment, which is in no project.
|
|
186
213
|
*/
|
|
187
214
|
const selectedDeployment = () => {
|
|
188
215
|
const fromEnv = process.env["CONVEX_DEPLOYMENT"];
|
|
@@ -193,8 +220,19 @@ const selectedDeployment = () => {
|
|
|
193
220
|
return;
|
|
194
221
|
}
|
|
195
222
|
})();
|
|
223
|
+
const localName = /^local:(local-[^:]+)$/.exec(value ?? "")?.[1];
|
|
224
|
+
if (localName !== void 0) {
|
|
225
|
+
const local = readLocalDeployment();
|
|
226
|
+
return local?.name === localName ? {
|
|
227
|
+
kind: "local",
|
|
228
|
+
projectId: local.projectId
|
|
229
|
+
} : void 0;
|
|
230
|
+
}
|
|
196
231
|
const name = /^(?:(?:dev|prod|preview):)?([^:]+)$/.exec(value ?? "")?.[1];
|
|
197
|
-
return name === void 0 || name.startsWith("anonymous-") ? void 0 :
|
|
232
|
+
return name === void 0 || name.startsWith("anonymous-") ? void 0 : {
|
|
233
|
+
kind: "cloud",
|
|
234
|
+
name
|
|
235
|
+
};
|
|
198
236
|
};
|
|
199
237
|
/** GET /token_details: the team of a team token, or the project of a project token. */
|
|
200
238
|
const TokenDetails = Schema.Union([Schema.Struct({
|
|
@@ -215,67 +253,24 @@ const makeService = (source) => {
|
|
|
215
253
|
const requestVoid = (operation, run) => client.pipe(Effect.flatMap((c) => settleVoid(operation, () => run(c))));
|
|
216
254
|
const deploymentRequest = (operation, deploymentUrlOrName, deployKey, run) => settle(operation, () => run(createDeploymentClient(deploymentUrlOrName, Redacted.value(deployKey))));
|
|
217
255
|
const tokenDetails = Effect.runSync(Effect.cached(request("get token details", (c) => c.GET("/token_details")).pipe(Effect.map((body) => Schema.decodeUnknownSync(TokenDetails)(body)), Effect.catchIf((error) => error.status === 403, () => Effect.succeed(void 0)))));
|
|
218
|
-
/** The slug of the team, from the first project of its listing, or undefined for a team without one. Read once. */
|
|
219
|
-
const teamSlug = (teamId) => request("list projects", (c) => c.GET("/teams/{team_id}/projects", { params: { path: { team_id: teamId } } })).pipe(Effect.map((body) => Schema.decodeUnknownSync(ProjectSlugRows)(body).items[0]?.teamSlug));
|
|
220
|
-
const projectTokenError = (projectId) => new ConvexApiError({
|
|
221
|
-
operation: "resolve team",
|
|
222
|
-
status: 403,
|
|
223
|
-
message: `the access token belongs to project ${projectId}, and a project token cannot create projects. Use a team access token.`
|
|
224
|
-
});
|
|
225
256
|
const teamId = Effect.runSync(Effect.cached(Effect.gen(function* () {
|
|
226
257
|
const details = yield* tokenDetails;
|
|
227
258
|
if (details?.type === "teamToken") return details.teamId;
|
|
228
|
-
if (details?.type === "projectToken") return yield*
|
|
259
|
+
if (details?.type === "projectToken") return yield* new ConvexApiError({
|
|
260
|
+
operation: "resolve team",
|
|
261
|
+
status: 403,
|
|
262
|
+
message: `the access token belongs to project ${details.projectId}, and a project token cannot create projects. Use a team access token.`
|
|
263
|
+
});
|
|
229
264
|
const selected = selectedDeployment();
|
|
230
265
|
if (selected === void 0) return yield* new ConvexApiError({
|
|
231
266
|
operation: "resolve team",
|
|
232
267
|
status: 0,
|
|
233
|
-
message: "the Convex CLI login names no team, and no
|
|
268
|
+
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`."
|
|
234
269
|
});
|
|
235
|
-
const
|
|
236
|
-
const { projectId } = Schema.decodeUnknownSync(DeploymentProject)(deployment);
|
|
270
|
+
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;
|
|
237
271
|
const project = yield* request("get project", (c) => c.GET("/projects/{project_id}", { params: { path: { project_id: projectId } } }));
|
|
238
272
|
return Schema.decodeUnknownSync(ProjectTeam)(project).teamId;
|
|
239
273
|
})));
|
|
240
|
-
const resolveTeamId = (team) => Effect.gen(function* () {
|
|
241
|
-
if (typeof team === "number") return team;
|
|
242
|
-
if (/^\d+$/.test(team)) return Number(team);
|
|
243
|
-
const details = yield* tokenDetails;
|
|
244
|
-
if (details?.type === "teamToken") {
|
|
245
|
-
const slug = yield* teamSlug(details.teamId);
|
|
246
|
-
if (slug === void 0) return yield* new ConvexApiError({
|
|
247
|
-
operation: "resolve team",
|
|
248
|
-
status: 0,
|
|
249
|
-
message: `team "${team}" cannot be checked against the access token: team ${details.teamId} has no project yet. Set team to ${details.teamId}.`
|
|
250
|
-
});
|
|
251
|
-
if (slug !== team) return yield* new ConvexApiError({
|
|
252
|
-
operation: "resolve team",
|
|
253
|
-
status: 403,
|
|
254
|
-
message: `the access token belongs to team ${details.teamId} ("${slug}"), and team is "${team}". Use a token of "${team}", or set team to ${details.teamId}.`
|
|
255
|
-
});
|
|
256
|
-
return details.teamId;
|
|
257
|
-
}
|
|
258
|
-
if (details?.type === "projectToken") return yield* projectTokenError(details.projectId);
|
|
259
|
-
const resolved = yield* credentials;
|
|
260
|
-
const match = (yield* Effect.tryPromise({
|
|
261
|
-
try: async () => {
|
|
262
|
-
const response = await fetch("https://api.convex.dev/api/dashboard/teams", { headers: { Authorization: `Bearer ${Redacted.value(resolved.accessToken)}` } });
|
|
263
|
-
if (!response.ok) throw new Error(`team lookup for "${team}" failed with HTTP ${response.status}`);
|
|
264
|
-
return Schema.decodeUnknownSync(TeamRows)(await response.json());
|
|
265
|
-
},
|
|
266
|
-
catch: (cause) => new ConvexApiError({
|
|
267
|
-
operation: "resolve team",
|
|
268
|
-
status: 0,
|
|
269
|
-
message: cause instanceof Error ? cause.message : String(cause)
|
|
270
|
-
})
|
|
271
|
-
})).find((row) => row.slug === team);
|
|
272
|
-
if (match === void 0) return yield* new ConvexApiError({
|
|
273
|
-
operation: "resolve team",
|
|
274
|
-
status: 404,
|
|
275
|
-
message: `no team with slug "${team}" for this token`
|
|
276
|
-
});
|
|
277
|
-
return match.id;
|
|
278
|
-
});
|
|
279
274
|
const isCredentialToken = (secret) => credentials.pipe(Effect.map((resolved) => tokenPart(Redacted.value(resolved.accessToken)) === tokenPart(secret)));
|
|
280
275
|
const isOAuthCredential = credentials.pipe(Effect.map((resolved) => /^(team|project):/.test(Redacted.value(resolved.accessToken))));
|
|
281
276
|
const withToken = (token) => makeService(Effect.succeed({
|
|
@@ -287,7 +282,6 @@ const makeService = (source) => {
|
|
|
287
282
|
requestVoid,
|
|
288
283
|
deploymentRequest,
|
|
289
284
|
teamId,
|
|
290
|
-
resolveTeamId,
|
|
291
285
|
isCredentialToken,
|
|
292
286
|
isOAuthCredential,
|
|
293
287
|
withToken
|
|
@@ -1554,14 +1548,8 @@ const stateKeyName = (keyId) => `STATE_KEY_${keyId}`;
|
|
|
1554
1548
|
//#region src/State.ts
|
|
1555
1549
|
/** The name of the state project in each team. */
|
|
1556
1550
|
const STORE_PROJECT_NAME = "alchemy-state-store";
|
|
1557
|
-
/**
|
|
1558
|
-
* The actions of the key of one run: the internal queries and mutations of
|
|
1559
|
-
* the store, nothing else. Measured: `deployment:data:view` and
|
|
1560
|
-
* `deployment:data:write` do not run an internal function.
|
|
1561
|
-
*/
|
|
1562
|
-
const RUN_KEY_ACTIONS = ["deployment:functions:runInternalQueries", "deployment:functions:runInternalMutations"];
|
|
1563
1551
|
/** The actions of the key of one run on the store: its writes are actions that seal. */
|
|
1564
|
-
const STORE_KEY_ACTIONS = [...
|
|
1552
|
+
const STORE_KEY_ACTIONS = [...["deployment:functions:runInternalQueries", "deployment:functions:runInternalMutations"], "deployment:functions:runInternalActions"];
|
|
1565
1553
|
/** The body of POST /api/function, with HTTP 200 for a function error too. */
|
|
1566
1554
|
const Reply = Schema.Union([Schema.Struct({
|
|
1567
1555
|
status: Schema.Literal("success"),
|
|
@@ -1850,166 +1838,6 @@ const state = () => Layer.effect(State, Effect.gen(function* () {
|
|
|
1850
1838
|
}).pipe(Effect.provideContext(context), Effect.orDie));
|
|
1851
1839
|
}));
|
|
1852
1840
|
//#endregion
|
|
1853
|
-
|
|
1854
|
-
/** The name of the project of the hub in each team. */
|
|
1855
|
-
const HUB_PROJECT_NAME = "identity-hub";
|
|
1856
|
-
const HubClient = Resource("IdentityHub.Client");
|
|
1857
|
-
/** The hub of the team could not do the call. The reason is the Convex message: it holds no secret. */
|
|
1858
|
-
var HubClientFailed = class extends Schema.TaggedError()("HubClientFailed", {
|
|
1859
|
-
team: Schema.Union([Schema.String, Schema.Number]),
|
|
1860
|
-
reason: Schema.String
|
|
1861
|
-
}) {
|
|
1862
|
-
get message() {
|
|
1863
|
-
return `Convex.HubClient: the hub of team ${this.team}: ${this.reason}.`;
|
|
1864
|
-
}
|
|
1865
|
-
};
|
|
1866
|
-
/** The reply of `identityBroker:registerClient`. */
|
|
1867
|
-
const Registered = Schema.Struct({
|
|
1868
|
-
issuer: Schema.NonEmptyString,
|
|
1869
|
-
clientId: Schema.NonEmptyString,
|
|
1870
|
-
clientSecret: Schema.NonEmptyString
|
|
1871
|
-
});
|
|
1872
|
-
/** The reply of `identityBroker:renewClient`: false when the hub no longer has the client. */
|
|
1873
|
-
const Renewed = Schema.Boolean;
|
|
1874
|
-
/** Runs `use` with the function API of the hub of `team`, with a key of this call only. */
|
|
1875
|
-
const withHub = (api, team, use) => Effect.gen(function* () {
|
|
1876
|
-
const teamId = yield* api.resolveTeamId(team);
|
|
1877
|
-
const project = yield* findProjectByName(api, teamId, HUB_PROJECT_NAME);
|
|
1878
|
-
if (project === void 0) return yield* new HubClientFailed({
|
|
1879
|
-
team,
|
|
1880
|
-
reason: `no project ${HUB_PROJECT_NAME}, which holds the hub`
|
|
1881
|
-
});
|
|
1882
|
-
const deployment = yield* prodDeploymentOf(api, project.id);
|
|
1883
|
-
if (deployment === void 0) return yield* new HubClientFailed({
|
|
1884
|
-
team,
|
|
1885
|
-
reason: `project ${HUB_PROJECT_NAME} has no production deployment`
|
|
1886
|
-
});
|
|
1887
|
-
return yield* withPushKey(api, deployment.name, RUN_KEY_ACTIONS, (key) => use(makeFunctionApi(deployment.deploymentUrl, key)));
|
|
1888
|
-
});
|
|
1889
|
-
/** One internal function of the hub: its value, or the Convex message as an error. */
|
|
1890
|
-
const runHub = (functions, team, name, args) => functions.call(`identityBroker:${name}`, args).pipe(Effect.mapError((error) => new HubClientFailed({
|
|
1891
|
-
team,
|
|
1892
|
-
reason: error.message
|
|
1893
|
-
})), Effect.flatMap((reply) => reply.status === "success" ? Effect.succeed(reply.value) : Effect.fail(new HubClientFailed({
|
|
1894
|
-
team,
|
|
1895
|
-
reason: reply.errorMessage.trim()
|
|
1896
|
-
}))));
|
|
1897
|
-
/**
|
|
1898
|
-
* Registers one client, which expires unless it is a production client. An
|
|
1899
|
-
* attempt that a lost reply repeats leaves one spare client on the hub, which
|
|
1900
|
-
* signs nobody in, and which the hub deletes after 14 days.
|
|
1901
|
-
*/
|
|
1902
|
-
const registerHubClient = (api, props) => withHub(api, props.team, (functions) => runHub(functions, props.team, "registerClient", {
|
|
1903
|
-
appId: props.app,
|
|
1904
|
-
redirectUri: props.redirectUri,
|
|
1905
|
-
deploymentType: props.deploymentType,
|
|
1906
|
-
clientName: props.clientName,
|
|
1907
|
-
softwareVersion: props.softwareVersion ?? "unknown",
|
|
1908
|
-
tokenEndpointAuthMethod: "client_secret_post",
|
|
1909
|
-
expires: true
|
|
1910
|
-
})).pipe(Effect.flatMap((value) => Schema.decodeUnknownEffect(Registered)(value).pipe(Effect.mapError(() => new HubClientFailed({
|
|
1911
|
-
team: props.team,
|
|
1912
|
-
reason: "registerClient gave no client"
|
|
1913
|
-
})))), Effect.map(({ issuer, clientId, clientSecret }) => ({
|
|
1914
|
-
issuer,
|
|
1915
|
-
clientId,
|
|
1916
|
-
clientSecret: Redacted.make(clientSecret)
|
|
1917
|
-
})));
|
|
1918
|
-
/**
|
|
1919
|
-
* Renews one client: true while the hub has it. A preview or development client
|
|
1920
|
-
* then expires 14 days after this call.
|
|
1921
|
-
*/
|
|
1922
|
-
const renewHubClient = (api, team, clientId) => withHub(api, team, (functions) => runHub(functions, team, "renewClient", {
|
|
1923
|
-
clientId,
|
|
1924
|
-
expires: true
|
|
1925
|
-
})).pipe(Effect.flatMap((value) => Schema.decodeUnknownEffect(Renewed)(value).pipe(Effect.mapError(() => new HubClientFailed({
|
|
1926
|
-
team,
|
|
1927
|
-
reason: "renewClient gave no answer"
|
|
1928
|
-
})))));
|
|
1929
|
-
/**
|
|
1930
|
-
* Renews a client whose values the caller holds: false only when the hub answers that the client is
|
|
1931
|
-
* gone. Any other failure, such as a hub or a Convex API that cannot answer, keeps the client and
|
|
1932
|
-
* warns, so an outage never stops a deploy or a dev start; the next one renews it.
|
|
1933
|
-
*/
|
|
1934
|
-
const renewOrKeep = (api, team, clientId) => renewHubClient(api, team, clientId).pipe(Effect.catch((error) => Effect.logWarning(`Convex.HubClient: ${clientId} keeps its saved values, because the hub could not renew it: ${error.message}`).pipe(Effect.as(true))));
|
|
1935
|
-
const unregister = (api, team, clientId) => withHub(api, team, (functions) => runHub(functions, team, "deleteClient", { clientId }));
|
|
1936
|
-
/** True when the client in state serves the redirect URI and deployment type of `props`. */
|
|
1937
|
-
const registeredFor = (output, props) => output.redirectUri === props.redirectUri && output.deploymentType === props.deploymentType;
|
|
1938
|
-
const HubClientProvider = () => Provider.effect(HubClient, Effect.gen(function* () {
|
|
1939
|
-
const api = yield* ManagementApi;
|
|
1940
|
-
return {
|
|
1941
|
-
diff: ({ news }) => Effect.succeed(isResolved(news) ? { action: "update" } : void 0),
|
|
1942
|
-
read: ({ output }) => Effect.succeed(output),
|
|
1943
|
-
reconcile: Effect.fn(function* ({ news, output }) {
|
|
1944
|
-
const saved = output !== void 0 && registeredFor(output, news) ? output : void 0;
|
|
1945
|
-
if (saved !== void 0 && (yield* renewOrKeep(api, news.team, saved.clientId))) return saved;
|
|
1946
|
-
const client = yield* registerHubClient(api, news);
|
|
1947
|
-
if (output !== void 0 && saved === void 0) yield* unregister(api, news.team, output.clientId).pipe(Effect.catchTag("HubClientFailed", (error) => Effect.logWarning(`Client ${output.clientId} stays on the hub: ${error.message} Delete it with \`npx convex run --prod identityBroker:deleteClient\`.`)));
|
|
1948
|
-
return {
|
|
1949
|
-
...client,
|
|
1950
|
-
redirectUri: news.redirectUri,
|
|
1951
|
-
deploymentType: news.deploymentType,
|
|
1952
|
-
clientName: news.clientName
|
|
1953
|
-
};
|
|
1954
|
-
}),
|
|
1955
|
-
delete: ({ olds, output }) => output.deploymentType === "production" ? Effect.void : unregister(api, olds.team, output.clientId).pipe(Effect.asVoid)
|
|
1956
|
-
};
|
|
1957
|
-
}));
|
|
1958
|
-
/**
|
|
1959
|
-
* `alchemy-convex hub-client`: a stack deploys production and previews, and this covers the
|
|
1960
|
-
* development deployment, which no stack deploys. Run it at each dev start: it renews the client
|
|
1961
|
-
* that the three variables name, so the client expires 14 days after the last dev start or use. A
|
|
1962
|
-
* deployment without all three variables, or whose client the hub no longer has, such as one with
|
|
1963
|
-
* the `no-hub` values, gets a new client. Answers the callback URL of a new client, or undefined
|
|
1964
|
-
* for a renewal. The secret reaches the Convex CLI on standard input, never in its arguments.
|
|
1965
|
-
*/
|
|
1966
|
-
const registerDevelopmentClient = (options) => Effect.gen(function* () {
|
|
1967
|
-
const { convex } = options;
|
|
1968
|
-
const api = yield* ManagementApi;
|
|
1969
|
-
const envPrefix = options.envPrefix ?? "HUB";
|
|
1970
|
-
const variables = [
|
|
1971
|
-
`${envPrefix}_ISSUER`,
|
|
1972
|
-
`${envPrefix}_CLIENT_ID`,
|
|
1973
|
-
`${envPrefix}_CLIENT_SECRET`
|
|
1974
|
-
];
|
|
1975
|
-
const names = convex([
|
|
1976
|
-
"env",
|
|
1977
|
-
"list",
|
|
1978
|
-
"--names-only"
|
|
1979
|
-
]).split("\n");
|
|
1980
|
-
if (variables.every((name) => names.includes(name))) {
|
|
1981
|
-
const clientId = convex([
|
|
1982
|
-
"env",
|
|
1983
|
-
"get",
|
|
1984
|
-
`${envPrefix}_CLIENT_ID`
|
|
1985
|
-
]);
|
|
1986
|
-
if (yield* renewOrKeep(api, options.team, clientId)) return void 0;
|
|
1987
|
-
}
|
|
1988
|
-
const siteUrl = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.String))(convex([
|
|
1989
|
-
"run",
|
|
1990
|
-
"--inline-query",
|
|
1991
|
-
"process.env.CONVEX_SITE_URL"
|
|
1992
|
-
])).pipe(Effect.mapError(() => new HubClientFailed({
|
|
1993
|
-
team: options.team,
|
|
1994
|
-
reason: "no CONVEX_SITE_URL to register"
|
|
1995
|
-
})));
|
|
1996
|
-
const callbackUrl = `${siteUrl.replace(/\/$/, "")}${options.callbackPath}`;
|
|
1997
|
-
const client = yield* registerHubClient(api, {
|
|
1998
|
-
team: options.team,
|
|
1999
|
-
app: options.app,
|
|
2000
|
-
redirectUri: callbackUrl,
|
|
2001
|
-
deploymentType: "development",
|
|
2002
|
-
clientName: "development",
|
|
2003
|
-
softwareVersion: new URL(siteUrl).host
|
|
2004
|
-
});
|
|
2005
|
-
convex([
|
|
2006
|
-
"env",
|
|
2007
|
-
"set",
|
|
2008
|
-
"--force"
|
|
2009
|
-
], `${envPrefix}_ISSUER='${client.issuer}'\n${envPrefix}_CLIENT_ID='${client.clientId}'\n${envPrefix}_CLIENT_SECRET='${Redacted.value(client.clientSecret)}'\n`);
|
|
2010
|
-
return callbackUrl;
|
|
2011
|
-
});
|
|
2012
|
-
//#endregion
|
|
2013
|
-
export { PushTargetMismatch as A, DEPLOY_KEY_ENV as B, DeploymentProvider as C, ConvexAppNotFound as D, CodePushFailed as E, ManagementApi as F, fromValues as H, ManagementApiLive as I, ACCESS_TOKEN_ENV as L, installedCli as M, parseDeployOutput as N, ConvexCliNotFound as O, ConvexApiError as P, Credentials as R, DeploymentIdentityChange as S, ProductionDeploymentNotFound as T, fromConfig as V, ProjectProvider as _, registerDevelopmentClient as a, AmbiguousDeployment as b, RUN_RECORD_KEY as c, withRunRecord as d, AmbiguousProject as f, ProjectNotFound as g, ProjectDeploymentChange as h, HubClientProvider as i, VariablesOwnedBySomeoneElse as j, EnvironmentNeedsDeployKey as k, RunRecordError as l, Project as m, HubClient as n, STORE_PROJECT_NAME as o, CreatedProjectNotFound as p, HubClientFailed as r, state as s, HUB_PROJECT_NAME as t, runRecord as u, ProjectTeamChange as v, DeploymentResource as w, Deployment as x, AbsoluteRootDir as y, CredentialsError as z };
|
|
1841
|
+
export { ManagementApi as A, ConvexCliNotFound as C, parseDeployOutput as D, VariablesOwnedBySomeoneElse as E, CredentialsError as F, DEPLOY_KEY_ENV as I, fromConfig as L, readLocalDeployment as M, ACCESS_TOKEN_ENV as N, push as O, Credentials as P, fromValues as R, ConvexAppNotFound as S, PushTargetMismatch as T, DeploymentIdentityChange as _, runRecord as a, ProductionDeploymentNotFound as b, CreatedProjectNotFound as c, ProjectNotFound as d, ProjectProvider as f, Deployment as g, AmbiguousDeployment as h, RunRecordError as i, ManagementApiLive as j, ConvexApiError as k, Project as l, AbsoluteRootDir as m, state as n, withRunRecord as o, ProjectTeamChange as p, RUN_RECORD_KEY as r, AmbiguousProject as s, STORE_PROJECT_NAME as t, ProjectDeploymentChange as u, DeploymentProvider as v, EnvironmentNeedsDeployKey as w, CodePushFailed as x, DeploymentResource as y };
|
|
2014
1842
|
|
|
2015
|
-
//# sourceMappingURL=
|
|
1843
|
+
//# sourceMappingURL=State-t0BZggNl.js.map
|