OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
ralph(P2-002): core logger + shared basics
ralph4e1962d68eb2
diff --git a/packages/core/package.json b/packages/core/package.jsonindex 05c127c96..64156c693 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -16,6 +16,8 @@"@elysiajs/openapi": "1.4.15","@trpc/server": "^11.17.0","elysia": "1.4.30",+ "nanoid": "^5.1.6",+ "superjson": "^1.13.3","zod": "catalog:"},"devDependencies": {diff --git a/packages/core/src/logger.test.ts b/packages/core/src/logger.test.tsnew file mode 100644index 000000000..e517b6810--- /dev/null+++ b/packages/core/src/logger.test.ts@@ -0,0 +1,43 @@+import { describe, expect, test } from 'bun:test';+import { type Logger, REQUEST_ID_HEADER, REQUEST_ID_LOG_FIELD } from './logger';++function createFakeLogger(bindings: Record<string, unknown> = {}): Logger {+ // biome-ignore lint/suspicious/noEmptyBlockStatements: the fake only needs a shape, not behavior+ const noop: Logger['info'] = () => {};+ return {+ fatal: noop,+ error: noop,+ warn: noop,+ info: noop,+ debug: noop,+ trace: noop,+ child: (childBindings) =>+ createFakeLogger({ ...bindings, ...childBindings }),+ };+}++describe('Logger structural interface', () => {+ test('a plain object satisfies it with no pino import', () => {+ const logger = createFakeLogger();+ expect(typeof logger.info).toBe('function');+ expect(typeof logger.error).toBe('function');+ expect(typeof logger.child).toBe('function');+ });++ test('child() returns another Logger', () => {+ const logger = createFakeLogger();+ const child = logger.child({ requestId: 'abc123' });+ expect(typeof child.info).toBe('function');+ expect(typeof child.child).toBe('function');+ });+});++describe('requestId constants', () => {+ test('the log field is requestId, not V1s reqId', () => {+ expect(REQUEST_ID_LOG_FIELD).toBe('requestId');+ });++ test('the wire header stays request-id byte-for-byte', () => {+ expect(REQUEST_ID_HEADER).toBe('request-id');+ });+});diff --git a/packages/core/src/logger.ts b/packages/core/src/logger.tsnew file mode 100644index 000000000..96a7e6bdf--- /dev/null+++ b/packages/core/src/logger.ts@@ -0,0 +1,31 @@+// Structural interface only. pino satisfies this shape once it is+// instantiated in apps/api (ADR-007 layout: "pino instantiated later in+// apps/api") — nothing here imports pino, so shared/ and modules/ can depend+// on the shape of a logger without pulling the implementation into core.++export type LogLevel = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace';++export interface LogFn {+ (msg: string, ...args: unknown[]): void;+ (obj: Record<string, unknown>, msg?: string, ...args: unknown[]): void;+}++export interface Logger {+ fatal: LogFn;+ error: LogFn;+ warn: LogFn;+ info: LogFn;+ debug: LogFn;+ trace: LogFn;+ child(bindings: Record<string, unknown>): Logger;+}++// ADR-018 R1: one identifier, one name, one constant — the field is+// `requestId` everywhere (JobMeta.requestId, every log line, Ctx), replacing+// V1's `reqId`. Exported here to kill the four-file literal coupling.+export const REQUEST_ID_LOG_FIELD = 'requestId' as const;++// The wire header stays `request-id` byte-for-byte — it is caller-visible+// and NON_GOALS forbids changing endpoint contracts, even though the log+// field it feeds is renamed.+export const REQUEST_ID_HEADER = 'request-id' as const;diff --git a/packages/core/src/shared/cookie.test.ts b/packages/core/src/shared/cookie.test.tsnew file mode 100644index 000000000..c2001e797--- /dev/null+++ b/packages/core/src/shared/cookie.test.ts@@ -0,0 +1,36 @@+import { describe, expect, test } from 'bun:test';+import type { CookieOptions, ISetCookie } from './cookie';++describe('ISetCookie', () => {+ test('a conforming implementation receives key, value and options', () => {+ const calls: Array<{+ key: string;+ value: string;+ options: CookieOptions;+ }> = [];+ const setCookie: ISetCookie = (key, value, options) => {+ calls.push({ key, value, options });+ };++ setCookie('session', 'token-value', { httpOnly: true, path: '/' });++ expect(calls).toEqual([+ {+ key: 'session',+ value: 'token-value',+ options: { httpOnly: true, path: '/' },+ },+ ]);+ });++ test('deleting a cookie is expressing a zero maxAge, not a separate API', () => {+ const calls: CookieOptions[] = [];+ const setCookie: ISetCookie = (_key, _value, options) => {+ calls.push(options);+ };++ setCookie('session', '', { maxAge: 0 });++ expect(calls[0]?.maxAge).toBe(0);+ });+});diff --git a/packages/core/src/shared/cookie.ts b/packages/core/src/shared/cookie.tsnew file mode 100644index 000000000..f87799e9e--- /dev/null+++ b/packages/core/src/shared/cookie.ts@@ -0,0 +1,19 @@+// Ported from @openpanel/validation's ISetCookie, unchanged shape. This is+// the transport-agnostic type HttpCtx.setCookie exposes to every module, so+// a module depends on this instead of Elysia's cookie type directly.++export interface CookieOptions {+ maxAge?: number;+ domain?: string;+ path?: string;+ sameSite?: 'lax' | 'strict' | 'none';+ secure?: boolean;+ httpOnly?: boolean;+ signed?: boolean;+}++export type ISetCookie = (+ key: string,+ value: string,+ options: CookieOptions+) => void;diff --git a/packages/core/src/shared/errors.test.ts b/packages/core/src/shared/errors.test.tsnew file mode 100644index 000000000..bd3e2e8ec--- /dev/null+++ b/packages/core/src/shared/errors.test.ts@@ -0,0 +1,84 @@+import { describe, expect, test } from 'bun:test';+import { HttpError, LogError, normalizeError } from './errors';++describe('LogError', () => {+ test('carries a payload and keeps its name and prototype chain', () => {+ const error = new LogError('bad state', { projectId: 'p1' });+ expect(error).toBeInstanceOf(LogError);+ expect(error).toBeInstanceOf(Error);+ expect(error.name).toBe('LogError');+ expect(error.payload).toEqual({ projectId: 'p1' });+ });+});++describe('HttpError', () => {+ test('defaults to a 500 status', () => {+ expect(new HttpError('boom').status).toBe(500);+ });++ test('carries an explicit status, fingerprint, extra and cause', () => {+ const cause = new Error('root cause');+ const error = new HttpError('rate limited', {+ status: 429,+ fingerprint: 'rate-limit',+ extra: { key: 'abc' },+ error: cause,+ });+ expect(error).toBeInstanceOf(HttpError);+ expect(error.status).toBe(429);+ expect(error.fingerprint).toBe('rate-limit');+ expect(error.extra).toEqual({ key: 'abc' });+ expect(error.error).toBe(cause);+ });+});++describe('normalizeError', () => {+ test('reads statusCode off an Error', () => {+ const error = Object.assign(new Error('nope'), { statusCode: 404 });+ expect(normalizeError(error)).toEqual({+ status: 404,+ code: undefined,+ message: 'nope',+ errorName: 'Error',+ });+ });++ test('prefers statusCode over status when both are present', () => {+ const error = Object.assign(new Error('nope'), {+ statusCode: 404,+ status: 500,+ });+ expect(normalizeError(error).status).toBe(404);+ });++ test('falls back to status when statusCode is absent', () => {+ const error = Object.assign(new Error('nope'), { status: 403 });+ expect(normalizeError(error).status).toBe(403);+ });++ test('normalizes a plain thrown object', () => {+ expect(+ normalizeError({ statusCode: 400, message: 'bad input', code: 'E_BAD' })+ ).toEqual({+ status: 400,+ code: 'E_BAD',+ message: 'bad input',+ errorName: 'Error',+ });+ });++ test('handles a bare string throw', () => {+ expect(normalizeError('oops')).toEqual({+ status: 500,+ code: undefined,+ message: 'oops',+ errorName: 'Error',+ });+ });++ test('handles null, undefined and other non-object throws', () => {+ expect(normalizeError(null).message).toBe('Internal server error');+ expect(normalizeError(undefined).status).toBe(500);+ expect(normalizeError(42).message).toBe('Internal server error');+ });+});diff --git a/packages/core/src/shared/errors.ts b/packages/core/src/shared/errors.tsnew file mode 100644index 000000000..de4d6ea7b--- /dev/null+++ b/packages/core/src/shared/errors.ts@@ -0,0 +1,104 @@+// Ported from apps/api/src/utils/errors.ts. Transport-agnostic: HTTP, jobs+// and the Kafka consumer all throw and normalize through this, not through+// an rpc/-specific error type (see rpc/errors.ts for the TRPCError family).++const DEFAULT_HTTP_STATUS = 500;++export class LogError extends Error {+ public readonly payload?: Record<string, unknown>;++ constructor(+ message: string,+ payload?: Record<string, unknown>,+ options?: ErrorOptions+ ) {+ super(message, options);+ this.name = 'LogError';+ this.payload = payload;+ Object.setPrototypeOf(this, new.target.prototype);+ }+}++export class HttpError extends Error {+ public readonly status: number;+ public readonly fingerprint?: string;+ public readonly extra?: Record<string, unknown>;+ public readonly error?: unknown;++ constructor(+ message: string,+ options?: {+ status?: number;+ fingerprint?: string;+ extra?: Record<string, unknown>;+ error?: unknown;+ }+ ) {+ super(message);+ this.name = 'HttpError';+ this.status = options?.status ?? DEFAULT_HTTP_STATUS;+ this.fingerprint = options?.fingerprint;+ this.extra = options?.extra;+ this.error = options?.error;+ Object.setPrototypeOf(this, new.target.prototype);+ }+}++export interface NormalizedError {+ status: number;+ code: string | undefined;+ message: string;+ errorName: string;+}++export function normalizeError(error: unknown): NormalizedError {+ if (error instanceof Error) {+ const meta = error as Error & {+ statusCode?: unknown;+ status?: unknown;+ code?: unknown;+ };+ const status =+ typeof meta.statusCode === 'number'+ ? meta.statusCode+ : typeof meta.status === 'number'+ ? meta.status+ : DEFAULT_HTTP_STATUS;+ return {+ status,+ code: typeof meta.code === 'string' ? meta.code : undefined,+ message: error.message || 'Internal server error',+ errorName: error.name || 'Error',+ };+ }++ // Plain object thrown (e.g. `throw { statusCode: 400, message: '...' }`).+ if (typeof error === 'object' && error !== null) {+ const e = error as Record<string, unknown>;+ return {+ status:+ typeof e.statusCode === 'number' ? e.statusCode : DEFAULT_HTTP_STATUS,+ code: typeof e.code === 'string' ? e.code : undefined,+ message:+ typeof e.message === 'string' ? e.message : 'Internal server error',+ errorName: typeof e.name === 'string' ? e.name : 'Error',+ };+ }++ if (typeof error === 'string') {+ return {+ status: DEFAULT_HTTP_STATUS,+ code: undefined,+ message: error,+ errorName: 'Error',+ };+ }++ // null, undefined, number, boolean, symbol, bigint+ return {+ status: DEFAULT_HTTP_STATUS,+ code: undefined,+ message: 'Internal server error',+ errorName: 'Error',+ };+}diff --git a/packages/core/src/shared/id.test.ts b/packages/core/src/shared/id.test.tsnew file mode 100644index 000000000..1d37c3f88--- /dev/null+++ b/packages/core/src/shared/id.test.ts@@ -0,0 +1,27 @@+import { describe, expect, test } from 'bun:test';+import { generateId, shortId } from './id';++describe('shortId', () => {+ test('is 4 characters', () => {+ expect(shortId()).toHaveLength(4);+ });++ test('is not the same twice in a row', () => {+ expect(shortId()).not.toBe(shortId());+ });+});++describe('generateId', () => {+ test('defaults to an 8-character id with no prefix', () => {+ expect(generateId()).toHaveLength(8);+ });++ test('prefixes with an underscore', () => {+ expect(generateId('evt')).toMatch(/^evt_.{8}$/);+ });++ test('honours a custom length, prefixed or not', () => {+ expect(generateId(undefined, 21)).toHaveLength(21);+ expect(generateId('req', 21)).toMatch(/^req_.{21}$/);+ });+});diff --git a/packages/core/src/shared/id.ts b/packages/core/src/shared/id.tsnew file mode 100644index 000000000..d27ed73ff--- /dev/null+++ b/packages/core/src/shared/id.ts@@ -0,0 +1,15 @@+// Ported from @openpanel/common's id.ts, unchanged. nanoid/non-secure is+// deliberate: these are correlation/display ids, not secrets.+import { nanoid } from 'nanoid/non-secure';++const SHORT_ID_LENGTH = 4;+const DEFAULT_ID_LENGTH = 8;++export function shortId(): string {+ return nanoid(SHORT_ID_LENGTH);+}++export function generateId(prefix?: string, length?: number): string {+ const id = nanoid(length ?? DEFAULT_ID_LENGTH);+ return prefix ? `${prefix}_${id}` : id;+}diff --git a/packages/core/src/shared/json.test.ts b/packages/core/src/shared/json.test.tsnew file mode 100644index 000000000..71b401f6e--- /dev/null+++ b/packages/core/src/shared/json.test.ts@@ -0,0 +1,30 @@+import { describe, expect, test } from 'bun:test';+import { getSafeJson, getSuperJson, setSuperJson } from './json';++describe('getSafeJson', () => {+ test('parses valid JSON', () => {+ expect(getSafeJson<{ a: number }>('{"a":1}')).toEqual({ a: 1 });+ });++ test('returns null instead of throwing on invalid JSON', () => {+ expect(getSafeJson('not json')).toBeNull();+ });+});++describe('setSuperJson / getSuperJson', () => {+ test('round-trips a Date through the superjson envelope', () => {+ const original = { at: new Date('2026-01-01T00:00:00.000Z') };+ const serialized = setSuperJson(original);+ const restored = getSuperJson<typeof original>(serialized);+ expect(restored?.at).toBeInstanceOf(Date);+ expect(restored?.at.toISOString()).toBe(original.at.toISOString());+ });++ test('falls back to plain JSON.parse for a non-superjson payload', () => {+ expect(getSuperJson<{ a: number }>('{"a":1}')).toEqual({ a: 1 });+ });++ test('returns null for invalid input', () => {+ expect(getSuperJson('not json')).toBeNull();+ });+});diff --git a/packages/core/src/shared/json.ts b/packages/core/src/shared/json.tsnew file mode 100644index 000000000..14403889e--- /dev/null+++ b/packages/core/src/shared/json.ts@@ -0,0 +1,25 @@+// Ported from @openpanel/json, same semantics: getSafeJson never throws, and+// getSuperJson only hands off to superjson's parser when the payload looks+// like superjson's own `{ json, meta }` envelope — a plain JSON payload+// round-trips through JSON.parse instead.+import superjson from 'superjson';++export function getSafeJson<T>(str: string): T | null {+ try {+ return JSON.parse(str);+ } catch {+ return null;+ }+}++export function getSuperJson<T>(str: string): T | null {+ const json = getSafeJson<T>(str);+ if (typeof json === 'object' && json !== null && 'json' in json) {+ return superjson.parse<T>(str);+ }+ return json;+}++export function setSuperJson(value: unknown): string {+ return superjson.stringify(value);+}diff --git a/packages/core/src/shared/pagination.test.ts b/packages/core/src/shared/pagination.test.tsnew file mode 100644index 000000000..ade7334f5--- /dev/null+++ b/packages/core/src/shared/pagination.test.ts@@ -0,0 +1,60 @@+import { describe, expect, test } from 'bun:test';+import {+ DEFAULT_PAGE_SIZE,+ decodeCursor,+ encodeCursor,+ offsetFromPage,+} from './pagination';++describe('offsetFromPage', () => {+ test('page 0 or undefined is offset 0', () => {+ expect(offsetFromPage(0)).toBe(0);+ expect(offsetFromPage(undefined)).toBe(0);+ });++ test('multiplies by the default page size', () => {+ expect(offsetFromPage(2)).toBe(2 * DEFAULT_PAGE_SIZE);+ });++ test('honours a custom page size', () => {+ expect(offsetFromPage(3, 10)).toBe(30);+ });+});++interface KeysetCursor {+ createdAt: string;+ id: string;+}++function isKeysetCursor(value: unknown): value is KeysetCursor {+ return (+ typeof value === 'object' &&+ value !== null &&+ typeof (value as KeysetCursor).createdAt === 'string' &&+ typeof (value as KeysetCursor).id === 'string'+ );+}++describe('encodeCursor / decodeCursor', () => {+ test('round-trips a cursor', () => {+ const cursor: KeysetCursor = {+ createdAt: '2026-01-01T00:00:00.000Z',+ id: 'evt_1',+ };+ expect(decodeCursor(encodeCursor(cursor), isKeysetCursor)).toEqual(cursor);+ });++ test('is URL-safe', () => {+ const encoded = encodeCursor({ createdAt: 'x'.repeat(50), id: 'evt_1' });+ expect(encoded).not.toMatch(/[+/=]/);+ });++ test('fails closed on a garbled cursor instead of throwing', () => {+ expect(decodeCursor('not-base64-json', isKeysetCursor)).toBeNull();+ });++ test('fails closed on a well-formed but wrong-shaped cursor', () => {+ const encoded = encodeCursor({ other: 'shape' });+ expect(decodeCursor(encoded, isKeysetCursor)).toBeNull();+ });+});diff --git a/packages/core/src/shared/pagination.ts b/packages/core/src/shared/pagination.tsnew file mode 100644index 000000000..3fe53a5a4--- /dev/null+++ b/packages/core/src/shared/pagination.ts@@ -0,0 +1,33 @@+// Two pagination shapes ported from V1's routers, generalized: numeric-page+// offsets (packages/trpc's reference.ts: `cursor ? cursor * 50 : 0`) and+// opaque keyset cursors (packages/trpc's session.ts encodeCursor/decodeCursor,+// generalized from its {createdAt, id} shape to any JSON-serializable cursor).++export const DEFAULT_PAGE_SIZE = 50;++// Page 0 (or no page) is the first page — offset 0.+export function offsetFromPage(+ page: number | undefined,+ pageSize: number = DEFAULT_PAGE_SIZE+): number {+ return page ? page * pageSize : 0;+}++export function encodeCursor<T>(cursor: T): string {+ return Buffer.from(JSON.stringify(cursor), 'utf8').toString('base64url');+}++// A cursor is user-controlled input: a malformed or tampered value must fail+// closed to null, never throw. `isValid` narrows the decoded JSON to T.+export function decodeCursor<T>(+ encoded: string,+ isValid: (value: unknown) => value is T+): T | null {+ try {+ const json = Buffer.from(encoded, 'base64url').toString('utf8');+ const parsed: unknown = JSON.parse(json);+ return isValid(parsed) ? parsed : null;+ } catch {+ return null;+ }+}diff --git a/packages/core/src/shared/try-catch.test.ts b/packages/core/src/shared/try-catch.test.tsnew file mode 100644index 000000000..13a47d54a--- /dev/null+++ b/packages/core/src/shared/try-catch.test.ts@@ -0,0 +1,31 @@+import { describe, expect, test } from 'bun:test';+import { tryCatch } from './try-catch';++describe('tryCatch', () => {+ test('wraps a resolved promise', async () => {+ const result = await tryCatch(Promise.resolve(42));+ expect(result).toEqual({ ok: true, data: 42, error: null });+ });++ test('wraps the result of a resolving function', async () => {+ const result = await tryCatch(async () => 'value');+ expect(result).toEqual({ ok: true, data: 'value', error: null });+ });++ test('captures a rejected promise', async () => {+ const error = new Error('boom');+ const result = await tryCatch(Promise.reject(error));+ expect(result.ok).toBe(false);+ expect(result.data).toBeNull();+ expect(result.error).toBe(error);+ });++ test('captures a throw from inside a function input', async () => {+ const result = await tryCatch(async () => {+ throw new Error('nope');+ });+ expect(result.ok).toBe(false);+ expect(result.error).toBeInstanceOf(Error);+ expect((result.error as Error).message).toBe('nope');+ });+});diff --git a/packages/core/src/shared/try-catch.ts b/packages/core/src/shared/try-catch.tsnew file mode 100644index 000000000..ab057e9d2--- /dev/null+++ b/packages/core/src/shared/try-catch.ts@@ -0,0 +1,17 @@+// Ported from @openpanel/common's try-catch.ts, unchanged.++export type TryCatchResult<T, E = Error> =+ | { ok: true; data: T; error: null }+ | { ok: false; data: null; error: E };++export async function tryCatch<T, E = Error>(+ input: (() => Promise<T>) | Promise<T>+): Promise<TryCatchResult<T, E>> {+ try {+ const promise = typeof input === 'function' ? input() : input;+ const data = await promise;+ return { ok: true, data, error: null };+ } catch (error) {+ return { ok: false, data: null, error: error as E };+ }+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 454f18af3..dff7a0bac 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1210,6 +1210,12 @@ importers:elysia:specifier: 1.4.30version: 1.4.30(@sinclair/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])+ nanoid:+ specifier: ^5.1.6+ version: 5.1.6+ superjson:+ specifier: ^1.13.3+ version: 1.13.3zod:specifier: 'catalog:'version: 4.3.6