@nymbalhq/platform 1.0.0 → 1.1.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/index.js CHANGED
@@ -44,13 +44,103 @@ import {
44
44
  registerAllRoutes,
45
45
  routeSchemas,
46
46
  settlementOf
47
- } from "./chunk-74KODSYJ.js";
47
+ } from "./chunk-2GFZHF5W.js";
48
48
  import "./chunk-PZ5AY32C.js";
49
49
 
50
+ // src/platform.ts
51
+ import { join as join4 } from "path";
52
+ import {
53
+ ConfigError as ConfigError3
54
+ } from "@nymbalhq/types";
55
+
56
+ // src/adapters/loader.ts
57
+ import { existsSync } from "fs";
58
+ import { join } from "path";
59
+ import { ConfigError } from "@nymbalhq/types";
60
+ var PROVIDER_PACKAGES = {
61
+ payments: { stripe: { package: "@nymbalhq/adapter-stripe", sdk: "stripe" } },
62
+ ai: { anthropic: { package: "@nymbalhq/adapter-anthropic", sdk: "@anthropic-ai/sdk" } },
63
+ email: { smtp: { package: "@nymbalhq/adapter-smtp", sdk: "nodemailer" } },
64
+ documentStore: {
65
+ redis: { package: "@nymbalhq/doc-store-redis", sdk: "ioredis" },
66
+ "postgres-jsonb": { package: "@nymbalhq/doc-store-postgres-jsonb", sdk: "pg" }
67
+ },
68
+ eventBus: {
69
+ "redis-streams": { package: "@nymbalhq/event-bus-redis-streams", sdk: "ioredis" }
70
+ },
71
+ media: { s3: { package: "@nymbalhq/media-s3", sdk: "@aws-sdk/client-s3" } }
72
+ };
73
+ var INFRASTRUCTURE_SLOTS = /* @__PURE__ */ new Set(["documentStore", "eventBus", "media"]);
74
+ function choiceOf(slot, provider) {
75
+ return INFRASTRUCTURE_SLOTS.has(slot) ? `infrastructure.${slot} '${provider}'` : `${slot}.provider '${provider}'`;
76
+ }
77
+ var INSTALL_VERBS = {
78
+ npm: "npm install",
79
+ pnpm: "pnpm add",
80
+ yarn: "yarn add",
81
+ bun: "bun add"
82
+ };
83
+ var LOCKFILES = [
84
+ ["pnpm-lock.yaml", "pnpm"],
85
+ ["yarn.lock", "yarn"],
86
+ ["bun.lock", "bun"],
87
+ ["bun.lockb", "bun"],
88
+ ["package-lock.json", "npm"]
89
+ ];
90
+ function packageManager(env, cwd) {
91
+ const agent = env["npm_config_user_agent"]?.split("/")[0];
92
+ if (agent !== void 0 && agent in INSTALL_VERBS) return agent;
93
+ for (const [file, pm] of LOCKFILES) {
94
+ if (existsSync(join(cwd, file))) return pm;
95
+ }
96
+ return "npm";
97
+ }
98
+ function installLine(packages, env, cwd) {
99
+ return [INSTALL_VERBS[packageManager(env, cwd)], ...packages].join(" ");
100
+ }
101
+ function packageOf(specifier) {
102
+ const parts = specifier.split("/");
103
+ return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
104
+ }
105
+ function missingPackage(error) {
106
+ if (error?.code !== "ERR_MODULE_NOT_FOUND") return null;
107
+ const match = /Cannot find (?:package|module) '([^']+)'/.exec(String(error.message));
108
+ return match?.[1] === void 0 ? null : packageOf(match[1]);
109
+ }
110
+ async function importProviderPackage(slot, provider, env) {
111
+ const entry = PROVIDER_PACKAGES[slot]?.[provider];
112
+ if (entry === void 0) return void 0;
113
+ let mod;
114
+ try {
115
+ mod = await import(entry.package);
116
+ } catch (error) {
117
+ const missing = missingPackage(error);
118
+ if (missing !== entry.package && missing !== entry.sdk) throw error;
119
+ const install = installLine([entry.package, entry.sdk], env, process.cwd());
120
+ throw new ConfigError(`${choiceOf(slot, provider)} needs ${entry.package}: ${install}`, {
121
+ code: "adapter.package_missing",
122
+ cause: error,
123
+ context: { slot, provider, missing, install }
124
+ });
125
+ }
126
+ if (typeof mod.createAdapter !== "function") {
127
+ throw new ConfigError(`${entry.package} exports no createAdapter(ctx)`, {
128
+ code: "adapter.package_invalid",
129
+ context: { slot, provider, package: entry.package }
130
+ });
131
+ }
132
+ return mod;
133
+ }
134
+ async function loadProviderAdapter(slot, provider, ctx) {
135
+ const mod = await importProviderPackage(slot, provider, ctx.env);
136
+ if (mod === void 0) return void 0;
137
+ return await mod.createAdapter({ ...ctx, slot });
138
+ }
139
+
50
140
  // src/db/command-store.ts
51
141
  import { AsyncLocalStorage } from "async_hooks";
52
142
  import { envOptional } from "@nymbalhq/config";
53
- import { AdapterError, ConfigError } from "@nymbalhq/types";
143
+ import { AdapterError, ConfigError as ConfigError2 } from "@nymbalhq/types";
54
144
  import BetterSqlite3 from "better-sqlite3";
55
145
  import pg from "pg";
56
146
  import { drizzle as drizzleSqlite } from "drizzle-orm/better-sqlite3";
@@ -79,6 +169,11 @@ var Scope = class {
79
169
  };
80
170
  var context = new AsyncLocalStorage();
81
171
  var rawByStore = /* @__PURE__ */ new WeakMap();
172
+ var turnByRaw = /* @__PURE__ */ new WeakMap();
173
+ async function sqliteTurn(raw, fn) {
174
+ const turn = turnByRaw.get(raw);
175
+ return turn === void 0 ? fn() : turn(fn);
176
+ }
82
177
  function liveScope(tx) {
83
178
  if (!(tx instanceof Scope)) {
84
179
  throw new TypeError("expected a handle from CommandStore.read or CommandStore.transaction");
@@ -115,7 +210,7 @@ function joinable(owner) {
115
210
  const scope = context.getStore();
116
211
  return scope !== void 0 && scope.owner === owner && !scope.settled ? scope : void 0;
117
212
  }
118
- async function join(scope, fn) {
213
+ async function join2(scope, fn) {
119
214
  if (!scope.writable) {
120
215
  throw new Error(
121
216
  "CommandStore.transaction() was called inside CommandStore.read(); open the transaction first"
@@ -217,8 +312,8 @@ function createQueue() {
217
312
  async acquire() {
218
313
  const previous = tail;
219
314
  let release;
220
- tail = new Promise((resolve2) => {
221
- release = resolve2;
315
+ tail = new Promise((resolve4) => {
316
+ release = resolve4;
222
317
  });
223
318
  await previous;
224
319
  return release;
@@ -239,18 +334,23 @@ async function beginImmediate(raw) {
239
334
  throw error;
240
335
  }
241
336
  }
242
- await new Promise((resolve2) => setTimeout(resolve2, pauseMs));
337
+ await new Promise((resolve4) => setTimeout(resolve4, pauseMs));
243
338
  }
244
339
  } finally {
245
340
  raw.pragma(`busy_timeout = ${SQLITE_BUSY_WAIT_MS}`);
246
341
  }
247
342
  }
343
+ function sqliteFile(options = {}) {
344
+ return options.sqlitePath ?? envOptional("NYMBAL_SQLITE_PATH") ?? "./nymbal.db";
345
+ }
248
346
  function createCommandStore(config, options = {}) {
249
347
  if (config.infrastructure.commandStore === "sqlite") {
250
- const path = options.sqlitePath ?? envOptional("NYMBAL_SQLITE_PATH") ?? "./nymbal.db";
251
- const raw = new BetterSqlite3(path);
252
- raw.pragma("journal_mode = WAL");
253
- raw.pragma("foreign_keys = ON");
348
+ const path = sqliteFile(options);
349
+ const raw = options.readOnly ? new BetterSqlite3(path, { readonly: true, fileMustExist: true }) : new BetterSqlite3(path);
350
+ if (!options.readOnly) {
351
+ raw.pragma("journal_mode = WAL");
352
+ raw.pragma("foreign_keys = ON");
353
+ }
254
354
  const db = drizzleSqlite(raw, { schema: sqlite_exports });
255
355
  const client = { kind: "sqlite", db };
256
356
  const queue = createQueue();
@@ -264,7 +364,7 @@ function createCommandStore(config, options = {}) {
264
364
  },
265
365
  async transaction(fn) {
266
366
  const scope = joinable(owner);
267
- if (scope !== void 0) return join(scope, fn);
367
+ if (scope !== void 0) return join2(scope, fn);
268
368
  const release = await queue.acquire();
269
369
  return runTransaction(
270
370
  owner,
@@ -294,17 +394,29 @@ function createCommandStore(config, options = {}) {
294
394
  }
295
395
  };
296
396
  rawByStore.set(store, { kind: "sqlite", db, raw });
397
+ turnByRaw.set(raw, async (fn) => {
398
+ if (joinable(owner) !== void 0) return fn();
399
+ const release = await queue.acquire();
400
+ try {
401
+ return fn();
402
+ } finally {
403
+ release();
404
+ }
405
+ });
297
406
  return store;
298
407
  }
299
408
  if (config.infrastructure.commandStore === "postgres") {
300
409
  const connectionString = options.postgresUrl ?? envOptional("DATABASE_URL");
301
410
  if (!connectionString) {
302
- throw new ConfigError(
411
+ throw new ConfigError2(
303
412
  "commandStore=postgres requires DATABASE_URL to be set (or pass postgresUrl option).",
304
413
  { context: { commandStore: "postgres" } }
305
414
  );
306
415
  }
307
- const pool = new pg.Pool({ connectionString });
416
+ const pool = new pg.Pool({
417
+ connectionString,
418
+ ...options.readOnly && { options: "-c default_transaction_read_only=on" }
419
+ });
308
420
  const db = drizzlePg(pool, { schema: postgres_exports });
309
421
  const owner = {};
310
422
  const connect = async () => {
@@ -324,7 +436,7 @@ function createCommandStore(config, options = {}) {
324
436
  },
325
437
  async transaction(fn) {
326
438
  const scope = joinable(owner);
327
- if (scope !== void 0) return join(scope, fn);
439
+ if (scope !== void 0) return join2(scope, fn);
328
440
  const { client, connection } = await connect();
329
441
  return runTransaction(
330
442
  owner,
@@ -367,16 +479,13 @@ function createCommandStore(config, options = {}) {
367
479
  rawByStore.set(store, { kind: "postgres", db, pool });
368
480
  return store;
369
481
  }
370
- throw new ConfigError(`Unsupported commandStore: ${String(config.infrastructure.commandStore)}`, {
482
+ throw new ConfigError2(`Unsupported commandStore: ${String(config.infrastructure.commandStore)}`, {
371
483
  context: { commandStore: config.infrastructure.commandStore }
372
484
  });
373
485
  }
374
486
 
375
- // src/document-store/factory.ts
376
- import { ConfigError as ConfigError2 } from "@nymbalhq/types";
377
-
378
487
  // src/document-store/in-memory.ts
379
- import { AdapterError as AdapterError2, ValidationError } from "@nymbalhq/types";
488
+ import { AdapterError as AdapterError2, queryDocuments } from "@nymbalhq/types";
380
489
  var InMemoryDocumentStore = class {
381
490
  #data = /* @__PURE__ */ new Map();
382
491
  #now;
@@ -394,6 +503,10 @@ var InMemoryDocumentStore = class {
394
503
  capabilities() {
395
504
  return ["get", "put", "delete", "query", "batch", "ttl", "conditional-put"];
396
505
  }
506
+ /** The process's own memory: healthy whenever it can answer. */
507
+ async healthCheck() {
508
+ return { status: "healthy" };
509
+ }
397
510
  async get(collection, key) {
398
511
  const entry = this.#data.get(collection)?.get(key);
399
512
  if (!entry) return null;
@@ -440,37 +553,11 @@ var InMemoryDocumentStore = class {
440
553
  async query(collection, params) {
441
554
  const bucket = this.#data.get(collection);
442
555
  if (!bucket) return { items: [], nextCursor: null };
443
- const ascending = params.ascending ?? true;
444
- const limit = params.limit ?? 50;
445
- const decodedCursor = params.cursor ? decodeCursor(params.cursor) : null;
446
- const matches = [];
556
+ const live = [];
447
557
  for (const [key, entry] of bucket) {
448
- if (this.#isExpired(entry)) continue;
449
- const doc = entry.doc;
450
- const partition = params.partitionKey;
451
- if (partition.value !== "*" && doc[partition.field] !== partition.value) continue;
452
- if (params.sortKey) {
453
- const value = doc[params.sortKey.field];
454
- if (!sortKeyMatches(value, params.sortKey.operator, params.sortKey.value)) continue;
455
- }
456
- matches.push({ key, doc });
558
+ if (!this.#isExpired(entry)) live.push([key, entry.doc]);
457
559
  }
458
- if (params.orderBy) return orderedPage(matches, params.orderBy, params, limit);
459
- const sortField = params.sortKey?.field;
460
- matches.sort((a, b) => {
461
- const aKey = sortField ? a.doc[sortField] : a.key;
462
- const bKey = sortField ? b.doc[sortField] : b.key;
463
- const cmp = compare(aKey, bKey);
464
- return ascending ? cmp : -cmp;
465
- });
466
- let start = 0;
467
- if (decodedCursor) {
468
- const idx = matches.findIndex((m) => m.key === decodedCursor);
469
- start = idx >= 0 ? idx + 1 : 0;
470
- }
471
- const page = matches.slice(start, start + limit);
472
- const nextCursor = start + limit < matches.length && page.length > 0 ? encodeCursor(page[page.length - 1].key) : null;
473
- return { items: page.map((m) => m.doc), nextCursor };
560
+ return queryDocuments(live, params);
474
561
  }
475
562
  async batchGet(collection, keys) {
476
563
  const result = /* @__PURE__ */ new Map();
@@ -511,124 +598,10 @@ var InMemoryDocumentStore = class {
511
598
  }
512
599
  }
513
600
  };
514
- function sortKeyMatches(value, operator, target) {
515
- switch (operator) {
516
- case "eq":
517
- return value === target;
518
- case "gt":
519
- return compare(value, target) > 0;
520
- case "lt":
521
- return compare(value, target) < 0;
522
- case "between": {
523
- if (!Array.isArray(target) || target.length !== 2) return false;
524
- const [low, high] = target;
525
- return compare(value, low) >= 0 && compare(value, high) <= 0;
526
- }
527
- }
528
- }
529
- function compare(a, b) {
530
- if (a === b) return 0;
531
- if (a === null || a === void 0) return -1;
532
- if (b === null || b === void 0) return 1;
533
- if (typeof a === "number" && typeof b === "number") return a - b;
534
- return String(a) < String(b) ? -1 : 1;
535
- }
536
- function orderedPage(matches, orderBy, params, limit) {
537
- const order = JSON.stringify([
538
- orderBy.field,
539
- orderBy.direction,
540
- orderBy.nulls ?? null,
541
- params.partitionKey
542
- ]);
543
- const positions = matches.map((m) => ({
544
- position: { key: m.key, value: valueAt(m.doc, orderBy.field) },
545
- doc: m.doc
546
- }));
547
- positions.sort((a, b) => compareOrdered(a.position, b.position, orderBy));
548
- let start = 0;
549
- if (params.cursor) {
550
- const after = decodeOrderedCursor(params.cursor, order);
551
- const idx = positions.findIndex((p) => compareOrdered(p.position, after, orderBy) > 0);
552
- start = idx >= 0 ? idx : positions.length;
553
- }
554
- const page = positions.slice(start, start + limit);
555
- const last = page[page.length - 1];
556
- const nextCursor = start + limit < positions.length && last !== void 0 ? Buffer.from(
557
- JSON.stringify({ o: order, k: last.position.key, v: last.position.value }),
558
- "utf8"
559
- ).toString("base64url") : null;
560
- return { items: page.map((p) => p.doc), nextCursor };
561
- }
562
- function decodeOrderedCursor(cursor, order) {
563
- let decoded;
564
- try {
565
- decoded = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
566
- } catch {
567
- decoded = null;
568
- }
569
- const c = decoded;
570
- if (c === null || typeof c !== "object" || typeof c.k !== "string" || !("v" in c)) {
571
- throw new ValidationError("The cursor is not valid", { context: { cursor } });
572
- }
573
- if (c.o !== order) {
574
- throw new ValidationError("The cursor was issued under another order", { context: { cursor } });
575
- }
576
- return { key: c.k, value: c.v };
577
- }
578
- function valueAt(doc, path) {
579
- let value = doc;
580
- for (const part of path.split(".")) {
581
- if (value === null || typeof value !== "object") return null;
582
- value = value[part];
583
- }
584
- return value ?? null;
585
- }
586
- var collator = new Intl.Collator(void 0, { sensitivity: "base" });
587
- function compareOrdered(a, b, orderBy) {
588
- const aNull = a.value === null;
589
- const bNull = b.value === null;
590
- let c = 0;
591
- if (orderBy.nulls === "last" && aNull !== bNull) return aNull ? 1 : -1;
592
- if (typeof a.value === "string" && typeof b.value === "string")
593
- c = collator.compare(a.value, b.value);
594
- else c = compare(a.value, b.value);
595
- if (orderBy.direction === "desc") c = -c;
596
- if (c !== 0) return c;
597
- return a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
598
- }
599
- function encodeCursor(key) {
600
- return Buffer.from(key, "utf8").toString("base64url");
601
- }
602
- function decodeCursor(cursor) {
603
- return Buffer.from(cursor, "base64url").toString("utf8");
604
- }
605
-
606
- // src/document-store/factory.ts
607
- function createDocumentStore(config) {
608
- switch (config.infrastructure.documentStore) {
609
- case "in-memory":
610
- return new InMemoryDocumentStore();
611
- case "dynamodb":
612
- case "firestore":
613
- case "cosmosdb":
614
- case "postgres-jsonb":
615
- throw new ConfigError2(
616
- `documentStore=${config.infrastructure.documentStore} is planned for v1.0 and not yet implemented.`,
617
- { context: { documentStore: config.infrastructure.documentStore } }
618
- );
619
- default: {
620
- const exhaustive = config.infrastructure.documentStore;
621
- throw new ConfigError2(`Unknown documentStore: ${String(exhaustive)}`);
622
- }
623
- }
624
- }
625
-
626
- // src/event-bus/factory.ts
627
- import { ConfigError as ConfigError3 } from "@nymbalhq/types";
628
601
 
629
602
  // src/event-bus/in-process.ts
630
603
  import { v7 as uuidv7 } from "uuid";
631
- import { ValidationError as ValidationError2 } from "@nymbalhq/types";
604
+ import { ValidationError } from "@nymbalhq/types";
632
605
  var InProcessEventBus = class {
633
606
  #registrations = /* @__PURE__ */ new Map();
634
607
  #logger;
@@ -638,6 +611,10 @@ var InProcessEventBus = class {
638
611
  capabilities() {
639
612
  return ["publish", "subscribe", "wildcard", "replay"];
640
613
  }
614
+ /** Delivery within the process: healthy whenever it can answer. */
615
+ async healthCheck() {
616
+ return { status: "healthy" };
617
+ }
641
618
  async publish(event) {
642
619
  await this.#deliver(event, () => true);
643
620
  }
@@ -692,12 +669,12 @@ var InProcessEventBus = class {
692
669
  }
693
670
  #validate(event) {
694
671
  if (!event.id || !event.type || !event.timestamp || !event.source) {
695
- throw new ValidationError2("Event is missing required envelope fields", {
672
+ throw new ValidationError("Event is missing required envelope fields", {
696
673
  context: { event }
697
674
  });
698
675
  }
699
676
  if (!event.metadata || !event.metadata.storeId || !event.metadata.environment) {
700
- throw new ValidationError2("Event metadata is missing required fields", {
677
+ throw new ValidationError("Event metadata is missing required fields", {
701
678
  context: { event }
702
679
  });
703
680
  }
@@ -708,26 +685,6 @@ function compilePattern(pattern) {
708
685
  return new RegExp(`^${escaped}$`);
709
686
  }
710
687
 
711
- // src/event-bus/factory.ts
712
- function createEventBus(config, logger) {
713
- switch (config.infrastructure.eventBus) {
714
- case "in-process":
715
- return new InProcessEventBus(logger ? { logger } : {});
716
- case "eventbridge":
717
- case "pubsub":
718
- case "service-bus":
719
- case "redis-streams":
720
- throw new ConfigError3(
721
- `eventBus=${config.infrastructure.eventBus} is planned for v1.0 and not yet implemented.`,
722
- { context: { eventBus: config.infrastructure.eventBus } }
723
- );
724
- default: {
725
- const exhaustive = config.infrastructure.eventBus;
726
- throw new ConfigError3(`Unknown eventBus: ${String(exhaustive)}`);
727
- }
728
- }
729
- }
730
-
731
688
  // src/logger.ts
732
689
  import { pino } from "pino";
733
690
  function createLogger(options = {}) {
@@ -756,8 +713,198 @@ function wrap(p) {
756
713
  };
757
714
  }
758
715
 
716
+ // src/media/local-fs-storage.ts
717
+ import { constants } from "fs";
718
+ import { access, mkdir, writeFile } from "fs/promises";
719
+ import { dirname, join as join3, resolve } from "path";
720
+ var LOCAL_FS_MEDIA_CAPABILITIES = ["put"];
721
+ async function nearestExisting(root) {
722
+ let dir = resolve(root);
723
+ for (; ; ) {
724
+ try {
725
+ await access(dir, constants.F_OK);
726
+ return dir;
727
+ } catch {
728
+ const parent = dirname(dir);
729
+ if (parent === dir) return dir;
730
+ dir = parent;
731
+ }
732
+ }
733
+ }
734
+ function createLocalFsMediaStorage(options) {
735
+ const { root } = options;
736
+ const urlPrefix = options.urlPrefix ?? "/imported-media";
737
+ return {
738
+ capabilities: () => LOCAL_FS_MEDIA_CAPABILITIES,
739
+ async put(key, body, _contentType) {
740
+ const dest = join3(root, key);
741
+ const dir = dest.substring(0, dest.lastIndexOf("/"));
742
+ await mkdir(dir, { recursive: true });
743
+ await writeFile(dest, body);
744
+ return { url: `${urlPrefix}/${key}` };
745
+ },
746
+ // Permission is read with access(2), never probed by writing a file.
747
+ async healthCheck() {
748
+ const dir = await nearestExisting(root);
749
+ try {
750
+ await access(dir, constants.W_OK);
751
+ return { status: "healthy", detail: root };
752
+ } catch {
753
+ return { status: "down", detail: `${dir} is not writable` };
754
+ }
755
+ }
756
+ };
757
+ }
758
+
759
759
  // src/platform.ts
760
- function createPlatform(config, options = {}) {
760
+ var REDIS_DEFAULTS = {
761
+ prefix: "nymbal",
762
+ ackTimeoutMs: 15e3,
763
+ claimIdleMs: 5e3,
764
+ streamMaxLen: 1e4
765
+ };
766
+ var S3_DEFAULT_REGION = "us-east-1";
767
+ var JSONB_PREFIX = "nymbal";
768
+ function nonEmpty(value) {
769
+ return value === void 0 || value === "" ? void 0 : value;
770
+ }
771
+ function redisUrlOf(config, env) {
772
+ return config.infrastructure.redis?.url ?? nonEmpty(env["REDIS_URL"]);
773
+ }
774
+ function redisConnection(config, env, slot) {
775
+ const block = config.infrastructure.redis ?? {};
776
+ const url = redisUrlOf(config, env);
777
+ if (url === void 0) {
778
+ throw new ConfigError3(
779
+ `infrastructure.${slot} needs a Redis server: set infrastructure.redis.url or REDIS_URL`,
780
+ { code: "config.redis_url_missing", context: { slot } }
781
+ );
782
+ }
783
+ return {
784
+ url,
785
+ prefix: block.prefix ?? nonEmpty(env["NYMBAL_REDIS_PREFIX"]) ?? REDIS_DEFAULTS.prefix,
786
+ ackTimeoutMs: block.ackTimeoutMs ?? REDIS_DEFAULTS.ackTimeoutMs,
787
+ claimIdleMs: block.claimIdleMs ?? REDIS_DEFAULTS.claimIdleMs,
788
+ streamMaxLen: block.streamMaxLen ?? REDIS_DEFAULTS.streamMaxLen
789
+ };
790
+ }
791
+ function s3Connection(config, env) {
792
+ const block = config.infrastructure.s3 ?? {};
793
+ const bucket = nonEmpty(block.bucket) ?? nonEmpty(env["S3_BUCKET"]);
794
+ if (bucket === void 0) {
795
+ throw new ConfigError3(
796
+ "infrastructure.media 's3' needs a bucket: set infrastructure.s3.bucket or S3_BUCKET",
797
+ { code: "config.s3_bucket_missing", context: { slot: "media" } }
798
+ );
799
+ }
800
+ const endpoint = nonEmpty(block.endpoint) ?? nonEmpty(env["S3_ENDPOINT"]);
801
+ const publicUrl = nonEmpty(block.publicUrl) ?? nonEmpty(env["S3_PUBLIC_URL"]);
802
+ return {
803
+ bucket,
804
+ region: nonEmpty(block.region) ?? nonEmpty(env["AWS_REGION"]) ?? S3_DEFAULT_REGION,
805
+ prefix: block.prefix ?? nonEmpty(env["NYMBAL_S3_PREFIX"]) ?? "",
806
+ forcePathStyle: block.forcePathStyle ?? endpoint !== void 0,
807
+ ...endpoint !== void 0 && { endpoint },
808
+ ...publicUrl !== void 0 && { publicUrl }
809
+ };
810
+ }
811
+ async function loadPrimitive(slot, provider, config, logger, env) {
812
+ const instance = await loadProviderAdapter(slot, provider, {
813
+ config,
814
+ logger: logger.child({ primitive: slot }),
815
+ env
816
+ });
817
+ if (instance === void 0) {
818
+ throw new ConfigError3(`infrastructure.${slot} '${provider}' has no implementation`, {
819
+ context: { slot, provider }
820
+ });
821
+ }
822
+ return instance;
823
+ }
824
+ async function buildDocumentStore(config, options, logger, env) {
825
+ const choice = config.infrastructure.documentStore;
826
+ switch (choice) {
827
+ case "in-memory":
828
+ return new InMemoryDocumentStore();
829
+ case "redis": {
830
+ const { url, prefix } = redisConnection(config, env, "documentStore");
831
+ return loadPrimitive("documentStore", choice, { url, prefix }, logger, env);
832
+ }
833
+ case "postgres-jsonb": {
834
+ const postgresUrl = options.postgresUrl ?? nonEmpty(env["DATABASE_URL"]);
835
+ if (postgresUrl === void 0) {
836
+ throw new ConfigError3(
837
+ "documentStore 'postgres-jsonb' uses the command store's Postgres: set DATABASE_URL (or pass postgresUrl)",
838
+ { code: "config.postgres_url_missing", context: { slot: "documentStore" } }
839
+ );
840
+ }
841
+ return loadPrimitive(
842
+ "documentStore",
843
+ choice,
844
+ { postgresUrl, prefix: JSONB_PREFIX },
845
+ logger,
846
+ env
847
+ );
848
+ }
849
+ default: {
850
+ const exhaustive = choice;
851
+ throw new ConfigError3(`Unknown documentStore: ${String(exhaustive)}`);
852
+ }
853
+ }
854
+ }
855
+ async function buildEventBus(config, logger, env) {
856
+ const choice = config.infrastructure.eventBus;
857
+ switch (choice) {
858
+ case "in-process":
859
+ return new InProcessEventBus({ logger });
860
+ case "redis-streams":
861
+ return loadPrimitive(
862
+ "eventBus",
863
+ choice,
864
+ redisConnection(config, env, "eventBus"),
865
+ logger,
866
+ env
867
+ );
868
+ default: {
869
+ const exhaustive = choice;
870
+ throw new ConfigError3(`Unknown eventBus: ${String(exhaustive)}`);
871
+ }
872
+ }
873
+ }
874
+ async function buildMedia(config, options, logger, env) {
875
+ const choice = config.infrastructure.media;
876
+ switch (choice) {
877
+ case "local-fs":
878
+ return createLocalFsMediaStorage({
879
+ root: options.mediaRoot ?? join4(process.cwd(), "public", "imported-media"),
880
+ urlPrefix: "/imported-media"
881
+ });
882
+ case "s3":
883
+ return loadPrimitive("media", choice, s3Connection(config, env), logger, env);
884
+ default: {
885
+ const exhaustive = choice;
886
+ throw new ConfigError3(`Unknown media: ${String(exhaustive)}`);
887
+ }
888
+ }
889
+ }
890
+ async function resolvePrimitives(config, options = {}) {
891
+ const env = options.env ?? process.env;
892
+ const logger = options.logger ?? createLogger({ base: { store: config.store.name } });
893
+ if (config.infrastructure.media === "s3") s3Connection(config, env);
894
+ if (config.infrastructure.documentStore === "redis") redisConnection(config, env, "documentStore");
895
+ if (config.infrastructure.eventBus === "redis-streams") redisConnection(config, env, "eventBus");
896
+ const media = await buildMedia(config, options, logger, env);
897
+ const documentStore = await buildDocumentStore(config, options, logger, env);
898
+ try {
899
+ if (config.infrastructure.documentStore === "postgres-jsonb") await documentStore.initialize?.();
900
+ const eventBus = await buildEventBus(config, logger, env);
901
+ return { documentStore, eventBus, media };
902
+ } catch (error) {
903
+ await documentStore.close();
904
+ throw error;
905
+ }
906
+ }
907
+ function createPlatform(config, options) {
761
908
  const logger = options.logger ?? createLogger({
762
909
  base: { store: config.store.name }
763
910
  });
@@ -765,35 +912,69 @@ function createPlatform(config, options = {}) {
765
912
  ...options.sqlitePath !== void 0 && { sqlitePath: options.sqlitePath },
766
913
  ...options.postgresUrl !== void 0 && { postgresUrl: options.postgresUrl }
767
914
  });
768
- const documentStore = createDocumentStore(config);
769
- const eventBus = createEventBus(config, logger);
915
+ const { documentStore, eventBus, media } = options;
770
916
  return {
771
917
  config,
772
918
  commandStore,
773
919
  documentStore,
774
920
  eventBus,
921
+ media,
775
922
  logger,
776
923
  async close() {
777
- await commandStore.close();
778
- await documentStore.close();
779
924
  await eventBus.close();
925
+ await documentStore.close();
926
+ await commandStore.close();
780
927
  }
781
928
  };
782
929
  }
783
930
 
784
931
  // src/db/migrate.ts
785
- import { resolve } from "path";
932
+ import { readFileSync } from "fs";
933
+ import { resolve as resolve2 } from "path";
786
934
  import { migrate as migrateSqlite } from "drizzle-orm/better-sqlite3/migrator";
787
935
  import { migrate as migratePostgres } from "drizzle-orm/node-postgres/migrator";
936
+ function rootOf(options) {
937
+ return options.migrationsRoot ?? resolve2(process.cwd(), "migrations");
938
+ }
788
939
  async function runMigrations(store, options = {}) {
789
- const root = options.migrationsRoot ?? resolve(process.cwd(), "migrations");
940
+ const root = rootOf(options);
790
941
  const clients = rawClients(store);
791
942
  if (clients.kind === "sqlite") {
792
- migrateSqlite(clients.db, { migrationsFolder: resolve(root, "sqlite") });
943
+ migrateSqlite(clients.db, { migrationsFolder: resolve2(root, "sqlite") });
793
944
  } else {
794
- await migratePostgres(clients.db, { migrationsFolder: resolve(root, "postgres") });
945
+ await migratePostgres(clients.db, { migrationsFolder: resolve2(root, "postgres") });
795
946
  }
796
947
  }
948
+ async function migrationState(store, options = {}) {
949
+ const clients = rawClients(store);
950
+ const journal = JSON.parse(
951
+ readFileSync(resolve2(rootOf(options), clients.kind, "meta", "_journal.json"), "utf8")
952
+ );
953
+ let applied = 0;
954
+ let newest = Number.NEGATIVE_INFINITY;
955
+ if (clients.kind === "sqlite") {
956
+ const table = clients.raw.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = '__drizzle_migrations'").get();
957
+ if (table !== void 0) {
958
+ const row = clients.raw.prepare("SELECT count(*) AS n, max(created_at) AS last FROM __drizzle_migrations").get();
959
+ applied = row.n;
960
+ if (row.last !== null) newest = Number(row.last);
961
+ }
962
+ } else {
963
+ const { rows } = await clients.pool.query(
964
+ "SELECT to_regclass('drizzle.__drizzle_migrations')::text AS table"
965
+ );
966
+ if (rows[0]?.table != null) {
967
+ const counted = await clients.pool.query(
968
+ "SELECT count(*)::int AS n, max(created_at)::text AS last FROM drizzle.__drizzle_migrations"
969
+ );
970
+ applied = counted.rows[0]?.n ?? 0;
971
+ const last = counted.rows[0]?.last ?? null;
972
+ if (last !== null) newest = Number(last);
973
+ }
974
+ }
975
+ const pending = journal.entries.filter((entry) => entry.when > newest).length;
976
+ return { applied, pending };
977
+ }
797
978
 
798
979
  // src/db/repositories/products.ts
799
980
  import { eq } from "drizzle-orm";
@@ -2571,11 +2752,11 @@ function createEventPublisher(opts) {
2571
2752
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
2572
2753
  var PAGE_SIZE = 100;
2573
2754
  function deferred() {
2574
- let resolve2;
2755
+ let resolve4;
2575
2756
  const promise = new Promise((r) => {
2576
- resolve2 = r;
2757
+ resolve4 = r;
2577
2758
  });
2578
- return { promise, resolve: resolve2 };
2759
+ return { promise, resolve: resolve4 };
2579
2760
  }
2580
2761
  function createRelay(opts) {
2581
2762
  const { store, eventLog } = opts;
@@ -2663,9 +2844,23 @@ function createRelay(opts) {
2663
2844
  timer = void 0;
2664
2845
  if (delivering.getStore() === true) return Promise.resolve();
2665
2846
  return idle?.promise ?? Promise.resolve();
2847
+ },
2848
+ asDelivery(handler) {
2849
+ return (event) => delivering.run(true, () => handler(event));
2666
2850
  }
2667
2851
  };
2668
2852
  }
2853
+ function deliveringBus(bus, relay) {
2854
+ return {
2855
+ capabilities: () => bus.capabilities(),
2856
+ publish: (event) => bus.publish(event),
2857
+ publishBatch: (events3) => bus.publishBatch(events3),
2858
+ replay: (events3) => bus.replay(events3),
2859
+ subscribe: (pattern, handler, config) => bus.subscribe(pattern, relay.asDelivery(handler), config),
2860
+ unsubscribe: (subscription) => bus.unsubscribe(subscription),
2861
+ close: () => bus.close()
2862
+ };
2863
+ }
2669
2864
 
2670
2865
  // src/handlers/idempotency.ts
2671
2866
  function withIdempotency(handlerName, handler, { repo, logger }) {
@@ -2728,7 +2923,21 @@ import {
2728
2923
  } from "@nymbalhq/types";
2729
2924
  var PRODUCTS = "products";
2730
2925
  var PRODUCTS_BY_CATEGORY = "products-by-category";
2731
- function denormalise(p, storeId, storeCurrency, categories3) {
2926
+ var isVariantOption = (o) => typeof o === "object" && o !== null && typeof o.name === "string" && typeof o.value === "string";
2927
+ function variantOptions(raw, logger, sku) {
2928
+ let value = raw;
2929
+ if (typeof raw === "string") {
2930
+ try {
2931
+ value = JSON.parse(raw);
2932
+ } catch (err) {
2933
+ logger.warn({ sku, err }, "variant options are not JSON; projected as none");
2934
+ return [];
2935
+ }
2936
+ }
2937
+ if (!Array.isArray(value)) return [];
2938
+ return value.filter(isVariantOption).map((o) => ({ name: o.name, value: o.value }));
2939
+ }
2940
+ function denormalise(p, storeId, storeCurrency, categories3, logger) {
2732
2941
  const prices = p.variants.map((v) => v.priceMinor);
2733
2942
  const priceRange = prices.length ? { minMinor: Math.min(...prices), maxMinor: Math.max(...prices) } : null;
2734
2943
  const inStock = p.variants.some((v) => v.stock > 0);
@@ -2753,7 +2962,7 @@ function denormalise(p, storeId, storeCurrency, categories3) {
2753
2962
  name: v.name,
2754
2963
  priceMinor: v.priceMinor,
2755
2964
  stock: v.stock,
2756
- options: v.options
2965
+ options: variantOptions(v.options, logger, v.sku)
2757
2966
  })),
2758
2967
  categoryIds: p.categoryIds,
2759
2968
  categories: categories3,
@@ -2778,7 +2987,7 @@ async function registerProductProjection(deps) {
2778
2987
  const onUpsert = async (event) => {
2779
2988
  const { product } = event.payload;
2780
2989
  const categories3 = await resolveCategories(product.categoryIds, documentStore, storeId);
2781
- const doc = denormalise(product, storeId, currency, categories3);
2990
+ const doc = denormalise(product, storeId, currency, categories3, logger);
2782
2991
  await documentStore.put(PRODUCTS, product.slug, doc);
2783
2992
  for (const cat of categories3) {
2784
2993
  await documentStore.put(
@@ -3171,16 +3380,16 @@ async function registerHandlers(deps) {
3171
3380
  logger: handlerLogger.child({ handler: "reviews" }),
3172
3381
  processedEventRepo: repos.processedEvent
3173
3382
  });
3174
- logger.info("event handlers registered");
3383
+ logger.debug("event handlers registered");
3175
3384
  }
3176
3385
 
3177
3386
  // src/app.ts
3178
3387
  import { DEFAULT_JWT_SECRET } from "@nymbalhq/config";
3179
- import { ConfigError as ConfigError6 } from "@nymbalhq/types";
3388
+ import { ConfigError as ConfigError5 } from "@nymbalhq/types";
3180
3389
 
3181
3390
  // src/adapters/registry.ts
3182
3391
  import {
3183
- ConfigError as ConfigError5
3392
+ ConfigError as ConfigError4
3184
3393
  } from "@nymbalhq/types";
3185
3394
 
3186
3395
  // src/adapters/security/headers.ts
@@ -3273,6 +3482,8 @@ function createNativeStubPaymentsAdapter(deps) {
3273
3482
  providerName: "native-stub",
3274
3483
  // No `webhook`: parseWebhook verifies no signature, so a template cannot rely on it.
3275
3484
  capabilities: () => ["intent", "capture", "refund"],
3485
+ // Nothing to collect: the receipt email decides the outcome.
3486
+ client: () => ({ driver: "test-mode", options: {} }),
3276
3487
  producesEvents: [EVT_PAYMENT_CAPTURED, EVT_PAYMENT_FAILED, EVT_PAYMENT_REFUNDED],
3277
3488
  consumesEvents: [],
3278
3489
  initialize: noopInitialize,
@@ -3406,22 +3617,263 @@ function createNativeEmailAdapter(deps) {
3406
3617
  import {
3407
3618
  EVT_PRODUCT_CREATED as EVT_PRODUCT_CREATED3,
3408
3619
  EVT_PRODUCT_DELETED as EVT_PRODUCT_DELETED3,
3409
- EVT_PRODUCT_UPDATED as EVT_PRODUCT_UPDATED3
3620
+ EVT_PRODUCT_UPDATED as EVT_PRODUCT_UPDATED3,
3621
+ ValidationError as ValidationError2
3410
3622
  } from "@nymbalhq/types";
3411
- var INDEX_COLLECTION = "search-index";
3412
- function flatten(value) {
3413
- if (value == null) return "";
3414
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
3415
- return String(value);
3416
- }
3417
- if (Array.isArray(value)) return value.map(flatten).join(" ");
3418
- if (typeof value === "object") {
3419
- return Object.values(value).map(flatten).join(" ");
3623
+
3624
+ // src/adapters/search/terms.ts
3625
+ function searchTerms(text) {
3626
+ return text.toLowerCase().match(/[a-z0-9]+/g) ?? [];
3627
+ }
3628
+ var textOf = (value) => typeof value === "string" ? value : "";
3629
+ function toIndexRow(doc) {
3630
+ const { fields } = doc;
3631
+ const variants3 = Array.isArray(fields["variants"]) ? fields["variants"].filter(
3632
+ (v) => typeof v === "object" && v !== null
3633
+ ) : [];
3634
+ const categoryIds = Array.isArray(fields["categoryIds"]) ? [...new Set(fields["categoryIds"].filter((c) => typeof c === "string"))] : [];
3635
+ return {
3636
+ id: doc.id,
3637
+ type: doc.type,
3638
+ fields,
3639
+ categoryIds,
3640
+ name: searchTerms(textOf(fields["name"])),
3641
+ strong: variants3.flatMap((v) => [
3642
+ ...searchTerms(textOf(v["sku"])),
3643
+ ...searchTerms(textOf(v["name"]))
3644
+ ]),
3645
+ body: searchTerms(textOf(fields["description"]))
3646
+ };
3647
+ }
3648
+ function latestById(rows) {
3649
+ return [...new Map(rows.map((row) => [row.id, row])).values()];
3650
+ }
3651
+
3652
+ // src/adapters/search/postgres-index.ts
3653
+ var MAX_LEXEME = 2046;
3654
+ var MAX_POSITION = 16383;
3655
+ var MAX_POSITIONS = 256;
3656
+ var lexeme = (term) => term.slice(0, MAX_LEXEME);
3657
+ function tsvectorLiteral(row) {
3658
+ const positions = /* @__PURE__ */ new Map();
3659
+ let position = 0;
3660
+ const add = (terms, weight) => {
3661
+ for (const term of terms) {
3662
+ position = Math.min(position + 1, MAX_POSITION);
3663
+ const key = lexeme(term);
3664
+ const list = positions.get(key) ?? [];
3665
+ if (list.length < MAX_POSITIONS) list.push(`${position}${weight}`);
3666
+ positions.set(key, list);
3667
+ }
3668
+ };
3669
+ add(row.name, "A");
3670
+ add(row.strong, "B");
3671
+ add(row.body, "C");
3672
+ return [...positions].map(([key, list]) => `'${key}':${list.join(",")}`).join(" ");
3673
+ }
3674
+ function tsqueryLiteral(terms, weights) {
3675
+ return terms.map((t) => `'${lexeme(t)}':*${weights}`).join(" & ");
3676
+ }
3677
+ var IN_CATEGORY = `($2::text[] IS NULL OR category_ids && $2::text[])`;
3678
+ var SQL = {
3679
+ upsert: `INSERT INTO search_documents (id, type, fields, category_ids, tsv)
3680
+ SELECT r.id, r.type, r.fields, ARRAY(SELECT jsonb_array_elements_text(r.cats)), r.tsv::tsvector
3681
+ FROM jsonb_to_recordset($1::jsonb) AS r(id text, type text, fields jsonb, cats jsonb, tsv text)
3682
+ ON CONFLICT (id) DO UPDATE SET
3683
+ type = excluded.type, fields = excluded.fields, category_ids = excluded.category_ids, tsv = excluded.tsv
3684
+ WHERE search_documents.type IS DISTINCT FROM excluded.type
3685
+ OR search_documents.fields IS DISTINCT FROM excluded.fields`,
3686
+ remove: `DELETE FROM search_documents WHERE id = ANY($1::text[])`,
3687
+ // Rank: every term in the name, then every term in name, SKU or variant name, then ts_rank, then id.
3688
+ page: `SELECT id, type, fields, (count(*) OVER ())::int AS total
3689
+ FROM search_documents
3690
+ WHERE tsv @@ $1::tsquery AND ${IN_CATEGORY}
3691
+ ORDER BY tsv @@ $3::tsquery DESC, tsv @@ $4::tsquery DESC, ts_rank(tsv, $1::tsquery) DESC, id COLLATE "C"
3692
+ LIMIT $5 OFFSET $6`,
3693
+ count: `SELECT count(*)::int AS total FROM search_documents WHERE tsv @@ $1::tsquery AND ${IN_CATEGORY}`,
3694
+ facet: `SELECT c AS value, count(*)::int AS count
3695
+ FROM search_documents, unnest(category_ids) AS c
3696
+ WHERE ($1::tsquery IS NULL OR tsv @@ $1::tsquery) AND ${IN_CATEGORY}
3697
+ GROUP BY c ORDER BY count DESC, c COLLATE "C" LIMIT $3`
3698
+ };
3699
+ var named = (key, values) => ({
3700
+ name: `nymbal-search-${key}`,
3701
+ text: SQL[key],
3702
+ values
3703
+ });
3704
+ function createPostgresSearchIndex(pool) {
3705
+ return {
3706
+ async upsert(rows) {
3707
+ const batch = latestById(rows).map((row) => ({
3708
+ id: row.id,
3709
+ type: row.type,
3710
+ fields: row.fields,
3711
+ cats: row.categoryIds,
3712
+ tsv: tsvectorLiteral(row)
3713
+ }));
3714
+ if (batch.length > 0) await pool.query(named("upsert", [JSON.stringify(batch)]));
3715
+ },
3716
+ async remove(ids) {
3717
+ if (ids.length > 0) await pool.query(named("remove", [ids]));
3718
+ },
3719
+ async page(terms, categories3, limit, offset) {
3720
+ const result = await pool.query(SQL.page, [
3721
+ tsqueryLiteral(terms, ""),
3722
+ categories3,
3723
+ tsqueryLiteral(terms, "A"),
3724
+ tsqueryLiteral(terms, "AB"),
3725
+ limit,
3726
+ offset
3727
+ ]);
3728
+ const docs = result.rows.map(({ id, type, fields }) => ({ id, type, fields }));
3729
+ return { docs, total: result.rows[0]?.total ?? null };
3730
+ },
3731
+ async count(terms, categories3) {
3732
+ const result = await pool.query(SQL.count, [
3733
+ tsqueryLiteral(terms, ""),
3734
+ categories3
3735
+ ]);
3736
+ return result.rows[0].total;
3737
+ },
3738
+ async categoryCounts(terms, categories3, limit) {
3739
+ const result = await pool.query(SQL.facet, [
3740
+ terms === null ? null : tsqueryLiteral(terms, ""),
3741
+ categories3,
3742
+ limit
3743
+ ]);
3744
+ return result.rows;
3745
+ }
3746
+ };
3747
+ }
3748
+
3749
+ // src/adapters/search/sqlite-index.ts
3750
+ function matchAll(terms) {
3751
+ return terms.map((t) => `"${t}"*`).join(" AND ");
3752
+ }
3753
+ var IN_CATEGORY2 = `(@cats IS NULL OR EXISTS (
3754
+ SELECT 1 FROM json_each(d.category_ids) c WHERE c.value IN (SELECT value FROM json_each(@cats))))`;
3755
+ var matching = (score) => `hits AS MATERIALIZED (
3756
+ SELECT rowid AS rid${score ? ", bm25(search_documents_fts) AS score" : ""}
3757
+ FROM search_documents_fts WHERE search_documents_fts MATCH @all)`;
3758
+ var SQL2 = {
3759
+ upsert: `INSERT INTO search_documents (id, type, fields, category_ids, name_terms, strong_terms, body_terms)
3760
+ VALUES (@id, @type, @fields, @cats, @name, @strong, @body)
3761
+ ON CONFLICT (id) DO UPDATE SET
3762
+ type = excluded.type, fields = excluded.fields, category_ids = excluded.category_ids,
3763
+ name_terms = excluded.name_terms, strong_terms = excluded.strong_terms, body_terms = excluded.body_terms
3764
+ WHERE search_documents.type IS NOT excluded.type OR search_documents.fields IS NOT excluded.fields`,
3765
+ remove: `DELETE FROM search_documents WHERE id = ?`,
3766
+ // Rank: every term in the name, then every term in name, SKU or variant name, then bm25 (lower is better), then id.
3767
+ page: `WITH ${matching(true)},
3768
+ named AS MATERIALIZED (
3769
+ SELECT rowid AS rid FROM search_documents_fts WHERE search_documents_fts MATCH @name),
3770
+ strong AS MATERIALIZED (
3771
+ SELECT rowid AS rid FROM search_documents_fts WHERE search_documents_fts MATCH @strong)
3772
+ SELECT d.id, d.type, d.fields, count(*) OVER () AS total
3773
+ FROM hits h JOIN search_documents d ON d.rid = h.rid
3774
+ WHERE ${IN_CATEGORY2}
3775
+ ORDER BY h.rid IN (SELECT rid FROM named) DESC, h.rid IN (SELECT rid FROM strong) DESC, h.score, d.id
3776
+ LIMIT @limit OFFSET @offset`,
3777
+ count: `WITH ${matching(false)}
3778
+ SELECT count(*) AS total FROM hits h JOIN search_documents d ON d.rid = h.rid WHERE ${IN_CATEGORY2}`,
3779
+ facet: `WITH ${matching(false)}
3780
+ SELECT c.value AS value, count(*) AS count
3781
+ FROM hits h JOIN search_documents d ON d.rid = h.rid JOIN json_each(d.category_ids) c
3782
+ WHERE ${IN_CATEGORY2}
3783
+ GROUP BY c.value ORDER BY count DESC, c.value LIMIT @limit`,
3784
+ facetAll: `SELECT c.value AS value, count(*) AS count
3785
+ FROM search_documents d JOIN json_each(d.category_ids) c
3786
+ WHERE ${IN_CATEGORY2}
3787
+ GROUP BY c.value ORDER BY count DESC, c.value LIMIT @limit`
3788
+ };
3789
+ function createSqliteSearchIndex(raw) {
3790
+ const prepared = /* @__PURE__ */ new Map();
3791
+ const statement = (key) => {
3792
+ let stmt = prepared.get(key);
3793
+ if (stmt === void 0) {
3794
+ stmt = raw.prepare(SQL2[key]);
3795
+ prepared.set(key, stmt);
3796
+ }
3797
+ return stmt;
3798
+ };
3799
+ const cats = (categories3) => categories3 === null ? null : JSON.stringify(categories3);
3800
+ const queryParams = (terms, categories3) => ({
3801
+ all: matchAll(terms),
3802
+ cats: cats(categories3)
3803
+ });
3804
+ return {
3805
+ upsert: (rows) => sqliteTurn(raw, () => {
3806
+ const upsert = statement("upsert");
3807
+ raw.transaction((batch) => {
3808
+ for (const row of batch) {
3809
+ upsert.run({
3810
+ id: row.id,
3811
+ type: row.type,
3812
+ fields: JSON.stringify(row.fields),
3813
+ cats: JSON.stringify(row.categoryIds),
3814
+ name: row.name.join(" "),
3815
+ strong: row.strong.join(" "),
3816
+ body: row.body.join(" ")
3817
+ });
3818
+ }
3819
+ })(latestById(rows));
3820
+ }),
3821
+ remove: (ids) => sqliteTurn(raw, () => {
3822
+ const remove = statement("remove");
3823
+ raw.transaction((batch) => {
3824
+ for (const id of batch) remove.run(id);
3825
+ })(ids);
3826
+ }),
3827
+ page: (terms, categories3, limit, offset) => sqliteTurn(raw, () => {
3828
+ const all = matchAll(terms);
3829
+ const rows = statement("page").all({
3830
+ ...queryParams(terms, categories3),
3831
+ name: `name_terms : (${all})`,
3832
+ strong: `{name_terms strong_terms} : (${all})`,
3833
+ limit,
3834
+ offset
3835
+ });
3836
+ const docs = rows.map((r) => ({
3837
+ id: r.id,
3838
+ type: r.type,
3839
+ fields: JSON.parse(r.fields)
3840
+ }));
3841
+ return { docs, total: rows[0]?.total ?? null };
3842
+ }),
3843
+ count: (terms, categories3) => sqliteTurn(
3844
+ raw,
3845
+ () => statement("count").get(queryParams(terms, categories3)).total
3846
+ ),
3847
+ categoryCounts: (terms, categories3, limit) => sqliteTurn(raw, () => {
3848
+ const params = { cats: cats(categories3), limit: limit ?? -1 };
3849
+ return terms === null ? statement("facetAll").all(params) : statement("facet").all({ ...params, all: matchAll(terms) });
3850
+ })
3851
+ };
3852
+ }
3853
+
3854
+ // src/adapters/search/native-adapter.ts
3855
+ var DEFAULT_LIMIT = 20;
3856
+ function encodeSearchCursor(offset) {
3857
+ return Buffer.from(String(offset), "utf8").toString("base64url");
3858
+ }
3859
+ function decodeSearchCursor(cursor) {
3860
+ const text = Buffer.from(cursor, "base64url").toString("utf8");
3861
+ const offset = Number(text);
3862
+ if (!/^\d+$/.test(text) || !Number.isSafeInteger(offset) || encodeSearchCursor(offset) !== cursor) {
3863
+ throw new ValidationError2("malformed search cursor");
3420
3864
  }
3421
- return "";
3865
+ return offset;
3422
3866
  }
3867
+ function categoryFilter(filters) {
3868
+ const value = filters?.["categoryIds"];
3869
+ if (typeof value === "string") return [value];
3870
+ if (Array.isArray(value)) return value.filter((v) => typeof v === "string");
3871
+ return null;
3872
+ }
3873
+ var uniqueTerms = (query) => [...new Set(searchTerms(query))];
3423
3874
  function createNativeSearchAdapter(deps) {
3424
- const { documentStore, logger } = deps;
3875
+ const { sql: sql6, logger } = deps;
3876
+ const index = sql6.kind === "sqlite" ? createSqliteSearchIndex(sql6.raw) : createPostgresSearchIndex(sql6.pool);
3425
3877
  return {
3426
3878
  kind: "search",
3427
3879
  providerName: "native",
@@ -3431,71 +3883,40 @@ function createNativeSearchAdapter(deps) {
3431
3883
  initialize: noopInitialize,
3432
3884
  healthCheck: () => okHealth(),
3433
3885
  async index(documents) {
3434
- const entries = /* @__PURE__ */ new Map();
3435
- for (const doc of documents) {
3436
- entries.set(doc.id, {
3437
- id: doc.id,
3438
- type: doc.type,
3439
- fields: doc.fields,
3440
- text: flatten(doc.fields).toLowerCase()
3441
- });
3442
- }
3443
- await documentStore.batchPut(INDEX_COLLECTION, entries);
3886
+ await index.upsert(documents.map(toIndexRow));
3444
3887
  logger.debug({ count: documents.length }, "search.index");
3445
3888
  return { indexed: documents.length };
3446
3889
  },
3447
3890
  async remove(ids) {
3448
- for (const id of ids) {
3449
- await documentStore.delete(INDEX_COLLECTION, id);
3450
- }
3891
+ await index.remove(ids);
3451
3892
  },
3452
3893
  async search(query, params) {
3453
- const q = query.trim().toLowerCase();
3454
- const limit = params?.limit ?? 20;
3455
- const result = await documentStore.query(INDEX_COLLECTION, {
3456
- partitionKey: { field: "type", value: "product" },
3457
- limit: 1e3
3458
- });
3459
- const filtered = result.items.filter((item) => {
3460
- if (!q) return true;
3461
- if (!item.text.includes(q)) return false;
3462
- for (const [k, v] of Object.entries(params?.filters ?? {})) {
3463
- const field = item.fields[k];
3464
- if (field !== v) return false;
3465
- }
3466
- return true;
3467
- });
3894
+ const offset = params?.cursor === void 0 ? 0 : decodeSearchCursor(params.cursor);
3895
+ const requested = params?.limit ?? DEFAULT_LIMIT;
3896
+ const limit = Number.isFinite(requested) ? Math.max(1, Math.floor(requested)) : DEFAULT_LIMIT;
3897
+ const terms = uniqueTerms(query);
3898
+ if (terms.length === 0) return { items: [], total: 0, nextCursor: null };
3899
+ const categories3 = categoryFilter(params?.filters);
3900
+ const page = await index.page(terms, categories3, limit, offset);
3901
+ const total = page.total ?? await index.count(terms, categories3);
3902
+ const end = offset + page.docs.length;
3468
3903
  return {
3469
- items: filtered.slice(0, limit).map((it) => ({
3470
- id: it.id,
3471
- type: it.type,
3472
- fields: it.fields
3473
- })),
3474
- total: filtered.length,
3475
- nextCursor: null
3904
+ items: page.docs,
3905
+ total,
3906
+ nextCursor: page.docs.length > 0 && end < total ? encodeSearchCursor(end) : null
3476
3907
  };
3477
3908
  },
3478
- async facet(field) {
3479
- const result = await documentStore.query(INDEX_COLLECTION, {
3480
- partitionKey: { field: "type", value: "product" },
3481
- limit: 1e3
3482
- });
3483
- const counts = /* @__PURE__ */ new Map();
3484
- for (const item of result.items) {
3485
- const raw = item.fields[field];
3486
- if (raw == null) continue;
3487
- const vals = Array.isArray(raw) ? raw : [raw];
3488
- for (const v of vals) {
3489
- const key = String(v);
3490
- counts.set(key, (counts.get(key) ?? 0) + 1);
3491
- }
3492
- }
3493
- const label = field.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
3494
- return {
3495
- field,
3496
- label,
3497
- values: [...counts.entries()].sort((a, b) => b[1] - a[1]).map(([value, count]) => ({ value, count }))
3498
- };
3909
+ async facet(field, params) {
3910
+ const label = field === "categoryIds" ? "Category" : field;
3911
+ if (field !== "categoryIds") return { field, label, values: [] };
3912
+ const terms = params?.query === void 0 ? null : uniqueTerms(params.query);
3913
+ if (terms !== null && terms.length === 0) return { field, label, values: [] };
3914
+ const values = await index.categoryCounts(
3915
+ terms,
3916
+ categoryFilter(params?.filters),
3917
+ params?.limit ?? null
3918
+ );
3919
+ return { field, label, values };
3499
3920
  }
3500
3921
  };
3501
3922
  }
@@ -3635,70 +4056,6 @@ function createNativeTaxAdapter(logger, defaultRate = 0) {
3635
4056
  };
3636
4057
  }
3637
4058
 
3638
- // src/adapters/loader.ts
3639
- import { existsSync } from "fs";
3640
- import { join as join2 } from "path";
3641
- import { ConfigError as ConfigError4 } from "@nymbalhq/types";
3642
- var PROVIDER_PACKAGES = {
3643
- payments: { stripe: { package: "@nymbalhq/adapter-stripe", sdk: "stripe" } },
3644
- ai: { anthropic: { package: "@nymbalhq/adapter-anthropic", sdk: "@anthropic-ai/sdk" } },
3645
- email: { smtp: { package: "@nymbalhq/adapter-smtp", sdk: "nodemailer" } }
3646
- };
3647
- var INSTALL_VERBS = {
3648
- npm: "npm install",
3649
- pnpm: "pnpm add",
3650
- yarn: "yarn add",
3651
- bun: "bun add"
3652
- };
3653
- var LOCKFILES = [
3654
- ["pnpm-lock.yaml", "pnpm"],
3655
- ["yarn.lock", "yarn"],
3656
- ["bun.lock", "bun"],
3657
- ["bun.lockb", "bun"],
3658
- ["package-lock.json", "npm"]
3659
- ];
3660
- function packageManager(env, cwd) {
3661
- const agent = env["npm_config_user_agent"]?.split("/")[0];
3662
- if (agent !== void 0 && agent in INSTALL_VERBS) return agent;
3663
- for (const [file, pm] of LOCKFILES) {
3664
- if (existsSync(join2(cwd, file))) return pm;
3665
- }
3666
- return "npm";
3667
- }
3668
- function packageOf(specifier) {
3669
- const parts = specifier.split("/");
3670
- return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
3671
- }
3672
- function missingPackage(error) {
3673
- if (error?.code !== "ERR_MODULE_NOT_FOUND") return null;
3674
- const match = /Cannot find (?:package|module) '([^']+)'/.exec(String(error.message));
3675
- return match?.[1] === void 0 ? null : packageOf(match[1]);
3676
- }
3677
- async function loadProviderAdapter(slot, provider, ctx) {
3678
- const entry = PROVIDER_PACKAGES[slot]?.[provider];
3679
- if (entry === void 0) return void 0;
3680
- let mod;
3681
- try {
3682
- mod = await import(entry.package);
3683
- } catch (error) {
3684
- const missing = missingPackage(error);
3685
- if (missing !== entry.package && missing !== entry.sdk) throw error;
3686
- const install = `${INSTALL_VERBS[packageManager(ctx.env, process.cwd())]} ${entry.package} ${entry.sdk}`;
3687
- throw new ConfigError4(`${slot}.provider '${provider}' needs ${entry.package}: ${install}`, {
3688
- code: "adapter.package_missing",
3689
- cause: error,
3690
- context: { slot, provider, missing, install }
3691
- });
3692
- }
3693
- if (typeof mod.createAdapter !== "function") {
3694
- throw new ConfigError4(`${entry.package} exports no createAdapter(ctx)`, {
3695
- code: "adapter.package_invalid",
3696
- context: { slot, provider, package: entry.package }
3697
- });
3698
- }
3699
- return mod.createAdapter({ ...ctx, slot });
3700
- }
3701
-
3702
4059
  // src/adapters/registry.ts
3703
4060
  var COMMERCE_SLOTS = [
3704
4061
  "payments",
@@ -3711,21 +4068,22 @@ var COMMERCE_SLOTS = [
3711
4068
  "ai"
3712
4069
  ];
3713
4070
  function checkInjectedAdapters(config, injected = {}) {
3714
- for (const slot of COMMERCE_SLOTS) {
3715
- const provider = config.commerce[slot].provider;
3716
- const given = injected[slot] !== void 0;
3717
- if (provider === "custom" && !given) {
3718
- throw new ConfigError5(
3719
- `commerce.${slot}.provider is 'custom' but createApp was given no ${slot} adapter (createApp(config, { adapters: { ${slot} } })). nymbal dev and nymbal start cannot inject one yet: run the app from an entry of your own that calls createApp.`,
3720
- { code: "adapter.custom_mismatch", context: { slot } }
3721
- );
3722
- }
3723
- if (provider !== "custom" && given) {
3724
- throw new ConfigError5(
3725
- `createApp was given a ${slot} adapter, but commerce.${slot}.provider is '${provider}'; set it to 'custom' to use the injected adapter.`,
3726
- { code: "adapter.custom_mismatch", context: { slot, provider } }
3727
- );
3728
- }
4071
+ for (const slot of COMMERCE_SLOTS) checkInjectedSlot(config, slot, injected);
4072
+ }
4073
+ function checkInjectedSlot(config, slot, injected = {}) {
4074
+ const provider = config.commerce[slot].provider;
4075
+ const given = injected[slot] !== void 0;
4076
+ if (provider === "custom" && !given) {
4077
+ throw new ConfigError4(
4078
+ `commerce.${slot}.provider is 'custom' but createApp was given no ${slot} adapter (createApp(config, { adapters: { ${slot} } })); nymbal dev takes it from the \`adapters\` export of nymbal.config.ts.`,
4079
+ { code: "adapter.custom_mismatch", context: { slot } }
4080
+ );
4081
+ }
4082
+ if (provider !== "custom" && given) {
4083
+ throw new ConfigError4(
4084
+ `createApp was given a ${slot} adapter, but commerce.${slot}.provider is '${provider}'; set it to 'custom' to use the injected adapter.`,
4085
+ { code: "adapter.custom_mismatch", context: { slot, provider } }
4086
+ );
3729
4087
  }
3730
4088
  }
3731
4089
  async function resolveSlot(slot, config, logger, injected, builtIns) {
@@ -3745,7 +4103,7 @@ async function resolveSlot(slot, config, logger, injected, builtIns) {
3745
4103
  }
3746
4104
  }
3747
4105
  if (adapter === void 0) {
3748
- throw new ConfigError5(`commerce.${slot}.provider '${block.provider}' has no adapter`, {
4106
+ throw new ConfigError4(`commerce.${slot}.provider '${block.provider}' has no adapter`, {
3749
4107
  context: { slot, provider: block.provider }
3750
4108
  });
3751
4109
  }
@@ -3757,48 +4115,42 @@ function resolvePaymentsAdapter(config, logger, injected = {}) {
3757
4115
  native: () => createNativeStubPaymentsAdapter({ logger: logger.child({ adapter: "payments" }) })
3758
4116
  });
3759
4117
  }
3760
- async function buildAdapters(deps) {
3761
- const { config, logger, documentStore, repos, payments } = deps;
4118
+ function slotBuilders(deps) {
4119
+ const { config, logger, sql: sql6, repos } = deps;
3762
4120
  const injected = deps.injected ?? {};
3763
4121
  const slot = (name, builtIns) => resolveSlot(name, config, logger, injected, builtIns);
3764
- const email = await slot("email", {
3765
- native: () => createNativeEmailAdapter({ logger: logger.child({ adapter: "email" }) })
3766
- });
3767
- const search = await slot("search", {
3768
- native: () => createNativeSearchAdapter({ documentStore, logger: logger.child({ adapter: "search" }) })
3769
- });
3770
- const reviews3 = await slot("reviews", {
3771
- native: () => createNativeReviewsAdapter({ repos, logger: logger.child({ adapter: "reviews" }) })
3772
- });
3773
- const analytics = await slot("analytics", { native: () => createNativeAnalyticsAdapter(logger) });
3774
- const shipping = await slot("shipping", { native: () => createNativeShippingAdapter(logger) });
3775
- const tax = await slot("tax", { native: () => createNativeTaxAdapter(logger) });
3776
- const ai = await slot("ai", { none: () => null });
4122
+ return {
4123
+ email: () => slot("email", {
4124
+ native: () => createNativeEmailAdapter({ logger: logger.child({ adapter: "email" }) })
4125
+ }),
4126
+ search: () => slot("search", {
4127
+ native: () => createNativeSearchAdapter({ sql: sql6, logger: logger.child({ adapter: "search" }) })
4128
+ }),
4129
+ reviews: () => slot("reviews", {
4130
+ native: () => createNativeReviewsAdapter({ repos, logger: logger.child({ adapter: "reviews" }) })
4131
+ }),
4132
+ analytics: () => slot("analytics", { native: () => createNativeAnalyticsAdapter(logger) }),
4133
+ shipping: () => slot("shipping", { native: () => createNativeShippingAdapter(logger) }),
4134
+ tax: () => slot("tax", { native: () => createNativeTaxAdapter(logger) }),
4135
+ ai: () => slot("ai", { none: () => null })
4136
+ };
4137
+ }
4138
+ async function buildAdapters(deps) {
4139
+ const { logger, payments } = deps;
4140
+ const build = slotBuilders(deps);
4141
+ const email = await build.email();
4142
+ const search = await build.search();
4143
+ const reviews3 = await build.reviews();
4144
+ const analytics = await build.analytics();
4145
+ const shipping = await build.shipping();
4146
+ const tax = await build.tax();
4147
+ const ai = await build.ai();
3777
4148
  const security = createMiddlewareSecurityAdapter({
3778
4149
  logger: logger.child({ adapter: "security" })
3779
4150
  });
3780
4151
  return { security, payments, email, search, reviews: reviews3, analytics, shipping, tax, ai };
3781
4152
  }
3782
4153
 
3783
- // src/media/local-fs-storage.ts
3784
- import { mkdir, writeFile } from "fs/promises";
3785
- import { join as join3 } from "path";
3786
- var LOCAL_FS_MEDIA_CAPABILITIES = ["put"];
3787
- function createLocalFsMediaStorage(options) {
3788
- const { root } = options;
3789
- const urlPrefix = options.urlPrefix ?? "/imported-media";
3790
- return {
3791
- capabilities: () => LOCAL_FS_MEDIA_CAPABILITIES,
3792
- async put(key, body, _contentType) {
3793
- const dest = join3(root, key);
3794
- const dir = dest.substring(0, dest.lastIndexOf("/"));
3795
- await mkdir(dir, { recursive: true });
3796
- await writeFile(dest, body);
3797
- return { url: `${urlPrefix}/${key}` };
3798
- }
3799
- };
3800
- }
3801
-
3802
4154
  // src/services/product-service.ts
3803
4155
  import { v7 as uuidv75 } from "uuid";
3804
4156
  import {
@@ -5608,7 +5960,7 @@ async function warmDocumentStore(deps) {
5608
5960
  if (events3.length > 0) {
5609
5961
  await eventBus.replay(events3);
5610
5962
  }
5611
- logger.info(
5963
+ logger.debug(
5612
5964
  { products: products3.length, orders: orders3.length, customers: customers3.length },
5613
5965
  `Warmed document store: ${products3.length} products, ${orders3.length} orders, ${customers3.length} customers`
5614
5966
  );
@@ -5737,13 +6089,13 @@ function refuseUnsafeProduction(config, payments) {
5737
6089
  if (process.env.NODE_ENV !== "production") return;
5738
6090
  const provider = config.commerce.payments.provider;
5739
6091
  if (payments.providerName === "native-stub") {
5740
- throw new ConfigError6(
6092
+ throw new ConfigError5(
5741
6093
  `Payments provider "${provider}" resolves to the stub adapter, which verifies no webhook signature; configure a real payments provider for production.`,
5742
6094
  { code: "config.production_stub_payments", context: { provider } }
5743
6095
  );
5744
6096
  }
5745
6097
  if (config.security.auth.jwtSecret === DEFAULT_JWT_SECRET) {
5746
- throw new ConfigError6(
6098
+ throw new ConfigError5(
5747
6099
  "security.auth.jwtSecret is the schema default; set a secret of your own for production.",
5748
6100
  { code: "config.production_default_jwt_secret" }
5749
6101
  );
@@ -5755,140 +6107,156 @@ async function createApp(config, options = {}) {
5755
6107
  checkInjectedAdapters(config, options.adapters);
5756
6108
  const payments = await resolvePaymentsAdapter(config, adapterLogger, options.adapters);
5757
6109
  refuseUnsafeProduction(config, payments);
5758
- const platform = createPlatform(config, { ...options, logger });
5759
- const version = options.version ?? "0.1.0";
5760
- const repos = buildRepositories(platform.commandStore, platform.documentStore);
5761
- const adapters = await buildAdapters({
5762
- config,
5763
- logger: adapterLogger,
5764
- documentStore: platform.documentStore,
5765
- repos,
5766
- payments,
5767
- ...options.adapters !== void 0 && { injected: options.adapters }
5768
- });
5769
- const relay = createRelay({
5770
- store: platform.commandStore,
5771
- eventLog: repos.eventLog,
5772
- eventBus: platform.eventBus,
5773
- logger
5774
- });
5775
- const publisher = createEventPublisher({
5776
- eventBus: platform.eventBus,
5777
- store: platform.commandStore,
5778
- eventLog: repos.eventLog,
5779
- relay,
5780
- builderContext: {
5781
- storeId: config.store.name,
5782
- environment: process.env.NODE_ENV === "production" ? "production" : process.env.NODE_ENV === "staging" ? "staging" : "development",
5783
- version,
5784
- source: "nymbal-app"
5785
- }
5786
- });
5787
- const services = buildServices({
5788
- config,
5789
- store: platform.commandStore,
5790
- repos,
5791
- publisher,
5792
- logger: logger.child({ layer: "service" }),
5793
- payments: adapters.payments,
5794
- searchAdapter: adapters.search
5795
- });
5796
- await registerHandlers({
5797
- config,
5798
- eventBus: platform.eventBus,
5799
- documentStore: platform.documentStore,
5800
- repos,
5801
- adapters,
5802
- logger
5803
- });
5804
- await warmDocumentStore({
5805
- config,
5806
- repos,
5807
- eventBus: platform.eventBus,
5808
- logger,
5809
- version
5810
- });
5811
- await relay.drain();
5812
- relay.start();
5813
- const sweepers = [
5814
- startInventoryReservationSweeper({
5815
- inventoryService: services.inventory,
5816
- reservationRepo: repos.inventoryReservation,
5817
- logger
5818
- }),
5819
- startCartAbandonmentSweeper({
6110
+ const primitives = await resolvePrimitives(config, { ...options, logger });
6111
+ let release = async () => {
6112
+ await primitives.eventBus.close();
6113
+ await primitives.documentStore.close();
6114
+ };
6115
+ try {
6116
+ const platform = createPlatform(config, { ...options, ...primitives, logger });
6117
+ release = () => platform.close();
6118
+ const version = options.version ?? "0.1.0";
6119
+ const repos = buildRepositories(platform.commandStore, platform.documentStore);
6120
+ const adapters = await buildAdapters({
6121
+ config,
6122
+ logger: adapterLogger,
6123
+ sql: rawClients(platform.commandStore),
6124
+ repos,
6125
+ payments,
6126
+ ...options.adapters !== void 0 && { injected: options.adapters }
6127
+ });
6128
+ const relay = createRelay({
5820
6129
  store: platform.commandStore,
5821
- carts: repos.cart,
5822
- publisher,
6130
+ eventLog: repos.eventLog,
6131
+ eventBus: platform.eventBus,
5823
6132
  logger
5824
- }),
5825
- startEventRetentionSweeper({
6133
+ });
6134
+ const subscriberBus = deliveringBus(platform.eventBus, relay);
6135
+ const publisher = createEventPublisher({
6136
+ eventBus: platform.eventBus,
5826
6137
  store: platform.commandStore,
5827
6138
  eventLog: repos.eventLog,
5828
- processedEvents: repos.processedEvent,
6139
+ relay,
6140
+ builderContext: {
6141
+ storeId: config.store.name,
6142
+ environment: process.env.NODE_ENV === "production" ? "production" : process.env.NODE_ENV === "staging" ? "staging" : "development",
6143
+ version,
6144
+ source: "nymbal-app"
6145
+ }
6146
+ });
6147
+ const services = buildServices({
6148
+ config,
6149
+ store: platform.commandStore,
6150
+ repos,
6151
+ publisher,
6152
+ logger: logger.child({ layer: "service" }),
6153
+ payments: adapters.payments,
6154
+ searchAdapter: adapters.search
6155
+ });
6156
+ await registerHandlers({
6157
+ config,
6158
+ eventBus: subscriberBus,
6159
+ documentStore: platform.documentStore,
6160
+ repos,
6161
+ adapters,
5829
6162
  logger
5830
- })
5831
- ];
5832
- const app = {
5833
- platform,
5834
- repos,
5835
- adapters,
5836
- services,
5837
- publisher,
5838
- relay,
5839
- async attachHttp(adapter, options2 = {}) {
5840
- await adapters.security.applyMiddleware(adapter, config.security);
5841
- const { registerAllRoutes: registerAllRoutes2 } = await import("./register-IVFYBJSX.js");
5842
- registerAllRoutes2({
5843
- config,
5844
- adapter,
5845
- services,
5846
- adapters,
5847
- repos,
5848
- documentStore: platform.documentStore,
5849
- eventBus: platform.eventBus,
6163
+ });
6164
+ await warmDocumentStore({
6165
+ config,
6166
+ repos,
6167
+ eventBus: platform.eventBus,
6168
+ logger,
6169
+ version
6170
+ });
6171
+ await relay.drain();
6172
+ relay.start();
6173
+ const sweepers = [
6174
+ startInventoryReservationSweeper({
6175
+ inventoryService: services.inventory,
6176
+ reservationRepo: repos.inventoryReservation,
6177
+ logger
6178
+ }),
6179
+ startCartAbandonmentSweeper({
6180
+ store: platform.commandStore,
6181
+ carts: repos.cart,
5850
6182
  publisher,
5851
- adminRoot: options2.adminRoot !== void 0 ? options2.adminRoot : process.env["NYMBAL_ADMIN_DIST"]
5852
- });
5853
- },
5854
- capabilities() {
5855
- const commerce = Object.fromEntries(
5856
- COMMERCE_SLOTS.map((slot) => {
5857
- const adapter = adapters[slot];
5858
- return [
5859
- slot,
5860
- {
5861
- provider: config.commerce[slot].provider,
5862
- capabilities: adapter === null ? [] : adapter.capabilities()
5863
- }
5864
- ];
5865
- })
5866
- );
5867
- return {
5868
- ...commerce,
5869
- security: {
5870
- provider: config.security.adapter,
5871
- capabilities: adapters.security.capabilities()
5872
- },
5873
- documentStore: {
5874
- provider: config.infrastructure.documentStore,
5875
- capabilities: platform.documentStore.capabilities()
5876
- },
5877
- eventBus: {
5878
- provider: config.infrastructure.eventBus,
5879
- capabilities: platform.eventBus.capabilities()
5880
- },
5881
- // The kernel ships one media storage, on the local filesystem; the importer creates it per run.
5882
- media: { provider: "local-fs", capabilities: LOCAL_FS_MEDIA_CAPABILITIES }
5883
- };
5884
- },
5885
- async stop() {
5886
- await relay.stop();
5887
- for (const s of sweepers) s.stop();
5888
- await platform.close();
5889
- }
5890
- };
5891
- return app;
6183
+ logger
6184
+ }),
6185
+ startEventRetentionSweeper({
6186
+ store: platform.commandStore,
6187
+ eventLog: repos.eventLog,
6188
+ processedEvents: repos.processedEvent,
6189
+ logger
6190
+ })
6191
+ ];
6192
+ const app = {
6193
+ platform,
6194
+ repos,
6195
+ adapters,
6196
+ services,
6197
+ publisher,
6198
+ relay,
6199
+ async attachHttp(adapter, options2 = {}) {
6200
+ await adapters.security.applyMiddleware(adapter, config.security);
6201
+ const { registerAllRoutes: registerAllRoutes2 } = await import("./register-FJA7YJV3.js");
6202
+ registerAllRoutes2({
6203
+ config,
6204
+ adapter,
6205
+ services,
6206
+ adapters,
6207
+ repos,
6208
+ documentStore: platform.documentStore,
6209
+ eventBus: subscriberBus,
6210
+ publisher,
6211
+ adminRoot: options2.adminRoot !== void 0 ? options2.adminRoot : process.env["NYMBAL_ADMIN_DIST"]
6212
+ });
6213
+ },
6214
+ capabilities() {
6215
+ const commerce = Object.fromEntries(
6216
+ COMMERCE_SLOTS.map((slot) => {
6217
+ const adapter = adapters[slot];
6218
+ return [
6219
+ slot,
6220
+ {
6221
+ provider: config.commerce[slot].provider,
6222
+ capabilities: adapter === null ? [] : adapter.capabilities()
6223
+ }
6224
+ ];
6225
+ })
6226
+ );
6227
+ return {
6228
+ ...commerce,
6229
+ security: {
6230
+ provider: config.security.adapter,
6231
+ capabilities: adapters.security.capabilities()
6232
+ },
6233
+ documentStore: {
6234
+ provider: config.infrastructure.documentStore,
6235
+ capabilities: platform.documentStore.capabilities()
6236
+ },
6237
+ eventBus: {
6238
+ provider: config.infrastructure.eventBus,
6239
+ capabilities: platform.eventBus.capabilities()
6240
+ },
6241
+ media: {
6242
+ provider: config.infrastructure.media,
6243
+ capabilities: platform.media.capabilities()
6244
+ }
6245
+ };
6246
+ },
6247
+ async stop() {
6248
+ await relay.stop();
6249
+ for (const s of sweepers) s.stop();
6250
+ await platform.close();
6251
+ }
6252
+ };
6253
+ return app;
6254
+ } catch (error) {
6255
+ await release().catch(
6256
+ (err) => logger.error({ err }, "closing the primitives after a failed start failed")
6257
+ );
6258
+ throw error;
6259
+ }
5892
6260
  }
5893
6261
 
5894
6262
  // src/adapters/security/rate-limit.ts
@@ -5970,6 +6338,276 @@ function createNativeAiAdapter(_logger) {
5970
6338
  };
5971
6339
  }
5972
6340
 
6341
+ // src/diagnose.ts
6342
+ import { existsSync as existsSync2 } from "fs";
6343
+ import { resolve as resolve3 } from "path";
6344
+ import { fileURLToPath } from "url";
6345
+ import { nymbalConfigSchema } from "@nymbalhq/config";
6346
+ import {
6347
+ boundedHealthCheck,
6348
+ connectionSecrets,
6349
+ displayUrl,
6350
+ errorText,
6351
+ HEALTH_CHECK_TIMEOUT_MS
6352
+ } from "@nymbalhq/types";
6353
+ var OWN_MIGRATIONS = fileURLToPath(new URL("../migrations", import.meta.url));
6354
+ var PRIMITIVES = ["documentStore", "eventBus", "media"];
6355
+ async function within(timeoutMs, run, dispose) {
6356
+ let timer;
6357
+ let timedOut = false;
6358
+ const work = Promise.resolve().then(run);
6359
+ const timeout = new Promise((resolveTimeout) => {
6360
+ timer = setTimeout(() => {
6361
+ timedOut = true;
6362
+ resolveTimeout({ ok: false, detail: `timed out after ${timeoutMs} ms` });
6363
+ }, timeoutMs);
6364
+ });
6365
+ try {
6366
+ return await Promise.race([
6367
+ work.then(
6368
+ (value) => ({ ok: true, value }),
6369
+ (error) => ({ ok: false, detail: errorText(error) })
6370
+ ),
6371
+ timeout
6372
+ ]);
6373
+ } finally {
6374
+ clearTimeout(timer);
6375
+ if (timedOut && dispose !== void 0) {
6376
+ work.then(dispose).catch(() => void 0);
6377
+ }
6378
+ }
6379
+ }
6380
+ function unavailableCommandStore(kind) {
6381
+ const refuse = () => Promise.reject(new Error("the command store is down"));
6382
+ return { kind, read: refuse, transaction: refuse, savepoint: refuse, close: async () => {
6383
+ } };
6384
+ }
6385
+ function unavailableRawClients(kind) {
6386
+ const refuse = () => {
6387
+ throw new Error("the command store is down");
6388
+ };
6389
+ const client = new Proxy({}, { get: () => refuse });
6390
+ return kind === "sqlite" ? { kind, db: client, raw: client } : { kind, db: client, pool: client };
6391
+ }
6392
+ function unavailableDocumentStore() {
6393
+ const refuse = () => Promise.reject(new Error("the document store is down"));
6394
+ return {
6395
+ capabilities: () => [],
6396
+ get: refuse,
6397
+ put: refuse,
6398
+ delete: refuse,
6399
+ query: refuse,
6400
+ batchGet: refuse,
6401
+ batchPut: refuse,
6402
+ close: async () => {
6403
+ }
6404
+ };
6405
+ }
6406
+ function described(what, detail) {
6407
+ return detail === void 0 || detail === "" ? what : `${what}: ${detail}`;
6408
+ }
6409
+ function notChecked(prerequisite) {
6410
+ return `not checked: ${prerequisite} down`;
6411
+ }
6412
+ async function diagnose(input, options = {}) {
6413
+ const parsed = nymbalConfigSchema.safeParse(input);
6414
+ if (!parsed.success) {
6415
+ const detail = parsed.error.issues.map((issue) => `${issue.path.length > 0 ? issue.path.join(".") : "<root>"}: ${issue.message}`).join("; ");
6416
+ return { checks: [{ name: "config", status: "down", detail }] };
6417
+ }
6418
+ const config = parsed.data;
6419
+ const timeoutMs = options.timeoutMs ?? HEALTH_CHECK_TIMEOUT_MS;
6420
+ const env = options.env ?? process.env;
6421
+ const logger = options.logger ?? createLogger({ base: { store: config.store.name } });
6422
+ const injected = options.adapters ?? {};
6423
+ const infrastructure = config.infrastructure;
6424
+ const providers = {
6425
+ ...Object.fromEntries(COMMERCE_SLOTS.map((s) => [s, config.commerce[s].provider])),
6426
+ documentStore: infrastructure.documentStore,
6427
+ eventBus: infrastructure.eventBus,
6428
+ media: infrastructure.media
6429
+ };
6430
+ const packages = [];
6431
+ for (const slot of [...COMMERCE_SLOTS, ...PRIMITIVES]) {
6432
+ const entry = PROVIDER_PACKAGES[slot]?.[providers[slot]];
6433
+ if (entry === void 0) continue;
6434
+ const found = await within(
6435
+ timeoutMs,
6436
+ () => importProviderPackage(slot, providers[slot], env)
6437
+ );
6438
+ packages.push({
6439
+ name: `package ${slot}`,
6440
+ status: found.ok ? "ok" : "down",
6441
+ detail: found.ok ? entry.package : found.detail
6442
+ });
6443
+ }
6444
+ const closers = [];
6445
+ let commandStore;
6446
+ let storeCheck;
6447
+ let migrationsCheck;
6448
+ const storeOptions = {
6449
+ readOnly: true,
6450
+ ...options.sqlitePath !== void 0 && { sqlitePath: options.sqlitePath },
6451
+ ...options.postgresUrl !== void 0 && { postgresUrl: options.postgresUrl }
6452
+ };
6453
+ const postgresUrl = options.postgresUrl ?? (env["DATABASE_URL"] === "" ? void 0 : env["DATABASE_URL"]);
6454
+ const redisUrl = redisUrlOf(config, env);
6455
+ const where = infrastructure.commandStore === "sqlite" ? `sqlite ${sqliteFile(storeOptions)}` : `postgres ${postgresUrl === void 0 ? "(no DATABASE_URL)" : displayUrl(postgresUrl)}`;
6456
+ if (infrastructure.commandStore === "sqlite" && !existsSync2(resolve3(sqliteFile(storeOptions)))) {
6457
+ storeCheck = {
6458
+ name: "command store",
6459
+ status: "down",
6460
+ detail: `no database at ${sqliteFile(storeOptions)}: run \`nymbal migrate\``
6461
+ };
6462
+ } else {
6463
+ const opened = await within(
6464
+ timeoutMs,
6465
+ async () => {
6466
+ const store = createCommandStore(config, storeOptions);
6467
+ try {
6468
+ const clients = rawClients(store);
6469
+ if (clients.kind === "sqlite") clients.raw.prepare("SELECT 1").get();
6470
+ else await clients.pool.query("SELECT 1");
6471
+ return store;
6472
+ } catch (error) {
6473
+ await store.close().catch(() => void 0);
6474
+ throw error;
6475
+ }
6476
+ },
6477
+ (late) => late.close()
6478
+ );
6479
+ if (opened.ok) {
6480
+ commandStore = opened.value;
6481
+ closers.push(() => opened.value.close());
6482
+ storeCheck = { name: "command store", status: "healthy", detail: where };
6483
+ } else {
6484
+ storeCheck = { name: "command store", status: "down", detail: `${where}: ${opened.detail}` };
6485
+ }
6486
+ }
6487
+ if (commandStore === void 0) {
6488
+ migrationsCheck = { name: "migrations", status: "down", detail: notChecked("command store") };
6489
+ } else {
6490
+ const store = commandStore;
6491
+ const state = await within(
6492
+ timeoutMs,
6493
+ () => migrationState(store, { migrationsRoot: options.migrationsRoot ?? OWN_MIGRATIONS })
6494
+ );
6495
+ migrationsCheck = !state.ok ? { name: "migrations", status: "down", detail: state.detail } : state.value.pending > 0 ? {
6496
+ name: "migrations",
6497
+ status: "down",
6498
+ detail: `${state.value.pending} pending: run \`nymbal migrate\``
6499
+ } : { name: "migrations", status: "ok", detail: `${state.value.applied} applied, none pending` };
6500
+ }
6501
+ const primitiveOptions = {
6502
+ logger,
6503
+ env,
6504
+ ...options.postgresUrl !== void 0 && { postgresUrl: options.postgresUrl },
6505
+ ...options.mediaRoot !== void 0 && { mediaRoot: options.mediaRoot }
6506
+ };
6507
+ const subject = (name) => {
6508
+ const provider = providers[name];
6509
+ const url = provider === "redis" || provider === "redis-streams" ? redisUrl : provider === "postgres-jsonb" ? postgresUrl : void 0;
6510
+ return url === void 0 ? provider : `${provider} ${displayUrl(url)}`;
6511
+ };
6512
+ const built = {};
6513
+ const primitiveFailures = {};
6514
+ let documentStore;
6515
+ if (infrastructure.documentStore === "postgres-jsonb" && commandStore === void 0) {
6516
+ primitiveFailures.documentStore = notChecked("command store");
6517
+ } else {
6518
+ const store = await within(
6519
+ timeoutMs,
6520
+ () => buildDocumentStore(config, primitiveOptions, logger, env),
6521
+ (late) => late.close()
6522
+ );
6523
+ if (store.ok) {
6524
+ documentStore = store.value;
6525
+ built.documentStore = store.value;
6526
+ closers.unshift(() => store.value.close());
6527
+ } else {
6528
+ primitiveFailures.documentStore = described(subject("documentStore"), store.detail);
6529
+ }
6530
+ }
6531
+ const bus = await within(
6532
+ timeoutMs,
6533
+ () => buildEventBus(config, logger, env),
6534
+ (late) => late.close()
6535
+ );
6536
+ if (bus.ok) {
6537
+ built.eventBus = bus.value;
6538
+ closers.unshift(() => bus.value.close());
6539
+ } else {
6540
+ primitiveFailures.eventBus = described(subject("eventBus"), bus.detail);
6541
+ }
6542
+ const media = await within(timeoutMs, () => buildMedia(config, primitiveOptions, logger, env));
6543
+ if (media.ok) built.media = media.value;
6544
+ else primitiveFailures.media = described(subject("media"), media.detail);
6545
+ const health = (subject2) => {
6546
+ if (typeof subject2.healthCheck !== "function") {
6547
+ return Promise.resolve({ status: "degraded", detail: "no healthCheck" });
6548
+ }
6549
+ const check = subject2.healthCheck.bind(subject2);
6550
+ return boundedHealthCheck(() => check(), { timeoutMs });
6551
+ };
6552
+ const slots = [];
6553
+ const adapterLogger = logger.child({ layer: "adapter" });
6554
+ const builders = slotBuilders({
6555
+ config,
6556
+ logger: adapterLogger,
6557
+ sql: commandStore === void 0 ? unavailableRawClients(infrastructure.commandStore) : rawClients(commandStore),
6558
+ repos: buildRepositories(
6559
+ commandStore ?? unavailableCommandStore(infrastructure.commandStore),
6560
+ documentStore ?? unavailableDocumentStore()
6561
+ ),
6562
+ injected
6563
+ });
6564
+ for (const slot of COMMERCE_SLOTS) {
6565
+ const provider = providers[slot];
6566
+ const adapter = await within(timeoutMs, async () => {
6567
+ checkInjectedSlot(config, slot, injected);
6568
+ return slot === "payments" ? resolvePaymentsAdapter(config, adapterLogger, injected) : builders[slot]();
6569
+ });
6570
+ if (!adapter.ok) {
6571
+ slots.push({ name: `slot ${slot}`, status: "down", detail: described(provider, adapter.detail) });
6572
+ } else if (adapter.value === null) {
6573
+ slots.push({ name: `slot ${slot}`, status: "ok", detail: provider });
6574
+ } else {
6575
+ slots.push(fromReport(`slot ${slot}`, provider, await health(adapter.value)));
6576
+ }
6577
+ }
6578
+ const primitives = [];
6579
+ for (const name of PRIMITIVES) {
6580
+ const primitive = built[name];
6581
+ if (primitive === void 0) {
6582
+ primitives.push({ name: `primitive ${name}`, status: "down", detail: primitiveFailures[name] ?? "" });
6583
+ } else {
6584
+ primitives.push(fromReport(`primitive ${name}`, subject(name), await health(primitive)));
6585
+ }
6586
+ }
6587
+ for (const close of closers) {
6588
+ const closed = await within(timeoutMs, close);
6589
+ if (!closed.ok) logger.debug({ detail: closed.detail }, "diagnose: a connection did not close");
6590
+ }
6591
+ const secrets = [postgresUrl, redisUrl].flatMap(
6592
+ (url) => url === void 0 ? [] : connectionSecrets(url, { user: false })
6593
+ );
6594
+ const checks = [
6595
+ { name: "config", status: "ok", detail: "valid" },
6596
+ ...packages,
6597
+ storeCheck,
6598
+ migrationsCheck,
6599
+ ...slots,
6600
+ ...primitives
6601
+ ].map((check) => ({
6602
+ ...check,
6603
+ detail: secrets.reduce((text, secret) => text.split(secret).join("***"), check.detail)
6604
+ }));
6605
+ return { checks };
6606
+ }
6607
+ function fromReport(name, what, report) {
6608
+ return { name, status: report.status, detail: described(what, report.detail) };
6609
+ }
6610
+
5973
6611
  // src/seed/run.ts
5974
6612
  import { inArray as inArray3 } from "drizzle-orm";
5975
6613
  import { v7 as uuidv713 } from "uuid";
@@ -6387,8 +7025,10 @@ export {
6387
7025
  CSRF_HEADER,
6388
7026
  InMemoryDocumentStore,
6389
7027
  InProcessEventBus,
7028
+ LOCAL_FS_MEDIA_CAPABILITIES,
6390
7029
  PROVIDER_PACKAGES,
6391
7030
  PROVIDER_REFUND_REASON,
7031
+ REDIS_DEFAULTS,
6392
7032
  RateLimiter,
6393
7033
  buildAdapters,
6394
7034
  buildRepositories,
@@ -6404,9 +7044,7 @@ export {
6404
7044
  createCommandStore,
6405
7045
  createCustomerRepository,
6406
7046
  createCustomerService,
6407
- createDocumentStore,
6408
7047
  createEventBuilder,
6409
- createEventBus,
6410
7048
  createEventLogRepository,
6411
7049
  createEventPublisher,
6412
7050
  createInventoryReservationRepository,
@@ -6441,18 +7079,23 @@ export {
6441
7079
  createSearchService,
6442
7080
  createStockAdjustmentRepository,
6443
7081
  createVariantRepository,
7082
+ diagnose,
7083
+ encodeSearchCursor,
7084
+ installLine,
6444
7085
  orderPayment,
6445
7086
  rawClients,
6446
7087
  refreshRefunded,
6447
7088
  registerAdminStaticRoute,
6448
7089
  registerAllRoutes,
6449
7090
  registerHandlers,
7091
+ resolvePrimitives,
6450
7092
  routeSchemas,
6451
7093
  runMigrations,
6452
7094
  runSeed,
6453
7095
  seedCategories,
6454
7096
  seedProducts,
6455
7097
  settlementOf,
7098
+ sqliteFile,
6456
7099
  startCartAbandonmentSweeper,
6457
7100
  startEventRetentionSweeper,
6458
7101
  startInventoryReservationSweeper,