Cotton code
256 lines · 10.1 KB · TypeScriptRaw
/** * A record's values checked against its table, with the refusal words of the * kit's `refusal.records.*` lines (crates/cotton-core/src/records/mod.rs * `check_value_as`, `validate_create_as`, `validate_patch_as`, * `without_unchanged_readonly`; records/refusal.rs for the quoting). */import { fail, type Data } from "../../context.ts";import type { Column, Table } from "./table.ts";/** A value as a refusal names it (`records::describe`). */export function describe(value: unknown): string {  if (value === null || value === undefined) return "null";  if (typeof value === "boolean") return String(value);  if (typeof value === "number") return String(value);  if (typeof value === "string") return JSON.stringify(value);  if (Array.isArray(value)) return "a list";  return "an object";}/** A key as a refusal quotes it (Rust `{:?}`). */export function quoted(text: string): string {  return JSON.stringify(text);}const WANTED: Record<string, string> = {  place: "place text, {place: stable id}, or {kept: words, near: dataset id}",  text: "text",  web_address: "a web address starting http:// or https://",  date: "a date written YYYY-MM-DD",  time: "a time written HH:MM",  number: "a number",  bytes: "a non-negative whole number of bytes",  minor_units: "a whole number of minor units",  choice_list: "a list of its choices",  one_choice: "one of its choices",  link_id: "the id of the record it links to",  media_key: "a media key",  bool: "true or false",};function wrongType(column: string, wanted: string, value: unknown): never {  fail(`${quoted(column)} takes ${wanted}; ${describe(value)} is not one`);}export function isDate(text: string): boolean {  if (!/^\d{4}-\d{2}-\d{2}$/.test(text)) return false;  const d = new Date(`${text}T00:00:00Z`);  return !Number.isNaN(d.getTime()) && d.toISOString().slice(0, 10) === text;}export function isTime(text: string): boolean {  const m = /^(\d{2}):(\d{2})$/.exec(text);  return !!m && Number(m[1]) <= 23 && Number(m[2]) <= 59;}/** An RFC 3339 instant (chrono `parse_from_rfc3339`). */export function isInstant(text: string): boolean {  const m = /^(\d{4}-\d{2}-\d{2})[Tt ](\d{2}):(\d{2}):(\d{2})(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$/.exec(text);  if (!m || !isDate(m[1]!)) return false;  return Number(m[2]) <= 23 && Number(m[3]) <= 59 && Number(m[4]) <= 60;}function isWebAddress(text: string): boolean {  if (text.trim() !== text) return false;  try {    const url = new URL(text);    return (url.protocol === "http:" || url.protocol === "https:") && url.hostname !== "";  } catch {    return false;  }}/** A date column also takes an instant when it is said against now or as a calendar time (`check_value_in`). */function takesInstants(c: Column): boolean {  return c.format === "ago" || c.format === "calendar-datetime" || c.format === "countdown";}/** Does `value` (never null) fit `c`? A refusal in the kit's words when it does not. */export function checkValue(t: Table, c: Column, value: unknown): void {  const key = c.key;  // A several-valued column of a type that is not a choice holds a list of that type's values.  if (c.multiple === true && c.type !== "choice") {    if (!Array.isArray(value)) wrongType(key, `a list of ${WANTED[wantedOf(c.type)] ?? c.type}`, value);    for (const item of value) checkOne(t, { ...c, multiple: false }, item);    return;  }  checkOne(t, c, value);}function wantedOf(type: string): string {  switch (type) {    case "url":      return "web_address";    case "amount":      return "minor_units";    case "link":      return "link_id";    case "photo":    case "file":      return "media_key";    case "longtext":    case "account_number":      return "text";    default:      return type;  }}function checkOne(_t: Table, c: Column, value: unknown): void {  const key = c.key;  const str = typeof value === "string" ? value : null;  switch (c.type) {    case "place": {      const o = value && typeof value === "object" && !Array.isArray(value) ? (value as Data) : null;      const ok = str !== null || (o !== null && ((Object.keys(o).length === 1 && typeof o.place === "string" && o.place !== "") || typeof o.kept === "string"));      if (!ok) wrongType(key, WANTED.place!, value);      return;    }    case "text":    case "longtext":    case "account_number":      if (str === null) wrongType(key, WANTED.text!, value);      return;    case "url":      if (str === null || !isWebAddress(str)) wrongType(key, WANTED.web_address!, value);      return;    case "date":      if (str !== null && (isDate(str) || (takesInstants(c) && isInstant(str)))) return;      wrongType(key, WANTED.date!, value);      return;    case "time":      if (str === null || !isTime(str)) wrongType(key, WANTED.time!, value);      return;    case "number":      if (typeof value !== "number") wrongType(key, WANTED.number!, value);      return;    case "bytes":      if (typeof value !== "number" || !Number.isInteger(value) || value < 0) wrongType(key, WANTED.bytes!, value);      return;    case "amount":      if (typeof value === "number" && Number.isSafeInteger(value)) return;      if (typeof value === "number") fail(`${quoted(key)} is an amount in minor units and takes a whole number; ${describe(value)} is not one, and an amount is never rounded`);      wrongType(key, WANTED.minor_units!, value);      return;    case "choice": {      const choices = Array.isArray(c.choices) ? c.choices : [];      if (c.multiple === true) {        if (!Array.isArray(value)) wrongType(key, WANTED.choice_list!, value);        for (const item of value) {          if (typeof item !== "string") wrongType(key, WANTED.choice_list!, value);          if (!choices.includes(item)) fail(`${quoted(key)} takes one of ${choices.join(", ")}; ${quoted(item)} is not one`);        }        return;      }      if (!Array.isArray(c.choices) && c.choices_from !== undefined && c.choices_from !== null) {        if (str === null) wrongType(key, WANTED.one_choice!, value);        return;      }      if (str === null) wrongType(key, WANTED.one_choice!, value);      if (!choices.includes(str)) fail(`${quoted(key)} takes one of ${choices.join(", ")}; ${quoted(str)} is not one`);      return;    }    case "link":      if (str === null || !str.trim()) wrongType(key, WANTED.link_id!, value);      return;    case "photo":    case "file":      if (str === null || !str.trim()) wrongType(key, WANTED.media_key!, value);      return;    case "bool":      if (typeof value !== "boolean") wrongType(key, WANTED.bool!, value);      return;    default:      fail(`${quoted(key)} is a ${c.type} column, a type this server does not write`);  }}function columnFor(t: Table, key: string): Column {  return t.column(key) ?? fail(`${t.plural} have no column ${quoted(key)}`);}/** * The writer an object's own verb names when it writes the columns it works * out itself (Cotton Story's scene figures, worked out by story_scene_write): * never a token's id, so no caller can say it. */export const PRODUCED_BY_THE_OBJECT = "\u0000object";/** A computed column is the engine's to work out; a readonly one is its producer's to write (`authored_column`). */function authored(t: Table, c: Column, tokenId: string): void {  if (c.computed !== undefined && c.computed !== null) fail(`${quoted(c.key)} is worked out from other records, so it cannot be written`);  if (c.readonly === true && tokenId !== PRODUCED_BY_THE_OBJECT && !(tokenId !== "" && t.producerToken === tokenId)) fail(`${quoted(c.key)} is read only`);}function asObject(value: unknown): Data {  if (!value || typeof value !== "object" || Array.isArray(value)) fail("the data must be an object of column keys and values");  return value as Data;}/** A new record's data: every key a column, every value its type; nulls dropped, defaults filled, required ones present. */export function validateCreate(t: Table, data: unknown, tokenId: string): Data {  const given = asObject(data);  const clean: Data = {};  for (const [key, value] of Object.entries(given)) {    const c = columnFor(t, key);    if (value === null) continue;    authored(t, c, tokenId);    checkValue(t, c, value);    clean[key] = value;  }  for (const c of t.columns) if (c.default !== undefined && c.default !== null && !(c.key in clean)) clean[c.key] = c.default;  for (const c of t.columns) if (c.required === true && !(c.key in clean)) fail(`${quoted(c.key)} is required`);  return clean;}/** A patch: every key a column, every value its type or null (never on a required column); empty is nothing to change. */export function validatePatch(t: Table, patch: unknown, tokenId: string): Data {  const given = asObject(patch);  if (!Object.keys(given).length) fail("the patch changes nothing");  for (const [key, value] of Object.entries(given)) {    const c = columnFor(t, key);    authored(t, c, tokenId);    if (value === null) {      if (c.required === true) fail(`${quoted(c.key)} is required`);      continue;    }    checkValue(t, c, value);  }  return { ...given };}/** A patch without the readonly columns it merely repeats (`without_unchanged_readonly`): the reporters echo them. */export function withoutUnchangedReadonly(t: Table, patch: unknown, stored: Data): unknown {  if (!patch || typeof patch !== "object" || Array.isArray(patch)) return patch;  const kept: Data = {};  for (const [key, value] of Object.entries(patch as Data)) {    const c = t.column(key);    const repeats = !!c && c.readonly === true && (c.computed === undefined || c.computed === null) && sameJson(stored[key] ?? null, value);    if (!repeats) kept[key] = value;  }  return kept;}/** Strict JSON equality, keys in any order. */export function sameJson(a: unknown, b: unknown): boolean {  if (a === b) return true;  if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false;  if (Array.isArray(a) !== Array.isArray(b)) return false;  if (Array.isArray(a)) {    const bb = b as unknown[];    return a.length === bb.length && a.every((v, i) => sameJson(v, bb[i]));  }  const ak = Object.keys(a as Data);  const bo = b as Data;  return ak.length === Object.keys(bo).length && ak.every((k) => k in bo && sameJson((a as Data)[k], bo[k]));}