import {z} from 'zod' export type GetApiV1ProjectsIdCreditsArgs = {id: string}; export type GetApiV1ProjectsIdCreditsOptions = {baseUrl?: string | undefined, bearer?: string | undefined, fetch?: typeof fetch | undefined}; export const projectCreditDataSummary = z.object({exPost: z.number(), exPostCancelled: z.number(), exAnte: z.number(), exAnteCancelled: z.number(), retired: z.number(), validated: z.number()}); export const creditVintageEventFile = z.object({fileName: z.string(), id: z.string(), size: z.number().optional(), url: z.string(), type: z.enum(["proofOfConcept", "proofOfOwnership", "projectDescription", "validationReport", "monitoringReport", "verificationReport", "otherNote", "noIssuanceStatement", "hostCountryApprovalDocument", "kmlFile", "representationDeed", "projectDesignDescriptionAndMonitoringReport", "vvbAgreement", "validationAndVerificationReport", "methodologyConcept", "nonPerformanceReport", "reversalEventReport", "reviewReport"]).optional()}); export const verificationBodyData = z.object({id: z.string(), directoryUrl: z.string(), fullName: z.string()}); export const creditVintageEventData = z.object({id: z.string(), vintage: z.string(), createdAt: z.string(), amount: z.number(), type: z.literal("issuance"), creditType: z.enum(["carbon", "water", "energy"]), monitoringPeriodStart: z.string().optional(), monitoringPeriodEnd: z.string().optional(), files: z.array(creditVintageEventFile), verificationBody: verificationBodyData.optional()}); export const projectCreditVintageData = z.object({events: z.array(creditVintageEventData), vintage: z.string(), summary: projectCreditDataSummary}); export const apiProject = z.object({id: z.string(), fullName: z.string(), url: z.string(), publicUrl: z.string(), num: z.number()}); export const projectCreditDataResponseDto = z.object({summary: projectCreditDataSummary, vintages: z.array(projectCreditVintageData), project: apiProject}); 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 }; /** * Retrieve credits for a specific project * * GET /v1/projects/{id}/credits */ export const getApiV1ProjectsIdCredits = async (args: GetApiV1ProjectsIdCreditsArgs, options?: GetApiV1ProjectsIdCreditsOptions) => { const {baseUrl = "https://api.carbonregistry.com", fetch: fetchFn = fetch, bearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (bearer !== undefined) headers.set('authorization', `Bearer ${bearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/projects/${encodeURIComponent(String(args.id))}/credits${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(projectCreditDataResponseDto, await res.json()) };