V1 remains intact on main and in history. This branch replaces it with a new application: node:sqlite storage with migrations, scrypt auth and sessions, content/SRS/attempt/stats services, document extraction and chunking, a provider-neutral AI layer (OpenAI, Anthropic, Gemini, OpenAI-compatible, Ollama), the generation pipeline and the tool-using assistant. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
97 lines
3.5 KiB
TypeScript
97 lines
3.5 KiB
TypeScript
import crypto from 'node:crypto';
|
|
|
|
/** 16-character URL-safe id (96 bits). */
|
|
export function newId(): string {
|
|
return crypto.randomBytes(12).toString('base64url');
|
|
}
|
|
|
|
/** 32-character URL-safe token (192 bits) for share links and sessions. */
|
|
export function newToken(): string {
|
|
return crypto.randomBytes(24).toString('base64url');
|
|
}
|
|
|
|
export function sha256(input: string | Uint8Array): string {
|
|
return crypto.createHash('sha256').update(input).digest('hex');
|
|
}
|
|
|
|
export const now = (): number => Date.now();
|
|
|
|
export function parseJson<T>(text: string | null | undefined, fallback: T): T {
|
|
if (!text) return fallback;
|
|
try {
|
|
return JSON.parse(text) as T;
|
|
} catch {
|
|
return fallback;
|
|
}
|
|
}
|
|
|
|
export const DAY_MS = 86_400_000;
|
|
|
|
/** YYYY-MM-DD for a timestamp in the given IANA timezone. */
|
|
export function dayKey(ts: number, timeZone: string): string {
|
|
const parts = new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' }).formatToParts(new Date(ts));
|
|
const get = (t: string) => parts.find((p) => p.type === t)?.value ?? '';
|
|
return `${get('year')}-${get('month')}-${get('day')}`;
|
|
}
|
|
|
|
/** Offset in ms between UTC and the timezone at the given instant (positive = ahead of UTC). */
|
|
export function tzOffsetMs(ts: number, timeZone: string): number {
|
|
const parts = new Intl.DateTimeFormat('en-US', {
|
|
timeZone,
|
|
hourCycle: 'h23',
|
|
year: 'numeric',
|
|
month: 'numeric',
|
|
day: 'numeric',
|
|
hour: 'numeric',
|
|
minute: 'numeric',
|
|
second: 'numeric',
|
|
}).formatToParts(new Date(ts));
|
|
const get = (t: string) => Number(parts.find((p) => p.type === t)?.value ?? 0);
|
|
const asUtc = Date.UTC(get('year'), get('month') - 1, get('day'), get('hour'), get('minute'), get('second'));
|
|
return asUtc - Math.floor(ts / 1000) * 1000;
|
|
}
|
|
|
|
/** Timestamp of local midnight that starts the day containing `ts` in the timezone. */
|
|
export function startOfDay(ts: number, timeZone: string): number {
|
|
const key = dayKey(ts, timeZone);
|
|
const utcMidnight = Date.parse(`${key}T00:00:00.000Z`);
|
|
// Two passes handle days where the offset at midnight differs from the offset at `ts` (DST).
|
|
let guess = utcMidnight - tzOffsetMs(ts, timeZone);
|
|
guess = utcMidnight - tzOffsetMs(guess, timeZone);
|
|
return guess;
|
|
}
|
|
|
|
export function addDaysToKey(key: string, days: number): string {
|
|
const d = new Date(`${key}T00:00:00.000Z`);
|
|
d.setUTCDate(d.getUTCDate() + days);
|
|
return d.toISOString().slice(0, 10);
|
|
}
|
|
|
|
export function clamp(n: number, min: number, max: number): number {
|
|
return Math.min(max, Math.max(min, n));
|
|
}
|
|
|
|
export function slugify(input: string): string {
|
|
return (
|
|
input
|
|
.toLowerCase()
|
|
.normalize('NFKD')
|
|
.replace(/[^\w\s-]/g, '')
|
|
.trim()
|
|
.replace(/[\s_]+/g, '-')
|
|
.slice(0, 60) || 'export'
|
|
);
|
|
}
|
|
|
|
/** Builds an FTS5 MATCH expression from free text: quoted terms OR-ed together, prefix match on the last term. */
|
|
export function ftsQuery(input: string, mode: 'or' | 'and' = 'or'): string | null {
|
|
const terms = (input.toLowerCase().match(/[\p{L}\p{N}]{2,}/gu) ?? []).filter((t) => !STOP_WORDS.has(t)).slice(0, 24);
|
|
if (terms.length === 0) return null;
|
|
return [...new Set(terms)].map((t) => `"${t}"`).join(mode === 'or' ? ' OR ' : ' AND ');
|
|
}
|
|
|
|
const STOP_WORDS = new Set(
|
|
'a an and are as at be but by for from has have how if in into is it its of on or that the their them then there these this to was what when where which who why will with about your you can do does i me my we our should would could not no nor so than too very'.split(
|
|
' ',
|
|
),
|
|
);
|