gencow 0.1.296 → 0.1.297
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/lib/deploy-admission-transport-failure.mjs +62 -11
- package/lib/deploy-local-dir-header.mjs +23 -0
- package/lib/deploy-package-runtime.mjs +2 -1
- package/lib/dev-cloud-command.mjs +2 -1
- package/lib/platform-client.mjs +37 -9
- package/lib/static-deploy-command.mjs +16 -6
- package/package.json +5 -5
- package/runtime/server.mjs +1 -1
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
// Typed diagnosis for a deploy admission request that got no HTTP response.
|
|
2
2
|
//
|
|
3
3
|
// Two cases are told apart by a stable error code:
|
|
4
|
-
// - ERR_INVALID_URL: the request was rejected before any network
|
|
5
|
-
// malformed Platform URL
|
|
4
|
+
// - ERR_INVALID_URL, CLI_REQUEST_HEADER_INVALID: the request was rejected before any network
|
|
5
|
+
// I/O (a malformed Platform URL, or a header value that cannot be sent). Nothing was sent,
|
|
6
|
+
// so the state is known: NOT CHANGED.
|
|
6
7
|
// - Any other rejection: a network-layer failure. The request may have reached the
|
|
7
8
|
// Platform, so the state is UNKNOWN and the next step is a status check before a rerun.
|
|
8
9
|
//
|
|
@@ -38,7 +39,11 @@ const KNOWN_CAUSE_CODES = new Set([
|
|
|
38
39
|
"ConnectionRefused",
|
|
39
40
|
]);
|
|
40
41
|
|
|
41
|
-
const
|
|
42
|
+
const INVALID_URL_CAUSE_CODE = "ERR_INVALID_URL";
|
|
43
|
+
// Thrown by platformFetch before fetch is called (see platform-client.mjs).
|
|
44
|
+
const INVALID_HEADER_CAUSE_CODE = "CLI_REQUEST_HEADER_INVALID";
|
|
45
|
+
const NOT_SENT_CAUSE_CODES = new Set([INVALID_URL_CAUSE_CODE, INVALID_HEADER_CAUSE_CODE]);
|
|
46
|
+
const SAFE_HEADER_NAME = /^[A-Za-z][A-Za-z0-9-]{0,63}$/u;
|
|
42
47
|
// Release steps that run before any serving change. Only these may be rendered as
|
|
43
48
|
// "Database: NOT CHANGED" with a stage label; the deploy admission submit keeps its own wording.
|
|
44
49
|
const RELEASE_STAGES = new Set(["release capability check", "release-attempt registration"]);
|
|
@@ -60,6 +65,14 @@ function readAllowlistedCauseCode(cause) {
|
|
|
60
65
|
return code !== null && KNOWN_CAUSE_CODES.has(code) ? code : null;
|
|
61
66
|
}
|
|
62
67
|
|
|
68
|
+
// The header a local check refused to send: { name } (name is null when it is not a safe token),
|
|
69
|
+
// or null when the cause is something else. The header value is never read.
|
|
70
|
+
function readInvalidHeader(cause) {
|
|
71
|
+
if (readCauseCode(cause) !== INVALID_HEADER_CAUSE_CODE) return null;
|
|
72
|
+
const name = cause?.headerName ?? cause?.cause?.headerName;
|
|
73
|
+
return { name: typeof name === "string" && SAFE_HEADER_NAME.test(name) ? name : null };
|
|
74
|
+
}
|
|
75
|
+
|
|
63
76
|
// The in-process message stays the original cause text, so callers that inspect the thrown
|
|
64
77
|
// error keep their existing contract. The CLI prints only the typed rendering, never this message.
|
|
65
78
|
export function createAdmissionTransportFailure({
|
|
@@ -77,7 +90,8 @@ export function createAdmissionTransportFailure({
|
|
|
77
90
|
appName: typeof appName === "string" && SAFE_APP_ID.test(appName) ? appName : null,
|
|
78
91
|
requestId: typeof requestId === "string" && SAFE_REQUEST_ID.test(requestId) ? requestId : null,
|
|
79
92
|
envTarget: envTarget === "prod" ? "prod" : "dev",
|
|
80
|
-
requestSent: readCauseCode(cause)
|
|
93
|
+
requestSent: !NOT_SENT_CAUSE_CODES.has(readCauseCode(cause)),
|
|
94
|
+
invalidHeader: readInvalidHeader(cause),
|
|
81
95
|
causeMessage: readAllowlistedCauseMessage(cause),
|
|
82
96
|
causeCode: readAllowlistedCauseCode(cause),
|
|
83
97
|
attempts: null,
|
|
@@ -112,6 +126,32 @@ function causeLine(detail) {
|
|
|
112
126
|
return detail.causeMessage ? `Cause: ${detail.causeMessage}` : `Cause: network error (${detail.causeCode})`;
|
|
113
127
|
}
|
|
114
128
|
|
|
129
|
+
function invalidHeaderCauseLine(invalidHeader) {
|
|
130
|
+
return invalidHeader.name
|
|
131
|
+
? `Cause: the ${invalidHeader.name} request header has a value that cannot be sent over HTTP`
|
|
132
|
+
: "Cause: a request header has a value that cannot be sent over HTTP";
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// What to fix before a rerun when the request never left this machine.
|
|
136
|
+
function notSentNextLines(invalidHeader) {
|
|
137
|
+
const urlLines = [
|
|
138
|
+
"Retryable: yes, after the Platform URL setting is fixed",
|
|
139
|
+
"Next: check the Platform URL in your CLI login/configuration, then rerun the same deploy command.",
|
|
140
|
+
];
|
|
141
|
+
if (!invalidHeader) return urlLines;
|
|
142
|
+
if (invalidHeader.name === "Origin") return urlLines;
|
|
143
|
+
if (invalidHeader.name === "Authorization") {
|
|
144
|
+
return [
|
|
145
|
+
"Retryable: yes, after the saved CLI credential is replaced",
|
|
146
|
+
"Next: run `gencow login` (or set a valid GENCOW_TOKEN), then rerun the same deploy command.",
|
|
147
|
+
];
|
|
148
|
+
}
|
|
149
|
+
return [
|
|
150
|
+
"Retryable: yes, after the CLI is updated",
|
|
151
|
+
"Next: rerun the same deploy command with the latest CLI (for example `npx gencow@latest deploy`). If it fails again, report the header name above and the CLI version (`gencow --version`) in a GitHub issue.",
|
|
152
|
+
];
|
|
153
|
+
}
|
|
154
|
+
|
|
115
155
|
// Release steps before the serving change. The capability check is read-only; a registration
|
|
116
156
|
// that got no response is not confirmed to have created anything, so the rerun is the plain
|
|
117
157
|
// deploy command (no request ID or --resume).
|
|
@@ -144,7 +184,9 @@ function releaseStageLines(detail) {
|
|
|
144
184
|
return lines;
|
|
145
185
|
}
|
|
146
186
|
|
|
147
|
-
|
|
187
|
+
// `resumeCommand` lets a caller whose resume entry point differs from `gencow deploy --resume`
|
|
188
|
+
// (for example `gencow deploy --static ...`) name its own exact command.
|
|
189
|
+
export function renderAdmissionTransportFailureLines(caught, { resumeCommand = null } = {}) {
|
|
148
190
|
const detail = caught.deployAdmissionTransport;
|
|
149
191
|
if (detail.stage) return releaseStageLines(detail);
|
|
150
192
|
const prodFlag = detail.envTarget === "prod" ? " --prod" : "";
|
|
@@ -160,7 +202,7 @@ export function renderAdmissionTransportFailureLines(caught) {
|
|
|
160
202
|
);
|
|
161
203
|
if (detail.appName) lines.push(`App ID: ${detail.appName}`);
|
|
162
204
|
lines.push(detail.requestSent ? "Response: none received (network error)" : "Response: none (request not sent)");
|
|
163
|
-
lines.push(causeLine(detail));
|
|
205
|
+
lines.push(detail.invalidHeader ? invalidHeaderCauseLine(detail.invalidHeader) : causeLine(detail));
|
|
164
206
|
lines.push(`Request ID: ${detail.requestId ?? "none"}`);
|
|
165
207
|
lines.push("Correlation ID: none (no response from the Platform)");
|
|
166
208
|
const attempts = attemptsLine(detail);
|
|
@@ -169,8 +211,7 @@ export function renderAdmissionTransportFailureLines(caught) {
|
|
|
169
211
|
if (!detail.requestSent) {
|
|
170
212
|
lines.push("Database: NOT CHANGED (no request was sent)");
|
|
171
213
|
lines.push("Incumbent serving: PRESERVED (no request was sent)");
|
|
172
|
-
lines.push(
|
|
173
|
-
lines.push("Next: check the Platform URL in your CLI login/configuration, then rerun the same deploy command.");
|
|
214
|
+
lines.push(...notSentNextLines(detail.invalidHeader));
|
|
174
215
|
return lines;
|
|
175
216
|
}
|
|
176
217
|
|
|
@@ -183,11 +224,21 @@ export function renderAdmissionTransportFailureLines(caught) {
|
|
|
183
224
|
`Next: gencow deploy status${prodFlag} (shows the app status and last deployed time; a deployment from this attempt may or may not appear)`,
|
|
184
225
|
);
|
|
185
226
|
if (detail.requestId) {
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
);
|
|
227
|
+
const resume =
|
|
228
|
+
typeof resumeCommand === "string" && resumeCommand ? resumeCommand : `gencow deploy --resume ${detail.requestId}${prodFlag}`;
|
|
229
|
+
lines.push(`Then: if no deployment from this attempt appears, rerun with the same request ID: ${resume}`);
|
|
189
230
|
} else {
|
|
190
231
|
lines.push("Then: if no deployment from this attempt appears, rerun the same deploy command. Do not rerun first.");
|
|
191
232
|
}
|
|
192
233
|
return lines;
|
|
193
234
|
}
|
|
235
|
+
|
|
236
|
+
// Prints the typed rendering through the caller's output functions. Returns false (and prints
|
|
237
|
+
// nothing) when `caught` is not a typed transport failure, so the caller can use its own fallback.
|
|
238
|
+
export function reportAdmissionTransportFailure(caught, { resumeCommand = null, errorImpl, infoImpl }) {
|
|
239
|
+
if (!isAdmissionTransportFailure(caught)) return false;
|
|
240
|
+
const [headline, ...details] = renderAdmissionTransportFailureLines(caught, { resumeCommand });
|
|
241
|
+
errorImpl(headline);
|
|
242
|
+
for (const line of details) infoImpl(line);
|
|
243
|
+
return true;
|
|
244
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// Request headers that tell the Platform which local directory a deploy came from.
|
|
2
|
+
//
|
|
3
|
+
// An HTTP header value cannot carry characters outside Latin-1, so a directory such as
|
|
4
|
+
// /Users/홍길동/app makes fetch reject the request before anything is sent. A directory that
|
|
5
|
+
// is plain printable ASCII keeps the original header, which every Platform version reads.
|
|
6
|
+
// Any other directory is sent percent-encoded (UTF-8) in a separate header: a Platform that
|
|
7
|
+
// predates it ignores the header and records no directory, and the deploy still runs.
|
|
8
|
+
|
|
9
|
+
const PLAIN_HEADER = "X-Deploy-Local-Dir";
|
|
10
|
+
const ENCODED_HEADER = "X-Deploy-Local-Dir-Encoded";
|
|
11
|
+
// Printable ASCII with no leading or trailing space (a header value is trimmed in transit).
|
|
12
|
+
const PLAIN_SAFE_VALUE = /^[\x21-\x7e](?:[\x20-\x7e]*[\x21-\x7e])?$/u;
|
|
13
|
+
|
|
14
|
+
export function deployLocalDirHeaders(localDir) {
|
|
15
|
+
if (typeof localDir !== "string" || localDir.length === 0) return {};
|
|
16
|
+
if (PLAIN_SAFE_VALUE.test(localDir)) return { [PLAIN_HEADER]: localDir };
|
|
17
|
+
try {
|
|
18
|
+
return { [ENCODED_HEADER]: encodeURIComponent(localDir) };
|
|
19
|
+
} catch {
|
|
20
|
+
// A lone surrogate cannot be encoded. The directory is display metadata, so it is left out.
|
|
21
|
+
return {};
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -28,6 +28,7 @@ import { credentialEnvNameOf, renderDeployFailureDiagnosticLines } from "./deplo
|
|
|
28
28
|
import { readJsonObjectResponse } from "./http-response-json.mjs";
|
|
29
29
|
import { createDeploymentProgressObservers, pollAcceptedDeploymentOperation } from "./deployment-operation-poll.mjs";
|
|
30
30
|
import { postDeploymentAdmissionWithTimeout } from "./deploy-admission-boundary.mjs";
|
|
31
|
+
import { deployLocalDirHeaders } from "./deploy-local-dir-header.mjs";
|
|
31
32
|
import { submitDeploymentWithIdempotentRetry } from "./deployment-admission-retry.mjs";
|
|
32
33
|
import * as deployReceiptStore from "./deploy-receipt-store.mjs";
|
|
33
34
|
import { CYAN, DIM, RED, RESET, YELLOW, error, info, log, success, warn } from "./output.mjs";
|
|
@@ -562,7 +563,7 @@ export function createDeployPackageRuntime({
|
|
|
562
563
|
method: "POST",
|
|
563
564
|
headers: {
|
|
564
565
|
"Content-Type": "application/octet-stream",
|
|
565
|
-
|
|
566
|
+
...deployLocalDirHeaders(cwd),
|
|
566
567
|
...(activeReleaseAttemptId
|
|
567
568
|
? {
|
|
568
569
|
"X-Gencow-Release-Attempt-Id": activeReleaseAttemptId,
|
|
@@ -34,6 +34,7 @@ import {
|
|
|
34
34
|
import { buildClientUserFixableDiagnostic } from "./migration-client-diagnostic.mjs";
|
|
35
35
|
import { metadataErrorDetails } from "./metadata-diagnostic.mjs";
|
|
36
36
|
import { formatCommandError } from "./cli-command-runner.mjs";
|
|
37
|
+
import { deployLocalDirHeaders } from "./deploy-local-dir-header.mjs";
|
|
37
38
|
|
|
38
39
|
export function resolveDevCloudAppName({
|
|
39
40
|
cloudArgs,
|
|
@@ -316,7 +317,7 @@ export function createDevCloudCommand(deps) {
|
|
|
316
317
|
method: "POST",
|
|
317
318
|
body: form,
|
|
318
319
|
headers: {
|
|
319
|
-
|
|
320
|
+
...deployLocalDirHeaders(projectDir),
|
|
320
321
|
...protocolHeaders,
|
|
321
322
|
},
|
|
322
323
|
});
|
package/lib/platform-client.mjs
CHANGED
|
@@ -102,17 +102,45 @@ export function requireCreds({ throwOnMissing = false } = {}) {
|
|
|
102
102
|
return creds;
|
|
103
103
|
}
|
|
104
104
|
|
|
105
|
+
export const REQUEST_HEADER_INVALID_CODE = "CLI_REQUEST_HEADER_INVALID";
|
|
106
|
+
|
|
107
|
+
// fetch rejects a header value it cannot encode before any network I/O, with a runtime-specific
|
|
108
|
+
// TypeError that looks like a network failure to callers. Checking here gives one stable code and
|
|
109
|
+
// the header name. The value is never included: it can be a credential.
|
|
110
|
+
function assertSendableRequestHeaders(headers) {
|
|
111
|
+
try {
|
|
112
|
+
new Headers(headers);
|
|
113
|
+
return;
|
|
114
|
+
} catch {
|
|
115
|
+
// Fall through to name the header.
|
|
116
|
+
}
|
|
117
|
+
const headerName =
|
|
118
|
+
Object.entries(headers).find(([name, value]) => {
|
|
119
|
+
try {
|
|
120
|
+
new Headers([[name, value]]);
|
|
121
|
+
return false;
|
|
122
|
+
} catch {
|
|
123
|
+
return true;
|
|
124
|
+
}
|
|
125
|
+
})?.[0] ?? null;
|
|
126
|
+
const error = new Error(
|
|
127
|
+
`${REQUEST_HEADER_INVALID_CODE}: the request was not sent because the ${headerName ?? "request"} header value cannot be sent over HTTP.`,
|
|
128
|
+
);
|
|
129
|
+
error.code = REQUEST_HEADER_INVALID_CODE;
|
|
130
|
+
error.headerName = headerName;
|
|
131
|
+
throw error;
|
|
132
|
+
}
|
|
133
|
+
|
|
105
134
|
export async function platformFetch(creds, path, opts = {}) {
|
|
106
135
|
const url = `${creds.platformUrl}${path}`;
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
});
|
|
136
|
+
const headers = {
|
|
137
|
+
Authorization: `Bearer ${creds.apiKey}`,
|
|
138
|
+
Origin: creds.platformUrl,
|
|
139
|
+
...opts.headers,
|
|
140
|
+
"X-Gencow-CLI-Capabilities": CLI_CAPABILITIES,
|
|
141
|
+
};
|
|
142
|
+
assertSendableRequestHeaders(headers);
|
|
143
|
+
return fetch(url, { ...opts, headers });
|
|
116
144
|
}
|
|
117
145
|
|
|
118
146
|
function safePlatformCorrelationId(value) {
|
|
@@ -25,6 +25,8 @@ import { renderDeployFailureDiagnosticLines } from "./deploy-failure-diagnostic.
|
|
|
25
25
|
import { credentialEnvNameOf } from "./prod-create-auth-diagnostic.mjs";
|
|
26
26
|
import { writeProjectMetadata } from "./deploy-project-metadata.mjs";
|
|
27
27
|
import { postDeploymentAdmissionWithTimeout } from "./deploy-admission-boundary.mjs";
|
|
28
|
+
import { deployLocalDirHeaders } from "./deploy-local-dir-header.mjs";
|
|
29
|
+
import { recordAdmissionTransportAttempts, reportAdmissionTransportFailure } from "./deploy-admission-transport-failure.mjs";
|
|
28
30
|
import { installLocalDeployInterruptGuard } from "./local-deploy-interrupt-guard.mjs";
|
|
29
31
|
import {
|
|
30
32
|
loadStaticDeployReceipt,
|
|
@@ -66,7 +68,10 @@ export async function postStaticDeployWithTransientProxyRetry({
|
|
|
66
68
|
// release attempt). Replaying it is admission observation, not a new
|
|
67
69
|
// static deployment. Keep this bounded; the final transport error is
|
|
68
70
|
// still reported to the caller without inventing a terminal outcome.
|
|
69
|
-
if (attempt >= retryDelaysMs.length)
|
|
71
|
+
if (attempt >= retryDelaysMs.length) {
|
|
72
|
+
recordAdmissionTransportAttempts(error, attempt + 1);
|
|
73
|
+
throw error;
|
|
74
|
+
}
|
|
70
75
|
await delayImpl(retryDelaysMs[attempt]);
|
|
71
76
|
continue;
|
|
72
77
|
}
|
|
@@ -593,6 +598,7 @@ export function createStaticDeployRuntime({
|
|
|
593
598
|
infoImpl("Deploying static files...");
|
|
594
599
|
let deployRes;
|
|
595
600
|
let acceptedServerOperation = false;
|
|
601
|
+
const staticResumeCommand = `gencow deploy --static${opts.envTarget === "prod" ? " --prod" : ""} --app ${appId}${opts.clientName ? ` --client ${opts.clientName}` : ""} --resume ${deployClaim.claim.requestId}`;
|
|
596
602
|
try {
|
|
597
603
|
deployRes = await postStaticDeployWithTransientProxyRetry({
|
|
598
604
|
send: () =>
|
|
@@ -602,13 +608,13 @@ export function createStaticDeployRuntime({
|
|
|
602
608
|
envTarget: opts.envTarget || "dev",
|
|
603
609
|
// Resume static admission directly; fullstack flow skips the
|
|
604
610
|
// already-completed backend component for this scoped receipt.
|
|
605
|
-
resumeCommand:
|
|
611
|
+
resumeCommand: staticResumeCommand,
|
|
606
612
|
send: ({ signal }) =>
|
|
607
613
|
platformFetchImpl(creds, `/platform/apps/${appId}/deploy-static`, {
|
|
608
614
|
method: "POST",
|
|
609
615
|
headers: {
|
|
610
616
|
"Content-Type": "application/octet-stream",
|
|
611
|
-
|
|
617
|
+
...deployLocalDirHeaders(cwd),
|
|
612
618
|
"X-Gencow-Deploy-Claim": deployClaim.header,
|
|
613
619
|
"X-Gencow-Deploy-Protocol": "1",
|
|
614
620
|
"X-Gencow-CLI-Version": deployClaim.claim.generatedBy.version,
|
|
@@ -636,7 +642,7 @@ export function createStaticDeployRuntime({
|
|
|
636
642
|
setTimeoutImpl,
|
|
637
643
|
});
|
|
638
644
|
}
|
|
639
|
-
} catch {
|
|
645
|
+
} catch (caught) {
|
|
640
646
|
// Without a response, the accepted operation may already exist. Do not let
|
|
641
647
|
// this observer infer a terminal result; retain the same claim/attempt so its
|
|
642
648
|
// owner can converge without duplicate work.
|
|
@@ -645,8 +651,11 @@ export function createStaticDeployRuntime({
|
|
|
645
651
|
} catch {
|
|
646
652
|
/* ignore */
|
|
647
653
|
}
|
|
648
|
-
|
|
649
|
-
|
|
654
|
+
// Show the typed transport diagnosis (cause, attempts, state impact, exact next command).
|
|
655
|
+
if (!reportAdmissionTransportFailure(caught, { resumeCommand: staticResumeCommand, errorImpl, infoImpl })) {
|
|
656
|
+
errorImpl("Static deployment admission is temporarily unavailable. Retry the same command.");
|
|
657
|
+
infoImpl("Code: PLATFORM_DEPLOYMENT_ADMISSION_UNAVAILABLE");
|
|
658
|
+
}
|
|
650
659
|
exitImpl(1);
|
|
651
660
|
return;
|
|
652
661
|
}
|
|
@@ -666,6 +675,7 @@ export function createStaticDeployRuntime({
|
|
|
666
675
|
) {
|
|
667
676
|
errorImpl("Static deploy status is unknown. The same server request may already be running.");
|
|
668
677
|
infoImpl("Code: PLATFORM_DEPLOYMENT_ADMISSION_UNAVAILABLE");
|
|
678
|
+
infoImpl(`Response: HTTP ${deployRes.status} from the network edge, without a Platform diagnostic body`);
|
|
669
679
|
infoImpl("Retry the same gencow static command from this app workspace.");
|
|
670
680
|
exitImpl(1);
|
|
671
681
|
return;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "gencow",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.297",
|
|
4
4
|
"description": "Gencow — AI Backend Engine",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -40,11 +40,11 @@
|
|
|
40
40
|
"ai": "^6.0.326",
|
|
41
41
|
"better-auth": "1.7.11",
|
|
42
42
|
"postgres": "^3.4.9",
|
|
43
|
-
"@gencow/client": "0.2.9",
|
|
44
|
-
"@gencow/server": "0.1.3",
|
|
45
|
-
"@gencow/react": "0.2.9",
|
|
46
43
|
"@gencow/core": "0.1.48",
|
|
47
|
-
"@gencow/
|
|
44
|
+
"@gencow/react": "0.2.9",
|
|
45
|
+
"@gencow/server": "0.1.3",
|
|
46
|
+
"@gencow/shared": "0.0.0",
|
|
47
|
+
"@gencow/client": "0.2.9"
|
|
48
48
|
},
|
|
49
49
|
"scripts": {
|
|
50
50
|
"build": "node scripts/bundle-core.mjs && node scripts/bundle-shared.mjs && node scripts/bundle-server.mjs",
|
package/runtime/server.mjs
CHANGED
|
@@ -12390,7 +12390,7 @@ CREATE INDEX IF NOT EXISTS idx_gencow_realtime_outbox_pending
|
|
|
12390
12390
|
AND doomed.observer_id = expired.observer_id
|
|
12391
12391
|
AND doomed.observation_complete = TRUE
|
|
12392
12392
|
AND doomed.lease_expires_at <= NOW() - ($2::DOUBLE PRECISION * INTERVAL '1 millisecond')
|
|
12393
|
-
RETURNING doomed.app_id`,[input2.nodeId,retentionMs,batch]);return deletedCount(result3)}function startRuntimeActivityObserverReaper(params){const logger3=params.logger??console;let running=false;const runOnce=async()=>{if(running)return 0;running=true;let total=0;try{for(;;){const deleted=await reapExpiredRuntimeActivityObservers(params.rawSql,{nodeId:params.nodeId});total+=deleted;if(deleted<RUNTIME_ACTIVITY_OBSERVER_REAP_BATCH)break}return total}catch(error62){logger3.warn(`[runtime-activity] observer reap deferred: ${error62 instanceof Error?error62.message:String(error62)}`);return total}finally{running=false}};const interval=params.intervalMs??RUNTIME_ACTIVITY_OBSERVER_REAP_INTERVAL_MS;if(interval>0){const timer2=(params.setIntervalImpl??setInterval)(()=>void runOnce(),interval);timer2?.unref?.()}return{runOnce}}var RUNTIME_ACTIVITY_OBSERVER_REAP_RETENTION_MS,RUNTIME_ACTIVITY_OBSERVER_REAP_INTERVAL_MS,RUNTIME_ACTIVITY_OBSERVER_REAP_BATCH;var init_server_runtime_activity_observer_reaper=__esm({"../server/dist/server-runtime-activity-observer-reaper.js"(){"use strict";RUNTIME_ACTIVITY_OBSERVER_REAP_RETENTION_MS=10*6e4;RUNTIME_ACTIVITY_OBSERVER_REAP_INTERVAL_MS=5*6e4;RUNTIME_ACTIVITY_OBSERVER_REAP_BATCH=500}});function activitySyncPreservationReason(error62){const code=error62 instanceof Error?error62.message:"";if(code==="RUNTIME_ACTIVITY_CHECKPOINT_MISSING"){return"runtime_activity_checkpoint_missing"}if(code==="RUNTIME_ACTIVITY_CHECKPOINT_NOT_CURRENT"){return"runtime_activity_checkpoint_not_current"}if(code==="RUNTIME_ACTIVITY_BINDING_CONVERGENCE_TIMEOUT"){return"runtime_activity_binding_sync_timeout"}return"runtime_activity_binding_sync_failed"}async function executeRuntimeIdleCertificationWithActivityBinding(params){const requestedTimeoutMs=params.activitySyncTimeoutMs??RUNTIME_IDLE_CERTIFICATION_ACTIVITY_SYNC_TIMEOUT_MS;const timeoutMs=Number.isFinite(requestedTimeoutMs)?Math.max(1,Math.min(requestedTimeoutMs,RUNTIME_IDLE_CERTIFICATION_ACTIVITY_SYNC_TIMEOUT_MS)):RUNTIME_IDLE_CERTIFICATION_ACTIVITY_SYNC_TIMEOUT_MS;const synchronization=params.activity.synchronizeRuntimeBinding(params.request.appId,params.request.appName,{timeoutMs}).then(()=>({status:"ready"}),error62=>({status:"failed",error:error62}));let timeout;const outcome2=await Promise.race([synchronization,new Promise(resolveTimeout=>{timeout=setTimeout(()=>resolveTimeout({status:"timeout"}),timeoutMs)})]);if(timeout)clearTimeout(timeout);if(outcome2.status==="timeout"){return{kind:"preserved",reason:"runtime_activity_binding_sync_timeout"}}if(outcome2.status==="failed"){return{kind:"preserved",reason:activitySyncPreservationReason(outcome2.error)}}return params.executeScaleDown()}var RUNTIME_IDLE_CERTIFICATION_ACTIVITY_SYNC_TIMEOUT_MS;var init_server_runtime_idle_certification_control=__esm({"../server/dist/server-runtime-idle-certification-control.js"(){"use strict";RUNTIME_IDLE_CERTIFICATION_ACTIVITY_SYNC_TIMEOUT_MS=2e3}});import{resolve as resolve168}from"node:path";function runtimeActivityFencedTombstoneMs(env){const parsed=Number(env.GENCOW_RUNTIME_ACTIVITY_FENCED_TOMBSTONE_MS);return Number.isFinite(parsed)&&env.GENCOW_RUNTIME_ACTIVITY_FENCED_TOMBSTONE_MS?.trim()?Math.min(36e5,Math.max(6e4,Math.trunc(parsed))):void 0}async function bootstrapRuntimeLifecycleControl(params){const logger3=params.logger??console;const runtimeNodeId=params.currentNodeId??"node-1";const sleepConfig=loadSleepMaintenanceConfig({env:process.env});const runtimeActivity=createRuntimeActivityTracker({rawSql:params.rawSql,nodeId:runtimeNodeId,idleTimeoutMs:sleepConfig.sleepTimeoutMinutes*6e4,setIntervalImpl:params.setIntervalImpl,logger:logger3,fencedTombstoneMs:runtimeActivityFencedTombstoneMs(process.env),onDrainStateQuery:params.onDrainStateQuery});void startRuntimeActivityObserverReaper({rawSql:params.rawSql,nodeId:runtimeNodeId,setIntervalImpl:params.setIntervalImpl,logger:logger3}).runOnce();const{configureRuntimeLifecycleActivityCoordinator}=await import(resolve168(params.functionsPath,"../src/runtime-lifecycle-activity-coordinator.ts"));configureRuntimeLifecycleActivityCoordinator(runtimeActivity);configureRuntimeActivityObserver(({appId,appName})=>{runtimeActivity.recordExternalActivity(appId,appName);void runtimeActivity.flush(appId).catch(error62=>{logger3.warn(`[runtime-activity] websocket checkpoint deferred: ${error62 instanceof Error?error62.message:String(error62)}`)})});const{apps:apps5,appRuntimeActivityState:appRuntimeActivityState2,appRuntimeDesiredState:appRuntimeDesiredState3}=await import(resolve168(params.functionsPath,"schema.ts"));const{and:and147,eq:eq163}=await import("drizzle-orm");const{executeAutomaticScaleDown}=await import(resolve168(params.functionsPath,"../src/runtime-auto-scale-down.ts"));const{RUNTIME_PROD_IDLE_CERTIFICATION_CONFIRMATION:RUNTIME_PROD_IDLE_CERTIFICATION_CONFIRMATION2,RUNTIME_QC_IDLE_CERTIFICATION_CONFIRMATION:RUNTIME_QC_IDLE_CERTIFICATION_CONFIRMATION2,runtimeIdleCertificationControllerId:runtimeIdleCertificationControllerId3}=await import(resolve168(params.functionsPath,"../src/runtime-scale-down-store.ts"));const{isActivePlatformControllerSlot}=await import(resolve168(params.functionsPath,"platform-slot-guard.ts"));const controllerEnv={GENCOW_NODE_ID:runtimeNodeId,PORT:params.currentPlatformPort?.trim()||process.env.PORT?.trim()};const isActiveController=params.isActiveController??(()=>isActivePlatformControllerSlot({db:params.db},controllerEnv));const assertActiveController=params.assertActiveController??(tx=>isActivePlatformControllerSlot({db:tx},controllerEnv,{lockForUpdate:true}));const fetchAppStatuses=async()=>await params.db.select({id:apps5.id,name:apps5.name,status:apps5.status,hasBackend:apps5.hasBackend,parentAppId:apps5.parentAppId,nodeId:apps5.nodeId,authorityMode:appRuntimeDesiredState3.authorityMode,lastUserActivityAt:appRuntimeActivityState2.lastUserActivityAt}).from(apps5).leftJoin(appRuntimeDesiredState3,eq163(appRuntimeDesiredState3.appId,apps5.id)).leftJoin(appRuntimeActivityState2,eq163(appRuntimeActivityState2.appId,apps5.id));const refreshRuntimeActivityBindings=async appRows=>{for(const app2 of appRows??await fetchAppStatuses()){if(app2.status!=="running"||!app2.hasBackend||(app2.nodeId?.trim()||"node-1")!==runtimeNodeId){continue}try{await runtimeActivity.hydrateRuntime(app2.id,app2.name)}catch(error62){logger3.warn(`[runtime-activity] binding checkpoint preserved for retry: ${error62 instanceof Error?error62.message:String(error62)}`)}}};let initialActivityHydration;const startActivityHydrationAfterListen=()=>initialActivityHydration??=refreshRuntimeActivityBindings().catch(()=>{logger3.warn("[runtime-activity] initial binding hydration deferred; maintenance refresh will retry")});const requestAutomaticScaleDown=async candidate=>{if(!candidate.appId)return{kind:"preserved",reason:"app_identity_missing"};if(!await isActiveController()){return{kind:"skipped",reason:"controller_slot_inactive"}}if(candidate.reason==="ghost_idle"){return{kind:"remediation",reason:"idle_projection_has_runtime"}}return executeAutomaticScaleDown({db:params.db,appId:candidate.appId,appName:candidate.appName,currentNodeId:runtimeNodeId,trigger:candidate.trigger,activity:runtimeActivity,isControllerActive:isActiveController,assertControllerActive:assertActiveController,removeRuntimeRoute:params.removeRuntimeRoute})};const requestRuntimeIdleCertification=async request=>{if(!Number.isSafeInteger(request.appId)||request.appId<=0||typeof request.appName!=="string"||request.appName.trim()===""||request.appName.length>128||!Number.isSafeInteger(request.expectedRolloutRevision)||request.expectedRolloutRevision<=0||![RUNTIME_PROD_IDLE_CERTIFICATION_CONFIRMATION2,RUNTIME_QC_IDLE_CERTIFICATION_CONFIRMATION2].includes(request.confirmation)){return{kind:"skipped",reason:"idle_certification_invalid"}}if(!await isActiveController()){return{kind:"skipped",reason:"controller_slot_inactive"}}const appRows=await params.db.select({id:apps5.id,name:apps5.name}).from(apps5).where(and147(eq163(apps5.id,request.appId),eq163(apps5.name,request.appName))).limit(1);if(!appRows[0]){return{kind:"preserved",reason:"app_identity_changed"}}const certificationRequest={...request,appId:appRows[0].id,appName:appRows[0].name,scope:request.confirmation===RUNTIME_PROD_IDLE_CERTIFICATION_CONFIRMATION2?"prod":"qc"};return executeRuntimeIdleCertificationWithActivityBinding({request:certificationRequest,activity:runtimeActivity,executeScaleDown:()=>executeAutomaticScaleDown({db:params.db,appId:certificationRequest.appId,appName:certificationRequest.appName,currentNodeId:runtimeNodeId,trigger:"idle_timeout",controllerId:runtimeIdleCertificationControllerId3(certificationRequest.scope,certificationRequest.appId),productionIdleCertification:certificationRequest,activity:runtimeActivity,isControllerActive:isActiveController,assertControllerActive:assertActiveController,removeRuntimeRoute:params.removeRuntimeRoute})})};return{runtimeActivity,fetchAppStatuses,refreshRuntimeActivityBindings,startActivityHydrationAfterListen,requestAutomaticScaleDown,requestRuntimeIdleCertification,runtimeIdleCertificationConfirmation:RUNTIME_PROD_IDLE_CERTIFICATION_CONFIRMATION2,runtimeIdleCertificationConfirmations:[RUNTIME_PROD_IDLE_CERTIFICATION_CONFIRMATION2,RUNTIME_QC_IDLE_CERTIFICATION_CONFIRMATION2]}}var init_server_runtime_lifecycle_control=__esm({"../server/dist/server-runtime-lifecycle-control.js"(){"use strict";init_server_platform_maintenance();init_server_runtime_activity();init_server_runtime_activity_observer_reaper();init_server_runtime_idle_certification_control();init_ws_gateway2()}});import{resolve as resolve169}from"path";async function bootstrapPlatformIdleWake(input2){const{params,platformNodeId,isActiveLifecycleController,removeAppPortIfEquals:removeAppPortIfEquals2}=input2;const lifecycle=await bootstrapRuntimeLifecycleControl({functionsPath:params.functionsPath,db:params.db,rawSql:params.rawSql,currentNodeId:platformNodeId,currentPlatformPort:process.env.PORT?.trim()||null,isActiveController:isActiveLifecycleController,removeRuntimeRoute:(appName,expectedPort)=>{if(Number.isInteger(expectedPort)&&Number(expectedPort)>0){removeAppPortIfEquals2(appName,Number(expectedPort))}},setIntervalImpl:params.setIntervalImpl,logger:params.logger,onDrainStateQuery:()=>recordServingPlanePlatformDbQuery("runtime_drain_state")});return{...lifecycle,registerIdleWakeRoutes:async()=>{registerRuntimeIdleCertificationRoute({app:params.app,maintenanceToken:resolvePlatformMaintenanceToken(params.platformMaintenanceEnv??process.env),confirmationValue:lifecycle.runtimeIdleCertificationConfirmations,requestRuntimeIdleCertification:lifecycle.requestRuntimeIdleCertification,logger:params.logger});const{registerRuntimeDurableWakeRoute}=await import(resolve169(params.functionsPath,"../src/runtime-durable-wake-route.ts"));registerRuntimeDurableWakeRoute({app:params.app,getDb:()=>params.db,env:process.env,logger:params.logger});const{registerRuntimeRouteActivityRoute}=await import(resolve169(params.functionsPath,"../src/runtime-route-activity-route.ts"));registerRuntimeRouteActivityRoute({app:params.app,getDb:()=>params.db,nodeId:platformNodeId||"node-1",activity:lifecycle.runtimeActivity,env:process.env,logger:params.logger})}}}var init_server_platform_idle_wake_bootstrap=__esm({"../server/dist/server-platform-idle-wake-bootstrap.js"(){"use strict";init_server_runtime_idle_certification();init_server_runtime_lifecycle_control();init_server_serving_plane_dependency_metrics();init_server_platform_maintenance_http()}});import{resolve as resolve170}from"path";async function initializePlatformRuntimeGenerationForServer(functionsPath){const{initializePlatformCurrentRuntimeGeneration}=await import(resolve170(functionsPath,"../src/current-runtime-generation.ts"));initializePlatformCurrentRuntimeGeneration({repoRoot:resolve170(functionsPath,"../../..")})}var init_server_platform_runtime_generation_bootstrap=__esm({"../server/dist/server-platform-runtime-generation-bootstrap.js"(){"use strict"}});function readPositiveIntEnv3(name2,fallback){const value2=Number(process.env[name2]);return Number.isFinite(value2)&&value2>0?Math.floor(value2):fallback}function nowMs(){return globalThis.performance?.now?.()??Date.now()}function toMB(bytes2){return typeof bytes2==="number"?Math.round(bytes2/1024/1024*10)/10:null}function addLagSample(valueMs){lagSamplesMs.push(Math.max(0,Math.round(valueMs*10)/10));if(lagSamplesMs.length>windowSize){lagSamplesMs=lagSamplesMs.slice(lagSamplesMs.length-windowSize)}}function summarizeMs(values2){if(values2.length===0){return{count:0,p50Ms:null,p95Ms:null,maxMs:null,lastMs:null}}const sorted=[...values2].sort((a,b5)=>a-b5);const percentile=pct=>{const index28=Math.max(0,Math.min(sorted.length-1,Math.floor((sorted.length-1)*pct/100)));return sorted[index28]};return{count:values2.length,p50Ms:percentile(50),p95Ms:percentile(95),maxMs:sorted[sorted.length-1],lastMs:values2[values2.length-1]}}function observeEventLoopLagForTests(currentTimeMs){if(lastTickAtMs===0){lastTickAtMs=currentTimeMs;return null}const lagMs=currentTimeMs-lastTickAtMs-sampleIntervalMs;lastTickAtMs=currentTimeMs;addLagSample(lagMs);return Math.max(0,lagMs)}function observeEventLoopLag(){observeEventLoopLagForTests(nowMs())}function startRuntimeMetricsSampler(options={}){if(timer)return;sampleIntervalMs=options.intervalMs??sampleIntervalMs;windowSize=options.maxSamples??windowSize;lastTickAtMs=nowMs();timer=setInterval(observeEventLoopLag,sampleIntervalMs);timer.unref?.()}function getRuntimeMetricsSnapshot(){const memoryUsage=typeof process!=="undefined"&&process.memoryUsage?process.memoryUsage():void 0;const uptimeSec=typeof process!=="undefined"&&typeof process.uptime==="function"?process.uptime():null;const eventLoopSummary=summarizeMs(lagSamplesMs);return{timestamp:new Date().toISOString(),uptimeSec:uptimeSec===null?null:Math.round(uptimeSec),memory:{rssMB:toMB(memoryUsage?.rss),heapUsedMB:toMB(memoryUsage?.heapUsed),heapTotalMB:toMB(memoryUsage?.heapTotal),externalMB:toMB(memoryUsage?.external)},eventLoopLag:{...eventLoopSummary,sampleIntervalMs,windowSize}}}function resetRuntimeMetricsForTests(options={}){if(timer){clearInterval(timer);timer=null}sampleIntervalMs=options.intervalMs??DEFAULT_SAMPLE_INTERVAL_MS;windowSize=options.maxSamples??DEFAULT_WINDOW_SIZE;lagSamplesMs=[];lastTickAtMs=0}var DEFAULT_SAMPLE_INTERVAL_MS,DEFAULT_WINDOW_SIZE,sampleIntervalMs,windowSize,lagSamplesMs,lastTickAtMs,timer;var init_runtime_metrics=__esm({"../platform/src/runtime-metrics.ts"(){"use strict";DEFAULT_SAMPLE_INTERVAL_MS=1e3;DEFAULT_WINDOW_SIZE=300;sampleIntervalMs=readPositiveIntEnv3("GENCOW_RUNTIME_METRICS_INTERVAL_MS",DEFAULT_SAMPLE_INTERVAL_MS);windowSize=readPositiveIntEnv3("GENCOW_RUNTIME_METRICS_WINDOW_SIZE",DEFAULT_WINDOW_SIZE);lagSamplesMs=[];lastTickAtMs=0;timer=null}});var runtime_metrics_exports={};__export(runtime_metrics_exports,{getRuntimeMetricsSnapshot:()=>getRuntimeMetricsSnapshot,observeEventLoopLagForTests:()=>observeEventLoopLagForTests,resetRuntimeMetricsForTests:()=>resetRuntimeMetricsForTests,startRuntimeMetricsSampler:()=>startRuntimeMetricsSampler,summarizeMs:()=>summarizeMs});var init_runtime_metrics2=__esm({"../server/dist/runtime-metrics.js"(){"use strict";init_runtime_metrics()}});var server_platform_runtime_bootstrap_exports={};__export(server_platform_runtime_bootstrap_exports,{bootstrapPlatformRuntime:()=>bootstrapPlatformRuntime,createPlatformActiveSlotWorkerCheck:()=>createPlatformActiveSlotWorkerCheck,createPlatformSubdomainRegex:()=>createPlatformSubdomainRegex,platformNodeProxyWsTunnel:()=>platformNodeProxyWsTunnel,platformWebsocketGateway:()=>platformWebsocketGateway,registerCapacityRoute:()=>registerCapacityRoute,registerPlatformInternalMiddleware:()=>registerPlatformInternalMiddleware,registerRealtimeNotifyRoute:()=>registerRealtimeNotifyRoute,registerRuntimeMetricsRoute:()=>registerRuntimeMetricsRoute,startGatewayRealtimeUsageMeteringForRuntime:()=>startGatewayRealtimeUsageMeteringForRuntime});import{resolve as resolve171}from"path";function registerRealtimeNotifyRoute(params){const logger3=params.logger??console;params.app.post("/internal/realtime-notify",async c2=>{try{const body=await c2.req.json();if(!body.type){return c2.json({error:"type required"},400)}const auth=await params.gateway.authorizeRealtimeNotifyRequest({appName:body.appName,token:c2.req.header("X-Internal-Token")||"",findAppByName:async appName=>{const rows8=await params.db.select({id:params.appsTable.id,name:params.appsTable.name}).from(params.appsTable).where(params.eqOp(params.appsTable.name,appName)).limit(1);return rows8[0]??null},generateInternalToken:params.generateInternalToken});if(!auth.ok){return c2.json({error:auth.error},auth.status)}const rateLimit2=params.gateway.consumeRealtimeNotifyRateLimit?.(auth.appName);if(rateLimit2&&!rateLimit2.ok){return c2.json({error:"Realtime notify rate limit exceeded",retryAfterMs:rateLimit2.retryAfterMs},429)}const forwarded=await forwardPlatformRealtimeNotify({appName:auth.appName,body,token:c2.req.header("X-Internal-Token")||"",logger:logger3});if(forwarded){const forwardedBody=await forwarded.json().catch(()=>({error:"Realtime gateway unavailable"}));return c2.json(forwardedBody,forwarded.status)}if(body.type==="emit"){if(typeof body.queryKey!=="string"||body.queryKey.length===0){return c2.json({error:"queryKey required"},400)}const sent=params.gateway.notifyEmit(auth.appName,body.queryKey,body.data);return c2.json({ok:true,sent})}if(body.type==="invalidate"){const queryKeys=typeof body.queryKey==="string"&&body.queryKey.length>0?[body.queryKey]:Array.isArray(body.queryKeys)&&body.queryKeys.every(key2=>typeof key2==="string"&&key2.length>0)?[...new Set(body.queryKeys)]:null;if(!queryKeys)return c2.json({error:"queryKey required"},400);const sent=params.gateway.notifyInvalidate(auth.appName,queryKeys);return c2.json({ok:true,sent})}if(body.type==="query_invalidate"){if(typeof body.query!=="string"||body.query.length===0){return c2.json({error:"query required"},400)}if(typeof body.subscriptionKey!=="string"||body.subscriptionKey.length===0){return c2.json({error:"subscriptionKey required"},400)}if(typeof body.scopeHash!=="string"||body.scopeHash.length===0||body.scopeHash.length>200){return c2.json({error:"scopeHash required"},400)}const eventId=typeof body.eventId==="string"&&body.eventId.length>0?body.eventId:void 0;const legacyQueryKey=normalizeOptionalPlatformRuntimeString(body.legacyQueryKey);if(legacyQueryKey===null){return c2.json({error:"legacyQueryKey must be a non-empty string"},400)}const crudRealtimeEmitMode=body.crudRealtimeEmitMode===void 0?void 0:body.crudRealtimeEmitMode==="legacy"||body.crudRealtimeEmitMode==="scoped"||body.crudRealtimeEmitMode==="dual"?body.crudRealtimeEmitMode:null;if(crudRealtimeEmitMode===null){return c2.json({error:"crudRealtimeEmitMode must be legacy, scoped, or dual"},400)}const sent=params.gateway.notifyQueryInvalidate(auth.appName,body.query,body.subscriptionKey,eventId,body.scopeHash,legacyQueryKey,crudRealtimeEmitMode);return c2.json({ok:true,sent})}if(body.type==="query_revoke"){if(typeof body.query!=="string"||body.query.length===0){return c2.json({error:"query required"},400)}if(typeof body.subscriptionKey!=="string"||body.subscriptionKey.length===0){return c2.json({error:"subscriptionKey required"},400)}if(typeof body.scopeHash!=="string"||body.scopeHash.length===0||body.scopeHash.length>200){return c2.json({error:"scopeHash required"},400)}const epoch=normalizeOptionalPlatformRuntimeString(body.epoch);const reason=normalizeOptionalPlatformRuntimeString(body.reason);if(epoch===null)return c2.json({error:"epoch must be a non-empty string"},400);if(reason===null)return c2.json({error:"reason must be a non-empty string"},400);const sent=params.gateway.notifyQueryRevoke(auth.appName,body.query,body.subscriptionKey,epoch,reason,body.scopeHash);return c2.json({ok:true,sent})}if(body.type==="channel_publish"){if(typeof body.channelKey!=="string"||body.channelKey.length===0){return c2.json({error:"channelKey required"},400)}const eventId=typeof body.eventId==="string"&&body.eventId.length>0?body.eventId:void 0;const sent=params.gateway.notifyChannelPublish(auth.appName,body.channelKey,body.data,eventId);return c2.json({ok:true,sent})}if(body.type==="channel_invalidate"){if(typeof body.channelKey!=="string"||body.channelKey.length===0){return c2.json({error:"channelKey required"},400)}const sent=params.gateway.notifyChannelInvalidate(auth.appName,body.channelKey);return c2.json({ok:true,sent})}if(body.type==="channel_revoke"){if(typeof body.channelKey!=="string"||body.channelKey.length===0){return c2.json({error:"channelKey required"},400)}const epoch=body.epoch===void 0||body.epoch===null?void 0:typeof body.epoch==="string"&&body.epoch.length>0&&body.epoch.length<=200?body.epoch:null;const reason=body.reason===void 0||body.reason===null?void 0:typeof body.reason==="string"&&body.reason.length>0&&body.reason.length<=200?body.reason:null;if(epoch===null)return c2.json({error:"epoch must be a non-empty string"},400);if(reason===null)return c2.json({error:"reason must be a non-empty string"},400);const sent=params.gateway.notifyChannelRevoke(auth.appName,body.channelKey,epoch,reason);return c2.json({ok:true,sent})}return c2.json({error:`Unknown type: ${body.type}`},400)}catch(error62){const message=error62 instanceof Error?error62.message:String(error62);logger3.error("[ws-gateway] notify error:",message);return c2.json({error:REALTIME_NOTIFY_INTERNAL_ERROR},500)}})}async function bootstrapPlatformRuntime(params){const logger3=params.logger??console;const timed=params.startupTiming??{step:(_name,operation)=>operation()};const fetchImpl=params.fetchImpl??fetch;const setIntervalImpl=params.setIntervalImpl??setInterval;const clearIntervalImpl=params.clearIntervalImpl??clearInterval;const setTimeoutImpl=params.setTimeoutImpl??setTimeout;const subdomainRegex=createPlatformSubdomainRegex(params.platformDomain);const{apps:appsTable,customDomainBindings:customDomainBindingsTable,platformNodes:platformNodes2}=await timed.step("platform:import-schema",()=>import(resolve171(params.functionsPath,"schema.ts")));const{eq:eqOp,and:andOp,inArray:inArrayOp,sql:sqlOp}=await timed.step("platform:import-drizzle",()=>import("drizzle-orm"));const{createProxyRequestReplayPlan}=await timed.step("platform:import-replay",()=>import(resolve171(params.functionsPath,"../src/proxy-request-replay.ts")));const{canonicalDeploymentPresentSql:canonicalDeploymentPresentSql2}=await timed.step("platform:import-deploy-admission",()=>import(resolve171(params.functionsPath,"../src/deploy-contract-admission.ts")));const{buildAppRuntimeUnavailableResult,buildPublicAppLookupDeferredResult,ensureAppRuntimeReady}=await timed.step("platform:import-app-recovery",()=>import(resolve171(params.functionsPath,"../src/app-runtime-recovery.ts")));const{createPublicRuntimeWakeCorrelation,executeLegacyRuntimeWakeByName,PUBLIC_RUNTIME_CONVERGENCE_TIMEOUT_MS:PUBLIC_RUNTIME_CONVERGENCE_TIMEOUT_MS2}=await timed.step("platform:import-lifecycle-adapter",()=>import(resolve171(params.functionsPath,"../src/simple-lifecycle/legacy-runtime-effect-adapter.ts")));await timed.step("platform:init-generation",()=>initializePlatformRuntimeGenerationForServer(params.functionsPath));const{getAppPort:getLivePort,setAppPort:setAppPort2,removeAppPort:removeAppPort2,removeAppPortIfEquals:removeAppPortIfEquals2,setAppMeta:setAppMeta2,setLastAccess:markLastAccess,hasLiveRuntimeProcess:hasLiveRuntimeProcess3,resolveLiveRuntimePort:resolveLiveRuntimePort3,reapWarmPoolStale:reapWarmPoolStale2,getWakeCapacitySnapshot:getWakeCapacitySnapshot2,setWakeCapacityMaxConcurrentRunning:setWakeCapacityMaxConcurrentRunning2,setWakeCapacityUpdateInProgress:setWakeCapacityUpdateInProgress2,generateInternalToken:generateInternalToken3,setDatabasePreflightRawSql:setDatabasePreflightRawSql2,setPlatformRuntimeDb:setPlatformRuntimeDb2,buildAppDatabaseUrl:buildAppDatabaseUrl2}=await timed.step("platform:import-provisioner",()=>loadPlatformProvisionerWithScheduledJobSigningSecret(()=>import(resolve171(params.functionsPath,"../src/provisioner.ts"))));setDatabasePreflightRawSql2(params.rawSql);wirePlatformDatabaseUrls(setPlatformRuntimeDb2,params.db,params.databaseUrlResolvers);const storageDirectRuntime=await timed.step("platform:storage-direct",()=>createPlatformStorageDirectRuntime(params.functionsPath,buildAppDatabaseUrl2));const{getRuntimeMetricsSnapshot:getRuntimeMetricsSnapshot2,startRuntimeMetricsSampler:startRuntimeMetricsSampler2}=await Promise.resolve().then(()=>(init_runtime_metrics2(),runtime_metrics_exports));const platformNodeId=process.env.GENCOW_NODE_ID?.trim()||null;const isActiveLifecycleController=createPlatformActiveWorkerCheck({rawSql:params.rawSql,nodeId:platformNodeId,logger:logger3});const{runtimeActivity,fetchAppStatuses,refreshRuntimeActivityBindings,startActivityHydrationAfterListen,requestAutomaticScaleDown,registerIdleWakeRoutes}=await timed.step("platform:idle-wake",()=>bootstrapPlatformIdleWake({params:{...params,setIntervalImpl,logger:logger3},platformNodeId,isActiveLifecycleController,removeAppPortIfEquals:removeAppPortIfEquals2}));await timed.step("platform:lifecycle-api",()=>registerPackedPlatformLifecycleApi({...params,nodeId:platformNodeId??void 0,logger:logger3}));registerPlatformRuntimeInternalMiddleware(params.app,params.functionsPath);await timed.step("platform:idle-wake-routes",()=>registerIdleWakeRoutes());bootstrapLegacyRuntimeRecoveryRoute(params.app,params.db,appsTable,eqOp,params.functionsPath,platformNodeId||"node-1",process.env.GENCOW_INTERNAL_TOKEN||"",createPlatformActiveWorkerCheck({rawSql:params.rawSql,nodeId:platformNodeId,logger:logger3,uncached:true}),logger3);const nodeProxyKeyId=process.env.GENCOW_NODE_PROXY_KEY_ID?.trim()||null;const nodeProxySecret=process.env.GENCOW_NODE_PROXY_SECRET?.trim()||null;const nodeProxyEnabled=Boolean(platformNodeId&&nodeProxyKeyId&&nodeProxySecret);const nodeProxyHttpClient=nodeProxyEnabled?await timed.step("platform:import-node-proxy",()=>import(resolve171(params.functionsPath,"../src/node-proxy-http-client.ts"))):null;const nodeProxyInternalRoutes=nodeProxyEnabled?await timed.step("platform:import-node-routes",()=>import(resolve171(params.functionsPath,"../src/platform-internal-routes.ts"))):null;const nodeOpsPath=resolve171(params.functionsPath,"../src/platform-node-ops.ts");const nodeOpsRoutes=await timed.step("platform:import-node-ops",()=>import(nodeOpsPath).catch(()=>null));const routeProjectionRuntime=await timed.step("platform:route-projection",()=>bootstrapRuntimeRouteProjectionForPlatform({app:params.app,db:params.db,functionsPath:params.functionsPath,nodeId:platformNodeId||"node-1",getAppPort:getLivePort,setAppPort:setAppPort2,fetchImpl,logger:logger3,setIntervalImpl}));await timed.step("platform:analytics-ingest-route",()=>registerManagedAnalyticsIngestRoute(params.app,params.functionsPath,params.analyticsRawSql??params.rawSql,params.db,void 0,params.analyticsCatalogAuthority));await timed.step("platform:media-storage-bridge",()=>registerMediaWorkerStorageBridgeForRuntime(params,logger3));const[{createAppProxyRouteCache,resolveAppProxyRouteCacheConfig},{listInstalledAppRouteCacheTriggerNames}]=await timed.step("platform:import-app-route-cache",()=>Promise.all([import(resolve171(params.functionsPath,"../src/app-proxy-route-cache.ts")),import(resolve171(params.functionsPath,"../src/app-route-cache-invalidation-signal.ts"))]));const appRouteCache=createAppProxyRouteCache({async loadAppRow(appName){const rows8=await params.db.select({id:appsTable.id,instanceId:appsTable.instanceId,name:appsTable.name,port:appsTable.port,status:appsTable.status,statusReason:appsTable.statusReason,dataDir:appsTable.dataDir,staticDeployedAt:appsTable.staticDeployedAt,currentStaticGenerationRef:appsTable.currentStaticGenerationRef,hasBackend:appsTable.hasBackend,plan:appsTable.plan,customDomain:appsTable.customDomain,customDomainStatus:appsTable.customDomainStatus,nodeId:appsTable.nodeId,ownerAccountHold:appsTable.ownerAccountHold,ownerAccountHoldReason:appsTable.ownerAccountHoldReason,runtimeAuthorityMode:sqlOp`(SELECT desired.authority_mode FROM app_runtime_desired_state AS desired WHERE desired.app_id = ${appsTable.id} LIMIT 1)`,canonicalDeploymentPresent:canonicalDeploymentPresentSql2({currentDeploymentId:appsTable.currentDeployId,appId:appsTable.id})}).from(appsTable).where(eqOp(appsTable.name,appName));return rows8[0]??null},onLoad:()=>recordServingPlanePlatformDbQuery("app_catalog"),config:resolveAppProxyRouteCacheConfig(process.env),databaseUrl:(params.wakeSignalEnv??process.env).GENCOW_WAKE_SIGNAL_DATABASE_URL,listInstalledTriggerNames:()=>listInstalledAppRouteCacheTriggerNames(params.db)});const{createPlatformNodeRouteCache,resolvePlatformNodeRouteCacheConfig}=await timed.step("platform:import-node-route-cache",()=>import(resolve171(params.functionsPath,"../src/platform-node-route-cache.ts")));const platformNodeRouteCache=nodeProxyEnabled&&platformNodes2?createPlatformNodeRouteCache({async loadNode(nodeId){const rows8=await params.db.select({id:platformNodes2.id,status:platformNodes2.status,internalOrigin:platformNodes2.internalOrigin,lastHeartbeatAt:platformNodes2.lastHeartbeatAt,gatewayReady:platformNodes2.gatewayReady,gatewayCheckedAt:platformNodes2.gatewayCheckedAt}).from(platformNodes2).where(eqOp(platformNodes2.id,nodeId)).limit(1);return rows8[0]?buildServerPlatformNodeRouteRecord(rows8[0]):null},onLoad:()=>recordServingPlanePlatformDbQuery("platform_node_catalog"),config:resolvePlatformNodeRouteCacheConfig(process.env)}):void 0;const{wireRealtimeLimitCache}=await timed.step("platform:import-realtime-limit-cache",()=>import(resolve171(params.functionsPath,"../src/realtime-limit-cache.ts")));const realtimeLimitCache=wireRealtimeLimitCache({routeCache:appRouteCache,loadLimit:loadRealtimeConnectionLimit,env:process.env});registerPlatformAppProxy({app:params.app,resolveRealtimeConnectionLimit:realtimeLimitCache.resolve,platformDomain:params.platformDomain,publicWakeTimeoutMs:PUBLIC_RUNTIME_CONVERGENCE_TIMEOUT_MS2,reservedHosts:params.reservedAppProxyHosts,subdomainRegex,getBunServer:params.getBunServer,domainLookupDb:params.db,resolveExistingOnlyRoute:routeProjectionRuntime.resolveExistingOnlyRoute,...createPlatformCustomDomainProxyResolvers({db:params.db,appsTable,customDomainBindingsTable,andOp,eqOp}),findAppRow:appRouteCache.findAppRow,findAppRowFresh:appRouteCache.findAppRowFresh,findAppRowMetersCatalogLoads:true,currentNodeId:nodeProxyEnabled?platformNodeId:null,isAppRuntimeProjectionBlocked:routeProjectionRuntime.isAppProjectionBlocked,loadAppRouteNode:platformNodeRouteCache?nodeId=>platformNodeRouteCache.loadNode(nodeId):void 0,loadAppRouteNodeMetersCatalogLoads:true,proxyRemoteNodeRequest:nodeProxyEnabled&&nodeProxyHttpClient?({c:c2,host,appId,appName,nodeId,origin,body})=>{recordNodeRouteMetric2({protocol:"http",kind:"remote",appName});return nodeProxyHttpClient.proxyRemoteNodeHttpRequest({request:c2.req.raw,originalHost:host,origin,sourceNode:platformNodeId,targetNode:nodeId,keyId:nodeProxyKeyId,secret:nodeProxySecret,body,operationClass:"tenant",routeBinding:{appId,appName}})}:void 0,proxyRemoteNodeWebSocket:nodeProxyEnabled?async({c:c2,host,appName,nodeId,origin})=>{recordNodeRouteMetric2({protocol:"ws",kind:"remote",appName});return createNodeProxyWsTunnelUpgradeResponse({server:params.getBunServer(),request:c2.req.raw,originalHost:host,origin,sourceNode:platformNodeId,targetNode:nodeId,keyId:nodeProxyKeyId,secret:nodeProxySecret})}:void 0,generateInternalToken:generateInternalToken3,authorizeExistingOnlyRuntimeProbe:createExistingOnlyRuntimeProbeAuthorizer(generateInternalToken3),rawSql:params.rawSql,platformStorageEnv:params.platformStorageBridgeEnv,analyticsRawSql:params.analyticsRawSql??params.rawSql,functionsPath:params.functionsPath,...storageDirectRuntime,createProxyRequestReplayPlan,buildAppRuntimeUnavailableResult,buildPublicAppLookupDeferredResult,ensureAppRuntimeReady,getLivePort,setAppPort:setAppPort2,removeAppPort:removeAppPort2,removeAppPortIfEquals:removeAppPortIfEquals2,wakeRuntime:(appRow,options)=>executeLegacyRuntimeWakeByName({appName:appRow.name,expectedAppIdentity:{id:appRow.id,instanceId:appRow.instanceId},correlationId:createPublicRuntimeWakeCorrelation(appRow),deadlineAt:options?.deadlineAt}),setAppMeta:setAppMeta2,markLastAccess,beginRuntimeActivity:runtimeActivity.beginHttp,admitRuntimeActivity:runtimeActivity.admitHttp,admitRuntimeWebsocket:runtimeActivity.admitWebsocket,hasLiveRuntimeProcess:hasLiveRuntimeProcess3,resolveLiveRuntimePort:resolveLiveRuntimePort3,reapRuntimeExits:reapWarmPoolStale2,logger:logger3});logger3.log(`[platform] Subdomain proxy enabled for *.${process.env.BASE_DOMAIN||"gencow.app"}`);const autoRecoveryRuntime=await timed.step("platform:auto-recovery",()=>bootstrapPlatformAutoRecoveryWithObserver({functionsPath:params.functionsPath,db:params.db,appsTable,eqOp,andOp,inArrayOp,currentNodeId:platformNodeId,logger:logger3,fetchImpl,isActiveWorker:()=>getPlatformSlotActivity({rawSql:params.rawSql,nodeId:platformNodeId,logger:logger3}).then(x4=>x4.active),setIntervalImpl,standbyCandidate:isProcessPlatformStandbyCandidate()}));await timed.step("platform:auto-recovery-prepare",()=>autoRecoveryRuntime.prepare());const convergeRuntimeRouteProjection=requirePlatformExplicitStopConverger(autoRecoveryRuntime.convergeRuntimeRouteProjection);routeProjectionRuntime.setAbsentRouteConverger(convergeRuntimeRouteProjection);params.app.get("/internal/platform-recovery/status",c2=>c2.json(autoRecoveryRuntime.snapshot()));registerProcessPlatformSlotPromotionRoute(params.app,params.rawSql,autoRecoveryRuntime,logger3);const explicitStopReconciler=await timed.step("platform:explicit-stop-reconciler",()=>preparePlatformExplicitStopReconcilerForRuntime({functionsPath:params.functionsPath,db:params.db,currentNodeId:platformNodeId,isActiveWorker:isActiveLifecycleController,logger:logger3,setIntervalImpl,convergeRuntimeRoute:convergeRuntimeRouteProjection}));registerPlatformMaintenanceCrons({platformPort:process.env.PORT||"4100",platformMaintenanceEnv:params.platformMaintenanceEnv,logger:logger3,fetchImpl,setIntervalImpl,setTimeoutImpl,isActiveBillingWorker:createPlatformActiveSlotWorkerCheck({rawSql:params.rawSql,workerName:"billing-maintenance",logger:logger3,requireActiveReason:true}),isActiveUsageSnapshotWorker:createPlatformActiveSlotWorkerCheck({rawSql:params.rawSql,workerName:"usage-snapshot",logger:logger3,requireActiveReason:true})});registerPlatformSleepChecker({functionsPath:params.functionsPath,fetchAppStatuses,prepareRuntimeActivity:refreshRuntimeActivityBindings,requestAutomaticScaleDown,logger:logger3,setIntervalImpl,currentNodeId:platformNodeId,isActiveWorker:isActiveLifecycleController,sleepCheckIntervalMs:sleepCheckIntervalForTier(process.env.GENCOW_DEPLOY_TIER)});await timed.step("platform:cron-scheduler",()=>registerPlatformCronScheduler({functionsPath:params.functionsPath,rawSql:params.rawSql,admitRuntimeWorkload:runtimeActivity.admitWorkload}));const wakeSignalRuntime=await timed.step("platform:wake-signal",()=>createPostgresWakeSignalRuntime({rawSql:params.rawSql,env:params.wakeSignalEnv,logger:logger3}).catch(error62=>{const message=error62 instanceof Error?error62.message:String(error62);logger3.warn(`[wake-signal] PostgreSQL listener runtime disabled: ${message}`);return null}));await timed.step("platform:scheduled-jobs-poller",()=>registerScheduledJobsPoller({functionsPath:params.functionsPath,rawSql:params.rawSql,cronExecTimeoutMs:FUNCTION_TIMEOUTS.cron,logger:logger3,wakeSignalBus:wakeSignalRuntime?.bus,admitRuntimeWorkload:runtimeActivity.admitWorkload}));await timed.step("platform:state-table",()=>ensurePlatformRuntimeStateTable(params.rawSql).catch(error62=>{const message=error62 instanceof Error?error62.message:String(error62);logger3.warn(`[platform] worker active-slot table init failed: ${message}`)}));await startPlatformRuntimeWorkers({params,timed,logger:logger3,fetchImpl,setIntervalImpl,clearIntervalImpl,wakeSignalBus:wakeSignalRuntime?.bus});registerCapacityRoute({app:params.app,gateway:{getCapacity:getWakeCapacitySnapshot2}});startRuntimeMetricsSampler2();registerRuntimeMetricsRoute({app:params.app,gateway:{getRuntimeMetrics:getRuntimeMetricsSnapshot2}});registerWakeSignalDiagnosticsRoute({app:params.app,getDiagnostics:()=>wakeSignalRuntime?.getDiagnostics()??createDisabledWakeSignalDiagnostics("disabled"),getWorkerDiagnostics:()=>getPlatformWorkerDiagnostics({functionsPath:params.functionsPath})});registerPlatformNodeOpsForRuntime({nodeOpsRoutes,app:params.app,db:params.db,appsTable,platformNodes:platformNodes2,eqOp,rawSql:params.rawSql,platformDomain:params.platformDomain,platformNodeId,getCapacity:getWakeCapacitySnapshot2,setMaxConcurrentRunning:setWakeCapacityMaxConcurrentRunning2,setCapacityUpdateInProgress:setWakeCapacityUpdateInProgress2,getRuntimeMetrics:getRuntimeMetricsSnapshot2,getLivePort,setIntervalImpl,clearIntervalImpl,logger:logger3});registerRealtimeNotifyRoute({app:params.app,db:params.db,appsTable,eqOp,gateway:ws_gateway_exports,generateInternalToken:generateInternalToken3,logger:logger3});registerNodeProxyInternalRoutesForRuntime({nodeProxyEnabled,nodeProxyInternalRoutes,app:params.app,db:params.db,appsTable,eqOp,andOp,rawSql:params.rawSql,resolveRealtimeConnectionLimit:realtimeLimitCache.resolve,platformDomain:params.platformDomain,subdomainRegex,platformNodeId,nodeProxyKeyId,nodeProxySecret,generateInternalToken:generateInternalToken3,getLivePort,admitRuntimeWebsocket:runtimeActivity.admitWebsocket,logger:logger3});registerScheduledJobRoutes({app:params.app,rawSql:params.rawSql,generateInternalToken:generateInternalToken3,logger:logger3});params.app.get("/internal/ws-gateway/stats",c2=>c2.json(getStats()));params.app.get("/internal/warm-pool/stats",async c2=>{try{const{getWarmPoolStats:getWarmPoolStats2}=await import(resolve171(params.functionsPath,"../src/provisioner.ts"));return c2.json(await getWarmPoolStats2())}catch{return c2.json({enabled:false,error:"warm-pool not loaded"})}});try{await timed.step("platform:realtime-usage-metering",()=>startGatewayRealtimeUsageMeteringForRuntime({functionsPath:params.functionsPath,db:params.db,logger:logger3,setIntervalImpl}))}catch(error62){const message=error62 instanceof Error?error62.message:String(error62);logger3.error("[ws-gateway] realtime usage metering bootstrap failed:",message)}startHeartbeat();logger3.log(`[ws-gateway] WS Gateway active (max ${getGatewayLimits().maxConnectionsPerApp}/app, ${getGatewayLimits().maxTotalConnections} total)`);const startAfterListen=async()=>{await timed.step("platform:after-listen-route-recovery",()=>routeProjectionRuntime.startAfterRecovery(autoRecoveryRuntime));explicitStopReconciler.start();void startActivityHydrationAfterListen()};return{startAfterListen,close:()=>appRouteCache.close()}}var platformWebsocketGateway,platformNodeProxyWsTunnel,REALTIME_NOTIFY_INTERNAL_ERROR;var init_server_platform_runtime_bootstrap=__esm({"../server/dist/server-platform-runtime-bootstrap.js"(){"use strict";init_server_platform_maintenance();init_server_platform_runtime_sleep_tier();init_server_platform_app_proxy();init_server_platform_media_worker_storage_runtime();init_server_platform_control_plane_observer_runtime();init_server_platform_cron_scheduler();init_server_scheduled_jobs_runtime();init_platform_scheduled_job_secret();init_server_execution();init_server_wake_signal_diagnostics_route();init_server_platform_worker_diagnostics();init_platform_active_slot();init_server_platform_slot_promotion();init_server_platform_explicit_stop_reconciler_runtime();init_postgres_wake_signal_runtime();init_wake_signal_diagnostics();init_ws_gateway2();init_server_platform_node_routing();init_server_realtime_connection_limit();init_server_serving_plane_dependency_metrics();init_server_platform_node_routes_bootstrap();init_server_node_proxy_ws_tunnel();init_server_node_routing_metrics();init_server_platform_storage_direct_runtime();init_server_platform_runtime_helpers();init_server_platform_internal_middleware();init_server_platform_realtime_forwarder();init_server_platform_analytics_ingest();init_server_legacy_runtime_recovery_route();init_server_runtime_route_projection_runtime();init_server_platform_lifecycle_authority();init_server_platform_custom_domain_readiness_worker_runtime();init_server_platform_runtime_worker_startup();init_platform_database_url_resolvers();init_server_platform_lifecycle_api_runtime();init_server_platform_observability_routes();init_server_platform_idle_wake_bootstrap();init_server_platform_runtime_generation_bootstrap();init_server_platform_observability_routes();init_server_platform_runtime_helpers();platformWebsocketGateway=ws_gateway_exports;platformNodeProxyWsTunnel={handleOpen:handleNodeProxyWsTunnelOpen,handleMessage:handleNodeProxyWsTunnelMessage,handleClose:handleNodeProxyWsTunnelClose};REALTIME_NOTIFY_INTERNAL_ERROR="Internal realtime notify failed"}});function isAllowedBuilderPreviewHostPath(path5){return path5.startsWith(BUILDER_PREVIEW_PATH_PREFIX)}function registerBuilderPreviewHostGuard(params){if(!params.previewHost)return;params.app.use("*",async(c2,next)=>{const host=String(c2.req.header("host")??"").trim().toLowerCase();if(host!==params.previewHost)return next();const path5=c2.req.path??new URL(c2.req.url).pathname;if(isAllowedBuilderPreviewHostPath(path5))return next();return c2.json({error:"Not found"},404)})}function resolveIsolatedBuilderPreviewHost(origin,platformDomain){if(!origin?.trim())return null;const url2=new URL(origin.trim());if(url2.protocol!=="https:"||url2.username||url2.password||url2.pathname!=="/"||url2.search||url2.hash){throw new Error("GENCOW_BUILDER_PREVIEW_ORIGIN must be a bare HTTPS origin")}const host=url2.host.toLowerCase();if(host===platformDomain.trim().toLowerCase()){throw new Error("Builder preview origin must be isolated from the platform origin")}return host}var BUILDER_PREVIEW_PATH_PREFIX;var init_server_platform_builder_preview_origin=__esm({"../server/dist/server-platform-builder-preview-origin.js"(){"use strict";BUILDER_PREVIEW_PATH_PREFIX="/platform/builder/preview/"}});import{resolve as resolve172}from"path";async function startPlatformBuilderWorkerForRuntime(params){const env=params.env??{};const importImpl=params.importImpl??(path5=>import(path5));const mod=await importImpl(resolve172(params.functionsPath,"../src/builder-worker-runtime.ts"));mod.captureBuilderStorageRuntimeEnv(env);if(!mod.shouldStartEmbeddedBuilderWorker(env)){return null}return mod.startBuilderWorkerRuntime({db:params.db,catalogQuery:params.catalogQuery,env,isActiveWorker:params.isActiveWorker,logger:params.logger??console})}var init_server_platform_builder_worker_runtime=__esm({"../server/dist/server-platform-builder-worker-runtime.js"(){"use strict"}});var server_platform_builder_runtime_exports={};__export(server_platform_builder_runtime_exports,{bootstrapPlatformBuilderRuntime:()=>bootstrapPlatformBuilderRuntime});async function bootstrapPlatformBuilderRuntime(params){const logger3=params.logger??console;const previewHost=resolveIsolatedBuilderPreviewHost(params.env.GENCOW_BUILDER_PREVIEW_ORIGIN,params.platformDomain);registerBuilderPreviewHostGuard({app:params.app,previewHost});try{await startPlatformBuilderWorkerForRuntime({functionsPath:params.functionsPath,db:params.db,catalogQuery:params.catalogQuery,env:params.env,isActiveWorker:params.isActiveWorker,logger:logger3})}catch(error62){const message=error62 instanceof Error?error62.message:String(error62);logger3.error("[builder-worker] bootstrap failed:",message)}return{previewHost}}var init_server_platform_builder_runtime=__esm({"../server/dist/server-platform-builder-runtime.js"(){"use strict";init_server_platform_builder_preview_origin();init_server_platform_builder_worker_runtime()}});init_http_exception();var GET_MATCH_RESULT=Symbol();var bufferToFormData=(arrayBuffer,contentType)=>{return new Response(arrayBuffer,{headers:{"Content-Type":contentType.replace(/^[^;]+/,mediaType=>mediaType.toLowerCase())}}).formData()};var MAX_NESTED_OBJECTS=1e4;var isRawRequest=request=>"headers"in request;var parseBody=async(request,options=Object.create(null))=>{const{all:all2=false,dot=false}=options;const mediaType=(isRawRequest(request)?request.headers:request.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();if(mediaType==="multipart/form-data"||mediaType==="application/x-www-form-urlencoded")return parseFormData(request,{all:all2,dot});return{}};async function parseFormData(request,options){if(!isRawRequest(request)&&request.bodyCache.formData)return convertFormDataToBodyData(await request.bodyCache.formData,options);const headers=isRawRequest(request)?request.headers:request.raw.headers;const arrayBuffer=await request.arrayBuffer();const formDataPromise=bufferToFormData(arrayBuffer,headers.get("Content-Type")||"");if(!isRawRequest(request))request.bodyCache.formData=formDataPromise;const formData=await formDataPromise;if(formData)return convertFormDataToBodyData(formData,options);return{}}function convertFormDataToBodyData(formData,options){const form=Object.create(null);const nestingState={count:0};formData.forEach((value2,key2)=>{if(!(options.all||key2.endsWith("[]")))form[key2]=value2;else handleParsingAllValues(form,key2,value2)});if(options.dot)Object.entries(form).forEach(([key2,value2])=>{if(key2.includes(".")){handleParsingNestedValues(form,key2,value2,nestingState);delete form[key2]}});return form}var handleParsingAllValues=(form,key2,value2)=>{if(form[key2]!==void 0){if(Array.isArray(form[key2]))form[key2].push(value2);else form[key2]=[form[key2],value2]}else if(!key2.endsWith("[]"))form[key2]=value2;else form[key2]=[value2]};var handleParsingNestedValues=(form,key2,value2,state2)=>{if(/(?:^|\.)__proto__\./.test(key2))return;let nestedForm=form;const keys2=key2.split(".",34);if(keys2.length>33)throwNestingLimitExceeded();keys2.forEach((key3,index28)=>{if(index28===keys2.length-1)nestedForm[key3]=value2;else{if(!nestedForm[key3]||typeof nestedForm[key3]!=="object"||Array.isArray(nestedForm[key3])||nestedForm[key3]instanceof File){if(state2.count++>=MAX_NESTED_OBJECTS)throwNestingLimitExceeded();nestedForm[key3]=Object.create(null)}nestedForm=nestedForm[key3]}})};var throwNestingLimitExceeded=()=>{throw new Error("Nesting limit exceeded")};init_url();var HonoRequest=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(request,path5="/",matchResult=[[]]){this.raw=request;this.path=path5;this.#matchResult=matchResult}param(key2){return key2?this.#getDecodedParam(key2):this.#getAllDecodedParams()}#getDecodedParam(key2){const paramKey=this.#matchResult[0][this.routeIndex]?.[1][key2];const param=this.#getParamValue(paramKey);return param&&tryDecodeURIComponent(param)}#getAllDecodedParams(){const decoded={};const keys2=Object.keys(this.#matchResult[0][this.routeIndex]?.[1]??{});for(const key2 of keys2){const value2=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key2]);if(value2!==void 0)decoded[key2]=tryDecodeURIComponent(value2)}return decoded}#getParamValue(paramKey){return this.#matchResult[1]?this.#matchResult[1][paramKey]:paramKey}query(key2){return getQueryParam(this.url,key2)}queries(key2){return getQueryParams(this.url,key2)}header(name2){if(name2)return this.raw.headers.get(name2)??void 0;const headerData=Object.create(null);this.raw.headers.forEach((value2,key2)=>{headerData[key2]=value2});return headerData}async parseBody(options){return parseBody(this,options)}#cachedBody=key2=>{const{bodyCache,raw:raw2}=this;const cachedBody=bodyCache[key2];if(cachedBody)return cachedBody;for(const anyCachedKey in bodyCache)return bodyCache[anyCachedKey].then(body=>{if(anyCachedKey==="json")body=JSON.stringify(body);const contentType=anyCachedKey==="formData"?void 0:raw2.headers.get("content-type");return new Response(body,{headers:contentType?{"Content-Type":contentType}:void 0})[key2]()});return bodyCache[key2]=raw2[key2]()};json(){return this.#cachedBody("text").then(text35=>JSON.parse(text35))}text(){return this.#cachedBody("text")}arrayBuffer(){return this.#cachedBody("arrayBuffer")}bytes(){return this.#cachedBody("arrayBuffer").then(buffer=>new Uint8Array(buffer))}blob(){return this.#cachedBody("blob")}formData(){return this.#cachedBody("formData")}addValidatedData(target,data){(this.#validatedData??={})[target]=data}valid(target){return this.#validatedData?.[target]}get url(){return this.raw.url}get method(){return this.raw.method}get[GET_MATCH_RESULT](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,route]])=>route)}get routePath(){return this.#matchResult[0].map(([[,route]])=>route)[this.routeIndex].path}};var HtmlEscapedCallbackPhase={Stringify:1,BeforeStream:2,Stream:3};var raw=(value2,callbacks)=>{const escapedString=new String(value2);escapedString.isEscaped=true;escapedString.callbacks=callbacks;return escapedString};var resolveCallback=async(str,phase,preserveCallbacks,context,buffer)=>{if(typeof str==="object"&&!(str instanceof String)){if(!(str instanceof Promise))str=str.toString();if(str instanceof Promise)str=await str}const callbacks=str.callbacks;if(!callbacks?.length)return Promise.resolve(str);if(buffer)buffer[0]+=str;else buffer=[str];const resStr=Promise.all(callbacks.map(c2=>c2({phase,buffer,context}))).then(res=>Promise.all(res.filter(Boolean).map(str2=>resolveCallback(str2,phase,false,context,buffer))).then(()=>buffer[0]));if(preserveCallbacks)return raw(await resStr,callbacks);else return resStr};var TEXT_PLAIN="text/plain; charset=UTF-8";var setDefaultContentType=(contentType,headers)=>{return{"Content-Type":contentType,...headers}};var createResponseInstance=(body,init)=>new Response(body,init);var Context=class{#rawRequest;#req;env={};#var;finalized=false;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(req,options){this.#rawRequest=req;if(options){this.#executionCtx=options.executionCtx;this.env=options.env;this.#notFoundHandler=options.notFoundHandler;this.#path=options.path;this.#matchResult=options.matchResult}}get req(){this.#req??=new HonoRequest(this.#rawRequest,this.#path,this.#matchResult);return this.#req}get event(){if(this.#executionCtx&&"respondWith"in this.#executionCtx)return this.#executionCtx;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;else throw Error("This context has no ExecutionContext")}get res(){return this.#res||=createResponseInstance(null,{headers:this.#preparedHeaders??=new Headers})}set res(_res){if(this.#res&&_res){_res=createResponseInstance(_res.body,_res);for(const[k5,v5]of this.#res.headers.entries()){if(k5==="content-type")continue;if(k5==="set-cookie"){const cookies=this.#res.headers.getSetCookie();_res.headers.delete("set-cookie");for(const cookie of cookies)_res.headers.append("set-cookie",cookie)}else _res.headers.set(k5,v5)}}this.#res=_res;this.finalized=true}render=(...args)=>{this.#renderer??=content=>this.html(content);return this.#renderer(...args)};setLayout=layout=>this.#layout=layout;getLayout=()=>this.#layout;setRenderer=renderer=>{this.#renderer=renderer};header=(name2,value2,options)=>{if(this.finalized&&!this.#res.bodyUsed)this.#res=createResponseInstance(this.#res.body,this.#res);const headers=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;if(value2===void 0)headers.delete(name2);else if(options?.append)headers.append(name2,value2);else headers.set(name2,value2)};status=status=>{this.#status=status};set=(key2,value2)=>{this.#var??=new Map;this.#var.set(key2,value2)};get=key2=>{return this.#var?this.#var.get(key2):void 0};get var(){if(!this.#var)return{};return Object.fromEntries(this.#var)}#newResponse(data,arg,headers){let responseHeaders=this.#res?new Headers(this.#res.headers):this.#preparedHeaders;if(typeof arg==="object"&&arg.headers){responseHeaders??=new Headers;for(const[key2,value2]of new Headers(arg.headers))if(key2==="set-cookie")responseHeaders.append(key2,value2);else responseHeaders.set(key2,value2)}if(headers){if(!responseHeaders){let count3=0;for(const k5 in headers)if(++count3>1||typeof headers[k5]!=="string"){responseHeaders=new Headers;break}}if(responseHeaders)for(const k5 in headers){const v5=headers[k5];if(typeof v5==="string")responseHeaders.set(k5,v5);else{responseHeaders.delete(k5);for(const v22 of v5)responseHeaders.append(k5,v22)}}}const status=typeof arg==="number"?arg:arg?.status??this.#status;return createResponseInstance(data,{status,headers:responseHeaders??headers})}newResponse=(...args)=>this.#newResponse(...args);body=(data,arg,headers)=>this.#newResponse(data,arg,headers);text=(text35,arg,headers)=>{return!this.#preparedHeaders&&!this.#status&&!arg&&!headers&&!this.finalized?new Response(text35):this.#newResponse(text35,arg,setDefaultContentType(TEXT_PLAIN,headers))};json=(object5,arg,headers)=>{return this.#newResponse(JSON.stringify(object5),arg,setDefaultContentType("application/json",headers))};html=(html2,arg,headers)=>{const res=html3=>this.#newResponse(html3,arg,setDefaultContentType("text/html; charset=UTF-8",headers));return typeof html2==="object"?resolveCallback(html2,HtmlEscapedCallbackPhase.Stringify,false,{}).then(res):res(html2)};redirect=(location,status)=>{const locationString=String(location);this.header("Location",!/[^\x00-\xFF]/.test(locationString)?locationString:encodeURI(locationString));return this.newResponse(null,status??302)};notFound=()=>{this.#notFoundHandler??=()=>createResponseInstance();return this.#notFoundHandler(this)}};var compose=(middleware,onError,onNotFound)=>{return(context,next)=>{let index28=-1;return dispatch(0);async function dispatch(i){if(i<=index28)throw new Error("next() called multiple times");index28=i;let res;let isError=false;let handler;if(middleware[i]){handler=middleware[i][0][0];context.req.routeIndex=i}else handler=i===middleware.length&&next||void 0;if(handler)try{res=await handler(context,()=>dispatch(i+1))}catch(err){if(err instanceof Error&&onError){context.error=err;res=await onError(err,context);isError=true}else throw err}else if(context.finalized===false&&onNotFound)res=await onNotFound(context);if(res&&(context.finalized===false||isError))context.res=res;return context}}};init_url();var METHODS=["get","post","put","delete","options","patch","query"];var MESSAGE_MATCHER_IS_ALREADY_BUILT="Can not add a route since the matcher is already built.";var UnsupportedPathError=class extends Error{};var COMPOSED_HANDLER="__COMPOSED_HANDLER";init_url();var getPathPrefixLength=(c2,pathPrefix,routePath)=>{if(!/[:*]/.test(pathPrefix))return pathPrefix.length;const path5=c2.req.path;const matchResult=c2.req[GET_MATCH_RESULT];const paramNames=new Set;let length=0;for(const part of splitRoutingPath(pathPrefix)){const pattern=getPattern(part);if(pattern&&pattern!=="*"){const name2=pattern[1];if(paramNames.has(name2))throw new Error(`mount(): Duplicate path parameter "${name2}" in "${routePath}".`);paramNames.add(name2)}if(pattern&&pattern!=="*"&&pattern[2]!==true){const value2=matchResult.length===2?matchResult[1][matchResult[0][c2.req.routeIndex][1][pattern[1]]]:matchResult[0][c2.req.routeIndex][1][pattern[1]];length+=value2.length+1}else if(pattern||part.endsWith("*")){const end=path5.indexOf("/",length+1);length=end===-1?path5.length:end}else length+=part.length+1}return length};var createMountedRequest=(c2,pathPrefix,routePath)=>{if(/[^/]\*$/.test(routePath))throw new Error(`mount(): Wildcard must follow "/" in "${routePath}".`);const url2=new URL(c2.req.raw.url);url2.pathname=stripPathPrefix(url2.pathname,c2.req.path,getPathPrefixLength(c2,pathPrefix,routePath));return new Request(url2,c2.req.raw)};var notFoundHandler=c2=>{return c2.text("404 Not Found",404)};var errorHandler=(err,c2)=>{if("getResponse"in err){const res=err.getResponse();return c2.newResponse(res.body,res)}console.error(err);return c2.text("Internal Server Error",500)};var Hono=class Hono2{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#path="/";routes=[];constructor(options={}){[...METHODS,"all"].forEach(method=>{this[method]=(args1,...args)=>{const methodName=method.toUpperCase();if(typeof args1==="string")this.#path=args1;else this.#addRoute(methodName,this.#path,args1);args.forEach(handler=>{this.#addRoute(methodName,this.#path,handler)});return this}});this.on=(method,path5,...handlers)=>{for(const p3 of[path5].flat()){this.#path=p3;for(const m4 of[method].flat()){const methodName=m4.toUpperCase();for(const handler of handlers)this.#addRoute(methodName,this.#path,handler)}}return this};this.use=(arg1,...handlers)=>{if(typeof arg1==="string")this.#path=arg1;else{this.#path="*";handlers.unshift(arg1)}handlers.forEach(handler=>{this.#addRoute("ALL",this.#path,handler)});return this};const{strict,...optionsWithoutStrict}=options;Object.assign(this,optionsWithoutStrict);this.getPath=strict??true?options.getPath??getPath:getPathNoStrict}#clone(){const clone3=new Hono2({router:this.router,getPath:this.getPath});clone3.errorHandler=this.errorHandler;clone3.#notFoundHandler=this.#notFoundHandler;clone3.routes=this.routes;return clone3}#notFoundHandler=notFoundHandler;errorHandler=errorHandler;route(path5,app2){const subApp=this.basePath(path5);app2.routes.map(r2=>{let handler;if(app2.errorHandler===errorHandler)handler=r2.handler;else{handler=async(c2,next)=>(await compose([],app2.errorHandler)(c2,()=>r2.handler(c2,next))).res;handler[COMPOSED_HANDLER]=r2.handler}subApp.#addRoute(r2.method,r2.path,handler,r2.basePath)});return this}basePath(path5){const subApp=this.#clone();subApp._basePath=mergePath(this._basePath,path5);return subApp}onError=handler=>{this.errorHandler=handler;return this};notFound=handler=>{this.#notFoundHandler=handler;return this};mount(path5,applicationHandler,options){let replaceRequest;let optionHandler;if(options){if(typeof options==="function")optionHandler=options;else{optionHandler=options.optionHandler;if(options.replaceRequest===false)replaceRequest=request=>request;else replaceRequest=options.replaceRequest}}const getOptions=optionHandler?c2=>{const options2=optionHandler(c2);return Array.isArray(options2)?options2:[options2]}:c2=>{let executionContext=void 0;try{executionContext=c2.executionCtx}catch{}return[c2.env,executionContext]};const mergedPath=mergePath(this._basePath,path5);const defaultReplaceRequest=c2=>createMountedRequest(c2,mergedPath.replace(/\/$/,""),mergePath(mergedPath,"*"));const handler=async(c2,next)=>{const res=await applicationHandler(replaceRequest?replaceRequest(c2.req.raw):defaultReplaceRequest(c2),...getOptions(c2));if(res)return res;await next()};this.#addRoute("ALL",mergePath(path5,"*"),handler);return this}#addRoute(method,path5,handler,baseRoutePath){path5=mergePath(this._basePath,path5);const r2={basePath:baseRoutePath!==void 0?mergePath(this._basePath,baseRoutePath):this._basePath,path:path5,method,handler};this.router.add(method,path5,[handler,r2]);this.routes.push(r2)}#handleError(err,c2){if(err instanceof Error)return this.errorHandler(err,c2);throw err}#dispatch(request,executionCtx,env,method){if(method==="HEAD")return(async()=>new Response(null,await this.#dispatch(request,executionCtx,env,"GET")))();const path5=this.getPath(request,{env});const matchResult=this.router.match(method,path5);const c2=new Context(request,{path:path5,matchResult,env,executionCtx,notFoundHandler:this.#notFoundHandler});if(matchResult[0].length===1){let res;try{res=matchResult[0][0][0][0](c2,async()=>{c2.res=await this.#notFoundHandler(c2)})}catch(err){return this.#handleError(err,c2)}return res instanceof Promise?res.then(resolved=>resolved||(c2.finalized?c2.res:this.#notFoundHandler(c2))).catch(err=>this.#handleError(err,c2)):res??this.#notFoundHandler(c2)}const composed=compose(matchResult[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{const context=await composed(c2);if(!context.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return context.res}catch(err){return this.#handleError(err,c2)}})()}fetch=(request,...rest2)=>{return this.#dispatch(request,rest2[1],rest2[0],request.method)};request=(input2,requestInit,Env,executionCtx)=>{if(input2 instanceof Request)return this.fetch(requestInit?new Request(input2,requestInit):input2,Env,executionCtx);input2=input2.toString();return this.fetch(new Request(/^https?:\/\//.test(input2)?input2:`http://localhost${mergePath("/",input2)}`,requestInit),Env,executionCtx)};fire=()=>{addEventListener("fetch",event=>{event.respondWith(this.#dispatch(event.request,event,void 0,event.request.method))})}};init_url();var createNullObject=()=>Object.create(null);var emptyParam=[];function match(method,path5){const matchers=this.buildAllMatchers();const match2=((method2,path6)=>{const matcher2=matchers[method2]||matchers["ALL"];const staticMatch=matcher2[2][path6];if(staticMatch)return staticMatch;const match3=path6.match(matcher2[0]);if(!match3)return[[],emptyParam];const index28=match3.indexOf("",1);return[matcher2[1][index28],match3]});this.match=match2;return match2(method,path5)}var LABEL_REG_EXP_STR="[^/]+";var ONLY_WILDCARD_REG_EXP_STR="[^]*";var TAIL_WILDCARD_REG_EXP_STR="(?:|/[^]*)";var PATH_ERROR=Symbol();var regExpMetaChars=new Set(".\\+*[^]$()");function compareKey(a,b5){if(a.length===1)return b5.length===1?a<b5?-1:1:-1;if(b5.length===1)return 1;if(a==="[^]*"||a==="(?:|/[^]*)")return b5==="[^]*"?-1:1;else if(b5==="[^]*"||b5==="(?:|/[^]*)")return-1;if(a==="[^/]+")return 1;else if(b5==="[^/]+")return-1;return a.length===b5.length?a<b5?-1:1:b5.length-a.length}var Node2=class Node3{#index;#varIndex;#children=createNullObject();insert(tokens,index28,paramMap,context,keys2){let node2=this;for(let i=0,len=tokens.length;i<len;i++){const token2=tokens[i];const pattern=token2.length===1?token2==="*"?i===len-1?["","",ONLY_WILDCARD_REG_EXP_STR]:["","",LABEL_REG_EXP_STR]:null:token2==="/*"?["","",TAIL_WILDCARD_REG_EXP_STR]:token2.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);let nextNode;if(pattern){const name2=pattern[1];let regexpStr=pattern[2]||"[^/]+";if(name2&&pattern[2]){if(new RegExp(regexpStr).test(""))throw PATH_ERROR;regexpStr=regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:");if(/\((?!\?:)/.test(regexpStr))throw PATH_ERROR;if(regexpStr.length===1&®ExpMetaChars.has(regexpStr))throw PATH_ERROR}keys2.push(regexpStr);nextNode=node2.#children[regexpStr];if(!nextNode){if(regexpStr!=="[^]*"&®expStr!=="(?:|/[^]*)"){for(const k5 in node2.#children)if((regexpStr.length>1||k5.length>1)&&k5!=="[^]*"&&k5!=="(?:|/[^]*)")throw PATH_ERROR}nextNode=node2.#children[regexpStr]=new Node3}if(name2!==""){nextNode.#varIndex??=context.varIndex++;paramMap.push([name2,nextNode.#varIndex])}}else{keys2.push(token2);nextNode=node2.#children[token2];if(!nextNode){for(const k5 in node2.#children)if(k5.length>1&&k5!=="[^]*"&&k5!=="(?:|/[^]*)")throw PATH_ERROR;nextNode=node2.#children[token2]=new Node3}}node2=nextNode}if(node2.#index!==void 0)throw PATH_ERROR;node2.#index=index28}buildRegExpStr(){const strList=Object.keys(this.#children).sort(compareKey).map(k5=>{const c2=this.#children[k5];const childStr=c2.buildRegExpStr();return childStr===""?"":(typeof c2.#varIndex==="number"?`(${k5})@${c2.#varIndex}`:regExpMetaChars.has(k5)?`\\${k5}`:k5)+childStr}).filter(Boolean);if(typeof this.#index==="number"&&this.#index!==-1)strList.unshift(`#${this.#index}`);if(strList.length===0)return"";if(strList.length===1)return strList[0];return"(?:"+strList.join("|")+")"}};var Trie=class{#context={varIndex:0};#root=new Node2;#index=0;paths=createNullObject();insert(path5,isStatic){const keys2=[];if(isStatic){this.#root.insert(path5.split(""),-1,[],this.#context,keys2);this.paths[path5]=[-1,[],keys2];return}const paramAssoc=[];const groups=[];let markedPath=path5;for(let i=0;;){let replaced=false;markedPath=markedPath.replace(/\{(?:\{[\d,]+\}|[^}])+\}/g,m4=>{const mark=`@\\${i}`;groups[i]=[mark,m4];i++;replaced=true;return mark});if(!replaced)break}const tokens=markedPath.match(/(?::[^\/]+)|(?:\/\*$)|./gs)||[];for(let i=groups.length-1;i>=0;i--){const[mark]=groups[i];for(let j5=tokens.length-1;j5>=0;j5--)if(tokens[j5].indexOf(mark)!==-1){tokens[j5]=tokens[j5].replace(mark,groups[i][1]);break}}this.#root.insert(tokens,this.#index,paramAssoc,this.#context,keys2);this.paths[path5]=[this.#index++,paramAssoc,keys2]}buildRegExp(){let regexp=this.#root.buildRegExpStr();if(regexp==="")return[/^$/,[],[]];let captureIndex=0;const indexReplacementMap=[];const paramReplacementMap=[];regexp=regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g,(_5,handlerIndex,paramIndex)=>{if(handlerIndex!==void 0){indexReplacementMap[++captureIndex]=Number(handlerIndex);return"$()"}if(paramIndex!==void 0){paramReplacementMap[Number(paramIndex)]=++captureIndex;return""}return""});return[new RegExp(`^${regexp}`),indexReplacementMap,paramReplacementMap]}};function endsWithWildcard(keys2){const tail=keys2[keys2.length-1];return tail==="[^]*"||tail==="(?:|/[^]*)"}function covers(wildcard,target){const last2=wildcard.length-1;for(let i=0;i<last2;i++)if(wildcard[i]!==target[i])return false;return wildcard[last2]==="[^]*"||target.length===last2||target[last2]==="/"}var RegExpRouter=class{name="RegExpRouter";#handlers;#tries;constructor(){this.#handlers={["ALL"]:[]};this.#tries={["ALL"]:new Trie}}#insertPath(method,path5){try{this.#tries[method].insert(path5,!/\*|\/:/.test(path5))}catch(e5){throw e5===PATH_ERROR?new UnsupportedPathError(path5):e5}}add(method,path5,handler){const handlers=this.#handlers;if(!handlers)throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);const tries=this.#tries;if(!handlers[method]){tries[method]=new Trie;handlers[method]=[...handlers["ALL"]];for(const p3 in tries["ALL"].paths)this.#insertPath(method,p3)}if(path5==="/*")path5="*";const methods=method==="ALL"?Object.keys(handlers):[method];const paths=checkOptionalParameter(path5)||[path5];for(const path6 of paths)for(const m4 of methods){if(!tries[m4].paths[path6])this.#insertPath(m4,path6);handlers[m4].push([handler,path6])}}match=match;buildAllMatchers(){const matchers=createNullObject();for(const method of Object.keys(this.#handlers))matchers[method]=this.#buildMatcher(method);this.#handlers=this.#tries=void 0;return matchers}#buildMatcher(method){const handlers=this.#handlers[method];const trie=this.#tries[method];const staticMap=createNullObject();const handlerData=[];const[regexp,indexReplacementMap,paramReplacementMap]=trie.buildRegExp();const own2=createNullObject();const entries=handlers.map(([h,p3],i)=>{(own2[p3]??=[]).push(i);return[h,trie.paths[p3][1].reduceRight((map6,[key2,varIndex])=>{map6[key2]=paramReplacementMap[varIndex];return map6},createNullObject())]});const wildcards=Object.keys(own2).filter(p3=>endsWithWildcard(trie.paths[p3][2]));for(const path5 in trie.paths){const[index28,,keys2]=trie.paths[path5];const indexes=[...own2[path5]];for(const p3 of wildcards)if(p3!==path5&&covers(trie.paths[p3][2],keys2))indexes.push(...own2[p3]);const data=indexes.sort((a,b5)=>a-b5).map(i=>entries[i]);if(index28===-1){const last2=Math.max(-1,...data.flatMap(([,map6])=>Object.values(map6)));staticMap[path5]=[data,last2===-1?emptyParam:path5.match(regexp).slice(0,last2+1)]}else handlerData[index28]=data}return[regexp,indexReplacementMap.map(i=>handlerData[i]),staticMap]}};var SmartRouter=class{name="SmartRouter";#routers=[];#routes=[];constructor(init){this.#routers=init.routers}add(method,path5,handler){if(!this.#routes)throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);this.#routes.push([method,path5,handler])}match(method,path5){if(!this.#routes)throw new Error("Fatal error");const routers=this.#routers;const routes=this.#routes;const len=routers.length;let i=0;let res;for(;i<len;i++){const router=routers[i];try{for(let i2=0,len2=routes.length;i2<len2;i2++)router.add(...routes[i2]);res=router.match(method,path5)}catch(e5){if(e5 instanceof UnsupportedPathError)continue;throw e5}this.match=router.match.bind(router);this.#routers=[router];this.#routes=void 0;break}if(i===len)throw new Error("Fatal error");this.name=`SmartRouter + ${this.activeRouter.name}`;return res}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw new Error("No active router has been determined yet.");return this.#routers[0]}};init_url();init_url();var emptyParams=createNullObject();var order=0;var Node4=class Node5{#methods=[];#children=createNullObject();#patterns=[];#pattern;#params=emptyParams;insert(method,path5,handler){let curNode=this;const parts=splitRoutingPath(path5);const possibleKeys=new Set;let i=0;for(const p3 of parts){const nextP=parts[++i];const pattern=getPattern(p3,nextP)||(nextP===void 0&&p3&&p3.indexOf("*")===p3.length-1?p3:null);const isParam=Array.isArray(pattern);const key2=isParam?pattern[0]:pattern||p3;const child=curNode.#children[key2]||=new Node5;if(pattern&&!child.#pattern){child.#pattern=pattern;curNode.#patterns.push(child)}curNode=child;if(isParam)possibleKeys.add(pattern[1])}curNode.#methods.push({[method]:{handler,possibleKeys:[...possibleKeys],score:++order}})}#pushHandlerSets(handlerSets,node2,method,nodeParams,params){for(let i=0,len=node2.#methods.length;i<len;i++){const m4=node2.#methods[i];const handlerSet=m4[method]||m4["ALL"];if(handlerSet){handlerSet.params=createNullObject();handlerSets.push(handlerSet);for(let i2=0,len2=handlerSet.possibleKeys.length;i2<len2;i2++){const key2=handlerSet.possibleKeys[i2];handlerSet.params[key2]=params?.[key2]&&!i2?params[key2]:nodeParams[key2]??params?.[key2]}}}}search(method,path5){const handlerSets=[];this.#params=emptyParams;let curNodes=[this];const parts=splitPath(path5);const curNodesQueue=[];const len=parts.length;let partOffsets=null;for(let i=0;i<len;i++){const part=parts[i];const isLast=i===len-1;const tempNodes=[];for(let j5=0,len2=curNodes.length;j5<len2;j5++){const node2=curNodes[j5];const nextNode=node2.#children[part];if(nextNode){nextNode.#params=node2.#params;if(isLast){if(nextNode.#children["*"])this.#pushHandlerSets(handlerSets,nextNode.#children["*"],method,node2.#params);this.#pushHandlerSets(handlerSets,nextNode,method,node2.#params)}else tempNodes.push(nextNode)}for(const child of node2.#patterns){const pattern=child.#pattern;const params=node2.#params===emptyParams?{}:{...node2.#params};if(typeof pattern==="string"){if(pattern==="*"||part.startsWith(pattern.slice(0,-1))){this.#pushHandlerSets(handlerSets,child,method,node2.#params);if(pattern==="*"){child.#params=params;tempNodes.push(child)}}continue}const[,name2,matcher2]=pattern;if(!part&&matcher2===true)continue;if(matcher2!==true){if(!partOffsets){partOffsets=[];let offset=path5[0]==="/"?1:0;for(let p3=0;p3<len;p3++){partOffsets[p3]=offset;offset+=parts[p3].length+1}}const restPathString=path5.slice(partOffsets[i]);const m4=matcher2.exec(restPathString);if(m4){if(!Object.hasOwn(params,name2))params[name2]=m4[0];this.#pushHandlerSets(handlerSets,child,method,node2.#params,params);if(m4[0].length===restPathString.length&&child.#children["*"])this.#pushHandlerSets(handlerSets,child.#children["*"],method,node2.#params,params);for(const _5 in child.#children){child.#params=params;const componentCount=m4[0].match(/\//g)?.length??0;(curNodesQueue[componentCount]||=[]).push(child);break}continue}}if(matcher2===true||matcher2.test(part)){if(!Object.hasOwn(params,name2))params[name2]=part;if(isLast){this.#pushHandlerSets(handlerSets,child,method,params,node2.#params);if(child.#children["*"])this.#pushHandlerSets(handlerSets,child.#children["*"],method,params,node2.#params)}else{child.#params=params;tempNodes.push(child)}}}}const shifted=curNodesQueue.shift();curNodes=shifted?tempNodes.concat(shifted):tempNodes}if(handlerSets[1])handlerSets.sort((a,b5)=>{return a.score-b5.score});return[handlerSets.map(({handler,params})=>[handler,params])]}};var TrieRouter=class{name="TrieRouter";#node=new Node4;add(method,path5,handler){for(const result3 of checkOptionalParameter(path5)||[path5])this.#node.insert(method,result3,handler)}match(method,path5){return this.#node.search(method,path5)}};var Hono3=class extends Hono{constructor(options={}){super(options);this.router=options.router??new SmartRouter({routers:[new RegExpRouter,new TrieRouter]})}};import{existsSync as existsSync77,readFileSync as readFileSync78}from"fs";import{resolve as resolve173}from"path";import{createHash as createHash5}from"crypto";var SYSTEM_RLS_GUC_SQL="select set_config($1::text, $2::text, true), set_config($3::text, $4::text, true), set_config($5::text, $6::text, true)";var SYSTEM_RLS_GUC_PARAMS=["app.current_user_id","","app.current_user_role","system","app.internal_system","true"];init_dist();init_database_config();import{existsSync as existsSync2,mkdirSync as mkdirSync2,mkdtempSync as mkdtempSync2,readdirSync as readdirSync3,readFileSync as readFileSync2,rmSync as rmSync2,writeFileSync as writeFileSync2}from"fs";import{tmpdir as tmpdir2}from"os";import{dirname,join as join3,resolve}from"path";init_postgres_json_parameter();var INVALID_RAW_SQL_PARAMETER_CODE="GENCOW_DB_INVALID_RAW_SQL_PARAMETER";var InvalidRawSqlParameterError=class extends Error{code=INVALID_RAW_SQL_PARAMETER_CODE;parameterIndex;constructor(parameterIndex){super(`Invalid raw SQL Date parameter at index ${parameterIndex}`);this.name="InvalidRawSqlParameterError";this.parameterIndex=parameterIndex}};function normalizeRawSqlParams(params,jsonMode){if(!params)return void 0;const normalized=params.map((value2,parameterIndex)=>{if(!(value2 instanceof Date))return value2;if(!Number.isFinite(value2.getTime())){throw new InvalidRawSqlParameterError(parameterIndex)}return value2.toISOString()});return jsonMode?materializePostgresParameters(normalized,jsonMode):normalized}init_postgres_temporal();init_runtime_postgres_client();init_runtime_postgres_transaction_options();init_runtime_postgres_client();function createRuntimePostgresWorkloads(params){const createClient3=(label,databaseName,options)=>createRuntimePostgresClient({label,databaseName,operationTimeoutMs:params.operationTimeoutMs,recoveryJitterMaxMs:params.recoveryJitterMaxMs,logger:params.logger,createClient:()=>params.createClient(options,label)});const runtimeClient=createClient3("tenant-runtime",params.runtimeDatabaseName,params.runtimeOptions);const systemClient=params.systemIsDistinct?createClient3("system-runtime",params.systemDatabaseName,params.systemOptions):runtimeClient;const readinessClient=params.isPlatform?createClient3("platform-system-readiness",params.systemDatabaseName,{...params.readinessOptions}):systemClient;return{runtimeClient,systemClient,readinessClient,async close(){const uniqueClients=[...new Set([runtimeClient,systemClient,readinessClient])];await Promise.allSettled(uniqueClients.map(client=>client.close()))}}}init_database_config();import{createHash as createHash3}from"node:crypto";init_runtime_postgres_client();import{createHash}from"node:crypto";var PlatformDatabaseCapabilityConfigurationError=class extends Error{code;constructor(code="PLATFORM_DB_CAPABILITY_INVALID"){super("Platform database capability is not configured correctly");this.code=code;this.name="PlatformDatabaseCapabilityConfigurationError"}};function fingerprint(value2){return createHash("sha256").update(value2.toLowerCase()).digest("hex").slice(0,12)}function endpointIdentity(urlText,capability2){let url2;try{url2=new URL(urlText)}catch{throw new PlatformDatabaseCapabilityConfigurationError}if(url2.protocol!=="postgres:"&&url2.protocol!=="postgresql:"){throw new PlatformDatabaseCapabilityConfigurationError}const database=decodeURIComponent(url2.pathname.replace(/^\/+/u,""));const port=url2.port?Number(url2.port):5432;if(!url2.hostname||!url2.username||!database||!Number.isInteger(port)||port<1||port>65535){throw new PlatformDatabaseCapabilityConfigurationError}return{capability:capability2,hostFingerprint:fingerprint(url2.hostname),roleFingerprint:fingerprint(decodeURIComponent(url2.username)),port,database,tlsMode:url2.searchParams.get("sslmode")?.trim()||"default"}}function expectedPlatformDatabase(env){const runtimeUrl=env.PLATFORM_DATABASE_URL?.trim()||env.DATABASE_URL?.trim();if(!runtimeUrl)throw new PlatformDatabaseCapabilityConfigurationError;return endpointIdentity(runtimeUrl,"catalog_read").database}function assertDistinctCapabilityRoles(identities){if(new Set(identities.map(({roleFingerprint})=>roleFingerprint)).size!==identities.length){throw new PlatformDatabaseCapabilityConfigurationError}}function resolvePlatformDatabaseCapabilityConfig(params){if(!params.isPlatform||params.driver==="pglite"){return{backupReadUrl:null,backupReadIdentity:null,catalogReadUrl:null,catalogReadIdentity:null,databaseAdminUrl:null,databaseAdminIdentity:null,tenantDdlUrl:null,tenantDdlIdentity:null}}const env=params.env??process.env;const backupReadUrl=env.GENCOW_BACKUP_DATABASE_URL?.trim();const catalogReadUrl=env.GENCOW_CATALOG_READ_DATABASE_URL?.trim();const databaseAdminUrl=env.GENCOW_DIRECT_DATABASE_URL?.trim();const tenantDdlUrl=env.GENCOW_DIRECT_DDL_DATABASE_URL?.trim();if(!catalogReadUrl){throw new PlatformDatabaseCapabilityConfigurationError("PLATFORM_DB_CATALOG_READ_NOT_CONFIGURED")}if(!tenantDdlUrl){throw new PlatformDatabaseCapabilityConfigurationError("PLATFORM_DB_TENANT_DDL_NOT_CONFIGURED")}const catalogReadIdentity=endpointIdentity(catalogReadUrl,"catalog_read");const backupReadIdentity=backupReadUrl?endpointIdentity(backupReadUrl,"backup_read"):null;const backupReadRole=backupReadUrl?decodeURIComponent(new URL(backupReadUrl).username):null;if(backupReadIdentity&&(backupReadRole!=="gencow_backup_reader"||backupReadIdentity.database!=="postgres")){throw new PlatformDatabaseCapabilityConfigurationError}const runtimeUrl=env.PLATFORM_DATABASE_URL?.trim()||env.DATABASE_URL?.trim()||"";const runtimeIdentity=endpointIdentity(runtimeUrl,"catalog_read");if(catalogReadIdentity.database!==expectedPlatformDatabase(env)){throw new PlatformDatabaseCapabilityConfigurationError}const tenantDdlIdentity=endpointIdentity(tenantDdlUrl,"tenant_ddl");const tenantDdlRole=decodeURIComponent(new URL(tenantDdlUrl).username);const expectedTenantDdlRole=env.GENCOW_TENANT_DDL_EXPECTED_ROLE?.trim()||"gencow_ddl_user";if(!/^[A-Za-z0-9_.@-]{1,63}$/u.test(expectedTenantDdlRole)||tenantDdlRole!==expectedTenantDdlRole){throw new PlatformDatabaseCapabilityConfigurationError}const databaseAdminIdentity=databaseAdminUrl?endpointIdentity(databaseAdminUrl,"database_admin"):null;assertDistinctCapabilityRoles([runtimeIdentity,backupReadIdentity,catalogReadIdentity,tenantDdlIdentity,databaseAdminIdentity].filter(identity2=>identity2!==null));return{backupReadUrl:backupReadUrl||null,backupReadIdentity,catalogReadUrl,catalogReadIdentity,databaseAdminUrl:databaseAdminUrl||null,databaseAdminIdentity,tenantDdlUrl,tenantDdlIdentity}}function buildPlatformCapabilityDatabaseUrl(authorityUrl,database){if(!/^app_[a-z0-9_]+$/u.test(database)){throw new PlatformDatabaseCapabilityConfigurationError}const url2=new URL(authorityUrl);url2.pathname=`/${database}`;return url2.toString()}function buildTenantDdlDatabaseUrl(authorityUrl,database){return buildPlatformCapabilityDatabaseUrl(authorityUrl,database)}init_deployment_executor_authority_contract();import{createHash as createHash2}from"node:crypto";var ROLE_ATTRIBUTE_RESULT_KEYS={superuser:"superuser",createDatabase:"createDb",createRole:"createRole",replication:"replication",bypassRls:"bypassRls"};function roleAttributesMatch(row,capability2){const expected=deploymentExecutorCapabilityAuthority(capability2).roleAttributes;const attributesMatch=Object.entries(ROLE_ATTRIBUTE_RESULT_KEYS).every(([attribute,resultKey])=>row[resultKey]===expected[attribute]);if(capability2!=="database_admin")return attributesMatch;const membershipsMatch=row.membershipCount===expected.allowedMemberships.length&&row.hasSignalBackend===expected.allowedMemberships.includes("pg_signal_backend");return attributesMatch&&membershipsMatch}function roleIdentityMatches(row,identity2){return typeof row.role==="string"&&createHash2("sha256").update(row.role.toLowerCase()).digest("hex").slice(0,12)===identity2.roleFingerprint}var PlatformDatabaseCapabilityUnavailableError=class extends Error{code;constructor(code){super("Platform database capability is unavailable");this.code=code;this.name="PlatformDatabaseCapabilityUnavailableError"}};function normalizeCapabilityRows(result3){if(!Array.isArray(result3)){throw new PlatformDatabaseCapabilityUnavailableError("PLATFORM_DB_CATALOG_READ_UNAVAILABLE")}return result3.filter(row=>row!==null&&typeof row==="object"&&!Array.isArray(row))}function assertSystemCapabilityProbe(rows8){const row=rows8[0];const protectedRead=Number(row?.protectedRead);if(row?.role!=="system"||row?.internalSystem!=="true"||!Number.isFinite(protectedRead)||protectedRead<0){throw new PlatformDatabaseCapabilityUnavailableError("PLATFORM_DB_SYSTEM_UNAVAILABLE")}}function assertCatalogCapabilityProbe(rows8,identity2){const row=rows8[0];const authority=deploymentExecutorCapabilityAuthority("catalog_reader");const databasePrivilegesMatch=row?.databaseCreate===authority.database.create&&row?.databaseTemporary===authority.database.temporary&&row?.schemaCreate===authority.schema.create;if(!row||row.database!==identity2.database||!roleIdentityMatches(row,identity2)||!roleAttributesMatch(row,"catalog_reader")||!databasePrivilegesMatch||row.publicTablePrivileges!==false){throw new PlatformDatabaseCapabilityUnavailableError("PLATFORM_DB_CATALOG_READ_UNAVAILABLE")}}function assertTenantDdlCapabilityProbe(rows8,identity2){const row=rows8[0];if(!row||row.database!==identity2.database||!roleIdentityMatches(row,identity2)||!roleAttributesMatch(row,"tenant_ddl")){throw new PlatformDatabaseCapabilityUnavailableError("PLATFORM_DB_TENANT_DDL_UNAVAILABLE")}}function assertDatabaseAdminCapabilityProbe(rows8,identity2){const row=rows8[0];if(!row||row.database!==identity2.database||!roleIdentityMatches(row,identity2)||!roleAttributesMatch(row,"database_admin")){throw new PlatformDatabaseCapabilityUnavailableError("PLATFORM_DB_DATABASE_ADMIN_UNAVAILABLE")}}var DATABASE_ADMIN_CAPABILITY_READINESS_SQL=`
|
|
12393
|
+
RETURNING doomed.app_id`,[input2.nodeId,retentionMs,batch]);return deletedCount(result3)}function startRuntimeActivityObserverReaper(params){const logger3=params.logger??console;let running=false;const runOnce=async()=>{if(running)return 0;running=true;let total=0;try{for(;;){const deleted=await reapExpiredRuntimeActivityObservers(params.rawSql,{nodeId:params.nodeId});total+=deleted;if(deleted<RUNTIME_ACTIVITY_OBSERVER_REAP_BATCH)break}return total}catch(error62){logger3.warn(`[runtime-activity] observer reap deferred: ${error62 instanceof Error?error62.message:String(error62)}`);return total}finally{running=false}};const interval=params.intervalMs??RUNTIME_ACTIVITY_OBSERVER_REAP_INTERVAL_MS;if(interval>0){const timer2=(params.setIntervalImpl??setInterval)(()=>void runOnce(),interval);timer2?.unref?.()}return{runOnce}}var RUNTIME_ACTIVITY_OBSERVER_REAP_RETENTION_MS,RUNTIME_ACTIVITY_OBSERVER_REAP_INTERVAL_MS,RUNTIME_ACTIVITY_OBSERVER_REAP_BATCH;var init_server_runtime_activity_observer_reaper=__esm({"../server/dist/server-runtime-activity-observer-reaper.js"(){"use strict";RUNTIME_ACTIVITY_OBSERVER_REAP_RETENTION_MS=10*6e4;RUNTIME_ACTIVITY_OBSERVER_REAP_INTERVAL_MS=5*6e4;RUNTIME_ACTIVITY_OBSERVER_REAP_BATCH=500}});function activitySyncPreservationReason(error62){const code=error62 instanceof Error?error62.message:"";if(code==="RUNTIME_ACTIVITY_CHECKPOINT_MISSING"){return"runtime_activity_checkpoint_missing"}if(code==="RUNTIME_ACTIVITY_CHECKPOINT_NOT_CURRENT"){return"runtime_activity_checkpoint_not_current"}if(code==="RUNTIME_ACTIVITY_BINDING_CONVERGENCE_TIMEOUT"){return"runtime_activity_binding_sync_timeout"}return"runtime_activity_binding_sync_failed"}async function executeRuntimeIdleCertificationWithActivityBinding(params){const requestedTimeoutMs=params.activitySyncTimeoutMs??RUNTIME_IDLE_CERTIFICATION_ACTIVITY_SYNC_TIMEOUT_MS;const timeoutMs=Number.isFinite(requestedTimeoutMs)?Math.max(1,Math.min(requestedTimeoutMs,RUNTIME_IDLE_CERTIFICATION_ACTIVITY_SYNC_TIMEOUT_MS)):RUNTIME_IDLE_CERTIFICATION_ACTIVITY_SYNC_TIMEOUT_MS;const synchronization=params.activity.synchronizeRuntimeBinding(params.request.appId,params.request.appName,{timeoutMs}).then(()=>({status:"ready"}),error62=>({status:"failed",error:error62}));let timeout;const outcome2=await Promise.race([synchronization,new Promise(resolveTimeout=>{timeout=setTimeout(()=>resolveTimeout({status:"timeout"}),timeoutMs)})]);if(timeout)clearTimeout(timeout);if(outcome2.status==="timeout"){return{kind:"preserved",reason:"runtime_activity_binding_sync_timeout"}}if(outcome2.status==="failed"){return{kind:"preserved",reason:activitySyncPreservationReason(outcome2.error)}}return params.executeScaleDown()}var RUNTIME_IDLE_CERTIFICATION_ACTIVITY_SYNC_TIMEOUT_MS;var init_server_runtime_idle_certification_control=__esm({"../server/dist/server-runtime-idle-certification-control.js"(){"use strict";RUNTIME_IDLE_CERTIFICATION_ACTIVITY_SYNC_TIMEOUT_MS=2e3}});import{resolve as resolve168}from"node:path";function runtimeActivityFencedTombstoneMs(env){const parsed=Number(env.GENCOW_RUNTIME_ACTIVITY_FENCED_TOMBSTONE_MS);return Number.isFinite(parsed)&&env.GENCOW_RUNTIME_ACTIVITY_FENCED_TOMBSTONE_MS?.trim()?Math.min(36e5,Math.max(6e4,Math.trunc(parsed))):void 0}async function bootstrapRuntimeLifecycleControl(params){const logger3=params.logger??console;const runtimeNodeId=params.currentNodeId??"node-1";const sleepConfig=loadSleepMaintenanceConfig({env:process.env});const runtimeActivity=createRuntimeActivityTracker({rawSql:params.rawSql,nodeId:runtimeNodeId,idleTimeoutMs:sleepConfig.sleepTimeoutMinutes*6e4,setIntervalImpl:params.setIntervalImpl,logger:logger3,fencedTombstoneMs:runtimeActivityFencedTombstoneMs(process.env),onDrainStateQuery:params.onDrainStateQuery});void startRuntimeActivityObserverReaper({rawSql:params.rawSql,nodeId:runtimeNodeId,setIntervalImpl:params.setIntervalImpl,logger:logger3}).runOnce();const{configureRuntimeLifecycleActivityCoordinator}=await import(resolve168(params.functionsPath,"../src/runtime-lifecycle-activity-coordinator.ts"));configureRuntimeLifecycleActivityCoordinator(runtimeActivity);configureRuntimeActivityObserver(({appId,appName})=>{runtimeActivity.recordExternalActivity(appId,appName);void runtimeActivity.flush(appId).catch(error62=>{logger3.warn(`[runtime-activity] websocket checkpoint deferred: ${error62 instanceof Error?error62.message:String(error62)}`)})});const{apps:apps5,appRuntimeActivityState:appRuntimeActivityState2,appRuntimeDesiredState:appRuntimeDesiredState3}=await import(resolve168(params.functionsPath,"schema.ts"));const{and:and147,eq:eq163}=await import("drizzle-orm");const{executeAutomaticScaleDown}=await import(resolve168(params.functionsPath,"../src/runtime-auto-scale-down.ts"));const{RUNTIME_PROD_IDLE_CERTIFICATION_CONFIRMATION:RUNTIME_PROD_IDLE_CERTIFICATION_CONFIRMATION2,RUNTIME_QC_IDLE_CERTIFICATION_CONFIRMATION:RUNTIME_QC_IDLE_CERTIFICATION_CONFIRMATION2,runtimeIdleCertificationControllerId:runtimeIdleCertificationControllerId3}=await import(resolve168(params.functionsPath,"../src/runtime-scale-down-store.ts"));const{isActivePlatformControllerSlot}=await import(resolve168(params.functionsPath,"platform-slot-guard.ts"));const controllerEnv={GENCOW_NODE_ID:runtimeNodeId,PORT:params.currentPlatformPort?.trim()||process.env.PORT?.trim()};const isActiveController=params.isActiveController??(()=>isActivePlatformControllerSlot({db:params.db},controllerEnv));const assertActiveController=params.assertActiveController??(tx=>isActivePlatformControllerSlot({db:tx},controllerEnv,{lockForUpdate:true}));const fetchAppStatuses=async()=>await params.db.select({id:apps5.id,name:apps5.name,status:apps5.status,hasBackend:apps5.hasBackend,parentAppId:apps5.parentAppId,nodeId:apps5.nodeId,authorityMode:appRuntimeDesiredState3.authorityMode,lastUserActivityAt:appRuntimeActivityState2.lastUserActivityAt}).from(apps5).leftJoin(appRuntimeDesiredState3,eq163(appRuntimeDesiredState3.appId,apps5.id)).leftJoin(appRuntimeActivityState2,eq163(appRuntimeActivityState2.appId,apps5.id));const refreshRuntimeActivityBindings=async appRows=>{for(const app2 of appRows??await fetchAppStatuses()){if(app2.status!=="running"||!app2.hasBackend||(app2.nodeId?.trim()||"node-1")!==runtimeNodeId){continue}try{await runtimeActivity.hydrateRuntime(app2.id,app2.name)}catch(error62){logger3.warn(`[runtime-activity] binding checkpoint preserved for retry: ${error62 instanceof Error?error62.message:String(error62)}`)}}};let initialActivityHydration;const startActivityHydrationAfterListen=()=>initialActivityHydration??=refreshRuntimeActivityBindings().catch(()=>{logger3.warn("[runtime-activity] initial binding hydration deferred; maintenance refresh will retry")});const requestAutomaticScaleDown=async candidate=>{if(!candidate.appId)return{kind:"preserved",reason:"app_identity_missing"};if(!await isActiveController()){return{kind:"skipped",reason:"controller_slot_inactive"}}if(candidate.reason==="ghost_idle"){return{kind:"remediation",reason:"idle_projection_has_runtime"}}return executeAutomaticScaleDown({db:params.db,appId:candidate.appId,appName:candidate.appName,currentNodeId:runtimeNodeId,trigger:candidate.trigger,activity:runtimeActivity,isControllerActive:isActiveController,assertControllerActive:assertActiveController,removeRuntimeRoute:params.removeRuntimeRoute})};const requestRuntimeIdleCertification=async request=>{if(!Number.isSafeInteger(request.appId)||request.appId<=0||typeof request.appName!=="string"||request.appName.trim()===""||request.appName.length>128||!Number.isSafeInteger(request.expectedRolloutRevision)||request.expectedRolloutRevision<=0||![RUNTIME_PROD_IDLE_CERTIFICATION_CONFIRMATION2,RUNTIME_QC_IDLE_CERTIFICATION_CONFIRMATION2].includes(request.confirmation)){return{kind:"skipped",reason:"idle_certification_invalid"}}if(!await isActiveController()){return{kind:"skipped",reason:"controller_slot_inactive"}}const appRows=await params.db.select({id:apps5.id,name:apps5.name}).from(apps5).where(and147(eq163(apps5.id,request.appId),eq163(apps5.name,request.appName))).limit(1);if(!appRows[0]){return{kind:"preserved",reason:"app_identity_changed"}}const certificationRequest={...request,appId:appRows[0].id,appName:appRows[0].name,scope:request.confirmation===RUNTIME_PROD_IDLE_CERTIFICATION_CONFIRMATION2?"prod":"qc"};return executeRuntimeIdleCertificationWithActivityBinding({request:certificationRequest,activity:runtimeActivity,executeScaleDown:()=>executeAutomaticScaleDown({db:params.db,appId:certificationRequest.appId,appName:certificationRequest.appName,currentNodeId:runtimeNodeId,trigger:"idle_timeout",controllerId:runtimeIdleCertificationControllerId3(certificationRequest.scope,certificationRequest.appId),productionIdleCertification:certificationRequest,activity:runtimeActivity,isControllerActive:isActiveController,assertControllerActive:assertActiveController,removeRuntimeRoute:params.removeRuntimeRoute})})};return{runtimeActivity,fetchAppStatuses,refreshRuntimeActivityBindings,startActivityHydrationAfterListen,requestAutomaticScaleDown,requestRuntimeIdleCertification,runtimeIdleCertificationConfirmation:RUNTIME_PROD_IDLE_CERTIFICATION_CONFIRMATION2,runtimeIdleCertificationConfirmations:[RUNTIME_PROD_IDLE_CERTIFICATION_CONFIRMATION2,RUNTIME_QC_IDLE_CERTIFICATION_CONFIRMATION2]}}var init_server_runtime_lifecycle_control=__esm({"../server/dist/server-runtime-lifecycle-control.js"(){"use strict";init_server_platform_maintenance();init_server_runtime_activity();init_server_runtime_activity_observer_reaper();init_server_runtime_idle_certification_control();init_ws_gateway2()}});import{resolve as resolve169}from"path";async function bootstrapPlatformIdleWake(input2){const{params,platformNodeId,isActiveLifecycleController,removeAppPortIfEquals:removeAppPortIfEquals2}=input2;const lifecycle=await bootstrapRuntimeLifecycleControl({functionsPath:params.functionsPath,db:params.db,rawSql:params.rawSql,currentNodeId:platformNodeId,currentPlatformPort:process.env.PORT?.trim()||null,isActiveController:isActiveLifecycleController,removeRuntimeRoute:(appName,expectedPort)=>{if(Number.isInteger(expectedPort)&&Number(expectedPort)>0){removeAppPortIfEquals2(appName,Number(expectedPort))}},setIntervalImpl:params.setIntervalImpl,logger:params.logger,onDrainStateQuery:()=>recordServingPlanePlatformDbQuery("runtime_drain_state")});return{...lifecycle,registerIdleWakeRoutes:async()=>{registerRuntimeIdleCertificationRoute({app:params.app,maintenanceToken:resolvePlatformMaintenanceToken(params.platformMaintenanceEnv??process.env),confirmationValue:lifecycle.runtimeIdleCertificationConfirmations,requestRuntimeIdleCertification:lifecycle.requestRuntimeIdleCertification,logger:params.logger});const{registerRuntimeDurableWakeRoute}=await import(resolve169(params.functionsPath,"../src/runtime-durable-wake-route.ts"));registerRuntimeDurableWakeRoute({app:params.app,getDb:()=>params.db,env:process.env,logger:params.logger});const{registerRuntimeRouteActivityRoute}=await import(resolve169(params.functionsPath,"../src/runtime-route-activity-route.ts"));registerRuntimeRouteActivityRoute({app:params.app,getDb:()=>params.db,nodeId:platformNodeId||"node-1",activity:lifecycle.runtimeActivity,env:process.env,logger:params.logger})}}}var init_server_platform_idle_wake_bootstrap=__esm({"../server/dist/server-platform-idle-wake-bootstrap.js"(){"use strict";init_server_runtime_idle_certification();init_server_runtime_lifecycle_control();init_server_serving_plane_dependency_metrics();init_server_platform_maintenance_http()}});import{resolve as resolve170}from"path";async function initializePlatformRuntimeGenerationForServer(functionsPath){const{initializePlatformCurrentRuntimeGeneration}=await import(resolve170(functionsPath,"../src/current-runtime-generation.ts"));initializePlatformCurrentRuntimeGeneration({repoRoot:resolve170(functionsPath,"../../..")})}var init_server_platform_runtime_generation_bootstrap=__esm({"../server/dist/server-platform-runtime-generation-bootstrap.js"(){"use strict"}});function readPositiveIntEnv3(name2,fallback){const value2=Number(process.env[name2]);return Number.isFinite(value2)&&value2>0?Math.floor(value2):fallback}function nowMs(){return globalThis.performance?.now?.()??Date.now()}function toMB(bytes2){return typeof bytes2==="number"?Math.round(bytes2/1024/1024*10)/10:null}function addLagSample(valueMs){lagSamplesMs.push(Math.max(0,Math.round(valueMs*10)/10));if(lagSamplesMs.length>windowSize){lagSamplesMs=lagSamplesMs.slice(lagSamplesMs.length-windowSize)}}function summarizeMs(values2){if(values2.length===0){return{count:0,p50Ms:null,p95Ms:null,maxMs:null,lastMs:null}}const sorted=[...values2].sort((a,b5)=>a-b5);const percentile=pct=>{const index28=Math.max(0,Math.min(sorted.length-1,Math.floor((sorted.length-1)*pct/100)));return sorted[index28]};return{count:values2.length,p50Ms:percentile(50),p95Ms:percentile(95),maxMs:sorted[sorted.length-1],lastMs:values2[values2.length-1]}}function toMiB(bytes2){return typeof bytes2==="number"?Math.round(bytes2/1024/1024):null}function readEventLoopLagWarnMs(){return readPositiveIntEnv3("GENCOW_RUNTIME_EVENT_LOOP_LAG_WARN_MS",DEFAULT_EVENT_LOOP_LAG_WARN_MS)}function warnIfEventLoopLagOverThreshold(lagMs){if(!(lagMs>=readEventLoopLagWarnMs()))return;try{const memoryUsage=typeof process!=="undefined"&&process.memoryUsage?process.memoryUsage():void 0;console.warn(`[runtime] event loop lag lagMs=${Math.round(lagMs)} rssMiB=${toMiB(memoryUsage?.rss)} heapMiB=${toMiB(memoryUsage?.heapUsed)}`)}catch{}}function observeEventLoopLagForTests(currentTimeMs){if(lastTickAtMs===0){lastTickAtMs=currentTimeMs;return null}const lagMs=currentTimeMs-lastTickAtMs-sampleIntervalMs;lastTickAtMs=currentTimeMs;addLagSample(lagMs);warnIfEventLoopLagOverThreshold(lagMs);return Math.max(0,lagMs)}function observeEventLoopLag(){observeEventLoopLagForTests(nowMs())}function startRuntimeMetricsSampler(options={}){if(timer)return;sampleIntervalMs=options.intervalMs??sampleIntervalMs;windowSize=options.maxSamples??windowSize;lastTickAtMs=nowMs();timer=setInterval(observeEventLoopLag,sampleIntervalMs);timer.unref?.()}function getRuntimeMetricsSnapshot(){const memoryUsage=typeof process!=="undefined"&&process.memoryUsage?process.memoryUsage():void 0;const uptimeSec=typeof process!=="undefined"&&typeof process.uptime==="function"?process.uptime():null;const eventLoopSummary=summarizeMs(lagSamplesMs);return{timestamp:new Date().toISOString(),uptimeSec:uptimeSec===null?null:Math.round(uptimeSec),memory:{rssMB:toMB(memoryUsage?.rss),heapUsedMB:toMB(memoryUsage?.heapUsed),heapTotalMB:toMB(memoryUsage?.heapTotal),externalMB:toMB(memoryUsage?.external)},eventLoopLag:{...eventLoopSummary,sampleIntervalMs,windowSize}}}function resetRuntimeMetricsForTests(options={}){if(timer){clearInterval(timer);timer=null}sampleIntervalMs=options.intervalMs??DEFAULT_SAMPLE_INTERVAL_MS;windowSize=options.maxSamples??DEFAULT_WINDOW_SIZE;lagSamplesMs=[];lastTickAtMs=0}var DEFAULT_SAMPLE_INTERVAL_MS,DEFAULT_WINDOW_SIZE,DEFAULT_EVENT_LOOP_LAG_WARN_MS,sampleIntervalMs,windowSize,lagSamplesMs,lastTickAtMs,timer;var init_runtime_metrics=__esm({"../platform/src/runtime-metrics.ts"(){"use strict";DEFAULT_SAMPLE_INTERVAL_MS=1e3;DEFAULT_WINDOW_SIZE=300;DEFAULT_EVENT_LOOP_LAG_WARN_MS=2e3;sampleIntervalMs=readPositiveIntEnv3("GENCOW_RUNTIME_METRICS_INTERVAL_MS",DEFAULT_SAMPLE_INTERVAL_MS);windowSize=readPositiveIntEnv3("GENCOW_RUNTIME_METRICS_WINDOW_SIZE",DEFAULT_WINDOW_SIZE);lagSamplesMs=[];lastTickAtMs=0;timer=null}});var runtime_metrics_exports={};__export(runtime_metrics_exports,{getRuntimeMetricsSnapshot:()=>getRuntimeMetricsSnapshot,observeEventLoopLagForTests:()=>observeEventLoopLagForTests,resetRuntimeMetricsForTests:()=>resetRuntimeMetricsForTests,startRuntimeMetricsSampler:()=>startRuntimeMetricsSampler,summarizeMs:()=>summarizeMs});var init_runtime_metrics2=__esm({"../server/dist/runtime-metrics.js"(){"use strict";init_runtime_metrics()}});var server_platform_runtime_bootstrap_exports={};__export(server_platform_runtime_bootstrap_exports,{bootstrapPlatformRuntime:()=>bootstrapPlatformRuntime,createPlatformActiveSlotWorkerCheck:()=>createPlatformActiveSlotWorkerCheck,createPlatformSubdomainRegex:()=>createPlatformSubdomainRegex,platformNodeProxyWsTunnel:()=>platformNodeProxyWsTunnel,platformWebsocketGateway:()=>platformWebsocketGateway,registerCapacityRoute:()=>registerCapacityRoute,registerPlatformInternalMiddleware:()=>registerPlatformInternalMiddleware,registerRealtimeNotifyRoute:()=>registerRealtimeNotifyRoute,registerRuntimeMetricsRoute:()=>registerRuntimeMetricsRoute,startGatewayRealtimeUsageMeteringForRuntime:()=>startGatewayRealtimeUsageMeteringForRuntime});import{resolve as resolve171}from"path";function registerRealtimeNotifyRoute(params){const logger3=params.logger??console;params.app.post("/internal/realtime-notify",async c2=>{try{const body=await c2.req.json();if(!body.type){return c2.json({error:"type required"},400)}const auth=await params.gateway.authorizeRealtimeNotifyRequest({appName:body.appName,token:c2.req.header("X-Internal-Token")||"",findAppByName:async appName=>{const rows8=await params.db.select({id:params.appsTable.id,name:params.appsTable.name}).from(params.appsTable).where(params.eqOp(params.appsTable.name,appName)).limit(1);return rows8[0]??null},generateInternalToken:params.generateInternalToken});if(!auth.ok){return c2.json({error:auth.error},auth.status)}const rateLimit2=params.gateway.consumeRealtimeNotifyRateLimit?.(auth.appName);if(rateLimit2&&!rateLimit2.ok){return c2.json({error:"Realtime notify rate limit exceeded",retryAfterMs:rateLimit2.retryAfterMs},429)}const forwarded=await forwardPlatformRealtimeNotify({appName:auth.appName,body,token:c2.req.header("X-Internal-Token")||"",logger:logger3});if(forwarded){const forwardedBody=await forwarded.json().catch(()=>({error:"Realtime gateway unavailable"}));return c2.json(forwardedBody,forwarded.status)}if(body.type==="emit"){if(typeof body.queryKey!=="string"||body.queryKey.length===0){return c2.json({error:"queryKey required"},400)}const sent=params.gateway.notifyEmit(auth.appName,body.queryKey,body.data);return c2.json({ok:true,sent})}if(body.type==="invalidate"){const queryKeys=typeof body.queryKey==="string"&&body.queryKey.length>0?[body.queryKey]:Array.isArray(body.queryKeys)&&body.queryKeys.every(key2=>typeof key2==="string"&&key2.length>0)?[...new Set(body.queryKeys)]:null;if(!queryKeys)return c2.json({error:"queryKey required"},400);const sent=params.gateway.notifyInvalidate(auth.appName,queryKeys);return c2.json({ok:true,sent})}if(body.type==="query_invalidate"){if(typeof body.query!=="string"||body.query.length===0){return c2.json({error:"query required"},400)}if(typeof body.subscriptionKey!=="string"||body.subscriptionKey.length===0){return c2.json({error:"subscriptionKey required"},400)}if(typeof body.scopeHash!=="string"||body.scopeHash.length===0||body.scopeHash.length>200){return c2.json({error:"scopeHash required"},400)}const eventId=typeof body.eventId==="string"&&body.eventId.length>0?body.eventId:void 0;const legacyQueryKey=normalizeOptionalPlatformRuntimeString(body.legacyQueryKey);if(legacyQueryKey===null){return c2.json({error:"legacyQueryKey must be a non-empty string"},400)}const crudRealtimeEmitMode=body.crudRealtimeEmitMode===void 0?void 0:body.crudRealtimeEmitMode==="legacy"||body.crudRealtimeEmitMode==="scoped"||body.crudRealtimeEmitMode==="dual"?body.crudRealtimeEmitMode:null;if(crudRealtimeEmitMode===null){return c2.json({error:"crudRealtimeEmitMode must be legacy, scoped, or dual"},400)}const sent=params.gateway.notifyQueryInvalidate(auth.appName,body.query,body.subscriptionKey,eventId,body.scopeHash,legacyQueryKey,crudRealtimeEmitMode);return c2.json({ok:true,sent})}if(body.type==="query_revoke"){if(typeof body.query!=="string"||body.query.length===0){return c2.json({error:"query required"},400)}if(typeof body.subscriptionKey!=="string"||body.subscriptionKey.length===0){return c2.json({error:"subscriptionKey required"},400)}if(typeof body.scopeHash!=="string"||body.scopeHash.length===0||body.scopeHash.length>200){return c2.json({error:"scopeHash required"},400)}const epoch=normalizeOptionalPlatformRuntimeString(body.epoch);const reason=normalizeOptionalPlatformRuntimeString(body.reason);if(epoch===null)return c2.json({error:"epoch must be a non-empty string"},400);if(reason===null)return c2.json({error:"reason must be a non-empty string"},400);const sent=params.gateway.notifyQueryRevoke(auth.appName,body.query,body.subscriptionKey,epoch,reason,body.scopeHash);return c2.json({ok:true,sent})}if(body.type==="channel_publish"){if(typeof body.channelKey!=="string"||body.channelKey.length===0){return c2.json({error:"channelKey required"},400)}const eventId=typeof body.eventId==="string"&&body.eventId.length>0?body.eventId:void 0;const sent=params.gateway.notifyChannelPublish(auth.appName,body.channelKey,body.data,eventId);return c2.json({ok:true,sent})}if(body.type==="channel_invalidate"){if(typeof body.channelKey!=="string"||body.channelKey.length===0){return c2.json({error:"channelKey required"},400)}const sent=params.gateway.notifyChannelInvalidate(auth.appName,body.channelKey);return c2.json({ok:true,sent})}if(body.type==="channel_revoke"){if(typeof body.channelKey!=="string"||body.channelKey.length===0){return c2.json({error:"channelKey required"},400)}const epoch=body.epoch===void 0||body.epoch===null?void 0:typeof body.epoch==="string"&&body.epoch.length>0&&body.epoch.length<=200?body.epoch:null;const reason=body.reason===void 0||body.reason===null?void 0:typeof body.reason==="string"&&body.reason.length>0&&body.reason.length<=200?body.reason:null;if(epoch===null)return c2.json({error:"epoch must be a non-empty string"},400);if(reason===null)return c2.json({error:"reason must be a non-empty string"},400);const sent=params.gateway.notifyChannelRevoke(auth.appName,body.channelKey,epoch,reason);return c2.json({ok:true,sent})}return c2.json({error:`Unknown type: ${body.type}`},400)}catch(error62){const message=error62 instanceof Error?error62.message:String(error62);logger3.error("[ws-gateway] notify error:",message);return c2.json({error:REALTIME_NOTIFY_INTERNAL_ERROR},500)}})}async function bootstrapPlatformRuntime(params){const logger3=params.logger??console;const timed=params.startupTiming??{step:(_name,operation)=>operation()};const fetchImpl=params.fetchImpl??fetch;const setIntervalImpl=params.setIntervalImpl??setInterval;const clearIntervalImpl=params.clearIntervalImpl??clearInterval;const setTimeoutImpl=params.setTimeoutImpl??setTimeout;const subdomainRegex=createPlatformSubdomainRegex(params.platformDomain);const{apps:appsTable,customDomainBindings:customDomainBindingsTable,platformNodes:platformNodes2}=await timed.step("platform:import-schema",()=>import(resolve171(params.functionsPath,"schema.ts")));const{eq:eqOp,and:andOp,inArray:inArrayOp,sql:sqlOp}=await timed.step("platform:import-drizzle",()=>import("drizzle-orm"));const{createProxyRequestReplayPlan}=await timed.step("platform:import-replay",()=>import(resolve171(params.functionsPath,"../src/proxy-request-replay.ts")));const{canonicalDeploymentPresentSql:canonicalDeploymentPresentSql2}=await timed.step("platform:import-deploy-admission",()=>import(resolve171(params.functionsPath,"../src/deploy-contract-admission.ts")));const{buildAppRuntimeUnavailableResult,buildPublicAppLookupDeferredResult,ensureAppRuntimeReady}=await timed.step("platform:import-app-recovery",()=>import(resolve171(params.functionsPath,"../src/app-runtime-recovery.ts")));const{createPublicRuntimeWakeCorrelation,executeLegacyRuntimeWakeByName,PUBLIC_RUNTIME_CONVERGENCE_TIMEOUT_MS:PUBLIC_RUNTIME_CONVERGENCE_TIMEOUT_MS2}=await timed.step("platform:import-lifecycle-adapter",()=>import(resolve171(params.functionsPath,"../src/simple-lifecycle/legacy-runtime-effect-adapter.ts")));await timed.step("platform:init-generation",()=>initializePlatformRuntimeGenerationForServer(params.functionsPath));const{getAppPort:getLivePort,setAppPort:setAppPort2,removeAppPort:removeAppPort2,removeAppPortIfEquals:removeAppPortIfEquals2,setAppMeta:setAppMeta2,setLastAccess:markLastAccess,hasLiveRuntimeProcess:hasLiveRuntimeProcess3,resolveLiveRuntimePort:resolveLiveRuntimePort3,reapWarmPoolStale:reapWarmPoolStale2,getWakeCapacitySnapshot:getWakeCapacitySnapshot2,setWakeCapacityMaxConcurrentRunning:setWakeCapacityMaxConcurrentRunning2,setWakeCapacityUpdateInProgress:setWakeCapacityUpdateInProgress2,generateInternalToken:generateInternalToken3,setDatabasePreflightRawSql:setDatabasePreflightRawSql2,setPlatformRuntimeDb:setPlatformRuntimeDb2,buildAppDatabaseUrl:buildAppDatabaseUrl2}=await timed.step("platform:import-provisioner",()=>loadPlatformProvisionerWithScheduledJobSigningSecret(()=>import(resolve171(params.functionsPath,"../src/provisioner.ts"))));setDatabasePreflightRawSql2(params.rawSql);wirePlatformDatabaseUrls(setPlatformRuntimeDb2,params.db,params.databaseUrlResolvers);const storageDirectRuntime=await timed.step("platform:storage-direct",()=>createPlatformStorageDirectRuntime(params.functionsPath,buildAppDatabaseUrl2));const{getRuntimeMetricsSnapshot:getRuntimeMetricsSnapshot2,startRuntimeMetricsSampler:startRuntimeMetricsSampler2}=await Promise.resolve().then(()=>(init_runtime_metrics2(),runtime_metrics_exports));const platformNodeId=process.env.GENCOW_NODE_ID?.trim()||null;const isActiveLifecycleController=createPlatformActiveWorkerCheck({rawSql:params.rawSql,nodeId:platformNodeId,logger:logger3});const{runtimeActivity,fetchAppStatuses,refreshRuntimeActivityBindings,startActivityHydrationAfterListen,requestAutomaticScaleDown,registerIdleWakeRoutes}=await timed.step("platform:idle-wake",()=>bootstrapPlatformIdleWake({params:{...params,setIntervalImpl,logger:logger3},platformNodeId,isActiveLifecycleController,removeAppPortIfEquals:removeAppPortIfEquals2}));await timed.step("platform:lifecycle-api",()=>registerPackedPlatformLifecycleApi({...params,nodeId:platformNodeId??void 0,logger:logger3}));registerPlatformRuntimeInternalMiddleware(params.app,params.functionsPath);await timed.step("platform:idle-wake-routes",()=>registerIdleWakeRoutes());bootstrapLegacyRuntimeRecoveryRoute(params.app,params.db,appsTable,eqOp,params.functionsPath,platformNodeId||"node-1",process.env.GENCOW_INTERNAL_TOKEN||"",createPlatformActiveWorkerCheck({rawSql:params.rawSql,nodeId:platformNodeId,logger:logger3,uncached:true}),logger3);const nodeProxyKeyId=process.env.GENCOW_NODE_PROXY_KEY_ID?.trim()||null;const nodeProxySecret=process.env.GENCOW_NODE_PROXY_SECRET?.trim()||null;const nodeProxyEnabled=Boolean(platformNodeId&&nodeProxyKeyId&&nodeProxySecret);const nodeProxyHttpClient=nodeProxyEnabled?await timed.step("platform:import-node-proxy",()=>import(resolve171(params.functionsPath,"../src/node-proxy-http-client.ts"))):null;const nodeProxyInternalRoutes=nodeProxyEnabled?await timed.step("platform:import-node-routes",()=>import(resolve171(params.functionsPath,"../src/platform-internal-routes.ts"))):null;const nodeOpsPath=resolve171(params.functionsPath,"../src/platform-node-ops.ts");const nodeOpsRoutes=await timed.step("platform:import-node-ops",()=>import(nodeOpsPath).catch(()=>null));const routeProjectionRuntime=await timed.step("platform:route-projection",()=>bootstrapRuntimeRouteProjectionForPlatform({app:params.app,db:params.db,functionsPath:params.functionsPath,nodeId:platformNodeId||"node-1",getAppPort:getLivePort,setAppPort:setAppPort2,fetchImpl,logger:logger3,setIntervalImpl}));await timed.step("platform:analytics-ingest-route",()=>registerManagedAnalyticsIngestRoute(params.app,params.functionsPath,params.analyticsRawSql??params.rawSql,params.db,void 0,params.analyticsCatalogAuthority));await timed.step("platform:media-storage-bridge",()=>registerMediaWorkerStorageBridgeForRuntime(params,logger3));const[{createAppProxyRouteCache,resolveAppProxyRouteCacheConfig},{listInstalledAppRouteCacheTriggerNames}]=await timed.step("platform:import-app-route-cache",()=>Promise.all([import(resolve171(params.functionsPath,"../src/app-proxy-route-cache.ts")),import(resolve171(params.functionsPath,"../src/app-route-cache-invalidation-signal.ts"))]));const appRouteCache=createAppProxyRouteCache({async loadAppRow(appName){const rows8=await params.db.select({id:appsTable.id,instanceId:appsTable.instanceId,name:appsTable.name,port:appsTable.port,status:appsTable.status,statusReason:appsTable.statusReason,dataDir:appsTable.dataDir,staticDeployedAt:appsTable.staticDeployedAt,currentStaticGenerationRef:appsTable.currentStaticGenerationRef,hasBackend:appsTable.hasBackend,plan:appsTable.plan,customDomain:appsTable.customDomain,customDomainStatus:appsTable.customDomainStatus,nodeId:appsTable.nodeId,ownerAccountHold:appsTable.ownerAccountHold,ownerAccountHoldReason:appsTable.ownerAccountHoldReason,runtimeAuthorityMode:sqlOp`(SELECT desired.authority_mode FROM app_runtime_desired_state AS desired WHERE desired.app_id = ${appsTable.id} LIMIT 1)`,canonicalDeploymentPresent:canonicalDeploymentPresentSql2({currentDeploymentId:appsTable.currentDeployId,appId:appsTable.id})}).from(appsTable).where(eqOp(appsTable.name,appName));return rows8[0]??null},onLoad:()=>recordServingPlanePlatformDbQuery("app_catalog"),config:resolveAppProxyRouteCacheConfig(process.env),databaseUrl:(params.wakeSignalEnv??process.env).GENCOW_WAKE_SIGNAL_DATABASE_URL,listInstalledTriggerNames:()=>listInstalledAppRouteCacheTriggerNames(params.db)});const{createPlatformNodeRouteCache,resolvePlatformNodeRouteCacheConfig}=await timed.step("platform:import-node-route-cache",()=>import(resolve171(params.functionsPath,"../src/platform-node-route-cache.ts")));const platformNodeRouteCache=nodeProxyEnabled&&platformNodes2?createPlatformNodeRouteCache({async loadNode(nodeId){const rows8=await params.db.select({id:platformNodes2.id,status:platformNodes2.status,internalOrigin:platformNodes2.internalOrigin,lastHeartbeatAt:platformNodes2.lastHeartbeatAt,gatewayReady:platformNodes2.gatewayReady,gatewayCheckedAt:platformNodes2.gatewayCheckedAt}).from(platformNodes2).where(eqOp(platformNodes2.id,nodeId)).limit(1);return rows8[0]?buildServerPlatformNodeRouteRecord(rows8[0]):null},onLoad:()=>recordServingPlanePlatformDbQuery("platform_node_catalog"),config:resolvePlatformNodeRouteCacheConfig(process.env)}):void 0;const{wireRealtimeLimitCache}=await timed.step("platform:import-realtime-limit-cache",()=>import(resolve171(params.functionsPath,"../src/realtime-limit-cache.ts")));const realtimeLimitCache=wireRealtimeLimitCache({routeCache:appRouteCache,loadLimit:loadRealtimeConnectionLimit,env:process.env});registerPlatformAppProxy({app:params.app,resolveRealtimeConnectionLimit:realtimeLimitCache.resolve,platformDomain:params.platformDomain,publicWakeTimeoutMs:PUBLIC_RUNTIME_CONVERGENCE_TIMEOUT_MS2,reservedHosts:params.reservedAppProxyHosts,subdomainRegex,getBunServer:params.getBunServer,domainLookupDb:params.db,resolveExistingOnlyRoute:routeProjectionRuntime.resolveExistingOnlyRoute,...createPlatformCustomDomainProxyResolvers({db:params.db,appsTable,customDomainBindingsTable,andOp,eqOp}),findAppRow:appRouteCache.findAppRow,findAppRowFresh:appRouteCache.findAppRowFresh,findAppRowMetersCatalogLoads:true,currentNodeId:nodeProxyEnabled?platformNodeId:null,isAppRuntimeProjectionBlocked:routeProjectionRuntime.isAppProjectionBlocked,loadAppRouteNode:platformNodeRouteCache?nodeId=>platformNodeRouteCache.loadNode(nodeId):void 0,loadAppRouteNodeMetersCatalogLoads:true,proxyRemoteNodeRequest:nodeProxyEnabled&&nodeProxyHttpClient?({c:c2,host,appId,appName,nodeId,origin,body})=>{recordNodeRouteMetric2({protocol:"http",kind:"remote",appName});return nodeProxyHttpClient.proxyRemoteNodeHttpRequest({request:c2.req.raw,originalHost:host,origin,sourceNode:platformNodeId,targetNode:nodeId,keyId:nodeProxyKeyId,secret:nodeProxySecret,body,operationClass:"tenant",routeBinding:{appId,appName}})}:void 0,proxyRemoteNodeWebSocket:nodeProxyEnabled?async({c:c2,host,appName,nodeId,origin})=>{recordNodeRouteMetric2({protocol:"ws",kind:"remote",appName});return createNodeProxyWsTunnelUpgradeResponse({server:params.getBunServer(),request:c2.req.raw,originalHost:host,origin,sourceNode:platformNodeId,targetNode:nodeId,keyId:nodeProxyKeyId,secret:nodeProxySecret})}:void 0,generateInternalToken:generateInternalToken3,authorizeExistingOnlyRuntimeProbe:createExistingOnlyRuntimeProbeAuthorizer(generateInternalToken3),rawSql:params.rawSql,platformStorageEnv:params.platformStorageBridgeEnv,analyticsRawSql:params.analyticsRawSql??params.rawSql,functionsPath:params.functionsPath,...storageDirectRuntime,createProxyRequestReplayPlan,buildAppRuntimeUnavailableResult,buildPublicAppLookupDeferredResult,ensureAppRuntimeReady,getLivePort,setAppPort:setAppPort2,removeAppPort:removeAppPort2,removeAppPortIfEquals:removeAppPortIfEquals2,wakeRuntime:(appRow,options)=>executeLegacyRuntimeWakeByName({appName:appRow.name,expectedAppIdentity:{id:appRow.id,instanceId:appRow.instanceId},correlationId:createPublicRuntimeWakeCorrelation(appRow),deadlineAt:options?.deadlineAt}),setAppMeta:setAppMeta2,markLastAccess,beginRuntimeActivity:runtimeActivity.beginHttp,admitRuntimeActivity:runtimeActivity.admitHttp,admitRuntimeWebsocket:runtimeActivity.admitWebsocket,hasLiveRuntimeProcess:hasLiveRuntimeProcess3,resolveLiveRuntimePort:resolveLiveRuntimePort3,reapRuntimeExits:reapWarmPoolStale2,logger:logger3});logger3.log(`[platform] Subdomain proxy enabled for *.${process.env.BASE_DOMAIN||"gencow.app"}`);const autoRecoveryRuntime=await timed.step("platform:auto-recovery",()=>bootstrapPlatformAutoRecoveryWithObserver({functionsPath:params.functionsPath,db:params.db,appsTable,eqOp,andOp,inArrayOp,currentNodeId:platformNodeId,logger:logger3,fetchImpl,isActiveWorker:()=>getPlatformSlotActivity({rawSql:params.rawSql,nodeId:platformNodeId,logger:logger3}).then(x4=>x4.active),setIntervalImpl,standbyCandidate:isProcessPlatformStandbyCandidate()}));await timed.step("platform:auto-recovery-prepare",()=>autoRecoveryRuntime.prepare());const convergeRuntimeRouteProjection=requirePlatformExplicitStopConverger(autoRecoveryRuntime.convergeRuntimeRouteProjection);routeProjectionRuntime.setAbsentRouteConverger(convergeRuntimeRouteProjection);params.app.get("/internal/platform-recovery/status",c2=>c2.json(autoRecoveryRuntime.snapshot()));registerProcessPlatformSlotPromotionRoute(params.app,params.rawSql,autoRecoveryRuntime,logger3);const explicitStopReconciler=await timed.step("platform:explicit-stop-reconciler",()=>preparePlatformExplicitStopReconcilerForRuntime({functionsPath:params.functionsPath,db:params.db,currentNodeId:platformNodeId,isActiveWorker:isActiveLifecycleController,logger:logger3,setIntervalImpl,convergeRuntimeRoute:convergeRuntimeRouteProjection}));registerPlatformMaintenanceCrons({platformPort:process.env.PORT||"4100",platformMaintenanceEnv:params.platformMaintenanceEnv,logger:logger3,fetchImpl,setIntervalImpl,setTimeoutImpl,isActiveBillingWorker:createPlatformActiveSlotWorkerCheck({rawSql:params.rawSql,workerName:"billing-maintenance",logger:logger3,requireActiveReason:true}),isActiveUsageSnapshotWorker:createPlatformActiveSlotWorkerCheck({rawSql:params.rawSql,workerName:"usage-snapshot",logger:logger3,requireActiveReason:true})});registerPlatformSleepChecker({functionsPath:params.functionsPath,fetchAppStatuses,prepareRuntimeActivity:refreshRuntimeActivityBindings,requestAutomaticScaleDown,logger:logger3,setIntervalImpl,currentNodeId:platformNodeId,isActiveWorker:isActiveLifecycleController,sleepCheckIntervalMs:sleepCheckIntervalForTier(process.env.GENCOW_DEPLOY_TIER)});await timed.step("platform:cron-scheduler",()=>registerPlatformCronScheduler({functionsPath:params.functionsPath,rawSql:params.rawSql,admitRuntimeWorkload:runtimeActivity.admitWorkload}));const wakeSignalRuntime=await timed.step("platform:wake-signal",()=>createPostgresWakeSignalRuntime({rawSql:params.rawSql,env:params.wakeSignalEnv,logger:logger3}).catch(error62=>{const message=error62 instanceof Error?error62.message:String(error62);logger3.warn(`[wake-signal] PostgreSQL listener runtime disabled: ${message}`);return null}));await timed.step("platform:scheduled-jobs-poller",()=>registerScheduledJobsPoller({functionsPath:params.functionsPath,rawSql:params.rawSql,cronExecTimeoutMs:FUNCTION_TIMEOUTS.cron,logger:logger3,wakeSignalBus:wakeSignalRuntime?.bus,admitRuntimeWorkload:runtimeActivity.admitWorkload}));await timed.step("platform:state-table",()=>ensurePlatformRuntimeStateTable(params.rawSql).catch(error62=>{const message=error62 instanceof Error?error62.message:String(error62);logger3.warn(`[platform] worker active-slot table init failed: ${message}`)}));await startPlatformRuntimeWorkers({params,timed,logger:logger3,fetchImpl,setIntervalImpl,clearIntervalImpl,wakeSignalBus:wakeSignalRuntime?.bus});registerCapacityRoute({app:params.app,gateway:{getCapacity:getWakeCapacitySnapshot2}});startRuntimeMetricsSampler2();registerRuntimeMetricsRoute({app:params.app,gateway:{getRuntimeMetrics:getRuntimeMetricsSnapshot2}});registerWakeSignalDiagnosticsRoute({app:params.app,getDiagnostics:()=>wakeSignalRuntime?.getDiagnostics()??createDisabledWakeSignalDiagnostics("disabled"),getWorkerDiagnostics:()=>getPlatformWorkerDiagnostics({functionsPath:params.functionsPath})});registerPlatformNodeOpsForRuntime({nodeOpsRoutes,app:params.app,db:params.db,appsTable,platformNodes:platformNodes2,eqOp,rawSql:params.rawSql,platformDomain:params.platformDomain,platformNodeId,getCapacity:getWakeCapacitySnapshot2,setMaxConcurrentRunning:setWakeCapacityMaxConcurrentRunning2,setCapacityUpdateInProgress:setWakeCapacityUpdateInProgress2,getRuntimeMetrics:getRuntimeMetricsSnapshot2,getLivePort,setIntervalImpl,clearIntervalImpl,logger:logger3});registerRealtimeNotifyRoute({app:params.app,db:params.db,appsTable,eqOp,gateway:ws_gateway_exports,generateInternalToken:generateInternalToken3,logger:logger3});registerNodeProxyInternalRoutesForRuntime({nodeProxyEnabled,nodeProxyInternalRoutes,app:params.app,db:params.db,appsTable,eqOp,andOp,rawSql:params.rawSql,resolveRealtimeConnectionLimit:realtimeLimitCache.resolve,platformDomain:params.platformDomain,subdomainRegex,platformNodeId,nodeProxyKeyId,nodeProxySecret,generateInternalToken:generateInternalToken3,getLivePort,admitRuntimeWebsocket:runtimeActivity.admitWebsocket,logger:logger3});registerScheduledJobRoutes({app:params.app,rawSql:params.rawSql,generateInternalToken:generateInternalToken3,logger:logger3});params.app.get("/internal/ws-gateway/stats",c2=>c2.json(getStats()));params.app.get("/internal/warm-pool/stats",async c2=>{try{const{getWarmPoolStats:getWarmPoolStats2}=await import(resolve171(params.functionsPath,"../src/provisioner.ts"));return c2.json(await getWarmPoolStats2())}catch{return c2.json({enabled:false,error:"warm-pool not loaded"})}});try{await timed.step("platform:realtime-usage-metering",()=>startGatewayRealtimeUsageMeteringForRuntime({functionsPath:params.functionsPath,db:params.db,logger:logger3,setIntervalImpl}))}catch(error62){const message=error62 instanceof Error?error62.message:String(error62);logger3.error("[ws-gateway] realtime usage metering bootstrap failed:",message)}startHeartbeat();logger3.log(`[ws-gateway] WS Gateway active (max ${getGatewayLimits().maxConnectionsPerApp}/app, ${getGatewayLimits().maxTotalConnections} total)`);const startAfterListen=async()=>{await timed.step("platform:after-listen-route-recovery",()=>routeProjectionRuntime.startAfterRecovery(autoRecoveryRuntime));explicitStopReconciler.start();void startActivityHydrationAfterListen()};return{startAfterListen,close:()=>appRouteCache.close()}}var platformWebsocketGateway,platformNodeProxyWsTunnel,REALTIME_NOTIFY_INTERNAL_ERROR;var init_server_platform_runtime_bootstrap=__esm({"../server/dist/server-platform-runtime-bootstrap.js"(){"use strict";init_server_platform_maintenance();init_server_platform_runtime_sleep_tier();init_server_platform_app_proxy();init_server_platform_media_worker_storage_runtime();init_server_platform_control_plane_observer_runtime();init_server_platform_cron_scheduler();init_server_scheduled_jobs_runtime();init_platform_scheduled_job_secret();init_server_execution();init_server_wake_signal_diagnostics_route();init_server_platform_worker_diagnostics();init_platform_active_slot();init_server_platform_slot_promotion();init_server_platform_explicit_stop_reconciler_runtime();init_postgres_wake_signal_runtime();init_wake_signal_diagnostics();init_ws_gateway2();init_server_platform_node_routing();init_server_realtime_connection_limit();init_server_serving_plane_dependency_metrics();init_server_platform_node_routes_bootstrap();init_server_node_proxy_ws_tunnel();init_server_node_routing_metrics();init_server_platform_storage_direct_runtime();init_server_platform_runtime_helpers();init_server_platform_internal_middleware();init_server_platform_realtime_forwarder();init_server_platform_analytics_ingest();init_server_legacy_runtime_recovery_route();init_server_runtime_route_projection_runtime();init_server_platform_lifecycle_authority();init_server_platform_custom_domain_readiness_worker_runtime();init_server_platform_runtime_worker_startup();init_platform_database_url_resolvers();init_server_platform_lifecycle_api_runtime();init_server_platform_observability_routes();init_server_platform_idle_wake_bootstrap();init_server_platform_runtime_generation_bootstrap();init_server_platform_observability_routes();init_server_platform_runtime_helpers();platformWebsocketGateway=ws_gateway_exports;platformNodeProxyWsTunnel={handleOpen:handleNodeProxyWsTunnelOpen,handleMessage:handleNodeProxyWsTunnelMessage,handleClose:handleNodeProxyWsTunnelClose};REALTIME_NOTIFY_INTERNAL_ERROR="Internal realtime notify failed"}});function isAllowedBuilderPreviewHostPath(path5){return path5.startsWith(BUILDER_PREVIEW_PATH_PREFIX)}function registerBuilderPreviewHostGuard(params){if(!params.previewHost)return;params.app.use("*",async(c2,next)=>{const host=String(c2.req.header("host")??"").trim().toLowerCase();if(host!==params.previewHost)return next();const path5=c2.req.path??new URL(c2.req.url).pathname;if(isAllowedBuilderPreviewHostPath(path5))return next();return c2.json({error:"Not found"},404)})}function resolveIsolatedBuilderPreviewHost(origin,platformDomain){if(!origin?.trim())return null;const url2=new URL(origin.trim());if(url2.protocol!=="https:"||url2.username||url2.password||url2.pathname!=="/"||url2.search||url2.hash){throw new Error("GENCOW_BUILDER_PREVIEW_ORIGIN must be a bare HTTPS origin")}const host=url2.host.toLowerCase();if(host===platformDomain.trim().toLowerCase()){throw new Error("Builder preview origin must be isolated from the platform origin")}return host}var BUILDER_PREVIEW_PATH_PREFIX;var init_server_platform_builder_preview_origin=__esm({"../server/dist/server-platform-builder-preview-origin.js"(){"use strict";BUILDER_PREVIEW_PATH_PREFIX="/platform/builder/preview/"}});import{resolve as resolve172}from"path";async function startPlatformBuilderWorkerForRuntime(params){const env=params.env??{};const importImpl=params.importImpl??(path5=>import(path5));const mod=await importImpl(resolve172(params.functionsPath,"../src/builder-worker-runtime.ts"));mod.captureBuilderStorageRuntimeEnv(env);if(!mod.shouldStartEmbeddedBuilderWorker(env)){return null}return mod.startBuilderWorkerRuntime({db:params.db,catalogQuery:params.catalogQuery,env,isActiveWorker:params.isActiveWorker,logger:params.logger??console})}var init_server_platform_builder_worker_runtime=__esm({"../server/dist/server-platform-builder-worker-runtime.js"(){"use strict"}});var server_platform_builder_runtime_exports={};__export(server_platform_builder_runtime_exports,{bootstrapPlatformBuilderRuntime:()=>bootstrapPlatformBuilderRuntime});async function bootstrapPlatformBuilderRuntime(params){const logger3=params.logger??console;const previewHost=resolveIsolatedBuilderPreviewHost(params.env.GENCOW_BUILDER_PREVIEW_ORIGIN,params.platformDomain);registerBuilderPreviewHostGuard({app:params.app,previewHost});try{await startPlatformBuilderWorkerForRuntime({functionsPath:params.functionsPath,db:params.db,catalogQuery:params.catalogQuery,env:params.env,isActiveWorker:params.isActiveWorker,logger:logger3})}catch(error62){const message=error62 instanceof Error?error62.message:String(error62);logger3.error("[builder-worker] bootstrap failed:",message)}return{previewHost}}var init_server_platform_builder_runtime=__esm({"../server/dist/server-platform-builder-runtime.js"(){"use strict";init_server_platform_builder_preview_origin();init_server_platform_builder_worker_runtime()}});init_http_exception();var GET_MATCH_RESULT=Symbol();var bufferToFormData=(arrayBuffer,contentType)=>{return new Response(arrayBuffer,{headers:{"Content-Type":contentType.replace(/^[^;]+/,mediaType=>mediaType.toLowerCase())}}).formData()};var MAX_NESTED_OBJECTS=1e4;var isRawRequest=request=>"headers"in request;var parseBody=async(request,options=Object.create(null))=>{const{all:all2=false,dot=false}=options;const mediaType=(isRawRequest(request)?request.headers:request.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();if(mediaType==="multipart/form-data"||mediaType==="application/x-www-form-urlencoded")return parseFormData(request,{all:all2,dot});return{}};async function parseFormData(request,options){if(!isRawRequest(request)&&request.bodyCache.formData)return convertFormDataToBodyData(await request.bodyCache.formData,options);const headers=isRawRequest(request)?request.headers:request.raw.headers;const arrayBuffer=await request.arrayBuffer();const formDataPromise=bufferToFormData(arrayBuffer,headers.get("Content-Type")||"");if(!isRawRequest(request))request.bodyCache.formData=formDataPromise;const formData=await formDataPromise;if(formData)return convertFormDataToBodyData(formData,options);return{}}function convertFormDataToBodyData(formData,options){const form=Object.create(null);const nestingState={count:0};formData.forEach((value2,key2)=>{if(!(options.all||key2.endsWith("[]")))form[key2]=value2;else handleParsingAllValues(form,key2,value2)});if(options.dot)Object.entries(form).forEach(([key2,value2])=>{if(key2.includes(".")){handleParsingNestedValues(form,key2,value2,nestingState);delete form[key2]}});return form}var handleParsingAllValues=(form,key2,value2)=>{if(form[key2]!==void 0){if(Array.isArray(form[key2]))form[key2].push(value2);else form[key2]=[form[key2],value2]}else if(!key2.endsWith("[]"))form[key2]=value2;else form[key2]=[value2]};var handleParsingNestedValues=(form,key2,value2,state2)=>{if(/(?:^|\.)__proto__\./.test(key2))return;let nestedForm=form;const keys2=key2.split(".",34);if(keys2.length>33)throwNestingLimitExceeded();keys2.forEach((key3,index28)=>{if(index28===keys2.length-1)nestedForm[key3]=value2;else{if(!nestedForm[key3]||typeof nestedForm[key3]!=="object"||Array.isArray(nestedForm[key3])||nestedForm[key3]instanceof File){if(state2.count++>=MAX_NESTED_OBJECTS)throwNestingLimitExceeded();nestedForm[key3]=Object.create(null)}nestedForm=nestedForm[key3]}})};var throwNestingLimitExceeded=()=>{throw new Error("Nesting limit exceeded")};init_url();var HonoRequest=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(request,path5="/",matchResult=[[]]){this.raw=request;this.path=path5;this.#matchResult=matchResult}param(key2){return key2?this.#getDecodedParam(key2):this.#getAllDecodedParams()}#getDecodedParam(key2){const paramKey=this.#matchResult[0][this.routeIndex]?.[1][key2];const param=this.#getParamValue(paramKey);return param&&tryDecodeURIComponent(param)}#getAllDecodedParams(){const decoded={};const keys2=Object.keys(this.#matchResult[0][this.routeIndex]?.[1]??{});for(const key2 of keys2){const value2=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key2]);if(value2!==void 0)decoded[key2]=tryDecodeURIComponent(value2)}return decoded}#getParamValue(paramKey){return this.#matchResult[1]?this.#matchResult[1][paramKey]:paramKey}query(key2){return getQueryParam(this.url,key2)}queries(key2){return getQueryParams(this.url,key2)}header(name2){if(name2)return this.raw.headers.get(name2)??void 0;const headerData=Object.create(null);this.raw.headers.forEach((value2,key2)=>{headerData[key2]=value2});return headerData}async parseBody(options){return parseBody(this,options)}#cachedBody=key2=>{const{bodyCache,raw:raw2}=this;const cachedBody=bodyCache[key2];if(cachedBody)return cachedBody;for(const anyCachedKey in bodyCache)return bodyCache[anyCachedKey].then(body=>{if(anyCachedKey==="json")body=JSON.stringify(body);const contentType=anyCachedKey==="formData"?void 0:raw2.headers.get("content-type");return new Response(body,{headers:contentType?{"Content-Type":contentType}:void 0})[key2]()});return bodyCache[key2]=raw2[key2]()};json(){return this.#cachedBody("text").then(text35=>JSON.parse(text35))}text(){return this.#cachedBody("text")}arrayBuffer(){return this.#cachedBody("arrayBuffer")}bytes(){return this.#cachedBody("arrayBuffer").then(buffer=>new Uint8Array(buffer))}blob(){return this.#cachedBody("blob")}formData(){return this.#cachedBody("formData")}addValidatedData(target,data){(this.#validatedData??={})[target]=data}valid(target){return this.#validatedData?.[target]}get url(){return this.raw.url}get method(){return this.raw.method}get[GET_MATCH_RESULT](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,route]])=>route)}get routePath(){return this.#matchResult[0].map(([[,route]])=>route)[this.routeIndex].path}};var HtmlEscapedCallbackPhase={Stringify:1,BeforeStream:2,Stream:3};var raw=(value2,callbacks)=>{const escapedString=new String(value2);escapedString.isEscaped=true;escapedString.callbacks=callbacks;return escapedString};var resolveCallback=async(str,phase,preserveCallbacks,context,buffer)=>{if(typeof str==="object"&&!(str instanceof String)){if(!(str instanceof Promise))str=str.toString();if(str instanceof Promise)str=await str}const callbacks=str.callbacks;if(!callbacks?.length)return Promise.resolve(str);if(buffer)buffer[0]+=str;else buffer=[str];const resStr=Promise.all(callbacks.map(c2=>c2({phase,buffer,context}))).then(res=>Promise.all(res.filter(Boolean).map(str2=>resolveCallback(str2,phase,false,context,buffer))).then(()=>buffer[0]));if(preserveCallbacks)return raw(await resStr,callbacks);else return resStr};var TEXT_PLAIN="text/plain; charset=UTF-8";var setDefaultContentType=(contentType,headers)=>{return{"Content-Type":contentType,...headers}};var createResponseInstance=(body,init)=>new Response(body,init);var Context=class{#rawRequest;#req;env={};#var;finalized=false;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(req,options){this.#rawRequest=req;if(options){this.#executionCtx=options.executionCtx;this.env=options.env;this.#notFoundHandler=options.notFoundHandler;this.#path=options.path;this.#matchResult=options.matchResult}}get req(){this.#req??=new HonoRequest(this.#rawRequest,this.#path,this.#matchResult);return this.#req}get event(){if(this.#executionCtx&&"respondWith"in this.#executionCtx)return this.#executionCtx;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;else throw Error("This context has no ExecutionContext")}get res(){return this.#res||=createResponseInstance(null,{headers:this.#preparedHeaders??=new Headers})}set res(_res){if(this.#res&&_res){_res=createResponseInstance(_res.body,_res);for(const[k5,v5]of this.#res.headers.entries()){if(k5==="content-type")continue;if(k5==="set-cookie"){const cookies=this.#res.headers.getSetCookie();_res.headers.delete("set-cookie");for(const cookie of cookies)_res.headers.append("set-cookie",cookie)}else _res.headers.set(k5,v5)}}this.#res=_res;this.finalized=true}render=(...args)=>{this.#renderer??=content=>this.html(content);return this.#renderer(...args)};setLayout=layout=>this.#layout=layout;getLayout=()=>this.#layout;setRenderer=renderer=>{this.#renderer=renderer};header=(name2,value2,options)=>{if(this.finalized&&!this.#res.bodyUsed)this.#res=createResponseInstance(this.#res.body,this.#res);const headers=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;if(value2===void 0)headers.delete(name2);else if(options?.append)headers.append(name2,value2);else headers.set(name2,value2)};status=status=>{this.#status=status};set=(key2,value2)=>{this.#var??=new Map;this.#var.set(key2,value2)};get=key2=>{return this.#var?this.#var.get(key2):void 0};get var(){if(!this.#var)return{};return Object.fromEntries(this.#var)}#newResponse(data,arg,headers){let responseHeaders=this.#res?new Headers(this.#res.headers):this.#preparedHeaders;if(typeof arg==="object"&&arg.headers){responseHeaders??=new Headers;for(const[key2,value2]of new Headers(arg.headers))if(key2==="set-cookie")responseHeaders.append(key2,value2);else responseHeaders.set(key2,value2)}if(headers){if(!responseHeaders){let count3=0;for(const k5 in headers)if(++count3>1||typeof headers[k5]!=="string"){responseHeaders=new Headers;break}}if(responseHeaders)for(const k5 in headers){const v5=headers[k5];if(typeof v5==="string")responseHeaders.set(k5,v5);else{responseHeaders.delete(k5);for(const v22 of v5)responseHeaders.append(k5,v22)}}}const status=typeof arg==="number"?arg:arg?.status??this.#status;return createResponseInstance(data,{status,headers:responseHeaders??headers})}newResponse=(...args)=>this.#newResponse(...args);body=(data,arg,headers)=>this.#newResponse(data,arg,headers);text=(text35,arg,headers)=>{return!this.#preparedHeaders&&!this.#status&&!arg&&!headers&&!this.finalized?new Response(text35):this.#newResponse(text35,arg,setDefaultContentType(TEXT_PLAIN,headers))};json=(object5,arg,headers)=>{return this.#newResponse(JSON.stringify(object5),arg,setDefaultContentType("application/json",headers))};html=(html2,arg,headers)=>{const res=html3=>this.#newResponse(html3,arg,setDefaultContentType("text/html; charset=UTF-8",headers));return typeof html2==="object"?resolveCallback(html2,HtmlEscapedCallbackPhase.Stringify,false,{}).then(res):res(html2)};redirect=(location,status)=>{const locationString=String(location);this.header("Location",!/[^\x00-\xFF]/.test(locationString)?locationString:encodeURI(locationString));return this.newResponse(null,status??302)};notFound=()=>{this.#notFoundHandler??=()=>createResponseInstance();return this.#notFoundHandler(this)}};var compose=(middleware,onError,onNotFound)=>{return(context,next)=>{let index28=-1;return dispatch(0);async function dispatch(i){if(i<=index28)throw new Error("next() called multiple times");index28=i;let res;let isError=false;let handler;if(middleware[i]){handler=middleware[i][0][0];context.req.routeIndex=i}else handler=i===middleware.length&&next||void 0;if(handler)try{res=await handler(context,()=>dispatch(i+1))}catch(err){if(err instanceof Error&&onError){context.error=err;res=await onError(err,context);isError=true}else throw err}else if(context.finalized===false&&onNotFound)res=await onNotFound(context);if(res&&(context.finalized===false||isError))context.res=res;return context}}};init_url();var METHODS=["get","post","put","delete","options","patch","query"];var MESSAGE_MATCHER_IS_ALREADY_BUILT="Can not add a route since the matcher is already built.";var UnsupportedPathError=class extends Error{};var COMPOSED_HANDLER="__COMPOSED_HANDLER";init_url();var getPathPrefixLength=(c2,pathPrefix,routePath)=>{if(!/[:*]/.test(pathPrefix))return pathPrefix.length;const path5=c2.req.path;const matchResult=c2.req[GET_MATCH_RESULT];const paramNames=new Set;let length=0;for(const part of splitRoutingPath(pathPrefix)){const pattern=getPattern(part);if(pattern&&pattern!=="*"){const name2=pattern[1];if(paramNames.has(name2))throw new Error(`mount(): Duplicate path parameter "${name2}" in "${routePath}".`);paramNames.add(name2)}if(pattern&&pattern!=="*"&&pattern[2]!==true){const value2=matchResult.length===2?matchResult[1][matchResult[0][c2.req.routeIndex][1][pattern[1]]]:matchResult[0][c2.req.routeIndex][1][pattern[1]];length+=value2.length+1}else if(pattern||part.endsWith("*")){const end=path5.indexOf("/",length+1);length=end===-1?path5.length:end}else length+=part.length+1}return length};var createMountedRequest=(c2,pathPrefix,routePath)=>{if(/[^/]\*$/.test(routePath))throw new Error(`mount(): Wildcard must follow "/" in "${routePath}".`);const url2=new URL(c2.req.raw.url);url2.pathname=stripPathPrefix(url2.pathname,c2.req.path,getPathPrefixLength(c2,pathPrefix,routePath));return new Request(url2,c2.req.raw)};var notFoundHandler=c2=>{return c2.text("404 Not Found",404)};var errorHandler=(err,c2)=>{if("getResponse"in err){const res=err.getResponse();return c2.newResponse(res.body,res)}console.error(err);return c2.text("Internal Server Error",500)};var Hono=class Hono2{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#path="/";routes=[];constructor(options={}){[...METHODS,"all"].forEach(method=>{this[method]=(args1,...args)=>{const methodName=method.toUpperCase();if(typeof args1==="string")this.#path=args1;else this.#addRoute(methodName,this.#path,args1);args.forEach(handler=>{this.#addRoute(methodName,this.#path,handler)});return this}});this.on=(method,path5,...handlers)=>{for(const p3 of[path5].flat()){this.#path=p3;for(const m4 of[method].flat()){const methodName=m4.toUpperCase();for(const handler of handlers)this.#addRoute(methodName,this.#path,handler)}}return this};this.use=(arg1,...handlers)=>{if(typeof arg1==="string")this.#path=arg1;else{this.#path="*";handlers.unshift(arg1)}handlers.forEach(handler=>{this.#addRoute("ALL",this.#path,handler)});return this};const{strict,...optionsWithoutStrict}=options;Object.assign(this,optionsWithoutStrict);this.getPath=strict??true?options.getPath??getPath:getPathNoStrict}#clone(){const clone3=new Hono2({router:this.router,getPath:this.getPath});clone3.errorHandler=this.errorHandler;clone3.#notFoundHandler=this.#notFoundHandler;clone3.routes=this.routes;return clone3}#notFoundHandler=notFoundHandler;errorHandler=errorHandler;route(path5,app2){const subApp=this.basePath(path5);app2.routes.map(r2=>{let handler;if(app2.errorHandler===errorHandler)handler=r2.handler;else{handler=async(c2,next)=>(await compose([],app2.errorHandler)(c2,()=>r2.handler(c2,next))).res;handler[COMPOSED_HANDLER]=r2.handler}subApp.#addRoute(r2.method,r2.path,handler,r2.basePath)});return this}basePath(path5){const subApp=this.#clone();subApp._basePath=mergePath(this._basePath,path5);return subApp}onError=handler=>{this.errorHandler=handler;return this};notFound=handler=>{this.#notFoundHandler=handler;return this};mount(path5,applicationHandler,options){let replaceRequest;let optionHandler;if(options){if(typeof options==="function")optionHandler=options;else{optionHandler=options.optionHandler;if(options.replaceRequest===false)replaceRequest=request=>request;else replaceRequest=options.replaceRequest}}const getOptions=optionHandler?c2=>{const options2=optionHandler(c2);return Array.isArray(options2)?options2:[options2]}:c2=>{let executionContext=void 0;try{executionContext=c2.executionCtx}catch{}return[c2.env,executionContext]};const mergedPath=mergePath(this._basePath,path5);const defaultReplaceRequest=c2=>createMountedRequest(c2,mergedPath.replace(/\/$/,""),mergePath(mergedPath,"*"));const handler=async(c2,next)=>{const res=await applicationHandler(replaceRequest?replaceRequest(c2.req.raw):defaultReplaceRequest(c2),...getOptions(c2));if(res)return res;await next()};this.#addRoute("ALL",mergePath(path5,"*"),handler);return this}#addRoute(method,path5,handler,baseRoutePath){path5=mergePath(this._basePath,path5);const r2={basePath:baseRoutePath!==void 0?mergePath(this._basePath,baseRoutePath):this._basePath,path:path5,method,handler};this.router.add(method,path5,[handler,r2]);this.routes.push(r2)}#handleError(err,c2){if(err instanceof Error)return this.errorHandler(err,c2);throw err}#dispatch(request,executionCtx,env,method){if(method==="HEAD")return(async()=>new Response(null,await this.#dispatch(request,executionCtx,env,"GET")))();const path5=this.getPath(request,{env});const matchResult=this.router.match(method,path5);const c2=new Context(request,{path:path5,matchResult,env,executionCtx,notFoundHandler:this.#notFoundHandler});if(matchResult[0].length===1){let res;try{res=matchResult[0][0][0][0](c2,async()=>{c2.res=await this.#notFoundHandler(c2)})}catch(err){return this.#handleError(err,c2)}return res instanceof Promise?res.then(resolved=>resolved||(c2.finalized?c2.res:this.#notFoundHandler(c2))).catch(err=>this.#handleError(err,c2)):res??this.#notFoundHandler(c2)}const composed=compose(matchResult[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{const context=await composed(c2);if(!context.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return context.res}catch(err){return this.#handleError(err,c2)}})()}fetch=(request,...rest2)=>{return this.#dispatch(request,rest2[1],rest2[0],request.method)};request=(input2,requestInit,Env,executionCtx)=>{if(input2 instanceof Request)return this.fetch(requestInit?new Request(input2,requestInit):input2,Env,executionCtx);input2=input2.toString();return this.fetch(new Request(/^https?:\/\//.test(input2)?input2:`http://localhost${mergePath("/",input2)}`,requestInit),Env,executionCtx)};fire=()=>{addEventListener("fetch",event=>{event.respondWith(this.#dispatch(event.request,event,void 0,event.request.method))})}};init_url();var createNullObject=()=>Object.create(null);var emptyParam=[];function match(method,path5){const matchers=this.buildAllMatchers();const match2=((method2,path6)=>{const matcher2=matchers[method2]||matchers["ALL"];const staticMatch=matcher2[2][path6];if(staticMatch)return staticMatch;const match3=path6.match(matcher2[0]);if(!match3)return[[],emptyParam];const index28=match3.indexOf("",1);return[matcher2[1][index28],match3]});this.match=match2;return match2(method,path5)}var LABEL_REG_EXP_STR="[^/]+";var ONLY_WILDCARD_REG_EXP_STR="[^]*";var TAIL_WILDCARD_REG_EXP_STR="(?:|/[^]*)";var PATH_ERROR=Symbol();var regExpMetaChars=new Set(".\\+*[^]$()");function compareKey(a,b5){if(a.length===1)return b5.length===1?a<b5?-1:1:-1;if(b5.length===1)return 1;if(a==="[^]*"||a==="(?:|/[^]*)")return b5==="[^]*"?-1:1;else if(b5==="[^]*"||b5==="(?:|/[^]*)")return-1;if(a==="[^/]+")return 1;else if(b5==="[^/]+")return-1;return a.length===b5.length?a<b5?-1:1:b5.length-a.length}var Node2=class Node3{#index;#varIndex;#children=createNullObject();insert(tokens,index28,paramMap,context,keys2){let node2=this;for(let i=0,len=tokens.length;i<len;i++){const token2=tokens[i];const pattern=token2.length===1?token2==="*"?i===len-1?["","",ONLY_WILDCARD_REG_EXP_STR]:["","",LABEL_REG_EXP_STR]:null:token2==="/*"?["","",TAIL_WILDCARD_REG_EXP_STR]:token2.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);let nextNode;if(pattern){const name2=pattern[1];let regexpStr=pattern[2]||"[^/]+";if(name2&&pattern[2]){if(new RegExp(regexpStr).test(""))throw PATH_ERROR;regexpStr=regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:");if(/\((?!\?:)/.test(regexpStr))throw PATH_ERROR;if(regexpStr.length===1&®ExpMetaChars.has(regexpStr))throw PATH_ERROR}keys2.push(regexpStr);nextNode=node2.#children[regexpStr];if(!nextNode){if(regexpStr!=="[^]*"&®expStr!=="(?:|/[^]*)"){for(const k5 in node2.#children)if((regexpStr.length>1||k5.length>1)&&k5!=="[^]*"&&k5!=="(?:|/[^]*)")throw PATH_ERROR}nextNode=node2.#children[regexpStr]=new Node3}if(name2!==""){nextNode.#varIndex??=context.varIndex++;paramMap.push([name2,nextNode.#varIndex])}}else{keys2.push(token2);nextNode=node2.#children[token2];if(!nextNode){for(const k5 in node2.#children)if(k5.length>1&&k5!=="[^]*"&&k5!=="(?:|/[^]*)")throw PATH_ERROR;nextNode=node2.#children[token2]=new Node3}}node2=nextNode}if(node2.#index!==void 0)throw PATH_ERROR;node2.#index=index28}buildRegExpStr(){const strList=Object.keys(this.#children).sort(compareKey).map(k5=>{const c2=this.#children[k5];const childStr=c2.buildRegExpStr();return childStr===""?"":(typeof c2.#varIndex==="number"?`(${k5})@${c2.#varIndex}`:regExpMetaChars.has(k5)?`\\${k5}`:k5)+childStr}).filter(Boolean);if(typeof this.#index==="number"&&this.#index!==-1)strList.unshift(`#${this.#index}`);if(strList.length===0)return"";if(strList.length===1)return strList[0];return"(?:"+strList.join("|")+")"}};var Trie=class{#context={varIndex:0};#root=new Node2;#index=0;paths=createNullObject();insert(path5,isStatic){const keys2=[];if(isStatic){this.#root.insert(path5.split(""),-1,[],this.#context,keys2);this.paths[path5]=[-1,[],keys2];return}const paramAssoc=[];const groups=[];let markedPath=path5;for(let i=0;;){let replaced=false;markedPath=markedPath.replace(/\{(?:\{[\d,]+\}|[^}])+\}/g,m4=>{const mark=`@\\${i}`;groups[i]=[mark,m4];i++;replaced=true;return mark});if(!replaced)break}const tokens=markedPath.match(/(?::[^\/]+)|(?:\/\*$)|./gs)||[];for(let i=groups.length-1;i>=0;i--){const[mark]=groups[i];for(let j5=tokens.length-1;j5>=0;j5--)if(tokens[j5].indexOf(mark)!==-1){tokens[j5]=tokens[j5].replace(mark,groups[i][1]);break}}this.#root.insert(tokens,this.#index,paramAssoc,this.#context,keys2);this.paths[path5]=[this.#index++,paramAssoc,keys2]}buildRegExp(){let regexp=this.#root.buildRegExpStr();if(regexp==="")return[/^$/,[],[]];let captureIndex=0;const indexReplacementMap=[];const paramReplacementMap=[];regexp=regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g,(_5,handlerIndex,paramIndex)=>{if(handlerIndex!==void 0){indexReplacementMap[++captureIndex]=Number(handlerIndex);return"$()"}if(paramIndex!==void 0){paramReplacementMap[Number(paramIndex)]=++captureIndex;return""}return""});return[new RegExp(`^${regexp}`),indexReplacementMap,paramReplacementMap]}};function endsWithWildcard(keys2){const tail=keys2[keys2.length-1];return tail==="[^]*"||tail==="(?:|/[^]*)"}function covers(wildcard,target){const last2=wildcard.length-1;for(let i=0;i<last2;i++)if(wildcard[i]!==target[i])return false;return wildcard[last2]==="[^]*"||target.length===last2||target[last2]==="/"}var RegExpRouter=class{name="RegExpRouter";#handlers;#tries;constructor(){this.#handlers={["ALL"]:[]};this.#tries={["ALL"]:new Trie}}#insertPath(method,path5){try{this.#tries[method].insert(path5,!/\*|\/:/.test(path5))}catch(e5){throw e5===PATH_ERROR?new UnsupportedPathError(path5):e5}}add(method,path5,handler){const handlers=this.#handlers;if(!handlers)throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);const tries=this.#tries;if(!handlers[method]){tries[method]=new Trie;handlers[method]=[...handlers["ALL"]];for(const p3 in tries["ALL"].paths)this.#insertPath(method,p3)}if(path5==="/*")path5="*";const methods=method==="ALL"?Object.keys(handlers):[method];const paths=checkOptionalParameter(path5)||[path5];for(const path6 of paths)for(const m4 of methods){if(!tries[m4].paths[path6])this.#insertPath(m4,path6);handlers[m4].push([handler,path6])}}match=match;buildAllMatchers(){const matchers=createNullObject();for(const method of Object.keys(this.#handlers))matchers[method]=this.#buildMatcher(method);this.#handlers=this.#tries=void 0;return matchers}#buildMatcher(method){const handlers=this.#handlers[method];const trie=this.#tries[method];const staticMap=createNullObject();const handlerData=[];const[regexp,indexReplacementMap,paramReplacementMap]=trie.buildRegExp();const own2=createNullObject();const entries=handlers.map(([h,p3],i)=>{(own2[p3]??=[]).push(i);return[h,trie.paths[p3][1].reduceRight((map6,[key2,varIndex])=>{map6[key2]=paramReplacementMap[varIndex];return map6},createNullObject())]});const wildcards=Object.keys(own2).filter(p3=>endsWithWildcard(trie.paths[p3][2]));for(const path5 in trie.paths){const[index28,,keys2]=trie.paths[path5];const indexes=[...own2[path5]];for(const p3 of wildcards)if(p3!==path5&&covers(trie.paths[p3][2],keys2))indexes.push(...own2[p3]);const data=indexes.sort((a,b5)=>a-b5).map(i=>entries[i]);if(index28===-1){const last2=Math.max(-1,...data.flatMap(([,map6])=>Object.values(map6)));staticMap[path5]=[data,last2===-1?emptyParam:path5.match(regexp).slice(0,last2+1)]}else handlerData[index28]=data}return[regexp,indexReplacementMap.map(i=>handlerData[i]),staticMap]}};var SmartRouter=class{name="SmartRouter";#routers=[];#routes=[];constructor(init){this.#routers=init.routers}add(method,path5,handler){if(!this.#routes)throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);this.#routes.push([method,path5,handler])}match(method,path5){if(!this.#routes)throw new Error("Fatal error");const routers=this.#routers;const routes=this.#routes;const len=routers.length;let i=0;let res;for(;i<len;i++){const router=routers[i];try{for(let i2=0,len2=routes.length;i2<len2;i2++)router.add(...routes[i2]);res=router.match(method,path5)}catch(e5){if(e5 instanceof UnsupportedPathError)continue;throw e5}this.match=router.match.bind(router);this.#routers=[router];this.#routes=void 0;break}if(i===len)throw new Error("Fatal error");this.name=`SmartRouter + ${this.activeRouter.name}`;return res}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw new Error("No active router has been determined yet.");return this.#routers[0]}};init_url();init_url();var emptyParams=createNullObject();var order=0;var Node4=class Node5{#methods=[];#children=createNullObject();#patterns=[];#pattern;#params=emptyParams;insert(method,path5,handler){let curNode=this;const parts=splitRoutingPath(path5);const possibleKeys=new Set;let i=0;for(const p3 of parts){const nextP=parts[++i];const pattern=getPattern(p3,nextP)||(nextP===void 0&&p3&&p3.indexOf("*")===p3.length-1?p3:null);const isParam=Array.isArray(pattern);const key2=isParam?pattern[0]:pattern||p3;const child=curNode.#children[key2]||=new Node5;if(pattern&&!child.#pattern){child.#pattern=pattern;curNode.#patterns.push(child)}curNode=child;if(isParam)possibleKeys.add(pattern[1])}curNode.#methods.push({[method]:{handler,possibleKeys:[...possibleKeys],score:++order}})}#pushHandlerSets(handlerSets,node2,method,nodeParams,params){for(let i=0,len=node2.#methods.length;i<len;i++){const m4=node2.#methods[i];const handlerSet=m4[method]||m4["ALL"];if(handlerSet){handlerSet.params=createNullObject();handlerSets.push(handlerSet);for(let i2=0,len2=handlerSet.possibleKeys.length;i2<len2;i2++){const key2=handlerSet.possibleKeys[i2];handlerSet.params[key2]=params?.[key2]&&!i2?params[key2]:nodeParams[key2]??params?.[key2]}}}}search(method,path5){const handlerSets=[];this.#params=emptyParams;let curNodes=[this];const parts=splitPath(path5);const curNodesQueue=[];const len=parts.length;let partOffsets=null;for(let i=0;i<len;i++){const part=parts[i];const isLast=i===len-1;const tempNodes=[];for(let j5=0,len2=curNodes.length;j5<len2;j5++){const node2=curNodes[j5];const nextNode=node2.#children[part];if(nextNode){nextNode.#params=node2.#params;if(isLast){if(nextNode.#children["*"])this.#pushHandlerSets(handlerSets,nextNode.#children["*"],method,node2.#params);this.#pushHandlerSets(handlerSets,nextNode,method,node2.#params)}else tempNodes.push(nextNode)}for(const child of node2.#patterns){const pattern=child.#pattern;const params=node2.#params===emptyParams?{}:{...node2.#params};if(typeof pattern==="string"){if(pattern==="*"||part.startsWith(pattern.slice(0,-1))){this.#pushHandlerSets(handlerSets,child,method,node2.#params);if(pattern==="*"){child.#params=params;tempNodes.push(child)}}continue}const[,name2,matcher2]=pattern;if(!part&&matcher2===true)continue;if(matcher2!==true){if(!partOffsets){partOffsets=[];let offset=path5[0]==="/"?1:0;for(let p3=0;p3<len;p3++){partOffsets[p3]=offset;offset+=parts[p3].length+1}}const restPathString=path5.slice(partOffsets[i]);const m4=matcher2.exec(restPathString);if(m4){if(!Object.hasOwn(params,name2))params[name2]=m4[0];this.#pushHandlerSets(handlerSets,child,method,node2.#params,params);if(m4[0].length===restPathString.length&&child.#children["*"])this.#pushHandlerSets(handlerSets,child.#children["*"],method,node2.#params,params);for(const _5 in child.#children){child.#params=params;const componentCount=m4[0].match(/\//g)?.length??0;(curNodesQueue[componentCount]||=[]).push(child);break}continue}}if(matcher2===true||matcher2.test(part)){if(!Object.hasOwn(params,name2))params[name2]=part;if(isLast){this.#pushHandlerSets(handlerSets,child,method,params,node2.#params);if(child.#children["*"])this.#pushHandlerSets(handlerSets,child.#children["*"],method,params,node2.#params)}else{child.#params=params;tempNodes.push(child)}}}}const shifted=curNodesQueue.shift();curNodes=shifted?tempNodes.concat(shifted):tempNodes}if(handlerSets[1])handlerSets.sort((a,b5)=>{return a.score-b5.score});return[handlerSets.map(({handler,params})=>[handler,params])]}};var TrieRouter=class{name="TrieRouter";#node=new Node4;add(method,path5,handler){for(const result3 of checkOptionalParameter(path5)||[path5])this.#node.insert(method,result3,handler)}match(method,path5){return this.#node.search(method,path5)}};var Hono3=class extends Hono{constructor(options={}){super(options);this.router=options.router??new SmartRouter({routers:[new RegExpRouter,new TrieRouter]})}};import{existsSync as existsSync77,readFileSync as readFileSync78}from"fs";import{resolve as resolve173}from"path";import{createHash as createHash5}from"crypto";var SYSTEM_RLS_GUC_SQL="select set_config($1::text, $2::text, true), set_config($3::text, $4::text, true), set_config($5::text, $6::text, true)";var SYSTEM_RLS_GUC_PARAMS=["app.current_user_id","","app.current_user_role","system","app.internal_system","true"];init_dist();init_database_config();import{existsSync as existsSync2,mkdirSync as mkdirSync2,mkdtempSync as mkdtempSync2,readdirSync as readdirSync3,readFileSync as readFileSync2,rmSync as rmSync2,writeFileSync as writeFileSync2}from"fs";import{tmpdir as tmpdir2}from"os";import{dirname,join as join3,resolve}from"path";init_postgres_json_parameter();var INVALID_RAW_SQL_PARAMETER_CODE="GENCOW_DB_INVALID_RAW_SQL_PARAMETER";var InvalidRawSqlParameterError=class extends Error{code=INVALID_RAW_SQL_PARAMETER_CODE;parameterIndex;constructor(parameterIndex){super(`Invalid raw SQL Date parameter at index ${parameterIndex}`);this.name="InvalidRawSqlParameterError";this.parameterIndex=parameterIndex}};function normalizeRawSqlParams(params,jsonMode){if(!params)return void 0;const normalized=params.map((value2,parameterIndex)=>{if(!(value2 instanceof Date))return value2;if(!Number.isFinite(value2.getTime())){throw new InvalidRawSqlParameterError(parameterIndex)}return value2.toISOString()});return jsonMode?materializePostgresParameters(normalized,jsonMode):normalized}init_postgres_temporal();init_runtime_postgres_client();init_runtime_postgres_transaction_options();init_runtime_postgres_client();function createRuntimePostgresWorkloads(params){const createClient3=(label,databaseName,options)=>createRuntimePostgresClient({label,databaseName,operationTimeoutMs:params.operationTimeoutMs,recoveryJitterMaxMs:params.recoveryJitterMaxMs,logger:params.logger,createClient:()=>params.createClient(options,label)});const runtimeClient=createClient3("tenant-runtime",params.runtimeDatabaseName,params.runtimeOptions);const systemClient=params.systemIsDistinct?createClient3("system-runtime",params.systemDatabaseName,params.systemOptions):runtimeClient;const readinessClient=params.isPlatform?createClient3("platform-system-readiness",params.systemDatabaseName,{...params.readinessOptions}):systemClient;return{runtimeClient,systemClient,readinessClient,async close(){const uniqueClients=[...new Set([runtimeClient,systemClient,readinessClient])];await Promise.allSettled(uniqueClients.map(client=>client.close()))}}}init_database_config();import{createHash as createHash3}from"node:crypto";init_runtime_postgres_client();import{createHash}from"node:crypto";var PlatformDatabaseCapabilityConfigurationError=class extends Error{code;constructor(code="PLATFORM_DB_CAPABILITY_INVALID"){super("Platform database capability is not configured correctly");this.code=code;this.name="PlatformDatabaseCapabilityConfigurationError"}};function fingerprint(value2){return createHash("sha256").update(value2.toLowerCase()).digest("hex").slice(0,12)}function endpointIdentity(urlText,capability2){let url2;try{url2=new URL(urlText)}catch{throw new PlatformDatabaseCapabilityConfigurationError}if(url2.protocol!=="postgres:"&&url2.protocol!=="postgresql:"){throw new PlatformDatabaseCapabilityConfigurationError}const database=decodeURIComponent(url2.pathname.replace(/^\/+/u,""));const port=url2.port?Number(url2.port):5432;if(!url2.hostname||!url2.username||!database||!Number.isInteger(port)||port<1||port>65535){throw new PlatformDatabaseCapabilityConfigurationError}return{capability:capability2,hostFingerprint:fingerprint(url2.hostname),roleFingerprint:fingerprint(decodeURIComponent(url2.username)),port,database,tlsMode:url2.searchParams.get("sslmode")?.trim()||"default"}}function expectedPlatformDatabase(env){const runtimeUrl=env.PLATFORM_DATABASE_URL?.trim()||env.DATABASE_URL?.trim();if(!runtimeUrl)throw new PlatformDatabaseCapabilityConfigurationError;return endpointIdentity(runtimeUrl,"catalog_read").database}function assertDistinctCapabilityRoles(identities){if(new Set(identities.map(({roleFingerprint})=>roleFingerprint)).size!==identities.length){throw new PlatformDatabaseCapabilityConfigurationError}}function resolvePlatformDatabaseCapabilityConfig(params){if(!params.isPlatform||params.driver==="pglite"){return{backupReadUrl:null,backupReadIdentity:null,catalogReadUrl:null,catalogReadIdentity:null,databaseAdminUrl:null,databaseAdminIdentity:null,tenantDdlUrl:null,tenantDdlIdentity:null}}const env=params.env??process.env;const backupReadUrl=env.GENCOW_BACKUP_DATABASE_URL?.trim();const catalogReadUrl=env.GENCOW_CATALOG_READ_DATABASE_URL?.trim();const databaseAdminUrl=env.GENCOW_DIRECT_DATABASE_URL?.trim();const tenantDdlUrl=env.GENCOW_DIRECT_DDL_DATABASE_URL?.trim();if(!catalogReadUrl){throw new PlatformDatabaseCapabilityConfigurationError("PLATFORM_DB_CATALOG_READ_NOT_CONFIGURED")}if(!tenantDdlUrl){throw new PlatformDatabaseCapabilityConfigurationError("PLATFORM_DB_TENANT_DDL_NOT_CONFIGURED")}const catalogReadIdentity=endpointIdentity(catalogReadUrl,"catalog_read");const backupReadIdentity=backupReadUrl?endpointIdentity(backupReadUrl,"backup_read"):null;const backupReadRole=backupReadUrl?decodeURIComponent(new URL(backupReadUrl).username):null;if(backupReadIdentity&&(backupReadRole!=="gencow_backup_reader"||backupReadIdentity.database!=="postgres")){throw new PlatformDatabaseCapabilityConfigurationError}const runtimeUrl=env.PLATFORM_DATABASE_URL?.trim()||env.DATABASE_URL?.trim()||"";const runtimeIdentity=endpointIdentity(runtimeUrl,"catalog_read");if(catalogReadIdentity.database!==expectedPlatformDatabase(env)){throw new PlatformDatabaseCapabilityConfigurationError}const tenantDdlIdentity=endpointIdentity(tenantDdlUrl,"tenant_ddl");const tenantDdlRole=decodeURIComponent(new URL(tenantDdlUrl).username);const expectedTenantDdlRole=env.GENCOW_TENANT_DDL_EXPECTED_ROLE?.trim()||"gencow_ddl_user";if(!/^[A-Za-z0-9_.@-]{1,63}$/u.test(expectedTenantDdlRole)||tenantDdlRole!==expectedTenantDdlRole){throw new PlatformDatabaseCapabilityConfigurationError}const databaseAdminIdentity=databaseAdminUrl?endpointIdentity(databaseAdminUrl,"database_admin"):null;assertDistinctCapabilityRoles([runtimeIdentity,backupReadIdentity,catalogReadIdentity,tenantDdlIdentity,databaseAdminIdentity].filter(identity2=>identity2!==null));return{backupReadUrl:backupReadUrl||null,backupReadIdentity,catalogReadUrl,catalogReadIdentity,databaseAdminUrl:databaseAdminUrl||null,databaseAdminIdentity,tenantDdlUrl,tenantDdlIdentity}}function buildPlatformCapabilityDatabaseUrl(authorityUrl,database){if(!/^app_[a-z0-9_]+$/u.test(database)){throw new PlatformDatabaseCapabilityConfigurationError}const url2=new URL(authorityUrl);url2.pathname=`/${database}`;return url2.toString()}function buildTenantDdlDatabaseUrl(authorityUrl,database){return buildPlatformCapabilityDatabaseUrl(authorityUrl,database)}init_deployment_executor_authority_contract();import{createHash as createHash2}from"node:crypto";var ROLE_ATTRIBUTE_RESULT_KEYS={superuser:"superuser",createDatabase:"createDb",createRole:"createRole",replication:"replication",bypassRls:"bypassRls"};function roleAttributesMatch(row,capability2){const expected=deploymentExecutorCapabilityAuthority(capability2).roleAttributes;const attributesMatch=Object.entries(ROLE_ATTRIBUTE_RESULT_KEYS).every(([attribute,resultKey])=>row[resultKey]===expected[attribute]);if(capability2!=="database_admin")return attributesMatch;const membershipsMatch=row.membershipCount===expected.allowedMemberships.length&&row.hasSignalBackend===expected.allowedMemberships.includes("pg_signal_backend");return attributesMatch&&membershipsMatch}function roleIdentityMatches(row,identity2){return typeof row.role==="string"&&createHash2("sha256").update(row.role.toLowerCase()).digest("hex").slice(0,12)===identity2.roleFingerprint}var PlatformDatabaseCapabilityUnavailableError=class extends Error{code;constructor(code){super("Platform database capability is unavailable");this.code=code;this.name="PlatformDatabaseCapabilityUnavailableError"}};function normalizeCapabilityRows(result3){if(!Array.isArray(result3)){throw new PlatformDatabaseCapabilityUnavailableError("PLATFORM_DB_CATALOG_READ_UNAVAILABLE")}return result3.filter(row=>row!==null&&typeof row==="object"&&!Array.isArray(row))}function assertSystemCapabilityProbe(rows8){const row=rows8[0];const protectedRead=Number(row?.protectedRead);if(row?.role!=="system"||row?.internalSystem!=="true"||!Number.isFinite(protectedRead)||protectedRead<0){throw new PlatformDatabaseCapabilityUnavailableError("PLATFORM_DB_SYSTEM_UNAVAILABLE")}}function assertCatalogCapabilityProbe(rows8,identity2){const row=rows8[0];const authority=deploymentExecutorCapabilityAuthority("catalog_reader");const databasePrivilegesMatch=row?.databaseCreate===authority.database.create&&row?.databaseTemporary===authority.database.temporary&&row?.schemaCreate===authority.schema.create;if(!row||row.database!==identity2.database||!roleIdentityMatches(row,identity2)||!roleAttributesMatch(row,"catalog_reader")||!databasePrivilegesMatch||row.publicTablePrivileges!==false){throw new PlatformDatabaseCapabilityUnavailableError("PLATFORM_DB_CATALOG_READ_UNAVAILABLE")}}function assertTenantDdlCapabilityProbe(rows8,identity2){const row=rows8[0];if(!row||row.database!==identity2.database||!roleIdentityMatches(row,identity2)||!roleAttributesMatch(row,"tenant_ddl")){throw new PlatformDatabaseCapabilityUnavailableError("PLATFORM_DB_TENANT_DDL_UNAVAILABLE")}}function assertDatabaseAdminCapabilityProbe(rows8,identity2){const row=rows8[0];if(!row||row.database!==identity2.database||!roleIdentityMatches(row,identity2)||!roleAttributesMatch(row,"database_admin")){throw new PlatformDatabaseCapabilityUnavailableError("PLATFORM_DB_DATABASE_ADMIN_UNAVAILABLE")}}var DATABASE_ADMIN_CAPABILITY_READINESS_SQL=`
|
|
12394
12394
|
SELECT
|
|
12395
12395
|
current_database() AS "database",
|
|
12396
12396
|
current_user AS "role",
|