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.

refactor(edge-functions): centralize HTTP response construction into lib/response.ts (#1293)

Side3464d23db07
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 05a653b871..87e89d698a 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -100190,7 +100190,7 @@ export default {
properties: {
id: {
description:
- "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
format: "text",
type: "string"
},
@@ -100239,7 +100239,7 @@ export default {
},
supplierLocationId: {
description:
- "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
+ "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
format: "text",
type: "string"
},
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 37aee90f86..4df16bf76e 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -69811,14 +69811,14 @@ export type Database = {
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -70365,14 +70365,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
diff --git a/packages/database/supabase/functions/close-job/index.ts b/packages/database/supabase/functions/close-job/index.ts
index f22a660c2f..ab30f33ce2 100644
--- a/packages/database/supabase/functions/close-job/index.ts
+++ b/packages/database/supabase/functions/close-job/index.ts
@@ -3,7 +3,7 @@ import { format } from "https://deno.land/[email protected]/datetime/mod.ts";
import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";
import z from "npm:zod@^3.24.1";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { requirePermissions } from "../lib/supabase.ts";
import { credit, debit, journalReference } from "../lib/utils.ts";
import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";
@@ -20,9 +20,8 @@ const payloadValidator = z.object({
});
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
const payload = await req.json();
const today = format(new Date(), "yyyy-MM-dd");
@@ -48,9 +47,7 @@ serve(async (req: Request) => {
const accountingEnabled = accountingSettings.data?.accountingEnabled ?? false;
if (!accountingEnabled) {
- return new Response(JSON.stringify({ success: true }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- });
+ return jsonResponse({ success: true });
}
if (companyRecord.error) throw new Error("Failed to fetch company");
@@ -226,14 +223,8 @@ serve(async (req: Request) => {
}
});
- return new Response(JSON.stringify({ success: true }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- });
+ return jsonResponse({ success: true });
} catch (err) {
- console.error(err);
- return new Response(JSON.stringify({ error: (err as Error).message }), {
- status: 500,
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- });
+ return errorResponse(err, 500);
}
});
diff --git a/packages/database/supabase/functions/convert/index.ts b/packages/database/supabase/functions/convert/index.ts
index c23b831dad..ca74324376 100644
--- a/packages/database/supabase/functions/convert/index.ts
+++ b/packages/database/supabase/functions/convert/index.ts
@@ -9,7 +9,7 @@ import { z } from "npm:zod@^3.24.1";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import { format } from "https://deno.land/[email protected]/datetime/format.ts";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { requirePermissions } from "../lib/supabase.ts";
import { Database } from "../lib/types.ts";
import { getNextSequence } from "../shared/get-next-sequence.ts";
@@ -131,9 +131,8 @@ const payloadValidator = z.discriminatedUnion("type", [
]);
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
const payload = await req.json();
let convertedId = "";
try {
@@ -441,14 +440,11 @@ serve(async (req: Request) => {
.execute();
});
- return new Response(
- JSON.stringify({
- id: purchaseInvoiceId,
- }),
+ return jsonResponse(
{
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 201,
- }
+ id: purchaseInvoiceId,
+ },
+ 201
);
}
case "quoteToSalesOrder": {
@@ -943,14 +939,11 @@ serve(async (req: Request) => {
}
});
- return new Response(
- JSON.stringify({
- id: salesInvoiceId,
- }),
+ return jsonResponse(
{
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 201,
- }
+ id: salesInvoiceId,
+ },
+ 201
);
}
case "salesRfqToQuote": {
@@ -1536,14 +1529,11 @@ serve(async (req: Request) => {
}
});
- return new Response(
- JSON.stringify({
- id: salesInvoiceId,
- }),
+ return jsonResponse(
{
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 201,
- }
+ id: salesInvoiceId,
+ },
+ 201
);
}
case "supplierQuoteToPurchaseOrder": {
@@ -2034,28 +2024,10 @@ serve(async (req: Request) => {
throw new Error(`Invalid type ${type}`);
}
- return new Response(
- JSON.stringify({
- convertedId,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
+ return jsonResponse({
+ convertedId,
+ });
} catch (err) {
- console.error(err);
- // JSON.stringify(err) → "{}" for Errors (non-enumerable properties); use .message
- // duck-typing. Omit key when empty so the caller's fallback string wins.
- const message = (err as { message?: unknown })?.message;
- return new Response(
- JSON.stringify(
- typeof message === "string" && message !== "" ? { message } : {}
- ),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- }
- );
+ return errorResponse(err, 500);
}
});
diff --git a/packages/database/supabase/functions/correct-stock-movement/index.ts b/packages/database/supabase/functions/correct-stock-movement/index.ts
index e4a21e6397..b634d9cca8 100644
--- a/packages/database/supabase/functions/correct-stock-movement/index.ts
+++ b/packages/database/supabase/functions/correct-stock-movement/index.ts
@@ -1,7 +1,7 @@
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { z } from "https://deno.land/x/[email protected]/mod.ts";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { getFunctionLogger } from "../lib/logging.ts";
import { requirePermissions } from "../lib/supabase.ts";
import { getAccountingPeriodForDate } from "../shared/get-accounting-period.ts";
@@ -38,9 +38,8 @@ class ValidationError extends Error {}
const MAX_CORRECTION_CHAIN_DEPTH = 100;
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
try {
const payload = await req.json();
@@ -332,24 +331,15 @@ serve(async (req: Request) => {
resultLedgerId = booked.itemLedgerId;
});
- return new Response(
- JSON.stringify({
- success: true,
- itemLedger: resultLedgerId ? { id: resultLedgerId } : null,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
+ return jsonResponse({
+ success: true,
+ itemLedger: resultLedgerId ? { id: resultLedgerId } : null,
+ });
} catch (err) {
logger.error("correct-stock-movement failed", {
error: String((err as Error).stack ?? err),
});
const isValidationError = err instanceof ValidationError;
- return new Response(JSON.stringify({ message: (err as Error).message }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: isValidationError ? 400 : 500,
- });
+ return errorResponse(err, isValidationError ? 400 : 500);
}
});
diff --git a/packages/database/supabase/functions/create/index.ts b/packages/database/supabase/functions/create/index.ts
index 87334b7e2d..a55990cad2 100644
--- a/packages/database/supabase/functions/create/index.ts
+++ b/packages/database/supabase/functions/create/index.ts
@@ -3,7 +3,7 @@ import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import z from "npm:zod@^3.24.1";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { requirePermissions } from "../lib/supabase.ts";
import { Database } from "../lib/types.ts";
import { getNextSequence } from "../shared/get-next-sequence.ts";
@@ -114,9 +114,9 @@ const payloadValidator = z.discriminatedUnion("type", [
}),
]);
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
+ try {
const payload = await req.json();
const { type, companyId, userId } = payloadValidator.parse(payload);
@@ -379,21 +379,9 @@ serve(async (req: Request) => {
}
});
} catch (error) {
- console.error(error);
- return new Response(error.message, {
- status: 500,
- headers: corsHeaders,
- });
+ return errorResponse(error, 500);
}
- return new Response(
- JSON.stringify({
- success: true,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
+ return jsonResponse({ success: true });
}
case "purchaseOrderFromJob": {
@@ -707,26 +695,10 @@ serve(async (req: Request) => {
});
}
} catch (err) {
- console.error(err);
- const message = (err as { message?: unknown })?.message;
- return new Response(
- JSON.stringify(typeof message === "string" && message !== "" ? { message } : {}),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- }
- );
+ return errorResponse(err, 500);
}
- return new Response(
- JSON.stringify({
- success: true,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
+ return jsonResponse({ success: true });
}
case "receiptDefault": {
const { locationId } = payload;
@@ -756,25 +728,9 @@ serve(async (req: Request) => {
if (!createdDocumentId) throw new Error("Failed to create receipt");
});
- return new Response(
- JSON.stringify({
- id: createdDocumentId,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 201,
- }
- );
+ return jsonResponse({ id: createdDocumentId }, 201);
} catch (err) {
- console.error(err);
- const message = (err as { message?: unknown })?.message;
- return new Response(
- JSON.stringify(typeof message === "string" && message !== "" ? { message } : {}),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- }
- );
+ return errorResponse(err, 500);
}
}
case "receiptFromPurchaseOrder": {
@@ -1038,25 +994,9 @@ serve(async (req: Request) => {
}
});
- return new Response(
- JSON.stringify({
- id: receiptId,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 201,
- }
- );
+ return jsonResponse({ id: receiptId }, 201);
} catch (err) {
- console.error(err);
- const message = (err as { message?: unknown })?.message;
- return new Response(
- JSON.stringify(typeof message === "string" && message !== "" ? { message } : {}),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- }
- );
+ return errorResponse(err, 500);
}
}
case "receiptFromInboundTransfer": {
@@ -1221,20 +1161,9 @@ serve(async (req: Request) => {
return { id };
});
- return new Response(JSON.stringify(result, null, 2), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 201,
- });
+ return jsonResponse(result, 201);
} catch (err) {
- console.error(err);
- const message = (err as { message?: unknown })?.message;
- return new Response(
- JSON.stringify(typeof message === "string" && message !== "" ? { message } : {}),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- }
- );
+ return errorResponse(err, 500);
}
}
case "receiptFromWarehouseTransfer": {
@@ -1406,19 +1335,9 @@ serve(async (req: Request) => {
return { id };
});
- return new Response(JSON.stringify(result), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- });
+ return jsonResponse(result);
} catch (err) {
- console.error(err);
- const message = (err as { message?: unknown })?.message;
- return new Response(
- JSON.stringify(typeof message === "string" && message !== "" ? { message } : {}),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- }
- );
+ return errorResponse(err, 500);
}
}
case "receiptLineSplit": {
@@ -1539,25 +1458,9 @@ serve(async (req: Request) => {
}
});
- return new Response(
- JSON.stringify({
- id: receiptLineId,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 201,
- }
- );
+ return jsonResponse({ id: receiptLineId }, 201);
} catch (err) {
- console.error(err);
- const message = (err as { message?: unknown })?.message;
- return new Response(
- JSON.stringify(typeof message === "string" && message !== "" ? { message } : {}),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- }
- );
+ return errorResponse(err, 500);
}
}
case "shipmentDefault": {
@@ -1589,25 +1492,9 @@ serve(async (req: Request) => {
if (!createdDocumentId) throw new Error("Failed to create shipment");
});
- return new Response(
- JSON.stringify({
- id: createdDocumentId,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 201,
- }
- );
+ return jsonResponse({ id: createdDocumentId }, 201);
} catch (err) {
- console.error(err);
- const message = (err as { message?: unknown })?.message;
- return new Response(
- JSON.stringify(typeof message === "string" && message !== "" ? { message } : {}),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- }
- );
+ return errorResponse(err, 500);
}
}
case "shipmentFromWarehouseTransfer": {
@@ -1770,20 +1657,9 @@ serve(async (req: Request) => {
return { id };
});
- return new Response(JSON.stringify(result, null, 2), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 201,
- });
+ return jsonResponse(result, 201);
} catch (err) {
- console.error(err);
- const message = (err as { message?: unknown })?.message;
- return new Response(
- JSON.stringify(typeof message === "string" && message !== "" ? { message } : {}),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- }
- );
+ return errorResponse(err, 500);
}
}
case "shipmentFromPurchaseOrder": {
@@ -1975,25 +1851,9 @@ serve(async (req: Request) => {
}
});
- return new Response(
- JSON.stringify({
- id: shipmentId,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 201,
- }
- );
+ return jsonResponse({ id: shipmentId }, 201);
} catch (err) {
- console.error(err);
- const message = (err as { message?: unknown })?.message;
- return new Response(
- JSON.stringify(typeof message === "string" && message !== "" ? { message } : {}),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- }
- );
+ return errorResponse(err, 500);
}
}
case "shipmentFromSalesOrder": {
@@ -2339,25 +2199,9 @@ serve(async (req: Request) => {
}
});
- return new Response(
- JSON.stringify({
- id: shipmentId,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 201,
- }
- );
+ return jsonResponse({ id: shipmentId }, 201);
} catch (err) {
- console.error(err);
- const message = (err as { message?: unknown })?.message;
- return new Response(
- JSON.stringify(typeof message === "string" && message !== "" ? { message } : {}),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- }
- );
+ return errorResponse(err, 500);
}
}
case "shipmentFromSalesOrderLine": {
@@ -2616,25 +2460,9 @@ serve(async (req: Request) => {
}
});
- return new Response(
- JSON.stringify({
- id: shipmentId,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 201,
- }
- );
+ return jsonResponse({ id: shipmentId }, 201);
} catch (err) {
- console.error(err);
- const message = (err as { message?: unknown })?.message;
- return new Response(
- JSON.stringify(typeof message === "string" && message !== "" ? { message } : {}),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- }
- );
+ return errorResponse(err, 500);
}
}
case "shipmentLineSplit": {
@@ -2689,25 +2517,9 @@ serve(async (req: Request) => {
.execute();
});
- return new Response(
- JSON.stringify({
- id: shipmentLineId,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 201,
- }
- );
+ return jsonResponse({ id: shipmentLineId }, 201);
} catch (err) {
- console.error(err);
- const message = (err as { message?: unknown })?.message;
- return new Response(
- JSON.stringify(typeof message === "string" && message !== "" ? { message } : {}),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- }
- );
+ return errorResponse(err, 500);
}
}
case "journalEntry": {
@@ -2738,32 +2550,17 @@ serve(async (req: Request) => {
throw new Error("Failed to create journal entry");
});
- return new Response(
- JSON.stringify({
- id: createdDocumentId,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 201,
- }
- );
+ return jsonResponse({ id: createdDocumentId }, 201);
} catch (err) {
- console.error(err);
- const message = (err as { message?: unknown })?.message;
- return new Response(
- JSON.stringify(typeof message === "string" && message !== "" ? { message } : {}),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- }
- );
+ return errorResponse(err, 500);
}
}
default:
- return new Response(JSON.stringify({ error: "Invalid document type" }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 400,
- });
+ return errorResponse("Invalid document type", 400);
+ }
+ } catch (err) {
+ if (err instanceof z.ZodError) return errorResponse("Invalid payload", 400);
+ return errorResponse(err, 500);
}
});
diff --git a/packages/database/supabase/functions/deno.json b/packages/database/supabase/functions/deno.json
index 52263be0e0..18c5494fca 100644
--- a/packages/database/supabase/functions/deno.json
+++ b/packages/database/supabase/functions/deno.json
@@ -1,5 +1,9 @@
{
"lock": false,
+ "tasks": {
+ "test": "deno test --no-lock",
+ "check:response": "deno check --no-lock lib/response.ts lib/response.test.ts"
+ },
"imports": {
"kysely": "npm:[email protected]",
"pg": "https://deno.land/x/[email protected]/mod.ts",
diff --git a/packages/database/supabase/functions/download/index.ts b/packages/database/supabase/functions/download/index.ts
index 382decf686..eb9ba518fc 100644
--- a/packages/database/supabase/functions/download/index.ts
+++ b/packages/database/supabase/functions/download/index.ts
@@ -1,7 +1,7 @@
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { z } from "npm:zod@^3.24.1";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { requirePermissions } from "../lib/supabase.ts";
const downloadValidator = z.object({
@@ -12,9 +12,8 @@ const downloadValidator = z.object({
});
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
const payload = await req.json();
try {
@@ -37,33 +36,14 @@ serve(async (req: Request) => {
.createSignedUrl(path, 60);
if (signedUrl.error) {
- return new Response(
- JSON.stringify({
- success: false,
- error: signedUrl.error.message,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 404,
- }
- );
+ return errorResponse(signedUrl.error, 404);
}
- return new Response(
- JSON.stringify({
- success: true,
- signedUrl: signedUrl.data?.signedUrl,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
- } catch (err) {
- console.error(err);
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
+ return jsonResponse({
+ success: true,
+ signedUrl: signedUrl.data?.signedUrl,
});
+ } catch (err) {
+ return errorResponse(err, 500);
}
});
diff --git a/packages/database/supabase/functions/embedding/index.ts b/packages/database/supabase/functions/embedding/index.ts
index 8f9e81f599..71275ace50 100644
--- a/packages/database/supabase/functions/embedding/index.ts
+++ b/packages/database/supabase/functions/embedding/index.ts
@@ -5,38 +5,25 @@
// Setup type definitions for built-in Supabase Runtime APIs
import "jsr:@supabase/functions-js/edge-runtime.d.ts";
import { generateEmbedding } from "../lib/ai/embedding.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
Deno.serve(async (req) => {
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
+
try {
const { text } = await req.json();
if (!text || typeof text !== "string") {
- return new Response(
- JSON.stringify({ error: "Text parameter is required and must be a string" }),
- {
- status: 400,
- headers: { "Content-Type": "application/json" }
- }
- );
+ return errorResponse("Text parameter is required and must be a string", 400);
}
const embedding = await generateEmbedding(text);
- return new Response(
- JSON.stringify({ embedding }),
- { headers: { "Content-Type": "application/json" } }
- );
+ return jsonResponse({ embedding });
} catch (error) {
console.error("Error generating embedding:", error);
- return new Response(
- JSON.stringify({
- error: error instanceof Error ? error.message : "Failed to generate embedding"
- }),
- {
- status: 500,
- headers: { "Content-Type": "application/json" }
- }
- );
+ return errorResponse(error, 500);
}
})
diff --git a/packages/database/supabase/functions/event-wake/index.ts b/packages/database/supabase/functions/event-wake/index.ts
index 9a04625e16..0558dfd654 100644
--- a/packages/database/supabase/functions/event-wake/index.ts
+++ b/packages/database/supabase/functions/event-wake/index.ts
@@ -1,6 +1,6 @@
import { serve } from "https://deno.land/[email protected]/http/server.ts";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { sendInngestEvent } from "../lib/inngest.ts";
import { getFunctionLogger } from "../lib/logging.ts";
@@ -13,24 +13,17 @@ const logger = getFunctionLogger("event-wake");
* the queue itself is the source of truth; this is only a doorbell.
*/
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
try {
await sendInngestEvent("carbon/event-queue.process", {});
- return new Response(JSON.stringify({ success: true }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- });
+ return jsonResponse({ success: true });
} catch (err) {
// A failed wake is harmless: the pg_cron sweeper re-fires while the
// queue is non-empty.
logger.error("Error in event-wake", { error: (err as Error).message });
- return new Response(JSON.stringify({ error: (err as Error).message }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ return errorResponse(err, 500);
}
});
diff --git a/packages/database/supabase/functions/export-company/index.ts b/packages/database/supabase/functions/export-company/index.ts
index ca56737ea2..c6eb1b97a1 100644
--- a/packages/database/supabase/functions/export-company/index.ts
+++ b/packages/database/supabase/functions/export-company/index.ts
@@ -1,6 +1,5 @@
import { serve } from "https://deno.land/[email protected]/http/server.ts";
-import { errorResponse, jsonResponse } from "../lib/company-backup.ts";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { sendInngestEvent } from "../lib/inngest.ts";
import { requirePermissions } from "../lib/supabase.ts";
@@ -11,9 +10,8 @@ import { requirePermissions } from "../lib/supabase.ts";
* bucket under `exports/`.
*/
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
try {
const { companyId, userId, label, includeStorage } = await req.json();
@@ -35,8 +33,8 @@ serve(async (req: Request) => {
includeStorage: includeStorage ?? "none"
});
- return jsonResponse({ success: true }, 202, corsHeaders);
+ return jsonResponse({ success: true }, 202);
} catch (err) {
- return errorResponse(err, 400, corsHeaders);
+ return errorResponse(err, 400);
}
});
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index b974f7fe5c..2e3eb39ebc 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -17,7 +17,7 @@ import {
now,
toCalendarDate,
} from "npm:@internationalized/date";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import {
calculateQuoteLinePrices,
getJobMethodTree,
@@ -153,9 +153,8 @@ const payloadValidator = z.object({
});
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
const payload = await req.json();
try {
@@ -6046,16 +6045,10 @@ serve(async (req: Request) => {
}
});
if (newQuoteId) {
- return new Response(
- JSON.stringify({
- success: true,
- newQuoteId,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
+ return jsonResponse({
+ success: true,
+ newQuoteId,
+ });
}
break;
}
@@ -6063,21 +6056,11 @@ serve(async (req: Request) => {
throw new Error(`Invalid type ${type}`);
}
- return new Response(
- JSON.stringify({
- success: true,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
- } catch (err) {
- console.error(err);
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
+ return jsonResponse({
+ success: true,
});
+ } catch (err) {
+ return errorResponse(err, 500);
}
});
diff --git a/packages/database/supabase/functions/image-resizer/index.ts b/packages/database/supabase/functions/image-resizer/index.ts
index 4e055f097d..85b9be9843 100644
--- a/packages/database/supabase/functions/image-resizer/index.ts
+++ b/packages/database/supabase/functions/image-resizer/index.ts
@@ -17,6 +17,7 @@ const wasmBytes = await Deno.readFile(
await initializeImageMagick(wasmBytes);
import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse } from "../lib/response.ts";
// Maximum dimensions to process without aggressive downscaling
const MAX_SAFE_DIMENSION = 2000;
@@ -24,9 +25,8 @@ const MAX_SAFE_DIMENSION = 2000;
const MAX_ALLOWED_DIMENSION = 5000;
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
try {
console.log({
@@ -365,9 +365,6 @@ serve(async (req: Request) => {
});
} catch (err) {
console.error("Image processing error:", err);
- return new Response(JSON.stringify({ error: err.message }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ return errorResponse(err, 500);
}
});
diff --git a/packages/database/supabase/functions/import-csv/index.ts b/packages/database/supabase/functions/import-csv/index.ts
index 760ba75eda..4944abdfa2 100644
--- a/packages/database/supabase/functions/import-csv/index.ts
+++ b/packages/database/supabase/functions/import-csv/index.ts
@@ -4,7 +4,7 @@ import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";
import { sql } from "npm:[email protected]";
import z from "npm:zod@^3.24.1";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { requirePermissions } from "../lib/supabase.ts";
import { Database } from "../lib/types.ts";
import { getReadableIdWithRevision } from "../lib/utils.ts";
@@ -821,9 +821,8 @@ async function upsertTaxIdentifiers(
}
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
const payload = await req.json();
try {
@@ -2314,25 +2313,15 @@ serve(async (req: Request) => {
const withValues = (issues: Array<{ row: number; reason: string }>) =>
issues.map((issue) => ({ ...issue, values: parsedCsv[issue.row] ?? {} }));
- return new Response(
- JSON.stringify({
- success: true,
- inserted: summary.inserted,
- updated: summary.updated,
- errors: withValues(summary.errors),
- skipped: withValues(summary.skipped),
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
- } catch (err) {
- console.error(err);
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
+ return jsonResponse({
+ success: true,
+ inserted: summary.inserted,
+ updated: summary.updated,
+ errors: withValues(summary.errors),
+ skipped: withValues(summary.skipped),
});
+ } catch (err) {
+ return errorResponse(err, 500);
}
});
diff --git a/packages/database/supabase/functions/issue/index.ts b/packages/database/supabase/functions/issue/index.ts
index 051c0547e6..725b1979bd 100644
--- a/packages/database/supabase/functions/issue/index.ts
+++ b/packages/database/supabase/functions/issue/index.ts
@@ -6,7 +6,7 @@ import { z } from "npm:zod@^3.24.1";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import { nanoid } from "https://deno.land/x/[email protected]/nanoid.ts";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import {
getStorageUnitWithHighestQuantity,
updatePickMethodDefaultStorageUnitIfNeeded,
@@ -936,9 +936,8 @@ const payloadValidator = z.discriminatedUnion("type", [
]);
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
const payload = await req.json();
console.log({ payload });
@@ -1145,15 +1144,9 @@ serve(async (req: Request) => {
});
});
- return new Response(
- JSON.stringify({
- success: true,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
+ return jsonResponse({
+ success: true,
+ });
}
case "jobOperationSerialComplete": {
const { trackedEntityId, companyId, userId, ...row } = validatedPayload;
@@ -1322,16 +1315,10 @@ serve(async (req: Request) => {
});
});
- return new Response(
- JSON.stringify({
- success: true,
- newTrackedEntityId: newEntityId,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
+ return jsonResponse({
+ success: true,
+ newTrackedEntityId: newEntityId,
+ });
}
case "partToOperation": {
const {
@@ -1815,15 +1802,9 @@ serve(async (req: Request) => {
.execute();
});
- return new Response(
- JSON.stringify({
- success: true,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
+ return jsonResponse({
+ success: true,
+ });
}
case "trackedEntitiesToOperation": {
const {
@@ -2443,17 +2424,11 @@ serve(async (req: Request) => {
return splitEntities;
});
- return new Response(
- JSON.stringify({
- success: true,
- splitEntities,
- warning: expiredWarning,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
+ return jsonResponse({
+ success: true,
+ splitEntities,
+ warning: expiredWarning,
+ });
}
case "unconsumeTrackedEntities": {
const {
@@ -2962,17 +2937,11 @@ serve(async (req: Request) => {
};
});
- return new Response(
- JSON.stringify({
- success: true,
- message: "Entity converted successfully",
- convertedEntity,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
+ return jsonResponse({
+ success: true,
+ message: "Entity converted successfully",
+ convertedEntity,
+ });
}
case "maintenanceDispatchInventory": {
const {
@@ -3056,16 +3025,10 @@ serve(async (req: Request) => {
}
});
- return new Response(
- JSON.stringify({
- success: true,
- message: "Material issued successfully",
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
+ return jsonResponse({
+ success: true,
+ message: "Material issued successfully",
+ });
}
case "maintenanceDispatchTrackedEntities": {
const {
@@ -3449,18 +3412,12 @@ serve(async (req: Request) => {
return splitEntities;
});
- return new Response(
- JSON.stringify({
- success: true,
- message: "Material issued successfully",
- splitEntities,
- warning: expiredWarning,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
+ return jsonResponse({
+ success: true,
+ message: "Material issued successfully",
+ splitEntities,
+ warning: expiredWarning,
+ });
}
case "maintenanceDispatchUnconsume": {
const { maintenanceDispatchItemId, children, companyId, userId } =
@@ -3651,16 +3608,10 @@ serve(async (req: Request) => {
.execute();
});
- return new Response(
- JSON.stringify({
- success: true,
- message: "Material unconsumed successfully",
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
+ return jsonResponse({
+ success: true,
+ message: "Material unconsumed successfully",
+ });
}
case "maintenanceDispatchUnissue": {
const { maintenanceDispatchItemId, companyId, userId } =
@@ -3848,47 +3799,18 @@ serve(async (req: Request) => {
.execute();
});
- return new Response(
- JSON.stringify({
- success: true,
- message: "Item unissued and removed successfully",
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
+ return jsonResponse({
+ success: true,
+ message: "Item unissued and removed successfully",
+ });
}
}
- return new Response(
- JSON.stringify({
- success: true,
- message: "x",
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
+ return jsonResponse({
+ success: true,
+ message: "x",
+ });
} catch (err) {
- console.error(err);
- // Error.prototype properties (message, name, stack) aren't enumerable,
- // so a plain JSON.stringify(err) produces "{}" and clients lose the
- // actual reason (e.g. "Cannot consume expired tracked entity ...").
- // Pull the message out explicitly.
- const message =
- err instanceof Error
- ? err.message
- : typeof err === "string"
- ? err
- : "Unexpected error";
- return new Response(
- JSON.stringify({ success: false, message }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 400,
- }
- );
+ return errorResponse(err, 400);
}
});
diff --git a/packages/database/supabase/functions/lib/company-backup.ts b/packages/database/supabase/functions/lib/company-backup.ts
index 20c9ab3b6f..cd67962a0e 100644
--- a/packages/database/supabase/functions/lib/company-backup.ts
+++ b/packages/database/supabase/functions/lib/company-backup.ts
@@ -14,24 +14,3 @@ export function getUserIdFromRequest(req: Request): string | null {
return null;
}
}
-
-export function jsonResponse(
- body: Record<string, unknown>,
- status: number,
- corsHeaders: Record<string, string>
-): Response {
- return new Response(JSON.stringify(body), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status
- });
-}
-
-export function errorResponse(
- err: unknown,
- status: number,
- corsHeaders: Record<string, string>
-): Response {
- const message = err instanceof Error ? err.message : String(err);
- console.error(message);
- return jsonResponse({ success: false, message }, status, corsHeaders);
-}
diff --git a/packages/database/supabase/functions/lib/response.test.ts b/packages/database/supabase/functions/lib/response.test.ts
new file mode 100644
index 0000000000..a59b378c34
--- /dev/null
+++ b/packages/database/supabase/functions/lib/response.test.ts
@@ -0,0 +1,146 @@
+import {
+ assert,
+ assertEquals,
+} from "https://deno.land/[email protected]/testing/asserts.ts";
+import { PostgresError } from "pg";
+import {
+ corsPreflight,
+ errorResponse,
+ isDataLayerError,
+ jsonResponse,
+} from "./response.ts";
+
+// This suite asserts on real `Response` objects — `Response` is a Deno built-in and
+// needs no permissions. The contract under test: error bodies carry the reason under
+// `message` (and nothing else), the key is omitted when there is no usable message, and
+// data-layer errors are structurally classified and sanitized without text-matching.
+
+Deno.test("corsPreflight returns null for non-OPTIONS methods", () => {
+ assertEquals(corsPreflight(new Request("http://x", { method: "POST" })), null);
+ assertEquals(corsPreflight(new Request("http://x", { method: "GET" })), null);
+});
+
+Deno.test("corsPreflight handles OPTIONS with CORS and no JSON content-type", async () => {
+ const res = corsPreflight(new Request("http://x", { method: "OPTIONS" }));
+ assert(res !== null);
+ assertEquals(res.status, 200);
+ assertEquals(await res.text(), "ok");
+ assertEquals(res.headers.get("Access-Control-Allow-Origin"), "*");
+ assert(res.headers.get("Content-Type") !== "application/json");
+});
+
+Deno.test("jsonResponse defaults to 200 with CORS + JSON content-type", async () => {
+ const res = jsonResponse({ success: true });
+ assertEquals(res.status, 200);
+ assertEquals(res.headers.get("Content-Type"), "application/json");
+ assertEquals(res.headers.get("Access-Control-Allow-Origin"), "*");
+ assertEquals(await res.json(), { success: true });
+});
+
+Deno.test("jsonResponse honors explicit status", () => {
+ assertEquals(jsonResponse({ id: "x" }, 201).status, 201);
+});
+
+Deno.test("errorResponse defaults to 500 and surfaces Error.message", async () => {
+ const res = errorResponse(new Error("boom"));
+ assertEquals(res.status, 500);
+ assertEquals(await res.json(), { message: "boom" });
+});
+
+Deno.test("errorResponse accepts a raw string literal", async () => {
+ const res = errorResponse("Invalid operation type", 400);
+ assertEquals(res.status, 400);
+ assertEquals(await res.json(), { message: "Invalid operation type" });
+});
+
+Deno.test("errorResponse duck-types { message }", async () => {
+ assertEquals(await errorResponse({ message: "duck" }).json(), {
+ message: "duck",
+ });
+});
+
+Deno.test("errorResponse omits message when there is none", async () => {
+ for (const input of [new Error(""), null, undefined, 42, {}]) {
+ const body = await errorResponse(input).json();
+ assertEquals(body, {});
+ assert(!("message" in body));
+ }
+});
+
+Deno.test("original-bug guard: Error serializes to {} but errorResponse recovers message", async () => {
+ assertEquals(JSON.stringify(new Error("boom")), "{}");
+ assertEquals(await errorResponse(new Error("boom")).json(), { message: "boom" });
+});
+
+Deno.test("errorResponse merges defined extras", async () => {
+ const res = errorResponse(new Error("bad"), 400, { invalidLineIds: ["a", "b"] });
+ assertEquals(res.status, 400);
+ assertEquals(await res.json(), { message: "bad", invalidLineIds: ["a", "b"] });
+});
+
+Deno.test("errorResponse drops undefined extras", async () => {
+ const body = await errorResponse(new Error("bad"), 500, {
+ invalidLineIds: undefined,
+ }).json();
+ assertEquals(body, { message: "bad" });
+ assert(!("invalidLineIds" in body));
+});
+
+Deno.test("contract lock: error bodies contain no error or success key", async () => {
+ const body = await errorResponse(new Error("boom")).json();
+ assert(!("error" in body));
+ assert(!("success" in body));
+});
+
+Deno.test("sanitizer suppresses PostgresError (imported class)", async () => {
+ const err = new PostgresError({
+ severity: "ERROR",
+ code: "23505",
+ message: 'duplicate key value violates unique constraint "receiptLine_pkey"',
+ // deno-lint-ignore no-explicit-any
+ } as any);
+ assert(isDataLayerError(err));
+ assertEquals(await errorResponse(err).json(), {});
+});
+
+Deno.test("sanitizer suppresses Postgrest-shaped error", async () => {
+ const err = {
+ code: "23505",
+ details: "Key (id)=(x) already exists.",
+ hint: null,
+ message: 'duplicate key value violates unique constraint "receiptLine_pkey"',
+ };
+ assert(isDataLayerError(err));
+ assertEquals(await errorResponse(err).json(), {});
+});
+
+Deno.test("sanitizer suppresses node-pg-shaped error", async () => {
+ const err = { code: "23505", severity: "ERROR", message: "boom" };
+ assert(isDataLayerError(err));
+ assertEquals(await errorResponse(err).json(), {});
+});
+
+Deno.test("sanitizer suppresses ZodError", async () => {
+ const err = Object.assign(new Error("[{...}]"), {
+ name: "ZodError",
+ issues: [{ path: [], message: "x" }],
+ });
+ assert(isDataLayerError(err));
+ assertEquals(await errorResponse(err).json(), {});
+});
+
+Deno.test("sanitizer does not overreach: authored Error with DB-looking text is surfaced", async () => {
+ const err = new Error(
+ 'duplicate key value violates unique constraint "x"'
+ );
+ assert(!isDataLayerError(err));
+ assertEquals(await errorResponse(err).json(), {
+ message: 'duplicate key value violates unique constraint "x"',
+ });
+});
+
+Deno.test("isDataLayerError returns false for non-data-layer values", () => {
+ for (const input of ["a string", null, undefined, 42, {}, new Error("x")]) {
+ assertEquals(isDataLayerError(input), false);
+ }
+});
diff --git a/packages/database/supabase/functions/lib/response.ts b/packages/database/supabase/functions/lib/response.ts
new file mode 100644
index 0000000000..93f7d80440
--- /dev/null
+++ b/packages/database/supabase/functions/lib/response.ts
@@ -0,0 +1,116 @@
+import { PostgresError } from "pg";
+import { corsHeaders } from "./headers.ts";
+
+/**
+ * Shared HTTP response construction for Supabase edge functions.
+ *
+ * ERROR BODY CONTRACT — the apps read `body.message` and nothing else. See
+ * `apps/erp/app/utils/error.ts`. `supabase-js` wraps non-2xx responses in a
+ * `FunctionsHttpError` whose own `.message` is the useless fixed string
+ * "Edge Function returned a non-2xx status code", so the real reason has to
+ * travel in the body under `message`. Do not add `error` or `success: false`
+ * to error bodies — no consumer reads them.
+ */
+
+/** `corsHeaders` plus the JSON content type. For responses this module can't build (binary bodies). */
+export const jsonHeaders = {
+ ...corsHeaders,
+ "Content-Type": "application/json",
+};
+
+/**
+ * Handles the CORS preflight. Returns `null` for every other method:
+ *
+ * const preflight = corsPreflight(req);
+ * if (preflight) return preflight;
+ */
+export function corsPreflight(req: Request): Response | null {
+ if (req.method !== "OPTIONS") return null;
+ return new Response("ok", { headers: corsHeaders });
+}
+
+/** JSON response with CORS headers. `status` defaults to 200 — pass it only when it is not 200. */
+export function jsonResponse(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), { headers: jsonHeaders, status });
+}
+
+/**
+ * True when `err` came from the data layer rather than from our own `throw`.
+ *
+ * Classification is STRUCTURAL — an `instanceof` against a real imported class, or the
+ * presence of a documented set of keys. It never inspects message TEXT, so it cannot
+ * misfire on an authored message that happens to mention a table or a constraint.
+ *
+ * Unknown shapes return `false` (treated as authored, message surfaced). That is
+ * deliberate: the ~541 `throw new Error("...")` sites in this directory are the dominant
+ * case, and defaulting to "surface" preserves their behavior exactly.
+ */
+export function isDataLayerError(err: unknown): boolean {
+ // 1. deno.land/x/postgres — thrown by the Kysely pool via lib/driver.ts.
+ // Real imported class, so this is an exact check with no duck-typing.
+ if (err instanceof PostgresError) return true;
+
+ if (err === null || typeof err !== "object") return false;
+ const e = err as Record<string, unknown>;
+
+ // 2. supabase-js PostgrestError, rethrown directly by e.g. convert/index.ts:1056-1059,
+ // mrp/index.ts:95. Its documented shape is exactly these four keys.
+ if (
+ typeof e.code === "string" &&
+ "details" in e &&
+ "hint" in e &&
+ "message" in e
+ ) {
+ return true;
+ }
+
+ // 3. node-postgres-shaped errors (SQLSTATE + protocol fields on the error itself).
+ if (typeof e.code === "string" && typeof e.severity === "string") return true;
+
+ // 4. ZodError — `.message` is a multi-line JSON dump of `issues`, never user-facing.
+ if (e.name === "ZodError" && Array.isArray(e.issues)) return true;
+
+ return false;
+}
+
+/**
+ * JSON error response built from a thrown value.
+ *
+ * - Duck-types `.message` (so `Error` and any `{ message }` object work) and accepts a
+ * raw `string` for call-site literals.
+ * - SANITIZES: when `isDataLayerError(err)`, the message is dropped from the body and only
+ * logged. Raw text like `duplicate key value violates unique constraint "receiptLine_pkey"`
+ * must never reach a toast. The caller's fallback string wins instead.
+ * - OMITS the `message` key entirely when there is no usable message. Load-bearing —
+ * `getEdgeFunctionErrorMessage(err, fallback)` falls back to the caller's own copy.
+ * - `console.error`s the ORIGINAL value (not the extracted string) so the stack and the
+ * sanitized detail both survive into the Supabase log drain.
+ * - `extra` merges additional top-level keys — currently only `invalidLineIds` from
+ * `post-inventory-count`. `undefined` values are dropped so callers can pass optionals
+ * without conditional spreads.
+ */
+export function errorResponse(
+ err: unknown,
+ status = 500,
+ extra?: Record<string, unknown>
+): Response {
+ console.error(err);
+
+ const raw =
+ typeof err === "string"
+ ? err
+ : (err as { message?: unknown } | null | undefined)?.message;
+
+ const body: Record<string, unknown> = {};
+ if (typeof raw === "string" && raw !== "" && !isDataLayerError(err)) {
+ body.message = raw;
+ }
+
+ if (extra) {
+ for (const [key, value] of Object.entries(extra)) {
+ if (value !== undefined) body[key] = value;
+ }
+ }
+
+ return jsonResponse(body, status);
+}
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 37aee90f86..4df16bf76e 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -69811,14 +69811,14 @@ export type Database = {
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -70365,14 +70365,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
diff --git a/packages/database/supabase/functions/logo-resizer/index.ts b/packages/database/supabase/functions/logo-resizer/index.ts
index cab2247d43..0145b8225e 100644
--- a/packages/database/supabase/functions/logo-resizer/index.ts
+++ b/packages/database/supabase/functions/logo-resizer/index.ts
@@ -9,7 +9,7 @@ import {
Percentage,
} from "npm:@imagemagick/[email protected]";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
const wasmBytes = await Deno.readFile(
new URL(
@@ -46,9 +46,8 @@ function rgbaToGFA(rgba: Uint8Array, w: number, h: number, thresh = 128): string
}
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
try {
const formData = await req.formData();
@@ -119,14 +118,8 @@ serve(async (req: Request) => {
});
});
- return new Response(
- JSON.stringify({ monoPng, gfa, widthDots: outW, heightDots: outH }),
- { headers: { ...corsHeaders, "Content-Type": "application/json" } }
- );
+ return jsonResponse({ monoPng, gfa, widthDots: outW, heightDots: outH });
} catch (err) {
- return new Response(JSON.stringify({ error: (err as Error).message }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ return errorResponse(err, 500);
}
});
diff --git a/packages/database/supabase/functions/mrp/index.ts b/packages/database/supabase/functions/mrp/index.ts
index 48a75dbe05..1d8a05a167 100644
--- a/packages/database/supabase/functions/mrp/index.ts
+++ b/packages/database/supabase/functions/mrp/index.ts
@@ -18,7 +18,7 @@ import {
import { Kysely, sql } from "npm:kysely";
import z from "npm:zod@^3.24.1";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { requirePermissions } from "../lib/supabase.ts";
import { Database } from "../lib/types.ts";
import { buildSupersessionRedirectMap } from "../lib/supersession-pick.ts";
@@ -72,9 +72,8 @@ const payloadValidator = z.discriminatedUnion("type", [
]);
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
const payload = await req.json();
const parsedPayload = payloadValidator.parse(payload);
@@ -865,23 +864,12 @@ serve(async (req: Request) => {
.execute();
}
- return new Response(JSON.stringify({ success: true }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 201,
- });
+ return jsonResponse({ success: true }, 201);
} catch (err) {
- console.error(err);
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ return errorResponse(err, 500);
}
} catch (err) {
- console.error(err);
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ return errorResponse(err, 500);
}
});
diff --git a/packages/database/supabase/functions/pick/index.ts b/packages/database/supabase/functions/pick/index.ts
index e5f6c4a6ed..bbb71e1037 100644
--- a/packages/database/supabase/functions/pick/index.ts
+++ b/packages/database/supabase/functions/pick/index.ts
@@ -4,7 +4,7 @@ import { z } from "npm:zod@^3.24.1";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import { requirePermissions } from "../lib/supabase.ts";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse } from "../lib/response.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -39,9 +39,8 @@ const payloadValidator = z.discriminatedUnion("type", [
]);
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
const payload = await req.json();
try {
@@ -62,24 +61,10 @@ serve(async (req: Request) => {
case "executePick":
case "completeStockTransfer":
default:
- return new Response(
- JSON.stringify({ error: "Invalid operation type" }),
- {
- status: 400,
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- }
- );
+ return errorResponse("Invalid operation type", 400);
}
} catch (error) {
console.error("Error in pick:", error);
- return new Response(
- JSON.stringify({
- error: error instanceof Error ? error.message : "Unknown error",
- }),
- {
- status: 500,
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- }
- );
+ return errorResponse(error, 500);
}
});
diff --git a/packages/database/supabase/functions/post-inventory-adjustment/index.ts b/packages/database/supabase/functions/post-inventory-adjustment/index.ts
index 28087da4a5..eb250df732 100644
--- a/packages/database/supabase/functions/post-inventory-adjustment/index.ts
+++ b/packages/database/supabase/functions/post-inventory-adjustment/index.ts
@@ -3,7 +3,7 @@ import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { z } from "https://deno.land/x/[email protected]/mod.ts";
import { Transaction } from "kysely";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { getFunctionLogger } from "../lib/logging.ts";
import { requirePermissions } from "../lib/supabase.ts";
import type { Json } from "../lib/types.ts";
@@ -47,9 +47,8 @@ const payloadValidator = z.object({
class ValidationError extends Error {}
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
try {
const payload = await req.json();
@@ -563,27 +562,15 @@ serve(async (req: Request) => {
resultLedgerId = booked.itemLedgerId;
});
- return new Response(
- JSON.stringify({
- success: true,
- itemLedger: resultLedgerId ? { id: resultLedgerId } : null,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
+ return jsonResponse({
+ success: true,
+ itemLedger: resultLedgerId ? { id: resultLedgerId } : null,
+ });
} catch (err) {
logger.error("post-inventory-adjustment failed", {
error: String((err as Error).stack ?? err),
});
const isValidationError = err instanceof ValidationError;
- return new Response(
- JSON.stringify({ message: (err as Error).message }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: isValidationError ? 400 : 500,
- }
- );
+ return errorResponse(err, isValidationError ? 400 : 500);
}
});
diff --git a/packages/database/supabase/functions/post-inventory-count/index.ts b/packages/database/supabase/functions/post-inventory-count/index.ts
index 904ec2ee65..336bdcfd01 100644
--- a/packages/database/supabase/functions/post-inventory-count/index.ts
+++ b/packages/database/supabase/functions/post-inventory-count/index.ts
@@ -2,7 +2,7 @@ import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { format } from "https://deno.land/[email protected]/datetime/mod.ts";
import { z } from "https://deno.land/x/[email protected]/mod.ts";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { getFunctionLogger } from "../lib/logging.ts";
import { requirePermissions } from "../lib/supabase.ts";
import type { Database } from "../lib/types.ts";
@@ -60,9 +60,8 @@ const payloadValidator = z.object({
});
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
const payload = await req.json();
@@ -350,9 +349,7 @@ serve(async (req: Request) => {
}
});
- return new Response(JSON.stringify({ success: true }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" }
- });
+ return jsonResponse({ success: true });
} catch (err) {
logger.error("post-inventory-count failed", {
error: String((err as Error).stack ?? err)
@@ -372,15 +369,6 @@ serve(async (req: Request) => {
// real outages surface in monitoring instead of hiding as a 400.
const isValidationError = err instanceof InvalidLinesError;
const invalidLineIds = isValidationError ? err.lineIds : undefined;
- return new Response(
- JSON.stringify({
- message: (err as Error).message,
- ...(invalidLineIds ? { invalidLineIds } : {})
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: isValidationError ? 400 : 500
- }
- );
+ return errorResponse(err, isValidationError ? 400 : 500, { invalidLineIds });
}
});
diff --git a/packages/database/supabase/functions/post-memo/index.ts b/packages/database/supabase/functions/post-memo/index.ts
index 790e6ad98c..1db76f1165 100644
--- a/packages/database/supabase/functions/post-memo/index.ts
+++ b/packages/database/supabase/functions/post-memo/index.ts
@@ -3,7 +3,7 @@ import { format } from "https://deno.land/[email protected]/datetime/mod.ts";
import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";
import z from "npm:zod@^3.24.1";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { getSupabaseServiceRole } from "../lib/supabase.ts";
import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";
@@ -22,9 +22,8 @@ const payloadValidator = z.object({
});
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
const payload = await req.json();
const today = format(new Date(), "yyyy-MM-dd");
@@ -194,9 +193,7 @@ serve(async (req: Request) => {
.execute();
});
- return new Response(JSON.stringify({ success: true }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- });
+ return jsonResponse({ success: true });
}
// --------------------------------------------------------------
@@ -428,21 +425,8 @@ serve(async (req: Request) => {
createdJournalId = journalId;
});
- return new Response(
- JSON.stringify({ success: true, journalId: createdJournalId }),
- { headers: { ...corsHeaders, "Content-Type": "application/json" } }
- );
+ return jsonResponse({ success: true, journalId: createdJournalId });
} catch (err) {
- console.error(err);
- return new Response(
- JSON.stringify({
- success: false,
- message: err instanceof Error ? err.message : String(err),
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- }
- );
+ return errorResponse(err, 500);
}
});
diff --git a/packages/database/supabase/functions/post-nonconformance/index.ts b/packages/database/supabase/functions/post-nonconformance/index.ts
index 7d1ebc294d..92850df900 100644
--- a/packages/database/supabase/functions/post-nonconformance/index.ts
+++ b/packages/database/supabase/functions/post-nonconformance/index.ts
@@ -2,7 +2,7 @@ import { format } from "https://deno.land/[email protected]/datetime/mod.ts";
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { z } from "https://deno.land/x/[email protected]/mod.ts";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { getFunctionLogger } from "../lib/logging.ts";
import { requirePermissions } from "../lib/supabase.ts";
import { Database } from "../lib/types.ts";
@@ -52,9 +52,8 @@ const payloadValidator = z.object({
});
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
try {
const payload = await req.json();
@@ -77,10 +76,7 @@ serve(async (req: Request) => {
// Only movements that actually move stock post anything.
const effectiveMovements = movements.filter((m) => m.quantity !== 0);
if (effectiveMovements.length === 0) {
- return new Response(JSON.stringify({ success: true, journalId: null }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- });
+ return jsonResponse({ success: true, journalId: null });
}
const itemIds = [...new Set(effectiveMovements.map((m) => m.itemId))];
@@ -283,17 +279,11 @@ serve(async (req: Request) => {
}
});
- return new Response(JSON.stringify({ success: true, journalId }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- });
+ return jsonResponse({ success: true, journalId });
} catch (err) {
logger.error("post-nonconformance failed", {
error: String((err as Error).stack ?? err),
});
- return new Response(JSON.stringify({ error: (err as Error).message }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ return errorResponse(err, 500);
}
});
diff --git a/packages/database/supabase/functions/post-payment/index.ts b/packages/database/supabase/functions/post-payment/index.ts
index d6b80164bc..8d05a5a668 100644
--- a/packages/database/supabase/functions/post-payment/index.ts
+++ b/packages/database/supabase/functions/post-payment/index.ts
@@ -3,7 +3,7 @@ import { format } from "https://deno.land/[email protected]/datetime/mod.ts";
import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";
import z from "npm:zod@^3.24.1";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { getSupabaseServiceRole } from "../lib/supabase.ts";
import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";
@@ -26,9 +26,8 @@ const payloadValidator = z.object({
});
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
const payload = await req.json();
const today = format(new Date(), "yyyy-MM-dd");
@@ -206,9 +205,7 @@ serve(async (req: Request) => {
.execute();
});
- return new Response(JSON.stringify({ success: true }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- });
+ return jsonResponse({ success: true });
}
// --------------------------------------------------------------
@@ -791,21 +788,8 @@ serve(async (req: Request) => {
createdJournalId = journalId;
});
- return new Response(
- JSON.stringify({ success: true, journalId: createdJournalId }),
- { headers: { ...corsHeaders, "Content-Type": "application/json" } }
- );
+ return jsonResponse({ success: true, journalId: createdJournalId });
} catch (err) {
- console.error(err);
- return new Response(
- JSON.stringify({
- success: false,
- message: err instanceof Error ? err.message : String(err),
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- }
- );
+ return errorResponse(err, 500);
}
});
diff --git a/packages/database/supabase/functions/post-picking/index.ts b/packages/database/supabase/functions/post-picking/index.ts
index a3cdf8ca93..f4f96ed08f 100644
--- a/packages/database/supabase/functions/post-picking/index.ts
+++ b/packages/database/supabase/functions/post-picking/index.ts
@@ -4,7 +4,7 @@ import { getLocalTimeZone, today as getToday } from "npm:@internationalized/date
import { nanoid } from "https://deno.land/x/[email protected]/nanoid.ts";
import { z } from "https://deno.land/x/[email protected]/mod.ts";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import type { Database } from "../lib/types.ts";
const pool = getConnectionPool(1);
@@ -92,9 +92,8 @@ const payloadValidator = z.discriminatedUnion("type", [
]);
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
const today = format(getToday(getLocalTimeZone()).toDate(getLocalTimeZone()), "yyyy-MM-dd");
@@ -906,22 +905,9 @@ serve(async (req: Request) => {
}
}
- return new Response(
- JSON.stringify({ success: true, splitEntityId }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200
- }
- );
+ return jsonResponse({ success: true, splitEntityId });
} catch (err) {
- console.error(err);
- return new Response(
- JSON.stringify({ success: false, message: (err as Error).message }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500
- }
- );
+ return errorResponse(err, 500);
}
});
diff --git a/packages/database/supabase/functions/post-production-event/index.ts b/packages/database/supabase/functions/post-production-event/index.ts
index b59cfc8d61..e8b2a0a355 100644
--- a/packages/database/supabase/functions/post-production-event/index.ts
+++ b/packages/database/supabase/functions/post-production-event/index.ts
@@ -3,7 +3,7 @@ import { format } from "https://deno.land/[email protected]/datetime/mod.ts";
import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";
import z from "npm:zod@^3.24.1";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { requirePermissions } from "../lib/supabase.ts";
import { credit, debit, journalReference } from "../lib/utils.ts";
@@ -24,9 +24,8 @@ const payloadValidator = z.object({
});
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
const payload = await req.json();
const today = format(new Date(), "yyyy-MM-dd");
@@ -53,9 +52,7 @@ serve(async (req: Request) => {
const accountingEnabled = accountingSettings.data?.accountingEnabled ?? false;
if (!accountingEnabled) {
- return new Response(JSON.stringify({ success: true }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- });
+ return jsonResponse({ success: true });
}
if (companyRecord.error) throw new Error("Failed to fetch company");
@@ -90,9 +87,7 @@ serve(async (req: Request) => {
if (reverse && !event.postedToGL) {
// Nothing was posted for this event, so there is nothing to reverse.
- return new Response(JSON.stringify({ success: true }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- });
+ return jsonResponse({ success: true });
}
if (!reverse && (!event.endTime || !event.duration || !event.workCenterId)) {
@@ -103,9 +98,9 @@ serve(async (req: Request) => {
: !event.duration
? "event has no duration"
: "event has no work center";
- return new Response(JSON.stringify({ success: false, reason }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- });
+ // FIXME: returns { success: false } at HTTP 200, so callers (error === null)
+ // read it as success. A real status (409/422?) needs its own decision — see §6c.
+ return jsonResponse({ success: false, reason });
}
const jobId = (event.jobOperation as any).jobId as string;
@@ -185,14 +180,13 @@ serve(async (req: Request) => {
// can't attribute/reverse. A zero-cost posted event posted nothing, so
// there's nothing to reverse and it's safe to delete.
if (event.postedToGL && reversalLines.length === 0 && hasOldSchemePostings) {
- return new Response(
- JSON.stringify({
- success: false,
- reason:
- "event was posted before per-event journal references; adjust with a manual journal entry",
- }),
- { headers: { ...corsHeaders, "Content-Type": "application/json" } }
- );
+ // FIXME: returns { success: false } at HTTP 200, so callers (error === null)
+ // read it as success. A real status (409/422?) needs its own decision — see §6c.
+ return jsonResponse({
+ success: false,
+ reason:
+ "event was posted before per-event journal references; adjust with a manual journal entry",
+ });
}
if (cost <= 0 && overheadCost <= 0 && reversalLines.length === 0) {
@@ -202,9 +196,7 @@ serve(async (req: Request) => {
.from("productionEvent")
.update({ postedToGL: !reverse })
.eq("id", productionEventId);
- return new Response(JSON.stringify({ success: true }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- });
+ return jsonResponse({ success: true });
}
const dimensionMap = new Map<string, string>();
@@ -426,14 +418,8 @@ serve(async (req: Request) => {
.execute();
});
- return new Response(JSON.stringify({ success: true }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- });
+ return jsonResponse({ success: true });
} catch (err) {
- console.error(err);
- return new Response(JSON.stringify({ error: (err as Error).message }), {
- status: 500,
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- });
+ return errorResponse(err, 500);
}
});
diff --git a/packages/database/supabase/functions/post-purchase-invoice/index.ts b/packages/database/supabase/functions/post-purchase-invoice/index.ts
index 2c00d94af2..607669d226 100644
--- a/packages/database/supabase/functions/post-purchase-invoice/index.ts
+++ b/packages/database/supabase/functions/post-purchase-invoice/index.ts
@@ -3,7 +3,7 @@ import { format } from "https://deno.land/[email protected]/datetime/mod.ts";
import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";
import z from "npm:zod@^3.24.1";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { requirePermissions } from "../lib/supabase.ts";
import type { Database } from "../lib/types.ts";
import { credit, debit, journalReference } from "../lib/utils.ts";
@@ -34,9 +34,8 @@ const payloadValidator = z.object({
});
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
const payload = await req.json();
const today = format(new Date(), "yyyy-MM-dd");
@@ -495,9 +494,7 @@ serve(async (req: Request) => {
.execute();
});
- return new Response(JSON.stringify({ success: true }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- });
+ return jsonResponse({ success: true });
}
const companyRecord = await client
@@ -2029,15 +2026,10 @@ serve(async (req: Request) => {
.execute();
});
- return new Response(
- JSON.stringify({
- success: true,
- receiptIds: createdReceiptIds,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- }
- );
+ return jsonResponse({
+ success: true,
+ receiptIds: createdReceiptIds,
+ });
} catch (err) {
console.error(err);
if (payload.type !== "void" && "invoiceId" in payload) {
@@ -2047,9 +2039,6 @@ serve(async (req: Request) => {
.update({ status: "Draft" })
.eq("id", payload.invoiceId);
}
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ return errorResponse(err, 500);
}
});
diff --git a/packages/database/supabase/functions/post-receipt/index.ts b/packages/database/supabase/functions/post-receipt/index.ts
index 564377af1e..7ede0244c6 100644
--- a/packages/database/supabase/functions/post-receipt/index.ts
+++ b/packages/database/supabase/functions/post-receipt/index.ts
@@ -3,7 +3,7 @@ import { format } from "https://deno.land/[email protected]/datetime/mod.ts";
import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";
import { z } from "https://deno.land/x/[email protected]/mod.ts";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { requirePermissions } from "../lib/supabase.ts";
import type { Database } from "../lib/types.ts";
import {
@@ -36,9 +36,8 @@ const payloadValidator = z.object({
});
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
const payload = await req.json();
const today = format(new Date(), "yyyy-MM-dd");
@@ -581,9 +580,7 @@ serve(async (req: Request) => {
.execute();
});
- return new Response(JSON.stringify({ success: true }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- });
+ return jsonResponse({ success: true });
}
if (receipt.data?.status === "Voided") {
@@ -2312,14 +2309,7 @@ serve(async (req: Request) => {
}
}
- return new Response(
- JSON.stringify({
- success: true,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- }
- );
+ return jsonResponse({ success: true });
} catch (err) {
console.error(err);
if (payload.type !== "void" && "receiptId" in payload) {
@@ -2329,9 +2319,6 @@ serve(async (req: Request) => {
.update({ status: "Draft" })
.eq("id", payload.receiptId);
}
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ return errorResponse(err, 500);
}
});
diff --git a/packages/database/supabase/functions/post-sales-invoice/index.ts b/packages/database/supabase/functions/post-sales-invoice/index.ts
index 7f8e6632f7..2dc662152a 100644
--- a/packages/database/supabase/functions/post-sales-invoice/index.ts
+++ b/packages/database/supabase/functions/post-sales-invoice/index.ts
@@ -3,7 +3,7 @@ import { format } from "https://deno.land/[email protected]/datetime/mod.ts";
import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";
import z from "npm:zod@^3.24.1";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { requirePermissions } from "../lib/supabase.ts";
import type { Database } from "../lib/types.ts";
@@ -27,9 +27,8 @@ const payloadValidator = z.object({
});
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
const payload = await req.json();
const today = format(new Date(), "yyyy-MM-dd");
@@ -1561,14 +1560,7 @@ serve(async (req: Request) => {
}
}
- return new Response(
- JSON.stringify({
- success: true,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- }
- );
+ return jsonResponse({ success: true });
} catch (err) {
console.error(err);
if ("invoiceId" in payload) {
@@ -1578,9 +1570,6 @@ serve(async (req: Request) => {
.update({ status: "Draft" })
.eq("id", payload.invoiceId);
}
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ return errorResponse(err, 500);
}
});
diff --git a/packages/database/supabase/functions/post-shipment/index.ts b/packages/database/supabase/functions/post-shipment/index.ts
index 4f65db9dd0..ea857187f5 100644
--- a/packages/database/supabase/functions/post-shipment/index.ts
+++ b/packages/database/supabase/functions/post-shipment/index.ts
@@ -3,7 +3,7 @@ import { format } from "https://deno.land/[email protected]/datetime/mod.ts";
import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";
import { z } from "https://deno.land/x/[email protected]/mod.ts";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { requirePermissions } from "../lib/supabase.ts";
import type { Database, Json } from "../lib/types.ts";
import { TrackedEntityAttributes, credit, debit, journalReference } from "../lib/utils.ts";
@@ -26,9 +26,8 @@ const payloadValidator = z.object({
});
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
const payload = await req.json();
const today = format(new Date(), "yyyy-MM-dd");
@@ -2887,15 +2886,10 @@ serve(async (req: Request) => {
}
}
- return new Response(
- JSON.stringify({
- success: true,
- splitEntityIds,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- }
- );
+ return jsonResponse({
+ success: true,
+ splitEntityIds,
+ });
} catch (err) {
console.error(err);
if ("shipmentId" in payload) {
@@ -2905,9 +2899,6 @@ serve(async (req: Request) => {
.update({ status: "Draft" })
.eq("id", payload.shipmentId);
}
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ return errorResponse(err, 500);
}
});
diff --git a/packages/database/supabase/functions/post-stock-transfer/index.ts b/packages/database/supabase/functions/post-stock-transfer/index.ts
index 2a8eaa4b89..c37a8328c1 100644
--- a/packages/database/supabase/functions/post-stock-transfer/index.ts
+++ b/packages/database/supabase/functions/post-stock-transfer/index.ts
@@ -4,7 +4,7 @@ import { getLocalTimeZone, parseDate, today } from "npm:@internationalized/date"
import { nanoid } from "https://deno.land/x/[email protected]/nanoid.ts";
import { z } from "https://deno.land/x/[email protected]/mod.ts";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import type { Database } from "../lib/types.ts";
const pool = getConnectionPool(1);
@@ -121,9 +121,8 @@ const payloadValidator = z.discriminatedUnion("type", [
]);
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
const payload = await req.json();
const today = format(new Date(), "yyyy-MM-dd");
@@ -1061,22 +1060,12 @@ serve(async (req: Request) => {
}
}
- return new Response(
- JSON.stringify({
- success: true,
- warning: expiredWarning,
- splitEntityId,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
- } catch (err) {
- console.error(err);
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
+ return jsonResponse({
+ success: true,
+ warning: expiredWarning,
+ splitEntityId,
});
+ } catch (err) {
+ return errorResponse(err, 500);
}
});
diff --git a/packages/database/supabase/functions/recalculate/index.ts b/packages/database/supabase/functions/recalculate/index.ts
index 29b8808a25..916bfd0de9 100644
--- a/packages/database/supabase/functions/recalculate/index.ts
+++ b/packages/database/supabase/functions/recalculate/index.ts
@@ -4,7 +4,7 @@ import { z } from "npm:zod@^3.24.1";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import { Transaction } from "kysely";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { getJobMethodTree, JobMethodTreeItem } from "../lib/methods.ts";
import { requirePermissions } from "../lib/supabase.ts";
@@ -19,9 +19,8 @@ const payloadValidator = z.object({
});
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
const payload = await req.json();
try {
@@ -63,10 +62,7 @@ serve(async (req: Request) => {
.eq("id", jobMakeMethod.data.parentMaterialId)
.single();
if (jobMaterial.data?.methodType !== "Make to Order") {
- return new Response(JSON.stringify({ success: true }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- });
+ return jsonResponse({ success: true });
}
if (jobMaterial.error) {
@@ -85,10 +81,7 @@ serve(async (req: Request) => {
console.log(
`Job material ${jobMakeMethod.data.parentMaterialId} is not a 'Make' type. Skipping recalculation.`
);
- return new Response(JSON.stringify({ success: true }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- });
+ return jsonResponse({ success: true });
}
parentQuantity =
@@ -178,21 +171,11 @@ serve(async (req: Request) => {
throw new Error(`Invalid type ${type}`);
}
- return new Response(
- JSON.stringify({
- success: true,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
- } catch (err) {
- console.error(err);
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
+ return jsonResponse({
+ success: true,
});
+ } catch (err) {
+ return errorResponse(err, 500);
}
});
diff --git a/packages/database/supabase/functions/reschedule/index.ts b/packages/database/supabase/functions/reschedule/index.ts
index bd5e542d87..59db4296ca 100644
--- a/packages/database/supabase/functions/reschedule/index.ts
+++ b/packages/database/supabase/functions/reschedule/index.ts
@@ -1,7 +1,7 @@
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import type { Transaction } from "kysely";
import { getConnectionPool, getDatabaseClient } from "../lib/database.ts";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import type { DB } from "../lib/types.ts";
const pool = getConnectionPool(1);
@@ -381,9 +381,8 @@ async function recalculatePriorities(
// Main handler
serve(async (req) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
try {
const { jobId, companyId, userId } = await req.json();
@@ -458,24 +457,13 @@ serve(async (req) => {
};
});
- return new Response(JSON.stringify({ success: true, ...result }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- });
+ return jsonResponse({ success: true, ...result });
} catch (error) {
console.error(
`❌ Reschedule failed: ${
error instanceof Error ? error.message : String(error)
}`
);
- return new Response(
- JSON.stringify({
- success: false,
- message: error instanceof Error ? error.message : String(error),
- }),
- {
- status: 500,
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- }
- );
+ return errorResponse(error, 500);
}
});
diff --git a/packages/database/supabase/functions/schedule/index.ts b/packages/database/supabase/functions/schedule/index.ts
index 433f7f40a3..551553d83b 100644
--- a/packages/database/supabase/functions/schedule/index.ts
+++ b/packages/database/supabase/functions/schedule/index.ts
@@ -2,7 +2,7 @@ import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { z } from "npm:zod@^3.24.1";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { SchedulingEngine } from "../lib/scheduling/scheduling-engine.ts";
import type {
SchedulingDirection,
@@ -22,9 +22,8 @@ const payloadValidator = z.object({
});
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
try {
const payload = await req.json();
@@ -56,30 +55,15 @@ serve(async (req: Request) => {
);
console.info(` Assembly depth: ${result.assemblyDepth}`);
- return new Response(
- JSON.stringify({
- ...result,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
+ return jsonResponse({
+ ...result,
+ });
} catch (error) {
console.error(
`❌ Scheduling failed: ${
error instanceof Error ? error.message : String(error)
}`
);
- return new Response(
- JSON.stringify({
- success: false,
- message: error instanceof Error ? error.message : String(error),
- }),
- {
- status: 500,
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- }
- );
+ return errorResponse(error, 500);
}
});
diff --git a/packages/database/supabase/functions/seed-company/index.ts b/packages/database/supabase/functions/seed-company/index.ts
index 6c8bd9bf74..808ce2e678 100644
--- a/packages/database/supabase/functions/seed-company/index.ts
+++ b/packages/database/supabase/functions/seed-company/index.ts
@@ -1,7 +1,7 @@
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import {
accountDefaults,
accounts,
@@ -31,9 +31,8 @@ const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
const { companyId: id, userId, parentCompanyId, identityOnly } =
await req.json();
@@ -77,13 +76,7 @@ serve(async (req: Request) => {
.eq("companyId", companyId);
if ((existingLink.count ?? 0) > 0) {
- return new Response(
- JSON.stringify({ success: true, alreadySeeded: true }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
+ return jsonResponse({ success: true, alreadySeeded: true });
}
// Determine if this is a new root company or joining an existing group
@@ -540,20 +533,8 @@ serve(async (req: Request) => {
}
});
- return new Response(
- JSON.stringify({
- success: true,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
+ return jsonResponse({ success: true });
} catch (err) {
- console.error(err);
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ return errorResponse(err, 500);
}
});
diff --git a/packages/database/supabase/functions/sync/index.ts b/packages/database/supabase/functions/sync/index.ts
index 33a5979c61..2c849dfcaf 100644
--- a/packages/database/supabase/functions/sync/index.ts
+++ b/packages/database/supabase/functions/sync/index.ts
@@ -3,7 +3,7 @@ import { Transaction } from "npm:kysely";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import z from "npm:zod@^3.24.1";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { requirePermissions } from "../lib/supabase.ts";
import { getReadableIdWithRevision } from "../lib/utils.ts";
@@ -165,9 +165,8 @@ async function copyMakeMethodOperations(
}
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
const payload = await req.json();
const { type, companyId, userId } = payloadValidator.parse(payload);
@@ -743,23 +742,13 @@ serve(async (req: Request) => {
}
});
} catch (err) {
- console.error(err);
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ return errorResponse(err, 500);
}
- return new Response(
- JSON.stringify({
- success: true,
- makeMethodId: activeMakeMethodId,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
+ return jsonResponse({
+ success: true,
+ makeMethodId: activeMakeMethodId,
+ });
}
}
});
diff --git a/packages/database/supabase/functions/textract/index.ts b/packages/database/supabase/functions/textract/index.ts
index 5afc31509d..f6c3c7a465 100644
--- a/packages/database/supabase/functions/textract/index.ts
+++ b/packages/database/supabase/functions/textract/index.ts
@@ -10,7 +10,7 @@ import {
} from "https://deno.land/x/[email protected]/client-textract/mod.ts";
import z from "npm:zod@^3.24.1";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { getSupabaseServiceRole } from "../lib/supabase.ts";
const AWS_REGION = Deno.env.get("AWS_REGION");
@@ -48,9 +48,8 @@ const payloadValidator = z.object({
});
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
const payload = await req.json();
@@ -114,21 +113,11 @@ serve(async (req: Request) => {
})
);
- return new Response(
- JSON.stringify({
- success: true,
- analysis: textractResponse,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
- } catch (err) {
- console.error(err);
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
+ return jsonResponse({
+ success: true,
+ analysis: textractResponse,
});
+ } catch (err) {
+ return errorResponse(err, 500);
}
});
diff --git a/packages/database/supabase/functions/thumbnail/index.ts b/packages/database/supabase/functions/thumbnail/index.ts
index f723741399..c486cf07d6 100644
--- a/packages/database/supabase/functions/thumbnail/index.ts
+++ b/packages/database/supabase/functions/thumbnail/index.ts
@@ -3,6 +3,7 @@ import puppeteer from "https://deno.land/x/[email protected]/mod.ts";
import { z } from "npm:zod@^3.24.1";
import { Buffer } from "node:buffer";
import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse } from "../lib/response.ts";
import {
ImageMagick,
@@ -30,9 +31,8 @@ const browserWSEndpoint =
`ws://5.161.255.30?token=59ecf910-aaa8-4c7e-aedb-7c18b34e266e`;
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
let browser;
try {
@@ -91,11 +91,7 @@ serve(async (req: Request) => {
status: 200,
});
} catch (err) {
- console.error(err);
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 400,
- });
+ return errorResponse(err, 400);
} finally {
if (browser) {
await browser.close();
diff --git a/packages/database/supabase/functions/transcription/index.ts b/packages/database/supabase/functions/transcription/index.ts
index 63de58d52c..d8dc07a3cf 100644
--- a/packages/database/supabase/functions/transcription/index.ts
+++ b/packages/database/supabase/functions/transcription/index.ts
@@ -4,6 +4,7 @@ import { experimental_transcribe as transcribe } from "npm:[email protected]";
import { z } from "npm:zod@^3.24.1";
import { openai } from "../lib/ai/openai.ts";
import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { getSupabase } from "../lib/supabase.ts";
import { Database } from "../lib/types.ts";
@@ -13,9 +14,8 @@ const transcriptionRequestSchema = z.object({
});
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
console.log({
function: "transcription",
@@ -94,30 +94,14 @@ serve(async (req: Request) => {
transcriptLength: result.text.length,
});
- return new Response(
- JSON.stringify({
- success: true,
- text: result.text,
- language: result.language,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
+ return jsonResponse({
+ success: true,
+ text: result.text,
+ language: result.language,
+ });
} catch (error) {
console.error("Transcription failed:", error);
- return new Response(
- JSON.stringify({
- success: false,
- error: "Failed to transcribe audio",
- message: error instanceof Error ? error.message : "Unknown error",
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- }
- );
+ return errorResponse(error, 500);
}
});
diff --git a/packages/database/supabase/functions/trigger-rework/index.ts b/packages/database/supabase/functions/trigger-rework/index.ts
index b1ac87091d..48b4cb665e 100644
--- a/packages/database/supabase/functions/trigger-rework/index.ts
+++ b/packages/database/supabase/functions/trigger-rework/index.ts
@@ -3,7 +3,7 @@ import type { Transaction } from "kysely";
import { nanoid } from "https://deno.land/x/[email protected]/nanoid.ts";
import z from "npm:zod@^3.24.1";
import { getConnectionPool, getDatabaseClient } from "../lib/database.ts";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import type { DB } from "../lib/types.ts";
const pool = getConnectionPool(1);
@@ -397,9 +397,8 @@ async function triggerRework(
// Main handler
serve(async (req) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
try {
const raw = await req.json();
@@ -418,15 +417,9 @@ serve(async (req) => {
.safeParse(raw);
if (!parsed.success) {
- return new Response(
- JSON.stringify({
- success: false,
- message: `Invalid request: ${parsed.error.issues.map((i) => i.message).join(", ")}`,
- }),
- {
- status: 400,
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- }
+ return errorResponse(
+ `Invalid request: ${parsed.error.issues.map((i) => i.message).join(", ")}`,
+ 400
);
}
@@ -460,24 +453,13 @@ serve(async (req) => {
console.error("Failed to trigger reschedule after rework:", err);
}
- return new Response(JSON.stringify({ success: true, ...result }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- });
+ return jsonResponse({ success: true, ...result });
} catch (error) {
console.error(
`❌ Rework failed: ${
error instanceof Error ? error.message : String(error)
}`
);
- return new Response(
- JSON.stringify({
- success: false,
- message: error instanceof Error ? error.message : String(error),
- }),
- {
- status: 500,
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- }
- );
+ return errorResponse(error, 500);
}
});
diff --git a/packages/database/supabase/functions/trigger/index.ts b/packages/database/supabase/functions/trigger/index.ts
index 053ca3c2e5..406c8429d3 100644
--- a/packages/database/supabase/functions/trigger/index.ts
+++ b/packages/database/supabase/functions/trigger/index.ts
@@ -1,7 +1,7 @@
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { z } from "npm:zod@^3.24.1";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { sendInngestEvent } from "../lib/inngest.ts";
const recipientValidator = z.discriminatedUnion("type", [
@@ -36,9 +36,8 @@ const payloadValidator = z.discriminatedUnion("type", [
]);
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
const payload = await req.json();
try {
@@ -67,20 +66,8 @@ serve(async (req: Request) => {
throw new Error(`Invalid type ${type}`);
}
- return new Response(
- JSON.stringify({
- success: true,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- },
- );
+ return jsonResponse({ success: true });
} catch (err) {
- console.error(err);
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ return errorResponse(err, 500);
}
});
diff --git a/packages/database/supabase/functions/update-purchased-prices/index.ts b/packages/database/supabase/functions/update-purchased-prices/index.ts
index b47b4e586c..970528aa81 100644
--- a/packages/database/supabase/functions/update-purchased-prices/index.ts
+++ b/packages/database/supabase/functions/update-purchased-prices/index.ts
@@ -4,7 +4,7 @@ import { format } from "https://deno.land/[email protected]/datetime/mod.ts";
import { sql } from "kysely";
import z from "npm:zod@^3.24.1";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { requirePermissions } from "../lib/supabase.ts";
import { Database } from "../lib/types.ts";
@@ -54,9 +54,8 @@ const calculateLeadTimeInDays = (
};
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
const payload = await req.json();
const parsedPayload = payloadValidator.parse(payload);
@@ -524,20 +523,10 @@ serve(async (req: Request) => {
}
});
- return new Response(
- JSON.stringify({
- success: true,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- }
- );
- } catch (err) {
- console.error(err);
-
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
+ return jsonResponse({
+ success: true,
});
+ } catch (err) {
+ return errorResponse(err, 500);
}
});
diff --git a/packages/database/supabase/functions/webhook/index.ts b/packages/database/supabase/functions/webhook/index.ts
index ac3dd9e1cc..473961eb8b 100644
--- a/packages/database/supabase/functions/webhook/index.ts
+++ b/packages/database/supabase/functions/webhook/index.ts
@@ -1,7 +1,7 @@
import { createClient } from "@supabase/supabase-js";
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { z } from "npm:zod@^3.24.1";
-import { corsHeaders } from "../lib/headers.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import type { Database } from "../lib/types.ts";
const payloadValidator = z.object({
@@ -15,9 +15,8 @@ const payloadValidator = z.object({
});
serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
const payload = await req.json();
const { type, record, old, url, companyId, table, webhookId } =
payloadValidator.parse(payload);
@@ -65,15 +64,7 @@ serve(async (req: Request) => {
webhook_id: webhookId,
});
- return new Response(
- JSON.stringify({
- success: true,
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200,
- }
- );
+ return jsonResponse({ success: true });
} catch (err) {
console.error(err);
if (webhookId) {
@@ -81,9 +72,6 @@ serve(async (req: Request) => {
webhook_id: webhookId,
});
}
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ return errorResponse(err, 500);
}
});