Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kentcdodds/cloudflare

Cloudflare helpers: API v4, static site publishing to Pages, analytics, WAF rules, logs, and docs.

FollowFork

Files

custom-domain-runtime.ts

58 lines · 2.4 KB · TypeScript
import { kody } from 'kody:runtime'
import cloudflareApiV4 from './api-v4.ts'
import type { CloudflareAuthOptions } from './auth.ts'
import type { CloudflareCaller, CustomDomainDeps, KodyCustomDomainClient } from './custom-domain-core.ts'

const ORG_CAPABILITIES = [
	'packageList',
	'packageAppCustomHostnameList',
	'packageAppCustomHostnameAdd',
	'packageAppCustomHostnameSync',
	'packageAppCustomHostnameDelete',
] as const

function wrapKody(): KodyCustomDomainClient {
	const runtime = kody as unknown as Record<string, (input: unknown) => Promise<unknown>>
	const client: Record<string, (input: unknown) => Promise<unknown>> = {}
	for (const name of ORG_CAPABILITIES) {
		client[name] = async (input: unknown) => {
			if (typeof runtime[name] !== 'function') {
				throw new Error(`kody.${name} is not available in this runtime. Call this export from a Kody execute run as a signed-in org admin.`)
			}
			try {
				return await runtime[name](input)
			} catch (error) {
				const message = error instanceof Error ? error.message : String(error)
				const hint = name.startsWith('packageAppCustomHostname')
					? ' (Custom hostname capabilities need a signed-in person with org:write on a paid plan; call this export from execute, not from a job, webhook, or app request.)'
					: ''
				throw new Error(`kody.${name} failed: ${message}${hint}`)
			}
		}
	}
	return client as unknown as KodyCustomDomainClient
}

/** Live deps: the Kody runtime plus `./api-v4` with the chosen token alias. */
export function liveDeps(auth: CloudflareAuthOptions): CustomDomainDeps {
	const cloudflare: CloudflareCaller = (request) =>
		cloudflareApiV4({
			...(auth.account !== undefined ? { account: auth.account } : {}),
			...(auth.apiTokenSecret !== undefined ? { apiTokenSecret: auth.apiTokenSecret } : {}),
			method: request.method ?? 'GET',
			path: request.path,
			query: request.query,
			body: request.body,
		})
	return { kody: wrapKody(), cloudflare }
}

/** Pull auth keys from raw input without validating the rest (core validates). */
export function authFrom(raw: unknown): CloudflareAuthOptions {
	if (!raw || typeof raw !== 'object') return {}
	const record = raw as Record<string, unknown>
	const out: CloudflareAuthOptions = {}
	if (typeof record.account === 'string') out.account = record.account as CloudflareAuthOptions['account']
	if (typeof record.apiTokenSecret === 'string') out.apiTokenSecret = record.apiTokenSecret
	return out
}