import type { Communication } from "fhir/r4"; import { mayHaveBeenWritten } from "../fetchFailureMessage"; /** * One message send, named so the server can tell a retry from a new message. A send whose answer was lost is sent * again under the same name, and the server returns the message the first attempt wrote rather than a second copy. */ export const SEND_OPERATION_SYSTEM = "https://akashichealthrecords.com/fhir/sid/send-operation"; export interface SendOperation { operationId: string; /** Throws once whatever began the send is gone; checked at the last moment before it leaves, and on its answer. */ admit?: (phase?: "answer") => void; } export const newSendOperation = (): SendOperation => ({ operationId: crypto.randomUUID() }); /** The message carrying its send's name; without one it is sent as before. */ export const namedSend = (communication: T, send?: SendOperation): T => send ? { ...communication, identifier: [ ...(communication.identifier ?? []).filter((each) => each.system !== SEND_OPERATION_SYSTEM), { system: SEND_OPERATION_SYSTEM, value: send.operationId }, ], } : communication; // The server's own words for a send it has not finished or could not confirm: either way it may already be written. // A conflict or unproved replay refuses this request, not the send that first used the name, which may be written. const STILL_OPEN = new Set(["SEND_IN_PROGRESS", "AUTHORIZATION_UNRESOLVED", "SEND_OPERATION_CONFLICT", "SEND_OPERATION_UNPROVED"]); /** A send that may have been written, so the honest answer is "not confirmed", never "not sent". */ export const sendUnconfirmed = (error: unknown): boolean => { if (mayHaveBeenWritten(error)) return true; const code = (error as { body?: { code?: unknown } } | null | undefined)?.body?.code; return typeof code === "string" && STILL_OPEN.has(code); };