import {z} from 'zod' export type RelationshipType = 'proximity'; export type YearMonth = string; export type IntervalType = 'month'; export type ResourceId = string; export type ConceptIdsObject = {ids: Array}; export type ConceptTypeEnum = 'entity' | 'entity/person' | 'entity/organisation' | 'entity/location' | 'entity/substance' | 'entity/disease' | 'entity/product' | 'entity/regulation' | 'topic'; export type PostAffinityQuery = {relationship: {type: RelationshipType, date: {start: YearMonth, end: YearMonth}, interval: IntervalType, 'limit-per-interval'?: number | undefined}, 'source-concept': {id: ResourceId}, 'target-concepts'?: (ConceptIdsObject | {types: Array, exclude?: ConceptIdsObject | undefined} | {types?: Array | undefined, exclude: ConceptIdsObject}) | undefined}; export type CreateApiAffinityArgs = {body: PostAffinityQuery}; export type CreateApiAffinityOptions = {baseUrl?: string | undefined, OAuth2?: string | undefined, fetch?: typeof fetch | undefined}; export const resourceId = z.string(); export const conceptTypeEnum = z.enum(["entity", "entity/person", "entity/organisation", "entity/location", "entity/substance", "entity/disease", "entity/product", "entity/regulation", "topic"]); export const concept = z.object({id: resourceId, type: conceptTypeEnum, name: z.string()}); export const yearMonth = z.string(); export const relationshipType = z.literal("proximity"); export const postAffinityResponse = z.object({"source-concept": concept, results: z.array(z.object({relationship: z.object({date: yearMonth, type: relationshipType, "proximity-score": z.number().gte(0).lte(1), "sentiment-score": z.number().gte(-1).lte(1)}), "target-concept": concept}))}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Explore concept connections (powered by the Signal AI Knowledge Graph) * * POST /affinity */ export const createApiAffinity = async (args: CreateApiAffinityArgs, options?: CreateApiAffinityOptions) => { const {baseUrl = "https://api.signal-ai.com", fetch: fetchFn = fetch, OAuth2} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (OAuth2 !== undefined) headers.set('authorization', `Bearer ${OAuth2}`) const url = `${baseUrl.replace(/\/+$/, '')}/affinity${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(postAffinityResponse, await res.json()) };