@samebase/alchemy-convex 0.39.1 → 0.40.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -240,7 +240,8 @@ stage output of any state layer, `Convex.state()` or `Cloudflare.state()`: the d
240
240
  `setOutput` stores is the stack's output plus the key `samebase.run`. Samebase shows a stage only
241
241
  when its output has this record. On GitHub Actions the record comes from the run's variables and the
242
242
  event payload; on a development machine from git, which needs a branch and an `origin` remote. It
243
- holds no secret.
243
+ holds no secret. The function comes from `@samebase/alchemy-kit/run-record` and works over any state
244
+ layer.
244
245
 
245
246
  ```json
246
247
  {
@@ -373,10 +374,13 @@ resources and output, from the store function `state:readStack({ stack })` in on
373
374
  - A destroy deletes a preview or development client. It does nothing to a production client,
374
375
  because the production deployment can stay.
375
376
  - `hub` is the identity hub to register at, required: `{ issuer }`, such as
376
- `{ issuer: "https://id.samebase.com" }`. The run asks at `<issuer>/hub-clients` with a GitHub
377
- token whose audience is the issuer, and the answer must name that issuer. A client is renewed
378
- only at the hub that issued it: a changed hub registers a new client there, and the old one
379
- stays at the old hub.
377
+ `{ issuer: "https://id.samebase.com" }`. The run registers at `<issuer>/register`, the client
378
+ registration endpoint of RFC 7591, with a GitHub token whose audience is the issuer, and the
379
+ answer must name that issuer. The request sends `redirect_uris`, `software_id` (the app name),
380
+ `software_version`, `token_endpoint_auth_method` (`client_secret_post`), and the hub's own
381
+ `connectors`. The hub must run `@samebase/identity-broker` 0.33.0 or later. An earlier hub
382
+ answers 404, and the client gets the off values. A client is renewed only at the hub that issued
383
+ it: a changed hub registers a new client there, and the old one stays at the old hub.
380
384
 
381
385
  - `Convex.LocalDeployment`: `{ rootDir?, env }` writes the `env` of the logged-in local deployment
382
386
  of the folder `rootDir` (the working directory without it), which
@@ -100,7 +100,10 @@ var IdentityHubClientFailed = class extends Schema.TaggedError()("IdentityHubCli
100
100
  }
101
101
  };
102
102
  const OidcToken = Schema.Struct({ value: Schema.NonEmptyString });
103
- /** The 201 answer of `POST /hub-clients`. */
103
+ /**
104
+ * The 201 answer of `POST /register` (RFC 7591 section 3.2.1), in the members that this file reads.
105
+ * The decoder ignores the other members, such as `software_id`, whose full form the hub writes.
106
+ */
104
107
  const NewClient = Schema.Struct({
105
108
  issuer: Schema.NonEmptyString,
106
109
  client_id: Schema.NonEmptyString,
@@ -114,17 +117,23 @@ const NewClient = Schema.Struct({
114
117
  initial_access_token: Schema.optionalKey(Schema.NonEmptyString),
115
118
  repository: Schema.optionalKey(Schema.String.check(Schema.isPattern(/^\d+$/)))
116
119
  });
117
- /** The other answers of `POST /hub-clients`, by status. */
120
+ /** The other answers of `POST /register`, by status. A 401 can have no body (RFC 6750). */
118
121
  const REFUSALS = {
119
- 400: "the identity hub refused the request: one to eight return addresses, each https on a DNS name, and the app name at most 64 characters",
122
+ 400: "the identity hub refused the client metadata, such as the app name",
120
123
  401: "the identity hub refused the GitHub OIDC token",
121
- 403: "the identity hub does not allow this repository or return address",
122
- 404: "the identity hub has no /hub-clients",
124
+ 403: "the identity hub does not allow this repository",
125
+ 404: "the identity hub has no /register: it runs an identity-broker before 0.33.0",
123
126
  429: "the identity hub limits new clients",
124
- 502: "GitHub's keys are not available to the identity hub"
127
+ 502: "GitHub's keys are not available to the identity hub",
128
+ 503: "the identity hub could not apply its policy"
125
129
  };
126
- /** The reasons of a 403 that a log line shows. Any other text of the answer is never logged. */
127
- const NOT_ALLOWED = /* @__PURE__ */ new Map([
130
+ /** The text of an `invalid_redirect_uri` 400 without a known reason. */
131
+ const BAD_REDIRECT_URIS = "the identity hub refused the return addresses: one to eight, each https on a DNS name, or http on a loopback host for a development client";
132
+ /**
133
+ * The reasons of a 400 or a 403 that a log line shows. Any other text of the answer is never
134
+ * logged.
135
+ */
136
+ const REASONS = /* @__PURE__ */ new Map([
128
137
  ["paused", "this app is paused on the identity hub"],
129
138
  ["run_not_allowed", "the identity hub gives clients only to runs of main and of pull requests"],
130
139
  ["blocked", "Samebase blocked this repository or its owner"],
@@ -136,7 +145,8 @@ const NOT_ALLOWED = /* @__PURE__ */ new Map([
136
145
  ["verification_file_missing", "the host of the return address does not serve /samebase-verification.json"],
137
146
  ["verification_file_invalid", "/samebase-verification.json on the host holds no repository id"],
138
147
  ["repository_mismatch", "/samebase-verification.json on the host names another repository"],
139
- ["app_mismatch", "the initial access token belongs to another app on the identity hub"]
148
+ ["app_mismatch", "the initial access token belongs to another app on the identity hub"],
149
+ ["stale_proof", "the identity hub took a newer GitHub OIDC token of this repository"]
140
150
  ]);
141
151
  /** The windows of a 429, by the name that the answer gives. */
142
152
  const RATE_LIMITED = /* @__PURE__ */ new Map([
@@ -145,16 +155,18 @@ const RATE_LIMITED = /* @__PURE__ */ new Map([
145
155
  ["new_owners", "the identity hub takes at most 50 new owners an hour"]
146
156
  ]);
147
157
  const Refusal = Schema.Struct({ reason: Schema.String });
158
+ const InvalidRedirectUri = Schema.Struct({ error: Schema.Literal("invalid_redirect_uri") });
148
159
  const RateLimited = Schema.Struct({ window: Schema.String });
149
160
  /** A 400 for a connector the hub does not offer or allow, with the names it allows. */
150
161
  const InvalidConnectors = Schema.Struct({
151
- error: Schema.Literal("invalid_connectors"),
162
+ reason: Schema.Literal("invalid_connectors"),
152
163
  allowed: Schema.Array(Schema.String)
153
164
  });
154
165
  /**
155
- * The text of a refusal: a known reason of a 403 or window of a 429, the allowed connectors of an
156
- * `invalid_connectors` 400 (only names of the connector grammar, so no other text of the answer is
157
- * printed), else the text of its status.
166
+ * The text of a refusal: a known reason of a 400 or a 403, or window of a 429, the allowed
167
+ * connectors of an `invalid_connectors` 400 (only names of the connector grammar, so no other text
168
+ * of the answer is printed), the text of an `invalid_redirect_uri` 400, else the text of its
169
+ * status. `body` is undefined for an answer without JSON, such as a bare 401.
158
170
  */
159
171
  const refusalOf = (status, body) => {
160
172
  const decoded = (schema) => Option.getOrUndefined(Schema.decodeUnknownOption(schema)(body));
@@ -162,9 +174,9 @@ const refusalOf = (status, body) => {
162
174
  switch (status) {
163
175
  case 400: {
164
176
  const allowed = decoded(InvalidConnectors)?.allowed.filter((name) => CONNECTOR_NAME.test(name));
165
- return allowed === void 0 ? ofStatus() : `the identity hub does not offer or allow one of the connectors; it allows ${allowed.length === 0 ? "none for this app" : allowed.join(", ")}`;
177
+ return allowed === void 0 ? REASONS.get(decoded(Refusal)?.reason ?? "") ?? (decoded(InvalidRedirectUri) === void 0 ? ofStatus() : BAD_REDIRECT_URIS) : `the identity hub does not offer or allow one of the connectors; it allows ${allowed.length === 0 ? "none for this app" : allowed.join(", ")}`;
166
178
  }
167
- case 403: return NOT_ALLOWED.get(decoded(Refusal)?.reason ?? "") ?? ofStatus();
179
+ case 403: return REASONS.get(decoded(Refusal)?.reason ?? "") ?? ofStatus();
168
180
  case 429: return RATE_LIMITED.get(decoded(RateLimited)?.window ?? "") ?? ofStatus();
169
181
  default: return ofStatus();
170
182
  }
@@ -197,17 +209,23 @@ const readOidcToken = (requestUrl, requestToken, audience) => Effect.gen(functio
197
209
  if (status !== 200) return yield* new IdentityHubClientFailed({ reason: `GitHub gave no OIDC token (HTTP ${status})` });
198
210
  return (yield* decode(OidcToken, "GitHub")(body)).value;
199
211
  });
200
- /** `POST /hub-clients` with `bearer`: the GitHub OIDC token, or the app's initial access token. */
212
+ /**
213
+ * `POST /register`, the client registration request of RFC 7591, with `bearer` as its initial
214
+ * access token: the GitHub OIDC token, or the app's own token. `software_id` is the app's name, and
215
+ * `connectors` is the hub's own metadata field. Convex Auth posts the client's secret in the body
216
+ * at the token endpoint, so the client registers that method.
217
+ */
201
218
  const requestNewClient = (props, enrollment, bearer) => Effect.gen(function* () {
202
219
  const { hub } = props;
203
220
  const { app, connectors, redirectUris } = enrollment;
204
- const { body, status } = yield* send("The identity hub", `${hub.issuer}/hub-clients`, bearer, {
221
+ const { body, status } = yield* send("The identity hub", `${hub.issuer}/register`, bearer, {
205
222
  method: "POST",
206
223
  body: JSON.stringify({
207
- app,
208
- redirectUris,
209
- softwareVersion: props.softwareVersion ?? "unknown",
210
- connectors
224
+ redirect_uris: redirectUris,
225
+ software_id: app,
226
+ software_version: props.softwareVersion ?? "unknown",
227
+ connectors,
228
+ token_endpoint_auth_method: "client_secret_post"
211
229
  })
212
230
  });
213
231
  if (status !== 201) return yield* new IdentityHubClientFailed({ reason: `${status === 401 && props.deploymentType === "development" ? "the identity hub refused the initial access token" : refusalOf(status, body)} (HTTP ${status})` });
@@ -348,4 +366,4 @@ const ClientProvider = () => Provider.succeed(Client, {
348
366
  //#endregion
349
367
  export { ClientProvider as n, defaultApp as r, Client as t };
350
368
 
351
- //# sourceMappingURL=IdentityHub-B3Awt5KE.js.map
369
+ //# sourceMappingURL=IdentityHub-lx5BPjOS.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"IdentityHub-lx5BPjOS.js","names":[],"sources":["../src/IdentityHub.ts"],"sourcesContent":["// IdentityHub.Client: one deployment of an app as a client of the identity hub that the stack\n// names, for an app that deploys in its own GitHub Actions run, on any host, and in development as a\n// stage of the same stack. Import it as\n// `import * as IdentityHub from \"@samebase/alchemy-convex/identity-hub\"`; `Convex.providers()`\n// registers its provider.\n//\n// A run in GitHub Actions asks the hub for a new client with a GitHub OIDC token, so the stack needs\n// no key and no Samebase account. The token names the repository. The hub reads\n// `/samebase-verification.json` at the origin of the return address, which must name the same\n// repository, and registers the client on that address. The answer holds the client's own\n// registration access token (RFC 7591), and each later deploy reads the client on the hub with that\n// token (RFC 7592). The hub keeps only hashes, so the state is the only record of the secret and the\n// token.\n//\n// The answer to a production registration also holds the app's initial access token (RFC 7591\n// section 1.2) and the repository id. The state of stage `prod` keeps them. A development checkout\n// runs the stack as a stage `dev-<name>`: it reads them with `IdentityHub.Client.read`, and a client\n// with `deploymentType: \"development\"` asks the hub with the token in place of the GitHub token\n// (RFC 133).\n//\n// A client is enrolled in the connectors it signs in through, such as `google` and `github`, at\n// registration (RFC 137), and holds the return addresses its requests may name, one per handler of\n// the app, such as the sign-in callback and the connections callback. The hub records both sets on\n// the client and never changes them: a stack with another set registers a new client.\n//\n// The app is the stack: its name on the hub defaults to the stack's path in the repository, as the\n// state store groups stacks (`owner/repo/<path>`), and `app` for a stack named after the repository.\n// `app` overrides it. The name groups the clients, their budgets, and the initial access token; it\n// plays no part in user ids, which the hub derives from the provider's own id.\n//\n// A push removes a variable that a deploy stops passing, so a failure here must not drop working\n// variables or stop the deploy. A renewal that fails keeps the saved values. Only a client that\n// cannot work asks for a new one: it is gone, or it has another app name, return address set, type,\n// or connector set. If that request fails, the run gives the off values, so the app has guest\n// sign-in and not a broken button. The off values are the `no-hub` variables of a checkout without\n// a hub: Convex needs the variables, and the app hides the button for this client ID.\n//\n// No text in this file quotes an answer or a fetch error, so no log line can hold a secret. The one\n// exception is the connector names of an `invalid_connectors` refusal, each checked against the\n// grammar of a connector name before it is printed.\nimport { Resource } from \"alchemy\";\nimport { isResolved } from \"alchemy/Diff\";\nimport * as Output from \"alchemy/Output\";\nimport * as Provider from \"alchemy/Provider\";\nimport { Stack } from \"alchemy/Stack\";\nimport { State } from \"alchemy/State\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Redacted from \"effect/Redacted\";\nimport * as Schema from \"effect/Schema\";\nimport type { Providers } from \"./Providers.ts\";\n\n/** A hung service must not hold a deploy: the time limit of one request. */\nconst REQUEST_TIMEOUT_MS = 30_000;\n\n/** The variables of a deployment without a hub client, as the starter writes them. */\nconst OFF_VALUES = { issuer: \"http://127.0.0.1:1\", clientId: \"no-hub\", clientSecret: \"no-hub\" };\n\n/** The name of a connector on the hub. */\nconst CONNECTOR_NAME = /^[a-z0-9-]{1,64}$/;\n\n/** The return addresses of one client, as the hub caps them. */\nconst MAX_REDIRECT_URIS = 8;\n/** The app's name, as the hub caps it. A deeper stack path needs an explicit `app`. */\nconst MAX_APP_LENGTH = 64;\n\n/**\n * The app's default name: the stack's path below `owner/repo`, or `app` for a stack named after\n * the repository. Undefined for a stack whose name is not `owner/repo` or `owner/repo/<path>`.\n */\nexport const defaultApp = (stackName: string): string | undefined => {\n const segments = stackName.split(\"/\");\n if (segments.length < 2 || segments.some((segment) => segment === \"\")) {\n return undefined;\n }\n return segments.slice(2).join(\"/\") || \"app\";\n};\n\n/**\n * An identity hub of @samebase/identity-broker, such as Samebase's public hub:\n * `{ issuer: \"https://id.samebase.com\" }`.\n */\nexport interface Hub {\n /**\n * The hub's issuer, such as `https://auth.example.com`. The run asks at `<issuer>/register`, with\n * a GitHub token whose audience is the issuer, so no other hub can use that token.\n */\n readonly issuer: string;\n}\n\ninterface CommonProps {\n /**\n * The app's name in its repository. Default: the stack's path in the repository, `apps/samebase`\n * for the stack `samebase/samebase/apps/samebase`, and `app` for a stack named after the\n * repository. A changed name registers a new client under the new name.\n */\n readonly app?: string;\n /** The hub to register at. A changed hub registers a new client there; the old one stays. */\n readonly hub: Hub;\n /**\n * The connectors the client signs in through, by their names on the hub, such as\n * `[\"google\", \"github\"]`: at least one, each of `[a-z0-9-]{1,64}`. The hub refuses a name it does\n * not offer, or does not allow this repository, and the log then names the allowed ones. The set\n * is recorded on the client for good: a changed set registers a new client.\n */\n readonly connectors: readonly string[];\n /**\n * The return addresses of this deployment, one to eight, such as\n * `[`${site.siteUrl}/auth/hub/callback`]`: each an https URL whose origin serves\n * `/samebase-verification.json` with the numeric GitHub id of this repository,\n * `{ \"repository\": \"123\" }`. They can come from a resource that this run creates. A development\n * client can also have http on a loopback host, which needs no file. Every request of the client\n * names one of them. The set is recorded on the client for good: a changed set registers a new\n * client.\n */\n readonly redirectUris: string[];\n /** Recorded on the hub's client, such as the commit. The hub records \"unknown\" without it. */\n readonly softwareVersion?: string;\n /**\n * The run fails unless the hub confirms the client in this run: it fails when the hub refuses or\n * does not answer a registration or a renewal, and when it suspended the client. Without it, such\n * a run gives the off values or keeps the saved client, so the app deploys anyway. Set it where\n * sign-in is the product. A failed run saves nothing, so the next run asks the hub again.\n */\n readonly required?: boolean;\n}\n\n/**\n * A production or preview client asks with the GitHub OIDC token of the run. A development client\n * asks with the app's initial access token, which `IdentityHub.Client.read` gives from stage `prod`.\n */\nexport type ClientProps =\n | (CommonProps & {\n readonly deploymentType: \"production\" | \"preview\";\n readonly initialAccessToken?: never;\n })\n | (CommonProps & {\n readonly deploymentType: \"development\";\n /** Empty before the first production registration: the client gets the off values. */\n readonly initialAccessToken: Redacted.Redacted<string>;\n });\n\nconst DeploymentType = Schema.Literals([\"production\", \"preview\", \"development\"]);\n\nconst Attributes = Schema.Struct({\n /** `off`: no client, and the values below are the off values. */\n status: Schema.Literals([\"on\", \"off\", \"suspended\"]),\n /** The issuer of the hub, which the deployment names to sign in. */\n issuer: Schema.String,\n clientId: Schema.String,\n /** Returned only at registration. */\n clientSecret: Schema.Redacted(Schema.String),\n /** Returned only at registration. It reads and deletes this client on the hub, and nothing else. */\n registrationAccessToken: Schema.Redacted(Schema.String),\n registrationClientUri: Schema.String,\n deploymentType: DeploymentType,\n /** The app's name on the hub, as sent. Empty for the off values. */\n app: Schema.String,\n /** The return addresses the client serves, sorted, each once. Empty for the off values. */\n redirectUris: Schema.Array(Schema.String),\n /** The connectors the client is enrolled in, sorted, each once. Empty for the off values. */\n connectors: Schema.Array(Schema.String),\n /**\n * Returned only at a production registration (RFC 7591 section 1.2). It registers development\n * clients of this app. Empty for a preview, for a development client, and for the off values.\n */\n initialAccessToken: Schema.Redacted(Schema.String),\n /** The numeric GitHub id of the repository, with the initial access token. Empty without it. */\n repository: Schema.String,\n});\n\n/**\n * The attributes keep the real values of a suspended client, so that an unblock needs no new client.\n * `IdentityHub.Client.variables` gives the values that the app gets.\n */\nexport interface ClientAttributes extends Schema.Schema.Type<typeof Attributes> {}\n\n/**\n * The attributes of a saved row. A row that does not have this version's shape, or any other\n * failure of the decoder, stops the run with `reason`. The text of a schema issue can quote a value\n * of the row, so it is never kept.\n */\nconst savedAttributes = (value: unknown, reason: string) =>\n Schema.decodeUnknownEffect(Attributes)(value).pipe(\n Effect.catchCause(() => Effect.die(new IdentityHubClientFailed({ reason }))),\n );\n\n/** The attributes of no client. */\nconst offAttributes = (deploymentType: ClientAttributes[\"deploymentType\"]): ClientAttributes => ({\n status: \"off\",\n issuer: OFF_VALUES.issuer,\n clientId: OFF_VALUES.clientId,\n clientSecret: Redacted.make(OFF_VALUES.clientSecret),\n registrationAccessToken: Redacted.make(\"\"),\n registrationClientUri: \"\",\n deploymentType,\n app: \"\",\n redirectUris: [],\n connectors: [],\n initialAccessToken: Redacted.make(\"\"),\n repository: \"\",\n});\n\n/** The set of `values`: sorted, each once. */\nconst sortedSet = (values: readonly string[]) => [...new Set(values)].sort();\n\nconst sameSet = (a: readonly string[], b: readonly string[]) =>\n a.length === b.length && a.every((name, index) => name === b[index]);\n\n/** The app and its return addresses, as every log line names a client: no secret, no answer. */\nconst where = (client: { app: string; redirectUris: readonly string[] }) =>\n `${client.app} on ${client.redirectUris.join(\", \")}`;\n\n/** What one registration sends, resolved from the props: the app's name and both sets. */\ninterface Enrollment {\n readonly app: string;\n readonly connectors: readonly string[];\n readonly redirectUris: readonly string[];\n}\n\n/** One request gave no usable answer. The reason holds no secret. */\nclass IdentityHubClientFailed extends Schema.TaggedError<IdentityHubClientFailed>()(\n \"IdentityHubClientFailed\",\n { reason: Schema.String },\n) {\n override get message() {\n return `IdentityHub.Client: ${this.reason}.`;\n }\n}\n\nconst OidcToken = Schema.Struct({ value: Schema.NonEmptyString });\n\n/**\n * The 201 answer of `POST /register` (RFC 7591 section 3.2.1), in the members that this file reads.\n * The decoder ignores the other members, such as `software_id`, whose full form the hub writes.\n */\nconst NewClient = Schema.Struct({\n issuer: Schema.NonEmptyString,\n client_id: Schema.NonEmptyString,\n client_secret: Schema.NonEmptyString,\n registration_access_token: Schema.NonEmptyString,\n registration_client_uri: Schema.NonEmptyString,\n /** The sets the hub recorded, which must be the sets the request sent. */\n redirect_uris: Schema.Array(Schema.String),\n connectors: Schema.Array(Schema.String),\n /** Only in the answer to a production registration with the GitHub token. */\n initial_access_token: Schema.optionalKey(Schema.NonEmptyString),\n repository: Schema.optionalKey(Schema.String.check(Schema.isPattern(/^\\d+$/))),\n});\n\n/** The other answers of `POST /register`, by status. A 401 can have no body (RFC 6750). */\nconst REFUSALS: Readonly<Record<number, string>> = {\n 400: \"the identity hub refused the client metadata, such as the app name\",\n 401: \"the identity hub refused the GitHub OIDC token\",\n 403: \"the identity hub does not allow this repository\",\n 404: \"the identity hub has no /register: it runs an identity-broker before 0.33.0\",\n 429: \"the identity hub limits new clients\",\n 502: \"GitHub's keys are not available to the identity hub\",\n 503: \"the identity hub could not apply its policy\",\n};\n\n/** The text of an `invalid_redirect_uri` 400 without a known reason. */\nconst BAD_REDIRECT_URIS =\n \"the identity hub refused the return addresses: one to eight, each https on a DNS name, or http on a loopback host for a development client\";\n\n/**\n * The reasons of a 400 or a 403 that a log line shows. Any other text of the answer is never\n * logged.\n */\nconst REASONS = new Map([\n [\"paused\", \"this app is paused on the identity hub\"],\n [\"run_not_allowed\", \"the identity hub gives clients only to runs of main and of pull requests\"],\n [\"blocked\", \"Samebase blocked this repository or its owner\"],\n [\"suspended\", \"the identity hub suspended this repository\"],\n [\"too_many_apps\", \"the repository has as many apps on the identity hub as it may\"],\n [\"too_many_clients\", \"the app has as many clients on the identity hub as it may\"],\n [\"app_taken\", \"the app's name belongs to another app on the identity hub\"],\n [\"host_unreachable\", \"the identity hub could not reach the host of the return address\"],\n [\n \"verification_file_missing\",\n \"the host of the return address does not serve /samebase-verification.json\",\n ],\n [\"verification_file_invalid\", \"/samebase-verification.json on the host holds no repository id\"],\n [\"repository_mismatch\", \"/samebase-verification.json on the host names another repository\"],\n [\"app_mismatch\", \"the initial access token belongs to another app on the identity hub\"],\n [\"stale_proof\", \"the identity hub took a newer GitHub OIDC token of this repository\"],\n]);\n\n/** The windows of a 429, by the name that the answer gives. */\nconst RATE_LIMITED = new Map([\n [\"repository\", \"the identity hub gives one repository at most 30 new clients an hour\"],\n [\"owner\", \"the identity hub gives one owner at most 100 new clients an hour\"],\n [\"new_owners\", \"the identity hub takes at most 50 new owners an hour\"],\n]);\n\nconst Refusal = Schema.Struct({ reason: Schema.String });\nconst InvalidRedirectUri = Schema.Struct({ error: Schema.Literal(\"invalid_redirect_uri\") });\nconst RateLimited = Schema.Struct({ window: Schema.String });\n/** A 400 for a connector the hub does not offer or allow, with the names it allows. */\nconst InvalidConnectors = Schema.Struct({\n reason: Schema.Literal(\"invalid_connectors\"),\n allowed: Schema.Array(Schema.String),\n});\n\n/**\n * The text of a refusal: a known reason of a 400 or a 403, or window of a 429, the allowed\n * connectors of an `invalid_connectors` 400 (only names of the connector grammar, so no other text\n * of the answer is printed), the text of an `invalid_redirect_uri` 400, else the text of its\n * status. `body` is undefined for an answer without JSON, such as a bare 401.\n */\nconst refusalOf = (status: number, body: unknown): string => {\n const decoded = <S extends Schema.Codec<unknown, unknown>>(schema: S) =>\n Option.getOrUndefined(Schema.decodeUnknownOption(schema)(body));\n const ofStatus = () => REFUSALS[status] ?? \"the identity hub refused the request\";\n switch (status) {\n case 400: {\n const allowed = decoded(InvalidConnectors)?.allowed.filter((name) =>\n CONNECTOR_NAME.test(name),\n );\n return allowed === undefined\n ? (REASONS.get(decoded(Refusal)?.reason ?? \"\") ??\n (decoded(InvalidRedirectUri) === undefined ? ofStatus() : BAD_REDIRECT_URIS))\n : `the identity hub does not offer or allow one of the connectors; it allows ${allowed.length === 0 ? \"none for this app\" : allowed.join(\", \")}`;\n }\n case 403:\n return REASONS.get(decoded(Refusal)?.reason ?? \"\") ?? ofStatus();\n case 429:\n return RATE_LIMITED.get(decoded(RateLimited)?.window ?? \"\") ?? ofStatus();\n default:\n return ofStatus();\n }\n};\n\nconst send = (who: string, url: string, token: string, init: { method: string; body?: string }) =>\n Effect.tryPromise({\n try: async () => {\n const response = await fetch(url, {\n ...init,\n headers: { Authorization: `Bearer ${token}`, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n const body: unknown = await response.json().catch(() => undefined);\n return { status: response.status, body };\n },\n catch: () => new IdentityHubClientFailed({ reason: `${who} gave no answer` }),\n });\n\nconst decode =\n <S extends Schema.Codec<unknown, unknown>>(schema: S, who: string) =>\n (value: unknown) =>\n Schema.decodeUnknownEffect(schema)(value).pipe(\n Effect.mapError(() => new IdentityHubClientFailed({ reason: `${who} gave a bad answer` })),\n );\n\n/**\n * The OIDC token of this run for `audience`, read right before the call, because it lives for\n * minutes only.\n */\nconst readOidcToken = (requestUrl: string, requestToken: string, audience: string) =>\n Effect.gen(function* () {\n const { body, status } = yield* send(\n \"GitHub\",\n `${requestUrl}&audience=${encodeURIComponent(audience)}`,\n requestToken,\n { method: \"GET\" },\n );\n if (status !== 200) {\n return yield* new IdentityHubClientFailed({\n reason: `GitHub gave no OIDC token (HTTP ${status})`,\n });\n }\n return (yield* decode(OidcToken, \"GitHub\")(body)).value;\n });\n\n/**\n * `POST /register`, the client registration request of RFC 7591, with `bearer` as its initial\n * access token: the GitHub OIDC token, or the app's own token. `software_id` is the app's name, and\n * `connectors` is the hub's own metadata field. Convex Auth posts the client's secret in the body\n * at the token endpoint, so the client registers that method.\n */\nconst requestNewClient = (props: ClientProps, enrollment: Enrollment, bearer: string) =>\n Effect.gen(function* () {\n const { hub } = props;\n const { app, connectors, redirectUris } = enrollment;\n const { body, status } = yield* send(\"The identity hub\", `${hub.issuer}/register`, bearer, {\n method: \"POST\",\n body: JSON.stringify({\n redirect_uris: redirectUris,\n software_id: app,\n software_version: props.softwareVersion ?? \"unknown\",\n connectors,\n token_endpoint_auth_method: \"client_secret_post\",\n }),\n });\n if (status !== 201) {\n const reason =\n status === 401 && props.deploymentType === \"development\"\n ? \"the identity hub refused the initial access token\"\n : refusalOf(status, body);\n return yield* new IdentityHubClientFailed({ reason: `${reason} (HTTP ${status})` });\n }\n const client = yield* decode(NewClient, \"The identity hub\")(body);\n // The hub registers the addresses and the connectors that the request sent, under its own\n // issuer. The log and the state hold the stack's values, so no value that the answer chose is\n // printed or kept.\n if (\n client.issuer !== hub.issuer ||\n !sameSet(sortedSet(client.redirect_uris), redirectUris) ||\n !sameSet(client.connectors, connectors)\n ) {\n return yield* new IdentityHubClientFailed({ reason: \"The identity hub gave a bad answer\" });\n }\n yield* Effect.logInfo(\n `IdentityHub.Client: ${where(enrollment)} has a new client of the identity hub ${hub.issuer}.`,\n );\n // Only a production registration gives the app's token (RFC 7591); any other answer's is dropped.\n const production = props.deploymentType === \"production\";\n return {\n status: \"on\" as const,\n issuer: hub.issuer,\n clientId: client.client_id,\n clientSecret: Redacted.make(client.client_secret),\n registrationAccessToken: Redacted.make(client.registration_access_token),\n registrationClientUri: client.registration_client_uri,\n deploymentType: props.deploymentType,\n app,\n redirectUris,\n connectors,\n initialAccessToken: Redacted.make(production ? (client.initial_access_token ?? \"\") : \"\"),\n repository: production ? (client.repository ?? \"\") : \"\",\n };\n });\n\n/** A new client, or the off values. */\nconst newClient = (props: ClientProps, enrollment: Enrollment) => {\n const label = `IdentityHub.Client: ${where(enrollment)} deploys without the hub`;\n const off = offAttributes(props.deploymentType);\n const request = (bearer: Effect.Effect<string, IdentityHubClientFailed>) =>\n bearer.pipe(\n Effect.flatMap((token) => requestNewClient(props, enrollment, token)),\n Effect.catchTag(\"IdentityHubClientFailed\", (error) =>\n Effect.logWarning(`${label}: ${error.reason}. The next deploy asks again.`).pipe(\n Effect.as(off),\n ),\n ),\n );\n\n if (props.deploymentType === \"development\") {\n const token = Redacted.value(props.initialAccessToken);\n return token === \"\"\n ? Effect.logInfo(\n \"IdentityHub.Client: deploy to main once for hub sign-in in development.\",\n ).pipe(Effect.as(off))\n : request(Effect.succeed(token));\n }\n\n const requestUrl = process.env[\"ACTIONS_ID_TOKEN_REQUEST_URL\"];\n const requestToken = process.env[\"ACTIONS_ID_TOKEN_REQUEST_TOKEN\"];\n // A development machine, or another CI. In a workflow, `id-token: write` gives both, so a\n // workflow without them is a mistake to show, not a normal run.\n if (!requestUrl || !requestToken) {\n return (\n process.env[\"GITHUB_ACTIONS\"] === \"true\"\n ? Effect.logWarning(`${label}: this workflow needs the permission id-token: write.`)\n : Effect.logInfo(`${label}: this run has no GitHub OIDC token.`)\n ).pipe(Effect.as(off));\n }\n return request(readOidcToken(requestUrl, requestToken, props.hub.issuer));\n};\n\n/**\n * The client after a read on the hub, or undefined when the hub says that the client is gone. A\n * read with no usable answer keeps the saved client, except for a required one: a required client\n * passes a run only when the hub confirms it in that run, so a suspension that an earlier run saw,\n * and did not save because that run failed, cannot pass a run that the hub does not answer.\n */\nconst renew = (saved: ClientAttributes, required: boolean) =>\n Effect.gen(function* () {\n const { status } = yield* send(\n \"The identity hub\",\n saved.registrationClientUri,\n Redacted.value(saved.registrationAccessToken),\n { method: \"GET\" },\n );\n switch (status) {\n case 200:\n return { ...saved, status: \"on\" as const };\n case 401:\n return undefined;\n case 403:\n yield* Effect.logWarning(\n `IdentityHub.Client: the hub suspended the client of ${where(saved)}. It keeps its values, and nobody can sign in with it.`,\n );\n return { ...saved, status: \"suspended\" as const };\n default:\n return yield* new IdentityHubClientFailed({\n reason: `The identity hub answered HTTP ${status}`,\n });\n }\n }).pipe(\n Effect.catchTag(\"IdentityHubClientFailed\", (error) =>\n required\n ? Effect.fail(\n new IdentityHubClientFailed({\n reason: `${where(saved)} is required, and the hub did not confirm its client: ${error.reason}`,\n }),\n )\n : Effect.logWarning(\n `IdentityHub.Client: ${where(saved)} keeps the saved client: ${error.reason}.`,\n ).pipe(Effect.as(saved)),\n ),\n );\n\n/**\n * The type of this resource before 0.37.0. Alchemy finds this provider for a row of that type, and\n * the next write of the row gives it the new type, with the same client. Remove it, here and in\n * `SavedRow`, once no saved row has the old type.\n */\nconst OLD_TYPE = \"IdentityHub.SharedClient\";\n\n/** A saved row of this resource, whose `attr` `savedAttributes` reads. */\nconst SavedRow = Schema.Struct({\n resourceType: Schema.Literals([\"IdentityHub.Client\", OLD_TYPE]),\n attr: Schema.Unknown,\n});\n\n/**\n * The attributes of the client `id` in another stage of this stack, such as\n * `read(\"HubClient\", { stage: \"prod\" })` in a development stage, as Outputs: the\n * `initialAccessToken` and the `repository` of the production client. Without that row, the off\n * attributes, with `deploymentType: \"production\"`.\n *\n * `IdentityHub.Client.ref` is not enough: Alchemy fails the plan with `InvalidReferenceError` when the\n * row is missing, and a development stage before the first deploy to main has none. This read runs\n * when the plan resolves it, with the State service of the running stack and its `get`, so it never\n * creates or upgrades a store. The store revives each secret as `Redacted`, as it does for every\n * read.\n */\nconst read = (id: string, options: { readonly stage: string }) =>\n Output.fromEffect(\n Effect.gen(function* () {\n const stack = yield* Stack;\n const state = yield* yield* State;\n const row = yield* state\n .get({ stack: stack.name, stage: options.stage, fqn: id })\n .pipe(Effect.orDie);\n if (row === undefined) return offAttributes(\"production\");\n const { attr } = yield* Schema.decodeUnknownEffect(SavedRow)(row).pipe(\n Effect.catchCause(() =>\n Effect.die(\n new IdentityHubClientFailed({\n reason: `the row ${id} of stage ${options.stage} is not an IdentityHub.Client`,\n }),\n ),\n ),\n );\n return yield* savedAttributes(\n attr,\n `the row ${id} of stage ${options.stage} holds attributes that this version cannot read`,\n );\n }),\n );\n\n/**\n * The three values that the app's deployment gets, such as `IDENTITY_HUB_ISSUER`,\n * `IDENTITY_HUB_CLIENT_ID`, and `IDENTITY_HUB_CLIENT_SECRET`, as Outputs: the client's values when\n * `status` is `on`, else the off values, so that a suspended client gives guest sign-in and keeps\n * its values in state.\n */\nconst variables = (client: Client) =>\n Output.map(Output.of(client), (attributes) =>\n attributes.status === \"on\"\n ? {\n issuer: attributes.issuer,\n clientId: attributes.clientId,\n clientSecret: attributes.clientSecret,\n }\n : {\n issuer: OFF_VALUES.issuer,\n clientId: OFF_VALUES.clientId,\n clientSecret: Redacted.make(OFF_VALUES.clientSecret),\n },\n );\n\nexport type Client = Resource<\n \"IdentityHub.Client\",\n ClientProps,\n ClientAttributes,\n never,\n Providers\n>;\nexport const Client = Resource<Client>(\"IdentityHub.Client\", { aliases: [OLD_TYPE] })({\n read,\n variables,\n});\n\nexport const ClientProvider = () =>\n Provider.succeed(Client, {\n // Always an update, so that each deploy reaches the hub. No attribute is stable, so a push\n // reads the values that this run ended with. The same values cause no other push.\n diff: ({ news }) =>\n Effect.succeed(isResolved(news) ? ({ action: \"update\" } as const) : undefined),\n\n read: ({ output }) => Effect.succeed(output),\n\n // Only a client of the same hub (its issuer), app name, return address set, type, and\n // connector set is renewed. A saved row without this version's shape stops the run with a\n // fixed message.\n reconcile: Effect.fn(function* ({ news, output }) {\n // A bad prop is a mistake of the stack, not of the hub: the run fails, with no request.\n const stack = yield* Stack;\n const app = news.app ?? defaultApp(stack.name);\n if (app === undefined) {\n return yield* new IdentityHubClientFailed({\n reason: `the stack ${stack.name} is not named owner/repo or owner/repo/<path>, so set app`,\n });\n }\n if (app.length > MAX_APP_LENGTH) {\n return yield* new IdentityHubClientFailed({\n reason: `the app name ${app} is over ${MAX_APP_LENGTH} characters, the hub's limit, so set a shorter app`,\n });\n }\n const enrollment: Enrollment = {\n app,\n connectors: sortedSet(news.connectors),\n redirectUris: sortedSet(news.redirectUris),\n };\n if (\n enrollment.connectors.length === 0 ||\n !enrollment.connectors.every((name) => CONNECTOR_NAME.test(name))\n ) {\n return yield* new IdentityHubClientFailed({\n reason: `${where(enrollment)} needs connectors: one or more names of [a-z0-9-]{1,64}`,\n });\n }\n if (\n enrollment.redirectUris.length === 0 ||\n enrollment.redirectUris.length > MAX_REDIRECT_URIS ||\n !enrollment.redirectUris.every((uri) => URL.canParse(uri))\n ) {\n return yield* new IdentityHubClientFailed({\n reason: `${app} needs redirectUris: one to ${MAX_REDIRECT_URIS} absolute URLs`,\n });\n }\n const saved =\n output === undefined || output.status === \"off\"\n ? undefined\n : yield* savedAttributes(\n output,\n `the saved attributes of ${where(enrollment)} cannot be read by this version`,\n );\n const renewed =\n saved?.issuer === news.hub.issuer &&\n saved.app === app &&\n sameSet(saved.redirectUris, enrollment.redirectUris) &&\n saved.deploymentType === news.deploymentType &&\n sameSet(saved.connectors, enrollment.connectors)\n ? yield* renew(saved, news.required === true)\n : undefined;\n const client = renewed ?? (yield* newClient(news, enrollment));\n if (news.required === true && client.status !== \"on\") {\n return yield* new IdentityHubClientFailed({\n reason: `${where(enrollment)} is required and has no working client (${client.status}). The warning above names the reason`,\n });\n }\n return client;\n }),\n\n // A failed delete does not stop a destroy: the removal date of a preview or development client\n // cleans it up. A destroy can leave a production deployment running, so its client stays.\n delete: ({ output }) =>\n output.deploymentType === \"production\" || output.status === \"off\"\n ? Effect.void\n : Effect.gen(function* () {\n const { status } = yield* send(\n \"The identity hub\",\n output.registrationClientUri,\n Redacted.value(output.registrationAccessToken),\n { method: \"DELETE\" },\n );\n // 401: the client is gone already.\n if (status !== 204 && status !== 401) {\n return yield* new IdentityHubClientFailed({\n reason: `The identity hub answered HTTP ${status}`,\n });\n }\n }).pipe(\n // The row can be of an earlier version's shape, so the line names only the client id.\n Effect.catchTag(\"IdentityHubClientFailed\", (error) =>\n Effect.logWarning(\n `IdentityHub.Client: the client ${output.clientId} stays on the hub until its removal date: ${error.reason}.`,\n ),\n ),\n ),\n });\n"],"mappings":";;;;;;;;;;;;AAqDA,MAAM,qBAAqB;;AAG3B,MAAM,aAAa;CAAE,QAAQ;CAAsB,UAAU;CAAU,cAAc;AAAS;;AAG9F,MAAM,iBAAiB;;AAGvB,MAAM,oBAAoB;;AAE1B,MAAM,iBAAiB;;;;;AAMvB,MAAa,cAAc,cAA0C;CACnE,MAAM,WAAW,UAAU,MAAM,GAAG;CACpC,IAAI,SAAS,SAAS,KAAK,SAAS,MAAM,YAAY,YAAY,EAAE,GAClE;CAEF,OAAO,SAAS,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,KAAK;AACxC;AAkEA,MAAM,iBAAiB,OAAO,SAAS;CAAC;CAAc;CAAW;AAAa,CAAC;AAE/E,MAAM,aAAa,OAAO,OAAO;;CAE/B,QAAQ,OAAO,SAAS;EAAC;EAAM;EAAO;CAAW,CAAC;;CAElD,QAAQ,OAAO;CACf,UAAU,OAAO;;CAEjB,cAAc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CAA4C,MAAM,OAAO,EAC7G,CACF,CACF;AACR,CAAC"}
@@ -18,8 +18,8 @@ export declare const defaultApp: (stackName: string) => string | undefined;
18
18
  */
19
19
  export interface Hub {
20
20
  /**
21
- * The hub's issuer, such as `https://auth.example.com`. The run asks at `<issuer>/hub-clients`,
22
- * with a GitHub token whose audience is the issuer, so no other hub can use that token.
21
+ * The hub's issuer, such as `https://auth.example.com`. The run asks at `<issuer>/register`, with
22
+ * a GitHub token whose audience is the issuer, so no other hub can use that token.
23
23
  */
24
24
  readonly issuer: string;
25
25
  }
@@ -1 +1 @@
1
- {"version":3,"file":"IdentityHub.d.ts","names":[],"sources":["../src/IdentityHub.ts"],"mappings":";;;;;;;;;;;;;qBAsEa,aAAc;;;;;iBAYV;;;;;WAKN;;UAGD;;;;;;WAMC;;WAEA,KAAK;;;;;;;WAOL;;;;;;;;;;WAUA;;WAEA;;;;;;;WAOA;;;;;;YAOC,eACP;WACU;WACA;MAEV;WACU;;WAEA,oBAAoB,SAAS;;cAKtC,YAAU,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+BC,yBAAyB,OAAO,OAAO,YAAY;YAoYxD,SAAS,+BAEnB,aACA,yBAEA;qBAEW,0BAAM,yBAAA;WArDD,OAAA,YAAM;aAAsB;QAAe,OAAA;;;;;;;;;;;;;;WA+BlC,YAAA,QAAA,WAAM,OAAA;;;;;;qBA2BpB,6CAAc,MAAA,SAAA,SAAA,gBAAA"}
1
+ {"version":3,"file":"IdentityHub.d.ts","names":[],"sources":["../src/IdentityHub.ts"],"mappings":";;;;;;;;;;;;;qBAsEa,aAAc;;;;;iBAYV;;;;;WAKN;;UAGD;;;;;;WAMC;;WAEA,KAAK;;;;;;;WAOL;;;;;;;;;;WAUA;;WAEA;;;;;;;WAOA;;;;;;YAOC,eACP;WACU;WACA;MAEV;WACU;;WAEA,oBAAoB,SAAS;;cAKtC,YAAU,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+BC,yBAAyB,OAAO,OAAO,YAAY;YAyZxD,SAAS,+BAEnB,aACA,yBAEA;qBAEW,0BAAM,yBAAA;WArDD,OAAA,YAAM;aAAsB;QAAe,OAAA;;;;;;;;;;;;;;WA+BlC,YAAA,QAAA,WAAM,OAAA;;;;;;qBA2BpB,6CAAc,MAAA,SAAA,SAAA,gBAAA"}
@@ -1 +1 @@
1
- export { t as Client, n as ClientProvider, r as defaultApp } from "./IdentityHub-B3Awt5KE.js";
1
+ export { t as Client, n as ClientProvider, r as defaultApp } from "./IdentityHub-lx5BPjOS.js";
@@ -3,9 +3,9 @@ import { createRequire } from "node:module";
3
3
  import { Stack } from "alchemy/Stack";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as Schema from "effect/Schema";
6
- import { access, mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises";
6
+ import { access, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
7
7
  import { homedir, tmpdir } from "node:os";
8
- import { dirname, join, posix, relative, resolve, sep, win32 } from "node:path";
8
+ import { dirname, join, posix, relative, resolve, win32 } from "node:path";
9
9
  import * as Config from "effect/Config";
10
10
  import * as Context from "effect/Context";
11
11
  import * as Layer from "effect/Layer";
@@ -19,7 +19,7 @@ import * as Provider from "alchemy/Provider";
19
19
  import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
20
20
  import { AlchemyContext } from "alchemy/AlchemyContext";
21
21
  import { readFileSync } from "node:fs";
22
- import { parseEnv, promisify, stripVTControlCharacters } from "node:util";
22
+ import { parseEnv, stripVTControlCharacters } from "node:util";
23
23
  import { createDeploymentClient, createManagementClient } from "@convex-dev/platform";
24
24
  import * as Schedule from "effect/Schedule";
25
25
  import { createHash } from "node:crypto";
@@ -28,7 +28,6 @@ import * as Clock from "effect/Clock";
28
28
  import * as ChildProcess from "effect/process/ChildProcess";
29
29
  import * as Stream from "effect/Stream";
30
30
  import { STATE_STORE_VERSION, State, StateStoreError, encodeState, reviveState } from "alchemy/State";
31
- import { execFile } from "node:child_process";
32
31
  import { fileURLToPath } from "node:url";
33
32
  import * as Scope from "effect/Scope";
34
33
  //#region src/Credentials.ts
@@ -1436,164 +1435,6 @@ const ProjectProvider = () => Provider.effect(Project, Effect.gen(function* () {
1436
1435
  };
1437
1436
  }));
1438
1437
  //#endregion
1439
- //#region src/RunRecord.ts
1440
- /** The key of the record in the stage output document. */
1441
- const RUN_RECORD_KEY = "samebase.run";
1442
- /** The name of the stack file. Alchemy resolves `--config` against the working directory and does not expose it to a state layer, so the record assumes the default name. */
1443
- const STACK_FILE_NAME = "alchemy.run.ts";
1444
- var RunRecordError = class extends Schema.TaggedError()("RunRecordError", { reason: Schema.String }) {
1445
- get message() {
1446
- return `The run record of the stage output cannot be made: ${this.reason}`;
1447
- }
1448
- };
1449
- /** The part of the GitHub Actions event payload that the record reads. A push event has no `pull_request`. */
1450
- const EventPayload = Schema.Struct({ pull_request: Schema.optionalKey(Schema.Struct({
1451
- number: Schema.Number,
1452
- head: Schema.Struct({ sha: Schema.String })
1453
- })) });
1454
- /** `owner/name` of an https, ssh, or scp-like git URL with a host. A local path is not one. */
1455
- const REMOTE_URL = /^(?:[a-z+]+:\/\/[^/]+\/|[^/@:]+@[^:/]+:)([^/]+)\/([^/]+?)(?:\.git)?\/?$/;
1456
- const execFileAsync = promisify(execFile);
1457
- const now = Clock.currentTimeMillis.pipe(Effect.map((millis) => new Date(millis).toISOString()));
1458
- const git = (cwd, args) => Effect.tryPromise({
1459
- try: async () => (await execFileAsync("git", [
1460
- "-C",
1461
- cwd,
1462
- ...args
1463
- ], { encoding: "utf8" })).stdout.trim(),
1464
- catch: (error) => new RunRecordError({ reason: `git ${args.join(" ")} failed in ${cwd} (${error instanceof Error ? error.message.split("\n")[0] : String(error)})` })
1465
- });
1466
- /** The stack file from the repository root: the working directory below the git top level, plus {@link STACK_FILE_NAME}. */
1467
- const stackFileOf = (cwd) => Effect.gen(function* () {
1468
- const top = yield* git(cwd, ["rev-parse", "--show-toplevel"]);
1469
- const [realTop, realCwd] = yield* Effect.tryPromise({
1470
- try: () => Promise.all([realpath(top), realpath(cwd)]),
1471
- catch: () => new RunRecordError({ reason: `${cwd} is gone` })
1472
- });
1473
- return [...relative(realTop, realCwd).split(sep).filter((part) => part !== ""), STACK_FILE_NAME].join("/");
1474
- });
1475
- const variable = (env, name) => Effect.suspend(() => {
1476
- const value = env[name];
1477
- return value === void 0 || value === "" ? Effect.fail(new RunRecordError({ reason: `GITHUB_ACTIONS is true, and ${name} is not set` })) : Effect.succeed(value);
1478
- });
1479
- const fromGitHubActions = (where) => Effect.gen(function* () {
1480
- const { env } = where;
1481
- const repository = yield* variable(env, "GITHUB_REPOSITORY");
1482
- const refName = yield* variable(env, "GITHUB_REF_NAME");
1483
- const sha = yield* variable(env, "GITHUB_SHA");
1484
- const serverUrl = yield* variable(env, "GITHUB_SERVER_URL");
1485
- const runId = yield* variable(env, "GITHUB_RUN_ID");
1486
- const runAttempt = yield* variable(env, "GITHUB_RUN_ATTEMPT");
1487
- const eventPath = env["GITHUB_EVENT_PATH"];
1488
- const pullRequest = (eventPath === void 0 || eventPath === "" ? void 0 : yield* Effect.tryPromise({
1489
- try: () => readFile(eventPath, "utf8"),
1490
- catch: () => new RunRecordError({ reason: `GITHUB_EVENT_PATH ${eventPath} cannot be read` })
1491
- }).pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(EventPayload))), Effect.mapError((error) => error instanceof RunRecordError ? error : new RunRecordError({ reason: `GITHUB_EVENT_PATH ${eventPath} is not an event payload` }))))?.pull_request;
1492
- const headCommit = pullRequest?.head.sha ?? sha;
1493
- const headRef = env["GITHUB_HEAD_REF"];
1494
- const mergeRef = /^refs\/pull\/(\d+)\/merge$/.exec(env["GITHUB_REF"] ?? "");
1495
- return {
1496
- version: 1,
1497
- repository,
1498
- stackFile: yield* stackFileOf(where.cwd),
1499
- branch: headRef === void 0 || headRef === "" ? refName : headRef,
1500
- pullRequest: pullRequest?.number ?? (mergeRef === null ? null : Number(mergeRef[1])),
1501
- headCommit,
1502
- runUrl: `${serverUrl}/${repository}/actions/runs/${runId}/attempts/${runAttempt}`,
1503
- source: "github-actions",
1504
- recordedAt: yield* now
1505
- };
1506
- });
1507
- const fromGit = (where) => Effect.gen(function* () {
1508
- const { cwd } = where;
1509
- const origin = yield* git(cwd, [
1510
- "remote",
1511
- "get-url",
1512
- "origin"
1513
- ]);
1514
- const match = REMOTE_URL.exec(origin);
1515
- if (match === null) return yield* new RunRecordError({ reason: `the origin remote of ${cwd} is not a git URL with a host and owner/name: ${origin}` });
1516
- const branch = yield* git(cwd, [
1517
- "rev-parse",
1518
- "--abbrev-ref",
1519
- "HEAD"
1520
- ]);
1521
- if (branch === "HEAD") return yield* new RunRecordError({ reason: `the checkout at ${cwd} is on no branch (detached HEAD)` });
1522
- return {
1523
- version: 1,
1524
- repository: `${match[1]}/${match[2]}`,
1525
- stackFile: yield* stackFileOf(cwd),
1526
- branch,
1527
- pullRequest: null,
1528
- headCommit: yield* git(cwd, ["rev-parse", "HEAD"]),
1529
- runUrl: null,
1530
- source: "checkout",
1531
- recordedAt: yield* now
1532
- };
1533
- });
1534
- /**
1535
- * The record of this run: from the GitHub Actions variables and the event
1536
- * payload when GITHUB_ACTIONS is `true`, else from git in `cwd`, which needs
1537
- * a branch and an `origin` remote with `owner/name`. Fails when a value is
1538
- * missing; nothing is guessed.
1539
- */
1540
- const runRecord = (where) => where.env["GITHUB_ACTIONS"] === "true" ? fromGitHubActions(where) : fromGit(where);
1541
- /** A plain object, which a spread keeps whole. A Date, a Duration, or a Redacted value is an object too, and a spread loses it. */
1542
- const isPlainObject = (value) => {
1543
- if (typeof value !== "object" || value === null) return false;
1544
- const prototype = Object.getPrototypeOf(value);
1545
- return prototype === Object.prototype || prototype === null;
1546
- };
1547
- /**
1548
- * The output document of a stage: the stack's output plus the record under
1549
- * {@link RUN_RECORD_KEY}, or undefined for an output with no place for the
1550
- * key: a string, an array, null, or an object that is not plain, such as a
1551
- * Date. A value that the stack itself put under the key stays.
1552
- */
1553
- const outputWithRunRecord = (output, record) => isPlainObject(output) ? "samebase.run" in output ? output : {
1554
- ...output,
1555
- [RUN_RECORD_KEY]: record
1556
- } : void 0;
1557
- /**
1558
- * The state of `inner`, with the record of this run in each stage output that it writes, under
1559
- * {@link RUN_RECORD_KEY}: `state: withRunRecord(Convex.state())`, or the same over another state
1560
- * layer, such as the Cloudflare state store of Alchemy. Every other call goes to `inner` as it is.
1561
- *
1562
- * The record is derived once, at the first use of the state, and `recordedAt` is the time of the
1563
- * output write. A checkout that gives no record, such as a tarball without git, a checkout without
1564
- * `origin`, or a detached HEAD, still reads, plans, and destroys: its outputs are written without
1565
- * the record, and the log says why. The engine writes the output only after a full successful
1566
- * apply, so the record names the last full successful deploy of the stage.
1567
- */
1568
- const withRunRecord = (inner) => Layer.effect(State, Effect.gen(function* () {
1569
- const open = yield* State;
1570
- return yield* Effect.cached(Effect.gen(function* () {
1571
- const service = yield* open;
1572
- const run = yield* runRecord({
1573
- cwd: process.cwd(),
1574
- env: process.env
1575
- }).pipe(Effect.catch((error) => Effect.logWarning(`The stage outputs of this run carry no run record. ${error.message}`).pipe(Effect.as(void 0))));
1576
- const documentOf = (request) => Effect.gen(function* () {
1577
- if (run === void 0) return request.value;
1578
- const document = outputWithRunRecord(request.value, {
1579
- ...run,
1580
- recordedAt: yield* now
1581
- });
1582
- if (document !== void 0) return document;
1583
- yield* Effect.logWarning(`The output of ${request.stack}/${request.stage} is not a plain object, so it carries no run record.`);
1584
- return request.value;
1585
- });
1586
- return {
1587
- ...service,
1588
- setOutput: (request) => documentOf(request).pipe(Effect.flatMap((value) => service.setOutput({
1589
- stack: request.stack,
1590
- stage: request.stage,
1591
- value
1592
- })))
1593
- };
1594
- }));
1595
- })).pipe(Layer.provide(inner));
1596
- //#endregion
1597
1438
  //#region src/store/convex/sealing.ts
1598
1439
  /** The variable of the store deployment that holds the key `keyId`. */
1599
1440
  const stateKeyName = (keyId) => `STATE_KEY_${keyId}`;
@@ -1853,6 +1694,6 @@ const state = () => Layer.effect(State, Effect.gen(function* () {
1853
1694
  }).pipe(Effect.provideContext(context), Effect.orDie));
1854
1695
  }));
1855
1696
  //#endregion
1856
- 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 };
1697
+ export { Credentials as A, parseDeployOutput as C, ManagementApiLive as D, ManagementApi as E, DEPLOY_KEY_ENV as M, fromConfig as N, readLocalDeployment as O, fromValues as P, VariablesOwnedBySomeoneElse as S, ConvexApiError as T, CodePushFailed as _, Project as a, EnvironmentNeedsDeployKey as b, ProjectProvider as c, AmbiguousDeployment as d, Deployment as f, ProductionDeploymentNotFound as g, DeploymentResource as h, CreatedProjectNotFound as i, CredentialsError as j, ACCESS_TOKEN_ENV as k, ProjectTeamChange as l, DeploymentProvider as m, state as n, ProjectDeploymentChange as o, DeploymentIdentityChange as p, AmbiguousProject as r, ProjectNotFound as s, STORE_PROJECT_NAME as t, AbsoluteRootDir as u, ConvexAppNotFound as v, push as w, PushTargetMismatch as x, ConvexCliNotFound as y };
1857
1698
 
1858
- //# sourceMappingURL=State-CfIbfbVv.js.map
1699
+ //# sourceMappingURL=State-Bp7iSx8T.js.map