effect-vercel 0.3.0 → 0.5.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 +53 -23
- package/dist/AiGateway.d.ts +44 -0
- package/dist/{ai-gateway.js → AiGateway.js} +5 -106
- package/dist/AiGateway.js.map +1 -0
- package/dist/AiGatewayCredentials.d.ts +45 -0
- package/dist/AiGatewayCredentials.js +94 -0
- package/dist/AiGatewayCredentials.js.map +1 -0
- package/dist/Functions.d.ts +14 -0
- package/dist/Functions.js +34 -0
- package/dist/Functions.js.map +1 -0
- package/dist/Oidc.d.ts +23 -0
- package/dist/Oidc.js +59 -0
- package/dist/Oidc.js.map +1 -0
- package/dist/{runtime-cache.d.ts → RuntimeCache.d.ts} +5 -8
- package/dist/{runtime-cache.js → RuntimeCache.js} +6 -12
- package/dist/RuntimeCache.js.map +1 -0
- package/package.json +9 -6
- package/src/AiGateway.ts +1 -1
- package/src/AiGatewayCredentials.ts +53 -55
- package/src/Functions.ts +34 -0
- package/src/Oidc.ts +75 -0
- package/src/{VercelRuntimeCache.ts → RuntimeCache.ts} +2 -2
- package/dist/VercelOidc-DCkdXW3E.js +0 -70
- package/dist/VercelOidc-DCkdXW3E.js.map +0 -1
- package/dist/ai-gateway.d.ts +0 -87
- package/dist/ai-gateway.js.map +0 -1
- package/dist/oidc.d.ts +0 -27
- package/dist/oidc.js +0 -2
- package/dist/rolldown-runtime-D7D4PA-g.js +0 -13
- package/dist/runtime-cache.js.map +0 -1
- package/src/VercelOidc.ts +0 -86
- package/src/ai-gateway.ts +0 -2
- package/src/oidc.ts +0 -1
- package/src/runtime-cache.ts +0 -1
package/dist/ai-gateway.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ai-gateway.js","names":["VercelOidc.hints","layer","AiGatewayCredentials.AiGatewayCredentials","AiGatewayCredentials.layer","AiGatewayCredentials.formatHeaders"],"sources":["../src/AiGatewayCredentials.ts","../src/AiGateway.ts"],"sourcesContent":["/**\n * How gateway requests authenticate.\n *\n * `AiGatewayCredentials` holds an effect that produces the credential for one\n * request. It runs per request rather than once at startup: on Vercel the OIDC\n * token arrives on the request context and rotates, so it must not be cached.\n * `layer` is the default; pick a `layerFrom*` layer to use one source only.\n *\n * @example\n * ```ts\n * import { AiGatewayCredentials } from \"effect-vercel/ai-gateway\"\n *\n * AiGatewayCredentials.layer // AI_GATEWAY_API_KEY, else the Vercel OIDC token\n * AiGatewayCredentials.layerFromEnv // AI_GATEWAY_API_KEY only\n * AiGatewayCredentials.layerFromVercelOidc // the Vercel OIDC token only\n * AiGatewayCredentials.layerFromApiKey(\"…\") // a fixed value\n * ```\n */\n\nimport { Config, Context, Data, Effect, Layer, Option, Redacted } from \"effect\"\nimport * as VercelOidc from \"./VercelOidc.js\"\n\n/** The environment variable `layerFromEnv` reads. */\nexport const API_KEY_ENV = \"AI_GATEWAY_API_KEY\"\n\n/** Which layer produced or failed to produce a credential. */\nexport type Source = \"api-key\" | \"env\" | \"vercel-oidc\" | \"default\"\n\n/**\n * A credential ready to put on a request. `method` is what the gateway\n * records as the auth method; it matches the values Vercel's own SDK sends.\n */\nexport interface Resolved {\n readonly method: \"api-key\" | \"oidc\"\n readonly token: Redacted.Redacted<string>\n}\n\n/** No credential could be produced for a gateway request. */\nexport class AiGatewayCredentialsError extends Data.TaggedError(\"AiGatewayCredentialsError\")<{\n readonly message: string\n readonly source: Source\n readonly hints: ReadonlyArray<string>\n readonly cause?: unknown\n}> {}\n\nexport class AiGatewayCredentials extends Context.Service<\n AiGatewayCredentials,\n Effect.Effect<Resolved, AiGatewayCredentialsError>\n>()(\"effect-vercel/ai-gateway/AiGatewayCredentials\") {}\n\n/** The request headers that carry `credentials`. */\nexport const formatHeaders = (credentials: Resolved): Record<string, string> => ({\n \"x-api-key\": Redacted.value(credentials.token),\n \"ai-gateway-auth-method\": credentials.method,\n})\n\nconst hints: Record<Source, ReadonlyArray<string>> = {\n \"api-key\": [],\n env: [`Set ${API_KEY_ENV} to an AI Gateway API key.`],\n \"vercel-oidc\": VercelOidc.hints,\n default: [\n `Set ${API_KEY_ENV} to an AI Gateway API key.`,\n \"Or run on Vercel / `vercel env pull` so an OIDC token is available.\",\n ],\n}\n\n/**\n * Where a credential may come from. `None` means the place is not configured,\n * so a chain can move on; a failure means it is configured but unusable.\n */\ntype Lookup = Effect.Effect<Option.Option<Resolved>, AiGatewayCredentialsError>\n\nconst apiKeyLookup: Lookup = Config.option(Config.Redacted(API_KEY_ENV)).pipe(\n Effect.map(Option.map((token) => ({ method: \"api-key\" as const, token }))),\n Effect.catchTag(\n \"ConfigError\",\n (cause) =>\n new AiGatewayCredentialsError({\n message: `Failed to read ${API_KEY_ENV}.`,\n source: \"env\",\n hints: hints.env,\n cause,\n }),\n ),\n)\n\nconst vercelOidcLookup: Lookup = VercelOidc.find.pipe(\n Effect.map(Option.map((token) => ({ method: \"oidc\" as const, token }))),\n Effect.mapError(\n (cause) =>\n new AiGatewayCredentialsError({\n message: cause.message,\n source: \"vercel-oidc\",\n hints: cause.hints,\n cause,\n }),\n ),\n)\n\nconst firstOf = (lookups: ReadonlyArray<Lookup>): Lookup =>\n Effect.gen(function* () {\n for (const lookup of lookups) {\n const found = yield* lookup\n if (Option.isSome(found)) return found\n }\n return Option.none()\n })\n\nconst toLayer = (lookup: Lookup, source: Source, message: string) =>\n Layer.succeed(AiGatewayCredentials)(\n Effect.flatMap(lookup, (found) =>\n Option.isSome(found)\n ? Effect.succeed(found.value)\n : Effect.fail(new AiGatewayCredentialsError({ message, source, hints: hints[source] })),\n ),\n )\n\n/** A fixed API key. */\nexport const layerFromApiKey = (\n apiKey: string | Redacted.Redacted<string>,\n): Layer.Layer<AiGatewayCredentials> =>\n Layer.succeed(AiGatewayCredentials)(\n Effect.succeed({\n method: \"api-key\",\n token: Redacted.isRedacted(apiKey) ? apiKey : Redacted.make(apiKey),\n }),\n )\n\n/** `AI_GATEWAY_API_KEY`: local dev, CI, or anywhere off Vercel. */\nexport const layerFromEnv: Layer.Layer<AiGatewayCredentials> = toLayer(\n apiKeyLookup,\n \"env\",\n `${API_KEY_ENV} is not set.`,\n)\n\n/** The Vercel OIDC token (see `VercelOidc.find`). Not refreshed when it expires locally. */\nexport const layerFromVercelOidc: Layer.Layer<AiGatewayCredentials> = toLayer(\n vercelOidcLookup,\n \"vercel-oidc\",\n \"No Vercel OIDC token is available.\",\n)\n\n/**\n * The default: `layerFromEnv`, then `layerFromVercelOidc`. Same order as\n * Vercel's own SDK, so it works locally with an API key and on Vercel without\n * one.\n */\nexport const layer: Layer.Layer<AiGatewayCredentials> = toLayer(\n firstOf([apiKeyLookup, vercelOidcLookup]),\n \"default\",\n \"No AI Gateway credential found.\",\n)\n","/**\n * Vercel AI Gateway as an Anthropic Messages API client for Effect AI.\n *\n * The gateway serves the Anthropic Messages API at its root URL and accepts\n * any model it lists, named `provider/model` (for example\n * `anthropic/claude-sonnet-4.5` or `google/gemini-2.5-flash`). Effect AI's\n * Anthropic provider only needs the base URL and the credential swapped, plus\n * two small dialect fixes (see `dropNullCacheControl` and\n * `fillMissingResponseKeys`), so this module is the one place the gateway is\n * configured.\n *\n * Structured output (`output_config.format`) works for every provider behind\n * the gateway, so the Anthropic provider's default of native structured\n * output holds for models it does not recognise.\n *\n * @example\n * ```ts\n * import { AiGateway } from \"effect-vercel/ai-gateway\"\n * import { AnthropicLanguageModel } from \"@effect/ai-anthropic\"\n * import { Layer } from \"effect\"\n * import { FetchHttpClient } from \"effect/http\"\n *\n * const Model = AnthropicLanguageModel.layer({ model: \"anthropic/claude-sonnet-4.5\" }).pipe(\n * Layer.provide(AiGateway.layer),\n * Layer.provide(FetchHttpClient.layer),\n * )\n * ```\n */\n\nimport { AnthropicClient } from \"@effect/ai-anthropic\"\nimport { Effect, Layer } from \"effect\"\nimport {\n HttpBody,\n HttpClient,\n HttpClientError,\n HttpClientRequest,\n HttpClientResponse,\n} from \"effect/http\"\nimport * as AiGatewayCredentials from \"./AiGatewayCredentials.js\"\n\n/** Base URL of the Vercel AI Gateway. */\nexport const AI_GATEWAY_URL = \"https://ai-gateway.vercel.sh\"\n\n/**\n * Builds the Anthropic client against the gateway, authenticating each\n * request with `credentials`. A credential failure fails that request as an\n * `HttpClientError`, which Effect AI surfaces as a network `AiError`.\n */\nexport const make = (credentials: typeof AiGatewayCredentials.AiGatewayCredentials.Service) =>\n AnthropicClient.make({\n apiUrl: AI_GATEWAY_URL,\n transformClient: (client) =>\n client.pipe(\n HttpClient.mapRequestEffect(authenticate(credentials)),\n HttpClient.mapRequest(dropNullCacheControl),\n HttpClient.transformResponse(Effect.flatMap(fillMissingResponseKeys)),\n ),\n })\n\n/**\n * `AnthropicClient` backed by the gateway, authenticating with the\n * `AiGatewayCredentials` you provide (see that module's `layerFrom*` layers).\n * Needs an `HttpClient` too.\n */\nexport const layerWithoutCredentials: Layer.Layer<\n AnthropicClient.AnthropicClient,\n never,\n AiGatewayCredentials.AiGatewayCredentials | HttpClient.HttpClient\n> = Layer.effect(AnthropicClient.AnthropicClient)(\n Effect.flatMap(Effect.service(AiGatewayCredentials.AiGatewayCredentials), make),\n)\n\n/**\n * `layerWithoutCredentials` with the default `AiGatewayCredentials.layer`:\n * `AI_GATEWAY_API_KEY`, else the Vercel OIDC token. Needs an `HttpClient`.\n * Building never fails; without a usable credential, the requests fail.\n */\nexport const layer: Layer.Layer<AnthropicClient.AnthropicClient, never, HttpClient.HttpClient> =\n layerWithoutCredentials.pipe(Layer.provide(AiGatewayCredentials.layer))\n\nfunction authenticate(credentials: typeof AiGatewayCredentials.AiGatewayCredentials.Service) {\n return (request: HttpClientRequest.HttpClientRequest) =>\n credentials.pipe(\n Effect.map((resolved) =>\n HttpClientRequest.setHeaders(request, AiGatewayCredentials.formatHeaders(resolved)),\n ),\n Effect.mapError(\n (error) =>\n new HttpClientError.HttpClientError({\n reason: new HttpClientError.TransportError({\n request,\n cause: error,\n description: \"AI Gateway credential unavailable\",\n }),\n }),\n ),\n )\n}\n\n/**\n * The Effect provider writes `\"cache_control\": null` on every content block\n * it has no cache setting for. Anthropic accepts that; the gateway rejects\n * the request with `messages.0.content: Invalid input`. Remove the null keys.\n */\nexport function dropNullCacheControl(\n request: HttpClientRequest.HttpClientRequest,\n): HttpClientRequest.HttpClientRequest {\n const body = request.body\n if (body._tag !== \"Uint8Array\" || !isJson(body.contentType)) {\n return request\n }\n const json: unknown = JSON.parse(new TextDecoder().decode(body.body))\n return HttpClientRequest.setBody(\n request,\n HttpBody.jsonUnsafe(withoutNullCacheControl(json), body.contentType),\n )\n}\n\nfunction withoutNullCacheControl(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(withoutNullCacheControl)\n if (value === null || typeof value !== \"object\") return value\n const result: Record<string, unknown> = {}\n for (const [key, entry] of Object.entries(value)) {\n if (key === \"cache_control\" && entry === null) continue\n result[key] = withoutNullCacheControl(entry)\n }\n return result\n}\n\n/**\n * The gateway's Anthropic-shaped responses leave out keys that Anthropic\n * always sends and the Effect provider's schema requires: the cache and\n * service-tier usage fields, the `signature` of a thinking block from a\n * non-Anthropic model, and `type`/`request_id` on error envelopes, whose\n * `error.type` may also be a gateway-specific value. Fill them with the values\n * Anthropic uses when there is nothing to report. Streaming responses are not\n * JSON and pass through untouched.\n */\nexport function fillMissingResponseKeys(\n response: HttpClientResponse.HttpClientResponse,\n): Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError> {\n if (!isJson(response.headers[\"content-type\"] ?? \"\")) {\n return Effect.succeed(response)\n }\n return Effect.map(response.text, (text) => {\n const body = JSON.parse(text) as Record<string, unknown>\n return HttpClientResponse.fromWeb(\n response.request,\n new Response(JSON.stringify(patchResponseBody(body)), {\n status: response.status,\n headers: response.headers,\n }),\n )\n })\n}\n\nexport function patchResponseBody(body: Record<string, unknown>): Record<string, unknown> {\n if (body.type === \"message\") {\n const usage = (body.usage ?? {}) as Record<string, unknown>\n body.usage = {\n cache_creation: null,\n cache_creation_input_tokens: null,\n cache_read_input_tokens: null,\n inference_geo: null,\n service_tier: null,\n ...usage,\n }\n if (Array.isArray(body.content)) {\n body.content = body.content.map((block: unknown) =>\n isRecord(block) && block.type === \"thinking\" ? { signature: \"\", ...block } : block,\n )\n }\n return body\n }\n if (isRecord(body.error)) {\n const error = ANTHROPIC_ERROR_TYPES.has(String(body.error.type))\n ? body.error\n : { ...body.error, type: \"api_error\" }\n return { type: \"error\", request_id: null, ...body, error }\n }\n return body\n}\n\nconst ANTHROPIC_ERROR_TYPES = new Set([\n \"invalid_request_error\",\n \"authentication_error\",\n \"billing_error\",\n \"permission_error\",\n \"not_found_error\",\n \"rate_limit_error\",\n \"timeout_error\",\n \"api_error\",\n \"overloaded_error\",\n])\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n\nfunction isJson(contentType: string): boolean {\n return contentType.startsWith(\"application/json\")\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,MAAa,cAAc;;AAe3B,IAAa,4BAAb,cAA+C,KAAK,YAAY,2BAA2B,CAAC,CAKzF,CAAC;AAEJ,IAAa,uBAAb,cAA0C,QAAQ,QAGhD,CAAC,CAAC,+CAA+C,CAAC,CAAC,CAAC;;AAGtD,MAAa,iBAAiB,iBAAmD;CAC/E,aAAa,SAAS,MAAM,YAAY,KAAK;CAC7C,0BAA0B,YAAY;AACxC;AAEA,MAAM,QAA+C;CACnD,WAAW,CAAC;CACZ,KAAK,CAAC,OAAO,YAAY,2BAA2B;CACpD,eAAeA;CACf,SAAS,CACP,OAAO,YAAY,6BACnB,qEACF;AACF;AAQA,MAAM,eAAuB,OAAO,OAAO,OAAO,SAAS,WAAW,CAAC,CAAC,CAAC,KACvE,OAAO,IAAI,OAAO,KAAK,WAAW;CAAE,QAAQ;CAAoB;AAAM,EAAE,CAAC,GACzE,OAAO,SACL,gBACC,UACC,IAAI,0BAA0B;CAC5B,SAAS,kBAAkB,YAAY;CACvC,QAA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ports {
|
|
3
|
-
export { TOKEN_ENV, VercelOidcError, find, hints, token };
|
|
4
|
-
}
|
|
5
|
-
/** The environment variable read when no request carries a token. */
|
|
6
|
-
declare const TOKEN_ENV = "VERCEL_OIDC_TOKEN";
|
|
7
|
-
declare const VercelOidcError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
8
|
-
readonly _tag: "VercelOidcError";
|
|
9
|
-
} & Readonly<A>;
|
|
10
|
-
/** No usable OIDC token. */
|
|
11
|
-
declare class VercelOidcError extends VercelOidcError_base<{
|
|
12
|
-
readonly message: string;
|
|
13
|
-
readonly hints: ReadonlyArray<string>;
|
|
14
|
-
readonly cause?: unknown;
|
|
15
|
-
}> {}
|
|
16
|
-
/** How to make a token available. */
|
|
17
|
-
declare const hints: ReadonlyArray<string>;
|
|
18
|
-
/**
|
|
19
|
-
* The token if one is available: the request header, else `VERCEL_OIDC_TOKEN`.
|
|
20
|
-
* `None` means neither is set, so a caller can fall back to something else.
|
|
21
|
-
*/
|
|
22
|
-
declare const find: Effect.Effect<Option.Option<Redacted.Redacted<string>>, VercelOidcError>;
|
|
23
|
-
/** Like `find`, but fails when no token is available. */
|
|
24
|
-
declare const token: Effect.Effect<Redacted.Redacted<string>, VercelOidcError>;
|
|
25
|
-
//#endregion
|
|
26
|
-
export { VercelOidc_d_exports as VercelOidc };
|
|
27
|
-
//# sourceMappingURL=oidc.d.ts.map
|
package/dist/oidc.js
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
//#region \0rolldown/runtime.js
|
|
2
|
-
var __defProp = Object.defineProperty;
|
|
3
|
-
var __exportAll = (all, no_symbols) => {
|
|
4
|
-
let target = {};
|
|
5
|
-
for (var name in all) __defProp(target, name, {
|
|
6
|
-
get: all[name],
|
|
7
|
-
enumerable: true
|
|
8
|
-
});
|
|
9
|
-
if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
10
|
-
return target;
|
|
11
|
-
};
|
|
12
|
-
//#endregion
|
|
13
|
-
export { __exportAll as t };
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-cache.js","names":[],"sources":["../src/VercelRuntimeCache.ts"],"sourcesContent":["/**\n * Effect `Persistence` backed by the Vercel Runtime Cache, so a\n * `PersistedCache` shares results across Function instances in a region.\n *\n * Outside Vercel, `getCache` falls back to an in-memory cache, so the same\n * layer works in local dev and tests.\n *\n * @example\n * ```ts\n * import { VercelRuntimeCache } from \"effect-vercel/runtime-cache\"\n * import { Effect } from \"effect\"\n * import { PersistedCache } from \"effect/persistence\"\n *\n * const program = Effect.gen(function* () {\n * const users = yield* PersistedCache.make(fetchUser, {\n * storeId: \"users\",\n * timeToLive: () => \"1 hour\",\n * })\n * return yield* users.get(new GetUser({ id: 1 }))\n * }).pipe(Effect.scoped, Effect.provide(VercelRuntimeCache.layer))\n * ```\n */\n\nimport { createHash } from \"node:crypto\"\nimport { getCache, type RuntimeCache } from \"@vercel/functions\"\nimport { Duration, Effect, Layer } from \"effect\"\nimport { Persistence } from \"effect/persistence\"\n\nconst sha256 = (key: string) => createHash(\"sha256\").update(key).digest(\"hex\")\n\n/**\n * A `BackingPersistence` over `cache`.\n *\n * Entries are keyed by the JSON pair `[storeId, key]`, so no two stores share\n * a key. Each entry is tagged with a hash of the store id, since tags are\n * joined with `,` and sent unescaped, and `clear` expires that tag. Entries\n * are sent without a name, so keys don't reach Vercel's o11y or the request\n * headers, where non-Latin-1 characters would make the write fail. TTLs round\n * up to whole seconds, the cache's resolution.\n *\n * `getCache()` hashes keys with a 32-bit hash by default, which can collide.\n * Pass a cache made with a stronger `keyHashFunction`, as `layerBacking` does.\n */\nexport const makeBacking = (cache: RuntimeCache): Persistence.BackingPersistence[\"Service\"] =>\n Persistence.BackingPersistence.of({\n make: (storeId) =>\n Effect.sync(() => {\n const prefixed = (key: string) => JSON.stringify([storeId, key])\n const tag = `effect-persistence:${sha256(storeId)}`\n\n const get = (key: string) =>\n Effect.tryPromise({\n try: () => cache.get(prefixed(key)),\n catch: (cause) =>\n new Persistence.PersistenceError({ message: `Failed to get key ${key}`, cause }),\n }).pipe(\n Effect.map((value) =>\n typeof value === \"object\" && value !== null ? value : undefined,\n ),\n )\n\n const set = (key: string, value: object, ttl: Duration.Duration | undefined) =>\n Effect.tryPromise({\n try: () =>\n cache.set(prefixed(key), value, {\n name: \"\",\n tags: [tag],\n ...(ttl && { ttl: Math.max(1, Math.ceil(Duration.toSeconds(ttl))) }),\n }),\n catch: (cause) =>\n new Persistence.PersistenceError({ message: `Failed to set key ${key}`, cause }),\n })\n\n return {\n get,\n getMany: (keys) => Effect.forEach(keys, get, { concurrency: \"unbounded\" }),\n set,\n // Writes run concurrently, so keep only the last entry for each key.\n setMany: (entries) =>\n Effect.forEach(\n new Map(entries.map(([key, value, ttl]) => [key, [value, ttl] as const])),\n ([key, [value, ttl]]) => set(key, value, ttl),\n { concurrency: \"unbounded\", discard: true },\n ),\n remove: (key) =>\n Effect.tryPromise({\n try: () => cache.delete(prefixed(key)),\n catch: (cause) =>\n new Persistence.PersistenceError({ message: `Failed to remove key ${key}`, cause }),\n }),\n clear: Effect.tryPromise({\n try: () => cache.expireTag(tag),\n catch: (cause) =>\n new Persistence.PersistenceError({ message: `Failed to clear ${storeId}`, cause }),\n }),\n }\n }),\n })\n\n/** `BackingPersistence` over `getCache()`, with SHA-256 key hashing. */\nexport const layerBacking: Layer.Layer<Persistence.BackingPersistence> = Layer.sync(\n Persistence.BackingPersistence,\n)(() => makeBacking(getCache({ keyHashFunction: sha256 })))\n\n/** `Persistence` backed by the Vercel Runtime Cache. */\nexport const layer: Layer.Layer<Persistence.Persistence> = Persistence.layer.pipe(\n Layer.provide(layerBacking),\n)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,MAAM,UAAU,QAAgB,WAAW,QAAQ,CAAC,CAAC,OAAO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IAAE,SAAS,wBAAwB;IAAO;GAAM,CAAC;EACtF,CAAC;EACH,OAAO,OAAO,WAAW;GACvB,WAAW,MAAM,UAAU,GAAG;GAC9B,QAAQ,UACN,IAAI,YAAY,iBAAiB;IAAE,SAAS,mBAAmB;IAAW;GAAM,CAAC;EACrF,CAAC;CACH;AACF,CAAC,EACL,CAAC;;AAGH,MAAa,eAA4D,MAAM,KAC7E,YAAY,kBACd,CAAC,OAAO,YAAY,SAAS,EAAE,iBAAiB,OAAO,CAAC,CAAC,CAAC;;AAG1D,MAAa,QAA8C,YAAY,MAAM,KAC3E,MAAM,QAAQ,YAAY,CAC5B"}
|
package/src/VercelOidc.ts
DELETED
|
@@ -1,86 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The OIDC token Vercel issues to a deployment.
|
|
3
|
-
*
|
|
4
|
-
* In Functions the token arrives on each request as the `x-vercel-oidc-token`
|
|
5
|
-
* header and rotates, so it is read on every run of `token`/`find`, never
|
|
6
|
-
* cached. In builds and after `vercel env pull` it is `VERCEL_OIDC_TOKEN`.
|
|
7
|
-
* Use it to authenticate to the AI Gateway, or exchange it for cloud
|
|
8
|
-
* credentials (AWS `AssumeRoleWithWebIdentity`, GCP workload identity
|
|
9
|
-
* federation).
|
|
10
|
-
*
|
|
11
|
-
* @example
|
|
12
|
-
* ```ts
|
|
13
|
-
* import { VercelOidc } from "effect-vercel/oidc"
|
|
14
|
-
* import { Effect, Redacted } from "effect"
|
|
15
|
-
*
|
|
16
|
-
* const program = Effect.gen(function* () {
|
|
17
|
-
* const token = yield* VercelOidc.token
|
|
18
|
-
* // pass Redacted.value(token) as the web identity token
|
|
19
|
-
* })
|
|
20
|
-
* ```
|
|
21
|
-
*/
|
|
22
|
-
|
|
23
|
-
import { Config, Data, Effect, Option, Redacted } from "effect"
|
|
24
|
-
|
|
25
|
-
/** The environment variable read when no request carries a token. */
|
|
26
|
-
export const TOKEN_ENV = "VERCEL_OIDC_TOKEN"
|
|
27
|
-
|
|
28
|
-
/** No usable OIDC token. */
|
|
29
|
-
export class VercelOidcError extends Data.TaggedError("VercelOidcError")<{
|
|
30
|
-
readonly message: string
|
|
31
|
-
readonly hints: ReadonlyArray<string>
|
|
32
|
-
readonly cause?: unknown
|
|
33
|
-
}> {}
|
|
34
|
-
|
|
35
|
-
/** How to make a token available. */
|
|
36
|
-
export const hints: ReadonlyArray<string> = [
|
|
37
|
-
"Run on Vercel, where each request carries an OIDC token.",
|
|
38
|
-
`Or run \`vercel env pull\` locally to populate ${TOKEN_ENV}.`,
|
|
39
|
-
]
|
|
40
|
-
|
|
41
|
-
/**
|
|
42
|
-
* Vercel exposes the current request's context on a well-known global symbol.
|
|
43
|
-
* In Functions, the `x-vercel-oidc-token` header of the request lives there.
|
|
44
|
-
* Mirrors `@vercel/oidc`'s `getVercelOidcTokenSync`, minus the dev-time
|
|
45
|
-
* refresh that package also offers.
|
|
46
|
-
*/
|
|
47
|
-
const REQUEST_CONTEXT = Symbol.for("@vercel/request-context")
|
|
48
|
-
|
|
49
|
-
type RequestContext = { readonly headers?: Record<string, string | undefined> }
|
|
50
|
-
|
|
51
|
-
const fromRequestContext = Effect.sync(() => {
|
|
52
|
-
const holder = globalThis as typeof globalThis & {
|
|
53
|
-
[REQUEST_CONTEXT]?: { get?: () => RequestContext | undefined }
|
|
54
|
-
}
|
|
55
|
-
return Option.fromNullishOr(
|
|
56
|
-
holder[REQUEST_CONTEXT]?.get?.()?.headers?.["x-vercel-oidc-token"],
|
|
57
|
-
).pipe(Option.map(Redacted.make))
|
|
58
|
-
})
|
|
59
|
-
|
|
60
|
-
const fromEnv = Config.option(Config.Redacted(TOKEN_ENV)).pipe(
|
|
61
|
-
Effect.catchTag(
|
|
62
|
-
"ConfigError",
|
|
63
|
-
(cause) => new VercelOidcError({ message: `Failed to read ${TOKEN_ENV}.`, hints, cause }),
|
|
64
|
-
),
|
|
65
|
-
)
|
|
66
|
-
|
|
67
|
-
/**
|
|
68
|
-
* The token if one is available: the request header, else `VERCEL_OIDC_TOKEN`.
|
|
69
|
-
* `None` means neither is set, so a caller can fall back to something else.
|
|
70
|
-
*/
|
|
71
|
-
export const find: Effect.Effect<
|
|
72
|
-
Option.Option<Redacted.Redacted<string>>,
|
|
73
|
-
VercelOidcError
|
|
74
|
-
> = Effect.flatMap(fromRequestContext, (found) =>
|
|
75
|
-
Option.isSome(found) ? Effect.succeed(found) : fromEnv,
|
|
76
|
-
)
|
|
77
|
-
|
|
78
|
-
/** Like `find`, but fails when no token is available. */
|
|
79
|
-
export const token: Effect.Effect<Redacted.Redacted<string>, VercelOidcError> = Effect.flatMap(
|
|
80
|
-
find,
|
|
81
|
-
Option.match({
|
|
82
|
-
onNone: () =>
|
|
83
|
-
Effect.fail(new VercelOidcError({ message: "No Vercel OIDC token is available.", hints })),
|
|
84
|
-
onSome: Effect.succeed,
|
|
85
|
-
}),
|
|
86
|
-
)
|
package/src/ai-gateway.ts
DELETED
package/src/oidc.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * as VercelOidc from "./VercelOidc.js"
|
package/src/runtime-cache.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * as VercelRuntimeCache from "./VercelRuntimeCache.js"
|