domainkit 0.6.0 → 0.7.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 +13 -14
- package/dist/{canonical-json-9x7gHIoS.mjs → canonical-json-CQYKsZw7.mjs} +10 -4
- package/dist/canonical-json-CQYKsZw7.mjs.map +1 -0
- package/dist/{connect-Db830jad.d.mts → connect-10vHuShV.d.mts} +21 -7
- package/dist/{connect-ks3cpqBD.mjs → connect-oI8hcMxc.mjs} +4 -4
- package/dist/connect-oI8hcMxc.mjs.map +1 -0
- package/dist/{connection-DuYDgWir.d.mts → connection-C0xsU41C.d.mts} +2 -2
- package/dist/{connection-api-B__0M3PA.d.mts → connection-api-DW7xUJdj.d.mts} +2 -2
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +5 -4
- package/dist/index.mjs.map +1 -1
- package/dist/{managed-dns-connections-CaXts84E.mjs → managed-dns-connections-C3A_GBaz.mjs} +2 -2
- package/dist/{managed-dns-connections-CaXts84E.mjs.map → managed-dns-connections-C3A_GBaz.mjs.map} +1 -1
- package/dist/promise.d.mts +69 -10
- package/dist/promise.mjs +11 -6
- package/dist/promise.mjs.map +1 -1
- package/dist/{resolver-DxJPsq6l.mjs → resolver-DPJs8h0a.mjs} +46 -26
- package/dist/resolver-DPJs8h0a.mjs.map +1 -0
- package/dist/{resolver-DUAIlm2I.d.mts → resolver-DRrLm_hB.d.mts} +889 -15
- package/dist/server.d.mts +3 -3
- package/dist/server.mjs +3 -3
- package/dist/testing.d.mts +2 -2
- package/dist/testing.mjs +5 -7
- package/dist/testing.mjs.map +1 -1
- package/dist/{verify-yAy-r9no.d.mts → verify-C3V_GtzL.d.mts} +14 -4
- package/dist/{verify-DAtUAEeg.mjs → verify-DDnK8U7C.mjs} +20 -20
- package/dist/verify-DDnK8U7C.mjs.map +1 -0
- package/package.json +4 -2
- package/dist/canonical-json-9x7gHIoS.mjs.map +0 -1
- package/dist/connect-ks3cpqBD.mjs.map +0 -1
- package/dist/resolver-DxJPsq6l.mjs.map +0 -1
- package/dist/verify-DAtUAEeg.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"verify-DAtUAEeg.mjs","names":["S","Schema","decode","InvalidInputError","make","DomainName.Schema","DomainName.parse","Zones.candidates","Connection.authorizationError","DnsProvider.fromAsync","toAsync","DnsProvider.toAsync","DnsProvider.Error","Lifecycle.Service","Connection.authorizationError","Connection.assertAttachment","Connection.AuthorizationError","InvalidInputError","Provisioning.authorize","Secret.make","failure","clientAuthentication","Connection.Error","ErrorDetail","S","Record","RecordListEnvelope","Data","S","decode","DomainName.decode","decodeOpaque","failure","DnsRecord.decode","DnsRecord.Opaque","encode","DnsProvider.Error","discovery","failure","reason","decode","Protocol.ZoneListEnvelope","Protocol.TokenEnvelope","Zones.candidates","make","makeClient","Protocol.RecordListEnvelope","Records.decode","Records.encode","Protocol.RecordEnvelope","projectZone","candidates","DomainName.decode","S","Protocol.BaseEnvelope","DnsProvider.Error","Context","contextCodec","ProviderContext.codec","tokenMethod","manifest","Client.discoverAuthorizationAccount","Client.make","Client.validateDomainToken","tokenConnectionMethod","restore","failure","Connection.Error","AuthorizationCode.complete","Secret.make","AuthorizationCode.start","DnsProvider.Error","S","decode","DomainName.decode","DnsRecord.decode","failure","S","DnsRecord.Opaque","DnsProvider.Error","make","failure","Protocol.TeamListEnvelope","Protocol.DomainListEnvelope","Protocol.DomainConfig","Protocol.DomainEnvelope","DomainName.decode","Protocol.RecordListEnvelope","Records.decode","Records.encode","DnsProvider.Error","Protocol.CreateRecordEnvelope","Protocol.UserEnvelope","Zones.candidates","candidates","S","Protocol.ErrorEnvelope","Context","S","ProviderContext.codec","Protocol.ErrorEnvelope","Protocol.IntegrationToken","Secret.make","Client.make","Connection.Error","DnsProvider.Error","DomainName.parse","InvalidInputError","make","DnsResolver.Error","layer","DnsResolver.Service","toAsync","DnsResolver.toAsync","DomainName.parse","DomainName.decode","DnsData.parse","endpoint","make","DnsOverHttps.make","layer","DnsResolver.Service","toAsync","DnsResolver.toAsync","make","DnsOverHttps.make","DnsResolver.Service","DnsResolver.toAsync","observe","CloudflareDnsOverHttps.make","GoogleDnsOverHttps.make","DnsProvider.Service","DnsRecord.equals","InvalidInputError","DnsResolverPool.Service","DnsResolverPool.defaultMake","DnsData.parse","data","DnsRecord.data"],"sources":["../package.json","../src/auth/diagnostic.ts","../src/auth/manifest.ts","../src/auth/secret.ts","../src/discovery/selection.ts","../src/provider/session.ts","../src/plan/connection-authorization.ts","../src/auth/authorization-code.ts","../src/providers/cloudflare/protocol.ts","../src/providers/cloudflare/records.ts","../src/providers/cloudflare/client.ts","../src/providers/cloudflare/auth.ts","../src/providers/vercel/protocol.ts","../src/providers/vercel/records.ts","../src/providers/vercel/client.ts","../src/providers/vercel/auth.ts","../src/verification/dns-data.ts","../src/verification/doh.ts","../src/verification/cloudflare-doh.ts","../src/verification/google-doh.ts","../src/verification/resolver-pool.ts","../src/verification/verify.ts"],"sourcesContent":["","import { Schema } from \"effect\";\n\nexport const Category = Schema.Literals([\n \"authorization\",\n \"configuration\",\n \"provider\",\n \"storage\",\n \"validation\",\n]);\nexport type Category = typeof Category.Type;\n\nexport const RetryAdvice = Schema.Literals([\"never\", \"after-user-action\", \"safe\", \"unknown\"]);\nexport type RetryAdvice = typeof RetryAdvice.Type;\n\nexport const Fields = {\n category: Category,\n message: Schema.String,\n operation: Schema.String,\n retry: RetryAdvice,\n} as const;\n\nexport interface Diagnostic {\n readonly category: Category;\n readonly message: string;\n readonly operation: string;\n readonly retry: RetryAdvice;\n readonly tag: string;\n}\n\nexport function from(error: {\n readonly _tag: string;\n readonly category: Category;\n readonly message: string;\n readonly operation: string;\n readonly retry: RetryAdvice;\n}): Diagnostic {\n return {\n category: error.category,\n message: error.message,\n operation: error.operation,\n retry: error.retry,\n tag: error._tag,\n };\n}\n","import { Effect, Schema as S } from \"effect\";\nimport type * as oauth from \"oauth4webapi\";\n\nimport type * as DnsProvider from \"../provider/provider.ts\";\nimport { Error as InvalidInputError } from \"../invalid-input.ts\";\nimport type { Value as Secret } from \"./secret.ts\";\n\nexport const Method = S.TaggedUnion({\n integration: {\n capabilities: S.Array(S.Literals([\"dns:read\", \"dns:write\"])),\n installUrl: S.String,\n tokenEndpoint: S.String,\n },\n oauth2: {\n authorizationServer: S.Struct({\n authorization_endpoint: S.String,\n issuer: S.String,\n revocation_endpoint: S.optionalKey(S.String),\n token_endpoint: S.String,\n }),\n capabilities: S.Array(S.Literals([\"dns:read\", \"dns:write\"])),\n clientAuth: S.Literals([\"none\", \"client_secret_basic\", \"client_secret_post\"]),\n scopes: S.Array(S.String),\n },\n token: {\n capabilities: S.Array(S.Literals([\"dns:read\", \"dns:write\"])),\n instructionsUrl: S.String,\n },\n});\n\nexport const Schema = S.Struct({\n methods: S.Array(Method),\n providerId: S.String,\n});\nexport interface Manifest extends S.Schema.Type<typeof Schema> {}\nexport type OAuthMethod = Extract<Manifest[\"methods\"][number], { readonly _tag: \"oauth2\" }>;\n/** A provider-owned installation flow that returns a credential from a one-time code. */\nexport type IntegrationMethod = Extract<\n Manifest[\"methods\"][number],\n { readonly _tag: \"integration\" }\n>;\n\nexport const decode = Effect.fn(\"ProviderAuth.decode\")((input: unknown) =>\n S.decodeUnknownEffect(Schema)(input).pipe(\n Effect.mapError((cause) => new InvalidInputError({ message: cause.message })),\n ),\n);\n\nexport interface OAuthClientConfiguration {\n readonly clientId: string;\n readonly clientSecret?: Secret;\n}\n\nexport interface TokenValidation {\n readonly accountId: string;\n readonly capabilities: ReadonlyArray<\"dns:read\" | \"dns:write\">;\n readonly expiresAt: Date | null;\n readonly scopes: ReadonlyArray<string>;\n}\n\nexport interface OAuthSubjectResolver {\n (\n tokens: oauth.TokenEndpointResponse,\n accessToken: Secret,\n ): Effect.Effect<\n { readonly accountId: string; readonly expiresAt: Date | null },\n DnsProvider.Error\n >;\n}\n\nexport interface AsyncOAuthSubjectResolver {\n (\n tokens: oauth.TokenEndpointResponse,\n accessToken: Secret,\n ): Promise<{ readonly accountId: string; readonly expiresAt: Date | null }>;\n}\n","/** A deliberately non-serializable credential value. */\nexport class Value {\n readonly #value: string;\n\n private constructor(value: string) {\n this.#value = value;\n }\n\n static from(value: string): Value {\n if (value.length === 0) throw new Error(\"Secret values cannot be empty\");\n return new Value(value);\n }\n\n expose(): string {\n return this.#value;\n }\n\n toJSON(): string {\n return \"[REDACTED]\";\n }\n\n toString(): string {\n return \"[REDACTED]\";\n }\n}\n\nexport const make = Value.from;\n","import { Schema } from \"effect\";\n\nimport * as ProviderAuthorization from \"../auth/authorization.ts\";\nimport * as Connection from \"../auth/connection.ts\";\nimport * as DomainName from \"../domain/domain-name.ts\";\nimport * as Zones from \"./zones.ts\";\n\nexport interface ConnectedZone {\n readonly authorization: ProviderAuthorization.ProviderAuthorization;\n readonly attachment: Connection.DomainAttachment;\n readonly connection: Connection.ProviderConnection;\n readonly nameservers: ReadonlyArray<string>;\n}\n\nexport const Evidence = Schema.Struct({\n accountId: Schema.String,\n connectionId: Schema.String,\n decisiveNameserverMatch: Schema.Boolean,\n matchedNameservers: Schema.Array(DomainName.Schema),\n providerId: Schema.String,\n zone: DomainName.Schema,\n});\nexport interface Evidence extends Schema.Schema.Type<typeof Evidence> {}\n\nexport const Selection = Schema.TaggedUnion({\n selected: {\n candidate: Evidence,\n evidence: Schema.Array(Evidence),\n reason: Schema.Literals([\"explicit\", \"unique-nameserver-match\"]),\n },\n manual: {\n evidence: Schema.Array(Evidence),\n reason: Schema.Literals([\"ambiguous\", \"unsupported\"]),\n },\n});\nexport type Selection = typeof Selection.Type;\n\nexport function select(input: {\n readonly authoritativeNameservers: ReadonlyArray<string>;\n readonly connectedZones: ReadonlyArray<ConnectedZone>;\n readonly domain: string;\n readonly explicit?: {\n readonly accountId: string;\n readonly providerId: string;\n readonly zone: string;\n };\n readonly now?: Date;\n}): Selection {\n const domain = DomainName.parse(input.domain);\n const zoneCandidates = new Set(Zones.candidates(domain));\n const authoritative = nameserverSet(input.authoritativeNameservers);\n const eligible = input.connectedZones.filter((connected) => {\n if (!zoneCandidates.has(connected.attachment.target.zoneName)) return false;\n try {\n Connection.assertAttachment({\n attachment: connected.attachment,\n capability: \"dns:read\",\n connection: connected.connection,\n domain,\n ...(input.now === undefined ? {} : { now: input.now }),\n providerId: connected.connection.providerId,\n authorization: connected.authorization,\n });\n return true;\n } catch {\n return false;\n }\n });\n const evidence = eligible.map((connected) => evidenceFor(connected, authoritative));\n\n if (input.explicit !== undefined) {\n const explicitZone = DomainName.parse(input.explicit.zone);\n const index = eligible.findIndex(\n (connected) =>\n connected.connection.providerId === input.explicit?.providerId &&\n connected.attachment.target.accountId === input.explicit.accountId &&\n connected.attachment.target.zoneName === explicitZone,\n );\n if (index < 0) {\n throw Connection.authorizationError(\n \"Explicit provider zone is not connected for this domain\",\n \"ProviderDiscovery.select\",\n );\n }\n const candidate = evidence[index];\n if (candidate === undefined) throw new Error(\"Eligible provider evidence is missing\");\n return { _tag: \"selected\", candidate, evidence, reason: \"explicit\" };\n }\n\n const decisive = evidence.filter(({ decisiveNameserverMatch }) => decisiveNameserverMatch);\n const candidate = decisive[0];\n return decisive.length === 1 && candidate !== undefined\n ? { _tag: \"selected\", candidate, evidence, reason: \"unique-nameserver-match\" }\n : {\n _tag: \"manual\",\n evidence,\n reason: decisive.length > 1 ? \"ambiguous\" : \"unsupported\",\n };\n}\n\nfunction evidenceFor(\n connected: ConnectedZone,\n authoritative: ReadonlyArray<DomainName.DomainName>,\n): Evidence {\n const configured = new Set(nameserverSet(connected.nameservers));\n const matchedNameservers = authoritative.filter((nameserver) => configured.has(nameserver));\n return {\n accountId: connected.attachment.target.accountId,\n connectionId: connected.connection.id,\n decisiveNameserverMatch:\n authoritative.length > 0 && matchedNameservers.length === authoritative.length,\n matchedNameservers,\n providerId: connected.connection.providerId,\n zone: connected.attachment.target.zoneName,\n };\n}\n\nfunction nameserverSet(nameservers: ReadonlyArray<string>): ReadonlyArray<DomainName.DomainName> {\n return [...new Set(nameservers.map(DomainName.parse))].sort();\n}\n","import { Data, Effect } from \"effect\";\n\nimport type * as Connection from \"../auth/connection.ts\";\nimport type * as ProviderAuthorization from \"../auth/authorization.ts\";\nimport type * as Secret from \"../auth/secret.ts\";\nimport type * as DomainName from \"../domain/domain-name.ts\";\nimport * as DnsProvider from \"./provider.ts\";\n\n/** A credential-scoped provider session that discovers safe targets before DNS access. */\nexport interface Interface {\n /** The provider represented by this credential. */\n readonly providerId: string;\n /** Lists provider account and authoritative-zone targets visible to this credential. */\n readonly listTargets: (\n input?: ListTargetsInput,\n ) => Effect.Effect<ReadonlyArray<Connection.ProviderTarget>, DnsProvider.Error>;\n /** Resolves a domain without guessing when more than one account owns a matching zone. */\n readonly resolveTarget: (\n domain: DomainName.DomainName,\n ) => Effect.Effect<Resolution, DnsProvider.Error>;\n /** Creates the focused DNS-record capability bound to one exact discovered target. */\n readonly forTarget: (\n target: Connection.ProviderTarget,\n ) => Effect.Effect<DnsProvider.Interface, DnsProvider.Error>;\n}\n\nexport interface ListTargetsInput {\n /** Restrict results to the authoritative zone candidates for this domain. */\n readonly domain?: DomainName.DomainName;\n /** Provider-specific account filter, when supported by the adapter. */\n readonly accountId?: string;\n}\n\nexport type Resolution = Data.TaggedEnum<{\n NotFound: { readonly domain: DomainName.DomainName };\n Resolved: { readonly target: Connection.ProviderTarget };\n SelectionRequired: { readonly candidates: ReadonlyArray<Connection.ProviderTarget> };\n}>;\nexport const Resolution = Data.taggedEnum<Resolution>();\n\n/** The credential material a provider adapter needs to restore a session. */\nexport interface Credential {\n readonly accessToken: Secret.Value;\n readonly expiresAt: Date | null;\n readonly refreshToken: Secret.Value | null;\n readonly tokenType: string;\n}\n\n/** The non-secret authorization projection required when restoring a provider session. */\nexport type Authorization = Pick<\n ProviderAuthorization.ProviderAuthorization,\n | \"capabilityEvidence\"\n | \"method\"\n | \"providerContext\"\n | \"providerId\"\n | \"requiredCapabilities\"\n | \"revocation\"\n>;\n\nexport interface RestoreInput {\n readonly authorization: Authorization;\n readonly credential: Credential;\n}\n\n/** Minimal Promise-shaped provider-session contract for hosts that do not use Effect directly. */\nexport interface AsyncInterface {\n readonly providerId: string;\n readonly listTargets: (\n input?: ListTargetsInput,\n ) => Promise<ReadonlyArray<Connection.ProviderTarget>>;\n readonly resolveTarget: (domain: DomainName.DomainName) => Promise<Resolution>;\n readonly forTarget: (target: Connection.ProviderTarget) => Promise<DnsProvider.AsyncInterface>;\n}\n\n/** Adapts a Promise-shaped session to the Effect-native session boundary. */\nexport const fromAsync = (session: AsyncInterface): Interface => ({\n providerId: session.providerId,\n listTargets: (input) =>\n Effect.tryPromise({\n try: () => session.listTargets(input),\n catch: (cause) => sessionFailure(session.providerId, \"listTargets\", cause),\n }),\n resolveTarget: (domain) =>\n Effect.tryPromise({\n try: () => session.resolveTarget(domain),\n catch: (cause) => sessionFailure(session.providerId, \"resolveTarget\", cause),\n }),\n forTarget: (target) =>\n Effect.tryPromise({\n try: () => session.forTarget(target),\n catch: (cause) => sessionFailure(session.providerId, \"forTarget\", cause),\n }).pipe(Effect.map(DnsProvider.fromAsync)),\n});\n\n/** Adapts an Effect-native session to the Promise facade. */\nexport const toAsync = (session: Interface): AsyncInterface => ({\n providerId: session.providerId,\n listTargets: (input) => Effect.runPromise(session.listTargets(input)),\n resolveTarget: (domain) => Effect.runPromise(session.resolveTarget(domain)),\n forTarget: (target) => Effect.runPromise(session.forTarget(target)).then(DnsProvider.toAsync),\n});\n\nfunction sessionFailure(providerId: string, operation: string, cause: unknown): DnsProvider.Error {\n return cause instanceof DnsProvider.Error\n ? cause\n : new DnsProvider.Error({\n message: cause instanceof globalThis.Error ? cause.message : String(cause),\n operation: `ProviderSession.${operation}`,\n providerId,\n reason: \"transport\",\n });\n}\n","import { Crypto, Effect } from \"effect\";\n\nimport * as Connection from \"../auth/connection.ts\";\nimport * as ProviderAuthorization from \"../auth/authorization.ts\";\nimport * as Lifecycle from \"../auth/lifecycle-repository.ts\";\nimport { Error as InvalidInputError } from \"../invalid-input.ts\";\nimport { CryptoError } from \"./canonical-json.ts\";\nimport * as Provisioning from \"./plan.ts\";\nimport type * as DnsPlan from \"./types.ts\";\n\nexport const authorize = Effect.fn(\"ConnectionAuthorization.authorize\")(function* (input: {\n readonly allowPartial?: boolean;\n readonly authorization: ProviderAuthorization.ProviderAuthorization;\n readonly connection: Connection.ProviderConnection | Connection.StoredConnection;\n readonly domain: string;\n readonly attachment: Connection.DomainAttachment;\n readonly operationIds?: ReadonlyArray<string>;\n readonly plan: DnsPlan.DnsPlan;\n}) {\n const lifecycle = yield* Lifecycle.Service;\n const aggregate = yield* lifecycle.getByConnectionId(input.connection.id);\n const storedConnection = aggregate?.connections.find(({ id }) => id === input.connection.id);\n const storedAttachment = aggregate?.attachments.find(({ id }) => id === input.attachment.id);\n if (\n aggregate === null ||\n storedConnection === undefined ||\n storedAttachment === undefined ||\n storedConnection.ownerId !== input.connection.ownerId ||\n storedConnection.providerId !== input.connection.providerId ||\n storedConnection.method !== aggregate.authorization.method ||\n storedConnection.authorizationId !== input.authorization.id ||\n storedAttachment.connectionId !== storedConnection.id\n ) {\n return yield* Connection.authorizationError(\n \"Domain attachment is not owned by the active provider connection\",\n \"ConnectionAuthorization.authorize\",\n );\n }\n const domain = yield* Effect.try({\n try: () =>\n Connection.assertAttachment({\n attachment: storedAttachment,\n capability: \"dns:write\",\n authorization: aggregate.authorization,\n connection: storedConnection,\n credential: aggregate.credential,\n domain: input.domain,\n providerId: input.plan.providerId,\n }),\n catch: (cause) =>\n cause instanceof Connection.AuthorizationError || cause instanceof InvalidInputError\n ? cause\n : Connection.authorizationError(\n \"Domain attachment is invalid\",\n \"ConnectionAuthorization.authorize\",\n ),\n });\n const authorization = yield* Provisioning.authorize(\n input.plan,\n input.operationIds,\n input.allowPartial === undefined ? {} : { allowPartial: input.allowPartial },\n );\n const selected = new Set(authorization.operationIds);\n const outsideAttachment = input.plan.operations.filter(\n (operation) =>\n operation._tag === \"create\" &&\n selected.has(operation.id) &&\n operation.requirement.name !== domain &&\n !operation.requirement.name.endsWith(`.${domain}`),\n );\n if (outsideAttachment.length > 0) {\n return yield* Connection.authorizationError(\n `Plan operations are outside the attached domain ${domain}`,\n \"ConnectionAuthorization.authorize\",\n );\n }\n return authorization;\n});\n\nexport type Error =\n | Connection.AuthorizationError\n | InvalidInputError\n | CryptoError\n | Lifecycle.Error;\nexport type Requirements = Crypto.Crypto | Lifecycle.Service;\n","import { Crypto, Effect, Schema } from \"effect\";\nimport * as oauth from \"oauth4webapi\";\n\nimport type * as ProviderAuth from \"./manifest.ts\";\nimport * as Connection from \"./connect.ts\";\nimport * as Secret from \"./secret.ts\";\n\nexport type Fetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n\nexport interface Payload {\n readonly codeVerifier: string;\n readonly redirectUri: string;\n readonly state: string;\n}\n\nexport const start = Effect.fn(\"AuthorizationCode.start\")(function* (input: {\n readonly client: ProviderAuth.OAuthClientConfiguration;\n readonly method: ProviderAuth.OAuthMethod;\n readonly redirectUri: string;\n readonly state: string;\n}) {\n const crypto = yield* Crypto.Crypto;\n const codeVerifier = base64Url(yield* randomBytes(crypto, 32));\n const challenge = base64Url(yield* digest(crypto, codeVerifier));\n const authorizationUrl = new URL(input.method.authorizationServer.authorization_endpoint);\n authorizationUrl.search = new URLSearchParams({\n client_id: input.client.clientId,\n code_challenge: challenge,\n code_challenge_method: \"S256\",\n redirect_uri: input.redirectUri,\n response_type: \"code\",\n scope: input.method.scopes.join(\" \"),\n state: input.state,\n }).toString();\n return {\n authorizationUrl,\n payload: Secret.make(\n JSON.stringify({ codeVerifier, redirectUri: input.redirectUri, state: input.state }),\n ),\n };\n});\n\nexport const complete = Effect.fn(\"AuthorizationCode.complete\")(function* (input: {\n readonly callbackUrl: URL;\n readonly client: ProviderAuth.OAuthClientConfiguration;\n readonly fetch?: Fetch;\n readonly method: ProviderAuth.OAuthMethod;\n readonly payload: Secret.Value;\n readonly providerId: string;\n}) {\n const payload = yield* decodePayload(input.payload);\n if (input.callbackUrl.searchParams.get(\"state\") !== payload.state) {\n return yield* failure(\"Authorization callback state does not match its continuation\");\n }\n const server = input.method.authorizationServer as oauth.AuthorizationServer;\n const client: oauth.Client = { client_id: input.client.clientId };\n const authentication = yield* clientAuthentication(input.method, input.client);\n return yield* Effect.tryPromise({\n try: async (signal) => {\n const callback = oauth.validateAuthResponse(server, client, input.callbackUrl, payload.state);\n const response = await oauth.authorizationCodeGrantRequest(\n server,\n client,\n authentication,\n callback,\n payload.redirectUri,\n payload.codeVerifier,\n requestOptions(input.fetch, signal),\n );\n return oauth.processAuthorizationCodeResponse(server, client, response);\n },\n catch: (cause) =>\n new Connection.Error({\n category: \"provider\",\n message: cause instanceof globalThis.Error ? cause.name : \"OAuth provider request failed\",\n operation: \"AuthorizationCode.complete\",\n retry: \"unknown\",\n }),\n });\n});\n\nconst PayloadSchema = Schema.Struct({\n codeVerifier: Schema.String,\n redirectUri: Schema.String,\n state: Schema.String,\n});\n\nfunction decodePayload(payload: Secret.Value): Effect.Effect<Payload, Connection.Error> {\n return Schema.decodeUnknownEffect(Schema.fromJsonString(PayloadSchema))(payload.expose()).pipe(\n Effect.mapError(\n () =>\n new Connection.Error({\n category: \"authorization\",\n message: \"OAuth continuation payload is invalid\",\n operation: \"AuthorizationCode\",\n retry: \"after-user-action\",\n }),\n ),\n );\n}\n\nfunction clientAuthentication(\n method: ProviderAuth.OAuthMethod,\n client: ProviderAuth.OAuthClientConfiguration,\n): Effect.Effect<oauth.ClientAuth, Connection.Error> {\n switch (method.clientAuth) {\n case \"none\":\n return Effect.succeed(oauth.None());\n case \"client_secret_basic\":\n return client.clientSecret === undefined\n ? failure(\"OAuth client secret is required\")\n : Effect.succeed(oauth.ClientSecretBasic(client.clientSecret.expose()));\n case \"client_secret_post\":\n return client.clientSecret === undefined\n ? failure(\"OAuth client secret is required\")\n : Effect.succeed(oauth.ClientSecretPost(client.clientSecret.expose()));\n }\n}\n\nfunction requestOptions(\n fetchImplementation: Fetch | undefined,\n signal: AbortSignal,\n): oauth.TokenEndpointRequestOptions {\n return fetchImplementation === undefined\n ? { signal }\n : {\n signal,\n [oauth.customFetch]: (url, options) =>\n fetchImplementation(url, { ...options, body: options.body }),\n };\n}\n\nconst failure = (message: string): Effect.Effect<never, Connection.Error> =>\n Effect.fail(\n new Connection.Error({\n category: \"authorization\",\n message,\n operation: \"AuthorizationCode\",\n retry: \"after-user-action\",\n }),\n );\n\nfunction randomBytes(\n crypto: Crypto.Crypto,\n size: number,\n): Effect.Effect<Uint8Array, Connection.Error> {\n return crypto.randomBytes(size).pipe(\n Effect.mapError(\n (cause) =>\n new Connection.Error({\n category: \"validation\",\n message: cause.message,\n operation: \"AuthorizationCode.start\",\n retry: \"safe\",\n }),\n ),\n );\n}\n\nfunction digest(crypto: Crypto.Crypto, value: string): Effect.Effect<Uint8Array, Connection.Error> {\n return crypto.digest(\"SHA-256\", new TextEncoder().encode(value)).pipe(\n Effect.mapError(\n (cause) =>\n new Connection.Error({\n category: \"validation\",\n message: cause.message,\n operation: \"AuthorizationCode.start\",\n retry: \"safe\",\n }),\n ),\n );\n}\n\nfunction base64Url(bytes: Uint8Array): string {\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\").replaceAll(\"=\", \"\");\n}\n","import { Schema as S } from \"effect\";\n\nexport const ErrorDetail = S.Struct({\n code: S.Number,\n message: S.String,\n});\nexport interface ErrorDetail extends S.Schema.Type<typeof ErrorDetail> {}\n\nexport const ResultInfo = S.Struct({\n count: S.optionalKey(S.Number),\n page: S.optionalKey(S.Number),\n per_page: S.optionalKey(S.Number),\n total_count: S.optionalKey(S.Number),\n total_pages: S.optionalKey(S.Number),\n});\n\nconst Message = S.Struct({\n code: S.optionalKey(S.Number),\n message: S.String,\n});\n\nexport const BaseEnvelope = S.Struct({\n errors: S.Array(ErrorDetail),\n messages: S.Array(Message),\n success: S.Boolean,\n});\n\nexport const Account = S.Struct({\n id: S.String,\n name: S.String,\n});\nexport interface Account extends S.Schema.Type<typeof Account> {}\n\nexport const Zone = S.Struct({\n account: Account,\n id: S.String,\n name: S.String,\n name_servers: S.Array(S.String),\n status: S.optionalKey(S.String),\n type: S.optionalKey(S.Literals([\"full\", \"partial\", \"secondary\", \"internal\"])),\n});\nexport interface Zone extends S.Schema.Type<typeof Zone> {}\n\nexport const Record = S.Struct({\n content: S.optionalKey(S.String),\n data: S.optionalKey(S.Unknown),\n id: S.String,\n name: S.String,\n priority: S.optionalKey(S.Number),\n proxied: S.optionalKey(S.Boolean),\n ttl: S.Number,\n type: S.String,\n});\nexport interface Record extends S.Schema.Type<typeof Record> {}\n\nexport const Token = S.Struct({\n expires_on: S.optionalKey(S.String),\n id: S.String,\n not_before: S.optionalKey(S.String),\n status: S.Literals([\"active\", \"disabled\", \"expired\"]),\n});\nexport interface Token extends S.Schema.Type<typeof Token> {}\n\nexport const ZoneListEnvelope = S.Struct({\n errors: S.Array(ErrorDetail),\n messages: S.Array(Message),\n result: S.Array(Zone),\n result_info: S.optionalKey(ResultInfo),\n success: S.Boolean,\n});\nexport const RecordListEnvelope = S.Struct({\n errors: S.Array(ErrorDetail),\n messages: S.Array(Message),\n result: S.Array(Record),\n result_info: S.optionalKey(ResultInfo),\n success: S.Boolean,\n});\nexport const RecordEnvelope = S.Struct({\n errors: S.Array(ErrorDetail),\n messages: S.Array(Message),\n result: Record,\n success: S.Boolean,\n});\nexport const TokenEnvelope = S.Struct({\n errors: S.Array(ErrorDetail),\n messages: S.Array(Message),\n result: Token,\n success: S.Boolean,\n});\n","import { Effect, Schema as S } from \"effect\";\n\nimport * as DomainName from \"../../domain/domain-name.ts\";\nimport * as DnsRecord from \"../../domain/dns-record.ts\";\nimport * as DnsProvider from \"../../provider/provider.ts\";\nimport type * as Protocol from \"./protocol.ts\";\n\nconst Data = S.Struct({\n flags: S.optionalKey(S.Number),\n port: S.optionalKey(S.Number),\n priority: S.optionalKey(S.Number),\n tag: S.optionalKey(S.String),\n target: S.optionalKey(S.String),\n value: S.optionalKey(S.String),\n weight: S.optionalKey(S.Number),\n});\n\nexport type CreateBody = Readonly<Record<string, unknown>>;\n\nexport const decode = Effect.fn(\"CloudflareRecords.decode\")((record: Protocol.Record) =>\n Effect.gen(function* () {\n const name = yield* DomainName.decode(record.name).pipe(\n Effect.match({ onFailure: () => null, onSuccess: (value) => value }),\n );\n if (name === null) return yield* decodeOpaque(record);\n const common = {\n metadata: {\n ownership: \"provider\",\n provenance: record.proxied === true ? \"cloudflare:proxied\" : \"cloudflare\",\n purpose: \"existing DNS record\",\n },\n name,\n policy: record.type === \"CNAME\" ? \"exclusive\" : \"append\",\n ttl: record.ttl === 1 ? null : record.ttl,\n } as const;\n const content = () =>\n record.content === undefined\n ? Effect.fail(failure(\"decodeRecord\", `Cloudflare ${record.type} record has no content`))\n : Effect.succeed(record.content);\n\n switch (record.type) {\n case \"A\":\n case \"AAAA\":\n return yield* DnsRecord.decode({\n ...common,\n _tag: record.type,\n address: yield* content(),\n }).pipe(Effect.mapError((cause) => failure(\"decodeRecord\", cause.message)));\n case \"CNAME\":\n case \"NS\":\n return yield* DnsRecord.decode({\n ...common,\n _tag: record.type,\n target: yield* content(),\n }).pipe(Effect.mapError((cause) => failure(\"decodeRecord\", cause.message)));\n case \"TXT\":\n return yield* DnsRecord.decode({\n ...common,\n _tag: \"TXT\",\n value: yield* content(),\n }).pipe(Effect.mapError((cause) => failure(\"decodeRecord\", cause.message)));\n case \"MX\":\n return yield* DnsRecord.decode({\n ...common,\n _tag: \"MX\",\n exchange: yield* content(),\n priority: record.priority,\n }).pipe(Effect.mapError((cause) => failure(\"decodeRecord\", cause.message)));\n case \"CAA\": {\n const data = yield* decodeData(record);\n return yield* DnsRecord.decode({ ...common, _tag: \"CAA\", ...data }).pipe(\n Effect.mapError((cause) => failure(\"decodeRecord\", cause.message)),\n );\n }\n case \"SRV\": {\n const data = yield* decodeData(record);\n return yield* DnsRecord.decode({ ...common, _tag: \"SRV\", ...data }).pipe(\n Effect.mapError((cause) => failure(\"decodeRecord\", cause.message)),\n );\n }\n default:\n return yield* decodeOpaque(record);\n }\n }),\n);\n\nconst decodeOpaque = Effect.fn(\"CloudflareRecords.decodeOpaque\")((record: Protocol.Record) =>\n S.decodeUnknownEffect(DnsRecord.Opaque)({\n _tag: \"Opaque\",\n name: record.name,\n providerRecordId: record.id,\n providerType: record.type,\n }).pipe(Effect.mapError((cause) => failure(\"decodeRecord\", cause.message))),\n);\n\nexport function encode(record: DnsRecord.DnsRecord): CreateBody {\n const common = {\n name: record.name,\n proxied: false,\n ttl: record.ttl ?? 1,\n type: record._tag,\n };\n switch (record._tag) {\n case \"A\":\n case \"AAAA\":\n return { ...common, content: record.address };\n case \"CNAME\":\n case \"NS\":\n return { ...common, content: record.target };\n case \"TXT\":\n return { ...common, content: record.value };\n case \"MX\":\n return { ...common, content: record.exchange, priority: record.priority };\n case \"CAA\":\n return {\n ...common,\n data: { flags: record.flags, tag: record.tag, value: record.value },\n };\n case \"SRV\":\n return {\n ...common,\n data: {\n port: record.port,\n priority: record.priority,\n target: record.target,\n weight: record.weight,\n },\n };\n }\n}\n\nconst decodeData = Effect.fn(\"CloudflareRecords.decodeData\")((record: Protocol.Record) =>\n S.decodeUnknownEffect(Data)(record.data).pipe(\n Effect.mapError((cause) => failure(\"decodeRecord\", cause.message)),\n ),\n);\n\nfunction failure(\n operation: string,\n message: string,\n fields: Partial<Pick<DnsProvider.Error, \"reason\">> = {},\n): DnsProvider.Error {\n return new DnsProvider.Error({\n message,\n operation,\n providerId: \"cloudflare\",\n reason: fields.reason ?? \"response\",\n });\n}\n","import { Effect, Schema as S } from \"effect\";\n\nimport type * as ProviderAuth from \"../../auth/manifest.ts\";\nimport type * as Secret from \"../../auth/secret.ts\";\nimport * as Connection from \"../../auth/connection.ts\";\nimport * as DomainName from \"../../domain/domain-name.ts\";\nimport type * as DnsRecord from \"../../domain/dns-record.ts\";\nimport type * as ZoneDiscovery from \"../../discovery/zone-discovery.ts\";\nimport * as Zones from \"../../discovery/zones.ts\";\nimport * as DnsProvider from \"../../provider/provider.ts\";\nimport * as ProviderSession from \"../../provider/session.ts\";\nimport * as Protocol from \"./protocol.ts\";\nimport * as Records from \"./records.ts\";\n\nexport type Fetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n\n/** Configuration for an Effect-native Cloudflare authoritative-DNS client. */\nexport interface Options {\n /** Account scope for account tokens; omit for user or OAuth credentials. */\n readonly accountId?: string;\n readonly baseUrl?: string;\n /** Capabilities the host required when issuing or authorizing this credential. */\n readonly capabilities: ProviderAuth.TokenValidation[\"capabilities\"];\n readonly fetch?: Fetch;\n readonly token: Secret.Value;\n readonly tokenKind?: \"account\" | \"user\";\n}\n\nexport interface ListZonesInput {\n readonly accountId?: string;\n readonly name?: DomainName.DomainName;\n}\n\nexport type Account = Protocol.Account;\n\n/** A portable Cloudflare authoritative zone with normalized nameserver evidence. */\nexport interface Zone {\n readonly accountId: string;\n readonly id: string;\n readonly name: DomainName.DomainName;\n readonly nameservers: ReadonlyArray<DomainName.DomainName>;\n readonly status: string | null;\n}\n\nexport interface Interface extends DnsProvider.Interface {\n readonly providerId: \"cloudflare\";\n readonly forTarget: (\n target: Connection.ProviderTarget,\n ) => Effect.Effect<DnsProvider.Interface, DnsProvider.Error>;\n readonly listAccounts: () => Effect.Effect<ReadonlyArray<Account>, DnsProvider.Error>;\n readonly listZones: (\n input?: ListZonesInput,\n ) => Effect.Effect<ReadonlyArray<Zone>, DnsProvider.Error>;\n readonly listTargets: (\n input?: ProviderSession.ListTargetsInput,\n ) => Effect.Effect<ReadonlyArray<Connection.ProviderTarget>, DnsProvider.Error>;\n readonly resolveTarget: (\n domain: DomainName.DomainName,\n ) => Effect.Effect<ProviderSession.Resolution, DnsProvider.Error>;\n readonly validateToken: () => Effect.Effect<ProviderAuth.TokenValidation, DnsProvider.Error>;\n}\n\n/** Exposes Cloudflare zone lookup as the optional provider discovery capability. */\nexport function discovery(client: Interface): ZoneDiscovery.Source {\n return {\n listZones: (name) =>\n client.listZones({ name }).pipe(\n Effect.map((zones) =>\n zones.map((zone) => ({\n ...zone,\n status: zone.status === \"active\" || zone.status === \"pending\" ? zone.status : \"unknown\",\n })),\n ),\n ),\n provider: client,\n };\n}\n\ninterface CredentialOptions {\n readonly baseUrl?: string;\n readonly fetch?: Fetch;\n readonly token: Secret.Value;\n}\n\ninterface DomainCredentialOptions extends CredentialOptions {\n readonly capabilities: ProviderAuth.TokenValidation[\"capabilities\"];\n readonly domain: DomainName.DomainName;\n readonly tokenKind?: \"account\" | \"user\";\n}\n\ninterface TargetOptions {\n readonly target: Connection.ProviderTarget;\n}\n\ntype InternalOptions = Options & Partial<TargetOptions>;\n\nconst makeTransport = (options: CredentialOptions) => {\n const fetch = options.fetch ?? globalThis.fetch;\n const baseUrl = (options.baseUrl ?? \"https://api.cloudflare.com/client/v4\").replace(/\\/$/, \"\");\n\n const request = Effect.fn(\"CloudflareClient.request\")(\n (path: string, operation: string, init?: RequestInit) =>\n Effect.gen(function* () {\n const response = yield* Effect.tryPromise({\n try: () =>\n fetch(`${baseUrl}${path}`, {\n ...init,\n headers: {\n Accept: \"application/json\",\n Authorization: `Bearer ${options.token.expose()}`,\n ...(init?.body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n ...init?.headers,\n },\n }),\n catch: () =>\n failure(operation, \"Cloudflare request failed\", {\n reason: \"transport\",\n }),\n });\n const body = yield* Effect.tryPromise({\n try: () => response.json() as Promise<unknown>,\n catch: () => {\n const retryAfterMs = retryAfter(response.headers.get(\"retry-after\"));\n return failure(\n operation,\n response.ok\n ? \"Cloudflare returned a non-JSON response\"\n : `Cloudflare request failed with HTTP ${response.status}`,\n {\n reason: response.ok ? \"response\" : reason(response.status),\n ...(retryAfterMs === undefined ? {} : { retryAfterMs }),\n status: response.status,\n },\n );\n },\n });\n return { body, response } as const;\n }),\n );\n\n const listZonesPage = Effect.fn(\"CloudflareClient.listZonesPage\")(\n (accountId: string | undefined, name: DomainName.DomainName | undefined, page: number) =>\n Effect.gen(function* () {\n const query = new URLSearchParams({ page: String(page), per_page: \"50\" });\n query.set(\"type\", \"full,partial,secondary,internal\");\n if (accountId !== undefined) query.set(\"account.id\", accountId);\n if (name !== undefined) query.set(\"name\", name);\n const { body, response } = yield* request(`/zones?${query}`, \"listZones\");\n yield* ensureSuccess(body, \"listZones\", response);\n return yield* decode(Protocol.ZoneListEnvelope, body, \"listZones\", response);\n }),\n );\n\n const allZones = Effect.fn(\"CloudflareClient.allZones\")(\n (accountId?: string, name?: DomainName.DomainName) =>\n Effect.gen(function* () {\n const zones: Array<Protocol.Zone> = [];\n let page = 1;\n while (true) {\n const envelope = yield* listZonesPage(accountId, name, page);\n zones.push(...envelope.result);\n const totalPages = envelope.result_info?.total_pages;\n if (\n (totalPages !== undefined && page >= totalPages) ||\n (totalPages === undefined && envelope.result.length < 50)\n ) {\n return zones;\n }\n page += 1;\n }\n }),\n );\n\n const inspectToken = Effect.fn(\"CloudflareClient.inspectToken\")((path: string) =>\n Effect.gen(function* () {\n const { body, response } = yield* request(path, \"validateToken\");\n yield* ensureSuccess(body, \"validateToken\", response);\n const envelope = yield* decode(Protocol.TokenEnvelope, body, \"validateToken\", response);\n if (envelope.result.status !== \"active\") {\n return yield* Effect.fail(\n failure(\"validateToken\", `Cloudflare token is ${envelope.result.status}`, {\n reason: \"authentication\",\n status: response.status,\n }),\n );\n }\n const expiresAt =\n envelope.result.expires_on === undefined ? null : new Date(envelope.result.expires_on);\n if (expiresAt !== null && Number.isNaN(expiresAt.valueOf())) {\n return yield* Effect.fail(\n failure(\"validateToken\", \"Cloudflare token expiry is not a valid timestamp\", {\n reason: \"response\",\n status: response.status,\n }),\n );\n }\n return expiresAt;\n }),\n );\n\n return { allZones, inspectToken, request } as const;\n};\n\nconst discoverAccount = Effect.fn(\"CloudflareClient.discoverAccount\")(\n (options: CredentialOptions & { readonly domain: DomainName.DomainName }) =>\n Effect.gen(function* () {\n const { allZones } = makeTransport(options);\n for (const candidate of Zones.candidates(options.domain)) {\n const matches = yield* allZones(undefined, candidate);\n const match = matches[0];\n if (matches.length === 0) continue;\n if (matches.length === 1 && match !== undefined) return match.account;\n return yield* Effect.fail(\n failure(\n \"discoverAccount\",\n `Cloudflare returned multiple accessible zones named ${candidate}`,\n { reason: \"conflict\" },\n ),\n );\n }\n return yield* Effect.fail(\n failure(\n \"discoverAccount\",\n `Cloudflare did not expose an accessible zone for ${options.domain}`,\n { reason: \"not_found\" },\n ),\n );\n }),\n);\n\nexport const discoverAuthorizationAccount = discoverAccount;\n\nexport const validateDomainToken = Effect.fn(\"CloudflareClient.validateDomainToken\")(\n (options: DomainCredentialOptions) =>\n Effect.gen(function* () {\n const transport = makeTransport(options);\n const account = options.tokenKind === \"account\" ? yield* discoverAccount(options) : undefined;\n const expiresAt = yield* transport.inspectToken(\n account === undefined\n ? \"/user/tokens/verify\"\n : `/accounts/${encodeURIComponent(account.id)}/tokens/verify`,\n );\n const discoveredAccount = account ?? (yield* discoverAccount(options));\n return {\n accountId: discoveredAccount.id,\n capabilities: options.capabilities,\n expiresAt,\n scopes: [],\n } satisfies ProviderAuth.TokenValidation;\n }),\n);\n\n/** Creates an Effect-native Cloudflare client without owning the credential lifecycle. */\nexport function make(options: Options): Interface {\n return makeClient(options);\n}\n\nfunction makeClient(options: InternalOptions): Interface {\n const { allZones, inspectToken, request } = makeTransport(options);\n\n const resolveZone = Effect.fn(\"CloudflareClient.resolveZone\")((name: DomainName.DomainName) =>\n Effect.gen(function* () {\n if (options.target !== undefined) {\n if (name !== options.target.zoneName && !name.endsWith(`.${options.target.zoneName}`)) {\n return yield* Effect.fail(\n failure(\n \"resolveZone\",\n `Cloudflare target ${options.target.zoneName} does not cover ${name}`,\n { reason: \"not_found\" },\n ),\n );\n }\n return {\n account: { id: options.target.accountId, name: options.target.accountId },\n id: options.target.zoneId,\n name: options.target.zoneName,\n name_servers: options.target.evidence?.nameservers ?? [],\n } satisfies Protocol.Zone;\n }\n const matches = yield* allZones(options.accountId, name);\n const match = matches[0];\n if (matches.length === 1 && match !== undefined) return match;\n return yield* Effect.fail(\n failure(\n \"resolveZone\",\n matches.length === 0\n ? options.accountId === undefined\n ? `Cloudflare zone ${name} was not found in the authorized accounts`\n : `Cloudflare zone ${name} was not found in account ${options.accountId}`\n : options.accountId === undefined\n ? `Cloudflare returned multiple zones named ${name} across authorized accounts`\n : `Cloudflare returned multiple zones named ${name} in account ${options.accountId}`,\n { reason: matches.length === 0 ? \"not_found\" : \"response\" },\n ),\n );\n }),\n );\n\n const listRecords = Effect.fn(\"CloudflareClient.listRecords\")((zoneName: DomainName.DomainName) =>\n Effect.gen(function* () {\n const zone = yield* resolveZone(zoneName);\n const records: Array<DnsRecord.Observed> = [];\n let page = 1;\n while (true) {\n const query = new URLSearchParams({ page: String(page), per_page: \"100\" });\n const { body, response } = yield* request(\n `/zones/${encodeURIComponent(zone.id)}/dns_records?${query}`,\n \"listRecords\",\n );\n yield* ensureSuccess(body, \"listRecords\", response);\n const envelope = yield* decode(Protocol.RecordListEnvelope, body, \"listRecords\", response);\n records.push(...(yield* Effect.forEach(envelope.result, Records.decode)));\n const totalPages = envelope.result_info?.total_pages;\n if (\n (totalPages !== undefined && page >= totalPages) ||\n (totalPages === undefined && envelope.result.length < 100)\n ) {\n return records;\n }\n page += 1;\n }\n }),\n );\n\n const createRecord = Effect.fn(\"CloudflareClient.createRecord\")(\n (zoneName: DomainName.DomainName, record: DnsRecord.DnsRecord) =>\n Effect.gen(function* () {\n const zone = yield* resolveZone(zoneName);\n const { body, response } = yield* request(\n `/zones/${encodeURIComponent(zone.id)}/dns_records`,\n \"createRecord\",\n { body: JSON.stringify(Records.encode(record)), method: \"POST\" },\n );\n yield* ensureSuccess(body, \"createRecord\", response);\n const envelope = yield* decode(Protocol.RecordEnvelope, body, \"createRecord\", response);\n return { providerRecordId: envelope.result.id };\n }),\n );\n\n const getRecord = Effect.fn(\"CloudflareClient.getRecord\")(\n (zoneName: DomainName.DomainName, providerRecordId: string) =>\n Effect.gen(function* () {\n const zone = yield* resolveZone(zoneName);\n const { body, response } = yield* request(\n `/zones/${encodeURIComponent(zone.id)}/dns_records/${encodeURIComponent(providerRecordId)}`,\n \"getRecord\",\n );\n if (response.status === 404) return null;\n yield* ensureSuccess(body, \"getRecord\", response);\n const envelope = yield* decode(Protocol.RecordEnvelope, body, \"getRecord\", response);\n return yield* Records.decode(envelope.result);\n }),\n );\n\n const deleteRecord = Effect.fn(\"CloudflareClient.deleteRecord\")(\n (zoneName: DomainName.DomainName, providerRecordId: string) =>\n Effect.gen(function* () {\n const zone = yield* resolveZone(zoneName);\n const { body, response } = yield* request(\n `/zones/${encodeURIComponent(zone.id)}/dns_records/${encodeURIComponent(providerRecordId)}`,\n \"deleteRecord\",\n { method: \"DELETE\" },\n );\n yield* ensureSuccess(body, \"deleteRecord\", response);\n }),\n );\n\n const listAccounts = Effect.fn(\"CloudflareClient.listAccounts\")(() =>\n allZones().pipe(\n Effect.map((zones) => {\n const accounts = new Map<string, Protocol.Account>();\n for (const zone of zones) accounts.set(zone.account.id, zone.account);\n return [...accounts.values()].sort((left, right) => left.name.localeCompare(right.name));\n }),\n ),\n );\n\n const listZones = Effect.fn(\"CloudflareClient.listZones\")((input: ListZonesInput = {}) =>\n allZones(input.accountId ?? options.accountId, input.name).pipe(\n Effect.flatMap((zones) => Effect.forEach(zones, projectZone)),\n ),\n );\n\n const listTargets = Effect.fn(\"CloudflareClient.listTargets\")(\n (input: ProviderSession.ListTargetsInput = {}) =>\n Effect.gen(function* () {\n const names =\n input.domain === undefined\n ? undefined\n : new Set(Zones.candidates(input.domain).map((name) => String(name)));\n const zones = yield* allZones(input.accountId ?? options.accountId);\n return yield* Effect.forEach(\n zones.filter(\n (zone) => zone.type !== \"internal\" && (names === undefined || names.has(zone.name)),\n ),\n targetFromZone,\n );\n }),\n );\n\n const resolveTarget = Effect.fn(\"CloudflareClient.resolveTarget\")(\n (domain: DomainName.DomainName) =>\n Effect.gen(function* () {\n const candidates = yield* listTargets({ domain });\n for (const zoneName of Zones.candidates(domain)) {\n const matches = candidates.filter((target) => target.zoneName === zoneName);\n if (matches.length === 1) {\n const target = matches[0];\n if (target !== undefined) return ProviderSession.Resolution.Resolved({ target });\n }\n if (matches.length > 1) {\n return ProviderSession.Resolution.SelectionRequired({ candidates: matches });\n }\n }\n return ProviderSession.Resolution.NotFound({ domain });\n }),\n );\n\n const forTarget = Effect.fn(\"CloudflareClient.forTarget\")((target: Connection.ProviderTarget) =>\n Effect.gen(function* () {\n if (target.accountKind !== null && target.accountKind !== \"account\") {\n return yield* Effect.fail(\n failure(\"forTarget\", \"Cloudflare targets must use the account account kind\", {\n reason: \"request\",\n }),\n );\n }\n if (target.evidence?.zoneType === \"internal\") {\n return yield* Effect.fail(\n failure(\"forTarget\", \"Cloudflare internal zones cannot host managed DNS records\", {\n reason: \"unsupported\",\n }),\n );\n }\n const discovered = yield* listTargets({\n accountId: target.accountId,\n domain: target.zoneName,\n });\n const selected = discovered.find(\n (candidate) =>\n candidate.accountId === target.accountId &&\n candidate.zoneId === target.zoneId &&\n candidate.zoneName === target.zoneName,\n );\n if (selected === undefined) {\n return yield* Effect.fail(\n failure(\n \"forTarget\",\n `Cloudflare target ${target.zoneName} is not visible to this credential`,\n { reason: \"authorization\" },\n ),\n );\n }\n if (selected.evidence?.zoneType === \"internal\") {\n return yield* Effect.fail(\n failure(\"forTarget\", \"Cloudflare internal zones cannot host managed DNS records\", {\n reason: \"unsupported\",\n }),\n );\n }\n const client = makeClient({ ...options, accountId: selected.accountId, target: selected });\n return {\n id: client.id,\n createRecord: client.createRecord,\n deleteRecord: client.deleteRecord,\n getRecord: client.getRecord,\n listRecords: client.listRecords,\n } satisfies DnsProvider.Interface;\n }),\n );\n\n const validateToken = Effect.fn(\"CloudflareClient.validateToken\")(() =>\n Effect.gen(function* () {\n const path =\n options.tokenKind === \"account\"\n ? options.accountId === undefined\n ? yield* Effect.fail(\n failure(\"validateToken\", \"Cloudflare account tokens require an account ID\", {\n reason: \"request\",\n }),\n )\n : `/accounts/${encodeURIComponent(options.accountId)}/tokens/verify`\n : \"/user/tokens/verify\";\n const expiresAt = yield* inspectToken(path);\n yield* allZones(options.accountId);\n return {\n accountId: options.accountId ?? \"\",\n capabilities: options.capabilities,\n expiresAt,\n scopes: [],\n };\n }),\n );\n\n return {\n id: \"cloudflare\",\n providerId: \"cloudflare\",\n createRecord,\n deleteRecord,\n getRecord,\n listAccounts,\n listRecords,\n listZones,\n listTargets,\n resolveTarget,\n forTarget,\n validateToken,\n };\n}\n\nconst targetFromZone = Effect.fn(\"CloudflareClient.targetFromZone\")((zone: Protocol.Zone) =>\n Effect.gen(function* () {\n const name = yield* DomainName.decode(zone.name).pipe(\n Effect.mapError((cause) => failure(\"listTargets\", cause.message, { reason: \"response\" })),\n );\n const nameservers = yield* Effect.forEach(zone.name_servers, (nameserver) =>\n DomainName.decode(nameserver).pipe(\n Effect.mapError((cause) => failure(\"listTargets\", cause.message, { reason: \"response\" })),\n ),\n );\n return {\n accountId: zone.account.id,\n accountKind: \"account\" as const,\n evidence: {\n accountName: zone.account.name,\n nameservers,\n status: zone.status ?? \"unknown\",\n zoneType: zone.type ?? \"unknown\",\n },\n zoneId: zone.id,\n zoneName: name,\n } satisfies Connection.ProviderTarget;\n }),\n);\n\nconst projectZone = Effect.fn(\"CloudflareClient.projectZone\")((zone: Protocol.Zone) =>\n Effect.gen(function* () {\n const name = yield* DomainName.decode(zone.name).pipe(\n Effect.mapError((cause) => failure(\"listZones\", cause.message, { reason: \"response\" })),\n );\n const nameservers = yield* Effect.forEach(zone.name_servers, (nameserver) =>\n DomainName.decode(nameserver).pipe(\n Effect.mapError((cause) => failure(\"listZones\", cause.message, { reason: \"response\" })),\n ),\n );\n return {\n accountId: zone.account.id,\n id: zone.id,\n name,\n nameservers,\n status: zone.status ?? null,\n };\n }),\n);\n\nfunction decode<A>(\n schema: S.ConstraintCodec<A, unknown, never, unknown>,\n input: unknown,\n operation: string,\n response: Response,\n): Effect.Effect<A, DnsProvider.Error> {\n return S.decodeUnknownEffect(schema)(input).pipe(\n Effect.mapError((cause) =>\n failure(operation, `Cloudflare response did not match its API contract: ${cause.message}`, {\n reason: \"response\",\n status: response.status,\n }),\n ),\n );\n}\n\nfunction ensureSuccess(\n input: unknown,\n operation: string,\n response: Response,\n): Effect.Effect<void, DnsProvider.Error> {\n return S.decodeUnknownEffect(Protocol.BaseEnvelope)(input).pipe(\n Effect.mapError(() =>\n failure(operation, \"Cloudflare response did not contain a valid API envelope\", {\n reason: \"response\",\n status: response.status,\n }),\n ),\n Effect.flatMap((envelope) => {\n if (response.ok && envelope.success) return Effect.void;\n const detail = envelope.errors[0];\n const retryAfterMs = retryAfter(response.headers.get(\"retry-after\"));\n return Effect.fail(\n failure(\n operation,\n detail?.message ?? `Cloudflare request failed with HTTP ${response.status}`,\n {\n ...(detail === undefined ? {} : { code: detail.code }),\n reason: reason(response.status, detail?.code),\n ...(retryAfterMs === undefined ? {} : { retryAfterMs }),\n status: response.status,\n },\n ),\n );\n }),\n );\n}\n\nfunction reason(status: number, code?: number): DnsProvider.ErrorReason {\n if (status === 401) return \"authentication\";\n if (status === 403) return \"authorization\";\n if (status === 404) return \"not_found\";\n if (status === 409 || code === 81056 || code === 81057 || code === 81058) return \"conflict\";\n if (status === 429) return \"rate_limit\";\n if (status >= 500) return \"response\";\n return \"request\";\n}\n\nfunction retryAfter(value: string | null): number | undefined {\n if (value === null) return undefined;\n const seconds = Number(value);\n if (Number.isFinite(seconds)) return Math.max(0, seconds * 1_000);\n const date = Date.parse(value);\n return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());\n}\n\nfunction failure(\n operation: string,\n message: string,\n fields: Partial<Pick<DnsProvider.Error, \"code\" | \"reason\" | \"retryAfterMs\" | \"status\">> = {},\n): DnsProvider.Error {\n return new DnsProvider.Error({\n ...fields,\n message,\n operation,\n providerId: \"cloudflare\",\n });\n}\n","import * as oauth from \"oauth4webapi\";\nimport { Clock, Effect, Schema } from \"effect\";\n\nimport * as AuthorizationCode from \"../../auth/authorization-code.ts\";\nimport * as Connection from \"../../auth/connect.ts\";\nimport * as ProviderAuthorization from \"../../auth/authorization.ts\";\nimport type * as ProviderAuth from \"../../auth/manifest.ts\";\nimport * as ProviderContext from \"../../auth/provider-context.ts\";\nimport * as Secret from \"../../auth/secret.ts\";\nimport type * as DomainName from \"../../domain/domain-name.ts\";\nimport * as DnsProvider from \"../../provider/provider.ts\";\nimport * as Client from \"./client.ts\";\nimport * as ProviderSession from \"../../provider/session.ts\";\n\nconst authorizationServer = {\n authorization_endpoint: \"https://dash.cloudflare.com/oauth2/auth\",\n issuer: \"https://dash.cloudflare.com\",\n revocation_endpoint: \"https://dash.cloudflare.com/oauth2/revoke\",\n token_endpoint: \"https://dash.cloudflare.com/oauth2/token\",\n} as const;\n\nconst Context = Schema.Struct({\n accountId: Schema.optionalKey(Schema.String),\n tokenKind: Schema.Literals([\"account\", \"user\"]),\n});\nexport type Context = typeof Context.Type;\nexport const contextCodec = ProviderContext.codec(\"cloudflare.v1\", Context);\n\n/** Describes Cloudflare's caller-created API-token authorization method. */\nexport function tokenMethod(\n capabilities: ProviderAuth.TokenValidation[\"capabilities\"],\n): Extract<ProviderAuth.Manifest[\"methods\"][number], { readonly _tag: \"token\" }> {\n return {\n _tag: \"token\",\n capabilities: [...capabilities],\n instructionsUrl: \"https://developers.cloudflare.com/fundamentals/api/get-started/create-token/\",\n };\n}\n\nexport interface OAuthMethodOptions {\n /** Scope IDs assigned to the OAuth client by Cloudflare. */\n readonly scopes: ReadonlyArray<string>;\n /** Capabilities represented by those assigned scope IDs. */\n readonly capabilities: ProviderAuth.TokenValidation[\"capabilities\"];\n readonly clientAuth: ProviderAuth.OAuthMethod[\"clientAuth\"];\n}\n\n/** Describes a registered Cloudflare OAuth client and its assigned scope IDs. */\nexport function oauthMethod(options: OAuthMethodOptions): ProviderAuth.OAuthMethod {\n return {\n _tag: \"oauth2\",\n authorizationServer,\n capabilities: [...options.capabilities],\n clientAuth: options.clientAuth,\n scopes: [...options.scopes],\n };\n}\n\n/** Creates the Cloudflare token and OAuth authorization manifest. */\nexport function manifest(options: OAuthMethodOptions): ProviderAuth.Manifest {\n return {\n methods: [tokenMethod(options.capabilities), oauthMethod(options)],\n providerId: \"cloudflare\",\n };\n}\n\ntype CredentialOptions = Omit<Client.Options, \"accountId\" | \"token\" | \"tokenKind\">;\n\n/** Selects an explicit Cloudflare account or discovers it from an authorized domain. */\nexport type CredentialTarget =\n | {\n readonly accountId: string;\n readonly domain?: never;\n }\n | {\n readonly accountId?: never;\n readonly domain: DomainName.DomainName;\n };\n\nexport type SubjectResolverOptions = CredentialOptions & CredentialTarget;\n\n/** Configuration for validating a Cloudflare token against an account or authorized domain. */\nexport type TokenValidatorOptions = CredentialOptions &\n (\n | {\n readonly accountId: string;\n readonly domain?: never;\n readonly tokenKind?: \"account\" | \"user\";\n }\n | {\n readonly accountId?: never;\n readonly domain: DomainName.DomainName;\n readonly tokenKind?: \"account\" | \"user\";\n }\n );\n\n/** Resolves the Cloudflare account selected by a completed OAuth authorization. */\nexport function subjectResolver(\n options: SubjectResolverOptions,\n): ProviderAuth.OAuthSubjectResolver {\n return (tokens: oauth.TokenEndpointResponse, accessToken: Secret.Value) =>\n Effect.gen(function* () {\n const accountId =\n options.accountId ??\n (yield* Client.discoverAuthorizationAccount({\n ...(options.baseUrl === undefined ? {} : { baseUrl: options.baseUrl }),\n domain: options.domain,\n ...(options.fetch === undefined ? {} : { fetch: options.fetch }),\n token: accessToken,\n }).pipe(Effect.map((account) => account.id)));\n if (options.accountId !== undefined) {\n yield* Client.make({\n accountId: options.accountId,\n ...(options.baseUrl === undefined ? {} : { baseUrl: options.baseUrl }),\n capabilities: options.capabilities,\n ...(options.fetch === undefined ? {} : { fetch: options.fetch }),\n token: accessToken,\n tokenKind: \"user\",\n }).listZones();\n }\n const now = yield* Clock.currentTimeMillis;\n return {\n accountId,\n expiresAt:\n typeof tokens.expires_in === \"number\" ? new Date(now + tokens.expires_in * 1_000) : null,\n };\n });\n}\n\n/** Creates a host callback that validates a Cloudflare API token. */\nexport function tokenValidator(\n options: TokenValidatorOptions,\n): (token: Secret.Value) => ReturnType<Client.Interface[\"validateToken\"]> {\n return (token) =>\n options.accountId === undefined\n ? Client.validateDomainToken({\n ...(options.baseUrl === undefined ? {} : { baseUrl: options.baseUrl }),\n capabilities: options.capabilities,\n domain: options.domain,\n ...(options.fetch === undefined ? {} : { fetch: options.fetch }),\n token,\n ...(options.tokenKind === undefined ? {} : { tokenKind: options.tokenKind }),\n })\n : Client.make({\n accountId: options.accountId,\n ...(options.baseUrl === undefined ? {} : { baseUrl: options.baseUrl }),\n capabilities: options.capabilities,\n ...(options.fetch === undefined ? {} : { fetch: options.fetch }),\n token,\n ...(options.tokenKind === undefined ? {} : { tokenKind: options.tokenKind }),\n }).validateToken();\n}\n\nexport type TokenConnectionOptions = TokenValidatorOptions & {\n readonly token: Secret.Value;\n};\n\n/** Creates a provider-independent token connection method backed by Cloudflare validation. */\nexport function tokenConnectionMethod(\n options: TokenConnectionOptions,\n): Extract<Connection.Method, { readonly _tag: \"Token\" }> {\n const requiredCapabilities = [...options.capabilities];\n return Connection.Method.Token({\n authenticate: Effect.fn(\"CloudflareAuth.authenticateToken\")(function* (token) {\n const validated = yield* tokenValidator(options)(token);\n const observedAt = new Date(yield* Clock.currentTimeMillis);\n return {\n capabilityEvidence: validated.capabilities.map((capability) => ({\n capability,\n evidence: ProviderAuthorization.Evidence.Introspected({ observedAt }),\n })),\n credential: {\n accessToken: token,\n expiresAt: validated.expiresAt,\n refreshToken: null,\n tokenType: \"bearer\",\n },\n providerAccountId: validated.accountId,\n providerContext: yield* contextCodec.encode(\n options.tokenKind === \"account\"\n ? { accountId: validated.accountId, tokenKind: \"account\" }\n : { tokenKind: \"user\" },\n ),\n scopes: [...validated.scopes],\n } satisfies Connection.Authentication;\n }),\n providerId: \"cloudflare\",\n requiredCapabilities,\n token: options.token,\n });\n}\n\n/** Converts a completed Cloudflare OAuth authorization into canonical connection authentication. */\nexport const oauthAuthentication = Effect.fn(\"CloudflareAuth.oauthAuthentication\")(function* (\n options: SubjectResolverOptions & {\n readonly accessToken: Secret.Value;\n readonly tokens: oauth.TokenEndpointResponse;\n },\n) {\n const resolved = yield* subjectResolver(options)(options.tokens, options.accessToken);\n const observedAt = new Date(yield* Clock.currentTimeMillis);\n return {\n capabilityEvidence: options.capabilities.map((capability) => ({\n capability,\n evidence: ProviderAuthorization.Evidence.Introspected({ observedAt }),\n })),\n credential: {\n accessToken: options.accessToken,\n expiresAt: resolved.expiresAt,\n refreshToken:\n options.tokens.refresh_token === undefined\n ? null\n : Secret.Value.from(options.tokens.refresh_token),\n tokenType: options.tokens.token_type,\n },\n providerAccountId: resolved.accountId,\n providerContext: yield* contextCodec.encode({ tokenKind: \"user\" }),\n scopes: (options.tokens.scope ?? \"\").split(\" \").filter(Boolean),\n } satisfies Connection.Authentication;\n});\n\n/** Restore a credential-scoped Cloudflare session from persisted authorization state. */\nexport function restore(\n options: ProviderSession.RestoreInput & Pick<Client.Options, \"baseUrl\" | \"fetch\">,\n): Effect.Effect<Client.Interface, DnsProvider.Error> {\n return Effect.gen(function* () {\n if (options.authorization.providerId !== \"cloudflare\") {\n return yield* Effect.fail(\n failure(\"restore\", \"Provider authorization belongs to another provider\", \"authorization\"),\n );\n }\n if (options.authorization.method === \"integration\") {\n return yield* Effect.fail(\n failure(\"restore\", \"Cloudflare does not support integration credentials\", \"unsupported\"),\n );\n }\n if (options.authorization.revocation._tag !== \"Active\") {\n return yield* Effect.fail(\n failure(\"restore\", \"Cloudflare authorization is pending revocation\", \"authorization\"),\n );\n }\n const missingCapability = options.authorization.requiredCapabilities.find(\n (capability) =>\n !options.authorization.capabilityEvidence.some((item) => item.capability === capability),\n );\n if (missingCapability !== undefined) {\n return yield* Effect.fail(\n failure(\n \"restore\",\n `Cloudflare authorization lacks evidence for ${missingCapability}`,\n \"authorization\",\n ),\n );\n }\n if (\n options.credential.expiresAt !== null &&\n (Number.isNaN(options.credential.expiresAt.valueOf()) ||\n options.credential.expiresAt <= new Date())\n ) {\n return yield* Effect.fail(\n failure(\"restore\", \"Cloudflare authorization has expired\", \"authentication\"),\n );\n }\n const context = yield* contextCodec\n .decode(options.authorization.providerContext)\n .pipe(Effect.mapError((cause) => failure(\"restore\", cause.message, \"response\")));\n return Client.make({\n ...(context.accountId === undefined ? {} : { accountId: context.accountId }),\n ...(options.baseUrl === undefined ? {} : { baseUrl: options.baseUrl }),\n capabilities: options.authorization.capabilityEvidence.map(({ capability }) => capability),\n ...(options.fetch === undefined ? {} : { fetch: options.fetch }),\n token: options.credential.accessToken,\n tokenKind: context.tokenKind,\n });\n });\n}\n\nexport interface RefreshCredentialOptions {\n readonly client: ProviderAuth.OAuthClientConfiguration;\n readonly clientAuth: ProviderAuth.OAuthMethod[\"clientAuth\"];\n readonly credential: ProviderSession.Credential;\n readonly fetch?: Client.Fetch;\n}\n\n/** Exchanges a Cloudflare refresh token for a fresh provider credential. */\nexport const refreshCredential = Effect.fn(\"CloudflareAuth.refreshCredential\")(function* (\n options: RefreshCredentialOptions,\n) {\n if (options.credential.refreshToken === null) {\n return yield* new Connection.Error({\n category: \"authorization\",\n message: \"Cloudflare credential has no refresh token\",\n operation: \"CloudflareAuth.refreshCredential\",\n retry: \"after-user-action\",\n });\n }\n const refreshToken = options.credential.refreshToken;\n const client: oauth.Client = { client_id: options.client.clientId };\n const authentication = yield* Effect.try({\n try: () => clientAuthentication(options.clientAuth, options.client),\n catch: () =>\n new Connection.Error({\n category: \"authorization\",\n message: \"Cloudflare OAuth client authentication is invalid\",\n operation: \"CloudflareAuth.refreshCredential\",\n retry: \"never\",\n }),\n });\n const fetch = options.fetch;\n const tokens = yield* Effect.tryPromise({\n try: async (signal) => {\n const request = await oauth.refreshTokenGrantRequest(\n authorizationServer,\n client,\n authentication,\n refreshToken.expose(),\n fetch === undefined\n ? { signal }\n : {\n signal,\n [oauth.customFetch]: (url, init) => fetch(url, { ...init, body: init.body }),\n },\n );\n return oauth.processRefreshTokenResponse(authorizationServer, client, request);\n },\n catch: (cause) => refreshFailure(cause),\n });\n const now = yield* Clock.currentTimeMillis;\n return {\n accessToken: Secret.Value.from(tokens.access_token),\n expiresAt:\n typeof tokens.expires_in === \"number\" ? new Date(now + tokens.expires_in * 1_000) : null,\n refreshToken:\n tokens.refresh_token === undefined ? refreshToken : Secret.Value.from(tokens.refresh_token),\n tokenType: tokens.token_type,\n } satisfies ProviderSession.Credential;\n});\n\nexport type OAuthFlowOptions = SubjectResolverOptions & {\n readonly client: ProviderAuth.OAuthClientConfiguration;\n readonly clientAuth: ProviderAuth.OAuthMethod[\"clientAuth\"];\n readonly redirectUri: string;\n readonly scopes: ReadonlyArray<string>;\n};\n\n/** Creates Cloudflare's OAuth implementation of the common interactive connection capability. */\nexport function oauthFlow(options: OAuthFlowOptions): Connection.InteractiveFlow {\n const method = oauthMethod({\n capabilities: options.capabilities,\n clientAuth: options.clientAuth,\n scopes: options.scopes,\n });\n return {\n complete: Effect.fn(\"CloudflareAuth.oauthFlow.complete\")(function* (payload, callbackUrl) {\n const tokens = yield* AuthorizationCode.complete({\n callbackUrl,\n client: options.client,\n ...(options.fetch === undefined ? {} : { fetch: options.fetch }),\n method,\n payload,\n providerId: \"cloudflare\",\n });\n return yield* oauthAuthentication({\n ...(options.accountId === undefined\n ? { domain: options.domain }\n : { accountId: options.accountId }),\n ...(options.baseUrl === undefined ? {} : { baseUrl: options.baseUrl }),\n capabilities: options.capabilities,\n ...(options.fetch === undefined ? {} : { fetch: options.fetch }),\n accessToken: Secret.make(tokens.access_token),\n tokens,\n });\n }),\n method: \"oauth2\",\n providerId: \"cloudflare\",\n requiredCapabilities: [...options.capabilities],\n start: (continuationId) =>\n AuthorizationCode.start({\n client: options.client,\n method,\n redirectUri: options.redirectUri,\n state: continuationId,\n }),\n };\n}\n\nfunction failure(\n operation: string,\n message: string,\n reason: DnsProvider.ErrorReason,\n): DnsProvider.Error {\n return new DnsProvider.Error({ message, operation, providerId: \"cloudflare\", reason });\n}\n\nfunction clientAuthentication(\n method: ProviderAuth.OAuthMethod[\"clientAuth\"],\n client: ProviderAuth.OAuthClientConfiguration,\n): oauth.ClientAuth {\n if (method === \"none\") return oauth.None();\n if (client.clientSecret === undefined) throw new Error(\"Client secret is required\");\n return method === \"client_secret_basic\"\n ? oauth.ClientSecretBasic(client.clientSecret.expose())\n : oauth.ClientSecretPost(client.clientSecret.expose());\n}\n\nfunction refreshFailure(cause: unknown): Connection.Error | DnsProvider.Error {\n if (\n cause instanceof oauth.ResponseBodyError &&\n [\"invalid_client\", \"invalid_grant\"].includes(cause.error)\n ) {\n return new Connection.Error({\n category: \"authorization\",\n message: \"Cloudflare authorization can no longer be refreshed\",\n operation: \"CloudflareAuth.refreshCredential\",\n retry: \"after-user-action\",\n });\n }\n return failure(\n \"refreshCredential\",\n cause instanceof Error ? cause.message : \"Cloudflare token refresh failed\",\n cause instanceof oauth.ResponseBodyError ? \"response\" : \"transport\",\n );\n}\n","import { Schema as S } from \"effect\";\n\nexport const Pagination = S.Struct({\n count: S.Number,\n next: S.NullOr(S.Number),\n prev: S.NullOr(S.Number),\n});\nexport interface Pagination extends S.Schema.Type<typeof Pagination> {}\n\nexport const ErrorDetail = S.Struct({\n code: S.String,\n message: S.String,\n limit: S.optionalKey(\n S.Struct({\n remaining: S.Number,\n reset: S.optionalKey(S.Number),\n resetMs: S.optionalKey(S.Number),\n total: S.Number,\n }),\n ),\n});\nexport interface ErrorDetail extends S.Schema.Type<typeof ErrorDetail> {}\n\nexport const ErrorEnvelope = S.Struct({ error: ErrorDetail });\n\nexport const User = S.Struct({\n id: S.String,\n name: S.NullOr(S.String),\n username: S.String,\n});\nexport interface User extends S.Schema.Type<typeof User> {}\n\nexport const UserEnvelope = S.Struct({ user: User });\n\nexport const Team = S.Struct({\n id: S.String,\n name: S.NullOr(S.String),\n slug: S.String,\n});\nexport interface Team extends S.Schema.Type<typeof Team> {}\n\nexport const TeamListEnvelope = S.Struct({\n pagination: Pagination,\n teams: S.Array(Team),\n});\n\nexport const Domain = S.Struct({\n id: S.String,\n intendedNameservers: S.Array(S.String),\n name: S.String,\n nameservers: S.Array(S.String),\n serviceType: S.Literals([\"zeit.world\", \"external\", \"na\"]),\n teamId: S.NullOr(S.String),\n userId: S.String,\n verified: S.Boolean,\n zone: S.optionalKey(S.Boolean),\n});\nexport interface Domain extends S.Schema.Type<typeof Domain> {}\n\nexport const DomainConfig = S.Struct({\n misconfigured: S.Boolean,\n serviceType: S.Literals([\"zeit.world\", \"external\", \"na\"]),\n});\nexport interface DomainConfig extends S.Schema.Type<typeof DomainConfig> {}\n\nexport const DomainEnvelope = S.Struct({ domain: Domain });\n\nexport const DomainListEnvelope = S.Struct({\n domains: S.Array(Domain),\n pagination: Pagination,\n});\n\nexport const Record = S.Struct({\n id: S.String,\n mxPriority: S.optionalKey(S.Number),\n name: S.String,\n priority: S.optionalKey(S.Number),\n ttl: S.optionalKey(S.Number),\n type: S.String,\n value: S.String,\n});\nexport interface Record extends S.Schema.Type<typeof Record> {}\n\nexport const RecordListEnvelope = S.Struct({\n pagination: S.optionalKey(Pagination),\n records: S.Array(Record),\n});\n\nexport const CreateRecordEnvelope = S.Struct({\n uid: S.String,\n updated: S.optionalKey(S.Number),\n});\n\nexport const IntegrationToken = S.Struct({\n access_token: S.String,\n installation_id: S.optionalKey(S.String),\n team_id: S.NullOr(S.String),\n token_type: S.optionalKey(S.String),\n user_id: S.String,\n});\nexport interface IntegrationToken extends S.Schema.Type<typeof IntegrationToken> {}\n","import { Effect, Schema as S } from \"effect\";\n\nimport * as DomainName from \"../../domain/domain-name.ts\";\nimport * as DnsRecord from \"../../domain/dns-record.ts\";\nimport * as DnsProvider from \"../../provider/provider.ts\";\nimport type * as Protocol from \"./protocol.ts\";\n\nexport type CreateBody = Readonly<Record<string, unknown>>;\n\nexport const decode = Effect.fn(\"VercelRecords.decode\")(\n (zone: DomainName.DomainName, record: Protocol.Record) =>\n Effect.gen(function* () {\n const absolute = absoluteNameCandidate(zone, record.name);\n const name = yield* DomainName.decode(absolute).pipe(\n Effect.match({ onFailure: () => null, onSuccess: (value) => value }),\n );\n if (name === null) return yield* decodeOpaque(record, absolute);\n const common = {\n metadata: {\n ownership: \"provider\",\n provenance: \"vercel\",\n purpose: \"existing DNS record\",\n },\n name,\n policy: record.type === \"CNAME\" ? \"exclusive\" : \"append\",\n ttl: record.ttl ?? 60,\n } as const;\n const fromRecord = (input: unknown) =>\n DnsRecord.decode(input).pipe(\n Effect.mapError((cause) => failure(\"decodeRecord\", cause.message)),\n );\n\n switch (record.type) {\n case \"A\":\n case \"AAAA\":\n return yield* fromRecord({ ...common, _tag: record.type, address: record.value });\n case \"CNAME\":\n case \"NS\":\n return yield* fromRecord({ ...common, _tag: record.type, target: record.value });\n case \"TXT\":\n return yield* fromRecord({ ...common, _tag: \"TXT\", value: record.value });\n case \"MX\":\n return yield* fromRecord({\n ...common,\n _tag: \"MX\",\n exchange: record.value,\n priority: record.mxPriority ?? record.priority,\n });\n case \"CAA\": {\n const match = record.value.match(\n /^(\\d{1,3})\\s+(issue|issuewild|iodef)\\s+(?:\"((?:\\\\.|[^\"])*)\"|(\\S.*))$/,\n );\n if (match === null) {\n return yield* Effect.fail(\n failure(\"decodeRecord\", \"Vercel CAA record has an invalid value\"),\n );\n }\n return yield* fromRecord({\n ...common,\n _tag: \"CAA\",\n flags: Number(match[1]),\n tag: match[2],\n value: unescapeQuoted(match[3] ?? match[4] ?? \"\"),\n });\n }\n case \"SRV\": {\n const parts = record.value.trim().split(/\\s+/);\n const [priority, weight, port, target] =\n parts.length === 4\n ? parts\n : [String(record.priority ?? \"\"), parts[0], parts[1], parts[2]];\n return yield* fromRecord({\n ...common,\n _tag: \"SRV\",\n port: Number(port),\n priority: Number(priority),\n target,\n weight: Number(weight),\n });\n }\n default:\n return yield* decodeOpaque(record, name);\n }\n }),\n);\n\nconst decodeOpaque = Effect.fn(\"VercelRecords.decodeOpaque\")(\n (record: Protocol.Record, name: string) =>\n S.decodeUnknownEffect(DnsRecord.Opaque)({\n _tag: \"Opaque\",\n name,\n providerRecordId: record.id,\n providerType: record.type,\n }).pipe(Effect.mapError((cause) => failure(\"decodeRecord\", cause.message))),\n);\n\nexport function encode(zone: DomainName.DomainName, record: DnsRecord.DnsRecord): CreateBody {\n const common = {\n name: relativeName(zone, record.name),\n ...(record.ttl === null ? {} : { ttl: record.ttl }),\n type: record._tag,\n };\n switch (record._tag) {\n case \"A\":\n case \"AAAA\":\n return { ...common, value: record.address };\n case \"CNAME\":\n case \"NS\":\n return { ...common, value: record.target };\n case \"TXT\":\n return { ...common, value: record.value };\n case \"MX\":\n return { ...common, mxPriority: record.priority, value: record.exchange };\n case \"CAA\":\n return {\n ...common,\n value: `${record.flags} ${record.tag} \"${escapeQuoted(record.value)}\"`,\n };\n case \"SRV\":\n return {\n ...common,\n srv: {\n port: record.port,\n priority: record.priority,\n target: record.target,\n weight: record.weight,\n },\n };\n }\n}\n\nfunction absoluteNameCandidate(zone: DomainName.DomainName, name: string): string {\n return name === \"\" || name === \"@\"\n ? zone\n : name === zone || name.endsWith(`.${zone}`)\n ? name\n : `${name}.${zone}`;\n}\n\nfunction relativeName(zone: DomainName.DomainName, name: DomainName.DomainName): string {\n if (name === zone) return \"\";\n const suffix = `.${zone}`;\n if (!name.endsWith(suffix)) {\n throw failure(\"encodeRecord\", `DNS record ${name} is outside Vercel zone ${zone}`, {\n reason: \"request\",\n });\n }\n return name.slice(0, -suffix.length);\n}\n\nfunction escapeQuoted(value: string): string {\n return value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', '\\\\\"');\n}\n\nfunction unescapeQuoted(value: string): string {\n return value.replace(/\\\\([\\\\\"])/g, \"$1\");\n}\n\nfunction failure(\n operation: string,\n message: string,\n fields: Partial<Pick<DnsProvider.Error, \"reason\">> = {},\n): DnsProvider.Error {\n return new DnsProvider.Error({\n message,\n operation,\n providerId: \"vercel\",\n reason: fields.reason ?? \"response\",\n });\n}\n","import { Effect, Schema as S } from \"effect\";\n\nimport type * as ProviderAuth from \"../../auth/manifest.ts\";\nimport type * as Secret from \"../../auth/secret.ts\";\nimport * as Connection from \"../../auth/connection.ts\";\nimport * as DomainName from \"../../domain/domain-name.ts\";\nimport type * as DnsRecord from \"../../domain/dns-record.ts\";\nimport type * as ZoneDiscovery from \"../../discovery/zone-discovery.ts\";\nimport * as Zones from \"../../discovery/zones.ts\";\nimport * as DnsProvider from \"../../provider/provider.ts\";\nimport * as ProviderSession from \"../../provider/session.ts\";\nimport * as Protocol from \"./protocol.ts\";\nimport * as Records from \"./records.ts\";\n\nexport type Fetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n\n/** Selects whether Vercel requests operate on a personal account or a team. */\nexport type AccountContext =\n | { readonly _tag: \"personal\" }\n | { readonly _tag: \"team\"; readonly teamId: string };\n\n/** Configuration for an Effect-native Vercel authoritative-DNS client. */\nexport interface Options {\n readonly baseUrl?: string;\n /** Capabilities the host required when issuing or authorizing this credential. */\n readonly capabilities: ProviderAuth.TokenValidation[\"capabilities\"];\n readonly context: AccountContext;\n readonly fetch?: Fetch;\n readonly token: Secret.Value;\n}\n\nexport interface ListZonesInput {\n readonly name?: DomainName.DomainName;\n}\n\n/** A Vercel account visible to the supplied credential. */\nexport interface Account {\n readonly id: string;\n readonly name: string;\n readonly type: \"personal\" | \"team\";\n}\n\n/** A Vercel-managed authoritative zone with normalized nameserver evidence. */\nexport interface Zone {\n readonly accountId: string;\n readonly id: string;\n readonly name: DomainName.DomainName;\n readonly nameservers: ReadonlyArray<DomainName.DomainName>;\n readonly status: \"active\" | \"pending\";\n}\n\nexport interface Interface extends DnsProvider.Interface {\n readonly providerId: \"vercel\";\n readonly forTarget: (\n target: Connection.ProviderTarget,\n ) => Effect.Effect<DnsProvider.Interface, DnsProvider.Error>;\n readonly listAccounts: () => Effect.Effect<ReadonlyArray<Account>, DnsProvider.Error>;\n readonly listZones: (\n input?: ListZonesInput,\n ) => Effect.Effect<ReadonlyArray<Zone>, DnsProvider.Error>;\n readonly listTargets: (\n input?: ProviderSession.ListTargetsInput,\n ) => Effect.Effect<ReadonlyArray<Connection.ProviderTarget>, DnsProvider.Error>;\n readonly resolveTarget: (\n domain: DomainName.DomainName,\n ) => Effect.Effect<ProviderSession.Resolution, DnsProvider.Error>;\n readonly validateToken: () => Effect.Effect<ProviderAuth.TokenValidation, DnsProvider.Error>;\n}\n\n/** Exposes Vercel zone lookup as the optional provider discovery capability. */\nexport function discovery(client: Interface): ZoneDiscovery.Source {\n return {\n listZones: (name) => client.listZones({ name }),\n provider: client,\n };\n}\n\ninterface TargetOptions {\n readonly target: Connection.ProviderTarget;\n}\n\ntype InternalOptions = Options & Partial<TargetOptions>;\n\n/** Creates an Effect-native Vercel client without owning the credential lifecycle. */\nexport function make(options: Options): Interface {\n return makeClient(options);\n}\n\nfunction makeClient(options: InternalOptions): Interface {\n const fetch = options.fetch ?? globalThis.fetch;\n const baseUrl = (options.baseUrl ?? \"https://api.vercel.com\").replace(/\\/$/, \"\");\n\n const withContext = (path: string, values: Readonly<Record<string, string>> = {}) => {\n const url = new URL(`${baseUrl}${path}`);\n for (const [key, value] of Object.entries(values)) url.searchParams.set(key, value);\n if (options.context._tag === \"team\") url.searchParams.set(\"teamId\", options.context.teamId);\n return url;\n };\n\n const request = Effect.fn(\"VercelClient.request\")(\n (url: URL, operation: string, init?: RequestInit) =>\n Effect.gen(function* () {\n const response = yield* Effect.tryPromise({\n try: () =>\n fetch(url, {\n ...init,\n headers: {\n Accept: \"application/json\",\n Authorization: `Bearer ${options.token.expose()}`,\n ...(init?.body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n ...init?.headers,\n },\n }),\n catch: () => failure(operation, \"Vercel request failed\", { reason: \"transport\" }),\n });\n const body = yield* Effect.tryPromise({\n try: () => response.json() as Promise<unknown>,\n catch: () =>\n failure(\n operation,\n response.ok\n ? \"Vercel returned a non-JSON response\"\n : `Vercel request failed with HTTP ${response.status}`,\n {\n reason: response.ok ? \"response\" : reason(response.status),\n ...rateLimit(response),\n status: response.status,\n },\n ),\n });\n if (!response.ok) return yield* Effect.fail(apiFailure(body, operation, response));\n return { body, response } as const;\n }),\n );\n\n const allTeams = Effect.fn(\"VercelClient.allTeams\")(() =>\n Effect.gen(function* () {\n const teams: Array<Protocol.Team> = [];\n let until: number | null = null;\n while (true) {\n const url = new URL(`${baseUrl}/v2/teams`);\n url.searchParams.set(\"limit\", \"100\");\n if (until !== null) url.searchParams.set(\"until\", String(until));\n const { body, response } = yield* request(url, \"listAccounts\");\n const envelope = yield* decode(Protocol.TeamListEnvelope, body, \"listAccounts\", response);\n teams.push(...envelope.teams);\n if (envelope.pagination.next === null) return teams;\n until = envelope.pagination.next;\n }\n }),\n );\n\n const allDomains = Effect.fn(\"VercelClient.allDomains\")(() =>\n Effect.gen(function* () {\n const domains: Array<Protocol.Domain> = [];\n let until: number | null = null;\n while (true) {\n const values: Record<string, string> = { limit: \"100\" };\n if (until !== null) values.until = String(until);\n const { body, response } = yield* request(withContext(\"/v5/domains\", values), \"listZones\");\n const envelope = yield* decode(Protocol.DomainListEnvelope, body, \"listZones\", response);\n domains.push(...envelope.domains);\n if (envelope.pagination.next === null) return domains;\n until = envelope.pagination.next;\n }\n }),\n );\n\n const discoverZone = Effect.fn(\"VercelClient.discoverZone\")((name: DomainName.DomainName) =>\n Effect.gen(function* () {\n const configResult = yield* request(\n withContext(`/v6/domains/${encodeURIComponent(name)}/config`),\n \"resolveZone\",\n );\n const config = yield* decode(\n Protocol.DomainConfig,\n configResult.body,\n \"resolveZone\",\n configResult.response,\n );\n const domainResult = yield* request(\n withContext(`/v5/domains/${encodeURIComponent(name)}`),\n \"resolveZone\",\n );\n const envelope = yield* decode(\n Protocol.DomainEnvelope,\n domainResult.body,\n \"resolveZone\",\n domainResult.response,\n );\n if (!hasDnsStorage(envelope.domain, config.serviceType)) {\n return null;\n }\n return envelope.domain;\n }).pipe(\n Effect.catchTag(\"ProviderError\", (cause) =>\n cause.reason === \"not_found\" ? Effect.succeed(null) : Effect.fail(cause),\n ),\n ),\n );\n\n const resolveZone = Effect.fn(\"VercelClient.resolveZone\")((name: DomainName.DomainName) =>\n Effect.gen(function* () {\n if (options.target !== undefined) {\n if (name !== options.target.zoneName && !name.endsWith(`.${options.target.zoneName}`)) {\n return yield* Effect.fail(\n failure(\n \"resolveZone\",\n `Vercel target ${options.target.zoneName} does not cover ${name}`,\n { reason: \"not_found\" },\n ),\n );\n }\n return options.target.zoneName;\n }\n const domain = yield* discoverZone(name);\n if (domain === null) {\n return yield* Effect.fail(\n failure(\n \"resolveZone\",\n `Vercel zone ${name} is not configured for authoritative DNS in the selected account`,\n { reason: \"not_found\" },\n ),\n );\n }\n return yield* DomainName.decode(domain.name).pipe(\n Effect.mapError((cause) =>\n failure(\"resolveZone\", `Vercel returned an invalid storage zone: ${cause.message}`),\n ),\n );\n }),\n );\n\n const listRecords = Effect.fn(\"VercelClient.listRecords\")((zoneName: DomainName.DomainName) =>\n Effect.gen(function* () {\n const storageZone = yield* resolveZone(zoneName);\n const records: Array<DnsRecord.Observed> = [];\n let until: number | null = null;\n while (true) {\n const values: Record<string, string> = { limit: \"100\" };\n if (until !== null) values.until = String(until);\n const { body, response } = yield* request(\n withContext(`/v5/domains/${encodeURIComponent(storageZone)}/records`, values),\n \"listRecords\",\n );\n const envelope = yield* decode(Protocol.RecordListEnvelope, body, \"listRecords\", response);\n records.push(\n ...(yield* Effect.forEach(envelope.records, (record) =>\n Records.decode(storageZone, record),\n )),\n );\n const next = envelope.pagination?.next ?? null;\n if (next === null) {\n return records.filter(\n (record) => record.name === zoneName || record.name.endsWith(`.${zoneName}`),\n );\n }\n until = next;\n }\n }),\n );\n\n const createRecord = Effect.fn(\"VercelClient.createRecord\")(\n (zoneName: DomainName.DomainName, record: DnsRecord.DnsRecord) =>\n Effect.gen(function* () {\n const storageZone = yield* resolveZone(zoneName);\n const body = yield* Effect.try({\n try: () => Records.encode(storageZone, record),\n catch: (cause) =>\n cause instanceof DnsProvider.Error\n ? cause\n : failure(\"createRecord\", \"Vercel record could not be encoded\", {\n reason: \"request\",\n }),\n });\n const result = yield* request(\n withContext(`/v2/domains/${encodeURIComponent(storageZone)}/records`),\n \"createRecord\",\n { body: JSON.stringify(body), method: \"POST\" },\n );\n const envelope = yield* decode(\n Protocol.CreateRecordEnvelope,\n result.body,\n \"createRecord\",\n result.response,\n );\n return { providerRecordId: envelope.uid };\n }),\n );\n\n const getRecord = Effect.fn(\"VercelClient.getRecord\")(\n (zoneName: DomainName.DomainName, providerRecordId: string) =>\n Effect.gen(function* () {\n const storageZone = yield* resolveZone(zoneName);\n let until: number | null = null;\n while (true) {\n const values: Record<string, string> = { limit: \"100\" };\n if (until !== null) values.until = String(until);\n const { body, response } = yield* request(\n withContext(`/v5/domains/${encodeURIComponent(storageZone)}/records`, values),\n \"getRecord\",\n );\n const envelope = yield* decode(Protocol.RecordListEnvelope, body, \"getRecord\", response);\n const record = envelope.records.find(({ id }) => id === providerRecordId);\n if (record !== undefined) return yield* Records.decode(storageZone, record);\n const next = envelope.pagination?.next ?? null;\n if (next === null) return null;\n until = next;\n }\n }),\n );\n\n const deleteRecord = Effect.fn(\"VercelClient.deleteRecord\")(\n (zoneName: DomainName.DomainName, providerRecordId: string) =>\n Effect.gen(function* () {\n const storageZone = yield* resolveZone(zoneName);\n yield* request(\n withContext(\n `/v2/domains/${encodeURIComponent(storageZone)}/records/${encodeURIComponent(providerRecordId)}`,\n ),\n \"deleteRecord\",\n { method: \"DELETE\" },\n );\n }),\n );\n\n const listAccounts = Effect.fn(\"VercelClient.listAccounts\")(() =>\n Effect.gen(function* () {\n const userResult = yield* request(new URL(`${baseUrl}/v2/user`), \"listAccounts\");\n const { user } = yield* decode(\n Protocol.UserEnvelope,\n userResult.body,\n \"listAccounts\",\n userResult.response,\n );\n const teams = yield* allTeams();\n return [\n { id: user.id, name: user.name ?? user.username, type: \"personal\" as const },\n ...teams.map((team) => ({\n id: team.id,\n name: team.name ?? team.slug,\n type: \"team\" as const,\n })),\n ];\n }),\n );\n\n const listZones = Effect.fn(\"VercelClient.listZones\")((input: ListZonesInput = {}) =>\n Effect.gen(function* () {\n const domains = (yield* allDomains()).filter(\n (domain) =>\n hasDnsStorage(domain) && (input.name === undefined || domain.name === input.name),\n );\n if (domains.length > 0 || input.name === undefined) {\n return yield* Effect.forEach(domains, projectZone);\n }\n const discovered = yield* discoverZone(input.name);\n return discovered === null ? [] : [yield* projectZone(discovered)];\n }),\n );\n\n const listTargets = Effect.fn(\"VercelClient.listTargets\")(\n (input: ProviderSession.ListTargetsInput = {}) =>\n Effect.gen(function* () {\n const names =\n input.domain === undefined\n ? undefined\n : new Set(Zones.candidates(input.domain).map((name) => String(name)));\n const domains = (yield* allDomains()).filter(\n (domain) =>\n hasDnsStorage(domain) &&\n (names === undefined || names.has(domain.name)) &&\n (input.accountId === undefined || (domain.teamId ?? domain.userId) === input.accountId),\n );\n if (domains.length > 0 || input.domain === undefined) {\n return yield* Effect.forEach(domains, targetFromDomain);\n }\n for (const name of Zones.candidates(input.domain)) {\n const discovered = yield* discoverZone(name);\n if (\n discovered !== null &&\n (input.accountId === undefined ||\n (discovered.teamId ?? discovered.userId) === input.accountId)\n ) {\n return [yield* targetFromDomain(discovered)];\n }\n }\n return [];\n }),\n );\n\n const resolveTarget = Effect.fn(\"VercelClient.resolveTarget\")((domain: DomainName.DomainName) =>\n Effect.gen(function* () {\n const candidates = yield* listTargets({ domain });\n for (const zoneName of Zones.candidates(domain)) {\n const matches = candidates.filter((target) => target.zoneName === zoneName);\n if (matches.length === 1) {\n const target = matches[0];\n if (target !== undefined) return ProviderSession.Resolution.Resolved({ target });\n }\n if (matches.length > 1) {\n return ProviderSession.Resolution.SelectionRequired({ candidates: matches });\n }\n }\n return ProviderSession.Resolution.NotFound({ domain });\n }),\n );\n\n const forTarget = Effect.fn(\"VercelClient.forTarget\")((target: Connection.ProviderTarget) =>\n Effect.gen(function* () {\n if (target.accountKind === \"team\") {\n if (options.context._tag !== \"team\" || options.context.teamId !== target.accountId) {\n return yield* Effect.fail(\n failure(\"forTarget\", \"Vercel team target is outside the selected installation\", {\n reason: \"authorization\",\n }),\n );\n }\n } else if (target.accountKind === \"personal\" && options.context._tag !== \"personal\") {\n return yield* Effect.fail(\n failure(\"forTarget\", \"Vercel personal target is outside the selected installation\", {\n reason: \"authorization\",\n }),\n );\n } else if (target.accountKind === \"account\") {\n return yield* Effect.fail(\n failure(\"forTarget\", \"Vercel does not support account-kind targets\", {\n reason: \"unsupported\",\n }),\n );\n } else if (target.accountKind === null) {\n return yield* Effect.fail(\n failure(\"forTarget\", \"Vercel targets must identify a personal or team account\", {\n reason: \"request\",\n }),\n );\n }\n const discovered = yield* listTargets({\n accountId: target.accountId,\n domain: target.zoneName,\n });\n const selected = discovered.find(\n (candidate) =>\n candidate.accountId === target.accountId &&\n candidate.accountKind === target.accountKind &&\n candidate.zoneId === target.zoneId &&\n candidate.zoneName === target.zoneName,\n );\n if (selected === undefined) {\n return yield* Effect.fail(\n failure(\n \"forTarget\",\n `Vercel target ${target.zoneName} is not visible to this installation`,\n { reason: \"authorization\" },\n ),\n );\n }\n const client = makeClient({ ...options, target: selected });\n return {\n id: client.id,\n createRecord: client.createRecord,\n deleteRecord: client.deleteRecord,\n getRecord: client.getRecord,\n listRecords: client.listRecords,\n } satisfies DnsProvider.Interface;\n }),\n );\n\n const validateToken = Effect.fn(\"VercelClient.validateToken\")(() =>\n Effect.gen(function* () {\n let accountId: string;\n if (options.context._tag === \"team\") {\n yield* allDomains();\n accountId = options.context.teamId;\n } else {\n const result = yield* request(new URL(`${baseUrl}/v2/user`), \"validateToken\");\n const { user } = yield* decode(\n Protocol.UserEnvelope,\n result.body,\n \"validateToken\",\n result.response,\n );\n accountId = user.id;\n }\n return {\n accountId,\n capabilities: options.capabilities,\n expiresAt: null,\n scopes: [],\n };\n }),\n );\n\n return {\n id: \"vercel\",\n providerId: \"vercel\",\n createRecord,\n deleteRecord,\n getRecord,\n listAccounts,\n listRecords,\n listZones,\n listTargets,\n resolveTarget,\n forTarget,\n validateToken,\n };\n}\n\nfunction hasDnsStorage(\n domain: Protocol.Domain,\n configuredServiceType: Protocol.DomainConfig[\"serviceType\"] = domain.serviceType,\n): boolean {\n return (\n configuredServiceType === \"zeit.world\" ||\n domain.zone === true ||\n domain.intendedNameservers.length > 0\n );\n}\n\nconst projectZone = Effect.fn(\"VercelClient.projectZone\")((domain: Protocol.Domain) =>\n Effect.gen(function* () {\n const name = yield* DomainName.decode(domain.name).pipe(\n Effect.mapError((cause) => failure(\"listZones\", cause.message, { reason: \"response\" })),\n );\n const nameservers = yield* Effect.forEach(domain.intendedNameservers, (nameserver) =>\n DomainName.decode(nameserver).pipe(\n Effect.mapError((cause) => failure(\"listZones\", cause.message, { reason: \"response\" })),\n ),\n );\n return {\n accountId: domain.teamId ?? domain.userId,\n id: domain.id,\n name,\n nameservers,\n status: domain.verified ? \"active\" : \"pending\",\n } as const;\n }),\n);\n\nconst targetFromDomain = Effect.fn(\"VercelClient.targetFromDomain\")((domain: Protocol.Domain) =>\n Effect.gen(function* () {\n const zoneName = yield* DomainName.decode(domain.name).pipe(\n Effect.mapError((cause) => failure(\"listTargets\", cause.message, { reason: \"response\" })),\n );\n const nameservers = yield* Effect.forEach(\n domain.nameservers.length > 0 ? domain.nameservers : domain.intendedNameservers,\n (nameserver) =>\n DomainName.decode(nameserver).pipe(\n Effect.mapError((cause) => failure(\"listTargets\", cause.message, { reason: \"response\" })),\n ),\n );\n return {\n accountId: domain.teamId ?? domain.userId,\n accountKind: domain.teamId === null ? (\"personal\" as const) : (\"team\" as const),\n evidence: {\n nameservers,\n status: domain.verified ? \"active\" : \"pending\",\n zoneType: domain.serviceType,\n },\n zoneId: domain.id,\n zoneName,\n } satisfies Connection.ProviderTarget;\n }),\n);\n\nfunction decode<A>(\n schema: S.ConstraintCodec<A, unknown, never, unknown>,\n input: unknown,\n operation: string,\n response: Response,\n): Effect.Effect<A, DnsProvider.Error> {\n return S.decodeUnknownEffect(schema)(input).pipe(\n Effect.mapError((cause) =>\n failure(operation, `Vercel response did not match its API contract: ${cause.message}`, {\n reason: \"response\",\n status: response.status,\n }),\n ),\n );\n}\n\nfunction apiFailure(input: unknown, operation: string, response: Response): DnsProvider.Error {\n const detail = S.decodeUnknownOption(Protocol.ErrorEnvelope)(input);\n return failure(\n operation,\n detail._tag === \"Some\"\n ? detail.value.error.message\n : `Vercel request failed with HTTP ${response.status}`,\n {\n ...(detail._tag === \"Some\" ? { code: detail.value.error.code } : {}),\n reason: reason(response.status, detail._tag === \"Some\" ? detail.value.error.code : undefined),\n ...rateLimit(response, detail._tag === \"Some\" ? detail.value.error : undefined),\n status: response.status,\n },\n );\n}\n\nfunction reason(status: number, code?: string): DnsProvider.ErrorReason {\n if (status === 401 || code === \"invalid_token\") return \"authentication\";\n if (status === 403) return \"authorization\";\n if (status === 404 || code === \"not_found\") return \"not_found\";\n if (status === 409 || code === \"conflict\") return \"conflict\";\n if (status === 429 || code === \"rate_limited\") return \"rate_limit\";\n if (status >= 500) return \"response\";\n return \"request\";\n}\n\nfunction rateLimit(\n response: Response,\n detail?: Protocol.ErrorDetail,\n): Partial<Pick<DnsProvider.Error, \"retryAfterMs\">> {\n const resetMs = detail?.limit?.resetMs;\n const header = response.headers.get(\"x-ratelimit-reset\");\n const reset = resetMs ?? (header === null ? undefined : Number(header) * 1_000);\n return reset === undefined || !Number.isFinite(reset)\n ? {}\n : { retryAfterMs: Math.max(0, reset - Date.now()) };\n}\n\nfunction failure(\n operation: string,\n message: string,\n fields: Partial<Pick<DnsProvider.Error, \"code\" | \"reason\" | \"retryAfterMs\" | \"status\">> = {},\n): DnsProvider.Error {\n return new DnsProvider.Error({ ...fields, message, operation, providerId: \"vercel\" });\n}\n","import { Clock, Effect, Schema as S } from \"effect\";\n\nimport * as Connection from \"../../auth/connect.ts\";\nimport * as ProviderAuthorization from \"../../auth/authorization.ts\";\nimport type * as ProviderAuth from \"../../auth/manifest.ts\";\nimport * as ProviderContext from \"../../auth/provider-context.ts\";\nimport * as Secret from \"../../auth/secret.ts\";\nimport * as DnsProvider from \"../../provider/provider.ts\";\nimport * as ProviderSession from \"../../provider/session.ts\";\nimport * as Client from \"./client.ts\";\nimport * as Protocol from \"./protocol.ts\";\n\nconst Context = S.TaggedUnion({\n personal: { installationId: S.NullOr(S.String) },\n team: { installationId: S.NullOr(S.String), teamId: S.String },\n});\nexport type Context = typeof Context.Type;\nexport const contextCodec = ProviderContext.codec(\"vercel.v1\", Context);\n\n/** Describes Vercel's caller-created personal access-token method. */\nexport function tokenMethod(\n capabilities: ProviderAuth.TokenValidation[\"capabilities\"],\n): Extract<ProviderAuth.Manifest[\"methods\"][number], { readonly _tag: \"token\" }> {\n return {\n _tag: \"token\",\n capabilities: [...capabilities],\n instructionsUrl: \"https://vercel.com/account/settings/tokens\",\n };\n}\n\nexport interface IntegrationMethodOptions {\n readonly capabilities: ProviderAuth.TokenValidation[\"capabilities\"];\n readonly slug: string;\n}\n\n/** Describes Vercel's provider-specific integration installation flow. */\nexport function integrationMethod(\n options: IntegrationMethodOptions,\n): ProviderAuth.IntegrationMethod {\n return {\n _tag: \"integration\",\n capabilities: [...options.capabilities],\n installUrl: `https://vercel.com/integrations/${encodeURIComponent(options.slug)}/new`,\n tokenEndpoint: \"https://api.vercel.com/v2/oauth/access_token\",\n };\n}\n\n/** Creates the Vercel token and integration authorization manifest. */\nexport function manifest(options: IntegrationMethodOptions): ProviderAuth.Manifest {\n return {\n methods: [tokenMethod(options.capabilities), integrationMethod(options)],\n providerId: \"vercel\",\n };\n}\n\nexport interface ExchangeCodeOptions {\n readonly baseUrl?: string;\n readonly clientId: string;\n readonly clientSecret: Secret.Value;\n readonly code: Secret.Value;\n /** Configuration ID returned by Vercel's integration callback, when available. */\n readonly configurationId?: string;\n readonly fetch?: Client.Fetch;\n readonly redirectUri: string;\n}\n\nexport interface IntegrationCredential {\n readonly accessToken: Secret.Value;\n readonly context: Client.AccountContext;\n readonly installationId: string | null;\n readonly userId: string;\n}\n\n/** Exchanges Vercel's one-time integration code and preserves its account context. */\nexport const exchangeCode = Effect.fn(\"VercelAuth.exchangeCode\")((options: ExchangeCodeOptions) =>\n Effect.gen(function* () {\n const fetch = options.fetch ?? globalThis.fetch;\n const baseUrl = (options.baseUrl ?? \"https://api.vercel.com\").replace(/\\/$/, \"\");\n const body = new URLSearchParams({\n client_id: options.clientId,\n client_secret: options.clientSecret.expose(),\n code: options.code.expose(),\n redirect_uri: options.redirectUri,\n });\n const response = yield* Effect.tryPromise({\n try: () =>\n fetch(`${baseUrl}/v2/oauth/access_token`, {\n body,\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n },\n method: \"POST\",\n }),\n catch: () => failure(\"exchangeCode\", \"Vercel token exchange failed\", \"transport\"),\n });\n const input = yield* Effect.tryPromise({\n try: () => response.json() as Promise<unknown>,\n catch: () =>\n failure(\n \"exchangeCode\",\n response.ok\n ? \"Vercel returned a non-JSON token response\"\n : `Vercel token exchange failed with HTTP ${response.status}`,\n response.ok ? \"response\" : response.status === 401 ? \"authentication\" : \"request\",\n response.status,\n ),\n });\n if (!response.ok) {\n const detail = S.decodeUnknownOption(Protocol.ErrorEnvelope)(input);\n return yield* Effect.fail(\n failure(\n \"exchangeCode\",\n detail._tag === \"Some\"\n ? detail.value.error.message\n : `Vercel token exchange failed with HTTP ${response.status}`,\n response.status === 401 ? \"authentication\" : \"request\",\n response.status,\n detail._tag === \"Some\" ? detail.value.error.code : undefined,\n ),\n );\n }\n const token = yield* S.decodeUnknownEffect(Protocol.IntegrationToken)(input).pipe(\n Effect.mapError((cause) =>\n failure(\n \"exchangeCode\",\n `Vercel token response did not match its API contract: ${cause.message}`,\n \"response\",\n response.status,\n ),\n ),\n );\n return {\n accessToken: Secret.make(token.access_token),\n context:\n token.team_id === null\n ? ({ _tag: \"personal\" } as const)\n : ({ _tag: \"team\", teamId: token.team_id } as const),\n installationId: token.installation_id ?? options.configurationId ?? null,\n userId: token.user_id,\n };\n }),\n);\n\nexport interface TokenConnectionOptions extends Omit<Client.Options, \"token\"> {\n readonly token: Secret.Value;\n}\n\n/** Creates a provider-independent token connection method backed by Vercel validation. */\nexport function tokenConnectionMethod(\n options: TokenConnectionOptions,\n): Extract<Connection.Method, { readonly _tag: \"Token\" }> {\n const requiredCapabilities = [...options.capabilities];\n return Connection.Method.Token({\n authenticate: Effect.fn(\"VercelAuth.authenticateToken\")(function* (token) {\n const validated = yield* Client.make({ ...options, token }).validateToken();\n const observedAt = new Date(yield* Clock.currentTimeMillis);\n return {\n capabilityEvidence: validated.capabilities.map((capability) => ({\n capability,\n evidence: ProviderAuthorization.Evidence.Introspected({ observedAt }),\n })),\n credential: {\n accessToken: token,\n expiresAt: validated.expiresAt,\n refreshToken: null,\n tokenType: \"bearer\",\n },\n providerAccountId: validated.accountId,\n providerContext: yield* contextCodec.encode(\n options.context._tag === \"team\"\n ? { _tag: \"team\", installationId: null, teamId: options.context.teamId }\n : { _tag: \"personal\", installationId: null },\n ),\n scopes: [...validated.scopes],\n } satisfies Connection.Authentication;\n }),\n providerId: \"vercel\",\n requiredCapabilities,\n token: options.token,\n });\n}\n\n/** Converts a completed Vercel Integration exchange into canonical connection authentication. */\nexport const integrationAuthentication = Effect.fn(\"VercelAuth.integrationAuthentication\")(\n function* (\n options: ExchangeCodeOptions & {\n readonly capabilities: ReadonlyArray<ProviderAuthorization.Capability>;\n },\n ) {\n const exchanged = yield* exchangeCode(options);\n const observedAt = new Date(yield* Clock.currentTimeMillis);\n return {\n capabilityEvidence: options.capabilities.map((capability) => ({\n capability,\n evidence: ProviderAuthorization.Evidence.Introspected({ observedAt }),\n })),\n credential: {\n accessToken: exchanged.accessToken,\n expiresAt: null,\n refreshToken: null,\n tokenType: \"bearer\",\n },\n providerAccountId:\n exchanged.context._tag === \"team\" ? exchanged.context.teamId : exchanged.userId,\n providerContext: yield* contextCodec.encode(\n exchanged.context._tag === \"team\"\n ? {\n _tag: \"team\",\n installationId: exchanged.installationId,\n teamId: exchanged.context.teamId,\n }\n : { _tag: \"personal\", installationId: exchanged.installationId },\n ),\n scopes: [],\n } satisfies Connection.Authentication;\n },\n);\n\n/** Restore a credential-scoped Vercel session from persisted authorization state. */\nexport function restore(\n options: ProviderSession.RestoreInput & Pick<Client.Options, \"baseUrl\" | \"fetch\">,\n): Effect.Effect<Client.Interface, DnsProvider.Error> {\n return Effect.gen(function* () {\n if (options.authorization.providerId !== \"vercel\") {\n return yield* Effect.fail(\n failure(\"restore\", \"Provider authorization belongs to another provider\", \"authorization\"),\n );\n }\n if (options.authorization.revocation._tag !== \"Active\") {\n return yield* Effect.fail(\n failure(\"restore\", \"Vercel authorization is pending revocation\", \"authorization\"),\n );\n }\n const missingCapability = options.authorization.requiredCapabilities.find(\n (capability) =>\n !options.authorization.capabilityEvidence.some((item) => item.capability === capability),\n );\n if (missingCapability !== undefined) {\n return yield* Effect.fail(\n failure(\n \"restore\",\n `Vercel authorization lacks evidence for ${missingCapability}`,\n \"authorization\",\n ),\n );\n }\n if (\n options.credential.expiresAt !== null &&\n (Number.isNaN(options.credential.expiresAt.valueOf()) ||\n options.credential.expiresAt <= new Date())\n ) {\n return yield* Effect.fail(\n failure(\"restore\", \"Vercel authorization has expired\", \"authentication\"),\n );\n }\n const context = yield* contextCodec\n .decode(options.authorization.providerContext)\n .pipe(Effect.mapError((cause) => failure(\"restore\", cause.message, \"response\")));\n return Client.make({\n ...(options.baseUrl === undefined ? {} : { baseUrl: options.baseUrl }),\n capabilities: options.authorization.capabilityEvidence.map(({ capability }) => capability),\n ...(options.fetch === undefined ? {} : { fetch: options.fetch }),\n context:\n context._tag === \"team\" ? { _tag: \"team\", teamId: context.teamId } : { _tag: \"personal\" },\n token: options.credential.accessToken,\n });\n });\n}\n\nexport interface IntegrationFlowOptions\n extends Omit<ExchangeCodeOptions, \"code\">, IntegrationMethodOptions {}\n\n/** Creates Vercel Integration's implementation of the common interactive connection capability. */\nexport function integrationFlow(options: IntegrationFlowOptions): Connection.InteractiveFlow {\n const method = integrationMethod(options);\n const Payload = S.fromJsonString(S.Struct({ state: S.String }));\n return {\n complete: Effect.fn(\"VercelAuth.integrationFlow.complete\")(function* (payload, callbackUrl) {\n const continuation = yield* S.decodeUnknownEffect(Payload)(payload.expose()).pipe(\n Effect.mapError(\n () =>\n new Connection.Error({\n category: \"authorization\",\n message: \"Vercel Integration continuation payload is invalid\",\n operation: \"VercelAuth.integrationFlow.complete\",\n retry: \"after-user-action\",\n }),\n ),\n );\n const code = callbackUrl.searchParams.get(\"code\");\n const configurationId = callbackUrl.searchParams.get(\"configurationId\");\n if (\n callbackUrl.searchParams.get(\"state\") !== continuation.state ||\n code === null ||\n configurationId === null\n ) {\n return yield* new Connection.Error({\n category: \"authorization\",\n message: \"Vercel Integration callback does not match its continuation\",\n operation: \"VercelAuth.integrationFlow.complete\",\n retry: \"after-user-action\",\n });\n }\n const authentication = yield* integrationAuthentication({\n ...(options.baseUrl === undefined ? {} : { baseUrl: options.baseUrl }),\n capabilities: options.capabilities,\n clientId: options.clientId,\n clientSecret: options.clientSecret,\n code: Secret.make(code),\n configurationId,\n ...(options.fetch === undefined ? {} : { fetch: options.fetch }),\n redirectUri: options.redirectUri,\n });\n const callbackTeamId = callbackUrl.searchParams.get(\"teamId\");\n if (callbackTeamId !== null) {\n const context = yield* contextCodec.decode(authentication.providerContext).pipe(\n Effect.mapError(\n (cause) =>\n new Connection.Error({\n category: \"provider\",\n message: cause.message,\n operation: \"VercelAuth.integrationFlow.complete\",\n retry: \"unknown\",\n }),\n ),\n );\n if (context._tag !== \"team\" || context.teamId !== callbackTeamId) {\n return yield* new Connection.Error({\n category: \"authorization\",\n message: \"Vercel Integration callback team does not match the exchanged installation\",\n operation: \"VercelAuth.integrationFlow.complete\",\n retry: \"after-user-action\",\n });\n }\n }\n return authentication;\n }),\n method: \"integration\",\n providerId: \"vercel\",\n requiredCapabilities: [...options.capabilities],\n start: (continuationId) => {\n const authorizationUrl = new URL(method.installUrl);\n authorizationUrl.searchParams.set(\"source\", \"external\");\n authorizationUrl.searchParams.set(\"state\", continuationId);\n return Effect.succeed({\n authorizationUrl,\n payload: Secret.make(JSON.stringify({ state: continuationId })),\n });\n },\n };\n}\n\nfunction failure(\n operation: string,\n message: string,\n reason: DnsProvider.ErrorReason,\n status?: number,\n code?: string,\n): DnsProvider.Error {\n return new DnsProvider.Error({\n ...(code === undefined ? {} : { code }),\n message,\n operation,\n providerId: \"vercel\",\n reason,\n ...(status === undefined ? {} : { status }),\n });\n}\n","import { Effect, Schema, SchemaIssue, SchemaTransformation } from \"effect\";\n\nimport * as DomainName from \"../domain/domain-name.ts\";\nimport type * as DnsRecord from \"../domain/dns-record.ts\";\nimport { Error as InvalidInputError } from \"../invalid-input.ts\";\n\nconst CanonicalAddress = Schema.String.pipe(\n Schema.decodeTo(\n Schema.String,\n SchemaTransformation.transform({\n decode: (value) => value.trim().toLowerCase(),\n encode: (value) => value,\n }),\n ),\n);\n\nconst CanonicalDomain = Schema.String.pipe(\n Schema.decodeTo(\n Schema.String,\n SchemaTransformation.transformOrFail({\n decode: (value, options) =>\n Effect.try({\n try: () => DomainName.parse(value).toString(),\n catch: (cause) =>\n new SchemaIssue.InvalidValue(\n { message: cause instanceof Error ? cause.message : String(cause) },\n value,\n options,\n ),\n }),\n encode: (value) => Effect.succeed(value),\n }),\n ),\n);\n\nconst CanonicalMx = tokenizedDomain(2, 1);\nconst CanonicalSrv = tokenizedDomain(4, 3);\n\nconst CanonicalTxt = Schema.String.pipe(\n Schema.decodeTo(\n Schema.String,\n SchemaTransformation.transform({\n decode: (value) => {\n const trimmed = value.trim();\n const chunks = [...trimmed.matchAll(/\"((?:\\\\.|[^\"])*)\"/g)];\n return chunks.length === 0\n ? trimmed\n : chunks\n .map((match) => (match[1] ?? \"\").replace(/\\\\\"/g, '\"').replace(/\\\\\\\\/g, \"\\\\\"))\n .join(\"\");\n },\n encode: (value) => value,\n }),\n ),\n);\n\nconst CanonicalCaa = Schema.String.pipe(\n Schema.decodeTo(\n Schema.String,\n SchemaTransformation.transform({\n decode: (value) => value.trim().replace(/\\s+\"([\\s\\S]*)\"$/, \" $1\"),\n encode: (value) => value,\n }),\n ),\n);\n\nexport function parse(type: DnsRecord.Type, input: unknown): string {\n const schema = (() => {\n switch (type) {\n case \"A\":\n case \"AAAA\":\n return CanonicalAddress;\n case \"CNAME\":\n case \"NS\":\n return CanonicalDomain;\n case \"MX\":\n return CanonicalMx;\n case \"SRV\":\n return CanonicalSrv;\n case \"TXT\":\n return CanonicalTxt;\n case \"CAA\":\n return CanonicalCaa;\n }\n })();\n try {\n return Schema.decodeUnknownSync(schema)(input);\n } catch (cause) {\n throw new InvalidInputError({\n message: cause instanceof Error ? cause.message : String(cause),\n });\n }\n}\n\nfunction tokenizedDomain(length: number, domainIndex: number) {\n return Schema.String.pipe(\n Schema.decodeTo(\n Schema.String,\n SchemaTransformation.transformOrFail({\n decode: (value, options) =>\n Effect.try({\n try: () => {\n const parts = value.trim().split(/\\s+/);\n if (parts.length !== length)\n throw new Error(\"DNS record data has an invalid field count\");\n const domain = parts[domainIndex];\n if (domain === undefined) throw new Error(\"DNS record target is missing\");\n parts[domainIndex] = DomainName.parse(domain);\n return parts.join(\" \");\n },\n catch: (cause) =>\n new SchemaIssue.InvalidValue(\n { message: cause instanceof Error ? cause.message : String(cause) },\n value,\n options,\n ),\n }),\n encode: (value) => Effect.succeed(value),\n }),\n ),\n );\n}\n","import * as DnsPacket from \"@leichtgewicht/dns-packet\";\nimport { Effect, Layer } from \"effect\";\n\nimport * as DomainName from \"../domain/domain-name.ts\";\nimport * as DnsRecord from \"../domain/dns-record.ts\";\nimport * as DnsData from \"./dns-data.ts\";\nimport * as DnsResolver from \"./resolver.ts\";\n\nexport type Fetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n\nexport interface Options {\n readonly endpoint: string;\n readonly fetch?: Fetch;\n readonly timeoutMs?: number;\n}\n\nexport function make(options: Options): DnsResolver.Interface {\n const fetch = options.fetch ?? globalThis.fetch;\n const timeoutMs = options.timeoutMs ?? 5_000;\n return {\n resolve: Effect.fn(\"DnsOverHttps.resolve\")((query) =>\n Effect.tryPromise({\n try: (effectSignal) =>\n request({ effectSignal, fetch, query, timeoutMs, endpoint: options.endpoint }),\n catch: (cause) =>\n cause instanceof DnsResolver.Error\n ? cause\n : new DnsResolver.Error({\n cause,\n message: cause instanceof Error ? cause.message : \"DNS resolution failed\",\n reason: \"transport\",\n }),\n }).pipe(Effect.flatMap((message) => decodeResolution(query, message))),\n ),\n };\n}\n\nexport const layer = (options: Options): Layer.Layer<DnsResolver.Service> =>\n Layer.succeed(DnsResolver.Service, make(options));\n\nexport const toAsync = (options: Options): DnsResolver.AsyncInterface =>\n DnsResolver.toAsync(make(options));\n\nfunction decodeResolution(\n query: DnsResolver.Query,\n message: Uint8Array,\n): Effect.Effect<DnsResolver.Resolution, DnsResolver.Error> {\n return Effect.try({\n try: () => DnsPacket.decode(message),\n catch: (cause) =>\n new DnsResolver.Error({\n cause,\n message: \"DoH returned an invalid DNS message\",\n reason: \"response\",\n }),\n }).pipe(\n Effect.flatMap((packet) => validatePacket(query, packet)),\n Effect.flatMap(decodePacket),\n );\n}\n\nfunction decodePacket(\n packet: DnsPacket.Packet,\n): Effect.Effect<DnsResolver.Resolution, DnsResolver.Error> {\n if (packet.rcode === \"NXDOMAIN\") {\n return Effect.succeed({ _tag: \"nodata\" });\n }\n if (packet.rcode !== \"NOERROR\") {\n return Effect.fail(\n new DnsResolver.Error({\n message: `DNS resolver returned ${packet.rcode ?? \"an unknown response code\"}`,\n reason: \"response\",\n }),\n );\n }\n if (packet.answers === undefined || packet.answers.length === 0) {\n return Effect.succeed({ _tag: \"nodata\" });\n }\n return Effect.forEach(packet.answers, decodeAnswer, { concurrency: \"unbounded\" }).pipe(\n Effect.map((answers): DnsResolver.Resolution => {\n const supportedAnswers = answers.filter((answer) => answer !== null);\n return supportedAnswers.length === 0\n ? { _tag: \"nodata\" }\n : { _tag: \"answer\", answers: supportedAnswers };\n }),\n );\n}\n\nfunction validatePacket(\n query: DnsResolver.Query,\n packet: DnsPacket.Packet,\n): Effect.Effect<DnsPacket.Packet, DnsResolver.Error> {\n return Effect.try({\n try: () => {\n if (packet.type !== \"response\") throw new Error(\"DoH returned a DNS query\");\n if (packet.id !== 0) throw new Error(\"DoH response used an unexpected message ID\");\n if (packet.flag_tc) throw new Error(\"DoH returned a truncated DNS response\");\n const questions = packet.questions ?? [];\n if (questions.length !== 1) throw new Error(\"DoH returned an unexpected question count\");\n const question = questions[0];\n if (question === undefined) throw new Error(\"DoH response omitted the DNS question\");\n if (\n question.class !== \"IN\" ||\n question.type !== query.type ||\n DomainName.parse(question.name) !== query.name\n ) {\n throw new Error(\"DoH response did not match the DNS question\");\n }\n return packet;\n },\n catch: (cause) =>\n new DnsResolver.Error({\n cause,\n message: cause instanceof Error ? cause.message : \"DoH returned an invalid DNS response\",\n reason: \"response\",\n }),\n });\n}\n\nfunction decodeAnswer(\n answer: DnsPacket.Answer,\n): Effect.Effect<DnsResolver.Answer | null, DnsResolver.Error> {\n return Effect.gen(function* () {\n if (answer.class !== \"IN\") return null;\n const decoded = yield* Effect.try({\n try: () => answerData(answer),\n catch: (cause) =>\n new DnsResolver.Error({\n cause,\n message: \"DoH returned invalid DNS record data\",\n reason: \"response\",\n }),\n });\n if (decoded === undefined) return null;\n const name = yield* DomainName.decode(answer.name);\n const data = yield* Effect.try({\n try: () => DnsData.parse(decoded.type, decoded.data),\n catch: (cause) =>\n new DnsResolver.Error({\n cause,\n message: \"DoH returned invalid DNS record data\",\n reason: \"response\",\n }),\n });\n if (answer.ttl === undefined) {\n return yield* new DnsResolver.Error({\n message: \"DoH response omitted the DNS record TTL\",\n reason: \"response\",\n });\n }\n return { data, name, ttl: answer.ttl, type: decoded.type };\n }).pipe(\n Effect.mapError((cause) =>\n cause instanceof DnsResolver.Error\n ? cause\n : new DnsResolver.Error({ cause, message: cause.message, reason: \"response\" }),\n ),\n );\n}\n\nfunction answerData(\n answer: DnsPacket.Answer,\n): { readonly data: string; readonly type: DnsRecord.Type } | undefined {\n switch (answer.type) {\n case \"A\":\n case \"AAAA\":\n case \"CNAME\":\n case \"NS\":\n return { data: answer.data, type: answer.type };\n case \"CAA\":\n return {\n data: `${answer.data.flags ?? 0} ${answer.data.tag} ${answer.data.value}`,\n type: answer.type,\n };\n case \"MX\":\n return {\n data: `${requiredNumber(answer.data.preference, \"MX preference\")} ${answer.data.exchange}`,\n type: answer.type,\n };\n case \"SRV\":\n return {\n data: [\n requiredNumber(answer.data.priority, \"SRV priority\"),\n requiredNumber(answer.data.weight, \"SRV weight\"),\n requiredNumber(answer.data.port, \"SRV port\"),\n answer.data.target,\n ].join(\" \"),\n type: answer.type,\n };\n case \"TXT\":\n return { data: decodeTxt(answer.data), type: answer.type };\n default:\n return undefined;\n }\n}\n\nfunction decodeTxt(data: DnsPacket.TxtData): string {\n const chunks = Array.isArray(data) ? data : [data];\n const encoded = chunks.map((chunk) =>\n typeof chunk === \"string\" ? new TextEncoder().encode(chunk) : chunk,\n );\n const length = encoded.reduce((total, chunk) => total + chunk.length, 0);\n const joined = new Uint8Array(length);\n let offset = 0;\n for (const chunk of encoded) {\n joined.set(chunk, offset);\n offset += chunk.length;\n }\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(joined);\n}\n\nfunction requiredNumber(value: number | undefined, field: string): number {\n if (value === undefined) throw new Error(`DoH response omitted ${field}`);\n return value;\n}\n\nasync function request(input: {\n readonly effectSignal: AbortSignal;\n readonly endpoint: string;\n readonly fetch: Fetch;\n readonly query: DnsResolver.Query;\n readonly timeoutMs: number;\n}): Promise<Uint8Array> {\n const controller = new AbortController();\n let timedOut = false;\n const abortFromEffect = () => controller.abort(input.effectSignal.reason);\n const abortFromHost = () => controller.abort(input.query.signal?.reason);\n input.effectSignal.addEventListener(\"abort\", abortFromEffect, { once: true });\n input.query.signal?.addEventListener(\"abort\", abortFromHost, { once: true });\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort(new Error(\"DNS resolution timed out\"));\n }, input.timeoutMs);\n try {\n const query = Uint8Array.from(\n DnsPacket.encode({\n flags: DnsPacket.RECURSION_DESIRED,\n id: 0,\n questions: [{ name: input.query.name, type: input.query.type }],\n type: \"query\",\n }),\n );\n const response = await input.fetch(new URL(input.endpoint), {\n body: query,\n headers: {\n accept: \"application/dns-message\",\n \"content-type\": \"application/dns-message\",\n },\n method: \"POST\",\n signal: controller.signal,\n });\n if (!response.ok) {\n throw new DnsResolver.Error({\n message: `DoH returned HTTP ${response.status}`,\n reason: \"transport\",\n });\n }\n const contentType = response.headers\n .get(\"content-type\")\n ?.split(\";\", 1)[0]\n ?.trim()\n .toLowerCase();\n if (contentType !== \"application/dns-message\") {\n throw new DnsResolver.Error({\n message: `DoH returned unsupported content type ${contentType ?? \"<missing>\"}`,\n reason: \"response\",\n });\n }\n return new Uint8Array(await response.arrayBuffer());\n } catch (cause) {\n if (timedOut) {\n throw new DnsResolver.Error({ message: \"DNS query timed out\", reason: \"timeout\" });\n }\n throw cause;\n } finally {\n clearTimeout(timer);\n input.effectSignal.removeEventListener(\"abort\", abortFromEffect);\n input.query.signal?.removeEventListener(\"abort\", abortFromHost);\n }\n}\n","import { Layer } from \"effect\";\n\nimport * as DnsOverHttps from \"./doh.ts\";\nimport * as DnsResolver from \"./resolver.ts\";\n\nconst endpoint = \"https://cloudflare-dns.com/dns-query\";\n\nexport interface Options extends Omit<DnsOverHttps.Options, \"endpoint\"> {\n readonly endpoint?: string;\n}\n\nexport function make(options: Options = {}): DnsResolver.Interface {\n return DnsOverHttps.make({ ...options, endpoint: options.endpoint ?? endpoint });\n}\n\nexport const layer = (options: Options = {}): Layer.Layer<DnsResolver.Service> =>\n Layer.succeed(DnsResolver.Service, make(options));\n\nexport const toAsync = (options: Options = {}): DnsResolver.AsyncInterface =>\n DnsResolver.toAsync(make(options));\n","import { Layer } from \"effect\";\n\nimport * as DnsOverHttps from \"./doh.ts\";\nimport * as DnsResolver from \"./resolver.ts\";\n\nconst endpoint = \"https://dns.google/dns-query\";\n\nexport interface Options extends Omit<DnsOverHttps.Options, \"endpoint\"> {\n readonly endpoint?: string;\n}\n\nexport function make(options: Options = {}): DnsResolver.Interface {\n return DnsOverHttps.make({ ...options, endpoint: options.endpoint ?? endpoint });\n}\n\nexport const layer = (options: Options = {}): Layer.Layer<DnsResolver.Service> =>\n Layer.succeed(DnsResolver.Service, make(options));\n\nexport const toAsync = (options: Options = {}): DnsResolver.AsyncInterface =>\n DnsResolver.toAsync(make(options));\n","import { Context, Data, Effect, Layer, Schema } from \"effect\";\n\nimport * as CloudflareDnsOverHttps from \"./cloudflare-doh.ts\";\nimport * as DnsOverHttps from \"./doh.ts\";\nimport * as DnsResolver from \"./resolver.ts\";\nimport * as GoogleDnsOverHttps from \"./google-doh.ts\";\n\nexport interface Entry {\n readonly id: string;\n readonly resolver: DnsResolver.Interface;\n readonly timeoutMs?: number;\n}\n\nexport type Observation = Data.TaggedEnum<{\n Answer: { readonly answers: ReadonlyArray<DnsResolver.Answer>; readonly resolverId: string };\n Failed: {\n readonly message: string;\n readonly reason: Exclude<DnsResolver.Error[\"reason\"], \"timeout\">;\n readonly resolverId: string;\n };\n NoData: { readonly resolverId: string };\n TimedOut: { readonly resolverId: string; readonly timeoutMs: number };\n}>;\nexport const Observation = Data.taggedEnum<Observation>();\n\nexport type Policy = Data.TaggedEnum<{\n AllMatch: {};\n AnyMatch: {};\n Quorum: { readonly minimum: number };\n}>;\nconst PolicyVariants = Data.taggedEnum<Policy>();\nconst QuorumMinimum = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));\nconst PolicySchema = Schema.TaggedUnion({\n AllMatch: {},\n AnyMatch: {},\n Quorum: { minimum: QuorumMinimum },\n});\nexport const Policy = {\n AllMatch: PolicyVariants.AllMatch,\n AnyMatch: PolicyVariants.AnyMatch,\n Quorum: ({ minimum }: { readonly minimum: number }): Policy =>\n PolicyVariants.Quorum({ minimum: Schema.decodeUnknownSync(QuorumMinimum)(minimum) }),\n Schema: PolicySchema,\n};\n\nexport interface Interface {\n readonly observe: (query: DnsResolver.Query) => Effect.Effect<ReadonlyArray<Observation>>;\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@domainkit/DnsResolverPool\") {}\n\nexport function make(entries: ReadonlyArray<Entry>): Interface {\n return Service.of({\n observe: Effect.fn(\"DnsResolverPool.observe\")((query) =>\n Effect.forEach(entries, (entry) => observe(entry, query), { concurrency: \"unbounded\" }),\n ),\n });\n}\n\nexport interface DefaultOptions extends Omit<DnsOverHttps.Options, \"endpoint\"> {}\n\n/** Cloudflare and Google RFC wire-format DoH resolvers. */\nexport function defaultMake(options: DefaultOptions = {}): Interface {\n const timeoutMs = options.timeoutMs ?? 5_000;\n return make([\n {\n id: \"cloudflare\",\n resolver: CloudflareDnsOverHttps.make(options),\n timeoutMs,\n },\n { id: \"google\", resolver: GoogleDnsOverHttps.make(options), timeoutMs },\n ]);\n}\n\nexport const defaultLayer = (options: DefaultOptions = {}): Layer.Layer<Service> =>\n Layer.succeed(Service, defaultMake(options));\n\nfunction observe(entry: Entry, query: DnsResolver.Query): Effect.Effect<Observation> {\n const timeoutMs = entry.timeoutMs ?? 5_000;\n return entry.resolver.resolve(query).pipe(\n Effect.timeout(timeoutMs),\n Effect.match({\n onFailure: (failure): Observation => {\n if (\n failure._tag === \"TimeoutError\" ||\n (failure._tag === \"ResolverError\" && failure.reason === \"timeout\")\n ) {\n return Observation.TimedOut({ resolverId: entry.id, timeoutMs });\n }\n return Observation.Failed({\n message: failure.message,\n reason: failure.reason === \"response\" ? \"response\" : \"transport\",\n resolverId: entry.id,\n });\n },\n onSuccess: (resolution): Observation =>\n resolution._tag === \"nodata\"\n ? Observation.NoData({ resolverId: entry.id })\n : Observation.Answer({ answers: resolution.answers, resolverId: entry.id }),\n }),\n );\n}\n","import { Data, Effect, Option, Schema } from \"effect\";\n\nimport type * as DomainName from \"../domain/domain-name.ts\";\nimport * as DnsRecord from \"../domain/dns-record.ts\";\nimport { Error as InvalidInputError } from \"../invalid-input.ts\";\nimport * as DnsProvider from \"../provider/provider.ts\";\nimport * as DnsData from \"./dns-data.ts\";\nimport * as DnsResolverPool from \"./resolver-pool.ts\";\n\nexport type PublicDns = Data.TaggedEnum<{\n Disabled: {};\n Enabled: { readonly policy?: DnsResolverPool.Policy };\n}>;\nexport const PublicDns = Data.taggedEnum<PublicDns>();\n\nexport type Provider = Data.TaggedEnum<{\n Disabled: {};\n Enabled: { readonly zone: DomainName.DomainName };\n}>;\nexport const Provider = Data.taggedEnum<Provider>();\n\ntype ProviderEnabled = Extract<Provider, { readonly _tag: \"Enabled\" }>;\ntype ProviderDisabled = Extract<Provider, { readonly _tag: \"Disabled\" }>;\n\nexport interface PublicOnlyConfig {\n readonly provider?: ProviderDisabled;\n readonly publicDns?: PublicDns;\n readonly record: DnsRecord.DnsRecord;\n}\n\nexport interface ProviderConfig {\n readonly provider: ProviderEnabled;\n readonly publicDns?: PublicDns;\n readonly record: DnsRecord.DnsRecord;\n}\n\nexport type Config = ProviderConfig | PublicOnlyConfig;\n\nexport type ProviderObservation = Data.TaggedEnum<{\n Matched: {};\n Mismatch: { readonly records: ReadonlyArray<DnsRecord.DnsRecord> };\n Pending: {};\n Unavailable: { readonly message: string };\n}>;\nexport const ProviderObservation = Data.taggedEnum<ProviderObservation>();\n\nexport type PublicDnsObservation = Data.TaggedEnum<{\n Verified: {\n readonly evidence: ReadonlyArray<DnsResolverPool.Observation>;\n readonly matchedResolverIds: ReadonlyArray<string>;\n };\n Mismatch: { readonly evidence: ReadonlyArray<DnsResolverPool.Observation> };\n Pending: { readonly evidence: ReadonlyArray<DnsResolverPool.Observation> };\n Unavailable: { readonly evidence: ReadonlyArray<DnsResolverPool.Observation> };\n}>;\nexport const PublicDnsObservation = Data.taggedEnum<PublicDnsObservation>();\n\ninterface Evidence {\n readonly provider: ProviderObservation | null;\n readonly publicDns: PublicDnsObservation | null;\n}\n\nexport type Result = Data.TaggedEnum<{\n Mismatch: Evidence;\n NotObserved: Evidence;\n Pending: Evidence;\n Unavailable: Evidence;\n Verified: Evidence;\n}>;\nexport const Result = Data.taggedEnum<Result>();\n\nexport function observe(input: PublicOnlyConfig): Effect.Effect<Result, InvalidInputError>;\nexport function observe(\n input: ProviderConfig,\n): Effect.Effect<Result, InvalidInputError, DnsProvider.Service>;\nexport function observe(\n input: Config,\n): Effect.Effect<Result, InvalidInputError, DnsProvider.Service>;\nexport function observe(\n input: Config,\n): Effect.Effect<Result, InvalidInputError, DnsProvider.Service> {\n return observeEffect(input);\n}\n\nconst observeEffect = Effect.fn(\"Verification.observe\")(function* (input: Config) {\n const publicDns = input.publicDns ?? PublicDns.Enabled({});\n const provider = input.provider ?? Provider.Disabled();\n const publicEffect =\n publicDns._tag === \"Disabled\"\n ? Effect.succeed<PublicDnsObservation | null>(null)\n : observePublicDns(input.record, publicDns.policy ?? DnsResolverPool.Policy.AnyMatch());\n const providerEffect =\n provider._tag === \"Disabled\"\n ? Effect.succeed<ProviderObservation | null>(null)\n : Effect.flatMap(DnsProvider.Service, (service) =>\n observeProvider(service, provider.zone, input.record).pipe(\n Effect.catch((failure) =>\n Effect.succeed<ProviderObservation>(\n ProviderObservation.Unavailable({ message: failure.message }),\n ),\n ),\n ),\n );\n const [providerObservation, publicDnsObservation] = yield* Effect.all(\n [providerEffect, publicEffect] as const,\n { concurrency: \"unbounded\" },\n );\n return aggregate({ provider: providerObservation, publicDns: publicDnsObservation });\n});\n\nfunction observeProvider(\n provider: DnsProvider.Interface,\n zone: DomainName.DomainName,\n requirement: DnsRecord.DnsRecord,\n): Effect.Effect<ProviderObservation, DnsProvider.Error> {\n return provider.listRecords(zone).pipe(\n Effect.map((records): ProviderObservation => {\n if (\n records.some(\n (existing) => existing._tag !== \"Opaque\" && DnsRecord.equals(existing, requirement),\n )\n ) {\n return ProviderObservation.Matched();\n }\n const sameSet = records.filter(\n (existing): existing is DnsRecord.DnsRecord =>\n existing._tag !== \"Opaque\" &&\n existing.name === requirement.name &&\n existing._tag === requirement._tag,\n );\n return sameSet.length === 0\n ? ProviderObservation.Pending()\n : ProviderObservation.Mismatch({ records: sameSet });\n }),\n );\n}\n\nfunction observePublicDns(\n requirement: DnsRecord.DnsRecord,\n policy: DnsResolverPool.Policy,\n): Effect.Effect<PublicDnsObservation, InvalidInputError> {\n return Effect.gen(function* () {\n const validatedPolicy = yield* Schema.decodeUnknownEffect(DnsResolverPool.Policy.Schema)(\n policy,\n ).pipe(Effect.mapError((cause) => new InvalidInputError({ message: cause.message })));\n const configuredPool = yield* Effect.serviceOption(DnsResolverPool.Service);\n const pool = Option.getOrElse(configuredPool, () => DnsResolverPool.defaultMake());\n const evidence = yield* pool.observe({ name: requirement.name, type: requirement._tag });\n if (validatedPolicy._tag === \"Quorum\" && validatedPolicy.minimum > evidence.length) {\n return yield* new InvalidInputError({\n message: `Quorum minimum ${validatedPolicy.minimum} exceeds the ${evidence.length} configured resolvers`,\n });\n }\n return evaluatePublicDns(requirement, validatedPolicy, evidence);\n });\n}\n\nfunction evaluatePublicDns(\n requirement: DnsRecord.DnsRecord,\n policy: DnsResolverPool.Policy,\n evidence: ReadonlyArray<DnsResolverPool.Observation>,\n): PublicDnsObservation {\n const matchedResolverIds = evidence.flatMap((observation) =>\n observation._tag === \"Answer\" && answersMatch(requirement, observation.answers)\n ? [observation.resolverId]\n : [],\n );\n const required =\n policy._tag === \"AnyMatch\" ? 1 : policy._tag === \"AllMatch\" ? evidence.length : policy.minimum;\n if (required > 0 && matchedResolverIds.length >= required) {\n return PublicDnsObservation.Verified({ evidence, matchedResolverIds });\n }\n const unavailable = evidence.filter(\n (observation) => observation._tag === \"TimedOut\" || observation._tag === \"Failed\",\n ).length;\n if (unavailable > 0 && matchedResolverIds.length + unavailable >= required) {\n return PublicDnsObservation.Unavailable({ evidence });\n }\n if (\n evidence.some(\n (observation) =>\n observation._tag === \"Answer\" && !answersMatch(requirement, observation.answers),\n )\n ) {\n return PublicDnsObservation.Mismatch({ evidence });\n }\n if (evidence.some((observation) => observation._tag === \"NoData\")) {\n return PublicDnsObservation.Pending({ evidence });\n }\n return PublicDnsObservation.Unavailable({ evidence });\n}\n\nfunction answersMatch(\n requirement: DnsRecord.DnsRecord,\n answers: ReadonlyArray<{ readonly data: string; readonly name: string; readonly type: string }>,\n): boolean {\n const expected = DnsData.parse(requirement._tag, recordValue(requirement));\n return answers.some(\n (answer) =>\n answer.name === requirement.name &&\n answer.type === requirement._tag &&\n DnsData.parse(requirement._tag, answer.data) === expected,\n );\n}\n\nfunction aggregate(evidence: Evidence): Result {\n const requested = [evidence.provider, evidence.publicDns].filter(\n (observation): observation is ProviderObservation | PublicDnsObservation =>\n observation !== null,\n );\n if (requested.length === 0) return Result.NotObserved(evidence);\n if (\n requested.every(\n (observation) => observation._tag === \"Matched\" || observation._tag === \"Verified\",\n )\n ) {\n return Result.Verified(evidence);\n }\n if (requested.some((observation) => observation._tag === \"Unavailable\")) {\n return Result.Unavailable(evidence);\n }\n if (requested.some((observation) => observation._tag === \"Mismatch\")) {\n return Result.Mismatch(evidence);\n }\n return Result.Pending(evidence);\n}\n\nfunction recordValue(requirement: DnsRecord.DnsRecord): string {\n const data = DnsRecord.data(requirement);\n switch (requirement._tag) {\n case \"A\":\n case \"AAAA\":\n return String(data.address);\n case \"CNAME\":\n case \"NS\":\n return String(data.target);\n case \"TXT\":\n return String(data.value);\n case \"MX\":\n return `${data.priority} ${data.exchange}`;\n case \"CAA\":\n return `${data.flags} ${data.tag} ${data.value}`;\n case \"SRV\":\n return `${data.priority} ${data.weight} ${data.port} ${data.target}`;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;ACEA,MAAa,WAAW,OAAO,SAAS;CACtC;CACA;CACA;CACA;CACA;AACF,CAAC;AAGD,MAAa,cAAc,OAAO,SAAS;CAAC;CAAS;CAAqB;CAAQ;AAAS,CAAC;AAG5F,MAAa,SAAS;CACpB,U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