Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

JavaScript · 178 lines · 6.5 KiB · at 503e839

// @tsus/v2 runtime. Small on purpose: Option is `T | undefined` and needs no code at all, a Result// is a two-field object, and match is one property lookup and a call. Types: index.d.ts.// --- Option ---export const isSome = (o) => o !== undefined;export const isNone = (o) => o === undefined;export const fromNullable = (v) => (v === null ? undefined : v);export const matchOption = (o, arms) => (o === undefined ? arms.none() : arms.some(o));// --- Result ---export const Ok = (value) => ({ ok: true, value });export const Err = (error) => ({ ok: false, error });export const matchResult = (r, arms) => (r.ok ? arms.ok(r.value) : arms.err(r.error));export const tryCatch = (f) => {  try {    return Ok(f());  } catch (e) {    return Err(e);  }};export const tryAsync = async (f) => {  try {    return Ok(await f());  } catch (e) {    return Err(e);  }};// --- match ---const noArm = (what) => {  throw new TypeError(`TSUS100: no match arm for ${String(what)} (the checker was bypassed)`);};export const match = (value, key, arms) => {  const arm = arms[value[key]];  return arm === undefined ? noArm(value[key]) : arm(value);};export const matchLiteral = (value, arms) => {  const arm = arms[value];  return arm === undefined ? noArm(value) : arm(value);};export const exhaustive = (value) => noArm(value);// --- Sql ---const SQL = Symbol("tsus.sql");const isSql = (v) => typeof v === "object" && v !== null && v[SQL] === true;const makeSql = (text, params) => Object.freeze({ text, params: Object.freeze(params), [SQL]: true });export const sql = (strings, ...values) => {  // A template's strings array is frozen and carries .raw; a hand-built array is refused, so a  // string cannot be smuggled in as the "static" part.  if (!Array.isArray(strings) || !Object.isFrozen(strings) || !Array.isArray(strings.raw)) {    throw new TypeError("sql must be used as a tagged template: sql`...`");  }  let text = strings[0];  const params = [];  for (let i = 0; i < values.length; i += 1) {    const v = values[i];    if (isSql(v)) {      text += v.text;      for (const p of v.params) params.push(p);    } else {      text += "?";      params.push(v);    }    text += strings[i + 1];  }  return makeSql(text, params);};const COMMA = makeSql(", ", []);sql.empty = makeSql("", []);sql.join = (parts, separator = COMMA) => {  let text = "";  const params = [];  parts.forEach((part, i) => {    if (i > 0) {      text += separator.text;      for (const p of separator.params) params.push(p);    }    text += part.text;    for (const p of part.params) params.push(p);  });  return makeSql(text, params);};sql.ident = (name) => {  if (typeof name !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?$/.test(name)) {    throw new TypeError(`sql.ident: not an identifier: ${JSON.stringify(name)}`);  }  return makeSql(`"${name.replace(".", '"."')}"`, []);};const bindable = (v) => (v === undefined ? null : typeof v === "boolean" ? (v ? 1 : 0) : v);const nullsOut = (row) => {  for (const k in row) if (row[k] === null) row[k] = undefined;  return row;};const prepared = (db, q) => {  if (!isSql(q)) throw new TypeError("SafeDb accepts only Sql made by the sql tag");  const s = db.prepare(q.text);  return q.params.length === 0 ? s : s.bind(...q.params.map(bindable));};export const safeDb = (db) => ({  all: async (q) => (await prepared(db, q).all()).results.map(nullsOut),  first: async (q) => {    const row = await prepared(db, q).first();    return row === null ? undefined : nullsOut(row);  },  run: async (q) => ({ changes: (await prepared(db, q).run()).meta?.changes ?? 0 }),  batch: async (qs) => (await db.batch(qs.map((q) => prepared(db, q)))).map((r) => r.results.map(nullsOut)),});// --- Permit ---const PERMITS = new WeakSet();// Used by @tsus/v2/authority only; not declared in index.d.ts.export const __issuePermit = (action, resource) => {  const p = Object.freeze({ action, resource });  PERMITS.add(p);  return p;};export const isGenuinePermit = (v) => typeof v === "object" && v !== null && PERMITS.has(v);// --- Secret ---const SECRETS = new WeakMap();const REDACTED = "[secret]";const inspect = Symbol.for("nodejs.util.inspect.custom");export const secret = (value) => {  const s = Object.freeze({    toString: () => REDACTED,    toJSON: () => REDACTED,    [Symbol.toPrimitive]: () => REDACTED,    [inspect]: () => REDACTED,  });  SECRETS.set(s, value);  return s;};export const reveal = (s) => {  if (!SECRETS.has(s)) throw new TypeError("reveal: not a Secret");  return SECRETS.get(s);};// --- Untrusted ---// An Untrusted is the raw string at runtime; the type is what keeps it out of sinks.export const untrusted = (text) => text;export const untrustedLength = (text) => text.length;export const mapUntrusted = (text, f) => f(text);export const validate = (text, pattern) => {  const m = new RegExp(pattern.source, pattern.flags.replace("g", "").replace("y", "")).exec(text);  return m !== null && m.index === 0 && m[0].length === text.length ? text : undefined;};const HTML_ESCAPES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };const SAFE_HTML = Symbol("tsus.html");const escapeText = (text) => String(text).replace(/[&<>"']/g, (c) => HTML_ESCAPES[c]);const safeHtml = (s) => Object.freeze({ html: s, toString: () => s, [SAFE_HTML]: true });export const escapeHtml = (text) => safeHtml(escapeText(text));const htmlPart = (v) => {  if (v === undefined || v === false) return "";  if (Array.isArray(v)) return v.map(htmlPart).join("");  if (typeof v === "object" && v !== null && v[SAFE_HTML] === true) return v.html;  return escapeText(v);};export const html = (strings, ...values) => {  let out = strings[0];  for (let i = 0; i < values.length; i += 1) out += htmlPart(values[i]) + strings[i + 1];  return safeHtml(out);};// The markers Rebasely's injection screen treats as framing tricks (packages/shared/injection-screen.ts).const ROLE_MARKERS = /<\/?\s*(untrusted|system|assistant|user|human)\b[^>]*>|<\|im_(start|end)\|>|\[\/?INST\]/gi;export const fence = (text, source) => {  const body = String(text).replace(ROLE_MARKERS, (m) => m.replace(/</g, "&lt;").replace(/\[/g, "&#91;"));  const label = String(source).replace(/["<>\n]/g, " ");  return `<untrusted source="${label}">\n${body}\n</untrusted>`;};export const prompt = (strings, ...values) => {  let out = strings[0];  for (let i = 0; i < values.length; i += 1) out += String(values[i]) + strings[i + 1];  return out;};