Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

Harden the generator and utility scripts (#1645)

Sidb535ca44206d
diff --git a/scripts/generate-db-types.ts b/scripts/generate-db-types.ts
index d8b365331b..309dfe30f4 100644
--- a/scripts/generate-db-types.ts
+++ b/scripts/generate-db-types.ts
@@ -1,102 +1,13 @@
-import {
- closeSync,
- copyFileSync,
- openSync,
- readFileSync,
- writeFileSync
-} from "node:fs";
-import { spawnSync } from "node:child_process";
-import { join } from "node:path";
-import * as dotenv from "dotenv";
-
-dotenv.config({ path: ".env" });
-dotenv.config({ path: ".env.local", override: true });
-
-const dbUrl = process.env.SUPABASE_DB_URL;
-if (!dbUrl) {
- console.error(
- "SUPABASE_DB_URL not set (expected in .env or .env.local). Run `pnpm dev:up` first."
- );
- process.exit(1);
-}
-
-if (!/(localhost|127\.0\.0\.1)/.test(dbUrl)) {
- console.error(
- `Refusing to generate types against non-local DB: ${dbUrl.replace(/:[^:@/]+@/, ":***@")}`
+import { generateDatabaseTypes } from "./lib/generate-db-types";
+import { loadDotEnv } from "./lib/local-script-config";
+
+try {
+ loadDotEnv();
+ generateDatabaseTypes(process.env.SUPABASE_DB_URL);
+ process.stdout.write("Database types refreshed in both output files.\n");
+} catch (error) {
+ process.stderr.write(
+ `${error instanceof Error ? error.message : "Database type generation failed."}\n`
);
- process.exit(1);
-}
-
-const typesPath = join("packages", "database", "src", "types.ts");
-const fnTypesPath = join(
- "packages",
- "database",
- "supabase",
- "functions",
- "lib",
- "types.ts"
-);
-
-// Pipe supabase stdout directly to the types file to avoid spawnSync's 1MB
-// default buffer cap (generated types are ~MBs).
-const out = openSync(typesPath, "w");
-const r = spawnSync(
- "supabase",
- [
- "gen",
- "types",
- "typescript",
- "--db-url",
- dbUrl,
- "--schema",
- "public",
- "--schema",
- "storage",
- "--schema",
- "graphql_public"
- ],
- { stdio: ["ignore", out, "inherit"] }
-);
-closeSync(out);
-
-if (r.status !== 0) {
- console.error(`supabase gen types failed (exit ${r.status})`);
- process.exit(r.status ?? 1);
+ process.exitCode = 1;
}
-
-// Strip per-tenant `searchIndex_<companyId>` / `auditLog_<companyId>` tables.
-// They are created at runtime per company (rebuild_search_index and the audit
-// log setup in the migrations), so which ones exist depends on the local DB's
-// seeded companies — committing them makes types.ts machine-dependent and
-// churns on every regen. The static `searchIndexRegistry` / `auditLogArchive`
-// tables (no underscore) are unaffected.
-const stripPerTenantTables = (source: string): string => {
- const lines = source.split("\n");
- const result: string[] = [];
- let skipping = false;
- let stripped = 0;
- for (const line of lines) {
- if (
- !skipping &&
- /^ (searchIndex|auditLog)_[A-Za-z0-9]+: \{$/.test(line)
- ) {
- skipping = true;
- stripped++;
- continue;
- }
- if (skipping) {
- if (line === " }") skipping = false;
- continue;
- }
- result.push(line);
- }
- if (stripped > 0) {
- console.log(`stripped ${stripped} per-tenant table(s)`);
- }
- return result.join("\n");
-};
-
-writeFileSync(typesPath, stripPerTenantTables(readFileSync(typesPath, "utf8")));
-
-copyFileSync(typesPath, fnTypesPath);
-console.log(`wrote ${typesPath}\nwrote ${fnTypesPath}`);
diff --git a/scripts/generate-mcp.ts b/scripts/generate-mcp.ts
index f31a99ae54..22604e76de 100644
--- a/scripts/generate-mcp.ts
+++ b/scripts/generate-mcp.ts
@@ -14,7 +14,10 @@ import {
buildManifestDigest,
serializeManifestDigest
} from "./lib/manifest-digest";
-import { buildAllToolMetadataWithValidators } from "./lib/service-metadata";
+import {
+ buildAllToolMetadataWithValidators,
+ MODULE_LIST
+} from "./lib/service-metadata";
const ROOT = path.resolve(__dirname, "..");
const METADATA_FILE = path.join(
@@ -38,8 +41,9 @@ export async function generateToolMetadata(): Promise<void> {
onModule: (mod, count) => console.log(` ✓ ${mod}: ${count} tools`),
});
+ // No timestamp: the file must be a pure function of the sources so repeated
+ // runs on an unchanged tree are byte-identical.
const metadata = {
- generated: new Date().toISOString(),
totalTools: allTools.length,
modules: [...new Set(allTools.map((t) => t.module))].length,
tools: allTools,
@@ -61,7 +65,7 @@ export async function generateToolMetadata(): Promise<void> {
// silently — that fallback is the only path that can publish a lossy schema.
const fallbacks = resolutions.filter((r) => r.how !== "native");
console.log(
- ` Schemas: ${registryStats.validatorsConverted} validators converted from ${registryStats.modulesLoaded}/15 modules`
+ ` Schemas: ${registryStats.validatorsConverted} validators converted from ${registryStats.modulesLoaded}/${MODULE_LIST.length} modules`
);
console.log(
` Responses: ${responseStats.derived}/${responseStats.functions} reflected from return types (${responseStats.empty} yielded nothing usable)`
diff --git a/scripts/generate-swagger-docs.ts b/scripts/generate-swagger-docs.ts
index 031b177906..64bc28fd5a 100644
--- a/scripts/generate-swagger-docs.ts
+++ b/scripts/generate-swagger-docs.ts
@@ -1,26 +1,21 @@
-import { writeFileSync } from "node:fs";
-import * as dotenv from "dotenv";
+import { renameSync, writeFileSync } from "node:fs";
+import { loadDotEnv } from "./lib/local-script-config";
+import { normalizeSwaggerSchema } from "./lib/swagger-schema";
-dotenv.config({ path: ".env" });
-dotenv.config({ path: ".env.local", override: true });
-
-const studioPort = process.env.PORT_STUDIO;
-if (!studioPort) {
- console.error(
- "PORT_STUDIO not set (expected in .env.local). Run `pnpm dev:up` first."
+async function main(): Promise<void> {
+ loadDotEnv();
+ const studioPort = process.env.PORT_STUDIO;
+ if (!studioPort)
+ throw new Error(
+ "PORT_STUDIO not set (expected in .env.local). Run `pnpm dev:up` first."
+ );
+ const response = await fetch(
+ `http://127.0.0.1:${studioPort}/api/platform/projects/default/api/rest`,
+ { signal: AbortSignal.timeout(30_000) }
);
- process.exit(1);
-}
-
-const url = `http://localhost:${studioPort}/api/platform/projects/default/api/rest`;
-
-(async () => {
- const response = await fetch(url);
- if (!response.ok) {
- throw new Error(`HTTP error! status: ${response.status}`);
- }
-
- const data = await response.json();
+ if (!response.ok)
+ throw new Error(`Swagger request failed (HTTP ${response.status})`);
+ const data = normalizeSwaggerSchema(await response.json());
// Strip per-tenant `searchIndex_<companyId>` / `auditLog_<companyId>` tables
// (created at runtime per company) — which ones exist depends on the local
@@ -41,8 +36,18 @@ const url = `http://localhost:${studioPort}/api/platform/projects/default/api/re
return value;
};
+ const output = "packages/database/src/swagger-docs-schema.ts";
writeFileSync(
- "packages/database/src/swagger-docs-schema.ts",
+ `${output}.tmp`,
`export default ${JSON.stringify(stripPerTenantKeys(data), null, 2)}`
);
-})();
+ renameSync(`${output}.tmp`, output);
+ process.stdout.write("Swagger schema refreshed.\n");
+}
+
+main().catch((error) => {
+ process.stderr.write(
+ `Swagger generation failed: ${error instanceof Error ? error.message : String(error)}\n`
+ );
+ process.exitCode = 1;
+});
diff --git a/scripts/lib/generate-db-types.test.ts b/scripts/lib/generate-db-types.test.ts
new file mode 100644
index 0000000000..8bc25c6d96
--- /dev/null
+++ b/scripts/lib/generate-db-types.test.ts
@@ -0,0 +1,210 @@
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import {
+ copyFileSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ realpathSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync
+} from "node:fs";
+import { createRequire } from "node:module";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { test } from "node:test";
+import { fileURLToPath } from "node:url";
+import { sortRelationships } from "./generate-db-types";
+
+const require = createRequire(import.meta.url);
+const root = fileURLToPath(new URL("../../", import.meta.url));
+const targets = [
+ "packages/database/src/types.ts",
+ "packages/database/supabase/functions/lib/types.ts"
+] as const;
+const original = "export type Database = { public: { Tables: {} } };\n";
+const generated =
+ "export type Database = { public: { Tables: { example: {} } } };\n";
+
+function runGenerator(
+ output: string,
+ options: {
+ exit?: number;
+ databaseUrl?: string;
+ missingExecutable?: boolean;
+ envFiles?: Record<string, string>;
+ } = {}
+) {
+ const directory = realpathSync(
+ mkdtempSync(join(tmpdir(), "carbon-db-generation-"))
+ );
+ try {
+ for (const [file, content] of Object.entries(options.envFiles ?? {})) {
+ writeFileSync(join(directory, file), content);
+ }
+ for (const target of targets) {
+ mkdirSync(dirname(join(directory, target)), { recursive: true });
+ writeFileSync(join(directory, target), original);
+ }
+ mkdirSync(join(directory, "scripts/lib"), { recursive: true });
+ for (const file of [
+ "scripts/generate-db-types.ts",
+ "scripts/lib/generate-db-types.ts",
+ "scripts/lib/local-script-config.ts"
+ ]) {
+ copyFileSync(join(root, file), join(directory, file));
+ }
+ symlinkSync(
+ join(root, "node_modules"),
+ join(directory, "node_modules"),
+ "dir"
+ );
+ const bin = join(directory, "bin");
+ mkdirSync(bin);
+ const marker = join(directory, "invoked");
+ writeFileSync(join(directory, "output.txt"), output);
+ if (!options.missingExecutable) {
+ writeFileSync(
+ join(bin, "supabase"),
+ `#!${process.execPath}\nconst fs = require('node:fs');\nfs.writeFileSync(${JSON.stringify(marker)}, 'yes');\nfs.writeSync(1, fs.readFileSync(${JSON.stringify(join(directory, "output.txt"))}));\nprocess.exit(${options.exit ?? 0});\n`,
+ { mode: 0o755 }
+ );
+ }
+ const result = spawnSync(
+ process.execPath,
+ ["--import", require.resolve("tsx"), join(directory, "scripts/generate-db-types.ts")],
+ {
+ cwd: directory,
+ encoding: "utf8",
+ timeout: 20_000,
+ env: {
+ ...process.env,
+ NODE_PATH: undefined,
+ PATH: bin,
+ SUPABASE_DB_URL:
+ options.databaseUrl ??
+ "postgresql://example:[email protected]:5432/example"
+ }
+ }
+ );
+ return {
+ ...result,
+ invoked: existsSync(marker),
+ contents: targets.map((target) =>
+ readFileSync(join(directory, target), "utf8")
+ ),
+ remaining: targets.map((target) =>
+ readdirSync(dirname(join(directory, target)))
+ )
+ };
+ } finally {
+ rmSync(directory, { recursive: true, force: true });
+ }
+}
+
+test("default .env preserves the caller's database URL", () => {
+ const result = runGenerator(generated, {
+ envFiles: {
+ ".env": "SUPABASE_DB_URL=postgresql://external.example.com/database\n"
+ }
+ });
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.invoked, true);
+});
+
+test(".env.local overrides the caller's URL before the local-host safety check", () => {
+ const result = runGenerator(generated, {
+ envFiles: {
+ ".env.local":
+ "SUPABASE_DB_URL=postgresql://external.example.com/database\n"
+ }
+ });
+ assert.notEqual(result.status, 0);
+ assert.equal(result.invoked, false);
+ assert.deepEqual(result.contents, [original, original]);
+});
+
+test("failed subprocess preserves both last-good outputs and cleans temporary files", () => {
+ const result = runGenerator("partial output", { exit: 7 });
+ assert.equal(result.invoked, true, result.stderr);
+ assert.notEqual(result.status, 0);
+ assert.deepEqual(result.contents, [original, original]);
+ assert.deepEqual(result.remaining, [["types.ts"], ["types.ts"]]);
+});
+
+test("missing generator executable preserves both last-good outputs", () => {
+ const result = runGenerator(generated, { missingExecutable: true });
+ assert.notEqual(result.status, 0);
+ assert.deepEqual(result.contents, [original, original]);
+ assert.deepEqual(result.remaining, [["types.ts"], ["types.ts"]]);
+});
+
+for (const output of ["", " \n", "export const unrelated = 42;", "type Database = {};"]) {
+ test(`rejects unusable successful output (${JSON.stringify(output)})`, () => {
+ const result = runGenerator(output);
+ assert.equal(result.invoked, true, result.stderr);
+ assert.notEqual(result.status, 0);
+ assert.deepEqual(result.contents, [original, original]);
+ assert.deepEqual(result.remaining, [["types.ts"], ["types.ts"]]);
+ });
+}
+
+for (const databaseUrl of [
+ "postgresql://localhost:[email protected]/example",
+ "postgresql://example:[email protected]/example",
+ "postgresql://example:[email protected]/localhost",
+ "http://example:synthetic-secret@localhost/example",
+ "postgresql://example:synthetic-secret@localhost/example?host=example.com",
+ "postgresql://example:synthetic-secret@localhost/example?hostaddr=192.0.2.1",
+ "not-a-database-url"
+]) {
+ test(`rejects a malformed or non-local database URL (${databaseUrl.split(":")[0]})`, () => {
+ const result = runGenerator(generated, { databaseUrl });
+ assert.notEqual(result.status, 0);
+ assert.equal(result.invoked, false);
+ assert.deepEqual(result.contents, [original, original]);
+ assert.doesNotMatch(
+ result.stdout + result.stderr,
+ /synthetic-secret|example\.com/
+ );
+ });
+}
+
+for (const host of ["localhost", "127.0.0.1", "[::1]"]) {
+ test(`publishes identical validated outputs for local host ${host}`, () => {
+ const result = runGenerator(generated, {
+ databaseUrl: `postgresql://example:synthetic@${host}:5432/example`
+ });
+ assert.equal(result.status, 0, result.stderr);
+ assert.deepEqual(result.contents, [generated, generated]);
+ assert.deepEqual(result.remaining, [["types.ts"], ["types.ts"]]);
+ });
+}
+
+test("MCP generation does not cache incomplete transitive input coverage", () => {
+ const turbo = JSON.parse(readFileSync(join(root, "turbo.json"), "utf8"));
+ assert.equal(turbo.tasks["//#generate:mcp"].cache, false);
+});
+
+test("sortRelationships orders each Relationships block deterministically", () => {
+ const block = (entries: string[]) =>
+ [" x: {", " Relationships: [", ...entries, " ]", " }"].join("\n");
+ const entry = (fk: string, col: string, last = false) =>
+ [
+ " {",
+ ` foreignKeyName: "${fk}"`,
+ ` columns: ["${col}"]`,
+ " isOneToOne: false",
+ ' referencedRelation: "country"',
+ ' referencedColumns: ["code"]',
+ last ? " }" : " },"
+ ].join("\n");
+ const a = block([entry("x_fkey", "supplierCountryCode"), entry("x_fkey", "customerCountryCode", true)]);
+ const b = block([entry("x_fkey", "customerCountryCode"), entry("x_fkey", "supplierCountryCode", true)]);
+ assert.equal(sortRelationships(a), sortRelationships(b));
+ assert.equal(sortRelationships(a), b, "sorted output keeps a trailing comma on every entry but the last");
+ assert.equal(sortRelationships(" Relationships: []\n }"), " Relationships: []\n }");
+});
diff --git a/scripts/lib/generate-db-types.ts b/scripts/lib/generate-db-types.ts
new file mode 100644
index 0000000000..6571edac8b
--- /dev/null
+++ b/scripts/lib/generate-db-types.ts
@@ -0,0 +1,169 @@
+import { spawnSync } from "node:child_process";
+import {
+ closeSync,
+ mkdtempSync,
+ openSync,
+ readFileSync,
+ renameSync,
+ rmSync,
+ writeFileSync
+} from "node:fs";
+import { dirname, join, resolve } from "node:path";
+
+function validateDatabaseUrl(value: string | undefined): string {
+ if (!value?.trim()) {
+ throw new Error(
+ "SUPABASE_DB_URL is not set. Configure the local database before generating types."
+ );
+ }
+ let url: URL;
+ try {
+ url = new URL(value);
+ } catch {
+ throw new Error("SUPABASE_DB_URL must be a valid local PostgreSQL URL.");
+ }
+ if (
+ !["postgres:", "postgresql:"].includes(url.protocol) ||
+ !["localhost", "127.0.0.1", "[::1]"].includes(url.hostname) ||
+ url.searchParams.has("host") ||
+ url.searchParams.has("hostaddr")
+ ) {
+ // Never include the URL: even a redacted password can leave private hosts,
+ // usernames or query parameters in output copied into public run logs.
+ throw new Error(
+ "Refusing to generate types: SUPABASE_DB_URL must use a local PostgreSQL host."
+ );
+ }
+ return value;
+}
+
+// Strip per-tenant `searchIndex_<companyId>` / `auditLog_<companyId>` tables.
+// They are created at runtime per company, so which ones exist depends on the
+// local DB's seeded companies — committing them makes types.ts
+// machine-dependent. The static `searchIndexRegistry` / `auditLogArchive`
+// tables (no underscore) are unaffected.
+function stripPerTenantTables(source: string): string {
+ const lines: string[] = [];
+ let skipping = false;
+ for (const line of source.split("\n")) {
+ if (
+ !skipping &&
+ /^ (searchIndex|auditLog)_[A-Za-z0-9]+: \{$/.test(line)
+ ) {
+ skipping = true;
+ continue;
+ }
+ if (skipping) {
+ if (line === " }") skipping = false;
+ continue;
+ }
+ lines.push(line);
+ }
+ return lines.join("\n");
+}
+
+// `supabase gen types` emits a table's `Relationships` entries in catalog order,
+// which is not stable across databases built from the same migrations (two
+// foreign keys to the same table swap places between runs). Sort each block's
+// entries by their text so the output is a pure function of the schema and the
+// generated-files drift check can compare it byte for byte.
+export function sortRelationships(source: string): string {
+ const lines = source.split("\n");
+ const out: string[] = [];
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+ out.push(line);
+ if (!/^\s*Relationships: \[$/.test(line)) continue;
+ const indent = line.match(/^\s*/)?.[0] ?? "";
+ const entries: string[][] = [];
+ let j = i + 1;
+ while (j < lines.length && lines[j] !== `${indent}]`) {
+ if (lines[j] === `${indent} {`) {
+ const entry = [lines[j]];
+ j++;
+ while (j < lines.length && !/^\s*\},?$/.test(lines[j]))
+ entry.push(lines[j++]);
+ entry.push(lines[j]);
+ entries.push(entry);
+ }
+ j++;
+ }
+ if (j >= lines.length) continue;
+ const closing = lines[j];
+ entries.sort((a, b) => {
+ const ka = a.slice(1, -1).join("\n");
+ const kb = b.slice(1, -1).join("\n");
+ return ka < kb ? -1 : ka > kb ? 1 : 0;
+ });
+ entries.forEach((entry, index) => {
+ const last = entry[entry.length - 1].replace(/,$/, "");
+ out.push(
+ ...entry.slice(0, -1),
+ index < entries.length - 1 ? `${last},` : last
+ );
+ });
+ out.push(closing);
+ i = j;
+ }
+ return out.join("\n");
+}
+
+export function generateDatabaseTypes(databaseUrl: string | undefined): void {
+ const dbUrl = validateDatabaseUrl(databaseUrl);
+ const targets = [
+ resolve("packages/database/src/types.ts"),
+ resolve("packages/database/supabase/functions/lib/types.ts")
+ ];
+ const directory = mkdtempSync(join(dirname(targets[0]!), ".db-types-"));
+ try {
+ const candidate = join(directory, "types.ts");
+ const out = openSync(candidate, "wx");
+ try {
+ // File-backed stdout avoids truncating large schemas or a maxBuffer cap.
+ // Do not inherit stderr: CLI failures can echo the credential-bearing URL.
+ const result = spawnSync(
+ "supabase",
+ [
+ "gen",
+ "types",
+ "typescript",
+ "--db-url",
+ dbUrl,
+ "--schema",
+ "public",
+ "--schema",
+ "storage",
+ "--schema",
+ "graphql_public"
+ ],
+ { stdio: ["ignore", out, "pipe"] }
+ );
+ if (result.error || result.status !== 0) {
+ const status =
+ result.status === null
+ ? "could not complete"
+ : `exited ${result.status}`;
+ throw new Error(
+ `Supabase type generation ${status}; existing type files were preserved.`
+ );
+ }
+ } finally {
+ closeSync(out);
+ }
+ const normalized = sortRelationships(
+ stripPerTenantTables(readFileSync(candidate, "utf8"))
+ );
+ if (!/^export type Database\b/m.test(normalized)) {
+ throw new Error(
+ "Database type generation did not produce an exported Database type; existing type files were preserved."
+ );
+ }
+ for (const target of targets) {
+ const staged = join(directory, "staged.ts");
+ writeFileSync(staged, normalized);
+ renameSync(staged, target);
+ }
+ } finally {
+ rmSync(directory, { recursive: true, force: true });
+ }
+}
diff --git a/scripts/lib/local-script-config.test.ts b/scripts/lib/local-script-config.test.ts
new file mode 100644
index 0000000000..caa71869b8
--- /dev/null
+++ b/scripts/lib/local-script-config.test.ts
@@ -0,0 +1,113 @@
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { createRequire } from "node:module";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { test } from "node:test";
+import { pathToFileURL } from "node:url";
+import { readLocalScriptConfig } from "./local-script-config";
+
+test("readLocalScriptConfig returns the requested values from the environment", () => {
+ const config = readLocalScriptConfig(["A_KEY", "B_KEY"], {
+ A_KEY: "a",
+ B_KEY: "b",
+ C_KEY: "ignored"
+ });
+ assert.deepEqual(config, { A_KEY: "a", B_KEY: "b" });
+});
+
+test("readLocalScriptConfig names missing keys without disclosing configured values", () => {
+ assert.throws(
+ () =>
+ readLocalScriptConfig(["A_KEY", "B_KEY", "C_KEY"], {
+ A_KEY: "private-value-sentinel",
+ B_KEY: " "
+ }),
+ (error: Error) => {
+ assert.match(error.message, /B_KEY/);
+ assert.match(error.message, /C_KEY/);
+ assert.doesNotMatch(error.message, /private-value-sentinel/);
+ return true;
+ }
+ );
+});
+
+for (const script of ["sandbox", "model-upload", "sales-invoice-report"]) {
+ test(`${script} CLI reaches its configuration error with NODE_PATH unset`, () => {
+ const directory = mkdtempSync(join(tmpdir(), "carbon-script-config-"));
+ try {
+ const result = spawnSync(
+ process.execPath,
+ [
+ "--import",
+ createRequire(import.meta.url).resolve("tsx"),
+ resolve(`scripts/${script}.ts`)
+ ],
+ { cwd: directory, env: {}, encoding: "utf8", timeout: 15_000 }
+ );
+ assert(result.status === 1, "Missing configuration must fail the CLI");
+ assert(
+ result.stderr.includes("Missing required local configuration"),
+ "CLI must reach the configuration guard before any dependency or IO error"
+ );
+ assert(!result.stderr.includes("ERR_MODULE_NOT_FOUND"));
+ } finally {
+ rmSync(directory, { recursive: true, force: true });
+ }
+ });
+}
+
+test("real .env parser and pinned SDK load without root dependency aliases or network", () => {
+ const directory = mkdtempSync(join(tmpdir(), "carbon-script-client-"));
+ try {
+ writeFileSync(
+ join(directory, ".env"),
+ 'SUPABASE_URL="https://database.example.com"\nCARBON_API_KEY="fixture-api-key"\n'
+ );
+ writeFileSync(
+ join(directory, ".env.local"),
+ 'CARBON_API_KEY="fixture-local-override"\n'
+ );
+ const result = spawnSync(
+ process.execPath,
+ [
+ "--import",
+ createRequire(import.meta.url).resolve("tsx"),
+ "--input-type=module",
+ "--eval",
+ `import assert from "node:assert/strict";
+import helpers from ${JSON.stringify(
+ pathToFileURL(resolve("scripts/lib/local-script-config.ts")).href
+ )};
+const { createScriptClient, readLocalScriptConfig } = helpers;
+const config = readLocalScriptConfig(
+ ["SUPABASE_URL", "SUPABASE_ANON_KEY", "CARBON_API_KEY"],
+ { SUPABASE_ANON_KEY: "fixture-public-key", CARBON_API_KEY: "fixture-environment" }
+);
+let calls = 0;
+globalThis.fetch = async (input, init) => {
+ calls += 1;
+ assert(String(input).startsWith("https://database.example.com/rest/v1/fixture"));
+ assert(new Headers(init.headers).get("carbon-key") === "fixture-local-override");
+ return new Response('[{"id":"fixture"}]', {
+ status: 200,
+ headers: { "content-type": "application/json" }
+ });
+};
+const client = createScriptClient(config.SUPABASE_URL, config.SUPABASE_ANON_KEY, config.CARBON_API_KEY);
+const result = await client.from("fixture").select("*");
+assert.equal(result.error, null);
+assert.equal(result.data[0].id, "fixture");
+assert.equal(calls, 1);`
+ ],
+ { cwd: directory, env: {}, encoding: "utf8", timeout: 15_000 }
+ );
+ assert(
+ result.status === 0,
+ "Real environment parsing, pinned SDK resolution, and stubbed request must succeed"
+ );
+ } finally {
+ rmSync(directory, { recursive: true, force: true });
+ }
+});
diff --git a/scripts/lib/local-script-config.ts b/scripts/lib/local-script-config.ts
new file mode 100644
index 0000000000..67456452e5
--- /dev/null
+++ b/scripts/lib/local-script-config.ts
@@ -0,0 +1,59 @@
+import { existsSync, readFileSync } from "node:fs";
+import { createRequire } from "node:module";
+import { parseEnv } from "node:util";
+
+// Values from .env.local override the caller's environment (it is the file
+// `pnpm dev:up` writes); plain .env only fills in what is not already set.
+export function loadDotEnv(): void {
+ for (const file of [".env", ".env.local"]) {
+ if (!existsSync(file)) continue;
+ for (const [key, value] of Object.entries(
+ parseEnv(readFileSync(file, "utf8"))
+ )) {
+ if (file === ".env.local" || process.env[key] === undefined)
+ process.env[key] = value;
+ }
+ }
+}
+
+export function readLocalScriptConfig<const Keys extends readonly string[]>(
+ names: Keys,
+ environment: Record<string, string | undefined>
+): { [Key in Keys[number]]: string } {
+ const local = existsSync(".env")
+ ? parseEnv(readFileSync(".env", "utf8"))
+ : {};
+ const localOverride = existsSync(".env.local")
+ ? parseEnv(readFileSync(".env.local", "utf8"))
+ : {};
+ const values = Object.fromEntries(
+ names.map((name) => [
+ name,
+ localOverride[name] ?? environment[name] ?? local[name]
+ ])
+ );
+ const missing = names.filter((name) => !values[name]?.trim());
+ if (missing.length) {
+ throw new Error(
+ `Missing required local configuration: ${missing.join(", ")}. Set these values in your local environment or ignored .env file.`
+ );
+ }
+ return values as {
+ [Key in Keys[number]]: string;
+ };
+}
+
+export function createScriptClient(
+ url: string,
+ publicKey: string,
+ apiKey: string
+) {
+ // The database workspace declares and pins this dependency; root scripts do not.
+ const fromDatabase = createRequire(
+ new URL("../../packages/database/package.json", import.meta.url)
+ );
+ const { createClient } = fromDatabase("@supabase/supabase-js");
+ return createClient(url, publicKey, {
+ global: { headers: { "carbon-key": apiKey } }
+ });
+}
diff --git a/scripts/lib/swagger-schema.test.ts b/scripts/lib/swagger-schema.test.ts
new file mode 100644
index 0000000000..6e62df10ba
--- /dev/null
+++ b/scripts/lib/swagger-schema.test.ts
@@ -0,0 +1,149 @@
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import {
+ copyFileSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ rmSync,
+ writeFileSync
+} from "node:fs";
+import { createServer } from "node:http";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { test } from "node:test";
+import { fileURLToPath } from "node:url";
+import { normalizeSwaggerSchema } from "./swagger-schema";
+
+const pk = "This is a Primary Key.<pk/>";
+const fk =
+ "This is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>";
+const fixture = (chosen: "id" | "supplierLocationId") => ({
+ swagger: "2.0",
+ definitions: {
+ partners: {
+ properties: {
+ id: {
+ type: "string",
+ format: "text",
+ description: `Original id documentation.\n\nNote:\n${chosen === "id" ? `${pk}\n` : ""}${fk}`
+ },
+ supplierLocationId: {
+ type: "string",
+ format: "text",
+ description: `Alias documentation.\n\nNote:\n${chosen === "supplierLocationId" ? `${pk}\n` : ""}${fk}`
+ }
+ }
+ },
+ unrelated: { properties: { id: { description: `Leave untouched: ${pk}` } } }
+ },
+ paths: { "/partners": { get: { description: "Public API contract" } } }
+});
+
+test("both observed alias choices normalize to identical metadata", () => {
+ assert.deepEqual(
+ normalizeSwaggerSchema(fixture("supplierLocationId")),
+ fixture("id")
+ );
+ assert.deepEqual(normalizeSwaggerSchema(fixture("id")), fixture("id"));
+});
+
+test("keeps the alias note when id has no Note anchor to receive it", () => {
+ const input = fixture("supplierLocationId");
+ input.definitions.partners.properties.id.description = "No note block here.";
+ assert.deepEqual(normalizeSwaggerSchema(input), input);
+});
+
+test("normalization is idempotent and leaves the input object intact", () => {
+ const input = fixture("supplierLocationId");
+ const saved = structuredClone(input);
+ const first = normalizeSwaggerSchema(input);
+ assert.deepEqual(first, normalizeSwaggerSchema(first));
+ assert.deepEqual(input, saved);
+});
+
+async function runCli(options: { failStatus?: number; repeat?: boolean } = {}) {
+ const root = fileURLToPath(new URL("../../", import.meta.url));
+ const directory = mkdtempSync(join(tmpdir(), "carbon-swagger-generation-"));
+ const output = join(directory, "packages/database/src/swagger-docs-schema.ts");
+ const previous = "export default { previous: true };\n";
+ let generations = 0;
+ const server = createServer((request, response) => {
+ response.setHeader("Content-Type", "application/json");
+ if (options.failStatus) {
+ response.statusCode = options.failStatus;
+ response.end(JSON.stringify({ error: "synthetic-private-diagnostic" }));
+ return;
+ }
+ response.end(
+ JSON.stringify(
+ fixture(generations++ % 2 === 0 ? "supplierLocationId" : "id")
+ )
+ );
+ });
+ try {
+ await new Promise<void>((resolve) =>
+ server.listen(0, "127.0.0.1", resolve)
+ );
+ const address = server.address();
+ assert.ok(address && typeof address !== "string");
+ mkdirSync(dirname(output), { recursive: true });
+ writeFileSync(output, previous);
+ mkdirSync(join(directory, "scripts/lib"), { recursive: true });
+ for (const path of [
+ "scripts/generate-swagger-docs.ts",
+ "scripts/lib/swagger-schema.ts",
+ "scripts/lib/local-script-config.ts"
+ ])
+ copyFileSync(join(root, path), join(directory, path));
+ const results = [];
+ for (let iteration = 0; iteration < (options.repeat ? 2 : 1); iteration++) {
+ const child = spawn(
+ process.execPath,
+ [
+ "--import",
+ join(root, "node_modules/tsx/dist/loader.mjs"),
+ join(directory, "scripts/generate-swagger-docs.ts")
+ ],
+ {
+ cwd: directory,
+ env: {
+ PATH: process.env.PATH,
+ PORT_STUDIO: String(address.port),
+ NODE_PATH: undefined
+ },
+ stdio: ["ignore", "pipe", "pipe"]
+ }
+ );
+ let stderr = "";
+ child.stderr.on("data", (chunk) => {
+ stderr += chunk;
+ });
+ const code = await new Promise<number | null>((resolve, reject) => {
+ child.once("error", reject);
+ child.once("close", resolve);
+ });
+ results.push({ code, stderr, output: readFileSync(output, "utf8") });
+ }
+ return { results, previous, remaining: readdirSync(dirname(output)) };
+ } finally {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ rmSync(directory, { recursive: true, force: true });
+ }
+}
+
+test("real CLI produces identical files for both observed alias variants", async () => {
+ const result = await runCli({ repeat: true });
+ for (const run of result.results) assert.equal(run.code, 0, run.stderr);
+ assert.equal(result.results[0]!.output, result.results[1]!.output);
+ assert.deepEqual(result.remaining, ["swagger-docs-schema.ts"]);
+});
+
+test("real CLI preserves last-good output when the request fails", async () => {
+ const result = await runCli({ failStatus: 500 });
+ assert.notEqual(result.results[0]!.code, 0);
+ assert.equal(result.results[0]!.output, result.previous);
+ assert.deepEqual(result.remaining, ["swagger-docs-schema.ts"]);
+ assert.doesNotMatch(result.results[0]!.stderr, /synthetic/);
+});
diff --git a/scripts/lib/swagger-schema.ts b/scripts/lib/swagger-schema.ts
new file mode 100644
index 0000000000..4c322dd07f
--- /dev/null
+++ b/scripts/lib/swagger-schema.ts
@@ -0,0 +1,35 @@
+const PRIMARY_KEY_NOTE = "This is a Primary Key.<pk/>";
+
+// The `partners` view projects `partner.id` twice (as `id` and as
+// `supplierLocationId`), and PostgREST annotates the source primary key on
+// whichever alias it encounters first — which differs between databases built
+// from the same migrations. Pin the `<pk/>` note to `id` so the committed
+// schema is a pure function of the migrations. When neither or both aliases
+// carry the note there is nothing nondeterministic to fix, so leave the
+// document untouched.
+export function normalizeSwaggerSchema(schema: unknown): unknown {
+ const result = structuredClone(schema) as {
+ definitions?: {
+ partners?: {
+ properties?: Record<string, { description?: unknown }>;
+ };
+ };
+ };
+ const properties = result?.definitions?.partners?.properties;
+ const id = properties?.id;
+ const alias = properties?.supplierLocationId;
+ if (
+ typeof id?.description === "string" &&
+ typeof alias?.description === "string" &&
+ alias.description.includes(PRIMARY_KEY_NOTE) &&
+ !id.description.includes(PRIMARY_KEY_NOTE) &&
+ id.description.includes("Note:\n")
+ ) {
+ alias.description = alias.description.replace(`${PRIMARY_KEY_NOTE}\n`, "");
+ id.description = id.description.replace(
+ "Note:\n",
+ `Note:\n${PRIMARY_KEY_NOTE}\n`
+ );
+ }
+ return result;
+}
diff --git a/scripts/model-upload.ts b/scripts/model-upload.ts
index c21d1bfafe..c208c8141a 100644
--- a/scripts/model-upload.ts
+++ b/scripts/model-upload.ts
@@ -1,50 +1,58 @@
-import { createClient } from "@supabase/supabase-js";
-import axios from "axios";
-import crypto from "crypto";
-import fs from "fs";
-import path from "path";
+import { randomUUID } from "node:crypto";
+import fs from "node:fs";
+import { homedir } from "node:os";
+import path from "node:path";
+import {
+ createScriptClient,
+ readLocalScriptConfig
+} from "./lib/local-script-config";
-const companyId = "N4Mk6kWM4ycK5Qj941axi4";
-const apiKey = "crbn_JLN5eYtzfoIzdkncQo3uO";
-const carbonApiUrl = "http://localhost:54321"; // https://api.carbon.ms
-const carbonPublicKey =
- "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0";
-
-const apiUrl = "http://localhost:3000/api/model/upload"; // https://app.carbon.ms/api/model/upload
-
-const filePath = "~/Downloads/test.stl";
+const {
+ CARBON_COMPANY_ID: companyId,
+ CARBON_API_KEY: apiKey,
+ SUPABASE_URL: carbonApiUrl,
+ SUPABASE_ANON_KEY: carbonPublicKey,
+ MODEL_UPLOAD_URL: apiUrl,
+ MODEL_FILE_PATH: filePath
+} = readLocalScriptConfig(
+ [
+ "CARBON_COMPANY_ID",
+ "CARBON_API_KEY",
+ "SUPABASE_URL",
+ "SUPABASE_ANON_KEY",
+ "MODEL_UPLOAD_URL",
+ "MODEL_FILE_PATH"
+ ],
+ process.env
+);
(async () => {
- const resolvedPath = filePath.replace("~", process.env.HOME!);
+ const resolvedPath = filePath.startsWith("~/")
+ ? path.join(homedir(), filePath.slice(2))
+ : filePath;
const fileName = path.basename(resolvedPath);
const fileExtension = path.extname(resolvedPath).slice(1);
const fileBuffer = fs.readFileSync(resolvedPath);
const fileSize = fs.statSync(resolvedPath).size;
- const modelId = crypto.randomUUID();
+ const modelId = randomUUID();
const modelPath = `${companyId}/models/${modelId}.${fileExtension}`;
// 1. Upload the file to Supabase storage
- const client = createClient(carbonApiUrl, carbonPublicKey, {
- global: {
- headers: {
- "carbon-key": apiKey,
- },
- },
- });
+ const client = createScriptClient(carbonApiUrl, carbonPublicKey, apiKey);
const { error: uploadError } = await client.storage
.from("private")
.upload(modelPath, fileBuffer, {
- contentType: "application/octet-stream",
+ contentType: "application/octet-stream"
});
if (uploadError) {
- console.error("Storage upload failed:", uploadError);
+ process.stderr.write("Storage upload failed.\n");
process.exit(1);
}
- console.log("File uploaded to storage:", modelPath);
+ process.stdout.write(`File uploaded to storage: ${modelPath}\n`);
// 2. POST the metadata to the API
const formData = new FormData();
@@ -53,15 +61,17 @@ const filePath = "~/Downloads/test.stl";
formData.append("modelPath", modelPath);
formData.append("size", String(fileSize));
- const response = await axios.post(
- "http://localhost:3000/api/model/upload",
- formData,
- {
- headers: {
- "carbon-key": apiKey,
- },
+ const response = await fetch(apiUrl, {
+ method: "POST",
+ body: formData,
+ headers: {
+ "carbon-key": apiKey
}
- );
+ });
- console.log(response.data);
-})();
+ if (!response.ok) throw new Error("Model metadata request failed");
+ process.stdout.write(`${await response.text()}\n`);
+})().catch(() => {
+ process.stderr.write("Model upload failed.\n");
+ process.exitCode = 1;
+});
diff --git a/scripts/sales-invoice-report.ts b/scripts/sales-invoice-report.ts
index 41db52117a..1d01a6211b 100644
--- a/scripts/sales-invoice-report.ts
+++ b/scripts/sales-invoice-report.ts
@@ -1,17 +1,27 @@
-import { createClient } from "@supabase/supabase-js";
-import fs from "fs";
-const companyId = "********************";
-const apiKey = "crbn_******************";
-const publicApiKey =
- "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InNxb2ppamlpamtuaGJneW9nbWx1Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MjM2MDU0MzksImV4cCI6MjAzOTE4MTQzOX0.JMzLs9Y4Y4kQ-jhQHrSqgNyHSZgrkwzBd1PwPbVPtbQ";
+import fs from "node:fs";
+import {
+ createScriptClient,
+ readLocalScriptConfig
+} from "./lib/local-script-config";
-const carbon = createClient("https://api.carbon.ms", publicApiKey, {
- global: {
- headers: {
- "carbon-key": apiKey,
- },
- },
-});
+const {
+ CARBON_COMPANY_ID: companyId,
+ CARBON_API_KEY: apiKey,
+ SUPABASE_URL: carbonApiUrl,
+ SUPABASE_ANON_KEY: publicApiKey,
+ SALES_INVOICE_REPORT_PATH: outputPath
+} = readLocalScriptConfig(
+ [
+ "CARBON_COMPANY_ID",
+ "CARBON_API_KEY",
+ "SUPABASE_URL",
+ "SUPABASE_ANON_KEY",
+ "SALES_INVOICE_REPORT_PATH"
+ ],
+ process.env
+);
+
+const carbon = createScriptClient(carbonApiUrl, publicApiKey, apiKey);
(async () => {
const { data, error } = await carbon
@@ -24,13 +34,14 @@ const carbon = createClient("https://api.carbon.ms", publicApiKey, {
.order("createdAt", { ascending: false });
if (data) {
- fs.writeFileSync(
- "sales-invoice-report.json",
- JSON.stringify(data, null, 2)
- );
+ fs.writeFileSync(outputPath, JSON.stringify(data, null, 2));
}
if (error) {
- console.error(error);
+ process.stderr.write("Sales invoice query failed.\n");
+ process.exitCode = 1;
}
-})();
+})().catch(() => {
+ process.stderr.write("Sales invoice report failed.\n");
+ process.exitCode = 1;
+});
diff --git a/scripts/sandbox.ts b/scripts/sandbox.ts
index d33c4a3e2b..2fa8639045 100644
--- a/scripts/sandbox.ts
+++ b/scripts/sandbox.ts
@@ -1,22 +1,22 @@
-import { createClient } from "@supabase/supabase-js";
-import { config } from "dotenv";
+import {
+ createScriptClient,
+ readLocalScriptConfig
+} from "./lib/local-script-config";
-config();
+const { SUPABASE_URL, SUPABASE_ANON_KEY, CARBON_API_KEY } =
+ readLocalScriptConfig(
+ ["SUPABASE_URL", "SUPABASE_ANON_KEY", "CARBON_API_KEY"],
+ process.env
+ );
-const carbon = createClient(
- process.env.SUPABASE_URL!,
- process.env.SUPABASE_ANON_KEY!,
- {
- global: {
- headers: {
- "carbon-key": "crbn_yPkz1hszqh6mVLDf4jiDv",
- },
- },
- }
+const carbon = createScriptClient(
+ SUPABASE_URL,
+ SUPABASE_ANON_KEY,
+ CARBON_API_KEY
);
(async () => {
const employees = await carbon.from("salesOrder").select("*").limit(1000);
- console.log(employees);
+ process.stdout.write(`${JSON.stringify(employees, null, 2)}\n`);
})();
diff --git a/turbo.json b/turbo.json
index c77b11745a..bff389fbe9 100644
--- a/turbo.json
+++ b/turbo.json
@@ -72,6 +72,7 @@
"outputs": []
},
"//#generate:mcp": {
+ "cache": false,
"inputs": [
"apps/erp/app/modules/*/*.service.ts",
"apps/erp/app/modules/*/*.mcp.server.ts",