@nymbalhq/platform 1.4.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-SNNK2OX3.js → chunk-NNDIAIT6.js} +73 -5
- package/dist/chunk-NNDIAIT6.js.map +1 -0
- package/dist/{chunk-GMV3B3SC.js → chunk-TRLERRUI.js} +424 -137
- package/dist/chunk-TRLERRUI.js.map +1 -0
- package/dist/db/schema/index.d.ts +795 -105
- package/dist/db/schema/index.js +1 -1
- package/dist/index.d.ts +218 -85
- package/dist/index.js +658 -199
- package/dist/index.js.map +1 -1
- package/dist/register-SBGUI2L5.js +8 -0
- package/migrations/postgres/0016_email_suppressions.sql +7 -0
- package/migrations/postgres/0017_order_shipments.sql +14 -0
- package/migrations/postgres/0018_order_key_expiry.sql +8 -0
- package/migrations/postgres/meta/0016_snapshot.json +2233 -0
- package/migrations/postgres/meta/0017_snapshot.json +2300 -0
- package/migrations/postgres/meta/0018_snapshot.json +2306 -0
- package/migrations/postgres/meta/_journal.json +21 -0
- package/migrations/sqlite/0016_email_suppressions.sql +7 -0
- package/migrations/sqlite/0017_order_shipments.sql +9 -0
- package/migrations/sqlite/0018_order_key_expiry.sql +25 -0
- package/migrations/sqlite/meta/0016_snapshot.json +1981 -0
- package/migrations/sqlite/meta/0017_snapshot.json +2041 -0
- package/migrations/sqlite/meta/0018_snapshot.json +2048 -0
- package/migrations/sqlite/meta/_journal.json +21 -0
- package/package.json +17 -47
- package/dist/chunk-GMV3B3SC.js.map +0 -1
- package/dist/chunk-SNNK2OX3.js.map +0 -1
- package/dist/register-N2XGSFUF.js +0 -8
- /package/dist/{register-N2XGSFUF.js.map → register-SBGUI2L5.js.map} +0 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/platform.ts","../src/document-store/in-memory.ts","../src/event-bus/in-process.ts","../src/logger.ts","../src/media/local-fs-storage.ts","../src/db/migrate.ts","../src/db/repositories/products.ts","../src/db/repositories/categories.ts","../src/repositories/product.ts","../src/repositories/json.ts","../src/repositories/variant.ts","../src/repositories/category.ts","../src/repositories/product-category.ts","../src/repositories/customer.ts","../src/repositories/refresh-token.ts","../src/repositories/order.ts","../src/repositories/order-history.ts","../src/repositories/order-refund.ts","../src/repositories/order-sequence.ts","../src/repositories/order-access-key.ts","../src/repositories/inventory-reservation.ts","../src/repositories/stock-adjustment.ts","../src/repositories/review.ts","../src/repositories/processed-event.ts","../src/repositories/event-log.ts","../src/history/subject.ts","../src/repositories/cart.ts","../src/repositories/alert-subscription.ts","../src/repositories/index.ts","../src/events/builder.ts","../src/events/publisher.ts","../src/events/relay.ts","../src/handlers/idempotency.ts","../src/handlers/projections/category-projection.ts","../src/handlers/projections/product-projection.ts","../src/read-models/sources.ts","../src/handlers/projections/order-projection.ts","../src/handlers/projections/customer-projection.ts","../src/handlers/projections/inventory-projection.ts","../src/handlers/side-effects/email-handler.ts","../src/handlers/side-effects/search-handler.ts","../src/handlers/side-effects/reviews-handler.ts","../src/handlers/side-effects/alert-handler.ts","../src/handlers/register.ts","../src/app.ts","../src/read-models/index.ts","../src/read-models/catalogue.ts","../src/read-models/customers.ts","../src/read-models/model.ts","../src/read-models/orders.ts","../src/read-models/search.ts","../src/sweepers/inventory-reservation-sweeper.ts","../src/sweepers/cart-abandonment-sweeper.ts","../src/sweepers/event-retention-sweeper.ts","../src/adapters/security/rate-limit.ts","../src/diagnose.ts","../src/seed/run.ts","../src/seed/data.ts","../src/read-models/open.ts"],"sourcesContent":["import { join } from 'node:path'\nimport type { NymbalConfig } from '@nymbalhq/config'\nimport {\n ConfigError,\n type DocumentStoreAdapter,\n type EventBusAdapter,\n type Logger,\n type MediaStorage,\n} from '@nymbalhq/types'\nimport { loadProviderAdapter } from './adapters/loader.js'\nimport { createCommandStore, type CommandStore } from './db/command-store.js'\nimport { InMemoryDocumentStore } from './document-store/in-memory.js'\nimport { InProcessEventBus } from './event-bus/in-process.js'\nimport { createLogger } from './logger.js'\nimport { createLocalFsMediaStorage } from './media/index.js'\n\nexport interface Platform {\n config: NymbalConfig\n commandStore: CommandStore\n documentStore: DocumentStoreAdapter\n eventBus: EventBusAdapter\n media: MediaStorage\n logger: Logger\n close(): Promise<void>\n}\n\n/** Where the command store is, and the logger; what `createApp` and `resolvePrimitives` take as well. */\nexport interface PlatformConnectionOptions {\n logger?: Logger\n sqlitePath?: string\n postgresUrl?: string\n}\n\n/** The infrastructure primitives, as instances: `resolvePrimitives` builds them from the config. */\nexport interface Primitives {\n documentStore: DocumentStoreAdapter\n eventBus: EventBusAdapter\n media: MediaStorage\n}\n\nexport interface CreatePlatformOptions extends PlatformConnectionOptions, Primitives {}\n\nexport interface ResolvePrimitivesOptions extends PlatformConnectionOptions {\n /** Where local-fs media is written; `public/imported-media` under the working directory by default. */\n mediaRoot?: string\n env?: NodeJS.ProcessEnv\n}\n\nexport const REDIS_DEFAULTS = {\n prefix: 'nymbal',\n ackTimeoutMs: 15_000,\n claimIdleMs: 5_000,\n streamMaxLen: 10_000,\n} as const\n\nconst S3_DEFAULT_REGION = 'us-east-1'\n\n/** The Postgres JSONB store's namespace inside the command store's database. */\nconst JSONB_PREFIX = 'nymbal'\n\nfunction nonEmpty(value: string | undefined): string | undefined {\n return value === undefined || value === '' ? undefined : value\n}\n\n/** The Redis server the primitives use: `infrastructure.redis.url`, else `REDIS_URL`. */\nexport function redisUrlOf(config: NymbalConfig, env: NodeJS.ProcessEnv): string | undefined {\n return config.infrastructure.redis?.url ?? nonEmpty(env['REDIS_URL'])\n}\n\n/** The `redis` block with its defaults: the URL from `REDIS_URL`, the prefix from `NYMBAL_REDIS_PREFIX`. */\nfunction redisConnection(config: NymbalConfig, env: NodeJS.ProcessEnv, slot: string) {\n const block = config.infrastructure.redis ?? {}\n const url = redisUrlOf(config, env)\n if (url === undefined) {\n throw new ConfigError(\n `infrastructure.${slot} needs a Redis server: set infrastructure.redis.url or REDIS_URL`,\n { code: 'config.redis_url_missing', context: { slot } },\n )\n }\n return {\n url,\n prefix: block.prefix ?? nonEmpty(env['NYMBAL_REDIS_PREFIX']) ?? REDIS_DEFAULTS.prefix,\n ackTimeoutMs: block.ackTimeoutMs ?? REDIS_DEFAULTS.ackTimeoutMs,\n claimIdleMs: block.claimIdleMs ?? REDIS_DEFAULTS.claimIdleMs,\n streamMaxLen: block.streamMaxLen ?? REDIS_DEFAULTS.streamMaxLen,\n }\n}\n\n/**\n * The `s3` block with its defaults: each field from the environment when the block leaves it out (`S3_BUCKET`,\n * `AWS_REGION`, `S3_ENDPOINT`, `NYMBAL_S3_PREFIX`, `S3_PUBLIC_URL`), the region `us-east-1`, no prefix, and path-style\n * requests when an endpoint is set. Credentials are not here: the AWS SDK's default chain provides them.\n */\nfunction s3Connection(config: NymbalConfig, env: NodeJS.ProcessEnv) {\n const block = config.infrastructure.s3 ?? {}\n const bucket = nonEmpty(block.bucket) ?? nonEmpty(env['S3_BUCKET'])\n if (bucket === undefined) {\n throw new ConfigError(\n \"infrastructure.media 's3' needs a bucket: set infrastructure.s3.bucket or S3_BUCKET\",\n { code: 'config.s3_bucket_missing', context: { slot: 'media' } },\n )\n }\n const endpoint = nonEmpty(block.endpoint) ?? nonEmpty(env['S3_ENDPOINT'])\n const publicUrl = nonEmpty(block.publicUrl) ?? nonEmpty(env['S3_PUBLIC_URL'])\n return {\n bucket,\n region: nonEmpty(block.region) ?? nonEmpty(env['AWS_REGION']) ?? S3_DEFAULT_REGION,\n prefix: block.prefix ?? nonEmpty(env['NYMBAL_S3_PREFIX']) ?? '',\n forcePathStyle: block.forcePathStyle ?? endpoint !== undefined,\n ...(endpoint !== undefined && { endpoint }),\n ...(publicUrl !== undefined && { publicUrl }),\n }\n}\n\nasync function loadPrimitive<T>(\n slot: 'documentStore' | 'eventBus' | 'media',\n provider: string,\n config: Record<string, unknown>,\n logger: Logger,\n env: NodeJS.ProcessEnv,\n): Promise<T> {\n const instance = await loadProviderAdapter(slot, provider, {\n config,\n logger: logger.child({ primitive: slot }),\n env,\n })\n if (instance === undefined) {\n throw new ConfigError(`infrastructure.${slot} '${provider}' has no implementation`, {\n context: { slot, provider },\n })\n }\n return instance as T\n}\n\n/** A document store that must be initialized before use (postgres-jsonb creates its table). */\ntype InitializableDocumentStore = DocumentStoreAdapter & { initialize?(): Promise<void> }\n\n/**\n * The document store the config names, constructed and not initialized: `resolvePrimitives` initializes it, and\n * `diagnose` must not (initializing postgres-jsonb creates its table).\n */\nexport async function buildDocumentStore(\n config: NymbalConfig,\n options: ResolvePrimitivesOptions,\n logger: Logger,\n env: NodeJS.ProcessEnv,\n): Promise<InitializableDocumentStore> {\n const choice = config.infrastructure.documentStore\n switch (choice) {\n case 'in-memory':\n return new InMemoryDocumentStore()\n case 'redis': {\n const { url, prefix } = redisConnection(config, env, 'documentStore')\n return loadPrimitive('documentStore', choice, { url, prefix }, logger, env)\n }\n case 'postgres-jsonb': {\n const postgresUrl = options.postgresUrl ?? nonEmpty(env['DATABASE_URL'])\n if (postgresUrl === undefined) {\n throw new ConfigError(\n \"documentStore 'postgres-jsonb' uses the command store's Postgres: set DATABASE_URL (or pass postgresUrl)\",\n { code: 'config.postgres_url_missing', context: { slot: 'documentStore' } },\n )\n }\n return loadPrimitive<InitializableDocumentStore>(\n 'documentStore',\n choice,\n { postgresUrl, prefix: JSONB_PREFIX },\n logger,\n env,\n )\n }\n default: {\n const exhaustive: never = choice\n throw new ConfigError(`Unknown documentStore: ${String(exhaustive)}`)\n }\n }\n}\n\nexport async function buildEventBus(\n config: NymbalConfig,\n logger: Logger,\n env: NodeJS.ProcessEnv,\n): Promise<EventBusAdapter> {\n const choice = config.infrastructure.eventBus\n switch (choice) {\n case 'in-process':\n return new InProcessEventBus({ logger })\n case 'redis-streams':\n return loadPrimitive(\n 'eventBus',\n choice,\n redisConnection(config, env, 'eventBus'),\n logger,\n env,\n )\n default: {\n const exhaustive: never = choice\n throw new ConfigError(`Unknown eventBus: ${String(exhaustive)}`)\n }\n }\n}\n\nexport async function buildMedia(\n config: NymbalConfig,\n options: ResolvePrimitivesOptions,\n logger: Logger,\n env: NodeJS.ProcessEnv,\n): Promise<MediaStorage> {\n const choice = config.infrastructure.media\n switch (choice) {\n case 'local-fs':\n return createLocalFsMediaStorage({\n root: options.mediaRoot ?? join(process.cwd(), 'public', 'imported-media'),\n urlPrefix: '/imported-media',\n })\n case 's3':\n return loadPrimitive('media', choice, s3Connection(config, env), logger, env)\n default: {\n const exhaustive: never = choice\n throw new ConfigError(`Unknown media: ${String(exhaustive)}`)\n }\n }\n}\n\n/**\n * The document store, event bus and media storage the config names. A primitive that lives in its own package is\n * imported only when named; a missing package fails `adapter.package_missing` with the install line.\n */\nexport async function resolvePrimitives(\n config: NymbalConfig,\n options: ResolvePrimitivesOptions = {},\n): Promise<Primitives> {\n const env = options.env ?? process.env\n const logger = options.logger ?? createLogger({ base: { store: config.store.name } })\n // Checked before anything is loaded or connects, so a missing URL or bucket never leaves a half-built set behind.\n if (config.infrastructure.media === 's3') s3Connection(config, env)\n if (config.infrastructure.documentStore === 'redis') redisConnection(config, env, 'documentStore')\n if (config.infrastructure.eventBus === 'redis-streams') redisConnection(config, env, 'eventBus')\n const media = await buildMedia(config, options, logger, env)\n const documentStore = await buildDocumentStore(config, options, logger, env)\n try {\n if (config.infrastructure.documentStore === 'postgres-jsonb') await documentStore.initialize?.()\n const eventBus = await buildEventBus(config, logger, env)\n return { documentStore, eventBus, media }\n } catch (error) {\n await documentStore.close()\n throw error\n }\n}\n\nexport function createPlatform(config: NymbalConfig, options: CreatePlatformOptions): Platform {\n const logger =\n options.logger ??\n createLogger({\n base: { store: config.store.name },\n })\n const commandStore = createCommandStore(config, {\n ...(options.sqlitePath !== undefined && { sqlitePath: options.sqlitePath }),\n ...(options.postgresUrl !== undefined && { postgresUrl: options.postgresUrl }),\n })\n const { documentStore, eventBus, media } = options\n return {\n config,\n commandStore,\n documentStore,\n eventBus,\n media,\n logger,\n async close() {\n // The bus first: a handler still running may write to either store.\n await eventBus.close()\n await documentStore.close()\n await commandStore.close()\n },\n }\n}\n","import { AdapterError, queryDocuments } from '@nymbalhq/types'\nimport type {\n DocumentStoreAdapter,\n HealthReport,\n PutOptions,\n QueryParams,\n QueryResult,\n} from '@nymbalhq/types'\n\ninterface Entry {\n doc: unknown\n expiresAt: number | null\n}\n\nexport interface InMemoryDocumentStoreOptions {\n sweepIntervalMs?: number\n now?: () => number\n}\n\nexport class InMemoryDocumentStore implements DocumentStoreAdapter {\n readonly #data = new Map<string, Map<string, Entry>>()\n readonly #now: () => number\n readonly #sweepTimer: NodeJS.Timeout | null\n\n constructor(options: InMemoryDocumentStoreOptions = {}) {\n this.#now = options.now ?? Date.now\n const interval = options.sweepIntervalMs ?? 60_000\n if (interval > 0) {\n this.#sweepTimer = setInterval(() => this.#sweep(), interval)\n this.#sweepTimer.unref?.()\n } else {\n this.#sweepTimer = null\n }\n }\n\n capabilities(): readonly string[] {\n return ['get', 'put', 'delete', 'query', 'batch', 'ttl', 'conditional-put']\n }\n\n /** The process's own memory: healthy whenever it can answer. */\n async healthCheck(): Promise<HealthReport> {\n return { status: 'healthy' }\n }\n\n async get<T>(collection: string, key: string): Promise<T | null> {\n const entry = this.#data.get(collection)?.get(key)\n if (!entry) return null\n if (this.#isExpired(entry)) {\n this.#data.get(collection)?.delete(key)\n return null\n }\n return entry.doc as T\n }\n\n async put<T>(\n collection: string,\n key: string,\n document: T,\n options: PutOptions = {},\n ): Promise<void> {\n const bucket = this.#getOrCreate(collection)\n if (options.conditionKey !== undefined) {\n const existing = bucket.get(key)\n if (!existing || this.#isExpired(existing)) {\n throw new AdapterError(\n 'condition-failed',\n `Condition failed on ${collection}/${key}: document does not exist`,\n { context: { collection, key, conditionKey: options.conditionKey } },\n )\n }\n const actual = (existing.doc as Record<string, unknown>)[options.conditionKey]\n if (actual !== options.conditionValue) {\n throw new AdapterError(\n 'condition-failed',\n `Condition failed on ${collection}/${key}: ${options.conditionKey} mismatch`,\n {\n context: {\n collection,\n key,\n conditionKey: options.conditionKey,\n expected: options.conditionValue,\n actual,\n },\n },\n )\n }\n }\n const expiresAt = options.ttl !== undefined ? this.#now() + options.ttl * 1000 : null\n bucket.set(key, { doc: document, expiresAt })\n }\n\n async delete(collection: string, key: string): Promise<void> {\n this.#data.get(collection)?.delete(key)\n }\n\n async query<T>(collection: string, params: QueryParams): Promise<QueryResult<T>> {\n const bucket = this.#data.get(collection)\n if (!bucket) return { items: [], nextCursor: null }\n const live: Array<[string, unknown]> = []\n for (const [key, entry] of bucket) {\n if (!this.#isExpired(entry)) live.push([key, entry.doc])\n }\n return queryDocuments<T>(live, params)\n }\n\n async batchGet<T>(collection: string, keys: string[]): Promise<Map<string, T>> {\n const result = new Map<string, T>()\n for (const key of keys) {\n const value = await this.get<T>(collection, key)\n if (value !== null) result.set(key, value)\n }\n return result\n }\n\n async batchPut<T>(collection: string, items: Map<string, T>): Promise<void> {\n for (const [key, doc] of items) {\n await this.put(collection, key, doc)\n }\n }\n\n /** Builds the new contents in a map of their own and swaps it in, so a reader sees one set or the other. */\n async replaceCollection<T>(\n collection: string,\n entries: AsyncIterable<[string, T]>,\n ): Promise<void> {\n const next = new Map<string, Entry>()\n for await (const [key, doc] of entries) next.set(key, { doc, expiresAt: null })\n this.#data.set(collection, next)\n }\n\n async close(): Promise<void> {\n if (this.#sweepTimer) clearInterval(this.#sweepTimer)\n this.#data.clear()\n }\n\n #getOrCreate(collection: string): Map<string, Entry> {\n let bucket = this.#data.get(collection)\n if (!bucket) {\n bucket = new Map()\n this.#data.set(collection, bucket)\n }\n return bucket\n }\n\n #isExpired(entry: Entry): boolean {\n return entry.expiresAt !== null && entry.expiresAt <= this.#now()\n }\n\n #sweep(): void {\n const now = this.#now()\n for (const bucket of this.#data.values()) {\n for (const [key, entry] of bucket) {\n if (entry.expiresAt !== null && entry.expiresAt <= now) {\n bucket.delete(key)\n }\n }\n }\n }\n}\n","import { v7 as uuidv7 } from 'uuid'\nimport type {\n EventBusAdapter,\n EventHandler,\n HandlerFailure,\n HealthReport,\n NymbalEvent,\n Subscription,\n SubscriptionConfig,\n Logger,\n} from '@nymbalhq/types'\nimport { handlerFailedError, ValidationError } from '@nymbalhq/types'\n\ninterface Registration {\n id: string\n patterns: string[]\n regexes: RegExp[]\n handler: EventHandler\n config: SubscriptionConfig | undefined\n}\n\nexport interface InProcessEventBusOptions {\n logger?: Logger\n}\n\nexport class InProcessEventBus implements EventBusAdapter {\n readonly #registrations = new Map<string, Registration>()\n readonly #logger: Logger | undefined\n\n constructor(options: InProcessEventBusOptions = {}) {\n this.#logger = options.logger\n }\n\n capabilities(): readonly string[] {\n return ['publish', 'subscribe', 'wildcard', 'replay']\n }\n\n /** Delivery within the process: healthy whenever it can answer. */\n async healthCheck(): Promise<HealthReport> {\n return { status: 'healthy' }\n }\n\n async publish<T>(event: NymbalEvent<T>): Promise<void> {\n const failed = await this.#deliver(event, () => true)\n if (failed.length > 0) throw handlerFailedError(event, failed)\n }\n\n async publishBatch(events: NymbalEvent<unknown>[]): Promise<void> {\n let first: Error | undefined\n for (const event of events) {\n const failed = await this.#deliver(event, () => true)\n if (failed.length > 0) first ??= handlerFailedError(event, failed)\n }\n if (first !== undefined) throw first\n }\n\n async replay(events: NymbalEvent<unknown>[]): Promise<void> {\n for (const event of events) {\n await this.#deliver(event, (r) => r.config?.derived === true)\n }\n }\n\n /** Runs every matching handler to the end, each error logged; returns the named subscriptions that threw. */\n async #deliver<T>(\n event: NymbalEvent<T>,\n eligible: (r: Registration) => boolean,\n ): Promise<HandlerFailure[]> {\n this.#validate(event)\n const matches = Array.from(this.#registrations.values()).filter(\n (r) => eligible(r) && r.regexes.some((re) => re.test(event.type)),\n )\n const outcomes = await Promise.all(\n matches.map(async (r): Promise<HandlerFailure | null> => {\n try {\n await r.handler(event)\n return null\n } catch (err) {\n const subscription = r.config?.name\n this.#logger?.error(\n { err, subscriptionId: r.id, subscription, eventType: event.type, eventId: event.id },\n 'Event handler failed',\n )\n return subscription === undefined ? null : { subscription, message: messageOf(err) }\n }\n }),\n )\n return outcomes.filter((o) => o !== null)\n }\n\n async subscribe(\n eventPattern: string | string[],\n handler: EventHandler,\n config?: SubscriptionConfig,\n ): Promise<Subscription> {\n const patterns = Array.isArray(eventPattern) ? eventPattern : [eventPattern]\n const regexes = patterns.map(compilePattern)\n const id = uuidv7()\n const registration: Registration = { id, patterns, regexes, handler, config }\n this.#registrations.set(id, registration)\n const self = this\n return {\n id,\n patterns,\n async unsubscribe() {\n self.#registrations.delete(id)\n },\n }\n }\n\n async unsubscribe(subscription: Subscription): Promise<void> {\n this.#registrations.delete(subscription.id)\n }\n\n async close(): Promise<void> {\n this.#registrations.clear()\n }\n\n #validate(event: NymbalEvent<unknown>): void {\n if (!event.id || !event.type || !event.timestamp || !event.source) {\n throw new ValidationError('Event is missing required envelope fields', {\n context: { event },\n })\n }\n if (!event.metadata || !event.metadata.storeId || !event.metadata.environment) {\n throw new ValidationError('Event metadata is missing required fields', {\n context: { event },\n })\n }\n }\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\nfunction compilePattern(pattern: string): RegExp {\n const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\*]/g, '\\\\$&').replace(/\\\\\\*/g, '.*')\n return new RegExp(`^${escaped}$`)\n}\n","import { pino, type DestinationStream, type Logger as PinoLogger } from 'pino'\nimport type { Logger } from '@nymbalhq/types'\n\nexport interface CreateLoggerOptions {\n level?: string\n pretty?: boolean\n base?: Record<string, unknown>\n /** Where the JSON lines go instead of stdout; a destination is never pretty-printed. */\n destination?: DestinationStream\n}\n\nexport function createLogger(options: CreateLoggerOptions = {}): Logger {\n const isProduction = process.env.NODE_ENV === 'production'\n const pretty = options.destination === undefined && (options.pretty ?? !isProduction)\n const settings = {\n level: options.level ?? process.env.LOG_LEVEL ?? (isProduction ? 'info' : 'debug'),\n base: options.base ?? {},\n ...(pretty && {\n transport: {\n target: 'pino-pretty',\n options: { colorize: true, translateTime: 'HH:MM:ss.l', ignore: 'pid,hostname' },\n },\n }),\n }\n const logger =\n options.destination === undefined ? pino(settings) : pino(settings, options.destination)\n return wrap(logger)\n}\n\nfunction wrap(p: PinoLogger): Logger {\n return {\n trace: (obj, msg) => p.trace(obj as object, msg),\n debug: (obj, msg) => p.debug(obj as object, msg),\n info: (obj, msg) => p.info(obj as object, msg),\n warn: (obj, msg) => p.warn(obj as object, msg),\n error: (obj, msg) => p.error(obj as object, msg),\n child: (bindings) => wrap(p.child(bindings)),\n }\n}\n","import { constants } from 'node:fs'\nimport { access, mkdir, writeFile } from 'node:fs/promises'\nimport { dirname, join, resolve } from 'node:path'\nimport type { HealthReport, MediaStorage } from '@nymbalhq/types'\n\nexport interface LocalFsMediaStorageOptions {\n root: string\n urlPrefix?: string\n}\n\n/** What the local filesystem storage offers, whatever its root: the app reports it for the media slot. */\nexport const LOCAL_FS_MEDIA_CAPABILITIES: readonly string[] = ['put']\n\n/**\n * The directory whose write permission decides whether `put` can store under `root`: the root itself, or, when it\n * does not exist yet, its nearest existing ancestor, since `put` creates the missing directories.\n */\nasync function nearestExisting(root: string): Promise<string> {\n let dir = resolve(root)\n for (;;) {\n try {\n await access(dir, constants.F_OK)\n return dir\n } catch {\n const parent = dirname(dir)\n if (parent === dir) return dir\n dir = parent\n }\n }\n}\n\nexport function createLocalFsMediaStorage(options: LocalFsMediaStorageOptions): MediaStorage {\n const { root } = options\n const urlPrefix = options.urlPrefix ?? '/imported-media'\n\n return {\n capabilities: () => LOCAL_FS_MEDIA_CAPABILITIES,\n async put(key, body, _contentType) {\n const dest = join(root, key)\n const dir = dest.substring(0, dest.lastIndexOf('/'))\n await mkdir(dir, { recursive: true })\n await writeFile(dest, body)\n return { url: `${urlPrefix}/${key}` }\n },\n // Permission is read with access(2), never probed by writing a file.\n async healthCheck(): Promise<HealthReport> {\n const dir = await nearestExisting(root)\n try {\n await access(dir, constants.W_OK)\n return { status: 'healthy', detail: root }\n } catch {\n return { status: 'down', detail: `${dir} is not writable` }\n }\n },\n }\n}\n","import { readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { migrate as migrateSqlite } from 'drizzle-orm/better-sqlite3/migrator'\nimport { migrate as migratePostgres } from 'drizzle-orm/node-postgres/migrator'\nimport { rawClients, type CommandStore } from './command-store.js'\n\nexport interface MigrateOptions {\n migrationsRoot?: string\n}\n\nfunction rootOf(options: MigrateOptions): string {\n return options.migrationsRoot ?? resolve(process.cwd(), 'migrations')\n}\n\nexport async function runMigrations(\n store: CommandStore,\n options: MigrateOptions = {},\n): Promise<void> {\n const root = rootOf(options)\n const clients = rawClients(store)\n if (clients.kind === 'sqlite') {\n migrateSqlite(clients.db, { migrationsFolder: resolve(root, 'sqlite') })\n } else {\n await migratePostgres(clients.db, { migrationsFolder: resolve(root, 'postgres') })\n }\n}\n\nexport interface MigrationState {\n /** Rows in the store's migrations table. */\n applied: number\n /** Journal entries `runMigrations` would apply. */\n pending: number\n}\n\n/**\n * What `runMigrations` would do to `store`, read without writing. Drizzle applies every journal entry created after the\n * newest one its table records, so that is what counts as pending; a store with no table has every entry pending.\n */\nexport async function migrationState(\n store: CommandStore,\n options: MigrateOptions = {},\n): Promise<MigrationState> {\n const clients = rawClients(store)\n const journal = JSON.parse(\n readFileSync(resolve(rootOf(options), clients.kind, 'meta', '_journal.json'), 'utf8'),\n ) as { entries: Array<{ when: number }> }\n let applied = 0\n let newest = Number.NEGATIVE_INFINITY\n if (clients.kind === 'sqlite') {\n const table = clients.raw\n .prepare(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = '__drizzle_migrations'\")\n .get()\n if (table !== undefined) {\n const row = clients.raw\n .prepare('SELECT count(*) AS n, max(created_at) AS last FROM __drizzle_migrations')\n .get() as { n: number; last: number | null }\n applied = row.n\n if (row.last !== null) newest = Number(row.last)\n }\n } else {\n const { rows } = await clients.pool.query<{ table: string | null }>(\n \"SELECT to_regclass('drizzle.__drizzle_migrations')::text AS table\",\n )\n if (rows[0]?.table != null) {\n const counted = await clients.pool.query<{ n: number; last: string | null }>(\n 'SELECT count(*)::int AS n, max(created_at)::text AS last FROM drizzle.__drizzle_migrations',\n )\n applied = counted.rows[0]?.n ?? 0\n const last = counted.rows[0]?.last ?? null\n if (last !== null) newest = Number(last)\n }\n }\n const pending = journal.entries.filter((entry) => entry.when > newest).length\n return { applied, pending }\n}\n","import { eq } from 'drizzle-orm'\nimport { rawClients, type CommandStore } from '../command-store.js'\nimport * as sqliteSchema from '../schema/sqlite.js'\nimport * as postgresSchema from '../schema/postgres.js'\n\nexport interface ProductInsert {\n id: string\n slug: string\n name: string\n description: string\n shortDescription?: string\n status?: 'draft' | 'active' | 'archived'\n type?: 'simple' | 'variable'\n seoTitle?: string\n seoDescription?: string\n media?: unknown[]\n metadata?: Record<string, unknown>\n createdAt: Date\n updatedAt: Date\n}\n\nexport interface ProductRow {\n id: string\n slug: string\n name: string\n description: string\n shortDescription: string\n status: 'draft' | 'active' | 'archived'\n type: 'simple' | 'variable'\n seoTitle: string\n seoDescription: string\n media: unknown[]\n metadata: Record<string, unknown>\n createdAt: Date | string\n updatedAt: Date | string\n}\n\nfunction parseJson<T>(value: unknown, fallback: T): T {\n if (typeof value === 'string') {\n try {\n return JSON.parse(value) as T\n } catch {\n return fallback\n }\n }\n return (value ?? fallback) as T\n}\n\nfunction rowToDomain(row: Record<string, unknown>): ProductRow {\n return {\n id: String(row.id),\n slug: String(row.slug),\n name: String(row.name),\n description: String(row.description ?? ''),\n shortDescription: String(row.shortDescription ?? ''),\n status: row.status as 'draft' | 'active' | 'archived',\n type: row.type as 'simple' | 'variable',\n seoTitle: String(row.seoTitle ?? ''),\n seoDescription: String(row.seoDescription ?? ''),\n media: parseJson(row.media, [] as unknown[]),\n metadata: parseJson(row.metadata, {} as Record<string, unknown>),\n createdAt: row.createdAt as Date | string,\n updatedAt: row.updatedAt as Date | string,\n }\n}\n\nexport function createProductRepository(store: CommandStore) {\n const clients = rawClients(store)\n return {\n async findAll(): Promise<ProductRow[]> {\n if (clients.kind === 'sqlite') {\n const rows = clients.db.select().from(sqliteSchema.products).all()\n return rows.map((r) => rowToDomain(r as Record<string, unknown>))\n }\n const rows = await clients.db.select().from(postgresSchema.products)\n return rows.map((r) => rowToDomain(r as Record<string, unknown>))\n },\n\n async findBySlug(slug: string): Promise<ProductRow | null> {\n if (clients.kind === 'sqlite') {\n const row = clients.db\n .select()\n .from(sqliteSchema.products)\n .where(eq(sqliteSchema.products.slug, slug))\n .get()\n return row ? rowToDomain(row as Record<string, unknown>) : null\n }\n const [row] = await clients.db\n .select()\n .from(postgresSchema.products)\n .where(eq(postgresSchema.products.slug, slug))\n return row ? rowToDomain(row as Record<string, unknown>) : null\n },\n\n async insertMany(items: ProductInsert[]): Promise<void> {\n if (items.length === 0) return\n if (clients.kind === 'sqlite') {\n const rows = items.map((item) => ({\n id: item.id,\n slug: item.slug,\n name: item.name,\n description: item.description,\n shortDescription: item.shortDescription ?? '',\n status: item.status ?? 'active',\n type: item.type ?? 'simple',\n seoTitle: item.seoTitle ?? '',\n seoDescription: item.seoDescription ?? '',\n media: JSON.stringify(item.media ?? []),\n metadata: JSON.stringify(item.metadata ?? {}),\n createdAt: item.createdAt.toISOString(),\n updatedAt: item.updatedAt.toISOString(),\n }))\n clients.db.insert(sqliteSchema.products).values(rows).run()\n return\n }\n const rows = items.map((item) => ({\n id: item.id,\n slug: item.slug,\n name: item.name,\n description: item.description,\n shortDescription: item.shortDescription ?? '',\n status: item.status ?? 'active',\n type: item.type ?? 'simple',\n seoTitle: item.seoTitle ?? '',\n seoDescription: item.seoDescription ?? '',\n media: item.media ?? [],\n metadata: item.metadata ?? {},\n createdAt: item.createdAt,\n updatedAt: item.updatedAt,\n }))\n await clients.db.insert(postgresSchema.products).values(rows)\n },\n }\n}\n","import { rawClients, type CommandStore } from '../command-store.js'\nimport * as sqliteSchema from '../schema/sqlite.js'\nimport * as postgresSchema from '../schema/postgres.js'\n\nexport interface CategoryInsert {\n id: string\n parentId?: string | null\n slug: string\n name: string\n description: string\n position?: number\n createdAt: Date\n}\n\nexport interface CategoryRow {\n id: string\n parentId: string | null\n slug: string\n name: string\n description: string\n position: number\n createdAt: Date | string\n}\n\nexport function createCategoryRepository(store: CommandStore) {\n const clients = rawClients(store)\n return {\n async findAll(): Promise<CategoryRow[]> {\n if (clients.kind === 'sqlite') {\n const rows = clients.db.select().from(sqliteSchema.categories).all()\n return rows as CategoryRow[]\n }\n const rows = await clients.db.select().from(postgresSchema.categories)\n return rows as CategoryRow[]\n },\n\n async insertMany(items: CategoryInsert[]): Promise<void> {\n if (items.length === 0) return\n if (clients.kind === 'sqlite') {\n const rows = items.map((item) => ({\n id: item.id,\n parentId: item.parentId ?? null,\n slug: item.slug,\n name: item.name,\n description: item.description,\n position: item.position ?? 0,\n createdAt: item.createdAt.toISOString(),\n }))\n clients.db.insert(sqliteSchema.categories).values(rows).run()\n return\n }\n const rows = items.map((item) => ({\n id: item.id,\n parentId: item.parentId ?? null,\n slug: item.slug,\n name: item.name,\n description: item.description,\n position: item.position ?? 0,\n createdAt: item.createdAt,\n }))\n await clients.db.insert(postgresSchema.categories).values(rows)\n },\n }\n}\n","import { asc, eq, gt } from 'drizzle-orm'\nimport type { Product, ProductStatus, ProductType, ProductMedia } from '@nymbalhq/types'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport type { KeysetPage } from './page.js'\nimport { parseJson, serialiseJson, fromTimestamp } from './json.js'\n\nexport interface ProductInsert {\n id: string\n slug: string\n name: string\n description?: string\n shortDescription?: string\n status?: ProductStatus\n type?: ProductType\n seoTitle?: string\n seoDescription?: string\n media?: ProductMedia[]\n metadata?: Record<string, unknown>\n createdAt: Date\n updatedAt: Date\n}\n\nexport interface ProductUpdate {\n name?: string\n description?: string\n shortDescription?: string\n status?: ProductStatus\n type?: ProductType\n seoTitle?: string\n seoDescription?: string\n media?: ProductMedia[]\n metadata?: Record<string, unknown>\n updatedAt: Date\n}\n\nfunction rowToProduct(store: CommandStore['kind'], row: Record<string, unknown>): Product {\n return {\n id: String(row.id),\n slug: String(row.slug),\n name: String(row.name),\n description: String(row.description ?? ''),\n shortDescription: String(row.shortDescription ?? ''),\n status: row.status as ProductStatus,\n type: row.type as ProductType,\n seoTitle: String(row.seoTitle ?? ''),\n seoDescription: String(row.seoDescription ?? ''),\n media: parseJson<ProductMedia[]>(store, row.media, []),\n metadata: parseJson<Record<string, unknown>>(store, row.metadata, {}),\n createdAt: fromTimestamp(row.createdAt),\n updatedAt: fromTimestamp(row.updatedAt),\n }\n}\n\nexport interface ProductRepository extends StoreRepository {\n findById(tx: ReadTx, id: string): Promise<Product | null>\n findBySlug(tx: ReadTx, slug: string): Promise<Product | null>\n list(\n tx: ReadTx,\n opts?: { status?: ProductStatus; limit?: number; offset?: number },\n ): Promise<Product[]>\n /** Rows by id after `page.after`: a walk over the table that a concurrent write cannot make skip a row. */\n listPage(tx: ReadTx, page: KeysetPage): Promise<Product[]>\n insert(tx: Tx, p: ProductInsert): Promise<void>\n update(tx: Tx, id: string, patch: ProductUpdate): Promise<void>\n delete(tx: Tx, id: string): Promise<void>\n setStatus(tx: Tx, id: string, status: ProductStatus, updatedAt: Date): Promise<void>\n}\n\nexport function createProductRepository(store: CommandStore): ProductRepository {\n async function _find(tx: ReadTx, column: 'id' | 'slug', value: string): Promise<Product | null> {\n if (tx.kind === 'sqlite') {\n const col = column === 'id' ? sqliteSchema.products.id : sqliteSchema.products.slug\n const row = sqliteDb(tx).select().from(sqliteSchema.products).where(eq(col, value)).get()\n return row ? rowToProduct(tx.kind, row as Record<string, unknown>) : null\n }\n const col = column === 'id' ? postgresSchema.products.id : postgresSchema.products.slug\n const [row] = await postgresDb(tx).select().from(postgresSchema.products).where(eq(col, value))\n return row ? rowToProduct(tx.kind, row as Record<string, unknown>) : null\n }\n\n return {\n store,\n async findById(tx, id) {\n return _find(tx, 'id', id)\n },\n async findBySlug(tx, slug) {\n return _find(tx, 'slug', slug)\n },\n async listPage(tx, page) {\n if (tx.kind === 'sqlite') {\n const t = sqliteSchema.products\n const rows = sqliteDb(tx)\n .select()\n .from(t)\n .where(page.after === undefined ? undefined : gt(t.id, page.after))\n .orderBy(asc(t.id))\n .limit(page.limit)\n .all()\n return rows.map((r) => rowToProduct('sqlite', r as Record<string, unknown>))\n }\n const t = postgresSchema.products\n const rows = await postgresDb(tx)\n .select()\n .from(t)\n .where(page.after === undefined ? undefined : gt(t.id, page.after))\n .orderBy(asc(t.id))\n .limit(page.limit)\n return rows.map((r) => rowToProduct('postgres', r as Record<string, unknown>))\n },\n async list(tx, opts = {}) {\n const limit = opts.limit ?? 100\n const offset = opts.offset ?? 0\n if (tx.kind === 'sqlite') {\n const base = sqliteDb(tx).select().from(sqliteSchema.products)\n const filtered = opts.status\n ? base.where(eq(sqliteSchema.products.status, opts.status))\n : base\n const rows = filtered.limit(limit).offset(offset).all()\n return rows.map((r) => rowToProduct('sqlite', r as Record<string, unknown>))\n }\n const base = postgresDb(tx).select().from(postgresSchema.products)\n const filtered = opts.status\n ? base.where(eq(postgresSchema.products.status, opts.status))\n : base\n const rows = await filtered.limit(limit).offset(offset)\n return rows.map((r) => rowToProduct('postgres', r as Record<string, unknown>))\n },\n async insert(tx, p) {\n const common = {\n id: p.id,\n slug: p.slug,\n name: p.name,\n description: p.description ?? '',\n shortDescription: p.shortDescription ?? '',\n status: p.status ?? 'draft',\n type: p.type ?? 'simple',\n seoTitle: p.seoTitle ?? '',\n seoDescription: p.seoDescription ?? '',\n }\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.products)\n .values({\n ...common,\n media: serialiseJson('sqlite', p.media ?? []) as string,\n metadata: serialiseJson('sqlite', p.metadata ?? {}) as string,\n createdAt: p.createdAt.toISOString(),\n updatedAt: p.updatedAt.toISOString(),\n })\n .run()\n return\n }\n await postgresDb(tx)\n .insert(postgresSchema.products)\n .values({\n ...common,\n media: p.media ?? [],\n metadata: p.metadata ?? {},\n createdAt: p.createdAt,\n updatedAt: p.updatedAt,\n })\n },\n async update(tx, id, patch) {\n const pg: Record<string, unknown> = { updatedAt: patch.updatedAt }\n const sq: Record<string, unknown> = { updatedAt: patch.updatedAt.toISOString() }\n if (patch.name !== undefined) {\n pg.name = patch.name\n sq.name = patch.name\n }\n if (patch.description !== undefined) {\n pg.description = patch.description\n sq.description = patch.description\n }\n if (patch.shortDescription !== undefined) {\n pg.shortDescription = patch.shortDescription\n sq.shortDescription = patch.shortDescription\n }\n if (patch.status !== undefined) {\n pg.status = patch.status\n sq.status = patch.status\n }\n if (patch.type !== undefined) {\n pg.type = patch.type\n sq.type = patch.type\n }\n if (patch.seoTitle !== undefined) {\n pg.seoTitle = patch.seoTitle\n sq.seoTitle = patch.seoTitle\n }\n if (patch.seoDescription !== undefined) {\n pg.seoDescription = patch.seoDescription\n sq.seoDescription = patch.seoDescription\n }\n if (patch.media !== undefined) {\n pg.media = patch.media\n sq.media = JSON.stringify(patch.media)\n }\n if (patch.metadata !== undefined) {\n pg.metadata = patch.metadata\n sq.metadata = JSON.stringify(patch.metadata)\n }\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.products)\n .set(sq)\n .where(eq(sqliteSchema.products.id, id))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.products)\n .set(pg)\n .where(eq(postgresSchema.products.id, id))\n },\n async delete(tx, id) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx).delete(sqliteSchema.products).where(eq(sqliteSchema.products.id, id)).run()\n return\n }\n await postgresDb(tx).delete(postgresSchema.products).where(eq(postgresSchema.products.id, id))\n },\n async setStatus(tx, id, status, updatedAt) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.products)\n .set({ status, updatedAt: updatedAt.toISOString() })\n .where(eq(sqliteSchema.products.id, id))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.products)\n .set({ status, updatedAt })\n .where(eq(postgresSchema.products.id, id))\n },\n }\n}\n","export function serialiseJson(store: 'sqlite' | 'postgres', value: unknown): unknown {\n if (store === 'sqlite') {\n return JSON.stringify(value)\n }\n return value\n}\n\nexport function parseJson<T>(store: 'sqlite' | 'postgres', value: unknown, fallback: T): T {\n if (store === 'sqlite' && typeof value === 'string') {\n try {\n return JSON.parse(value) as T\n } catch {\n return fallback\n }\n }\n return (value ?? fallback) as T\n}\n\nexport function toIso(store: 'sqlite' | 'postgres', d: Date): Date | string {\n return store === 'sqlite' ? d.toISOString() : d\n}\n\nexport function fromTimestamp(value: unknown): string {\n if (value instanceof Date) return value.toISOString()\n return String(value)\n}\n","import { and, asc, eq, gte, sql } from 'drizzle-orm'\nimport type { Variant, VariantOption, VariantStatus, VariantDimensions } from '@nymbalhq/types'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport { parseJson, fromTimestamp } from './json.js'\n\nexport interface VariantInsert {\n id: string\n productId: string\n sku: string\n name: string\n priceMinor: number\n compareAtPriceMinor?: number | null\n weightGrams?: number | null\n dimensions?: VariantDimensions | null\n stock: number\n lowStockThreshold?: number\n options: VariantOption[]\n status?: VariantStatus\n createdAt: Date\n updatedAt: Date\n}\n\nexport interface VariantUpdate {\n name?: string\n priceMinor?: number\n compareAtPriceMinor?: number | null\n weightGrams?: number | null\n dimensions?: VariantDimensions | null\n lowStockThreshold?: number\n options?: VariantOption[]\n status?: VariantStatus\n updatedAt: Date\n}\n\nfunction rowToVariant(store: CommandStore['kind'], row: Record<string, unknown>): Variant {\n return {\n id: String(row.id),\n productId: String(row.productId),\n sku: String(row.sku),\n name: String(row.name ?? ''),\n priceMinor: Number(row.priceMinor),\n compareAtPriceMinor: row.compareAtPriceMinor == null ? null : Number(row.compareAtPriceMinor),\n weightGrams: row.weightGrams == null ? null : Number(row.weightGrams),\n dimensions: parseJson<VariantDimensions | null>(store, row.dimensions, null),\n stock: Number(row.stock),\n lowStockThreshold: Number(row.lowStockThreshold ?? 0),\n options: parseJson<VariantOption[]>(store, row.options, []),\n status: row.status as VariantStatus,\n createdAt: fromTimestamp(row.createdAt),\n updatedAt: fromTimestamp(row.updatedAt),\n }\n}\n\nexport interface VariantRepository extends StoreRepository {\n findById(tx: ReadTx, id: string): Promise<Variant | null>\n findBySku(tx: ReadTx, sku: string): Promise<Variant | null>\n findByProduct(tx: ReadTx, productId: string): Promise<Variant[]>\n insert(tx: Tx, v: VariantInsert): Promise<void>\n update(tx: Tx, id: string, patch: VariantUpdate): Promise<void>\n /** One conditional UPDATE: the new stock, or null when the variant is missing or holds fewer than `qty`. */\n decrementStock(tx: Tx, id: string, qty: number, at: Date): Promise<number | null>\n /** The new stock, or null when there is no such variant. */\n incrementStock(tx: Tx, id: string, qty: number, at: Date): Promise<number | null>\n delete(tx: Tx, id: string): Promise<void>\n}\n\nexport function createVariantRepository(store: CommandStore): VariantRepository {\n return {\n store,\n async findById(tx, id) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.variants)\n .where(eq(sqliteSchema.variants.id, id))\n .get()\n return row ? rowToVariant('sqlite', row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.variants)\n .where(eq(postgresSchema.variants.id, id))\n return row ? rowToVariant('postgres', row as Record<string, unknown>) : null\n },\n async findBySku(tx, sku) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.variants)\n .where(eq(sqliteSchema.variants.sku, sku))\n .get()\n return row ? rowToVariant('sqlite', row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.variants)\n .where(eq(postgresSchema.variants.sku, sku))\n return row ? rowToVariant('postgres', row as Record<string, unknown>) : null\n },\n async findByProduct(tx, productId) {\n if (tx.kind === 'sqlite') {\n const rows = sqliteDb(tx)\n .select()\n .from(sqliteSchema.variants)\n .where(eq(sqliteSchema.variants.productId, productId))\n .orderBy(asc(sqliteSchema.variants.createdAt), asc(sqliteSchema.variants.id))\n .all()\n return rows.map((r) => rowToVariant('sqlite', r as Record<string, unknown>))\n }\n const rows = await postgresDb(tx)\n .select()\n .from(postgresSchema.variants)\n .where(eq(postgresSchema.variants.productId, productId))\n .orderBy(asc(postgresSchema.variants.createdAt), asc(postgresSchema.variants.id))\n return rows.map((r) => rowToVariant('postgres', r as Record<string, unknown>))\n },\n async insert(tx, v) {\n const common = {\n id: v.id,\n productId: v.productId,\n sku: v.sku,\n name: v.name,\n priceMinor: v.priceMinor,\n compareAtPriceMinor: v.compareAtPriceMinor ?? null,\n weightGrams: v.weightGrams ?? null,\n stock: v.stock,\n lowStockThreshold: v.lowStockThreshold ?? 0,\n status: v.status ?? 'active',\n }\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.variants)\n .values({\n ...common,\n dimensions: v.dimensions ? JSON.stringify(v.dimensions) : null,\n options: JSON.stringify(v.options),\n createdAt: v.createdAt.toISOString(),\n updatedAt: v.updatedAt.toISOString(),\n })\n .run()\n return\n }\n await postgresDb(tx)\n .insert(postgresSchema.variants)\n .values({\n ...common,\n dimensions: v.dimensions ?? null,\n options: v.options,\n createdAt: v.createdAt,\n updatedAt: v.updatedAt,\n })\n },\n async update(tx, id, patch) {\n const pg: Record<string, unknown> = { updatedAt: patch.updatedAt }\n const sq: Record<string, unknown> = { updatedAt: patch.updatedAt.toISOString() }\n for (const k of [\n 'name',\n 'priceMinor',\n 'compareAtPriceMinor',\n 'weightGrams',\n 'lowStockThreshold',\n 'status',\n ] as const) {\n if (patch[k] !== undefined) {\n pg[k] = patch[k]\n sq[k] = patch[k]\n }\n }\n if (patch.dimensions !== undefined) {\n pg.dimensions = patch.dimensions ?? null\n sq.dimensions = patch.dimensions ? JSON.stringify(patch.dimensions) : null\n }\n if (patch.options !== undefined) {\n pg.options = patch.options\n sq.options = JSON.stringify(patch.options)\n }\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.variants)\n .set(sq)\n .where(eq(sqliteSchema.variants.id, id))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.variants)\n .set(pg)\n .where(eq(postgresSchema.variants.id, id))\n },\n async decrementStock(tx, id, qty, at) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .update(sqliteSchema.variants)\n .set({ stock: sql`${sqliteSchema.variants.stock} - ${qty}`, updatedAt: at.toISOString() })\n .where(and(eq(sqliteSchema.variants.id, id), gte(sqliteSchema.variants.stock, qty)))\n .returning({ stock: sqliteSchema.variants.stock })\n .get()\n return row ? Number(row.stock) : null\n }\n const [row] = await postgresDb(tx)\n .update(postgresSchema.variants)\n .set({ stock: sql`${postgresSchema.variants.stock} - ${qty}`, updatedAt: at })\n .where(and(eq(postgresSchema.variants.id, id), gte(postgresSchema.variants.stock, qty)))\n .returning({ stock: postgresSchema.variants.stock })\n return row ? Number(row.stock) : null\n },\n async incrementStock(tx, id, qty, at) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .update(sqliteSchema.variants)\n .set({ stock: sql`${sqliteSchema.variants.stock} + ${qty}`, updatedAt: at.toISOString() })\n .where(eq(sqliteSchema.variants.id, id))\n .returning({ stock: sqliteSchema.variants.stock })\n .get()\n return row ? Number(row.stock) : null\n }\n const [row] = await postgresDb(tx)\n .update(postgresSchema.variants)\n .set({ stock: sql`${postgresSchema.variants.stock} + ${qty}`, updatedAt: at })\n .where(eq(postgresSchema.variants.id, id))\n .returning({ stock: postgresSchema.variants.stock })\n return row ? Number(row.stock) : null\n },\n async delete(tx, id) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx).delete(sqliteSchema.variants).where(eq(sqliteSchema.variants.id, id)).run()\n return\n }\n await postgresDb(tx).delete(postgresSchema.variants).where(eq(postgresSchema.variants.id, id))\n },\n }\n}\n","import { asc, eq, gt } from 'drizzle-orm'\nimport type { Category } from '@nymbalhq/types'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport type { KeysetPage } from './page.js'\nimport { fromTimestamp } from './json.js'\n\nexport interface CategoryInsert {\n id: string\n parentId?: string | null\n slug: string\n name: string\n description?: string\n position?: number\n createdAt: Date\n}\n\nexport interface CategoryUpdate {\n parentId?: string | null\n name?: string\n description?: string\n position?: number\n}\n\nfunction rowToCategory(row: Record<string, unknown>): Category {\n return {\n id: String(row.id),\n parentId: (row.parentId as string | null) ?? null,\n slug: String(row.slug),\n name: String(row.name),\n description: String(row.description ?? ''),\n position: Number(row.position ?? 0),\n createdAt: fromTimestamp(row.createdAt),\n }\n}\n\nexport interface CategoryRepository extends StoreRepository {\n findById(tx: ReadTx, id: string): Promise<Category | null>\n findBySlug(tx: ReadTx, slug: string): Promise<Category | null>\n list(tx: ReadTx): Promise<Category[]>\n /** Rows by id after `page.after`: a walk over the table that a concurrent write cannot make skip a row. */\n listPage(tx: ReadTx, page: KeysetPage): Promise<Category[]>\n insert(tx: Tx, c: CategoryInsert): Promise<void>\n update(tx: Tx, id: string, patch: CategoryUpdate): Promise<void>\n delete(tx: Tx, id: string): Promise<void>\n}\n\nexport function createCategoryRepository(store: CommandStore): CategoryRepository {\n return {\n store,\n async findById(tx, id) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.categories)\n .where(eq(sqliteSchema.categories.id, id))\n .get()\n return row ? rowToCategory(row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.categories)\n .where(eq(postgresSchema.categories.id, id))\n return row ? rowToCategory(row as Record<string, unknown>) : null\n },\n async findBySlug(tx, slug) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.categories)\n .where(eq(sqliteSchema.categories.slug, slug))\n .get()\n return row ? rowToCategory(row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.categories)\n .where(eq(postgresSchema.categories.slug, slug))\n return row ? rowToCategory(row as Record<string, unknown>) : null\n },\n async listPage(tx, page) {\n if (tx.kind === 'sqlite') {\n const t = sqliteSchema.categories\n const rows = sqliteDb(tx)\n .select()\n .from(t)\n .where(page.after === undefined ? undefined : gt(t.id, page.after))\n .orderBy(asc(t.id))\n .limit(page.limit)\n .all()\n return rows.map((r) => rowToCategory(r as Record<string, unknown>))\n }\n const t = postgresSchema.categories\n const rows = await postgresDb(tx)\n .select()\n .from(t)\n .where(page.after === undefined ? undefined : gt(t.id, page.after))\n .orderBy(asc(t.id))\n .limit(page.limit)\n return rows.map((r) => rowToCategory(r as Record<string, unknown>))\n },\n async list(tx) {\n if (tx.kind === 'sqlite') {\n const rows = sqliteDb(tx).select().from(sqliteSchema.categories).all()\n return rows.map((r) => rowToCategory(r as Record<string, unknown>))\n }\n const rows = await postgresDb(tx).select().from(postgresSchema.categories)\n return rows.map((r) => rowToCategory(r as Record<string, unknown>))\n },\n async insert(tx, c) {\n const common = {\n id: c.id,\n parentId: c.parentId ?? null,\n slug: c.slug,\n name: c.name,\n description: c.description ?? '',\n position: c.position ?? 0,\n }\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.categories)\n .values({ ...common, createdAt: c.createdAt.toISOString() })\n .run()\n return\n }\n await postgresDb(tx)\n .insert(postgresSchema.categories)\n .values({ ...common, createdAt: c.createdAt })\n },\n async update(tx, id, patch) {\n const set: Record<string, unknown> = {}\n if (patch.parentId !== undefined) set.parentId = patch.parentId\n if (patch.name !== undefined) set.name = patch.name\n if (patch.description !== undefined) set.description = patch.description\n if (patch.position !== undefined) set.position = patch.position\n if (Object.keys(set).length === 0) return\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.categories)\n .set(set)\n .where(eq(sqliteSchema.categories.id, id))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.categories)\n .set(set)\n .where(eq(postgresSchema.categories.id, id))\n },\n async delete(tx, id) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx).delete(sqliteSchema.categories).where(eq(sqliteSchema.categories.id, id)).run()\n return\n }\n await postgresDb(tx)\n .delete(postgresSchema.categories)\n .where(eq(postgresSchema.categories.id, id))\n },\n }\n}\n","import { and, eq } from 'drizzle-orm'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\n\nexport interface ProductCategoryRepository extends StoreRepository {\n attach(tx: Tx, productId: string, categoryId: string): Promise<void>\n detach(tx: Tx, productId: string, categoryId: string): Promise<void>\n detachAllForProduct(tx: Tx, productId: string): Promise<void>\n listCategoriesForProduct(tx: ReadTx, productId: string): Promise<string[]>\n listProductsForCategory(tx: ReadTx, categoryId: string): Promise<string[]>\n}\n\nexport function createProductCategoryRepository(store: CommandStore): ProductCategoryRepository {\n return {\n store,\n async attach(tx, productId, categoryId) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.productCategories)\n .values({ productId, categoryId })\n .onConflictDoNothing()\n .run()\n return\n }\n await postgresDb(tx)\n .insert(postgresSchema.productCategories)\n .values({ productId, categoryId })\n .onConflictDoNothing()\n },\n async detach(tx, productId, categoryId) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .delete(sqliteSchema.productCategories)\n .where(\n and(\n eq(sqliteSchema.productCategories.productId, productId),\n eq(sqliteSchema.productCategories.categoryId, categoryId),\n ),\n )\n .run()\n return\n }\n await postgresDb(tx)\n .delete(postgresSchema.productCategories)\n .where(\n and(\n eq(postgresSchema.productCategories.productId, productId),\n eq(postgresSchema.productCategories.categoryId, categoryId),\n ),\n )\n },\n async detachAllForProduct(tx, productId) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .delete(sqliteSchema.productCategories)\n .where(eq(sqliteSchema.productCategories.productId, productId))\n .run()\n return\n }\n await postgresDb(tx)\n .delete(postgresSchema.productCategories)\n .where(eq(postgresSchema.productCategories.productId, productId))\n },\n async listCategoriesForProduct(tx, productId) {\n if (tx.kind === 'sqlite') {\n const rows = sqliteDb(tx)\n .select({ categoryId: sqliteSchema.productCategories.categoryId })\n .from(sqliteSchema.productCategories)\n .where(eq(sqliteSchema.productCategories.productId, productId))\n .all()\n return rows.map((r) => r.categoryId)\n }\n const rows = await postgresDb(tx)\n .select({ categoryId: postgresSchema.productCategories.categoryId })\n .from(postgresSchema.productCategories)\n .where(eq(postgresSchema.productCategories.productId, productId))\n return rows.map((r) => r.categoryId)\n },\n async listProductsForCategory(tx, categoryId) {\n if (tx.kind === 'sqlite') {\n const rows = sqliteDb(tx)\n .select({ productId: sqliteSchema.productCategories.productId })\n .from(sqliteSchema.productCategories)\n .where(eq(sqliteSchema.productCategories.categoryId, categoryId))\n .all()\n return rows.map((r) => r.productId)\n }\n const rows = await postgresDb(tx)\n .select({ productId: postgresSchema.productCategories.productId })\n .from(postgresSchema.productCategories)\n .where(eq(postgresSchema.productCategories.categoryId, categoryId))\n return rows.map((r) => r.productId)\n },\n }\n}\n","import { asc, eq, gt, sql } from 'drizzle-orm'\nimport type { Customer, CustomerAddress, Role } from '@nymbalhq/types'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport type { KeysetPage } from './page.js'\nimport { parseJson, fromTimestamp } from './json.js'\n\nexport interface CustomerInsert {\n id: string\n email: string\n passwordHash: string\n firstName?: string\n lastName?: string\n phone?: string\n addresses?: CustomerAddress[]\n metadata?: Record<string, unknown>\n /** Defaults to `['customer']`; only seed and admin code pass anything else. */\n roles?: Role[]\n requiresPasswordReset?: boolean\n createdAt: Date\n updatedAt: Date\n}\n\nexport interface CustomerUpdate {\n firstName?: string\n lastName?: string\n phone?: string\n addresses?: CustomerAddress[]\n metadata?: Record<string, unknown>\n passwordHash?: string\n requiresPasswordReset?: boolean\n updatedAt: Date\n}\n\nfunction rowToCustomer(\n store: CommandStore['kind'],\n row: Record<string, unknown>,\n): CustomerWithHash {\n return {\n id: String(row.id),\n email: String(row.email),\n passwordHash: String(row.passwordHash),\n firstName: String(row.firstName ?? ''),\n lastName: String(row.lastName ?? ''),\n phone: String(row.phone ?? ''),\n addresses: parseJson<CustomerAddress[]>(store, row.addresses, []),\n orderCount: Number(row.orderCount ?? 0),\n totalSpentMinor: Number(row.totalSpentMinor ?? 0),\n metadata: parseJson<Record<string, unknown>>(store, row.metadata, {}),\n roles: parseJson<Role[]>(store, row.roles, ['customer']),\n requiresPasswordReset: Boolean(row.requiresPasswordReset),\n createdAt: fromTimestamp(row.createdAt),\n updatedAt: fromTimestamp(row.updatedAt),\n }\n}\n\n/** A stored customer: its roles column is always read. */\nexport type CustomerWithHash = Customer & { passwordHash: string; roles: Role[] }\n\nexport interface CustomerRepository extends StoreRepository {\n findById(tx: ReadTx, id: string): Promise<CustomerWithHash | null>\n findByEmail(tx: ReadTx, email: string): Promise<CustomerWithHash | null>\n list(tx: ReadTx, opts?: { limit?: number; offset?: number }): Promise<CustomerWithHash[]>\n /** Rows by id after `page.after`: a walk over the table that a concurrent write cannot make skip a row. */\n listPage(tx: ReadTx, page: KeysetPage): Promise<CustomerWithHash[]>\n insert(tx: Tx, c: CustomerInsert): Promise<void>\n update(tx: Tx, id: string, patch: CustomerUpdate): Promise<void>\n incrementStats(\n tx: Tx,\n id: string,\n deltaOrders: number,\n deltaSpentMinor: number,\n updatedAt: Date,\n ): Promise<void>\n delete(tx: Tx, id: string): Promise<void>\n}\n\nexport function createCustomerRepository(store: CommandStore): CustomerRepository {\n return {\n store,\n async findById(tx, id) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.customers)\n .where(eq(sqliteSchema.customers.id, id))\n .get()\n return row ? rowToCustomer('sqlite', row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.customers)\n .where(eq(postgresSchema.customers.id, id))\n return row ? rowToCustomer('postgres', row as Record<string, unknown>) : null\n },\n async findByEmail(tx, email) {\n const normalized = email.toLowerCase()\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.customers)\n .where(eq(sqliteSchema.customers.email, normalized))\n .get()\n return row ? rowToCustomer('sqlite', row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.customers)\n .where(eq(postgresSchema.customers.email, normalized))\n return row ? rowToCustomer('postgres', row as Record<string, unknown>) : null\n },\n async listPage(tx, page) {\n if (tx.kind === 'sqlite') {\n const t = sqliteSchema.customers\n const rows = sqliteDb(tx)\n .select()\n .from(t)\n .where(page.after === undefined ? undefined : gt(t.id, page.after))\n .orderBy(asc(t.id))\n .limit(page.limit)\n .all()\n return rows.map((r) => rowToCustomer('sqlite', r as Record<string, unknown>))\n }\n const t = postgresSchema.customers\n const rows = await postgresDb(tx)\n .select()\n .from(t)\n .where(page.after === undefined ? undefined : gt(t.id, page.after))\n .orderBy(asc(t.id))\n .limit(page.limit)\n return rows.map((r) => rowToCustomer('postgres', r as Record<string, unknown>))\n },\n async list(tx, opts = {}) {\n const limit = opts.limit ?? 1000\n const offset = opts.offset ?? 0\n if (tx.kind === 'sqlite') {\n const rows = sqliteDb(tx)\n .select()\n .from(sqliteSchema.customers)\n .limit(limit)\n .offset(offset)\n .all()\n return rows.map((r) => rowToCustomer('sqlite', r as Record<string, unknown>))\n }\n const rows = await postgresDb(tx)\n .select()\n .from(postgresSchema.customers)\n .limit(limit)\n .offset(offset)\n return rows.map((r) => rowToCustomer('postgres', r as Record<string, unknown>))\n },\n async insert(tx, c) {\n const email = c.email.toLowerCase()\n const common = {\n id: c.id,\n email,\n passwordHash: c.passwordHash,\n firstName: c.firstName ?? '',\n lastName: c.lastName ?? '',\n phone: c.phone ?? '',\n orderCount: 0,\n totalSpentMinor: 0,\n requiresPasswordReset: c.requiresPasswordReset ?? false,\n }\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.customers)\n .values({\n ...common,\n addresses: JSON.stringify(c.addresses ?? []),\n metadata: JSON.stringify(c.metadata ?? {}),\n roles: JSON.stringify(c.roles ?? ['customer']),\n createdAt: c.createdAt.toISOString(),\n updatedAt: c.updatedAt.toISOString(),\n })\n .run()\n return\n }\n await postgresDb(tx)\n .insert(postgresSchema.customers)\n .values({\n ...common,\n addresses: c.addresses ?? [],\n metadata: c.metadata ?? {},\n roles: c.roles ?? ['customer'],\n createdAt: c.createdAt,\n updatedAt: c.updatedAt,\n })\n },\n async update(tx, id, patch) {\n const pg: Record<string, unknown> = { updatedAt: patch.updatedAt }\n const sq: Record<string, unknown> = { updatedAt: patch.updatedAt.toISOString() }\n for (const k of [\n 'firstName',\n 'lastName',\n 'phone',\n 'passwordHash',\n 'requiresPasswordReset',\n ] as const) {\n if (patch[k] !== undefined) {\n pg[k] = patch[k]\n sq[k] = patch[k]\n }\n }\n if (patch.addresses !== undefined) {\n pg.addresses = patch.addresses\n sq.addresses = JSON.stringify(patch.addresses)\n }\n if (patch.metadata !== undefined) {\n pg.metadata = patch.metadata\n sq.metadata = JSON.stringify(patch.metadata)\n }\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.customers)\n .set(sq)\n .where(eq(sqliteSchema.customers.id, id))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.customers)\n .set(pg)\n .where(eq(postgresSchema.customers.id, id))\n },\n async incrementStats(tx, id, deltaOrders, deltaSpent, updatedAt) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.customers)\n .set({\n orderCount: sql`${sqliteSchema.customers.orderCount} + ${deltaOrders}`,\n totalSpentMinor: sql`${sqliteSchema.customers.totalSpentMinor} + ${deltaSpent}`,\n updatedAt: updatedAt.toISOString(),\n })\n .where(eq(sqliteSchema.customers.id, id))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.customers)\n .set({\n orderCount: sql`${postgresSchema.customers.orderCount} + ${deltaOrders}`,\n totalSpentMinor: sql`${postgresSchema.customers.totalSpentMinor} + ${deltaSpent}`,\n updatedAt,\n })\n .where(eq(postgresSchema.customers.id, id))\n },\n async delete(tx, id) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx).delete(sqliteSchema.customers).where(eq(sqliteSchema.customers.id, id)).run()\n return\n }\n await postgresDb(tx)\n .delete(postgresSchema.customers)\n .where(eq(postgresSchema.customers.id, id))\n },\n }\n}\n","import { and, eq, isNull, lt } from 'drizzle-orm'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport { fromTimestamp } from './json.js'\n\nexport interface RefreshTokenInsert {\n id: string\n customerId: string\n tokenHash: string\n expiresAt: Date\n createdAt: Date\n}\n\nexport interface RefreshTokenRow {\n id: string\n customerId: string\n tokenHash: string\n revokedAt: string | null\n replacedByJti: string | null\n expiresAt: string\n createdAt: string\n}\n\nfunction rowToToken(row: Record<string, unknown>): RefreshTokenRow {\n return {\n id: String(row.id),\n customerId: String(row.customerId),\n tokenHash: String(row.tokenHash),\n revokedAt: row.revokedAt == null ? null : fromTimestamp(row.revokedAt),\n replacedByJti: (row.replacedByJti as string | null) ?? null,\n expiresAt: fromTimestamp(row.expiresAt),\n createdAt: fromTimestamp(row.createdAt),\n }\n}\n\nexport interface RefreshTokenRepository extends StoreRepository {\n insert(tx: Tx, t: RefreshTokenInsert): Promise<void>\n findById(tx: ReadTx, id: string): Promise<RefreshTokenRow | null>\n rotate(tx: Tx, oldJti: string, next: RefreshTokenInsert): Promise<void>\n revoke(tx: Tx, id: string): Promise<void>\n revokeAllForCustomer(tx: Tx, customerId: string): Promise<void>\n purgeExpired(tx: Tx, now: Date): Promise<number>\n}\n\nexport function createRefreshTokenRepository(store: CommandStore): RefreshTokenRepository {\n return {\n store,\n async insert(tx, t) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.refreshTokens)\n .values({\n id: t.id,\n customerId: t.customerId,\n tokenHash: t.tokenHash,\n revokedAt: null,\n replacedByJti: null,\n expiresAt: t.expiresAt.toISOString(),\n createdAt: t.createdAt.toISOString(),\n })\n .run()\n return\n }\n await postgresDb(tx).insert(postgresSchema.refreshTokens).values({\n id: t.id,\n customerId: t.customerId,\n tokenHash: t.tokenHash,\n revokedAt: null,\n replacedByJti: null,\n expiresAt: t.expiresAt,\n createdAt: t.createdAt,\n })\n },\n async findById(tx, id) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.refreshTokens)\n .where(eq(sqliteSchema.refreshTokens.id, id))\n .get()\n return row ? rowToToken(row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.refreshTokens)\n .where(eq(postgresSchema.refreshTokens.id, id))\n return row ? rowToToken(row as Record<string, unknown>) : null\n },\n async rotate(tx, oldJti, next) {\n if (tx.kind === 'sqlite') {\n const db = sqliteDb(tx)\n db.update(sqliteSchema.refreshTokens)\n .set({ revokedAt: new Date().toISOString(), replacedByJti: next.id })\n .where(eq(sqliteSchema.refreshTokens.id, oldJti))\n .run()\n db.insert(sqliteSchema.refreshTokens)\n .values({\n id: next.id,\n customerId: next.customerId,\n tokenHash: next.tokenHash,\n revokedAt: null,\n replacedByJti: null,\n expiresAt: next.expiresAt.toISOString(),\n createdAt: next.createdAt.toISOString(),\n })\n .run()\n return\n }\n const db = postgresDb(tx)\n await db\n .update(postgresSchema.refreshTokens)\n .set({ revokedAt: new Date(), replacedByJti: next.id })\n .where(eq(postgresSchema.refreshTokens.id, oldJti))\n await db.insert(postgresSchema.refreshTokens).values({\n id: next.id,\n customerId: next.customerId,\n tokenHash: next.tokenHash,\n revokedAt: null,\n replacedByJti: null,\n expiresAt: next.expiresAt,\n createdAt: next.createdAt,\n })\n },\n async revoke(tx, id) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.refreshTokens)\n .set({ revokedAt: new Date().toISOString() })\n .where(\n and(\n eq(sqliteSchema.refreshTokens.id, id),\n isNull(sqliteSchema.refreshTokens.revokedAt),\n ),\n )\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.refreshTokens)\n .set({ revokedAt: new Date() })\n .where(\n and(\n eq(postgresSchema.refreshTokens.id, id),\n isNull(postgresSchema.refreshTokens.revokedAt),\n ),\n )\n },\n async revokeAllForCustomer(tx, customerId) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.refreshTokens)\n .set({ revokedAt: new Date().toISOString() })\n .where(eq(sqliteSchema.refreshTokens.customerId, customerId))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.refreshTokens)\n .set({ revokedAt: new Date() })\n .where(eq(postgresSchema.refreshTokens.customerId, customerId))\n },\n async purgeExpired(tx, now) {\n if (tx.kind === 'sqlite') {\n const result = sqliteDb(tx)\n .delete(sqliteSchema.refreshTokens)\n .where(lt(sqliteSchema.refreshTokens.expiresAt, now.toISOString()))\n .run()\n return result.changes\n }\n const result = await postgresDb(tx)\n .delete(postgresSchema.refreshTokens)\n .where(lt(postgresSchema.refreshTokens.expiresAt, now))\n return result.rowCount ?? 0\n },\n }\n}\n","import { and, asc, desc, eq, gt, notInArray } from 'drizzle-orm'\nimport type { Address, CaptureMethod, Order, OrderLineItem, OrderStatus } from '@nymbalhq/types'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport type { KeysetPage } from './page.js'\nimport { parseJson, fromTimestamp } from './json.js'\n\nexport interface OrderInsert {\n id: string\n orderNumber: string\n sequence: number\n customerId: string | null\n status: OrderStatus\n email: string\n billingAddress: Address\n shippingAddress: Address\n lineItems: OrderLineItem[]\n subtotalMinor: number\n taxTotalMinor: number\n shippingTotalMinor: number\n discountTotalMinor: number\n totalMinor: number\n currency: string\n notes?: string\n metadata?: Record<string, unknown>\n paymentIntentId?: string | null\n /** The cart a checkout order was placed from. */\n cartToken?: string | null\n /** An imported order's money; a checkout order starts with nothing captured. */\n capture?: OrderCapture & { refundedMinor: number }\n createdAt: Date\n updatedAt: Date\n}\n\nexport interface OrderCapture {\n amountMinor: number\n method: CaptureMethod\n at: Date\n}\n\nfunction rowToOrder(store: CommandStore['kind'], row: Record<string, unknown>): Order {\n return {\n id: String(row.id),\n orderNumber: String(row.orderNumber),\n sequence: Number(row.sequence),\n customerId: (row.customerId as string | null) ?? null,\n status: row.status as OrderStatus,\n email: String(row.email),\n billingAddress: parseJson<Address>(store, row.billingAddress, {} as Address),\n shippingAddress: parseJson<Address>(store, row.shippingAddress, {} as Address),\n lineItems: parseJson<OrderLineItem[]>(store, row.lineItems, []),\n subtotalMinor: Number(row.subtotalMinor),\n taxTotalMinor: Number(row.taxTotalMinor ?? 0),\n shippingTotalMinor: Number(row.shippingTotalMinor ?? 0),\n discountTotalMinor: Number(row.discountTotalMinor ?? 0),\n totalMinor: Number(row.totalMinor),\n currency: String(row.currency),\n notes: String(row.notes ?? ''),\n metadata: parseJson<Record<string, unknown>>(store, row.metadata, {}),\n paymentIntentId: (row.paymentIntentId as string | null) ?? null,\n capturedMinor: Number(row.capturedMinor ?? 0),\n capturedAt: row.capturedAt == null ? null : fromTimestamp(row.capturedAt),\n refundedMinor: Number(row.refundedMinor ?? 0),\n captureMethod: (row.captureMethod as CaptureMethod | null) ?? null,\n createdAt: fromTimestamp(row.createdAt),\n updatedAt: fromTimestamp(row.updatedAt),\n }\n}\n\nexport interface OrderRepository extends StoreRepository {\n findById(tx: ReadTx, id: string): Promise<Order | null>\n /** The order, read under its row lock until the transaction ends (Postgres `FOR UPDATE`; on SQLite the open\n * `BEGIN IMMEDIATE` transaction already holds every write). */\n lock(tx: Tx, id: string): Promise<Order | null>\n findByOrderNumber(tx: ReadTx, orderNumber: string): Promise<Order | null>\n findByPaymentIntentId(tx: ReadTx, paymentIntentId: string): Promise<Order | null>\n /** The cart's pending order: at most one, by the partial unique index on `cart_token`. */\n findPendingByCartToken(tx: ReadTx, cartToken: string): Promise<Order | null>\n /** The newest order the cart became: neither pending nor cancelled. */\n findLastConvertedByCartToken(tx: ReadTx, cartToken: string): Promise<Order | null>\n listByCustomer(tx: ReadTx, customerId: string, limit?: number): Promise<Order[]>\n list(\n tx: ReadTx,\n opts?: { status?: OrderStatus; limit?: number; offset?: number },\n ): Promise<Order[]>\n /** Rows by id after `page.after`: a walk over the table that a concurrent write cannot make skip a row. */\n listPage(tx: ReadTx, page: KeysetPage): Promise<Order[]>\n insert(tx: Tx, o: OrderInsert): Promise<void>\n setStatus(tx: Tx, id: string, status: OrderStatus, updatedAt: Date): Promise<void>\n /** Sets `status` only while the order is still `from`; false when it was not, so a concurrent writer got there\n * first. */\n setStatusIf(\n tx: Tx,\n id: string,\n from: OrderStatus,\n status: OrderStatus,\n updatedAt: Date,\n ): Promise<boolean>\n setPaymentIntent(tx: Tx, id: string, paymentIntentId: string, updatedAt: Date): Promise<void>\n recordCapture(tx: Tx, id: string, capture: OrderCapture): Promise<void>\n setRefunded(tx: Tx, id: string, refundedMinor: number, updatedAt: Date): Promise<void>\n setNotes(tx: Tx, id: string, notes: string, updatedAt: Date): Promise<void>\n}\n\nexport function createOrderRepository(store: CommandStore): OrderRepository {\n return {\n store,\n async findById(tx, id) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.orders)\n .where(eq(sqliteSchema.orders.id, id))\n .get()\n return row ? rowToOrder('sqlite', row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.orders)\n .where(eq(postgresSchema.orders.id, id))\n return row ? rowToOrder('postgres', row as Record<string, unknown>) : null\n },\n async lock(tx, id) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.orders)\n .where(eq(sqliteSchema.orders.id, id))\n .get()\n return row ? rowToOrder('sqlite', row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.orders)\n .where(eq(postgresSchema.orders.id, id))\n .for('update')\n return row ? rowToOrder('postgres', row as Record<string, unknown>) : null\n },\n async findByOrderNumber(tx, orderNumber) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.orders)\n .where(eq(sqliteSchema.orders.orderNumber, orderNumber))\n .get()\n return row ? rowToOrder('sqlite', row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.orders)\n .where(eq(postgresSchema.orders.orderNumber, orderNumber))\n return row ? rowToOrder('postgres', row as Record<string, unknown>) : null\n },\n async findByPaymentIntentId(tx, paymentIntentId) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.orders)\n .where(eq(sqliteSchema.orders.paymentIntentId, paymentIntentId))\n .get()\n return row ? rowToOrder('sqlite', row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.orders)\n .where(eq(postgresSchema.orders.paymentIntentId, paymentIntentId))\n .limit(1)\n return row ? rowToOrder('postgres', row as Record<string, unknown>) : null\n },\n async findPendingByCartToken(tx, cartToken) {\n if (tx.kind === 'sqlite') {\n const o = sqliteSchema.orders\n const row = sqliteDb(tx)\n .select()\n .from(o)\n .where(and(eq(o.cartToken, cartToken), eq(o.status, 'pending')))\n .get()\n return row ? rowToOrder('sqlite', row as Record<string, unknown>) : null\n }\n const o = postgresSchema.orders\n const [row] = await postgresDb(tx)\n .select()\n .from(o)\n .where(and(eq(o.cartToken, cartToken), eq(o.status, 'pending')))\n return row ? rowToOrder('postgres', row as Record<string, unknown>) : null\n },\n async findLastConvertedByCartToken(tx, cartToken) {\n const unconverted = ['pending', 'cancelled'] as const\n if (tx.kind === 'sqlite') {\n const o = sqliteSchema.orders\n const row = sqliteDb(tx)\n .select()\n .from(o)\n .where(and(eq(o.cartToken, cartToken), notInArray(o.status, [...unconverted])))\n .orderBy(desc(o.sequence))\n .limit(1)\n .get()\n return row ? rowToOrder('sqlite', row as Record<string, unknown>) : null\n }\n const o = postgresSchema.orders\n const [row] = await postgresDb(tx)\n .select()\n .from(o)\n .where(and(eq(o.cartToken, cartToken), notInArray(o.status, [...unconverted])))\n .orderBy(desc(o.sequence))\n .limit(1)\n return row ? rowToOrder('postgres', row as Record<string, unknown>) : null\n },\n async listByCustomer(tx, customerId, limit = 50) {\n if (tx.kind === 'sqlite') {\n const rows = sqliteDb(tx)\n .select()\n .from(sqliteSchema.orders)\n .where(eq(sqliteSchema.orders.customerId, customerId))\n .orderBy(desc(sqliteSchema.orders.createdAt))\n .limit(limit)\n .all()\n return rows.map((r) => rowToOrder('sqlite', r as Record<string, unknown>))\n }\n const rows = await postgresDb(tx)\n .select()\n .from(postgresSchema.orders)\n .where(eq(postgresSchema.orders.customerId, customerId))\n .orderBy(desc(postgresSchema.orders.createdAt))\n .limit(limit)\n return rows.map((r) => rowToOrder('postgres', r as Record<string, unknown>))\n },\n async listPage(tx, page) {\n if (tx.kind === 'sqlite') {\n const t = sqliteSchema.orders\n const rows = sqliteDb(tx)\n .select()\n .from(t)\n .where(page.after === undefined ? undefined : gt(t.id, page.after))\n .orderBy(asc(t.id))\n .limit(page.limit)\n .all()\n return rows.map((r) => rowToOrder('sqlite', r as Record<string, unknown>))\n }\n const t = postgresSchema.orders\n const rows = await postgresDb(tx)\n .select()\n .from(t)\n .where(page.after === undefined ? undefined : gt(t.id, page.after))\n .orderBy(asc(t.id))\n .limit(page.limit)\n return rows.map((r) => rowToOrder('postgres', r as Record<string, unknown>))\n },\n async list(tx, opts = {}) {\n const limit = opts.limit ?? 100\n const offset = opts.offset ?? 0\n if (tx.kind === 'sqlite') {\n const base = sqliteDb(tx).select().from(sqliteSchema.orders)\n const filtered = opts.status\n ? base.where(eq(sqliteSchema.orders.status, opts.status))\n : base\n const rows = filtered\n .orderBy(desc(sqliteSchema.orders.createdAt))\n .limit(limit)\n .offset(offset)\n .all()\n return rows.map((r) => rowToOrder('sqlite', r as Record<string, unknown>))\n }\n const base = postgresDb(tx).select().from(postgresSchema.orders)\n const filtered = opts.status\n ? base.where(eq(postgresSchema.orders.status, opts.status))\n : base\n const rows = await filtered\n .orderBy(desc(postgresSchema.orders.createdAt))\n .limit(limit)\n .offset(offset)\n return rows.map((r) => rowToOrder('postgres', r as Record<string, unknown>))\n },\n async insert(tx, o) {\n const common = {\n id: o.id,\n orderNumber: o.orderNumber,\n sequence: o.sequence,\n customerId: o.customerId,\n status: o.status,\n email: o.email,\n subtotalMinor: o.subtotalMinor,\n taxTotalMinor: o.taxTotalMinor,\n shippingTotalMinor: o.shippingTotalMinor,\n discountTotalMinor: o.discountTotalMinor,\n totalMinor: o.totalMinor,\n currency: o.currency,\n notes: o.notes ?? '',\n paymentIntentId: o.paymentIntentId ?? null,\n cartToken: o.cartToken ?? null,\n capturedMinor: o.capture?.amountMinor ?? 0,\n refundedMinor: o.capture?.refundedMinor ?? 0,\n captureMethod: o.capture?.method ?? null,\n }\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.orders)\n .values({\n ...common,\n billingAddress: JSON.stringify(o.billingAddress),\n shippingAddress: JSON.stringify(o.shippingAddress),\n lineItems: JSON.stringify(o.lineItems),\n metadata: JSON.stringify(o.metadata ?? {}),\n capturedAt: o.capture?.at.toISOString() ?? null,\n createdAt: o.createdAt.toISOString(),\n updatedAt: o.updatedAt.toISOString(),\n })\n .run()\n return\n }\n await postgresDb(tx)\n .insert(postgresSchema.orders)\n .values({\n ...common,\n billingAddress: o.billingAddress,\n shippingAddress: o.shippingAddress,\n lineItems: o.lineItems,\n metadata: o.metadata ?? {},\n capturedAt: o.capture?.at ?? null,\n createdAt: o.createdAt,\n updatedAt: o.updatedAt,\n })\n },\n async setStatus(tx, id, status, updatedAt) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.orders)\n .set({ status, updatedAt: updatedAt.toISOString() })\n .where(eq(sqliteSchema.orders.id, id))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.orders)\n .set({ status, updatedAt })\n .where(eq(postgresSchema.orders.id, id))\n },\n async setStatusIf(tx, id, from, status, updatedAt) {\n if (tx.kind === 'sqlite') {\n const o = sqliteSchema.orders\n const { changes } = sqliteDb(tx)\n .update(o)\n .set({ status, updatedAt: updatedAt.toISOString() })\n .where(and(eq(o.id, id), eq(o.status, from)))\n .run()\n return changes > 0\n }\n const o = postgresSchema.orders\n const result = await postgresDb(tx)\n .update(o)\n .set({ status, updatedAt })\n .where(and(eq(o.id, id), eq(o.status, from)))\n return (result.rowCount ?? 0) > 0\n },\n async setPaymentIntent(tx, id, paymentIntentId, updatedAt) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.orders)\n .set({ paymentIntentId, updatedAt: updatedAt.toISOString() })\n .where(eq(sqliteSchema.orders.id, id))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.orders)\n .set({ paymentIntentId, updatedAt })\n .where(eq(postgresSchema.orders.id, id))\n },\n async recordCapture(tx, id, capture) {\n const values = {\n capturedMinor: capture.amountMinor,\n captureMethod: capture.method,\n }\n if (tx.kind === 'sqlite') {\n const at = capture.at.toISOString()\n sqliteDb(tx)\n .update(sqliteSchema.orders)\n .set({ ...values, capturedAt: at, updatedAt: at })\n .where(eq(sqliteSchema.orders.id, id))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.orders)\n .set({ ...values, capturedAt: capture.at, updatedAt: capture.at })\n .where(eq(postgresSchema.orders.id, id))\n },\n async setRefunded(tx, id, refundedMinor, updatedAt) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.orders)\n .set({ refundedMinor, updatedAt: updatedAt.toISOString() })\n .where(eq(sqliteSchema.orders.id, id))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.orders)\n .set({ refundedMinor, updatedAt })\n .where(eq(postgresSchema.orders.id, id))\n },\n async setNotes(tx, id, notes, updatedAt) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.orders)\n .set({ notes, updatedAt: updatedAt.toISOString() })\n .where(eq(sqliteSchema.orders.id, id))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.orders)\n .set({ notes, updatedAt })\n .where(eq(postgresSchema.orders.id, id))\n },\n }\n}\n","import { asc, eq } from 'drizzle-orm'\nimport type { OrderHistoryEntry, OrderStatus } from '@nymbalhq/types'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport { fromTimestamp } from './json.js'\n\nexport interface OrderHistoryInsert {\n id: string\n orderId: string\n fromStatus: OrderStatus | null\n toStatus: OrderStatus\n actor: string\n note?: string\n timestamp: Date\n}\n\nfunction rowToEntry(row: Record<string, unknown>): OrderHistoryEntry {\n return {\n id: String(row.id),\n orderId: String(row.orderId),\n fromStatus: (row.fromStatus as OrderStatus | null) ?? null,\n toStatus: row.toStatus as OrderStatus,\n actor: String(row.actor),\n note: String(row.note ?? ''),\n timestamp: fromTimestamp(row.timestamp),\n }\n}\n\nexport interface OrderHistoryRepository extends StoreRepository {\n append(tx: Tx, entry: OrderHistoryInsert): Promise<void>\n listByOrder(tx: ReadTx, orderId: string): Promise<OrderHistoryEntry[]>\n}\n\nexport function createOrderHistoryRepository(store: CommandStore): OrderHistoryRepository {\n return {\n store,\n async append(tx, entry) {\n const common = {\n id: entry.id,\n orderId: entry.orderId,\n fromStatus: entry.fromStatus,\n toStatus: entry.toStatus,\n actor: entry.actor,\n note: entry.note ?? '',\n }\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.orderHistory)\n .values({ ...common, timestamp: entry.timestamp.toISOString() })\n .run()\n return\n }\n await postgresDb(tx)\n .insert(postgresSchema.orderHistory)\n .values({ ...common, timestamp: entry.timestamp })\n },\n async listByOrder(tx, orderId) {\n if (tx.kind === 'sqlite') {\n const rows = sqliteDb(tx)\n .select()\n .from(sqliteSchema.orderHistory)\n .where(eq(sqliteSchema.orderHistory.orderId, orderId))\n .orderBy(asc(sqliteSchema.orderHistory.timestamp), asc(sqliteSchema.orderHistory.id))\n .all()\n return rows.map((r) => rowToEntry(r as Record<string, unknown>))\n }\n const rows = await postgresDb(tx)\n .select()\n .from(postgresSchema.orderHistory)\n .where(eq(postgresSchema.orderHistory.orderId, orderId))\n .orderBy(asc(postgresSchema.orderHistory.timestamp), asc(postgresSchema.orderHistory.id))\n return rows.map((r) => rowToEntry(r as Record<string, unknown>))\n },\n }\n}\n","import { and, asc, eq, inArray } from 'drizzle-orm'\nimport type { OrderRefund, OrderRefundStatus } from '@nymbalhq/types'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport { fromTimestamp } from './json.js'\n\nexport interface OrderRefundInsert {\n id: string\n orderId: string\n amountMinor: number\n currency: string\n providerRefundId: string | null\n status: OrderRefundStatus\n reason: string | null\n actor: string\n createdAt: Date\n /** The client's key for the request that made the refund; unique per order. */\n requestId?: string | null\n}\n\nfunction rowToRefund(row: Record<string, unknown>): OrderRefund {\n return {\n id: String(row.id),\n orderId: String(row.orderId),\n amountMinor: Number(row.amountMinor),\n currency: String(row.currency),\n providerRefundId: (row.providerRefundId as string | null) ?? null,\n status: row.status as OrderRefundStatus,\n reason: (row.reason as string | null) ?? null,\n actor: String(row.actor),\n createdAt: fromTimestamp(row.createdAt),\n }\n}\n\nexport interface OrderRefundRepository extends StoreRepository {\n insert(tx: Tx, refund: OrderRefundInsert): Promise<void>\n /** Settles a `pending` refund; false when the row is not pending (already settled). */\n settle(\n tx: Tx,\n id: string,\n outcome: { status: OrderRefundStatus; providerRefundId: string | null },\n ): Promise<boolean>\n /** The order's refund made by the request `requestId`, or null. */\n findByRequestId(tx: ReadTx, orderId: string, requestId: string): Promise<OrderRefund | null>\n /** The order's refunds, oldest first. */\n listByOrder(tx: ReadTx, orderId: string): Promise<OrderRefund[]>\n /** The refunds of each order, oldest first; an order without refunds is absent. */\n listByOrders(tx: ReadTx, orderIds: string[]): Promise<Map<string, OrderRefund[]>>\n}\n\nexport function createOrderRefundRepository(store: CommandStore): OrderRefundRepository {\n async function list(tx: ReadTx, orderIds: string[]): Promise<OrderRefund[]> {\n if (orderIds.length === 0) return []\n if (tx.kind === 'sqlite') {\n const r = sqliteSchema.orderRefunds\n const rows = sqliteDb(tx)\n .select()\n .from(r)\n .where(inArray(r.orderId, orderIds))\n .orderBy(asc(r.createdAt), asc(r.id))\n .all()\n return rows.map((row) => rowToRefund(row as Record<string, unknown>))\n }\n const r = postgresSchema.orderRefunds\n const rows = await postgresDb(tx)\n .select()\n .from(r)\n .where(inArray(r.orderId, orderIds))\n .orderBy(asc(r.createdAt), asc(r.id))\n return rows.map((row) => rowToRefund(row as Record<string, unknown>))\n }\n\n return {\n store,\n async insert(tx, refund) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.orderRefunds)\n .values({ ...refund, createdAt: refund.createdAt.toISOString() })\n .run()\n return\n }\n await postgresDb(tx).insert(postgresSchema.orderRefunds).values(refund)\n },\n async settle(tx, id, outcome) {\n if (tx.kind === 'sqlite') {\n const r = sqliteSchema.orderRefunds\n const { changes } = sqliteDb(tx)\n .update(r)\n .set(outcome)\n .where(and(eq(r.id, id), eq(r.status, 'pending')))\n .run()\n return changes > 0\n }\n const r = postgresSchema.orderRefunds\n const result = await postgresDb(tx)\n .update(r)\n .set(outcome)\n .where(and(eq(r.id, id), eq(r.status, 'pending')))\n return (result.rowCount ?? 0) > 0\n },\n async findByRequestId(tx, orderId, requestId) {\n if (tx.kind === 'sqlite') {\n const r = sqliteSchema.orderRefunds\n const row = sqliteDb(tx)\n .select()\n .from(r)\n .where(and(eq(r.orderId, orderId), eq(r.requestId, requestId)))\n .get()\n return row ? rowToRefund(row as Record<string, unknown>) : null\n }\n const r = postgresSchema.orderRefunds\n const [row] = await postgresDb(tx)\n .select()\n .from(r)\n .where(and(eq(r.orderId, orderId), eq(r.requestId, requestId)))\n return row ? rowToRefund(row as Record<string, unknown>) : null\n },\n listByOrder(tx, orderId) {\n return list(tx, [orderId])\n },\n async listByOrders(tx, orderIds) {\n const byOrder = new Map<string, OrderRefund[]>()\n for (const refund of await list(tx, orderIds)) {\n const refunds = byOrder.get(refund.orderId) ?? []\n refunds.push(refund)\n byOrder.set(refund.orderId, refunds)\n }\n return byOrder\n },\n }\n}\n","import { eq, sql } from 'drizzle-orm'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\n\nexport interface OrderSequenceRepository extends StoreRepository {\n nextSequence(tx: Tx, startFrom?: number): Promise<number>\n}\n\nexport function createOrderSequenceRepository(store: CommandStore): OrderSequenceRepository {\n return {\n store,\n async nextSequence(tx, startFrom = 1000): Promise<number> {\n if (tx.kind === 'sqlite') {\n const client = sqliteDb(tx)\n const row = client\n .select()\n .from(sqliteSchema.orderSequences)\n .where(eq(sqliteSchema.orderSequences.id, 1))\n .get()\n if (!row) {\n const next = startFrom + 1\n client.insert(sqliteSchema.orderSequences).values({ id: 1, nextValue: next }).run()\n return startFrom\n }\n const current = row.nextValue\n client\n .update(sqliteSchema.orderSequences)\n .set({ nextValue: current + 1 })\n .where(eq(sqliteSchema.orderSequences.id, 1))\n .run()\n return current\n }\n const client = postgresDb(tx)\n const [row] = await client\n .select()\n .from(postgresSchema.orderSequences)\n .where(eq(postgresSchema.orderSequences.id, 1))\n .for('update')\n if (!row) {\n const next = startFrom + 1\n await client.insert(postgresSchema.orderSequences).values({ id: 1, nextValue: next })\n return startFrom\n }\n const current = row.nextValue\n await client\n .update(postgresSchema.orderSequences)\n .set({ nextValue: sql`${postgresSchema.orderSequences.nextValue} + 1` })\n .where(eq(postgresSchema.orderSequences.id, 1))\n return current\n },\n }\n}\n","import { and, eq } from 'drizzle-orm'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\n\n/** Who minted the key: a checkout answer, or the order-placed email. */\nexport type OrderAccessKeyPurpose = 'checkout' | 'email'\n\nexport interface OrderAccessKeyInsert {\n id: string\n orderId: string\n /** sha256 hex of the key; the key itself is never stored. */\n keyHash: string\n purpose: OrderAccessKeyPurpose\n createdAt: Date\n}\n\nexport interface OrderAccessKeyRepository extends StoreRepository {\n insert(tx: Tx, k: OrderAccessKeyInsert): Promise<void>\n /** Whether a key with this hash opens this order: another order's key opens nothing here. */\n opens(tx: ReadTx, orderId: string, keyHash: string): Promise<boolean>\n}\n\nexport function createOrderAccessKeyRepository(store: CommandStore): OrderAccessKeyRepository {\n return {\n store,\n async insert(tx, k) {\n const row = { id: k.id, orderId: k.orderId, keyHash: k.keyHash, purpose: k.purpose }\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.orderAccessKeys)\n .values({ ...row, createdAt: k.createdAt.toISOString() })\n .run()\n return\n }\n await postgresDb(tx)\n .insert(postgresSchema.orderAccessKeys)\n .values({ ...row, createdAt: k.createdAt })\n },\n async opens(tx, orderId, keyHash) {\n if (tx.kind === 'sqlite') {\n const t = sqliteSchema.orderAccessKeys\n const row = sqliteDb(tx)\n .select({ id: t.id })\n .from(t)\n .where(and(eq(t.orderId, orderId), eq(t.keyHash, keyHash)))\n .get()\n return row !== undefined\n }\n const t = postgresSchema.orderAccessKeys\n const rows = await postgresDb(tx)\n .select({ id: t.id })\n .from(t)\n .where(and(eq(t.orderId, orderId), eq(t.keyHash, keyHash)))\n .limit(1)\n return rows.length > 0\n },\n }\n}\n","import { eq, lt } from 'drizzle-orm'\nimport type { InventoryReservation } from '@nymbalhq/types'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport { fromTimestamp } from './json.js'\n\nexport interface ReservationInsert {\n reservationId: string\n variantId: string\n qty: number\n orderRef?: string | null\n expiresAt: Date\n createdAt: Date\n}\n\nfunction rowToReservation(row: Record<string, unknown>): InventoryReservation {\n return {\n reservationId: String(row.reservationId),\n variantId: String(row.variantId),\n qty: Number(row.qty),\n orderRef: (row.orderRef as string | null) ?? null,\n expiresAt: fromTimestamp(row.expiresAt),\n createdAt: fromTimestamp(row.createdAt),\n }\n}\n\nexport interface InventoryReservationRepository extends StoreRepository {\n insert(tx: Tx, r: ReservationInsert): Promise<void>\n findById(tx: ReadTx, reservationId: string): Promise<InventoryReservation | null>\n findByVariant(tx: ReadTx, variantId: string): Promise<InventoryReservation[]>\n /** Deletes the reservation and returns the row it removed; null when none was there. Of two concurrent callers\n * only one gets the row, which is what makes a release and a commit of one reservation exclusive. */\n deleteById(tx: Tx, reservationId: string): Promise<InventoryReservation | null>\n /** Reservations whose expiry is before `at`; deletes nothing. */\n findExpiredBefore(tx: ReadTx, at: Date): Promise<InventoryReservation[]>\n setOrderRef(tx: Tx, reservationId: string, orderRef: string): Promise<void>\n}\n\nexport function createInventoryReservationRepository(\n store: CommandStore,\n): InventoryReservationRepository {\n return {\n store,\n async insert(tx, r) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.inventoryReservations)\n .values({\n reservationId: r.reservationId,\n variantId: r.variantId,\n qty: r.qty,\n orderRef: r.orderRef ?? null,\n expiresAt: r.expiresAt.toISOString(),\n createdAt: r.createdAt.toISOString(),\n })\n .run()\n return\n }\n await postgresDb(tx)\n .insert(postgresSchema.inventoryReservations)\n .values({\n reservationId: r.reservationId,\n variantId: r.variantId,\n qty: r.qty,\n orderRef: r.orderRef ?? null,\n expiresAt: r.expiresAt,\n createdAt: r.createdAt,\n })\n },\n async findById(tx, reservationId) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.inventoryReservations)\n .where(eq(sqliteSchema.inventoryReservations.reservationId, reservationId))\n .get()\n return row ? rowToReservation(row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.inventoryReservations)\n .where(eq(postgresSchema.inventoryReservations.reservationId, reservationId))\n return row ? rowToReservation(row as Record<string, unknown>) : null\n },\n async findByVariant(tx, variantId) {\n if (tx.kind === 'sqlite') {\n const rows = sqliteDb(tx)\n .select()\n .from(sqliteSchema.inventoryReservations)\n .where(eq(sqliteSchema.inventoryReservations.variantId, variantId))\n .all()\n return rows.map((r) => rowToReservation(r as Record<string, unknown>))\n }\n const rows = await postgresDb(tx)\n .select()\n .from(postgresSchema.inventoryReservations)\n .where(eq(postgresSchema.inventoryReservations.variantId, variantId))\n return rows.map((r) => rowToReservation(r as Record<string, unknown>))\n },\n async deleteById(tx, reservationId) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .delete(sqliteSchema.inventoryReservations)\n .where(eq(sqliteSchema.inventoryReservations.reservationId, reservationId))\n .returning()\n .get()\n return row ? rowToReservation(row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .delete(postgresSchema.inventoryReservations)\n .where(eq(postgresSchema.inventoryReservations.reservationId, reservationId))\n .returning()\n return row ? rowToReservation(row as Record<string, unknown>) : null\n },\n async findExpiredBefore(tx, at) {\n if (tx.kind === 'sqlite') {\n const rows = sqliteDb(tx)\n .select()\n .from(sqliteSchema.inventoryReservations)\n .where(lt(sqliteSchema.inventoryReservations.expiresAt, at.toISOString()))\n .all()\n return rows.map((r) => rowToReservation(r as Record<string, unknown>))\n }\n const rows = await postgresDb(tx)\n .select()\n .from(postgresSchema.inventoryReservations)\n .where(lt(postgresSchema.inventoryReservations.expiresAt, at))\n return rows.map((r) => rowToReservation(r as Record<string, unknown>))\n },\n async setOrderRef(tx, reservationId, orderRef) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.inventoryReservations)\n .set({ orderRef })\n .where(eq(sqliteSchema.inventoryReservations.reservationId, reservationId))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.inventoryReservations)\n .set({ orderRef })\n .where(eq(postgresSchema.inventoryReservations.reservationId, reservationId))\n },\n }\n}\n","import { desc, eq } from 'drizzle-orm'\nimport type { StockAdjustment, StockAdjustmentReason } from '@nymbalhq/types'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport { fromTimestamp } from './json.js'\n\nexport interface StockAdjustmentInsert {\n id: string\n variantId: string\n adjustment: number\n reason: StockAdjustmentReason\n actor: string\n previousQty: number\n newQty: number\n timestamp: Date\n}\n\nfunction rowToAdjustment(row: Record<string, unknown>): StockAdjustment {\n return {\n id: String(row.id),\n variantId: String(row.variantId),\n adjustment: Number(row.adjustment),\n reason: row.reason as StockAdjustmentReason,\n actor: String(row.actor),\n previousQty: Number(row.previousQty),\n newQty: Number(row.newQty),\n timestamp: fromTimestamp(row.timestamp),\n }\n}\n\nexport interface StockAdjustmentRepository extends StoreRepository {\n append(tx: Tx, a: StockAdjustmentInsert): Promise<void>\n listByVariant(tx: ReadTx, variantId: string, limit?: number): Promise<StockAdjustment[]>\n}\n\nexport function createStockAdjustmentRepository(store: CommandStore): StockAdjustmentRepository {\n return {\n store,\n async append(tx, a) {\n const common = {\n id: a.id,\n variantId: a.variantId,\n adjustment: a.adjustment,\n reason: a.reason,\n actor: a.actor,\n previousQty: a.previousQty,\n newQty: a.newQty,\n }\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.stockAdjustments)\n .values({ ...common, timestamp: a.timestamp.toISOString() })\n .run()\n return\n }\n await postgresDb(tx)\n .insert(postgresSchema.stockAdjustments)\n .values({ ...common, timestamp: a.timestamp })\n },\n async listByVariant(tx, variantId, limit = 100) {\n if (tx.kind === 'sqlite') {\n const rows = sqliteDb(tx)\n .select()\n .from(sqliteSchema.stockAdjustments)\n .where(eq(sqliteSchema.stockAdjustments.variantId, variantId))\n .orderBy(desc(sqliteSchema.stockAdjustments.timestamp))\n .limit(limit)\n .all()\n return rows.map((r) => rowToAdjustment(r as Record<string, unknown>))\n }\n const rows = await postgresDb(tx)\n .select()\n .from(postgresSchema.stockAdjustments)\n .where(eq(postgresSchema.stockAdjustments.variantId, variantId))\n .orderBy(desc(postgresSchema.stockAdjustments.timestamp))\n .limit(limit)\n return rows.map((r) => rowToAdjustment(r as Record<string, unknown>))\n },\n }\n}\n","import { and, desc, eq, lt, or, type SQL } from 'drizzle-orm'\nimport type { Review, ReviewModerationStatus } from '@nymbalhq/types'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport { fromTimestamp } from './json.js'\n\nexport interface ReviewInsert {\n id: string\n productId: string\n customerId: string | null\n orderId: string | null\n rating: number\n title: string\n body: string\n moderationStatus?: ReviewModerationStatus\n submittedAt: Date\n}\n\nfunction rowToReview(row: Record<string, unknown>): Review {\n return {\n id: String(row.id),\n productId: String(row.productId),\n customerId: (row.customerId as string | null) ?? null,\n orderId: (row.orderId as string | null) ?? null,\n rating: Number(row.rating),\n title: String(row.title ?? ''),\n body: String(row.body ?? ''),\n moderationStatus: row.moderationStatus as ReviewModerationStatus,\n submittedAt: fromTimestamp(row.submittedAt),\n moderatedAt: row.moderatedAt == null ? null : fromTimestamp(row.moderatedAt),\n moderatedBy: (row.moderatedBy as string | null) ?? null,\n }\n}\n\n/** Where a page of a product's reviews starts: after this review, in the newest-first, then id-descending order. */\nexport interface ReviewKey {\n submittedAt: string\n id: string\n}\n\nexport interface ReviewRepository extends StoreRepository {\n findById(tx: ReadTx, id: string): Promise<Review | null>\n /** Newest first, ties by id descending; `after` is the last review of the previous page. */\n listByProduct(\n tx: ReadTx,\n productId: string,\n status?: ReviewModerationStatus,\n limit?: number,\n after?: ReviewKey,\n ): Promise<Review[]>\n listByStatus(tx: ReadTx, status: ReviewModerationStatus, limit?: number): Promise<Review[]>\n insert(tx: Tx, r: ReviewInsert): Promise<void>\n setModerationStatus(\n tx: Tx,\n id: string,\n status: ReviewModerationStatus,\n moderatedBy: string,\n moderatedAt: Date,\n ): Promise<void>\n aggregateByProduct(\n tx: ReadTx,\n productId: string,\n ): Promise<{\n average: number\n count: number\n histogram: Record<'1' | '2' | '3' | '4' | '5', number>\n }>\n}\n\nexport function createReviewRepository(store: CommandStore): ReviewRepository {\n return {\n store,\n async findById(tx, id) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.reviews)\n .where(eq(sqliteSchema.reviews.id, id))\n .get()\n return row ? rowToReview(row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.reviews)\n .where(eq(postgresSchema.reviews.id, id))\n return row ? rowToReview(row as Record<string, unknown>) : null\n },\n async listByProduct(tx, productId, status, limit = 50, after) {\n if (tx.kind === 'sqlite') {\n const t = sqliteSchema.reviews\n const conds: SQL[] = [eq(t.productId, productId)]\n if (status) conds.push(eq(t.moderationStatus, status))\n if (after) {\n const at = new Date(after.submittedAt).toISOString()\n conds.push(or(lt(t.submittedAt, at), and(eq(t.submittedAt, at), lt(t.id, after.id)))!)\n }\n const rows = sqliteDb(tx)\n .select()\n .from(t)\n .where(and(...conds))\n .orderBy(desc(t.submittedAt), desc(t.id))\n .limit(limit)\n .all()\n return rows.map((r) => rowToReview(r as Record<string, unknown>))\n }\n const t = postgresSchema.reviews\n const conds: SQL[] = [eq(t.productId, productId)]\n if (status) conds.push(eq(t.moderationStatus, status))\n if (after) {\n const at = new Date(after.submittedAt)\n conds.push(or(lt(t.submittedAt, at), and(eq(t.submittedAt, at), lt(t.id, after.id)))!)\n }\n const rows = await postgresDb(tx)\n .select()\n .from(t)\n .where(and(...conds))\n .orderBy(desc(t.submittedAt), desc(t.id))\n .limit(limit)\n return rows.map((r) => rowToReview(r as Record<string, unknown>))\n },\n async listByStatus(tx, status, limit = 100) {\n if (tx.kind === 'sqlite') {\n const rows = sqliteDb(tx)\n .select()\n .from(sqliteSchema.reviews)\n .where(eq(sqliteSchema.reviews.moderationStatus, status))\n .orderBy(desc(sqliteSchema.reviews.submittedAt))\n .limit(limit)\n .all()\n return rows.map((r) => rowToReview(r as Record<string, unknown>))\n }\n const rows = await postgresDb(tx)\n .select()\n .from(postgresSchema.reviews)\n .where(eq(postgresSchema.reviews.moderationStatus, status))\n .orderBy(desc(postgresSchema.reviews.submittedAt))\n .limit(limit)\n return rows.map((r) => rowToReview(r as Record<string, unknown>))\n },\n async insert(tx, r) {\n const common = {\n id: r.id,\n productId: r.productId,\n customerId: r.customerId,\n orderId: r.orderId,\n rating: r.rating,\n title: r.title,\n body: r.body,\n moderationStatus: r.moderationStatus ?? 'pending',\n }\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.reviews)\n .values({\n ...common,\n submittedAt: r.submittedAt.toISOString(),\n moderatedAt: null,\n moderatedBy: null,\n })\n .run()\n return\n }\n await postgresDb(tx)\n .insert(postgresSchema.reviews)\n .values({\n ...common,\n submittedAt: r.submittedAt,\n moderatedAt: null,\n moderatedBy: null,\n })\n },\n async setModerationStatus(tx, id, status, moderatedBy, moderatedAt) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.reviews)\n .set({\n moderationStatus: status,\n moderatedBy,\n moderatedAt: moderatedAt.toISOString(),\n })\n .where(eq(sqliteSchema.reviews.id, id))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.reviews)\n .set({ moderationStatus: status, moderatedBy, moderatedAt })\n .where(eq(postgresSchema.reviews.id, id))\n },\n async aggregateByProduct(tx, productId) {\n const approved = await this.listByProduct(tx, productId, 'approved', 1000)\n const histogram: Record<'1' | '2' | '3' | '4' | '5', number> = {\n '1': 0,\n '2': 0,\n '3': 0,\n '4': 0,\n '5': 0,\n }\n let total = 0\n for (const r of approved) {\n const bucket = String(\n Math.max(1, Math.min(5, Math.round(r.rating))),\n ) as keyof typeof histogram\n histogram[bucket] += 1\n total += r.rating\n }\n const count = approved.length\n const average = count === 0 ? 0 : total / count\n return { average, count, histogram }\n },\n }\n}\n","import { and, eq, lt } from 'drizzle-orm'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\n\n/** Which handler has already run for which event id: what stops a side effect running twice, across restarts. */\nexport interface ProcessedEventRepository extends StoreRepository {\n seen(tx: ReadTx, handlerName: string, eventId: string): Promise<boolean>\n /** Idempotent on (handlerName, eventId): a second call keeps the first record. */\n markProcessed(tx: Tx, handlerName: string, eventId: string, at: Date): Promise<void>\n /**\n * Records (handlerName, eventId) before its work runs: true when this call inserted it, false when it was there.\n * On Postgres a concurrent claim of the same key waits for this transaction, so only one of them does the work.\n */\n claim(tx: Tx, handlerName: string, eventId: string, at: Date): Promise<boolean>\n /** Deletes records processed before `at`; returns how many. */\n deleteBefore(tx: Tx, at: Date): Promise<number>\n}\n\nexport function createProcessedEventRepository(store: CommandStore): ProcessedEventRepository {\n const s = sqliteSchema.processedEvents\n const p = postgresSchema.processedEvents\n return {\n store,\n async seen(tx, handlerName, eventId) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select({ eventId: s.eventId })\n .from(s)\n .where(and(eq(s.handlerName, handlerName), eq(s.eventId, eventId)))\n .get()\n return row !== undefined\n }\n const rows = await postgresDb(tx)\n .select({ eventId: p.eventId })\n .from(p)\n .where(and(eq(p.handlerName, handlerName), eq(p.eventId, eventId)))\n .limit(1)\n return rows.length > 0\n },\n async markProcessed(tx, handlerName, eventId, at) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(s)\n .values({ handlerName, eventId, processedAt: at.toISOString() })\n .onConflictDoNothing()\n .run()\n return\n }\n await postgresDb(tx)\n .insert(p)\n .values({ handlerName, eventId, processedAt: at })\n .onConflictDoNothing()\n },\n async claim(tx, handlerName, eventId, at) {\n if (tx.kind === 'sqlite') {\n const result = sqliteDb(tx)\n .insert(s)\n .values({ handlerName, eventId, processedAt: at.toISOString() })\n .onConflictDoNothing()\n .run()\n return result.changes > 0\n }\n const result = await postgresDb(tx)\n .insert(p)\n .values({ handlerName, eventId, processedAt: at })\n .onConflictDoNothing()\n return (result.rowCount ?? 0) > 0\n },\n async deleteBefore(tx, at) {\n if (tx.kind === 'sqlite') {\n return sqliteDb(tx).delete(s).where(lt(s.processedAt, at.toISOString())).run().changes\n }\n const result = await postgresDb(tx).delete(p).where(lt(p.processedAt, at))\n return result.rowCount ?? 0\n },\n }\n}\n","import {\n and,\n asc,\n eq,\n gt,\n gte,\n inArray,\n isNotNull,\n isNull,\n lt,\n lte,\n or,\n sql,\n type SQL,\n} from 'drizzle-orm'\nimport type { NymbalEvent } from '@nymbalhq/types'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport { subjectOf, type EventSubject } from '../history/subject.js'\n\nexport interface LoggedEvent {\n seq: number\n event: NymbalEvent<unknown>\n deliveredAt: Date | null\n attempts: number\n deadAt: Date | null\n createdAt: Date\n}\n\n/** Filters for reading the log. A type glob's `*` matches any run of characters, dots included (`order.*`). */\nexport interface EventLogFilter {\n /** Type globs; an event matches when its type matches any of them. */\n types?: string[]\n /** Appended at or after. */\n since?: Date\n /** Appended before. */\n until?: Date\n limit: number\n}\n\nexport interface EventLogRepository extends StoreRepository {\n /** Appends in array order, so `seq` follows publish order. */\n append(tx: Tx, events: NymbalEvent<unknown>[]): Promise<void>\n /**\n * Neither delivered nor dead, by `seq`; `afterSeq` pages through one pass without re-reading rows it just tried.\n * Given `now`, a row whose `retry_at` is after it is left out.\n */\n listUndelivered(tx: ReadTx, limit: number, afterSeq?: number, now?: Date): Promise<LoggedEvent[]>\n markDelivered(tx: Tx, ids: string[], at: Date): Promise<void>\n /**\n * One more failed attempt; the event is dead (`dead_at = at`) once its attempts reach `maxAttempts`. `retryAt`, when\n * given, is the earliest the next attempt may be made.\n */\n recordFailure(tx: Tx, id: string, at: Date, maxAttempts: number, retryAt?: Date): Promise<void>\n countDead(tx: ReadTx): Promise<number>\n /** Dead events, oldest first. */\n listDead(tx: ReadTx, limit: number): Promise<LoggedEvent[]>\n /** Neither delivered nor dead, with at least one failed attempt. */\n countRetrying(tx: ReadTx): Promise<number>\n /** Deletes delivered events delivered before `at`; returns how many. Undelivered and dead events are never deleted. */\n deleteDeliveredBefore(tx: Tx, at: Date): Promise<number>\n listAll(tx: ReadTx): Promise<LoggedEvent[]>\n /** One correlation id's events, by `seq`. */\n queryByCorrelation(\n tx: ReadTx,\n correlationId: string,\n filter: EventLogFilter,\n ): Promise<LoggedEvent[]>\n /** Events above `seq`, by `seq`. */\n listAfter(\n tx: ReadTx,\n seq: number,\n filter: Pick<EventLogFilter, 'types' | 'limit'>,\n ): Promise<LoggedEvent[]>\n /** The highest `seq` in the log, or 0 when it is empty. */\n maxSeq(tx: ReadTx): Promise<number>\n /**\n * What a read-model rebuild re-applies after its swap: every event that is not dead and was delivered at or after\n * `since`, or not yet delivered, by `seq`. `afterSeq` and `limit` page through them.\n */\n listForCatchUp(\n tx: ReadTx,\n since: Date,\n page?: { afterSeq?: number; limit?: number },\n ): Promise<LoggedEvent[]>\n /** Delivered events delivered before `at`, by `seq`: what retention may archive. Undelivered and dead events never are. */\n listDeliveredBefore(tx: ReadTx, at: Date, limit: number): Promise<LoggedEvent[]>\n /** Deletes the delivered events with these `seq`s; returns how many. */\n deleteSeqs(tx: Tx, seqs: number[]): Promise<number>\n /**\n * The events whose subject is one of `subjects`, by `seq`: those appended at or before `until`, above `afterSeq`, at\n * most `limit`.\n */\n listBySubjects(\n tx: ReadTx,\n subjects: EventSubject[],\n page: { until?: Date; afterSeq?: number; limit: number },\n ): Promise<LoggedEvent[]>\n}\n\n// SQLite's bound-parameter limit is per statement; seven columns a row keep a chunk well under it.\nconst APPEND_CHUNK = 100\nconst DELETE_CHUNK = 500\nconst APPEND_INTO =\n 'INSERT INTO events (id, type, envelope, correlation_id, subject_type, subject_id, created_at) VALUES'\n/** The page `listForCatchUp` reads when it is given none. */\nconst CATCH_UP_LIMIT = 10_000\n\n/** A type glob as a SQLite GLOB pattern: `*` stays the wildcard, and GLOB's other metacharacters match themselves. */\nfunction sqliteGlob(glob: string): string {\n return glob.replace(/[[?]/g, (c) => `[${c}]`)\n}\n\n/**\n * A type glob as a Postgres LIKE pattern with a backslash escape: `*` is `%`, and LIKE's own metacharacters match\n * themselves. Case-sensitive, as SQLite's GLOB is.\n */\nfunction likePattern(glob: string): string {\n return glob.replace(/[\\\\%_]/g, (c) => `\\\\${c}`).replace(/\\*/g, '%')\n}\n\nfunction subjectColumns(e: NymbalEvent<unknown>): {\n subjectType: string | null\n subjectId: string | null\n} {\n const subject = subjectOf(e)\n return { subjectType: subject?.type ?? null, subjectId: subject?.id ?? null }\n}\n\nfunction toDate(value: unknown): Date | null {\n if (value === null || value === undefined) return null\n return value instanceof Date ? value : new Date(String(value))\n}\n\nfunction rowToLogged(row: {\n seq: number\n envelope: unknown\n deliveredAt: unknown\n attempts: number\n deadAt: unknown\n createdAt: unknown\n}): LoggedEvent {\n const envelope =\n typeof row.envelope === 'string'\n ? (JSON.parse(row.envelope) as NymbalEvent<unknown>)\n : (row.envelope as NymbalEvent<unknown>)\n return {\n seq: Number(row.seq),\n event: envelope,\n deliveredAt: toDate(row.deliveredAt),\n attempts: Number(row.attempts),\n deadAt: toDate(row.deadAt),\n createdAt: toDate(row.createdAt)!,\n }\n}\n\nexport function createEventLogRepository(store: CommandStore): EventLogRepository {\n const s = sqliteSchema.events\n const p = postgresSchema.events\n // The columns `rowToLogged` reads.\n const sqliteLogged = {\n seq: s.seq,\n envelope: s.envelope,\n deliveredAt: s.deliveredAt,\n attempts: s.attempts,\n deadAt: s.deadAt,\n createdAt: s.createdAt,\n }\n const postgresLogged = {\n seq: p.seq,\n envelope: p.envelope,\n deliveredAt: p.deliveredAt,\n attempts: p.attempts,\n deadAt: p.deadAt,\n createdAt: p.createdAt,\n }\n\n function sqliteWhere(filter: Partial<EventLogFilter>): SQL[] {\n const where: SQL[] = []\n if (filter.types !== undefined && filter.types.length > 0) {\n where.push(or(...filter.types.map((t) => sql`${s.type} GLOB ${sqliteGlob(t)}`))!)\n }\n if (filter.since !== undefined) where.push(gte(s.createdAt, filter.since.toISOString()))\n if (filter.until !== undefined) where.push(lt(s.createdAt, filter.until.toISOString()))\n return where\n }\n\n function postgresWhere(filter: Partial<EventLogFilter>): SQL[] {\n const where: SQL[] = []\n if (filter.types !== undefined && filter.types.length > 0) {\n where.push(or(...filter.types.map((t) => sql`${p.type} LIKE ${likePattern(t)} ESCAPE '\\\\'`))!)\n }\n if (filter.since !== undefined) where.push(gte(p.createdAt, filter.since))\n if (filter.until !== undefined) where.push(lt(p.createdAt, filter.until))\n return where\n }\n\n /** Only the columns a LoggedEvent maps: a boot rebuild reads the log on a store not yet migrated past 0007. */\n async function select(\n tx: ReadTx,\n where: { sqlite: SQL[]; postgres: SQL[] },\n limit: number,\n ): Promise<LoggedEvent[]> {\n if (tx.kind === 'sqlite') {\n return sqliteDb(tx)\n .select(sqliteLogged)\n .from(s)\n .where(and(...where.sqlite))\n .orderBy(asc(s.seq))\n .limit(limit)\n .all()\n .map(rowToLogged)\n }\n const rows = await postgresDb(tx)\n .select(postgresLogged)\n .from(p)\n .where(and(...where.postgres))\n .orderBy(asc(p.seq))\n .limit(limit)\n return rows.map(rowToLogged)\n }\n\n return {\n store,\n // The columns are named, not taken from the schema: a store a migration behind, before a later column of the log\n // (retry_at), still takes appends.\n async append(tx, events) {\n const now = new Date()\n for (let i = 0; i < events.length; i += APPEND_CHUNK) {\n const chunk = events.slice(i, i + APPEND_CHUNK)\n const rows = (row: (e: NymbalEvent<unknown>) => SQL) => sql.join(chunk.map(row), sql`, `)\n if (tx.kind === 'sqlite') {\n const at = now.toISOString()\n sqliteDb(tx).run(\n sql`${sql.raw(APPEND_INTO)} ${rows((e) => {\n const { subjectType, subjectId } = subjectColumns(e)\n return sql`(${e.id}, ${e.type}, ${JSON.stringify(e)}, ${e.correlationId}, ${subjectType}, ${subjectId}, ${at})`\n })}`,\n )\n } else {\n await postgresDb(tx).execute(\n sql`${sql.raw(APPEND_INTO)} ${rows((e) => {\n const { subjectType, subjectId } = subjectColumns(e)\n return sql`(${e.id}, ${e.type}, ${JSON.stringify(e)}::jsonb, ${e.correlationId}, ${subjectType}, ${subjectId}, ${now.toISOString()}::timestamptz)`\n })}`,\n )\n }\n }\n },\n listUndelivered(tx, limit, afterSeq = 0, now) {\n return select(\n tx,\n {\n sqlite: [\n isNull(s.deliveredAt),\n isNull(s.deadAt),\n gt(s.seq, afterSeq),\n ...(now === undefined\n ? []\n : [or(isNull(s.retryAt), lte(s.retryAt, now.toISOString()))!]),\n ],\n postgres: [\n isNull(p.deliveredAt),\n isNull(p.deadAt),\n gt(p.seq, afterSeq),\n ...(now === undefined ? [] : [or(isNull(p.retryAt), lte(p.retryAt, now))!]),\n ],\n },\n limit,\n )\n },\n async markDelivered(tx, ids, at) {\n if (ids.length === 0) return\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(s)\n .set({ deliveredAt: at.toISOString() })\n .where(inArray(s.id, ids))\n .run()\n return\n }\n await postgresDb(tx).update(p).set({ deliveredAt: at }).where(inArray(p.id, ids))\n },\n async recordFailure(tx, id, at, maxAttempts, retryAt) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(s)\n .set({\n attempts: sql`${s.attempts} + 1`,\n deadAt: sql`CASE WHEN ${s.attempts} + 1 >= ${maxAttempts} THEN ${at.toISOString()} ELSE ${s.deadAt} END`,\n ...(retryAt !== undefined && { retryAt: retryAt.toISOString() }),\n })\n .where(eq(s.id, id))\n .run()\n return\n }\n await postgresDb(tx)\n .update(p)\n .set({\n attempts: sql`${p.attempts} + 1`,\n deadAt: sql`CASE WHEN ${p.attempts} + 1 >= ${maxAttempts} THEN ${at.toISOString()}::timestamptz ELSE ${p.deadAt} END`,\n ...(retryAt !== undefined && { retryAt }),\n })\n .where(eq(p.id, id))\n },\n async countDead(tx) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select({ n: sql<number>`count(*)` })\n .from(s)\n .where(isNotNull(s.deadAt))\n .get()\n return Number(row?.n ?? 0)\n }\n const [row] = await postgresDb(tx)\n .select({ n: sql<string>`count(*)` })\n .from(p)\n .where(isNotNull(p.deadAt))\n return Number(row?.n ?? 0)\n },\n listDead(tx, limit) {\n return select(tx, { sqlite: [isNotNull(s.deadAt)], postgres: [isNotNull(p.deadAt)] }, limit)\n },\n async countRetrying(tx) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select({ n: sql<number>`count(*)` })\n .from(s)\n .where(and(isNull(s.deliveredAt), isNull(s.deadAt), gt(s.attempts, 0)))\n .get()\n return Number(row?.n ?? 0)\n }\n const [row] = await postgresDb(tx)\n .select({ n: sql<string>`count(*)` })\n .from(p)\n .where(and(isNull(p.deliveredAt), isNull(p.deadAt), gt(p.attempts, 0)))\n return Number(row?.n ?? 0)\n },\n async deleteDeliveredBefore(tx, at) {\n if (tx.kind === 'sqlite') {\n const result = sqliteDb(tx)\n .delete(s)\n .where(and(isNotNull(s.deliveredAt), lt(s.deliveredAt, at.toISOString())))\n .run()\n return result.changes\n }\n const result = await postgresDb(tx)\n .delete(p)\n .where(and(isNotNull(p.deliveredAt), lt(p.deliveredAt, at)))\n return result.rowCount ?? 0\n },\n async listAll(tx) {\n if (tx.kind === 'sqlite') {\n return sqliteDb(tx).select(sqliteLogged).from(s).orderBy(asc(s.seq)).all().map(rowToLogged)\n }\n const rows = await postgresDb(tx).select(postgresLogged).from(p).orderBy(asc(p.seq))\n return rows.map(rowToLogged)\n },\n queryByCorrelation(tx, correlationId, filter) {\n return select(\n tx,\n {\n sqlite: [eq(s.correlationId, correlationId), ...sqliteWhere(filter)],\n postgres: [eq(p.correlationId, correlationId), ...postgresWhere(filter)],\n },\n filter.limit,\n )\n },\n listAfter(tx, seq, filter) {\n return select(\n tx,\n {\n sqlite: [gt(s.seq, seq), ...sqliteWhere(filter)],\n postgres: [gt(p.seq, seq), ...postgresWhere(filter)],\n },\n filter.limit,\n )\n },\n async maxSeq(tx) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select({ max: sql<number | null>`max(${s.seq})` })\n .from(s)\n .get()\n return Number(row?.max ?? 0)\n }\n const [row] = await postgresDb(tx)\n .select({ max: sql<string | null>`max(${p.seq})` })\n .from(p)\n return Number(row?.max ?? 0)\n },\n // Only the columns a LoggedEvent maps: a boot rebuild runs this on a store not yet migrated past 0007.\n async listForCatchUp(tx, since, page = {}) {\n const afterSeq = page.afterSeq ?? 0\n const limit = page.limit ?? CATCH_UP_LIMIT\n if (tx.kind === 'sqlite') {\n return sqliteDb(tx)\n .select(sqliteLogged)\n .from(s)\n .where(\n and(\n isNull(s.deadAt),\n or(isNull(s.deliveredAt), gte(s.deliveredAt, since.toISOString())),\n gt(s.seq, afterSeq),\n ),\n )\n .orderBy(asc(s.seq))\n .limit(limit)\n .all()\n .map(rowToLogged)\n }\n const rows = await postgresDb(tx)\n .select(postgresLogged)\n .from(p)\n .where(\n and(\n isNull(p.deadAt),\n or(isNull(p.deliveredAt), gte(p.deliveredAt, since)),\n gt(p.seq, afterSeq),\n ),\n )\n .orderBy(asc(p.seq))\n .limit(limit)\n return rows.map(rowToLogged)\n },\n listDeliveredBefore(tx, at, limit) {\n return select(\n tx,\n {\n sqlite: [isNull(s.deadAt), isNotNull(s.deliveredAt), lt(s.deliveredAt, at.toISOString())],\n postgres: [isNull(p.deadAt), isNotNull(p.deliveredAt), lt(p.deliveredAt, at)],\n },\n limit,\n )\n },\n async deleteSeqs(tx, seqs) {\n let deleted = 0\n for (let i = 0; i < seqs.length; i += DELETE_CHUNK) {\n const chunk = seqs.slice(i, i + DELETE_CHUNK)\n if (tx.kind === 'sqlite') {\n deleted += sqliteDb(tx)\n .delete(s)\n .where(and(inArray(s.seq, chunk), isNotNull(s.deliveredAt), isNull(s.deadAt)))\n .run().changes\n } else {\n const result = await postgresDb(tx)\n .delete(p)\n .where(and(inArray(p.seq, chunk), isNotNull(p.deliveredAt), isNull(p.deadAt)))\n deleted += result.rowCount ?? 0\n }\n }\n return deleted\n },\n async listBySubjects(tx, subjects, page) {\n if (subjects.length === 0) return []\n const afterSeq = page.afterSeq ?? 0\n return select(\n tx,\n {\n sqlite: [\n or(...subjects.map((x) => and(eq(s.subjectType, x.type), eq(s.subjectId, x.id))))!,\n gt(s.seq, afterSeq),\n ...(page.until === undefined ? [] : [lte(s.createdAt, page.until.toISOString())]),\n ],\n postgres: [\n or(...subjects.map((x) => and(eq(p.subjectType, x.type), eq(p.subjectId, x.id))))!,\n gt(p.seq, afterSeq),\n ...(page.until === undefined ? [] : [lte(p.createdAt, page.until)]),\n ],\n },\n page.limit,\n )\n },\n }\n}\n","import { EVT_PRODUCT_VIEWED, type NymbalEvent } from '@nymbalhq/types'\n\n/** The record an event is about: what `events.subject_type` and `events.subject_id` hold. */\nexport interface EventSubject {\n type: string\n id: string\n}\n\nfunction text(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined\n}\n\nfunction nestedId(value: unknown): string | undefined {\n return value !== null && typeof value === 'object'\n ? text((value as { id?: unknown }).id)\n : undefined\n}\n\n/**\n * Whose event this is, by its type's prefix and the payload path that names the record; null when the type names no\n * record or the payload lacks its id. Migration 0012's backfill mirrors this, rule for rule.\n */\nexport function subjectOf(\n envelope: Pick<NymbalEvent<unknown>, 'type' | 'payload'>,\n): EventSubject | null {\n const payload = (envelope.payload ?? {}) as Record<string, unknown>\n const type = envelope.type\n let subject: EventSubject['type'] | undefined\n let id: string | undefined\n // A shopper's view is no change to the product, so it is no row of the product's history.\n if (type === EVT_PRODUCT_VIEWED) return null\n if (type.startsWith('product.')) {\n subject = 'product'\n id = nestedId(payload['product']) ?? text(payload['productId'])\n } else if (type.startsWith('order.') || type.startsWith('payment.')) {\n subject = 'order'\n id = nestedId(payload['order']) ?? text(payload['orderId'])\n } else if (type.startsWith('customer.')) {\n subject = 'customer'\n id = text(payload['customerId'])\n } else if (type.startsWith('inventory.')) {\n subject = 'variant'\n id = text(payload['variantId'])\n }\n return subject === undefined || id === undefined ? null : { type: subject, id }\n}\n","import { and, asc, eq, gt, isNull, lt, lte, sql } from 'drizzle-orm'\nimport type { Cart, CartItem } from '@nymbalhq/types'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport { fromTimestamp, parseJson } from './json.js'\n\n/** What makes a cart due an abandonment notice at `at`: live, holding items, unwritten since `cutoff`, not yet\n * notified in this inactivity period. */\nexport interface AbandonedWindow {\n cutoff: Date\n at: Date\n}\n\nexport interface AbandonedCart {\n token: string\n /** The cart's last write. */\n lastActivityAt: string\n}\n\nexport interface CartRepository extends StoreRepository {\n findByToken(tx: ReadTx, token: string): Promise<Cart | null>\n /** `findByToken`, holding the row for the rest of the transaction so concurrent commands on the cart queue behind\n * this one (Postgres `FOR UPDATE`; SQLite's `BEGIN IMMEDIATE` already holds the database). */\n lock(tx: Tx, token: string): Promise<Cart | null>\n /** Inserts the cart, or replaces an expired row on its token. A live row on the token is left as it is and\n * returned with `created: false`. */\n create(tx: Tx, cart: Cart): Promise<{ cart: Cart; created: boolean }>\n /** Writes the cart whole and starts a new inactivity period (clears the abandonment claim). */\n put(tx: Tx, cart: Cart): Promise<void>\n remove(tx: Tx, token: string): Promise<void>\n /** Empties the cart if it is still live at `at`, in one conditional write; false when there was no live row to\n * empty (expired, or deleted by a sweep or a merge). Starts a new inactivity period; the expiry stays as it was. */\n clearIfLive(tx: Tx, token: string, at: Date): Promise<boolean>\n /** Deletes every cart whose expiry is at or before `at`; returns how many. */\n deleteExpired(tx: Tx, at: Date): Promise<number>\n /** Up to `limit` tokens due a notice, in token order after `after`; claims nothing. */\n listAbandoned(\n tx: ReadTx,\n window: AbandonedWindow,\n page: { after: string | undefined; limit: number },\n ): Promise<string[]>\n /** Marks the cart notified if it is still due a notice; null when it is not (another sweeper claimed it, or a\n * write, expiry or delete came first). */\n claimAbandoned(tx: Tx, token: string, window: AbandonedWindow): Promise<AbandonedCart | null>\n}\n\nfunction rowToCart(store: 'sqlite' | 'postgres', row: Record<string, unknown>): Cart {\n return {\n token: String(row.token),\n customerId: (row.customerId as string | null) ?? null,\n items: parseJson<CartItem[]>(store, row.items, []),\n subtotalMinor: Number(row.subtotalMinor),\n currency: String(row.currency),\n expiresAt: fromTimestamp(row.expiresAt),\n createdAt: fromTimestamp(row.createdAt),\n updatedAt: fromTimestamp(row.updatedAt),\n }\n}\n\nfunction sqliteValues(cart: Cart) {\n return {\n token: cart.token,\n customerId: cart.customerId,\n currency: cart.currency,\n items: JSON.stringify(cart.items),\n lineCount: cart.items.length,\n subtotalMinor: cart.subtotalMinor,\n expiresAt: cart.expiresAt,\n createdAt: cart.createdAt,\n updatedAt: cart.updatedAt,\n abandonedNotifiedAt: null,\n }\n}\n\nfunction postgresValues(cart: Cart) {\n return {\n token: cart.token,\n customerId: cart.customerId,\n currency: cart.currency,\n items: cart.items,\n lineCount: cart.items.length,\n subtotalMinor: cart.subtotalMinor,\n expiresAt: new Date(cart.expiresAt),\n createdAt: new Date(cart.createdAt),\n updatedAt: new Date(cart.updatedAt),\n abandonedNotifiedAt: null,\n }\n}\n\n/** Every column but the key, taken from the row being inserted (`excluded` in both dialects' upsert). */\nconst fromExcluded = {\n customerId: sql`excluded.customer_id`,\n currency: sql`excluded.currency`,\n items: sql`excluded.items`,\n lineCount: sql`excluded.line_count`,\n subtotalMinor: sql`excluded.subtotal_minor`,\n expiresAt: sql`excluded.expires_at`,\n createdAt: sql`excluded.created_at`,\n updatedAt: sql`excluded.updated_at`,\n abandonedNotifiedAt: sql`excluded.abandoned_notified_at`,\n}\n\nfunction sqliteDue(window: AbandonedWindow) {\n const t = sqliteSchema.carts\n return and(\n isNull(t.abandonedNotifiedAt),\n gt(t.lineCount, 0),\n lt(t.updatedAt, window.cutoff.toISOString()),\n gt(t.expiresAt, window.at.toISOString()),\n )\n}\n\nfunction postgresDue(window: AbandonedWindow) {\n const t = postgresSchema.carts\n return and(\n isNull(t.abandonedNotifiedAt),\n gt(t.lineCount, 0),\n lt(t.updatedAt, window.cutoff),\n gt(t.expiresAt, window.at),\n )\n}\n\nexport function createCartRepository(store: CommandStore): CartRepository {\n async function findByToken(tx: ReadTx, token: string): Promise<Cart | null> {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.carts)\n .where(eq(sqliteSchema.carts.token, token))\n .get()\n return row ? rowToCart('sqlite', row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.carts)\n .where(eq(postgresSchema.carts.token, token))\n return row ? rowToCart('postgres', row as Record<string, unknown>) : null\n }\n\n async function lock(tx: Tx, token: string): Promise<Cart | null> {\n if (tx.kind === 'sqlite') return findByToken(tx, token)\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.carts)\n .where(eq(postgresSchema.carts.token, token))\n .for('update')\n return row ? rowToCart('postgres', row as Record<string, unknown>) : null\n }\n\n return {\n store,\n findByToken,\n lock,\n async create(tx, cart) {\n let inserted: Record<string, unknown> | undefined\n if (tx.kind === 'sqlite') {\n inserted = sqliteDb(tx)\n .insert(sqliteSchema.carts)\n .values(sqliteValues(cart))\n .onConflictDoUpdate({\n target: sqliteSchema.carts.token,\n set: fromExcluded,\n setWhere: lte(sqliteSchema.carts.expiresAt, sql`excluded.updated_at`),\n })\n .returning()\n .get() as Record<string, unknown> | undefined\n } else {\n // A live row on the token makes the update a no-op, and `ON CONFLICT` waits for an insert in flight, so the\n // row read below is committed.\n ;[inserted] = await postgresDb(tx)\n .insert(postgresSchema.carts)\n .values(postgresValues(cart))\n .onConflictDoUpdate({\n target: postgresSchema.carts.token,\n set: fromExcluded,\n setWhere: lte(postgresSchema.carts.expiresAt, sql`excluded.updated_at`),\n })\n .returning()\n }\n if (inserted !== undefined) return { cart: rowToCart(tx.kind, inserted), created: true }\n const live = await lock(tx, cart.token)\n if (live === null) throw new Error(`cart ${cart.token} vanished while it was being created`)\n return { cart: live, created: false }\n },\n async put(tx, cart) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.carts)\n .values(sqliteValues(cart))\n .onConflictDoUpdate({ target: sqliteSchema.carts.token, set: fromExcluded })\n .run()\n return\n }\n await postgresDb(tx)\n .insert(postgresSchema.carts)\n .values(postgresValues(cart))\n .onConflictDoUpdate({ target: postgresSchema.carts.token, set: fromExcluded })\n },\n async remove(tx, token) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx).delete(sqliteSchema.carts).where(eq(sqliteSchema.carts.token, token)).run()\n return\n }\n await postgresDb(tx).delete(postgresSchema.carts).where(eq(postgresSchema.carts.token, token))\n },\n async clearIfLive(tx, token, at) {\n if (tx.kind === 'sqlite') {\n const t = sqliteSchema.carts\n const result = sqliteDb(tx)\n .update(t)\n .set({\n items: '[]',\n lineCount: 0,\n subtotalMinor: 0,\n updatedAt: at.toISOString(),\n abandonedNotifiedAt: null,\n })\n .where(and(eq(t.token, token), gt(t.expiresAt, at.toISOString())))\n .run()\n return result.changes > 0\n }\n // Under READ COMMITTED the update waits for a concurrent delete or write on the row and re-checks the condition\n // against what that one committed, so a row swept in between is skipped rather than reported missing.\n const t = postgresSchema.carts\n const rows = await postgresDb(tx)\n .update(t)\n .set({\n items: [],\n lineCount: 0,\n subtotalMinor: 0,\n updatedAt: at,\n abandonedNotifiedAt: null,\n })\n .where(and(eq(t.token, token), gt(t.expiresAt, at)))\n .returning({ token: t.token })\n return rows.length > 0\n },\n async deleteExpired(tx, at) {\n if (tx.kind === 'sqlite') {\n const result = sqliteDb(tx)\n .delete(sqliteSchema.carts)\n .where(lte(sqliteSchema.carts.expiresAt, at.toISOString()))\n .run()\n return result.changes\n }\n const rows = await postgresDb(tx)\n .delete(postgresSchema.carts)\n .where(lte(postgresSchema.carts.expiresAt, at))\n .returning({ token: postgresSchema.carts.token })\n return rows.length\n },\n async listAbandoned(tx, window, page) {\n if (tx.kind === 'sqlite') {\n const t = sqliteSchema.carts\n const rows = sqliteDb(tx)\n .select({ token: t.token })\n .from(t)\n .where(\n and(sqliteDue(window), page.after === undefined ? undefined : gt(t.token, page.after)),\n )\n .orderBy(asc(t.token))\n .limit(page.limit)\n .all()\n return rows.map((r) => r.token)\n }\n const t = postgresSchema.carts\n const rows = await postgresDb(tx)\n .select({ token: t.token })\n .from(t)\n .where(\n and(postgresDue(window), page.after === undefined ? undefined : gt(t.token, page.after)),\n )\n .orderBy(asc(t.token))\n .limit(page.limit)\n return rows.map((r) => r.token)\n },\n async claimAbandoned(tx, token, window) {\n if (tx.kind === 'sqlite') {\n const t = sqliteSchema.carts\n const row = sqliteDb(tx)\n .update(t)\n .set({ abandonedNotifiedAt: window.at.toISOString() })\n .where(and(eq(t.token, token), sqliteDue(window)))\n .returning({ token: t.token, updatedAt: t.updatedAt })\n .get()\n return row ? { token: row.token, lastActivityAt: fromTimestamp(row.updatedAt) } : null\n }\n // Under READ COMMITTED the update waits for a concurrent claim or write on the row and re-checks the condition\n // against what that one committed, so of two sweepers only one gets the row back.\n const t = postgresSchema.carts\n const [row] = await postgresDb(tx)\n .update(t)\n .set({ abandonedNotifiedAt: window.at })\n .where(and(eq(t.token, token), postgresDue(window)))\n .returning({ token: t.token, updatedAt: t.updatedAt })\n return row ? { token: row.token, lastActivityAt: fromTimestamp(row.updatedAt) } : null\n },\n }\n}\n","import { and, eq, inArray, sql } from 'drizzle-orm'\nimport type { AlertKind, AlertStatus } from '@nymbalhq/types'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\n\n/** A row of `alert_subscriptions`: one address's alert of one kind on one variant. */\nexport interface AlertSubscription {\n id: string\n /** Trimmed and lower-cased. */\n email: string\n kind: AlertKind\n variantId: string\n productId: string\n status: AlertStatus\n confirmToken: string\n unsubscribeToken: string\n /** The storefront origin its links point at. */\n origin: string\n baselinePriceMinor: number | null\n createdAt: Date\n updatedAt: Date\n confirmedAt: Date | null\n}\n\n/** A subscribe request: a new row's values, of which a row already there takes only what its status allows. */\nexport interface AlertSubscriptionRequest {\n id: string\n email: string\n kind: AlertKind\n variantId: string\n productId: string\n confirmToken: string\n unsubscribeToken: string\n origin: string\n /** A price-drop row's price at subscribe time; null for a back-in-stock row. */\n baselinePriceMinor: number | null\n at: Date\n}\n\nexport interface AlertSubscriptionPatch {\n status: AlertStatus\n updatedAt: Date\n confirmedAt?: Date\n /** The price a price-drop row was last told. */\n baselinePriceMinor?: number\n}\n\nexport interface AlertSubscriptionRepository extends StoreRepository {\n /**\n * One write on the unique (email, variant, kind): a new row is `pending`; a `pending` row takes the request's origin;\n * an `unsubscribed` or `fired` row returns to `pending` with the request's origin, confirm token and baseline (its\n * unsubscribe token is kept); an `active` row only has `updated_at` touched. Answers the row after the write.\n */\n upsertPending(tx: Tx, request: AlertSubscriptionRequest): Promise<AlertSubscription>\n findById(tx: ReadTx, id: string): Promise<AlertSubscription | null>\n findByConfirmToken(tx: ReadTx, token: string): Promise<AlertSubscription | null>\n findByUnsubscribeToken(tx: ReadTx, token: string): Promise<AlertSubscription | null>\n listActive(tx: ReadTx, variantId: string, kind: AlertKind): Promise<AlertSubscription[]>\n /** Applies `patch` when the row's status is one of `from`; the row after, or null when nothing changed. */\n update(\n tx: Tx,\n id: string,\n patch: AlertSubscriptionPatch,\n from: readonly AlertStatus[],\n ): Promise<AlertSubscription | null>\n}\n\ntype SqliteRow = typeof sqliteSchema.alertSubscriptions.$inferSelect\ntype PostgresRow = typeof postgresSchema.alertSubscriptions.$inferSelect\n\nfunction fromSqlite(row: SqliteRow): AlertSubscription {\n return {\n ...row,\n kind: row.kind as AlertKind,\n status: row.status as AlertStatus,\n createdAt: new Date(row.createdAt),\n updatedAt: new Date(row.updatedAt),\n confirmedAt: row.confirmedAt === null ? null : new Date(row.confirmedAt),\n }\n}\n\nfunction fromPostgres(row: PostgresRow): AlertSubscription {\n return { ...row, kind: row.kind as AlertKind, status: row.status as AlertStatus }\n}\n\nexport function createAlertSubscriptionRepository(\n store: CommandStore,\n): AlertSubscriptionRepository {\n const s = sqliteSchema.alertSubscriptions\n const p = postgresSchema.alertSubscriptions\n\n async function findOne(\n tx: ReadTx,\n where: (t: typeof s | typeof p) => ReturnType<typeof eq>,\n ): Promise<AlertSubscription | null> {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx).select().from(s).where(where(s)).get()\n return row === undefined ? null : fromSqlite(row)\n }\n const [row] = await postgresDb(tx).select().from(p).where(where(p)).limit(1)\n return row === undefined ? null : fromPostgres(row)\n }\n\n return {\n store,\n async upsertPending(tx, r) {\n const keep = (t: typeof s | typeof p) => sql`${t.status} = 'active'`\n const reissue = (t: typeof s | typeof p) => sql`${t.status} IN ('unsubscribed', 'fired')`\n const set = (t: typeof s | typeof p) => ({\n status: sql`CASE WHEN ${keep(t)} THEN ${t.status} ELSE 'pending' END`,\n origin: sql`CASE WHEN ${keep(t)} THEN ${t.origin} ELSE excluded.origin END`,\n confirmToken: sql`CASE WHEN ${reissue(t)} THEN excluded.confirm_token ELSE ${t.confirmToken} END`,\n baselinePriceMinor: sql`CASE WHEN ${reissue(t)} THEN excluded.baseline_price_minor ELSE ${t.baselinePriceMinor} END`,\n confirmedAt: sql`CASE WHEN ${keep(t)} THEN ${t.confirmedAt} ELSE NULL END`,\n updatedAt: sql`excluded.updated_at`,\n })\n const values = {\n id: r.id,\n email: r.email,\n kind: r.kind,\n variantId: r.variantId,\n productId: r.productId,\n status: 'pending' as const,\n confirmToken: r.confirmToken,\n unsubscribeToken: r.unsubscribeToken,\n origin: r.origin,\n baselinePriceMinor: r.baselinePriceMinor,\n confirmedAt: null,\n }\n if (tx.kind === 'sqlite') {\n const at = r.at.toISOString()\n const row = sqliteDb(tx)\n .insert(s)\n .values({ ...values, createdAt: at, updatedAt: at })\n .onConflictDoUpdate({ target: [s.email, s.variantId, s.kind], set: set(s) })\n .returning()\n .get()\n return fromSqlite(row)\n }\n const [row] = await postgresDb(tx)\n .insert(p)\n .values({ ...values, createdAt: r.at, updatedAt: r.at })\n .onConflictDoUpdate({ target: [p.email, p.variantId, p.kind], set: set(p) })\n .returning()\n return fromPostgres(row!)\n },\n findById: (tx, id) => findOne(tx, (t) => eq(t.id, id)),\n findByConfirmToken: (tx, token) => findOne(tx, (t) => eq(t.confirmToken, token)),\n findByUnsubscribeToken: (tx, token) => findOne(tx, (t) => eq(t.unsubscribeToken, token)),\n async listActive(tx, variantId, kind) {\n if (tx.kind === 'sqlite') {\n return sqliteDb(tx)\n .select()\n .from(s)\n .where(and(eq(s.variantId, variantId), eq(s.kind, kind), eq(s.status, 'active')))\n .orderBy(s.id)\n .all()\n .map(fromSqlite)\n }\n const rows = await postgresDb(tx)\n .select()\n .from(p)\n .where(and(eq(p.variantId, variantId), eq(p.kind, kind), eq(p.status, 'active')))\n .orderBy(p.id)\n return rows.map(fromPostgres)\n },\n async update(tx, id, patch, from) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .update(s)\n .set({\n status: patch.status,\n updatedAt: patch.updatedAt.toISOString(),\n ...(patch.confirmedAt !== undefined && {\n confirmedAt: patch.confirmedAt.toISOString(),\n }),\n ...(patch.baselinePriceMinor !== undefined && {\n baselinePriceMinor: patch.baselinePriceMinor,\n }),\n })\n .where(and(eq(s.id, id), inArray(s.status, [...from])))\n .returning()\n .get()\n return row === undefined ? null : fromSqlite(row)\n }\n const [row] = await postgresDb(tx)\n .update(p)\n .set({\n status: patch.status,\n updatedAt: patch.updatedAt,\n ...(patch.confirmedAt !== undefined && { confirmedAt: patch.confirmedAt }),\n ...(patch.baselinePriceMinor !== undefined && {\n baselinePriceMinor: patch.baselinePriceMinor,\n }),\n })\n .where(and(eq(p.id, id), inArray(p.status, [...from])))\n .returning()\n return row === undefined ? null : fromPostgres(row)\n },\n }\n}\n","import type { DocumentStoreAdapter } from '@nymbalhq/types'\nimport type { CommandStore } from '../db/command-store.js'\nimport { createProductRepository, type ProductRepository } from './product.js'\nimport { createVariantRepository, type VariantRepository } from './variant.js'\nimport { createCategoryRepository, type CategoryRepository } from './category.js'\nimport {\n createProductCategoryRepository,\n type ProductCategoryRepository,\n} from './product-category.js'\nimport { createCustomerRepository, type CustomerRepository } from './customer.js'\nimport { createRefreshTokenRepository, type RefreshTokenRepository } from './refresh-token.js'\nimport { createOrderRepository, type OrderRepository } from './order.js'\nimport { createOrderHistoryRepository, type OrderHistoryRepository } from './order-history.js'\nimport { createOrderRefundRepository, type OrderRefundRepository } from './order-refund.js'\nimport { createOrderSequenceRepository, type OrderSequenceRepository } from './order-sequence.js'\nimport {\n createOrderAccessKeyRepository,\n type OrderAccessKeyRepository,\n} from './order-access-key.js'\nimport {\n createInventoryReservationRepository,\n type InventoryReservationRepository,\n} from './inventory-reservation.js'\nimport {\n createStockAdjustmentRepository,\n type StockAdjustmentRepository,\n} from './stock-adjustment.js'\nimport { createReviewRepository, type ReviewRepository } from './review.js'\nimport { createProcessedEventRepository, type ProcessedEventRepository } from './processed-event.js'\nimport { createEventLogRepository, type EventLogRepository } from './event-log.js'\nimport { createCartRepository, type CartRepository } from './cart.js'\nimport { createSettingsRepository, type SettingsRepository } from './settings.js'\nimport { createAuditEntryRepository, type AuditEntryRepository } from './audit-entry.js'\nimport {\n createAlertSubscriptionRepository,\n type AlertSubscriptionRepository,\n} from './alert-subscription.js'\n\nexport * from './product.js'\nexport * from './variant.js'\nexport * from './category.js'\nexport * from './product-category.js'\nexport * from './customer.js'\nexport * from './refresh-token.js'\nexport * from './order.js'\nexport * from './order-history.js'\nexport * from './order-refund.js'\nexport * from './order-sequence.js'\nexport * from './order-access-key.js'\nexport * from './inventory-reservation.js'\nexport * from './stock-adjustment.js'\nexport * from './review.js'\nexport * from './processed-event.js'\nexport * from './event-log.js'\nexport * from './cart.js'\nexport * from './settings.js'\nexport * from './audit-entry.js'\nexport * from './alert-subscription.js'\nexport * from './page.js'\n\nexport interface Repositories {\n product: ProductRepository\n variant: VariantRepository\n category: CategoryRepository\n productCategory: ProductCategoryRepository\n customer: CustomerRepository\n refreshToken: RefreshTokenRepository\n order: OrderRepository\n orderHistory: OrderHistoryRepository\n orderRefund: OrderRefundRepository\n orderSequence: OrderSequenceRepository\n orderAccessKey: OrderAccessKeyRepository\n inventoryReservation: InventoryReservationRepository\n stockAdjustment: StockAdjustmentRepository\n review: ReviewRepository\n processedEvent: ProcessedEventRepository\n eventLog: EventLogRepository\n cart: CartRepository\n settings: SettingsRepository\n auditEntry: AuditEntryRepository\n alertSubscription: AlertSubscriptionRepository\n}\n\nexport function buildRepositories(\n commandStore: CommandStore,\n // Every repository is command-store backed; the parameter stays so existing callers keep compiling.\n _documentStore: DocumentStoreAdapter,\n): Repositories {\n return {\n product: createProductRepository(commandStore),\n variant: createVariantRepository(commandStore),\n category: createCategoryRepository(commandStore),\n productCategory: createProductCategoryRepository(commandStore),\n customer: createCustomerRepository(commandStore),\n refreshToken: createRefreshTokenRepository(commandStore),\n order: createOrderRepository(commandStore),\n orderHistory: createOrderHistoryRepository(commandStore),\n orderRefund: createOrderRefundRepository(commandStore),\n orderSequence: createOrderSequenceRepository(commandStore),\n orderAccessKey: createOrderAccessKeyRepository(commandStore),\n inventoryReservation: createInventoryReservationRepository(commandStore),\n stockAdjustment: createStockAdjustmentRepository(commandStore),\n review: createReviewRepository(commandStore),\n processedEvent: createProcessedEventRepository(commandStore),\n eventLog: createEventLogRepository(commandStore),\n cart: createCartRepository(commandStore),\n settings: createSettingsRepository(commandStore),\n auditEntry: createAuditEntryRepository(commandStore),\n alertSubscription: createAlertSubscriptionRepository(commandStore),\n }\n}\n","import { v7 as uuidv7 } from 'uuid'\nimport type { NymbalEvent, NymbalEnvironment } from '@nymbalhq/types'\n\nexport interface EventBuilderContext {\n storeId: string\n environment: NymbalEnvironment\n version: string\n source?: string\n}\n\nexport interface MakeEventOptions {\n source?: string\n correlationId?: string\n timestamp?: Date\n}\n\nexport function createEventBuilder(ctx: EventBuilderContext) {\n return function makeEvent<T>(\n type: string,\n payload: T,\n options: MakeEventOptions = {},\n ): NymbalEvent<T> {\n const id = uuidv7()\n return {\n id,\n type,\n timestamp: (options.timestamp ?? new Date()).toISOString(),\n source: options.source ?? ctx.source ?? 'nymbal-platform',\n correlationId: options.correlationId ?? id,\n payload,\n metadata: {\n storeId: ctx.storeId,\n environment: ctx.environment,\n version: ctx.version,\n },\n }\n }\n}\n","import type { EventBusAdapter, NymbalEvent, NymbalEventMap, NymbalEventType } from '@nymbalhq/types'\nimport { afterCommit, type CommandStore } from '../db/command-store.js'\nimport type { EventLogRepository } from '../repositories/event-log.js'\nimport { createEventBuilder, type EventBuilderContext, type MakeEventOptions } from './builder.js'\nimport { currentCorrelationId } from './correlation.js'\nimport type { Relay } from './relay.js'\n\nexport interface PublishOptions extends MakeEventOptions {}\n\nexport interface EventPublisher {\n publish<E extends NymbalEventType>(\n type: E,\n payload: NymbalEventMap[E],\n options?: PublishOptions,\n ): Promise<NymbalEvent<NymbalEventMap[E]>>\n publishMany(\n events: Array<\n {\n [E in NymbalEventType]: {\n type: E\n payload: NymbalEventMap[E]\n options?: PublishOptions\n }\n }[NymbalEventType]\n >,\n ): Promise<void>\n /**\n * Events of types the kernel does not declare (an adapter's own, already checked by the caller), with the same\n * append and drain as `publish`.\n */\n publishUntyped(\n events: ReadonlyArray<{ type: string; payload: unknown }>,\n options?: PublishOptions,\n ): Promise<NymbalEvent<unknown>[]>\n correlated(correlationId: string): EventPublisher\n}\n\nexport interface CreatePublisherOptions {\n eventBus: EventBusAdapter\n builderContext: EventBuilderContext\n /** Events are appended to `eventLog` on this store and reach the bus only through `relay`. */\n store: CommandStore\n eventLog: EventLogRepository\n relay: Relay\n correlationId?: string\n}\n\nexport function createEventPublisher(opts: CreatePublisherOptions): EventPublisher {\n const makeEvent = createEventBuilder(opts.builderContext)\n const { store, eventLog, relay } = opts\n\n /**\n * Appends in the open transaction (same COMMIT, gone on rollback) or in one of its own, and drains the relay once\n * the outermost transaction has committed; `afterCommit` holds one drain however many publishes the transaction\n * made.\n */\n async function append(events: NymbalEvent<unknown>[]): Promise<void> {\n if (events.length === 0) return\n await store.transaction(async (tx) => {\n await eventLog.append(tx, events)\n await afterCommit(relay.drain)\n })\n }\n\n function build<T>(type: string, payload: T, options: PublishOptions = {}): NymbalEvent<T> {\n // An explicit id, then a correlated() publisher's, then the scope's; with none, the event is its own id.\n const correlationId = options.correlationId ?? opts.correlationId ?? currentCorrelationId()\n return makeEvent(type, payload, {\n ...options,\n ...(correlationId !== undefined && { correlationId }),\n })\n }\n\n return {\n async publish(type, payload, options) {\n const event = build(type, payload, options ?? {})\n await append([event])\n return event\n },\n async publishMany(events) {\n await append(events.map((e) => build(e.type, e.payload, e.options ?? {})))\n },\n async publishUntyped(events, options) {\n const built = events.map((e) => build(e.type, e.payload, options ?? {}))\n await append(built)\n return built\n },\n correlated(correlationId) {\n return createEventPublisher({ ...opts, correlationId })\n },\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport type { EventBusAdapter, EventHandler, Logger } from '@nymbalhq/types'\nimport type { CommandStore } from '../db/command-store.js'\nimport type { EventLogRepository, LoggedEvent } from '../repositories/event-log.js'\nimport { outsideCorrelation } from './correlation.js'\nimport { outsideActor } from '../audit/actor.js'\nimport { outsideCommand } from '../audit/audit.js'\n\n/** Hands committed events from the log to the bus. */\nexport interface Relay {\n /** Delivers every undelivered, non-dead event in `seq` order. Never rejects. */\n drain(): Promise<void>\n /** Drains on an interval (the timer does not keep the process alive). */\n start(): void\n /** Stops the interval and starts no new pass; resolves when the pass in flight, if any, has finished, so the\n * store can be closed without cutting a delivery off between the handler and its bookkeeping. */\n stop(): Promise<void>\n /**\n * `handler`, run as part of a delivery: a drain it asks for (by running a command) returns at once instead of\n * waiting on the pass that waits on it. The app wraps every subscribed handler in it, so this holds whether the bus\n * calls the handler inside `publish` or from a consumer loop of its own.\n */\n asDelivery(handler: EventHandler): EventHandler\n}\n\nexport interface CreateRelayOptions {\n store: CommandStore\n eventLog: EventLogRepository\n eventBus: EventBusAdapter\n logger: Logger\n /** Failed bus publishes after which an event is dead and never handed to the bus again. */\n maxAttempts?: number\n intervalMs?: number\n /** The wait before the first retry of a failed event (default `intervalMs`); each later wait doubles it. */\n retryDelayMs?: number\n /** The clock failures and retry waits are read from. */\n now?: () => Date\n}\n\nconst PAGE_SIZE = 100\n\ninterface Deferred {\n promise: Promise<void>\n resolve(): void\n}\n\nfunction deferred(): Deferred {\n let resolve!: () => void\n const promise = new Promise<void>((r) => {\n resolve = r\n })\n return { promise, resolve }\n}\n\n/** The subscriptions a bus's `handler_failed` rejection names, for the relay's log lines. */\nfunction failedOf(err: unknown): { failed?: unknown[] } {\n const failed = (err as { context?: { failed?: unknown } } | null)?.context?.failed\n return Array.isArray(failed) ? { failed } : {}\n}\n\nexport function createRelay(opts: CreateRelayOptions): Relay {\n const { store, eventLog } = opts\n const maxAttempts = opts.maxAttempts ?? 5\n const intervalMs = opts.intervalMs ?? 10_000\n const retryDelayMs = opts.retryDelayMs ?? intervalMs\n const now = opts.now ?? (() => new Date())\n const logger = opts.logger.child({ component: 'event-relay' })\n // Set around each bus publish and each subscribed handler: a drain asked for by a subscriber (one that ran a\n // command) must not wait for the drain that is delivering to it.\n const delivering = new AsyncLocalStorage<true>()\n\n let active = false\n // Resolved when `active` turns false, i.e. after the last chained follow-up pass.\n let idle: Deferred | undefined\n let followUp: Deferred | undefined\n let timer: ReturnType<typeof setInterval> | undefined\n let stopped = false\n\n async function deliver({ event, attempts }: LoggedEvent): Promise<void> {\n try {\n // Looked up on every call: a wrapper installed on the bus instance after construction must see the event.\n await delivering.run(true, () => opts.eventBus.publish(event))\n } catch (err) {\n const at = now()\n const failures = attempts + 1\n // Backed off in the log, not in memory: every drain in between (each commit asks for one) and a restart see it.\n const retryAt = new Date(at.getTime() + retryDelayMs * 2 ** (failures - 1))\n await store.transaction((tx) =>\n eventLog.recordFailure(tx, event.id, at, maxAttempts, retryAt),\n )\n const context = {\n err,\n eventId: event.id,\n eventType: event.type,\n attempts: failures,\n ...failedOf(err),\n }\n if (failures >= maxAttempts) {\n logger.error(context, 'event delivery failed for the last time; the event is dead')\n } else {\n logger.warn(\n { ...context, retryAt: retryAt.toISOString() },\n 'event delivery failed; the event stays in the log and is tried again from retryAt',\n )\n }\n return\n }\n await store.transaction((tx) => eventLog.markDelivered(tx, [event.id], new Date()))\n }\n\n /** One pass over the log. The cursor only spans this pass: a row that commits behind it is left for the next\n * pass, which the committing transaction requests. */\n async function pass(): Promise<void> {\n try {\n let afterSeq = 0\n for (;;) {\n if (stopped) return\n const page = await store.read((tx) =>\n eventLog.listUndelivered(tx, PAGE_SIZE, afterSeq, now()),\n )\n for (const logged of page) {\n if (stopped) return\n afterSeq = logged.seq\n await deliver(logged)\n }\n if (page.length < PAGE_SIZE) return\n }\n } catch (err) {\n logger.error({ err }, 'event relay pass failed; undelivered events stay in the log')\n }\n }\n\n async function run(): Promise<void> {\n active = true\n try {\n await pass()\n } finally {\n const next = followUp\n followUp = undefined\n if (next === undefined) {\n active = false\n idle?.resolve()\n idle = undefined\n } else {\n // Still active: nothing can start a second pass alongside this one.\n void run().then(next.resolve)\n }\n }\n }\n\n function request(): Promise<void> {\n if (!active) {\n idle = deferred()\n // A pass delivers every operation's events, not only the requester's: its handlers run in no scope of the caller,\n // neither its correlation id nor its actor and command, so a handler's writes are never the caller's entry.\n return outsideCorrelation(() => outsideActor(() => outsideCommand(run)))\n }\n followUp ??= deferred()\n return followUp.promise\n }\n\n return {\n drain() {\n if (stopped) return Promise.resolve()\n const done = request()\n return delivering.getStore() === true ? Promise.resolve() : done\n },\n start() {\n if (timer !== undefined) return\n stopped = false\n timer = setInterval(() => void request(), intervalMs)\n timer.unref()\n },\n stop() {\n stopped = true\n if (timer !== undefined) clearInterval(timer)\n timer = undefined\n // A subscriber that stops the app would otherwise wait on the pass that is waiting on it.\n if (delivering.getStore() === true) return Promise.resolve()\n return idle?.promise ?? Promise.resolve()\n },\n asDelivery(handler) {\n return (event) => delivering.run(true, () => handler(event))\n },\n }\n}\n\n/**\n * The bus as subscribers see it: every handler runs as part of a relay delivery, so a command it runs does not wait\n * on the drain that is waiting on the handler, whether the bus calls it inside `publish` or from a consumer loop.\n */\nexport function deliveringBus(bus: EventBusAdapter, relay: Relay): EventBusAdapter {\n return {\n capabilities: () => bus.capabilities(),\n publish: (event) => bus.publish(event),\n publishBatch: (events) => bus.publishBatch(events),\n replay: (events) => bus.replay(events),\n subscribe: (pattern, handler, config) =>\n bus.subscribe(pattern, relay.asDelivery(handler), config),\n unsubscribe: (subscription) => bus.unsubscribe(subscription),\n close: () => bus.close(),\n }\n}\n","import type { EventHandler, Logger, NymbalEvent } from '@nymbalhq/types'\nimport type { ProcessedEventRepository } from '../repositories/processed-event.js'\n\nexport interface IdempotencyOptions {\n repo: ProcessedEventRepository\n logger?: Logger\n}\n\nexport function withIdempotency<T = unknown>(\n handlerName: string,\n handler: EventHandler<T>,\n { repo, logger }: IdempotencyOptions,\n): EventHandler<T> {\n return async (event: NymbalEvent<T>) => {\n const { store } = repo\n if (await store.read((tx) => repo.seen(tx, handlerName, event.id))) {\n logger?.debug(\n { handlerName, eventId: event.id, type: event.type },\n 'idempotency: skipping duplicate event',\n )\n return\n }\n await handler(event)\n await store.transaction((tx) => repo.markProcessed(tx, handlerName, event.id, new Date()))\n }\n}\n","import {\n EVT_CATEGORY_CREATED,\n EVT_CATEGORY_DELETED,\n EVT_CATEGORY_UPDATED,\n type CategoryCreatedV1Payload,\n type CategoryDeletedV1Payload,\n type CategoryUpdatedV1Payload,\n type DocumentStoreAdapter,\n type EventBusAdapter,\n type EventHandler,\n type Logger,\n} from '@nymbalhq/types'\nimport type { Repositories } from '../../repositories/index.js'\nimport { buildCategoryDoc, CATEGORIES } from '../../read-models/builders.js'\nimport { subscribeDerived, type DerivedHandler } from '../derived.js'\n\nexport interface CategoryProjectionDeps {\n documentStore: DocumentStoreAdapter\n logger: Logger\n storeId: string\n repos: Pick<Repositories, 'category'>\n}\n\nexport interface RegisterCategoryProjectionDeps extends CategoryProjectionDeps {\n eventBus: EventBusAdapter\n}\n\n/**\n * The `categories` documents, built from the category row read at handle time: a re-applied old delivery then writes\n * what a rebuild writes, not the payload it carried.\n */\nexport function categoryProjection(deps: CategoryProjectionDeps): DerivedHandler[] {\n const { documentStore, logger, storeId, repos } = deps\n\n const onUpsert: EventHandler<CategoryCreatedV1Payload | CategoryUpdatedV1Payload> = async (\n event,\n ) => {\n const { id, slug } = event.payload.category\n const category = await repos.category.store.read((tx) => repos.category.findById(tx, id))\n if (!category) {\n // The slug may since have gone to another category, whose document stays.\n const stored = await documentStore.get<{ id: string }>(CATEGORIES, slug)\n if (stored?.id === id) await documentStore.delete(CATEGORIES, slug)\n logger.debug({ slug, eventType: event.type }, 'category gone; projection deleted')\n return\n }\n await documentStore.put(CATEGORIES, category.slug, buildCategoryDoc(category, storeId))\n logger.debug({ slug: category.slug, eventType: event.type }, 'category projected')\n }\n\n const onDeleted: EventHandler<CategoryDeletedV1Payload> = async (event) => {\n await documentStore.delete(CATEGORIES, event.payload.slug)\n logger.debug({ slug: event.payload.slug }, 'category projection deleted')\n }\n\n return [\n {\n name: 'category-projection-upsert',\n types: [EVT_CATEGORY_CREATED, EVT_CATEGORY_UPDATED],\n handle: onUpsert as EventHandler,\n },\n {\n name: 'category-projection-delete',\n types: [EVT_CATEGORY_DELETED],\n handle: onDeleted as EventHandler,\n },\n ]\n}\n\nexport async function registerCategoryProjection(\n deps: RegisterCategoryProjectionDeps,\n): Promise<void> {\n await subscribeDerived(deps.eventBus, categoryProjection(deps))\n}\n","import {\n EVT_CATEGORY_CREATED,\n EVT_CATEGORY_DELETED,\n EVT_CATEGORY_UPDATED,\n EVT_PRODUCT_CREATED,\n EVT_PRODUCT_DELETED,\n EVT_PRODUCT_UPDATED,\n type CategoryCreatedV1Payload,\n type CategoryDeletedV1Payload,\n type CategoryUpdatedV1Payload,\n type DocumentStoreAdapter,\n type EventBusAdapter,\n type EventHandler,\n type Logger,\n type ProductCreatedV1Payload,\n type ProductDeletedV1Payload,\n type ProductUpdatedV1Payload,\n} from '@nymbalhq/types'\nimport type { Repositories } from '../../repositories/index.js'\nimport {\n buildProductDoc,\n productByCategoryKey,\n productWrites,\n PRODUCTS,\n PRODUCTS_BY_CATEGORY,\n type DenormalisedProduct,\n} from '../../read-models/builders.js'\nimport { loadProduct } from '../../read-models/sources.js'\nimport { subscribeDerived, type DerivedHandler } from '../derived.js'\n\nexport type { DenormalisedProduct } from '../../read-models/builders.js'\n\nexport interface ProductProjectionDeps {\n documentStore: DocumentStoreAdapter\n logger: Logger\n storeId: string\n currency: string\n repos: Pick<Repositories, 'product' | 'variant' | 'category' | 'productCategory'>\n}\n\nexport interface RegisterProductProjectionDeps extends ProductProjectionDeps {\n eventBus: EventBusAdapter\n}\n\nexport interface ProductReprojector {\n /** Rebuilds the product's documents from its rows as they are now; a product that is gone is left to its delete. */\n reproject(productId: string): Promise<void>\n /** Removes the product's documents, by slug. */\n remove(slug: string): Promise<void>\n}\n\n/**\n * Writes `products` and `products-by-category` from the product's rows, read at handle time, so any event about a\n * product, its stock or one of its categories leaves the documents a rebuild writes.\n */\nexport function productReprojector(deps: ProductProjectionDeps): ProductReprojector {\n const { documentStore, logger, storeId, currency, repos } = deps\n\n /** The category keys the stored document was filed under. */\n async function filedUnder(slug: string): Promise<string[]> {\n const existing = await documentStore.get<DenormalisedProduct>(PRODUCTS, slug)\n return (existing?.categories ?? []).map((c) => productByCategoryKey(c.slug, slug))\n }\n\n return {\n async reproject(productId) {\n const loaded = await repos.product.store.read((tx) => loadProduct(tx, repos, productId))\n if (!loaded) return\n const doc = buildProductDoc(loaded.snapshot, loaded.categories, { storeId, currency, logger })\n const writes = productWrites(doc)\n const kept = new Set(writes.map((w) => w.key))\n const stale = (await filedUnder(doc.slug)).filter((key) => !kept.has(key))\n for (const w of writes) await documentStore.put(w.collection, w.key, w.doc)\n for (const key of stale) await documentStore.delete(PRODUCTS_BY_CATEGORY, key)\n logger.debug({ slug: doc.slug }, 'product projected')\n },\n async remove(slug) {\n for (const key of await filedUnder(slug)) {\n await documentStore.delete(PRODUCTS_BY_CATEGORY, key)\n }\n await documentStore.delete(PRODUCTS, slug)\n logger.debug({ slug }, 'product projection deleted')\n },\n }\n}\n\nexport function productProjection(deps: ProductProjectionDeps): DerivedHandler[] {\n const products = productReprojector(deps)\n const { repos } = deps\n\n const onUpsert: EventHandler<ProductCreatedV1Payload | ProductUpdatedV1Payload> = (event) =>\n products.reproject(event.payload.product.id)\n\n const onDelete: EventHandler<ProductDeletedV1Payload> = (event) =>\n products.remove(event.payload.slug)\n\n // A category's name and slug are in its products' documents, and its slug in their category keys.\n const onCategory: EventHandler<\n CategoryCreatedV1Payload | CategoryUpdatedV1Payload | CategoryDeletedV1Payload\n > = async (event) => {\n const payload = event.payload\n const categoryId = 'category' in payload ? payload.category.id : payload.categoryId\n const productIds = await repos.productCategory.store.read((tx) =>\n repos.productCategory.listProductsForCategory(tx, categoryId),\n )\n for (const productId of productIds) await products.reproject(productId)\n }\n\n return [\n {\n name: 'product-projection-upsert',\n types: [EVT_PRODUCT_CREATED, EVT_PRODUCT_UPDATED],\n handle: onUpsert as EventHandler,\n },\n {\n name: 'product-projection-delete',\n types: [EVT_PRODUCT_DELETED],\n handle: onDelete as EventHandler,\n },\n {\n name: 'product-projection-category',\n types: [EVT_CATEGORY_CREATED, EVT_CATEGORY_UPDATED, EVT_CATEGORY_DELETED],\n handle: onCategory as EventHandler,\n },\n ]\n}\n\nexport async function registerProductProjection(\n deps: RegisterProductProjectionDeps,\n): Promise<void> {\n await subscribeDerived(deps.eventBus, productProjection(deps))\n}\n","import type { Category, Product, ProductSnapshot } from '@nymbalhq/types'\nimport type { ReadTx } from '../db/command-store.js'\nimport type { Repositories } from '../repositories/index.js'\nimport { buildOrderDoc, type OrderDoc } from './builders.js'\n\n// What the builders are given, read from the command store: the same reads for a live projection at handle time and\n// for a rebuild's pages.\n\ntype CatalogueRepos = Pick<Repositories, 'product' | 'variant' | 'category' | 'productCategory'>\n\n/** The product with its variants and category ids. The ids are sorted: the join table keeps no order of its own. */\nexport async function productSnapshot(\n tx: ReadTx,\n repos: Pick<Repositories, 'variant' | 'productCategory'>,\n product: Product,\n): Promise<ProductSnapshot> {\n const variants = await repos.variant.findByProduct(tx, product.id)\n const categoryIds = await repos.productCategory.listCategoriesForProduct(tx, product.id)\n return { ...product, variants, categoryIds: [...categoryIds].sort() }\n}\n\n/** The category rows of `ids` that exist, by id. */\nexport async function categoriesOf(\n tx: ReadTx,\n repos: Pick<Repositories, 'category'>,\n ids: readonly string[],\n): Promise<Map<string, Category>> {\n const found = new Map<string, Category>()\n for (const id of new Set(ids)) {\n const category = await repos.category.findById(tx, id)\n if (category) found.set(id, category)\n }\n return found\n}\n\n/** The product as its document is built from it, or null when it is gone. */\nexport async function loadProduct(\n tx: ReadTx,\n repos: CatalogueRepos,\n productId: string,\n): Promise<{ snapshot: ProductSnapshot; categories: Map<string, Category> } | null> {\n const product = await repos.product.findById(tx, productId)\n if (!product) return null\n const snapshot = await productSnapshot(tx, repos, product)\n return { snapshot, categories: await categoriesOf(tx, repos, snapshot.categoryIds) }\n}\n\n/** The order's document, or null when it is gone. */\nexport async function loadOrderDoc(\n tx: ReadTx,\n repos: Pick<Repositories, 'order' | 'orderHistory'>,\n orderId: string,\n): Promise<OrderDoc | null> {\n const order = await repos.order.findById(tx, orderId)\n if (!order) return null\n return buildOrderDoc(order, await repos.orderHistory.listByOrder(tx, order.id))\n}\n","import {\n EVT_ORDER_CANCELLED,\n EVT_ORDER_DELIVERED,\n EVT_ORDER_PAID,\n EVT_ORDER_PARTIALLY_REFUNDED,\n EVT_ORDER_PLACED,\n EVT_ORDER_REFUNDED,\n EVT_ORDER_SHIPPED,\n EVT_ORDER_STATUS_CHANGED,\n EVT_PAYMENT_FAILED,\n EVT_PAYMENT_INTENT_CREATED,\n EVT_PAYMENT_REFUNDED,\n type DocumentStoreAdapter,\n type EventBusAdapter,\n type EventHandler,\n type Logger,\n type OrderPlacedV1Payload,\n} from '@nymbalhq/types'\nimport type { OrderRepository } from '../../repositories/order.js'\nimport type { OrderHistoryRepository } from '../../repositories/order-history.js'\nimport { orderWrites } from '../../read-models/builders.js'\nimport { loadOrderDoc } from '../../read-models/sources.js'\nimport { subscribeDerived, type DerivedHandler } from '../derived.js'\n\nexport interface OrderProjectionDeps {\n documentStore: DocumentStoreAdapter\n logger: Logger\n orderRepo: OrderRepository\n orderHistoryRepo: OrderHistoryRepository\n}\n\nexport interface RegisterOrderProjectionDeps extends OrderProjectionDeps {\n eventBus: EventBusAdapter\n}\n\n/** `orders` and `orders-by-customer`, from the order and its history as they are at handle time. */\nexport function orderProjection(deps: OrderProjectionDeps): DerivedHandler[] {\n const { documentStore, logger, orderRepo, orderHistoryRepo } = deps\n const repos = { order: orderRepo, orderHistory: orderHistoryRepo }\n\n async function reproject(orderId: string): Promise<void> {\n const doc = await orderRepo.store.read((tx) => loadOrderDoc(tx, repos, orderId))\n if (!doc) return\n for (const w of orderWrites(doc)) await documentStore.put(w.collection, w.key, w.doc)\n logger.debug({ orderNumber: doc.orderNumber, status: doc.status }, 'order projected')\n }\n\n const onPlaced: EventHandler<OrderPlacedV1Payload> = (event) => reproject(event.payload.order.id)\n\n const onStatusChange: EventHandler<{ orderId: string }> = (event) =>\n reproject(event.payload.orderId)\n\n return [\n {\n name: 'order-projection-placed',\n types: [EVT_ORDER_PLACED],\n handle: onPlaced as EventHandler,\n },\n {\n name: 'order-projection-status',\n types: [\n EVT_ORDER_PAID,\n EVT_ORDER_SHIPPED,\n EVT_ORDER_DELIVERED,\n EVT_ORDER_CANCELLED,\n EVT_ORDER_REFUNDED,\n EVT_ORDER_PARTIALLY_REFUNDED,\n EVT_ORDER_STATUS_CHANGED,\n ],\n handle: onStatusChange as EventHandler,\n },\n {\n // A payment's outcome is written on its order (the intent, a failure note, a refund of a cancelled capture).\n name: 'order-projection-payment',\n types: [EVT_PAYMENT_INTENT_CREATED, EVT_PAYMENT_FAILED, EVT_PAYMENT_REFUNDED],\n handle: onStatusChange as EventHandler,\n },\n ]\n}\n\nexport async function registerOrderProjection(deps: RegisterOrderProjectionDeps): Promise<void> {\n await subscribeDerived(deps.eventBus, orderProjection(deps))\n}\n","import {\n EVT_CUSTOMER_CREATED,\n EVT_CUSTOMER_DELETED,\n EVT_CUSTOMER_UPDATED,\n EVT_ORDER_PAID,\n EVT_ORDER_PARTIALLY_REFUNDED,\n EVT_ORDER_REFUNDED,\n type CustomerProfile,\n type DocumentStoreAdapter,\n type EventBusAdapter,\n type EventHandler,\n type Logger,\n} from '@nymbalhq/types'\nimport type { CustomerRepository } from '../../repositories/customer.js'\nimport type { OrderRepository } from '../../repositories/order.js'\nimport { buildCustomerProfile, CUSTOMER_PROFILES } from '../../read-models/builders.js'\nimport { subscribeDerived, type DerivedHandler } from '../derived.js'\n\nexport interface CustomerProjectionDeps {\n documentStore: DocumentStoreAdapter\n logger: Logger\n customerRepo: CustomerRepository\n orderRepo: OrderRepository\n}\n\nexport interface RegisterCustomerProjectionDeps extends CustomerProjectionDeps {\n eventBus: EventBusAdapter\n}\n\n/** `customer-profiles`, from the customer row as it is at handle time: its stats move with payments and refunds. */\nexport function customerProjection(deps: CustomerProjectionDeps): DerivedHandler[] {\n const { documentStore, logger, customerRepo, orderRepo } = deps\n\n async function reproject(customerId: string): Promise<void> {\n const c = await customerRepo.store.read((tx) => customerRepo.findById(tx, customerId))\n if (!c) {\n await documentStore.delete(CUSTOMER_PROFILES, customerId)\n return\n }\n await documentStore.put<CustomerProfile>(CUSTOMER_PROFILES, c.id, buildCustomerProfile(c))\n logger.debug({ customerId }, 'customer profile projected')\n }\n\n const onCustomer: EventHandler<{ customerId: string }> = (event) =>\n reproject(event.payload.customerId)\n\n const onOrder: EventHandler<{ orderId: string }> = async (event) => {\n const order = await orderRepo.store.read((tx) => orderRepo.findById(tx, event.payload.orderId))\n if (order?.customerId) await reproject(order.customerId)\n }\n\n return [\n {\n name: 'customer-projection-created',\n types: [EVT_CUSTOMER_CREATED],\n handle: onCustomer as EventHandler,\n },\n {\n name: 'customer-projection-updated',\n types: [EVT_CUSTOMER_UPDATED],\n handle: onCustomer as EventHandler,\n },\n {\n name: 'customer-projection-deleted',\n types: [EVT_CUSTOMER_DELETED],\n handle: onCustomer as EventHandler,\n },\n {\n name: 'customer-projection-order-paid',\n types: [EVT_ORDER_PAID],\n handle: onOrder as EventHandler,\n },\n {\n name: 'customer-projection-order-refunded',\n types: [EVT_ORDER_REFUNDED, EVT_ORDER_PARTIALLY_REFUNDED],\n handle: onOrder as EventHandler,\n },\n ]\n}\n\nexport async function registerCustomerProjection(\n deps: RegisterCustomerProjectionDeps,\n): Promise<void> {\n await subscribeDerived(deps.eventBus, customerProjection(deps))\n}\n","import {\n EVT_INVENTORY_CHANGED,\n type EventBusAdapter,\n type EventHandler,\n type InventoryChangedV1Payload,\n} from '@nymbalhq/types'\nimport { subscribeDerived, type DerivedHandler } from '../derived.js'\nimport { productReprojector, type ProductProjectionDeps } from './product-projection.js'\n\nexport interface RegisterInventoryProjectionDeps extends ProductProjectionDeps {\n eventBus: EventBusAdapter\n}\n\n/** A stock change re-projects the variant's product, so `products` and `products-by-category` both carry it. */\nexport function inventoryProjection(deps: ProductProjectionDeps): DerivedHandler[] {\n const products = productReprojector(deps)\n const { repos, logger } = deps\n\n const handler: EventHandler<InventoryChangedV1Payload> = async (event) => {\n const { variantId, newQty } = event.payload\n const variant = await repos.variant.store.read((tx) => repos.variant.findById(tx, variantId))\n if (!variant) return\n await products.reproject(variant.productId)\n logger.debug({ variantId, newQty }, 'inventory projection updated')\n }\n\n return [\n {\n name: 'inventory-projection',\n types: [EVT_INVENTORY_CHANGED],\n handle: handler as EventHandler,\n },\n ]\n}\n\nexport async function registerInventoryProjection(\n deps: RegisterInventoryProjectionDeps,\n): Promise<void> {\n await subscribeDerived(deps.eventBus, inventoryProjection(deps))\n}\n","import { v7 as uuidv7 } from 'uuid'\nimport {\n EVT_CART_ABANDONED,\n EVT_CUSTOMER_CREATED,\n EVT_ORDER_CONFIRMATION_RESEND_REQUESTED,\n EVT_ORDER_PAID,\n EVT_ORDER_SHIPPED,\n type CartAbandonedV1Payload,\n type CustomerCreatedV1Payload,\n type EmailAdapter,\n type EventBusAdapter,\n type EventHandler,\n type Logger,\n type Order,\n type OrderConfirmationResendRequestedV1Payload,\n type OrderPaidV1Payload,\n type OrderShippedV1Payload,\n} from '@nymbalhq/types'\nimport { formatMoney } from '../../money.js'\nimport { mintOrderKey } from '../../order-access-key.js'\nimport { withIdempotency } from '../idempotency.js'\nimport type { OrderAccessKeyRepository } from '../../repositories/order-access-key.js'\nimport type { OrderRepository } from '../../repositories/order.js'\nimport type { ProcessedEventRepository } from '../../repositories/processed-event.js'\n\n/** The handler name of the order-placed email's records: one per order, whatever number of order.paid it gets. */\nconst ORDER_PAID_EMAIL = 'email:order-paid'\n\nexport interface RegisterEmailHandlerDeps {\n eventBus: EventBusAdapter\n email: EmailAdapter\n logger: Logger\n processedEventRepo: ProcessedEventRepository\n orderRepo: OrderRepository\n orderAccessKeyRepo: OrderAccessKeyRepository\n storeName: string\n /** The storefront's URL, with no trailing `/`; with none, the order-placed email links nowhere and mints no key. */\n storeUrl?: string\n}\n\nexport async function registerEmailHandler(deps: RegisterEmailHandlerDeps): Promise<void> {\n const { eventBus, email, logger, processedEventRepo, orderRepo, orderAccessKeyRepo } = deps\n const { storeName, storeUrl } = deps\n\n /**\n * The order page's link, with a key of the email's own: only the hash of the checkout's key is stored, so the\n * handler never has it.\n */\n async function orderLink(\n base: string,\n order: Order,\n ): Promise<{ orderUrl: string; orderLink: string }> {\n const { key, hash } = mintOrderKey()\n await orderAccessKeyRepo.store.transaction((tx) =>\n orderAccessKeyRepo.insert(tx, {\n id: uuidv7(),\n orderId: order.id,\n keyHash: hash,\n purpose: 'email',\n createdAt: new Date(),\n }),\n )\n const orderUrl = `${base}/order/${encodeURIComponent(order.orderNumber)}?key=${key}`\n return { orderUrl, orderLink: `\\n\\nView your order: ${orderUrl}` }\n }\n\n /** The order-placed email, with a link carrying a key minted for this send when the store has a URL. */\n async function sendOrderPlaced(order: Order): Promise<void> {\n await email.sendTransactional({\n template: 'order-placed',\n to: order.email,\n vars: {\n orderNumber: order.orderNumber,\n customerName: order.billingAddress.firstName,\n totalFormatted: formatMoney(order.totalMinor, order.currency),\n ...(storeUrl !== undefined && (await orderLink(storeUrl, order))),\n },\n })\n }\n\n // Sent on payment, never at placement: an unpaid order (or an imported one) emails nobody. Keyed per order, so a\n // second order.paid for the order (a redelivered or replayed event) sends nothing more.\n const onOrderPaid: EventHandler<OrderPaidV1Payload> = async (event) => {\n const { orderId } = event.payload\n const { store } = processedEventRepo\n if (await store.read((tx) => processedEventRepo.seen(tx, ORDER_PAID_EMAIL, orderId))) return\n const order = await orderRepo.store.read((tx) => orderRepo.findById(tx, orderId))\n if (order === null) {\n logger.warn({ orderId, eventId: event.id }, 'email handler: paid order not found')\n return\n }\n await sendOrderPlaced(order)\n await store.transaction((tx) =>\n processedEventRepo.markProcessed(tx, ORDER_PAID_EMAIL, orderId, new Date()),\n )\n }\n\n // An admin's resend: once per resend event, never per order, so it sends whatever became of order.paid's email.\n const onConfirmationResendRequested: EventHandler<\n OrderConfirmationResendRequestedV1Payload\n > = async (event) => {\n const { orderId } = event.payload\n const order = await orderRepo.store.read((tx) => orderRepo.findById(tx, orderId))\n if (order === null) {\n logger.warn({ orderId, eventId: event.id }, 'email handler: resent order not found')\n return\n }\n await sendOrderPlaced(order)\n }\n\n const onOrderShipped: EventHandler<OrderShippedV1Payload> = async (event) => {\n logger.debug({ orderId: event.payload.orderId }, 'email handler: order shipped')\n // Need to look up customer email; skip in v0.1 (requires order repo).\n }\n\n const onCustomerCreated: EventHandler<CustomerCreatedV1Payload> = async (event) => {\n await email.sendTransactional({\n template: 'welcome',\n to: event.payload.email,\n vars: { customerName: 'there', storeName },\n })\n }\n\n const onCartAbandoned: EventHandler<CartAbandonedV1Payload> = async (event) => {\n logger.debug({ cartId: event.payload.cartId }, 'email handler: cart abandoned (stub)')\n }\n\n await eventBus.subscribe(EVT_ORDER_PAID, onOrderPaid as EventHandler, {\n name: 'email-order-paid',\n })\n await eventBus.subscribe(\n EVT_ORDER_CONFIRMATION_RESEND_REQUESTED,\n withIdempotency(\n 'email:order-confirmation-resend',\n onConfirmationResendRequested as EventHandler,\n { repo: processedEventRepo, logger },\n ),\n { name: 'email-order-confirmation-resend' },\n )\n await eventBus.subscribe(\n EVT_ORDER_SHIPPED,\n withIdempotency('email:order-shipped', onOrderShipped as EventHandler, {\n repo: processedEventRepo,\n logger,\n }),\n { name: 'email-order-shipped' },\n )\n await eventBus.subscribe(\n EVT_CUSTOMER_CREATED,\n withIdempotency('email:customer-created', onCustomerCreated as EventHandler, {\n repo: processedEventRepo,\n logger,\n }),\n { name: 'email-customer-created' },\n )\n await eventBus.subscribe(\n EVT_CART_ABANDONED,\n withIdempotency('email:cart-abandoned', onCartAbandoned as EventHandler, {\n repo: processedEventRepo,\n logger,\n }),\n { name: 'email-cart-abandoned' },\n )\n}\n","import {\n EVT_PRODUCT_CREATED,\n EVT_PRODUCT_DELETED,\n EVT_PRODUCT_UPDATED,\n type EventBusAdapter,\n type EventHandler,\n type ProductCreatedV1Payload,\n type ProductDeletedV1Payload,\n type ProductUpdatedV1Payload,\n type SearchAdapter,\n} from '@nymbalhq/types'\nimport type { Repositories } from '../../repositories/index.js'\nimport { buildSearchDoc } from '../../read-models/builders.js'\nimport { productSnapshot } from '../../read-models/sources.js'\nimport { subscribeDerived, type DerivedHandler } from '../derived.js'\n\nexport interface SearchHandlerDeps {\n search: SearchAdapter\n repos: Pick<Repositories, 'product' | 'variant' | 'category' | 'productCategory'>\n}\n\nexport interface RegisterSearchHandlerDeps extends SearchHandlerDeps {\n eventBus: EventBusAdapter\n}\n\n/**\n * The search index, from the product's rows at handle time. Derived state: indexing and removing by id is idempotent,\n * so no processed-event record is kept, and a rebuild refills it.\n */\nexport function searchHandler(deps: SearchHandlerDeps): DerivedHandler[] {\n const { search, repos } = deps\n\n const onUpsert: EventHandler<ProductCreatedV1Payload | ProductUpdatedV1Payload> = async (\n event,\n ) => {\n const { id } = event.payload.product\n const snapshot = await repos.product.store.read(async (tx) => {\n const product = await repos.product.findById(tx, id)\n return product ? productSnapshot(tx, repos, product) : null\n })\n if (snapshot) await search.index([buildSearchDoc(snapshot)])\n else await search.remove([id])\n }\n\n const onDelete: EventHandler<ProductDeletedV1Payload> = async (event) => {\n await search.remove([event.payload.productId])\n }\n\n return [\n {\n name: 'search-product-upsert',\n types: [EVT_PRODUCT_CREATED, EVT_PRODUCT_UPDATED],\n handle: onUpsert as EventHandler,\n },\n {\n name: 'search-product-delete',\n types: [EVT_PRODUCT_DELETED],\n handle: onDelete as EventHandler,\n },\n ]\n}\n\nexport async function registerSearchHandler(deps: RegisterSearchHandlerDeps): Promise<void> {\n await subscribeDerived(deps.eventBus, searchHandler(deps))\n}\n","import {\n EVT_ORDER_DELIVERED,\n type EventBusAdapter,\n type EventHandler,\n type Logger,\n type OrderDeliveredV1Payload,\n type ReviewsAdapter,\n} from '@nymbalhq/types'\nimport { withIdempotency } from '../idempotency.js'\nimport type { ProcessedEventRepository } from '../../repositories/processed-event.js'\n\nexport interface RegisterReviewsHandlerDeps {\n eventBus: EventBusAdapter\n reviews: ReviewsAdapter\n logger: Logger\n processedEventRepo: ProcessedEventRepository\n}\n\nexport async function registerReviewsHandler(deps: RegisterReviewsHandlerDeps): Promise<void> {\n const { eventBus, reviews, logger, processedEventRepo } = deps\n\n const handler: EventHandler<OrderDeliveredV1Payload> = async (event) => {\n await reviews.requestReview(event.payload.orderId)\n }\n\n await eventBus.subscribe(\n EVT_ORDER_DELIVERED,\n withIdempotency('reviews:order-delivered', handler as EventHandler, {\n repo: processedEventRepo,\n logger,\n }),\n { name: 'reviews-order-delivered' },\n )\n}\n","import {\n EVT_ALERT_REQUESTED,\n EVT_PRODUCT_RESTOCKED,\n EVT_PRODUCT_VARIANT_PRICE_CHANGED,\n type AlertRequestedV1Payload,\n type EmailAdapter,\n type EventBusAdapter,\n type EventHandler,\n type Logger,\n type NymbalEvent,\n type Product,\n type ProductRestockedV1Payload,\n type ProductVariantPriceChangedV1Payload,\n type TransactionalEmail,\n} from '@nymbalhq/types'\nimport { formatMoney } from '../../money.js'\nimport type { AlertSubscription } from '../../repositories/alert-subscription.js'\nimport type { Repositories } from '../../repositories/index.js'\nimport type { AlertService } from '../../services/alert-service.js'\n\n/**\n * The handler name of every alert email's record, keyed `<event id>:<subscription id>`: a redelivered event finds the\n * key and sends that row nothing more.\n */\nconst HANDLER = 'email:alert'\n\nexport interface RegisterAlertHandlerDeps {\n eventBus: EventBusAdapter\n email: EmailAdapter\n logger: Logger\n repos: Pick<Repositories, 'alertSubscription' | 'processedEvent' | 'product'>\n alerts: AlertService\n storeName: string\n}\n\nfunction links(row: AlertSubscription, product: Product) {\n const token = (value: string) => encodeURIComponent(value)\n return {\n confirmUrl: `${row.origin}/alerts/confirm?token=${token(row.confirmToken)}`,\n unsubscribeUrl: `${row.origin}/alerts/unsubscribe?token=${token(row.unsubscribeToken)}`,\n productUrl: `${row.origin}/product/${encodeURIComponent(product.slug)}`,\n }\n}\n\nexport async function registerAlertHandler(deps: RegisterAlertHandlerDeps): Promise<void> {\n const { eventBus, email, logger, repos, alerts, storeName } = deps\n const { store } = repos.processedEvent\n\n // A confirmation goes only to a row still waiting for one: a row confirmed or left since is sent nothing.\n const onRequested: EventHandler<AlertRequestedV1Payload> = async (event) => {\n const key = `${event.id}:${event.payload.subscriptionId}`\n const found = await store.read(async (tx) => {\n if (await repos.processedEvent.seen(tx, HANDLER, key)) return null\n const row = await repos.alertSubscription.findById(tx, event.payload.subscriptionId)\n if (row === null || row.status !== 'pending') return null\n const product = await repos.product.findById(tx, row.productId)\n return product === null ? null : { row, product }\n })\n if (found === null) return\n const { row, product } = found\n const { confirmUrl, unsubscribeUrl, productUrl } = links(row, product)\n await email.sendTransactional({\n template: row.kind === 'price_drop' ? 'alert-confirm-price-drop' : 'alert-confirm',\n to: row.email,\n vars: { storeName, productName: product.name, productUrl, confirmUrl, unsubscribeUrl },\n })\n await store.transaction((tx) =>\n repos.processedEvent.markProcessed(tx, HANDLER, key, new Date()),\n )\n }\n\n // Each row is mailed and recorded on its own: one refused address neither stops nor repeats another's alert, and keeps\n // its status (and a price-drop row its baseline). Any refused row fails the delivery, so the event is retried; the\n // retry finds the mailed rows' keys and mails only the refused ones.\n async function fanOut(\n event: NymbalEvent<unknown>,\n rows: AlertSubscription[],\n what: { alert: string; next: string },\n message: (row: AlertSubscription) => Omit<TransactionalEmail, 'to'>,\n ): Promise<void> {\n const failed: string[] = []\n for (const row of rows) {\n const key = `${event.id}:${row.id}`\n if (await store.read((tx) => repos.processedEvent.seen(tx, HANDLER, key))) continue\n try {\n await email.sendTransactional({ ...message(row), to: row.email })\n await store.transaction(async (tx) => {\n await repos.processedEvent.markProcessed(tx, HANDLER, key, new Date())\n await alerts.recordSent(tx, row, event)\n })\n } catch (err) {\n failed.push(row.id)\n logger.warn(\n { err, subscriptionId: row.id, eventId: event.id },\n `${what.alert} alert failed; the subscription stays active until a retry or the next ${what.next}`,\n )\n }\n }\n if (failed.length > 0) {\n throw new Error(\n `${what.alert} alerts for event ${event.id} failed for subscriptions ${failed.join(', ')}`,\n )\n }\n }\n\n const onRestocked: EventHandler<ProductRestockedV1Payload> = async (event) => {\n const { variantId, productId } = event.payload\n const { rows, product } = await store.read(async (tx) => ({\n rows: await repos.alertSubscription.listActive(tx, variantId, 'back_in_stock'),\n product: await repos.product.findById(tx, productId),\n }))\n if (product === null) return\n await fanOut(event, rows, { alert: 'back-in-stock', next: 'restock' }, (row) => {\n const { productUrl, unsubscribeUrl } = links(row, product)\n return {\n template: 'alert-back-in-stock',\n vars: { storeName, productName: product.name, productUrl, unsubscribeUrl },\n }\n })\n }\n\n // A row is mailed when the price falls below both the previous price and the last price it was told (its baseline).\n const onPriceChanged: EventHandler<ProductVariantPriceChangedV1Payload> = async (event) => {\n const { variantId, productId, previousPriceMinor, priceMinor, currency } = event.payload\n if (priceMinor >= previousPriceMinor) return\n const { rows, product } = await store.read(async (tx) => ({\n rows: await repos.alertSubscription.listActive(tx, variantId, 'price_drop'),\n product: await repos.product.findById(tx, productId),\n }))\n if (product === null) return\n const due = rows.filter(\n (row) => row.baselinePriceMinor !== null && priceMinor < row.baselinePriceMinor,\n )\n const previousPriceFormatted = formatMoney(previousPriceMinor, currency)\n const priceFormatted = formatMoney(priceMinor, currency)\n await fanOut(event, due, { alert: 'price-drop', next: 'drop' }, (row) => {\n const { productUrl, unsubscribeUrl } = links(row, product)\n return {\n template: 'alert-price-drop',\n vars: {\n storeName,\n productName: product.name,\n productUrl,\n unsubscribeUrl,\n previousPriceFormatted,\n priceFormatted,\n },\n }\n })\n }\n\n await eventBus.subscribe(EVT_ALERT_REQUESTED, onRequested as EventHandler, {\n name: 'email-alert-requested',\n })\n await eventBus.subscribe(EVT_PRODUCT_RESTOCKED, onRestocked as EventHandler, {\n name: 'email-alert-back-in-stock',\n })\n await eventBus.subscribe(EVT_PRODUCT_VARIANT_PRICE_CHANGED, onPriceChanged as EventHandler, {\n name: 'email-alert-price-drop',\n })\n}\n","import type { DocumentStoreAdapter, EventBusAdapter, Logger } from '@nymbalhq/types'\nimport type { NymbalConfig } from '@nymbalhq/config'\nimport type { Repositories } from '../repositories/index.js'\nimport type { AdapterRegistry } from '../adapters/registry.js'\nimport type { AlertService } from '../services/alert-service.js'\nimport { registerCategoryProjection } from './projections/category-projection.js'\nimport { registerProductProjection } from './projections/product-projection.js'\nimport { registerOrderProjection } from './projections/order-projection.js'\nimport { registerCustomerProjection } from './projections/customer-projection.js'\nimport { registerInventoryProjection } from './projections/inventory-projection.js'\nimport { registerRecentlyViewedProjection } from './projections/recently-viewed-projection.js'\nimport { registerEmailHandler } from './side-effects/email-handler.js'\nimport { registerSearchHandler } from './side-effects/search-handler.js'\nimport { registerReviewsHandler } from './side-effects/reviews-handler.js'\nimport { registerAlertHandler } from './side-effects/alert-handler.js'\n\nexport interface RegisterHandlersDeps {\n config: NymbalConfig\n eventBus: EventBusAdapter\n documentStore: DocumentStoreAdapter\n repos: Repositories\n adapters: AdapterRegistry\n /** Records each alert's send: the row fired and `alert.sent.v1` published. */\n alerts: AlertService\n logger: Logger\n}\n\nexport async function registerHandlers(deps: RegisterHandlersDeps): Promise<void> {\n const { config, eventBus, documentStore, repos, adapters, alerts, logger } = deps\n const handlerLogger = logger.child({ component: 'handlers' })\n\n await registerCategoryProjection({\n eventBus,\n documentStore,\n logger: handlerLogger.child({ projection: 'category' }),\n storeId: config.store.name,\n repos,\n })\n await registerProductProjection({\n eventBus,\n documentStore,\n logger: handlerLogger.child({ projection: 'product' }),\n storeId: config.store.name,\n currency: config.store.currency,\n repos,\n })\n await registerOrderProjection({\n eventBus,\n documentStore,\n logger: handlerLogger.child({ projection: 'order' }),\n orderRepo: repos.order,\n orderHistoryRepo: repos.orderHistory,\n })\n await registerCustomerProjection({\n eventBus,\n documentStore,\n logger: handlerLogger.child({ projection: 'customer' }),\n customerRepo: repos.customer,\n orderRepo: repos.order,\n })\n await registerInventoryProjection({\n eventBus,\n documentStore,\n logger: handlerLogger.child({ projection: 'inventory' }),\n storeId: config.store.name,\n currency: config.store.currency,\n repos,\n })\n await registerRecentlyViewedProjection({\n eventBus,\n documentStore,\n logger: handlerLogger.child({ projection: 'recently-viewed' }),\n })\n\n await registerEmailHandler({\n eventBus,\n email: adapters.email,\n logger: handlerLogger.child({ handler: 'email' }),\n processedEventRepo: repos.processedEvent,\n orderRepo: repos.order,\n orderAccessKeyRepo: repos.orderAccessKey,\n storeName: config.store.name,\n ...(config.store.url !== undefined && { storeUrl: config.store.url }),\n })\n await registerAlertHandler({\n eventBus,\n email: adapters.email,\n logger: handlerLogger.child({ handler: 'alert' }),\n repos,\n alerts,\n storeName: config.store.name,\n })\n await registerSearchHandler({\n eventBus,\n search: adapters.search,\n repos,\n })\n await registerReviewsHandler({\n eventBus,\n reviews: adapters.reviews,\n logger: handlerLogger.child({ handler: 'reviews' }),\n processedEventRepo: repos.processedEvent,\n })\n\n logger.debug('event handlers registered')\n}\n","import { DEFAULT_JWT_SECRET, type NymbalConfig } from '@nymbalhq/config'\nimport { ConfigError, type CommerceSlot, type PaymentsAdapter } from '@nymbalhq/types'\nimport { createPlatform, resolvePrimitives, type Platform } from './platform.js'\nimport type { ResolvePrimitivesOptions } from './platform.js'\nimport { buildRepositories, type Repositories } from './repositories/index.js'\nimport { rawClients } from './db/command-store.js'\nimport {\n buildAdapters,\n checkInjectedAdapters,\n COMMERCE_SLOTS,\n resolvePaymentsAdapter,\n resolveSecurityAdapter,\n type AdapterRegistry,\n type InjectedAdapters,\n} from './adapters/registry.js'\nimport { createLogger } from './logger.js'\nimport { loadBootSettings } from './settings/load.js'\nimport { scrubbingLogger } from './settings/secret-set.js'\nimport { buildServices, type ServiceRegistry } from './services/index.js'\nimport { createEventPublisher, type EventPublisher } from './events/publisher.js'\nimport { createRelay, deliveringBus, type CreateRelayOptions, type Relay } from './events/relay.js'\nimport { registerHandlers } from './handlers/register.js'\nimport { READ_MODEL_NAMES, rebuild } from './read-models/index.js'\nimport {\n startInventoryReservationSweeper,\n startCartAbandonmentSweeper,\n startEventRetentionSweeper,\n type EventArchiveWriter,\n type SweeperHandle,\n} from './sweepers/index.js'\nimport { importProviderPackage } from './adapters/loader.js'\nimport type { HttpAdapter } from '@nymbalhq/types'\n\nexport interface NymbalApp {\n platform: Platform\n repos: Repositories\n adapters: AdapterRegistry\n services: ServiceRegistry\n publisher: EventPublisher\n /** Delivers the event log to the bus; started by createApp, stopped by stop(). */\n relay: Relay\n /**\n * Registers the API on the adapter. The admin is served at /admin/ when `adminRoot` is passed (its dist directory,\n * or null for a 404 that says how to build it) or `NYMBAL_ADMIN_DIST` is set.\n */\n attachHttp(adapter: HttpAdapter, options?: AttachHttpOptions): Promise<void>\n /** Each slot's provider and its adapter's own `capabilities()`; an ai slot of `none` offers nothing. */\n capabilities(): CapabilitiesReport\n stop(): Promise<void>\n}\n\nexport type CapabilitySlot = CommerceSlot | 'security' | 'documentStore' | 'eventBus' | 'media'\n\nexport interface SlotCapabilities {\n provider: string\n capabilities: readonly string[]\n}\n\nexport type CapabilitiesReport = Record<CapabilitySlot, SlotCapabilities>\n\nexport interface AttachHttpOptions {\n adminRoot?: string | null\n}\n\nexport interface CreateAppOptions extends ResolvePrimitivesOptions {\n version?: string\n /** The project's own adapters, one per slot whose provider is `custom`. */\n adapters?: InjectedAdapters\n /** How the event relay retries a failed delivery (`createRelay`). */\n relay?: Pick<CreateRelayOptions, 'maxAttempts' | 'retryDelayMs' | 'intervalMs' | 'now'>\n}\n\n/**\n * A production process must not run on the stub payments adapter (its unsigned webhook confirms any order) or sign\n * tokens with the schema's published default secret. Checked on the resolved adapter, built or injected, before\n * anything opens the store.\n */\nfunction refuseUnsafeProduction(config: NymbalConfig, payments: PaymentsAdapter): void {\n if (process.env.NODE_ENV !== 'production') return\n const provider = config.commerce.payments.provider\n if (payments.providerName === 'native-stub') {\n throw new ConfigError(\n `Payments provider \"${provider}\" resolves to the stub adapter, which verifies no webhook signature; ` +\n 'configure a real payments provider for production.',\n { code: 'config.production_stub_payments', context: { provider } },\n )\n }\n if (config.security.auth.jwtSecret === DEFAULT_JWT_SECRET) {\n throw new ConfigError(\n 'security.auth.jwtSecret is the schema default; set a secret of your own for production.',\n { code: 'config.production_default_jwt_secret' },\n )\n }\n}\n\ntype EventArchiveOptions = Omit<NonNullable<NymbalConfig['events']['archive']>, 'adapter'>\n\ninterface ObjectWriterModule {\n createS3ObjectWriter?: (options: EventArchiveOptions) => EventArchiveWriter\n}\n\n/**\n * The private object writer `events.archive` names, from `@nymbalhq/media-s3`, or undefined when no archive is set.\n * Its credentials come from the AWS SDK's default chain, as media's do.\n */\nasync function eventArchiveWriter(config: NymbalConfig): Promise<EventArchiveWriter | undefined> {\n const archive = config.events.archive\n if (archive === undefined) return undefined\n const { adapter, ...options } = archive\n let mod: ObjectWriterModule | undefined\n try {\n mod = (await importProviderPackage('media', adapter, process.env)) as\n | ObjectWriterModule\n | undefined\n } catch (error) {\n if (!(error instanceof ConfigError && error.code === 'adapter.package_missing')) throw error\n throw new ConfigError(\n `events.archive needs @nymbalhq/media-s3: ${String(error.context['install'])}`,\n {\n code: 'adapter.package_missing',\n cause: error,\n context: error.context,\n },\n )\n }\n if (typeof mod?.createS3ObjectWriter !== 'function') {\n throw new ConfigError('@nymbalhq/media-s3 exports no createS3ObjectWriter; upgrade it', {\n code: 'adapter.package_invalid',\n context: { package: '@nymbalhq/media-s3' },\n })\n }\n return mod.createS3ObjectWriter(options)\n}\n\nexport async function createApp(\n config: NymbalConfig,\n options: CreateAppOptions = {},\n): Promise<NymbalApp> {\n // Whatever logger the caller gives, nothing it writes carries a secret Settings hold.\n const logger = scrubbingLogger(\n options.logger ?? createLogger({ base: { store: config.store.name } }),\n )\n const adapterLogger = logger.child({ layer: 'adapter' })\n checkInjectedAdapters(config, options.adapters)\n // Settings are read, through a read-only open closed again here, before any adapter is built: payments first.\n const settings = await loadBootSettings(config, {\n storage: {\n ...(options.sqlitePath !== undefined && { sqlitePath: options.sqlitePath }),\n ...(options.postgresUrl !== undefined && { postgresUrl: options.postgresUrl }),\n },\n env: process.env,\n logger,\n })\n const payments = await resolvePaymentsAdapter(\n config,\n adapterLogger,\n options.adapters,\n settings.values,\n )\n refuseUnsafeProduction(config, payments)\n const security = await resolveSecurityAdapter(config, adapterLogger)\n const archive = await eventArchiveWriter(config)\n const primitives = await resolvePrimitives(config, { ...options, logger })\n // Until the app is returned, nothing else holds the connections the primitives and the command store open.\n let release = async (): Promise<void> => {\n await primitives.eventBus.close()\n await primitives.documentStore.close()\n }\n try {\n const platform = createPlatform(config, { ...options, ...primitives, logger })\n release = () => platform.close()\n const version = options.version ?? '0.1.0'\n\n const repos = buildRepositories(platform.commandStore, platform.documentStore)\n const adapters = await buildAdapters({\n config,\n logger: adapterLogger,\n sql: rawClients(platform.commandStore),\n repos,\n payments,\n security,\n settings: settings.values,\n ...(options.adapters !== undefined && { injected: options.adapters }),\n })\n const relay = createRelay({\n store: platform.commandStore,\n eventLog: repos.eventLog,\n eventBus: platform.eventBus,\n logger,\n ...options.relay,\n })\n const subscriberBus = deliveringBus(platform.eventBus, relay)\n const publisher = createEventPublisher({\n eventBus: platform.eventBus,\n store: platform.commandStore,\n eventLog: repos.eventLog,\n relay,\n builderContext: {\n storeId: config.store.name,\n environment:\n process.env.NODE_ENV === 'production'\n ? 'production'\n : process.env.NODE_ENV === 'staging'\n ? 'staging'\n : 'development',\n version,\n source: 'nymbal-app',\n },\n })\n const services = buildServices({\n config,\n store: platform.commandStore,\n repos,\n publisher,\n logger: logger.child({ layer: 'service' }),\n payments: adapters.payments,\n searchAdapter: adapters.search,\n email: adapters.email,\n })\n\n await registerHandlers({\n config,\n eventBus: subscriberBus,\n documentStore: platform.documentStore,\n repos,\n adapters,\n alerts: services.alert,\n logger,\n })\n\n // Every read model is rebuilt from the tables before anything is served, so a fresh process serves what a\n // long-running one does.\n await rebuild(READ_MODEL_NAMES, {\n config,\n store: platform.commandStore,\n repos,\n documentStore: platform.documentStore,\n search: adapters.search,\n logger,\n })\n\n // Events committed before a crash, or whose delivery failed, go out before the app serves anything.\n await relay.drain()\n relay.start()\n\n const sweepers: SweeperHandle[] = [\n startInventoryReservationSweeper({\n inventoryService: services.inventory,\n reservationRepo: repos.inventoryReservation,\n logger,\n }),\n startCartAbandonmentSweeper({\n store: platform.commandStore,\n carts: repos.cart,\n publisher,\n logger,\n }),\n startEventRetentionSweeper({\n store: platform.commandStore,\n eventLog: repos.eventLog,\n processedEvents: repos.processedEvent,\n logger,\n retentionDays: config.events.retentionDays,\n ...(archive !== undefined && { archive }),\n }),\n ]\n\n const app: NymbalApp = {\n platform,\n repos,\n adapters,\n services,\n publisher,\n relay,\n async attachHttp(adapter, options = {}) {\n await adapters.security.applyMiddleware(adapter, config.security)\n const { registerAllRoutes } = await import('./routes/register.js')\n registerAllRoutes({\n config,\n adapter,\n services,\n adapters,\n repos,\n documentStore: platform.documentStore,\n eventBus: subscriberBus,\n publisher,\n settingsSlots: settings.slots,\n adminRoot:\n options.adminRoot !== undefined ? options.adminRoot : process.env['NYMBAL_ADMIN_DIST'],\n })\n },\n capabilities() {\n const commerce = Object.fromEntries(\n COMMERCE_SLOTS.map((slot) => {\n const adapter = adapters[slot]\n return [\n slot,\n {\n provider: config.commerce[slot].provider,\n capabilities: adapter === null ? [] : adapter.capabilities(),\n },\n ]\n }),\n ) as Record<CommerceSlot, SlotCapabilities>\n return {\n ...commerce,\n security: {\n provider: config.security.adapter,\n capabilities: adapters.security.capabilities(),\n },\n documentStore: {\n provider: config.infrastructure.documentStore,\n capabilities: platform.documentStore.capabilities(),\n },\n eventBus: {\n provider: config.infrastructure.eventBus,\n capabilities: platform.eventBus.capabilities(),\n },\n media: {\n provider: config.infrastructure.media,\n capabilities: platform.media.capabilities(),\n },\n }\n },\n async stop() {\n await relay.stop()\n for (const s of sweepers) s.stop()\n await platform.close()\n },\n }\n return app\n } catch (error) {\n await release().catch((err: unknown) =>\n logger.error({ err }, 'closing the primitives after a failed start failed'),\n )\n throw error\n }\n}\n","import { errorText, type DocumentStoreAdapter, type SearchDocument } from '@nymbalhq/types'\nimport { rawClients } from '../db/command-store.js'\nimport { nativeIndexDocuments } from '../adapters/search/native-adapter.js'\nimport type { KeysetPage } from '../repositories/index.js'\nimport { KEY_OF } from './builders.js'\nimport { catalogue } from './catalogue.js'\nimport { customers } from './customers.js'\nimport {\n SEARCH_INDEX,\n searchOf,\n type ReadModel,\n type ReadModelName,\n type RebuildContext,\n type RebuildDeps,\n} from './model.js'\nimport { orders } from './orders.js'\nimport { recentlyViewed } from './recently-viewed.js'\nimport { search } from './search.js'\n\nexport {\n SEARCH_INDEX,\n type ReadModel,\n type ReadModelName,\n type RebuildContext,\n type RebuildDeps,\n} from './model.js'\n\n/** Every derived read model, in the order a rebuild of all of them runs. */\nexport const READ_MODELS: readonly ReadModel[] = [\n catalogue,\n orders,\n customers,\n search,\n recentlyViewed,\n]\n\nexport const READ_MODEL_NAMES: readonly ReadModelName[] = READ_MODELS.map((m) => m.name)\n\n/**\n * How long before the rebuild started a delivery may be stamped and still be caught up. The relay stamps\n * `delivered_at` on its own host's clock, which can run behind this process's; re-applying an event costs little,\n * skipping one loses a write.\n */\nexport const CATCH_UP_MARGIN_MS = 10 * 60_000\n\nconst DEFAULT_PAGE_SIZE = 200\nconst CATCH_UP_PAGE = 500\nconst SCAN_PAGE = 500\n\nexport interface CatchUpFailure {\n seq: number\n eventId: string\n type: string\n handler: string\n error: string\n}\n\nexport interface RebuildReportEntry {\n model: ReadModelName\n /** Each collection swapped in and the documents it was given (the search model's is `index`). */\n collections: Array<{ name: string; documents: number }>\n /** Logged events re-applied after the swap. */\n caughtUpEvents: number\n /** Catch-up events a handler failed on: the model is swapped all the same. */\n failures: CatchUpFailure[]\n ms: number\n /** Set when the search adapter has no `replaceAll`: it was given every document, and kept any others it held. */\n note?: string\n}\n\nexport type RebuildReport = RebuildReportEntry[]\n\n/** A rebuilder failed: nothing was swapped, so every read model keeps its old contents. */\nexport class RebuildError extends Error {\n readonly model: ReadModelName\n\n constructor(model: ReadModelName, cause: unknown) {\n super(\n `the ${model} read model was not rebuilt (its old contents are kept): ${errorText(cause)}`,\n {\n cause,\n },\n )\n this.name = 'RebuildError'\n this.model = model\n }\n}\n\nfunction modelsOf(names: readonly string[]): ReadModel[] {\n return names.map((name) => {\n const model = READ_MODELS.find((m) => m.name === name)\n if (model === undefined) {\n throw new Error(`unknown read model \"${name}\": one of ${READ_MODEL_NAMES.join(', ')}, or all`)\n }\n return model\n })\n}\n\n/** The context a model rebuilds with, and the highest seq it read from the log (undefined when it reads no log). */\nfunction contextFor(\n model: ReadModel,\n deps: RebuildDeps,\n): { ctx: RebuildContext; logReadThrough: () => number | undefined } {\n const limit = deps.pageSize ?? DEFAULT_PAGE_SIZE\n let page = 0\n let logReadThrough: number | undefined\n const ctx: RebuildContext = {\n deps,\n async *pages(table, read) {\n let after: string | undefined\n for (;;) {\n await deps.onPage?.({ model: model.name, table, page })\n page += 1\n const keyset: KeysetPage = after === undefined ? { limit } : { after, limit }\n const rows = await deps.store.read((tx) => read(tx, keyset))\n if (rows.length > 0) yield rows\n if (rows.length < limit) return\n after = rows[rows.length - 1]!.id\n }\n },\n async *events(types) {\n let after = 0\n logReadThrough ??= 0\n for (;;) {\n await deps.onPage?.({ model: model.name, table: 'events', page })\n page += 1\n const rows = await deps.store.read((tx) =>\n deps.repos.eventLog.listAfter(tx, after, { types: [...types], limit }),\n )\n if (rows.length > 0) {\n after = rows[rows.length - 1]!.seq\n logReadThrough = Math.max(logReadThrough, after)\n const live = rows.filter((r) => r.deadAt === null)\n if (live.length > 0) yield live\n }\n if (rows.length < limit) return\n }\n },\n }\n return { ctx, logReadThrough: () => logReadThrough }\n}\n\ninterface Collected {\n model: ReadModel\n /** When its first page was read: catch-up starts from here, less the margin. */\n startedAt: number\n /** The new contents, by collection (`SEARCH_INDEX` for search), then by key. */\n writes: Map<string, Map<string, unknown>>\n /** For a model rebuilt from the log, the last seq it read: its catch-up starts above it. */\n logReadThrough: number | undefined\n}\n\n/** Reads every document of `model` into memory, so a rebuilder that fails part-way leaves nothing half-swapped. */\nasync function collect(model: ReadModel, deps: RebuildDeps): Promise<Collected> {\n const startedAt = Date.now()\n const owned = model.target === 'search' ? [SEARCH_INDEX] : model.collections\n const writes = new Map(owned.map((c) => [c, new Map<string, unknown>()]))\n const { ctx, logReadThrough } = contextFor(model, deps)\n try {\n for await (const w of model.rebuild(ctx)) {\n const into = writes.get(w.collection)\n if (into === undefined) throw new Error(`it wrote to ${w.collection}, which it does not own`)\n into.set(w.key, w.doc)\n }\n } catch (error) {\n throw new RebuildError(model.name, error)\n }\n return { model, startedAt, writes, logReadThrough: logReadThrough() }\n}\n\nasync function* entries<T>(docs: Map<string, T>): AsyncGenerator<[string, T]> {\n yield* docs\n}\n\n/** Swaps the collected contents in; returns the note a search adapter without `replaceAll` earns. */\nasync function swap({ model, writes }: Collected, deps: RebuildDeps): Promise<string | undefined> {\n if (model.target === 'documents') {\n for (const collection of model.collections) {\n await deps.documentStore.replaceCollection(collection, entries(writes.get(collection)!))\n }\n return undefined\n }\n const search = searchOf(deps)\n const docs = [...writes.get(SEARCH_INDEX)!.values()] as SearchDocument[]\n if (search.replaceAll !== undefined) {\n await search.replaceAll(docs)\n return undefined\n }\n await search.index(docs)\n return `${search.providerName} has no replaceAll: every document was indexed, removals not guaranteed`\n}\n\n/**\n * Re-applies, in seq order, every logged event that is not dead and was delivered at or after `since` or not yet, to\n * the model's handlers, called directly so a failure is collected instead of logged by the bus. The handlers write\n * the state they read at handle time, so an event applied twice changes nothing.\n */\nasync function catchUp(\n model: ReadModel,\n since: Date,\n deps: RebuildDeps,\n afterSeq = 0,\n): Promise<{ applied: number; failures: CatchUpFailure[] }> {\n const handlers = model.handlers(deps)\n const failures: CatchUpFailure[] = []\n let applied = 0\n for (;;) {\n const page = await deps.store.read((tx) =>\n deps.repos.eventLog.listForCatchUp(tx, since, { afterSeq, limit: CATCH_UP_PAGE }),\n )\n for (const { seq, event } of page) {\n afterSeq = seq\n const matching = handlers.filter((h) => h.types.includes(event.type))\n if (matching.length === 0) continue\n applied += 1\n for (const h of matching) {\n try {\n await h.handle(event)\n } catch (error) {\n failures.push({\n seq,\n eventId: event.id,\n type: event.type,\n handler: h.name,\n error: errorText(error),\n })\n }\n }\n }\n if (page.length < CATCH_UP_PAGE) return { applied, failures }\n }\n}\n\n/**\n * Rebuilds `names` from the command store's tables: every model is read first, then each is swapped in (atomically\n * per collection) and caught up with the events delivered since its read began. A rebuilder that throws rejects with\n * a `RebuildError` before anything is swapped. Catch-up failures are in the report.\n */\nexport async function rebuild(\n names: readonly ReadModelName[],\n deps: RebuildDeps,\n): Promise<RebuildReport> {\n const collected: Collected[] = []\n for (const model of modelsOf(names)) collected.push(await collect(model, deps))\n const report: RebuildReport = []\n for (const c of collected) {\n const note = await swap(c, deps)\n const { applied, failures } = await catchUp(\n c.model,\n new Date(c.startedAt - CATCH_UP_MARGIN_MS),\n deps,\n c.logReadThrough,\n )\n const entry: RebuildReportEntry = {\n model: c.model.name,\n collections: [...c.writes].map(([name, docs]) => ({ name, documents: docs.size })),\n caughtUpEvents: applied,\n failures,\n ms: Date.now() - c.startedAt,\n ...(note !== undefined && { note }),\n }\n report.push(entry)\n const log =\n failures.length > 0 ? deps.logger.warn.bind(deps.logger) : deps.logger.debug.bind(deps.logger)\n log(\n { model: entry.model, collections: entry.collections, caughtUpEvents: applied, failures },\n `read model ${entry.model} rebuilt`,\n )\n }\n return report\n}\n\nexport interface CollectionDiff {\n name: string\n added: number\n changed: number\n removed: number\n}\n\nexport interface ReadModelDiff {\n model: ReadModelName\n collections: CollectionDiff[]\n /** Why the model was not compared, when it was not. */\n skipped?: string\n}\n\n/** JSON with sorted keys: two documents equal when they would be stored alike, whatever their key order. */\nfunction canonical(value: unknown): string {\n const sort = (v: unknown): unknown => {\n if (Array.isArray(v)) return v.map(sort)\n if (v !== null && typeof v === 'object') {\n return Object.fromEntries(\n Object.keys(v)\n .sort()\n .map((k) => [k, sort((v as Record<string, unknown>)[k])]),\n )\n }\n return v\n }\n return JSON.stringify(sort(JSON.parse(JSON.stringify(value ?? null))))\n}\n\n/**\n * The live collection, by the key its builder files each document under: read by full scans only, which leave a\n * store's internal order alone (a Redis point read can advance a hash's rehash and reorder it).\n */\nasync function liveOf(\n store: DocumentStoreAdapter,\n collection: string,\n): Promise<Map<string, unknown>> {\n const keyOf = KEY_OF[collection]!\n const live = new Map<string, unknown>()\n let cursor: string | undefined\n for (;;) {\n const page = await store.query(collection, {\n partitionKey: { field: 'id', value: '*' },\n limit: SCAN_PAGE,\n ...(cursor !== undefined && { cursor }),\n })\n for (const doc of page.items) live.set(keyOf(doc), doc)\n if (page.nextCursor === null) return live\n cursor = page.nextCursor\n }\n}\n\nfunction compare(\n name: string,\n next: Map<string, unknown>,\n live: Map<string, unknown>,\n): CollectionDiff {\n let added = 0\n let changed = 0\n for (const [key, doc] of next) {\n if (!live.has(key)) added += 1\n else if (canonical(live.get(key)) !== canonical(doc)) changed += 1\n }\n return { name, added, changed, removed: live.size - (next.size - added) }\n}\n\n/** Rebuilds `name` into memory and counts, per collection, what differs from the live read model; writes nothing. */\nexport async function diffReadModel(\n name: ReadModelName,\n deps: RebuildDeps,\n): Promise<ReadModelDiff> {\n const [model] = modelsOf([name])\n const { writes } = await collect(model!, deps)\n if (model!.target === 'search') {\n const { providerName } = searchOf(deps)\n if (providerName !== 'native') {\n return {\n model: name,\n collections: [],\n skipped: `the ${providerName} search adapter cannot list its documents, so it is not compared`,\n }\n }\n const held = await nativeIndexDocuments(rawClients(deps.store))\n const live = new Map<string, unknown>(held.map((d) => [d.id, d]))\n return {\n model: name,\n collections: [compare(SEARCH_INDEX, writes.get(SEARCH_INDEX)!, live)],\n }\n }\n const collections: CollectionDiff[] = []\n for (const collection of model!.collections) {\n const live = await liveOf(deps.documentStore, collection)\n collections.push(compare(collection, writes.get(collection)!, live))\n }\n return { model: name, collections }\n}\n","import type { Category, ProductSnapshot } from '@nymbalhq/types'\nimport type { ReadTx } from '../db/command-store.js'\nimport type { KeysetPage } from '../repositories/index.js'\nimport { categoryProjection } from '../handlers/projections/category-projection.js'\nimport { inventoryProjection } from '../handlers/projections/inventory-projection.js'\nimport { productProjection } from '../handlers/projections/product-projection.js'\nimport {\n buildCategoryDoc,\n buildProductDoc,\n CATEGORIES,\n productWrites,\n PRODUCTS,\n PRODUCTS_BY_CATEGORY,\n} from './builders.js'\nimport type { ReadModel, RebuildDeps } from './model.js'\nimport { productSnapshot } from './sources.js'\n\n/** Every product of a page, with its variants and category ids. */\nexport function snapshotsOf({ repos }: RebuildDeps) {\n return async (tx: ReadTx, page: KeysetPage): Promise<ProductSnapshot[]> => {\n const out: ProductSnapshot[] = []\n for (const p of await repos.product.listPage(tx, page)) {\n out.push(await productSnapshot(tx, repos, p))\n }\n return out\n }\n}\n\nexport const catalogue: ReadModel = {\n name: 'catalogue',\n target: 'documents',\n collections: [CATEGORIES, PRODUCTS, PRODUCTS_BY_CATEGORY],\n\n async *rebuild(ctx) {\n const { config, repos, logger } = ctx.deps\n const storeId = config.store.name\n const categories = new Map<string, Category>()\n for await (const page of ctx.pages('categories', (tx, p) => repos.category.listPage(tx, p))) {\n for (const c of page) {\n categories.set(c.id, c)\n yield { collection: CATEGORIES, key: c.slug, doc: buildCategoryDoc(c, storeId) }\n }\n }\n const context = { storeId, currency: config.store.currency, logger }\n for await (const page of ctx.pages('products', snapshotsOf(ctx.deps))) {\n for (const snapshot of page) {\n yield* productWrites(buildProductDoc(snapshot, categories, context))\n }\n }\n },\n\n handlers({ config, documentStore, logger, repos }) {\n const product = {\n documentStore,\n logger,\n storeId: config.store.name,\n currency: config.store.currency,\n repos,\n }\n return [\n ...categoryProjection({ documentStore, logger, storeId: config.store.name, repos }),\n ...productProjection(product),\n ...inventoryProjection(product),\n ]\n },\n}\n","import { customerProjection } from '../handlers/projections/customer-projection.js'\nimport { buildCustomerProfile, CUSTOMER_PROFILES } from './builders.js'\nimport type { ReadModel } from './model.js'\n\nexport const customers: ReadModel = {\n name: 'customers',\n target: 'documents',\n collections: [CUSTOMER_PROFILES],\n\n async *rebuild(ctx) {\n const { repos } = ctx.deps\n for await (const page of ctx.pages('customers', (tx, p) => repos.customer.listPage(tx, p))) {\n for (const c of page) {\n yield { collection: CUSTOMER_PROFILES, key: c.id, doc: buildCustomerProfile(c) }\n }\n }\n },\n\n handlers({ documentStore, logger, repos }) {\n return customerProjection({\n documentStore,\n logger,\n customerRepo: repos.customer,\n orderRepo: repos.order,\n })\n },\n}\n","import type { NymbalConfig } from '@nymbalhq/config'\nimport type { DocumentStoreAdapter, Logger, SearchAdapter } from '@nymbalhq/types'\nimport type { CommandStore, ReadTx } from '../db/command-store.js'\nimport type { DerivedHandler } from '../handlers/derived.js'\nimport type { KeysetPage, Repositories } from '../repositories/index.js'\nimport type { LoggedEvent } from '../repositories/event-log.js'\nimport type { DocumentWrite } from './builders.js'\n\nexport type ReadModelName = 'catalogue' | 'orders' | 'customers' | 'search' | 'recently-viewed'\n\n/** The pseudo-collection a search model's writes go to: the search adapter, not the document store. */\nexport const SEARCH_INDEX = 'index'\n\nexport interface RebuildDeps {\n config: NymbalConfig\n store: CommandStore\n repos: Repositories\n /** Where the document models are rebuilt and caught up. */\n documentStore: DocumentStoreAdapter\n /** Where the search model is rebuilt and caught up; the search model cannot be rebuilt without it. */\n search?: SearchAdapter\n logger: Logger\n /** Rows per page read from the command store. */\n pageSize?: number\n /** Called before each page is read. */\n onPage?: (page: { model: ReadModelName; table: string; page: number }) => void | Promise<void>\n}\n\n/** What a rebuilder reads with: the command store in pages, each page a read of its own. */\nexport interface RebuildContext {\n deps: RebuildDeps\n pages<T extends { id: string }>(\n table: string,\n read: (tx: ReadTx, page: KeysetPage) => Promise<T[]>,\n ): AsyncIterable<T[]>\n /**\n * The logged events of `types`, in seq pages, each page a read of its own (`onPage` names the table `events`). A model\n * that reads them is caught up only with events above the last one it read: re-applying one it already folded\n * would fold it twice. The bound is per model, not per collection: a model that reads both `pages()` and `events()`\n * would skip catch-up for the collections it builds from tables.\n */\n events(types: readonly string[]): AsyncIterable<LoggedEvent[]>\n}\n\nexport interface ReadModel {\n name: ReadModelName\n /** Where its documents go: document-store collections, or the search adapter. */\n target: 'documents' | 'search'\n /** The document-store collections it owns; the search model owns none. */\n collections: readonly string[]\n /** Every document of the model, from the authoritative tables. A search model writes to `SEARCH_INDEX`. */\n rebuild(ctx: RebuildContext): AsyncIterable<DocumentWrite>\n /** The live projections that keep the model, bound to `deps`' document store and search adapter. */\n handlers(deps: RebuildDeps): DerivedHandler[]\n}\n\n/** The search adapter of `deps`, which the search model needs. */\nexport function searchOf(deps: RebuildDeps): SearchAdapter {\n if (deps.search === undefined) throw new Error('the search read model needs a search adapter')\n return deps.search\n}\n","import { orderProjection } from '../handlers/projections/order-projection.js'\nimport {\n buildOrderDoc,\n orderWrites,\n ORDERS,\n ORDERS_BY_CUSTOMER,\n type OrderDoc,\n} from './builders.js'\nimport type { ReadModel } from './model.js'\n\nexport const orders: ReadModel = {\n name: 'orders',\n target: 'documents',\n collections: [ORDERS, ORDERS_BY_CUSTOMER],\n\n async *rebuild(ctx) {\n const { repos } = ctx.deps\n const docs = ctx.pages('orders', async (tx, page) => {\n const out: Array<OrderDoc & { id: string }> = []\n for (const order of await repos.order.listPage(tx, page)) {\n out.push(buildOrderDoc(order, await repos.orderHistory.listByOrder(tx, order.id)))\n }\n return out\n })\n for await (const page of docs) {\n for (const doc of page) yield* orderWrites(doc)\n }\n },\n\n handlers({ documentStore, logger, repos }) {\n return orderProjection({\n documentStore,\n logger,\n orderRepo: repos.order,\n orderHistoryRepo: repos.orderHistory,\n })\n },\n}\n","import { searchHandler } from '../handlers/side-effects/search-handler.js'\nimport { buildSearchDoc } from './builders.js'\nimport { snapshotsOf } from './catalogue.js'\nimport { SEARCH_INDEX, searchOf, type ReadModel } from './model.js'\n\nexport const search: ReadModel = {\n name: 'search',\n target: 'search',\n collections: [],\n\n async *rebuild(ctx) {\n for await (const page of ctx.pages('products', snapshotsOf(ctx.deps))) {\n for (const snapshot of page) {\n const doc = buildSearchDoc(snapshot)\n yield { collection: SEARCH_INDEX, key: doc.id, doc }\n }\n }\n },\n\n handlers(deps) {\n return searchHandler({ search: searchOf(deps), repos: deps.repos })\n },\n}\n","import type { Logger } from '@nymbalhq/types'\nimport type { InventoryService } from '../services/inventory-service.js'\nimport type { InventoryReservationRepository } from '../repositories/inventory-reservation.js'\nimport { newCorrelationId, runWithCorrelation } from '../events/correlation.js'\nimport { runAsActor } from '../audit/actor.js'\nimport { auditedCommand } from '../audit/audit.js'\n\nexport interface SweeperHandle {\n /** One sweep, awaited; the interval calls it. */\n tick(): Promise<void>\n stop(): void\n}\n\nexport interface InventoryReservationSweeperDeps {\n inventoryService: InventoryService\n reservationRepo: InventoryReservationRepository\n logger: Logger\n intervalMs?: number\n}\n\nexport function startInventoryReservationSweeper(\n deps: InventoryReservationSweeperDeps,\n): SweeperHandle {\n const intervalMs = deps.intervalMs ?? 60_000\n const logger = deps.logger.child({ sweeper: 'inventory-reservation' })\n let running = false\n async function tick(): Promise<void> {\n if (running) return\n running = true\n try {\n const { store } = deps.reservationRepo\n const now = new Date()\n const expired = await store.read((tx) => deps.reservationRepo.findExpiredBefore(tx, now))\n if (expired.length > 0) {\n logger.info({ count: expired.length }, 'releasing expired reservations')\n }\n for (const r of expired) {\n // releaseReservation deletes the row and restores its stock in one transaction; one that a commit or another\n // release already took is a no-op, and leaves no entry. Each release is a command of its own.\n await auditedCommand(store, 'inventory.releaseExpired', () =>\n deps.inventoryService.releaseReservation(r.reservationId, 'expired'),\n ).catch((err) => {\n logger.error({ err, reservationId: r.reservationId }, 'failed to release')\n })\n }\n } finally {\n running = false\n }\n }\n // Each run is one operation: its events share an id of their own, and its commands are the system's.\n const run = () =>\n runWithCorrelation(newCorrelationId('sweep:reservations'), () =>\n runAsActor({ kind: 'system', id: 'reservations' }, tick),\n )\n const handle = setInterval(() => {\n void run()\n }, intervalMs)\n return {\n tick: run,\n stop() {\n clearInterval(handle)\n },\n }\n}\n","import { EVT_CART_ABANDONED, type Logger } from '@nymbalhq/types'\nimport type { CommandStore } from '../db/command-store.js'\nimport type { CartRepository } from '../repositories/cart.js'\nimport type { EventPublisher } from '../events/publisher.js'\nimport {\n currentCorrelationId,\n newCorrelationId,\n runWithCorrelation,\n} from '../events/correlation.js'\nimport { runAsActor } from '../audit/actor.js'\nimport { audit, auditedCommand } from '../audit/audit.js'\nimport type { SweeperHandle } from './inventory-reservation-sweeper.js'\n\nconst COMMAND = 'cart.sweepAbandoned'\n\nexport interface CartAbandonmentSweeperDeps {\n store: CommandStore\n carts: CartRepository\n publisher: EventPublisher\n logger: Logger\n intervalMs?: number\n inactivityMs?: number\n /** Carts claimed per transaction; a tick runs as many as it takes to reach every due cart. */\n batchSize?: number\n now?: () => Date\n}\n\n/**\n * Deletes expired carts, then notifies each cart idle past `inactivityMs` once per inactivity period. The notice is\n * a durable claim on the cart row, committed with its `cart.abandoned` event, so a restart or another replica's\n * sweeper does not notify the same period again; a cart write clears the claim.\n */\nexport function startCartAbandonmentSweeper(deps: CartAbandonmentSweeperDeps): SweeperHandle {\n const { store, carts, publisher } = deps\n const intervalMs = deps.intervalMs ?? 5 * 60_000\n const inactivityMs = deps.inactivityMs ?? 24 * 60 * 60_000\n const batchSize = deps.batchSize ?? 500\n const now = deps.now ?? (() => new Date())\n const logger = deps.logger.child({ sweeper: 'cart-abandonment' })\n\n async function tick(): Promise<void> {\n try {\n const at = now()\n const window = { at, cutoff: new Date(at.getTime() - inactivityMs) }\n // The run is one command, noted only once it changes a cart. Its subject is the run, never a cart's token: a token\n // is a bearer credential, and an entry is kept for good.\n const noteRun = () =>\n audit.note(COMMAND, [{ type: 'sweep', id: currentCorrelationId() ?? 'cart-abandonment' }])\n // Expired carts go first, so a cart past its expiry is never notified.\n const expired = await store.transaction(async (tx) => {\n const deleted = await carts.deleteExpired(tx, at)\n if (deleted > 0) noteRun()\n return deleted\n })\n let abandoned = 0\n // Pages follow the token order rather than \"whatever is still unclaimed\", so a pass ends even when another\n // sweeper holds or has taken some of the rows.\n let after: string | undefined\n for (;;) {\n const page = await store.transaction(async (tx) => {\n const tokens = await carts.listAbandoned(tx, window, { after, limit: batchSize })\n for (const token of tokens) {\n const claimed = await carts.claimAbandoned(tx, token, window)\n if (claimed === null) continue\n noteRun()\n await publisher.publish(EVT_CART_ABANDONED, {\n cartId: claimed.token,\n lastActivityAt: claimed.lastActivityAt,\n })\n abandoned += 1\n }\n return tokens\n })\n if (page.length < batchSize) break\n after = page[page.length - 1]\n }\n if (expired > 0 || abandoned > 0) logger.info({ expired, abandoned }, 'carts swept')\n } catch (err) {\n logger.error({ err }, 'cart-abandonment sweep failed')\n }\n }\n\n // Each run is one operation: its events share an id of their own, and it is one command of the system's.\n const run = () =>\n runWithCorrelation(newCorrelationId('sweep:cart-abandonment'), () =>\n runAsActor({ kind: 'system', id: 'cart-abandonment' }, () =>\n auditedCommand(store, COMMAND, tick),\n ),\n )\n const handle = setInterval(() => void run(), intervalMs)\n return {\n tick: run,\n stop() {\n clearInterval(handle)\n },\n }\n}\n","import { promisify } from 'node:util'\nimport { gzip } from 'node:zlib'\nimport type { Logger } from '@nymbalhq/types'\nimport type { CommandStore } from '../db/command-store.js'\nimport type { EventLogRepository, LoggedEvent } from '../repositories/event-log.js'\nimport type { ProcessedEventRepository } from '../repositories/processed-event.js'\nimport type { SweeperHandle } from './inventory-reservation-sweeper.js'\n\n/** Where retention writes events before it deletes them: one object per batch, private to the operator. */\nexport interface EventArchiveWriter {\n put(key: string, body: Uint8Array, contentType: string): Promise<void>\n}\n\nexport interface EventRetentionSweeperDeps {\n store: CommandStore\n eventLog: EventLogRepository\n processedEvents: ProcessedEventRepository\n logger: Logger\n retentionDays?: number\n intervalMs?: number\n /** When set, delivered events past retention are archived here first, and deleted only once the put succeeds. */\n archive?: EventArchiveWriter\n}\n\nconst DAY_MS = 24 * 60 * 60 * 1000\nconst ARCHIVE_BATCH = 5000\nconst gzipAsync = promisify(gzip)\n\nconst pad = (n: number) => String(n).padStart(2, '0')\n\n/** `events/<yyyy>/<mm>/<dd>/<firstSeq>-<lastSeq>.ndjson.gz`, dated in UTC by the first row's append. */\nfunction archiveKey(batch: LoggedEvent[]): string {\n const first = batch[0]!\n const last = batch[batch.length - 1]!\n const at = first.createdAt\n const day = `${at.getUTCFullYear()}/${pad(at.getUTCMonth() + 1)}/${pad(at.getUTCDate())}`\n return `events/${day}/${first.seq}-${last.seq}.ndjson.gz`\n}\n\n/** One line per event: its envelope, with the log's `seq` and `deliveredAt`. */\nfunction archiveBody(batch: LoggedEvent[]): Promise<Buffer> {\n const lines = batch.map(\n (row) => `${JSON.stringify({ ...row.event, seq: row.seq, deliveredAt: row.deliveredAt })}\\n`,\n )\n return gzipAsync(lines.join(''))\n}\n\n/**\n * Deletes delivered events and processed-event records older than the window; undelivered and dead events stay. With\n * an archive, events go to it in `seq`-ordered batches first.\n */\nexport function startEventRetentionSweeper(deps: EventRetentionSweeperDeps): SweeperHandle {\n const retentionDays = deps.retentionDays ?? 30\n const intervalMs = deps.intervalMs ?? 3_600_000\n const logger = deps.logger.child({ sweeper: 'event-retention' })\n const { archive } = deps\n let running = false\n // The last seq of a batch whose put failed or whose delete did not follow. The next attempt ends there, so it writes\n // that key again rather than a wider batch overlapping it; the object may already exist, so readers dedupe by seq.\n let unconfirmedLastSeq: number | undefined\n\n /** Archives, then deletes, every delivered event past `cutoff`, batch by batch; a failed put stops the run. */\n async function archiveThenDelete(writer: EventArchiveWriter, cutoff: Date): Promise<number> {\n let deleted = 0\n for (;;) {\n const retry = unconfirmedLastSeq\n let batch = await deps.store.read((tx) =>\n deps.eventLog.listDeliveredBefore(tx, cutoff, ARCHIVE_BATCH),\n )\n if (retry !== undefined) batch = batch.filter((row) => row.seq <= retry)\n if (batch.length === 0) {\n // An unconfirmed batch's rows may have gone another way (another replica's sweep): nothing is pending then.\n unconfirmedLastSeq = undefined\n if (retry !== undefined) continue\n return deleted\n }\n unconfirmedLastSeq = batch[batch.length - 1]!.seq\n await writer.put(archiveKey(batch), await archiveBody(batch), 'application/gzip')\n const seqs = batch.map((row) => row.seq)\n deleted += await deps.store.transaction((tx) => deps.eventLog.deleteSeqs(tx, seqs))\n unconfirmedLastSeq = undefined\n if (retry === undefined && batch.length < ARCHIVE_BATCH) return deleted\n }\n }\n\n async function tick(): Promise<void> {\n if (running) return\n running = true\n try {\n const cutoff = new Date(Date.now() - retentionDays * DAY_MS)\n let deleted: { events: number; processed: number }\n if (archive === undefined) {\n deleted = await deps.store.transaction(async (tx) => ({\n events: await deps.eventLog.deleteDeliveredBefore(tx, cutoff),\n processed: await deps.processedEvents.deleteBefore(tx, cutoff),\n }))\n } else {\n const processed = await deps.store.transaction((tx) =>\n deps.processedEvents.deleteBefore(tx, cutoff),\n )\n deleted = { processed, events: await archiveThenDelete(archive, cutoff) }\n }\n if (deleted.events > 0 || deleted.processed > 0) {\n logger.info({ ...deleted, cutoff: cutoff.toISOString() }, 'deleted expired event records')\n }\n } catch (err) {\n logger.error({ err }, 'event retention sweep failed; undeleted events stay for the next run')\n } finally {\n running = false\n }\n }\n\n const handle = setInterval(() => void tick(), intervalMs)\n handle.unref()\n return {\n tick,\n stop() {\n clearInterval(handle)\n },\n }\n}\n","import type { RateLimitAction } from '@nymbalhq/types'\n\nexport interface ParsedRule {\n pattern: string\n regex: RegExp\n requests: number\n windowMs: number\n action: RateLimitAction\n}\n\ninterface Bucket {\n count: number\n resetAt: number\n}\n\nexport class RateLimiter {\n readonly #rules: ParsedRule[]\n readonly #buckets = new Map<string, Bucket>()\n\n constructor(\n rules: Record<string, { requests: number; window: string; action: RateLimitAction }>,\n ) {\n this.#rules = Object.entries(rules).map(([pattern, rule]) => ({\n pattern,\n regex: compilePathPattern(pattern),\n requests: rule.requests,\n windowMs: parseWindow(rule.window),\n action: rule.action,\n }))\n }\n\n check(ip: string, path: string): { allowed: boolean; action: RateLimitAction; retryAfter?: number } | null {\n const rule = this.#rules.find((r) => r.regex.test(path))\n if (!rule) return null\n const key = `${rule.pattern}|${ip}`\n const now = Date.now()\n const bucket = this.#buckets.get(key)\n if (!bucket || bucket.resetAt <= now) {\n this.#buckets.set(key, { count: 1, resetAt: now + rule.windowMs })\n return { allowed: true, action: rule.action }\n }\n bucket.count += 1\n if (bucket.count > rule.requests) {\n return {\n allowed: false,\n action: rule.action,\n retryAfter: Math.max(1, Math.ceil((bucket.resetAt - now) / 1000)),\n }\n }\n return { allowed: true, action: rule.action }\n }\n\n reset(): void {\n this.#buckets.clear()\n }\n}\n\nfunction parseWindow(window: string): number {\n const match = /^(\\d+)(ms|s|m|h)$/.exec(window)\n if (!match) throw new Error(`Invalid rate-limit window: ${window}`)\n const n = Number(match[1])\n switch (match[2]) {\n case 'ms':\n return n\n case 's':\n return n * 1000\n case 'm':\n return n * 60_000\n case 'h':\n return n * 3_600_000\n default:\n throw new Error(`Unreachable unit: ${match[2]}`)\n }\n}\n\nfunction compilePathPattern(pattern: string): RegExp {\n const escaped = pattern\n .replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\*\\*/g, '__DOUBLESTAR__')\n .replace(/\\*/g, '[^/]+')\n .replace(/__DOUBLESTAR__/g, '.*')\n return new RegExp(`^${escaped}$`)\n}\n","import { existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { nymbalConfigSchema, type NymbalConfig } from '@nymbalhq/config'\nimport {\n boundedHealthCheck,\n connectionSecrets,\n displayUrl,\n errorText,\n HEALTH_CHECK_TIMEOUT_MS,\n type CommerceSlot,\n type DocumentStoreAdapter,\n type HealthReport,\n type HealthStatus,\n type Logger,\n type Slot,\n} from '@nymbalhq/types'\nimport { declaredSettings, importProviderPackage, PROVIDER_PACKAGES } from './adapters/loader.js'\nimport {\n checkInjectedSlot,\n COMMERCE_SLOTS,\n resolvePaymentsAdapter,\n resolveSecurityAdapter,\n slotBuilders,\n type InjectedAdapters,\n} from './adapters/registry.js'\nimport {\n createCommandStore,\n rawClients,\n sqliteFile,\n type CommandStore,\n type RawClients,\n} from './db/command-store.js'\nimport { migrationState } from './db/migrate.js'\nimport { createLogger } from './logger.js'\nimport { buildDocumentStore, buildEventBus, buildMedia, redisUrlOf } from './platform.js'\nimport { createEventLogRepository } from './repositories/event-log.js'\nimport { buildRepositories, type SettingRow } from './repositories/index.js'\nimport { listStoredSettings, settingValues } from './settings/load.js'\nimport type { SettingValue } from './settings/resolve.js'\nimport { scrub, scrubbingLogger } from './settings/secret-set.js'\n\n/** `ok` is a check with no health semantics (config, a package, migrations); the rest are a health report's. */\nexport type DiagnosisStatus = HealthStatus | 'ok'\n\nexport interface DiagnosisCheck {\n name: string\n status: DiagnosisStatus\n detail: string\n}\n\nexport interface DiagnosisReport {\n checks: DiagnosisCheck[]\n}\n\nexport interface DiagnoseOptions {\n /** The project's adapters, one per slot whose provider is `custom`, as `createApp` takes them. */\n adapters?: InjectedAdapters\n logger?: Logger\n /** Each check's bound; `HEALTH_CHECK_TIMEOUT_MS` when not given. */\n timeoutMs?: number\n env?: NodeJS.ProcessEnv\n sqlitePath?: string\n postgresUrl?: string\n mediaRoot?: string\n /** Where the migrations journal is read; the platform's own migrations when not given. */\n migrationsRoot?: string\n}\n\nconst OWN_MIGRATIONS = fileURLToPath(new URL('../migrations', import.meta.url))\n\nconst PRIMITIVES = ['documentStore', 'eventBus', 'media'] as const\ntype PrimitiveName = (typeof PRIMITIVES)[number]\n\n/** What a primitive or a slot adapter may answer; a third-party one may lack `healthCheck`. */\ninterface Checkable {\n healthCheck?: () => Promise<HealthReport>\n}\n\ntype Outcome<T> = { ok: true; value: T } | { ok: false; detail: string }\n\n/**\n * Runs `run` within the bound. Something it opens after the bound has passed is handed to `dispose`, so a late\n * connection is not left open.\n */\nasync function within<T>(\n timeoutMs: number,\n run: () => Promise<T>,\n dispose?: (late: T) => Promise<void>,\n): Promise<Outcome<T>> {\n let timer: NodeJS.Timeout | undefined\n let timedOut = false\n // A run that throws before returning a promise is a failed outcome like a rejection, not an escape.\n const work = Promise.resolve().then(run)\n const timeout = new Promise<Outcome<T>>((resolveTimeout) => {\n timer = setTimeout(() => {\n timedOut = true\n resolveTimeout({ ok: false, detail: `timed out after ${timeoutMs} ms` })\n }, timeoutMs)\n })\n try {\n return await Promise.race([\n work.then(\n (value): Outcome<T> => ({ ok: true, value }),\n (error: unknown): Outcome<T> => ({ ok: false, detail: errorText(error) }),\n ),\n timeout,\n ])\n } finally {\n clearTimeout(timer)\n if (timedOut && dispose !== undefined) {\n // The check is already reported as timed out; a late open that fails, or a close that does, adds nothing.\n work.then(dispose).catch(() => undefined)\n }\n }\n}\n\n/** A store that did not open, held by the slot adapters that are built over one: any use of it rejects. */\nfunction unavailableCommandStore(kind: CommandStore['kind']): CommandStore {\n const refuse = () => Promise.reject(new Error('the command store is down'))\n return { kind, read: refuse, transaction: refuse, savepoint: refuse, close: async () => {} }\n}\n\n/** The raw clients of a store that did not open: any use of a client throws, as a down store's would. */\nfunction unavailableRawClients(kind: CommandStore['kind']): RawClients {\n const refuse = () => {\n throw new Error('the command store is down')\n }\n const client = new Proxy({}, { get: () => refuse })\n return kind === 'sqlite'\n ? { kind, db: client as never, raw: client as never }\n : { kind, db: client as never, pool: client as never }\n}\n\nfunction unavailableDocumentStore(): DocumentStoreAdapter {\n const refuse = () => Promise.reject(new Error('the document store is down'))\n return {\n capabilities: () => [],\n get: refuse,\n put: refuse,\n delete: refuse,\n query: refuse,\n batchGet: refuse,\n batchPut: refuse,\n replaceCollection: refuse,\n close: async () => {},\n }\n}\n\n/** A line's detail: what was checked (a provider, and where it connects), then what the check said. */\nfunction described(what: string, detail: string | undefined): string {\n return detail === undefined || detail === '' ? what : `${what}: ${detail}`\n}\n\nfunction notChecked(prerequisite: string): string {\n return `not checked: ${prerequisite} down`\n}\n\n/**\n * Checks a project without changing it: its config, the packages its providers live in, the command store and its\n * migrations, and the health of every commerce slot, the security slot and every primitive. It builds what `createApp`\n * builds, through the same registry and constructors, and nothing more: no warm-up, no relay, no sweeper, no migrator,\n * no seed, and no primitive's `initialize()` (the security adapter's makes no request). The command store is opened read-only. Every connection is closed before it returns.\n */\nexport async function diagnose(\n input: NymbalConfig,\n options: DiagnoseOptions = {},\n): Promise<DiagnosisReport> {\n const parsed = nymbalConfigSchema.safeParse(input)\n if (!parsed.success) {\n const detail = parsed.error.issues\n .map(\n (issue) => `${issue.path.length > 0 ? issue.path.join('.') : '<root>'}: ${issue.message}`,\n )\n .join('; ')\n return { checks: [{ name: 'config', status: 'down', detail }] }\n }\n const config = parsed.data\n const timeoutMs = options.timeoutMs ?? HEALTH_CHECK_TIMEOUT_MS\n const env = options.env ?? process.env\n const logger = scrubbingLogger(\n options.logger ?? createLogger({ base: { store: config.store.name } }),\n )\n const injected = options.adapters ?? {}\n const infrastructure = config.infrastructure\n const providers: Record<Slot, string> = {\n ...(Object.fromEntries(COMMERCE_SLOTS.map((s) => [s, config.commerce[s].provider])) as Record<\n CommerceSlot,\n string\n >),\n documentStore: infrastructure.documentStore,\n eventBus: infrastructure.eventBus,\n media: infrastructure.media,\n security: config.security.adapter,\n }\n\n const packages: DiagnosisCheck[] = []\n for (const slot of [...COMMERCE_SLOTS, ...PRIMITIVES, 'security'] as const) {\n const entry = PROVIDER_PACKAGES[slot]?.[providers[slot]]\n if (entry === undefined) continue\n const found = await within(timeoutMs, () => importProviderPackage(slot, providers[slot], env))\n packages.push({\n name: `package ${slot}`,\n status: found.ok ? 'ok' : 'down',\n detail: found.ok ? entry.package : found.detail,\n })\n }\n\n const closers: Array<() => Promise<void>> = []\n let commandStore: CommandStore | undefined\n let storeCheck: DiagnosisCheck\n let migrationsCheck: DiagnosisCheck\n const storeOptions = {\n readOnly: true,\n ...(options.sqlitePath !== undefined && { sqlitePath: options.sqlitePath }),\n ...(options.postgresUrl !== undefined && { postgresUrl: options.postgresUrl }),\n }\n const postgresUrl =\n options.postgresUrl ?? (env['DATABASE_URL'] === '' ? undefined : env['DATABASE_URL'])\n const redisUrl = redisUrlOf(config, env)\n const where =\n infrastructure.commandStore === 'sqlite'\n ? `sqlite ${sqliteFile(storeOptions)}`\n : `postgres ${postgresUrl === undefined ? '(no DATABASE_URL)' : displayUrl(postgresUrl)}`\n if (infrastructure.commandStore === 'sqlite' && !existsSync(resolve(sqliteFile(storeOptions)))) {\n storeCheck = {\n name: 'command store',\n status: 'down',\n detail: `no database at ${sqliteFile(storeOptions)}: run \\`nymbal migrate\\``,\n }\n } else {\n const opened = await within(\n timeoutMs,\n async () => {\n const store = createCommandStore(config, storeOptions)\n try {\n const clients = rawClients(store)\n if (clients.kind === 'sqlite') clients.raw.prepare('SELECT 1').get()\n else await clients.pool.query('SELECT 1')\n return store\n } catch (error) {\n // The probe's error is the one reported; closing a store that never answered may fail as well.\n await store.close().catch(() => undefined)\n throw error\n }\n },\n (late) => late.close(),\n )\n if (opened.ok) {\n commandStore = opened.value\n closers.push(() => opened.value.close())\n storeCheck = { name: 'command store', status: 'healthy', detail: where }\n } else {\n storeCheck = { name: 'command store', status: 'down', detail: `${where}: ${opened.detail}` }\n }\n }\n if (commandStore === undefined) {\n migrationsCheck = { name: 'migrations', status: 'down', detail: notChecked('command store') }\n } else {\n const store = commandStore\n const state = await within(timeoutMs, () =>\n migrationState(store, { migrationsRoot: options.migrationsRoot ?? OWN_MIGRATIONS }),\n )\n migrationsCheck = !state.ok\n ? { name: 'migrations', status: 'down', detail: state.detail }\n : state.value.pending > 0\n ? {\n name: 'migrations',\n status: 'down',\n detail: `${state.value.pending} pending: run \\`nymbal migrate\\``,\n }\n : {\n name: 'migrations',\n status: 'ok',\n detail: `${state.value.applied} applied, none pending`,\n }\n }\n\n const primitiveOptions = {\n logger,\n env,\n ...(options.postgresUrl !== undefined && { postgresUrl: options.postgresUrl }),\n ...(options.mediaRoot !== undefined && { mediaRoot: options.mediaRoot }),\n }\n /** A primitive as its line names it: the provider, and the server it connects to, if any. */\n const subject = (name: PrimitiveName): string => {\n const provider = providers[name]\n const url =\n provider === 'redis' || provider === 'redis-streams'\n ? redisUrl\n : provider === 'postgres-jsonb'\n ? postgresUrl\n : undefined\n return url === undefined ? provider : `${provider} ${displayUrl(url)}`\n }\n const built: Partial<Record<PrimitiveName, Checkable>> = {}\n const primitiveFailures: Partial<Record<PrimitiveName, string>> = {}\n let documentStore: DocumentStoreAdapter | undefined\n if (infrastructure.documentStore === 'postgres-jsonb' && commandStore === undefined) {\n primitiveFailures.documentStore = notChecked('command store')\n } else {\n const store = await within(\n timeoutMs,\n () => buildDocumentStore(config, primitiveOptions, logger, env),\n (late) => late.close(),\n )\n if (store.ok) {\n documentStore = store.value\n built.documentStore = store.value\n closers.unshift(() => store.value.close())\n } else {\n primitiveFailures.documentStore = described(subject('documentStore'), store.detail)\n }\n }\n const bus = await within(\n timeoutMs,\n () => buildEventBus(config, logger, env),\n (late) => late.close(),\n )\n if (bus.ok) {\n built.eventBus = bus.value\n closers.unshift(() => bus.value.close())\n } else {\n primitiveFailures.eventBus = described(subject('eventBus'), bus.detail)\n }\n const media = await within(timeoutMs, () => buildMedia(config, primitiveOptions, logger, env))\n if (media.ok) built.media = media.value\n else primitiveFailures.media = described(subject('media'), media.detail)\n\n const health = (subject: Checkable): Promise<HealthReport> => {\n if (typeof subject.healthCheck !== 'function') {\n return Promise.resolve({ status: 'degraded', detail: 'no healthCheck' })\n }\n const check = subject.healthCheck.bind(subject)\n return boundedHealthCheck(() => check(), { timeoutMs })\n }\n\n // The rows Settings hold fill each slot as createApp fills it; a store that did not open holds none.\n const stored: Outcome<SettingRow[]> =\n commandStore === undefined\n ? { ok: true, value: [] }\n : await within(timeoutMs, () => listStoredSettings(commandStore))\n /** The values Settings give `slot`'s declared fields, decrypted; a row that cannot be read fails the slot. */\n const settingsOf = async (slot: CommerceSlot): Promise<SettingValue[]> => {\n const provider = providers[slot]\n if (provider === 'custom') return []\n const declared = declaredSettings(await importProviderPackage(slot, provider, env))\n if (declared.length === 0) return []\n if (!stored.ok) throw new Error(`settings not read: ${stored.detail}`)\n return settingValues(config, [{ slot, provider, declared }], stored.value, env, logger)\n }\n\n const slots: DiagnosisCheck[] = []\n const adapterLogger = logger.child({ layer: 'adapter' })\n const builderDeps = {\n config,\n logger: adapterLogger,\n sql:\n commandStore === undefined\n ? unavailableRawClients(infrastructure.commandStore)\n : rawClients(commandStore),\n repos: buildRepositories(\n commandStore ?? unavailableCommandStore(infrastructure.commandStore),\n documentStore ?? unavailableDocumentStore(),\n ),\n injected,\n }\n for (const slot of COMMERCE_SLOTS) {\n const provider = providers[slot]\n const adapter = await within(timeoutMs, async (): Promise<Checkable | null> => {\n checkInjectedSlot(config, slot, injected)\n const settings = await settingsOf(slot)\n return slot === 'payments'\n ? resolvePaymentsAdapter(config, adapterLogger, injected, settings)\n : slotBuilders({ ...builderDeps, settings })[slot]()\n })\n if (!adapter.ok) {\n slots.push({\n name: `slot ${slot}`,\n status: 'down',\n detail: described(provider, adapter.detail),\n })\n } else if (adapter.value === null) {\n slots.push({ name: `slot ${slot}`, status: 'ok', detail: provider })\n } else {\n slots.push(fromReport(`slot ${slot}`, provider, await health(adapter.value)))\n }\n }\n\n const securityAdapter = await within(timeoutMs, () =>\n resolveSecurityAdapter(config, adapterLogger, env),\n )\n slots.push(\n securityAdapter.ok\n ? fromReport('slot security', providers.security, await health(securityAdapter.value))\n : {\n name: 'slot security',\n status: 'down',\n detail: described(providers.security, securityAdapter.detail),\n },\n )\n\n const primitives: DiagnosisCheck[] = []\n for (const name of PRIMITIVES) {\n const primitive = built[name]\n if (primitive === undefined) {\n primitives.push({\n name: `primitive ${name}`,\n status: 'down',\n detail: primitiveFailures[name] ?? '',\n })\n } else {\n primitives.push(fromReport(`primitive ${name}`, subject(name), await health(primitive)))\n }\n }\n\n const eventsCheck: DiagnosisCheck =\n commandStore === undefined\n ? { name: 'events', status: 'down', detail: notChecked('command store') }\n : migrationsCheck.status !== 'ok'\n ? { name: 'events', status: 'down', detail: notChecked('migrations') }\n : await eventLogCheck(commandStore, timeoutMs)\n\n for (const close of closers) {\n const closed = await within(timeoutMs, close)\n if (!closed.ok) logger.debug({ detail: closed.detail }, 'diagnose: a connection did not close')\n }\n\n const secrets = [postgresUrl, redisUrl].flatMap((url) =>\n url === undefined ? [] : connectionSecrets(url, { user: false }),\n )\n const checks = [\n { name: 'config', status: 'ok' as const, detail: 'valid' },\n ...packages,\n storeCheck,\n migrationsCheck,\n ...slots,\n ...primitives,\n eventsCheck,\n ].map((check) => ({\n ...check,\n detail: scrub(secrets.reduce((text, secret) => text.split(secret).join('***'), check.detail)),\n }))\n return { checks }\n}\n\n/** How many events show when some are dead; the rest are counted. */\nconst DEAD_SHOWN = 5\n\n/** The event log's dead events, the oldest first, and how many wait for a retry: read only. */\nasync function eventLogCheck(store: CommandStore, timeoutMs: number): Promise<DiagnosisCheck> {\n const eventLog = createEventLogRepository(store)\n const read = await within(timeoutMs, () =>\n store.read(async (tx) => ({\n dead: await eventLog.countDead(tx),\n shown: await eventLog.listDead(tx, DEAD_SHOWN),\n waiting: await eventLog.countRetrying(tx),\n })),\n )\n if (!read.ok) return { name: 'events', status: 'down', detail: read.detail }\n const { dead, shown, waiting } = read.value\n if (dead === 0) {\n return { name: 'events', status: 'ok', detail: `none dead, ${waiting} waiting to retry` }\n }\n const named = shown.map((e) => `seq ${e.seq} ${e.event.type} ${e.event.id}`)\n if (dead > shown.length) named.push(`${dead - shown.length} more`)\n return {\n name: 'events',\n status: 'degraded',\n detail: `${dead} dead: ${named.join(', ')}; ${waiting} waiting to retry`,\n }\n}\n\nfunction fromReport(name: string, what: string, report: HealthReport): DiagnosisCheck {\n return { name, status: report.status, detail: described(what, report.detail) }\n}\n","import { inArray } from 'drizzle-orm'\nimport { v7 as uuidv7 } from 'uuid'\nimport bcrypt from 'bcryptjs'\nconst { hashSync } = bcrypt\nimport type {\n DocumentStoreAdapter,\n EventBusAdapter,\n Logger,\n MediaStorage,\n NymbalEvent,\n Role,\n SearchAdapter,\n} from '@nymbalhq/types'\nimport type { NymbalConfig } from '@nymbalhq/config'\nimport { rawClients, type CommandStore } from '../db/command-store.js'\nimport { createCategoryRepository } from '../db/repositories/categories.js'\nimport { createProductRepository } from '../db/repositories/products.js'\nimport { createEventBuilder } from '../events/builder.js'\nimport { EVT_CATEGORY_CREATED, EVT_PRODUCT_CREATED, EVT_CUSTOMER_CREATED } from '@nymbalhq/types'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport { seedCategories, seedImage, seedProducts, type SeedProduct } from './data.js'\nimport { buildRepositories } from '../repositories/index.js'\nimport { READ_MODEL_NAMES, rebuild } from '../read-models/index.js'\n\nexport interface SeedDeps {\n config: NymbalConfig\n commandStore: CommandStore\n documentStore: DocumentStoreAdapter\n eventBus: EventBusAdapter\n logger: Logger\n version: string\n /**\n * When given, each product's image is generated and written here, and the product points at the stored copy\n * instead of the third-party placeholder host: a store measured or run offline then serves its own images.\n */\n media?: MediaStorage\n /** The search index to rebuild with the document store; without it the next start's rebuild fills it. */\n search?: SearchAdapter\n}\n\nexport interface SeedResult {\n categories: number\n products: number\n variants: number\n customers: number\n admins: number\n /** True when any demo row was already in the command store, so nothing was inserted. */\n alreadySeeded: boolean\n}\n\nasync function insertVariants(\n store: CommandStore,\n rows: Array<{\n id: string\n productId: string\n sku: string\n name: string\n priceMinor: number\n stock: number\n options: unknown[]\n createdAt: Date\n updatedAt: Date\n }>,\n): Promise<void> {\n if (rows.length === 0) return\n const clients = rawClients(store)\n if (clients.kind === 'sqlite') {\n const values = rows.map((r) => ({\n id: r.id,\n productId: r.productId,\n sku: r.sku,\n name: r.name,\n priceMinor: r.priceMinor,\n compareAtPriceMinor: null,\n weightGrams: null,\n dimensions: null,\n stock: r.stock,\n lowStockThreshold: 3,\n options: JSON.stringify(r.options),\n status: 'active' as const,\n createdAt: r.createdAt.toISOString(),\n updatedAt: r.updatedAt.toISOString(),\n }))\n clients.db.insert(sqliteSchema.variants).values(values).run()\n return\n }\n const values = rows.map((r) => ({\n id: r.id,\n productId: r.productId,\n sku: r.sku,\n name: r.name,\n priceMinor: r.priceMinor,\n compareAtPriceMinor: null,\n weightGrams: null,\n dimensions: null,\n stock: r.stock,\n lowStockThreshold: 3,\n options: r.options,\n status: 'active' as const,\n createdAt: r.createdAt,\n updatedAt: r.updatedAt,\n }))\n await clients.db.insert(postgresSchema.variants).values(values)\n}\n\nasync function insertProductCategories(\n store: CommandStore,\n rows: Array<{ productId: string; categoryId: string }>,\n): Promise<void> {\n if (rows.length === 0) return\n const clients = rawClients(store)\n if (clients.kind === 'sqlite') {\n clients.db.insert(sqliteSchema.productCategories).values(rows).run()\n return\n }\n await clients.db.insert(postgresSchema.productCategories).values(rows)\n}\n\n/**\n * Any demo row (category slug, product slug, seeded customer email) means an earlier seed ran, in full or in part.\n * Each is unique, so inserting the demo again would fail on the first collision: skip instead.\n */\nasync function demoRowsPresent(store: CommandStore, emails: string[]): Promise<boolean> {\n const categorySlugs = seedCategories.map((c) => c.slug)\n const productSlugs = seedProducts.map((p) => p.slug)\n const clients = rawClients(store)\n if (clients.kind === 'sqlite') {\n const { categories, products, customers } = sqliteSchema\n return (\n clients.db\n .select({ id: categories.id })\n .from(categories)\n .where(inArray(categories.slug, categorySlugs))\n .limit(1)\n .all().length > 0 ||\n clients.db\n .select({ id: products.id })\n .from(products)\n .where(inArray(products.slug, productSlugs))\n .limit(1)\n .all().length > 0 ||\n clients.db\n .select({ id: customers.id })\n .from(customers)\n .where(inArray(customers.email, emails))\n .limit(1)\n .all().length > 0\n )\n }\n const { categories, products, customers } = postgresSchema\n const [category, product, customer] = await Promise.all([\n clients.db\n .select({ id: categories.id })\n .from(categories)\n .where(inArray(categories.slug, categorySlugs))\n .limit(1),\n clients.db\n .select({ id: products.id })\n .from(products)\n .where(inArray(products.slug, productSlugs))\n .limit(1),\n clients.db\n .select({ id: customers.id })\n .from(customers)\n .where(inArray(customers.email, emails))\n .limit(1),\n ])\n return category.length > 0 || product.length > 0 || customer.length > 0\n}\n\nasync function insertCustomer(\n store: CommandStore,\n row: {\n id: string\n email: string\n passwordHash: string\n firstName: string\n lastName: string\n roles?: Role[]\n createdAt: Date\n updatedAt: Date\n },\n): Promise<void> {\n const roles = row.roles ?? ['customer']\n const clients = rawClients(store)\n if (clients.kind === 'sqlite') {\n clients.db\n .insert(sqliteSchema.customers)\n .values({\n id: row.id,\n email: row.email,\n passwordHash: row.passwordHash,\n firstName: row.firstName,\n lastName: row.lastName,\n phone: '',\n addresses: '[]',\n orderCount: 0,\n totalSpentMinor: 0,\n metadata: '{}',\n roles: JSON.stringify(roles),\n requiresPasswordReset: false,\n createdAt: row.createdAt.toISOString(),\n updatedAt: row.updatedAt.toISOString(),\n })\n .run()\n return\n }\n await clients.db.insert(postgresSchema.customers).values({\n id: row.id,\n email: row.email,\n passwordHash: row.passwordHash,\n firstName: row.firstName,\n lastName: row.lastName,\n phone: '',\n addresses: [],\n orderCount: 0,\n totalSpentMinor: 0,\n metadata: {},\n roles,\n requiresPasswordReset: false,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n })\n}\n\nfunction failedOf(err: unknown): unknown {\n return (err as { context?: { failed?: unknown } }).context?.failed ?? []\n}\n\nexport async function runSeed(deps: SeedDeps): Promise<SeedResult> {\n const { config, commandStore, documentStore, eventBus, logger, version } = deps\n const categoryRepo = createCategoryRepository(commandStore)\n const productRepo = createProductRepository(commandStore)\n const makeEvent = createEventBuilder({\n storeId: config.store.name,\n environment: (process.env.NODE_ENV === 'production' ? 'production' : 'development') as\n | 'production'\n | 'development',\n version,\n source: 'nymbal-seed',\n })\n\n const demoEmail = 'demo@nymbal.dev'\n const adminEmail = process.env['NYMBAL_ADMIN_EMAIL'] ?? 'admin@nymbal.local'\n if (await demoRowsPresent(commandStore, [demoEmail, adminEmail])) {\n logger.info({}, 'Demo content already present, seed skipped')\n return { categories: 0, products: 0, variants: 0, customers: 0, admins: 0, alreadySeeded: true }\n }\n\n const now = new Date()\n\n // Categories\n const categoryInserts = seedCategories.map((c, i) => ({\n id: uuidv7(),\n slug: c.slug,\n name: c.name,\n description: c.description,\n parentId: null,\n position: i,\n createdAt: now,\n }))\n await categoryRepo.insertMany(categoryInserts)\n const categoryBySlug = new Map(categoryInserts.map((c) => [c.slug, c]))\n\n const imageUrls = new Map<string, string>()\n if (deps.media !== undefined) {\n for (const p of seedProducts) {\n const { url } = await deps.media.put(`seed/${p.slug}.svg`, seedImage(p), 'image/svg+xml')\n imageUrls.set(p.slug, url)\n }\n }\n\n // Products\n const productInserts = seedProducts.map((p) => ({\n id: uuidv7(),\n slug: p.slug,\n name: p.title,\n description: p.description,\n shortDescription: '',\n status: 'active' as const,\n type: 'simple' as const,\n seoTitle: p.title,\n seoDescription: p.description.slice(0, 160),\n media: [{ url: imageUrls.get(p.slug) ?? p.imageUrl, altText: p.title, position: 0 }],\n metadata: {},\n createdAt: now,\n updatedAt: now,\n }))\n await productRepo.insertMany(productInserts)\n\n // Variants — one per product (simple type)\n const variantInserts = productInserts.map((p, i) => {\n const seed = seedProducts[i] as SeedProduct\n return {\n id: uuidv7(),\n productId: p.id,\n sku: p.slug.toUpperCase().replaceAll('-', '_'),\n name: 'Default',\n priceMinor: seed.priceMinor,\n stock: 25,\n options: [],\n createdAt: now,\n updatedAt: now,\n }\n })\n await insertVariants(commandStore, variantInserts)\n\n // Product ↔ Category joins\n const joinRows = productInserts.map((p, i) => {\n const seed = seedProducts[i] as SeedProduct\n const cat = categoryBySlug.get(seed.categorySlug)\n if (!cat) throw new Error(`Seed references unknown category: ${seed.categorySlug}`)\n return { productId: p.id, categoryId: cat.id }\n })\n await insertProductCategories(commandStore, joinRows)\n\n // Demo customer — password: nymbal\n const demoCustomer = {\n id: uuidv7(),\n email: demoEmail,\n passwordHash: hashSync('nymbal', 10),\n firstName: 'Demo',\n lastName: 'User',\n createdAt: now,\n updatedAt: now,\n }\n await insertCustomer(commandStore, demoCustomer)\n\n // Admin user — email and password from env, defaults for dev\n const adminPassword = process.env['NYMBAL_ADMIN_PASSWORD'] ?? 'nymbal-admin-dev'\n const adminRoles: Role[] = ['admin']\n const adminCustomer = {\n id: uuidv7(),\n email: adminEmail,\n passwordHash: hashSync(adminPassword, 10),\n firstName: 'Admin',\n lastName: 'User',\n roles: adminRoles,\n createdAt: now,\n updatedAt: now,\n }\n await insertCustomer(commandStore, adminCustomer)\n\n // Emit events\n const events = [\n ...categoryInserts.map((c) =>\n makeEvent(EVT_CATEGORY_CREATED, {\n category: {\n id: c.id,\n parentId: c.parentId,\n name: c.name,\n slug: c.slug,\n description: c.description,\n position: c.position,\n createdAt: now.toISOString(),\n },\n }),\n ),\n ...productInserts.map((p, i) => {\n const v = variantInserts[i]!\n const seed = seedProducts[i] as SeedProduct\n const cat = categoryBySlug.get(seed.categorySlug)!\n return makeEvent(EVT_PRODUCT_CREATED, {\n product: {\n id: p.id,\n slug: p.slug,\n name: p.name,\n description: p.description,\n shortDescription: p.shortDescription,\n status: p.status,\n type: p.type,\n seoTitle: p.seoTitle,\n seoDescription: p.seoDescription,\n media: p.media,\n metadata: p.metadata,\n createdAt: now.toISOString(),\n updatedAt: now.toISOString(),\n variants: [\n {\n id: v.id,\n productId: p.id,\n sku: v.sku,\n name: v.name,\n priceMinor: v.priceMinor,\n compareAtPriceMinor: null,\n weightGrams: null,\n dimensions: null,\n stock: v.stock,\n lowStockThreshold: 3,\n options: v.options,\n status: 'active' as const,\n createdAt: now.toISOString(),\n updatedAt: now.toISOString(),\n },\n ],\n categoryIds: [cat.id],\n },\n })\n }),\n makeEvent(EVT_CUSTOMER_CREATED, {\n customerId: demoCustomer.id,\n email: demoCustomer.email,\n }),\n makeEvent(EVT_CUSTOMER_CREATED, {\n customerId: adminCustomer.id,\n email: adminCustomer.email,\n }),\n ]\n // The seed's events are not in the log, so nothing retries them: a handler that fails on one (a welcome mail the\n // mail host refuses) is reported and the seed goes on; its rows are committed, and the rebuild below projects them.\n const failures: Array<{ eventId: string; eventType: string; failed: unknown }> = []\n for (const event of events as NymbalEvent<unknown>[]) {\n try {\n await eventBus.publish(event)\n } catch (err) {\n if ((err as { code?: unknown } | null)?.code !== 'adapter.handler_failed') throw err\n failures.push({ eventId: event.id, eventType: event.type, failed: failedOf(err) })\n }\n }\n if (failures.length > 0) {\n logger.warn({ failures }, 'seed events whose handlers failed; they are not retried')\n }\n\n logger.info({ adminEmail }, 'Admin user seeded')\n if (!process.env['NYMBAL_ADMIN_EMAIL']) {\n console.log(\n `Admin seeded: ${adminEmail} / ${adminPassword} (change NYMBAL_ADMIN_PASSWORD to override)`,\n )\n }\n\n logger.info(\n {\n categories: categoryInserts.length,\n products: productInserts.length,\n variants: variantInserts.length,\n customers: 1,\n admins: 1,\n },\n 'Seed complete',\n )\n\n const search = deps.search\n await rebuild(\n search === undefined ? READ_MODEL_NAMES.filter((name) => name !== 'search') : READ_MODEL_NAMES,\n {\n config,\n store: commandStore,\n repos: buildRepositories(commandStore, documentStore),\n documentStore,\n ...(search !== undefined && { search }),\n logger,\n },\n )\n\n return {\n categories: categoryInserts.length,\n products: productInserts.length,\n variants: variantInserts.length,\n customers: 1,\n admins: 1,\n alreadySeeded: false,\n }\n}\n","export interface SeedCategory {\n slug: string\n name: string\n description: string\n}\n\nexport interface SeedProduct {\n slug: string\n title: string\n description: string\n priceMinor: number\n categorySlug: string\n imageUrl: string\n}\n\nexport const seedCategories: SeedCategory[] = [\n {\n slug: 'apparel',\n name: 'Apparel',\n description: 'Everyday clothing and accessories',\n },\n { slug: 'home', name: 'Home', description: 'Homeware, decor, and kitchen essentials' },\n {\n slug: 'electronics',\n name: 'Electronics',\n description: 'Gadgets, audio, and computing accessories',\n },\n { slug: 'books', name: 'Books', description: 'Fiction, non-fiction, and reference' },\n]\n\nfunction img(seed: string): string {\n return `https://picsum.photos/seed/${encodeURIComponent(seed)}/600/600`\n}\n\nexport const seedProducts: SeedProduct[] = [\n // Apparel — 6\n { slug: 'merino-crew', title: 'Merino Crew Sweater', description: 'Midweight merino wool, unisex fit.', priceMinor: 8900, categorySlug: 'apparel', imageUrl: img('merino-crew') },\n { slug: 'organic-tee', title: 'Organic Cotton Tee', description: 'Heavyweight organic cotton, pre-washed.', priceMinor: 2400, categorySlug: 'apparel', imageUrl: img('organic-tee') },\n { slug: 'selvedge-denim', title: 'Selvedge Denim Jeans', description: '14oz Japanese selvedge, straight leg.', priceMinor: 14500, categorySlug: 'apparel', imageUrl: img('selvedge-denim') },\n { slug: 'runner-socks', title: 'Runner Socks (3-pack)', description: 'Moisture-wicking, cushioned heel.', priceMinor: 1800, categorySlug: 'apparel', imageUrl: img('runner-socks') },\n { slug: 'wool-beanie', title: 'Ribbed Wool Beanie', description: 'Hand-knit in Scotland, one size.', priceMinor: 3200, categorySlug: 'apparel', imageUrl: img('wool-beanie') },\n { slug: 'leather-belt', title: 'Bridle Leather Belt', description: 'Full-grain English bridle leather.', priceMinor: 6500, categorySlug: 'apparel', imageUrl: img('leather-belt') },\n\n // Home — 6\n { slug: 'ceramic-mug', title: 'Stoneware Mug', description: 'Hand-thrown stoneware, 350ml.', priceMinor: 1900, categorySlug: 'home', imageUrl: img('ceramic-mug') },\n { slug: 'linen-sheets', title: 'Washed Linen Sheet Set', description: 'French linen, stonewashed for softness.', priceMinor: 17900, categorySlug: 'home', imageUrl: img('linen-sheets') },\n { slug: 'cast-iron-pan', title: 'Cast Iron Skillet 12\"', description: 'Pre-seasoned, made in the USA.', priceMinor: 7900, categorySlug: 'home', imageUrl: img('cast-iron-pan') },\n { slug: 'soy-candle', title: 'Soy Candle — Fig & Cedar', description: 'Hand-poured, 50hr burn time.', priceMinor: 3400, categorySlug: 'home', imageUrl: img('soy-candle') },\n { slug: 'walnut-board', title: 'Walnut Cutting Board', description: 'End-grain walnut, oiled finish.', priceMinor: 8900, categorySlug: 'home', imageUrl: img('walnut-board') },\n { slug: 'wool-throw', title: 'Lambswool Throw', description: 'Welsh-woven lambswool, 130×180cm.', priceMinor: 11500, categorySlug: 'home', imageUrl: img('wool-throw') },\n\n // Electronics — 6\n { slug: 'wireless-earbuds', title: 'Wireless Earbuds', description: 'Active noise cancellation, 30hr case.', priceMinor: 14900, categorySlug: 'electronics', imageUrl: img('wireless-earbuds') },\n { slug: 'mechanical-keyboard', title: '75% Mechanical Keyboard', description: 'Hot-swap switches, PBT keycaps.', priceMinor: 16500, categorySlug: 'electronics', imageUrl: img('mechanical-keyboard') },\n { slug: 'portable-ssd', title: 'Portable SSD 1TB', description: 'USB-C, 1050MB/s read.', priceMinor: 11900, categorySlug: 'electronics', imageUrl: img('portable-ssd') },\n { slug: 'desk-lamp', title: 'Bias Desk Lamp', description: 'Tunable white, monitor-friendly glare shield.', priceMinor: 9800, categorySlug: 'electronics', imageUrl: img('desk-lamp') },\n { slug: 'usb-c-hub', title: '7-in-1 USB-C Hub', description: 'HDMI 4K60, 100W PD pass-through.', priceMinor: 5900, categorySlug: 'electronics', imageUrl: img('usb-c-hub') },\n { slug: 'bluetooth-speaker', title: 'Portable Bluetooth Speaker', description: 'IPX7 waterproof, 20hr battery.', priceMinor: 8900, categorySlug: 'electronics', imageUrl: img('bluetooth-speaker') },\n\n // Books — 6\n { slug: 'designing-data-intensive-applications', title: 'Designing Data-Intensive Applications', description: 'Martin Kleppmann’s canonical guide to modern data systems.', priceMinor: 3600, categorySlug: 'books', imageUrl: img('ddia') },\n { slug: 'the-pragmatic-programmer', title: 'The Pragmatic Programmer (20th anniversary)', description: 'Hunt & Thomas on the craft of software.', priceMinor: 3200, categorySlug: 'books', imageUrl: img('pragprog') },\n { slug: 'shape-up', title: 'Shape Up', description: 'Stop running in circles — ship work that matters.', priceMinor: 2500, categorySlug: 'books', imageUrl: img('shapeup') },\n { slug: 'the-manager-path', title: 'The Manager’s Path', description: 'Camille Fournier on engineering leadership.', priceMinor: 2800, categorySlug: 'books', imageUrl: img('manager-path') },\n { slug: 'accelerate', title: 'Accelerate', description: 'The science of lean software and DevOps.', priceMinor: 2400, categorySlug: 'books', imageUrl: img('accelerate') },\n { slug: 'working-effectively-with-legacy-code', title: 'Working Effectively with Legacy Code', description: 'Michael Feathers on rescuing complex codebases.', priceMinor: 3400, categorySlug: 'books', imageUrl: img('legacy-code') },\n]\n\nconst escapeXml = (text: string): string =>\n text.replace(/[<>&'\"]/g, (c) => `&#${c.charCodeAt(0)};`)\n\n/** A 600×600 placeholder for a seed product, its colour derived from the slug, so no image host is needed. */\nexport function seedImage(product: SeedProduct): Uint8Array {\n let hash = 0\n for (const char of product.slug) hash = (hash * 31 + char.charCodeAt(0)) >>> 0\n const hue = hash % 360\n const svg = `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"600\" height=\"600\" viewBox=\"0 0 600 600\"><rect width=\"600\" height=\"600\" fill=\"hsl(${hue} 45% 82%)\"/><circle cx=\"300\" cy=\"260\" r=\"120\" fill=\"hsl(${hue} 40% 62%)\"/><text x=\"300\" y=\"480\" font-family=\"system-ui,sans-serif\" font-size=\"32\" text-anchor=\"middle\" fill=\"hsl(${hue} 40% 22%)\">${escapeXml(product.title)}</text></svg>`\n return new TextEncoder().encode(svg)\n}\n","import type { NymbalConfig } from '@nymbalhq/config'\nimport type { Logger } from '@nymbalhq/types'\nimport { createCommandStore, rawClients } from '../db/command-store.js'\nimport { slotBuilders, type InjectedAdapters } from '../adapters/registry.js'\nimport { buildDocumentStore } from '../platform.js'\nimport { buildRepositories } from '../repositories/index.js'\nimport { loadBootSettings } from '../settings/load.js'\nimport type { RebuildDeps } from './model.js'\n\nexport interface OpenReadModelsOptions {\n logger: Logger\n /** The project's own adapters, for a `custom` search slot. */\n adapters?: InjectedAdapters\n sqlitePath?: string\n postgresUrl?: string\n env?: NodeJS.ProcessEnv\n}\n\n/**\n * What a rebuild outside the server needs, built as `createApp` builds it: the command store (writable), the document\n * store and the search adapter. No bus, relay, sweeper or other slot. `close()` closes what it opened.\n */\nexport async function openReadModels(\n config: NymbalConfig,\n options: OpenReadModelsOptions,\n): Promise<{ deps: RebuildDeps; close(): Promise<void> }> {\n const { logger } = options\n const env = options.env ?? process.env\n const storage = {\n ...(options.sqlitePath !== undefined && { sqlitePath: options.sqlitePath }),\n ...(options.postgresUrl !== undefined && { postgresUrl: options.postgresUrl }),\n }\n const settings = await loadBootSettings(config, { storage, env, logger })\n const store = createCommandStore(config, storage)\n const closers: Array<() => Promise<void>> = [() => store.close()]\n const close = async () => {\n for (const c of closers.splice(0).reverse()) await c()\n }\n try {\n const documentStore = await buildDocumentStore(config, { ...storage, logger, env }, logger, env)\n closers.push(() => documentStore.close())\n if (config.infrastructure.documentStore === 'postgres-jsonb') await documentStore.initialize?.()\n const repos = buildRepositories(store, documentStore)\n const search = await slotBuilders({\n config,\n logger: logger.child({ layer: 'adapter' }),\n sql: rawClients(store),\n repos,\n settings: settings.values,\n ...(options.adapters !== undefined && { injected: options.adapters }),\n }).search()\n return { deps: { config, store, repos, documentStore, search, logger }, close }\n } catch (error) {\n await close()\n throw error\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,QAAAA,aAAY;AAErB;AAAA,EACE;AAAA,OAKK;;;ACRP,SAAS,cAAc,sBAAsB;AAmBtC,IAAM,wBAAN,MAA4D;AAAA,EACxD,QAAQ,oBAAI,IAAgC;AAAA,EAC5C;AAAA,EACA;AAAA,EAET,YAAY,UAAwC,CAAC,GAAG;AACtD,SAAK,OAAO,QAAQ,OAAO,KAAK;AAChC,UAAM,WAAW,QAAQ,mBAAmB;AAC5C,QAAI,WAAW,GAAG;AAChB,WAAK,cAAc,YAAY,MAAM,KAAK,OAAO,GAAG,QAAQ;AAC5D,WAAK,YAAY,QAAQ;AAAA,IAC3B,OAAO;AACL,WAAK,cAAc;AAAA,IACrB;AAAA,EACF;AAAA,EAEA,eAAkC;AAChC,WAAO,CAAC,OAAO,OAAO,UAAU,SAAS,SAAS,OAAO,iBAAiB;AAAA,EAC5E;AAAA;AAAA,EAGA,MAAM,cAAqC;AACzC,WAAO,EAAE,QAAQ,UAAU;AAAA,EAC7B;AAAA,EAEA,MAAM,IAAO,YAAoB,KAAgC;AAC/D,UAAM,QAAQ,KAAK,MAAM,IAAI,UAAU,GAAG,IAAI,GAAG;AACjD,QAAI,CAAC,MAAO,QAAO;AACnB,QAAI,KAAK,WAAW,KAAK,GAAG;AAC1B,WAAK,MAAM,IAAI,UAAU,GAAG,OAAO,GAAG;AACtC,aAAO;AAAA,IACT;AACA,WAAO,MAAM;AAAA,EACf;AAAA,EAEA,MAAM,IACJ,YACA,KACA,UACA,UAAsB,CAAC,GACR;AACf,UAAM,SAAS,K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B,eACpB,QACA,SACwD;AACxD,QAAM,EAAE,OAAO,IAAI;AACnB,QAAM,MAAM,QAAQ,OAAO,QAAQ;AACnC,QAAM,UAAU;AAAA,IACd,GAAI,QAAQ,eAAe,UAAa,EAAE,YAAY,QAAQ,WAAW;AAAA,IACzE,GAAI,QAAQ,gBAAgB,UAAa,EAAE,aAAa,QAAQ,YAAY;AAAA,EAC9E;AACA,QAAM,WAAW,MAAM,iBAAiB,QAAQ,EAAE,SAAS,KAAK,OAAO,CAAC;AACxE,QAAM,QAAQ,mBAAmB,QAAQ,OAAO;AAChD,QAAM,UAAsC,CAAC,MAAM,MAAM,MAAM,CAAC;AAChE,QAAM,QAAQ,YAAY;AACxB,eAAW,KAAK,QAAQ,OAAO,CAAC,EAAE,QAAQ,EAAG,OAAM,EAAE;AAAA,EACvD;AACA,MAAI;AACF,UAAM,gBAAgB,MAAM,mBAAmB,QAAQ,EAAE,GAAG,SAAS,QAAQ,IAAI,GAAG,QAAQ,GAAG;AAC/F,YAAQ,KAAK,MAAM,cAAc,MAAM,CAAC;AACxC,QAAI,OAAO,eAAe,kBAAkB,iBAAkB,OAAM,cAAc,aAAa;AAC/F,UAAM,QAAQ,kBAAkB,OAAO,aAAa;AACpD,UAAMC,UAAS,MAAM,aAAa;AAAA,MAChC;AAAA,MACA,QAAQ,OAAO,MAAM,EAAE,OAAO,UAAU,CAAC;AAAA,MACzC,KAAK,WAAW,KAAK;AAAA,MACrB;AAAA,MACA,UAAU,SAAS;AAAA,MACnB,GAAI,QAAQ,aAAa,UAAa,EAAE,UAAU,QAAQ,SAAS;AAAA,IACrE,CAAC,EAAE,OAAO;AACV,WAAO,EAAE,MAAM,EAAE,QAAQ,OAAO,OAAO,eAAe,QAAAA,SAAQ,OAAO,GAAG,MAAM;AAAA,EAChF,SAAS,OAAO;AACd,UAAM,MAAM;AACZ,UAAM;AAAA,EACR;AACF;","names":["join","entries","events","join","resolve","resolve","rows","products","row","rows","categories","eq","parseJson","parseJson","createProductRepository","col","row","eq","products","t","rows","base","filtered","asc","eq","parseJson","row","eq","variants","rows","asc","asc","eq","gt","createCategoryRepository","row","eq","categories","t","rows","gt","asc","and","eq","productCategories","and","eq","rows","asc","eq","gt","sql","parseJson","row","eq","customers","t","rows","gt","asc","sql","and","eq","refreshTokens","row","eq","db","and","result","and","asc","eq","gt","parseJson","row","eq","orders","o","and","rows","t","gt","asc","base","filtered","asc","eq","orderHistory","rows","eq","asc","and","asc","eq","r","rows","asc","orderRefunds","and","eq","row","eq","sql","client","row","eq","current","orderSequences","sql","and","eq","orderAccessKeys","t","and","eq","eq","lt","inventoryReservations","row","eq","rows","lt","desc","eq","stockAdjustments","rows","eq","desc","and","desc","eq","lt","row","eq","reviews","t","conds","lt","and","rows","desc","and","eq","lt","processedEvents","and","eq","result","lt","and","asc","eq","gt","gte","inArray","isNull","lt","or","sql","events","or","sql","gte","lt","and","asc","isNull","gt","inArray","eq","row","result","and","asc","eq","gt","isNull","lt","lte","sql","parseJson","sql","and","isNull","gt","lt","carts","row","eq","lte","t","rows","asc","and","eq","inArray","sql","alertSubscriptions","row","sql","eq","and","inArray","createProductRepository","createCategoryRepository","uuidv7","events","resolve","events","EVT_CATEGORY_CREATED","EVT_CATEGORY_DELETED","EVT_CATEGORY_UPDATED","variants","products","EVT_CATEGORY_CREATED","EVT_CATEGORY_UPDATED","EVT_CATEGORY_DELETED","EVT_ORDER_PAID","EVT_ORDER_PARTIALLY_REFUNDED","EVT_ORDER_REFUNDED","EVT_ORDER_PAID","EVT_ORDER_REFUNDED","EVT_ORDER_PARTIALLY_REFUNDED","products","uuidv7","EVT_CUSTOMER_CREATED","EVT_ORDER_PAID","EVT_ORDER_SHIPPED","uuidv7","EVT_ORDER_PAID","EVT_ORDER_SHIPPED","EVT_CUSTOMER_CREATED","EVT_PRODUCT_CREATED","EVT_PRODUCT_DELETED","EVT_PRODUCT_UPDATED","search","EVT_PRODUCT_CREATED","EVT_PRODUCT_UPDATED","EVT_PRODUCT_DELETED","EVT_ORDER_DELIVERED","reviews","EVT_ORDER_DELIVERED","row","product","ConfigError","categories","customers","orders","orders","customers","search","EVT_CART_ABANDONED","carts","EVT_CART_ABANDONED","ConfigError","options","registerAllRoutes","resolve","errorText","errorText","resolve","subject","text","inArray","uuidv7","EVT_CATEGORY_CREATED","EVT_PRODUCT_CREATED","EVT_CUSTOMER_CREATED","text","values","variants","productCategories","categories","products","customers","inArray","failedOf","uuidv7","events","EVT_CATEGORY_CREATED","EVT_PRODUCT_CREATED","EVT_CUSTOMER_CREATED","search","search"]}
|
|
1
|
+
{"version":3,"sources":["../src/platform.ts","../src/document-store/in-memory.ts","../src/event-bus/in-process.ts","../src/logger.ts","../src/media/local-fs-storage.ts","../src/db/migrate.ts","../src/db/repositories/products.ts","../src/db/repositories/categories.ts","../src/repositories/product.ts","../src/repositories/json.ts","../src/repositories/variant.ts","../src/repositories/category.ts","../src/repositories/product-category.ts","../src/repositories/customer.ts","../src/repositories/refresh-token.ts","../src/repositories/order.ts","../src/repositories/order-history.ts","../src/repositories/order-refund.ts","../src/repositories/order-sequence.ts","../src/repositories/order-access-key.ts","../src/repositories/inventory-reservation.ts","../src/repositories/stock-adjustment.ts","../src/repositories/review.ts","../src/repositories/processed-event.ts","../src/repositories/event-log.ts","../src/history/subject.ts","../src/repositories/cart.ts","../src/repositories/alert-subscription.ts","../src/repositories/email-suppression.ts","../src/repositories/order-shipment.ts","../src/repositories/index.ts","../src/events/builder.ts","../src/events/publisher.ts","../src/events/relay.ts","../src/handlers/idempotency.ts","../src/handlers/projections/category-projection.ts","../src/handlers/projections/product-projection.ts","../src/read-models/sources.ts","../src/handlers/projections/order-projection.ts","../src/handlers/projections/customer-projection.ts","../src/handlers/projections/inventory-projection.ts","../src/handlers/side-effects/email-handler.ts","../src/handlers/side-effects/search-handler.ts","../src/handlers/side-effects/reviews-handler.ts","../src/handlers/side-effects/alert-handler.ts","../src/handlers/side-effects/email-feedback-handler.ts","../src/handlers/side-effects/shipping-tracking-handler.ts","../src/handlers/register.ts","../src/app.ts","../src/auth-secret.ts","../src/events/outage.ts","../src/read-models/index.ts","../src/read-models/catalogue.ts","../src/read-models/customers.ts","../src/read-models/model.ts","../src/read-models/orders.ts","../src/read-models/search.ts","../src/sweepers/inventory-reservation-sweeper.ts","../src/sweepers/cart-abandonment-sweeper.ts","../src/sweepers/event-retention-sweeper.ts","../src/adapters/security/rate-limit.ts","../src/diagnose.ts","../src/seed/run.ts","../src/seed/data.ts","../src/read-models/open.ts"],"sourcesContent":["import { join } from 'node:path'\nimport type { NymbalConfig } from '@nymbalhq/config'\nimport {\n ConfigError,\n type DocumentStoreAdapter,\n type EventBusAdapter,\n type Logger,\n type MediaStorage,\n} from '@nymbalhq/types'\nimport { loadProviderAdapter, type Choice } from './adapters/resolve.js'\nimport { createCommandStore, type CommandStore } from './db/command-store.js'\nimport { InMemoryDocumentStore } from './document-store/in-memory.js'\nimport { InProcessEventBus } from './event-bus/in-process.js'\nimport { createLogger } from './logger.js'\nimport { createLocalFsMediaStorage } from './media/index.js'\n\nexport interface Platform {\n config: NymbalConfig\n commandStore: CommandStore\n documentStore: DocumentStoreAdapter\n eventBus: EventBusAdapter\n media: MediaStorage\n logger: Logger\n close(): Promise<void>\n}\n\n/** Where the command store is, and the logger; what `createApp` and `resolvePrimitives` take as well. */\nexport interface PlatformConnectionOptions {\n logger?: Logger\n sqlitePath?: string\n postgresUrl?: string\n}\n\n/** The infrastructure primitives, as instances: `resolvePrimitives` builds them from the config. */\nexport interface Primitives {\n documentStore: DocumentStoreAdapter\n eventBus: EventBusAdapter\n media: MediaStorage\n}\n\nexport interface CreatePlatformOptions extends PlatformConnectionOptions, Primitives {}\n\nexport interface ResolvePrimitivesOptions extends PlatformConnectionOptions {\n /** Where local-fs media is written; `public/imported-media` under the working directory by default. */\n mediaRoot?: string\n env?: NodeJS.ProcessEnv\n}\n\nexport const REDIS_DEFAULTS = {\n prefix: 'nymbal',\n ackTimeoutMs: 15_000,\n claimIdleMs: 5_000,\n streamMaxLen: 10_000,\n} as const\n\nconst S3_DEFAULT_REGION = 'us-east-1'\n\n/** The Postgres JSONB store's namespace inside the command store's database. */\nconst JSONB_PREFIX = 'nymbal'\n\nfunction nonEmpty(value: string | undefined): string | undefined {\n return value === undefined || value === '' ? undefined : value\n}\n\n/** The Redis server the primitives use: `infrastructure.redis.url`, else `REDIS_URL`. */\nexport function redisUrlOf(config: NymbalConfig, env: NodeJS.ProcessEnv): string | undefined {\n return config.infrastructure.redis?.url ?? nonEmpty(env['REDIS_URL'])\n}\n\n/** The `redis` block with its defaults: the URL from `REDIS_URL`, the prefix from `NYMBAL_REDIS_PREFIX`. */\nfunction redisConnection(config: NymbalConfig, env: NodeJS.ProcessEnv, slot: string) {\n const block = config.infrastructure.redis ?? {}\n const url = redisUrlOf(config, env)\n if (url === undefined) {\n throw new ConfigError(\n `infrastructure.${slot} needs a Redis server: set infrastructure.redis.url or REDIS_URL`,\n { code: 'config.redis_url_missing', context: { slot } },\n )\n }\n return {\n url,\n prefix: block.prefix ?? nonEmpty(env['NYMBAL_REDIS_PREFIX']) ?? REDIS_DEFAULTS.prefix,\n ackTimeoutMs: block.ackTimeoutMs ?? REDIS_DEFAULTS.ackTimeoutMs,\n claimIdleMs: block.claimIdleMs ?? REDIS_DEFAULTS.claimIdleMs,\n streamMaxLen: block.streamMaxLen ?? REDIS_DEFAULTS.streamMaxLen,\n }\n}\n\n/**\n * The `s3` block with its defaults: each field from the environment when the block leaves it out (`S3_BUCKET`,\n * `AWS_REGION`, `S3_ENDPOINT`, `NYMBAL_S3_PREFIX`, `S3_PUBLIC_URL`), the region `us-east-1`, no prefix, and path-style\n * requests when an endpoint is set. Credentials are not here: the AWS SDK's default chain provides them.\n */\nfunction s3Connection(config: NymbalConfig, env: NodeJS.ProcessEnv) {\n const block = config.infrastructure.s3 ?? {}\n const bucket = nonEmpty(block.bucket) ?? nonEmpty(env['S3_BUCKET'])\n if (bucket === undefined) {\n throw new ConfigError(\n \"infrastructure.media 's3' needs a bucket: set infrastructure.s3.bucket or S3_BUCKET\",\n { code: 'config.s3_bucket_missing', context: { slot: 'media' } },\n )\n }\n const endpoint = nonEmpty(block.endpoint) ?? nonEmpty(env['S3_ENDPOINT'])\n const publicUrl = nonEmpty(block.publicUrl) ?? nonEmpty(env['S3_PUBLIC_URL'])\n return {\n bucket,\n region: nonEmpty(block.region) ?? nonEmpty(env['AWS_REGION']) ?? S3_DEFAULT_REGION,\n prefix: block.prefix ?? nonEmpty(env['NYMBAL_S3_PREFIX']) ?? '',\n forcePathStyle: block.forcePathStyle ?? endpoint !== undefined,\n ...(endpoint !== undefined && { endpoint }),\n ...(publicUrl !== undefined && { publicUrl }),\n }\n}\n\nasync function loadPrimitive<T>(\n slot: 'documentStore' | 'eventBus' | 'media',\n choice: Choice,\n config: Record<string, unknown>,\n logger: Logger,\n env: NodeJS.ProcessEnv,\n): Promise<T> {\n const instance = await loadProviderAdapter(slot, choice, {\n config,\n logger: logger.child({ primitive: slot }),\n env,\n })\n if (instance === undefined) {\n throw new ConfigError(`infrastructure.${slot} '${choice.provider}' has no implementation`, {\n context: { slot, provider: choice.provider },\n })\n }\n return instance as T\n}\n\n/** A document store that must be initialized before use (postgres-jsonb creates its table). */\ntype InitializableDocumentStore = DocumentStoreAdapter & { initialize?(): Promise<void> }\n\n/**\n * The document store the config names, constructed and not initialized: `resolvePrimitives` initializes it, and\n * `diagnose` must not (initializing postgres-jsonb creates its table).\n */\nexport async function buildDocumentStore(\n config: NymbalConfig,\n options: ResolvePrimitivesOptions,\n logger: Logger,\n env: NodeJS.ProcessEnv,\n): Promise<InitializableDocumentStore> {\n const choice = config.infrastructure.documentStore\n switch (choice.provider) {\n case 'in-memory':\n return new InMemoryDocumentStore()\n case 'redis': {\n const { url, prefix } = redisConnection(config, env, 'documentStore')\n return loadPrimitive('documentStore', choice, { url, prefix }, logger, env)\n }\n case 'postgres-jsonb': {\n const postgresUrl = options.postgresUrl ?? nonEmpty(env['DATABASE_URL'])\n if (postgresUrl === undefined) {\n throw new ConfigError(\n \"documentStore 'postgres-jsonb' uses the command store's Postgres: set DATABASE_URL (or pass postgresUrl)\",\n { code: 'config.postgres_url_missing', context: { slot: 'documentStore' } },\n )\n }\n return loadPrimitive<InitializableDocumentStore>(\n 'documentStore',\n choice,\n { postgresUrl, prefix: JSONB_PREFIX },\n logger,\n env,\n )\n }\n default:\n return loadPrimitive('documentStore', choice, choice.config ?? {}, logger, env)\n }\n}\n\nexport async function buildEventBus(\n config: NymbalConfig,\n logger: Logger,\n env: NodeJS.ProcessEnv,\n): Promise<EventBusAdapter> {\n const choice = config.infrastructure.eventBus\n switch (choice.provider) {\n case 'in-process':\n return new InProcessEventBus({ logger })\n case 'redis-streams':\n return loadPrimitive(\n 'eventBus',\n choice,\n redisConnection(config, env, 'eventBus'),\n logger,\n env,\n )\n default:\n return loadPrimitive('eventBus', choice, choice.config ?? {}, logger, env)\n }\n}\n\nexport async function buildMedia(\n config: NymbalConfig,\n options: ResolvePrimitivesOptions,\n logger: Logger,\n env: NodeJS.ProcessEnv,\n): Promise<MediaStorage> {\n const choice = config.infrastructure.media\n switch (choice.provider) {\n case 'local-fs':\n return createLocalFsMediaStorage({\n root: options.mediaRoot ?? join(process.cwd(), 'public', 'imported-media'),\n urlPrefix: '/imported-media',\n })\n case 's3':\n return loadPrimitive('media', choice, s3Connection(config, env), logger, env)\n default:\n return loadPrimitive('media', choice, choice.config ?? {}, logger, env)\n }\n}\n\n/**\n * The document store, event bus and media storage the config names. A primitive that lives in its own package is\n * imported only when named, from its block's `package` or `@nymbalhq/<slot>-<provider>`; a missing package fails\n * `adapter.package_missing` with the install line. A provider whose connection the kernel does not build gets its\n * block's `config`.\n */\nexport async function resolvePrimitives(\n config: NymbalConfig,\n options: ResolvePrimitivesOptions = {},\n): Promise<Primitives> {\n const env = options.env ?? process.env\n const logger = options.logger ?? createLogger({ base: { store: config.store.name } })\n // Checked before anything is loaded or connects, so a missing URL or bucket never leaves a half-built set behind.\n const { documentStore: store, eventBus: bus, media: storage } = config.infrastructure\n if (storage.provider === 's3') s3Connection(config, env)\n if (store.provider === 'redis') redisConnection(config, env, 'documentStore')\n if (bus.provider === 'redis-streams') redisConnection(config, env, 'eventBus')\n const media = await buildMedia(config, options, logger, env)\n const documentStore = await buildDocumentStore(config, options, logger, env)\n try {\n if (store.provider === 'postgres-jsonb') await documentStore.initialize?.()\n const eventBus = await buildEventBus(config, logger, env)\n return { documentStore, eventBus, media }\n } catch (error) {\n await documentStore.close()\n throw error\n }\n}\n\nexport function createPlatform(config: NymbalConfig, options: CreatePlatformOptions): Platform {\n const logger =\n options.logger ??\n createLogger({\n base: { store: config.store.name },\n })\n const commandStore = createCommandStore(config, {\n ...(options.sqlitePath !== undefined && { sqlitePath: options.sqlitePath }),\n ...(options.postgresUrl !== undefined && { postgresUrl: options.postgresUrl }),\n })\n const { documentStore, eventBus, media } = options\n return {\n config,\n commandStore,\n documentStore,\n eventBus,\n media,\n logger,\n async close() {\n // The bus first: a handler still running may write to either store.\n await eventBus.close()\n await documentStore.close()\n await commandStore.close()\n },\n }\n}\n","import { AdapterError, queryDocuments } from '@nymbalhq/types'\nimport type {\n DocumentStoreAdapter,\n HealthReport,\n PutOptions,\n QueryParams,\n QueryResult,\n} from '@nymbalhq/types'\n\ninterface Entry {\n doc: unknown\n expiresAt: number | null\n}\n\nexport interface InMemoryDocumentStoreOptions {\n sweepIntervalMs?: number\n now?: () => number\n}\n\nexport class InMemoryDocumentStore implements DocumentStoreAdapter {\n readonly #data = new Map<string, Map<string, Entry>>()\n readonly #now: () => number\n readonly #sweepTimer: NodeJS.Timeout | null\n\n constructor(options: InMemoryDocumentStoreOptions = {}) {\n this.#now = options.now ?? Date.now\n const interval = options.sweepIntervalMs ?? 60_000\n if (interval > 0) {\n this.#sweepTimer = setInterval(() => this.#sweep(), interval)\n this.#sweepTimer.unref?.()\n } else {\n this.#sweepTimer = null\n }\n }\n\n capabilities(): readonly string[] {\n return ['get', 'put', 'delete', 'query', 'batch', 'ttl', 'conditional-put']\n }\n\n /** The process's own memory: healthy whenever it can answer. */\n async healthCheck(): Promise<HealthReport> {\n return { status: 'healthy' }\n }\n\n async get<T>(collection: string, key: string): Promise<T | null> {\n const entry = this.#data.get(collection)?.get(key)\n if (!entry) return null\n if (this.#isExpired(entry)) {\n this.#data.get(collection)?.delete(key)\n return null\n }\n return entry.doc as T\n }\n\n async put<T>(\n collection: string,\n key: string,\n document: T,\n options: PutOptions = {},\n ): Promise<void> {\n const bucket = this.#getOrCreate(collection)\n if (options.conditionKey !== undefined) {\n const existing = bucket.get(key)\n if (!existing || this.#isExpired(existing)) {\n throw new AdapterError(\n 'condition-failed',\n `Condition failed on ${collection}/${key}: document does not exist`,\n { context: { collection, key, conditionKey: options.conditionKey } },\n )\n }\n const actual = (existing.doc as Record<string, unknown>)[options.conditionKey]\n if (actual !== options.conditionValue) {\n throw new AdapterError(\n 'condition-failed',\n `Condition failed on ${collection}/${key}: ${options.conditionKey} mismatch`,\n {\n context: {\n collection,\n key,\n conditionKey: options.conditionKey,\n expected: options.conditionValue,\n actual,\n },\n },\n )\n }\n }\n const expiresAt = options.ttl !== undefined ? this.#now() + options.ttl * 1000 : null\n bucket.set(key, { doc: document, expiresAt })\n }\n\n async delete(collection: string, key: string): Promise<void> {\n this.#data.get(collection)?.delete(key)\n }\n\n async query<T>(collection: string, params: QueryParams): Promise<QueryResult<T>> {\n const bucket = this.#data.get(collection)\n if (!bucket) return { items: [], nextCursor: null }\n const live: Array<[string, unknown]> = []\n for (const [key, entry] of bucket) {\n if (!this.#isExpired(entry)) live.push([key, entry.doc])\n }\n return queryDocuments<T>(live, params)\n }\n\n async batchGet<T>(collection: string, keys: string[]): Promise<Map<string, T>> {\n const result = new Map<string, T>()\n for (const key of keys) {\n const value = await this.get<T>(collection, key)\n if (value !== null) result.set(key, value)\n }\n return result\n }\n\n async batchPut<T>(collection: string, items: Map<string, T>): Promise<void> {\n for (const [key, doc] of items) {\n await this.put(collection, key, doc)\n }\n }\n\n /** Builds the new contents in a map of their own and swaps it in, so a reader sees one set or the other. */\n async replaceCollection<T>(\n collection: string,\n entries: AsyncIterable<[string, T]>,\n ): Promise<void> {\n const next = new Map<string, Entry>()\n for await (const [key, doc] of entries) next.set(key, { doc, expiresAt: null })\n this.#data.set(collection, next)\n }\n\n async close(): Promise<void> {\n if (this.#sweepTimer) clearInterval(this.#sweepTimer)\n this.#data.clear()\n }\n\n #getOrCreate(collection: string): Map<string, Entry> {\n let bucket = this.#data.get(collection)\n if (!bucket) {\n bucket = new Map()\n this.#data.set(collection, bucket)\n }\n return bucket\n }\n\n #isExpired(entry: Entry): boolean {\n return entry.expiresAt !== null && entry.expiresAt <= this.#now()\n }\n\n #sweep(): void {\n const now = this.#now()\n for (const bucket of this.#data.values()) {\n for (const [key, entry] of bucket) {\n if (entry.expiresAt !== null && entry.expiresAt <= now) {\n bucket.delete(key)\n }\n }\n }\n }\n}\n","import { v7 as uuidv7 } from 'uuid'\nimport type {\n EventBusAdapter,\n EventHandler,\n HandlerFailure,\n HealthReport,\n NymbalEvent,\n Subscription,\n SubscriptionConfig,\n Logger,\n} from '@nymbalhq/types'\nimport { handlerFailedError, ValidationError } from '@nymbalhq/types'\n\ninterface Registration {\n id: string\n patterns: string[]\n regexes: RegExp[]\n handler: EventHandler\n config: SubscriptionConfig | undefined\n}\n\nexport interface InProcessEventBusOptions {\n logger?: Logger\n}\n\nexport class InProcessEventBus implements EventBusAdapter {\n readonly #registrations = new Map<string, Registration>()\n readonly #logger: Logger | undefined\n\n constructor(options: InProcessEventBusOptions = {}) {\n this.#logger = options.logger\n }\n\n capabilities(): readonly string[] {\n return ['publish', 'subscribe', 'wildcard', 'replay']\n }\n\n /** Delivery within the process: healthy whenever it can answer. */\n async healthCheck(): Promise<HealthReport> {\n return { status: 'healthy' }\n }\n\n async publish<T>(event: NymbalEvent<T>): Promise<void> {\n const failed = await this.#deliver(event, () => true)\n if (failed.length > 0) throw handlerFailedError(event, failed)\n }\n\n async publishBatch(events: NymbalEvent<unknown>[]): Promise<void> {\n let first: Error | undefined\n for (const event of events) {\n const failed = await this.#deliver(event, () => true)\n if (failed.length > 0) first ??= handlerFailedError(event, failed)\n }\n if (first !== undefined) throw first\n }\n\n async replay(events: NymbalEvent<unknown>[]): Promise<void> {\n for (const event of events) {\n await this.#deliver(event, (r) => r.config?.derived === true)\n }\n }\n\n /** Runs every matching handler to the end, each error logged; returns the named subscriptions that threw. */\n async #deliver<T>(\n event: NymbalEvent<T>,\n eligible: (r: Registration) => boolean,\n ): Promise<HandlerFailure[]> {\n this.#validate(event)\n const matches = Array.from(this.#registrations.values()).filter(\n (r) => eligible(r) && r.regexes.some((re) => re.test(event.type)),\n )\n const outcomes = await Promise.all(\n matches.map(async (r): Promise<HandlerFailure | null> => {\n try {\n await r.handler(event)\n return null\n } catch (err) {\n const subscription = r.config?.name\n this.#logger?.error(\n { err, subscriptionId: r.id, subscription, eventType: event.type, eventId: event.id },\n 'Event handler failed',\n )\n return subscription === undefined ? null : { subscription, message: messageOf(err) }\n }\n }),\n )\n return outcomes.filter((o) => o !== null)\n }\n\n async subscribe(\n eventPattern: string | string[],\n handler: EventHandler,\n config?: SubscriptionConfig,\n ): Promise<Subscription> {\n const patterns = Array.isArray(eventPattern) ? eventPattern : [eventPattern]\n const regexes = patterns.map(compilePattern)\n const id = uuidv7()\n const registration: Registration = { id, patterns, regexes, handler, config }\n this.#registrations.set(id, registration)\n const self = this\n return {\n id,\n patterns,\n async unsubscribe() {\n self.#registrations.delete(id)\n },\n }\n }\n\n async unsubscribe(subscription: Subscription): Promise<void> {\n this.#registrations.delete(subscription.id)\n }\n\n async close(): Promise<void> {\n this.#registrations.clear()\n }\n\n #validate(event: NymbalEvent<unknown>): void {\n if (!event.id || !event.type || !event.timestamp || !event.source) {\n throw new ValidationError('Event is missing required envelope fields', {\n context: { event },\n })\n }\n if (!event.metadata || !event.metadata.storeId || !event.metadata.environment) {\n throw new ValidationError('Event metadata is missing required fields', {\n context: { event },\n })\n }\n }\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\nfunction compilePattern(pattern: string): RegExp {\n const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\*]/g, '\\\\$&').replace(/\\\\\\*/g, '.*')\n return new RegExp(`^${escaped}$`)\n}\n","import { pino, type DestinationStream, type Logger as PinoLogger } from 'pino'\nimport type { Logger } from '@nymbalhq/types'\n\nexport interface CreateLoggerOptions {\n level?: string\n pretty?: boolean\n base?: Record<string, unknown>\n /** Where the JSON lines go instead of stdout; a destination is never pretty-printed. */\n destination?: DestinationStream\n}\n\nexport function createLogger(options: CreateLoggerOptions = {}): Logger {\n const isProduction = process.env.NODE_ENV === 'production'\n const pretty = options.destination === undefined && (options.pretty ?? !isProduction)\n const settings = {\n level: options.level ?? process.env.LOG_LEVEL ?? (isProduction ? 'info' : 'debug'),\n base: options.base ?? {},\n ...(pretty && {\n transport: {\n target: 'pino-pretty',\n options: { colorize: true, translateTime: 'HH:MM:ss.l', ignore: 'pid,hostname' },\n },\n }),\n }\n const logger =\n options.destination === undefined ? pino(settings) : pino(settings, options.destination)\n return wrap(logger)\n}\n\nfunction wrap(p: PinoLogger): Logger {\n return {\n trace: (obj, msg) => p.trace(obj as object, msg),\n debug: (obj, msg) => p.debug(obj as object, msg),\n info: (obj, msg) => p.info(obj as object, msg),\n warn: (obj, msg) => p.warn(obj as object, msg),\n error: (obj, msg) => p.error(obj as object, msg),\n child: (bindings) => wrap(p.child(bindings)),\n }\n}\n","import { constants } from 'node:fs'\nimport { access, mkdir, writeFile } from 'node:fs/promises'\nimport { dirname, join, resolve } from 'node:path'\nimport type { HealthReport, MediaStorage } from '@nymbalhq/types'\n\nexport interface LocalFsMediaStorageOptions {\n root: string\n urlPrefix?: string\n}\n\n/** What the local filesystem storage offers, whatever its root: the app reports it for the media slot. */\nexport const LOCAL_FS_MEDIA_CAPABILITIES: readonly string[] = ['put']\n\n/**\n * The directory whose write permission decides whether `put` can store under `root`: the root itself, or, when it\n * does not exist yet, its nearest existing ancestor, since `put` creates the missing directories.\n */\nasync function nearestExisting(root: string): Promise<string> {\n let dir = resolve(root)\n for (;;) {\n try {\n await access(dir, constants.F_OK)\n return dir\n } catch {\n const parent = dirname(dir)\n if (parent === dir) return dir\n dir = parent\n }\n }\n}\n\nexport function createLocalFsMediaStorage(options: LocalFsMediaStorageOptions): MediaStorage {\n const { root } = options\n const urlPrefix = options.urlPrefix ?? '/imported-media'\n\n return {\n capabilities: () => LOCAL_FS_MEDIA_CAPABILITIES,\n async put(key, body, _contentType) {\n const dest = join(root, key)\n const dir = dest.substring(0, dest.lastIndexOf('/'))\n await mkdir(dir, { recursive: true })\n await writeFile(dest, body)\n return { url: `${urlPrefix}/${key}` }\n },\n // Permission is read with access(2), never probed by writing a file.\n async healthCheck(): Promise<HealthReport> {\n const dir = await nearestExisting(root)\n try {\n await access(dir, constants.W_OK)\n return { status: 'healthy', detail: root }\n } catch {\n return { status: 'down', detail: `${dir} is not writable` }\n }\n },\n }\n}\n","import { readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { migrate as migrateSqlite } from 'drizzle-orm/better-sqlite3/migrator'\nimport { migrate as migratePostgres } from 'drizzle-orm/node-postgres/migrator'\nimport { rawClients, type CommandStore } from './command-store.js'\n\nexport interface MigrateOptions {\n migrationsRoot?: string\n}\n\nfunction rootOf(options: MigrateOptions): string {\n return options.migrationsRoot ?? resolve(process.cwd(), 'migrations')\n}\n\nexport async function runMigrations(\n store: CommandStore,\n options: MigrateOptions = {},\n): Promise<void> {\n const root = rootOf(options)\n const clients = rawClients(store)\n if (clients.kind === 'sqlite') {\n migrateSqlite(clients.db, { migrationsFolder: resolve(root, 'sqlite') })\n } else {\n await migratePostgres(clients.db, { migrationsFolder: resolve(root, 'postgres') })\n }\n}\n\nexport interface MigrationState {\n /** Rows in the store's migrations table. */\n applied: number\n /** Journal entries `runMigrations` would apply. */\n pending: number\n}\n\n/**\n * What `runMigrations` would do to `store`, read without writing. Drizzle applies every journal entry created after the\n * newest one its table records, so that is what counts as pending; a store with no table has every entry pending.\n */\nexport async function migrationState(\n store: CommandStore,\n options: MigrateOptions = {},\n): Promise<MigrationState> {\n const clients = rawClients(store)\n const journal = JSON.parse(\n readFileSync(resolve(rootOf(options), clients.kind, 'meta', '_journal.json'), 'utf8'),\n ) as { entries: Array<{ when: number }> }\n let applied = 0\n let newest = Number.NEGATIVE_INFINITY\n if (clients.kind === 'sqlite') {\n const table = clients.raw\n .prepare(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = '__drizzle_migrations'\")\n .get()\n if (table !== undefined) {\n const row = clients.raw\n .prepare('SELECT count(*) AS n, max(created_at) AS last FROM __drizzle_migrations')\n .get() as { n: number; last: number | null }\n applied = row.n\n if (row.last !== null) newest = Number(row.last)\n }\n } else {\n const { rows } = await clients.pool.query<{ table: string | null }>(\n \"SELECT to_regclass('drizzle.__drizzle_migrations')::text AS table\",\n )\n if (rows[0]?.table != null) {\n const counted = await clients.pool.query<{ n: number; last: string | null }>(\n 'SELECT count(*)::int AS n, max(created_at)::text AS last FROM drizzle.__drizzle_migrations',\n )\n applied = counted.rows[0]?.n ?? 0\n const last = counted.rows[0]?.last ?? null\n if (last !== null) newest = Number(last)\n }\n }\n const pending = journal.entries.filter((entry) => entry.when > newest).length\n return { applied, pending }\n}\n","import { eq } from 'drizzle-orm'\nimport { rawClients, type CommandStore } from '../command-store.js'\nimport * as sqliteSchema from '../schema/sqlite.js'\nimport * as postgresSchema from '../schema/postgres.js'\n\nexport interface ProductInsert {\n id: string\n slug: string\n name: string\n description: string\n shortDescription?: string\n status?: 'draft' | 'active' | 'archived'\n type?: 'simple' | 'variable'\n seoTitle?: string\n seoDescription?: string\n media?: unknown[]\n metadata?: Record<string, unknown>\n createdAt: Date\n updatedAt: Date\n}\n\nexport interface ProductRow {\n id: string\n slug: string\n name: string\n description: string\n shortDescription: string\n status: 'draft' | 'active' | 'archived'\n type: 'simple' | 'variable'\n seoTitle: string\n seoDescription: string\n media: unknown[]\n metadata: Record<string, unknown>\n createdAt: Date | string\n updatedAt: Date | string\n}\n\nfunction parseJson<T>(value: unknown, fallback: T): T {\n if (typeof value === 'string') {\n try {\n return JSON.parse(value) as T\n } catch {\n return fallback\n }\n }\n return (value ?? fallback) as T\n}\n\nfunction rowToDomain(row: Record<string, unknown>): ProductRow {\n return {\n id: String(row.id),\n slug: String(row.slug),\n name: String(row.name),\n description: String(row.description ?? ''),\n shortDescription: String(row.shortDescription ?? ''),\n status: row.status as 'draft' | 'active' | 'archived',\n type: row.type as 'simple' | 'variable',\n seoTitle: String(row.seoTitle ?? ''),\n seoDescription: String(row.seoDescription ?? ''),\n media: parseJson(row.media, [] as unknown[]),\n metadata: parseJson(row.metadata, {} as Record<string, unknown>),\n createdAt: row.createdAt as Date | string,\n updatedAt: row.updatedAt as Date | string,\n }\n}\n\nexport function createProductRepository(store: CommandStore) {\n const clients = rawClients(store)\n return {\n async findAll(): Promise<ProductRow[]> {\n if (clients.kind === 'sqlite') {\n const rows = clients.db.select().from(sqliteSchema.products).all()\n return rows.map((r) => rowToDomain(r as Record<string, unknown>))\n }\n const rows = await clients.db.select().from(postgresSchema.products)\n return rows.map((r) => rowToDomain(r as Record<string, unknown>))\n },\n\n async findBySlug(slug: string): Promise<ProductRow | null> {\n if (clients.kind === 'sqlite') {\n const row = clients.db\n .select()\n .from(sqliteSchema.products)\n .where(eq(sqliteSchema.products.slug, slug))\n .get()\n return row ? rowToDomain(row as Record<string, unknown>) : null\n }\n const [row] = await clients.db\n .select()\n .from(postgresSchema.products)\n .where(eq(postgresSchema.products.slug, slug))\n return row ? rowToDomain(row as Record<string, unknown>) : null\n },\n\n async insertMany(items: ProductInsert[]): Promise<void> {\n if (items.length === 0) return\n if (clients.kind === 'sqlite') {\n const rows = items.map((item) => ({\n id: item.id,\n slug: item.slug,\n name: item.name,\n description: item.description,\n shortDescription: item.shortDescription ?? '',\n status: item.status ?? 'active',\n type: item.type ?? 'simple',\n seoTitle: item.seoTitle ?? '',\n seoDescription: item.seoDescription ?? '',\n media: JSON.stringify(item.media ?? []),\n metadata: JSON.stringify(item.metadata ?? {}),\n createdAt: item.createdAt.toISOString(),\n updatedAt: item.updatedAt.toISOString(),\n }))\n clients.db.insert(sqliteSchema.products).values(rows).run()\n return\n }\n const rows = items.map((item) => ({\n id: item.id,\n slug: item.slug,\n name: item.name,\n description: item.description,\n shortDescription: item.shortDescription ?? '',\n status: item.status ?? 'active',\n type: item.type ?? 'simple',\n seoTitle: item.seoTitle ?? '',\n seoDescription: item.seoDescription ?? '',\n media: item.media ?? [],\n metadata: item.metadata ?? {},\n createdAt: item.createdAt,\n updatedAt: item.updatedAt,\n }))\n await clients.db.insert(postgresSchema.products).values(rows)\n },\n }\n}\n","import { rawClients, type CommandStore } from '../command-store.js'\nimport * as sqliteSchema from '../schema/sqlite.js'\nimport * as postgresSchema from '../schema/postgres.js'\n\nexport interface CategoryInsert {\n id: string\n parentId?: string | null\n slug: string\n name: string\n description: string\n position?: number\n createdAt: Date\n}\n\nexport interface CategoryRow {\n id: string\n parentId: string | null\n slug: string\n name: string\n description: string\n position: number\n createdAt: Date | string\n}\n\nexport function createCategoryRepository(store: CommandStore) {\n const clients = rawClients(store)\n return {\n async findAll(): Promise<CategoryRow[]> {\n if (clients.kind === 'sqlite') {\n const rows = clients.db.select().from(sqliteSchema.categories).all()\n return rows as CategoryRow[]\n }\n const rows = await clients.db.select().from(postgresSchema.categories)\n return rows as CategoryRow[]\n },\n\n async insertMany(items: CategoryInsert[]): Promise<void> {\n if (items.length === 0) return\n if (clients.kind === 'sqlite') {\n const rows = items.map((item) => ({\n id: item.id,\n parentId: item.parentId ?? null,\n slug: item.slug,\n name: item.name,\n description: item.description,\n position: item.position ?? 0,\n createdAt: item.createdAt.toISOString(),\n }))\n clients.db.insert(sqliteSchema.categories).values(rows).run()\n return\n }\n const rows = items.map((item) => ({\n id: item.id,\n parentId: item.parentId ?? null,\n slug: item.slug,\n name: item.name,\n description: item.description,\n position: item.position ?? 0,\n createdAt: item.createdAt,\n }))\n await clients.db.insert(postgresSchema.categories).values(rows)\n },\n }\n}\n","import { asc, eq, gt } from 'drizzle-orm'\nimport type { Product, ProductStatus, ProductType, ProductMedia } from '@nymbalhq/types'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport type { KeysetPage } from './page.js'\nimport { parseJson, serialiseJson, fromTimestamp } from './json.js'\n\nexport interface ProductInsert {\n id: string\n slug: string\n name: string\n description?: string\n shortDescription?: string\n status?: ProductStatus\n type?: ProductType\n seoTitle?: string\n seoDescription?: string\n media?: ProductMedia[]\n metadata?: Record<string, unknown>\n createdAt: Date\n updatedAt: Date\n}\n\nexport interface ProductUpdate {\n name?: string\n description?: string\n shortDescription?: string\n status?: ProductStatus\n type?: ProductType\n seoTitle?: string\n seoDescription?: string\n media?: ProductMedia[]\n metadata?: Record<string, unknown>\n updatedAt: Date\n}\n\nfunction rowToProduct(store: CommandStore['kind'], row: Record<string, unknown>): Product {\n return {\n id: String(row.id),\n slug: String(row.slug),\n name: String(row.name),\n description: String(row.description ?? ''),\n shortDescription: String(row.shortDescription ?? ''),\n status: row.status as ProductStatus,\n type: row.type as ProductType,\n seoTitle: String(row.seoTitle ?? ''),\n seoDescription: String(row.seoDescription ?? ''),\n media: parseJson<ProductMedia[]>(store, row.media, []),\n metadata: parseJson<Record<string, unknown>>(store, row.metadata, {}),\n createdAt: fromTimestamp(row.createdAt),\n updatedAt: fromTimestamp(row.updatedAt),\n }\n}\n\nexport interface ProductRepository extends StoreRepository {\n findById(tx: ReadTx, id: string): Promise<Product | null>\n findBySlug(tx: ReadTx, slug: string): Promise<Product | null>\n list(\n tx: ReadTx,\n opts?: { status?: ProductStatus; limit?: number; offset?: number },\n ): Promise<Product[]>\n /** Rows by id after `page.after`: a walk over the table that a concurrent write cannot make skip a row. */\n listPage(tx: ReadTx, page: KeysetPage): Promise<Product[]>\n insert(tx: Tx, p: ProductInsert): Promise<void>\n update(tx: Tx, id: string, patch: ProductUpdate): Promise<void>\n delete(tx: Tx, id: string): Promise<void>\n setStatus(tx: Tx, id: string, status: ProductStatus, updatedAt: Date): Promise<void>\n}\n\nexport function createProductRepository(store: CommandStore): ProductRepository {\n async function _find(tx: ReadTx, column: 'id' | 'slug', value: string): Promise<Product | null> {\n if (tx.kind === 'sqlite') {\n const col = column === 'id' ? sqliteSchema.products.id : sqliteSchema.products.slug\n const row = sqliteDb(tx).select().from(sqliteSchema.products).where(eq(col, value)).get()\n return row ? rowToProduct(tx.kind, row as Record<string, unknown>) : null\n }\n const col = column === 'id' ? postgresSchema.products.id : postgresSchema.products.slug\n const [row] = await postgresDb(tx).select().from(postgresSchema.products).where(eq(col, value))\n return row ? rowToProduct(tx.kind, row as Record<string, unknown>) : null\n }\n\n return {\n store,\n async findById(tx, id) {\n return _find(tx, 'id', id)\n },\n async findBySlug(tx, slug) {\n return _find(tx, 'slug', slug)\n },\n async listPage(tx, page) {\n if (tx.kind === 'sqlite') {\n const t = sqliteSchema.products\n const rows = sqliteDb(tx)\n .select()\n .from(t)\n .where(page.after === undefined ? undefined : gt(t.id, page.after))\n .orderBy(asc(t.id))\n .limit(page.limit)\n .all()\n return rows.map((r) => rowToProduct('sqlite', r as Record<string, unknown>))\n }\n const t = postgresSchema.products\n const rows = await postgresDb(tx)\n .select()\n .from(t)\n .where(page.after === undefined ? undefined : gt(t.id, page.after))\n .orderBy(asc(t.id))\n .limit(page.limit)\n return rows.map((r) => rowToProduct('postgres', r as Record<string, unknown>))\n },\n async list(tx, opts = {}) {\n const limit = opts.limit ?? 100\n const offset = opts.offset ?? 0\n if (tx.kind === 'sqlite') {\n const base = sqliteDb(tx).select().from(sqliteSchema.products)\n const filtered = opts.status\n ? base.where(eq(sqliteSchema.products.status, opts.status))\n : base\n const rows = filtered.limit(limit).offset(offset).all()\n return rows.map((r) => rowToProduct('sqlite', r as Record<string, unknown>))\n }\n const base = postgresDb(tx).select().from(postgresSchema.products)\n const filtered = opts.status\n ? base.where(eq(postgresSchema.products.status, opts.status))\n : base\n const rows = await filtered.limit(limit).offset(offset)\n return rows.map((r) => rowToProduct('postgres', r as Record<string, unknown>))\n },\n async insert(tx, p) {\n const common = {\n id: p.id,\n slug: p.slug,\n name: p.name,\n description: p.description ?? '',\n shortDescription: p.shortDescription ?? '',\n status: p.status ?? 'draft',\n type: p.type ?? 'simple',\n seoTitle: p.seoTitle ?? '',\n seoDescription: p.seoDescription ?? '',\n }\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.products)\n .values({\n ...common,\n media: serialiseJson('sqlite', p.media ?? []) as string,\n metadata: serialiseJson('sqlite', p.metadata ?? {}) as string,\n createdAt: p.createdAt.toISOString(),\n updatedAt: p.updatedAt.toISOString(),\n })\n .run()\n return\n }\n await postgresDb(tx)\n .insert(postgresSchema.products)\n .values({\n ...common,\n media: p.media ?? [],\n metadata: p.metadata ?? {},\n createdAt: p.createdAt,\n updatedAt: p.updatedAt,\n })\n },\n async update(tx, id, patch) {\n const pg: Record<string, unknown> = { updatedAt: patch.updatedAt }\n const sq: Record<string, unknown> = { updatedAt: patch.updatedAt.toISOString() }\n if (patch.name !== undefined) {\n pg.name = patch.name\n sq.name = patch.name\n }\n if (patch.description !== undefined) {\n pg.description = patch.description\n sq.description = patch.description\n }\n if (patch.shortDescription !== undefined) {\n pg.shortDescription = patch.shortDescription\n sq.shortDescription = patch.shortDescription\n }\n if (patch.status !== undefined) {\n pg.status = patch.status\n sq.status = patch.status\n }\n if (patch.type !== undefined) {\n pg.type = patch.type\n sq.type = patch.type\n }\n if (patch.seoTitle !== undefined) {\n pg.seoTitle = patch.seoTitle\n sq.seoTitle = patch.seoTitle\n }\n if (patch.seoDescription !== undefined) {\n pg.seoDescription = patch.seoDescription\n sq.seoDescription = patch.seoDescription\n }\n if (patch.media !== undefined) {\n pg.media = patch.media\n sq.media = JSON.stringify(patch.media)\n }\n if (patch.metadata !== undefined) {\n pg.metadata = patch.metadata\n sq.metadata = JSON.stringify(patch.metadata)\n }\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.products)\n .set(sq)\n .where(eq(sqliteSchema.products.id, id))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.products)\n .set(pg)\n .where(eq(postgresSchema.products.id, id))\n },\n async delete(tx, id) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx).delete(sqliteSchema.products).where(eq(sqliteSchema.products.id, id)).run()\n return\n }\n await postgresDb(tx).delete(postgresSchema.products).where(eq(postgresSchema.products.id, id))\n },\n async setStatus(tx, id, status, updatedAt) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.products)\n .set({ status, updatedAt: updatedAt.toISOString() })\n .where(eq(sqliteSchema.products.id, id))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.products)\n .set({ status, updatedAt })\n .where(eq(postgresSchema.products.id, id))\n },\n }\n}\n","export function serialiseJson(store: 'sqlite' | 'postgres', value: unknown): unknown {\n if (store === 'sqlite') {\n return JSON.stringify(value)\n }\n return value\n}\n\nexport function parseJson<T>(store: 'sqlite' | 'postgres', value: unknown, fallback: T): T {\n if (store === 'sqlite' && typeof value === 'string') {\n try {\n return JSON.parse(value) as T\n } catch {\n return fallback\n }\n }\n return (value ?? fallback) as T\n}\n\nexport function toIso(store: 'sqlite' | 'postgres', d: Date): Date | string {\n return store === 'sqlite' ? d.toISOString() : d\n}\n\nexport function fromTimestamp(value: unknown): string {\n if (value instanceof Date) return value.toISOString()\n return String(value)\n}\n","import { and, asc, eq, gte, sql } from 'drizzle-orm'\nimport type { Variant, VariantOption, VariantStatus, VariantDimensions } from '@nymbalhq/types'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport { parseJson, fromTimestamp } from './json.js'\n\nexport interface VariantInsert {\n id: string\n productId: string\n sku: string\n name: string\n priceMinor: number\n compareAtPriceMinor?: number | null\n weightGrams?: number | null\n dimensions?: VariantDimensions | null\n stock: number\n lowStockThreshold?: number\n options: VariantOption[]\n status?: VariantStatus\n createdAt: Date\n updatedAt: Date\n}\n\nexport interface VariantUpdate {\n name?: string\n priceMinor?: number\n compareAtPriceMinor?: number | null\n weightGrams?: number | null\n dimensions?: VariantDimensions | null\n lowStockThreshold?: number\n options?: VariantOption[]\n status?: VariantStatus\n updatedAt: Date\n}\n\nfunction rowToVariant(store: CommandStore['kind'], row: Record<string, unknown>): Variant {\n return {\n id: String(row.id),\n productId: String(row.productId),\n sku: String(row.sku),\n name: String(row.name ?? ''),\n priceMinor: Number(row.priceMinor),\n compareAtPriceMinor: row.compareAtPriceMinor == null ? null : Number(row.compareAtPriceMinor),\n weightGrams: row.weightGrams == null ? null : Number(row.weightGrams),\n dimensions: parseJson<VariantDimensions | null>(store, row.dimensions, null),\n stock: Number(row.stock),\n lowStockThreshold: Number(row.lowStockThreshold ?? 0),\n options: parseJson<VariantOption[]>(store, row.options, []),\n status: row.status as VariantStatus,\n createdAt: fromTimestamp(row.createdAt),\n updatedAt: fromTimestamp(row.updatedAt),\n }\n}\n\nexport interface VariantRepository extends StoreRepository {\n findById(tx: ReadTx, id: string): Promise<Variant | null>\n findBySku(tx: ReadTx, sku: string): Promise<Variant | null>\n findByProduct(tx: ReadTx, productId: string): Promise<Variant[]>\n insert(tx: Tx, v: VariantInsert): Promise<void>\n update(tx: Tx, id: string, patch: VariantUpdate): Promise<void>\n /** One conditional UPDATE: the new stock, or null when the variant is missing or holds fewer than `qty`. */\n decrementStock(tx: Tx, id: string, qty: number, at: Date): Promise<number | null>\n /** The new stock, or null when there is no such variant. */\n incrementStock(tx: Tx, id: string, qty: number, at: Date): Promise<number | null>\n delete(tx: Tx, id: string): Promise<void>\n}\n\nexport function createVariantRepository(store: CommandStore): VariantRepository {\n return {\n store,\n async findById(tx, id) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.variants)\n .where(eq(sqliteSchema.variants.id, id))\n .get()\n return row ? rowToVariant('sqlite', row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.variants)\n .where(eq(postgresSchema.variants.id, id))\n return row ? rowToVariant('postgres', row as Record<string, unknown>) : null\n },\n async findBySku(tx, sku) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.variants)\n .where(eq(sqliteSchema.variants.sku, sku))\n .get()\n return row ? rowToVariant('sqlite', row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.variants)\n .where(eq(postgresSchema.variants.sku, sku))\n return row ? rowToVariant('postgres', row as Record<string, unknown>) : null\n },\n async findByProduct(tx, productId) {\n if (tx.kind === 'sqlite') {\n const rows = sqliteDb(tx)\n .select()\n .from(sqliteSchema.variants)\n .where(eq(sqliteSchema.variants.productId, productId))\n .orderBy(asc(sqliteSchema.variants.createdAt), asc(sqliteSchema.variants.id))\n .all()\n return rows.map((r) => rowToVariant('sqlite', r as Record<string, unknown>))\n }\n const rows = await postgresDb(tx)\n .select()\n .from(postgresSchema.variants)\n .where(eq(postgresSchema.variants.productId, productId))\n .orderBy(asc(postgresSchema.variants.createdAt), asc(postgresSchema.variants.id))\n return rows.map((r) => rowToVariant('postgres', r as Record<string, unknown>))\n },\n async insert(tx, v) {\n const common = {\n id: v.id,\n productId: v.productId,\n sku: v.sku,\n name: v.name,\n priceMinor: v.priceMinor,\n compareAtPriceMinor: v.compareAtPriceMinor ?? null,\n weightGrams: v.weightGrams ?? null,\n stock: v.stock,\n lowStockThreshold: v.lowStockThreshold ?? 0,\n status: v.status ?? 'active',\n }\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.variants)\n .values({\n ...common,\n dimensions: v.dimensions ? JSON.stringify(v.dimensions) : null,\n options: JSON.stringify(v.options),\n createdAt: v.createdAt.toISOString(),\n updatedAt: v.updatedAt.toISOString(),\n })\n .run()\n return\n }\n await postgresDb(tx)\n .insert(postgresSchema.variants)\n .values({\n ...common,\n dimensions: v.dimensions ?? null,\n options: v.options,\n createdAt: v.createdAt,\n updatedAt: v.updatedAt,\n })\n },\n async update(tx, id, patch) {\n const pg: Record<string, unknown> = { updatedAt: patch.updatedAt }\n const sq: Record<string, unknown> = { updatedAt: patch.updatedAt.toISOString() }\n for (const k of [\n 'name',\n 'priceMinor',\n 'compareAtPriceMinor',\n 'weightGrams',\n 'lowStockThreshold',\n 'status',\n ] as const) {\n if (patch[k] !== undefined) {\n pg[k] = patch[k]\n sq[k] = patch[k]\n }\n }\n if (patch.dimensions !== undefined) {\n pg.dimensions = patch.dimensions ?? null\n sq.dimensions = patch.dimensions ? JSON.stringify(patch.dimensions) : null\n }\n if (patch.options !== undefined) {\n pg.options = patch.options\n sq.options = JSON.stringify(patch.options)\n }\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.variants)\n .set(sq)\n .where(eq(sqliteSchema.variants.id, id))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.variants)\n .set(pg)\n .where(eq(postgresSchema.variants.id, id))\n },\n async decrementStock(tx, id, qty, at) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .update(sqliteSchema.variants)\n .set({ stock: sql`${sqliteSchema.variants.stock} - ${qty}`, updatedAt: at.toISOString() })\n .where(and(eq(sqliteSchema.variants.id, id), gte(sqliteSchema.variants.stock, qty)))\n .returning({ stock: sqliteSchema.variants.stock })\n .get()\n return row ? Number(row.stock) : null\n }\n const [row] = await postgresDb(tx)\n .update(postgresSchema.variants)\n .set({ stock: sql`${postgresSchema.variants.stock} - ${qty}`, updatedAt: at })\n .where(and(eq(postgresSchema.variants.id, id), gte(postgresSchema.variants.stock, qty)))\n .returning({ stock: postgresSchema.variants.stock })\n return row ? Number(row.stock) : null\n },\n async incrementStock(tx, id, qty, at) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .update(sqliteSchema.variants)\n .set({ stock: sql`${sqliteSchema.variants.stock} + ${qty}`, updatedAt: at.toISOString() })\n .where(eq(sqliteSchema.variants.id, id))\n .returning({ stock: sqliteSchema.variants.stock })\n .get()\n return row ? Number(row.stock) : null\n }\n const [row] = await postgresDb(tx)\n .update(postgresSchema.variants)\n .set({ stock: sql`${postgresSchema.variants.stock} + ${qty}`, updatedAt: at })\n .where(eq(postgresSchema.variants.id, id))\n .returning({ stock: postgresSchema.variants.stock })\n return row ? Number(row.stock) : null\n },\n async delete(tx, id) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx).delete(sqliteSchema.variants).where(eq(sqliteSchema.variants.id, id)).run()\n return\n }\n await postgresDb(tx).delete(postgresSchema.variants).where(eq(postgresSchema.variants.id, id))\n },\n }\n}\n","import { asc, eq, gt } from 'drizzle-orm'\nimport type { Category } from '@nymbalhq/types'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport type { KeysetPage } from './page.js'\nimport { fromTimestamp } from './json.js'\n\nexport interface CategoryInsert {\n id: string\n parentId?: string | null\n slug: string\n name: string\n description?: string\n position?: number\n createdAt: Date\n}\n\nexport interface CategoryUpdate {\n parentId?: string | null\n name?: string\n description?: string\n position?: number\n}\n\nfunction rowToCategory(row: Record<string, unknown>): Category {\n return {\n id: String(row.id),\n parentId: (row.parentId as string | null) ?? null,\n slug: String(row.slug),\n name: String(row.name),\n description: String(row.description ?? ''),\n position: Number(row.position ?? 0),\n createdAt: fromTimestamp(row.createdAt),\n }\n}\n\nexport interface CategoryRepository extends StoreRepository {\n findById(tx: ReadTx, id: string): Promise<Category | null>\n findBySlug(tx: ReadTx, slug: string): Promise<Category | null>\n list(tx: ReadTx): Promise<Category[]>\n /** Rows by id after `page.after`: a walk over the table that a concurrent write cannot make skip a row. */\n listPage(tx: ReadTx, page: KeysetPage): Promise<Category[]>\n insert(tx: Tx, c: CategoryInsert): Promise<void>\n update(tx: Tx, id: string, patch: CategoryUpdate): Promise<void>\n delete(tx: Tx, id: string): Promise<void>\n}\n\nexport function createCategoryRepository(store: CommandStore): CategoryRepository {\n return {\n store,\n async findById(tx, id) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.categories)\n .where(eq(sqliteSchema.categories.id, id))\n .get()\n return row ? rowToCategory(row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.categories)\n .where(eq(postgresSchema.categories.id, id))\n return row ? rowToCategory(row as Record<string, unknown>) : null\n },\n async findBySlug(tx, slug) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.categories)\n .where(eq(sqliteSchema.categories.slug, slug))\n .get()\n return row ? rowToCategory(row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.categories)\n .where(eq(postgresSchema.categories.slug, slug))\n return row ? rowToCategory(row as Record<string, unknown>) : null\n },\n async listPage(tx, page) {\n if (tx.kind === 'sqlite') {\n const t = sqliteSchema.categories\n const rows = sqliteDb(tx)\n .select()\n .from(t)\n .where(page.after === undefined ? undefined : gt(t.id, page.after))\n .orderBy(asc(t.id))\n .limit(page.limit)\n .all()\n return rows.map((r) => rowToCategory(r as Record<string, unknown>))\n }\n const t = postgresSchema.categories\n const rows = await postgresDb(tx)\n .select()\n .from(t)\n .where(page.after === undefined ? undefined : gt(t.id, page.after))\n .orderBy(asc(t.id))\n .limit(page.limit)\n return rows.map((r) => rowToCategory(r as Record<string, unknown>))\n },\n async list(tx) {\n if (tx.kind === 'sqlite') {\n const rows = sqliteDb(tx).select().from(sqliteSchema.categories).all()\n return rows.map((r) => rowToCategory(r as Record<string, unknown>))\n }\n const rows = await postgresDb(tx).select().from(postgresSchema.categories)\n return rows.map((r) => rowToCategory(r as Record<string, unknown>))\n },\n async insert(tx, c) {\n const common = {\n id: c.id,\n parentId: c.parentId ?? null,\n slug: c.slug,\n name: c.name,\n description: c.description ?? '',\n position: c.position ?? 0,\n }\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.categories)\n .values({ ...common, createdAt: c.createdAt.toISOString() })\n .run()\n return\n }\n await postgresDb(tx)\n .insert(postgresSchema.categories)\n .values({ ...common, createdAt: c.createdAt })\n },\n async update(tx, id, patch) {\n const set: Record<string, unknown> = {}\n if (patch.parentId !== undefined) set.parentId = patch.parentId\n if (patch.name !== undefined) set.name = patch.name\n if (patch.description !== undefined) set.description = patch.description\n if (patch.position !== undefined) set.position = patch.position\n if (Object.keys(set).length === 0) return\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.categories)\n .set(set)\n .where(eq(sqliteSchema.categories.id, id))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.categories)\n .set(set)\n .where(eq(postgresSchema.categories.id, id))\n },\n async delete(tx, id) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx).delete(sqliteSchema.categories).where(eq(sqliteSchema.categories.id, id)).run()\n return\n }\n await postgresDb(tx)\n .delete(postgresSchema.categories)\n .where(eq(postgresSchema.categories.id, id))\n },\n }\n}\n","import { and, eq } from 'drizzle-orm'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\n\nexport interface ProductCategoryRepository extends StoreRepository {\n attach(tx: Tx, productId: string, categoryId: string): Promise<void>\n detach(tx: Tx, productId: string, categoryId: string): Promise<void>\n detachAllForProduct(tx: Tx, productId: string): Promise<void>\n listCategoriesForProduct(tx: ReadTx, productId: string): Promise<string[]>\n listProductsForCategory(tx: ReadTx, categoryId: string): Promise<string[]>\n}\n\nexport function createProductCategoryRepository(store: CommandStore): ProductCategoryRepository {\n return {\n store,\n async attach(tx, productId, categoryId) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.productCategories)\n .values({ productId, categoryId })\n .onConflictDoNothing()\n .run()\n return\n }\n await postgresDb(tx)\n .insert(postgresSchema.productCategories)\n .values({ productId, categoryId })\n .onConflictDoNothing()\n },\n async detach(tx, productId, categoryId) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .delete(sqliteSchema.productCategories)\n .where(\n and(\n eq(sqliteSchema.productCategories.productId, productId),\n eq(sqliteSchema.productCategories.categoryId, categoryId),\n ),\n )\n .run()\n return\n }\n await postgresDb(tx)\n .delete(postgresSchema.productCategories)\n .where(\n and(\n eq(postgresSchema.productCategories.productId, productId),\n eq(postgresSchema.productCategories.categoryId, categoryId),\n ),\n )\n },\n async detachAllForProduct(tx, productId) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .delete(sqliteSchema.productCategories)\n .where(eq(sqliteSchema.productCategories.productId, productId))\n .run()\n return\n }\n await postgresDb(tx)\n .delete(postgresSchema.productCategories)\n .where(eq(postgresSchema.productCategories.productId, productId))\n },\n async listCategoriesForProduct(tx, productId) {\n if (tx.kind === 'sqlite') {\n const rows = sqliteDb(tx)\n .select({ categoryId: sqliteSchema.productCategories.categoryId })\n .from(sqliteSchema.productCategories)\n .where(eq(sqliteSchema.productCategories.productId, productId))\n .all()\n return rows.map((r) => r.categoryId)\n }\n const rows = await postgresDb(tx)\n .select({ categoryId: postgresSchema.productCategories.categoryId })\n .from(postgresSchema.productCategories)\n .where(eq(postgresSchema.productCategories.productId, productId))\n return rows.map((r) => r.categoryId)\n },\n async listProductsForCategory(tx, categoryId) {\n if (tx.kind === 'sqlite') {\n const rows = sqliteDb(tx)\n .select({ productId: sqliteSchema.productCategories.productId })\n .from(sqliteSchema.productCategories)\n .where(eq(sqliteSchema.productCategories.categoryId, categoryId))\n .all()\n return rows.map((r) => r.productId)\n }\n const rows = await postgresDb(tx)\n .select({ productId: postgresSchema.productCategories.productId })\n .from(postgresSchema.productCategories)\n .where(eq(postgresSchema.productCategories.categoryId, categoryId))\n return rows.map((r) => r.productId)\n },\n }\n}\n","import { asc, eq, gt, sql } from 'drizzle-orm'\nimport type { Customer, CustomerAddress, Role } from '@nymbalhq/types'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport type { KeysetPage } from './page.js'\nimport { parseJson, fromTimestamp } from './json.js'\n\nexport interface CustomerInsert {\n id: string\n email: string\n passwordHash: string\n firstName?: string\n lastName?: string\n phone?: string\n addresses?: CustomerAddress[]\n metadata?: Record<string, unknown>\n /** Defaults to `['customer']`; only seed and admin code pass anything else. */\n roles?: Role[]\n requiresPasswordReset?: boolean\n createdAt: Date\n updatedAt: Date\n}\n\nexport interface CustomerUpdate {\n firstName?: string\n lastName?: string\n phone?: string\n addresses?: CustomerAddress[]\n metadata?: Record<string, unknown>\n passwordHash?: string\n requiresPasswordReset?: boolean\n updatedAt: Date\n}\n\nfunction rowToCustomer(\n store: CommandStore['kind'],\n row: Record<string, unknown>,\n): CustomerWithHash {\n return {\n id: String(row.id),\n email: String(row.email),\n passwordHash: String(row.passwordHash),\n firstName: String(row.firstName ?? ''),\n lastName: String(row.lastName ?? ''),\n phone: String(row.phone ?? ''),\n addresses: parseJson<CustomerAddress[]>(store, row.addresses, []),\n orderCount: Number(row.orderCount ?? 0),\n totalSpentMinor: Number(row.totalSpentMinor ?? 0),\n metadata: parseJson<Record<string, unknown>>(store, row.metadata, {}),\n roles: parseJson<Role[]>(store, row.roles, ['customer']),\n requiresPasswordReset: Boolean(row.requiresPasswordReset),\n createdAt: fromTimestamp(row.createdAt),\n updatedAt: fromTimestamp(row.updatedAt),\n }\n}\n\n/** A stored customer: its roles column is always read. */\nexport type CustomerWithHash = Customer & { passwordHash: string; roles: Role[] }\n\nexport interface CustomerRepository extends StoreRepository {\n findById(tx: ReadTx, id: string): Promise<CustomerWithHash | null>\n findByEmail(tx: ReadTx, email: string): Promise<CustomerWithHash | null>\n list(tx: ReadTx, opts?: { limit?: number; offset?: number }): Promise<CustomerWithHash[]>\n /** Rows by id after `page.after`: a walk over the table that a concurrent write cannot make skip a row. */\n listPage(tx: ReadTx, page: KeysetPage): Promise<CustomerWithHash[]>\n insert(tx: Tx, c: CustomerInsert): Promise<void>\n update(tx: Tx, id: string, patch: CustomerUpdate): Promise<void>\n incrementStats(\n tx: Tx,\n id: string,\n deltaOrders: number,\n deltaSpentMinor: number,\n updatedAt: Date,\n ): Promise<void>\n delete(tx: Tx, id: string): Promise<void>\n}\n\nexport function createCustomerRepository(store: CommandStore): CustomerRepository {\n return {\n store,\n async findById(tx, id) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.customers)\n .where(eq(sqliteSchema.customers.id, id))\n .get()\n return row ? rowToCustomer('sqlite', row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.customers)\n .where(eq(postgresSchema.customers.id, id))\n return row ? rowToCustomer('postgres', row as Record<string, unknown>) : null\n },\n async findByEmail(tx, email) {\n const normalized = email.toLowerCase()\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.customers)\n .where(eq(sqliteSchema.customers.email, normalized))\n .get()\n return row ? rowToCustomer('sqlite', row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.customers)\n .where(eq(postgresSchema.customers.email, normalized))\n return row ? rowToCustomer('postgres', row as Record<string, unknown>) : null\n },\n async listPage(tx, page) {\n if (tx.kind === 'sqlite') {\n const t = sqliteSchema.customers\n const rows = sqliteDb(tx)\n .select()\n .from(t)\n .where(page.after === undefined ? undefined : gt(t.id, page.after))\n .orderBy(asc(t.id))\n .limit(page.limit)\n .all()\n return rows.map((r) => rowToCustomer('sqlite', r as Record<string, unknown>))\n }\n const t = postgresSchema.customers\n const rows = await postgresDb(tx)\n .select()\n .from(t)\n .where(page.after === undefined ? undefined : gt(t.id, page.after))\n .orderBy(asc(t.id))\n .limit(page.limit)\n return rows.map((r) => rowToCustomer('postgres', r as Record<string, unknown>))\n },\n async list(tx, opts = {}) {\n const limit = opts.limit ?? 1000\n const offset = opts.offset ?? 0\n if (tx.kind === 'sqlite') {\n const rows = sqliteDb(tx)\n .select()\n .from(sqliteSchema.customers)\n .limit(limit)\n .offset(offset)\n .all()\n return rows.map((r) => rowToCustomer('sqlite', r as Record<string, unknown>))\n }\n const rows = await postgresDb(tx)\n .select()\n .from(postgresSchema.customers)\n .limit(limit)\n .offset(offset)\n return rows.map((r) => rowToCustomer('postgres', r as Record<string, unknown>))\n },\n async insert(tx, c) {\n const email = c.email.toLowerCase()\n const common = {\n id: c.id,\n email,\n passwordHash: c.passwordHash,\n firstName: c.firstName ?? '',\n lastName: c.lastName ?? '',\n phone: c.phone ?? '',\n orderCount: 0,\n totalSpentMinor: 0,\n requiresPasswordReset: c.requiresPasswordReset ?? false,\n }\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.customers)\n .values({\n ...common,\n addresses: JSON.stringify(c.addresses ?? []),\n metadata: JSON.stringify(c.metadata ?? {}),\n roles: JSON.stringify(c.roles ?? ['customer']),\n createdAt: c.createdAt.toISOString(),\n updatedAt: c.updatedAt.toISOString(),\n })\n .run()\n return\n }\n await postgresDb(tx)\n .insert(postgresSchema.customers)\n .values({\n ...common,\n addresses: c.addresses ?? [],\n metadata: c.metadata ?? {},\n roles: c.roles ?? ['customer'],\n createdAt: c.createdAt,\n updatedAt: c.updatedAt,\n })\n },\n async update(tx, id, patch) {\n const pg: Record<string, unknown> = { updatedAt: patch.updatedAt }\n const sq: Record<string, unknown> = { updatedAt: patch.updatedAt.toISOString() }\n for (const k of [\n 'firstName',\n 'lastName',\n 'phone',\n 'passwordHash',\n 'requiresPasswordReset',\n ] as const) {\n if (patch[k] !== undefined) {\n pg[k] = patch[k]\n sq[k] = patch[k]\n }\n }\n if (patch.addresses !== undefined) {\n pg.addresses = patch.addresses\n sq.addresses = JSON.stringify(patch.addresses)\n }\n if (patch.metadata !== undefined) {\n pg.metadata = patch.metadata\n sq.metadata = JSON.stringify(patch.metadata)\n }\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.customers)\n .set(sq)\n .where(eq(sqliteSchema.customers.id, id))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.customers)\n .set(pg)\n .where(eq(postgresSchema.customers.id, id))\n },\n async incrementStats(tx, id, deltaOrders, deltaSpent, updatedAt) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.customers)\n .set({\n orderCount: sql`${sqliteSchema.customers.orderCount} + ${deltaOrders}`,\n totalSpentMinor: sql`${sqliteSchema.customers.totalSpentMinor} + ${deltaSpent}`,\n updatedAt: updatedAt.toISOString(),\n })\n .where(eq(sqliteSchema.customers.id, id))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.customers)\n .set({\n orderCount: sql`${postgresSchema.customers.orderCount} + ${deltaOrders}`,\n totalSpentMinor: sql`${postgresSchema.customers.totalSpentMinor} + ${deltaSpent}`,\n updatedAt,\n })\n .where(eq(postgresSchema.customers.id, id))\n },\n async delete(tx, id) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx).delete(sqliteSchema.customers).where(eq(sqliteSchema.customers.id, id)).run()\n return\n }\n await postgresDb(tx)\n .delete(postgresSchema.customers)\n .where(eq(postgresSchema.customers.id, id))\n },\n }\n}\n","import { and, eq, isNull, lt } from 'drizzle-orm'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport { fromTimestamp } from './json.js'\n\nexport interface RefreshTokenInsert {\n id: string\n customerId: string\n tokenHash: string\n expiresAt: Date\n createdAt: Date\n}\n\nexport interface RefreshTokenRow {\n id: string\n customerId: string\n tokenHash: string\n revokedAt: string | null\n replacedByJti: string | null\n expiresAt: string\n createdAt: string\n}\n\nfunction rowToToken(row: Record<string, unknown>): RefreshTokenRow {\n return {\n id: String(row.id),\n customerId: String(row.customerId),\n tokenHash: String(row.tokenHash),\n revokedAt: row.revokedAt == null ? null : fromTimestamp(row.revokedAt),\n replacedByJti: (row.replacedByJti as string | null) ?? null,\n expiresAt: fromTimestamp(row.expiresAt),\n createdAt: fromTimestamp(row.createdAt),\n }\n}\n\nexport interface RefreshTokenRepository extends StoreRepository {\n insert(tx: Tx, t: RefreshTokenInsert): Promise<void>\n findById(tx: ReadTx, id: string): Promise<RefreshTokenRow | null>\n rotate(tx: Tx, oldJti: string, next: RefreshTokenInsert): Promise<void>\n revoke(tx: Tx, id: string): Promise<void>\n revokeAllForCustomer(tx: Tx, customerId: string): Promise<void>\n purgeExpired(tx: Tx, now: Date): Promise<number>\n}\n\nexport function createRefreshTokenRepository(store: CommandStore): RefreshTokenRepository {\n return {\n store,\n async insert(tx, t) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.refreshTokens)\n .values({\n id: t.id,\n customerId: t.customerId,\n tokenHash: t.tokenHash,\n revokedAt: null,\n replacedByJti: null,\n expiresAt: t.expiresAt.toISOString(),\n createdAt: t.createdAt.toISOString(),\n })\n .run()\n return\n }\n await postgresDb(tx).insert(postgresSchema.refreshTokens).values({\n id: t.id,\n customerId: t.customerId,\n tokenHash: t.tokenHash,\n revokedAt: null,\n replacedByJti: null,\n expiresAt: t.expiresAt,\n createdAt: t.createdAt,\n })\n },\n async findById(tx, id) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.refreshTokens)\n .where(eq(sqliteSchema.refreshTokens.id, id))\n .get()\n return row ? rowToToken(row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.refreshTokens)\n .where(eq(postgresSchema.refreshTokens.id, id))\n return row ? rowToToken(row as Record<string, unknown>) : null\n },\n async rotate(tx, oldJti, next) {\n if (tx.kind === 'sqlite') {\n const db = sqliteDb(tx)\n db.update(sqliteSchema.refreshTokens)\n .set({ revokedAt: new Date().toISOString(), replacedByJti: next.id })\n .where(eq(sqliteSchema.refreshTokens.id, oldJti))\n .run()\n db.insert(sqliteSchema.refreshTokens)\n .values({\n id: next.id,\n customerId: next.customerId,\n tokenHash: next.tokenHash,\n revokedAt: null,\n replacedByJti: null,\n expiresAt: next.expiresAt.toISOString(),\n createdAt: next.createdAt.toISOString(),\n })\n .run()\n return\n }\n const db = postgresDb(tx)\n await db\n .update(postgresSchema.refreshTokens)\n .set({ revokedAt: new Date(), replacedByJti: next.id })\n .where(eq(postgresSchema.refreshTokens.id, oldJti))\n await db.insert(postgresSchema.refreshTokens).values({\n id: next.id,\n customerId: next.customerId,\n tokenHash: next.tokenHash,\n revokedAt: null,\n replacedByJti: null,\n expiresAt: next.expiresAt,\n createdAt: next.createdAt,\n })\n },\n async revoke(tx, id) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.refreshTokens)\n .set({ revokedAt: new Date().toISOString() })\n .where(\n and(\n eq(sqliteSchema.refreshTokens.id, id),\n isNull(sqliteSchema.refreshTokens.revokedAt),\n ),\n )\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.refreshTokens)\n .set({ revokedAt: new Date() })\n .where(\n and(\n eq(postgresSchema.refreshTokens.id, id),\n isNull(postgresSchema.refreshTokens.revokedAt),\n ),\n )\n },\n async revokeAllForCustomer(tx, customerId) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.refreshTokens)\n .set({ revokedAt: new Date().toISOString() })\n .where(eq(sqliteSchema.refreshTokens.customerId, customerId))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.refreshTokens)\n .set({ revokedAt: new Date() })\n .where(eq(postgresSchema.refreshTokens.customerId, customerId))\n },\n async purgeExpired(tx, now) {\n if (tx.kind === 'sqlite') {\n const result = sqliteDb(tx)\n .delete(sqliteSchema.refreshTokens)\n .where(lt(sqliteSchema.refreshTokens.expiresAt, now.toISOString()))\n .run()\n return result.changes\n }\n const result = await postgresDb(tx)\n .delete(postgresSchema.refreshTokens)\n .where(lt(postgresSchema.refreshTokens.expiresAt, now))\n return result.rowCount ?? 0\n },\n }\n}\n","import { and, asc, desc, eq, gt, notInArray } from 'drizzle-orm'\nimport type { Address, CaptureMethod, Order, OrderLineItem, OrderStatus } from '@nymbalhq/types'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport type { KeysetPage } from './page.js'\nimport { parseJson, fromTimestamp } from './json.js'\n\nexport interface OrderInsert {\n id: string\n orderNumber: string\n sequence: number\n customerId: string | null\n status: OrderStatus\n email: string\n billingAddress: Address\n shippingAddress: Address\n lineItems: OrderLineItem[]\n subtotalMinor: number\n taxTotalMinor: number\n shippingTotalMinor: number\n discountTotalMinor: number\n totalMinor: number\n currency: string\n notes?: string\n metadata?: Record<string, unknown>\n paymentIntentId?: string | null\n /** The cart a checkout order was placed from. */\n cartToken?: string | null\n /** An imported order's money; a checkout order starts with nothing captured. */\n capture?: OrderCapture & { refundedMinor: number }\n createdAt: Date\n updatedAt: Date\n}\n\nexport interface OrderCapture {\n amountMinor: number\n method: CaptureMethod\n at: Date\n}\n\nfunction rowToOrder(store: CommandStore['kind'], row: Record<string, unknown>): Order {\n return {\n id: String(row.id),\n orderNumber: String(row.orderNumber),\n sequence: Number(row.sequence),\n customerId: (row.customerId as string | null) ?? null,\n status: row.status as OrderStatus,\n email: String(row.email),\n billingAddress: parseJson<Address>(store, row.billingAddress, {} as Address),\n shippingAddress: parseJson<Address>(store, row.shippingAddress, {} as Address),\n lineItems: parseJson<OrderLineItem[]>(store, row.lineItems, []),\n subtotalMinor: Number(row.subtotalMinor),\n taxTotalMinor: Number(row.taxTotalMinor ?? 0),\n shippingTotalMinor: Number(row.shippingTotalMinor ?? 0),\n discountTotalMinor: Number(row.discountTotalMinor ?? 0),\n totalMinor: Number(row.totalMinor),\n currency: String(row.currency),\n notes: String(row.notes ?? ''),\n metadata: parseJson<Record<string, unknown>>(store, row.metadata, {}),\n paymentIntentId: (row.paymentIntentId as string | null) ?? null,\n capturedMinor: Number(row.capturedMinor ?? 0),\n capturedAt: row.capturedAt == null ? null : fromTimestamp(row.capturedAt),\n refundedMinor: Number(row.refundedMinor ?? 0),\n captureMethod: (row.captureMethod as CaptureMethod | null) ?? null,\n createdAt: fromTimestamp(row.createdAt),\n updatedAt: fromTimestamp(row.updatedAt),\n }\n}\n\nexport interface OrderRepository extends StoreRepository {\n findById(tx: ReadTx, id: string): Promise<Order | null>\n /** The order, read under its row lock until the transaction ends (Postgres `FOR UPDATE`; on SQLite the open\n * `BEGIN IMMEDIATE` transaction already holds every write). */\n lock(tx: Tx, id: string): Promise<Order | null>\n findByOrderNumber(tx: ReadTx, orderNumber: string): Promise<Order | null>\n findByPaymentIntentId(tx: ReadTx, paymentIntentId: string): Promise<Order | null>\n /** The cart's pending order: at most one, by the partial unique index on `cart_token`. */\n findPendingByCartToken(tx: ReadTx, cartToken: string): Promise<Order | null>\n /** The newest order the cart became: neither pending nor cancelled. */\n findLastConvertedByCartToken(tx: ReadTx, cartToken: string): Promise<Order | null>\n listByCustomer(tx: ReadTx, customerId: string, limit?: number): Promise<Order[]>\n list(\n tx: ReadTx,\n opts?: { status?: OrderStatus; limit?: number; offset?: number },\n ): Promise<Order[]>\n /** Rows by id after `page.after`: a walk over the table that a concurrent write cannot make skip a row. */\n listPage(tx: ReadTx, page: KeysetPage): Promise<Order[]>\n insert(tx: Tx, o: OrderInsert): Promise<void>\n setStatus(tx: Tx, id: string, status: OrderStatus, updatedAt: Date): Promise<void>\n /** Sets `status` only while the order is still `from`; false when it was not, so a concurrent writer got there\n * first. */\n setStatusIf(\n tx: Tx,\n id: string,\n from: OrderStatus,\n status: OrderStatus,\n updatedAt: Date,\n ): Promise<boolean>\n setPaymentIntent(tx: Tx, id: string, paymentIntentId: string, updatedAt: Date): Promise<void>\n recordCapture(tx: Tx, id: string, capture: OrderCapture): Promise<void>\n setRefunded(tx: Tx, id: string, refundedMinor: number, updatedAt: Date): Promise<void>\n setNotes(tx: Tx, id: string, notes: string, updatedAt: Date): Promise<void>\n}\n\nexport function createOrderRepository(store: CommandStore): OrderRepository {\n return {\n store,\n async findById(tx, id) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.orders)\n .where(eq(sqliteSchema.orders.id, id))\n .get()\n return row ? rowToOrder('sqlite', row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.orders)\n .where(eq(postgresSchema.orders.id, id))\n return row ? rowToOrder('postgres', row as Record<string, unknown>) : null\n },\n async lock(tx, id) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.orders)\n .where(eq(sqliteSchema.orders.id, id))\n .get()\n return row ? rowToOrder('sqlite', row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.orders)\n .where(eq(postgresSchema.orders.id, id))\n .for('update')\n return row ? rowToOrder('postgres', row as Record<string, unknown>) : null\n },\n async findByOrderNumber(tx, orderNumber) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.orders)\n .where(eq(sqliteSchema.orders.orderNumber, orderNumber))\n .get()\n return row ? rowToOrder('sqlite', row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.orders)\n .where(eq(postgresSchema.orders.orderNumber, orderNumber))\n return row ? rowToOrder('postgres', row as Record<string, unknown>) : null\n },\n async findByPaymentIntentId(tx, paymentIntentId) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.orders)\n .where(eq(sqliteSchema.orders.paymentIntentId, paymentIntentId))\n .get()\n return row ? rowToOrder('sqlite', row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.orders)\n .where(eq(postgresSchema.orders.paymentIntentId, paymentIntentId))\n .limit(1)\n return row ? rowToOrder('postgres', row as Record<string, unknown>) : null\n },\n async findPendingByCartToken(tx, cartToken) {\n if (tx.kind === 'sqlite') {\n const o = sqliteSchema.orders\n const row = sqliteDb(tx)\n .select()\n .from(o)\n .where(and(eq(o.cartToken, cartToken), eq(o.status, 'pending')))\n .get()\n return row ? rowToOrder('sqlite', row as Record<string, unknown>) : null\n }\n const o = postgresSchema.orders\n const [row] = await postgresDb(tx)\n .select()\n .from(o)\n .where(and(eq(o.cartToken, cartToken), eq(o.status, 'pending')))\n return row ? rowToOrder('postgres', row as Record<string, unknown>) : null\n },\n async findLastConvertedByCartToken(tx, cartToken) {\n const unconverted = ['pending', 'cancelled'] as const\n if (tx.kind === 'sqlite') {\n const o = sqliteSchema.orders\n const row = sqliteDb(tx)\n .select()\n .from(o)\n .where(and(eq(o.cartToken, cartToken), notInArray(o.status, [...unconverted])))\n .orderBy(desc(o.sequence))\n .limit(1)\n .get()\n return row ? rowToOrder('sqlite', row as Record<string, unknown>) : null\n }\n const o = postgresSchema.orders\n const [row] = await postgresDb(tx)\n .select()\n .from(o)\n .where(and(eq(o.cartToken, cartToken), notInArray(o.status, [...unconverted])))\n .orderBy(desc(o.sequence))\n .limit(1)\n return row ? rowToOrder('postgres', row as Record<string, unknown>) : null\n },\n async listByCustomer(tx, customerId, limit = 50) {\n if (tx.kind === 'sqlite') {\n const rows = sqliteDb(tx)\n .select()\n .from(sqliteSchema.orders)\n .where(eq(sqliteSchema.orders.customerId, customerId))\n .orderBy(desc(sqliteSchema.orders.createdAt))\n .limit(limit)\n .all()\n return rows.map((r) => rowToOrder('sqlite', r as Record<string, unknown>))\n }\n const rows = await postgresDb(tx)\n .select()\n .from(postgresSchema.orders)\n .where(eq(postgresSchema.orders.customerId, customerId))\n .orderBy(desc(postgresSchema.orders.createdAt))\n .limit(limit)\n return rows.map((r) => rowToOrder('postgres', r as Record<string, unknown>))\n },\n async listPage(tx, page) {\n if (tx.kind === 'sqlite') {\n const t = sqliteSchema.orders\n const rows = sqliteDb(tx)\n .select()\n .from(t)\n .where(page.after === undefined ? undefined : gt(t.id, page.after))\n .orderBy(asc(t.id))\n .limit(page.limit)\n .all()\n return rows.map((r) => rowToOrder('sqlite', r as Record<string, unknown>))\n }\n const t = postgresSchema.orders\n const rows = await postgresDb(tx)\n .select()\n .from(t)\n .where(page.after === undefined ? undefined : gt(t.id, page.after))\n .orderBy(asc(t.id))\n .limit(page.limit)\n return rows.map((r) => rowToOrder('postgres', r as Record<string, unknown>))\n },\n async list(tx, opts = {}) {\n const limit = opts.limit ?? 100\n const offset = opts.offset ?? 0\n if (tx.kind === 'sqlite') {\n const base = sqliteDb(tx).select().from(sqliteSchema.orders)\n const filtered = opts.status\n ? base.where(eq(sqliteSchema.orders.status, opts.status))\n : base\n const rows = filtered\n .orderBy(desc(sqliteSchema.orders.createdAt))\n .limit(limit)\n .offset(offset)\n .all()\n return rows.map((r) => rowToOrder('sqlite', r as Record<string, unknown>))\n }\n const base = postgresDb(tx).select().from(postgresSchema.orders)\n const filtered = opts.status\n ? base.where(eq(postgresSchema.orders.status, opts.status))\n : base\n const rows = await filtered\n .orderBy(desc(postgresSchema.orders.createdAt))\n .limit(limit)\n .offset(offset)\n return rows.map((r) => rowToOrder('postgres', r as Record<string, unknown>))\n },\n async insert(tx, o) {\n const common = {\n id: o.id,\n orderNumber: o.orderNumber,\n sequence: o.sequence,\n customerId: o.customerId,\n status: o.status,\n email: o.email,\n subtotalMinor: o.subtotalMinor,\n taxTotalMinor: o.taxTotalMinor,\n shippingTotalMinor: o.shippingTotalMinor,\n discountTotalMinor: o.discountTotalMinor,\n totalMinor: o.totalMinor,\n currency: o.currency,\n notes: o.notes ?? '',\n paymentIntentId: o.paymentIntentId ?? null,\n cartToken: o.cartToken ?? null,\n capturedMinor: o.capture?.amountMinor ?? 0,\n refundedMinor: o.capture?.refundedMinor ?? 0,\n captureMethod: o.capture?.method ?? null,\n }\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.orders)\n .values({\n ...common,\n billingAddress: JSON.stringify(o.billingAddress),\n shippingAddress: JSON.stringify(o.shippingAddress),\n lineItems: JSON.stringify(o.lineItems),\n metadata: JSON.stringify(o.metadata ?? {}),\n capturedAt: o.capture?.at.toISOString() ?? null,\n createdAt: o.createdAt.toISOString(),\n updatedAt: o.updatedAt.toISOString(),\n })\n .run()\n return\n }\n await postgresDb(tx)\n .insert(postgresSchema.orders)\n .values({\n ...common,\n billingAddress: o.billingAddress,\n shippingAddress: o.shippingAddress,\n lineItems: o.lineItems,\n metadata: o.metadata ?? {},\n capturedAt: o.capture?.at ?? null,\n createdAt: o.createdAt,\n updatedAt: o.updatedAt,\n })\n },\n async setStatus(tx, id, status, updatedAt) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.orders)\n .set({ status, updatedAt: updatedAt.toISOString() })\n .where(eq(sqliteSchema.orders.id, id))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.orders)\n .set({ status, updatedAt })\n .where(eq(postgresSchema.orders.id, id))\n },\n async setStatusIf(tx, id, from, status, updatedAt) {\n if (tx.kind === 'sqlite') {\n const o = sqliteSchema.orders\n const { changes } = sqliteDb(tx)\n .update(o)\n .set({ status, updatedAt: updatedAt.toISOString() })\n .where(and(eq(o.id, id), eq(o.status, from)))\n .run()\n return changes > 0\n }\n const o = postgresSchema.orders\n const result = await postgresDb(tx)\n .update(o)\n .set({ status, updatedAt })\n .where(and(eq(o.id, id), eq(o.status, from)))\n return (result.rowCount ?? 0) > 0\n },\n async setPaymentIntent(tx, id, paymentIntentId, updatedAt) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.orders)\n .set({ paymentIntentId, updatedAt: updatedAt.toISOString() })\n .where(eq(sqliteSchema.orders.id, id))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.orders)\n .set({ paymentIntentId, updatedAt })\n .where(eq(postgresSchema.orders.id, id))\n },\n async recordCapture(tx, id, capture) {\n const values = {\n capturedMinor: capture.amountMinor,\n captureMethod: capture.method,\n }\n if (tx.kind === 'sqlite') {\n const at = capture.at.toISOString()\n sqliteDb(tx)\n .update(sqliteSchema.orders)\n .set({ ...values, capturedAt: at, updatedAt: at })\n .where(eq(sqliteSchema.orders.id, id))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.orders)\n .set({ ...values, capturedAt: capture.at, updatedAt: capture.at })\n .where(eq(postgresSchema.orders.id, id))\n },\n async setRefunded(tx, id, refundedMinor, updatedAt) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.orders)\n .set({ refundedMinor, updatedAt: updatedAt.toISOString() })\n .where(eq(sqliteSchema.orders.id, id))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.orders)\n .set({ refundedMinor, updatedAt })\n .where(eq(postgresSchema.orders.id, id))\n },\n async setNotes(tx, id, notes, updatedAt) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.orders)\n .set({ notes, updatedAt: updatedAt.toISOString() })\n .where(eq(sqliteSchema.orders.id, id))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.orders)\n .set({ notes, updatedAt })\n .where(eq(postgresSchema.orders.id, id))\n },\n }\n}\n","import { asc, eq } from 'drizzle-orm'\nimport type { OrderHistoryEntry, OrderStatus } from '@nymbalhq/types'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport { fromTimestamp } from './json.js'\n\nexport interface OrderHistoryInsert {\n id: string\n orderId: string\n fromStatus: OrderStatus | null\n toStatus: OrderStatus\n actor: string\n note?: string\n timestamp: Date\n}\n\nfunction rowToEntry(row: Record<string, unknown>): OrderHistoryEntry {\n return {\n id: String(row.id),\n orderId: String(row.orderId),\n fromStatus: (row.fromStatus as OrderStatus | null) ?? null,\n toStatus: row.toStatus as OrderStatus,\n actor: String(row.actor),\n note: String(row.note ?? ''),\n timestamp: fromTimestamp(row.timestamp),\n }\n}\n\nexport interface OrderHistoryRepository extends StoreRepository {\n append(tx: Tx, entry: OrderHistoryInsert): Promise<void>\n listByOrder(tx: ReadTx, orderId: string): Promise<OrderHistoryEntry[]>\n}\n\nexport function createOrderHistoryRepository(store: CommandStore): OrderHistoryRepository {\n return {\n store,\n async append(tx, entry) {\n const common = {\n id: entry.id,\n orderId: entry.orderId,\n fromStatus: entry.fromStatus,\n toStatus: entry.toStatus,\n actor: entry.actor,\n note: entry.note ?? '',\n }\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.orderHistory)\n .values({ ...common, timestamp: entry.timestamp.toISOString() })\n .run()\n return\n }\n await postgresDb(tx)\n .insert(postgresSchema.orderHistory)\n .values({ ...common, timestamp: entry.timestamp })\n },\n async listByOrder(tx, orderId) {\n if (tx.kind === 'sqlite') {\n const rows = sqliteDb(tx)\n .select()\n .from(sqliteSchema.orderHistory)\n .where(eq(sqliteSchema.orderHistory.orderId, orderId))\n .orderBy(asc(sqliteSchema.orderHistory.timestamp), asc(sqliteSchema.orderHistory.id))\n .all()\n return rows.map((r) => rowToEntry(r as Record<string, unknown>))\n }\n const rows = await postgresDb(tx)\n .select()\n .from(postgresSchema.orderHistory)\n .where(eq(postgresSchema.orderHistory.orderId, orderId))\n .orderBy(asc(postgresSchema.orderHistory.timestamp), asc(postgresSchema.orderHistory.id))\n return rows.map((r) => rowToEntry(r as Record<string, unknown>))\n },\n }\n}\n","import { and, asc, eq, inArray } from 'drizzle-orm'\nimport type { OrderRefund, OrderRefundStatus } from '@nymbalhq/types'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport { fromTimestamp } from './json.js'\n\nexport interface OrderRefundInsert {\n id: string\n orderId: string\n amountMinor: number\n currency: string\n providerRefundId: string | null\n status: OrderRefundStatus\n reason: string | null\n actor: string\n createdAt: Date\n /** The client's key for the request that made the refund; unique per order. */\n requestId?: string | null\n}\n\nfunction rowToRefund(row: Record<string, unknown>): OrderRefund {\n return {\n id: String(row.id),\n orderId: String(row.orderId),\n amountMinor: Number(row.amountMinor),\n currency: String(row.currency),\n providerRefundId: (row.providerRefundId as string | null) ?? null,\n status: row.status as OrderRefundStatus,\n reason: (row.reason as string | null) ?? null,\n actor: String(row.actor),\n createdAt: fromTimestamp(row.createdAt),\n }\n}\n\nexport interface OrderRefundRepository extends StoreRepository {\n insert(tx: Tx, refund: OrderRefundInsert): Promise<void>\n /** Settles a `pending` refund; false when the row is not pending (already settled). */\n settle(\n tx: Tx,\n id: string,\n outcome: { status: OrderRefundStatus; providerRefundId: string | null },\n ): Promise<boolean>\n /** The order's refund made by the request `requestId`, or null. */\n findByRequestId(tx: ReadTx, orderId: string, requestId: string): Promise<OrderRefund | null>\n /** The order's refunds, oldest first. */\n listByOrder(tx: ReadTx, orderId: string): Promise<OrderRefund[]>\n /** The refunds of each order, oldest first; an order without refunds is absent. */\n listByOrders(tx: ReadTx, orderIds: string[]): Promise<Map<string, OrderRefund[]>>\n}\n\nexport function createOrderRefundRepository(store: CommandStore): OrderRefundRepository {\n async function list(tx: ReadTx, orderIds: string[]): Promise<OrderRefund[]> {\n if (orderIds.length === 0) return []\n if (tx.kind === 'sqlite') {\n const r = sqliteSchema.orderRefunds\n const rows = sqliteDb(tx)\n .select()\n .from(r)\n .where(inArray(r.orderId, orderIds))\n .orderBy(asc(r.createdAt), asc(r.id))\n .all()\n return rows.map((row) => rowToRefund(row as Record<string, unknown>))\n }\n const r = postgresSchema.orderRefunds\n const rows = await postgresDb(tx)\n .select()\n .from(r)\n .where(inArray(r.orderId, orderIds))\n .orderBy(asc(r.createdAt), asc(r.id))\n return rows.map((row) => rowToRefund(row as Record<string, unknown>))\n }\n\n return {\n store,\n async insert(tx, refund) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.orderRefunds)\n .values({ ...refund, createdAt: refund.createdAt.toISOString() })\n .run()\n return\n }\n await postgresDb(tx).insert(postgresSchema.orderRefunds).values(refund)\n },\n async settle(tx, id, outcome) {\n if (tx.kind === 'sqlite') {\n const r = sqliteSchema.orderRefunds\n const { changes } = sqliteDb(tx)\n .update(r)\n .set(outcome)\n .where(and(eq(r.id, id), eq(r.status, 'pending')))\n .run()\n return changes > 0\n }\n const r = postgresSchema.orderRefunds\n const result = await postgresDb(tx)\n .update(r)\n .set(outcome)\n .where(and(eq(r.id, id), eq(r.status, 'pending')))\n return (result.rowCount ?? 0) > 0\n },\n async findByRequestId(tx, orderId, requestId) {\n if (tx.kind === 'sqlite') {\n const r = sqliteSchema.orderRefunds\n const row = sqliteDb(tx)\n .select()\n .from(r)\n .where(and(eq(r.orderId, orderId), eq(r.requestId, requestId)))\n .get()\n return row ? rowToRefund(row as Record<string, unknown>) : null\n }\n const r = postgresSchema.orderRefunds\n const [row] = await postgresDb(tx)\n .select()\n .from(r)\n .where(and(eq(r.orderId, orderId), eq(r.requestId, requestId)))\n return row ? rowToRefund(row as Record<string, unknown>) : null\n },\n listByOrder(tx, orderId) {\n return list(tx, [orderId])\n },\n async listByOrders(tx, orderIds) {\n const byOrder = new Map<string, OrderRefund[]>()\n for (const refund of await list(tx, orderIds)) {\n const refunds = byOrder.get(refund.orderId) ?? []\n refunds.push(refund)\n byOrder.set(refund.orderId, refunds)\n }\n return byOrder\n },\n }\n}\n","import { sql } from 'drizzle-orm'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\n\nexport interface OrderSequenceRepository extends StoreRepository {\n nextSequence(tx: Tx, startFrom?: number): Promise<number>\n}\n\nexport function createOrderSequenceRepository(store: CommandStore): OrderSequenceRepository {\n return {\n store,\n // One upsert: on a fresh store a read finds no row to lock, so concurrent first allocations would each insert it.\n // The value handed out is the one the row held before this call (startFrom on the first).\n async nextSequence(tx, startFrom = 1000): Promise<number> {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .insert(sqliteSchema.orderSequences)\n .values({ id: 1, nextValue: startFrom + 1 })\n .onConflictDoUpdate({\n target: sqliteSchema.orderSequences.id,\n set: { nextValue: sql`${sqliteSchema.orderSequences.nextValue} + 1` },\n })\n .returning({ nextValue: sqliteSchema.orderSequences.nextValue })\n .get()\n return row.nextValue - 1\n }\n // Stryker disable all: the Postgres dialect, which the SQLite integration run cannot reach; tests/postgres covers it\n const [row] = await postgresDb(tx)\n .insert(postgresSchema.orderSequences)\n .values({ id: 1, nextValue: startFrom + 1 })\n .onConflictDoUpdate({\n target: postgresSchema.orderSequences.id,\n set: { nextValue: sql`${postgresSchema.orderSequences.nextValue} + 1` },\n })\n .returning({ nextValue: postgresSchema.orderSequences.nextValue })\n return row!.nextValue - 1\n // Stryker restore all\n },\n }\n}\n","import { and, asc, eq, inArray } from 'drizzle-orm'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\n\n/** Who minted the key: a checkout answer, or the order-placed email. */\nexport type OrderAccessKeyPurpose = 'checkout' | 'email'\n\n/** What a key does for an order: opens it, has expired, or is not one of its keys. */\nexport type OrderKeyState = 'open' | 'expired' | 'none'\n\nexport interface OrderAccessKeyInsert {\n id: string\n orderId: string\n /** sha256 hex of the key; the key itself is never stored. */\n keyHash: string\n purpose: OrderAccessKeyPurpose\n createdAt: Date\n expiresAt: Date\n}\n\nexport interface OrderAccessKeyRepository extends StoreRepository {\n insert(tx: Tx, k: OrderAccessKeyInsert): Promise<void>\n /** What a key with this hash does for this order at `now`: another order's key is `none` here. */\n opens(tx: ReadTx, orderId: string, keyHash: string, now: Date): Promise<OrderKeyState>\n /** Deletes the order's oldest keys of `purpose`, by `(created_at, id)`, until at most `keep` remain. */\n keepNewest(tx: Tx, orderId: string, purpose: OrderAccessKeyPurpose, keep: number): Promise<void>\n}\n\nexport function createOrderAccessKeyRepository(store: CommandStore): OrderAccessKeyRepository {\n return {\n store,\n async insert(tx, k) {\n const row = { id: k.id, orderId: k.orderId, keyHash: k.keyHash, purpose: k.purpose }\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.orderAccessKeys)\n .values({\n ...row,\n createdAt: k.createdAt.toISOString(),\n expiresAt: k.expiresAt.toISOString(),\n })\n .run()\n return\n }\n // Stryker disable all: the Postgres dialect, which the SQLite integration run cannot reach; tests/postgres covers it\n await postgresDb(tx)\n .insert(postgresSchema.orderAccessKeys)\n .values({ ...row, createdAt: k.createdAt, expiresAt: k.expiresAt })\n // Stryker restore all\n },\n async opens(tx, orderId, keyHash, now) {\n let expiresAt: number | undefined\n if (tx.kind === 'sqlite') {\n const t = sqliteSchema.orderAccessKeys\n const row = sqliteDb(tx)\n .select({ expiresAt: t.expiresAt })\n .from(t)\n .where(and(eq(t.orderId, orderId), eq(t.keyHash, keyHash)))\n .get()\n if (row !== undefined) expiresAt = Date.parse(row.expiresAt)\n } else {\n // Stryker disable all: the Postgres dialect, which the SQLite integration run cannot reach; tests/postgres covers it\n const t = postgresSchema.orderAccessKeys\n const rows = await postgresDb(tx)\n .select({ expiresAt: t.expiresAt })\n .from(t)\n .where(and(eq(t.orderId, orderId), eq(t.keyHash, keyHash)))\n .limit(1)\n if (rows[0] !== undefined) expiresAt = rows[0].expiresAt.getTime()\n }\n // Stryker restore all\n if (expiresAt === undefined) return 'none'\n return now.getTime() < expiresAt ? 'open' : 'expired'\n },\n async keepNewest(tx, orderId, purpose, keep) {\n let ids: string[]\n if (tx.kind === 'sqlite') {\n const t = sqliteSchema.orderAccessKeys\n ids = sqliteDb(tx)\n .select({ id: t.id })\n .from(t)\n .where(and(eq(t.orderId, orderId), eq(t.purpose, purpose)))\n .orderBy(asc(t.createdAt), asc(t.id))\n .all()\n .map((r) => r.id)\n } else {\n // Stryker disable all: the Postgres dialect, which the SQLite integration run cannot reach; tests/postgres covers it\n const t = postgresSchema.orderAccessKeys\n const rows = await postgresDb(tx)\n .select({ id: t.id })\n .from(t)\n .where(and(eq(t.orderId, orderId), eq(t.purpose, purpose)))\n .orderBy(asc(t.createdAt), asc(t.id))\n ids = rows.map((r) => r.id)\n }\n // Stryker restore all\n const stale = ids.slice(0, Math.max(0, ids.length - keep))\n if (stale.length === 0) return\n if (tx.kind === 'sqlite') {\n const t = sqliteSchema.orderAccessKeys\n sqliteDb(tx).delete(t).where(inArray(t.id, stale)).run()\n return\n }\n // Stryker disable all: the Postgres dialect, which the SQLite integration run cannot reach; tests/postgres covers it\n const t = postgresSchema.orderAccessKeys\n await postgresDb(tx).delete(t).where(inArray(t.id, stale))\n // Stryker restore all\n },\n }\n}\n","import { eq, lt } from 'drizzle-orm'\nimport type { InventoryReservation } from '@nymbalhq/types'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport { fromTimestamp } from './json.js'\n\nexport interface ReservationInsert {\n reservationId: string\n variantId: string\n qty: number\n orderRef?: string | null\n expiresAt: Date\n createdAt: Date\n}\n\nfunction rowToReservation(row: Record<string, unknown>): InventoryReservation {\n return {\n reservationId: String(row.reservationId),\n variantId: String(row.variantId),\n qty: Number(row.qty),\n orderRef: (row.orderRef as string | null) ?? null,\n expiresAt: fromTimestamp(row.expiresAt),\n createdAt: fromTimestamp(row.createdAt),\n }\n}\n\nexport interface InventoryReservationRepository extends StoreRepository {\n insert(tx: Tx, r: ReservationInsert): Promise<void>\n findById(tx: ReadTx, reservationId: string): Promise<InventoryReservation | null>\n findByVariant(tx: ReadTx, variantId: string): Promise<InventoryReservation[]>\n /** Deletes the reservation and returns the row it removed; null when none was there. Of two concurrent callers\n * only one gets the row, which is what makes a release and a commit of one reservation exclusive. */\n deleteById(tx: Tx, reservationId: string): Promise<InventoryReservation | null>\n /** Reservations whose expiry is before `at`; deletes nothing. */\n findExpiredBefore(tx: ReadTx, at: Date): Promise<InventoryReservation[]>\n setOrderRef(tx: Tx, reservationId: string, orderRef: string): Promise<void>\n}\n\nexport function createInventoryReservationRepository(\n store: CommandStore,\n): InventoryReservationRepository {\n return {\n store,\n async insert(tx, r) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.inventoryReservations)\n .values({\n reservationId: r.reservationId,\n variantId: r.variantId,\n qty: r.qty,\n orderRef: r.orderRef ?? null,\n expiresAt: r.expiresAt.toISOString(),\n createdAt: r.createdAt.toISOString(),\n })\n .run()\n return\n }\n await postgresDb(tx)\n .insert(postgresSchema.inventoryReservations)\n .values({\n reservationId: r.reservationId,\n variantId: r.variantId,\n qty: r.qty,\n orderRef: r.orderRef ?? null,\n expiresAt: r.expiresAt,\n createdAt: r.createdAt,\n })\n },\n async findById(tx, reservationId) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.inventoryReservations)\n .where(eq(sqliteSchema.inventoryReservations.reservationId, reservationId))\n .get()\n return row ? rowToReservation(row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.inventoryReservations)\n .where(eq(postgresSchema.inventoryReservations.reservationId, reservationId))\n return row ? rowToReservation(row as Record<string, unknown>) : null\n },\n async findByVariant(tx, variantId) {\n if (tx.kind === 'sqlite') {\n const rows = sqliteDb(tx)\n .select()\n .from(sqliteSchema.inventoryReservations)\n .where(eq(sqliteSchema.inventoryReservations.variantId, variantId))\n .all()\n return rows.map((r) => rowToReservation(r as Record<string, unknown>))\n }\n const rows = await postgresDb(tx)\n .select()\n .from(postgresSchema.inventoryReservations)\n .where(eq(postgresSchema.inventoryReservations.variantId, variantId))\n return rows.map((r) => rowToReservation(r as Record<string, unknown>))\n },\n async deleteById(tx, reservationId) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .delete(sqliteSchema.inventoryReservations)\n .where(eq(sqliteSchema.inventoryReservations.reservationId, reservationId))\n .returning()\n .get()\n return row ? rowToReservation(row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .delete(postgresSchema.inventoryReservations)\n .where(eq(postgresSchema.inventoryReservations.reservationId, reservationId))\n .returning()\n return row ? rowToReservation(row as Record<string, unknown>) : null\n },\n async findExpiredBefore(tx, at) {\n if (tx.kind === 'sqlite') {\n const rows = sqliteDb(tx)\n .select()\n .from(sqliteSchema.inventoryReservations)\n .where(lt(sqliteSchema.inventoryReservations.expiresAt, at.toISOString()))\n .all()\n return rows.map((r) => rowToReservation(r as Record<string, unknown>))\n }\n const rows = await postgresDb(tx)\n .select()\n .from(postgresSchema.inventoryReservations)\n .where(lt(postgresSchema.inventoryReservations.expiresAt, at))\n return rows.map((r) => rowToReservation(r as Record<string, unknown>))\n },\n async setOrderRef(tx, reservationId, orderRef) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.inventoryReservations)\n .set({ orderRef })\n .where(eq(sqliteSchema.inventoryReservations.reservationId, reservationId))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.inventoryReservations)\n .set({ orderRef })\n .where(eq(postgresSchema.inventoryReservations.reservationId, reservationId))\n },\n }\n}\n","import { desc, eq } from 'drizzle-orm'\nimport type { StockAdjustment, StockAdjustmentReason } from '@nymbalhq/types'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport { fromTimestamp } from './json.js'\n\nexport interface StockAdjustmentInsert {\n id: string\n variantId: string\n adjustment: number\n reason: StockAdjustmentReason\n actor: string\n previousQty: number\n newQty: number\n timestamp: Date\n}\n\nfunction rowToAdjustment(row: Record<string, unknown>): StockAdjustment {\n return {\n id: String(row.id),\n variantId: String(row.variantId),\n adjustment: Number(row.adjustment),\n reason: row.reason as StockAdjustmentReason,\n actor: String(row.actor),\n previousQty: Number(row.previousQty),\n newQty: Number(row.newQty),\n timestamp: fromTimestamp(row.timestamp),\n }\n}\n\nexport interface StockAdjustmentRepository extends StoreRepository {\n append(tx: Tx, a: StockAdjustmentInsert): Promise<void>\n listByVariant(tx: ReadTx, variantId: string, limit?: number): Promise<StockAdjustment[]>\n}\n\nexport function createStockAdjustmentRepository(store: CommandStore): StockAdjustmentRepository {\n return {\n store,\n async append(tx, a) {\n const common = {\n id: a.id,\n variantId: a.variantId,\n adjustment: a.adjustment,\n reason: a.reason,\n actor: a.actor,\n previousQty: a.previousQty,\n newQty: a.newQty,\n }\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.stockAdjustments)\n .values({ ...common, timestamp: a.timestamp.toISOString() })\n .run()\n return\n }\n await postgresDb(tx)\n .insert(postgresSchema.stockAdjustments)\n .values({ ...common, timestamp: a.timestamp })\n },\n async listByVariant(tx, variantId, limit = 100) {\n if (tx.kind === 'sqlite') {\n const rows = sqliteDb(tx)\n .select()\n .from(sqliteSchema.stockAdjustments)\n .where(eq(sqliteSchema.stockAdjustments.variantId, variantId))\n .orderBy(desc(sqliteSchema.stockAdjustments.timestamp))\n .limit(limit)\n .all()\n return rows.map((r) => rowToAdjustment(r as Record<string, unknown>))\n }\n const rows = await postgresDb(tx)\n .select()\n .from(postgresSchema.stockAdjustments)\n .where(eq(postgresSchema.stockAdjustments.variantId, variantId))\n .orderBy(desc(postgresSchema.stockAdjustments.timestamp))\n .limit(limit)\n return rows.map((r) => rowToAdjustment(r as Record<string, unknown>))\n },\n }\n}\n","import { and, desc, eq, lt, or, type SQL } from 'drizzle-orm'\nimport type { Review, ReviewModerationStatus } from '@nymbalhq/types'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport { fromTimestamp } from './json.js'\n\nexport interface ReviewInsert {\n id: string\n productId: string\n customerId: string | null\n orderId: string | null\n rating: number\n title: string\n body: string\n moderationStatus?: ReviewModerationStatus\n submittedAt: Date\n}\n\nfunction rowToReview(row: Record<string, unknown>): Review {\n return {\n id: String(row.id),\n productId: String(row.productId),\n customerId: (row.customerId as string | null) ?? null,\n orderId: (row.orderId as string | null) ?? null,\n rating: Number(row.rating),\n title: String(row.title ?? ''),\n body: String(row.body ?? ''),\n moderationStatus: row.moderationStatus as ReviewModerationStatus,\n submittedAt: fromTimestamp(row.submittedAt),\n moderatedAt: row.moderatedAt == null ? null : fromTimestamp(row.moderatedAt),\n moderatedBy: (row.moderatedBy as string | null) ?? null,\n }\n}\n\n/** Where a page of a product's reviews starts: after this review, in the newest-first, then id-descending order. */\nexport interface ReviewKey {\n submittedAt: string\n id: string\n}\n\nexport interface ReviewRepository extends StoreRepository {\n findById(tx: ReadTx, id: string): Promise<Review | null>\n /** Newest first, ties by id descending; `after` is the last review of the previous page. */\n listByProduct(\n tx: ReadTx,\n productId: string,\n status?: ReviewModerationStatus,\n limit?: number,\n after?: ReviewKey,\n ): Promise<Review[]>\n listByStatus(tx: ReadTx, status: ReviewModerationStatus, limit?: number): Promise<Review[]>\n insert(tx: Tx, r: ReviewInsert): Promise<void>\n setModerationStatus(\n tx: Tx,\n id: string,\n status: ReviewModerationStatus,\n moderatedBy: string,\n moderatedAt: Date,\n ): Promise<void>\n aggregateByProduct(\n tx: ReadTx,\n productId: string,\n ): Promise<{\n average: number\n count: number\n histogram: Record<'1' | '2' | '3' | '4' | '5', number>\n }>\n}\n\nexport function createReviewRepository(store: CommandStore): ReviewRepository {\n return {\n store,\n async findById(tx, id) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.reviews)\n .where(eq(sqliteSchema.reviews.id, id))\n .get()\n return row ? rowToReview(row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.reviews)\n .where(eq(postgresSchema.reviews.id, id))\n return row ? rowToReview(row as Record<string, unknown>) : null\n },\n async listByProduct(tx, productId, status, limit = 50, after) {\n if (tx.kind === 'sqlite') {\n const t = sqliteSchema.reviews\n const conds: SQL[] = [eq(t.productId, productId)]\n if (status) conds.push(eq(t.moderationStatus, status))\n if (after) {\n const at = new Date(after.submittedAt).toISOString()\n conds.push(or(lt(t.submittedAt, at), and(eq(t.submittedAt, at), lt(t.id, after.id)))!)\n }\n const rows = sqliteDb(tx)\n .select()\n .from(t)\n .where(and(...conds))\n .orderBy(desc(t.submittedAt), desc(t.id))\n .limit(limit)\n .all()\n return rows.map((r) => rowToReview(r as Record<string, unknown>))\n }\n const t = postgresSchema.reviews\n const conds: SQL[] = [eq(t.productId, productId)]\n if (status) conds.push(eq(t.moderationStatus, status))\n if (after) {\n const at = new Date(after.submittedAt)\n conds.push(or(lt(t.submittedAt, at), and(eq(t.submittedAt, at), lt(t.id, after.id)))!)\n }\n const rows = await postgresDb(tx)\n .select()\n .from(t)\n .where(and(...conds))\n .orderBy(desc(t.submittedAt), desc(t.id))\n .limit(limit)\n return rows.map((r) => rowToReview(r as Record<string, unknown>))\n },\n async listByStatus(tx, status, limit = 100) {\n if (tx.kind === 'sqlite') {\n const rows = sqliteDb(tx)\n .select()\n .from(sqliteSchema.reviews)\n .where(eq(sqliteSchema.reviews.moderationStatus, status))\n .orderBy(desc(sqliteSchema.reviews.submittedAt))\n .limit(limit)\n .all()\n return rows.map((r) => rowToReview(r as Record<string, unknown>))\n }\n const rows = await postgresDb(tx)\n .select()\n .from(postgresSchema.reviews)\n .where(eq(postgresSchema.reviews.moderationStatus, status))\n .orderBy(desc(postgresSchema.reviews.submittedAt))\n .limit(limit)\n return rows.map((r) => rowToReview(r as Record<string, unknown>))\n },\n async insert(tx, r) {\n const common = {\n id: r.id,\n productId: r.productId,\n customerId: r.customerId,\n orderId: r.orderId,\n rating: r.rating,\n title: r.title,\n body: r.body,\n moderationStatus: r.moderationStatus ?? 'pending',\n }\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.reviews)\n .values({\n ...common,\n submittedAt: r.submittedAt.toISOString(),\n moderatedAt: null,\n moderatedBy: null,\n })\n .run()\n return\n }\n await postgresDb(tx)\n .insert(postgresSchema.reviews)\n .values({\n ...common,\n submittedAt: r.submittedAt,\n moderatedAt: null,\n moderatedBy: null,\n })\n },\n async setModerationStatus(tx, id, status, moderatedBy, moderatedAt) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(sqliteSchema.reviews)\n .set({\n moderationStatus: status,\n moderatedBy,\n moderatedAt: moderatedAt.toISOString(),\n })\n .where(eq(sqliteSchema.reviews.id, id))\n .run()\n return\n }\n await postgresDb(tx)\n .update(postgresSchema.reviews)\n .set({ moderationStatus: status, moderatedBy, moderatedAt })\n .where(eq(postgresSchema.reviews.id, id))\n },\n async aggregateByProduct(tx, productId) {\n const approved = await this.listByProduct(tx, productId, 'approved', 1000)\n const histogram: Record<'1' | '2' | '3' | '4' | '5', number> = {\n '1': 0,\n '2': 0,\n '3': 0,\n '4': 0,\n '5': 0,\n }\n let total = 0\n for (const r of approved) {\n const bucket = String(\n Math.max(1, Math.min(5, Math.round(r.rating))),\n ) as keyof typeof histogram\n histogram[bucket] += 1\n total += r.rating\n }\n const count = approved.length\n const average = count === 0 ? 0 : total / count\n return { average, count, histogram }\n },\n }\n}\n","import { and, eq, lt } from 'drizzle-orm'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\n\n/** Which handler has already run for which event id: what stops a side effect running twice, across restarts. */\nexport interface ProcessedEventRepository extends StoreRepository {\n seen(tx: ReadTx, handlerName: string, eventId: string): Promise<boolean>\n /** Idempotent on (handlerName, eventId): a second call keeps the first record. */\n markProcessed(tx: Tx, handlerName: string, eventId: string, at: Date): Promise<void>\n /**\n * Records (handlerName, eventId) before its work runs: true when this call inserted it, false when it was there.\n * On Postgres a concurrent claim of the same key waits for this transaction, so only one of them does the work.\n */\n claim(tx: Tx, handlerName: string, eventId: string, at: Date): Promise<boolean>\n /** Deletes records processed before `at`; returns how many. */\n deleteBefore(tx: Tx, at: Date): Promise<number>\n}\n\nexport function createProcessedEventRepository(store: CommandStore): ProcessedEventRepository {\n const s = sqliteSchema.processedEvents\n const p = postgresSchema.processedEvents\n return {\n store,\n async seen(tx, handlerName, eventId) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select({ eventId: s.eventId })\n .from(s)\n .where(and(eq(s.handlerName, handlerName), eq(s.eventId, eventId)))\n .get()\n return row !== undefined\n }\n const rows = await postgresDb(tx)\n .select({ eventId: p.eventId })\n .from(p)\n .where(and(eq(p.handlerName, handlerName), eq(p.eventId, eventId)))\n .limit(1)\n return rows.length > 0\n },\n async markProcessed(tx, handlerName, eventId, at) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(s)\n .values({ handlerName, eventId, processedAt: at.toISOString() })\n .onConflictDoNothing()\n .run()\n return\n }\n await postgresDb(tx)\n .insert(p)\n .values({ handlerName, eventId, processedAt: at })\n .onConflictDoNothing()\n },\n async claim(tx, handlerName, eventId, at) {\n if (tx.kind === 'sqlite') {\n const result = sqliteDb(tx)\n .insert(s)\n .values({ handlerName, eventId, processedAt: at.toISOString() })\n .onConflictDoNothing()\n .run()\n return result.changes > 0\n }\n const result = await postgresDb(tx)\n .insert(p)\n .values({ handlerName, eventId, processedAt: at })\n .onConflictDoNothing()\n return (result.rowCount ?? 0) > 0\n },\n async deleteBefore(tx, at) {\n if (tx.kind === 'sqlite') {\n return sqliteDb(tx).delete(s).where(lt(s.processedAt, at.toISOString())).run().changes\n }\n const result = await postgresDb(tx).delete(p).where(lt(p.processedAt, at))\n return result.rowCount ?? 0\n },\n }\n}\n","import {\n and,\n asc,\n eq,\n gt,\n gte,\n inArray,\n isNotNull,\n isNull,\n lt,\n lte,\n or,\n sql,\n type SQL,\n} from 'drizzle-orm'\nimport type { NymbalEvent } from '@nymbalhq/types'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport { subjectOf, type EventSubject } from '../history/subject.js'\n\nexport interface LoggedEvent {\n seq: number\n event: NymbalEvent<unknown>\n deliveredAt: Date | null\n attempts: number\n deadAt: Date | null\n createdAt: Date\n}\n\n/** Filters for reading the log. A type glob's `*` matches any run of characters, dots included (`order.*`). */\nexport interface EventLogFilter {\n /** Type globs; an event matches when its type matches any of them. */\n types?: string[]\n /** Appended at or after. */\n since?: Date\n /** Appended before. */\n until?: Date\n limit: number\n}\n\nexport interface EventLogRepository extends StoreRepository {\n /** Appends in array order, so `seq` follows publish order. */\n append(tx: Tx, events: NymbalEvent<unknown>[]): Promise<void>\n /**\n * Neither delivered nor dead, by `seq`; `afterSeq` pages through one pass without re-reading rows it just tried.\n * Given `now`, a row whose `retry_at` is after it is left out.\n */\n listUndelivered(tx: ReadTx, limit: number, afterSeq?: number, now?: Date): Promise<LoggedEvent[]>\n markDelivered(tx: Tx, ids: string[], at: Date): Promise<void>\n /**\n * One more failed attempt; the event is dead (`dead_at = at`) once its attempts reach `maxAttempts`. `retryAt`, when\n * given, is the earliest the next attempt may be made.\n */\n recordFailure(tx: Tx, id: string, at: Date, maxAttempts: number, retryAt?: Date): Promise<void>\n /** A delivery that failed during an adapter outage: only the earliest next attempt moves, nothing is counted. */\n recordOutage(tx: Tx, id: string, retryAt: Date): Promise<void>\n countDead(tx: ReadTx): Promise<number>\n /** Dead events, oldest first. */\n listDead(tx: ReadTx, limit: number): Promise<LoggedEvent[]>\n /** Neither delivered nor dead, with at least one failed attempt. */\n countRetrying(tx: ReadTx): Promise<number>\n /** Deletes delivered events delivered before `at`; returns how many. Undelivered and dead events are never deleted. */\n deleteDeliveredBefore(tx: Tx, at: Date): Promise<number>\n listAll(tx: ReadTx): Promise<LoggedEvent[]>\n /** One correlation id's events, by `seq`. */\n queryByCorrelation(\n tx: ReadTx,\n correlationId: string,\n filter: EventLogFilter,\n ): Promise<LoggedEvent[]>\n /** Events above `seq`, by `seq`. */\n listAfter(\n tx: ReadTx,\n seq: number,\n filter: Pick<EventLogFilter, 'types' | 'limit'>,\n ): Promise<LoggedEvent[]>\n /** The highest `seq` in the log, or 0 when it is empty. */\n maxSeq(tx: ReadTx): Promise<number>\n /**\n * What a read-model rebuild re-applies after its swap: every event that is not dead and was delivered at or after\n * `since`, or not yet delivered, by `seq`. `afterSeq` and `limit` page through them.\n */\n listForCatchUp(\n tx: ReadTx,\n since: Date,\n page?: { afterSeq?: number; limit?: number },\n ): Promise<LoggedEvent[]>\n /** Delivered events delivered before `at`, by `seq`: what retention may archive. Undelivered and dead events never are. */\n listDeliveredBefore(tx: ReadTx, at: Date, limit: number): Promise<LoggedEvent[]>\n /** Deletes the delivered events with these `seq`s; returns how many. */\n deleteSeqs(tx: Tx, seqs: number[]): Promise<number>\n /**\n * The events whose subject is one of `subjects`, by `seq`: those appended at or before `until`, above `afterSeq`, at\n * most `limit`.\n */\n listBySubjects(\n tx: ReadTx,\n subjects: EventSubject[],\n page: { until?: Date; afterSeq?: number; limit: number },\n ): Promise<LoggedEvent[]>\n}\n\n// SQLite's bound-parameter limit is per statement; seven columns a row keep a chunk well under it.\nconst APPEND_CHUNK = 100\nconst DELETE_CHUNK = 500\nconst APPEND_INTO =\n 'INSERT INTO events (id, type, envelope, correlation_id, subject_type, subject_id, created_at) VALUES'\n/** The page `listForCatchUp` reads when it is given none. */\nconst CATCH_UP_LIMIT = 10_000\n\n/** A type glob as a SQLite GLOB pattern: `*` stays the wildcard, and GLOB's other metacharacters match themselves. */\nfunction sqliteGlob(glob: string): string {\n return glob.replace(/[[?]/g, (c) => `[${c}]`)\n}\n\n/**\n * A type glob as a Postgres LIKE pattern with a backslash escape: `*` is `%`, and LIKE's own metacharacters match\n * themselves. Case-sensitive, as SQLite's GLOB is.\n */\nfunction likePattern(glob: string): string {\n return glob.replace(/[\\\\%_]/g, (c) => `\\\\${c}`).replace(/\\*/g, '%')\n}\n\nfunction subjectColumns(e: NymbalEvent<unknown>): {\n subjectType: string | null\n subjectId: string | null\n} {\n const subject = subjectOf(e)\n return { subjectType: subject?.type ?? null, subjectId: subject?.id ?? null }\n}\n\nfunction toDate(value: unknown): Date | null {\n if (value === null || value === undefined) return null\n return value instanceof Date ? value : new Date(String(value))\n}\n\nfunction rowToLogged(row: {\n seq: number\n envelope: unknown\n deliveredAt: unknown\n attempts: number\n deadAt: unknown\n createdAt: unknown\n}): LoggedEvent {\n const envelope =\n typeof row.envelope === 'string'\n ? (JSON.parse(row.envelope) as NymbalEvent<unknown>)\n : (row.envelope as NymbalEvent<unknown>)\n return {\n seq: Number(row.seq),\n event: envelope,\n deliveredAt: toDate(row.deliveredAt),\n attempts: Number(row.attempts),\n deadAt: toDate(row.deadAt),\n createdAt: toDate(row.createdAt)!,\n }\n}\n\nexport function createEventLogRepository(store: CommandStore): EventLogRepository {\n const s = sqliteSchema.events\n const p = postgresSchema.events\n // The columns `rowToLogged` reads.\n const sqliteLogged = {\n seq: s.seq,\n envelope: s.envelope,\n deliveredAt: s.deliveredAt,\n attempts: s.attempts,\n deadAt: s.deadAt,\n createdAt: s.createdAt,\n }\n const postgresLogged = {\n seq: p.seq,\n envelope: p.envelope,\n deliveredAt: p.deliveredAt,\n attempts: p.attempts,\n deadAt: p.deadAt,\n createdAt: p.createdAt,\n }\n\n function sqliteWhere(filter: Partial<EventLogFilter>): SQL[] {\n const where: SQL[] = []\n if (filter.types !== undefined && filter.types.length > 0) {\n where.push(or(...filter.types.map((t) => sql`${s.type} GLOB ${sqliteGlob(t)}`))!)\n }\n if (filter.since !== undefined) where.push(gte(s.createdAt, filter.since.toISOString()))\n if (filter.until !== undefined) where.push(lt(s.createdAt, filter.until.toISOString()))\n return where\n }\n\n function postgresWhere(filter: Partial<EventLogFilter>): SQL[] {\n const where: SQL[] = []\n if (filter.types !== undefined && filter.types.length > 0) {\n where.push(or(...filter.types.map((t) => sql`${p.type} LIKE ${likePattern(t)} ESCAPE '\\\\'`))!)\n }\n if (filter.since !== undefined) where.push(gte(p.createdAt, filter.since))\n if (filter.until !== undefined) where.push(lt(p.createdAt, filter.until))\n return where\n }\n\n /** Only the columns a LoggedEvent maps: a boot rebuild reads the log on a store not yet migrated past 0007. */\n async function select(\n tx: ReadTx,\n where: { sqlite: SQL[]; postgres: SQL[] },\n limit: number,\n ): Promise<LoggedEvent[]> {\n if (tx.kind === 'sqlite') {\n return sqliteDb(tx)\n .select(sqliteLogged)\n .from(s)\n .where(and(...where.sqlite))\n .orderBy(asc(s.seq))\n .limit(limit)\n .all()\n .map(rowToLogged)\n }\n const rows = await postgresDb(tx)\n .select(postgresLogged)\n .from(p)\n .where(and(...where.postgres))\n .orderBy(asc(p.seq))\n .limit(limit)\n return rows.map(rowToLogged)\n }\n\n return {\n store,\n // The columns are named, not taken from the schema: a store a migration behind, before a later column of the log\n // (retry_at), still takes appends.\n async append(tx, events) {\n const now = new Date()\n for (let i = 0; i < events.length; i += APPEND_CHUNK) {\n const chunk = events.slice(i, i + APPEND_CHUNK)\n const rows = (row: (e: NymbalEvent<unknown>) => SQL) => sql.join(chunk.map(row), sql`, `)\n if (tx.kind === 'sqlite') {\n const at = now.toISOString()\n sqliteDb(tx).run(\n sql`${sql.raw(APPEND_INTO)} ${rows((e) => {\n const { subjectType, subjectId } = subjectColumns(e)\n return sql`(${e.id}, ${e.type}, ${JSON.stringify(e)}, ${e.correlationId}, ${subjectType}, ${subjectId}, ${at})`\n })}`,\n )\n } else {\n await postgresDb(tx).execute(\n sql`${sql.raw(APPEND_INTO)} ${rows((e) => {\n const { subjectType, subjectId } = subjectColumns(e)\n return sql`(${e.id}, ${e.type}, ${JSON.stringify(e)}::jsonb, ${e.correlationId}, ${subjectType}, ${subjectId}, ${now.toISOString()}::timestamptz)`\n })}`,\n )\n }\n }\n },\n listUndelivered(tx, limit, afterSeq = 0, now) {\n return select(\n tx,\n {\n sqlite: [\n isNull(s.deliveredAt),\n isNull(s.deadAt),\n gt(s.seq, afterSeq),\n ...(now === undefined\n ? []\n : [or(isNull(s.retryAt), lte(s.retryAt, now.toISOString()))!]),\n ],\n postgres: [\n isNull(p.deliveredAt),\n isNull(p.deadAt),\n gt(p.seq, afterSeq),\n ...(now === undefined ? [] : [or(isNull(p.retryAt), lte(p.retryAt, now))!]),\n ],\n },\n limit,\n )\n },\n async markDelivered(tx, ids, at) {\n if (ids.length === 0) return\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(s)\n .set({ deliveredAt: at.toISOString() })\n .where(inArray(s.id, ids))\n .run()\n return\n }\n await postgresDb(tx).update(p).set({ deliveredAt: at }).where(inArray(p.id, ids))\n },\n async recordFailure(tx, id, at, maxAttempts, retryAt) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .update(s)\n .set({\n attempts: sql`${s.attempts} + 1`,\n deadAt: sql`CASE WHEN ${s.attempts} + 1 >= ${maxAttempts} THEN ${at.toISOString()} ELSE ${s.deadAt} END`,\n ...(retryAt !== undefined && { retryAt: retryAt.toISOString() }),\n })\n .where(eq(s.id, id))\n .run()\n return\n }\n await postgresDb(tx)\n .update(p)\n .set({\n attempts: sql`${p.attempts} + 1`,\n deadAt: sql`CASE WHEN ${p.attempts} + 1 >= ${maxAttempts} THEN ${at.toISOString()}::timestamptz ELSE ${p.deadAt} END`,\n ...(retryAt !== undefined && { retryAt }),\n })\n .where(eq(p.id, id))\n },\n async recordOutage(tx, id, retryAt) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx).update(s).set({ retryAt: retryAt.toISOString() }).where(eq(s.id, id)).run()\n return\n }\n await postgresDb(tx).update(p).set({ retryAt }).where(eq(p.id, id))\n },\n async countDead(tx) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select({ n: sql<number>`count(*)` })\n .from(s)\n .where(isNotNull(s.deadAt))\n .get()\n return Number(row?.n ?? 0)\n }\n const [row] = await postgresDb(tx)\n .select({ n: sql<string>`count(*)` })\n .from(p)\n .where(isNotNull(p.deadAt))\n return Number(row?.n ?? 0)\n },\n listDead(tx, limit) {\n return select(tx, { sqlite: [isNotNull(s.deadAt)], postgres: [isNotNull(p.deadAt)] }, limit)\n },\n async countRetrying(tx) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select({ n: sql<number>`count(*)` })\n .from(s)\n .where(and(isNull(s.deliveredAt), isNull(s.deadAt), gt(s.attempts, 0)))\n .get()\n return Number(row?.n ?? 0)\n }\n const [row] = await postgresDb(tx)\n .select({ n: sql<string>`count(*)` })\n .from(p)\n .where(and(isNull(p.deliveredAt), isNull(p.deadAt), gt(p.attempts, 0)))\n return Number(row?.n ?? 0)\n },\n async deleteDeliveredBefore(tx, at) {\n if (tx.kind === 'sqlite') {\n const result = sqliteDb(tx)\n .delete(s)\n .where(and(isNotNull(s.deliveredAt), lt(s.deliveredAt, at.toISOString())))\n .run()\n return result.changes\n }\n const result = await postgresDb(tx)\n .delete(p)\n .where(and(isNotNull(p.deliveredAt), lt(p.deliveredAt, at)))\n return result.rowCount ?? 0\n },\n async listAll(tx) {\n if (tx.kind === 'sqlite') {\n return sqliteDb(tx).select(sqliteLogged).from(s).orderBy(asc(s.seq)).all().map(rowToLogged)\n }\n const rows = await postgresDb(tx).select(postgresLogged).from(p).orderBy(asc(p.seq))\n return rows.map(rowToLogged)\n },\n queryByCorrelation(tx, correlationId, filter) {\n return select(\n tx,\n {\n sqlite: [eq(s.correlationId, correlationId), ...sqliteWhere(filter)],\n postgres: [eq(p.correlationId, correlationId), ...postgresWhere(filter)],\n },\n filter.limit,\n )\n },\n listAfter(tx, seq, filter) {\n return select(\n tx,\n {\n sqlite: [gt(s.seq, seq), ...sqliteWhere(filter)],\n postgres: [gt(p.seq, seq), ...postgresWhere(filter)],\n },\n filter.limit,\n )\n },\n async maxSeq(tx) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select({ max: sql<number | null>`max(${s.seq})` })\n .from(s)\n .get()\n return Number(row?.max ?? 0)\n }\n const [row] = await postgresDb(tx)\n .select({ max: sql<string | null>`max(${p.seq})` })\n .from(p)\n return Number(row?.max ?? 0)\n },\n // Only the columns a LoggedEvent maps: a boot rebuild runs this on a store not yet migrated past 0007.\n async listForCatchUp(tx, since, page = {}) {\n const afterSeq = page.afterSeq ?? 0\n const limit = page.limit ?? CATCH_UP_LIMIT\n if (tx.kind === 'sqlite') {\n return sqliteDb(tx)\n .select(sqliteLogged)\n .from(s)\n .where(\n and(\n isNull(s.deadAt),\n or(isNull(s.deliveredAt), gte(s.deliveredAt, since.toISOString())),\n gt(s.seq, afterSeq),\n ),\n )\n .orderBy(asc(s.seq))\n .limit(limit)\n .all()\n .map(rowToLogged)\n }\n const rows = await postgresDb(tx)\n .select(postgresLogged)\n .from(p)\n .where(\n and(\n isNull(p.deadAt),\n or(isNull(p.deliveredAt), gte(p.deliveredAt, since)),\n gt(p.seq, afterSeq),\n ),\n )\n .orderBy(asc(p.seq))\n .limit(limit)\n return rows.map(rowToLogged)\n },\n listDeliveredBefore(tx, at, limit) {\n return select(\n tx,\n {\n sqlite: [isNull(s.deadAt), isNotNull(s.deliveredAt), lt(s.deliveredAt, at.toISOString())],\n postgres: [isNull(p.deadAt), isNotNull(p.deliveredAt), lt(p.deliveredAt, at)],\n },\n limit,\n )\n },\n async deleteSeqs(tx, seqs) {\n let deleted = 0\n for (let i = 0; i < seqs.length; i += DELETE_CHUNK) {\n const chunk = seqs.slice(i, i + DELETE_CHUNK)\n if (tx.kind === 'sqlite') {\n deleted += sqliteDb(tx)\n .delete(s)\n .where(and(inArray(s.seq, chunk), isNotNull(s.deliveredAt), isNull(s.deadAt)))\n .run().changes\n } else {\n const result = await postgresDb(tx)\n .delete(p)\n .where(and(inArray(p.seq, chunk), isNotNull(p.deliveredAt), isNull(p.deadAt)))\n deleted += result.rowCount ?? 0\n }\n }\n return deleted\n },\n async listBySubjects(tx, subjects, page) {\n if (subjects.length === 0) return []\n const afterSeq = page.afterSeq ?? 0\n return select(\n tx,\n {\n sqlite: [\n or(...subjects.map((x) => and(eq(s.subjectType, x.type), eq(s.subjectId, x.id))))!,\n gt(s.seq, afterSeq),\n ...(page.until === undefined ? [] : [lte(s.createdAt, page.until.toISOString())]),\n ],\n postgres: [\n or(...subjects.map((x) => and(eq(p.subjectType, x.type), eq(p.subjectId, x.id))))!,\n gt(p.seq, afterSeq),\n ...(page.until === undefined ? [] : [lte(p.createdAt, page.until)]),\n ],\n },\n page.limit,\n )\n },\n }\n}\n","import { EVT_PRODUCT_VIEWED, type NymbalEvent } from '@nymbalhq/types'\n\n/** The record an event is about: what `events.subject_type` and `events.subject_id` hold. */\nexport interface EventSubject {\n type: string\n id: string\n}\n\nfunction text(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined\n}\n\nfunction nestedId(value: unknown): string | undefined {\n return value !== null && typeof value === 'object'\n ? text((value as { id?: unknown }).id)\n : undefined\n}\n\n/**\n * Whose event this is, by its type's prefix and the payload path that names the record; null when the type names no\n * record or the payload lacks its id. Migration 0012's backfill mirrors this, rule for rule.\n */\nexport function subjectOf(\n envelope: Pick<NymbalEvent<unknown>, 'type' | 'payload'>,\n): EventSubject | null {\n const payload = (envelope.payload ?? {}) as Record<string, unknown>\n const type = envelope.type\n let subject: EventSubject['type'] | undefined\n let id: string | undefined\n // A shopper's view is no change to the product, so it is no row of the product's history.\n if (type === EVT_PRODUCT_VIEWED) return null\n if (type.startsWith('product.')) {\n subject = 'product'\n id = nestedId(payload['product']) ?? text(payload['productId'])\n } else if (type.startsWith('order.') || type.startsWith('payment.')) {\n subject = 'order'\n id = nestedId(payload['order']) ?? text(payload['orderId'])\n } else if (type.startsWith('customer.')) {\n subject = 'customer'\n id = text(payload['customerId'])\n } else if (type.startsWith('inventory.')) {\n subject = 'variant'\n id = text(payload['variantId'])\n }\n return subject === undefined || id === undefined ? null : { type: subject, id }\n}\n","import { and, asc, eq, gt, isNull, lt, lte, sql } from 'drizzle-orm'\nimport type { Cart, CartItem } from '@nymbalhq/types'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport { fromTimestamp, parseJson } from './json.js'\n\n/** What makes a cart due an abandonment notice at `at`: live, holding items, unwritten since `cutoff`, not yet\n * notified in this inactivity period. */\nexport interface AbandonedWindow {\n cutoff: Date\n at: Date\n}\n\nexport interface AbandonedCart {\n token: string\n /** The cart's last write. */\n lastActivityAt: string\n}\n\nexport interface CartRepository extends StoreRepository {\n findByToken(tx: ReadTx, token: string): Promise<Cart | null>\n /** `findByToken`, holding the row for the rest of the transaction so concurrent commands on the cart queue behind\n * this one (Postgres `FOR UPDATE`; SQLite's `BEGIN IMMEDIATE` already holds the database). */\n lock(tx: Tx, token: string): Promise<Cart | null>\n /** Inserts the cart, or replaces an expired row on its token. A live row on the token is left as it is and\n * returned with `created: false`. */\n create(tx: Tx, cart: Cart): Promise<{ cart: Cart; created: boolean }>\n /** Writes the cart whole and starts a new inactivity period (clears the abandonment claim). */\n put(tx: Tx, cart: Cart): Promise<void>\n remove(tx: Tx, token: string): Promise<void>\n /** Empties the cart if it is still live at `at`, in one conditional write; false when there was no live row to\n * empty (expired, or deleted by a sweep or a merge). Starts a new inactivity period; the expiry stays as it was. */\n clearIfLive(tx: Tx, token: string, at: Date): Promise<boolean>\n /** Deletes every cart whose expiry is at or before `at`; returns how many. */\n deleteExpired(tx: Tx, at: Date): Promise<number>\n /** Up to `limit` tokens due a notice, in token order after `after`; claims nothing. */\n listAbandoned(\n tx: ReadTx,\n window: AbandonedWindow,\n page: { after: string | undefined; limit: number },\n ): Promise<string[]>\n /** Marks the cart notified if it is still due a notice; null when it is not (another sweeper claimed it, or a\n * write, expiry or delete came first). */\n claimAbandoned(tx: Tx, token: string, window: AbandonedWindow): Promise<AbandonedCart | null>\n}\n\nfunction rowToCart(store: 'sqlite' | 'postgres', row: Record<string, unknown>): Cart {\n return {\n token: String(row.token),\n customerId: (row.customerId as string | null) ?? null,\n items: parseJson<CartItem[]>(store, row.items, []),\n subtotalMinor: Number(row.subtotalMinor),\n currency: String(row.currency),\n expiresAt: fromTimestamp(row.expiresAt),\n createdAt: fromTimestamp(row.createdAt),\n updatedAt: fromTimestamp(row.updatedAt),\n }\n}\n\nfunction sqliteValues(cart: Cart) {\n return {\n token: cart.token,\n customerId: cart.customerId,\n currency: cart.currency,\n items: JSON.stringify(cart.items),\n lineCount: cart.items.length,\n subtotalMinor: cart.subtotalMinor,\n expiresAt: cart.expiresAt,\n createdAt: cart.createdAt,\n updatedAt: cart.updatedAt,\n abandonedNotifiedAt: null,\n }\n}\n\nfunction postgresValues(cart: Cart) {\n return {\n token: cart.token,\n customerId: cart.customerId,\n currency: cart.currency,\n items: cart.items,\n lineCount: cart.items.length,\n subtotalMinor: cart.subtotalMinor,\n expiresAt: new Date(cart.expiresAt),\n createdAt: new Date(cart.createdAt),\n updatedAt: new Date(cart.updatedAt),\n abandonedNotifiedAt: null,\n }\n}\n\n/** Every column but the key, taken from the row being inserted (`excluded` in both dialects' upsert). */\nconst fromExcluded = {\n customerId: sql`excluded.customer_id`,\n currency: sql`excluded.currency`,\n items: sql`excluded.items`,\n lineCount: sql`excluded.line_count`,\n subtotalMinor: sql`excluded.subtotal_minor`,\n expiresAt: sql`excluded.expires_at`,\n createdAt: sql`excluded.created_at`,\n updatedAt: sql`excluded.updated_at`,\n abandonedNotifiedAt: sql`excluded.abandoned_notified_at`,\n}\n\nfunction sqliteDue(window: AbandonedWindow) {\n const t = sqliteSchema.carts\n return and(\n isNull(t.abandonedNotifiedAt),\n gt(t.lineCount, 0),\n lt(t.updatedAt, window.cutoff.toISOString()),\n gt(t.expiresAt, window.at.toISOString()),\n )\n}\n\nfunction postgresDue(window: AbandonedWindow) {\n const t = postgresSchema.carts\n return and(\n isNull(t.abandonedNotifiedAt),\n gt(t.lineCount, 0),\n lt(t.updatedAt, window.cutoff),\n gt(t.expiresAt, window.at),\n )\n}\n\nexport function createCartRepository(store: CommandStore): CartRepository {\n async function findByToken(tx: ReadTx, token: string): Promise<Cart | null> {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .select()\n .from(sqliteSchema.carts)\n .where(eq(sqliteSchema.carts.token, token))\n .get()\n return row ? rowToCart('sqlite', row as Record<string, unknown>) : null\n }\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.carts)\n .where(eq(postgresSchema.carts.token, token))\n return row ? rowToCart('postgres', row as Record<string, unknown>) : null\n }\n\n async function lock(tx: Tx, token: string): Promise<Cart | null> {\n if (tx.kind === 'sqlite') return findByToken(tx, token)\n const [row] = await postgresDb(tx)\n .select()\n .from(postgresSchema.carts)\n .where(eq(postgresSchema.carts.token, token))\n .for('update')\n return row ? rowToCart('postgres', row as Record<string, unknown>) : null\n }\n\n return {\n store,\n findByToken,\n lock,\n async create(tx, cart) {\n let inserted: Record<string, unknown> | undefined\n if (tx.kind === 'sqlite') {\n inserted = sqliteDb(tx)\n .insert(sqliteSchema.carts)\n .values(sqliteValues(cart))\n .onConflictDoUpdate({\n target: sqliteSchema.carts.token,\n set: fromExcluded,\n setWhere: lte(sqliteSchema.carts.expiresAt, sql`excluded.updated_at`),\n })\n .returning()\n .get() as Record<string, unknown> | undefined\n } else {\n // A live row on the token makes the update a no-op, and `ON CONFLICT` waits for an insert in flight, so the\n // row read below is committed.\n ;[inserted] = await postgresDb(tx)\n .insert(postgresSchema.carts)\n .values(postgresValues(cart))\n .onConflictDoUpdate({\n target: postgresSchema.carts.token,\n set: fromExcluded,\n setWhere: lte(postgresSchema.carts.expiresAt, sql`excluded.updated_at`),\n })\n .returning()\n }\n if (inserted !== undefined) return { cart: rowToCart(tx.kind, inserted), created: true }\n const live = await lock(tx, cart.token)\n if (live === null) throw new Error(`cart ${cart.token} vanished while it was being created`)\n return { cart: live, created: false }\n },\n async put(tx, cart) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(sqliteSchema.carts)\n .values(sqliteValues(cart))\n .onConflictDoUpdate({ target: sqliteSchema.carts.token, set: fromExcluded })\n .run()\n return\n }\n await postgresDb(tx)\n .insert(postgresSchema.carts)\n .values(postgresValues(cart))\n .onConflictDoUpdate({ target: postgresSchema.carts.token, set: fromExcluded })\n },\n async remove(tx, token) {\n if (tx.kind === 'sqlite') {\n sqliteDb(tx).delete(sqliteSchema.carts).where(eq(sqliteSchema.carts.token, token)).run()\n return\n }\n await postgresDb(tx).delete(postgresSchema.carts).where(eq(postgresSchema.carts.token, token))\n },\n async clearIfLive(tx, token, at) {\n if (tx.kind === 'sqlite') {\n const t = sqliteSchema.carts\n const result = sqliteDb(tx)\n .update(t)\n .set({\n items: '[]',\n lineCount: 0,\n subtotalMinor: 0,\n updatedAt: at.toISOString(),\n abandonedNotifiedAt: null,\n })\n .where(and(eq(t.token, token), gt(t.expiresAt, at.toISOString())))\n .run()\n return result.changes > 0\n }\n // Under READ COMMITTED the update waits for a concurrent delete or write on the row and re-checks the condition\n // against what that one committed, so a row swept in between is skipped rather than reported missing.\n const t = postgresSchema.carts\n const rows = await postgresDb(tx)\n .update(t)\n .set({\n items: [],\n lineCount: 0,\n subtotalMinor: 0,\n updatedAt: at,\n abandonedNotifiedAt: null,\n })\n .where(and(eq(t.token, token), gt(t.expiresAt, at)))\n .returning({ token: t.token })\n return rows.length > 0\n },\n async deleteExpired(tx, at) {\n if (tx.kind === 'sqlite') {\n const result = sqliteDb(tx)\n .delete(sqliteSchema.carts)\n .where(lte(sqliteSchema.carts.expiresAt, at.toISOString()))\n .run()\n return result.changes\n }\n const rows = await postgresDb(tx)\n .delete(postgresSchema.carts)\n .where(lte(postgresSchema.carts.expiresAt, at))\n .returning({ token: postgresSchema.carts.token })\n return rows.length\n },\n async listAbandoned(tx, window, page) {\n if (tx.kind === 'sqlite') {\n const t = sqliteSchema.carts\n const rows = sqliteDb(tx)\n .select({ token: t.token })\n .from(t)\n .where(\n and(sqliteDue(window), page.after === undefined ? undefined : gt(t.token, page.after)),\n )\n .orderBy(asc(t.token))\n .limit(page.limit)\n .all()\n return rows.map((r) => r.token)\n }\n const t = postgresSchema.carts\n const rows = await postgresDb(tx)\n .select({ token: t.token })\n .from(t)\n .where(\n and(postgresDue(window), page.after === undefined ? undefined : gt(t.token, page.after)),\n )\n .orderBy(asc(t.token))\n .limit(page.limit)\n return rows.map((r) => r.token)\n },\n async claimAbandoned(tx, token, window) {\n if (tx.kind === 'sqlite') {\n const t = sqliteSchema.carts\n const row = sqliteDb(tx)\n .update(t)\n .set({ abandonedNotifiedAt: window.at.toISOString() })\n .where(and(eq(t.token, token), sqliteDue(window)))\n .returning({ token: t.token, updatedAt: t.updatedAt })\n .get()\n return row ? { token: row.token, lastActivityAt: fromTimestamp(row.updatedAt) } : null\n }\n // Under READ COMMITTED the update waits for a concurrent claim or write on the row and re-checks the condition\n // against what that one committed, so of two sweepers only one gets the row back.\n const t = postgresSchema.carts\n const [row] = await postgresDb(tx)\n .update(t)\n .set({ abandonedNotifiedAt: window.at })\n .where(and(eq(t.token, token), postgresDue(window)))\n .returning({ token: t.token, updatedAt: t.updatedAt })\n return row ? { token: row.token, lastActivityAt: fromTimestamp(row.updatedAt) } : null\n },\n }\n}\n","import { and, eq, inArray, sql } from 'drizzle-orm'\nimport type { AlertKind, AlertStatus } from '@nymbalhq/types'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\n\n/** A row of `alert_subscriptions`: one address's alert of one kind on one variant. */\nexport interface AlertSubscription {\n id: string\n /** Trimmed and lower-cased. */\n email: string\n kind: AlertKind\n variantId: string\n productId: string\n status: AlertStatus\n confirmToken: string\n unsubscribeToken: string\n /** The storefront origin its links point at. */\n origin: string\n baselinePriceMinor: number | null\n createdAt: Date\n updatedAt: Date\n confirmedAt: Date | null\n}\n\n/** A subscribe request: a new row's values, of which a row already there takes only what its status allows. */\nexport interface AlertSubscriptionRequest {\n id: string\n email: string\n kind: AlertKind\n variantId: string\n productId: string\n confirmToken: string\n unsubscribeToken: string\n origin: string\n /** A price-drop row's price at subscribe time; null for a back-in-stock row. */\n baselinePriceMinor: number | null\n at: Date\n}\n\nexport interface AlertSubscriptionPatch {\n status: AlertStatus\n updatedAt: Date\n confirmedAt?: Date\n /** The price a price-drop row was last told. */\n baselinePriceMinor?: number\n}\n\nexport interface AlertSubscriptionRepository extends StoreRepository {\n /**\n * One write on the unique (email, variant, kind): a new row is `pending`; a `pending` row takes the request's origin;\n * an `unsubscribed` or `fired` row returns to `pending` with the request's origin, confirm token and baseline (its\n * unsubscribe token is kept); an `active` row only has `updated_at` touched. Answers the row after the write.\n */\n upsertPending(tx: Tx, request: AlertSubscriptionRequest): Promise<AlertSubscription>\n findById(tx: ReadTx, id: string): Promise<AlertSubscription | null>\n findByConfirmToken(tx: ReadTx, token: string): Promise<AlertSubscription | null>\n findByUnsubscribeToken(tx: ReadTx, token: string): Promise<AlertSubscription | null>\n listActive(tx: ReadTx, variantId: string, kind: AlertKind): Promise<AlertSubscription[]>\n /** Applies `patch` when the row's status is one of `from`; the row after, or null when nothing changed. */\n update(\n tx: Tx,\n id: string,\n patch: AlertSubscriptionPatch,\n from: readonly AlertStatus[],\n ): Promise<AlertSubscription | null>\n}\n\ntype SqliteRow = typeof sqliteSchema.alertSubscriptions.$inferSelect\ntype PostgresRow = typeof postgresSchema.alertSubscriptions.$inferSelect\n\nfunction fromSqlite(row: SqliteRow): AlertSubscription {\n return {\n ...row,\n kind: row.kind as AlertKind,\n status: row.status as AlertStatus,\n createdAt: new Date(row.createdAt),\n updatedAt: new Date(row.updatedAt),\n confirmedAt: row.confirmedAt === null ? null : new Date(row.confirmedAt),\n }\n}\n\nfunction fromPostgres(row: PostgresRow): AlertSubscription {\n return { ...row, kind: row.kind as AlertKind, status: row.status as AlertStatus }\n}\n\nexport function createAlertSubscriptionRepository(\n store: CommandStore,\n): AlertSubscriptionRepository {\n const s = sqliteSchema.alertSubscriptions\n const p = postgresSchema.alertSubscriptions\n\n async function findOne(\n tx: ReadTx,\n where: (t: typeof s | typeof p) => ReturnType<typeof eq>,\n ): Promise<AlertSubscription | null> {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx).select().from(s).where(where(s)).get()\n return row === undefined ? null : fromSqlite(row)\n }\n const [row] = await postgresDb(tx).select().from(p).where(where(p)).limit(1)\n return row === undefined ? null : fromPostgres(row)\n }\n\n return {\n store,\n async upsertPending(tx, r) {\n const keep = (t: typeof s | typeof p) => sql`${t.status} = 'active'`\n const reissue = (t: typeof s | typeof p) => sql`${t.status} IN ('unsubscribed', 'fired')`\n const set = (t: typeof s | typeof p) => ({\n status: sql`CASE WHEN ${keep(t)} THEN ${t.status} ELSE 'pending' END`,\n origin: sql`CASE WHEN ${keep(t)} THEN ${t.origin} ELSE excluded.origin END`,\n confirmToken: sql`CASE WHEN ${reissue(t)} THEN excluded.confirm_token ELSE ${t.confirmToken} END`,\n baselinePriceMinor: sql`CASE WHEN ${reissue(t)} THEN excluded.baseline_price_minor ELSE ${t.baselinePriceMinor} END`,\n confirmedAt: sql`CASE WHEN ${keep(t)} THEN ${t.confirmedAt} ELSE NULL END`,\n updatedAt: sql`excluded.updated_at`,\n })\n const values = {\n id: r.id,\n email: r.email,\n kind: r.kind,\n variantId: r.variantId,\n productId: r.productId,\n status: 'pending' as const,\n confirmToken: r.confirmToken,\n unsubscribeToken: r.unsubscribeToken,\n origin: r.origin,\n baselinePriceMinor: r.baselinePriceMinor,\n confirmedAt: null,\n }\n if (tx.kind === 'sqlite') {\n const at = r.at.toISOString()\n const row = sqliteDb(tx)\n .insert(s)\n .values({ ...values, createdAt: at, updatedAt: at })\n .onConflictDoUpdate({ target: [s.email, s.variantId, s.kind], set: set(s) })\n .returning()\n .get()\n return fromSqlite(row)\n }\n const [row] = await postgresDb(tx)\n .insert(p)\n .values({ ...values, createdAt: r.at, updatedAt: r.at })\n .onConflictDoUpdate({ target: [p.email, p.variantId, p.kind], set: set(p) })\n .returning()\n return fromPostgres(row!)\n },\n findById: (tx, id) => findOne(tx, (t) => eq(t.id, id)),\n findByConfirmToken: (tx, token) => findOne(tx, (t) => eq(t.confirmToken, token)),\n findByUnsubscribeToken: (tx, token) => findOne(tx, (t) => eq(t.unsubscribeToken, token)),\n async listActive(tx, variantId, kind) {\n if (tx.kind === 'sqlite') {\n return sqliteDb(tx)\n .select()\n .from(s)\n .where(and(eq(s.variantId, variantId), eq(s.kind, kind), eq(s.status, 'active')))\n .orderBy(s.id)\n .all()\n .map(fromSqlite)\n }\n const rows = await postgresDb(tx)\n .select()\n .from(p)\n .where(and(eq(p.variantId, variantId), eq(p.kind, kind), eq(p.status, 'active')))\n .orderBy(p.id)\n return rows.map(fromPostgres)\n },\n async update(tx, id, patch, from) {\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx)\n .update(s)\n .set({\n status: patch.status,\n updatedAt: patch.updatedAt.toISOString(),\n ...(patch.confirmedAt !== undefined && {\n confirmedAt: patch.confirmedAt.toISOString(),\n }),\n ...(patch.baselinePriceMinor !== undefined && {\n baselinePriceMinor: patch.baselinePriceMinor,\n }),\n })\n .where(and(eq(s.id, id), inArray(s.status, [...from])))\n .returning()\n .get()\n return row === undefined ? null : fromSqlite(row)\n }\n const [row] = await postgresDb(tx)\n .update(p)\n .set({\n status: patch.status,\n updatedAt: patch.updatedAt,\n ...(patch.confirmedAt !== undefined && { confirmedAt: patch.confirmedAt }),\n ...(patch.baselinePriceMinor !== undefined && {\n baselinePriceMinor: patch.baselinePriceMinor,\n }),\n })\n .where(and(eq(p.id, id), inArray(p.status, [...from])))\n .returning()\n return row === undefined ? null : fromPostgres(row)\n },\n }\n}\n","import { eq } from 'drizzle-orm'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport { normaliseEmail } from '../email-address.js'\n\nexport type EmailSuppressionReason = 'hard_bounce' | 'complaint'\n\nexport interface EmailSuppressionInput {\n email: string\n reason: EmailSuppressionReason\n /** The feedback event that suppresses the address. */\n eventId: string\n at: Date\n}\n\n/** Addresses that hard-bounced or complained. Each method normalises the address it is given. */\nexport interface EmailSuppressionRepository extends StoreRepository {\n /** True when this call suppressed the address; false when it already was, whose first reason stays. */\n suppress(tx: Tx, input: EmailSuppressionInput): Promise<boolean>\n isSuppressed(tx: ReadTx, email: string): Promise<boolean>\n}\n\nexport function createEmailSuppressionRepository(store: CommandStore): EmailSuppressionRepository {\n const s = sqliteSchema.emailSuppressions\n const p = postgresSchema.emailSuppressions\n return {\n store,\n async suppress(tx, { email, reason, eventId, at }) {\n const values = { email: normaliseEmail(email), reason, eventId }\n if (tx.kind === 'sqlite') {\n const result = sqliteDb(tx)\n .insert(s)\n .values({ ...values, createdAt: at.toISOString() })\n .onConflictDoNothing()\n .run()\n return result.changes > 0\n }\n const result = await postgresDb(tx)\n .insert(p)\n .values({ ...values, createdAt: at })\n .onConflictDoNothing()\n return (result.rowCount ?? 0) > 0\n },\n async isSuppressed(tx, email) {\n const key = normaliseEmail(email)\n if (tx.kind === 'sqlite') {\n const row = sqliteDb(tx).select({ email: s.email }).from(s).where(eq(s.email, key)).get()\n return row !== undefined\n }\n const rows = await postgresDb(tx)\n .select({ email: p.email })\n .from(p)\n .where(eq(p.email, key))\n .limit(1)\n return rows.length > 0\n },\n }\n}\n","import { eq } from 'drizzle-orm'\nimport { normaliseTrackingNumber } from '@nymbalhq/types'\nimport {\n postgresDb,\n sqliteDb,\n type CommandStore,\n type ReadTx,\n type StoreRepository,\n type Tx,\n} from '../db/command-store.js'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\n\nexport interface OrderShipmentInput {\n orderId: string\n carrier: string\n trackingNumber: string\n at: Date\n}\n\n/** The parcel each shipped order went out in. Each method normalises the tracking number it is given. */\nexport interface OrderShipmentRepository extends StoreRepository {\n record(tx: Tx, input: OrderShipmentInput): Promise<void>\n /** The ids of every order shipped under the number, in no particular order. */\n ordersByTrackingNumber(tx: ReadTx, trackingNumber: string): Promise<string[]>\n}\n\nexport function createOrderShipmentRepository(store: CommandStore): OrderShipmentRepository {\n const s = sqliteSchema.orderShipments\n const p = postgresSchema.orderShipments\n return {\n store,\n async record(tx, { orderId, carrier, trackingNumber, at }) {\n const values = { orderId, carrier, trackingNumber: normaliseTrackingNumber(trackingNumber) }\n if (tx.kind === 'sqlite') {\n sqliteDb(tx)\n .insert(s)\n .values({ ...values, createdAt: at.toISOString() })\n .run()\n return\n }\n await postgresDb(tx)\n .insert(p)\n .values({ ...values, createdAt: at })\n },\n async ordersByTrackingNumber(tx, trackingNumber) {\n const key = normaliseTrackingNumber(trackingNumber)\n if (tx.kind === 'sqlite') {\n return sqliteDb(tx)\n .select({ orderId: s.orderId })\n .from(s)\n .where(eq(s.trackingNumber, key))\n .all()\n .map((r) => r.orderId)\n }\n const rows = await postgresDb(tx)\n .select({ orderId: p.orderId })\n .from(p)\n .where(eq(p.trackingNumber, key))\n return rows.map((r) => r.orderId)\n },\n }\n}\n","import type { DocumentStoreAdapter } from '@nymbalhq/types'\nimport type { CommandStore } from '../db/command-store.js'\nimport { createProductRepository, type ProductRepository } from './product.js'\nimport { createVariantRepository, type VariantRepository } from './variant.js'\nimport { createCategoryRepository, type CategoryRepository } from './category.js'\nimport {\n createProductCategoryRepository,\n type ProductCategoryRepository,\n} from './product-category.js'\nimport { createCustomerRepository, type CustomerRepository } from './customer.js'\nimport { createRefreshTokenRepository, type RefreshTokenRepository } from './refresh-token.js'\nimport { createOrderRepository, type OrderRepository } from './order.js'\nimport { createOrderHistoryRepository, type OrderHistoryRepository } from './order-history.js'\nimport { createOrderRefundRepository, type OrderRefundRepository } from './order-refund.js'\nimport { createOrderSequenceRepository, type OrderSequenceRepository } from './order-sequence.js'\nimport {\n createOrderAccessKeyRepository,\n type OrderAccessKeyRepository,\n} from './order-access-key.js'\nimport {\n createInventoryReservationRepository,\n type InventoryReservationRepository,\n} from './inventory-reservation.js'\nimport {\n createStockAdjustmentRepository,\n type StockAdjustmentRepository,\n} from './stock-adjustment.js'\nimport { createReviewRepository, type ReviewRepository } from './review.js'\nimport { createProcessedEventRepository, type ProcessedEventRepository } from './processed-event.js'\nimport { createEventLogRepository, type EventLogRepository } from './event-log.js'\nimport { createCartRepository, type CartRepository } from './cart.js'\nimport { createSettingsRepository, type SettingsRepository } from './settings.js'\nimport { createAuditEntryRepository, type AuditEntryRepository } from './audit-entry.js'\nimport {\n createAlertSubscriptionRepository,\n type AlertSubscriptionRepository,\n} from './alert-subscription.js'\nimport {\n createEmailSuppressionRepository,\n type EmailSuppressionRepository,\n} from './email-suppression.js'\nimport { createOrderShipmentRepository, type OrderShipmentRepository } from './order-shipment.js'\n\nexport * from './product.js'\nexport * from './variant.js'\nexport * from './category.js'\nexport * from './product-category.js'\nexport * from './customer.js'\nexport * from './refresh-token.js'\nexport * from './order.js'\nexport * from './order-history.js'\nexport * from './order-refund.js'\nexport * from './order-sequence.js'\nexport * from './order-access-key.js'\nexport * from './inventory-reservation.js'\nexport * from './stock-adjustment.js'\nexport * from './review.js'\nexport * from './processed-event.js'\nexport * from './event-log.js'\nexport * from './cart.js'\nexport * from './settings.js'\nexport * from './audit-entry.js'\nexport * from './alert-subscription.js'\nexport * from './email-suppression.js'\nexport * from './order-shipment.js'\nexport * from './page.js'\n\nexport interface Repositories {\n product: ProductRepository\n variant: VariantRepository\n category: CategoryRepository\n productCategory: ProductCategoryRepository\n customer: CustomerRepository\n refreshToken: RefreshTokenRepository\n order: OrderRepository\n orderHistory: OrderHistoryRepository\n orderRefund: OrderRefundRepository\n orderSequence: OrderSequenceRepository\n orderAccessKey: OrderAccessKeyRepository\n inventoryReservation: InventoryReservationRepository\n stockAdjustment: StockAdjustmentRepository\n review: ReviewRepository\n processedEvent: ProcessedEventRepository\n eventLog: EventLogRepository\n cart: CartRepository\n settings: SettingsRepository\n auditEntry: AuditEntryRepository\n alertSubscription: AlertSubscriptionRepository\n emailSuppression: EmailSuppressionRepository\n orderShipment: OrderShipmentRepository\n}\n\nexport function buildRepositories(\n commandStore: CommandStore,\n // Every repository is command-store backed; the parameter stays so existing callers keep compiling.\n _documentStore: DocumentStoreAdapter,\n): Repositories {\n return {\n product: createProductRepository(commandStore),\n variant: createVariantRepository(commandStore),\n category: createCategoryRepository(commandStore),\n productCategory: createProductCategoryRepository(commandStore),\n customer: createCustomerRepository(commandStore),\n refreshToken: createRefreshTokenRepository(commandStore),\n order: createOrderRepository(commandStore),\n orderHistory: createOrderHistoryRepository(commandStore),\n orderRefund: createOrderRefundRepository(commandStore),\n orderSequence: createOrderSequenceRepository(commandStore),\n orderAccessKey: createOrderAccessKeyRepository(commandStore),\n inventoryReservation: createInventoryReservationRepository(commandStore),\n stockAdjustment: createStockAdjustmentRepository(commandStore),\n review: createReviewRepository(commandStore),\n processedEvent: createProcessedEventRepository(commandStore),\n eventLog: createEventLogRepository(commandStore),\n cart: createCartRepository(commandStore),\n settings: createSettingsRepository(commandStore),\n auditEntry: createAuditEntryRepository(commandStore),\n alertSubscription: createAlertSubscriptionRepository(commandStore),\n emailSuppression: createEmailSuppressionRepository(commandStore),\n orderShipment: createOrderShipmentRepository(commandStore),\n }\n}\n","import { v7 as uuidv7 } from 'uuid'\nimport type { NymbalEvent, NymbalEnvironment } from '@nymbalhq/types'\n\nexport interface EventBuilderContext {\n storeId: string\n environment: NymbalEnvironment\n version: string\n source?: string\n}\n\nexport interface MakeEventOptions {\n source?: string\n correlationId?: string\n timestamp?: Date\n}\n\nexport function createEventBuilder(ctx: EventBuilderContext) {\n return function makeEvent<T>(\n type: string,\n payload: T,\n options: MakeEventOptions = {},\n ): NymbalEvent<T> {\n const id = uuidv7()\n return {\n id,\n type,\n timestamp: (options.timestamp ?? new Date()).toISOString(),\n source: options.source ?? ctx.source ?? 'nymbal-platform',\n correlationId: options.correlationId ?? id,\n payload,\n metadata: {\n storeId: ctx.storeId,\n environment: ctx.environment,\n version: ctx.version,\n },\n }\n }\n}\n","import type { EventBusAdapter, NymbalEvent, NymbalEventMap, NymbalEventType } from '@nymbalhq/types'\nimport { afterCommit, type CommandStore } from '../db/command-store.js'\nimport type { EventLogRepository } from '../repositories/event-log.js'\nimport { createEventBuilder, type EventBuilderContext, type MakeEventOptions } from './builder.js'\nimport { currentCorrelationId } from './correlation.js'\nimport type { Relay } from './relay.js'\n\nexport interface PublishOptions extends MakeEventOptions {}\n\nexport interface EventPublisher {\n publish<E extends NymbalEventType>(\n type: E,\n payload: NymbalEventMap[E],\n options?: PublishOptions,\n ): Promise<NymbalEvent<NymbalEventMap[E]>>\n publishMany(\n events: Array<\n {\n [E in NymbalEventType]: {\n type: E\n payload: NymbalEventMap[E]\n options?: PublishOptions\n }\n }[NymbalEventType]\n >,\n ): Promise<void>\n /**\n * Events of types the kernel does not declare (an adapter's own, already checked by the caller), with the same\n * append and drain as `publish`.\n */\n publishUntyped(\n events: ReadonlyArray<{ type: string; payload: unknown }>,\n options?: PublishOptions,\n ): Promise<NymbalEvent<unknown>[]>\n correlated(correlationId: string): EventPublisher\n}\n\nexport interface CreatePublisherOptions {\n eventBus: EventBusAdapter\n builderContext: EventBuilderContext\n /** Events are appended to `eventLog` on this store and reach the bus only through `relay`. */\n store: CommandStore\n eventLog: EventLogRepository\n relay: Relay\n correlationId?: string\n}\n\nexport function createEventPublisher(opts: CreatePublisherOptions): EventPublisher {\n const makeEvent = createEventBuilder(opts.builderContext)\n const { store, eventLog, relay } = opts\n\n /**\n * Appends in the open transaction (same COMMIT, gone on rollback) or in one of its own, and drains the relay once\n * the outermost transaction has committed; `afterCommit` holds one drain however many publishes the transaction\n * made.\n */\n async function append(events: NymbalEvent<unknown>[]): Promise<void> {\n if (events.length === 0) return\n await store.transaction(async (tx) => {\n await eventLog.append(tx, events)\n await afterCommit(relay.drain)\n })\n }\n\n function build<T>(type: string, payload: T, options: PublishOptions = {}): NymbalEvent<T> {\n // An explicit id, then a correlated() publisher's, then the scope's; with none, the event is its own id.\n const correlationId = options.correlationId ?? opts.correlationId ?? currentCorrelationId()\n return makeEvent(type, payload, {\n ...options,\n ...(correlationId !== undefined && { correlationId }),\n })\n }\n\n return {\n async publish(type, payload, options) {\n const event = build(type, payload, options ?? {})\n await append([event])\n return event\n },\n async publishMany(events) {\n await append(events.map((e) => build(e.type, e.payload, e.options ?? {})))\n },\n async publishUntyped(events, options) {\n const built = events.map((e) => build(e.type, e.payload, options ?? {}))\n await append(built)\n return built\n },\n correlated(correlationId) {\n return createEventPublisher({ ...opts, correlationId })\n },\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport {\n HEALTH_CHECK_TIMEOUT_MS,\n type EventBusAdapter,\n type EventHandler,\n type Logger,\n} from '@nymbalhq/types'\nimport type { CommandStore } from '../db/command-store.js'\nimport type { EventLogRepository, LoggedEvent } from '../repositories/event-log.js'\nimport { outsideCorrelation } from './correlation.js'\nimport { outsideActor } from '../audit/actor.js'\nimport { outsideCommand } from '../audit/audit.js'\nimport type { OutageReport } from './outage.js'\n\n/** Hands committed events from the log to the bus. */\nexport interface Relay {\n /** Delivers every undelivered, non-dead event in `seq` order. Never rejects. */\n drain(): Promise<void>\n /** Drains on an interval (the timer does not keep the process alive). */\n start(): void\n /** Stops the interval and starts no new pass; resolves when the pass in flight, if any, has finished, so the\n * store can be closed without cutting a delivery off between the handler and its bookkeeping. */\n stop(): Promise<void>\n /**\n * `handler`, run as part of a delivery: a drain it asks for (by running a command) returns at once instead of\n * waiting on the pass that waits on it. The app wraps every subscribed handler in it, so this holds whether the bus\n * calls the handler inside `publish` or from a consumer loop of its own.\n */\n asDelivery(handler: EventHandler): EventHandler\n}\n\nexport interface CreateRelayOptions {\n store: CommandStore\n eventLog: EventLogRepository\n eventBus: EventBusAdapter\n logger: Logger\n /** Failed bus publishes after which an event is dead and never handed to the bus again. */\n maxAttempts?: number\n intervalMs?: number\n /** The wait before the first retry of a failed event (default `intervalMs`); each later wait doubles it. */\n retryDelayMs?: number\n /** The clock failures and retry waits are read from. */\n now?: () => Date\n /**\n * Asked once a pass, at its first failed delivery: a failure during an outage is not counted toward `maxAttempts`.\n * Absent, no failure is an outage.\n */\n outage?: () => Promise<OutageReport>\n /** How long the relay waits on `outage` before taking the pass as an outage (default the health check bound + 1 s). */\n outageTimeoutMs?: number\n}\n\nconst PAGE_SIZE = 100\nconst NO_OUTAGE: OutageReport = { outage: false, down: [] }\n\ninterface Deferred {\n promise: Promise<void>\n resolve(): void\n}\n\nfunction deferred(): Deferred {\n let resolve!: () => void\n const promise = new Promise<void>((r) => {\n resolve = r\n })\n return { promise, resolve }\n}\n\n/** The subscriptions a bus's `handler_failed` rejection names, for the relay's log lines. */\nfunction failedOf(err: unknown): { failed?: unknown[] } {\n const failed = (err as { context?: { failed?: unknown } } | null)?.context?.failed\n return Array.isArray(failed) ? { failed } : {}\n}\n\nexport function createRelay(opts: CreateRelayOptions): Relay {\n const { store, eventLog } = opts\n const maxAttempts = opts.maxAttempts ?? 5\n const intervalMs = opts.intervalMs ?? 10_000\n const retryDelayMs = opts.retryDelayMs ?? intervalMs\n const now = opts.now ?? (() => new Date())\n const outageTimeoutMs = opts.outageTimeoutMs ?? HEALTH_CHECK_TIMEOUT_MS + 1000\n const logger = opts.logger.child({ component: 'event-relay' })\n // Set around each bus publish and each subscribed handler: a drain asked for by a subscriber (one that ran a\n // command) must not wait for the drain that is delivering to it.\n const delivering = new AsyncLocalStorage<true>()\n\n let active = false\n // Resolved when `active` turns false, i.e. after the last chained follow-up pass.\n let idle: Deferred | undefined\n let followUp: Deferred | undefined\n let timer: ReturnType<typeof setInterval> | undefined\n let stopped = false\n\n /** The probe's answer, bounded by the relay itself: a probe that throws or does not settle in time is an outage. */\n async function probe(): Promise<OutageReport> {\n const ask = opts.outage\n if (ask === undefined) return NO_OUTAGE\n let bound: ReturnType<typeof setTimeout> | undefined\n const timedOut = new Promise<OutageReport>((resolve) => {\n bound = setTimeout(\n () =>\n resolve({\n outage: true,\n down: [{ name: 'probe', detail: `timed out after ${outageTimeoutMs} ms` }],\n }),\n outageTimeoutMs,\n )\n })\n try {\n return await Promise.race([Promise.resolve().then(ask), timedOut])\n } catch (err) {\n return {\n outage: true,\n down: [{ name: 'probe', detail: err instanceof Error ? err.message : String(err) }],\n }\n } finally {\n clearTimeout(bound)\n }\n }\n\n /** One probe for a whole pass, asked when it is first needed; an outage is logged once, naming every down subject. */\n function outageOfPass(): () => Promise<OutageReport> {\n let asked: Promise<OutageReport> | undefined\n return () =>\n (asked ??= probe().then((report) => {\n if (report.outage) {\n const named = report.down.map(({ name, detail }) => `${name} (${detail})`).join(', ')\n logger.warn({ down: report.down }, `outage: ${named}`)\n }\n return report\n }))\n }\n\n async function deliver(\n { event, attempts }: LoggedEvent,\n outage: () => Promise<OutageReport>,\n ): Promise<void> {\n try {\n // Looked up on every call: a wrapper installed on the bus instance after construction must see the event.\n await delivering.run(true, () => opts.eventBus.publish(event))\n } catch (err) {\n const at = now()\n if ((await outage()).outage) {\n // The same wait the next counted failure would get, so an outage neither ages the event nor grows its wait.\n const retryAt = new Date(at.getTime() + retryDelayMs * 2 ** attempts)\n await store.transaction((tx) => eventLog.recordOutage(tx, event.id, retryAt))\n logger.debug(\n { err, eventId: event.id, eventType: event.type, retryAt: retryAt.toISOString() },\n 'event delivery failed during an outage; not counted, tried again from retryAt',\n )\n return\n }\n const failures = attempts + 1\n // Backed off in the log, not in memory: every drain in between (each commit asks for one) and a restart see it.\n const retryAt = new Date(at.getTime() + retryDelayMs * 2 ** (failures - 1))\n await store.transaction((tx) =>\n eventLog.recordFailure(tx, event.id, at, maxAttempts, retryAt),\n )\n const context = {\n err,\n eventId: event.id,\n eventType: event.type,\n attempts: failures,\n ...failedOf(err),\n }\n if (failures >= maxAttempts) {\n logger.error(context, 'event delivery failed for the last time; the event is dead')\n } else {\n logger.warn(\n { ...context, retryAt: retryAt.toISOString() },\n 'event delivery failed; the event stays in the log and is tried again from retryAt',\n )\n }\n return\n }\n await store.transaction((tx) => eventLog.markDelivered(tx, [event.id], new Date()))\n }\n\n /** One pass over the log. The cursor only spans this pass: a row that commits behind it is left for the next\n * pass, which the committing transaction requests. */\n async function pass(): Promise<void> {\n try {\n let afterSeq = 0\n const outage = outageOfPass()\n for (;;) {\n if (stopped) return\n const page = await store.read((tx) =>\n eventLog.listUndelivered(tx, PAGE_SIZE, afterSeq, now()),\n )\n for (const logged of page) {\n if (stopped) return\n afterSeq = logged.seq\n await deliver(logged, outage)\n }\n if (page.length < PAGE_SIZE) return\n }\n } catch (err) {\n logger.error({ err }, 'event relay pass failed; undelivered events stay in the log')\n }\n }\n\n async function run(): Promise<void> {\n active = true\n try {\n await pass()\n } finally {\n const next = followUp\n followUp = undefined\n if (next === undefined) {\n active = false\n idle?.resolve()\n idle = undefined\n } else {\n // Still active: nothing can start a second pass alongside this one.\n void run().then(next.resolve)\n }\n }\n }\n\n function request(): Promise<void> {\n if (!active) {\n idle = deferred()\n // A pass delivers every operation's events, not only the requester's: its handlers run in no scope of the caller,\n // neither its correlation id nor its actor and command, so a handler's writes are never the caller's entry.\n return outsideCorrelation(() => outsideActor(() => outsideCommand(run)))\n }\n followUp ??= deferred()\n return followUp.promise\n }\n\n return {\n drain() {\n if (stopped) return Promise.resolve()\n const done = request()\n return delivering.getStore() === true ? Promise.resolve() : done\n },\n start() {\n if (timer !== undefined) return\n stopped = false\n timer = setInterval(() => void request(), intervalMs)\n timer.unref()\n },\n stop() {\n stopped = true\n if (timer !== undefined) clearInterval(timer)\n timer = undefined\n // A subscriber that stops the app would otherwise wait on the pass that is waiting on it.\n if (delivering.getStore() === true) return Promise.resolve()\n return idle?.promise ?? Promise.resolve()\n },\n asDelivery(handler) {\n return (event) => delivering.run(true, () => handler(event))\n },\n }\n}\n\n/**\n * The bus as subscribers see it: every handler runs as part of a relay delivery, so a command it runs does not wait\n * on the drain that is waiting on the handler, whether the bus calls it inside `publish` or from a consumer loop.\n */\nexport function deliveringBus(bus: EventBusAdapter, relay: Relay): EventBusAdapter {\n return {\n capabilities: () => bus.capabilities(),\n publish: (event) => bus.publish(event),\n publishBatch: (events) => bus.publishBatch(events),\n replay: (events) => bus.replay(events),\n subscribe: (pattern, handler, config) =>\n bus.subscribe(pattern, relay.asDelivery(handler), config),\n unsubscribe: (subscription) => bus.unsubscribe(subscription),\n close: () => bus.close(),\n }\n}\n","import type { EventHandler, Logger, NymbalEvent } from '@nymbalhq/types'\nimport type { ProcessedEventRepository } from '../repositories/processed-event.js'\n\nexport interface IdempotencyOptions {\n repo: ProcessedEventRepository\n logger?: Logger\n}\n\nexport function withIdempotency<T = unknown>(\n handlerName: string,\n handler: EventHandler<T>,\n { repo, logger }: IdempotencyOptions,\n): EventHandler<T> {\n return async (event: NymbalEvent<T>) => {\n const { store } = repo\n if (await store.read((tx) => repo.seen(tx, handlerName, event.id))) {\n logger?.debug(\n { handlerName, eventId: event.id, type: event.type },\n 'idempotency: skipping duplicate event',\n )\n return\n }\n await handler(event)\n await store.transaction((tx) => repo.markProcessed(tx, handlerName, event.id, new Date()))\n }\n}\n","import {\n EVT_CATEGORY_CREATED,\n EVT_CATEGORY_DELETED,\n EVT_CATEGORY_UPDATED,\n type CategoryCreatedV1Payload,\n type CategoryDeletedV1Payload,\n type CategoryUpdatedV1Payload,\n type DocumentStoreAdapter,\n type EventBusAdapter,\n type EventHandler,\n type Logger,\n} from '@nymbalhq/types'\nimport type { Repositories } from '../../repositories/index.js'\nimport { buildCategoryDoc, CATEGORIES } from '../../read-models/builders.js'\nimport { subscribeDerived, type DerivedHandler } from '../derived.js'\n\nexport interface CategoryProjectionDeps {\n documentStore: DocumentStoreAdapter\n logger: Logger\n storeId: string\n repos: Pick<Repositories, 'category'>\n}\n\nexport interface RegisterCategoryProjectionDeps extends CategoryProjectionDeps {\n eventBus: EventBusAdapter\n}\n\n/**\n * The `categories` documents, built from the category row read at handle time: a re-applied old delivery then writes\n * what a rebuild writes, not the payload it carried.\n */\nexport function categoryProjection(deps: CategoryProjectionDeps): DerivedHandler[] {\n const { documentStore, logger, storeId, repos } = deps\n\n const onUpsert: EventHandler<CategoryCreatedV1Payload | CategoryUpdatedV1Payload> = async (\n event,\n ) => {\n const { id, slug } = event.payload.category\n const category = await repos.category.store.read((tx) => repos.category.findById(tx, id))\n if (!category) {\n // The slug may since have gone to another category, whose document stays.\n const stored = await documentStore.get<{ id: string }>(CATEGORIES, slug)\n if (stored?.id === id) await documentStore.delete(CATEGORIES, slug)\n logger.debug({ slug, eventType: event.type }, 'category gone; projection deleted')\n return\n }\n await documentStore.put(CATEGORIES, category.slug, buildCategoryDoc(category, storeId))\n logger.debug({ slug: category.slug, eventType: event.type }, 'category projected')\n }\n\n const onDeleted: EventHandler<CategoryDeletedV1Payload> = async (event) => {\n await documentStore.delete(CATEGORIES, event.payload.slug)\n logger.debug({ slug: event.payload.slug }, 'category projection deleted')\n }\n\n return [\n {\n name: 'category-projection-upsert',\n types: [EVT_CATEGORY_CREATED, EVT_CATEGORY_UPDATED],\n handle: onUpsert as EventHandler,\n },\n {\n name: 'category-projection-delete',\n types: [EVT_CATEGORY_DELETED],\n handle: onDeleted as EventHandler,\n },\n ]\n}\n\nexport async function registerCategoryProjection(\n deps: RegisterCategoryProjectionDeps,\n): Promise<void> {\n await subscribeDerived(deps.eventBus, categoryProjection(deps))\n}\n","import {\n EVT_CATEGORY_CREATED,\n EVT_CATEGORY_DELETED,\n EVT_CATEGORY_UPDATED,\n EVT_PRODUCT_CREATED,\n EVT_PRODUCT_DELETED,\n EVT_PRODUCT_UPDATED,\n type CategoryCreatedV1Payload,\n type CategoryDeletedV1Payload,\n type CategoryUpdatedV1Payload,\n type DocumentStoreAdapter,\n type EventBusAdapter,\n type EventHandler,\n type Logger,\n type ProductCreatedV1Payload,\n type ProductDeletedV1Payload,\n type ProductUpdatedV1Payload,\n} from '@nymbalhq/types'\nimport type { Repositories } from '../../repositories/index.js'\nimport {\n buildProductDoc,\n productByCategoryKey,\n productWrites,\n PRODUCTS,\n PRODUCTS_BY_CATEGORY,\n type DenormalisedProduct,\n} from '../../read-models/builders.js'\nimport { loadProduct } from '../../read-models/sources.js'\nimport { subscribeDerived, type DerivedHandler } from '../derived.js'\n\nexport type { DenormalisedProduct } from '../../read-models/builders.js'\n\nexport interface ProductProjectionDeps {\n documentStore: DocumentStoreAdapter\n logger: Logger\n storeId: string\n currency: string\n repos: Pick<Repositories, 'product' | 'variant' | 'category' | 'productCategory'>\n}\n\nexport interface RegisterProductProjectionDeps extends ProductProjectionDeps {\n eventBus: EventBusAdapter\n}\n\nexport interface ProductReprojector {\n /** Rebuilds the product's documents from its rows as they are now; a product that is gone is left to its delete. */\n reproject(productId: string): Promise<void>\n /** Removes the product's documents, by slug. */\n remove(slug: string): Promise<void>\n}\n\n/**\n * Writes `products` and `products-by-category` from the product's rows, read at handle time, so any event about a\n * product, its stock or one of its categories leaves the documents a rebuild writes.\n */\nexport function productReprojector(deps: ProductProjectionDeps): ProductReprojector {\n const { documentStore, logger, storeId, currency, repos } = deps\n\n /** The category keys the stored document was filed under. */\n async function filedUnder(slug: string): Promise<string[]> {\n const existing = await documentStore.get<DenormalisedProduct>(PRODUCTS, slug)\n return (existing?.categories ?? []).map((c) => productByCategoryKey(c.slug, slug))\n }\n\n return {\n async reproject(productId) {\n const loaded = await repos.product.store.read((tx) => loadProduct(tx, repos, productId))\n if (!loaded) return\n const doc = buildProductDoc(loaded.snapshot, loaded.categories, { storeId, currency, logger })\n const writes = productWrites(doc)\n const kept = new Set(writes.map((w) => w.key))\n const stale = (await filedUnder(doc.slug)).filter((key) => !kept.has(key))\n for (const w of writes) await documentStore.put(w.collection, w.key, w.doc)\n for (const key of stale) await documentStore.delete(PRODUCTS_BY_CATEGORY, key)\n logger.debug({ slug: doc.slug }, 'product projected')\n },\n async remove(slug) {\n for (const key of await filedUnder(slug)) {\n await documentStore.delete(PRODUCTS_BY_CATEGORY, key)\n }\n await documentStore.delete(PRODUCTS, slug)\n logger.debug({ slug }, 'product projection deleted')\n },\n }\n}\n\nexport function productProjection(deps: ProductProjectionDeps): DerivedHandler[] {\n const products = productReprojector(deps)\n const { repos } = deps\n\n const onUpsert: EventHandler<ProductCreatedV1Payload | ProductUpdatedV1Payload> = (event) =>\n products.reproject(event.payload.product.id)\n\n const onDelete: EventHandler<ProductDeletedV1Payload> = (event) =>\n products.remove(event.payload.slug)\n\n // A category's name and slug are in its products' documents, and its slug in their category keys.\n const onCategory: EventHandler<\n CategoryCreatedV1Payload | CategoryUpdatedV1Payload | CategoryDeletedV1Payload\n > = async (event) => {\n const payload = event.payload\n const categoryId = 'category' in payload ? payload.category.id : payload.categoryId\n const productIds = await repos.productCategory.store.read((tx) =>\n repos.productCategory.listProductsForCategory(tx, categoryId),\n )\n for (const productId of productIds) await products.reproject(productId)\n }\n\n return [\n {\n name: 'product-projection-upsert',\n types: [EVT_PRODUCT_CREATED, EVT_PRODUCT_UPDATED],\n handle: onUpsert as EventHandler,\n },\n {\n name: 'product-projection-delete',\n types: [EVT_PRODUCT_DELETED],\n handle: onDelete as EventHandler,\n },\n {\n name: 'product-projection-category',\n types: [EVT_CATEGORY_CREATED, EVT_CATEGORY_UPDATED, EVT_CATEGORY_DELETED],\n handle: onCategory as EventHandler,\n },\n ]\n}\n\nexport async function registerProductProjection(\n deps: RegisterProductProjectionDeps,\n): Promise<void> {\n await subscribeDerived(deps.eventBus, productProjection(deps))\n}\n","import type { Category, Product, ProductSnapshot } from '@nymbalhq/types'\nimport type { ReadTx } from '../db/command-store.js'\nimport type { Repositories } from '../repositories/index.js'\nimport { buildOrderDoc, type OrderDoc } from './builders.js'\n\n// What the builders are given, read from the command store: the same reads for a live projection at handle time and\n// for a rebuild's pages.\n\ntype CatalogueRepos = Pick<Repositories, 'product' | 'variant' | 'category' | 'productCategory'>\n\n/** The product with its variants and category ids. The ids are sorted: the join table keeps no order of its own. */\nexport async function productSnapshot(\n tx: ReadTx,\n repos: Pick<Repositories, 'variant' | 'productCategory'>,\n product: Product,\n): Promise<ProductSnapshot> {\n const variants = await repos.variant.findByProduct(tx, product.id)\n const categoryIds = await repos.productCategory.listCategoriesForProduct(tx, product.id)\n return { ...product, variants, categoryIds: [...categoryIds].sort() }\n}\n\n/** The category rows of `ids` that exist, by id. */\nexport async function categoriesOf(\n tx: ReadTx,\n repos: Pick<Repositories, 'category'>,\n ids: readonly string[],\n): Promise<Map<string, Category>> {\n const found = new Map<string, Category>()\n for (const id of new Set(ids)) {\n const category = await repos.category.findById(tx, id)\n if (category) found.set(id, category)\n }\n return found\n}\n\n/** The product as its document is built from it, or null when it is gone. */\nexport async function loadProduct(\n tx: ReadTx,\n repos: CatalogueRepos,\n productId: string,\n): Promise<{ snapshot: ProductSnapshot; categories: Map<string, Category> } | null> {\n const product = await repos.product.findById(tx, productId)\n if (!product) return null\n const snapshot = await productSnapshot(tx, repos, product)\n return { snapshot, categories: await categoriesOf(tx, repos, snapshot.categoryIds) }\n}\n\n/** The order's document, or null when it is gone. */\nexport async function loadOrderDoc(\n tx: ReadTx,\n repos: Pick<Repositories, 'order' | 'orderHistory'>,\n orderId: string,\n): Promise<OrderDoc | null> {\n const order = await repos.order.findById(tx, orderId)\n if (!order) return null\n return buildOrderDoc(order, await repos.orderHistory.listByOrder(tx, order.id))\n}\n","import {\n EVT_ORDER_CANCELLED,\n EVT_ORDER_DELIVERED,\n EVT_ORDER_PAID,\n EVT_ORDER_PARTIALLY_REFUNDED,\n EVT_ORDER_PLACED,\n EVT_ORDER_REFUNDED,\n EVT_ORDER_SHIPPED,\n EVT_ORDER_STATUS_CHANGED,\n EVT_PAYMENT_FAILED,\n EVT_PAYMENT_INTENT_CREATED,\n EVT_PAYMENT_REFUNDED,\n type DocumentStoreAdapter,\n type EventBusAdapter,\n type EventHandler,\n type Logger,\n type OrderPlacedV1Payload,\n} from '@nymbalhq/types'\nimport type { OrderRepository } from '../../repositories/order.js'\nimport type { OrderHistoryRepository } from '../../repositories/order-history.js'\nimport { orderWrites } from '../../read-models/builders.js'\nimport { loadOrderDoc } from '../../read-models/sources.js'\nimport { subscribeDerived, type DerivedHandler } from '../derived.js'\n\nexport interface OrderProjectionDeps {\n documentStore: DocumentStoreAdapter\n logger: Logger\n orderRepo: OrderRepository\n orderHistoryRepo: OrderHistoryRepository\n}\n\nexport interface RegisterOrderProjectionDeps extends OrderProjectionDeps {\n eventBus: EventBusAdapter\n}\n\n/** `orders` and `orders-by-customer`, from the order and its history as they are at handle time. */\nexport function orderProjection(deps: OrderProjectionDeps): DerivedHandler[] {\n const { documentStore, logger, orderRepo, orderHistoryRepo } = deps\n const repos = { order: orderRepo, orderHistory: orderHistoryRepo }\n\n async function reproject(orderId: string): Promise<void> {\n const doc = await orderRepo.store.read((tx) => loadOrderDoc(tx, repos, orderId))\n if (!doc) return\n for (const w of orderWrites(doc)) await documentStore.put(w.collection, w.key, w.doc)\n logger.debug({ orderNumber: doc.orderNumber, status: doc.status }, 'order projected')\n }\n\n const onPlaced: EventHandler<OrderPlacedV1Payload> = (event) => reproject(event.payload.order.id)\n\n const onStatusChange: EventHandler<{ orderId: string }> = (event) =>\n reproject(event.payload.orderId)\n\n return [\n {\n name: 'order-projection-placed',\n types: [EVT_ORDER_PLACED],\n handle: onPlaced as EventHandler,\n },\n {\n name: 'order-projection-status',\n types: [\n EVT_ORDER_PAID,\n EVT_ORDER_SHIPPED,\n EVT_ORDER_DELIVERED,\n EVT_ORDER_CANCELLED,\n EVT_ORDER_REFUNDED,\n EVT_ORDER_PARTIALLY_REFUNDED,\n EVT_ORDER_STATUS_CHANGED,\n ],\n handle: onStatusChange as EventHandler,\n },\n {\n // A payment's outcome is written on its order (the intent, a failure note, a refund of a cancelled capture).\n name: 'order-projection-payment',\n types: [EVT_PAYMENT_INTENT_CREATED, EVT_PAYMENT_FAILED, EVT_PAYMENT_REFUNDED],\n handle: onStatusChange as EventHandler,\n },\n ]\n}\n\nexport async function registerOrderProjection(deps: RegisterOrderProjectionDeps): Promise<void> {\n await subscribeDerived(deps.eventBus, orderProjection(deps))\n}\n","import {\n EVT_CUSTOMER_CREATED,\n EVT_CUSTOMER_DELETED,\n EVT_CUSTOMER_UPDATED,\n EVT_ORDER_PAID,\n EVT_ORDER_PARTIALLY_REFUNDED,\n EVT_ORDER_REFUNDED,\n type CustomerProfile,\n type DocumentStoreAdapter,\n type EventBusAdapter,\n type EventHandler,\n type Logger,\n} from '@nymbalhq/types'\nimport type { CustomerRepository } from '../../repositories/customer.js'\nimport type { OrderRepository } from '../../repositories/order.js'\nimport { buildCustomerProfile, CUSTOMER_PROFILES } from '../../read-models/builders.js'\nimport { subscribeDerived, type DerivedHandler } from '../derived.js'\n\nexport interface CustomerProjectionDeps {\n documentStore: DocumentStoreAdapter\n logger: Logger\n customerRepo: CustomerRepository\n orderRepo: OrderRepository\n}\n\nexport interface RegisterCustomerProjectionDeps extends CustomerProjectionDeps {\n eventBus: EventBusAdapter\n}\n\n/** `customer-profiles`, from the customer row as it is at handle time: its stats move with payments and refunds. */\nexport function customerProjection(deps: CustomerProjectionDeps): DerivedHandler[] {\n const { documentStore, logger, customerRepo, orderRepo } = deps\n\n async function reproject(customerId: string): Promise<void> {\n const c = await customerRepo.store.read((tx) => customerRepo.findById(tx, customerId))\n if (!c) {\n await documentStore.delete(CUSTOMER_PROFILES, customerId)\n return\n }\n await documentStore.put<CustomerProfile>(CUSTOMER_PROFILES, c.id, buildCustomerProfile(c))\n logger.debug({ customerId }, 'customer profile projected')\n }\n\n const onCustomer: EventHandler<{ customerId: string }> = (event) =>\n reproject(event.payload.customerId)\n\n const onOrder: EventHandler<{ orderId: string }> = async (event) => {\n const order = await orderRepo.store.read((tx) => orderRepo.findById(tx, event.payload.orderId))\n if (order?.customerId) await reproject(order.customerId)\n }\n\n return [\n {\n name: 'customer-projection-created',\n types: [EVT_CUSTOMER_CREATED],\n handle: onCustomer as EventHandler,\n },\n {\n name: 'customer-projection-updated',\n types: [EVT_CUSTOMER_UPDATED],\n handle: onCustomer as EventHandler,\n },\n {\n name: 'customer-projection-deleted',\n types: [EVT_CUSTOMER_DELETED],\n handle: onCustomer as EventHandler,\n },\n {\n name: 'customer-projection-order-paid',\n types: [EVT_ORDER_PAID],\n handle: onOrder as EventHandler,\n },\n {\n name: 'customer-projection-order-refunded',\n types: [EVT_ORDER_REFUNDED, EVT_ORDER_PARTIALLY_REFUNDED],\n handle: onOrder as EventHandler,\n },\n ]\n}\n\nexport async function registerCustomerProjection(\n deps: RegisterCustomerProjectionDeps,\n): Promise<void> {\n await subscribeDerived(deps.eventBus, customerProjection(deps))\n}\n","import {\n EVT_INVENTORY_CHANGED,\n type EventBusAdapter,\n type EventHandler,\n type InventoryChangedV1Payload,\n} from '@nymbalhq/types'\nimport { subscribeDerived, type DerivedHandler } from '../derived.js'\nimport { productReprojector, type ProductProjectionDeps } from './product-projection.js'\n\nexport interface RegisterInventoryProjectionDeps extends ProductProjectionDeps {\n eventBus: EventBusAdapter\n}\n\n/** A stock change re-projects the variant's product, so `products` and `products-by-category` both carry it. */\nexport function inventoryProjection(deps: ProductProjectionDeps): DerivedHandler[] {\n const products = productReprojector(deps)\n const { repos, logger } = deps\n\n const handler: EventHandler<InventoryChangedV1Payload> = async (event) => {\n const { variantId, newQty } = event.payload\n const variant = await repos.variant.store.read((tx) => repos.variant.findById(tx, variantId))\n if (!variant) return\n await products.reproject(variant.productId)\n logger.debug({ variantId, newQty }, 'inventory projection updated')\n }\n\n return [\n {\n name: 'inventory-projection',\n types: [EVT_INVENTORY_CHANGED],\n handle: handler as EventHandler,\n },\n ]\n}\n\nexport async function registerInventoryProjection(\n deps: RegisterInventoryProjectionDeps,\n): Promise<void> {\n await subscribeDerived(deps.eventBus, inventoryProjection(deps))\n}\n","import { v7 as uuidv7 } from 'uuid'\nimport {\n EVT_CART_ABANDONED,\n EVT_CUSTOMER_CREATED,\n EVT_ORDER_CONFIRMATION_RESEND_REQUESTED,\n EVT_ORDER_PAID,\n EVT_ORDER_SHIPPED,\n type CartAbandonedV1Payload,\n type CustomerCreatedV1Payload,\n type EmailAdapter,\n type EventBusAdapter,\n type EventHandler,\n type Logger,\n type Order,\n type OrderConfirmationResendRequestedV1Payload,\n type OrderPaidV1Payload,\n type OrderShippedV1Payload,\n} from '@nymbalhq/types'\nimport { formatMoney } from '../../money.js'\nimport { mintOrderKey } from '../../order-access-key.js'\nimport { withIdempotency } from '../idempotency.js'\nimport type { OrderAccessKeyRepository } from '../../repositories/order-access-key.js'\nimport type { OrderRepository } from '../../repositories/order.js'\nimport type { ProcessedEventRepository } from '../../repositories/processed-event.js'\n\n/** The handler name of the order-placed email's records: one per order, whatever number of order.paid it gets. */\nconst ORDER_PAID_EMAIL = 'email:order-paid'\n\nexport interface RegisterEmailHandlerDeps {\n eventBus: EventBusAdapter\n email: EmailAdapter\n logger: Logger\n processedEventRepo: ProcessedEventRepository\n orderRepo: OrderRepository\n orderAccessKeyRepo: OrderAccessKeyRepository\n storeName: string\n /** The storefront's URL, with no trailing `/`; with none, the order-placed email links nowhere and mints no key. */\n storeUrl?: string\n /** How long the email's order key opens the order on its own; 30 days when not given. */\n keyLifetimeMs?: number\n}\n\nconst DEFAULT_EMAIL_KEY_LIFETIME_MS = 30 * 24 * 3_600_000\n\nexport async function registerEmailHandler(deps: RegisterEmailHandlerDeps): Promise<void> {\n const { eventBus, email, logger, processedEventRepo, orderRepo, orderAccessKeyRepo } = deps\n const { storeName, storeUrl } = deps\n const keyLifetimeMs = deps.keyLifetimeMs ?? DEFAULT_EMAIL_KEY_LIFETIME_MS\n\n /**\n * The order's page: a customer's in their account, with no key; a guest's with a key of the email's own, since only\n * the hash of the checkout's key is stored, so the handler never has it.\n */\n async function orderLink(\n base: string,\n order: Order,\n ): Promise<{ orderUrl: string; orderLink: string }> {\n const number = encodeURIComponent(order.orderNumber)\n let orderUrl = `${base}/account/orders/${number}`\n if (order.customerId === null) {\n const { key, hash } = mintOrderKey()\n const createdAt = new Date()\n await orderAccessKeyRepo.store.transaction((tx) =>\n orderAccessKeyRepo.insert(tx, {\n id: uuidv7(),\n orderId: order.id,\n keyHash: hash,\n purpose: 'email',\n createdAt,\n expiresAt: new Date(createdAt.getTime() + keyLifetimeMs),\n }),\n )\n orderUrl = `${base}/order/${number}?key=${key}`\n }\n return { orderUrl, orderLink: `\\n\\nView your order: ${orderUrl}` }\n }\n\n /** The order-placed email, with a link carrying a key minted for this send when the store has a URL. */\n async function sendOrderPlaced(order: Order): Promise<void> {\n await email.sendTransactional({\n template: 'order-placed',\n to: order.email,\n vars: {\n orderNumber: order.orderNumber,\n customerName: order.billingAddress.firstName,\n totalFormatted: formatMoney(order.totalMinor, order.currency),\n ...(storeUrl !== undefined && (await orderLink(storeUrl, order))),\n },\n })\n }\n\n // Sent on payment, never at placement: an unpaid order (or an imported one) emails nobody. Keyed per order, so a\n // second order.paid for the order (a redelivered or replayed event) sends nothing more.\n const onOrderPaid: EventHandler<OrderPaidV1Payload> = async (event) => {\n const { orderId } = event.payload\n const { store } = processedEventRepo\n if (await store.read((tx) => processedEventRepo.seen(tx, ORDER_PAID_EMAIL, orderId))) return\n const order = await orderRepo.store.read((tx) => orderRepo.findById(tx, orderId))\n if (order === null) {\n logger.warn({ orderId, eventId: event.id }, 'email handler: paid order not found')\n return\n }\n await sendOrderPlaced(order)\n await store.transaction((tx) =>\n processedEventRepo.markProcessed(tx, ORDER_PAID_EMAIL, orderId, new Date()),\n )\n }\n\n // An admin's resend: once per resend event, never per order, so it sends whatever became of order.paid's email.\n const onConfirmationResendRequested: EventHandler<\n OrderConfirmationResendRequestedV1Payload\n > = async (event) => {\n const { orderId } = event.payload\n const order = await orderRepo.store.read((tx) => orderRepo.findById(tx, orderId))\n if (order === null) {\n logger.warn({ orderId, eventId: event.id }, 'email handler: resent order not found')\n return\n }\n await sendOrderPlaced(order)\n }\n\n const onOrderShipped: EventHandler<OrderShippedV1Payload> = async (event) => {\n logger.debug({ orderId: event.payload.orderId }, 'email handler: order shipped')\n // Need to look up customer email; skip in v0.1 (requires order repo).\n }\n\n const onCustomerCreated: EventHandler<CustomerCreatedV1Payload> = async (event) => {\n await email.sendTransactional({\n template: 'welcome',\n to: event.payload.email,\n vars: { customerName: 'there', storeName },\n })\n }\n\n const onCartAbandoned: EventHandler<CartAbandonedV1Payload> = async (event) => {\n logger.debug({ cartId: event.payload.cartId }, 'email handler: cart abandoned (stub)')\n }\n\n await eventBus.subscribe(EVT_ORDER_PAID, onOrderPaid as EventHandler, {\n name: 'email-order-paid',\n })\n await eventBus.subscribe(\n EVT_ORDER_CONFIRMATION_RESEND_REQUESTED,\n withIdempotency(\n 'email:order-confirmation-resend',\n onConfirmationResendRequested as EventHandler,\n { repo: processedEventRepo, logger },\n ),\n { name: 'email-order-confirmation-resend' },\n )\n await eventBus.subscribe(\n EVT_ORDER_SHIPPED,\n withIdempotency('email:order-shipped', onOrderShipped as EventHandler, {\n repo: processedEventRepo,\n logger,\n }),\n { name: 'email-order-shipped' },\n )\n await eventBus.subscribe(\n EVT_CUSTOMER_CREATED,\n withIdempotency('email:customer-created', onCustomerCreated as EventHandler, {\n repo: processedEventRepo,\n logger,\n }),\n { name: 'email-customer-created' },\n )\n await eventBus.subscribe(\n EVT_CART_ABANDONED,\n withIdempotency('email:cart-abandoned', onCartAbandoned as EventHandler, {\n repo: processedEventRepo,\n logger,\n }),\n { name: 'email-cart-abandoned' },\n )\n}\n","import {\n EVT_PRODUCT_CREATED,\n EVT_PRODUCT_DELETED,\n EVT_PRODUCT_UPDATED,\n type EventBusAdapter,\n type EventHandler,\n type Logger,\n type ProductCreatedV1Payload,\n type ProductDeletedV1Payload,\n type ProductUpdatedV1Payload,\n type SearchAdapter,\n} from '@nymbalhq/types'\nimport type { Repositories } from '../../repositories/index.js'\nimport { buildSearchDoc } from '../../read-models/builders.js'\nimport { productSnapshot } from '../../read-models/sources.js'\nimport { subscribeDerived, type DerivedHandler } from '../derived.js'\n\nexport interface SearchHandlerDeps {\n search: SearchAdapter\n logger: Logger\n repos: Pick<Repositories, 'product' | 'variant' | 'category' | 'productCategory'>\n}\n\nexport interface RegisterSearchHandlerDeps extends SearchHandlerDeps {\n eventBus: EventBusAdapter\n}\n\n/**\n * The search index, from the product's rows at handle time. Derived state: indexing and removing by id is idempotent,\n * so no processed-event record is kept, and a rebuild refills it.\n */\nexport function searchHandler(deps: SearchHandlerDeps): DerivedHandler[] {\n const { search, repos, logger } = deps\n\n // A slot that cannot index (a provider whose key is not set yet) is skipped: failing would kill every product\n // event, and `nymbal replay --to search` fills the index once it can.\n const skips = (event: { id: string; type: string }): boolean => {\n if (search.capabilities().includes('index')) return false\n logger.debug(\n { eventId: event.id, type: event.type, provider: search.providerName },\n 'search: the slot cannot index, event skipped',\n )\n return true\n }\n\n const onUpsert: EventHandler<ProductCreatedV1Payload | ProductUpdatedV1Payload> = async (\n event,\n ) => {\n if (skips(event)) return\n const { id } = event.payload.product\n const snapshot = await repos.product.store.read(async (tx) => {\n const product = await repos.product.findById(tx, id)\n return product ? productSnapshot(tx, repos, product) : null\n })\n if (snapshot) await search.index([buildSearchDoc(snapshot)])\n else await search.remove([id])\n }\n\n const onDelete: EventHandler<ProductDeletedV1Payload> = async (event) => {\n if (skips(event)) return\n await search.remove([event.payload.productId])\n }\n\n return [\n {\n name: 'search-product-upsert',\n types: [EVT_PRODUCT_CREATED, EVT_PRODUCT_UPDATED],\n handle: onUpsert as EventHandler,\n },\n {\n name: 'search-product-delete',\n types: [EVT_PRODUCT_DELETED],\n handle: onDelete as EventHandler,\n },\n ]\n}\n\nexport async function registerSearchHandler(deps: RegisterSearchHandlerDeps): Promise<void> {\n await subscribeDerived(deps.eventBus, searchHandler(deps))\n}\n","import {\n EVT_ORDER_DELIVERED,\n type EventBusAdapter,\n type EventHandler,\n type Logger,\n type OrderDeliveredV1Payload,\n type ReviewsAdapter,\n} from '@nymbalhq/types'\nimport { withIdempotency } from '../idempotency.js'\nimport type { ProcessedEventRepository } from '../../repositories/processed-event.js'\n\nexport interface RegisterReviewsHandlerDeps {\n eventBus: EventBusAdapter\n reviews: ReviewsAdapter\n logger: Logger\n processedEventRepo: ProcessedEventRepository\n}\n\nexport async function registerReviewsHandler(deps: RegisterReviewsHandlerDeps): Promise<void> {\n const { eventBus, reviews, logger, processedEventRepo } = deps\n\n const handler: EventHandler<OrderDeliveredV1Payload> = async (event) => {\n await reviews.requestReview(event.payload.orderId)\n }\n\n await eventBus.subscribe(\n EVT_ORDER_DELIVERED,\n withIdempotency('reviews:order-delivered', handler as EventHandler, {\n repo: processedEventRepo,\n logger,\n }),\n { name: 'reviews-order-delivered' },\n )\n}\n","import {\n EVT_ALERT_REQUESTED,\n EVT_PRODUCT_RESTOCKED,\n EVT_PRODUCT_VARIANT_PRICE_CHANGED,\n type AlertRequestedV1Payload,\n type EmailAdapter,\n type EventBusAdapter,\n type EventHandler,\n type Logger,\n type NymbalEvent,\n type Product,\n type ProductRestockedV1Payload,\n type ProductVariantPriceChangedV1Payload,\n type TransactionalEmail,\n} from '@nymbalhq/types'\nimport { formatMoney } from '../../money.js'\nimport type { AlertSubscription } from '../../repositories/alert-subscription.js'\nimport type { Repositories } from '../../repositories/index.js'\nimport type { AlertService } from '../../services/alert-service.js'\n\n/**\n * The handler name of every alert email's record, keyed `<event id>:<subscription id>`: a redelivered event finds the\n * key and sends that row nothing more.\n */\nconst HANDLER = 'email:alert'\n\nexport interface RegisterAlertHandlerDeps {\n eventBus: EventBusAdapter\n email: EmailAdapter\n logger: Logger\n repos: Pick<Repositories, 'alertSubscription' | 'emailSuppression' | 'processedEvent' | 'product'>\n alerts: AlertService\n storeName: string\n}\n\nfunction links(row: AlertSubscription, product: Product) {\n const token = (value: string) => encodeURIComponent(value)\n return {\n confirmUrl: `${row.origin}/alerts/confirm?token=${token(row.confirmToken)}`,\n unsubscribeUrl: `${row.origin}/alerts/unsubscribe?token=${token(row.unsubscribeToken)}`,\n productUrl: `${row.origin}/product/${encodeURIComponent(product.slug)}`,\n }\n}\n\nexport async function registerAlertHandler(deps: RegisterAlertHandlerDeps): Promise<void> {\n const { eventBus, email, logger, repos, alerts, storeName } = deps\n const { store } = repos.processedEvent\n\n // A suppressed address is skipped, not failed: its row keeps its status and baseline, and the event is not retried\n // for it. The log names the row, never the address.\n const skipped = (subscriptionId: string, eventId: string) =>\n logger.info({ subscriptionId, eventId }, 'alert mail skipped: the address is suppressed')\n\n // A confirmation goes only to a row still waiting for one: a row confirmed or left since is sent nothing.\n const onRequested: EventHandler<AlertRequestedV1Payload> = async (event) => {\n const key = `${event.id}:${event.payload.subscriptionId}`\n const found = await store.read(async (tx) => {\n if (await repos.processedEvent.seen(tx, HANDLER, key)) return null\n const row = await repos.alertSubscription.findById(tx, event.payload.subscriptionId)\n if (row === null || row.status !== 'pending') return null\n if (await repos.emailSuppression.isSuppressed(tx, row.email)) return 'suppressed' as const\n const product = await repos.product.findById(tx, row.productId)\n return product === null ? null : { row, product }\n })\n if (found === null) return\n if (found === 'suppressed') return skipped(event.payload.subscriptionId, event.id)\n const { row, product } = found\n const { confirmUrl, unsubscribeUrl, productUrl } = links(row, product)\n await email.sendTransactional({\n template: row.kind === 'price_drop' ? 'alert-confirm-price-drop' : 'alert-confirm',\n to: row.email,\n vars: { storeName, productName: product.name, productUrl, confirmUrl, unsubscribeUrl },\n })\n await store.transaction((tx) =>\n repos.processedEvent.markProcessed(tx, HANDLER, key, new Date()),\n )\n }\n\n // Each row is mailed and recorded on its own: one refused address neither stops nor repeats another's alert, and keeps\n // its status (and a price-drop row its baseline). Any refused row fails the delivery, so the event is retried; the\n // retry finds the mailed rows' keys and mails only the refused ones.\n async function fanOut(\n event: NymbalEvent<unknown>,\n rows: AlertSubscription[],\n what: { alert: string; next: string },\n message: (row: AlertSubscription) => Omit<TransactionalEmail, 'to'>,\n ): Promise<void> {\n const failed: string[] = []\n for (const row of rows) {\n const key = `${event.id}:${row.id}`\n const skip = await store.read(async (tx) => {\n if (await repos.processedEvent.seen(tx, HANDLER, key)) return 'sent'\n return (await repos.emailSuppression.isSuppressed(tx, row.email)) ? 'suppressed' : null\n })\n if (skip === 'suppressed') skipped(row.id, event.id)\n if (skip !== null) continue\n try {\n await email.sendTransactional({ ...message(row), to: row.email })\n await store.transaction(async (tx) => {\n await repos.processedEvent.markProcessed(tx, HANDLER, key, new Date())\n await alerts.recordSent(tx, row, event)\n })\n } catch (err) {\n failed.push(row.id)\n logger.warn(\n { err, subscriptionId: row.id, eventId: event.id },\n `${what.alert} alert failed; the subscription stays active until a retry or the next ${what.next}`,\n )\n }\n }\n if (failed.length > 0) {\n throw new Error(\n `${what.alert} alerts for event ${event.id} failed for subscriptions ${failed.join(', ')}`,\n )\n }\n }\n\n const onRestocked: EventHandler<ProductRestockedV1Payload> = async (event) => {\n const { variantId, productId } = event.payload\n const { rows, product } = await store.read(async (tx) => ({\n rows: await repos.alertSubscription.listActive(tx, variantId, 'back_in_stock'),\n product: await repos.product.findById(tx, productId),\n }))\n if (product === null) return\n await fanOut(event, rows, { alert: 'back-in-stock', next: 'restock' }, (row) => {\n const { productUrl, unsubscribeUrl } = links(row, product)\n return {\n template: 'alert-back-in-stock',\n vars: { storeName, productName: product.name, productUrl, unsubscribeUrl },\n }\n })\n }\n\n // A row is mailed when the price falls below both the previous price and the last price it was told (its baseline).\n const onPriceChanged: EventHandler<ProductVariantPriceChangedV1Payload> = async (event) => {\n const { variantId, productId, previousPriceMinor, priceMinor, currency } = event.payload\n if (priceMinor >= previousPriceMinor) return\n const { rows, product } = await store.read(async (tx) => ({\n rows: await repos.alertSubscription.listActive(tx, variantId, 'price_drop'),\n product: await repos.product.findById(tx, productId),\n }))\n if (product === null) return\n const due = rows.filter(\n (row) => row.baselinePriceMinor !== null && priceMinor < row.baselinePriceMinor,\n )\n const previousPriceFormatted = formatMoney(previousPriceMinor, currency)\n const priceFormatted = formatMoney(priceMinor, currency)\n await fanOut(event, due, { alert: 'price-drop', next: 'drop' }, (row) => {\n const { productUrl, unsubscribeUrl } = links(row, product)\n return {\n template: 'alert-price-drop',\n vars: {\n storeName,\n productName: product.name,\n productUrl,\n unsubscribeUrl,\n previousPriceFormatted,\n priceFormatted,\n },\n }\n })\n }\n\n await eventBus.subscribe(EVT_ALERT_REQUESTED, onRequested as EventHandler, {\n name: 'email-alert-requested',\n })\n await eventBus.subscribe(EVT_PRODUCT_RESTOCKED, onRestocked as EventHandler, {\n name: 'email-alert-back-in-stock',\n })\n await eventBus.subscribe(EVT_PRODUCT_VARIANT_PRICE_CHANGED, onPriceChanged as EventHandler, {\n name: 'email-alert-price-drop',\n })\n}\n","import {\n emailFeedbackType,\n type EmailAdapter,\n type EmailBouncedV1Payload,\n type EmailComplainedV1Payload,\n type EventBusAdapter,\n type EventHandler,\n type Logger,\n type NymbalEvent,\n} from '@nymbalhq/types'\nimport { normaliseEmail } from '../../email-address.js'\nimport type { EmailSuppressionReason } from '../../repositories/email-suppression.js'\nimport type { Repositories } from '../../repositories/index.js'\nimport { isHooked } from '../../routes/webhooks-inbound.js'\n\nexport interface RegisterEmailFeedbackHandlerDeps {\n eventBus: EventBusAdapter\n email: EmailAdapter\n repos: Pick<Repositories, 'emailSuppression'>\n logger: Logger\n}\n\n/**\n * Suppresses an address the email adapter reports as hard-bounced or complaining. Only when that adapter takes webhooks\n * itself, by the route's own test: a hookless email adapter's name may be another slot's, whose events must not stop\n * the store's alert mail.\n */\nexport async function registerEmailFeedbackHandler(\n deps: RegisterEmailFeedbackHandlerDeps,\n): Promise<void> {\n const { eventBus, email, repos, logger } = deps\n if (!isHooked(email)) return\n const { store } = repos.emailSuppression\n\n // Insert-if-absent, so a redelivered event changes nothing and the first reason stays.\n async function suppress(\n event: NymbalEvent<{ recipient: string }>,\n reason: EmailSuppressionReason,\n ): Promise<void> {\n const suppressed = await store.transaction((tx) =>\n repos.emailSuppression.suppress(tx, {\n email: normaliseEmail(event.payload.recipient),\n reason,\n eventId: event.id,\n at: new Date(),\n }),\n )\n logger.info(\n { eventId: event.id, reason, suppressed },\n suppressed ? 'an address was suppressed' : 'the address was already suppressed',\n )\n }\n\n const onBounced: EventHandler<EmailBouncedV1Payload> = async (event) => {\n if (event.payload.bounce !== 'hard') {\n logger.info({ eventId: event.id }, 'a soft bounce changes nothing')\n return\n }\n await suppress(event, 'hard_bounce')\n }\n\n const onComplained: EventHandler<EmailComplainedV1Payload> = (event) =>\n suppress(event, 'complaint')\n\n await eventBus.subscribe(\n emailFeedbackType(email.providerName, 'bounced'),\n onBounced as EventHandler,\n { name: 'email-feedback-bounced' },\n )\n await eventBus.subscribe(\n emailFeedbackType(email.providerName, 'complained'),\n onComplained as EventHandler,\n { name: 'email-feedback-complained' },\n )\n}\n","import {\n StatusTransitionError,\n shippingTrackingType,\n type EventBusAdapter,\n type EventHandler,\n type Logger,\n type ShippingAdapter,\n type ShippingTrackingV1Payload,\n} from '@nymbalhq/types'\nimport { runAsActor } from '../../audit/actor.js'\nimport type { Repositories } from '../../repositories/index.js'\nimport { isHooked } from '../../routes/webhooks-inbound.js'\nimport type { OrderService } from '../../services/order-service.js'\n\nconst ACTOR = 'system:shipping-tracking'\n\nexport interface RegisterShippingTrackingHandlerDeps {\n eventBus: EventBusAdapter\n shipping: ShippingAdapter\n repos: Pick<Repositories, 'order' | 'orderShipment'>\n orderService: Pick<OrderService, 'markDelivered'>\n logger: Logger\n}\n\n/**\n * Delivers the shipped orders a delivered tracking update names. Only when the shipping adapter takes webhooks itself,\n * by the route's own test: a hookless shipping adapter's name may be another slot's, whose events must not move orders.\n * Nothing else is acted on and nothing it skips throws, so a carrier's updates are never retried for an order they\n * cannot move. The tracking number is never logged.\n */\nexport async function registerShippingTrackingHandler(\n deps: RegisterShippingTrackingHandlerDeps,\n): Promise<void> {\n const { eventBus, shipping, repos, orderService, logger } = deps\n if (!isHooked(shipping)) return\n const { store } = repos.orderShipment\n\n async function deliver(eventId: string, orderId: string): Promise<void> {\n try {\n await runAsActor({ kind: 'system', id: 'shipping-tracking' }, () =>\n orderService.markDelivered(orderId, ACTOR),\n )\n logger.info({ eventId, orderId }, 'a tracking update delivered the order')\n } catch (err) {\n // The order moved between the read and the move: another update or the admin delivered it first.\n if (!(err instanceof StatusTransitionError)) throw err\n logger.info({ eventId, orderId }, 'the order was no longer shipped')\n }\n }\n\n const onTracking: EventHandler<ShippingTrackingV1Payload> = async (event) => {\n const { status, trackingNumber } = event.payload\n if (status !== 'delivered') {\n logger.info({ eventId: event.id, status }, 'a tracking update other than delivered')\n return\n }\n const orders = await store.read(async (tx) => {\n const found = []\n for (const id of await repos.orderShipment.ordersByTrackingNumber(tx, trackingNumber)) {\n const order = await repos.order.findById(tx, id)\n if (order !== null) found.push(order)\n }\n return found\n })\n if (orders.length === 0) {\n logger.info({ eventId: event.id }, 'no order was shipped under the tracking number')\n return\n }\n for (const order of orders) {\n if (order.status !== 'shipped') {\n logger.info(\n { eventId: event.id, orderId: order.id, orderStatus: order.status },\n 'the order is not shipped',\n )\n continue\n }\n await deliver(event.id, order.id)\n }\n }\n\n await eventBus.subscribe(\n shippingTrackingType(shipping.providerName),\n onTracking as EventHandler,\n {\n name: 'shipping-tracking',\n },\n )\n}\n","import type { DocumentStoreAdapter, EventBusAdapter, Logger } from '@nymbalhq/types'\nimport type { NymbalConfig } from '@nymbalhq/config'\nimport type { Repositories } from '../repositories/index.js'\nimport type { AdapterRegistry } from '../adapters/registry.js'\nimport type { AlertService } from '../services/alert-service.js'\nimport type { OrderService } from '../services/order-service.js'\nimport { parseDurationToMs } from '../services/auth-service.js'\nimport { registerCategoryProjection } from './projections/category-projection.js'\nimport { registerProductProjection } from './projections/product-projection.js'\nimport { registerOrderProjection } from './projections/order-projection.js'\nimport { registerCustomerProjection } from './projections/customer-projection.js'\nimport { registerInventoryProjection } from './projections/inventory-projection.js'\nimport { registerRecentlyViewedProjection } from './projections/recently-viewed-projection.js'\nimport { registerEmailHandler } from './side-effects/email-handler.js'\nimport { registerSearchHandler } from './side-effects/search-handler.js'\nimport { registerReviewsHandler } from './side-effects/reviews-handler.js'\nimport { registerAlertHandler } from './side-effects/alert-handler.js'\nimport { registerEmailFeedbackHandler } from './side-effects/email-feedback-handler.js'\nimport { registerShippingTrackingHandler } from './side-effects/shipping-tracking-handler.js'\n\nexport interface RegisterHandlersDeps {\n config: NymbalConfig\n eventBus: EventBusAdapter\n documentStore: DocumentStoreAdapter\n repos: Repositories\n adapters: AdapterRegistry\n /** Records each alert's send: the row fired and `alert.sent.v1` published. */\n alerts: AlertService\n /** Moves an order a tracking update reports delivered. */\n orders: OrderService\n logger: Logger\n}\n\nexport async function registerHandlers(deps: RegisterHandlersDeps): Promise<void> {\n const { config, eventBus, documentStore, repos, adapters, alerts, orders, logger } = deps\n const handlerLogger = logger.child({ component: 'handlers' })\n\n await registerCategoryProjection({\n eventBus,\n documentStore,\n logger: handlerLogger.child({ projection: 'category' }),\n storeId: config.store.name,\n repos,\n })\n await registerProductProjection({\n eventBus,\n documentStore,\n logger: handlerLogger.child({ projection: 'product' }),\n storeId: config.store.name,\n currency: config.store.currency,\n repos,\n })\n await registerOrderProjection({\n eventBus,\n documentStore,\n logger: handlerLogger.child({ projection: 'order' }),\n orderRepo: repos.order,\n orderHistoryRepo: repos.orderHistory,\n })\n await registerCustomerProjection({\n eventBus,\n documentStore,\n logger: handlerLogger.child({ projection: 'customer' }),\n customerRepo: repos.customer,\n orderRepo: repos.order,\n })\n await registerInventoryProjection({\n eventBus,\n documentStore,\n logger: handlerLogger.child({ projection: 'inventory' }),\n storeId: config.store.name,\n currency: config.store.currency,\n repos,\n })\n await registerRecentlyViewedProjection({\n eventBus,\n documentStore,\n logger: handlerLogger.child({ projection: 'recently-viewed' }),\n })\n\n await registerEmailHandler({\n eventBus,\n email: adapters.email,\n logger: handlerLogger.child({ handler: 'email' }),\n processedEventRepo: repos.processedEvent,\n orderRepo: repos.order,\n orderAccessKeyRepo: repos.orderAccessKey,\n storeName: config.store.name,\n ...(config.store.url !== undefined && { storeUrl: config.store.url }),\n keyLifetimeMs: parseDurationToMs(config.commerce.orders.keyLifetime.email),\n })\n await registerAlertHandler({\n eventBus,\n email: adapters.email,\n logger: handlerLogger.child({ handler: 'alert' }),\n repos,\n alerts,\n storeName: config.store.name,\n })\n await registerEmailFeedbackHandler({\n eventBus,\n email: adapters.email,\n repos,\n logger: handlerLogger.child({ handler: 'email-feedback' }),\n })\n await registerShippingTrackingHandler({\n eventBus,\n shipping: adapters.shipping,\n repos,\n orderService: orders,\n logger: handlerLogger.child({ handler: 'shipping-tracking' }),\n })\n await registerSearchHandler({\n eventBus,\n search: adapters.search,\n repos,\n logger: handlerLogger.child({ handler: 'search' }),\n })\n await registerReviewsHandler({\n eventBus,\n reviews: adapters.reviews,\n logger: handlerLogger.child({ handler: 'reviews' }),\n processedEventRepo: repos.processedEvent,\n })\n\n logger.debug('event handlers registered')\n}\n","import { DEFAULT_JWT_SECRET, type NymbalConfig } from '@nymbalhq/config'\nimport {\n ConfigError,\n type CommerceSlot,\n type HealthReport,\n type PaymentsAdapter,\n} from '@nymbalhq/types'\nimport { createPlatform, resolvePrimitives, type Platform } from './platform.js'\nimport type { ResolvePrimitivesOptions } from './platform.js'\nimport { buildRepositories, type Repositories } from './repositories/index.js'\nimport { rawClients } from './db/command-store.js'\nimport {\n buildAdapters,\n checkInjectedAdapters,\n COMMERCE_SLOTS,\n resolvePaymentsAdapter,\n resolveSecurityAdapter,\n type AdapterRegistry,\n type InjectedAdapters,\n} from './adapters/registry.js'\nimport { isNotConfigured } from './adapters/not-configured.js'\nimport { createLogger } from './logger.js'\nimport { loadBootSettings } from './settings/load.js'\nimport { addSecret, scrubbingLogger } from './settings/secret-set.js'\nimport { JWT_SECRET_ENV, resolveAuthSecret } from './auth-secret.js'\nimport { buildServices, type ServiceRegistry } from './services/index.js'\nimport { createEventPublisher, type EventPublisher } from './events/publisher.js'\nimport { createRelay, deliveringBus, type CreateRelayOptions, type Relay } from './events/relay.js'\nimport { createOutageProbe, type OutageSubject } from './events/outage.js'\nimport { registerHandlers } from './handlers/register.js'\nimport { READ_MODEL_NAMES, rebuild } from './read-models/index.js'\nimport {\n startInventoryReservationSweeper,\n startCartAbandonmentSweeper,\n startEventRetentionSweeper,\n type EventArchiveWriter,\n type SweeperHandle,\n} from './sweepers/index.js'\nimport { importAdapterModule, resolveChoice } from './adapters/resolve.js'\nimport type { HttpAdapter } from '@nymbalhq/types'\n\nexport interface NymbalApp {\n platform: Platform\n repos: Repositories\n adapters: AdapterRegistry\n services: ServiceRegistry\n publisher: EventPublisher\n /** Delivers the event log to the bus; started by createApp, stopped by stop(). */\n relay: Relay\n /**\n * Registers the API on the adapter. The admin is served at /admin/ when `adminRoot` is passed (its dist directory,\n * or null for a 404 that says how to build it) or `NYMBAL_ADMIN_DIST` is set.\n */\n attachHttp(adapter: HttpAdapter, options?: AttachHttpOptions): Promise<void>\n /** Each slot's provider and its adapter's own `capabilities()`; an ai slot of `none` offers nothing. */\n capabilities(): CapabilitiesReport\n stop(): Promise<void>\n}\n\nexport type CapabilitySlot = CommerceSlot | 'security' | 'documentStore' | 'eventBus' | 'media'\n\nexport interface SlotCapabilities {\n provider: string\n capabilities: readonly string[]\n}\n\nexport type CapabilitiesReport = Record<CapabilitySlot, SlotCapabilities>\n\nexport interface AttachHttpOptions {\n adminRoot?: string | null\n}\n\nexport interface CreateAppOptions extends ResolvePrimitivesOptions {\n version?: string\n /** The project's own adapters, one per slot whose provider is `custom`. */\n adapters?: InjectedAdapters\n /** How the event relay retries a failed delivery (`createRelay`). */\n relay?: Pick<CreateRelayOptions, 'maxAttempts' | 'retryDelayMs' | 'intervalMs' | 'now'>\n}\n\n/**\n * A production process must not run on the stub payments adapter (its unsigned webhook confirms any order) or sign\n * tokens with the schema's published default secret. Checked on the resolved adapter, built or injected, and the\n * effective secret, before anything opens the store.\n */\nfunction refuseUnsafeProduction(\n config: NymbalConfig,\n payments: PaymentsAdapter,\n jwtSecret: string,\n): void {\n if (process.env.NODE_ENV !== 'production') return\n const provider = config.commerce.payments.provider\n if (payments.providerName === 'native-stub') {\n throw new ConfigError(\n `Payments provider \"${provider}\" resolves to the stub adapter, which verifies no webhook signature; ` +\n 'configure a real payments provider for production.',\n { code: 'config.production_stub_payments', context: { provider } },\n )\n }\n if (jwtSecret === DEFAULT_JWT_SECRET) {\n throw new ConfigError(\n `security.auth.jwtSecret is the schema default and ${JWT_SECRET_ENV} is not set; set either to a secret of your own for production.`,\n { code: 'config.production_default_jwt_secret' },\n )\n }\n}\n\ntype EventArchiveOptions = Omit<NonNullable<NymbalConfig['events']['archive']>, 'adapter'>\n\ninterface ObjectWriterModule {\n createS3ObjectWriter?: (options: EventArchiveOptions) => EventArchiveWriter\n}\n\n/**\n * The private object writer `events.archive` names, from `@nymbalhq/media-s3`, or undefined when no archive is set.\n * Its credentials come from the AWS SDK's default chain, as media's do.\n */\nasync function eventArchiveWriter(config: NymbalConfig): Promise<EventArchiveWriter | undefined> {\n const archive = config.events.archive\n if (archive === undefined) return undefined\n const { adapter, ...options } = archive\n let mod: ObjectWriterModule | undefined\n try {\n mod = (await importAdapterModule('media', { provider: adapter }, process.env)) as\n | ObjectWriterModule\n | undefined\n } catch (error) {\n if (!(error instanceof ConfigError && error.code === 'adapter.package_missing')) throw error\n throw new ConfigError(\n `events.archive needs @nymbalhq/media-s3: ${String(error.context['install'])}`,\n {\n code: 'adapter.package_missing',\n cause: error,\n context: error.context,\n },\n )\n }\n if (typeof mod?.createS3ObjectWriter !== 'function') {\n throw new ConfigError('@nymbalhq/media-s3 exports no createS3ObjectWriter; upgrade it', {\n code: 'adapter.package_invalid',\n context: { package: '@nymbalhq/media-s3' },\n })\n }\n return mod.createS3ObjectWriter(options)\n}\n\ninterface Checkable {\n providerName?: unknown\n healthCheck?(): Promise<HealthReport>\n}\n\n/**\n * What the relay's outage probe checks: the primitives and every commerce slot a delivery can go through, each named\n * by its slot with the provider in the detail. Security and ai are left out (no delivery goes through either), and a\n * not-configured placeholder is too: it is down until a restart with its key, which is not an outage.\n */\nfunction outageSubjects(\n config: NymbalConfig,\n platform: Platform,\n adapters: AdapterRegistry,\n): OutageSubject[] {\n const subject = (name: string, provider: string, adapter: Checkable): OutageSubject[] => {\n if (isNotConfigured(adapter)) return []\n if (typeof adapter.healthCheck !== 'function') return [{ name }]\n const check = adapter.healthCheck.bind(adapter)\n const named = (detail: string | undefined) => (detail ? `${provider}: ${detail}` : provider)\n return [\n {\n name,\n healthCheck: () =>\n Promise.resolve()\n .then(check)\n .then(\n (report) =>\n report.status === 'down' ? { ...report, detail: named(report.detail) } : report,\n (err: unknown) => {\n throw new Error(named(err instanceof Error ? err.message : String(err)))\n },\n ),\n },\n ]\n }\n const { infrastructure } = config\n return [\n ...subject('eventBus', infrastructure.eventBus.provider, platform.eventBus),\n ...subject('documentStore', infrastructure.documentStore.provider, platform.documentStore),\n ...subject('media', infrastructure.media.provider, platform.media),\n ...COMMERCE_SLOTS.filter((slot) => slot !== 'ai').flatMap((slot) => {\n const adapter = adapters[slot] as Checkable\n const provider =\n typeof adapter.providerName === 'string'\n ? adapter.providerName\n : config.commerce[slot].provider\n return subject(slot, provider, adapter)\n }),\n ]\n}\n\nexport async function createApp(\n config: NymbalConfig,\n options: CreateAppOptions = {},\n): Promise<NymbalApp> {\n // Whatever logger the caller gives, nothing it writes carries a secret Settings hold.\n const logger = scrubbingLogger(\n options.logger ?? createLogger({ base: { store: config.store.name } }),\n )\n const adapterLogger = logger.child({ layer: 'adapter' })\n checkInjectedAdapters(config, options.adapters)\n const jwt = resolveAuthSecret(config, process.env)\n addSecret(jwt.secret)\n const shadowed = process.env[JWT_SECRET_ENV]\n if (jwt.source === 'config' && shadowed !== undefined && shadowed !== jwt.secret) {\n logger.warn(\n { variable: JWT_SECRET_ENV },\n `security.auth.jwtSecret in the config is used; ${JWT_SECRET_ENV} is set and ignored`,\n )\n }\n if (process.env.NODE_ENV === 'production' && jwt.secret.length < 32) {\n logger.warn(\n { source: jwt.source },\n 'the JWT secret is shorter than 32 characters; HS256 wants 256 bits (`openssl rand -base64 32`)',\n )\n }\n // Settings are read, through a read-only open closed again here, before any adapter is built: payments first.\n const settings = await loadBootSettings(config, {\n storage: {\n ...(options.sqlitePath !== undefined && { sqlitePath: options.sqlitePath }),\n ...(options.postgresUrl !== undefined && { postgresUrl: options.postgresUrl }),\n },\n env: process.env,\n logger,\n })\n const payments = await resolvePaymentsAdapter(\n config,\n adapterLogger,\n options.adapters,\n settings.values,\n )\n refuseUnsafeProduction(config, payments, jwt.secret)\n const security = await resolveSecurityAdapter(config, adapterLogger)\n const archive = await eventArchiveWriter(config)\n const primitives = await resolvePrimitives(config, { ...options, logger })\n // Until the app is returned, nothing else holds the connections the primitives and the command store open.\n let release = async (): Promise<void> => {\n await primitives.eventBus.close()\n await primitives.documentStore.close()\n }\n try {\n const platform = createPlatform(config, { ...options, ...primitives, logger })\n release = () => platform.close()\n const version = options.version ?? '0.1.0'\n\n const repos = buildRepositories(platform.commandStore, platform.documentStore)\n const adapters = await buildAdapters({\n config,\n logger: adapterLogger,\n sql: rawClients(platform.commandStore),\n repos,\n payments,\n security,\n settings: settings.values,\n ...(options.adapters !== undefined && { injected: options.adapters }),\n })\n const relay = createRelay({\n store: platform.commandStore,\n eventLog: repos.eventLog,\n eventBus: platform.eventBus,\n logger,\n outage: createOutageProbe(outageSubjects(config, platform, adapters)),\n ...options.relay,\n })\n const subscriberBus = deliveringBus(platform.eventBus, relay)\n const publisher = createEventPublisher({\n eventBus: platform.eventBus,\n store: platform.commandStore,\n eventLog: repos.eventLog,\n relay,\n builderContext: {\n storeId: config.store.name,\n environment:\n process.env.NODE_ENV === 'production'\n ? 'production'\n : process.env.NODE_ENV === 'staging'\n ? 'staging'\n : 'development',\n version,\n source: 'nymbal-app',\n },\n })\n const services = buildServices({\n config,\n store: platform.commandStore,\n repos,\n publisher,\n logger: logger.child({ layer: 'service' }),\n payments: adapters.payments,\n searchAdapter: adapters.search,\n email: adapters.email,\n jwtSecret: jwt.secret,\n })\n\n await registerHandlers({\n config,\n eventBus: subscriberBus,\n documentStore: platform.documentStore,\n repos,\n adapters,\n alerts: services.alert,\n orders: services.order,\n logger,\n })\n\n // Every read model is rebuilt from the tables before anything is served, so a fresh process serves what a\n // long-running one does. A search index in a package lives outside the process and outlasts it: a restart would\n // only upload the catalogue again, so live events and `nymbal replay --to search` fill it instead.\n const externalSearch = resolveChoice('search', config.commerce.search).kind === 'package'\n await rebuild(\n externalSearch ? READ_MODEL_NAMES.filter((name) => name !== 'search') : READ_MODEL_NAMES,\n {\n config,\n store: platform.commandStore,\n repos,\n documentStore: platform.documentStore,\n search: adapters.search,\n logger,\n },\n )\n\n // Events committed before a crash, or whose delivery failed, go out before the app serves anything.\n await relay.drain()\n relay.start()\n\n const sweepers: SweeperHandle[] = [\n startInventoryReservationSweeper({\n inventoryService: services.inventory,\n reservationRepo: repos.inventoryReservation,\n logger,\n }),\n startCartAbandonmentSweeper({\n store: platform.commandStore,\n carts: repos.cart,\n publisher,\n logger,\n }),\n startEventRetentionSweeper({\n store: platform.commandStore,\n eventLog: repos.eventLog,\n processedEvents: repos.processedEvent,\n logger,\n retentionDays: config.events.retentionDays,\n ...(archive !== undefined && { archive }),\n }),\n ]\n\n const app: NymbalApp = {\n platform,\n repos,\n adapters,\n services,\n publisher,\n relay,\n async attachHttp(adapter, options = {}) {\n await adapters.security.applyMiddleware(adapter, config.security)\n const { registerAllRoutes } = await import('./routes/register.js')\n registerAllRoutes({\n config,\n adapter,\n services,\n adapters,\n repos,\n documentStore: platform.documentStore,\n eventBus: subscriberBus,\n publisher,\n settingsSlots: settings.slots,\n jwtSecret: jwt.secret,\n adminRoot:\n options.adminRoot !== undefined ? options.adminRoot : process.env['NYMBAL_ADMIN_DIST'],\n })\n },\n capabilities() {\n const commerce = Object.fromEntries(\n COMMERCE_SLOTS.map((slot) => {\n const adapter = adapters[slot]\n return [\n slot,\n {\n provider: config.commerce[slot].provider,\n capabilities: adapter === null ? [] : adapter.capabilities(),\n },\n ]\n }),\n ) as Record<CommerceSlot, SlotCapabilities>\n return {\n ...commerce,\n security: {\n provider: config.security.adapter,\n capabilities: adapters.security.capabilities(),\n },\n documentStore: {\n provider: config.infrastructure.documentStore.provider,\n capabilities: platform.documentStore.capabilities(),\n },\n eventBus: {\n provider: config.infrastructure.eventBus.provider,\n capabilities: platform.eventBus.capabilities(),\n },\n media: {\n provider: config.infrastructure.media.provider,\n capabilities: platform.media.capabilities(),\n },\n }\n },\n async stop() {\n await relay.stop()\n for (const s of sweepers) s.stop()\n await platform.close()\n },\n }\n return app\n } catch (error) {\n await release().catch((err: unknown) =>\n logger.error({ err }, 'closing the primitives after a failed start failed'),\n )\n throw error\n }\n}\n","import { DEFAULT_JWT_SECRET, type NymbalConfig } from '@nymbalhq/config'\nimport { ConfigError } from '@nymbalhq/types'\n\nexport const JWT_SECRET_ENV = 'NYMBAL_JWT_SECRET'\n/** The schema's own floor for `security.auth.jwtSecret`. */\nconst MIN_LENGTH = 16\n\nexport interface AuthSecret {\n secret: string\n source: 'config' | 'env' | 'default'\n}\n\n/**\n * The secret every token is signed with: the config's own, else NYMBAL_JWT_SECRET, else the schema default. Code that\n * names a secret wins, as it does over the environment for adapter settings. A set variable is checked first, so a\n * malformed one fails the boot even when the config's secret would win.\n */\nexport function resolveAuthSecret(config: NymbalConfig, env: NodeJS.ProcessEnv): AuthSecret {\n const fromEnv = env[JWT_SECRET_ENV]\n if (fromEnv !== undefined && fromEnv.length < MIN_LENGTH) {\n throw new ConfigError(\n `${JWT_SECRET_ENV} is shorter than ${MIN_LENGTH} characters; set it to a random secret, such as \\`openssl rand -base64 32\\`.`,\n { code: 'config.jwt_secret_too_short', context: { variable: JWT_SECRET_ENV } },\n )\n }\n const own = config.security.auth.jwtSecret\n if (own !== DEFAULT_JWT_SECRET) return { secret: own, source: 'config' }\n if (fromEnv !== undefined) return { secret: fromEnv, source: 'env' }\n return { secret: DEFAULT_JWT_SECRET, source: 'default' }\n}\n","import { boundedHealthCheck, HEALTH_CHECK_TIMEOUT_MS, type HealthReport } from '@nymbalhq/types'\nimport { isNotConfigured } from '../adapters/not-configured.js'\n\n/** A primitive or slot adapter the relay may depend on: `name` is the slot or primitive, the provider is in the detail. */\nexport interface OutageSubject {\n name: string\n healthCheck?(): Promise<HealthReport>\n}\n\nexport interface OutageReport {\n /** True when any checked subject is down, threw or did not answer in time. */\n outage: boolean\n down: readonly { name: string; detail: string }[]\n}\n\nexport interface OutageProbeOptions {\n /** The bound on each subject's health check (default `HEALTH_CHECK_TIMEOUT_MS`). */\n timeoutMs?: number\n}\n\n/**\n * Checks every subject in parallel. `degraded` and a subject with no health check are not an outage, and a\n * not-configured placeholder is skipped: it answers `down` for ever, so counting it would keep every failure from\n * counting and a poison event from ever dying.\n */\nexport function createOutageProbe(\n subjects: readonly OutageSubject[],\n options: OutageProbeOptions = {},\n): () => Promise<OutageReport> {\n const timeoutMs = options.timeoutMs ?? HEALTH_CHECK_TIMEOUT_MS\n const checked = subjects.filter(\n (subject) => !isNotConfigured(subject) && typeof subject.healthCheck === 'function',\n )\n return async () => {\n const reports = await Promise.all(\n checked.map(async (subject) => ({\n name: subject.name,\n report: await boundedHealthCheck(() => subject.healthCheck!(), { timeoutMs }),\n })),\n )\n const down = reports\n .filter(({ report }) => report.status === 'down')\n .map(({ name, report }) => ({ name, detail: report.detail ?? 'down' }))\n return { outage: down.length > 0, down }\n }\n}\n","import {\n errorText,\n type DocumentStoreAdapter,\n type PutOptions,\n type SearchAdapter,\n type SearchDocument,\n} from '@nymbalhq/types'\nimport { rawClients } from '../db/command-store.js'\nimport { nativeIndexDocuments } from '../adapters/search/native-adapter.js'\nimport type { KeysetPage } from '../repositories/index.js'\nimport { KEY_OF } from './builders.js'\nimport { catalogue } from './catalogue.js'\nimport { customers } from './customers.js'\nimport {\n SEARCH_INDEX,\n searchOf,\n type ReadModel,\n type ReadModelName,\n type RebuildContext,\n type RebuildDeps,\n} from './model.js'\nimport { orders } from './orders.js'\nimport { recentlyViewed } from './recently-viewed.js'\nimport { search } from './search.js'\n\nexport {\n SEARCH_INDEX,\n type ReadModel,\n type ReadModelName,\n type RebuildContext,\n type RebuildDeps,\n} from './model.js'\n\n/** Every derived read model, in the order a rebuild of all of them runs. */\nexport const READ_MODELS: readonly ReadModel[] = [\n catalogue,\n orders,\n customers,\n search,\n recentlyViewed,\n]\n\nexport const READ_MODEL_NAMES: readonly ReadModelName[] = READ_MODELS.map((m) => m.name)\n\n/**\n * How long before the rebuild started a delivery may be stamped and still be caught up. The relay stamps\n * `delivered_at` on its own host's clock, which can run behind this process's; re-applying an event costs little,\n * skipping one loses a write.\n */\nexport const CATCH_UP_MARGIN_MS = 10 * 60_000\n\nconst DEFAULT_PAGE_SIZE = 200\nconst CATCH_UP_PAGE = 500\nconst SCAN_PAGE = 500\n\nexport interface CatchUpFailure {\n seq: number\n eventId: string\n type: string\n handler: string\n error: string\n}\n\nexport interface RebuildReportEntry {\n model: ReadModelName\n /** Each collection swapped in and the documents it was given (the search model's is `index`). */\n collections: Array<{ name: string; documents: number }>\n /** Logged events applied to the collected contents before the swap. */\n caughtUpBeforeSwap: number\n /** Logged events re-applied after the swap. */\n caughtUpEvents: number\n /** Catch-up events a handler failed on: the model is swapped all the same. */\n failures: CatchUpFailure[]\n ms: number\n /** Set when the search adapter has no `replaceAll`: it was given every document, and kept any others it held. */\n note?: string\n}\n\nexport type RebuildReport = RebuildReportEntry[]\n\n/** A rebuilder failed: nothing was swapped, so every read model keeps its old contents. */\nexport class RebuildError extends Error {\n readonly model: ReadModelName\n\n constructor(model: ReadModelName, cause: unknown) {\n super(\n `the ${model} read model was not rebuilt (its old contents are kept): ${errorText(cause)}`,\n {\n cause,\n },\n )\n this.name = 'RebuildError'\n this.model = model\n }\n}\n\nfunction modelsOf(names: readonly string[]): ReadModel[] {\n return names.map((name) => {\n const model = READ_MODELS.find((m) => m.name === name)\n if (model === undefined) {\n throw new Error(`unknown read model \"${name}\": one of ${READ_MODEL_NAMES.join(', ')}, or all`)\n }\n return model\n })\n}\n\n/** The context a model rebuilds with, and the highest seq it read from the log (undefined when it reads no log). */\nfunction contextFor(\n model: ReadModel,\n deps: RebuildDeps,\n): { ctx: RebuildContext; logReadThrough: () => number | undefined } {\n const limit = deps.pageSize ?? DEFAULT_PAGE_SIZE\n let page = 0\n let logReadThrough: number | undefined\n const ctx: RebuildContext = {\n deps,\n async *pages(table, read) {\n let after: string | undefined\n for (;;) {\n await deps.onPage?.({ model: model.name, table, page })\n page += 1\n const keyset: KeysetPage = after === undefined ? { limit } : { after, limit }\n const rows = await deps.store.read((tx) => read(tx, keyset))\n if (rows.length > 0) yield rows\n if (rows.length < limit) return\n after = rows[rows.length - 1]!.id\n }\n },\n async *events(types) {\n let after = 0\n logReadThrough ??= 0\n for (;;) {\n await deps.onPage?.({ model: model.name, table: 'events', page })\n page += 1\n const rows = await deps.store.read((tx) =>\n deps.repos.eventLog.listAfter(tx, after, { types: [...types], limit }),\n )\n if (rows.length > 0) {\n after = rows[rows.length - 1]!.seq\n logReadThrough = Math.max(logReadThrough, after)\n const live = rows.filter((r) => r.deadAt === null)\n if (live.length > 0) yield live\n }\n if (rows.length < limit) return\n }\n },\n }\n return { ctx, logReadThrough: () => logReadThrough }\n}\n\ninterface Collected {\n model: ReadModel\n /** When its first page was read: catch-up starts from here, less the margin. */\n startedAt: number\n /** The new contents, by collection (`SEARCH_INDEX` for search), then by key. */\n writes: Map<string, Map<string, unknown>>\n /** For a model rebuilt from the log, the last seq it read: its catch-up starts above it. */\n logReadThrough: number | undefined\n}\n\n/** Reads every document of `model` into memory, so a rebuilder that fails part-way leaves nothing half-swapped. */\nasync function collect(model: ReadModel, deps: RebuildDeps): Promise<Collected> {\n const startedAt = Date.now()\n const owned = model.target === 'search' ? [SEARCH_INDEX] : model.collections\n const writes = new Map(owned.map((c) => [c, new Map<string, unknown>()]))\n const { ctx, logReadThrough } = contextFor(model, deps)\n try {\n for await (const w of model.rebuild(ctx)) {\n const into = writes.get(w.collection)\n if (into === undefined) throw new Error(`it wrote to ${w.collection}, which it does not own`)\n into.set(w.key, w.doc)\n }\n } catch (error) {\n throw new RebuildError(model.name, error)\n }\n return { model, startedAt, writes, logReadThrough: logReadThrough() }\n}\n\nasync function* entries<T>(docs: Map<string, T>): AsyncGenerator<[string, T]> {\n yield* docs\n}\n\n/** Swaps the collected contents in; returns the note a search adapter without `replaceAll` earns. */\nasync function swap({ model, writes }: Collected, deps: RebuildDeps): Promise<string | undefined> {\n if (model.target === 'documents') {\n for (const collection of model.collections) {\n await deps.documentStore.replaceCollection(collection, entries(writes.get(collection)!))\n }\n return undefined\n }\n const search = searchOf(deps)\n const docs = [...writes.get(SEARCH_INDEX)!.values()] as SearchDocument[]\n if (search.replaceAll !== undefined) {\n await search.replaceAll(docs)\n return undefined\n }\n await search.index(docs)\n return `${search.providerName} has no replaceAll: every document was indexed, removals not guaranteed`\n}\n\n/**\n * `deps` with the model's own collections (and, for search, the index) read from and written to `writes` instead of\n * the live stores, so the snapshot can be caught up before it is swapped in. Other collections stay live.\n */\nfunction stagedDeps({ model, writes }: Collected, deps: RebuildDeps): RebuildDeps {\n if (model.target === 'search') return { ...deps, search: stagedSearch(searchOf(deps), writes) }\n const live = deps.documentStore\n const documentStore: DocumentStoreAdapter = {\n capabilities: () => live.capabilities(),\n async get<T>(collection: string, key: string) {\n const docs = writes.get(collection)\n if (docs === undefined) return live.get<T>(collection, key)\n return (docs.get(key) as T | undefined) ?? null\n },\n async put<T>(collection: string, key: string, doc: T, options?: PutOptions) {\n const docs = writes.get(collection)\n if (docs === undefined) return live.put(collection, key, doc, options)\n docs.set(key, doc)\n },\n async delete(collection, key) {\n const docs = writes.get(collection)\n if (docs === undefined) return live.delete(collection, key)\n docs.delete(key)\n },\n async batchGet<T>(collection: string, keys: string[]) {\n const docs = writes.get(collection)\n if (docs === undefined) return live.batchGet<T>(collection, keys)\n const out = new Map<string, T>()\n for (const key of keys) if (docs.has(key)) out.set(key, docs.get(key) as T)\n return out\n },\n async batchPut<T>(collection: string, items: Map<string, T>) {\n const docs = writes.get(collection)\n if (docs === undefined) return live.batchPut(collection, items)\n for (const [key, doc] of items) docs.set(key, doc)\n },\n query() {\n throw new Error('a staged read model does not answer queries')\n },\n replaceCollection() {\n throw new Error('a staged read model is not replaced')\n },\n close: async () => undefined,\n }\n return { ...deps, documentStore }\n}\n\n/** The live search adapter's name and capabilities, with `index` and `remove` kept in the collected index. */\nfunction stagedSearch(live: SearchAdapter, writes: Collected['writes']): SearchAdapter {\n const held = writes.get(SEARCH_INDEX)!\n return {\n kind: 'search',\n get providerName() {\n return live.providerName\n },\n capabilities: () => live.capabilities(),\n producesEvents: [],\n consumesEvents: [],\n initialize: async () => undefined,\n healthCheck: () => live.healthCheck(),\n async index(docs) {\n for (const doc of docs) held.set(doc.id, doc)\n return { indexed: docs.length }\n },\n async remove(ids) {\n for (const id of ids) held.delete(id)\n },\n search() {\n throw new Error('a staged search index does not answer searches')\n },\n facet() {\n throw new Error('a staged search index does not answer facets')\n },\n }\n}\n\n/**\n * Re-applies, in seq order, every logged event that is not dead and was delivered at or after `since` or not yet, to\n * the model's handlers, called directly so a failure is collected instead of logged by the bus. The handlers write\n * the state they read at handle time, so an event applied twice changes nothing.\n */\nasync function catchUp(\n model: ReadModel,\n since: Date,\n deps: RebuildDeps,\n afterSeq = 0,\n): Promise<{ applied: number; failures: CatchUpFailure[] }> {\n const handlers = model.handlers(deps)\n const failures: CatchUpFailure[] = []\n let applied = 0\n for (;;) {\n const page = await deps.store.read((tx) =>\n deps.repos.eventLog.listForCatchUp(tx, since, { afterSeq, limit: CATCH_UP_PAGE }),\n )\n for (const { seq, event } of page) {\n afterSeq = seq\n const matching = handlers.filter((h) => h.types.includes(event.type))\n if (matching.length === 0) continue\n applied += 1\n for (const h of matching) {\n try {\n await h.handle(event)\n } catch (error) {\n failures.push({\n seq,\n eventId: event.id,\n type: event.type,\n handler: h.name,\n error: errorText(error),\n })\n }\n }\n }\n if (page.length < CATCH_UP_PAGE) return { applied, failures }\n }\n}\n\n/**\n * Rebuilds `names` from the command store's tables: every model is read first, then each is caught up in memory with\n * the events delivered since its read began, swapped in (atomically per collection) and caught up again, for the\n * events delivered while it was swapped. A rebuilder that throws rejects with\n * a `RebuildError` before anything is swapped. Catch-up failures are in the report.\n */\nexport async function rebuild(\n names: readonly ReadModelName[],\n deps: RebuildDeps,\n): Promise<RebuildReport> {\n const collected: Collected[] = []\n for (const model of modelsOf(names)) collected.push(await collect(model, deps))\n const report: RebuildReport = []\n for (const c of collected) {\n const since = new Date(c.startedAt - CATCH_UP_MARGIN_MS)\n await deps.onPhase?.('collected', c.model.name)\n // Caught up before the swap, so what was written since the read began is not missing once it is swapped in. The\n // tail after it starts from the margin again: on Postgres a lower seq can commit after a higher one.\n const staged = await catchUp(c.model, since, stagedDeps(c, deps), c.logReadThrough)\n const note = await swap(c, deps)\n await deps.onPhase?.('swapped', c.model.name)\n // The tail re-applies every event the staged pass saw, so a failure there is retried here and reported once.\n const { applied, failures } = await catchUp(c.model, since, deps, c.logReadThrough)\n const entry: RebuildReportEntry = {\n model: c.model.name,\n collections: [...c.writes].map(([name, docs]) => ({ name, documents: docs.size })),\n caughtUpBeforeSwap: staged.applied,\n caughtUpEvents: applied,\n failures,\n ms: Date.now() - c.startedAt,\n ...(note !== undefined && { note }),\n }\n report.push(entry)\n const log =\n failures.length > 0 ? deps.logger.warn.bind(deps.logger) : deps.logger.debug.bind(deps.logger)\n log(\n { model: entry.model, collections: entry.collections, caughtUpEvents: applied, failures },\n `read model ${entry.model} rebuilt`,\n )\n }\n return report\n}\n\nexport interface CollectionDiff {\n name: string\n added: number\n changed: number\n removed: number\n}\n\nexport interface ReadModelDiff {\n model: ReadModelName\n collections: CollectionDiff[]\n /** Why the model was not compared, when it was not. */\n skipped?: string\n}\n\n/** JSON with sorted keys: two documents equal when they would be stored alike, whatever their key order. */\nfunction canonical(value: unknown): string {\n const sort = (v: unknown): unknown => {\n if (Array.isArray(v)) return v.map(sort)\n if (v !== null && typeof v === 'object') {\n return Object.fromEntries(\n Object.keys(v)\n .sort()\n .map((k) => [k, sort((v as Record<string, unknown>)[k])]),\n )\n }\n return v\n }\n return JSON.stringify(sort(JSON.parse(JSON.stringify(value ?? null))))\n}\n\n/**\n * The live collection, by the key its builder files each document under: read by full scans only, which leave a\n * store's internal order alone (a Redis point read can advance a hash's rehash and reorder it).\n */\nasync function liveOf(\n store: DocumentStoreAdapter,\n collection: string,\n): Promise<Map<string, unknown>> {\n const keyOf = KEY_OF[collection]!\n const live = new Map<string, unknown>()\n let cursor: string | undefined\n for (;;) {\n const page = await store.query(collection, {\n partitionKey: { field: 'id', value: '*' },\n limit: SCAN_PAGE,\n ...(cursor !== undefined && { cursor }),\n })\n for (const doc of page.items) live.set(keyOf(doc), doc)\n if (page.nextCursor === null) return live\n cursor = page.nextCursor\n }\n}\n\nfunction compare(\n name: string,\n next: Map<string, unknown>,\n live: Map<string, unknown>,\n): CollectionDiff {\n let added = 0\n let changed = 0\n for (const [key, doc] of next) {\n if (!live.has(key)) added += 1\n else if (canonical(live.get(key)) !== canonical(doc)) changed += 1\n }\n return { name, added, changed, removed: live.size - (next.size - added) }\n}\n\n/** Rebuilds `name` into memory and counts, per collection, what differs from the live read model; writes nothing. */\nexport async function diffReadModel(\n name: ReadModelName,\n deps: RebuildDeps,\n): Promise<ReadModelDiff> {\n const [model] = modelsOf([name])\n const { writes } = await collect(model!, deps)\n if (model!.target === 'search') {\n const { providerName } = searchOf(deps)\n if (providerName !== 'native') {\n return {\n model: name,\n collections: [],\n skipped: `the ${providerName} search adapter cannot list its documents, so it is not compared`,\n }\n }\n const held = await nativeIndexDocuments(rawClients(deps.store))\n const live = new Map<string, unknown>(held.map((d) => [d.id, d]))\n return {\n model: name,\n collections: [compare(SEARCH_INDEX, writes.get(SEARCH_INDEX)!, live)],\n }\n }\n const collections: CollectionDiff[] = []\n for (const collection of model!.collections) {\n const live = await liveOf(deps.documentStore, collection)\n collections.push(compare(collection, writes.get(collection)!, live))\n }\n return { model: name, collections }\n}\n","import type { Category, ProductSnapshot } from '@nymbalhq/types'\nimport type { ReadTx } from '../db/command-store.js'\nimport type { KeysetPage } from '../repositories/index.js'\nimport { categoryProjection } from '../handlers/projections/category-projection.js'\nimport { inventoryProjection } from '../handlers/projections/inventory-projection.js'\nimport { productProjection } from '../handlers/projections/product-projection.js'\nimport {\n buildCategoryDoc,\n buildProductDoc,\n CATEGORIES,\n productWrites,\n PRODUCTS,\n PRODUCTS_BY_CATEGORY,\n} from './builders.js'\nimport type { ReadModel, RebuildDeps } from './model.js'\nimport { productSnapshot } from './sources.js'\n\n/** Every product of a page, with its variants and category ids. */\nexport function snapshotsOf({ repos }: RebuildDeps) {\n return async (tx: ReadTx, page: KeysetPage): Promise<ProductSnapshot[]> => {\n const out: ProductSnapshot[] = []\n for (const p of await repos.product.listPage(tx, page)) {\n out.push(await productSnapshot(tx, repos, p))\n }\n return out\n }\n}\n\nexport const catalogue: ReadModel = {\n name: 'catalogue',\n target: 'documents',\n collections: [CATEGORIES, PRODUCTS, PRODUCTS_BY_CATEGORY],\n\n async *rebuild(ctx) {\n const { config, repos, logger } = ctx.deps\n const storeId = config.store.name\n const categories = new Map<string, Category>()\n for await (const page of ctx.pages('categories', (tx, p) => repos.category.listPage(tx, p))) {\n for (const c of page) {\n categories.set(c.id, c)\n yield { collection: CATEGORIES, key: c.slug, doc: buildCategoryDoc(c, storeId) }\n }\n }\n const context = { storeId, currency: config.store.currency, logger }\n for await (const page of ctx.pages('products', snapshotsOf(ctx.deps))) {\n for (const snapshot of page) {\n yield* productWrites(buildProductDoc(snapshot, categories, context))\n }\n }\n },\n\n handlers({ config, documentStore, logger, repos }) {\n const product = {\n documentStore,\n logger,\n storeId: config.store.name,\n currency: config.store.currency,\n repos,\n }\n return [\n ...categoryProjection({ documentStore, logger, storeId: config.store.name, repos }),\n ...productProjection(product),\n ...inventoryProjection(product),\n ]\n },\n}\n","import { customerProjection } from '../handlers/projections/customer-projection.js'\nimport { buildCustomerProfile, CUSTOMER_PROFILES } from './builders.js'\nimport type { ReadModel } from './model.js'\n\nexport const customers: ReadModel = {\n name: 'customers',\n target: 'documents',\n collections: [CUSTOMER_PROFILES],\n\n async *rebuild(ctx) {\n const { repos } = ctx.deps\n for await (const page of ctx.pages('customers', (tx, p) => repos.customer.listPage(tx, p))) {\n for (const c of page) {\n yield { collection: CUSTOMER_PROFILES, key: c.id, doc: buildCustomerProfile(c) }\n }\n }\n },\n\n handlers({ documentStore, logger, repos }) {\n return customerProjection({\n documentStore,\n logger,\n customerRepo: repos.customer,\n orderRepo: repos.order,\n })\n },\n}\n","import type { NymbalConfig } from '@nymbalhq/config'\nimport type { DocumentStoreAdapter, Logger, SearchAdapter } from '@nymbalhq/types'\nimport type { CommandStore, ReadTx } from '../db/command-store.js'\nimport type { DerivedHandler } from '../handlers/derived.js'\nimport type { KeysetPage, Repositories } from '../repositories/index.js'\nimport type { LoggedEvent } from '../repositories/event-log.js'\nimport type { DocumentWrite } from './builders.js'\n\nexport type ReadModelName = 'catalogue' | 'orders' | 'customers' | 'search' | 'recently-viewed'\n\n/** The pseudo-collection a search model's writes go to: the search adapter, not the document store. */\nexport const SEARCH_INDEX = 'index'\n\nexport interface RebuildDeps {\n config: NymbalConfig\n store: CommandStore\n repos: Repositories\n /** Where the document models are rebuilt and caught up. */\n documentStore: DocumentStoreAdapter\n /** Where the search model is rebuilt and caught up; the search model cannot be rebuilt without it. */\n search?: SearchAdapter\n logger: Logger\n /** Rows per page read from the command store. */\n pageSize?: number\n /** Called before each page is read. */\n onPage?: (page: { model: ReadModelName; table: string; page: number }) => void | Promise<void>\n /** Awaited once every model is collected, before a model is caught up and swapped, and after its swap. */\n onPhase?: (phase: 'collected' | 'swapped', model: ReadModelName) => void | Promise<void>\n}\n\n/** What a rebuilder reads with: the command store in pages, each page a read of its own. */\nexport interface RebuildContext {\n deps: RebuildDeps\n pages<T extends { id: string }>(\n table: string,\n read: (tx: ReadTx, page: KeysetPage) => Promise<T[]>,\n ): AsyncIterable<T[]>\n /**\n * The logged events of `types`, in seq pages, each page a read of its own (`onPage` names the table `events`). A model\n * that reads them is caught up only with events above the last one it read: re-applying one it already folded\n * would fold it twice. The bound is per model, not per collection: a model that reads both `pages()` and `events()`\n * would skip catch-up for the collections it builds from tables.\n */\n events(types: readonly string[]): AsyncIterable<LoggedEvent[]>\n}\n\nexport interface ReadModel {\n name: ReadModelName\n /** Where its documents go: document-store collections, or the search adapter. */\n target: 'documents' | 'search'\n /** The document-store collections it owns; the search model owns none. */\n collections: readonly string[]\n /** Every document of the model, from the authoritative tables. A search model writes to `SEARCH_INDEX`. */\n rebuild(ctx: RebuildContext): AsyncIterable<DocumentWrite>\n /** The live projections that keep the model, bound to `deps`' document store and search adapter. */\n handlers(deps: RebuildDeps): DerivedHandler[]\n}\n\n/** The search adapter of `deps`, which the search model needs. */\nexport function searchOf(deps: RebuildDeps): SearchAdapter {\n if (deps.search === undefined) throw new Error('the search read model needs a search adapter')\n return deps.search\n}\n","import { orderProjection } from '../handlers/projections/order-projection.js'\nimport {\n buildOrderDoc,\n orderWrites,\n ORDERS,\n ORDERS_BY_CUSTOMER,\n type OrderDoc,\n} from './builders.js'\nimport type { ReadModel } from './model.js'\n\nexport const orders: ReadModel = {\n name: 'orders',\n target: 'documents',\n collections: [ORDERS, ORDERS_BY_CUSTOMER],\n\n async *rebuild(ctx) {\n const { repos } = ctx.deps\n const docs = ctx.pages('orders', async (tx, page) => {\n const out: Array<OrderDoc & { id: string }> = []\n for (const order of await repos.order.listPage(tx, page)) {\n out.push(buildOrderDoc(order, await repos.orderHistory.listByOrder(tx, order.id)))\n }\n return out\n })\n for await (const page of docs) {\n for (const doc of page) yield* orderWrites(doc)\n }\n },\n\n handlers({ documentStore, logger, repos }) {\n return orderProjection({\n documentStore,\n logger,\n orderRepo: repos.order,\n orderHistoryRepo: repos.orderHistory,\n })\n },\n}\n","import { searchHandler } from '../handlers/side-effects/search-handler.js'\nimport { buildSearchDoc } from './builders.js'\nimport { snapshotsOf } from './catalogue.js'\nimport { SEARCH_INDEX, searchOf, type ReadModel } from './model.js'\n\nexport const search: ReadModel = {\n name: 'search',\n target: 'search',\n collections: [],\n\n async *rebuild(ctx) {\n for await (const page of ctx.pages('products', snapshotsOf(ctx.deps))) {\n for (const snapshot of page) {\n const doc = buildSearchDoc(snapshot)\n yield { collection: SEARCH_INDEX, key: doc.id, doc }\n }\n }\n },\n\n handlers(deps) {\n return searchHandler({ search: searchOf(deps), repos: deps.repos, logger: deps.logger })\n },\n}\n","import type { Logger } from '@nymbalhq/types'\nimport type { InventoryService } from '../services/inventory-service.js'\nimport type { InventoryReservationRepository } from '../repositories/inventory-reservation.js'\nimport { newCorrelationId, runWithCorrelation } from '../events/correlation.js'\nimport { runAsActor } from '../audit/actor.js'\nimport { auditedCommand } from '../audit/audit.js'\n\nexport interface SweeperHandle {\n /** One sweep, awaited; the interval calls it. */\n tick(): Promise<void>\n stop(): void\n}\n\nexport interface InventoryReservationSweeperDeps {\n inventoryService: InventoryService\n reservationRepo: InventoryReservationRepository\n logger: Logger\n intervalMs?: number\n}\n\nexport function startInventoryReservationSweeper(\n deps: InventoryReservationSweeperDeps,\n): SweeperHandle {\n const intervalMs = deps.intervalMs ?? 60_000\n const logger = deps.logger.child({ sweeper: 'inventory-reservation' })\n let running = false\n async function tick(): Promise<void> {\n if (running) return\n running = true\n try {\n const { store } = deps.reservationRepo\n const now = new Date()\n const expired = await store.read((tx) => deps.reservationRepo.findExpiredBefore(tx, now))\n if (expired.length > 0) {\n logger.info({ count: expired.length }, 'releasing expired reservations')\n }\n for (const r of expired) {\n // releaseReservation deletes the row and restores its stock in one transaction; one that a commit or another\n // release already took is a no-op, and leaves no entry. Each release is a command of its own.\n await auditedCommand(store, 'inventory.releaseExpired', () =>\n deps.inventoryService.releaseReservation(r.reservationId, 'expired'),\n ).catch((err) => {\n logger.error({ err, reservationId: r.reservationId }, 'failed to release')\n })\n }\n } finally {\n running = false\n }\n }\n // Each run is one operation: its events share an id of their own, and its commands are the system's.\n const run = () =>\n runWithCorrelation(newCorrelationId('sweep:reservations'), () =>\n runAsActor({ kind: 'system', id: 'reservations' }, tick),\n )\n const handle = setInterval(() => {\n void run()\n }, intervalMs)\n return {\n tick: run,\n stop() {\n clearInterval(handle)\n },\n }\n}\n","import { EVT_CART_ABANDONED, type Logger } from '@nymbalhq/types'\nimport type { CommandStore } from '../db/command-store.js'\nimport type { CartRepository } from '../repositories/cart.js'\nimport type { EventPublisher } from '../events/publisher.js'\nimport {\n currentCorrelationId,\n newCorrelationId,\n runWithCorrelation,\n} from '../events/correlation.js'\nimport { runAsActor } from '../audit/actor.js'\nimport { audit, auditedCommand } from '../audit/audit.js'\nimport type { SweeperHandle } from './inventory-reservation-sweeper.js'\n\nconst COMMAND = 'cart.sweepAbandoned'\n\nexport interface CartAbandonmentSweeperDeps {\n store: CommandStore\n carts: CartRepository\n publisher: EventPublisher\n logger: Logger\n intervalMs?: number\n inactivityMs?: number\n /** Carts claimed per transaction; a tick runs as many as it takes to reach every due cart. */\n batchSize?: number\n now?: () => Date\n}\n\n/**\n * Deletes expired carts, then notifies each cart idle past `inactivityMs` once per inactivity period. The notice is\n * a durable claim on the cart row, committed with its `cart.abandoned` event, so a restart or another replica's\n * sweeper does not notify the same period again; a cart write clears the claim.\n */\nexport function startCartAbandonmentSweeper(deps: CartAbandonmentSweeperDeps): SweeperHandle {\n const { store, carts, publisher } = deps\n const intervalMs = deps.intervalMs ?? 5 * 60_000\n const inactivityMs = deps.inactivityMs ?? 24 * 60 * 60_000\n const batchSize = deps.batchSize ?? 500\n const now = deps.now ?? (() => new Date())\n const logger = deps.logger.child({ sweeper: 'cart-abandonment' })\n\n async function tick(): Promise<void> {\n try {\n const at = now()\n const window = { at, cutoff: new Date(at.getTime() - inactivityMs) }\n // The run is one command, noted only once it changes a cart. Its subject is the run, never a cart's token: a token\n // is a bearer credential, and an entry is kept for good.\n const noteRun = () =>\n audit.note(COMMAND, [{ type: 'sweep', id: currentCorrelationId() ?? 'cart-abandonment' }])\n // Expired carts go first, so a cart past its expiry is never notified.\n const expired = await store.transaction(async (tx) => {\n const deleted = await carts.deleteExpired(tx, at)\n if (deleted > 0) noteRun()\n return deleted\n })\n let abandoned = 0\n // Pages follow the token order rather than \"whatever is still unclaimed\", so a pass ends even when another\n // sweeper holds or has taken some of the rows.\n let after: string | undefined\n for (;;) {\n const page = await store.transaction(async (tx) => {\n const tokens = await carts.listAbandoned(tx, window, { after, limit: batchSize })\n for (const token of tokens) {\n const claimed = await carts.claimAbandoned(tx, token, window)\n if (claimed === null) continue\n noteRun()\n await publisher.publish(EVT_CART_ABANDONED, {\n cartId: claimed.token,\n lastActivityAt: claimed.lastActivityAt,\n })\n abandoned += 1\n }\n return tokens\n })\n if (page.length < batchSize) break\n after = page[page.length - 1]\n }\n if (expired > 0 || abandoned > 0) logger.info({ expired, abandoned }, 'carts swept')\n } catch (err) {\n logger.error({ err }, 'cart-abandonment sweep failed')\n }\n }\n\n // Each run is one operation: its events share an id of their own, and it is one command of the system's.\n const run = () =>\n runWithCorrelation(newCorrelationId('sweep:cart-abandonment'), () =>\n runAsActor({ kind: 'system', id: 'cart-abandonment' }, () =>\n auditedCommand(store, COMMAND, tick),\n ),\n )\n const handle = setInterval(() => void run(), intervalMs)\n return {\n tick: run,\n stop() {\n clearInterval(handle)\n },\n }\n}\n","import { promisify } from 'node:util'\nimport { gzip } from 'node:zlib'\nimport type { Logger } from '@nymbalhq/types'\nimport type { CommandStore } from '../db/command-store.js'\nimport type { EventLogRepository, LoggedEvent } from '../repositories/event-log.js'\nimport type { ProcessedEventRepository } from '../repositories/processed-event.js'\nimport type { SweeperHandle } from './inventory-reservation-sweeper.js'\n\n/** Where retention writes events before it deletes them: one object per batch, private to the operator. */\nexport interface EventArchiveWriter {\n put(key: string, body: Uint8Array, contentType: string): Promise<void>\n}\n\nexport interface EventRetentionSweeperDeps {\n store: CommandStore\n eventLog: EventLogRepository\n processedEvents: ProcessedEventRepository\n logger: Logger\n retentionDays?: number\n intervalMs?: number\n /** When set, delivered events past retention are archived here first, and deleted only once the put succeeds. */\n archive?: EventArchiveWriter\n}\n\nconst DAY_MS = 24 * 60 * 60 * 1000\nconst ARCHIVE_BATCH = 5000\nconst gzipAsync = promisify(gzip)\n\nconst pad = (n: number) => String(n).padStart(2, '0')\n\n/** `events/<yyyy>/<mm>/<dd>/<firstSeq>-<lastSeq>.ndjson.gz`, dated in UTC by the first row's append. */\nfunction archiveKey(batch: LoggedEvent[]): string {\n const first = batch[0]!\n const last = batch[batch.length - 1]!\n const at = first.createdAt\n const day = `${at.getUTCFullYear()}/${pad(at.getUTCMonth() + 1)}/${pad(at.getUTCDate())}`\n return `events/${day}/${first.seq}-${last.seq}.ndjson.gz`\n}\n\n/** One line per event: its envelope, with the log's `seq` and `deliveredAt`. */\nfunction archiveBody(batch: LoggedEvent[]): Promise<Buffer> {\n const lines = batch.map(\n (row) => `${JSON.stringify({ ...row.event, seq: row.seq, deliveredAt: row.deliveredAt })}\\n`,\n )\n return gzipAsync(lines.join(''))\n}\n\n/**\n * Deletes delivered events and processed-event records older than the window; undelivered and dead events stay. With\n * an archive, events go to it in `seq`-ordered batches first.\n */\nexport function startEventRetentionSweeper(deps: EventRetentionSweeperDeps): SweeperHandle {\n const retentionDays = deps.retentionDays ?? 30\n const intervalMs = deps.intervalMs ?? 3_600_000\n const logger = deps.logger.child({ sweeper: 'event-retention' })\n const { archive } = deps\n let running = false\n // The last seq of a batch whose put failed or whose delete did not follow. The next attempt ends there, so it writes\n // that key again rather than a wider batch overlapping it; the object may already exist, so readers dedupe by seq.\n let unconfirmedLastSeq: number | undefined\n\n /** Archives, then deletes, every delivered event past `cutoff`, batch by batch; a failed put stops the run. */\n async function archiveThenDelete(writer: EventArchiveWriter, cutoff: Date): Promise<number> {\n let deleted = 0\n for (;;) {\n const retry = unconfirmedLastSeq\n let batch = await deps.store.read((tx) =>\n deps.eventLog.listDeliveredBefore(tx, cutoff, ARCHIVE_BATCH),\n )\n if (retry !== undefined) batch = batch.filter((row) => row.seq <= retry)\n if (batch.length === 0) {\n // An unconfirmed batch's rows may have gone another way (another replica's sweep): nothing is pending then.\n unconfirmedLastSeq = undefined\n if (retry !== undefined) continue\n return deleted\n }\n unconfirmedLastSeq = batch[batch.length - 1]!.seq\n await writer.put(archiveKey(batch), await archiveBody(batch), 'application/gzip')\n const seqs = batch.map((row) => row.seq)\n deleted += await deps.store.transaction((tx) => deps.eventLog.deleteSeqs(tx, seqs))\n unconfirmedLastSeq = undefined\n if (retry === undefined && batch.length < ARCHIVE_BATCH) return deleted\n }\n }\n\n async function tick(): Promise<void> {\n if (running) return\n running = true\n try {\n const cutoff = new Date(Date.now() - retentionDays * DAY_MS)\n let deleted: { events: number; processed: number }\n if (archive === undefined) {\n deleted = await deps.store.transaction(async (tx) => ({\n events: await deps.eventLog.deleteDeliveredBefore(tx, cutoff),\n processed: await deps.processedEvents.deleteBefore(tx, cutoff),\n }))\n } else {\n const processed = await deps.store.transaction((tx) =>\n deps.processedEvents.deleteBefore(tx, cutoff),\n )\n deleted = { processed, events: await archiveThenDelete(archive, cutoff) }\n }\n if (deleted.events > 0 || deleted.processed > 0) {\n logger.info({ ...deleted, cutoff: cutoff.toISOString() }, 'deleted expired event records')\n }\n } catch (err) {\n logger.error({ err }, 'event retention sweep failed; undeleted events stay for the next run')\n } finally {\n running = false\n }\n }\n\n const handle = setInterval(() => void tick(), intervalMs)\n handle.unref()\n return {\n tick,\n stop() {\n clearInterval(handle)\n },\n }\n}\n","import type { RateLimitAction } from '@nymbalhq/types'\n\nexport interface ParsedRule {\n pattern: string\n regex: RegExp\n requests: number\n windowMs: number\n action: RateLimitAction\n}\n\ninterface Bucket {\n count: number\n resetAt: number\n}\n\nexport class RateLimiter {\n readonly #rules: ParsedRule[]\n readonly #buckets = new Map<string, Bucket>()\n\n constructor(\n rules: Record<string, { requests: number; window: string; action: RateLimitAction }>,\n ) {\n this.#rules = Object.entries(rules).map(([pattern, rule]) => ({\n pattern,\n regex: compilePathPattern(pattern),\n requests: rule.requests,\n windowMs: parseWindow(rule.window),\n action: rule.action,\n }))\n }\n\n check(ip: string, path: string): { allowed: boolean; action: RateLimitAction; retryAfter?: number } | null {\n const rule = this.#rules.find((r) => r.regex.test(path))\n if (!rule) return null\n const key = `${rule.pattern}|${ip}`\n const now = Date.now()\n const bucket = this.#buckets.get(key)\n if (!bucket || bucket.resetAt <= now) {\n this.#buckets.set(key, { count: 1, resetAt: now + rule.windowMs })\n return { allowed: true, action: rule.action }\n }\n bucket.count += 1\n if (bucket.count > rule.requests) {\n return {\n allowed: false,\n action: rule.action,\n retryAfter: Math.max(1, Math.ceil((bucket.resetAt - now) / 1000)),\n }\n }\n return { allowed: true, action: rule.action }\n }\n\n reset(): void {\n this.#buckets.clear()\n }\n}\n\nfunction parseWindow(window: string): number {\n const match = /^(\\d+)(ms|s|m|h)$/.exec(window)\n if (!match) throw new Error(`Invalid rate-limit window: ${window}`)\n const n = Number(match[1])\n switch (match[2]) {\n case 'ms':\n return n\n case 's':\n return n * 1000\n case 'm':\n return n * 60_000\n case 'h':\n return n * 3_600_000\n default:\n throw new Error(`Unreachable unit: ${match[2]}`)\n }\n}\n\nfunction compilePathPattern(pattern: string): RegExp {\n const escaped = pattern\n .replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\*\\*/g, '__DOUBLESTAR__')\n .replace(/\\*/g, '[^/]+')\n .replace(/__DOUBLESTAR__/g, '.*')\n return new RegExp(`^${escaped}$`)\n}\n","import { existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { nymbalConfigSchema, slotFolder, type NymbalConfig } from '@nymbalhq/config'\nimport {\n boundedHealthCheck,\n connectionSecrets,\n displayUrl,\n errorText,\n HEALTH_CHECK_TIMEOUT_MS,\n type CommerceSlot,\n type DocumentStoreAdapter,\n type HealthReport,\n type HealthStatus,\n type Logger,\n type Slot,\n} from '@nymbalhq/types'\nimport {\n declaredSettings,\n importAdapterModule,\n resolveChoice,\n type Choice,\n} from './adapters/resolve.js'\nimport {\n checkInjectedSlot,\n COMMERCE_SLOTS,\n resolvePaymentsAdapter,\n resolveSecurityAdapter,\n securityChoice,\n slotBuilders,\n type InjectedAdapters,\n} from './adapters/registry.js'\nimport {\n createCommandStore,\n rawClients,\n sqliteFile,\n type CommandStore,\n type RawClients,\n} from './db/command-store.js'\nimport { migrationState } from './db/migrate.js'\nimport { createLogger } from './logger.js'\nimport { buildDocumentStore, buildEventBus, buildMedia, redisUrlOf } from './platform.js'\nimport { createEventLogRepository } from './repositories/event-log.js'\nimport { buildRepositories, type SettingRow } from './repositories/index.js'\nimport { listStoredSettings, settingValues } from './settings/load.js'\nimport type { SettingValue } from './settings/resolve.js'\nimport { scrub, scrubbingLogger } from './settings/secret-set.js'\n\n/** `ok` is a check with no health semantics (config, a package, migrations); the rest are a health report's. */\nexport type DiagnosisStatus = HealthStatus | 'ok'\n\nexport interface DiagnosisCheck {\n name: string\n status: DiagnosisStatus\n detail: string\n}\n\nexport interface DiagnosisReport {\n checks: DiagnosisCheck[]\n}\n\nexport interface DiagnoseOptions {\n /** The project's adapters, one per slot whose provider is `custom`, as `createApp` takes them. */\n adapters?: InjectedAdapters\n logger?: Logger\n /** Each check's bound; `HEALTH_CHECK_TIMEOUT_MS` when not given. */\n timeoutMs?: number\n env?: NodeJS.ProcessEnv\n sqlitePath?: string\n postgresUrl?: string\n mediaRoot?: string\n /** Where the migrations journal is read; the platform's own migrations when not given. */\n migrationsRoot?: string\n}\n\nconst OWN_MIGRATIONS = fileURLToPath(new URL('../migrations', import.meta.url))\n\nconst PRIMITIVES = ['documentStore', 'eventBus', 'media'] as const\ntype PrimitiveName = (typeof PRIMITIVES)[number]\n\n/** What a primitive or a slot adapter may answer; a third-party one may lack `healthCheck`. */\ninterface Checkable {\n healthCheck?: () => Promise<HealthReport>\n}\n\ntype Outcome<T> = { ok: true; value: T } | { ok: false; detail: string }\n\n/**\n * Runs `run` within the bound. Something it opens after the bound has passed is handed to `dispose`, so a late\n * connection is not left open.\n */\nasync function within<T>(\n timeoutMs: number,\n run: () => Promise<T>,\n dispose?: (late: T) => Promise<void>,\n): Promise<Outcome<T>> {\n let timer: NodeJS.Timeout | undefined\n let timedOut = false\n // A run that throws before returning a promise is a failed outcome like a rejection, not an escape.\n const work = Promise.resolve().then(run)\n const timeout = new Promise<Outcome<T>>((resolveTimeout) => {\n timer = setTimeout(() => {\n timedOut = true\n resolveTimeout({ ok: false, detail: `timed out after ${timeoutMs} ms` })\n }, timeoutMs)\n })\n try {\n return await Promise.race([\n work.then(\n (value): Outcome<T> => ({ ok: true, value }),\n (error: unknown): Outcome<T> => ({ ok: false, detail: errorText(error) }),\n ),\n timeout,\n ])\n } finally {\n clearTimeout(timer)\n if (timedOut && dispose !== undefined) {\n // The check is already reported as timed out; a late open that fails, or a close that does, adds nothing.\n work.then(dispose).catch(() => undefined)\n }\n }\n}\n\n/** A store that did not open, held by the slot adapters that are built over one: any use of it rejects. */\nfunction unavailableCommandStore(kind: CommandStore['kind']): CommandStore {\n const refuse = () => Promise.reject(new Error('the command store is down'))\n return { kind, read: refuse, transaction: refuse, savepoint: refuse, close: async () => {} }\n}\n\n/** The raw clients of a store that did not open: any use of a client throws, as a down store's would. */\nfunction unavailableRawClients(kind: CommandStore['kind']): RawClients {\n const refuse = () => {\n throw new Error('the command store is down')\n }\n const client = new Proxy({}, { get: () => refuse })\n return kind === 'sqlite'\n ? { kind, db: client as never, raw: client as never }\n : { kind, db: client as never, pool: client as never }\n}\n\nfunction unavailableDocumentStore(): DocumentStoreAdapter {\n const refuse = () => Promise.reject(new Error('the document store is down'))\n return {\n capabilities: () => [],\n get: refuse,\n put: refuse,\n delete: refuse,\n query: refuse,\n batchGet: refuse,\n batchPut: refuse,\n replaceCollection: refuse,\n close: async () => {},\n }\n}\n\n/** A line's detail: what was checked (a provider, and where it connects), then what the check said. */\nfunction described(what: string, detail: string | undefined): string {\n return detail === undefined || detail === '' ? what : `${what}: ${detail}`\n}\n\nfunction notChecked(prerequisite: string): string {\n return `not checked: ${prerequisite} down`\n}\n\n/**\n * Checks a project without changing it: its config, the packages its providers live in, the command store and its\n * migrations, and the health of every commerce slot, the security slot and every primitive. It builds what `createApp`\n * builds, through the same registry and constructors, and nothing more: no warm-up, no relay, no sweeper, no migrator,\n * no seed, and no primitive's `initialize()` (the security adapter's makes no request). The command store is opened read-only. Every connection is closed before it returns.\n */\nexport async function diagnose(\n input: NymbalConfig,\n options: DiagnoseOptions = {},\n): Promise<DiagnosisReport> {\n const parsed = nymbalConfigSchema.safeParse(input)\n if (!parsed.success) {\n const detail = parsed.error.issues\n .map(\n (issue) => `${issue.path.length > 0 ? issue.path.join('.') : '<root>'}: ${issue.message}`,\n )\n .join('; ')\n return { checks: [{ name: 'config', status: 'down', detail }] }\n }\n const config = parsed.data\n const timeoutMs = options.timeoutMs ?? HEALTH_CHECK_TIMEOUT_MS\n const env = options.env ?? process.env\n const logger = scrubbingLogger(\n options.logger ?? createLogger({ base: { store: config.store.name } }),\n )\n const injected = options.adapters ?? {}\n const infrastructure = config.infrastructure\n const choices: Record<Slot, Choice> = {\n ...(Object.fromEntries(COMMERCE_SLOTS.map((s) => [s, config.commerce[s]])) as Record<\n CommerceSlot,\n Choice\n >),\n documentStore: infrastructure.documentStore,\n eventBus: infrastructure.eventBus,\n media: infrastructure.media,\n security: securityChoice(config),\n }\n const providers = Object.fromEntries(\n Object.entries(choices).map(([slot, choice]) => [slot, choice.provider]),\n ) as Record<Slot, string>\n\n // Each slot that resolves to a package, resolved as createApp resolves it: the package it names, or why it fails.\n const packages: DiagnosisCheck[] = []\n for (const slot of [...COMMERCE_SLOTS, ...PRIMITIVES, 'security'] as const) {\n const resolution = resolveChoice(slot, choices[slot])\n if (resolution.kind !== 'package') continue\n const found = await within(timeoutMs, () => importAdapterModule(slot, choices[slot], env))\n packages.push({\n name: `package ${slotFolder(slot)}`,\n status: found.ok ? 'ok' : 'down',\n detail: found.ok ? resolution.package : found.detail,\n })\n }\n\n const closers: Array<() => Promise<void>> = []\n let commandStore: CommandStore | undefined\n let storeCheck: DiagnosisCheck\n let migrationsCheck: DiagnosisCheck\n const storeOptions = {\n readOnly: true,\n ...(options.sqlitePath !== undefined && { sqlitePath: options.sqlitePath }),\n ...(options.postgresUrl !== undefined && { postgresUrl: options.postgresUrl }),\n }\n const postgresUrl =\n options.postgresUrl ?? (env['DATABASE_URL'] === '' ? undefined : env['DATABASE_URL'])\n const redisUrl = redisUrlOf(config, env)\n const where =\n infrastructure.commandStore === 'sqlite'\n ? `sqlite ${sqliteFile(storeOptions)}`\n : `postgres ${postgresUrl === undefined ? '(no DATABASE_URL)' : displayUrl(postgresUrl)}`\n if (infrastructure.commandStore === 'sqlite' && !existsSync(resolve(sqliteFile(storeOptions)))) {\n storeCheck = {\n name: 'command store',\n status: 'down',\n detail: `no database at ${sqliteFile(storeOptions)}: run \\`nymbal migrate\\``,\n }\n } else {\n const opened = await within(\n timeoutMs,\n async () => {\n const store = createCommandStore(config, storeOptions)\n try {\n const clients = rawClients(store)\n if (clients.kind === 'sqlite') clients.raw.prepare('SELECT 1').get()\n else await clients.pool.query('SELECT 1')\n return store\n } catch (error) {\n // The probe's error is the one reported; closing a store that never answered may fail as well.\n await store.close().catch(() => undefined)\n throw error\n }\n },\n (late) => late.close(),\n )\n if (opened.ok) {\n commandStore = opened.value\n closers.push(() => opened.value.close())\n storeCheck = { name: 'command store', status: 'healthy', detail: where }\n } else {\n storeCheck = { name: 'command store', status: 'down', detail: `${where}: ${opened.detail}` }\n }\n }\n if (commandStore === undefined) {\n migrationsCheck = { name: 'migrations', status: 'down', detail: notChecked('command store') }\n } else {\n const store = commandStore\n const state = await within(timeoutMs, () =>\n migrationState(store, { migrationsRoot: options.migrationsRoot ?? OWN_MIGRATIONS }),\n )\n migrationsCheck = !state.ok\n ? { name: 'migrations', status: 'down', detail: state.detail }\n : state.value.pending > 0\n ? {\n name: 'migrations',\n status: 'down',\n detail: `${state.value.pending} pending: run \\`nymbal migrate\\``,\n }\n : {\n name: 'migrations',\n status: 'ok',\n detail: `${state.value.applied} applied, none pending`,\n }\n }\n\n const primitiveOptions = {\n logger,\n env,\n ...(options.postgresUrl !== undefined && { postgresUrl: options.postgresUrl }),\n ...(options.mediaRoot !== undefined && { mediaRoot: options.mediaRoot }),\n }\n /** A primitive as its line names it: the provider, and the server it connects to, if any. */\n const subject = (name: PrimitiveName): string => {\n const provider = providers[name]\n const url =\n provider === 'redis' || provider === 'redis-streams'\n ? redisUrl\n : provider === 'postgres-jsonb'\n ? postgresUrl\n : undefined\n return url === undefined ? provider : `${provider} ${displayUrl(url)}`\n }\n const built: Partial<Record<PrimitiveName, Checkable>> = {}\n const primitiveFailures: Partial<Record<PrimitiveName, string>> = {}\n let documentStore: DocumentStoreAdapter | undefined\n if (infrastructure.documentStore.provider === 'postgres-jsonb' && commandStore === undefined) {\n primitiveFailures.documentStore = notChecked('command store')\n } else {\n const store = await within(\n timeoutMs,\n () => buildDocumentStore(config, primitiveOptions, logger, env),\n (late) => late.close(),\n )\n if (store.ok) {\n documentStore = store.value\n built.documentStore = store.value\n closers.unshift(() => store.value.close())\n } else {\n primitiveFailures.documentStore = described(subject('documentStore'), store.detail)\n }\n }\n const bus = await within(\n timeoutMs,\n () => buildEventBus(config, logger, env),\n (late) => late.close(),\n )\n if (bus.ok) {\n built.eventBus = bus.value\n closers.unshift(() => bus.value.close())\n } else {\n primitiveFailures.eventBus = described(subject('eventBus'), bus.detail)\n }\n const media = await within(timeoutMs, () => buildMedia(config, primitiveOptions, logger, env))\n if (media.ok) built.media = media.value\n else primitiveFailures.media = described(subject('media'), media.detail)\n\n const health = (subject: Checkable): Promise<HealthReport> => {\n if (typeof subject.healthCheck !== 'function') {\n return Promise.resolve({ status: 'degraded', detail: 'no healthCheck' })\n }\n const check = subject.healthCheck.bind(subject)\n return boundedHealthCheck(() => check(), { timeoutMs })\n }\n\n // The rows Settings hold fill each slot as createApp fills it; a store that did not open holds none.\n const stored: Outcome<SettingRow[]> =\n commandStore === undefined\n ? { ok: true, value: [] }\n : await within(timeoutMs, () => listStoredSettings(commandStore))\n /** The values Settings give `slot`'s declared fields, decrypted; a row that cannot be read fails the slot. */\n const settingsOf = async (slot: CommerceSlot): Promise<SettingValue[]> => {\n const provider = providers[slot]\n if (provider === 'custom') return []\n const declared = declaredSettings(await importAdapterModule(slot, choices[slot], env))\n if (declared.length === 0) return []\n if (!stored.ok) throw new Error(`settings not read: ${stored.detail}`)\n return settingValues(config, [{ slot, provider, declared }], stored.value, env, logger)\n }\n\n const slots: DiagnosisCheck[] = []\n const adapterLogger = logger.child({ layer: 'adapter' })\n const builderDeps = {\n config,\n logger: adapterLogger,\n sql:\n commandStore === undefined\n ? unavailableRawClients(infrastructure.commandStore)\n : rawClients(commandStore),\n repos: buildRepositories(\n commandStore ?? unavailableCommandStore(infrastructure.commandStore),\n documentStore ?? unavailableDocumentStore(),\n ),\n injected,\n }\n for (const slot of COMMERCE_SLOTS) {\n const provider = providers[slot]\n const adapter = await within(timeoutMs, async (): Promise<Checkable | null> => {\n checkInjectedSlot(config, slot, injected)\n const settings = await settingsOf(slot)\n return slot === 'payments'\n ? resolvePaymentsAdapter(config, adapterLogger, injected, settings)\n : slotBuilders({ ...builderDeps, settings })[slot]()\n })\n if (!adapter.ok) {\n slots.push({\n name: `slot ${slot}`,\n status: 'down',\n detail: described(provider, adapter.detail),\n })\n } else if (adapter.value === null) {\n slots.push({ name: `slot ${slot}`, status: 'ok', detail: provider })\n } else {\n slots.push(fromReport(`slot ${slot}`, provider, await health(adapter.value)))\n }\n }\n\n const securityAdapter = await within(timeoutMs, () =>\n resolveSecurityAdapter(config, adapterLogger, env),\n )\n slots.push(\n securityAdapter.ok\n ? fromReport('slot security', providers.security, await health(securityAdapter.value))\n : {\n name: 'slot security',\n status: 'down',\n detail: described(providers.security, securityAdapter.detail),\n },\n )\n\n const primitives: DiagnosisCheck[] = []\n for (const name of PRIMITIVES) {\n const primitive = built[name]\n if (primitive === undefined) {\n primitives.push({\n name: `primitive ${slotFolder(name)}`,\n status: 'down',\n detail: primitiveFailures[name] ?? '',\n })\n } else {\n primitives.push(\n fromReport(`primitive ${slotFolder(name)}`, subject(name), await health(primitive)),\n )\n }\n }\n\n const eventsCheck: DiagnosisCheck =\n commandStore === undefined\n ? { name: 'events', status: 'down', detail: notChecked('command store') }\n : migrationsCheck.status !== 'ok'\n ? { name: 'events', status: 'down', detail: notChecked('migrations') }\n : await eventLogCheck(commandStore, timeoutMs)\n\n for (const close of closers) {\n const closed = await within(timeoutMs, close)\n if (!closed.ok) logger.debug({ detail: closed.detail }, 'diagnose: a connection did not close')\n }\n\n const secrets = [postgresUrl, redisUrl].flatMap((url) =>\n url === undefined ? [] : connectionSecrets(url, { user: false }),\n )\n const checks = [\n { name: 'config', status: 'ok' as const, detail: 'valid' },\n ...packages,\n storeCheck,\n migrationsCheck,\n ...slots,\n ...primitives,\n eventsCheck,\n ].map((check) => ({\n ...check,\n detail: scrub(secrets.reduce((text, secret) => text.split(secret).join('***'), check.detail)),\n }))\n return { checks }\n}\n\n/** How many events show when some are dead; the rest are counted. */\nconst DEAD_SHOWN = 5\n\n/** The event log's dead events, the oldest first, and how many wait for a retry: read only. */\nasync function eventLogCheck(store: CommandStore, timeoutMs: number): Promise<DiagnosisCheck> {\n const eventLog = createEventLogRepository(store)\n const read = await within(timeoutMs, () =>\n store.read(async (tx) => ({\n dead: await eventLog.countDead(tx),\n shown: await eventLog.listDead(tx, DEAD_SHOWN),\n waiting: await eventLog.countRetrying(tx),\n })),\n )\n if (!read.ok) return { name: 'events', status: 'down', detail: read.detail }\n const { dead, shown, waiting } = read.value\n if (dead === 0) {\n return { name: 'events', status: 'ok', detail: `none dead, ${waiting} waiting to retry` }\n }\n const named = shown.map((e) => `seq ${e.seq} ${e.event.type} ${e.event.id}`)\n if (dead > shown.length) named.push(`${dead - shown.length} more`)\n return {\n name: 'events',\n status: 'degraded',\n detail: `${dead} dead: ${named.join(', ')}; ${waiting} waiting to retry`,\n }\n}\n\nfunction fromReport(name: string, what: string, report: HealthReport): DiagnosisCheck {\n return { name, status: report.status, detail: described(what, report.detail) }\n}\n","import { inArray } from 'drizzle-orm'\nimport { v7 as uuidv7 } from 'uuid'\nimport bcrypt from 'bcryptjs'\nconst { hashSync } = bcrypt\nimport type {\n DocumentStoreAdapter,\n EventBusAdapter,\n Logger,\n MediaStorage,\n NymbalEvent,\n Role,\n SearchAdapter,\n} from '@nymbalhq/types'\nimport type { NymbalConfig } from '@nymbalhq/config'\nimport { rawClients, type CommandStore } from '../db/command-store.js'\nimport { createCategoryRepository } from '../db/repositories/categories.js'\nimport { createProductRepository } from '../db/repositories/products.js'\nimport { createEventBuilder } from '../events/builder.js'\nimport { EVT_CATEGORY_CREATED, EVT_PRODUCT_CREATED, EVT_CUSTOMER_CREATED } from '@nymbalhq/types'\nimport * as sqliteSchema from '../db/schema/sqlite.js'\nimport * as postgresSchema from '../db/schema/postgres.js'\nimport { seedCategories, seedImage, seedProducts, type SeedProduct } from './data.js'\nimport { buildRepositories } from '../repositories/index.js'\nimport { READ_MODEL_NAMES, rebuild } from '../read-models/index.js'\n\nexport interface SeedDeps {\n config: NymbalConfig\n commandStore: CommandStore\n documentStore: DocumentStoreAdapter\n eventBus: EventBusAdapter\n logger: Logger\n version: string\n /**\n * When given, each product's image is generated and written here, and the product points at the stored copy\n * instead of the third-party placeholder host: a store measured or run offline then serves its own images.\n */\n media?: MediaStorage\n /** The search index to rebuild with the document store; without it the next start's rebuild fills it. */\n search?: SearchAdapter\n}\n\nexport interface SeedResult {\n categories: number\n products: number\n variants: number\n customers: number\n admins: number\n /** True when any demo row was already in the command store, so nothing was inserted. */\n alreadySeeded: boolean\n}\n\nasync function insertVariants(\n store: CommandStore,\n rows: Array<{\n id: string\n productId: string\n sku: string\n name: string\n priceMinor: number\n stock: number\n options: unknown[]\n createdAt: Date\n updatedAt: Date\n }>,\n): Promise<void> {\n if (rows.length === 0) return\n const clients = rawClients(store)\n if (clients.kind === 'sqlite') {\n const values = rows.map((r) => ({\n id: r.id,\n productId: r.productId,\n sku: r.sku,\n name: r.name,\n priceMinor: r.priceMinor,\n compareAtPriceMinor: null,\n weightGrams: null,\n dimensions: null,\n stock: r.stock,\n lowStockThreshold: 3,\n options: JSON.stringify(r.options),\n status: 'active' as const,\n createdAt: r.createdAt.toISOString(),\n updatedAt: r.updatedAt.toISOString(),\n }))\n clients.db.insert(sqliteSchema.variants).values(values).run()\n return\n }\n const values = rows.map((r) => ({\n id: r.id,\n productId: r.productId,\n sku: r.sku,\n name: r.name,\n priceMinor: r.priceMinor,\n compareAtPriceMinor: null,\n weightGrams: null,\n dimensions: null,\n stock: r.stock,\n lowStockThreshold: 3,\n options: r.options,\n status: 'active' as const,\n createdAt: r.createdAt,\n updatedAt: r.updatedAt,\n }))\n await clients.db.insert(postgresSchema.variants).values(values)\n}\n\nasync function insertProductCategories(\n store: CommandStore,\n rows: Array<{ productId: string; categoryId: string }>,\n): Promise<void> {\n if (rows.length === 0) return\n const clients = rawClients(store)\n if (clients.kind === 'sqlite') {\n clients.db.insert(sqliteSchema.productCategories).values(rows).run()\n return\n }\n await clients.db.insert(postgresSchema.productCategories).values(rows)\n}\n\n/**\n * Any demo row (category slug, product slug, seeded customer email) means an earlier seed ran, in full or in part.\n * Each is unique, so inserting the demo again would fail on the first collision: skip instead.\n */\nasync function demoRowsPresent(store: CommandStore, emails: string[]): Promise<boolean> {\n const categorySlugs = seedCategories.map((c) => c.slug)\n const productSlugs = seedProducts.map((p) => p.slug)\n const clients = rawClients(store)\n if (clients.kind === 'sqlite') {\n const { categories, products, customers } = sqliteSchema\n return (\n clients.db\n .select({ id: categories.id })\n .from(categories)\n .where(inArray(categories.slug, categorySlugs))\n .limit(1)\n .all().length > 0 ||\n clients.db\n .select({ id: products.id })\n .from(products)\n .where(inArray(products.slug, productSlugs))\n .limit(1)\n .all().length > 0 ||\n clients.db\n .select({ id: customers.id })\n .from(customers)\n .where(inArray(customers.email, emails))\n .limit(1)\n .all().length > 0\n )\n }\n const { categories, products, customers } = postgresSchema\n const [category, product, customer] = await Promise.all([\n clients.db\n .select({ id: categories.id })\n .from(categories)\n .where(inArray(categories.slug, categorySlugs))\n .limit(1),\n clients.db\n .select({ id: products.id })\n .from(products)\n .where(inArray(products.slug, productSlugs))\n .limit(1),\n clients.db\n .select({ id: customers.id })\n .from(customers)\n .where(inArray(customers.email, emails))\n .limit(1),\n ])\n return category.length > 0 || product.length > 0 || customer.length > 0\n}\n\nasync function insertCustomer(\n store: CommandStore,\n row: {\n id: string\n email: string\n passwordHash: string\n firstName: string\n lastName: string\n roles?: Role[]\n createdAt: Date\n updatedAt: Date\n },\n): Promise<void> {\n const roles = row.roles ?? ['customer']\n const clients = rawClients(store)\n if (clients.kind === 'sqlite') {\n clients.db\n .insert(sqliteSchema.customers)\n .values({\n id: row.id,\n email: row.email,\n passwordHash: row.passwordHash,\n firstName: row.firstName,\n lastName: row.lastName,\n phone: '',\n addresses: '[]',\n orderCount: 0,\n totalSpentMinor: 0,\n metadata: '{}',\n roles: JSON.stringify(roles),\n requiresPasswordReset: false,\n createdAt: row.createdAt.toISOString(),\n updatedAt: row.updatedAt.toISOString(),\n })\n .run()\n return\n }\n await clients.db.insert(postgresSchema.customers).values({\n id: row.id,\n email: row.email,\n passwordHash: row.passwordHash,\n firstName: row.firstName,\n lastName: row.lastName,\n phone: '',\n addresses: [],\n orderCount: 0,\n totalSpentMinor: 0,\n metadata: {},\n roles,\n requiresPasswordReset: false,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n })\n}\n\nfunction failedOf(err: unknown): unknown {\n return (err as { context?: { failed?: unknown } }).context?.failed ?? []\n}\n\nexport async function runSeed(deps: SeedDeps): Promise<SeedResult> {\n const { config, commandStore, documentStore, eventBus, logger, version } = deps\n const categoryRepo = createCategoryRepository(commandStore)\n const productRepo = createProductRepository(commandStore)\n const makeEvent = createEventBuilder({\n storeId: config.store.name,\n environment: (process.env.NODE_ENV === 'production' ? 'production' : 'development') as\n | 'production'\n | 'development',\n version,\n source: 'nymbal-seed',\n })\n\n const demoEmail = 'demo@nymbal.dev'\n const adminEmail = process.env['NYMBAL_ADMIN_EMAIL'] ?? 'admin@nymbal.local'\n if (await demoRowsPresent(commandStore, [demoEmail, adminEmail])) {\n logger.info({}, 'Demo content already present, seed skipped')\n return { categories: 0, products: 0, variants: 0, customers: 0, admins: 0, alreadySeeded: true }\n }\n\n const now = new Date()\n\n // Categories\n const categoryInserts = seedCategories.map((c, i) => ({\n id: uuidv7(),\n slug: c.slug,\n name: c.name,\n description: c.description,\n parentId: null,\n position: i,\n createdAt: now,\n }))\n await categoryRepo.insertMany(categoryInserts)\n const categoryBySlug = new Map(categoryInserts.map((c) => [c.slug, c]))\n\n const imageUrls = new Map<string, string>()\n if (deps.media !== undefined) {\n for (const p of seedProducts) {\n const { url } = await deps.media.put(`seed/${p.slug}.svg`, seedImage(p), 'image/svg+xml')\n imageUrls.set(p.slug, url)\n }\n }\n\n // Products\n const productInserts = seedProducts.map((p) => ({\n id: uuidv7(),\n slug: p.slug,\n name: p.title,\n description: p.description,\n shortDescription: '',\n status: 'active' as const,\n type: 'simple' as const,\n seoTitle: p.title,\n seoDescription: p.description.slice(0, 160),\n media: [{ url: imageUrls.get(p.slug) ?? p.imageUrl, altText: p.title, position: 0 }],\n metadata: {},\n createdAt: now,\n updatedAt: now,\n }))\n await productRepo.insertMany(productInserts)\n\n // Variants — one per product (simple type)\n const variantInserts = productInserts.map((p, i) => {\n const seed = seedProducts[i] as SeedProduct\n return {\n id: uuidv7(),\n productId: p.id,\n sku: p.slug.toUpperCase().replaceAll('-', '_'),\n name: 'Default',\n priceMinor: seed.priceMinor,\n stock: 25,\n options: [],\n createdAt: now,\n updatedAt: now,\n }\n })\n await insertVariants(commandStore, variantInserts)\n\n // Product ↔ Category joins\n const joinRows = productInserts.map((p, i) => {\n const seed = seedProducts[i] as SeedProduct\n const cat = categoryBySlug.get(seed.categorySlug)\n if (!cat) throw new Error(`Seed references unknown category: ${seed.categorySlug}`)\n return { productId: p.id, categoryId: cat.id }\n })\n await insertProductCategories(commandStore, joinRows)\n\n // Demo customer — password: nymbal\n const demoCustomer = {\n id: uuidv7(),\n email: demoEmail,\n passwordHash: hashSync('nymbal', 10),\n firstName: 'Demo',\n lastName: 'User',\n createdAt: now,\n updatedAt: now,\n }\n await insertCustomer(commandStore, demoCustomer)\n\n // Admin user — email and password from env, defaults for dev\n const adminPassword = process.env['NYMBAL_ADMIN_PASSWORD'] ?? 'nymbal-admin-dev'\n const adminRoles: Role[] = ['admin']\n const adminCustomer = {\n id: uuidv7(),\n email: adminEmail,\n passwordHash: hashSync(adminPassword, 10),\n firstName: 'Admin',\n lastName: 'User',\n roles: adminRoles,\n createdAt: now,\n updatedAt: now,\n }\n await insertCustomer(commandStore, adminCustomer)\n\n // Emit events\n const events = [\n ...categoryInserts.map((c) =>\n makeEvent(EVT_CATEGORY_CREATED, {\n category: {\n id: c.id,\n parentId: c.parentId,\n name: c.name,\n slug: c.slug,\n description: c.description,\n position: c.position,\n createdAt: now.toISOString(),\n },\n }),\n ),\n ...productInserts.map((p, i) => {\n const v = variantInserts[i]!\n const seed = seedProducts[i] as SeedProduct\n const cat = categoryBySlug.get(seed.categorySlug)!\n return makeEvent(EVT_PRODUCT_CREATED, {\n product: {\n id: p.id,\n slug: p.slug,\n name: p.name,\n description: p.description,\n shortDescription: p.shortDescription,\n status: p.status,\n type: p.type,\n seoTitle: p.seoTitle,\n seoDescription: p.seoDescription,\n media: p.media,\n metadata: p.metadata,\n createdAt: now.toISOString(),\n updatedAt: now.toISOString(),\n variants: [\n {\n id: v.id,\n productId: p.id,\n sku: v.sku,\n name: v.name,\n priceMinor: v.priceMinor,\n compareAtPriceMinor: null,\n weightGrams: null,\n dimensions: null,\n stock: v.stock,\n lowStockThreshold: 3,\n options: v.options,\n status: 'active' as const,\n createdAt: now.toISOString(),\n updatedAt: now.toISOString(),\n },\n ],\n categoryIds: [cat.id],\n },\n })\n }),\n makeEvent(EVT_CUSTOMER_CREATED, {\n customerId: demoCustomer.id,\n email: demoCustomer.email,\n }),\n makeEvent(EVT_CUSTOMER_CREATED, {\n customerId: adminCustomer.id,\n email: adminCustomer.email,\n }),\n ]\n // The seed's events are not in the log, so nothing retries them: a handler that fails on one (a welcome mail the\n // mail host refuses) is reported and the seed goes on; its rows are committed, and the rebuild below projects them.\n const failures: Array<{ eventId: string; eventType: string; failed: unknown }> = []\n for (const event of events as NymbalEvent<unknown>[]) {\n try {\n await eventBus.publish(event)\n } catch (err) {\n if ((err as { code?: unknown } | null)?.code !== 'adapter.handler_failed') throw err\n failures.push({ eventId: event.id, eventType: event.type, failed: failedOf(err) })\n }\n }\n if (failures.length > 0) {\n logger.warn({ failures }, 'seed events whose handlers failed; they are not retried')\n }\n\n logger.info({ adminEmail }, 'Admin user seeded')\n if (!process.env['NYMBAL_ADMIN_EMAIL']) {\n console.log(\n `Admin seeded: ${adminEmail} / ${adminPassword} (change NYMBAL_ADMIN_PASSWORD to override)`,\n )\n }\n\n logger.info(\n {\n categories: categoryInserts.length,\n products: productInserts.length,\n variants: variantInserts.length,\n customers: 1,\n admins: 1,\n },\n 'Seed complete',\n )\n\n const search = deps.search\n await rebuild(\n search === undefined ? READ_MODEL_NAMES.filter((name) => name !== 'search') : READ_MODEL_NAMES,\n {\n config,\n store: commandStore,\n repos: buildRepositories(commandStore, documentStore),\n documentStore,\n ...(search !== undefined && { search }),\n logger,\n },\n )\n\n return {\n categories: categoryInserts.length,\n products: productInserts.length,\n variants: variantInserts.length,\n customers: 1,\n admins: 1,\n alreadySeeded: false,\n }\n}\n","export interface SeedCategory {\n slug: string\n name: string\n description: string\n}\n\nexport interface SeedProduct {\n slug: string\n title: string\n description: string\n priceMinor: number\n categorySlug: string\n imageUrl: string\n}\n\nexport const seedCategories: SeedCategory[] = [\n {\n slug: 'apparel',\n name: 'Apparel',\n description: 'Everyday clothing and accessories',\n },\n { slug: 'home', name: 'Home', description: 'Homeware, decor, and kitchen essentials' },\n {\n slug: 'electronics',\n name: 'Electronics',\n description: 'Gadgets, audio, and computing accessories',\n },\n { slug: 'books', name: 'Books', description: 'Fiction, non-fiction, and reference' },\n]\n\nfunction img(seed: string): string {\n return `https://picsum.photos/seed/${encodeURIComponent(seed)}/600/600`\n}\n\nexport const seedProducts: SeedProduct[] = [\n // Apparel — 6\n { slug: 'merino-crew', title: 'Merino Crew Sweater', description: 'Midweight merino wool, unisex fit.', priceMinor: 8900, categorySlug: 'apparel', imageUrl: img('merino-crew') },\n { slug: 'organic-tee', title: 'Organic Cotton Tee', description: 'Heavyweight organic cotton, pre-washed.', priceMinor: 2400, categorySlug: 'apparel', imageUrl: img('organic-tee') },\n { slug: 'selvedge-denim', title: 'Selvedge Denim Jeans', description: '14oz Japanese selvedge, straight leg.', priceMinor: 14500, categorySlug: 'apparel', imageUrl: img('selvedge-denim') },\n { slug: 'runner-socks', title: 'Runner Socks (3-pack)', description: 'Moisture-wicking, cushioned heel.', priceMinor: 1800, categorySlug: 'apparel', imageUrl: img('runner-socks') },\n { slug: 'wool-beanie', title: 'Ribbed Wool Beanie', description: 'Hand-knit in Scotland, one size.', priceMinor: 3200, categorySlug: 'apparel', imageUrl: img('wool-beanie') },\n { slug: 'leather-belt', title: 'Bridle Leather Belt', description: 'Full-grain English bridle leather.', priceMinor: 6500, categorySlug: 'apparel', imageUrl: img('leather-belt') },\n\n // Home — 6\n { slug: 'ceramic-mug', title: 'Stoneware Mug', description: 'Hand-thrown stoneware, 350ml.', priceMinor: 1900, categorySlug: 'home', imageUrl: img('ceramic-mug') },\n { slug: 'linen-sheets', title: 'Washed Linen Sheet Set', description: 'French linen, stonewashed for softness.', priceMinor: 17900, categorySlug: 'home', imageUrl: img('linen-sheets') },\n { slug: 'cast-iron-pan', title: 'Cast Iron Skillet 12\"', description: 'Pre-seasoned, made in the USA.', priceMinor: 7900, categorySlug: 'home', imageUrl: img('cast-iron-pan') },\n { slug: 'soy-candle', title: 'Soy Candle — Fig & Cedar', description: 'Hand-poured, 50hr burn time.', priceMinor: 3400, categorySlug: 'home', imageUrl: img('soy-candle') },\n { slug: 'walnut-board', title: 'Walnut Cutting Board', description: 'End-grain walnut, oiled finish.', priceMinor: 8900, categorySlug: 'home', imageUrl: img('walnut-board') },\n { slug: 'wool-throw', title: 'Lambswool Throw', description: 'Welsh-woven lambswool, 130×180cm.', priceMinor: 11500, categorySlug: 'home', imageUrl: img('wool-throw') },\n\n // Electronics — 6\n { slug: 'wireless-earbuds', title: 'Wireless Earbuds', description: 'Active noise cancellation, 30hr case.', priceMinor: 14900, categorySlug: 'electronics', imageUrl: img('wireless-earbuds') },\n { slug: 'mechanical-keyboard', title: '75% Mechanical Keyboard', description: 'Hot-swap switches, PBT keycaps.', priceMinor: 16500, categorySlug: 'electronics', imageUrl: img('mechanical-keyboard') },\n { slug: 'portable-ssd', title: 'Portable SSD 1TB', description: 'USB-C, 1050MB/s read.', priceMinor: 11900, categorySlug: 'electronics', imageUrl: img('portable-ssd') },\n { slug: 'desk-lamp', title: 'Bias Desk Lamp', description: 'Tunable white, monitor-friendly glare shield.', priceMinor: 9800, categorySlug: 'electronics', imageUrl: img('desk-lamp') },\n { slug: 'usb-c-hub', title: '7-in-1 USB-C Hub', description: 'HDMI 4K60, 100W PD pass-through.', priceMinor: 5900, categorySlug: 'electronics', imageUrl: img('usb-c-hub') },\n { slug: 'bluetooth-speaker', title: 'Portable Bluetooth Speaker', description: 'IPX7 waterproof, 20hr battery.', priceMinor: 8900, categorySlug: 'electronics', imageUrl: img('bluetooth-speaker') },\n\n // Books — 6\n { slug: 'designing-data-intensive-applications', title: 'Designing Data-Intensive Applications', description: 'Martin Kleppmann’s canonical guide to modern data systems.', priceMinor: 3600, categorySlug: 'books', imageUrl: img('ddia') },\n { slug: 'the-pragmatic-programmer', title: 'The Pragmatic Programmer (20th anniversary)', description: 'Hunt & Thomas on the craft of software.', priceMinor: 3200, categorySlug: 'books', imageUrl: img('pragprog') },\n { slug: 'shape-up', title: 'Shape Up', description: 'Stop running in circles — ship work that matters.', priceMinor: 2500, categorySlug: 'books', imageUrl: img('shapeup') },\n { slug: 'the-manager-path', title: 'The Manager’s Path', description: 'Camille Fournier on engineering leadership.', priceMinor: 2800, categorySlug: 'books', imageUrl: img('manager-path') },\n { slug: 'accelerate', title: 'Accelerate', description: 'The science of lean software and DevOps.', priceMinor: 2400, categorySlug: 'books', imageUrl: img('accelerate') },\n { slug: 'working-effectively-with-legacy-code', title: 'Working Effectively with Legacy Code', description: 'Michael Feathers on rescuing complex codebases.', priceMinor: 3400, categorySlug: 'books', imageUrl: img('legacy-code') },\n]\n\nconst escapeXml = (text: string): string =>\n text.replace(/[<>&'\"]/g, (c) => `&#${c.charCodeAt(0)};`)\n\n/** A 600×600 placeholder for a seed product, its colour derived from the slug, so no image host is needed. */\nexport function seedImage(product: SeedProduct): Uint8Array {\n let hash = 0\n for (const char of product.slug) hash = (hash * 31 + char.charCodeAt(0)) >>> 0\n const hue = hash % 360\n const svg = `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"600\" height=\"600\" viewBox=\"0 0 600 600\"><rect width=\"600\" height=\"600\" fill=\"hsl(${hue} 45% 82%)\"/><circle cx=\"300\" cy=\"260\" r=\"120\" fill=\"hsl(${hue} 40% 62%)\"/><text x=\"300\" y=\"480\" font-family=\"system-ui,sans-serif\" font-size=\"32\" text-anchor=\"middle\" fill=\"hsl(${hue} 40% 22%)\">${escapeXml(product.title)}</text></svg>`\n return new TextEncoder().encode(svg)\n}\n","import type { NymbalConfig } from '@nymbalhq/config'\nimport type { Logger } from '@nymbalhq/types'\nimport { createCommandStore, rawClients } from '../db/command-store.js'\nimport { slotBuilders, type InjectedAdapters } from '../adapters/registry.js'\nimport { buildDocumentStore } from '../platform.js'\nimport { buildRepositories } from '../repositories/index.js'\nimport { loadBootSettings } from '../settings/load.js'\nimport type { RebuildDeps } from './model.js'\n\nexport interface OpenReadModelsOptions {\n logger: Logger\n /** The project's own adapters, for a `custom` search slot. */\n adapters?: InjectedAdapters\n sqlitePath?: string\n postgresUrl?: string\n env?: NodeJS.ProcessEnv\n}\n\n/**\n * What a rebuild outside the server needs, built as `createApp` builds it: the command store (writable), the document\n * store and the search adapter. No bus, relay, sweeper or other slot. `close()` closes what it opened.\n */\nexport async function openReadModels(\n config: NymbalConfig,\n options: OpenReadModelsOptions,\n): Promise<{ deps: RebuildDeps; close(): Promise<void> }> {\n const { logger } = options\n const env = options.env ?? process.env\n const storage = {\n ...(options.sqlitePath !== undefined && { sqlitePath: options.sqlitePath }),\n ...(options.postgresUrl !== undefined && { postgresUrl: options.postgresUrl }),\n }\n const settings = await loadBootSettings(config, { storage, env, logger })\n const store = createCommandStore(config, storage)\n const closers: Array<() => Promise<void>> = [() => store.close()]\n const close = async () => {\n for (const c of closers.splice(0).reverse()) await c()\n }\n try {\n const documentStore = await buildDocumentStore(config, { ...storage, logger, env }, logger, env)\n closers.push(() => documentStore.close())\n if (config.infrastructure.documentStore.provider === 'postgres-jsonb')\n await documentStore.initialize?.()\n const repos = buildRepositories(store, documentStore)\n const search = await slotBuilders({\n config,\n logger: logger.child({ layer: 'adapter' }),\n sql: rawClients(store),\n repos,\n settings: settings.values,\n ...(options.adapters !== undefined && { injected: options.adapters }),\n }).search()\n return { deps: { config, store, repos, documentStore, search, logger }, close }\n } catch (error) {\n await close()\n throw error\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,QAAAA,aAAY;AAErB;AAAA,EACE;AAAA,OAKK;;;ACRP,SAAS,cAAc,sBAAsB;AAmBtC,IAAM,wBAAN,MAA4D;AAAA,EACxD,QAAQ,oBAAI,IAAgC;AAAA,EAC5C;AAAA,EACA;AAAA,EAET,YAAY,UAAwC,CAAC,GAAG;AACtD,SAAK,OAAO,QAAQ,OAAO,KAAK;AAChC,UAAM,WAAW,QAAQ,mBAAmB;AAC5C,QAAI,WAAW,GAAG;AAChB,WAAK,cAAc,YAAY,MAAM,KAAK,OAAO,GAAG,QAAQ;AAC5D,WAAK,YAAY,QAAQ;AAAA,IAC3B,OAAO;AACL,WAAK,cAAc;AAAA,IACrB;AAAA,EAC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EAAE,OAAO,UAAU,CAAC;AAAA,MACzC,KAAK,WAAW,KAAK;AAAA,MACrB;AAAA,MACA,UAAU,SAAS;AAAA,MACnB,GAAI,QAAQ,aAAa,UAAa,EAAE,UAAU,QAAQ,SAAS;AAAA,IACrE,CAAC,EAAE,OAAO;AACV,WAAO,EAAE,MAAM,EAAE,QAAQ,OAAO,OAAO,eAAe,QAAAA,SAAQ,OAAO,GAAG,MAAM;AAAA,EAChF,SAAS,OAAO;AACd,UAAM,MAAM;AACZ,UAAM;AAAA,EACR;AACF;","names":["join","entries","events","join","resolve","resolve","rows","products","row","rows","categories","eq","parseJson","parseJson","createProductRepository","col","row","eq","products","t","rows","base","filtered","asc","eq","parseJson","row","eq","variants","rows","asc","asc","eq","gt","createCategoryRepository","row","eq","categories","t","rows","gt","asc","and","eq","productCategories","and","eq","rows","asc","eq","gt","sql","parseJson","row","eq","customers","t","rows","gt","asc","sql","and","eq","refreshTokens","row","eq","db","and","result","and","asc","eq","gt","parseJson","row","eq","orders","o","and","rows","t","gt","asc","base","filtered","asc","eq","orderHistory","rows","eq","asc","and","asc","eq","r","rows","asc","orderRefunds","and","eq","row","sql","row","sql","orderSequences","and","asc","eq","inArray","orderAccessKeys","and","eq","t","asc","inArray","eq","lt","inventoryReservations","row","eq","rows","lt","desc","eq","stockAdjustments","rows","eq","desc","and","desc","eq","lt","row","eq","reviews","t","conds","lt","and","rows","desc","and","eq","lt","processedEvents","and","eq","result","lt","and","asc","eq","gt","gte","inArray","isNull","lt","or","sql","events","or","sql","gte","lt","and","asc","isNull","gt","inArray","eq","row","result","and","asc","eq","gt","isNull","lt","lte","sql","parseJson","sql","and","isNull","gt","lt","carts","row","eq","lte","t","rows","asc","and","eq","inArray","sql","alertSubscriptions","row","sql","eq","and","inArray","eq","emailSuppressions","result","eq","eq","orderShipments","eq","createProductRepository","createCategoryRepository","uuidv7","events","resolve","retryAt","events","EVT_CATEGORY_CREATED","EVT_CATEGORY_DELETED","EVT_CATEGORY_UPDATED","variants","products","EVT_CATEGORY_CREATED","EVT_CATEGORY_UPDATED","EVT_CATEGORY_DELETED","EVT_ORDER_PAID","EVT_ORDER_PARTIALLY_REFUNDED","EVT_ORDER_REFUNDED","EVT_ORDER_PAID","EVT_ORDER_REFUNDED","EVT_ORDER_PARTIALLY_REFUNDED","products","uuidv7","EVT_CUSTOMER_CREATED","EVT_ORDER_PAID","EVT_ORDER_SHIPPED","uuidv7","EVT_ORDER_PAID","EVT_ORDER_SHIPPED","EVT_CUSTOMER_CREATED","EVT_PRODUCT_CREATED","EVT_PRODUCT_DELETED","EVT_PRODUCT_UPDATED","search","EVT_PRODUCT_CREATED","EVT_PRODUCT_UPDATED","EVT_PRODUCT_DELETED","EVT_ORDER_DELIVERED","reviews","EVT_ORDER_DELIVERED","row","product","orders","orders","DEFAULT_JWT_SECRET","ConfigError","ConfigError","HEALTH_CHECK_TIMEOUT_MS","HEALTH_CHECK_TIMEOUT_MS","categories","customers","orders","orders","customers","search","EVT_CART_ABANDONED","carts","EVT_CART_ABANDONED","ConfigError","DEFAULT_JWT_SECRET","options","registerAllRoutes","resolve","boundedHealthCheck","errorText","HEALTH_CHECK_TIMEOUT_MS","errorText","HEALTH_CHECK_TIMEOUT_MS","resolve","subject","boundedHealthCheck","text","inArray","uuidv7","EVT_CATEGORY_CREATED","EVT_PRODUCT_CREATED","EVT_CUSTOMER_CREATED","text","values","variants","productCategories","categories","products","customers","inArray","failedOf","uuidv7","events","EVT_CATEGORY_CREATED","EVT_PRODUCT_CREATED","EVT_CUSTOMER_CREATED","search","search"]}
|