@classytic/repo-core

中文文档
0.38.0发布于 2026/11/04MITTypeScriptES Module零依赖近 30 天下载 3555

Driver-agnostic repository primitives: hooks, Filter IR, operations, pagination, cache contract. Foundation for mongokit, sqlitekit, pgkit, and prismakit. Lean by design — no plugins ship here; each kit owns its own.

原始使用文档
文档目录12 节
  1. Design principles
  2. Subpaths
  3. Example: a kit's repository extends RepositoryBase
  4. Example: URL → ParsedQuery → any kit
  5. Plugin-friendly event names
  6. Capabilities — feature detection, not runtime surprises
  7. Config-driven validation + events (0.6.0)
  8. Change feed for realtime replay
  9. Typed result extras
  10. Status
  11. License
  12. Trademark

@classytic/repo-core

Sponsor

Driver-agnostic repository primitives. Hooks, Filter IR, operations registry, pagination, URL query parsing, cache contract — the shared foundation for @classytic/mongokit, @classytic/sqlitekit, and future @classytic/pgkit / @classytic/prismakit.

Repo-core is infrastructure for kit authors. End-users install a kit (mongokit / sqlitekit) and import their full API from that one namespace. Repo-core is what each kit's runtime is built on — you typically won't import it directly in application code.

Design principles

  • ESM only. .mjs + .d.mts output. Node 22+.
  • No root barrel. Every public surface is its own subpath in exports. Import directly from where the symbol lives; unused modules never enter your dep graph.
  • Zero runtime dependencies. No driver imports anywhere in src/.
  • Tree-shakeable by construction. unbundle: true in tsdown — 1:1 src→dist, no shared chunks.
  • No plugins ship here. Each kit owns its own plugin implementations so they can use driver-native features (mongoose's built-in timestamps, SQLite triggers, Postgres now(), Prisma @default). Repo-core provides the primitives kits compose: CacheAdapter, stableStringify, buildTenantScope, HOOK_PRIORITY, the hook engine, Filter IR.

Subpaths

// Hook engine + priority constants + canonical event names. HOOK_EVENTS turns
// raw strings into compile-checked constants so typos fail at build time.
import { HOOK_EVENTS, HOOK_PRIORITY, HookEngine } from '@classytic/repo-core/hooks';

// Abstract repository base + MinimalRepo / StandardRepo contracts + plugin types.
import { RepositoryBase, type MinimalRepo, type Plugin } from '@classytic/repo-core/repository';

// Driver-agnostic filter AST — combinators (eq/and/or/in/like/between/...) + walk/match + scope helpers.
import { and, eq, gte, in_, like, buildTenantScope, matchFilter } from '@classytic/repo-core/filter';

// URL → ParsedQuery grammar. Backend frameworks (Express/Arc/Fastify) parse req.query here.
import { parseUrl } from '@classytic/repo-core/query-parser';

// Pagination primitives — cursor codec, keyset helpers, offset math, the canonical
// result types (`OffsetPaginationResult`, `KeysetPaginationResult`,
// `AggregatePaginationResult`, `PaginationResult`) and the wire helper
// `toCanonicalList()`. Single source of truth — primitives' duplicate dropped,
// mongokit/sqlitekit re-export from here.
import { encodeCursor, decodeCursor, validateKeysetSort, toCanonicalList } from '@classytic/repo-core/pagination';
import type { OffsetPaginationResult, KeysetPaginationResult, AggregatePaginationResult, PaginationResult } from '@classytic/repo-core/pagination';

// Tenant config — the canonical `TenantConfig`, `TenantStrategy`, `TenantFieldType`,
// `resolveTenantConfig`, `DEFAULT_TENANT_CONFIG`, `ResolvedTenantConfig`. Kits'
// `MultiTenantOptions extends Pick<TenantConfig, ...>`.
import { resolveTenantConfig, DEFAULT_TENANT_CONFIG } from '@classytic/repo-core/tenant';
import type { TenantConfig, ResolvedTenantConfig } from '@classytic/repo-core/tenant';

// Cache plumbing — the CacheAdapter interface every kit's cachePlugin writes against.
import { type CacheAdapter, stableStringify, createMemoryCacheAdapter } from '@classytic/repo-core/cache';

// Error contracts — `HttpError` throwable + `ErrorContract` wire shape +
// `ErrorDetail` + `ErrorCode` + `ERROR_CODES` + `toErrorContract()` +
// `statusToErrorCode()`. Single source of truth — primitives' errors module dropped,
// mongokit's local `HttpError` dropped, `ArcError implements HttpError`.
import { toErrorContract, statusToErrorCode, ERROR_CODES, createError, conservativeMongoIsDuplicateKey } from '@classytic/repo-core/errors';
import type { HttpError, ErrorContract, ErrorDetail, ErrorCode } from '@classytic/repo-core/errors';

// Error kinds: one coarse class per wire code (validation, unauthorized, forbidden,
// not_found, conflict, precondition_failed, rate_limited, unavailable, internal).
// `errorKind(code, status?)` reads the table first, then falls back to the status.
import { errorKind, ERROR_KIND_BY_CODE, type ErrorKind } from '@classytic/repo-core/errors';

// Change feed: the ChangeLogStore contract a sync engine or a replaying SSE stream
// reads, plus the in-memory reference store. See "Change feed for realtime replay".
import { MemoryChangeLogStore, CursorExpiredError, isCursorExpiredError } from '@classytic/repo-core/sync';
import type { ChangeLogStore, ChangeEntry, ChangesSinceOptions, ChangesPage } from '@classytic/repo-core/sync';

// Schema generator interface — kits ship `SchemaGenerator<TModel>` + the
// compile-time conformance assertion; arc adapters are typed against it.
import type { SchemaGenerator, SchemaGeneratorContext } from '@classytic/repo-core/schema';
import { isSchemaGenerator } from '@classytic/repo-core/schema';

// Operation registry (for arc-level policy dispatch + doc generation).
import { CORE_OP_REGISTRY, describe } from '@classytic/repo-core/operations';

// Repository hook context type (for plugin authors).
import type { RepositoryContext } from '@classytic/repo-core/context';

// Capabilities + resilience (0.6.0) — runtime feature detection, the unified
// retry/abort primitives, and the change-feed contract types.
import { withRetry, throwIfAborted } from '@classytic/repo-core/repository';
import type { RepoCapabilities, RetryPolicy, ChangeEvent, WatchOptions } from '@classytic/repo-core/repository';

// Domain events (0.6.0) — pass `events: { transport }` at construction and every
// mutating op publishes `<resource>.<verb>` through any arc-compatible transport.
import type { RepositoryEventPublisher, DomainEvent } from '@classytic/repo-core/events';

// Standard Schema validation (0.6.0) — `schema` / `updateSchema` construction
// options accept any Zod / Valibot / ArkType / Effect schema.
import { validateStandardSchema, type StandardSchemaV1 } from '@classytic/repo-core/schema';

There is no . / root entry. Import from the exact subpath — that's the contract that keeps tree-shaking honest.

Example: a kit's repository extends RepositoryBase

import { RepositoryBase } from '@classytic/repo-core/repository';
import { compileFilter } from './my-kit-compiler.js';

export class MyKitRepository<T> extends RepositoryBase {
  // Kit-specific CRUD methods. Each routes through `_buildContext` → plugins
  // → native driver call → `_emitAfter` so every plugin (timestamp, cache,
  // multi-tenant, audit) composes identically across kits.
  async getAll(params: {...}) {
    const context = await this._buildContext('getAll', params);
    const cached = this._cachedValue(context);
    if (cached) return cached;
    const where = compileFilter(context.filters);
    const result = await this.driver.query(where);
    await this._emitAfter('getAll', context, result);
    return result;
  }
}

Example: URL → ParsedQuery → any kit

The URL grammar is identical across every kit. Frontends emit one URL; swapping the backend DB doesn't change a single query string.

import { parseUrl } from '@classytic/repo-core/query-parser';

app.get('/users', async (req, res) => {
  const parsed = parseUrl(req.query, {
    allowedFilterFields: ['email', 'role', 'active', 'createdAt'],
    fieldTypes: { active: 'boolean', createdAt: 'date' },
    maxLimit: 200,
  });
  // Works identically against any kit's repository:
  //   const page = await sqliteUserRepo.getAll(parsed);
  //   const page = await mongoUserRepo.getAll(parsed);
  res.json(await userRepo.getAll(parsed));
});

URL grammar:

URLFilter IR produced
?status=activeeq('status', 'active')
?age[gte]=18&age[lt]=65and(gte('age', 18), lt('age', 65))
?role[in]=admin,editorin_('role', ['admin', 'editor'])
?name[contains]=johnlike('name', '%john%')
?price[between]=10,100and(gte(...), lte(...))
?deletedAt[exists]=falseisNull('deletedAt')
?sort=-createdAt,name{ createdAt: -1, name: 1 } (on .sort)
?select=name,email,-password{ name: 1, email: 1, password: 0 }
?page=2&limit=50pagination fields on ParsedQuery
?after=eyJ2Ij...opaque keyset cursor

Plugin-friendly event names

import { HOOK_EVENTS, HOOK_PRIORITY } from '@classytic/repo-core/hooks';

// Cross-kit plugin — works identically on mongokit, sqlitekit, pgkit, prismakit.
export function stampOrgId(orgId: string): Plugin {
  return {
    name: 'stamp-org-id',
    apply(repo) {
      repo.on(HOOK_EVENTS.BEFORE_CREATE, (ctx) => {
        if (!ctx.data?.organizationId) ctx.data = { ...ctx.data, organizationId: orgId };
      }, { priority: HOOK_PRIORITY.POLICY });
    },
  };
}

Typos like 'before:craete' become compile errors. Subscribing to an event a given kit doesn't emit is a silent no-op (that's how the hook engine works), so a plugin can safely wire listeners for the full standard set.

Capabilities — feature detection, not runtime surprises

Every kit declares readonly capabilities: RepoCapabilities (required on StandardRepo since 0.6.0). Kit-portable hosts branch once at boot:

if (!repo.capabilities.arrayOperators) {
  // SQL kit without JSON array rewrites — model tags as a join table
}
if (repo.capabilities.aggregateOps?.percentile) {
  dashboard.enableLatencyPercentiles();
}

The conformance suite's ConformanceFeatures is an alias of the same type — what a kit declares at runtime is exactly what the cross-kit suite verifies.

Config-driven validation + events (0.6.0)

RepositoryBaseOptions follows media-kit's config-driven activation: pass the slot and the feature lights up; omit it and the wiring is inert.

import { z } from 'zod';

const repo = createRepository(UserModel, {
  // Any Standard Schema validator — Zod, Valibot, ArkType, Effect.
  schema: z.object({ name: z.string().min(1), email: z.string().email() }),
  updateSchema: z.object({ name: z.string().min(1) }).partial(),

  // Any arc / primitives-compatible EventTransport. Every mutating op then
  // publishes `user.created` / `user.updated` / `user.deleted` / ...
  events: { transport: redisTransport, source: 'commerce' },
});

Validation runs at HOOK_PRIORITY.VALIDATION (150) — after policy plugins (tenant-stamped fields are present), before cache. Event publishing never fails the operation; transport failures route to the error:events hook.

Warning — arc hosts: these are the same event names @classytic/arc's eventStrategy: 'auto' emits. Wiring BOTH the repo-level bridge and arc auto events for one resource double-publishes silently (arc's dual-publish dev-warn cannot see the repo layer). Pick one layer per resource.

Change feed for realtime replay

@classytic/repo-core/sync exports the ChangeLogStore contract: an append-only, commit-ordered feed of document changes. A sync engine pulls it; a server-sent-events stream can replay it, so a client that reconnects with Last-Event-ID (an entry's cursor) gets every change after that cursor, as each document's latest state if the feed was compacted. MemoryChangeLogStore is the reference store; mongokit's createChangeLogStore is the durable one. Prove a store with runChangeLogStoreConformance from @classytic/repo-core/testing.

Every store honors four rules, and a fifth if it prunes:

  1. Cursors are opaque, totally ordered per store, in commit order. Never checkpoint past an entry that commits later.
  2. append(entry, { session }) joins the caller's transaction, so the feed entry commits with the business write.
  3. Deletes are tombstones (op: 'delete', no doc), never gaps.
  4. since(cursor) is exclusive of cursor ('' means from the beginning) and returns entries in cursor order; page while hasMore, echoing the returned cursor.
  5. A store that implements the optional prune(before) keeps the latest state per document and returns the new horizon; a cursor older than it gets CursorExpiredError.
import { isCursorExpiredError, type ChangeLogStore, type ChangesSinceOptions } from '@classytic/repo-core/sync';

// MemoryChangeLogStore and mongokit only: 16-digit cursors, or '' for "from the beginning".
const CURSOR = /^(\d{16})?$/;

type Read = Pick<ChangesSinceOptions, 'tenantId' | 'scopes' | 'sharedScopes'>;

// One pass: every entry after `from`, in cursor order. Call it on connect with Last-Event-ID,
// then on every wake-up (a timer, or a "feed changed" ping) with the cursor it returned.
// The feed is the only source of events, so the hand-off from replay to live has no gap.
async function pump(store: ChangeLogStore, from: string, read: Read, send: (e: unknown) => void) {
  // A malformed cursor, or one ahead of the head (a restored DB, a restarted memory store, a
  // forged id), resyncs: echoing it back would replay nothing until the sequence caught up.
  if (!CURSOR.test(from) || from > (await store.latestCursor())) return { resync: true } as const;
  let cursor = from;
  try {
    for (;;) {
      const page = await store.since(cursor, { ...read, limit: 500 });
      for (const entry of page.changes) send(entry); // SSE `id:` = entry.cursor
      cursor = page.cursor;
      if (!page.hasMore) return { cursor } as const;
    }
  } catch (err) {
    if (isCursorExpiredError(err)) return { resync: true } as const;
    throw err; // a failure, not a resync: see "Errors" below
  }
}
  • Who may read what. Build read on the server, never from the request. A tenant reader takes tenantId from the authenticated scope and fails closed when there is none: since with tenantId: undefined returns every tenant's entries in both stores, so a user with no organization selected would stream everyone's data. scopes and sharedScopes widen the read (sharedScopes adds other tenants' entries in those scopes), so they come from server config or a server-side allowlist. A platform-view reader (no tenantId) is a separate, explicitly gated branch, such as an elevated or platform scope.
  • Resync. Take the head with latestCursor(read) before the client reloads its snapshot and send it as the new id:; continuing from it may repeat entries the snapshot already has, which is safe (next point). Capturing the head after the snapshot loses the entries committed in between. CursorExpiredError (checked with isCursorExpiredError, which matches by name, so it survives two repo-core copies in one graph) and a cursor that fails the check above are the resync signals.
  • At-least-once. Across reconnects and resyncs a client can see an entry twice. Apply entries by (scope, docId, version) and ignore one whose version is not newer than the one held.
  • Live events. If the hub pushes live events from somewhere other than the feed (arc events, a pub/sub message), they carry no feed cursor and the SSE id: cannot stay consistent. Either poll since as the live source (above), or subscribe to live feed entries first, buffer them, replay, then drop buffered entries whose cursor is <= the last replayed one.
  • Errors. Any other since error is a failure: log the cause on the server, send a fixed { code, message } (for example internal_error with a static message) and close. Never echo the error: CursorExpiredError and mongokit's cursor errors embed the client's raw cursor, and driver errors can name collections, indexes and query shapes.
  • Fixed-width cursors. MemoryChangeLogStore and mongokit mint 16-digit zero-padded sequence numbers, so CURSOR and plain string comparison work for them. Other stores may not: treat cursors as opaque unless you know the store. Compare against the unfiltered latestCursor(): a filtered head can sit behind a cursor a sharedScopes reader legitimately holds.
  • No pruning in memory or mongokit. MemoryChangeLogStore has no prune, so it never throws CursorExpiredError; use it for tests and dev, not to prove the resync path. Its sequence restarts at zero with the process. mongokit's store compacts with compactSuperseded (no horizon) and does not throw it either, so a reader should also cap how far back it replays.
  • Latest state, not every transition. After prune (or mongokit's compactSuperseded) a replay yields each document's latest entry. A reader that needs every transition must not compact that scope.

Typed result extras

import type { OffsetPaginationResult } from '@classytic/repo-core/pagination';

// Kit adds a typed surface-level extra without breaking cross-kit substitutability.
type MongokitPage<T> = OffsetPaginationResult<T, { warning?: string }>;

function render(page: MongokitPage<User>) {
  if (page.warning) showBanner(page.warning);
  return page.docs.map(userRow);
}

Default TExtra is Record<string, never> — OffsetPaginationResult<User> behaves identically before and after; the generic is free to ignore.

Status

v0.6.0 — standardization release. Required RepoCapabilities feature detection (unified with ConformanceFeatures), Standard Schema validation slot, domain-event emission (/events), watch() change-feed contract, unified RetryPolicy + signal cancellation, and recordToFilter promoted from per-kit copies.

Consumed by:

  • @classytic/mongokit ≥ 3.16 — Repository extends RepositoryBase; declares MONGOKIT_CAPABILITIES; implements watch() via change streams; hook engine, plugin-order validator, HOOK_PRIORITY, pagination + HttpError types all flow from repo-core. Mongokit's own QueryParser remains standalone.
  • @classytic/sqlitekit ≥ 0.6 — SqliteRepository extends RepositoryBase; declares SQLITEKIT_CAPABILITIES; Filter IR compiled to Drizzle / raw SQL natively; recordToFilter consumed from here.
  • @classytic/arc ≥ 2.12 — adapters typed against SchemaGenerator<TModel>; ArcError implements HttpError; pagination wire envelope (method discriminant) emitted via toCanonicalList() with reply.sendList().

See INFRA.md for the architectural principles, subpath map, build/tooling decisions, and the roadmap for pgkit / prismakit.

See docs/data-lifecycle.md for the billion-row runbook — retention/TTL, archiveByFilter cold-storage extraction, cursor() streaming scans, tenant purge, the distribution-key guard, and the per-backend sharding/partitioning/backup playbook (what the kits own vs what the database owns).

License

MIT — see LICENSE.

Trademark

The code is MIT-licensed. "Classytic", "arc", and the logos are trademarks of Classytic LLC and are not licensed under MIT — see TRADEMARK.md. Forks must be renamed; the license covers the code, not the brand.

版本与发布记录

@classytic/repo-core 共发布 43 个版本,首次发布于 2026/04/20;过去 12 个月发布了 43 个版本。

版本发布日期距今
0.38.0latest2026/11/046 天前
0.37.02026/11/036 天前
0.36.02026/10/2911 天前
0.35.02026/10/2912 天前
0.34.02026/10/2813 天前
0.33.02026/10/2714 天前

关于 @classytic/repo-core 的常见问题

@classytic/repo-core 是什么?

Driver-agnostic repository primitives: hooks, Filter IR, operations, pagination, cache contract. Foundation for mongokit, sqlitekit, pgkit, and prismakit. Lean by design — no plugins ship here; each kit owns its own.

如何安装 @classytic/repo-core?

在项目目录运行 npm install @classytic/repo-core,或使用 pnpm add / yarn add / bun add。

@classytic/repo-core 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@classytic/repo-core 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@classytic/repo-core 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@classytic/repo-core 可以商用吗?

@classytic/repo-core 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@classytic/repo-core 的下载量有多少?

根据 npm 官方下载统计,@classytic/repo-core 在 2026/10/10 – 2026/11/08 这 30 天内被下载 3,555 次,日均约 119 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@classytic/repo-core 还在维护吗?

最新版本 0.38.0 发布于 2026/11/04(6 天前);至今共发布 43 个版本,其中过去 12 个月发布了 43 个;首次发布于 2026/04/20。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。