/** * @file core/params.ts * @description Maps the positional arguments of a generated "flat" SDK * function onto the `{ body, headers, path, query }` slots a request needs. * Ported from Hey API's client core (MIT). */ type Slot = "body" | "headers" | "path" | "query"; /** One argument of a generated SDK function and the slot it belongs to. */ export type Field = | { in: Exclude; key: string; map?: string } | { in: Extract; key?: string; map?: string }; /** An object argument whose keys are spread across slots. */ export interface Fields { allowExtra?: Partial>; args?: ReadonlyArray; } export type FieldsConfig = ReadonlyArray; const extraPrefixesMap: Record = { $body_: "body", $headers_: "headers", $path_: "path", $query_: "query", }; const extraPrefixes = Object.entries(extraPrefixesMap); type KeyMap = Map; const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { if (!map) map = new Map(); for (const config of fields) { if ("in" in config) { if (config.key) map.set(config.key, { in: config.in, map: config.map }); } else if (config.args) { buildKeyMap(config.args, map); } } return map; }; interface Params { body: unknown; headers: Record; path: Record; query: Record; } const stripEmptySlots = (params: Params) => { for (const [slot, value] of Object.entries(params)) if (value && typeof value === "object" && !Object.keys(value).length) delete params[slot as Slot]; }; /** Builds request params from a flat SDK function's arguments. */ export const buildClientParams = ( args: ReadonlyArray, fields: FieldsConfig, ) => { const params: Params = { body: {}, headers: {}, path: {}, query: {} }; const map = buildKeyMap(fields); let config: FieldsConfig[number] | undefined; for (const [index, arg] of args.entries()) { if (fields[index]) config = fields[index]; if (!config) continue; if ("in" in config) { if (config.key) { const field = map.get(config.key)!; const name = field.map || config.key; (params[field.in] as Record)[name] = arg; } else { params.body = arg; } continue; } for (const [key, value] of Object.entries(arg ?? {})) { const field = map.get(key); if (field) { (params[field.in] as Record)[field.map || key] = value; continue; } const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix)); if (extra) { const [prefix, slot] = extra; (params[slot] as Record)[key.slice(prefix.length)] = value; continue; } for (const [slot, allowed] of Object.entries(config.allowExtra ?? {})) if (allowed) { (params[slot as Slot] as Record)[key] = value; break; } } } stripEmptySlots(params); return params; };