@supacloud/cli 0.118.2 → 0.119.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js
CHANGED
|
@@ -10004,6 +10004,7 @@ var WorkerExecutionGroupSchema = _Object_({
|
|
|
10004
10004
|
definitionVersion: String2({ pattern: "^[1-9][0-9]{0,8}$" }),
|
|
10005
10005
|
replicas: positive(16),
|
|
10006
10006
|
maxReplicas: positive(16),
|
|
10007
|
+
shardCount: Optional(positive(64)),
|
|
10007
10008
|
concurrencyPerReplica: positive(32),
|
|
10008
10009
|
resources: ComputeResourcesSchema,
|
|
10009
10010
|
database: _Object_({
|
|
@@ -10021,23 +10022,49 @@ var WorkerExecutionGroupSchema = _Object_({
|
|
|
10021
10022
|
var WorkerExecutionSchema = _Object_({
|
|
10022
10023
|
groups: _Array_(WorkerExecutionGroupSchema, { minItems: 1, maxItems: 32 })
|
|
10023
10024
|
}, closed);
|
|
10025
|
+
function workerShardCount(group) {
|
|
10026
|
+
return group.shardCount ?? 1;
|
|
10027
|
+
}
|
|
10028
|
+
function shardSuffix(shard) {
|
|
10029
|
+
if (!Number.isSafeInteger(shard) || shard < 0 || shard >= 64) {
|
|
10030
|
+
throw new Error("WORKER_SHARD_INVALID");
|
|
10031
|
+
}
|
|
10032
|
+
return `s${shard.toString(36).padStart(2, "0")}`;
|
|
10033
|
+
}
|
|
10034
|
+
function workerShardQueue(group, shard) {
|
|
10035
|
+
const count = workerShardCount(group);
|
|
10036
|
+
if (!Number.isSafeInteger(shard) || shard < 0 || shard >= count) {
|
|
10037
|
+
throw new Error("WORKER_SHARD_INVALID");
|
|
10038
|
+
}
|
|
10039
|
+
if (count === 1)
|
|
10040
|
+
return group.queue;
|
|
10041
|
+
const queue = `${group.queue}_${shardSuffix(shard)}`;
|
|
10042
|
+
if (!/^scw_[a-z0-9_]{1,40}$/.test(queue))
|
|
10043
|
+
throw new Error("WORKER_QUEUE_INVALID");
|
|
10044
|
+
return queue;
|
|
10045
|
+
}
|
|
10024
10046
|
function parseWorkerExecutionGroup(value) {
|
|
10025
10047
|
if (!Check2(WorkerExecutionGroupSchema, value) || value.replicas > value.maxReplicas || !value.queue.endsWith(`_v${value.definitionVersion}`) || value.lifecycle.visibilityTimeoutSeconds < value.lifecycle.executionTimeoutSeconds + value.lifecycle.shutdownGraceSeconds + 30) {
|
|
10026
10048
|
throw new Error("WORKER_EXECUTION_INVALID");
|
|
10027
10049
|
}
|
|
10028
|
-
|
|
10050
|
+
const group = structuredClone(value);
|
|
10051
|
+
for (let shard = 0;shard < workerShardCount(group); shard += 1)
|
|
10052
|
+
workerShardQueue(group, shard);
|
|
10053
|
+
return group;
|
|
10029
10054
|
}
|
|
10030
10055
|
function validateWorkerExecution(groups) {
|
|
10031
10056
|
const names = new Set, targets = new Set, queues = new Set, routes = new Set;
|
|
10032
10057
|
for (const candidate of groups) {
|
|
10033
10058
|
const group = parseWorkerExecutionGroup(candidate);
|
|
10034
10059
|
const route = `${group.taskKey}:${group.definitionVersion}`;
|
|
10035
|
-
|
|
10060
|
+
const physicalQueues = Array.from({ length: workerShardCount(group) }, (_, shard) => workerShardQueue(group, shard));
|
|
10061
|
+
if (names.has(group.name) || targets.has(group.target) || queues.has(group.queue) || physicalQueues.some((queue) => queues.has(queue)) || routes.has(route)) {
|
|
10036
10062
|
throw new Error("WORKER_EXECUTION_CONFLICT");
|
|
10037
10063
|
}
|
|
10038
10064
|
names.add(group.name);
|
|
10039
10065
|
targets.add(group.target);
|
|
10040
10066
|
queues.add(group.queue);
|
|
10067
|
+
physicalQueues.forEach((queue) => queues.add(queue));
|
|
10041
10068
|
routes.add(route);
|
|
10042
10069
|
}
|
|
10043
10070
|
}
|
|
@@ -10315,7 +10342,7 @@ function parseDeliveryBuildManifest(value) {
|
|
|
10315
10342
|
if (!Check2(DeliveryBuildManifestSchema, value))
|
|
10316
10343
|
throw new Error("Invalid delivery build manifest.");
|
|
10317
10344
|
validateWorkerExecution(value.plan.targets.flatMap((target) => target.execution ? [target.execution] : []));
|
|
10318
|
-
if (value.plan.targets.reduce((count, target) => count + (target.execution
|
|
10345
|
+
if (value.plan.targets.reduce((count, target) => count + (target.execution ? (target.execution.replicas ?? 1) * workerShardCount(target.execution) : 1), 0) > 256) {
|
|
10319
10346
|
throw new Error("Invalid delivery replica count.");
|
|
10320
10347
|
}
|
|
10321
10348
|
for (const target of value.plan.targets) {
|
|
@@ -10442,7 +10469,7 @@ function parseApplicationReleaseRecord(candidate) {
|
|
|
10442
10469
|
throw new Error("Invalid application release record.");
|
|
10443
10470
|
}
|
|
10444
10471
|
validateWorkerExecution(candidate.targets.flatMap((target) => target.execution ? [target.execution] : []));
|
|
10445
|
-
if (candidate.targets.reduce((count, target) => count + (target.execution
|
|
10472
|
+
if (candidate.targets.reduce((count, target) => count + (target.execution ? (target.execution.replicas ?? 1) * workerShardCount(target.execution) : 1), 0) > 256) {
|
|
10446
10473
|
throw new Error("Invalid application replica count.");
|
|
10447
10474
|
}
|
|
10448
10475
|
if (candidate.targets.some((target) => target.execution && (target.compute || target.kind !== "worker" || target.execution.target !== target.name))) {
|
|
@@ -22198,25 +22225,25 @@ var starter_metadata_default = {
|
|
|
22198
22225
|
generatedBy: "supacloud/starter-metadata-v1",
|
|
22199
22226
|
packages: {
|
|
22200
22227
|
compiler: {
|
|
22201
|
-
version: "0.
|
|
22228
|
+
version: "0.60.0"
|
|
22202
22229
|
},
|
|
22203
22230
|
app: {
|
|
22204
|
-
version: "0.39.
|
|
22231
|
+
version: "0.39.1",
|
|
22205
22232
|
dependencies: {
|
|
22206
22233
|
rxjs: "7.8.2"
|
|
22207
22234
|
}
|
|
22208
22235
|
},
|
|
22209
22236
|
elysia: {
|
|
22210
|
-
version: "0.
|
|
22237
|
+
version: "0.42.1"
|
|
22211
22238
|
},
|
|
22212
22239
|
commands: {
|
|
22213
22240
|
version: "0.12.0"
|
|
22214
22241
|
},
|
|
22215
22242
|
contracts: {
|
|
22216
|
-
version: "0.16.
|
|
22243
|
+
version: "0.16.1"
|
|
22217
22244
|
},
|
|
22218
22245
|
db: {
|
|
22219
|
-
version: "0.
|
|
22246
|
+
version: "0.24.0",
|
|
22220
22247
|
dependencies: {
|
|
22221
22248
|
"@zenstackhq/orm": "3.10.0",
|
|
22222
22249
|
"@zenstackhq/schema": "3.10.0",
|
|
@@ -23613,10 +23640,10 @@ export async function createReviewAttachmentWorker(options: ReviewAttachmentWork
|
|
|
23613
23640
|
};
|
|
23614
23641
|
}
|
|
23615
23642
|
`;
|
|
23616
|
-
var STARTER_ATTACHMENT_DELIVERY_WORKER = `
|
|
23643
|
+
var STARTER_ATTACHMENT_DELIVERY_WORKER = `
|
|
23617
23644
|
import { createClient } from "@supabase/supabase-js";
|
|
23618
23645
|
import { SupaCloudWorkflowsClient } from "@supacloud/js";
|
|
23619
|
-
import { createBunCommandDatabase } from "@supacloud/db/bun";
|
|
23646
|
+
import { createBunCommandDatabase, createBunSqlHost } from "@supacloud/db/bun";
|
|
23620
23647
|
import type { CompiledModule } from "@supacloud/elysia";
|
|
23621
23648
|
import { createReviewAttachmentWorker } from "./host/review-attachment-worker";
|
|
23622
23649
|
import { createReviewWorkerObserver } from "./host/review-worker-observability";
|
|
@@ -23627,27 +23654,11 @@ function required(name: string): string {
|
|
|
23627
23654
|
return value;
|
|
23628
23655
|
}
|
|
23629
23656
|
|
|
23630
|
-
function databaseConnection(): SQL.Options {
|
|
23631
|
-
const socket = process.env["DATABASE_SOCKET_PATH"];
|
|
23632
|
-
if (socket && process.env["DATABASE_URL"]) throw new Error("Conflicting database connection settings");
|
|
23633
|
-
if (socket) {
|
|
23634
|
-
return { adapter: "postgres", path: socket, database: required("DATABASE_NAME"), username: required("DATABASE_USER") };
|
|
23635
|
-
}
|
|
23636
|
-
const url = new URL(required("DATABASE_URL"));
|
|
23637
|
-
if (url.protocol !== "postgres:" && url.protocol !== "postgresql:") throw new Error("Invalid database URL");
|
|
23638
|
-
return {
|
|
23639
|
-
adapter: "postgres", url: url.href, hostname: url.hostname.replace(/^\\[|\\]$/g, ""), port: Number(url.port || 5432),
|
|
23640
|
-
username: decodeURIComponent(url.username), password: decodeURIComponent(url.password),
|
|
23641
|
-
database: decodeURIComponent(url.pathname.slice(1)),
|
|
23642
|
-
};
|
|
23643
|
-
}
|
|
23644
|
-
|
|
23645
23657
|
export async function createDeliveryWorker(modules: CompiledModule[], lifecycle: { signal: AbortSignal }) {
|
|
23646
23658
|
lifecycle.signal.throwIfAborted();
|
|
23647
23659
|
if (required("REVIEW_QUEUE_OWNERSHIP") !== "exclusive-review-attachments") {
|
|
23648
23660
|
throw new Error("Attachment worker requires an exclusively owned Workflow queue");
|
|
23649
23661
|
}
|
|
23650
|
-
const connection = databaseConnection();
|
|
23651
23662
|
const settings = {
|
|
23652
23663
|
projectId: required("SUPACLOUD_PROJECT_ID"), tenantId: required("APP_TENANT_ID"),
|
|
23653
23664
|
workerId: required("REVIEW_WORKER_ID"), url: required("SUPACLOUD_URL"), key: required("SUPACLOUD_SERVICE_ROLE_KEY"),
|
|
@@ -23655,9 +23666,10 @@ export async function createDeliveryWorker(modules: CompiledModule[], lifecycle:
|
|
|
23655
23666
|
const service = createClient(settings.url, settings.key, {
|
|
23656
23667
|
auth: { persistSession: false, autoRefreshToken: false, detectSessionInUrl: false },
|
|
23657
23668
|
});
|
|
23658
|
-
const
|
|
23669
|
+
const host = createBunSqlHost({ max: 4, connectionTimeout: 5 });
|
|
23670
|
+
const pool = host.pool;
|
|
23659
23671
|
let closing: Promise<void> | undefined;
|
|
23660
|
-
const closePool = () => closing ??=
|
|
23672
|
+
const closePool = () => closing ??= host.close();
|
|
23661
23673
|
try {
|
|
23662
23674
|
const worker = await createReviewAttachmentWorker({
|
|
23663
23675
|
database: createBunCommandDatabase(pool), service, projectId: settings.projectId,
|
|
@@ -24304,9 +24316,9 @@ test("PostgreSQL host never falls back to demo identity or unbound business stor
|
|
|
24304
24316
|
expect(db.queries).toHaveLength(1);
|
|
24305
24317
|
});
|
|
24306
24318
|
`;
|
|
24307
|
-
var STARTER_REVIEW_DELIVERY_HOST = `
|
|
24319
|
+
var STARTER_REVIEW_DELIVERY_HOST = `
|
|
24308
24320
|
import { createClient } from "@supabase/supabase-js";
|
|
24309
|
-
import { createBunCommandDatabase } from "@supacloud/db/bun";
|
|
24321
|
+
import { createBunCommandDatabase, createBunSqlHost } from "@supacloud/db/bun";
|
|
24310
24322
|
import { createApplication, type CompiledModule } from "@supacloud/elysia";
|
|
24311
24323
|
import { createReviewPostgresAdapters } from "./host/review-postgres";
|
|
24312
24324
|
import { createReviewAttachmentAdapters } from "./host/review-attachments";
|
|
@@ -24320,24 +24332,8 @@ function required(name: string): string {
|
|
|
24320
24332
|
return value;
|
|
24321
24333
|
}
|
|
24322
24334
|
|
|
24323
|
-
function databaseConnection(): SQL.Options {
|
|
24324
|
-
const socket = process.env["DATABASE_SOCKET_PATH"];
|
|
24325
|
-
if (socket && process.env["DATABASE_URL"]) throw new Error("Conflicting database connection settings");
|
|
24326
|
-
if (socket) {
|
|
24327
|
-
return { adapter: "postgres", path: socket, database: required("DATABASE_NAME"), username: required("DATABASE_USER") };
|
|
24328
|
-
}
|
|
24329
|
-
const url = new URL(required("DATABASE_URL"));
|
|
24330
|
-
if (url.protocol !== "postgres:" && url.protocol !== "postgresql:") throw new Error("Invalid database URL");
|
|
24331
|
-
return {
|
|
24332
|
-
adapter: "postgres", url: url.href, hostname: url.hostname.replace(/^\\[|\\]$/g, ""), port: Number(url.port || 5432),
|
|
24333
|
-
username: decodeURIComponent(url.username), password: decodeURIComponent(url.password),
|
|
24334
|
-
database: decodeURIComponent(url.pathname.slice(1)),
|
|
24335
|
-
};
|
|
24336
|
-
}
|
|
24337
|
-
|
|
24338
24335
|
export async function createDeliveryApplication(modules: CompiledModule[], lifecycle: { signal: AbortSignal }) {
|
|
24339
24336
|
lifecycle.signal.throwIfAborted();
|
|
24340
|
-
const connection = databaseConnection();
|
|
24341
24337
|
const attachments = process.env["REVIEW_ATTACHMENTS"];
|
|
24342
24338
|
if (attachments !== undefined && attachments !== "enabled") throw new Error("Invalid attachment configuration");
|
|
24343
24339
|
const settings = {
|
|
@@ -24348,9 +24344,10 @@ export async function createDeliveryApplication(modules: CompiledModule[], lifec
|
|
|
24348
24344
|
jwksUrl: required("SUPAUTH_JWKS_URL"),
|
|
24349
24345
|
},
|
|
24350
24346
|
};
|
|
24351
|
-
const
|
|
24347
|
+
const host = createBunSqlHost({ max: 12, connectionTimeout: 5 });
|
|
24348
|
+
const pool = host.pool;
|
|
24352
24349
|
let closing: Promise<void> | undefined;
|
|
24353
|
-
const close = () => closing ??=
|
|
24350
|
+
const close = () => closing ??= host.close();
|
|
24354
24351
|
let stage: "attachments" | "uploads" | "postgres" | "application" = "attachments";
|
|
24355
24352
|
try {
|
|
24356
24353
|
const database = createBunCommandDatabase(pool);
|
|
@@ -24567,6 +24564,15 @@ zen migrate deploy or db push against a managed production database.
|
|
|
24567
24564
|
\`bun run db:pull -- --candidate output/database-audit/schema.zmodel\` writes a
|
|
24568
24565
|
review candidate only; it never overwrites the maintained model. Add policies
|
|
24569
24566
|
before adopting introspection output. Keep one migration history and preserve RLS.
|
|
24567
|
+
|
|
24568
|
+
Adopting a database that has no model yet starts with the same command: pull
|
|
24569
|
+
introspects through a temporary datasource-only model, so no hand-written ZModel
|
|
24570
|
+
is required. Review the candidate, add the policy plugin and @@allow rules, move
|
|
24571
|
+
it to zenstack/schema.zmodel, then run \`bun run db:generate\`. Until that file
|
|
24572
|
+
exists, \`db:diff\` and \`db:generate\` fail closed instead of building from an
|
|
24573
|
+
unreviewed introspection result. Keep the host wiring unchanged: one
|
|
24574
|
+
createZenStackDatabase composition root supplies read-only models and the
|
|
24575
|
+
transactional command store.
|
|
24570
24576
|
`;
|
|
24571
24577
|
function starterDatabaseFiles() {
|
|
24572
24578
|
return {
|
|
@@ -26621,6 +26627,8 @@ queue; configure delivery.runtime only after that target is selected. Then run
|
|
|
26621
26627
|
\`bun --no-env-file node_modules/@supacloud/compiler/dist/cli.js build\`.
|
|
26622
26628
|
Inject DATABASE_URL, APP_TENANT_ID, SUPACLOUD_PROJECT_ID, SUPAUTH_ISSUER,
|
|
26623
26629
|
SUPAUTH_AUDIENCE, SUPAUTH_CLIENT_ID and SUPAUTH_JWKS_URL at runtime.
|
|
26630
|
+
The generated host calls \`createBunSqlHost\`, so application modules receive the
|
|
26631
|
+
platform-owned Bun SQL pool and never read or parse DATABASE_URL.
|
|
26624
26632
|
Identity uses the configured remote JWKS verifier, never a synthetic local key.
|
|
26625
26633
|
PORT/HOST and shutdown are owned by the delivery runtime; the host closes its pool.
|
|
26626
26634
|
Do not include runtime secrets in the source tree or build inputs.
|
|
@@ -26741,6 +26749,8 @@ delivery.build.workerApplications: [{ target: "jobs", source: "delivery-worker.t
|
|
|
26741
26749
|
It uses the existing Workflow SDK and the compiled attachment Job, not a second
|
|
26742
26750
|
retry engine. Inject SUPACLOUD_URL, SUPACLOUD_SERVICE_ROLE_KEY,
|
|
26743
26751
|
SUPACLOUD_PROJECT_ID, APP_TENANT_ID, REVIEW_WORKER_ID and DATABASE_URL.
|
|
26752
|
+
The generated worker also uses \`createBunSqlHost\`; connection parsing remains
|
|
26753
|
+
inside the trusted host package.
|
|
26744
26754
|
Alternatively use DATABASE_SOCKET_PATH with DATABASE_NAME and DATABASE_USER,
|
|
26745
26755
|
but never alongside DATABASE_URL. Secrets belong only in runtime configuration.
|
|
26746
26756
|
REVIEW_QUEUE_OWNERSHIP must be exclusive-review-attachments: the Workflow claim
|
|
@@ -31032,6 +31042,7 @@ function buildDatabaseAiContext(modules, root, moduleName, target) {
|
|
|
31032
31042
|
"Edit the selected maintained source, not a generated snapshot.",
|
|
31033
31043
|
...sqlFirst ? ["Author structure in supabase/schemas SQL; derive query models, never run a second migration generator."] : [],
|
|
31034
31044
|
"Keep RPC, RLS, trigger and grant behavior in explicit SQL sources.",
|
|
31045
|
+
"Adopt an existing database from a generated candidate: pull a model candidate, review policies, then promote it to the maintained source; never build from unreviewed introspection.",
|
|
31035
31046
|
"Create a new forward migration; never rewrite an applied migration.",
|
|
31036
31047
|
"Run lint, focused behavior tests and catalog reconciliation after edits."
|
|
31037
31048
|
]
|
|
@@ -34290,7 +34301,7 @@ async function runProjectDeployment(http, args) {
|
|
|
34290
34301
|
// package.json
|
|
34291
34302
|
var package_default = {
|
|
34292
34303
|
name: "@supacloud/cli",
|
|
34293
|
-
version: "0.
|
|
34304
|
+
version: "0.119.0",
|
|
34294
34305
|
description: "Project-scoped CLI for SupaCloud users",
|
|
34295
34306
|
type: "module",
|
|
34296
34307
|
main: "./dist/index.js",
|
|
@@ -34342,23 +34353,23 @@ var package_default = {
|
|
|
34342
34353
|
directory: "packages/cli"
|
|
34343
34354
|
},
|
|
34344
34355
|
dependencies: {
|
|
34345
|
-
"@supacloud/compiler": "^0.
|
|
34346
|
-
"@supacloud/delivery": "0.
|
|
34347
|
-
"@supacloud/db": "0.
|
|
34356
|
+
"@supacloud/compiler": "^0.60.0",
|
|
34357
|
+
"@supacloud/delivery": "0.26.0",
|
|
34358
|
+
"@supacloud/db": "0.24.0",
|
|
34348
34359
|
typebox: "1.4.3"
|
|
34349
34360
|
},
|
|
34350
34361
|
overrides: {
|
|
34351
|
-
"@supacloud/contracts": "0.16.
|
|
34352
|
-
"@supacloud/delivery": "0.
|
|
34362
|
+
"@supacloud/contracts": "0.16.1",
|
|
34363
|
+
"@supacloud/delivery": "0.26.0",
|
|
34353
34364
|
"@graphql-tools/utils": "^12.0.4",
|
|
34354
|
-
"@supacloud/compiler": "^0.
|
|
34355
|
-
"@supacloud/db": "0.
|
|
34365
|
+
"@supacloud/compiler": "^0.60.0",
|
|
34366
|
+
"@supacloud/db": "0.24.0",
|
|
34356
34367
|
"deepmerge-ts": "8.0.2",
|
|
34357
34368
|
prisma: "6.19.3"
|
|
34358
34369
|
},
|
|
34359
34370
|
devDependencies: {
|
|
34360
34371
|
"@supabase/supabase-js": "2.118.0",
|
|
34361
|
-
"@supacloud/elysia": "0.
|
|
34372
|
+
"@supacloud/elysia": "0.42.1",
|
|
34362
34373
|
"@types/bun": "^1.4.4",
|
|
34363
34374
|
effect: "4.0.5",
|
|
34364
34375
|
elysia: "2.0.0-rc.1",
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export declare const STARTER_ATTACHMENT_WORKER = "import { createWorker, type CompiledModule, type ExecutionObserver } from \"@supacloud/elysia\";\nimport {\n createSupaCloudWorkflowTransport,\n type SupaCloudWorkflowClaim,\n type SupaCloudWorkflowsClient,\n} from \"@supacloud/js\";\nimport { createReviewAttachmentAdapters, type ReviewAttachmentOptions } from \"./review-attachments\";\n\nexport interface ReviewAttachmentWorkerOptions extends ReviewAttachmentOptions {\n modules: readonly CompiledModule[];\n workflows: Pick<SupaCloudWorkflowsClient, \"claim\" | \"complete\" | \"retry\" | \"fail\">;\n workerId: string;\n queueOwnership: \"exclusive-review-attachments\";\n pollIntervalMs?: number;\n onExecution?: ExecutionObserver;\n}\n\nexport async function createReviewAttachmentWorker(options: ReviewAttachmentWorkerOptions) {\n if (options.queueOwnership !== \"exclusive-review-attachments\") {\n throw new Error(\"Attachment worker requires an exclusively owned Workflow queue\");\n }\n const { store } = await createReviewAttachmentAdapters(options);\n const { workflows, workerId } = options;\n const failure = Promise.withResolvers<never>();\n // The executable attaches its fatal listener after this async factory returns.\n void failure.promise.catch(() => {});\n let halted: boolean = false;\n const fatal = () => {\n halted = true;\n failure.reject(new Error(\"Attachment worker requires recovery\"));\n };\n async function ownedClaim(claim: SupaCloudWorkflowClaim) {\n if (claim.workflowName !== \"review.verify-attachment\" || claim.workflowVersion !== \"1\"\n || claim.stepKey !== \"verify\" || claim.maxAttempts !== 3 || claim.workerId !== workerId) {\n throw new Error(\"Unsupported attachment workflow\");\n }\n const { reviewId, artifactId } = claim.input;\n if (typeof reviewId !== \"string\" || typeof artifactId !== \"string\") {\n throw new Error(\"Invalid attachment workflow input\");\n }\n const bound = await options.database.transaction(tx => tx.query(\n \"SELECT a.run_id FROM public.starter_attachments a WHERE a.review_id=$1 AND a.artifact_id=$2 \" +\n \"AND COALESCE((SELECT r.run_id FROM public.starter_attachment_retries r \" +\n \"WHERE r.review_id=a.review_id ORDER BY r.generation DESC LIMIT 1),a.run_id)=$3\",\n [reviewId, artifactId, claim.runId],\n ));\n if (!Array.isArray(bound) || bound.length !== 1) throw new Error(\"Attachment workflow ownership mismatch\");\n }\n const workflowTransport = createSupaCloudWorkflowTransport({\n workflows, workerId, visibilityTimeoutSeconds: 120, retryDelaySeconds: 5, acceptClaim: ownedClaim,\n });\n const worker = createWorker({\n modules: options.modules, deps: { dbClient: store }, workerId, concurrency: 1,\n pollIntervalMs: options.pollIntervalMs ?? 1000,\n onError: fatal,\n ...(options.onExecution === undefined ? {} : { onExecution: options.onExecution }),\n transport: {\n async claim(signal): Promise<SupaCloudWorkflowClaim | null> {\n if (halted || signal.aborted) return null;\n try {\n return await workflowTransport.claim(signal);\n } catch {\n if (!signal.aborted) fatal();\n throw new Error(\"Attachment workflow claim failed\");\n }\n },\n async ack(claim, output) {\n try {\n await workflowTransport.ack(claim, output);\n } catch {\n fatal();\n throw new Error(\"Attachment workflow completion is unconfirmed\");\n }\n },\n async fail(claim) {\n try {\n await workflowTransport.fail(claim, \"Attachment verification failed\");\n } catch {\n fatal();\n throw new Error(\"Attachment workflow failure receipt is unconfirmed\");\n }\n },\n },\n mapClaim: (claim: SupaCloudWorkflowClaim) => ({\n id: claim.stepId, jobName: claim.workflowName, input: claim.input, attempt: claim.attempt,\n requestContext: { workerId, jobId: claim.stepId, requestId: claim.runId },\n }),\n });\n if (worker.jobNames.length !== 1 || worker.jobNames[0] !== \"review.verify-attachment\") {\n throw new Error(\"Attachment worker requires its compiled reference Job\");\n }\n let closing: Promise<void> | undefined;\n return {\n failure: failure.promise,\n async start() {\n if (halted) throw new Error(\"Attachment worker is not startable\");\n await worker.start();\n },\n close() {\n halted = true;\n return closing ??= worker.stop();\n },\n };\n}\n";
|
|
2
|
-
export declare const STARTER_ATTACHMENT_DELIVERY_WORKER = "
|
|
2
|
+
export declare const STARTER_ATTACHMENT_DELIVERY_WORKER = "\nimport { createClient } from \"@supabase/supabase-js\";\nimport { SupaCloudWorkflowsClient } from \"@supacloud/js\";\nimport { createBunCommandDatabase, createBunSqlHost } from \"@supacloud/db/bun\";\nimport type { CompiledModule } from \"@supacloud/elysia\";\nimport { createReviewAttachmentWorker } from \"./host/review-attachment-worker\";\nimport { createReviewWorkerObserver } from \"./host/review-worker-observability\";\n\nfunction required(name: string): string {\n const value = process.env[name];\n if (!value?.trim()) throw new Error(\"Missing required worker setting: \" + name);\n return value;\n}\n\nexport async function createDeliveryWorker(modules: CompiledModule[], lifecycle: { signal: AbortSignal }) {\n lifecycle.signal.throwIfAborted();\n if (required(\"REVIEW_QUEUE_OWNERSHIP\") !== \"exclusive-review-attachments\") {\n throw new Error(\"Attachment worker requires an exclusively owned Workflow queue\");\n }\n const settings = {\n projectId: required(\"SUPACLOUD_PROJECT_ID\"), tenantId: required(\"APP_TENANT_ID\"),\n workerId: required(\"REVIEW_WORKER_ID\"), url: required(\"SUPACLOUD_URL\"), key: required(\"SUPACLOUD_SERVICE_ROLE_KEY\"),\n };\n const service = createClient(settings.url, settings.key, {\n auth: { persistSession: false, autoRefreshToken: false, detectSessionInUrl: false },\n });\n const host = createBunSqlHost({ max: 4, connectionTimeout: 5 });\n const pool = host.pool;\n let closing: Promise<void> | undefined;\n const closePool = () => closing ??= host.close();\n try {\n const worker = await createReviewAttachmentWorker({\n database: createBunCommandDatabase(pool), service, projectId: settings.projectId,\n tenantId: settings.tenantId, modules, workerId: settings.workerId,\n workflows: new SupaCloudWorkflowsClient(service), queueOwnership: \"exclusive-review-attachments\",\n onExecution: createReviewWorkerObserver(settings.workerId),\n });\n lifecycle.signal.throwIfAborted();\n return {\n start: () => worker.start(), failure: worker.failure,\n async close() { try { await worker.close(); } finally { await closePool(); } },\n };\n } catch (error) {\n await closePool();\n const code = error !== null && typeof error === \"object\" && \"code\" in error\n && typeof error.code === \"string\" && /^[A-Z0-9_]{1,64}$/.test(error.code) ? error.code : \"UNKNOWN\";\n console.error(JSON.stringify({ event: \"review-worker-initialization-failed\", code }));\n throw new Error(\"Attachment worker initialization failed\");\n }\n}\n";
|
|
@@ -14,5 +14,5 @@ export declare const STARTER_DATABASE_MODEL = "datasource db {\n provider = \"p
|
|
|
14
14
|
export declare const STARTER_DATABASE_SCHEMA = "export type { Review as ReviewRow, Attachment as AttachmentRow, AttachmentRetry as AttachmentRetryRow } from \"../zenstack/generated/models\";\nimport type { Review } from \"../zenstack/generated/models\";\nexport type NewReview = Review;\n";
|
|
15
15
|
export declare const STARTER_DATABASE_MODULES = "import { defineDatabaseModule } from \"@supacloud/db\";\n\nconst backendPolicies = [\n [\"starter_backend_binding_read\", \"public.starter_application\", \"select\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_binding_lock\", \"public.starter_application\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_binding_immutable\", \"public.starter_application\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_member_read\", \"public.starter_members\", \"select\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_member_lock\", \"public.starter_members\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_member_immutable\", \"public.starter_members\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_review_read\", \"public.starter_reviews\", \"select\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_review_update\", \"public.starter_reviews\", \"update\", [\"starter_review_http\"]],\n [\"starter_worker_review_immutable\", \"public.starter_reviews\", \"update\", [\"starter_review_worker\"]],\n [\"starter_backend_attachment_read\", \"public.starter_attachments\", \"select\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_attachment_lock\", \"public.starter_attachments\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_attachment_immutable\", \"public.starter_attachments\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_http_attachment_insert\", \"public.starter_attachments\", \"insert\", [\"starter_review_http\"]],\n [\"starter_worker_result_read\", \"public.starter_attachment_results\", \"select\", [\"starter_review_worker\"]],\n [\"starter_worker_result_insert\", \"public.starter_attachment_results\", \"insert\", [\"starter_review_worker\"]],\n] as const;\n\n// The module is the single live-Catalog ownership contract for starter tables.\nexport default defineDatabaseModule({\n name: \"starter\",\n tables: [\"public.starter_application\", \"public.starter_reviews\", \"public.starter_members\", \"public.starter_attachments\", \"public.starter_attachment_results\", \"public.starter_attachment_retries\"],\n policies: [\n ...([\n [\"starter_http_retry_read\", \"select\", \"starter_review_http\"],\n [\"starter_http_retry_insert\", \"insert\", \"starter_review_http\"],\n [\"starter_worker_retry_read\", \"select\", \"starter_review_worker\"],\n ] as const).map(([name, operation, role]) => ({\n name, table: \"public.starter_attachment_retries\", operation, roles: [role],\n source: \"migrations/005-review-task-recovery.sql\", tests: [\"tests/database-governance.sql\"],\n })),\n ...backendPolicies.map(([name, table, operation, roles]) => ({\n name, table, operation, roles: [...roles], source: \"migrations/004-review-runtime-roles.sql\",\n tests: [\"tests/database-governance.sql\"],\n })),\n {\n name: \"starter_member_read\", table: \"public.starter_members\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/003-review-uploads.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n {\n name: \"starter_review_read\", table: \"public.starter_reviews\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/003-review-uploads.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n ],\n});\n";
|
|
16
16
|
export declare const STARTER_DATABASE_TEST = "-- Read-only catalog assertions; behavioral authorization tests remain separate.\nBEGIN READ ONLY;\nDO $test$\nDECLARE\n owned text[] := ARRAY['starter_application','starter_reviews','starter_members',\n 'starter_attachments','starter_attachment_results','starter_attachment_retries'];\nBEGIN\n IF (SELECT count(*) FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace\n WHERE n.nspname='public' AND c.relname=ANY(owned) AND c.relrowsecurity) <> 6 THEN\n RAISE EXCEPTION 'All starter tables must exist with RLS enabled';\n END IF;\n IF (SELECT count(*) FROM pg_policy p JOIN pg_class c ON c.oid=p.polrelid\n JOIN pg_namespace n ON n.oid=c.relnamespace\n WHERE n.nspname='public' AND c.relname=ANY(owned)) <> 20 THEN\n RAISE EXCEPTION 'Starter policy inventory changed; reconcile db/modules.ts';\n END IF;\n IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname IN ('starter_review_http','starter_review_worker')\n AND (rolsuper OR rolbypassrls)) THEN\n RAISE EXCEPTION 'Starter roles must not bypass row security';\n END IF;\n IF (SELECT count(*) FROM pg_roles WHERE rolname IN ('starter_review_http','starter_review_worker')) <> 2 THEN\n RAISE EXCEPTION 'Starter runtime roles are missing';\n END IF;\nEND\n$test$;\nROLLBACK;\n";
|
|
17
|
-
export declare const STARTER_DATABASE_GUIDE = "\n## Model and migration workflow\n\nMaintain zenstack/schema.zmodel. Run `bun run db:generate` to compile model and RPC\ncontracts; commit generated types with their sources. Do not introduce any/@ts-ignore\nto bypass model or contract diagnostics. `bun run db:check` compares\nfresh generation without writing files or opening a database. Model read policies\ncomplement existing database RLS; command writes still use the shared transaction,\nreceipt and audit boundary, not unrestricted CRUD. SQL constraints, RPCs and RLS\nremain explicit reviewed migrations when the model language cannot express them.\n\nUse `bun run db:diff -- --candidate output/database-audit/change.sql` with an\nexplicit read-only SUPACLOUD_MODEL_DATABASE_URL. Review the SQL, then promote a new\nforward migration through the existing SupaCloud plan/apply ledger. Never run\nzen migrate deploy or db push against a managed production database.\n`bun run db:pull -- --candidate output/database-audit/schema.zmodel` writes a\nreview candidate only; it never overwrites the maintained model. Add policies\nbefore adopting introspection output. Keep one migration history and preserve RLS.\n";
|
|
17
|
+
export declare const STARTER_DATABASE_GUIDE = "\n## Model and migration workflow\n\nMaintain zenstack/schema.zmodel. Run `bun run db:generate` to compile model and RPC\ncontracts; commit generated types with their sources. Do not introduce any/@ts-ignore\nto bypass model or contract diagnostics. `bun run db:check` compares\nfresh generation without writing files or opening a database. Model read policies\ncomplement existing database RLS; command writes still use the shared transaction,\nreceipt and audit boundary, not unrestricted CRUD. SQL constraints, RPCs and RLS\nremain explicit reviewed migrations when the model language cannot express them.\n\nUse `bun run db:diff -- --candidate output/database-audit/change.sql` with an\nexplicit read-only SUPACLOUD_MODEL_DATABASE_URL. Review the SQL, then promote a new\nforward migration through the existing SupaCloud plan/apply ledger. Never run\nzen migrate deploy or db push against a managed production database.\n`bun run db:pull -- --candidate output/database-audit/schema.zmodel` writes a\nreview candidate only; it never overwrites the maintained model. Add policies\nbefore adopting introspection output. Keep one migration history and preserve RLS.\n\nAdopting a database that has no model yet starts with the same command: pull\nintrospects through a temporary datasource-only model, so no hand-written ZModel\nis required. Review the candidate, add the policy plugin and @@allow rules, move\nit to zenstack/schema.zmodel, then run `bun run db:generate`. Until that file\nexists, `db:diff` and `db:generate` fail closed instead of building from an\nunreviewed introspection result. Keep the host wiring unchanged: one\ncreateZenStackDatabase composition root supplies read-only models and the\ntransactional command store.\n";
|
|
18
18
|
export declare function starterDatabaseFiles(): Record<string, string>;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export declare const STARTER_REVIEW_SCHEMA = "-- Apply with the platform migration owner, never from the HTTP process.\n-- One application database belongs to one explicitly provisioned project/tenant.\nCREATE TABLE public.starter_application (\n singleton boolean PRIMARY KEY DEFAULT true CHECK (singleton),\n project_id text NOT NULL CHECK (length(project_id) > 0),\n tenant_id text NOT NULL CHECK (length(tenant_id) > 0)\n);\nCREATE TABLE public.starter_reviews (\n id text PRIMARY KEY, owner_id text NOT NULL,\n state text NOT NULL CHECK (state IN ('draft','approved')),\n version integer NOT NULL CHECK (version > 0)\n);\nCREATE TABLE public.starter_members (\n subject text PRIMARY KEY, enabled boolean NOT NULL DEFAULT true,\n can_approve boolean NOT NULL DEFAULT false\n);\nALTER TABLE public.starter_application ENABLE ROW LEVEL SECURITY;\nALTER TABLE public.starter_reviews ENABLE ROW LEVEL SECURITY;\nALTER TABLE public.starter_members ENABLE ROW LEVEL SECURITY;\n";
|
|
2
2
|
export declare const STARTER_REVIEW_POSTGRES = "import { createTransactionalCommand, plaintextCommandInput } from \"@supacloud/commands\";\nimport { CommandError } from \"@supacloud/contracts\";\nimport { createPostgresCommandStore, type CommandDatabase, type CommandTransaction } from \"@supacloud/db\";\nimport {\n ApplicationError, createSchemaDecoder, createSupAuthRequestContext, requireTrustedIdentity,\n createTransactionalCommandGovernance,\n type SupAuthContextOptions,\n} from \"@supacloud/elysia\";\nimport type { AppAdapters } from \"../application\";\nimport type { ReviewStore } from \"../review/review\";\nimport type { ReviewUploadPort } from \"../review/uploads\";\nimport type { ReviewTaskPort } from \"../review/tasks\";\nimport { ApprovalInput, ReviewResult } from \"../review/contracts\";\nimport type { ReviewRow } from \"../../db/schema\";\n\nconst input = createSchemaDecoder(ApprovalInput, { normalize: false });\nconst result: (value: unknown) => Pick<ReviewRow, \"state\" | \"version\"> =\n createSchemaDecoder(ReviewResult, { normalize: false });\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\nfunction record(value: unknown): Record<string, unknown> {\n if (!isRecord(value)) throw new TypeError(\"Invalid review record\");\n return value;\n}\nfunction rows(value: unknown): Record<string, unknown>[] {\n if (!Array.isArray(value)) throw new TypeError(\"Invalid database result\");\n return value.map(record);\n}\nfunction isPublicConflict(value: unknown): boolean {\n return value instanceof ApplicationError && value.status === 409\n || isRecord(value) && value[\"expose\"] === true && value[\"status\"] === 409 && typeof value[\"code\"] === \"string\";\n}\nexport interface ReviewPostgresOptions {\n database: CommandDatabase;\n tenantId: string;\n identity: Omit<SupAuthContextOptions, \"resolveAccess\">;\n uploads?: ReviewUploadPort;\n tasks?: ReviewTaskPort;\n // Only database effects here: they commit/rollback with the approval and receipt.\n afterApproved?(tx: CommandTransaction, id: string, version: number): Promise<void>;\n}\n\nexport async function createReviewPostgresAdapters(options: ReviewPostgresOptions): Promise<\n AppAdapters & { requestContext: ReturnType<typeof createSupAuthRequestContext> }\n> {\n const { database, tenantId, identity } = options;\n const projectId = identity.projectId;\n const afterApproved = options.afterApproved;\n if (!tenantId.trim()) throw new TypeError(\"Review tenantId is required\");\n const query = (text: string, parameters: readonly string[] = []) =>\n database.transaction(tx => tx.query(text, parameters));\n const binding = rows(await query(\n \"SELECT project_id,tenant_id FROM public.starter_application WHERE singleton\",\n ));\n if (binding.length !== 1 || binding[0]?.[\"project_id\"] !== projectId || binding[0]?.[\"tenant_id\"] !== tenantId) {\n throw new Error(\"Review database project/tenant binding mismatch\");\n }\n const requestContext = createSupAuthRequestContext({\n ...identity,\n async resolveAccess(who) {\n const found = rows(await query(\n \"SELECT m.can_approve FROM public.starter_members m,public.starter_application a \" +\n \"WHERE m.subject=$1 AND m.enabled AND a.singleton AND a.project_id=$2 AND a.tenant_id=$3\",\n [who.subject, projectId, tenantId],\n ));\n return found.length === 1 ? { projectId, tenantId,\n permissions: found[0]?.[\"can_approve\"] === true ? [\"review.approve\"] : [],\n } : null;\n },\n });\n const transaction = () => commandBinding.transaction();\n const store: ReviewStore = {\n ...options.uploads,\n ...options.tasks,\n async lookupOperation(context, operation) {\n const subject = actor(context);\n try {\n let confirmed: boolean = false;\n if (operation.kind === \"upload\") {\n if (!options.uploads?.lookupUpload) {\n throw new ApplicationError(\"Upload receipt lookup unavailable\", { status: 503, code: \"RECEIPTS_UNAVAILABLE\" });\n }\n confirmed = await options.uploads.lookupUpload(context, {\n reviewId: operation.reviewId, artifactId: operation.operationId, expectedVersion: operation.expectedVersion,\n });\n } else {\n const command = createTransactionalCommand({\n name: \"review.approve\", store: commandStore, inputCodec: plaintextCommandInput, input, result,\n authorize: authorizeApproval,\n execute: async () => { throw new Error(\"Receipt lookup cannot execute a command\"); },\n audit: { event: \"review.approved\", details: request => ({ reviewId: request.id }) },\n });\n const receipt = await command.lookup({ actorId: subject, tenantId }, operation.operationId,\n { id: operation.reviewId, expectedVersion: operation.expectedVersion });\n confirmed = receipt?.status === \"confirmed\";\n }\n return { status: confirmed ? \"confirmed\" : \"unknown\", operationId: operation.operationId, reviewId: operation.reviewId };\n } catch (error) {\n if (error instanceof ApplicationError) throw error;\n if (error instanceof CommandError && [\"COMMAND_REJECTED\", \"COMMAND_IDEMPOTENCY_CONFLICT\"].includes(error.code)) {\n throw new ApplicationError(error.code, { code: error.code, status: error.code === \"COMMAND_REJECTED\" ? 403 : 409 });\n }\n throw new ApplicationError(\"Receipt lookup unavailable\", { status: 503, code: \"RECEIPTS_UNAVAILABLE\" });\n }\n },\n async get(table, id) {\n if (table !== \"reviews\") throw new Error(\"Unsupported review table\");\n return rows(await transaction().query(\n \"SELECT state,version FROM public.starter_reviews WHERE id=$1 FOR UPDATE\", [id],\n ))[0];\n },\n async set(table, id, value) {\n if (table !== \"reviews\") throw new Error(\"Unsupported review table\");\n const review = result(value);\n const updated = rows(await transaction().query(\n \"UPDATE public.starter_reviews SET state=$2,version=$3 WHERE id=$1 RETURNING id\",\n [id, review.state, review.version],\n ));\n if (updated.length !== 1) throw new Error(\"Review write did not update one record\");\n await afterApproved?.(transaction(), id, review.version);\n },\n };\n function actor(context: unknown): string {\n const who = requireTrustedIdentity(context);\n const access = record(record(context)[\"access\"]);\n if (access[\"projectId\"] !== projectId || access[\"tenantId\"] !== tenantId\n || !Array.isArray(access[\"permissions\"]) || !access[\"permissions\"].includes(\"review.approve\")) {\n throw new ApplicationError(\"Command permission denied\", { status: 403, code: \"REVIEW_PERMISSION_DENIED\" });\n }\n return who.subject;\n }\n const commandStore = createPostgresCommandStore(database);\n async function authorizeApproval(who: { actorId: string; tenantId: string }, request: ReturnType<typeof input>, tx: CommandTransaction): Promise<\"allow\" | \"deny\"> {\n const found = rows(await tx.query(\n \"SELECT r.id FROM public.starter_reviews r JOIN public.starter_members m ON m.subject=r.owner_id \" +\n \"CROSS JOIN public.starter_application a \" +\n \"WHERE r.id=$1 AND r.owner_id=$2 AND m.enabled AND m.can_approve \" +\n \"AND a.singleton AND a.project_id=$3 AND a.tenant_id=$4 FOR UPDATE OF r,m FOR SHARE OF a\",\n [request.id, who.actorId, projectId, who.tenantId],\n ));\n return found.length === 1 ? \"allow\" : \"deny\";\n }\n const commandBinding = createTransactionalCommandGovernance({\n permission: \"review.approve\",\n identity: invocation => ({ actorId: actor(invocation.requestContext), tenantId }),\n input: invocation => ({\n ...record(invocation.input.body), id: invocation.input.params[\"id\"],\n }),\n rejection: error => isPublicConflict(error) ? new CommandError(\"COMMAND_IDEMPOTENCY_CONFLICT\") : undefined,\n definition: {\n name: \"review.approve\", store: commandStore,\n inputCodec: plaintextCommandInput, input, result,\n authorize: authorizeApproval,\n audit: { event: \"review.approved\", details: request => ({ reviewId: request.id }) },\n },\n });\n return { deps: { dbClient: store }, requestContext, commandGovernance: commandBinding.governance };\n}\n";
|
|
3
3
|
export declare const STARTER_REVIEW_POSTGRES_TEST = "import { expect, test } from \"bun:test\";\nimport { createReviewPostgresAdapters } from \"../src/host/review-postgres\";\nimport type { ReviewStore } from \"../src/review/review\";\n\nconst identity = {\n issuer: \"https://identity.example.test\", audience: \"review-test\", clientId: \"review-client\",\n projectId: \"review-test\", jwksUrl: \"https://identity.example.test/jwks\",\n};\nfunction database(binding: unknown) {\n const queries: string[] = [];\n return {\n queries,\n async transaction<T>(run: (tx: { query(text: string): Promise<unknown> }) => Promise<T>): Promise<T> {\n return run({ async query(text) { queries.push(text); return binding; } });\n },\n };\n}\n\ntest(\"PostgreSQL host rejects missing or mismatched application ownership without creating data\", async () => {\n for (const binding of [[], [{ project_id: \"other\", tenant_id: \"review-test\" }],\n [{ project_id: \"review-test\", tenant_id: \"other\" }]]) {\n const db = database(binding);\n await expect(createReviewPostgresAdapters({ database: db, identity, tenantId: \"review-test\" }))\n .rejects.toThrow(\"binding mismatch\");\n expect(db.queries).toEqual([\"SELECT project_id,tenant_id FROM public.starter_application WHERE singleton\"]);\n }\n});\n\ntest(\"PostgreSQL host never falls back to demo identity or unbound business storage\", async () => {\n const db = database([{ project_id: \"review-test\", tenant_id: \"review-test\" }]);\n const adapters = await createReviewPostgresAdapters({ database: db, identity, tenantId: \"review-test\" });\n await expect(adapters.requestContext(new Request(\"http://localhost/reviews/health\")))\n .rejects.toMatchObject({ code: \"AUTHENTICATION_REQUIRED\" });\n const store = adapters.deps[\"dbClient\"] as ReviewStore;\n await expect(store.get(\"reviews\", \"example\")).rejects.toThrow(\"not active\");\n await expect(store.set(\"reviews\", \"example\", { state: \"approved\", version: 2 }))\n .rejects.toThrow(\"not active\");\n expect(db.queries).toHaveLength(1);\n});\n";
|
|
4
|
-
export declare const STARTER_REVIEW_DELIVERY_HOST = "
|
|
4
|
+
export declare const STARTER_REVIEW_DELIVERY_HOST = "\nimport { createClient } from \"@supabase/supabase-js\";\nimport { createBunCommandDatabase, createBunSqlHost } from \"@supacloud/db/bun\";\nimport { createApplication, type CompiledModule } from \"@supacloud/elysia\";\nimport { createReviewPostgresAdapters } from \"./host/review-postgres\";\nimport { createReviewAttachmentAdapters } from \"./host/review-attachments\";\nimport { createReviewUploadAdapters } from \"./host/review-uploads\";\nimport { createReviewTaskAdapters } from \"./host/review-tasks\";\nimport { createReviewHttpObserver } from \"./host/review-execution-observability\";\n\nfunction required(name: string): string {\n const value = process.env[name];\n if (!value?.trim()) throw new Error(\"Missing required host setting: \" + name);\n return value;\n}\n\nexport async function createDeliveryApplication(modules: CompiledModule[], lifecycle: { signal: AbortSignal }) {\n lifecycle.signal.throwIfAborted();\n const attachments = process.env[\"REVIEW_ATTACHMENTS\"];\n if (attachments !== undefined && attachments !== \"enabled\") throw new Error(\"Invalid attachment configuration\");\n const settings = {\n tenantId: required(\"APP_TENANT_ID\"),\n identity: {\n issuer: required(\"SUPAUTH_ISSUER\"), audience: required(\"SUPAUTH_AUDIENCE\"),\n clientId: required(\"SUPAUTH_CLIENT_ID\"), projectId: required(\"SUPACLOUD_PROJECT_ID\"),\n jwksUrl: required(\"SUPAUTH_JWKS_URL\"),\n },\n };\n const host = createBunSqlHost({ max: 12, connectionTimeout: 5 });\n const pool = host.pool;\n let closing: Promise<void> | undefined;\n const close = () => closing ??= host.close();\n let stage: \"attachments\" | \"uploads\" | \"postgres\" | \"application\" = \"attachments\";\n try {\n const database = createBunCommandDatabase(pool);\n const attachmentOptions = attachments === \"enabled\" ? {\n database, tenantId: settings.tenantId, projectId: settings.identity.projectId,\n service: createClient(required(\"SUPACLOUD_URL\"), required(\"SUPACLOUD_SERVICE_ROLE_KEY\"), {\n auth: { persistSession: false, autoRefreshToken: false, detectSessionInUrl: false },\n }),\n } : undefined;\n const durable = attachmentOptions ? await createReviewAttachmentAdapters(attachmentOptions) : undefined;\n stage = \"uploads\";\n const uploads = attachmentOptions ? await createReviewUploadAdapters(attachmentOptions) : undefined;\n const tasks = attachmentOptions ? await createReviewTaskAdapters(attachmentOptions) : undefined;\n stage = \"postgres\";\n const adapters = await createReviewPostgresAdapters({\n database, tenantId: settings.tenantId, identity: settings.identity,\n ...(uploads ? { uploads } : {}),\n ...(tasks ? { tasks } : {}),\n ...(durable ? { afterApproved: durable.enqueue } : {}),\n });\n lifecycle.signal.throwIfAborted();\n stage = \"application\";\n const app = createApplication({ name: \"review\", modules, ...adapters, onExecution: createReviewHttpObserver() });\n return { fetch: (request: Request) => app.handle(request), close };\n } catch (error) {\n await close();\n const code = error !== null && typeof error === \"object\" && \"code\" in error\n && typeof error.code === \"string\" && /^[A-Z0-9_]{1,64}$/.test(error.code) ? error.code : \"UNKNOWN\";\n console.error(JSON.stringify({ event: \"review-host-initialization-failed\", stage, code }));\n // Database/identity errors can contain connection details; never echo the underlying cause.\n throw new Error(\"Review host initialization failed\");\n }\n}\n";
|
|
@@ -23,6 +23,7 @@ export declare const ApplicationReleaseRecordSchema: import("typebox").TObject<{
|
|
|
23
23
|
definitionVersion: import("typebox").TString;
|
|
24
24
|
replicas: import("typebox").TInteger;
|
|
25
25
|
maxReplicas: import("typebox").TInteger;
|
|
26
|
+
shardCount: import("typebox").TOptional<import("typebox").TInteger>;
|
|
26
27
|
concurrencyPerReplica: import("typebox").TInteger;
|
|
27
28
|
resources: import("typebox").TObject<{
|
|
28
29
|
cpuLimit: import("typebox").TNumber;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@supacloud/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.119.0",
|
|
4
4
|
"description": "Project-scoped CLI for SupaCloud users",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -52,23 +52,23 @@
|
|
|
52
52
|
"directory": "packages/cli"
|
|
53
53
|
},
|
|
54
54
|
"dependencies": {
|
|
55
|
-
"@supacloud/compiler": "^0.
|
|
56
|
-
"@supacloud/delivery": "0.
|
|
57
|
-
"@supacloud/db": "0.
|
|
55
|
+
"@supacloud/compiler": "^0.60.0",
|
|
56
|
+
"@supacloud/delivery": "0.26.0",
|
|
57
|
+
"@supacloud/db": "0.24.0",
|
|
58
58
|
"typebox": "1.4.3"
|
|
59
59
|
},
|
|
60
60
|
"overrides": {
|
|
61
|
-
"@supacloud/contracts": "0.16.
|
|
62
|
-
"@supacloud/delivery": "0.
|
|
61
|
+
"@supacloud/contracts": "0.16.1",
|
|
62
|
+
"@supacloud/delivery": "0.26.0",
|
|
63
63
|
"@graphql-tools/utils": "^12.0.4",
|
|
64
|
-
"@supacloud/compiler": "^0.
|
|
65
|
-
"@supacloud/db": "0.
|
|
64
|
+
"@supacloud/compiler": "^0.60.0",
|
|
65
|
+
"@supacloud/db": "0.24.0",
|
|
66
66
|
"deepmerge-ts": "8.0.2",
|
|
67
67
|
"prisma": "6.19.3"
|
|
68
68
|
},
|
|
69
69
|
"devDependencies": {
|
|
70
70
|
"@supabase/supabase-js": "2.118.0",
|
|
71
|
-
"@supacloud/elysia": "0.
|
|
71
|
+
"@supacloud/elysia": "0.42.1",
|
|
72
72
|
"@types/bun": "^1.4.4",
|
|
73
73
|
"effect": "4.0.5",
|
|
74
74
|
"elysia": "2.0.0-rc.1",
|