nymbal 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/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/index.ts
2
- import { defineCommand as defineCommand15, runMain } from "citty";
2
+ import { defineCommand as defineCommand17, runMain, showUsage } from "citty";
3
3
 
4
4
  // src/utils/version.ts
5
5
  import { readFileSync } from "fs";
@@ -30,6 +30,7 @@ import { resolve as resolve4 } from "path";
30
30
  import { defineCommand as defineCommand2 } from "citty";
31
31
  import pc from "picocolors";
32
32
  import { KNOWN_PROVIDERS } from "@nymbalhq/config";
33
+ import { ConfigError } from "@nymbalhq/types";
33
34
 
34
35
  // src/utils/project.ts
35
36
  import { existsSync } from "fs";
@@ -56,9 +57,9 @@ function run(command, args, options = {}) {
56
57
  shell: false,
57
58
  ...options
58
59
  });
59
- const done = new Promise((resolve10, reject) => {
60
+ const done = new Promise((resolve11, reject) => {
60
61
  child2.on("error", reject);
61
- child2.on("exit", (code) => resolve10(code ?? 0));
62
+ child2.on("exit", (code) => resolve11(code ?? 0));
62
63
  });
63
64
  return { child: child2, done };
64
65
  }
@@ -73,16 +74,16 @@ async function runOrFail(command, args, options = {}) {
73
74
  // src/utils/port.ts
74
75
  import { createServer } from "net";
75
76
  async function isPortFree(port, host) {
76
- return new Promise((resolve10) => {
77
+ return new Promise((resolve11) => {
77
78
  const server = createServer();
78
79
  server.once("error", (err2) => {
79
80
  if (err2.code !== "EADDRINUSE" && err2.code !== "EACCES") {
80
81
  console.error(`[dev] unexpected error probing port ${port}:`, err2.message);
81
82
  }
82
- resolve10(false);
83
+ resolve11(false);
83
84
  });
84
85
  server.once("listening", () => {
85
- server.close(() => resolve10(true));
86
+ server.close(() => resolve11(true));
86
87
  });
87
88
  if (host) {
88
89
  server.listen(port, host);
@@ -243,8 +244,8 @@ async function runShutdown(steps, opts) {
243
244
  pending = void 0;
244
245
  })();
245
246
  let timer;
246
- const bound = new Promise((resolve10) => {
247
- timer = setTimeout(() => resolve10("bound"), opts.boundMs);
247
+ const bound = new Promise((resolve11) => {
248
+ timer = setTimeout(() => resolve11("bound"), opts.boundMs);
248
249
  });
249
250
  const outcome = await Promise.race([work.then(() => "done"), bound]);
250
251
  clearTimeout(timer);
@@ -259,6 +260,7 @@ async function runShutdown(steps, opts) {
259
260
  }
260
261
 
261
262
  // src/commands/dev-summary.ts
263
+ import { slotFolder } from "@nymbalhq/config";
262
264
  import { displayUrl } from "@nymbalhq/types";
263
265
  var WIDTH = 100;
264
266
  var LABEL = 14;
@@ -307,7 +309,7 @@ function renderDevSummary(info) {
307
309
  "",
308
310
  ...slotLines,
309
311
  "",
310
- ...info.primitives.map(({ name, provider }) => row(name, provider)),
312
+ ...info.primitives.map(({ name, provider }) => row(slotFolder(name), provider)),
311
313
  "",
312
314
  " Debug logs: run with --verbose (or LOG_LEVEL=debug)."
313
315
  ];
@@ -426,6 +428,11 @@ var devCommand = defineCommand2({
426
428
  version,
427
429
  logger,
428
430
  ...loaded.adapters !== void 0 && { adapters: loaded.adapters }
431
+ }).catch((error) => {
432
+ if (!(error instanceof ConfigError)) throw error;
433
+ process.stderr.write(`${pc.red(error.message)}
434
+ `);
435
+ process.exit(1);
429
436
  });
430
437
  const { platform } = app;
431
438
  if (args.seed) {
@@ -522,11 +529,93 @@ var devCommand = defineCommand2({
522
529
  });
523
530
 
524
531
  // src/commands/build.ts
532
+ import { existsSync as existsSync5, readFileSync as readFileSync2, writeFileSync } from "fs";
533
+ import { join as join3 } from "path";
525
534
  import { defineCommand as defineCommand3 } from "citty";
535
+
536
+ // src/deploy/dockerfile.ts
537
+ var FROZEN_INSTALL = {
538
+ npm: "npm ci",
539
+ pnpm: "pnpm install --frozen-lockfile",
540
+ yarn: "yarn install --immutable",
541
+ bun: "bun install --frozen-lockfile"
542
+ };
543
+ function parsePackageManager(packageManager) {
544
+ const match = /^(npm|pnpm|yarn|bun)@(\d+\.\d+\.\d+[^\s+]*)/.exec(packageManager.trim());
545
+ if (!match) {
546
+ throw new Error(
547
+ `package.json "packageManager" must be npm, pnpm, yarn or bun at a version, such as "pnpm@10.18.0"`
548
+ );
549
+ }
550
+ return { name: match[1], version: match[2] };
551
+ }
552
+ function renderDockerfile(options) {
553
+ const { name, version } = parsePackageManager(options.packageManager);
554
+ const manager = name === "bun" ? `RUN npm install -g bun@${version}` : "RUN npm install -g corepack@0.36.0 && corepack enable";
555
+ const berry = name === "yarn" && Number(version.split(".")[0]) >= 2;
556
+ return [
557
+ `ARG NODE_VERSION=${options.nodeVersion}`,
558
+ "",
559
+ "FROM node:${NODE_VERSION}-slim AS build",
560
+ "ENV COREPACK_ENABLE_DOWNLOAD_PROMPT=0",
561
+ "WORKDIR /app",
562
+ // better-sqlite3 compiles from source when its prebuilt binary cannot be fetched for this Node and platform.
563
+ "RUN apt-get update && apt-get install -y --no-install-recommends python3 make g++ && rm -rf /var/lib/apt/lists/*",
564
+ manager,
565
+ "COPY . .",
566
+ ...berry ? [
567
+ "RUN grep -q '^nodeLinker:' .yarnrc.yml 2>/dev/null || echo 'nodeLinker: node-modules' >> .yarnrc.yml"
568
+ ] : [],
569
+ `RUN ${FROZEN_INSTALL[name]}`,
570
+ // An empty public API URL: the browser calls the origin that served the page.
571
+ "RUN PUBLIC_NYMBAL_API_URL= NEXT_PUBLIC_NYMBAL_API_URL= node node_modules/nymbal/bin/nymbal.mjs build",
572
+ "",
573
+ "FROM node:${NODE_VERSION}-slim",
574
+ "ENV NODE_ENV=production",
575
+ "WORKDIR /app",
576
+ "COPY --from=build --chown=node:node /app /app",
577
+ "USER node",
578
+ "EXPOSE 3001",
579
+ 'CMD ["node", "node_modules/nymbal/bin/nymbal.mjs", "start"]',
580
+ ""
581
+ ].join("\n");
582
+ }
583
+ var DOCKERIGNORE = [
584
+ ".env*",
585
+ "**/.env*",
586
+ "*.db",
587
+ "*.db-*",
588
+ "**/*.db",
589
+ "**/*.db-*",
590
+ "node_modules",
591
+ "**/node_modules",
592
+ "dist",
593
+ ".astro",
594
+ ".next",
595
+ ".git",
596
+ ""
597
+ ].join("\n");
598
+
599
+ // src/commands/build.ts
526
600
  var buildCommand = defineCommand3({
527
601
  meta: { name: "build", description: "Production build of the configured template" },
528
- async run() {
602
+ args: {
603
+ image: {
604
+ type: "boolean",
605
+ description: "Build a container image of the store (writes a Dockerfile when absent)",
606
+ default: false
607
+ },
608
+ tag: {
609
+ type: "string",
610
+ description: "The image name (default: <package name>:latest)"
611
+ }
612
+ },
613
+ async run({ args }) {
529
614
  const { config, projectRoot } = await loadProject();
615
+ if (args.image) {
616
+ await buildImage(projectRoot, config.template, args.tag, args._);
617
+ return;
618
+ }
530
619
  if (!isFlatScaffold(projectRoot, config.template)) {
531
620
  await runOrFail("pnpm", ["--filter", templateFilterFor(config.template), "build"], {
532
621
  cwd: projectRoot
@@ -543,11 +632,617 @@ var buildCommand = defineCommand3({
543
632
  await runOrFail(bin, ["build"], { cwd: projectRoot });
544
633
  }
545
634
  });
635
+ async function buildImage(root, template, tag, dockerArgs) {
636
+ const pkg = JSON.parse(readFileSync2(join3(root, "package.json"), "utf8"));
637
+ const dockerfile = join3(root, "Dockerfile");
638
+ if (existsSync5(dockerfile)) {
639
+ console.log("Using the Dockerfile already in the project, as it is");
640
+ } else {
641
+ if (pkg.packageManager === void 0) {
642
+ throw new Error(
643
+ 'package.json records no "packageManager" (such as "pnpm@10.18.0"), so the image cannot install as the project does'
644
+ );
645
+ }
646
+ const nodeVersionFile = join3(root, ".node-version");
647
+ const nodeVersion = existsSync5(nodeVersionFile) ? readFileSync2(nodeVersionFile, "utf8").trim().replace(/^v/, "") : process.versions.node;
648
+ writeFileSync(
649
+ dockerfile,
650
+ renderDockerfile({ packageManager: pkg.packageManager, nodeVersion, template })
651
+ );
652
+ console.log("\u2713 wrote Dockerfile");
653
+ }
654
+ const ignore = join3(root, ".dockerignore");
655
+ if (!existsSync5(ignore)) {
656
+ writeFileSync(ignore, DOCKERIGNORE);
657
+ console.log("\u2713 wrote .dockerignore");
658
+ }
659
+ const name = tag ?? `${(pkg.name ?? "store").replace(/^@/, "").replace(/\//g, "-")}:latest`;
660
+ await runOrFail("docker", ["build", "-t", name, ...dockerArgs, "."], { cwd: root });
661
+ }
546
662
 
547
- // src/commands/seed.ts
663
+ // src/commands/start.ts
664
+ import { spawn as spawn2 } from "child_process";
665
+ import { existsSync as existsSync6 } from "fs";
666
+ import { createRequire as createRequire2 } from "module";
667
+ import { connect, createServer as createServer2 } from "net";
668
+ import { join as join4, resolve as resolve5 } from "path";
548
669
  import { defineCommand as defineCommand4 } from "citty";
549
- import { createPlatform, resolvePrimitives, runSeed as runSeed2 } from "@nymbalhq/platform";
550
- var seedCommand = defineCommand4({
670
+ import pc2 from "picocolors";
671
+ import { boundedHealthCheck, ConfigError as ConfigError2 } from "@nymbalhq/types";
672
+ import {
673
+ createApp as createApp2,
674
+ createCommandStore as createCommandStore2,
675
+ createLogger as createLogger2,
676
+ keyProblem,
677
+ migrationState,
678
+ readSecretsKey,
679
+ resolveAuthSecret,
680
+ runMigrations as runMigrations2
681
+ } from "@nymbalhq/platform";
682
+ import {
683
+ createHttpServer as createHttpServer2,
684
+ createReadyRoute,
685
+ FastifyHttpAdapter,
686
+ forwardToStorefront,
687
+ resolveTrustProxy
688
+ } from "@nymbalhq/http";
689
+ var DEFAULT_PORT = 3001;
690
+ var DEFAULT_SHUTDOWN_MS = 1e4;
691
+ var STOREFRONT_START_MS = 6e4;
692
+ function publicOrigin(value) {
693
+ if (value === void 0 || value.trim() === "") return null;
694
+ try {
695
+ const url = new URL(value.trim());
696
+ const plain = (url.protocol === "http:" || url.protocol === "https:") && url.pathname === "/" && url.search === "" && url.hash === "" && url.username === "" && url.password === "";
697
+ return plain ? url.origin : null;
698
+ } catch {
699
+ return null;
700
+ }
701
+ }
702
+ function checkStartEnv(config, env) {
703
+ const problems = [];
704
+ const isSet2 = (name) => (env[name] ?? "").trim() !== "";
705
+ const infra = config.infrastructure;
706
+ if (infra.commandStore === "postgres" && !isSet2("DATABASE_URL")) {
707
+ problems.push("DATABASE_URL is not set: the postgres command store connects with it");
708
+ }
709
+ const onRedis = infra.documentStore.provider === "redis" || infra.eventBus.provider === "redis-streams";
710
+ if (onRedis && infra.redis?.url === void 0 && !isSet2("REDIS_URL")) {
711
+ problems.push(
712
+ "REDIS_URL is not set: the Redis document store and event bus connect with it (or set infrastructure.redis.url)"
713
+ );
714
+ }
715
+ const key = readSecretsKey(env);
716
+ if (!key.ok) {
717
+ problems.push(`${keyProblem(key.reason)}: settings are encrypted with it`);
718
+ }
719
+ if (!isSet2("NYMBAL_PUBLIC_URL")) {
720
+ problems.push("NYMBAL_PUBLIC_URL is not set: give the store's public origin, such as https://\u2026");
721
+ } else if (publicOrigin(env["NYMBAL_PUBLIC_URL"]) === null) {
722
+ problems.push("NYMBAL_PUBLIC_URL must be an http or https origin with no path");
723
+ }
724
+ const refusal = (check) => {
725
+ try {
726
+ return check();
727
+ } catch (error) {
728
+ if (!(error instanceof ConfigError2)) throw error;
729
+ problems.push(error.message);
730
+ return void 0;
731
+ }
732
+ };
733
+ const jwt = refusal(() => resolveAuthSecret(config, env));
734
+ refusal(() => resolveTrustProxy(config, env));
735
+ if (env["NODE_ENV"] === "development") {
736
+ problems.push("NODE_ENV is development: nymbal start runs in production; unset it");
737
+ }
738
+ if (env["NODE_ENV"] === "production") {
739
+ if (config.commerce.payments.provider === "native") {
740
+ problems.push(
741
+ "commerce.payments.provider is native, the stub that verifies no webhook signature (config.production_stub_payments): configure a real payments provider, such as `nymbal add stripe`"
742
+ );
743
+ }
744
+ if (jwt?.source === "default") {
745
+ problems.push(
746
+ "security.auth.jwtSecret is the schema default (config.production_default_jwt_secret): set NYMBAL_JWT_SECRET (create-nymbal-app writes one into .env) or a secret of your own in nymbal.config.ts"
747
+ );
748
+ }
749
+ }
750
+ return problems;
751
+ }
752
+ var STOREFRONT_NYMBAL_ENV = /* @__PURE__ */ new Set([
753
+ "NYMBAL_API_URL",
754
+ "NYMBAL_PUBLIC_URL",
755
+ "NYMBAL_CATALOG_REVALIDATE_S",
756
+ "NYMBAL_NEXT_DIST_DIR"
757
+ ]);
758
+ function storefrontEnv2(env) {
759
+ return Object.fromEntries(
760
+ Object.entries(env).filter(
761
+ ([name]) => name !== "DATABASE_URL" && name !== "REDIS_URL" && (!name.startsWith("NYMBAL_") || STOREFRONT_NYMBAL_ENV.has(name))
762
+ )
763
+ );
764
+ }
765
+ function fail(lines) {
766
+ for (const line of lines) process.stderr.write(`${pc2.red(line)}
767
+ `);
768
+ process.exit(1);
769
+ }
770
+ function publicPort(flag2, env) {
771
+ const given = flag2 !== void 0 && flag2.trim() !== "" ? flag2 : env["PORT"];
772
+ if (given === void 0 || given.trim() === "") return DEFAULT_PORT;
773
+ const port = Number(given);
774
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
775
+ fail([`The port must be an integer from 1 to 65535, got "${given}"`]);
776
+ }
777
+ return port;
778
+ }
779
+ function shutdownBound(env) {
780
+ const ms = Number(env["NYMBAL_SHUTDOWN_MS"]);
781
+ return Number.isInteger(ms) && ms > 0 ? ms : DEFAULT_SHUTDOWN_MS;
782
+ }
783
+ function storefrontLaunch(root, template, env) {
784
+ const entry = env["NYMBAL_STOREFRONT_ENTRY"];
785
+ if (entry !== void 0 && entry.trim() !== "") {
786
+ const file = resolve5(root, entry);
787
+ return () => [file];
788
+ }
789
+ if (template === "astro") {
790
+ const file = join4(root, "dist", "server", "entry.mjs");
791
+ if (!existsSync6(file)) return "The storefront is not built: run `nymbal build` first";
792
+ return () => [file];
793
+ }
794
+ if (!existsSync6(join4(root, ".next", "BUILD_ID"))) {
795
+ return "The storefront is not built: run `nymbal build` first";
796
+ }
797
+ const next = createRequire2(join4(root, "package.json")).resolve("next/dist/bin/next");
798
+ return (port) => [next, "start", "-H", "127.0.0.1", "-p", String(port)];
799
+ }
800
+ async function migrationGate(config, migrationsRoot, apply) {
801
+ const store = createCommandStore2(config);
802
+ try {
803
+ const { pending } = await migrationState(store, { migrationsRoot });
804
+ if (pending === 0) return;
805
+ if (!apply) {
806
+ fail([
807
+ `${pending} migration${pending === 1 ? "" : "s"} pending: run \`nymbal migrate\` (a deploy's release step does), or \`nymbal start --migrate\` on a single host`
808
+ ]);
809
+ }
810
+ await runMigrations2(store, { migrationsRoot });
811
+ } finally {
812
+ await store.close();
813
+ }
814
+ }
815
+ function loopbackPort() {
816
+ return new Promise((resolvePort, reject) => {
817
+ const server = createServer2();
818
+ server.once("error", reject);
819
+ server.listen(0, "127.0.0.1", () => {
820
+ const { port } = server.address();
821
+ server.close(() => resolvePort(port));
822
+ });
823
+ });
824
+ }
825
+ async function listening(port, gone, withinMs) {
826
+ let exited = false;
827
+ void gone.then(() => exited = true);
828
+ const deadline = Date.now() + withinMs;
829
+ while (!exited && Date.now() < deadline) {
830
+ const open = await new Promise((resolveOpen) => {
831
+ const socket = connect(port, "127.0.0.1");
832
+ socket.once("connect", () => {
833
+ socket.destroy();
834
+ resolveOpen(true);
835
+ });
836
+ socket.once("error", () => resolveOpen(false));
837
+ });
838
+ if (open) return true;
839
+ await new Promise((r) => setTimeout(r, 100));
840
+ }
841
+ return false;
842
+ }
843
+ async function commandStoreReport(store, migrationsRoot) {
844
+ const { pending } = await migrationState(store, { migrationsRoot });
845
+ return { status: pending === 0 ? "healthy" : "down" };
846
+ }
847
+ var startCommand = defineCommand4({
848
+ meta: {
849
+ name: "start",
850
+ description: "Run the built store in production: the API, the admin and the storefront on one port"
851
+ },
852
+ args: {
853
+ migrate: {
854
+ type: "boolean",
855
+ description: "Apply pending migrations first (a single host; a deploy runs `nymbal migrate`)",
856
+ default: false
857
+ },
858
+ port: {
859
+ type: "string",
860
+ description: "The public port (default: PORT, else 3001)"
861
+ }
862
+ },
863
+ async run({ args }) {
864
+ let child2 = null;
865
+ const childAlive = () => child2 !== null && child2.exitCode === null && child2.signalCode === null;
866
+ const stopBoot = () => {
867
+ if (childAlive()) child2.kill("SIGKILL");
868
+ process.exit(1);
869
+ };
870
+ process.on("SIGTERM", stopBoot);
871
+ process.on("SIGINT", stopBoot);
872
+ const loaded = await loadProject().catch(
873
+ (error) => fail([error instanceof Error ? error.message : String(error)])
874
+ );
875
+ const { projectRoot } = loaded;
876
+ if ((process.env["NODE_ENV"] ?? "") === "") process.env["NODE_ENV"] = "production";
877
+ const problems = checkStartEnv(loaded.config, process.env);
878
+ if (problems.length > 0) fail(problems);
879
+ const port = publicPort(args.port, process.env);
880
+ const publicUrl = publicOrigin(process.env["NYMBAL_PUBLIC_URL"]);
881
+ const launch = storefrontLaunch(projectRoot, loaded.config.template, process.env);
882
+ if (typeof launch === "string") fail([launch]);
883
+ const config = {
884
+ ...loaded.config,
885
+ http: {
886
+ ...loaded.config.http,
887
+ port,
888
+ // The store's own pages subscribe to alerts and call the API from this origin.
889
+ cors: {
890
+ ...loaded.config.http.cors,
891
+ allowedOrigins: [.../* @__PURE__ */ new Set([...loaded.config.http.cors.allowedOrigins, publicUrl])]
892
+ }
893
+ }
894
+ };
895
+ const migrationsRoot = resolveMigrations(projectRoot);
896
+ await migrationGate(config, migrationsRoot, args.migrate);
897
+ const version = getCliVersion();
898
+ const logger = createLogger2({
899
+ base: { store: config.store.name },
900
+ level: process.env["LOG_LEVEL"] || "info"
901
+ });
902
+ const app = await createApp2(config, {
903
+ version,
904
+ logger,
905
+ ...loaded.adapters !== void 0 && { adapters: loaded.adapters }
906
+ }).catch((error) => {
907
+ if (!(error instanceof ConfigError2)) throw error;
908
+ return fail([error.message]);
909
+ });
910
+ const { platform } = app;
911
+ let stopping = false;
912
+ const downAs = async (name, check) => (await boundedHealthCheck(check)).status === "down" ? name : null;
913
+ const probe = async () => {
914
+ if (stopping) return { ready: false, failing: [] };
915
+ const down = (await Promise.all([
916
+ downAs("command-store", () => commandStoreReport(platform.commandStore, migrationsRoot)),
917
+ downAs(
918
+ "document-store",
919
+ () => platform.documentStore.healthCheck?.() ?? { status: "degraded" }
920
+ ),
921
+ downAs("event-bus", () => platform.eventBus.healthCheck?.() ?? { status: "degraded" })
922
+ ])).filter((name) => name !== null);
923
+ return down.length === 0 ? { ready: true } : { ready: false, failing: down };
924
+ };
925
+ const http = createHttpServer2({
926
+ config,
927
+ logger: platform.logger,
928
+ documentStore: platform.documentStore,
929
+ version
930
+ });
931
+ http.registerRoute("GET", "/ready", createReadyRoute(probe));
932
+ await app.attachHttp(http.adapter, { adminRoot: resolveAdminRoot() });
933
+ if (!(http.adapter instanceof FastifyHttpAdapter)) {
934
+ throw new Error("nymbal start needs the fastify http adapter");
935
+ }
936
+ const internalPort = await loopbackPort();
937
+ const forward = forwardToStorefront(http.adapter, { port: internalPort, publicUrl });
938
+ const storefront = spawn2(process.execPath, launch(internalPort), {
939
+ cwd: projectRoot,
940
+ stdio: "inherit",
941
+ env: {
942
+ ...storefrontEnv2(process.env),
943
+ HOST: "127.0.0.1",
944
+ PORT: String(internalPort),
945
+ NYMBAL_API_URL: `http://127.0.0.1:${port}`,
946
+ NYMBAL_PUBLIC_URL: publicUrl
947
+ }
948
+ });
949
+ child2 = storefront;
950
+ const childGone = new Promise((resolveGone) => {
951
+ storefront.once("exit", () => resolveGone());
952
+ storefront.once("error", () => resolveGone());
953
+ });
954
+ process.on("exit", () => {
955
+ if (childAlive()) storefront.kill("SIGKILL");
956
+ });
957
+ if (!await listening(internalPort, childGone, STOREFRONT_START_MS)) {
958
+ fail([`The storefront did not start listening within ${STOREFRONT_START_MS / 1e3} s`]);
959
+ }
960
+ const bound = await http.start();
961
+ console.log(`nymbal start: ${publicUrl} on port ${bound.port}`);
962
+ const boundMs = shutdownBound(process.env);
963
+ const reserveMs = Math.min(3e3, Math.floor(boundMs * 0.3));
964
+ const steps = [
965
+ {
966
+ name: "ready.refuse",
967
+ run: async () => {
968
+ stopping = true;
969
+ }
970
+ },
971
+ {
972
+ name: "storefront.drain",
973
+ run: async () => {
974
+ forward.refuse();
975
+ if (!await forward.drained(boundMs - reserveMs)) {
976
+ platform.logger.warn({ inFlight: forward.inFlight() }, "Page requests still open");
977
+ }
978
+ }
979
+ },
980
+ {
981
+ name: "storefront.stop",
982
+ run: async () => {
983
+ if (!childAlive()) return;
984
+ storefront.kill("SIGTERM");
985
+ let timer;
986
+ const graceful = await Promise.race([
987
+ childGone.then(() => true),
988
+ new Promise((r) => timer = setTimeout(() => r(false), reserveMs / 2))
989
+ ]);
990
+ clearTimeout(timer);
991
+ if (!graceful) {
992
+ storefront.kill("SIGKILL");
993
+ await childGone;
994
+ }
995
+ }
996
+ },
997
+ { name: "http.stop", run: () => http.stop() },
998
+ { name: "app.stop", run: () => app.stop() }
999
+ ];
1000
+ let failed = false;
1001
+ const shutdown = (reason) => {
1002
+ platform.logger.info({ reason }, "Shutting down");
1003
+ return runShutdown(steps, {
1004
+ boundMs,
1005
+ logger: platform.logger,
1006
+ exit: (code) => process.exit(failed ? 1 : code)
1007
+ });
1008
+ };
1009
+ process.off("SIGTERM", stopBoot);
1010
+ process.off("SIGINT", stopBoot);
1011
+ process.on("SIGTERM", () => void shutdown("SIGTERM"));
1012
+ process.on("SIGINT", () => void shutdown("SIGINT"));
1013
+ void childGone.then(() => {
1014
+ if (stopping) return;
1015
+ failed = true;
1016
+ platform.logger.error(
1017
+ { code: storefront.exitCode, signal: storefront.signalCode },
1018
+ "The storefront exited"
1019
+ );
1020
+ void shutdown("storefront-exit");
1021
+ });
1022
+ }
1023
+ });
1024
+
1025
+ // src/commands/deploy.ts
1026
+ import { spawnSync } from "child_process";
1027
+ import { accessSync, constants, existsSync as existsSync7, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
1028
+ import { delimiter, join as join5 } from "path";
1029
+ import { defineCommand as defineCommand5 } from "citty";
1030
+ import pc3 from "picocolors";
1031
+ import { DEFAULT_JWT_SECRET } from "@nymbalhq/config";
1032
+ var NYMBAL = "node node_modules/nymbal/bin/nymbal.mjs";
1033
+ var KILL_TIMEOUT_S = 15;
1034
+ var FROM_ENV = "<from .env>";
1035
+ function usesPostgres(config) {
1036
+ return config.infrastructure.commandStore === "postgres";
1037
+ }
1038
+ function usesRedis(config) {
1039
+ return config.infrastructure.documentStore.provider === "redis" || config.infrastructure.eventBus.provider === "redis-streams";
1040
+ }
1041
+ function prerequisites(config) {
1042
+ return config.commerce.payments.provider === "native" ? ["<first: configure a real payments provider (nymbal add stripe); production refuses the native stub>"] : [];
1043
+ }
1044
+ function jwtFromEnv(config) {
1045
+ return config.security.auth.jwtSecret === DEFAULT_JWT_SECRET;
1046
+ }
1047
+ var PROXY_HOPS = 1;
1048
+ function flyRecipe(project) {
1049
+ const { name, config } = project;
1050
+ const toml = [
1051
+ `app = "${name}"`,
1052
+ `kill_signal = "SIGTERM"`,
1053
+ `kill_timeout = ${KILL_TIMEOUT_S}`,
1054
+ "",
1055
+ "[build]",
1056
+ ' dockerfile = "Dockerfile"',
1057
+ "",
1058
+ "[deploy]",
1059
+ ` release_command = "${NYMBAL} migrate"`,
1060
+ "",
1061
+ "[env]",
1062
+ ` NYMBAL_PUBLIC_URL = "https://${name}.fly.dev"`,
1063
+ ` NYMBAL_TRUST_PROXY_HOPS = "${PROXY_HOPS}"`,
1064
+ "",
1065
+ "[http_service]",
1066
+ " internal_port = 3001",
1067
+ " force_https = true",
1068
+ "",
1069
+ " [[http_service.checks]]",
1070
+ ' method = "GET"',
1071
+ ' path = "/ready"',
1072
+ ' interval = "15s"',
1073
+ ' timeout = "6s"',
1074
+ ' grace_period = "20s"',
1075
+ ""
1076
+ ].join("\n");
1077
+ const steps = [
1078
+ ...prerequisites(config),
1079
+ `flyctl apps create ${name}`,
1080
+ ...usesPostgres(config) ? [
1081
+ `flyctl postgres create --name ${name}-db`,
1082
+ `flyctl postgres attach ${name}-db --app ${name}`
1083
+ ] : [],
1084
+ ...usesRedis(config) ? [
1085
+ `flyctl redis create --name ${name}-redis`,
1086
+ `flyctl secrets set REDIS_URL=<from flyctl redis status ${name}-redis> --app ${name} --stage`
1087
+ ] : [],
1088
+ `flyctl secrets set NYMBAL_SECRETS_KEY=${FROM_ENV} --app ${name} --stage`,
1089
+ ...jwtFromEnv(config) ? [`flyctl secrets set NYMBAL_JWT_SECRET=${FROM_ENV} --app ${name} --stage`] : [],
1090
+ `flyctl deploy --app ${name}`
1091
+ ];
1092
+ return { file: join5(project.root, "fly.toml"), toml, steps };
1093
+ }
1094
+ function railwayRecipe(project) {
1095
+ const { name, config } = project;
1096
+ const json2 = `${JSON.stringify(
1097
+ {
1098
+ $schema: "https://railway.com/railway.schema.json",
1099
+ build: { builder: "DOCKERFILE", dockerfilePath: "Dockerfile" },
1100
+ deploy: {
1101
+ preDeployCommand: [`${NYMBAL} migrate`],
1102
+ startCommand: `${NYMBAL} start`,
1103
+ healthcheckPath: "/ready",
1104
+ drainingSeconds: KILL_TIMEOUT_S,
1105
+ restartPolicyType: "ON_FAILURE"
1106
+ }
1107
+ },
1108
+ null,
1109
+ 2
1110
+ )}
1111
+ `;
1112
+ const service = `--service ${name}`;
1113
+ const steps = [
1114
+ ...prerequisites(config),
1115
+ `railway init --name ${name}`,
1116
+ ...usesPostgres(config) ? ["railway add --database postgres"] : [],
1117
+ ...usesRedis(config) ? ["railway add --database redis"] : [],
1118
+ `railway add ${service}`,
1119
+ ...usesPostgres(config) ? [`railway variables ${service} --set 'DATABASE_URL=\${{Postgres.DATABASE_URL}}'`] : [],
1120
+ ...usesRedis(config) ? [`railway variables ${service} --set 'REDIS_URL=\${{Redis.REDIS_URL}}'`] : [],
1121
+ `railway variables ${service} --set 'NYMBAL_PUBLIC_URL=https://\${{RAILWAY_PUBLIC_DOMAIN}}'`,
1122
+ `railway variables ${service} --set NYMBAL_SECRETS_KEY=${FROM_ENV}`,
1123
+ ...jwtFromEnv(config) ? [`railway variables ${service} --set NYMBAL_JWT_SECRET=${FROM_ENV}`] : [],
1124
+ `railway variables ${service} --set NYMBAL_TRUST_PROXY_HOPS=${PROXY_HOPS}`,
1125
+ `railway domain ${service}`,
1126
+ `railway up ${service}`
1127
+ ];
1128
+ return { file: join5(project.root, "railway.json"), json: json2, steps };
1129
+ }
1130
+ function onPath(command) {
1131
+ for (const dir of (process.env["PATH"] ?? "").split(delimiter)) {
1132
+ if (dir === "") continue;
1133
+ try {
1134
+ accessSync(join5(dir, command), constants.X_OK);
1135
+ return true;
1136
+ } catch {
1137
+ }
1138
+ }
1139
+ return false;
1140
+ }
1141
+ function appName(root) {
1142
+ const pkg = JSON.parse(readFileSync3(join5(root, "package.json"), "utf8"));
1143
+ const name = (pkg.name ?? "").replace(/^@/, "").toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "");
1144
+ if (name === "") throw new Error('package.json needs a "name" to name the app');
1145
+ return name;
1146
+ }
1147
+ function runSteps(steps, tool) {
1148
+ for (const step of steps) {
1149
+ console.log(pc3.dim(`$ ${step}`));
1150
+ const unresolved = /<(?!from \.env>)[^>]+>/.exec(step);
1151
+ if (unresolved) {
1152
+ process.stderr.write(
1153
+ `${pc3.yellow(`Finish from here by hand: this step needs ${unresolved[0]}.`)}
1154
+ `
1155
+ );
1156
+ process.exit(1);
1157
+ }
1158
+ const argv = (step.match(/'[^']*'|\S+/g) ?? []).map(
1159
+ (part) => part.startsWith("'") ? part.slice(1, -1) : part
1160
+ );
1161
+ const filled = argv.map((part) => {
1162
+ const at = part.indexOf(FROM_ENV);
1163
+ if (at < 0) return part;
1164
+ const key = part.slice(0, at - 1);
1165
+ const value = process.env[key];
1166
+ if (value === void 0 || value === "") {
1167
+ const make = key === "NYMBAL_JWT_SECRET" ? ": add one made by `openssl rand -base64 32`" : "";
1168
+ process.stderr.write(`${pc3.red(`${key} is not set in .env${make}`)}
1169
+ `);
1170
+ process.exit(1);
1171
+ }
1172
+ return `${key}=${value}`;
1173
+ });
1174
+ const done = spawnSync(filled[0], filled.slice(1), { stdio: "inherit" });
1175
+ if (done.status !== 0) {
1176
+ process.stderr.write(`${pc3.red(`${tool} step failed: ${step}`)}
1177
+ `);
1178
+ process.exit(1);
1179
+ }
1180
+ }
1181
+ }
1182
+ function platformCommand(platform) {
1183
+ const tool = platform === "fly" ? "flyctl" : "railway";
1184
+ return defineCommand5({
1185
+ meta: {
1186
+ name: platform,
1187
+ description: `Write ${platform === "fly" ? "fly.toml" : "railway.json"} and deploy with ${tool}`
1188
+ },
1189
+ args: {
1190
+ dryRun: {
1191
+ type: "boolean",
1192
+ alias: "dry-run",
1193
+ description: "Write the recipe and print the steps; run nothing",
1194
+ default: false
1195
+ }
1196
+ },
1197
+ async run({ args }) {
1198
+ const { config, projectRoot } = await loadProject();
1199
+ if (!args.dryRun && !onPath(tool)) {
1200
+ process.stderr.write(
1201
+ `${pc3.red(`${tool} is not on PATH.`)} Install it and log in, or run with --dry-run to see the steps.
1202
+ `
1203
+ );
1204
+ process.exit(1);
1205
+ }
1206
+ const project = { name: appName(projectRoot), root: projectRoot, config };
1207
+ const recipe = platform === "fly" ? flyRecipe(project) : railwayRecipe(project);
1208
+ const content = "toml" in recipe ? recipe.toml : recipe.json;
1209
+ if (!existsSync7(join5(projectRoot, "Dockerfile"))) {
1210
+ console.log(pc3.yellow("No Dockerfile yet: `nymbal build --image` writes one."));
1211
+ }
1212
+ writeFileSync2(recipe.file, content);
1213
+ console.log(`\u2713 wrote ${recipe.file}`);
1214
+ if (args.dryRun) {
1215
+ console.log(`
1216
+ The steps, with ${tool}:
1217
+ ${recipe.steps.map((s) => ` ${s}`).join("\n")}`);
1218
+ return;
1219
+ }
1220
+ const whoami = spawnSync(tool, platform === "fly" ? ["auth", "whoami"] : ["whoami"], {
1221
+ stdio: "ignore"
1222
+ });
1223
+ if (whoami.status !== 0) {
1224
+ process.stderr.write(
1225
+ `${pc3.red(`${tool} is not logged in.`)} Run \`${tool === "flyctl" ? "flyctl auth login" : "railway login"}\` first.
1226
+ `
1227
+ );
1228
+ process.exit(1);
1229
+ }
1230
+ runSteps(recipe.steps, tool);
1231
+ }
1232
+ });
1233
+ }
1234
+ var deployCommand = defineCommand5({
1235
+ meta: { name: "deploy", description: "Deploy the store to Fly or Railway" },
1236
+ subCommands: {
1237
+ fly: platformCommand("fly"),
1238
+ railway: platformCommand("railway")
1239
+ }
1240
+ });
1241
+
1242
+ // src/commands/seed.ts
1243
+ import { defineCommand as defineCommand6 } from "citty";
1244
+ import { createPlatform, resolveChoice, resolvePrimitives, runSeed as runSeed2 } from "@nymbalhq/platform";
1245
+ var seedCommand = defineCommand6({
551
1246
  meta: { name: "seed", description: "Re-seed demo content (products, categories)" },
552
1247
  args: {
553
1248
  localImages: {
@@ -584,6 +1279,10 @@ var seedCommand = defineCommand4({
584
1279
  console.log(
585
1280
  result.alreadySeeded ? "\u2713 demo content already present, nothing to seed" : `\u2713 seeded ${result.products} products across ${result.categories} categories`
586
1281
  );
1282
+ const search = config.commerce.search;
1283
+ if (!result.alreadySeeded && resolveChoice("search", search).kind === "package") {
1284
+ console.log(`search: run \`nymbal replay --to search\` to fill ${search.provider}`);
1285
+ }
587
1286
  } finally {
588
1287
  await platform.close();
589
1288
  }
@@ -591,13 +1290,13 @@ var seedCommand = defineCommand4({
591
1290
  });
592
1291
 
593
1292
  // src/commands/import.ts
594
- import { defineCommand as defineCommand5 } from "citty";
1293
+ import { defineCommand as defineCommand7 } from "citty";
595
1294
  import { intro, outro, text, select, spinner, isCancel, cancel } from "@clack/prompts";
596
1295
  import p from "picocolors";
597
- import { createApp as createApp2, newCorrelationId, runAsActor, runWithCorrelation } from "@nymbalhq/platform";
1296
+ import { createApp as createApp3, newCorrelationId, runAsActor, runWithCorrelation } from "@nymbalhq/platform";
598
1297
  import { runWooCommerceImport, writeReport } from "@nymbalhq/importers";
599
- import { join as join3 } from "path";
600
- var importCommand = defineCommand5({
1298
+ import { join as join6 } from "path";
1299
+ var importCommand = defineCommand7({
601
1300
  meta: {
602
1301
  name: "import",
603
1302
  description: "Migrate content from WooCommerce (or other sources) into Nymbal"
@@ -646,7 +1345,7 @@ var importCommand = defineCommand5({
646
1345
  async run({ args }) {
647
1346
  const { config } = await loadProject();
648
1347
  const projectRoot = process.cwd();
649
- const statePath = join3(projectRoot, ".nymbal-migration.json");
1348
+ const statePath = join6(projectRoot, ".nymbal-migration.json");
650
1349
  const isTTY = process.stdin.isTTY ?? false;
651
1350
  intro(p.bold("Nymbal Import"));
652
1351
  let source = args.source;
@@ -719,7 +1418,7 @@ var importCommand = defineCommand5({
719
1418
  const gdprEnabled = args.gdpr !== false;
720
1419
  const loadSpin = spinner();
721
1420
  loadSpin.start("Starting platform\u2026");
722
- const app = await createApp2(config, { version: getCliVersion() });
1421
+ const app = await createApp3(config, { version: getCliVersion() });
723
1422
  loadSpin.stop("Platform ready");
724
1423
  try {
725
1424
  const report = await runWithCorrelation(
@@ -777,22 +1476,23 @@ var importCommand = defineCommand5({
777
1476
  });
778
1477
 
779
1478
  // src/commands/config-validate.ts
780
- import { defineCommand as defineCommand6 } from "citty";
781
- import pc2 from "picocolors";
1479
+ import { defineCommand as defineCommand8 } from "citty";
1480
+ import pc4 from "picocolors";
1481
+ import { slotFolder as slotFolder2 } from "@nymbalhq/config";
782
1482
  import { NymbalError } from "@nymbalhq/types";
783
- var configValidateCommand = defineCommand6({
1483
+ var configValidateCommand = defineCommand8({
784
1484
  meta: { name: "config:validate", description: "Validate nymbal.config.ts" },
785
1485
  async run() {
786
1486
  try {
787
1487
  const { config, path } = await loadProject();
788
- console.log(pc2.green(`\u2713 config valid`) + ` (${path})`);
1488
+ console.log(pc4.green(`\u2713 config valid`) + ` (${path})`);
789
1489
  console.log(
790
- ` template: ${config.template}, commandStore: ${config.infrastructure.commandStore}, documentStore: ${config.infrastructure.documentStore}, eventBus: ${config.infrastructure.eventBus}`
1490
+ ` template: ${config.template}, command store: ${config.infrastructure.commandStore}, ${slotFolder2("documentStore")}: ${config.infrastructure.documentStore.provider}, ${slotFolder2("eventBus")}: ${config.infrastructure.eventBus.provider}`
791
1491
  );
792
1492
  process.exit(0);
793
1493
  } catch (err2) {
794
1494
  if (err2 instanceof NymbalError) {
795
- console.error(pc2.red("\u2717 config invalid"));
1495
+ console.error(pc4.red("\u2717 config invalid"));
796
1496
  console.error(err2.message);
797
1497
  } else {
798
1498
  console.error(err2);
@@ -803,28 +1503,49 @@ var configValidateCommand = defineCommand6({
803
1503
  });
804
1504
 
805
1505
  // src/commands/add.ts
806
- import { spawnSync } from "child_process";
807
- import { existsSync as existsSync6, mkdtempSync, readFileSync as readFileSync2, rmSync, writeFileSync } from "fs";
808
- import { dirname as dirname6, join as join5 } from "path";
1506
+ import { spawnSync as spawnSync2 } from "child_process";
1507
+ import { existsSync as existsSync9, mkdtempSync, readFileSync as readFileSync4, rmSync, writeFileSync as writeFileSync3 } from "fs";
1508
+ import { dirname as dirname6, join as join8 } from "path";
1509
+ import { pathToFileURL as pathToFileURL2 } from "url";
809
1510
  import { parseEnv } from "util";
810
- import { defineCommand as defineCommand7 } from "citty";
811
- import pc3 from "picocolors";
812
- import { findConfigFile as findConfigFile2, loadConfig as loadConfig2 } from "@nymbalhq/config";
813
- import { installLine } from "@nymbalhq/platform";
1511
+ import { defineCommand as defineCommand9 } from "citty";
1512
+ import { resolve as resolveFrom } from "import-meta-resolve";
1513
+ import pc5 from "picocolors";
1514
+ import {
1515
+ ADAPTER_CATALOGUE as ADAPTER_CATALOGUE2,
1516
+ BUILT_IN,
1517
+ PROVIDER_NAME,
1518
+ conventionPackage as conventionPackage2,
1519
+ findConfigFile as findConfigFile2,
1520
+ loadConfig as loadConfig2,
1521
+ slotFolder as slotFolder5,
1522
+ suggestProvider
1523
+ } from "@nymbalhq/config";
1524
+ import { checkAdapterModule, installLine, missingPackage, resolveChoice as resolveChoice2 } from "@nymbalhq/platform";
814
1525
 
815
1526
  // src/recipes/holders.ts
816
- import { existsSync as existsSync5 } from "fs";
1527
+ import { existsSync as existsSync8 } from "fs";
817
1528
  import { readFile } from "fs/promises";
818
- import { createRequire as createRequire2 } from "module";
819
- import { dirname as dirname5, join as join4, resolve as resolve5 } from "path";
1529
+ import { createRequire as createRequire3 } from "module";
1530
+ import { dirname as dirname5, join as join7, resolve as resolve6 } from "path";
820
1531
  import { pathToFileURL } from "url";
1532
+ import { conventionPackage } from "@nymbalhq/config";
821
1533
  var RECIPE_HOLDERS = {
822
- cloudflare: "@nymbalhq/security-cloudflare",
1534
+ algolia: conventionPackage("search", "algolia"),
1535
+ cloudflare: conventionPackage("security", "cloudflare"),
823
1536
  postgres: "@nymbalhq/platform",
824
- redis: "@nymbalhq/doc-store-redis",
825
- s3: "@nymbalhq/media-s3",
826
- stripe: "@nymbalhq/adapter-stripe"
1537
+ // Sets the document store and the bus; the document store's package ships it.
1538
+ redis: conventionPackage("documentStore", "redis"),
1539
+ s3: conventionPackage("media", "s3"),
1540
+ stripe: conventionPackage("payments", "stripe")
1541
+ };
1542
+ var MULTI_SLOT_PAIRS = {
1543
+ redis: ["documentStore/redis", "eventBus/redis-streams"]
827
1544
  };
1545
+ function multiSlotRecipe(slot, provider) {
1546
+ const pair = `${slot}/${provider}`;
1547
+ return Object.keys(MULTI_SLOT_PAIRS).find((name) => MULTI_SLOT_PAIRS[name].includes(pair));
1548
+ }
828
1549
  function knownRecipes() {
829
1550
  return Object.keys(RECIPE_HOLDERS).sort();
830
1551
  }
@@ -835,28 +1556,31 @@ function unknownRecipe(name) {
835
1556
  return new Error(`unknown recipe '${name}': the recipes are ${knownRecipes().join(", ")}`);
836
1557
  }
837
1558
  function packageDir(pkg, projectRoot) {
838
- let dir = resolve5(projectRoot);
1559
+ let dir = resolve6(projectRoot);
839
1560
  while (true) {
840
- const candidate = join4(dir, "node_modules", pkg);
841
- if (existsSync5(join4(candidate, "package.json"))) return candidate;
1561
+ const candidate = join7(dir, "node_modules", pkg);
1562
+ if (existsSync8(join7(candidate, "package.json"))) return candidate;
842
1563
  const parent = dirname5(dir);
843
1564
  if (parent === dir) return null;
844
1565
  dir = parent;
845
1566
  }
846
1567
  }
847
- function recipeFile(name, projectRoot) {
848
- const holder = RECIPE_HOLDERS[name];
849
- if (holder === void 0 || !isKnownRecipe(name)) throw unknownRecipe(name);
850
- const dir = packageDir(holder, projectRoot);
1568
+ function packageRecipeFile(pkg, name, projectRoot) {
1569
+ const dir = packageDir(pkg, projectRoot);
851
1570
  if (dir === null) return null;
852
1571
  try {
853
- return createRequire2(join4(dir, "package.json")).resolve(`${holder}/recipes/${name}.json`);
1572
+ return createRequire3(join7(dir, "package.json")).resolve(`${pkg}/recipes/${name}.json`);
854
1573
  } catch (error) {
855
1574
  const code = error.code;
856
1575
  if (code === "MODULE_NOT_FOUND" || code === "ERR_PACKAGE_PATH_NOT_EXPORTED") return null;
857
1576
  throw error;
858
1577
  }
859
1578
  }
1579
+ function recipeFile(name, projectRoot) {
1580
+ const holder = RECIPE_HOLDERS[name];
1581
+ if (holder === void 0 || !isKnownRecipe(name)) throw unknownRecipe(name);
1582
+ return packageRecipeFile(holder, name, projectRoot);
1583
+ }
860
1584
  function isInstalled(pkg, projectRoot) {
861
1585
  return packageDir(pkg, projectRoot) !== null;
862
1586
  }
@@ -867,6 +1591,9 @@ async function readRecipe(name, projectRoot) {
867
1591
  `${RECIPE_HOLDERS[name]} is not installed in ${projectRoot}, so its ${name} recipe cannot be read`
868
1592
  );
869
1593
  }
1594
+ return readRecipeFile(file, name);
1595
+ }
1596
+ async function readRecipeFile(file, name) {
870
1597
  const recipe = JSON.parse(await readFile(file, "utf8"));
871
1598
  const malformed = recipe === null || typeof recipe !== "object" || recipe.name !== name || !Array.isArray(recipe.install) || !Array.isArray(recipe.set) || !Array.isArray(recipe.env) || !Array.isArray(recipe.next);
872
1599
  if (malformed) throw new Error(`${file} is not a ${name} recipe`);
@@ -876,22 +1603,21 @@ function entryOf(dir, manifest) {
876
1603
  const exportsField = manifest["exports"];
877
1604
  const root = typeof exportsField === "object" ? exportsField["."] : exportsField;
878
1605
  const entry = typeof root === "string" ? root : typeof root === "object" && root !== null ? root["import"] ?? root["default"] : manifest["module"] ?? manifest["main"];
879
- return typeof entry === "string" ? join4(dir, entry) : null;
1606
+ return typeof entry === "string" ? join7(dir, entry) : null;
880
1607
  }
881
1608
  async function settingsEnv(packages, projectRoot) {
882
1609
  const names = /* @__PURE__ */ new Set();
883
- for (const pkg of packages.filter((p2) => p2.startsWith("@nymbalhq/"))) {
1610
+ for (const pkg of packages) {
884
1611
  const dir = packageDir(pkg, projectRoot);
885
1612
  if (dir === null) continue;
886
- const manifest = JSON.parse(await readFile(join4(dir, "package.json"), "utf8"));
1613
+ const manifest = JSON.parse(await readFile(join7(dir, "package.json"), "utf8"));
887
1614
  const entry = entryOf(dir, manifest);
888
- if (entry === null || !existsSync5(entry)) continue;
1615
+ if (entry === null || !existsSync8(entry)) continue;
889
1616
  let mod;
890
1617
  try {
891
1618
  mod = await import(pathToFileURL(entry).href);
892
- } catch (error) {
893
- if (error.code === "ERR_MODULE_NOT_FOUND") continue;
894
- throw error;
1619
+ } catch {
1620
+ continue;
895
1621
  }
896
1622
  if (!Array.isArray(mod.settings)) continue;
897
1623
  for (const setting of mod.settings) {
@@ -909,6 +1635,7 @@ var SCAFFOLD_DEFAULTS = [
909
1635
  "in-process",
910
1636
  "local-fs",
911
1637
  "native",
1638
+ "none",
912
1639
  "middleware"
913
1640
  ];
914
1641
  var CONFIG_MODULE = "@nymbalhq/config";
@@ -1275,19 +2002,115 @@ function appendRecipeEnv(example, recipe) {
1275
2002
  return `${head}${gap}${block.join(eol)}${eol}`;
1276
2003
  }
1277
2004
 
2005
+ // src/recipes/slot-recipe.ts
2006
+ import { slotFolder as slotFolder3 } from "@nymbalhq/config";
2007
+ var INFRASTRUCTURE = /* @__PURE__ */ new Set(["documentStore", "eventBus", "media"]);
2008
+ function slotPath(slot) {
2009
+ if (slot === "security") return "security";
2010
+ return INFRASTRUCTURE.has(slot) ? `infrastructure.${slot}` : `commerce.${slot}`;
2011
+ }
2012
+ function slotAt(path) {
2013
+ const [top, key] = path.split(".");
2014
+ return (top === "commerce" || top === "infrastructure") && key !== void 0 ? key : top;
2015
+ }
2016
+ function slotsSetBy(recipe) {
2017
+ return [...new Set(recipe.set.map(({ path }) => slotFolder3(slotAt(path))))];
2018
+ }
2019
+ function setsOnly(recipe, slot) {
2020
+ const base = slotPath(slot);
2021
+ return recipe.set.every(({ path }) => path === base || path.startsWith(`${base}.`));
2022
+ }
2023
+ function slotRecipe(opts) {
2024
+ const { slot, provider, settings } = opts;
2025
+ const set = slot === "security" ? [
2026
+ { path: "security.adapter", value: provider },
2027
+ ...opts.package === void 0 ? [] : [{ path: "security.package", value: opts.package }]
2028
+ ] : [
2029
+ {
2030
+ path: slotPath(slot),
2031
+ value: { provider, ...opts.package !== void 0 && { package: opts.package } }
2032
+ }
2033
+ ];
2034
+ const from = opts.package === void 0 ? "" : ` from ${opts.package}`;
2035
+ return {
2036
+ name: opts.name,
2037
+ summary: `${slotFolder3(slot)} is ${provider}${from}`,
2038
+ install: opts.install,
2039
+ set,
2040
+ env: settings.flatMap(
2041
+ (s) => s.env === void 0 ? [] : [{ name: s.env, example: "", required: s.optional !== true, comment: s.label }]
2042
+ ),
2043
+ next: [
2044
+ ...settings.filter((s) => s.env === void 0).map((s) => `set ${s.path} in the admin's Settings (${s.label})`),
2045
+ ...INFRASTRUCTURE.has(slot) && settings.length === 0 ? [`run nymbal doctor to check ${slotFolder3(slot)} on ${provider}`] : []
2046
+ ]
2047
+ };
2048
+ }
2049
+
2050
+ // src/slot-names.ts
2051
+ import { ADAPTER_CATALOGUE, slotFolder as slotFolder4 } from "@nymbalhq/config";
2052
+ var SLOTS = Object.keys(ADAPTER_CATALOGUE);
2053
+ function slotNamed(word) {
2054
+ return SLOTS.find((slot) => slot === word || slotFolder4(slot) === word);
2055
+ }
2056
+
1278
2057
  // src/commands/add.ts
2058
+ var SLOTS2 = Object.keys(ADAPTER_CATALOGUE2);
2059
+ var PACKAGE_NAME = /^@[a-z0-9-~][a-z0-9-._~]*\/[a-z0-9-~][a-z0-9-._~]*$/;
2060
+ var usageHint = () => `nymbal add takes <recipe> (${knownRecipes().join(", ")}), <slot> <provider> or <package> (a scoped npm name, @scope/name)`;
2061
+ function parseAddTarget(args) {
2062
+ if (args.length === 1) {
2063
+ const name = args[0];
2064
+ if (isKnownRecipe(name)) return { kind: "recipe", name };
2065
+ if (PACKAGE_NAME.test(name)) return { kind: "package", name };
2066
+ const slot = slotNamed(name);
2067
+ if (slot !== void 0) {
2068
+ return {
2069
+ error: `name the ${slotFolder5(slot)} provider: nymbal add ${slotFolder5(slot)} <provider>, one of ${Object.keys(ADAPTER_CATALOGUE2[slot]).join(", ")}. ${usageHint()}`
2070
+ };
2071
+ }
2072
+ return { error: `unknown name '${name}'. ${usageHint()}` };
2073
+ }
2074
+ if (args.length === 2) {
2075
+ const [word, provider] = args;
2076
+ const slot = slotNamed(word);
2077
+ if (slot === void 0)
2078
+ return { error: `unknown slot '${word}'; the slots are ${SLOTS2.map(slotFolder5).join(", ")}` };
2079
+ return { kind: "slot", slot, provider };
2080
+ }
2081
+ return {
2082
+ error: `${args.length === 0 ? "name what to add" : `nymbal add takes one or two names, not ${args.length}`}. ${usageHint()}`
2083
+ };
2084
+ }
2085
+ function addUsage() {
2086
+ const forms = [
2087
+ ["nymbal add <recipe>", `a service, as in nymbal add redis: ${knownRecipes().join(", ")}`],
2088
+ ["nymbal add <slot> <provider>", "one slot on a provider, as in nymbal add media s3"],
2089
+ ["nymbal add <package>", "a third-party adapter by its npm name, as in nymbal add @acme/x"]
2090
+ ];
2091
+ const lines = ["Forms:"];
2092
+ for (const [form, what] of forms) lines.push(` ${form.padEnd(30)}${what}`);
2093
+ lines.push("", "Slots and the providers Nymbal ships:");
2094
+ for (const slot of SLOTS2) {
2095
+ const providers = Object.entries(ADAPTER_CATALOGUE2[slot]).map(
2096
+ ([provider, entry]) => entry.builtIn === true ? `${provider} (built in)` : provider
2097
+ );
2098
+ lines.push(` ${slotFolder5(slot)}: ${providers.join(", ")}`);
2099
+ }
2100
+ return lines.join("\n");
2101
+ }
1279
2102
  var out = (line = "") => void process.stdout.write(`${line}
1280
2103
  `);
1281
2104
  var err = (line) => void process.stderr.write(`${line}
1282
2105
  `);
1283
- function fail(message) {
1284
- err(pc3.red(`\u2717 ${message}`));
2106
+ function fail2(message) {
2107
+ err(pc5.red(`\u2717 ${message}`));
1285
2108
  return 1;
1286
2109
  }
1287
2110
  function runInstall(line, root) {
1288
- out(pc3.dim(`$ ${line}`));
2111
+ out(pc5.dim(`$ ${line}`));
1289
2112
  const [command, ...args] = line.split(" ");
1290
- const result = spawnSync(command, args, {
2113
+ const result = spawnSync2(command, args, {
1291
2114
  cwd: root,
1292
2115
  stdio: "inherit",
1293
2116
  shell: process.platform === "win32"
@@ -1295,8 +2118,8 @@ function runInstall(line, root) {
1295
2118
  return result.status === 0;
1296
2119
  }
1297
2120
  function dotEnv(root) {
1298
- const file = join5(root, ".env");
1299
- return existsSync6(file) ? parseEnv(readFileSync2(file, "utf8")) : {};
2121
+ const file = join8(root, ".env");
2122
+ return existsSync9(file) ? parseEnv(readFileSync4(file, "utf8")) : {};
1300
2123
  }
1301
2124
  var isSet = (name, fromFile) => (process.env[name] ?? "") !== "" || (fromFile[name] ?? "") !== "";
1302
2125
  async function problemsWith(candidate, recipe, root, fromFile) {
@@ -1315,9 +2138,9 @@ async function problemsWith(candidate, recipe, root, fromFile) {
1315
2138
  saved.set(name, process.env[name]);
1316
2139
  process.env[name] = value;
1317
2140
  }
1318
- const dir = mkdtempSync(join5(root, ".nymbal-add-"));
2141
+ const dir = mkdtempSync(join8(root, ".nymbal-add-"));
1319
2142
  try {
1320
- writeFileSync(join5(dir, "nymbal.config.ts"), candidate);
2143
+ writeFileSync3(join8(dir, "nymbal.config.ts"), candidate);
1321
2144
  await loadConfig2(dir);
1322
2145
  } catch (error) {
1323
2146
  problems.push(error.message);
@@ -1345,54 +2168,207 @@ function lineDiff(before, after) {
1345
2168
  i++;
1346
2169
  j++;
1347
2170
  } else if (j < b.length && (i === a.length || t[i][j + 1] >= t[i + 1][j])) {
1348
- lines.push(pc3.green(`+ ${b[j++]}`));
2171
+ lines.push(pc5.green(`+ ${b[j++]}`));
1349
2172
  } else {
1350
- lines.push(pc3.red(`- ${a[i++]}`));
2173
+ lines.push(pc5.red(`- ${a[i++]}`));
1351
2174
  }
1352
2175
  }
1353
2176
  return lines;
1354
2177
  }
1355
2178
  var show = (value) => typeof value === "string" ? `'${value}'` : JSON.stringify(value);
1356
- async function add(opts, cwd = process.cwd()) {
1357
- const name = opts.recipe;
1358
- if (!isKnownRecipe(name)) {
1359
- return fail(`unknown recipe '${name}'. The recipes are: ${knownRecipes().join(", ")}`);
2179
+ var messageOf = (error) => error instanceof Error ? error.message : String(error);
2180
+ function removeLine(pkg, root) {
2181
+ return installLine([pkg], process.env, root).replace(
2182
+ /^(\S+) \S+/,
2183
+ (_, pm) => `${pm} ${pm === "npm" ? "uninstall" : "remove"}`
2184
+ );
2185
+ }
2186
+ function ensureInstalled(pkg, packages, notInstalled, root, opts, installed) {
2187
+ if (isInstalled(pkg, root)) return null;
2188
+ const line = installLine(packages, process.env, root);
2189
+ if (!opts.install || opts.dryRun) return fail2(`${notInstalled}. Install it: ${line}`);
2190
+ if (!runInstall(line, root)) return fail2(`${line} failed`);
2191
+ installed.push(...packages);
2192
+ return null;
2193
+ }
2194
+ async function importFromProject(pkg, root) {
2195
+ const mod = await import(resolveFrom(pkg, pathToFileURL2(join8(root, "package.json")).href));
2196
+ return mod ?? {};
2197
+ }
2198
+ function loadFailure(pkg, error, root) {
2199
+ const missing = missingPackage(error);
2200
+ const install = missing === null || missing === pkg ? "" : `: ${installLine([missing], process.env, root)}`;
2201
+ return `${pkg} could not be loaded: ${messageOf(error)}${install}`;
2202
+ }
2203
+ async function packageRecipe(file, provider, slot) {
2204
+ const recipe = await readRecipeFile(file, provider);
2205
+ if (!setsOnly(recipe, slot)) {
2206
+ return fail2(
2207
+ `${recipe.name} sets ${slotsSetBy(recipe).join(" and ")} together: run nymbal add ${recipe.name}`
2208
+ );
1360
2209
  }
1361
- const configPath = findConfigFile2(cwd);
1362
- if (configPath === null) return fail(`no nymbal.config.ts in ${cwd} or any parent directory`);
1363
- const root = dirname6(configPath);
2210
+ return recipe;
2211
+ }
2212
+ async function recipePlan(name, root, opts, installed) {
1364
2213
  const holder = RECIPE_HOLDERS[name];
1365
- const installed = [];
1366
2214
  if (recipeFile(name, root) === null) {
1367
- const line = installLine([holder], process.env, root);
1368
- if (!opts.install || opts.dryRun) {
1369
- return fail(
1370
- `the ${name} recipe ships in ${holder}, which is not installed. Install it: ${line}`
1371
- );
1372
- }
1373
- if (!runInstall(line, root)) return fail(`${line} failed`);
1374
- installed.push(holder);
2215
+ const failed = ensureInstalled(
2216
+ holder,
2217
+ [holder],
2218
+ `the ${name} recipe ships in ${holder}, which is not installed`,
2219
+ root,
2220
+ opts,
2221
+ installed
2222
+ );
2223
+ if (failed !== null) return failed;
1375
2224
  }
1376
2225
  const recipe = await readRecipe(name, root);
1377
- const source = readFileSync2(configPath, "utf8");
2226
+ return { recipe, label: name, what: `the ${name} recipe`, adapters: recipe.install };
2227
+ }
2228
+ async function slotPlan(slot, provider, root, opts, installed) {
2229
+ const label = `${slotFolder5(slot)} ${provider}`;
2230
+ const kind = slot === "security" ? "security adapter" : `${slotFolder5(slot)} provider`;
2231
+ if (!PROVIDER_NAME.test(provider)) {
2232
+ return fail2(`'${provider}' is no provider name: lower-case letters, digits and hyphens`);
2233
+ }
2234
+ if (provider === "custom") {
2235
+ return fail2("custom is an adapter you pass to createApp: there is no package to add");
2236
+ }
2237
+ if (!Object.hasOwn(ADAPTER_CATALOGUE2[slot], provider)) {
2238
+ const suggestion = suggestProvider(slot, provider);
2239
+ return fail2(
2240
+ suggestion === void 0 ? `unknown ${kind} '${provider}': no first-party adapter is named that; a third-party one: nymbal add <package>` : `unknown ${kind} '${provider}'; did you mean '${suggestion}'?`
2241
+ );
2242
+ }
2243
+ const owner = multiSlotRecipe(slot, provider);
2244
+ if (owner !== void 0) {
2245
+ const slots = MULTI_SLOT_PAIRS[owner].map((pair) => slotFolder5(pair.split("/")[0]));
2246
+ return fail2(`${owner} sets ${slots.join(" and ")} together: run nymbal add ${owner}`);
2247
+ }
2248
+ const what = `nymbal add ${label}`;
2249
+ const resolution = resolveChoice2(slot, { provider });
2250
+ if (resolution.kind !== "package") {
2251
+ const recipe2 = slotRecipe({ name: label, slot, provider, install: [], settings: [] });
2252
+ return { recipe: recipe2, label, what, adapters: [] };
2253
+ }
2254
+ const pkg = resolution.package;
2255
+ const packages = [pkg, ...resolution.sdk === void 0 ? [] : [resolution.sdk]];
2256
+ const failed = ensureInstalled(
2257
+ pkg,
2258
+ packages,
2259
+ `${label} is ${pkg}, which is not installed`,
2260
+ root,
2261
+ opts,
2262
+ installed
2263
+ );
2264
+ if (failed !== null) return failed;
2265
+ const file = packageRecipeFile(pkg, provider, root);
2266
+ if (file !== null) {
2267
+ const recipe2 = await packageRecipe(file, provider, slot);
2268
+ if (typeof recipe2 === "number") return recipe2;
2269
+ return { recipe: recipe2, label, what: `the ${recipe2.name} recipe`, adapters: recipe2.install };
2270
+ }
2271
+ let settings;
2272
+ try {
2273
+ settings = checkAdapterModule(await importFromProject(pkg, root), slot, provider, pkg).settings ?? [];
2274
+ } catch (error) {
2275
+ return fail2(
2276
+ error.code === "ERR_MODULE_NOT_FOUND" ? loadFailure(pkg, error, root) : messageOf(error)
2277
+ );
2278
+ }
2279
+ const recipe = slotRecipe({ name: label, slot, provider, install: packages, settings });
2280
+ return { recipe, label, what, adapters: [pkg] };
2281
+ }
2282
+ async function packagePlan(name, root, opts, installed) {
2283
+ const failed = ensureInstalled(name, [name], `${name} is not installed`, root, opts, installed);
2284
+ if (failed !== null) return failed;
2285
+ const refuse2 = (why) => fail2(
2286
+ installed.includes(name) ? `${why}
2287
+ ${name} stays installed; ${removeLine(name, root)} removes it` : why
2288
+ );
2289
+ let mod;
2290
+ try {
2291
+ mod = await importFromProject(name, root);
2292
+ } catch (error) {
2293
+ return refuse2(loadFailure(name, error, root));
2294
+ }
2295
+ const { slot, provider } = mod;
2296
+ if (slot === void 0) return refuse2(`${name} exports no slot`);
2297
+ if (typeof slot !== "string" || !SLOTS2.includes(slot)) {
2298
+ return refuse2(
2299
+ `${name} exports slot ${show(slot)}, which is no slot; the slots are ${SLOTS2.join(", ")}`
2300
+ );
2301
+ }
2302
+ const at = slot;
2303
+ if (provider === void 0) return refuse2(`${name} exports no provider`);
2304
+ if (typeof provider !== "string" || !PROVIDER_NAME.test(provider)) {
2305
+ return refuse2(
2306
+ `${name} exports provider ${show(provider)}, which is no provider name: lower-case letters, digits and hyphens`
2307
+ );
2308
+ }
2309
+ if (provider === "custom") {
2310
+ return refuse2(`${name} exports provider 'custom', the name of an adapter passed to createApp`);
2311
+ }
2312
+ if (BUILT_IN[at].includes(provider)) {
2313
+ return refuse2(
2314
+ `${name} exports provider '${provider}', the name of the built-in ${slotFolder5(at)} provider`
2315
+ );
2316
+ }
2317
+ let settings;
2318
+ try {
2319
+ settings = checkAdapterModule(mod, at, provider, name).settings ?? [];
2320
+ } catch (error) {
2321
+ return refuse2(messageOf(error));
2322
+ }
2323
+ const file = packageRecipeFile(name, provider, root);
2324
+ if (file !== null) {
2325
+ const recipe2 = await packageRecipe(file, provider, at);
2326
+ if (typeof recipe2 === "number") return recipe2;
2327
+ return { recipe: recipe2, label: name, what: `the ${recipe2.name} recipe`, adapters: recipe2.install };
2328
+ }
2329
+ const convention = conventionPackage2(at, provider) === name;
2330
+ const sdk = convention ? ADAPTER_CATALOGUE2[at][provider]?.sdk : void 0;
2331
+ const recipe = slotRecipe({
2332
+ name,
2333
+ slot: at,
2334
+ provider,
2335
+ package: convention ? void 0 : name,
2336
+ install: [name, ...sdk === void 0 ? [] : [sdk]],
2337
+ settings
2338
+ });
2339
+ return { recipe, label: name, what: `nymbal add ${name}`, adapters: [name] };
2340
+ }
2341
+ async function add(opts, cwd = process.cwd()) {
2342
+ const { target } = opts;
2343
+ if (target.kind === "recipe" && !isKnownRecipe(target.name)) {
2344
+ return fail2(`unknown recipe '${target.name}'. ${usageHint()}`);
2345
+ }
2346
+ const configPath = findConfigFile2(cwd);
2347
+ if (configPath === null) return fail2(`no nymbal.config.ts in ${cwd} or any parent directory`);
2348
+ const root = dirname6(configPath);
2349
+ const installed = [];
2350
+ const plan = target.kind === "recipe" ? await recipePlan(target.name, root, opts, installed) : target.kind === "slot" ? await slotPlan(target.slot, target.provider, root, opts, installed) : await packagePlan(target.name, root, opts, installed);
2351
+ if (typeof plan === "number") return plan;
2352
+ const { recipe, label, what } = plan;
2353
+ const source = readFileSync4(configPath, "utf8");
1378
2354
  let edited;
1379
2355
  try {
1380
2356
  const applied = applyRecipeToConfig(source, recipe, { force: opts.force });
1381
2357
  if ("conflict" in applied) {
1382
2358
  const { path, current, wanted } = applied.conflict;
1383
- return fail(
1384
- `${path} is ${show(current)} in nymbal.config.ts, and the ${name} recipe sets it to ${show(wanted)}. nymbal.config.ts is unchanged: edit it by hand, or re-run with --force to overwrite it.`
2359
+ return fail2(
2360
+ `${path} is ${show(current)} in nymbal.config.ts, and ${what} sets it to ${show(wanted)}. nymbal.config.ts is unchanged: edit it by hand, or re-run with --force to overwrite it.`
1385
2361
  );
1386
2362
  }
1387
2363
  edited = applied;
1388
2364
  } catch (error) {
1389
- return fail(error.message);
2365
+ return fail2(error.message);
1390
2366
  }
1391
- const examplePath = join5(root, ".env.example");
1392
- const example = existsSync6(examplePath) ? readFileSync2(examplePath, "utf8") : "";
2367
+ const examplePath = join8(root, ".env.example");
2368
+ const example = existsSync9(examplePath) ? readFileSync4(examplePath, "utf8") : "";
1393
2369
  const nextExample = appendRecipeEnv(example, recipe);
1394
2370
  if (opts.dryRun) {
1395
- out(pc3.bold(`nymbal add ${name} --dry-run: nothing is written`));
2371
+ out(pc5.bold(`nymbal add ${label} --dry-run: nothing is written`));
1396
2372
  out();
1397
2373
  out(
1398
2374
  recipe.install.length > 0 ? `install: ${installLine(recipe.install, process.env, root)}` : "install: nothing"
@@ -1411,36 +2387,36 @@ async function add(opts, cwd = process.cwd()) {
1411
2387
  const pending = recipe.install.filter((pkg) => !isInstalled(pkg, root));
1412
2388
  if (pending.length > 0 && opts.install) {
1413
2389
  const line = installLine(pending, process.env, root);
1414
- if (!runInstall(line, root)) return fail(`${line} failed`);
2390
+ if (!runInstall(line, root)) return fail2(`${line} failed`);
1415
2391
  installed.push(...pending);
1416
2392
  }
1417
2393
  const fromFile = dotEnv(root);
1418
2394
  const problems = await problemsWith(edited.source, recipe, root, fromFile);
1419
2395
  if (problems.length > 0) {
1420
- return fail(
1421
- `the ${name} recipe would leave a config that does not load, so nymbal.config.ts is unchanged:
2396
+ return fail2(
2397
+ `${what} would leave a config that does not load, so nymbal.config.ts is unchanged:
1422
2398
  ${problems.join("\n ")}`
1423
2399
  );
1424
2400
  }
1425
2401
  const written = [];
1426
2402
  if (installed.length > 0) written.push(`package.json and its lockfile (${installed.join(", ")})`);
1427
2403
  if (edited.source !== source) {
1428
- writeFileSync(configPath, edited.source);
2404
+ writeFileSync3(configPath, edited.source);
1429
2405
  written.push(`nymbal.config.ts (${edited.changed.join(", ")})`);
1430
2406
  }
1431
2407
  if (nextExample !== example) {
1432
- writeFileSync(examplePath, nextExample);
2408
+ writeFileSync3(examplePath, nextExample);
1433
2409
  written.push(
1434
2410
  `.env.example (${missingEnv(example, recipe).map((v) => v.name).join(", ")})`
1435
2411
  );
1436
2412
  }
1437
- out(pc3.green(`\u2713 ${name}: ${recipe.summary}`));
2413
+ out(pc5.green(`\u2713 ${label}: ${recipe.summary}`));
1438
2414
  out(written.length > 0 ? ` changed ${written.join(", ")}` : " already added: nothing changed");
1439
2415
  const unset = recipe.env.filter((v) => v.required && !isSet(v.name, fromFile));
1440
2416
  if (unset.length > 0 || recipe.next.length > 0) {
1441
2417
  out();
1442
2418
  out("Next:");
1443
- const fromSettings = unset.length > 0 ? await settingsEnv(recipe.install, root) : /* @__PURE__ */ new Set();
2419
+ const fromSettings = unset.length > 0 ? await settingsEnv(plan.adapters, root) : /* @__PURE__ */ new Set();
1444
2420
  for (const v of unset) {
1445
2421
  out(
1446
2422
  fromSettings.has(v.name) ? ` - set ${v.name} in .env or in the admin's Settings` : ` - set ${v.name} in .env`
@@ -1450,13 +2426,22 @@ async function add(opts, cwd = process.cwd()) {
1450
2426
  }
1451
2427
  return 0;
1452
2428
  }
1453
- var addCommand = defineCommand7({
2429
+ var addCommand = defineCommand9({
1454
2430
  meta: {
1455
2431
  name: "add",
1456
- description: `Put the store on a service: ${knownRecipes().join(", ")}`
2432
+ description: "Add a provider by slot, a third-party adapter by package, or a service by recipe (nymbal add lists them)"
1457
2433
  },
1458
2434
  args: {
1459
- recipe: { type: "positional", required: true, description: knownRecipes().join(", ") },
2435
+ name: {
2436
+ type: "positional",
2437
+ required: false,
2438
+ description: "<recipe>, <slot> or <package>"
2439
+ },
2440
+ provider: {
2441
+ type: "positional",
2442
+ required: false,
2443
+ description: "after <slot>: the slot's provider"
2444
+ },
1460
2445
  install: {
1461
2446
  type: "boolean",
1462
2447
  default: true,
@@ -1465,7 +2450,7 @@ var addCommand = defineCommand7({
1465
2450
  force: {
1466
2451
  type: "boolean",
1467
2452
  default: false,
1468
- description: "Overwrite a config value the recipe conflicts with"
2453
+ description: "Overwrite a config value the addition conflicts with"
1469
2454
  },
1470
2455
  "dry-run": {
1471
2456
  type: "boolean",
@@ -1474,8 +2459,19 @@ var addCommand = defineCommand7({
1474
2459
  }
1475
2460
  },
1476
2461
  async run({ args }) {
2462
+ const positionals = args._.map(String);
2463
+ if (positionals.length === 0) {
2464
+ out(addUsage());
2465
+ process.exitCode = 1;
2466
+ return;
2467
+ }
2468
+ const target = parseAddTarget(positionals);
2469
+ if ("error" in target) {
2470
+ process.exitCode = fail2(target.error);
2471
+ return;
2472
+ }
1477
2473
  process.exitCode = await add({
1478
- recipe: args.recipe,
2474
+ target,
1479
2475
  install: args.install,
1480
2476
  force: args.force,
1481
2477
  dryRun: args["dry-run"]
@@ -1484,13 +2480,13 @@ var addCommand = defineCommand7({
1484
2480
  });
1485
2481
 
1486
2482
  // src/commands/doctor.ts
1487
- import { existsSync as existsSync7 } from "fs";
1488
- import { defineCommand as defineCommand8 } from "citty";
1489
- import { createLogger as createLogger2, diagnose } from "@nymbalhq/platform";
2483
+ import { existsSync as existsSync10 } from "fs";
2484
+ import { defineCommand as defineCommand10 } from "citty";
2485
+ import { createLogger as createLogger3, diagnose } from "@nymbalhq/platform";
1490
2486
  import { errorText, HEALTH_CHECK_TIMEOUT_MS } from "@nymbalhq/types";
1491
2487
 
1492
2488
  // src/commands/doctor-report.ts
1493
- import pc4 from "picocolors";
2489
+ import pc6 from "picocolors";
1494
2490
  import { scrub as scrubSettings } from "@nymbalhq/platform";
1495
2491
  import { connectionSecrets, displayUrl as displayUrl2, SECRET_MIN_LENGTH } from "@nymbalhq/types";
1496
2492
  var TEXT_STATUS = {
@@ -1505,7 +2501,7 @@ var JSON_STATUS = {
1505
2501
  degraded: "degraded",
1506
2502
  down: "down"
1507
2503
  };
1508
- var COLOUR = { ok: pc4.green, warn: pc4.yellow, down: pc4.red };
2504
+ var COLOUR = { ok: pc6.green, warn: pc6.yellow, down: pc6.red };
1509
2505
  var SECRET_KEY = /secret|passw(?:or)?d|^pass$|token|api[-_]?key|private[-_]?key|credential|access[-_]?key/i;
1510
2506
  var SECRET_ENV = /SECRET|PASSWORD|PASSWD|(?:^|_)PASS(?:$|_)|TOKEN|API_KEY|PRIVATE_KEY|CREDENTIAL|ACCESS_KEY/i;
1511
2507
  var URL_IN_TEXT = /\b[a-z][a-z0-9+.-]*:\/\/[^\s'"`<>]+/gi;
@@ -1585,9 +2581,9 @@ function timeoutOf(flag2) {
1585
2581
  }
1586
2582
  function migrationsOf(projectRoot) {
1587
2583
  const root = resolveMigrations(projectRoot);
1588
- return existsSync7(root) ? { migrationsRoot: root } : {};
2584
+ return existsSync10(root) ? { migrationsRoot: root } : {};
1589
2585
  }
1590
- var doctorCommand = defineCommand8({
2586
+ var doctorCommand = defineCommand10({
1591
2587
  meta: {
1592
2588
  name: "doctor",
1593
2589
  description: "Check the project without changing it: config, packages, command store, migrations, slots and primitives"
@@ -1613,7 +2609,7 @@ var doctorCommand = defineCommand8({
1613
2609
  ) : await diagnose(loaded.config, {
1614
2610
  ...loaded.adapters !== void 0 && { adapters: loaded.adapters },
1615
2611
  // The report carries every failure; a log line would only repeat one, and break `--json`.
1616
- logger: createLogger2({ level: "silent", pretty: false }),
2612
+ logger: createLogger3({ level: "silent", pretty: false }),
1617
2613
  timeoutMs,
1618
2614
  ...migrationsOf(loaded.projectRoot)
1619
2615
  });
@@ -1629,16 +2625,16 @@ var doctorCommand = defineCommand8({
1629
2625
  });
1630
2626
 
1631
2627
  // src/commands/secrets.ts
1632
- import { defineCommand as defineCommand9 } from "citty";
1633
- import pc5 from "picocolors";
2628
+ import { defineCommand as defineCommand11 } from "citty";
2629
+ import pc7 from "picocolors";
1634
2630
  import {
1635
- createCommandStore as createCommandStore2,
2631
+ createCommandStore as createCommandStore3,
1636
2632
  createSettingsRepository,
1637
2633
  decrypt,
1638
2634
  encrypt,
1639
2635
  isMissingSettingsTable,
1640
- keyProblem,
1641
- readSecretsKey,
2636
+ keyProblem as keyProblem2,
2637
+ readSecretsKey as readSecretsKey2,
1642
2638
  SECRETS_KEY_ENV,
1643
2639
  SECRETS_KEY_OLD_ENV,
1644
2640
  settingAad
@@ -1646,17 +2642,17 @@ import {
1646
2642
  var RotationRefused = class extends Error {
1647
2643
  };
1648
2644
  function refuse(message) {
1649
- process.stderr.write(`${pc5.red(`\u2717 ${message}`)}
2645
+ process.stderr.write(`${pc7.red(`\u2717 ${message}`)}
1650
2646
  `);
1651
2647
  process.exitCode = 2;
1652
2648
  }
1653
2649
  async function rotateSecrets(env = process.env) {
1654
- const oldKey = readSecretsKey(env, SECRETS_KEY_OLD_ENV);
1655
- if (!oldKey.ok) throw new RotationRefused(keyProblem(oldKey.reason, SECRETS_KEY_OLD_ENV));
1656
- const newKey = readSecretsKey(env, SECRETS_KEY_ENV);
1657
- if (!newKey.ok) throw new RotationRefused(keyProblem(newKey.reason, SECRETS_KEY_ENV));
2650
+ const oldKey = readSecretsKey2(env, SECRETS_KEY_OLD_ENV);
2651
+ if (!oldKey.ok) throw new RotationRefused(keyProblem2(oldKey.reason, SECRETS_KEY_OLD_ENV));
2652
+ const newKey = readSecretsKey2(env, SECRETS_KEY_ENV);
2653
+ if (!newKey.ok) throw new RotationRefused(keyProblem2(newKey.reason, SECRETS_KEY_ENV));
1658
2654
  const { config } = await loadProject();
1659
- const store = createCommandStore2(config);
2655
+ const store = createCommandStore3(config);
1660
2656
  try {
1661
2657
  const repo = createSettingsRepository(store);
1662
2658
  return await store.transaction(async (tx) => {
@@ -1690,7 +2686,7 @@ async function rotateSecrets(env = process.env) {
1690
2686
  }
1691
2687
  async function clearSecrets(filter) {
1692
2688
  const { config } = await loadProject();
1693
- const store = createCommandStore2(config);
2689
+ const store = createCommandStore3(config);
1694
2690
  try {
1695
2691
  const repo = createSettingsRepository(store);
1696
2692
  return await store.transaction((tx) => repo.clear(tx, filter));
@@ -1701,7 +2697,7 @@ async function clearSecrets(filter) {
1701
2697
  await store.close();
1702
2698
  }
1703
2699
  }
1704
- var rotateCommand = defineCommand9({
2700
+ var rotateCommand = defineCommand11({
1705
2701
  meta: {
1706
2702
  name: "rotate",
1707
2703
  description: `Re-encrypt every saved secret from ${SECRETS_KEY_OLD_ENV} to ${SECRETS_KEY_ENV}, all or none`
@@ -1710,7 +2706,7 @@ var rotateCommand = defineCommand9({
1710
2706
  try {
1711
2707
  const count = await rotateSecrets();
1712
2708
  process.stdout.write(
1713
- `${pc5.green(`\u2713 rotated ${count} secret${count === 1 ? "" : "s"} to ${SECRETS_KEY_ENV}`)}
2709
+ `${pc7.green(`\u2713 rotated ${count} secret${count === 1 ? "" : "s"} to ${SECRETS_KEY_ENV}`)}
1714
2710
  `
1715
2711
  );
1716
2712
  } catch (error) {
@@ -1718,7 +2714,7 @@ var rotateCommand = defineCommand9({
1718
2714
  }
1719
2715
  }
1720
2716
  });
1721
- var clearCommand = defineCommand9({
2717
+ var clearCommand = defineCommand11({
1722
2718
  meta: {
1723
2719
  name: "clear",
1724
2720
  description: "Delete saved settings (all, or one slot or path); needs no key"
@@ -1733,22 +2729,22 @@ var clearCommand = defineCommand9({
1733
2729
  ...args.path !== void 0 && { path: args.path }
1734
2730
  });
1735
2731
  process.stdout.write(
1736
- `${pc5.green(`\u2713 cleared ${count} setting${count === 1 ? "" : "s"}`)}; restart the store to apply
2732
+ `${pc7.green(`\u2713 cleared ${count} setting${count === 1 ? "" : "s"}`)}; restart the store to apply
1737
2733
  `
1738
2734
  );
1739
2735
  }
1740
2736
  });
1741
- var secretsCommand = defineCommand9({
2737
+ var secretsCommand = defineCommand11({
1742
2738
  meta: { name: "secrets", description: "Manage the values saved in the admin's Settings" },
1743
2739
  subCommands: { rotate: rotateCommand, clear: clearCommand }
1744
2740
  });
1745
2741
 
1746
2742
  // src/commands/events.ts
1747
- import { existsSync as existsSync8 } from "fs";
1748
- import { resolve as resolve6 } from "path";
1749
- import { defineCommand as defineCommand10 } from "citty";
2743
+ import { existsSync as existsSync11 } from "fs";
2744
+ import { resolve as resolve7 } from "path";
2745
+ import { defineCommand as defineCommand12 } from "citty";
1750
2746
  import {
1751
- createCommandStore as createCommandStore3,
2747
+ createCommandStore as createCommandStore4,
1752
2748
  createEventLogRepository,
1753
2749
  sqliteFile as sqliteFile2
1754
2750
  } from "@nymbalhq/platform";
@@ -1798,11 +2794,11 @@ async function openLog() {
1798
2794
  const { config } = await loadProject();
1799
2795
  if (config.infrastructure.commandStore === "sqlite") {
1800
2796
  const path = sqliteFile2();
1801
- if (!existsSync8(resolve6(path))) {
2797
+ if (!existsSync11(resolve7(path))) {
1802
2798
  throw new EventsError(`no database at ${path}: run \`nymbal migrate\``);
1803
2799
  }
1804
2800
  }
1805
- const store = createCommandStore3(config, { readOnly: true });
2801
+ const store = createCommandStore4(config, { readOnly: true });
1806
2802
  return { store, eventLog: createEventLogRepository(store) };
1807
2803
  }
1808
2804
  async function guarded(body) {
@@ -1831,7 +2827,7 @@ var outputArgs = {
1831
2827
  default: false
1832
2828
  }
1833
2829
  };
1834
- var queryCommand = defineCommand10({
2830
+ var queryCommand = defineCommand12({
1835
2831
  meta: { name: "query", description: "Print one correlation id\u2019s events, in seq order" },
1836
2832
  args: {
1837
2833
  correlation: { type: "string", description: "The correlation id (required)" },
@@ -1868,7 +2864,7 @@ var queryCommand = defineCommand10({
1868
2864
  }
1869
2865
  })
1870
2866
  });
1871
- var tailCommand = defineCommand10({
2867
+ var tailCommand = defineCommand12({
1872
2868
  meta: {
1873
2869
  name: "tail",
1874
2870
  description: "Print events as they are appended, until interrupted. Exact for serially committed events; on Postgres an event whose lower seq commits after a higher one has been printed is skipped."
@@ -1924,19 +2920,19 @@ var tailCommand = defineCommand10({
1924
2920
  }
1925
2921
  })
1926
2922
  });
1927
- var eventsCommand = defineCommand10({
2923
+ var eventsCommand = defineCommand12({
1928
2924
  meta: { name: "events", description: "Read the event log without changing it" },
1929
2925
  subCommands: { query: queryCommand, tail: tailCommand }
1930
2926
  });
1931
2927
 
1932
2928
  // src/commands/audit.ts
1933
- import { createWriteStream, existsSync as existsSync9 } from "fs";
1934
- import { resolve as resolve7 } from "path";
2929
+ import { createWriteStream, existsSync as existsSync12 } from "fs";
2930
+ import { resolve as resolve8 } from "path";
1935
2931
  import { once } from "events";
1936
- import { defineCommand as defineCommand11 } from "citty";
2932
+ import { defineCommand as defineCommand13 } from "citty";
1937
2933
  import {
1938
2934
  auditEntriesInOrder,
1939
- createCommandStore as createCommandStore4,
2935
+ createCommandStore as createCommandStore5,
1940
2936
  sqliteFile as sqliteFile3
1941
2937
  } from "@nymbalhq/platform";
1942
2938
  import { errorText as errorText3 } from "@nymbalhq/types";
@@ -1953,7 +2949,7 @@ function timeFlag2(name, value) {
1953
2949
  async function write2(out2, text2) {
1954
2950
  if (!out2.write(text2)) await once(out2, "drain");
1955
2951
  }
1956
- var exportCommand = defineCommand11({
2952
+ var exportCommand = defineCommand13({
1957
2953
  meta: {
1958
2954
  name: "export",
1959
2955
  description: "Print audit entries as NDJSON, oldest first: ids only, no event payloads or customer data"
@@ -1976,11 +2972,11 @@ var exportCommand = defineCommand11({
1976
2972
  const { config } = await loadProject();
1977
2973
  if (config.infrastructure.commandStore === "sqlite") {
1978
2974
  const path = sqliteFile3();
1979
- if (!existsSync9(resolve7(path))) {
2975
+ if (!existsSync12(resolve8(path))) {
1980
2976
  throw new AuditError(`no database at ${path}: run \`nymbal migrate\``);
1981
2977
  }
1982
2978
  }
1983
- const store = createCommandStore4(config, { readOnly: true });
2979
+ const store = createCommandStore5(config, { readOnly: true });
1984
2980
  const out2 = args.out === void 0 ? process.stdout : createWriteStream(args.out);
1985
2981
  try {
1986
2982
  for await (const entry of auditEntriesInOrder(store, filter)) {
@@ -2001,17 +2997,17 @@ var exportCommand = defineCommand11({
2001
2997
  }
2002
2998
  }
2003
2999
  });
2004
- var auditCommand = defineCommand11({
3000
+ var auditCommand = defineCommand13({
2005
3001
  meta: { name: "audit", description: "Read the audit trail" },
2006
3002
  subCommands: { export: exportCommand }
2007
3003
  });
2008
3004
 
2009
3005
  // src/commands/replay.ts
2010
- import { existsSync as existsSync10 } from "fs";
2011
- import { resolve as resolve8 } from "path";
2012
- import { defineCommand as defineCommand12 } from "citty";
3006
+ import { existsSync as existsSync13 } from "fs";
3007
+ import { resolve as resolve9 } from "path";
3008
+ import { defineCommand as defineCommand14 } from "citty";
2013
3009
  import {
2014
- createLogger as createLogger3,
3010
+ createLogger as createLogger4,
2015
3011
  diffReadModel,
2016
3012
  openReadModels,
2017
3013
  READ_MODEL_NAMES,
@@ -2061,7 +3057,7 @@ function write3(stream, text2) {
2061
3057
  return new Promise((done) => stream.write(`${text2}
2062
3058
  `, () => done()));
2063
3059
  }
2064
- var replayCommand = defineCommand12({
3060
+ var replayCommand = defineCommand14({
2065
3061
  meta: {
2066
3062
  name: "replay",
2067
3063
  description: "Rebuild a derived read model from the command store and swap it in: catalogue, orders, customers, search, recently-viewed or all"
@@ -2082,17 +3078,17 @@ var replayCommand = defineCommand12({
2082
3078
  const names = modelsOf(args.to);
2083
3079
  const { config, adapters } = await loadProject();
2084
3080
  const shared = names.filter((n) => n !== "search");
2085
- if (config.infrastructure.documentStore === "in-memory" && shared.length > 0) {
3081
+ if (config.infrastructure.documentStore.provider === "in-memory" && shared.length > 0) {
2086
3082
  throw new ReplayError(
2087
- `the ${shared.join(", ")} read model${shared.length === 1 ? "" : "s"} live in the server's own process (documentStore: in-memory), out of reach of this one; a restart of the server rebuilds them. With documentStore redis or postgres-jsonb the read models are shared, and replay rebuilds them in place. --to search works here: the native index lives in the command store.`
3083
+ `the ${shared.join(", ")} read model${shared.length === 1 ? "" : "s"} live in the server's own process (infrastructure.documentStore 'in-memory'), out of reach of this one; a restart of the server rebuilds them. With infrastructure.documentStore redis or postgres-jsonb the read models are shared, and replay rebuilds them in place. --to search works here: the native index lives in the command store.`
2088
3084
  );
2089
3085
  }
2090
- if (config.infrastructure.commandStore === "sqlite" && !existsSync10(resolve8(sqliteFile4()))) {
3086
+ if (config.infrastructure.commandStore === "sqlite" && !existsSync13(resolve9(sqliteFile4()))) {
2091
3087
  throw new ReplayError(`no database at ${sqliteFile4()}: run \`nymbal migrate\``);
2092
3088
  }
2093
3089
  const { deps, close } = await openReadModels(config, {
2094
3090
  // The report says what happened; log lines would repeat it.
2095
- logger: createLogger3({ level: "silent", pretty: false }),
3091
+ logger: createLogger4({ level: "silent", pretty: false }),
2096
3092
  ...adapters !== void 0 && { adapters }
2097
3093
  });
2098
3094
  try {
@@ -2117,8 +3113,8 @@ var replayCommand = defineCommand12({
2117
3113
  });
2118
3114
 
2119
3115
  // src/commands/security.ts
2120
- import { defineCommand as defineCommand13 } from "citty";
2121
- import { createLogger as createLogger4, importProviderPackage } from "@nymbalhq/platform";
3116
+ import { defineCommand as defineCommand15 } from "citty";
3117
+ import { createLogger as createLogger5, importAdapterModule } from "@nymbalhq/platform";
2122
3118
  import {
2123
3119
  errorText as errorText5
2124
3120
  } from "@nymbalhq/types";
@@ -2174,15 +3170,18 @@ async function runEdge(command, body) {
2174
3170
  `security.adapter is '${security.adapter}', which has no edge rules for nymbal ${command}: set security.adapter to 'cloudflare' (nymbal add cloudflare) to manage them on a Cloudflare zone`
2175
3171
  );
2176
3172
  } else {
2177
- const mod = await importProviderPackage(
3173
+ const mod = await importAdapterModule(
2178
3174
  "security",
2179
- "cloudflare",
3175
+ {
3176
+ provider: "cloudflare",
3177
+ ...security.package !== void 0 && { package: security.package }
3178
+ },
2180
3179
  process.env
2181
3180
  );
2182
3181
  const adapter = await mod.createAdapter({
2183
3182
  slot: "security",
2184
3183
  config: security.cloudflare ?? {},
2185
- logger: createLogger4({ level: "silent", pretty: false }),
3184
+ logger: createLogger5({ level: "silent", pretty: false }),
2186
3185
  env: process.env
2187
3186
  });
2188
3187
  outcome = await body(adapter, security, mod);
@@ -2200,7 +3199,7 @@ var json = {
2200
3199
  description: "Print the result as one JSON document",
2201
3200
  default: false
2202
3201
  };
2203
- var securityPlanCommand = defineCommand13({
3202
+ var securityPlanCommand = defineCommand15({
2204
3203
  meta: {
2205
3204
  name: "security:plan",
2206
3205
  description: "Show what security:apply would change on the Cloudflare zone"
@@ -2216,7 +3215,7 @@ var securityPlanCommand = defineCommand13({
2216
3215
  return { code: 0, stdout: [...lines, ...notes], stderr: [] };
2217
3216
  })
2218
3217
  });
2219
- var securityApplyCommand = defineCommand13({
3218
+ var securityApplyCommand = defineCommand15({
2220
3219
  meta: {
2221
3220
  name: "security:apply",
2222
3221
  description: "Write the store's security rules to the Cloudflare zone, leaving the zone's own rules"
@@ -2229,7 +3228,7 @@ var securityApplyCommand = defineCommand13({
2229
3228
  return { code: 0, stdout: lines, stderr: [] };
2230
3229
  })
2231
3230
  });
2232
- var securityDriftCommand = defineCommand13({
3231
+ var securityDriftCommand = defineCommand15({
2233
3232
  meta: {
2234
3233
  name: "security:drift",
2235
3234
  description: "Report where the zone's Nymbal rules differ from the config (exit 1 on drift)"
@@ -2254,7 +3253,7 @@ var securityDriftCommand = defineCommand13({
2254
3253
  };
2255
3254
  })
2256
3255
  });
2257
- var securityInspectCommand = defineCommand13({
3256
+ var securityInspectCommand = defineCommand15({
2258
3257
  meta: {
2259
3258
  name: "security:inspect",
2260
3259
  description: "List the Nymbal rules live on the Cloudflare zone"
@@ -2267,53 +3266,69 @@ var securityInspectCommand = defineCommand13({
2267
3266
  });
2268
3267
 
2269
3268
  // src/commands/test.ts
2270
- import { defineCommand as defineCommand14 } from "citty";
3269
+ import { defineCommand as defineCommand16 } from "citty";
2271
3270
  import { loadConfig as loadConfig4 } from "@nymbalhq/config";
2272
3271
 
2273
3272
  // src/commands/test-contracts.ts
2274
- import { mkdirSync, realpathSync, writeFileSync as writeFileSync2 } from "fs";
2275
- import { createRequire as createRequire3 } from "module";
2276
- import { dirname as dirname7, join as join6, resolve as resolve9 } from "path";
2277
- import { pathToFileURL as pathToFileURL2 } from "url";
3273
+ import { mkdirSync, realpathSync, writeFileSync as writeFileSync4 } from "fs";
3274
+ import { createRequire as createRequire4 } from "module";
3275
+ import { dirname as dirname7, join as join9, resolve as resolve10 } from "path";
3276
+ import { pathToFileURL as pathToFileURL3 } from "url";
2278
3277
  import { isDeepStrictEqual } from "util";
2279
- import { findConfigFile as findConfigFile3, loadConfig as loadConfig3 } from "@nymbalhq/config";
3278
+ import { findConfigFile as findConfigFile3, loadConfig as loadConfig3, slotFolder as slotFolder6 } from "@nymbalhq/config";
3279
+ import { checkAdapterModule as checkAdapterModule2, resolveChoice as resolveChoice3 } from "@nymbalhq/platform";
2280
3280
  var CertifyError = class extends Error {
2281
3281
  };
2282
3282
  var firstLine = (text2) => text2.split("\n")[0].trim();
2283
- var messageOf = (err2) => firstLine(err2 instanceof Error ? err2.message : String(err2));
2284
- function resolveFrom(project, specifier, name, install) {
3283
+ var messageOf2 = (err2) => firstLine(err2 instanceof Error ? err2.message : String(err2));
3284
+ function resolveFrom2(project, specifier, name, install) {
2285
3285
  try {
2286
- return createRequire3(join6(project, "package.json")).resolve(specifier);
3286
+ return createRequire4(join9(project, "package.json")).resolve(specifier);
2287
3287
  } catch (err2) {
2288
3288
  if (err2.code === "MODULE_NOT_FOUND") {
2289
3289
  throw new CertifyError(`${name} is not installed in ${project}: ${install}`);
2290
3290
  }
2291
- throw new CertifyError(`${name} could not be resolved from ${project}: ${messageOf(err2)}`);
3291
+ throw new CertifyError(`${name} could not be resolved from ${project}: ${messageOf2(err2)}`);
2292
3292
  }
2293
3293
  }
2294
- async function slotOptions(project, pkg, slot) {
3294
+ function slotBlocks(config) {
3295
+ const { commerce, infrastructure, security } = config;
3296
+ const slots = Object.entries(commerce).filter(([name]) => name !== "orders");
3297
+ return [
3298
+ ...slots,
3299
+ ["documentStore", infrastructure.documentStore],
3300
+ ["eventBus", infrastructure.eventBus],
3301
+ ["media", infrastructure.media],
3302
+ [
3303
+ "security",
3304
+ { provider: security.adapter, package: security.package, config: security.config }
3305
+ ]
3306
+ ];
3307
+ }
3308
+ async function pickSlot(project, pkg, slot) {
2295
3309
  if (findConfigFile3(project) === null) return void 0;
2296
- let commerce;
3310
+ let config;
2297
3311
  try {
2298
- commerce = (await loadConfig3(project)).config.commerce;
3312
+ config = (await loadConfig3(project)).config;
2299
3313
  } catch (err2) {
2300
- throw new CertifyError(`the project's config could not be loaded: ${messageOf(err2)}`);
3314
+ throw new CertifyError(`the project's config could not be loaded: ${messageOf2(err2)}`);
2301
3315
  }
2302
- const naming = Object.entries(commerce).filter(([, block2]) => {
2303
- const b = block2;
2304
- return b.provider === "custom" && b.package === pkg;
3316
+ const naming = slotBlocks(config).filter(([name, block]) => {
3317
+ const resolved = resolveChoice3(name, block);
3318
+ return block.package === pkg || resolved.kind === "package" && resolved.package === pkg;
2305
3319
  });
2306
- const picked = slot === void 0 ? naming : naming.filter(([name]) => name === slot);
3320
+ const wanted = slot === void 0 ? void 0 : slotNamed(slot);
3321
+ const picked = slot === void 0 ? naming : naming.filter(([name]) => name === wanted);
2307
3322
  if (slot !== void 0 && picked.length === 0) {
2308
- throw new CertifyError(`no commerce slot '${slot}' with provider 'custom' names ${pkg}`);
3323
+ throw new CertifyError(`no slot '${slot}' loads ${pkg}`);
2309
3324
  }
2310
3325
  if (picked.length > 1) {
2311
3326
  throw new CertifyError(
2312
- `${pkg} is named by the ${picked.map(([name]) => name).join(", ")} slots: pick one with --slot`
3327
+ `${pkg} is named by the ${picked.map(([name]) => slotFolder6(name)).join(", ")} slots: pick one with --slot`
2313
3328
  );
2314
3329
  }
2315
- const block = picked[0]?.[1];
2316
- return block === void 0 ? void 0 : block.config ?? {};
3330
+ const found = picked[0];
3331
+ return found === void 0 ? void 0 : { slot: found[0], block: found[1] };
2317
3332
  }
2318
3333
  function withoutUndefined(value, path = /* @__PURE__ */ new Set()) {
2319
3334
  if (value === null || typeof value !== "object" || path.has(value)) return value;
@@ -2353,9 +3368,9 @@ function countCases(files) {
2353
3368
  async function certifyPackage(input) {
2354
3369
  const { pkg, slot } = input;
2355
3370
  const config = findConfigFile3(input.cwd);
2356
- const project = realpathSync(config === null ? resolve9(input.cwd) : dirname7(config));
2357
- const vitestNode = resolveFrom(project, "vitest/node", "vitest", "npm install --save-dev vitest");
2358
- const kindsEntry = resolveFrom(
3371
+ const project = realpathSync(config === null ? resolve10(input.cwd) : dirname7(config));
3372
+ const vitestNode = resolveFrom2(project, "vitest/node", "vitest", "npm install --save-dev vitest");
3373
+ const kindsEntry = resolveFrom2(
2359
3374
  project,
2360
3375
  "@nymbalhq/contract-tests/kinds",
2361
3376
  "@nymbalhq/contract-tests",
@@ -2364,24 +3379,31 @@ async function certifyPackage(input) {
2364
3379
  if (!isInstalled(pkg, project)) {
2365
3380
  throw new CertifyError(`${pkg} is not installed in ${project}: npm install ${pkg}`);
2366
3381
  }
2367
- const contracts = join6(project, ".nymbal", "contracts");
3382
+ const contracts = join9(project, ".nymbal", "contracts");
2368
3383
  const slug = pkg.replace(/[^a-z0-9]+/gi, "-").replace(/^-|-$/g, "");
2369
3384
  mkdirSync(contracts, { recursive: true });
2370
- const shim = join6(contracts, `${slug}.adapter.mjs`);
2371
- writeFileSync2(shim, `export * from ${JSON.stringify(pkg)}
3385
+ const shim = join9(contracts, `${slug}.adapter.mjs`);
3386
+ writeFileSync4(shim, `export * from ${JSON.stringify(pkg)}
2372
3387
  `);
2373
3388
  let mod;
2374
3389
  try {
2375
- mod = await import(pathToFileURL2(shim).href);
3390
+ mod = await import(pathToFileURL3(shim).href);
2376
3391
  } catch (err2) {
2377
- throw new CertifyError(`${pkg} could not be loaded: ${messageOf(err2)}`);
3392
+ throw new CertifyError(`${pkg} could not be loaded: ${messageOf2(err2)}`);
2378
3393
  }
2379
- if (typeof mod.createAdapter !== "function") {
3394
+ const picked = await pickSlot(project, pkg, slot);
3395
+ if (picked !== void 0) {
3396
+ try {
3397
+ checkAdapterModule2(mod, picked.slot, picked.block.provider, pkg);
3398
+ } catch (err2) {
3399
+ throw new CertifyError(messageOf2(err2));
3400
+ }
3401
+ } else if (typeof mod.createAdapter !== "function") {
2380
3402
  throw new CertifyError(`${pkg} exports no createAdapter(options) function to certify`);
2381
3403
  }
2382
3404
  const createAdapter = mod.createAdapter;
2383
3405
  const extra = mod.contractOptions ?? {};
2384
- const slotConfig = await slotOptions(project, pkg, slot);
3406
+ const slotConfig = picked === void 0 ? void 0 : picked.block.config ?? {};
2385
3407
  const fromSlot = slotConfig === void 0 ? void 0 : withoutUndefined(slotConfig);
2386
3408
  const options = fromSlot ?? extra.options ?? {};
2387
3409
  if (fromSlot !== void 0 && !survivesJson(fromSlot)) {
@@ -2396,22 +3418,22 @@ async function certifyPackage(input) {
2396
3418
  kind = typeof own === "string" ? own : extra.kind;
2397
3419
  await closeProbe(probe);
2398
3420
  } catch (err2) {
2399
- throw new CertifyError(`createAdapter from ${pkg} threw: ${messageOf(err2)}`);
3421
+ throw new CertifyError(`createAdapter from ${pkg} threw: ${messageOf2(err2)}`);
2400
3422
  }
2401
3423
  if (kind === void 0) {
2402
3424
  throw new CertifyError(
2403
3425
  `${pkg}'s adapter has no kind: a primitive names its own in contractOptions.kind`
2404
3426
  );
2405
3427
  }
2406
- const { CONTRACT_KINDS } = await import(pathToFileURL2(kindsEntry).href);
3428
+ const { CONTRACT_KINDS } = await import(pathToFileURL3(kindsEntry).href);
2407
3429
  if (!CONTRACT_KINDS.includes(kind)) {
2408
3430
  throw new CertifyError(
2409
3431
  `no contract suite for kind '${kind}' (${pkg}); the kinds with one are ${CONTRACT_KINDS.join(", ")}`
2410
3432
  );
2411
3433
  }
2412
3434
  const file = `${slug}.contract.test.mjs`;
2413
- writeFileSync2(
2414
- join6(contracts, file),
3435
+ writeFileSync4(
3436
+ join9(contracts, file),
2415
3437
  [
2416
3438
  `// Written by \`nymbal test:contracts --package ${pkg}\`, and again on every run.`,
2417
3439
  `import * as adapter from ${JSON.stringify(pkg)}`,
@@ -2432,7 +3454,7 @@ async function certifyPackage(input) {
2432
3454
  ``
2433
3455
  ].join("\n")
2434
3456
  );
2435
- const { startVitest } = await import(pathToFileURL2(vitestNode).href);
3457
+ const { startVitest } = await import(pathToFileURL3(vitestNode).href);
2436
3458
  const vitest = await startVitest(
2437
3459
  "test",
2438
3460
  [],
@@ -2444,7 +3466,7 @@ async function certifyPackage(input) {
2444
3466
  testTimeout: 6e4,
2445
3467
  hookTimeout: 6e4
2446
3468
  },
2447
- { cacheDir: join6(contracts, ".vite") }
3469
+ { cacheDir: join9(contracts, ".vite") }
2448
3470
  );
2449
3471
  if (vitest === void 0) throw new CertifyError(`vitest did not start for ${pkg}`);
2450
3472
  const files = vitest.state.getFiles();
@@ -2463,13 +3485,13 @@ async function certifyPackage(input) {
2463
3485
  }
2464
3486
 
2465
3487
  // src/commands/test.ts
2466
- var testCommand = defineCommand14({
3488
+ var testCommand = defineCommand16({
2467
3489
  meta: { name: "test", description: "Run unit + integration tests (vitest)" },
2468
3490
  async run() {
2469
3491
  await runOrFail("pnpm", ["vitest", "run"]);
2470
3492
  }
2471
3493
  });
2472
- var testE2eCommand = defineCommand14({
3494
+ var testE2eCommand = defineCommand16({
2473
3495
  meta: { name: "test:e2e", description: "Run Playwright E2E against the configured template" },
2474
3496
  async run() {
2475
3497
  const { config } = await loadConfig4();
@@ -2486,7 +3508,7 @@ var testE2eCommand = defineCommand14({
2486
3508
  ]);
2487
3509
  }
2488
3510
  });
2489
- var testVisualCommand = defineCommand14({
3511
+ var testVisualCommand = defineCommand16({
2490
3512
  meta: { name: "test:visual", description: "Run visual regression tests (Playwright toHaveScreenshot)" },
2491
3513
  args: {
2492
3514
  "update-baselines": {
@@ -2531,7 +3553,7 @@ var testVisualCommand = defineCommand14({
2531
3553
  }
2532
3554
  }
2533
3555
  });
2534
- var testContractsCommand = defineCommand14({
3556
+ var testContractsCommand = defineCommand16({
2535
3557
  meta: { name: "test:contracts", description: "Run adapter contract tests, or certify an adapter package" },
2536
3558
  args: {
2537
3559
  adapter: { type: "string", description: "Run only contracts for a specific adapter (e.g. payments, email)" },
@@ -2572,7 +3594,7 @@ var testContractsCommand = defineCommand14({
2572
3594
  await runOrFail("pnpm", vArgs);
2573
3595
  }
2574
3596
  });
2575
- var testPerformanceCommand = defineCommand14({
3597
+ var testPerformanceCommand = defineCommand16({
2576
3598
  meta: { name: "test:performance", description: "Run Lighthouse CI against the configured template" },
2577
3599
  async run() {
2578
3600
  const { config } = await loadConfig4();
@@ -2586,7 +3608,7 @@ var testPerformanceCommand = defineCommand14({
2586
3608
  });
2587
3609
  }
2588
3610
  });
2589
- var testAllCommand = defineCommand14({
3611
+ var testAllCommand = defineCommand16({
2590
3612
  meta: { name: "test:all", description: "Run unit, contract, e2e, visual, and performance tests" },
2591
3613
  async run() {
2592
3614
  const steps = [
@@ -2631,7 +3653,7 @@ var testAllCommand = defineCommand14({
2631
3653
  });
2632
3654
 
2633
3655
  // src/index.ts
2634
- var main = defineCommand15({
3656
+ var main = defineCommand17({
2635
3657
  meta: {
2636
3658
  name: "nymbal",
2637
3659
  version: getCliVersion(),
@@ -2640,6 +3662,8 @@ var main = defineCommand15({
2640
3662
  subCommands: {
2641
3663
  dev: devCommand,
2642
3664
  build: buildCommand,
3665
+ start: startCommand,
3666
+ deploy: deployCommand,
2643
3667
  migrate: migrateCommand,
2644
3668
  seed: seedCommand,
2645
3669
  import: importCommand,
@@ -2667,7 +3691,14 @@ if (rest.length === 0 && (flag === "--version" || flag === "-v")) {
2667
3691
  process.stdout.write(`${getCliVersion()}
2668
3692
  `);
2669
3693
  } else {
2670
- runMain(main);
3694
+ runMain(main, {
3695
+ // `nymbal add --help` lists the forms, the slots with their providers, and the recipes.
3696
+ showUsage: async (cmd, parent) => {
3697
+ await showUsage(cmd, parent);
3698
+ if (cmd === addCommand) process.stdout.write(`${addUsage()}
3699
+ `);
3700
+ }
3701
+ });
2671
3702
  }
2672
3703
  export {
2673
3704
  resolveAdminRoot