Files
faunosteo/apps/app/src/catalogue/catalogue.ts
T

219 lines
7.1 KiB
TypeScript

import { z } from 'zod'
import {
SheetFailure,
downloadSheetDrawing,
getSheetVersion,
listOfficialCatalog,
type FaunosteoClient,
} from '@faunosteo/supabase'
import type { PreviewState } from '@faunosteo/core-wasm/types'
import { coreRuntime } from '@/core/runtime'
import { coreFailure, serverFailure, type CatalogueFailure } from './failure'
import { CataloguePreview, type PreviewDrawing } from './preview'
/**
* The catalogue's reads (contract §10, §11.1): the list of published sheets and
* one published or deprecated version loaded into the core. The answers are
* checked against their shape only (a different one is `unavailable`); the
* document and the drawings are the core's to judge.
*/
const LocalizedSchema = z.object({ fr: z.string(), en: z.string() })
const CatalogEntrySchema = z.object({
sheet_id: z.string(),
species_id: z.string(),
slug: z.string(),
name: LocalizedSchema,
version_number: z.number(),
version_id: z.string(),
})
export type CatalogEntry = z.infer<typeof CatalogEntrySchema>
const VersionAnswerSchema = z.object({
sheet_id: z.string(),
version_id: z.string(),
version_number: z.number(),
status: z.enum(['draft', 'published', 'deprecated']),
species_id: z.string(),
document: z.unknown(),
fingerprint: z.string().nullable(),
drawings: z.array(z.object({ asset_id: z.string(), sha256: z.string() })),
})
export type VersionAnswer = z.infer<typeof VersionAnswerSchema>
function parsed<T>(schema: z.ZodType<T>, data: unknown): T {
const result = schema.safeParse(data)
if (!result.success) throw new SheetFailure('unavailable', result.error)
return result.data
}
/** The current published version of every listed sheet (`list_official_catalog`). */
export async function fetchCatalog(client: FaunosteoClient): Promise<CatalogEntry[]> {
return parsed(z.array(CatalogEntrySchema), await listOfficialCatalog(client))
}
export type VersionLoad =
| {
ok: true
version: VersionAnswer
preview: CataloguePreview
state: PreviewState
}
| { ok: false; failure: CatalogueFailure }
/** One drawing as `downloadSheetDrawing` settled it: bytes, or the closed failure. */
export type DrawingFetch =
| { ok: true; drawing: PreviewDrawing }
| { ok: false; assetId: string; sha256: string; failure: CatalogueFailure }
type DrawingEntry = VersionAnswer['drawings'][number]
/** Never rejects: a drawing Storage does not give is missing, the version answered. */
export async function fetchDrawing(
client: FaunosteoClient,
entry: DrawingEntry,
): Promise<DrawingFetch> {
try {
const bytes = await downloadSheetDrawing(client, entry.sha256)
return {
ok: true,
drawing: { assetId: entry.asset_id, sha256: entry.sha256, bytes },
}
} catch (error) {
const failure = serverFailure(error)
return {
ok: false,
assetId: entry.asset_id,
sha256: entry.sha256,
failure: failure === 'denied' ? 'drawing_missing' : failure,
}
}
}
async function downloadDrawings(
client: FaunosteoClient,
version: VersionAnswer,
): Promise<PreviewDrawing[]> {
return Promise.all(
version.drawings.map(async (drawing) => ({
assetId: drawing.asset_id,
sha256: drawing.sha256,
bytes: await downloadSheetDrawing(client, drawing.sha256),
})),
)
}
type VersionRead =
| { ok: true; version: VersionAnswer; drawings: PreviewDrawing[] }
| { ok: false; failure: CatalogueFailure }
const DraftAnswerSchema = VersionAnswerSchema.extend({
revision: z.number().int().nonnegative(),
})
export type DraftAnswer = z.infer<typeof DraftAnswerSchema>
/** The editor's read: any status, the revision of the same answer, settled drawings. */
export type DraftRead =
| {
ok: true
version: DraftAnswer
revision: number
drawings: DrawingFetch[]
}
| { ok: false; failure: CatalogueFailure }
export interface DraftReadOptions {
draft: true
/** Asset ids the caller already holds: not downloaded again. */
have?: ReadonlySet<string>
}
async function readAnswer<T>(
client: FaunosteoClient,
versionId: string,
schema: z.ZodType<T>,
): Promise<{ ok: true; version: T } | { ok: false; failure: CatalogueFailure }> {
try {
return { ok: true, version: parsed(schema, await getSheetVersion(client, versionId)) }
} catch (error) {
return { ok: false, failure: serverFailure(error) }
}
}
async function readDraft(
client: FaunosteoClient,
versionId: string,
have: ReadonlySet<string>,
): Promise<DraftRead> {
const answer = await readAnswer(client, versionId, DraftAnswerSchema)
if (!answer.ok) return answer
const { version } = answer
const wanted = version.drawings.filter((entry) => !have.has(entry.asset_id))
const drawings = await Promise.all(wanted.map((e) => fetchDrawing(client, e)))
return { ok: true, version, revision: version.revision, drawings }
}
/**
* One version as the server gave it. Catalogue mode: published and deprecated only, every
* drawing or none. Draft mode (the editor): any status, `revision` from the same answer,
* each drawing settled alone so one bad drawing never blocks authoring.
*/
export async function readVersion(
client: FaunosteoClient,
versionId: string,
): Promise<VersionRead>
export async function readVersion(
client: FaunosteoClient,
versionId: string,
options: DraftReadOptions,
): Promise<DraftRead>
export async function readVersion(
client: FaunosteoClient,
versionId: string,
options?: DraftReadOptions,
): Promise<VersionRead | DraftRead> {
if (options) return readDraft(client, versionId, options.have ?? new Set())
const answer = await readAnswer(client, versionId, VersionAnswerSchema)
if (!answer.ok) return answer
const { version } = answer
// The catalogue reads published and deprecated versions only (§11.1).
if (version.status === 'draft') return { ok: false, failure: 'denied' }
try {
return { ok: true, version, drawings: await downloadDrawings(client, version) }
} catch (error) {
// The version answered: a drawing it names that Storage does not give is missing.
const failure = serverFailure(error)
return { ok: false, failure: failure === 'denied' ? 'drawing_missing' : failure }
}
}
/**
* One version through `get_sheet_version`, its drawings downloaded under RLS
* and the whole handed to `PreviewSheet`, which checks hashes, fingerprint and
* caps. Unknown and refused ids are the same `denied`. The caller frees the
* preview.
*/
export async function loadVersion(
client: FaunosteoClient,
versionId: string,
): Promise<VersionLoad> {
const read = await readVersion(client, versionId)
if (!read.ok) return read
const { version, drawings } = read
if (!(await coreRuntime().ready())) return { ok: false, failure: 'core_unavailable' }
const preview = new CataloguePreview(
coreRuntime(),
{
status: version.status,
document: JSON.stringify(version.document),
fingerprint: version.fingerprint ?? undefined,
},
drawings,
)
const state = preview.state()
if (state.ok) return { ok: true, version, preview, state: state.value }
preview.free()
return { ok: false, failure: coreFailure(state.kind) }
}