@prisma/composer-prisma-cloud 0.26.0 → 0.27.0-dev.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth/pack.mjs +1 -1
- package/dist/auth/pack.mjs.map +1 -1
- package/dist/auth/testing.mjs +9510 -2309
- package/dist/auth/testing.mjs.map +1 -1
- package/dist/buckets-main.mjs +1 -1
- package/dist/buckets-main.mjs.map +1 -1
- package/dist/{secret-C__qAfZr-CUc_Mgbg.mjs → casts-DpaahrlC-Ykus3kCE.mjs} +42 -2
- package/dist/casts-DpaahrlC-Ykus3kCE.mjs.map +1 -0
- package/dist/compute-main.mjs +1 -1
- package/dist/compute-main.mjs.map +1 -1
- package/dist/control.mjs +23 -7
- package/dist/control.mjs.map +1 -1
- package/dist/index.mjs +3 -3
- package/dist/local-target.d.mts +7 -1
- package/dist/local-target.d.mts.map +1 -1
- package/dist/local-target.mjs +108 -10
- package/dist/local-target.mjs.map +1 -1
- package/dist/postgres-main.mjs +1 -1
- package/dist/postgres-main.mjs.map +1 -1
- package/dist/{provisioned-edges-CPrUiJ1K-DKbfx776.mjs → provisioned-edges-CPrUiJ1K--R7PIGoz.mjs} +2 -2
- package/dist/{provisioned-edges-CPrUiJ1K-DKbfx776.mjs.map → provisioned-edges-CPrUiJ1K--R7PIGoz.mjs.map} +1 -1
- package/dist/{s3-credentials-resource-CySVP49N-BQLhUtvi.mjs → s3-credentials-resource-CySVP49N-B91rwV42.mjs} +5 -5
- package/dist/s3-credentials-resource-CySVP49N-B91rwV42.mjs.map +1 -0
- package/dist/{segments-D-anjQ84-BNgikNpo.mjs → segments-DRPHe3kK-BNgikNpo.mjs} +1 -1
- package/dist/{segments-D-anjQ84-BNgikNpo.mjs.map → segments-DRPHe3kK-BNgikNpo.mjs.map} +1 -1
- package/dist/{serializer-CE3hLPYz-BnSjO4w7.mjs → serializer-CE3hLPYz-DfUFvkm9.mjs} +2 -42
- package/dist/serializer-CE3hLPYz-DfUFvkm9.mjs.map +1 -0
- package/dist/testing.mjs +1 -1
- package/package.json +18 -18
- package/dist/s3-credentials-resource-CySVP49N-BQLhUtvi.mjs.map +0 -1
- package/dist/secret-C__qAfZr-CUc_Mgbg.mjs.map +0 -1
- package/dist/serializer-CE3hLPYz-BnSjO4w7.mjs.map +0 -1
package/dist/buckets-main.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as readOwnVersion, i as readJsonFile, r as isValidSegment, t as StateFile } from "./segments-
|
|
1
|
+
import { a as readOwnVersion, i as readJsonFile, r as isValidSegment, t as StateFile } from "./segments-DRPHe3kK-BNgikNpo.mjs";
|
|
2
2
|
import * as fs from "node:fs";
|
|
3
3
|
import * as fs$1 from "node:fs/promises";
|
|
4
4
|
import * as path from "node:path";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"buckets-main.mjs","names":["fs"],"sources":["../../../1-prisma-cloud/0-lowering/s3-protocol/dist/index.mjs","../../../1-prisma-cloud/0-lowering/dev-emulators/dist/buckets-main.mjs"],"sourcesContent":["import { createHash, createHmac, randomUUID, timingSafeEqual } from \"node:crypto\";\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nconst DEFAULT_CONTENT_TYPE$1 = \"application/octet-stream\";\nconst TMP_DIR_NAME = \".tmp\";\nconst META_DIR_NAME = \".meta\";\nconst RESERVED_SEGMENTS = /* @__PURE__ */ new Set([TMP_DIR_NAME, META_DIR_NAME]);\nconst BUCKET_NAME_RE = /^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/;\nfunction etagOf$1(bytes) {\n\treturn `\"${createHash(\"sha256\").update(bytes).digest(\"hex\")}\"`;\n}\nfunction isErrnoException(err) {\n\treturn err instanceof Error && \"code\" in err;\n}\nfunction isEnoent(err) {\n\treturn isErrnoException(err) && err.code === \"ENOENT\";\n}\n/**\n* Splits a key into its `/` segments, rejecting anything that could escape\n* the bucket dir or collide with the reserved `.tmp`/`.meta` namespaces:\n* `..` segments, an empty segment (leading/trailing/doubled `/`, which also\n* catches a leading-slash \"absolute\" key), or a segment literally `.tmp` or\n* `.meta` at any depth.\n*/\nfunction keySegments(key) {\n\tconst segments = key.split(\"/\");\n\tfor (const segment of segments) if (segment === \"\" || segment === \".\" || segment === \"..\" || RESERVED_SEGMENTS.has(segment)) throw new Error(`invalid object key: \"${key}\"`);\n\treturn segments;\n}\n/** `<bucketDir>/<key's segments>`, double-checked to still resolve inside `bucketDir`. */\nfunction objectPath(bucketDir, key) {\n\tconst target = path.join(bucketDir, ...keySegments(key));\n\tconst resolvedRoot = path.resolve(bucketDir) + path.sep;\n\tif (!(path.resolve(target) + path.sep).startsWith(resolvedRoot)) throw new Error(`invalid object key: \"${key}\"`);\n\treturn target;\n}\n/** `<bucketDir>/.meta/<key's segments>.json` — mirrors `objectPath`'s tree under `.meta`. */\nfunction sidecarPath(bucketDir, key) {\n\tconst segments = keySegments(key);\n\tconst last = segments[segments.length - 1];\n\tconst dirs = segments.slice(0, -1);\n\treturn path.join(bucketDir, META_DIR_NAME, ...dirs, `${last}.json`);\n}\n/** Write-temp-then-rename: never leaves a reader observing a partial file. */\nasync function writeAtomic(finalPath, tmpRoot, bytes) {\n\tawait fs.mkdir(tmpRoot, { recursive: true });\n\tconst tmpPath = path.join(tmpRoot, randomUUID());\n\tawait fs.writeFile(tmpPath, bytes);\n\tawait fs.mkdir(path.dirname(finalPath), { recursive: true });\n\tawait fs.rename(tmpPath, finalPath);\n}\nfunction isSidecar(value) {\n\treturn typeof value === \"object\" && value !== null && \"contentType\" in value && typeof value.contentType === \"string\" && \"etag\" in value && typeof value.etag === \"string\";\n}\nasync function readSidecar(sidecar) {\n\tlet raw;\n\ttry {\n\t\traw = await fs.readFile(sidecar, \"utf8\");\n\t} catch (err) {\n\t\tif (isEnoent(err)) return null;\n\t\tthrow err;\n\t}\n\ttry {\n\t\tconst parsed = JSON.parse(raw);\n\t\tif (isSidecar(parsed)) return parsed;\n\t} catch {}\n\treturn null;\n}\n/** Read the object's bytes plus its metadata — adopting a sidecar-less file (dropped in by a developer) by computing and lazily persisting one. `null` when the object is missing. */\nasync function readObject(bucketDir, key) {\n\tconst target = objectPath(bucketDir, key);\n\tlet bytes;\n\ttry {\n\t\tbytes = await fs.readFile(target);\n\t} catch (err) {\n\t\tif (isEnoent(err)) return null;\n\t\tthrow err;\n\t}\n\tconst existing = await readSidecar(sidecarPath(bucketDir, key));\n\tif (existing) return {\n\t\tbytes,\n\t\tmeta: existing\n\t};\n\tconst meta = {\n\t\tcontentType: DEFAULT_CONTENT_TYPE$1,\n\t\tetag: etagOf$1(bytes)\n\t};\n\tawait writeAtomic(sidecarPath(bucketDir, key), path.join(bucketDir, TMP_DIR_NAME), Buffer.from(JSON.stringify(meta)));\n\treturn {\n\t\tbytes,\n\t\tmeta\n\t};\n}\n/** Remove now-empty directories from `startDir` up to (never including) `root`. */\nasync function pruneEmptyDirs(root, startDir) {\n\tconst resolvedRoot = path.resolve(root);\n\tlet dir = path.resolve(startDir);\n\twhile (dir !== resolvedRoot && dir.startsWith(resolvedRoot + path.sep)) {\n\t\tlet entries;\n\t\ttry {\n\t\t\tentries = await fs.readdir(dir);\n\t\t} catch (err) {\n\t\t\tif (isEnoent(err)) {\n\t\t\t\tdir = path.dirname(dir);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t\tif (entries.length > 0) break;\n\t\ttry {\n\t\t\tawait fs.rmdir(dir);\n\t\t} catch (err) {\n\t\t\tif (!isEnoent(err)) throw err;\n\t\t}\n\t\tdir = path.dirname(dir);\n\t}\n}\n/** Recursively lists every object key under `dir`, skipping `.tmp`/`.meta` at any depth. */\nasync function walkKeys(dir) {\n\tconst keys = [];\n\tasync function walk(current, prefix) {\n\t\tlet entries;\n\t\ttry {\n\t\t\tentries = await fs.readdir(current, { withFileTypes: true });\n\t\t} catch (err) {\n\t\t\tif (isEnoent(err)) return;\n\t\t\tthrow err;\n\t\t}\n\t\tfor (const entry of entries) {\n\t\t\tif (RESERVED_SEGMENTS.has(entry.name)) continue;\n\t\t\tconst rel = prefix === \"\" ? entry.name : `${prefix}/${entry.name}`;\n\t\t\tif (entry.isDirectory()) await walk(path.join(current, entry.name), rel);\n\t\t\telse if (entry.isFile()) keys.push(rel);\n\t\t}\n\t}\n\tawait walk(dir, \"\");\n\treturn keys;\n}\n/**\n* A disk-backed `ObjectStore`: object bytes and a metadata sidecar under a\n* per-bucket directory the caller resolves. See the module doc for the\n* unknown-bucket / invalid-key failure shapes.\n*/\nfunction fsStore(resolveBucketDir) {\n\tfunction resolveDir(bucket) {\n\t\tif (!BUCKET_NAME_RE.test(bucket)) return void 0;\n\t\treturn resolveBucketDir(bucket);\n\t}\n\treturn {\n\t\tasync put(bucket, key, bytes, opts = {}) {\n\t\t\tconst dir = resolveDir(bucket);\n\t\t\tif (dir === void 0) throw new Error(`no such bucket: \"${bucket}\"`);\n\t\t\tconst target = objectPath(dir, key);\n\t\t\tconst tmpRoot = path.join(dir, TMP_DIR_NAME);\n\t\t\tconst etag = etagOf$1(bytes);\n\t\t\tconst contentType = opts.contentType ?? DEFAULT_CONTENT_TYPE$1;\n\t\t\tawait writeAtomic(target, tmpRoot, bytes);\n\t\t\tawait writeAtomic(sidecarPath(dir, key), tmpRoot, Buffer.from(JSON.stringify({\n\t\t\t\tcontentType,\n\t\t\t\tetag\n\t\t\t})));\n\t\t\treturn { etag };\n\t\t},\n\t\tasync get(bucket, key, opts = {}) {\n\t\t\tconst dir = resolveDir(bucket);\n\t\t\tif (dir === void 0) return null;\n\t\t\tconst found = await readObject(dir, key);\n\t\t\tif (!found) return null;\n\t\t\tconst { bytes, meta } = found;\n\t\t\tconst size = bytes.byteLength;\n\t\t\tif (opts.range) {\n\t\t\t\tconst start = opts.range.start;\n\t\t\t\tconst end = opts.range.end === void 0 ? size - 1 : Math.min(opts.range.end, size - 1);\n\t\t\t\treturn {\n\t\t\t\t\tbytes: start > end ? /* @__PURE__ */ new Uint8Array(0) : bytes.subarray(start, end + 1),\n\t\t\t\t\tetag: meta.etag,\n\t\t\t\t\tcontentType: meta.contentType,\n\t\t\t\t\tsize\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tbytes: new Uint8Array(bytes),\n\t\t\t\tetag: meta.etag,\n\t\t\t\tcontentType: meta.contentType,\n\t\t\t\tsize\n\t\t\t};\n\t\t},\n\t\tasync head(bucket, key) {\n\t\t\tconst dir = resolveDir(bucket);\n\t\t\tif (dir === void 0) return null;\n\t\t\tconst found = await readObject(dir, key);\n\t\t\tif (!found) return null;\n\t\t\treturn {\n\t\t\t\tetag: found.meta.etag,\n\t\t\t\tsize: found.bytes.byteLength,\n\t\t\t\tcontentType: found.meta.contentType\n\t\t\t};\n\t\t},\n\t\tasync delete(bucket, key) {\n\t\t\tconst dir = resolveDir(bucket);\n\t\t\tif (dir === void 0) return;\n\t\t\tconst target = objectPath(dir, key);\n\t\t\tconst sidecar = sidecarPath(dir, key);\n\t\t\ttry {\n\t\t\t\tawait fs.unlink(target);\n\t\t\t} catch (err) {\n\t\t\t\tif (!isEnoent(err)) throw err;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait fs.unlink(sidecar);\n\t\t\t} catch (err) {\n\t\t\t\tif (!isEnoent(err)) throw err;\n\t\t\t}\n\t\t\tawait pruneEmptyDirs(dir, path.dirname(target));\n\t\t\tawait pruneEmptyDirs(path.join(dir, META_DIR_NAME), path.dirname(sidecar));\n\t\t},\n\t\tasync list(bucket, opts = {}) {\n\t\t\tconst dir = resolveDir(bucket);\n\t\t\tif (dir === void 0) return {\n\t\t\t\tkeys: [],\n\t\t\t\tisTruncated: false\n\t\t\t};\n\t\t\tconst prefix = opts.prefix ?? \"\";\n\t\t\tconst maxKeys = opts.maxKeys ?? 1e3;\n\t\t\tconst token = opts.continuationToken;\n\t\t\tconst matching = (await walkKeys(dir)).filter((key) => key.startsWith(prefix)).sort().filter((key) => token === void 0 ? true : key > token);\n\t\t\tconst page = matching.slice(0, maxKeys);\n\t\t\tconst isTruncated = matching.length > maxKeys;\n\t\t\tconst last = page.at(-1);\n\t\t\treturn {\n\t\t\t\tkeys: page,\n\t\t\t\tisTruncated,\n\t\t\t\t...isTruncated && last !== void 0 ? { nextContinuationToken: last } : {}\n\t\t\t};\n\t\t}\n\t};\n}\n//#endregion\n//#region src/sigv4.ts\n/**\n* AWS SigV4 verification for the S3 wire protocol (spec § 2 auth). The payload\n* hash comes from the client — `x-amz-content-sha256` (a real hash or\n* `UNSIGNED-PAYLOAD`) for header auth, `UNSIGNED-PAYLOAD` for presign — and is\n* never re-hashed; the verifier trusts what was signed, like a real S3 endpoint.\n* Runtime engine code (`node:crypto`); not re-exported from the authoring barrel.\n*\n* Also owns `mintKeyPair` (local-dev spec § 1) — the one key-pair generator\n* both the deploy-time `S3Credentials` resource and the local dev bucket\n* emulator's credential provisioning use.\n*/\nfunction randomBytes(n) {\n\treturn crypto.getRandomValues(new Uint8Array(n));\n}\nfunction toHexUpper(bytes) {\n\treturn Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\").toUpperCase();\n}\n/** A fresh SigV4 key pair: an AKIA-prefixed id and a 40-char base64 secret. */\nfunction mintKeyPair() {\n\treturn {\n\t\taccessKeyId: `AKIA${toHexUpper(randomBytes(8))}`,\n\t\tsecretAccessKey: btoa(String.fromCharCode(...randomBytes(30)))\n\t};\n}\nconst ALGORITHM = \"AWS4-HMAC-SHA256\";\nconst UNSIGNED_PAYLOAD = \"UNSIGNED-PAYLOAD\";\nfunction sha256Hex(data) {\n\treturn createHash(\"sha256\").update(data).digest(\"hex\");\n}\nfunction hmac(key, data) {\n\treturn createHmac(\"sha256\", key).update(data).digest();\n}\n/** AWS canonical URI encoding: every byte except the unreserved set is %XX. */\nfunction awsUriEncode(value) {\n\treturn encodeURIComponent(value).replace(/[!'()*]/g, (ch) => `%${ch.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%7E/g, \"~\");\n}\nfunction parseCredential(credential) {\n\tconst parts = credential.split(\"/\");\n\tif (parts.length !== 5 || parts[4] !== \"aws4_request\") return null;\n\tconst [accessKeyId, date, region, service] = parts;\n\tif (!accessKeyId || !date || !region || !service) return null;\n\treturn {\n\t\taccessKeyId,\n\t\tdate,\n\t\tregion,\n\t\tservice\n\t};\n}\nfunction signingKey(secret, scope) {\n\treturn hmac(hmac(hmac(hmac(`AWS4${secret}`, scope.date), scope.region), scope.service), \"aws4_request\");\n}\nfunction canonicalHeaders(url, req, signedHeaders) {\n\treturn signedHeaders.map((name) => {\n\t\treturn `${name}:${(name === \"host\" ? url.host : req.headers.get(name) ?? \"\").trim().replace(/\\s+/g, \" \")}\\n`;\n\t}).join(\"\");\n}\nfunction canonicalQuery(url, exclude) {\n\tconst entries = [];\n\tfor (const [key, value] of url.searchParams.entries()) {\n\t\tif (exclude !== void 0 && key === exclude) continue;\n\t\tentries.push([awsUriEncode(key), awsUriEncode(value)]);\n\t}\n\tconst cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;\n\tentries.sort(([ak, av], [bk, bv]) => cmp(ak, bk) || cmp(av, bv));\n\treturn entries.map(([k, v]) => `${k}=${v}`).join(\"&\");\n}\nfunction stringToSign(amzDate, scope, canonicalRequest) {\n\tconst scopeString = `${scope.date}/${scope.region}/${scope.service}/aws4_request`;\n\treturn [\n\t\tALGORITHM,\n\t\tamzDate,\n\t\tscopeString,\n\t\tsha256Hex(canonicalRequest)\n\t].join(\"\\n\");\n}\nfunction signatureMatches(expected, provided) {\n\tconst a = Buffer.from(expected, \"hex\");\n\tconst b = Buffer.from(provided, \"hex\");\n\treturn a.length === b.length && a.length > 0 && timingSafeEqual(a, b);\n}\n/** `YYYYMMDDTHHMMSSZ` → epoch ms, or null when malformed. */\nfunction parseAmzDate(amzDate) {\n\tconst match = /^(\\d{4})(\\d{2})(\\d{2})T(\\d{2})(\\d{2})(\\d{2})Z$/.exec(amzDate);\n\tif (!match) return null;\n\tconst [, y, mo, d, h, mi, s] = match;\n\treturn Date.UTC(Number(y), Number(mo) - 1, Number(d), Number(h), Number(mi), Number(s));\n}\nfunction parseAuthorizationHeader(header) {\n\tif (!header.startsWith(`${ALGORITHM} `)) return null;\n\tconst rest = header.slice(17);\n\tconst fields = /* @__PURE__ */ new Map();\n\tfor (const part of rest.split(\",\")) {\n\t\tconst eq = part.indexOf(\"=\");\n\t\tif (eq === -1) continue;\n\t\tfields.set(part.slice(0, eq).trim(), part.slice(eq + 1).trim());\n\t}\n\tconst credential = fields.get(\"Credential\");\n\tconst signedHeaders = fields.get(\"SignedHeaders\");\n\tconst signature = fields.get(\"Signature\");\n\tif (!credential || !signedHeaders || !signature) return null;\n\treturn {\n\t\tcredential,\n\t\tsignedHeaders: signedHeaders.split(\";\"),\n\t\tsignature\n\t};\n}\n/** The one signing core both auth forms share: check the access key, rebuild the canonical request, derive the key, compare in constant time. */\nfunction verifySignature(req, url, credentials, params) {\n\tif (params.scope.accessKeyId !== credentials.accessKeyId) return {\n\t\tok: false,\n\t\treason: \"unknown access key\"\n\t};\n\tconst canonicalRequest = [\n\t\treq.method,\n\t\turl.pathname,\n\t\tcanonicalQuery(url, params.excludeQuery),\n\t\tcanonicalHeaders(url, req, params.signedHeaders),\n\t\tparams.signedHeaders.join(\";\"),\n\t\tparams.payloadHash\n\t].join(\"\\n\");\n\treturn signatureMatches(hmac(signingKey(credentials.secretAccessKey, params.scope), stringToSign(params.amzDate, params.scope, canonicalRequest)).toString(\"hex\"), params.signature) ? { ok: true } : {\n\t\tok: false,\n\t\treason: \"signature mismatch\"\n\t};\n}\nfunction verifyHeader(req, url, credentials) {\n\tconst auth = parseAuthorizationHeader(req.headers.get(\"authorization\") ?? \"\");\n\tif (!auth) return {\n\t\tok: false,\n\t\treason: \"malformed Authorization header\"\n\t};\n\tconst scope = parseCredential(auth.credential);\n\tif (!scope) return {\n\t\tok: false,\n\t\treason: \"malformed credential scope\"\n\t};\n\tconst amzDate = req.headers.get(\"x-amz-date\");\n\tif (!amzDate) return {\n\t\tok: false,\n\t\treason: \"missing x-amz-date\"\n\t};\n\tconst payloadHash = req.headers.get(\"x-amz-content-sha256\");\n\tif (!payloadHash) return {\n\t\tok: false,\n\t\treason: \"missing x-amz-content-sha256\"\n\t};\n\treturn verifySignature(req, url, credentials, {\n\t\tscope,\n\t\tamzDate,\n\t\tsignedHeaders: auth.signedHeaders,\n\t\tpayloadHash,\n\t\tsignature: auth.signature\n\t});\n}\nfunction verifyPresigned(req, url, credentials, now) {\n\tconst q = url.searchParams;\n\tif (q.get(\"X-Amz-Algorithm\") !== ALGORITHM) return {\n\t\tok: false,\n\t\treason: \"unsupported presign algorithm\"\n\t};\n\tconst credentialRaw = q.get(\"X-Amz-Credential\");\n\tconst amzDate = q.get(\"X-Amz-Date\");\n\tconst expiresRaw = q.get(\"X-Amz-Expires\");\n\tconst signedHeadersRaw = q.get(\"X-Amz-SignedHeaders\");\n\tconst signature = q.get(\"X-Amz-Signature\");\n\tif (!credentialRaw || !amzDate || !expiresRaw || !signedHeadersRaw || !signature) return {\n\t\tok: false,\n\t\treason: \"incomplete presign parameters\"\n\t};\n\tconst scope = parseCredential(credentialRaw);\n\tif (!scope) return {\n\t\tok: false,\n\t\treason: \"malformed credential scope\"\n\t};\n\tconst signedAt = parseAmzDate(amzDate);\n\tconst expires = Number(expiresRaw);\n\tif (signedAt === null || !Number.isFinite(expires)) return {\n\t\tok: false,\n\t\treason: \"malformed presign date\"\n\t};\n\tif (now.getTime() > signedAt + expires * 1e3) return {\n\t\tok: false,\n\t\treason: \"presign expired\"\n\t};\n\treturn verifySignature(req, url, credentials, {\n\t\tscope,\n\t\tamzDate,\n\t\tsignedHeaders: signedHeadersRaw.split(\";\"),\n\t\tpayloadHash: UNSIGNED_PAYLOAD,\n\t\tsignature,\n\t\texcludeQuery: \"X-Amz-Signature\"\n\t});\n}\n/**\n* Verify a request's SigV4 signature against a single credential pair. Picks\n* the presigned form when `X-Amz-Signature` is present, otherwise the\n* `Authorization`-header form. `now` is injectable for deterministic\n* expiry tests.\n*/\nfunction verifyRequest(req, credentials, now = /* @__PURE__ */ new Date()) {\n\tconst url = new URL(req.url);\n\tif (url.searchParams.has(\"X-Amz-Signature\")) return verifyPresigned(req, url, credentials, now);\n\tif (req.headers.has(\"authorization\")) return verifyHeader(req, url, credentials);\n\treturn {\n\t\tok: false,\n\t\treason: \"unsigned request\"\n\t};\n}\n//#endregion\n//#region src/handler.ts\nconst DEFAULT_CONTENT_TYPE = \"application/octet-stream\";\n/** Path-style: `/{bucket}/{key…}`. Each segment is percent-decoded. */\nfunction parseTarget(url) {\n\tconst segments = url.pathname.split(\"/\").filter((s) => s.length > 0);\n\tif (segments.length === 0) return null;\n\tconst [bucket, ...keyParts] = segments;\n\treturn {\n\t\tbucket: decodeURIComponent(bucket ?? \"\"),\n\t\tkey: keyParts.map(decodeURIComponent).join(\"/\")\n\t};\n}\n/** `bytes=a-b` (inclusive) or `bytes=a-` (open-ended). Null when absent/malformed. */\nfunction parseRange(header) {\n\tif (!header) return null;\n\tconst match = /^bytes=(\\d+)-(\\d*)$/.exec(header.trim());\n\tif (!match) return null;\n\tconst start = Number(match[1]);\n\treturn match[2] ? {\n\t\tstart,\n\t\tend: Number(match[2])\n\t} : { start };\n}\nfunction xmlEscape(value) {\n\treturn value.replace(/&/g, \"&\").replace(/</g, \"<\").replace(/>/g, \">\").replace(/\"/g, \""\").replace(/'/g, \"'\");\n}\nfunction listXml(bucket, prefix, maxKeys, result) {\n\tconst contents = result.keys.map((k) => `<Contents><Key>${xmlEscape(k)}</Key></Contents>`).join(\"\");\n\tconst next = result.isTruncated && result.nextContinuationToken !== void 0 ? `<NextContinuationToken>${xmlEscape(result.nextContinuationToken)}</NextContinuationToken>` : \"\";\n\treturn `<?xml version=\"1.0\" encoding=\"UTF-8\"?><ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Name>${xmlEscape(bucket)}</Name><Prefix>${xmlEscape(prefix)}</Prefix><KeyCount>${result.keys.length}</KeyCount><MaxKeys>${maxKeys}</MaxKeys><IsTruncated>${result.isTruncated}</IsTruncated>` + contents + next + \"</ListBucketResult>\";\n}\nconst DEFAULT_MAX_KEYS$1 = 1e3;\nasync function handleList(store, bucket, url) {\n\tconst prefix = url.searchParams.get(\"prefix\") ?? \"\";\n\tconst continuationToken = url.searchParams.get(\"continuation-token\");\n\tconst maxKeysRaw = url.searchParams.get(\"max-keys\");\n\tconst maxKeys = maxKeysRaw !== null && Number.isFinite(Number(maxKeysRaw)) ? Number(maxKeysRaw) : DEFAULT_MAX_KEYS$1;\n\tconst result = await store.list(bucket, {\n\t\tprefix,\n\t\tmaxKeys,\n\t\t...continuationToken !== null ? { continuationToken } : {}\n\t});\n\treturn new Response(listXml(bucket, prefix, maxKeys, result), {\n\t\tstatus: 200,\n\t\theaders: { \"content-type\": \"application/xml\" }\n\t});\n}\n/** aws-chunked / flexible-checksum PUTs frame the body as chunks + a trailer (signalled by `x-amz-content-sha256: STREAMING-…` or `content-encoding: aws-chunked`); the seed signature still verifies, so reject them (501) rather than store the raw framing as the object bytes. Decoding is out of scope. */\nfunction isStreamingPut(req) {\n\tconst contentSha = req.headers.get(\"x-amz-content-sha256\") ?? \"\";\n\tconst contentEncoding = req.headers.get(\"content-encoding\") ?? \"\";\n\treturn contentSha.startsWith(\"STREAMING-\") || contentEncoding.split(\",\").some((e) => e.trim() === \"aws-chunked\");\n}\nasync function handlePut(store, t, req) {\n\tif (isStreamingPut(req)) return new Response(\"aws-chunked / flexible checksums not supported; set requestChecksumCalculation: 'WHEN_REQUIRED'\", { status: 501 });\n\tconst body = new Uint8Array(await req.arrayBuffer());\n\tconst contentType = req.headers.get(\"content-type\") ?? DEFAULT_CONTENT_TYPE;\n\tconst { etag } = await store.put(t.bucket, t.key, body, { contentType });\n\treturn new Response(null, {\n\t\tstatus: 200,\n\t\theaders: { etag }\n\t});\n}\n/** The etag/content-type/content-length/accept-ranges headers GET and HEAD share — `contentLength` is the slice length for GET, the total object size for HEAD. */\nfunction metaHeaders(meta) {\n\treturn new Headers({\n\t\tetag: meta.etag,\n\t\t\"content-type\": meta.contentType,\n\t\t\"content-length\": String(meta.contentLength),\n\t\t\"accept-ranges\": \"bytes\"\n\t});\n}\nasync function handleGet(store, t, req) {\n\tconst range = parseRange(req.headers.get(\"range\"));\n\tconst object = await store.get(t.bucket, t.key, range ? { range } : void 0);\n\tif (!object) return new Response(null, { status: 404 });\n\tconst headers = metaHeaders({\n\t\tetag: object.etag,\n\t\tcontentType: object.contentType,\n\t\tcontentLength: object.bytes.byteLength\n\t});\n\tif (!range) return new Response(object.bytes, {\n\t\tstatus: 200,\n\t\theaders\n\t});\n\tif (range.start >= object.size && object.size > 0) return new Response(null, {\n\t\tstatus: 416,\n\t\theaders: { \"content-range\": `bytes */${object.size}` }\n\t});\n\tconst end = range.end === void 0 ? object.size - 1 : Math.min(range.end, object.size - 1);\n\theaders.set(\"content-range\", `bytes ${range.start}-${end}/${object.size}`);\n\treturn new Response(object.bytes, {\n\t\tstatus: 206,\n\t\theaders\n\t});\n}\nasync function handleHead(store, t) {\n\tconst meta = await store.head(t.bucket, t.key);\n\tif (!meta) return new Response(null, { status: 404 });\n\treturn new Response(null, {\n\t\tstatus: 200,\n\t\theaders: metaHeaders({\n\t\t\tetag: meta.etag,\n\t\t\tcontentType: meta.contentType,\n\t\t\tcontentLength: meta.size\n\t\t})\n\t});\n}\nasync function handleDelete(store, t) {\n\tawait store.delete(t.bucket, t.key);\n\treturn new Response(null, { status: 204 });\n}\nfunction createS3Handler(opts) {\n\tconst { store, credentials } = opts;\n\treturn async (req) => {\n\t\tif (!verifyRequest(req, credentials).ok) return new Response(null, { status: 403 });\n\t\tconst url = new URL(req.url);\n\t\tconst target = parseTarget(url);\n\t\tif (!target) return new Response(null, { status: 400 });\n\t\tif (req.method === \"GET\" && url.searchParams.get(\"list-type\") === \"2\" && target.key === \"\") return handleList(store, target.bucket, url);\n\t\tif (target.key === \"\") return new Response(null, { status: 400 });\n\t\tswitch (req.method) {\n\t\t\tcase \"PUT\": return handlePut(store, target, req);\n\t\t\tcase \"GET\": return handleGet(store, target, req);\n\t\t\tcase \"HEAD\": return handleHead(store, target);\n\t\t\tcase \"DELETE\": return handleDelete(store, target);\n\t\t\tdefault: return new Response(null, { status: 405 });\n\t\t}\n\t};\n}\n//#endregion\n//#region src/memory-store.ts\n/**\n* An in-memory `ObjectStore` for the protocol tests — the same contract the\n* Postgres store (D3) implements. Test-only; never wired into a deployed\n* service. Not re-exported from the authoring barrel.\n*/\nconst DEFAULT_MAX_KEYS = 1e3;\nfunction etagOf(bytes) {\n\treturn `\"${createHash(\"sha256\").update(bytes).digest(\"hex\")}\"`;\n}\nvar MemoryObjectStore = class {\n\tentries = /* @__PURE__ */ new Map();\n\tid(bucket, key) {\n\t\treturn `${bucket}\\x00${key}`;\n\t}\n\tasync put(bucket, key, bytes, opts = {}) {\n\t\tconst copy = bytes.slice();\n\t\tconst etag = etagOf(copy);\n\t\tthis.entries.set(this.id(bucket, key), {\n\t\t\tbytes: copy,\n\t\t\tetag,\n\t\t\tcontentType: opts.contentType ?? \"application/octet-stream\"\n\t\t});\n\t\treturn { etag };\n\t}\n\tasync get(bucket, key, opts = {}) {\n\t\tconst entry = this.entries.get(this.id(bucket, key));\n\t\tif (!entry) return null;\n\t\tconst size = entry.bytes.byteLength;\n\t\tif (opts.range) {\n\t\t\tconst start = opts.range.start;\n\t\t\tconst end = opts.range.end === void 0 ? size - 1 : Math.min(opts.range.end, size - 1);\n\t\t\treturn {\n\t\t\t\tbytes: start > end ? /* @__PURE__ */ new Uint8Array(0) : entry.bytes.slice(start, end + 1),\n\t\t\t\tetag: entry.etag,\n\t\t\t\tcontentType: entry.contentType,\n\t\t\t\tsize\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tbytes: entry.bytes.slice(),\n\t\t\tetag: entry.etag,\n\t\t\tcontentType: entry.contentType,\n\t\t\tsize\n\t\t};\n\t}\n\tasync head(bucket, key) {\n\t\tconst entry = this.entries.get(this.id(bucket, key));\n\t\tif (!entry) return null;\n\t\treturn {\n\t\t\tetag: entry.etag,\n\t\t\tsize: entry.bytes.byteLength,\n\t\t\tcontentType: entry.contentType\n\t\t};\n\t}\n\tasync delete(bucket, key) {\n\t\tthis.entries.delete(this.id(bucket, key));\n\t}\n\tasync list(bucket, opts = {}) {\n\t\tconst prefix = opts.prefix ?? \"\";\n\t\tconst maxKeys = opts.maxKeys ?? DEFAULT_MAX_KEYS;\n\t\tconst token = opts.continuationToken;\n\t\tconst prefixHit = `${bucket}\\x00${prefix}`;\n\t\tconst matching = [...this.entries.keys()].filter((id) => id.startsWith(prefixHit)).map((id) => id.slice(bucket.length + 1)).sort().filter((key) => token === void 0 ? true : key > token);\n\t\tconst page = matching.slice(0, maxKeys);\n\t\tconst isTruncated = matching.length > maxKeys;\n\t\tconst last = page.at(-1);\n\t\treturn {\n\t\t\tkeys: page,\n\t\t\tisTruncated,\n\t\t\t...isTruncated && last !== void 0 ? { nextContinuationToken: last } : {}\n\t\t};\n\t}\n};\n//#endregion\nexport { MemoryObjectStore, createS3Handler, fsStore, mintKeyPair, verifyRequest };\n\n//# sourceMappingURL=index.mjs.map","import { c as readOwnVersion, f as StateFile, p as readJsonFile, t as isValidSegment } from \"./segments-D-anjQ84.mjs\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport * as http from \"node:http\";\nimport { createS3Handler, fsStore } from \"@internal/s3-protocol\";\n//#region src/buckets-main.ts\n/**\n* The bucket emulator daemon (local-dev spec § 2 `buckets-main.ts`): the S3\n* wire protocol (`@internal/s3-protocol`'s handler + `fsStore`) over\n* registered per-app, per-bucket directories, multi-tenant via physical\n* names `<app>--<name>`. Admin lives under `/_pcdev/` (the underscore can't\n* collide with a valid bucket name). Plain `node:http`.\n*\n* Runs as its own OS process, started by `daemon.ts`'s `ensureDaemon` via\n* `process.execPath <this file> --port <n> --state-dir <dir>`.\n*/\nconst STATE_MODE = 384;\nconst PHYSICAL_BUCKET_NAME_RE = /^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/;\nconst MULTIPART_MESSAGE = \"multipart upload is not supported by the local dev bucket emulator yet\";\nfunction isBucketRegistration(value) {\n\treturn typeof value === \"object\" && value !== null && \"app\" in value && typeof value.app === \"string\" && \"name\" in value && typeof value.name === \"string\" && \"dir\" in value && typeof value.dir === \"string\";\n}\nfunction isCredentialRecord(value) {\n\treturn typeof value === \"object\" && value !== null && \"app\" in value && typeof value.app === \"string\" && \"secretAccessKey\" in value && typeof value.secretAccessKey === \"string\";\n}\nfunction isBucketsState(value) {\n\treturn typeof value === \"object\" && value !== null && \"buckets\" in value && typeof value.buckets === \"object\" && value.buckets !== null && Object.values(value.buckets).every(isBucketRegistration) && \"credentials\" in value && typeof value.credentials === \"object\" && value.credentials !== null && Object.values(value.credentials).every(isCredentialRecord);\n}\nfunction isBucketBody(value) {\n\treturn typeof value === \"object\" && value !== null && \"dir\" in value && typeof value.dir === \"string\";\n}\nfunction isCredentialsBody(value) {\n\treturn typeof value === \"object\" && value !== null && \"accessKeyId\" in value && typeof value.accessKeyId === \"string\" && \"secretAccessKey\" in value && typeof value.secretAccessKey === \"string\";\n}\nfunction parseArgs(argv) {\n\tlet port;\n\tlet stateDir;\n\tfor (let i = 0; i < argv.length; i++) if (argv[i] === \"--port\") port = Number(argv[i + 1]);\n\telse if (argv[i] === \"--state-dir\") stateDir = argv[i + 1];\n\tif (port === void 0 || Number.isNaN(port)) throw new Error(\"buckets-main: --port <n> is required\");\n\tif (stateDir === void 0) throw new Error(\"buckets-main: --state-dir <dir> is required\");\n\treturn {\n\t\tport,\n\t\tstateDir\n\t};\n}\nfunction readBody(req) {\n\treturn new Promise((resolve, reject) => {\n\t\tconst chunks = [];\n\t\treq.on(\"data\", (chunk) => chunks.push(chunk));\n\t\treq.on(\"end\", () => resolve(Buffer.concat(chunks)));\n\t\treq.on(\"error\", reject);\n\t});\n}\nfunction toWebHeaders(nodeHeaders) {\n\tconst headers = new Headers();\n\tfor (const [key, value] of Object.entries(nodeHeaders)) {\n\t\tif (value === void 0) continue;\n\t\tif (Array.isArray(value)) for (const v of value) headers.append(key, v);\n\t\telse headers.set(key, value);\n\t}\n\treturn headers;\n}\nasync function sendWebResponse(res, webRes) {\n\tconst headers = {};\n\twebRes.headers.forEach((value, key) => {\n\t\theaders[key] = value;\n\t});\n\tconst buf = Buffer.from(await webRes.arrayBuffer());\n\tres.writeHead(webRes.status, headers);\n\tres.end(buf);\n}\nfunction main() {\n\tconst { port, stateDir } = parseArgs(process.argv.slice(2));\n\tconst ownVersion = readOwnVersion();\n\tconst stateJsonPath = path.join(stateDir, \"state.json\");\n\tconst stateFile = new StateFile(stateJsonPath, STATE_MODE);\n\tlet state = {\n\t\tbuckets: {},\n\t\tcredentials: {}\n\t};\n\tconst store = fsStore((physicalName) => state.buckets[physicalName]?.dir);\n\tfunction json(res, status, body) {\n\t\tres.writeHead(status, { \"content-type\": \"application/json\" });\n\t\tres.end(JSON.stringify(body));\n\t}\n\tfunction text(res, status, body) {\n\t\tres.writeHead(status, { \"content-type\": \"text/plain; charset=utf-8\" });\n\t\tres.end(body);\n\t}\n\tfunction badSegment(res, segment) {\n\t\ttext(res, 400, `invalid path segment \"${segment}\": must match /^[a-z0-9][a-z0-9-]*$/ and be at most 63 characters`);\n\t}\n\tasync function handlePutBucket(req, res, app, name) {\n\t\tconst physicalName = `${app}--${name}`;\n\t\tif (!PHYSICAL_BUCKET_NAME_RE.test(physicalName)) return text(res, 400, `invalid bucket \"${physicalName}\" (app \"${app}\", name \"${name}\"): the physical bucket name must match /^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/ and be at most 63 characters`);\n\t\tconst raw = await readBody(req);\n\t\tlet parsed;\n\t\ttry {\n\t\t\tparsed = JSON.parse(raw.toString(\"utf8\"));\n\t\t} catch {\n\t\t\treturn text(res, 400, \"malformed JSON body\");\n\t\t}\n\t\tif (!isBucketBody(parsed)) return text(res, 400, \"malformed bucket body: expected { \\\"dir\\\": string }\");\n\t\tawait fs.promises.mkdir(parsed.dir, { recursive: true });\n\t\tstate.buckets[physicalName] = {\n\t\t\tapp,\n\t\t\tname,\n\t\t\tdir: parsed.dir\n\t\t};\n\t\tawait stateFile.write(state);\n\t\tres.writeHead(204);\n\t\tres.end();\n\t}\n\tasync function handlePutCredentials(req, res, app) {\n\t\tconst raw = await readBody(req);\n\t\tlet parsed;\n\t\ttry {\n\t\t\tparsed = JSON.parse(raw.toString(\"utf8\"));\n\t\t} catch {\n\t\t\treturn text(res, 400, \"malformed JSON body\");\n\t\t}\n\t\tif (!isCredentialsBody(parsed)) return text(res, 400, \"malformed credentials body: expected { \\\"accessKeyId\\\", \\\"secretAccessKey\\\" }\");\n\t\tconst existing = state.credentials[parsed.accessKeyId];\n\t\tif (existing && existing.app !== app) return text(res, 409, `accessKeyId \"${parsed.accessKeyId}\" is already registered by a different app`);\n\t\tstate.credentials[parsed.accessKeyId] = {\n\t\t\tapp,\n\t\t\tsecretAccessKey: parsed.secretAccessKey\n\t\t};\n\t\tawait stateFile.write(state);\n\t\tres.writeHead(204);\n\t\tres.end();\n\t}\n\tasync function handleDeleteApp(res, app) {\n\t\tfor (const [key, reg] of Object.entries(state.buckets)) if (reg.app === app) delete state.buckets[key];\n\t\tfor (const [key, cred] of Object.entries(state.credentials)) if (cred.app === app) delete state.credentials[key];\n\t\tawait stateFile.write(state);\n\t\tres.writeHead(204);\n\t\tres.end();\n\t}\n\t/** Path-style addressing: the bucket is the first non-empty path segment. Mirrors the handler's own `parseTarget`, which isn't exported. */\n\tfunction bucketFromPath(pathname) {\n\t\tconst first = pathname.split(\"/\").find((s) => s.length > 0);\n\t\treturn first !== void 0 ? decodeURIComponent(first) : void 0;\n\t}\n\t/**\n\t* Credentials accepted for THIS request's target bucket only — its\n\t* owning app, derived from the bucket's registration (the authoritative\n\t* source for the `<app>--<name>` split; unregistered apps/names may\n\t* themselves contain `--`, so the registration is trusted over re-parsing\n\t* the string). An unknown bucket or an app with no registered credentials\n\t* yields no candidates, which still resolves through the real 403 path\n\t* below — never a bespoke \"unknown bucket\" shortcut that would reveal\n\t* anything.\n\t*/\n\tfunction credentialsForBucket(bucket) {\n\t\tconst owningApp = bucket !== void 0 ? state.buckets[bucket]?.app : void 0;\n\t\tif (owningApp === void 0) return [];\n\t\treturn Object.entries(state.credentials).filter(([, rec]) => rec.app === owningApp).map(([accessKeyId, rec]) => ({\n\t\t\taccessKeyId,\n\t\t\tsecretAccessKey: rec.secretAccessKey\n\t\t}));\n\t}\n\tasync function handleS3Wire(req, res, url) {\n\t\tif (url.searchParams.has(\"uploads\") || url.searchParams.has(\"uploadId\") || url.searchParams.has(\"partNumber\")) return text(res, 501, MULTIPART_MESSAGE);\n\t\tconst method = req.method ?? \"GET\";\n\t\tconst bodyBuf = method !== \"GET\" && method !== \"HEAD\" ? await readBody(req) : void 0;\n\t\tconst fullUrl = `http://${req.headers.host ?? `127.0.0.1:${String(port)}`}${req.url ?? \"/\"}`;\n\t\tconst headers = toWebHeaders(req.headers);\n\t\tconst candidates = credentialsForBucket(bucketFromPath(url.pathname));\n\t\tif (candidates.length === 0) candidates.push({\n\t\t\taccessKeyId: \"\",\n\t\t\tsecretAccessKey: \"\"\n\t\t});\n\t\tlet last;\n\t\tfor (const credentials of candidates) {\n\t\t\tconst webReq = new Request(fullUrl, {\n\t\t\t\tmethod,\n\t\t\t\theaders,\n\t\t\t\t...bodyBuf && bodyBuf.length > 0 ? { body: bodyBuf } : {}\n\t\t\t});\n\t\t\tconst webRes = await createS3Handler({\n\t\t\t\tstore,\n\t\t\t\tcredentials\n\t\t\t})(webReq);\n\t\t\tif (webRes.status !== 403) return sendWebResponse(res, webRes);\n\t\t\tlast = webRes;\n\t\t}\n\t\tif (last) await sendWebResponse(res, last);\n\t}\n\tasync function handleRequest(req, res) {\n\t\tconst url = new URL(req.url ?? \"/\", `http://127.0.0.1:${String(port)}`);\n\t\tconst method = req.method ?? \"GET\";\n\t\tif (method === \"GET\" && url.pathname === \"/health\") return json(res, 200, { version: ownVersion });\n\t\tif (url.pathname === \"/_pcdev/health\" || url.pathname.startsWith(\"/_pcdev/\")) {\n\t\t\tconst segments = url.pathname.split(\"/\").filter((s) => s.length > 0).map((s) => decodeURIComponent(s));\n\t\t\tif (method === \"GET\" && segments.length === 2 && segments[1] === \"health\") return json(res, 200, { version: ownVersion });\n\t\t\tif (segments[1] === \"apps\" && segments.length >= 3) {\n\t\t\t\tconst app = segments[2];\n\t\t\t\tif (app === void 0 || !isValidSegment(app)) return badSegment(res, app ?? \"\");\n\t\t\t\tif (method === \"PUT\" && segments.length === 5 && segments[3] === \"buckets\") {\n\t\t\t\t\tconst name = segments[4];\n\t\t\t\t\tif (name === void 0 || !isValidSegment(name)) return badSegment(res, name ?? \"\");\n\t\t\t\t\treturn handlePutBucket(req, res, app, name);\n\t\t\t\t}\n\t\t\t\tif (method === \"PUT\" && segments.length === 4 && segments[3] === \"credentials\") return handlePutCredentials(req, res, app);\n\t\t\t\tif (method === \"DELETE\" && segments.length === 3) return handleDeleteApp(res, app);\n\t\t\t}\n\t\t\tres.writeHead(404);\n\t\t\tres.end();\n\t\t\treturn;\n\t\t}\n\t\treturn handleS3Wire(req, res, url);\n\t}\n\tconst server = http.createServer((req, res) => {\n\t\thandleRequest(req, res).catch((err) => {\n\t\t\tif (!res.headersSent) res.writeHead(500, { \"content-type\": \"text/plain\" });\n\t\t\tres.end(err instanceof Error ? err.message : String(err));\n\t\t});\n\t});\n\tasync function shutdown() {\n\t\tawait stateFile.flush();\n\t\tserver.close();\n\t\tprocess.exit(0);\n\t}\n\tprocess.on(\"SIGTERM\", () => void shutdown());\n\tprocess.on(\"SIGINT\", () => void shutdown());\n\treadJsonFile(stateJsonPath, isBucketsState).then((loaded) => {\n\t\tif (loaded) state = loaded;\n\t\tserver.listen(port, \"127.0.0.1\", () => {\n\t\t\tconsole.log(`[dev-emulators] buckets-main listening on 127.0.0.1:${String(port)}`);\n\t\t});\n\t}).catch((err) => {\n\t\tconsole.error(\"buckets-main: failed to load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AAO,MAAM,mBAAmB;GACtC,QAAQ,IAAI,uDAAuD,OAAO,IAAI,GAAG;EAClF,CAAC;CACF,CAAC,CAAC,CAAC,OAAO,QAAQ;EACjB,QAAQ,MAAM,sCAAsC,GAAG;EACvD,QAAQ,KAAK,CAAC;CACf,CAAC;AACF;AACA,KAAK"}
|
|
1
|
+
{"version":3,"file":"buckets-main.mjs","names":["fs"],"sources":["../../../1-prisma-cloud/0-lowering/s3-protocol/dist/index.mjs","../../../1-prisma-cloud/0-lowering/dev-emulators/dist/buckets-main.mjs"],"sourcesContent":["import { createHash, createHmac, randomUUID, timingSafeEqual } from \"node:crypto\";\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nconst DEFAULT_CONTENT_TYPE$1 = \"application/octet-stream\";\nconst TMP_DIR_NAME = \".tmp\";\nconst META_DIR_NAME = \".meta\";\nconst RESERVED_SEGMENTS = /* @__PURE__ */ new Set([TMP_DIR_NAME, META_DIR_NAME]);\nconst BUCKET_NAME_RE = /^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/;\nfunction etagOf$1(bytes) {\n\treturn `\"${createHash(\"sha256\").update(bytes).digest(\"hex\")}\"`;\n}\nfunction isErrnoException(err) {\n\treturn err instanceof Error && \"code\" in err;\n}\nfunction isEnoent(err) {\n\treturn isErrnoException(err) && err.code === \"ENOENT\";\n}\n/**\n* Splits a key into its `/` segments, rejecting anything that could escape\n* the bucket dir or collide with the reserved `.tmp`/`.meta` namespaces:\n* `..` segments, an empty segment (leading/trailing/doubled `/`, which also\n* catches a leading-slash \"absolute\" key), or a segment literally `.tmp` or\n* `.meta` at any depth.\n*/\nfunction keySegments(key) {\n\tconst segments = key.split(\"/\");\n\tfor (const segment of segments) if (segment === \"\" || segment === \".\" || segment === \"..\" || RESERVED_SEGMENTS.has(segment)) throw new Error(`invalid object key: \"${key}\"`);\n\treturn segments;\n}\n/** `<bucketDir>/<key's segments>`, double-checked to still resolve inside `bucketDir`. */\nfunction objectPath(bucketDir, key) {\n\tconst target = path.join(bucketDir, ...keySegments(key));\n\tconst resolvedRoot = path.resolve(bucketDir) + path.sep;\n\tif (!(path.resolve(target) + path.sep).startsWith(resolvedRoot)) throw new Error(`invalid object key: \"${key}\"`);\n\treturn target;\n}\n/** `<bucketDir>/.meta/<key's segments>.json` — mirrors `objectPath`'s tree under `.meta`. */\nfunction sidecarPath(bucketDir, key) {\n\tconst segments = keySegments(key);\n\tconst last = segments[segments.length - 1];\n\tconst dirs = segments.slice(0, -1);\n\treturn path.join(bucketDir, META_DIR_NAME, ...dirs, `${last}.json`);\n}\n/** Write-temp-then-rename: never leaves a reader observing a partial file. */\nasync function writeAtomic(finalPath, tmpRoot, bytes) {\n\tawait fs.mkdir(tmpRoot, { recursive: true });\n\tconst tmpPath = path.join(tmpRoot, randomUUID());\n\tawait fs.writeFile(tmpPath, bytes);\n\tawait fs.mkdir(path.dirname(finalPath), { recursive: true });\n\tawait fs.rename(tmpPath, finalPath);\n}\nfunction isSidecar(value) {\n\treturn typeof value === \"object\" && value !== null && \"contentType\" in value && typeof value.contentType === \"string\" && \"etag\" in value && typeof value.etag === \"string\";\n}\nasync function readSidecar(sidecar) {\n\tlet raw;\n\ttry {\n\t\traw = await fs.readFile(sidecar, \"utf8\");\n\t} catch (err) {\n\t\tif (isEnoent(err)) return null;\n\t\tthrow err;\n\t}\n\ttry {\n\t\tconst parsed = JSON.parse(raw);\n\t\tif (isSidecar(parsed)) return parsed;\n\t} catch {}\n\treturn null;\n}\n/** Read the object's bytes plus its metadata — adopting a sidecar-less file (dropped in by a developer) by computing and lazily persisting one. `null` when the object is missing. */\nasync function readObject(bucketDir, key) {\n\tconst target = objectPath(bucketDir, key);\n\tlet bytes;\n\ttry {\n\t\tbytes = await fs.readFile(target);\n\t} catch (err) {\n\t\tif (isEnoent(err)) return null;\n\t\tthrow err;\n\t}\n\tconst existing = await readSidecar(sidecarPath(bucketDir, key));\n\tif (existing) return {\n\t\tbytes,\n\t\tmeta: existing\n\t};\n\tconst meta = {\n\t\tcontentType: DEFAULT_CONTENT_TYPE$1,\n\t\tetag: etagOf$1(bytes)\n\t};\n\tawait writeAtomic(sidecarPath(bucketDir, key), path.join(bucketDir, TMP_DIR_NAME), Buffer.from(JSON.stringify(meta)));\n\treturn {\n\t\tbytes,\n\t\tmeta\n\t};\n}\n/** Remove now-empty directories from `startDir` up to (never including) `root`. */\nasync function pruneEmptyDirs(root, startDir) {\n\tconst resolvedRoot = path.resolve(root);\n\tlet dir = path.resolve(startDir);\n\twhile (dir !== resolvedRoot && dir.startsWith(resolvedRoot + path.sep)) {\n\t\tlet entries;\n\t\ttry {\n\t\t\tentries = await fs.readdir(dir);\n\t\t} catch (err) {\n\t\t\tif (isEnoent(err)) {\n\t\t\t\tdir = path.dirname(dir);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t\tif (entries.length > 0) break;\n\t\ttry {\n\t\t\tawait fs.rmdir(dir);\n\t\t} catch (err) {\n\t\t\tif (!isEnoent(err)) throw err;\n\t\t}\n\t\tdir = path.dirname(dir);\n\t}\n}\n/** Recursively lists every object key under `dir`, skipping `.tmp`/`.meta` at any depth. */\nasync function walkKeys(dir) {\n\tconst keys = [];\n\tasync function walk(current, prefix) {\n\t\tlet entries;\n\t\ttry {\n\t\t\tentries = await fs.readdir(current, { withFileTypes: true });\n\t\t} catch (err) {\n\t\t\tif (isEnoent(err)) return;\n\t\t\tthrow err;\n\t\t}\n\t\tfor (const entry of entries) {\n\t\t\tif (RESERVED_SEGMENTS.has(entry.name)) continue;\n\t\t\tconst rel = prefix === \"\" ? entry.name : `${prefix}/${entry.name}`;\n\t\t\tif (entry.isDirectory()) await walk(path.join(current, entry.name), rel);\n\t\t\telse if (entry.isFile()) keys.push(rel);\n\t\t}\n\t}\n\tawait walk(dir, \"\");\n\treturn keys;\n}\n/**\n* A disk-backed `ObjectStore`: object bytes and a metadata sidecar under a\n* per-bucket directory the caller resolves. See the module doc for the\n* unknown-bucket / invalid-key failure shapes.\n*/\nfunction fsStore(resolveBucketDir) {\n\tfunction resolveDir(bucket) {\n\t\tif (!BUCKET_NAME_RE.test(bucket)) return void 0;\n\t\treturn resolveBucketDir(bucket);\n\t}\n\treturn {\n\t\tasync put(bucket, key, bytes, opts = {}) {\n\t\t\tconst dir = resolveDir(bucket);\n\t\t\tif (dir === void 0) throw new Error(`no such bucket: \"${bucket}\"`);\n\t\t\tconst target = objectPath(dir, key);\n\t\t\tconst tmpRoot = path.join(dir, TMP_DIR_NAME);\n\t\t\tconst etag = etagOf$1(bytes);\n\t\t\tconst contentType = opts.contentType ?? DEFAULT_CONTENT_TYPE$1;\n\t\t\tawait writeAtomic(target, tmpRoot, bytes);\n\t\t\tawait writeAtomic(sidecarPath(dir, key), tmpRoot, Buffer.from(JSON.stringify({\n\t\t\t\tcontentType,\n\t\t\t\tetag\n\t\t\t})));\n\t\t\treturn { etag };\n\t\t},\n\t\tasync get(bucket, key, opts = {}) {\n\t\t\tconst dir = resolveDir(bucket);\n\t\t\tif (dir === void 0) return null;\n\t\t\tconst found = await readObject(dir, key);\n\t\t\tif (!found) return null;\n\t\t\tconst { bytes, meta } = found;\n\t\t\tconst size = bytes.byteLength;\n\t\t\tif (opts.range) {\n\t\t\t\tconst start = opts.range.start;\n\t\t\t\tconst end = opts.range.end === void 0 ? size - 1 : Math.min(opts.range.end, size - 1);\n\t\t\t\treturn {\n\t\t\t\t\tbytes: start > end ? /* @__PURE__ */ new Uint8Array(0) : bytes.subarray(start, end + 1),\n\t\t\t\t\tetag: meta.etag,\n\t\t\t\t\tcontentType: meta.contentType,\n\t\t\t\t\tsize\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tbytes: new Uint8Array(bytes),\n\t\t\t\tetag: meta.etag,\n\t\t\t\tcontentType: meta.contentType,\n\t\t\t\tsize\n\t\t\t};\n\t\t},\n\t\tasync head(bucket, key) {\n\t\t\tconst dir = resolveDir(bucket);\n\t\t\tif (dir === void 0) return null;\n\t\t\tconst found = await readObject(dir, key);\n\t\t\tif (!found) return null;\n\t\t\treturn {\n\t\t\t\tetag: found.meta.etag,\n\t\t\t\tsize: found.bytes.byteLength,\n\t\t\t\tcontentType: found.meta.contentType\n\t\t\t};\n\t\t},\n\t\tasync delete(bucket, key) {\n\t\t\tconst dir = resolveDir(bucket);\n\t\t\tif (dir === void 0) return;\n\t\t\tconst target = objectPath(dir, key);\n\t\t\tconst sidecar = sidecarPath(dir, key);\n\t\t\ttry {\n\t\t\t\tawait fs.unlink(target);\n\t\t\t} catch (err) {\n\t\t\t\tif (!isEnoent(err)) throw err;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait fs.unlink(sidecar);\n\t\t\t} catch (err) {\n\t\t\t\tif (!isEnoent(err)) throw err;\n\t\t\t}\n\t\t\tawait pruneEmptyDirs(dir, path.dirname(target));\n\t\t\tawait pruneEmptyDirs(path.join(dir, META_DIR_NAME), path.dirname(sidecar));\n\t\t},\n\t\tasync list(bucket, opts = {}) {\n\t\t\tconst dir = resolveDir(bucket);\n\t\t\tif (dir === void 0) return {\n\t\t\t\tkeys: [],\n\t\t\t\tisTruncated: false\n\t\t\t};\n\t\t\tconst prefix = opts.prefix ?? \"\";\n\t\t\tconst maxKeys = opts.maxKeys ?? 1e3;\n\t\t\tconst token = opts.continuationToken;\n\t\t\tconst matching = (await walkKeys(dir)).filter((key) => key.startsWith(prefix)).sort().filter((key) => token === void 0 ? true : key > token);\n\t\t\tconst page = matching.slice(0, maxKeys);\n\t\t\tconst isTruncated = matching.length > maxKeys;\n\t\t\tconst last = page.at(-1);\n\t\t\treturn {\n\t\t\t\tkeys: page,\n\t\t\t\tisTruncated,\n\t\t\t\t...isTruncated && last !== void 0 ? { nextContinuationToken: last } : {}\n\t\t\t};\n\t\t}\n\t};\n}\n//#endregion\n//#region src/sigv4.ts\n/**\n* AWS SigV4 verification for the S3 wire protocol (spec § 2 auth). The payload\n* hash comes from the client — `x-amz-content-sha256` (a real hash or\n* `UNSIGNED-PAYLOAD`) for header auth, `UNSIGNED-PAYLOAD` for presign — and is\n* never re-hashed; the verifier trusts what was signed, like a real S3 endpoint.\n* Runtime engine code (`node:crypto`); not re-exported from the authoring barrel.\n*\n* Also owns `mintKeyPair` (local-dev spec § 1) — the one key-pair generator\n* both the deploy-time `S3Credentials` resource and the local dev bucket\n* emulator's credential provisioning use.\n*/\nfunction randomBytes(n) {\n\treturn crypto.getRandomValues(new Uint8Array(n));\n}\nfunction toHexUpper(bytes) {\n\treturn Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\").toUpperCase();\n}\n/** A fresh SigV4 key pair: an AKIA-prefixed id and a 40-char base64 secret. */\nfunction mintKeyPair() {\n\treturn {\n\t\taccessKeyId: `AKIA${toHexUpper(randomBytes(8))}`,\n\t\tsecretAccessKey: btoa(String.fromCharCode(...randomBytes(30)))\n\t};\n}\nconst ALGORITHM = \"AWS4-HMAC-SHA256\";\nconst UNSIGNED_PAYLOAD = \"UNSIGNED-PAYLOAD\";\nfunction sha256Hex(data) {\n\treturn createHash(\"sha256\").update(data).digest(\"hex\");\n}\nfunction hmac(key, data) {\n\treturn createHmac(\"sha256\", key).update(data).digest();\n}\n/** AWS canonical URI encoding: every byte except the unreserved set is %XX. */\nfunction awsUriEncode(value) {\n\treturn encodeURIComponent(value).replace(/[!'()*]/g, (ch) => `%${ch.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%7E/g, \"~\");\n}\nfunction parseCredential(credential) {\n\tconst parts = credential.split(\"/\");\n\tif (parts.length !== 5 || parts[4] !== \"aws4_request\") return null;\n\tconst [accessKeyId, date, region, service] = parts;\n\tif (!accessKeyId || !date || !region || !service) return null;\n\treturn {\n\t\taccessKeyId,\n\t\tdate,\n\t\tregion,\n\t\tservice\n\t};\n}\nfunction signingKey(secret, scope) {\n\treturn hmac(hmac(hmac(hmac(`AWS4${secret}`, scope.date), scope.region), scope.service), \"aws4_request\");\n}\nfunction canonicalHeaders(url, req, signedHeaders) {\n\treturn signedHeaders.map((name) => {\n\t\treturn `${name}:${(name === \"host\" ? url.host : req.headers.get(name) ?? \"\").trim().replace(/\\s+/g, \" \")}\\n`;\n\t}).join(\"\");\n}\nfunction canonicalQuery(url, exclude) {\n\tconst entries = [];\n\tfor (const [key, value] of url.searchParams.entries()) {\n\t\tif (exclude !== void 0 && key === exclude) continue;\n\t\tentries.push([awsUriEncode(key), awsUriEncode(value)]);\n\t}\n\tconst cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;\n\tentries.sort(([ak, av], [bk, bv]) => cmp(ak, bk) || cmp(av, bv));\n\treturn entries.map(([k, v]) => `${k}=${v}`).join(\"&\");\n}\nfunction stringToSign(amzDate, scope, canonicalRequest) {\n\tconst scopeString = `${scope.date}/${scope.region}/${scope.service}/aws4_request`;\n\treturn [\n\t\tALGORITHM,\n\t\tamzDate,\n\t\tscopeString,\n\t\tsha256Hex(canonicalRequest)\n\t].join(\"\\n\");\n}\nfunction signatureMatches(expected, provided) {\n\tconst a = Buffer.from(expected, \"hex\");\n\tconst b = Buffer.from(provided, \"hex\");\n\treturn a.length === b.length && a.length > 0 && timingSafeEqual(a, b);\n}\n/** `YYYYMMDDTHHMMSSZ` → epoch ms, or null when malformed. */\nfunction parseAmzDate(amzDate) {\n\tconst match = /^(\\d{4})(\\d{2})(\\d{2})T(\\d{2})(\\d{2})(\\d{2})Z$/.exec(amzDate);\n\tif (!match) return null;\n\tconst [, y, mo, d, h, mi, s] = match;\n\treturn Date.UTC(Number(y), Number(mo) - 1, Number(d), Number(h), Number(mi), Number(s));\n}\nfunction parseAuthorizationHeader(header) {\n\tif (!header.startsWith(`${ALGORITHM} `)) return null;\n\tconst rest = header.slice(17);\n\tconst fields = /* @__PURE__ */ new Map();\n\tfor (const part of rest.split(\",\")) {\n\t\tconst eq = part.indexOf(\"=\");\n\t\tif (eq === -1) continue;\n\t\tfields.set(part.slice(0, eq).trim(), part.slice(eq + 1).trim());\n\t}\n\tconst credential = fields.get(\"Credential\");\n\tconst signedHeaders = fields.get(\"SignedHeaders\");\n\tconst signature = fields.get(\"Signature\");\n\tif (!credential || !signedHeaders || !signature) return null;\n\treturn {\n\t\tcredential,\n\t\tsignedHeaders: signedHeaders.split(\";\"),\n\t\tsignature\n\t};\n}\n/** The one signing core both auth forms share: check the access key, rebuild the canonical request, derive the key, compare in constant time. */\nfunction verifySignature(req, url, credentials, params) {\n\tif (params.scope.accessKeyId !== credentials.accessKeyId) return {\n\t\tok: false,\n\t\treason: \"unknown access key\"\n\t};\n\tconst canonicalRequest = [\n\t\treq.method,\n\t\turl.pathname,\n\t\tcanonicalQuery(url, params.excludeQuery),\n\t\tcanonicalHeaders(url, req, params.signedHeaders),\n\t\tparams.signedHeaders.join(\";\"),\n\t\tparams.payloadHash\n\t].join(\"\\n\");\n\treturn signatureMatches(hmac(signingKey(credentials.secretAccessKey, params.scope), stringToSign(params.amzDate, params.scope, canonicalRequest)).toString(\"hex\"), params.signature) ? { ok: true } : {\n\t\tok: false,\n\t\treason: \"signature mismatch\"\n\t};\n}\nfunction verifyHeader(req, url, credentials) {\n\tconst auth = parseAuthorizationHeader(req.headers.get(\"authorization\") ?? \"\");\n\tif (!auth) return {\n\t\tok: false,\n\t\treason: \"malformed Authorization header\"\n\t};\n\tconst scope = parseCredential(auth.credential);\n\tif (!scope) return {\n\t\tok: false,\n\t\treason: \"malformed credential scope\"\n\t};\n\tconst amzDate = req.headers.get(\"x-amz-date\");\n\tif (!amzDate) return {\n\t\tok: false,\n\t\treason: \"missing x-amz-date\"\n\t};\n\tconst payloadHash = req.headers.get(\"x-amz-content-sha256\");\n\tif (!payloadHash) return {\n\t\tok: false,\n\t\treason: \"missing x-amz-content-sha256\"\n\t};\n\treturn verifySignature(req, url, credentials, {\n\t\tscope,\n\t\tamzDate,\n\t\tsignedHeaders: auth.signedHeaders,\n\t\tpayloadHash,\n\t\tsignature: auth.signature\n\t});\n}\nfunction verifyPresigned(req, url, credentials, now) {\n\tconst q = url.searchParams;\n\tif (q.get(\"X-Amz-Algorithm\") !== ALGORITHM) return {\n\t\tok: false,\n\t\treason: \"unsupported presign algorithm\"\n\t};\n\tconst credentialRaw = q.get(\"X-Amz-Credential\");\n\tconst amzDate = q.get(\"X-Amz-Date\");\n\tconst expiresRaw = q.get(\"X-Amz-Expires\");\n\tconst signedHeadersRaw = q.get(\"X-Amz-SignedHeaders\");\n\tconst signature = q.get(\"X-Amz-Signature\");\n\tif (!credentialRaw || !amzDate || !expiresRaw || !signedHeadersRaw || !signature) return {\n\t\tok: false,\n\t\treason: \"incomplete presign parameters\"\n\t};\n\tconst scope = parseCredential(credentialRaw);\n\tif (!scope) return {\n\t\tok: false,\n\t\treason: \"malformed credential scope\"\n\t};\n\tconst signedAt = parseAmzDate(amzDate);\n\tconst expires = Number(expiresRaw);\n\tif (signedAt === null || !Number.isFinite(expires)) return {\n\t\tok: false,\n\t\treason: \"malformed presign date\"\n\t};\n\tif (now.getTime() > signedAt + expires * 1e3) return {\n\t\tok: false,\n\t\treason: \"presign expired\"\n\t};\n\treturn verifySignature(req, url, credentials, {\n\t\tscope,\n\t\tamzDate,\n\t\tsignedHeaders: signedHeadersRaw.split(\";\"),\n\t\tpayloadHash: UNSIGNED_PAYLOAD,\n\t\tsignature,\n\t\texcludeQuery: \"X-Amz-Signature\"\n\t});\n}\n/**\n* Verify a request's SigV4 signature against a single credential pair. Picks\n* the presigned form when `X-Amz-Signature` is present, otherwise the\n* `Authorization`-header form. `now` is injectable for deterministic\n* expiry tests.\n*/\nfunction verifyRequest(req, credentials, now = /* @__PURE__ */ new Date()) {\n\tconst url = new URL(req.url);\n\tif (url.searchParams.has(\"X-Amz-Signature\")) return verifyPresigned(req, url, credentials, now);\n\tif (req.headers.has(\"authorization\")) return verifyHeader(req, url, credentials);\n\treturn {\n\t\tok: false,\n\t\treason: \"unsigned request\"\n\t};\n}\n//#endregion\n//#region src/handler.ts\nconst DEFAULT_CONTENT_TYPE = \"application/octet-stream\";\n/** Path-style: `/{bucket}/{key…}`. Each segment is percent-decoded. */\nfunction parseTarget(url) {\n\tconst segments = url.pathname.split(\"/\").filter((s) => s.length > 0);\n\tif (segments.length === 0) return null;\n\tconst [bucket, ...keyParts] = segments;\n\treturn {\n\t\tbucket: decodeURIComponent(bucket ?? \"\"),\n\t\tkey: keyParts.map(decodeURIComponent).join(\"/\")\n\t};\n}\n/** `bytes=a-b` (inclusive) or `bytes=a-` (open-ended). Null when absent/malformed. */\nfunction parseRange(header) {\n\tif (!header) return null;\n\tconst match = /^bytes=(\\d+)-(\\d*)$/.exec(header.trim());\n\tif (!match) return null;\n\tconst start = Number(match[1]);\n\treturn match[2] ? {\n\t\tstart,\n\t\tend: Number(match[2])\n\t} : { start };\n}\nfunction xmlEscape(value) {\n\treturn value.replace(/&/g, \"&\").replace(/</g, \"<\").replace(/>/g, \">\").replace(/\"/g, \""\").replace(/'/g, \"'\");\n}\nfunction listXml(bucket, prefix, maxKeys, result) {\n\tconst contents = result.keys.map((k) => `<Contents><Key>${xmlEscape(k)}</Key></Contents>`).join(\"\");\n\tconst next = result.isTruncated && result.nextContinuationToken !== void 0 ? `<NextContinuationToken>${xmlEscape(result.nextContinuationToken)}</NextContinuationToken>` : \"\";\n\treturn `<?xml version=\"1.0\" encoding=\"UTF-8\"?><ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Name>${xmlEscape(bucket)}</Name><Prefix>${xmlEscape(prefix)}</Prefix><KeyCount>${result.keys.length}</KeyCount><MaxKeys>${maxKeys}</MaxKeys><IsTruncated>${result.isTruncated}</IsTruncated>` + contents + next + \"</ListBucketResult>\";\n}\nconst DEFAULT_MAX_KEYS$1 = 1e3;\nasync function handleList(store, bucket, url) {\n\tconst prefix = url.searchParams.get(\"prefix\") ?? \"\";\n\tconst continuationToken = url.searchParams.get(\"continuation-token\");\n\tconst maxKeysRaw = url.searchParams.get(\"max-keys\");\n\tconst maxKeys = maxKeysRaw !== null && Number.isFinite(Number(maxKeysRaw)) ? Number(maxKeysRaw) : DEFAULT_MAX_KEYS$1;\n\tconst result = await store.list(bucket, {\n\t\tprefix,\n\t\tmaxKeys,\n\t\t...continuationToken !== null ? { continuationToken } : {}\n\t});\n\treturn new Response(listXml(bucket, prefix, maxKeys, result), {\n\t\tstatus: 200,\n\t\theaders: { \"content-type\": \"application/xml\" }\n\t});\n}\n/** aws-chunked / flexible-checksum PUTs frame the body as chunks + a trailer (signalled by `x-amz-content-sha256: STREAMING-…` or `content-encoding: aws-chunked`); the seed signature still verifies, so reject them (501) rather than store the raw framing as the object bytes. Decoding is out of scope. */\nfunction isStreamingPut(req) {\n\tconst contentSha = req.headers.get(\"x-amz-content-sha256\") ?? \"\";\n\tconst contentEncoding = req.headers.get(\"content-encoding\") ?? \"\";\n\treturn contentSha.startsWith(\"STREAMING-\") || contentEncoding.split(\",\").some((e) => e.trim() === \"aws-chunked\");\n}\nasync function handlePut(store, t, req) {\n\tif (isStreamingPut(req)) return new Response(\"aws-chunked / flexible checksums not supported; set requestChecksumCalculation: 'WHEN_REQUIRED'\", { status: 501 });\n\tconst body = new Uint8Array(await req.arrayBuffer());\n\tconst contentType = req.headers.get(\"content-type\") ?? DEFAULT_CONTENT_TYPE;\n\tconst { etag } = await store.put(t.bucket, t.key, body, { contentType });\n\treturn new Response(null, {\n\t\tstatus: 200,\n\t\theaders: { etag }\n\t});\n}\n/** The etag/content-type/content-length/accept-ranges headers GET and HEAD share — `contentLength` is the slice length for GET, the total object size for HEAD. */\nfunction metaHeaders(meta) {\n\treturn new Headers({\n\t\tetag: meta.etag,\n\t\t\"content-type\": meta.contentType,\n\t\t\"content-length\": String(meta.contentLength),\n\t\t\"accept-ranges\": \"bytes\"\n\t});\n}\nasync function handleGet(store, t, req) {\n\tconst range = parseRange(req.headers.get(\"range\"));\n\tconst object = await store.get(t.bucket, t.key, range ? { range } : void 0);\n\tif (!object) return new Response(null, { status: 404 });\n\tconst headers = metaHeaders({\n\t\tetag: object.etag,\n\t\tcontentType: object.contentType,\n\t\tcontentLength: object.bytes.byteLength\n\t});\n\tif (!range) return new Response(object.bytes, {\n\t\tstatus: 200,\n\t\theaders\n\t});\n\tif (range.start >= object.size && object.size > 0) return new Response(null, {\n\t\tstatus: 416,\n\t\theaders: { \"content-range\": `bytes */${object.size}` }\n\t});\n\tconst end = range.end === void 0 ? object.size - 1 : Math.min(range.end, object.size - 1);\n\theaders.set(\"content-range\", `bytes ${range.start}-${end}/${object.size}`);\n\treturn new Response(object.bytes, {\n\t\tstatus: 206,\n\t\theaders\n\t});\n}\nasync function handleHead(store, t) {\n\tconst meta = await store.head(t.bucket, t.key);\n\tif (!meta) return new Response(null, { status: 404 });\n\treturn new Response(null, {\n\t\tstatus: 200,\n\t\theaders: metaHeaders({\n\t\t\tetag: meta.etag,\n\t\t\tcontentType: meta.contentType,\n\t\t\tcontentLength: meta.size\n\t\t})\n\t});\n}\nasync function handleDelete(store, t) {\n\tawait store.delete(t.bucket, t.key);\n\treturn new Response(null, { status: 204 });\n}\nfunction createS3Handler(opts) {\n\tconst { store, credentials } = opts;\n\treturn async (req) => {\n\t\tif (!verifyRequest(req, credentials).ok) return new Response(null, { status: 403 });\n\t\tconst url = new URL(req.url);\n\t\tconst target = parseTarget(url);\n\t\tif (!target) return new Response(null, { status: 400 });\n\t\tif (req.method === \"GET\" && url.searchParams.get(\"list-type\") === \"2\" && target.key === \"\") return handleList(store, target.bucket, url);\n\t\tif (target.key === \"\") return new Response(null, { status: 400 });\n\t\tswitch (req.method) {\n\t\t\tcase \"PUT\": return handlePut(store, target, req);\n\t\t\tcase \"GET\": return handleGet(store, target, req);\n\t\t\tcase \"HEAD\": return handleHead(store, target);\n\t\t\tcase \"DELETE\": return handleDelete(store, target);\n\t\t\tdefault: return new Response(null, { status: 405 });\n\t\t}\n\t};\n}\n//#endregion\n//#region src/memory-store.ts\n/**\n* An in-memory `ObjectStore` for the protocol tests — the same contract the\n* Postgres store (D3) implements. Test-only; never wired into a deployed\n* service. Not re-exported from the authoring barrel.\n*/\nconst DEFAULT_MAX_KEYS = 1e3;\nfunction etagOf(bytes) {\n\treturn `\"${createHash(\"sha256\").update(bytes).digest(\"hex\")}\"`;\n}\nvar MemoryObjectStore = class {\n\tentries = /* @__PURE__ */ new Map();\n\tid(bucket, key) {\n\t\treturn `${bucket}\\x00${key}`;\n\t}\n\tasync put(bucket, key, bytes, opts = {}) {\n\t\tconst copy = bytes.slice();\n\t\tconst etag = etagOf(copy);\n\t\tthis.entries.set(this.id(bucket, key), {\n\t\t\tbytes: copy,\n\t\t\tetag,\n\t\t\tcontentType: opts.contentType ?? \"application/octet-stream\"\n\t\t});\n\t\treturn { etag };\n\t}\n\tasync get(bucket, key, opts = {}) {\n\t\tconst entry = this.entries.get(this.id(bucket, key));\n\t\tif (!entry) return null;\n\t\tconst size = entry.bytes.byteLength;\n\t\tif (opts.range) {\n\t\t\tconst start = opts.range.start;\n\t\t\tconst end = opts.range.end === void 0 ? size - 1 : Math.min(opts.range.end, size - 1);\n\t\t\treturn {\n\t\t\t\tbytes: start > end ? /* @__PURE__ */ new Uint8Array(0) : entry.bytes.slice(start, end + 1),\n\t\t\t\tetag: entry.etag,\n\t\t\t\tcontentType: entry.contentType,\n\t\t\t\tsize\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tbytes: entry.bytes.slice(),\n\t\t\tetag: entry.etag,\n\t\t\tcontentType: entry.contentType,\n\t\t\tsize\n\t\t};\n\t}\n\tasync head(bucket, key) {\n\t\tconst entry = this.entries.get(this.id(bucket, key));\n\t\tif (!entry) return null;\n\t\treturn {\n\t\t\tetag: entry.etag,\n\t\t\tsize: entry.bytes.byteLength,\n\t\t\tcontentType: entry.contentType\n\t\t};\n\t}\n\tasync delete(bucket, key) {\n\t\tthis.entries.delete(this.id(bucket, key));\n\t}\n\tasync list(bucket, opts = {}) {\n\t\tconst prefix = opts.prefix ?? \"\";\n\t\tconst maxKeys = opts.maxKeys ?? DEFAULT_MAX_KEYS;\n\t\tconst token = opts.continuationToken;\n\t\tconst prefixHit = `${bucket}\\x00${prefix}`;\n\t\tconst matching = [...this.entries.keys()].filter((id) => id.startsWith(prefixHit)).map((id) => id.slice(bucket.length + 1)).sort().filter((key) => token === void 0 ? true : key > token);\n\t\tconst page = matching.slice(0, maxKeys);\n\t\tconst isTruncated = matching.length > maxKeys;\n\t\tconst last = page.at(-1);\n\t\treturn {\n\t\t\tkeys: page,\n\t\t\tisTruncated,\n\t\t\t...isTruncated && last !== void 0 ? { nextContinuationToken: last } : {}\n\t\t};\n\t}\n};\n//#endregion\nexport { MemoryObjectStore, createS3Handler, fsStore, mintKeyPair, verifyRequest };\n\n//# sourceMappingURL=index.mjs.map","import { l as readOwnVersion, m as readJsonFile, p as StateFile, t as isValidSegment } from \"./segments-DRPHe3kK.mjs\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport * as http from \"node:http\";\nimport { createS3Handler, fsStore } from \"@internal/s3-protocol\";\n//#region src/buckets-main.ts\n/**\n* The bucket emulator daemon (local-dev spec § 2 `buckets-main.ts`): the S3\n* wire protocol (`@internal/s3-protocol`'s handler + `fsStore`) over\n* registered per-app, per-bucket directories, multi-tenant via physical\n* names `<app>--<name>`. Admin lives under `/_pcdev/` (the underscore can't\n* collide with a valid bucket name). Plain `node:http`.\n*\n* Runs as its own OS process, started by `daemon.ts`'s `ensureDaemon` via\n* `process.execPath <this file> --port <n> --state-dir <dir>`.\n*/\nconst STATE_MODE = 384;\nconst PHYSICAL_BUCKET_NAME_RE = /^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/;\nconst MULTIPART_MESSAGE = \"multipart upload is not supported by the local dev bucket emulator yet\";\nfunction isBucketRegistration(value) {\n\treturn typeof value === \"object\" && value !== null && \"app\" in value && typeof value.app === \"string\" && \"name\" in value && typeof value.name === \"string\" && \"dir\" in value && typeof value.dir === \"string\";\n}\nfunction isCredentialRecord(value) {\n\treturn typeof value === \"object\" && value !== null && \"app\" in value && typeof value.app === \"string\" && \"secretAccessKey\" in value && typeof value.secretAccessKey === \"string\";\n}\nfunction isBucketsState(value) {\n\treturn typeof value === \"object\" && value !== null && \"buckets\" in value && typeof value.buckets === \"object\" && value.buckets !== null && Object.values(value.buckets).every(isBucketRegistration) && \"credentials\" in value && typeof value.credentials === \"object\" && value.credentials !== null && Object.values(value.credentials).every(isCredentialRecord);\n}\nfunction isBucketBody(value) {\n\treturn typeof value === \"object\" && value !== null && \"dir\" in value && typeof value.dir === \"string\";\n}\nfunction isCredentialsBody(value) {\n\treturn typeof value === \"object\" && value !== null && \"accessKeyId\" in value && typeof value.accessKeyId === \"string\" && \"secretAccessKey\" in value && typeof value.secretAccessKey === \"string\";\n}\nfunction parseArgs(argv) {\n\tlet port;\n\tlet stateDir;\n\tfor (let i = 0; i < argv.length; i++) if (argv[i] === \"--port\") port = Number(argv[i + 1]);\n\telse if (argv[i] === \"--state-dir\") stateDir = argv[i + 1];\n\tif (port === void 0 || Number.isNaN(port)) throw new Error(\"buckets-main: --port <n> is required\");\n\tif (stateDir === void 0) throw new Error(\"buckets-main: --state-dir <dir> is required\");\n\treturn {\n\t\tport,\n\t\tstateDir\n\t};\n}\nfunction readBody(req) {\n\treturn new Promise((resolve, reject) => {\n\t\tconst chunks = [];\n\t\treq.on(\"data\", (chunk) => chunks.push(chunk));\n\t\treq.on(\"end\", () => resolve(Buffer.concat(chunks)));\n\t\treq.on(\"error\", reject);\n\t});\n}\nfunction toWebHeaders(nodeHeaders) {\n\tconst headers = new Headers();\n\tfor (const [key, value] of Object.entries(nodeHeaders)) {\n\t\tif (value === void 0) continue;\n\t\tif (Array.isArray(value)) for (const v of value) headers.append(key, v);\n\t\telse headers.set(key, value);\n\t}\n\treturn headers;\n}\nasync function sendWebResponse(res, webRes) {\n\tconst headers = {};\n\twebRes.headers.forEach((value, key) => {\n\t\theaders[key] = value;\n\t});\n\tconst buf = Buffer.from(await webRes.arrayBuffer());\n\tres.writeHead(webRes.status, headers);\n\tres.end(buf);\n}\nfunction main() {\n\tconst { port, stateDir } = parseArgs(process.argv.slice(2));\n\tconst ownVersion = readOwnVersion();\n\tconst stateJsonPath = path.join(stateDir, \"state.json\");\n\tconst stateFile = new StateFile(stateJsonPath, STATE_MODE);\n\tlet state = {\n\t\tbuckets: {},\n\t\tcredentials: {}\n\t};\n\tconst store = fsStore((physicalName) => state.buckets[physicalName]?.dir);\n\tfunction json(res, status, body) {\n\t\tres.writeHead(status, { \"content-type\": \"application/json\" });\n\t\tres.end(JSON.stringify(body));\n\t}\n\tfunction text(res, status, body) {\n\t\tres.writeHead(status, { \"content-type\": \"text/plain; charset=utf-8\" });\n\t\tres.end(body);\n\t}\n\tfunction badSegment(res, segment) {\n\t\ttext(res, 400, `invalid path segment \"${segment}\": must match /^[a-z0-9][a-z0-9-]*$/ and be at most 63 characters`);\n\t}\n\tasync function handlePutBucket(req, res, app, name) {\n\t\tconst physicalName = `${app}--${name}`;\n\t\tif (!PHYSICAL_BUCKET_NAME_RE.test(physicalName)) return text(res, 400, `invalid bucket \"${physicalName}\" (app \"${app}\", name \"${name}\"): the physical bucket name must match /^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/ and be at most 63 characters`);\n\t\tconst raw = await readBody(req);\n\t\tlet parsed;\n\t\ttry {\n\t\t\tparsed = JSON.parse(raw.toString(\"utf8\"));\n\t\t} catch {\n\t\t\treturn text(res, 400, \"malformed JSON body\");\n\t\t}\n\t\tif (!isBucketBody(parsed)) return text(res, 400, \"malformed bucket body: expected { \\\"dir\\\": string }\");\n\t\tawait fs.promises.mkdir(parsed.dir, { recursive: true });\n\t\tstate.buckets[physicalName] = {\n\t\t\tapp,\n\t\t\tname,\n\t\t\tdir: parsed.dir\n\t\t};\n\t\tawait stateFile.write(state);\n\t\tres.writeHead(204);\n\t\tres.end();\n\t}\n\tasync function handlePutCredentials(req, res, app) {\n\t\tconst raw = await readBody(req);\n\t\tlet parsed;\n\t\ttry {\n\t\t\tparsed = JSON.parse(raw.toString(\"utf8\"));\n\t\t} catch {\n\t\t\treturn text(res, 400, \"malformed JSON body\");\n\t\t}\n\t\tif (!isCredentialsBody(parsed)) return text(res, 400, \"malformed credentials body: expected { \\\"accessKeyId\\\", \\\"secretAccessKey\\\" }\");\n\t\tconst existing = state.credentials[parsed.accessKeyId];\n\t\tif (existing && existing.app !== app) return text(res, 409, `accessKeyId \"${parsed.accessKeyId}\" is already registered by a different app`);\n\t\tstate.credentials[parsed.accessKeyId] = {\n\t\t\tapp,\n\t\t\tsecretAccessKey: parsed.secretAccessKey\n\t\t};\n\t\tawait stateFile.write(state);\n\t\tres.writeHead(204);\n\t\tres.end();\n\t}\n\tasync function handleDeleteApp(res, app) {\n\t\tfor (const [key, reg] of Object.entries(state.buckets)) if (reg.app === app) delete state.buckets[key];\n\t\tfor (const [key, cred] of Object.entries(state.credentials)) if (cred.app === app) delete state.credentials[key];\n\t\tawait stateFile.write(state);\n\t\tres.writeHead(204);\n\t\tres.end();\n\t}\n\t/** Path-style addressing: the bucket is the first non-empty path segment. Mirrors the handler's own `parseTarget`, which isn't exported. */\n\tfunction bucketFromPath(pathname) {\n\t\tconst first = pathname.split(\"/\").find((s) => s.length > 0);\n\t\treturn first !== void 0 ? decodeURIComponent(first) : void 0;\n\t}\n\t/**\n\t* Credentials accepted for THIS request's target bucket only — its\n\t* owning app, derived from the bucket's registration (the authoritative\n\t* source for the `<app>--<name>` split; unregistered apps/names may\n\t* themselves contain `--`, so the registration is trusted over re-parsing\n\t* the string). An unknown bucket or an app with no registered credentials\n\t* yields no candidates, which still resolves through the real 403 path\n\t* below — never a bespoke \"unknown bucket\" shortcut that would reveal\n\t* anything.\n\t*/\n\tfunction credentialsForBucket(bucket) {\n\t\tconst owningApp = bucket !== void 0 ? state.buckets[bucket]?.app : void 0;\n\t\tif (owningApp === void 0) return [];\n\t\treturn Object.entries(state.credentials).filter(([, rec]) => rec.app === owningApp).map(([accessKeyId, rec]) => ({\n\t\t\taccessKeyId,\n\t\t\tsecretAccessKey: rec.secretAccessKey\n\t\t}));\n\t}\n\tasync function handleS3Wire(req, res, url) {\n\t\tif (url.searchParams.has(\"uploads\") || url.searchParams.has(\"uploadId\") || url.searchParams.has(\"partNumber\")) return text(res, 501, MULTIPART_MESSAGE);\n\t\tconst method = req.method ?? \"GET\";\n\t\tconst bodyBuf = method !== \"GET\" && method !== \"HEAD\" ? await readBody(req) : void 0;\n\t\tconst fullUrl = `http://${req.headers.host ?? `127.0.0.1:${String(port)}`}${req.url ?? \"/\"}`;\n\t\tconst headers = toWebHeaders(req.headers);\n\t\tconst candidates = credentialsForBucket(bucketFromPath(url.pathname));\n\t\tif (candidates.length === 0) candidates.push({\n\t\t\taccessKeyId: \"\",\n\t\t\tsecretAccessKey: \"\"\n\t\t});\n\t\tlet last;\n\t\tfor (const credentials of candidates) {\n\t\t\tconst webReq = new Request(fullUrl, {\n\t\t\t\tmethod,\n\t\t\t\theaders,\n\t\t\t\t...bodyBuf && bodyBuf.length > 0 ? { body: bodyBuf } : {}\n\t\t\t});\n\t\t\tconst webRes = await createS3Handler({\n\t\t\t\tstore,\n\t\t\t\tcredentials\n\t\t\t})(webReq);\n\t\t\tif (webRes.status !== 403) return sendWebResponse(res, webRes);\n\t\t\tlast = webRes;\n\t\t}\n\t\tif (last) await sendWebResponse(res, last);\n\t}\n\tasync function handleRequest(req, res) {\n\t\tconst url = new URL(req.url ?? \"/\", `http://127.0.0.1:${String(port)}`);\n\t\tconst method = req.method ?? \"GET\";\n\t\tif (method === \"GET\" && url.pathname === \"/health\") return json(res, 200, { version: ownVersion });\n\t\tif (url.pathname === \"/_pcdev/health\" || url.pathname.startsWith(\"/_pcdev/\")) {\n\t\t\tconst segments = url.pathname.split(\"/\").filter((s) => s.length > 0).map((s) => decodeURIComponent(s));\n\t\t\tif (method === \"GET\" && segments.length === 2 && segments[1] === \"health\") return json(res, 200, { version: ownVersion });\n\t\t\tif (segments[1] === \"apps\" && segments.length >= 3) {\n\t\t\t\tconst app = segments[2];\n\t\t\t\tif (app === void 0 || !isValidSegment(app)) return badSegment(res, app ?? \"\");\n\t\t\t\tif (method === \"PUT\" && segments.length === 5 && segments[3] === \"buckets\") {\n\t\t\t\t\tconst name = segments[4];\n\t\t\t\t\tif (name === void 0 || !isValidSegment(name)) return badSegment(res, name ?? \"\");\n\t\t\t\t\treturn handlePutBucket(req, res, app, name);\n\t\t\t\t}\n\t\t\t\tif (method === \"PUT\" && segments.length === 4 && segments[3] === \"credentials\") return handlePutCredentials(req, res, app);\n\t\t\t\tif (method === \"DELETE\" && segments.length === 3) return handleDeleteApp(res, app);\n\t\t\t}\n\t\t\tres.writeHead(404);\n\t\t\tres.end();\n\t\t\treturn;\n\t\t}\n\t\treturn handleS3Wire(req, res, url);\n\t}\n\tconst server = http.createServer((req, res) => {\n\t\thandleRequest(req, res).catch((err) => {\n\t\t\tif (!res.headersSent) res.writeHead(500, { \"content-type\": \"text/plain\" });\n\t\t\tres.end(err instanceof Error ? err.message : String(err));\n\t\t});\n\t});\n\tasync function shutdown() {\n\t\tawait stateFile.flush();\n\t\tserver.close();\n\t\tprocess.exit(0);\n\t}\n\tprocess.on(\"SIGTERM\", () => void shutdown());\n\tprocess.on(\"SIGINT\", () => void shutdown());\n\treadJsonFile(stateJsonPath, isBucketsState).then((loaded) => {\n\t\tif (loaded) state = loaded;\n\t\tserver.listen(port, \"127.0.0.1\", () => {\n\t\t\tconsole.log(`[dev-emulators] buckets-main listening on 127.0.0.1:${String(port)}`);\n\t\t});\n\t}).catch((err) => {\n\t\tconsole.error(\"buckets-main: failed to load state\", err);\n\t\tprocess.exit(1);\n\t});\n}\nmain();\n//#endregion\nexport {};\n\n//# sourceMappingURL=buckets-main.mjs.map"],"mappings":";;;;;;;AAGA,MAAM,yBAAyB;AAC/B,MAAM,eAAe;AACrB,MAAM,gBAAgB;AACtB,MAAM,oCAAoC,IAAI,IAAI,CAAC,cAAc,aAAa,CAAC;AAC/E,MAAM,iBAAiB;AACvB,SAAS,SAAS,OAAO;CACxB,OAAO,IAAI,WAAW,QAAQ,CAAC,CAAC,OAAO,KAA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//#region ../../0-framework/0-foundation/foundation/dist/casts-DpaahrlC.mjs
|
|
159
|
+
/**
|
|
160
|
+
* **Last-resort escape hatch for unsafe type assertions. Not a sanctioned tool to reach for.**
|
|
161
|
+
*
|
|
162
|
+
* Before reaching for `blindCast`, **rewrite the surrounding code so the cast becomes
|
|
163
|
+
* unnecessary**: tighten an input type, add a runtime check that narrows via a type
|
|
164
|
+
* predicate, restructure a generic so the compiler can see the relationship you're
|
|
165
|
+
* asserting, or use {@link castAs} when the value already satisfies the target type.
|
|
166
|
+
* Only when no rewrite is feasible does `blindCast` become the right answer — and at
|
|
167
|
+
* that point, the `Reason` literal you supply must articulate the compromise in
|
|
168
|
+
* language a reviewer can evaluate.
|
|
169
|
+
*
|
|
170
|
+
* The reviewer **will** validate the `Reason`. If it doesn't hold up under scrutiny,
|
|
171
|
+
* that is not a signal to soften the reason; it is a signal to go back and solve the
|
|
172
|
+
* underlying type-system problem properly. An unconvincing justification is rework,
|
|
173
|
+
* not a free pass.
|
|
174
|
+
*
|
|
175
|
+
* `blindCast` is the auditable form of `as Foo` / `as unknown as Foo`: it bypasses
|
|
176
|
+
* the compiler's checks (the input type is `unknown`, the output type is whatever the
|
|
177
|
+
* caller asks for), but it forces the unsafety to be named at the call site instead of
|
|
178
|
+
* smuggled in via a bare `as`. The `Reason` type parameter exists only at compile
|
|
179
|
+
* time — it is not present in the emitted JavaScript — but it is grep-able and
|
|
180
|
+
* visible to future readers.
|
|
181
|
+
*
|
|
182
|
+
* @example
|
|
183
|
+
* ```typescript
|
|
184
|
+
* const stringValue = blindCast<
|
|
185
|
+
* string,
|
|
186
|
+
* "JSON.parse returns `unknown`; this field is documented to be a string in the API contract"
|
|
187
|
+
* >(parsed[key]);
|
|
188
|
+
* ```
|
|
189
|
+
*
|
|
190
|
+
* @typeParam TargetType - The type the caller is asserting the input has.
|
|
191
|
+
* @typeParam _Reason - A string literal describing why bypassing the type system is necessary here.
|
|
192
|
+
* Only meaningful at compile time. The reviewer evaluates whether it justifies the unsafety.
|
|
193
|
+
*/
|
|
194
|
+
function blindCast$1(input) {
|
|
195
|
+
return input;
|
|
196
|
+
}
|
|
197
|
+
//#endregion
|
|
198
|
+
export { isEnvParamSource as a, paramBindingFor as c, serviceOrigin as d, generatedParam as i, paramName as l, envParam as n, isGeneratedParamSource as o, envSecret as r, isOriginParamSource as s, blindCast$1 as t, secretName as u };
|
|
159
199
|
|
|
160
|
-
//# sourceMappingURL=
|
|
200
|
+
//# sourceMappingURL=casts-DpaahrlC-Ykus3kCE.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"casts-DpaahrlC-Ykus3kCE.mjs","names":["blindCast"],"sources":["../../../1-prisma-cloud/1-extensions/target/dist/secret-C__qAfZr.mjs","../../../0-framework/0-foundation/foundation/dist/casts-DpaahrlC.mjs"],"sourcesContent":["import { isParamSource, paramSource, secretSource } from \"@internal/core\";\nimport { blindCast } from \"@internal/foundation/casts\";\n//#region src/param.ts\n/**\n* Brands the payload `envParam` builds. Core's `paramSource()` is a public\n* SPI, so a user could bypass `envParam` and bind a raw `paramSource('x')`;\n* the brand lets `paramName` reject such a source (or another target's) with\n* a clear error instead of reading an absent `.name`.\n*/\nconst PRISMA_CLOUD_PARAM_SOURCE = blindCast(Symbol.for(\"prisma:prisma-cloud-param-source\"));\nconst RESERVED_PARAM_PREFIX = \"COMPOSER_\";\n/** The names Prisma Cloud owns: it seeds and manages them, so Composer never binds one. */\nconst PLATFORM_OWNED_PARAM_NAMES = /* @__PURE__ */ new Set([\"DATABASE_URL\", \"DATABASE_URL_POOLED\"]);\n/**\n* Binds a param slot to a named Prisma Cloud platform env var — the non-secret\n* sibling of `envSecret` (spec: env-sourced config params). The platform\n* injects the value into the running instance per stage; the param's own\n* schema validates it at boot, unredacted. The name may not use the\n* framework's reserved `COMPOSER_` prefix or the platform-owned\n* `DATABASE_URL(_POOLED)` keys — same parity as `envSecret`.\n*/\nfunction envParam(name) {\n\tif (typeof name !== \"string\" || name.length === 0) throw new Error(\"envParam() requires a non-empty platform env-var name, e.g. envParam('APP_ORIGIN').\");\n\tif (name.startsWith(RESERVED_PARAM_PREFIX)) throw new Error(`envParam name \"${name}\" may not start with \"${RESERVED_PARAM_PREFIX}\" — that prefix is reserved for the framework's own generated config keys.`);\n\tif (PLATFORM_OWNED_PARAM_NAMES.has(name)) throw new Error(`envParam name \"${name}\" is reserved — ${[...PLATFORM_OWNED_PARAM_NAMES].join(\" and \")} are seeded and managed by Prisma Cloud itself, so the framework refuses to bind them. Declare the database your service uses and read its url from that connection.`);\n\treturn paramSource({\n\t\t[PRISMA_CLOUD_PARAM_SOURCE]: true,\n\t\tname\n\t});\n}\n/** True only for a payload that `envParam` built — i.e. one carrying the brand. */\nfunction isEnvParamPayload(payload) {\n\treturn typeof payload === \"object\" && payload !== null && blindCast(payload)[PRISMA_CLOUD_PARAM_SOURCE] === true;\n}\n/** True iff a resolved param value is an env-sourced pointer this target built (as opposed to a literal, or a foreign/raw `ParamSource`). */\nfunction isEnvParamSource(value) {\n\treturn isParamSource(value) && isEnvParamPayload(value.payload);\n}\n/**\n* Brands the payload `generatedParam` builds — a distinct brand from\n* `envParam`'s, so `isGeneratedParamSource` and `isEnvParamSource` are mutually\n* exclusive even though both are `ParamSource`s.\n*/\nconst PRISMA_CLOUD_GENERATED_PARAM_SOURCE = blindCast(Symbol.for(\"prisma:prisma-cloud-generated-param-source\"));\nconst GENERATED_PARAM_DEFAULT_BYTES = 32;\nconst GENERATED_PARAM_MIN_BYTES = 16;\nconst GENERATED_PARAM_MAX_BYTES = 1024;\n/**\n* Binds an input leaf to a value the target GENERATES at deploy — the sibling\n* of `envParam` whose value comes from deploy-time generation instead of the\n* environment. The generated value is produced once and persisted in deploy\n* state, so it is stable across redeploys (rotation is destroy/recreate). It is\n* config, not a secret; `redacted` is an orthogonal facet (default `true`).\n* `bytes` must be an integer between 16 and 1024 (default 32).\n*/\nfunction generatedParam(opts = {}) {\n\tconst bytes = opts.bytes ?? GENERATED_PARAM_DEFAULT_BYTES;\n\tconst redacted = opts.redacted ?? true;\n\tif (!Number.isInteger(bytes) || bytes < GENERATED_PARAM_MIN_BYTES || bytes > GENERATED_PARAM_MAX_BYTES) throw new Error(`generatedParam() bytes must be an integer between ${GENERATED_PARAM_MIN_BYTES} and ${GENERATED_PARAM_MAX_BYTES} (got ${String(bytes)}).`);\n\treturn paramSource({\n\t\t[PRISMA_CLOUD_GENERATED_PARAM_SOURCE]: true,\n\t\tbytes,\n\t\tredacted\n\t});\n}\n/** True only for a payload that `generatedParam` built — i.e. one carrying the brand. */\nfunction isGeneratedParamPayload(payload) {\n\treturn typeof payload === \"object\" && payload !== null && blindCast(payload)[PRISMA_CLOUD_GENERATED_PARAM_SOURCE] === true;\n}\n/** True iff a resolved value is a generated-param source this target built (as opposed to a literal, an `envParam` source, or a foreign/raw `ParamSource`). */\nfunction isGeneratedParamSource(value) {\n\treturn isParamSource(value) && isGeneratedParamPayload(value.payload);\n}\nconst PRISMA_CLOUD_ORIGIN_PARAM_SOURCE = Symbol.for(\"prisma:prisma-cloud-origin-param-source\");\n/**\n* Binds an input leaf to another service's public origin on the stage being deployed,\n* e.g. `auth()`'s `baseUrl: serviceOrigin('web')`. `address` is the target's provision id.\n*/\nfunction serviceOrigin(address) {\n\tif (typeof address !== \"string\" || address.length === 0) throw new Error(\"serviceOrigin() requires the target service's deployment address, e.g. serviceOrigin('web').\");\n\treturn paramSource({\n\t\t[PRISMA_CLOUD_ORIGIN_PARAM_SOURCE]: true,\n\t\taddress\n\t});\n}\n/** True iff `value` was built by `serviceOrigin`. */\nfunction isOriginParamSource(value) {\n\treturn isParamSource(value) && typeof value.payload === \"object\" && value.payload !== null && PRISMA_CLOUD_ORIGIN_PARAM_SOURCE in value.payload && value.payload[PRISMA_CLOUD_ORIGIN_PARAM_SOURCE] === true;\n}\n/**\n* Reads the Prisma Cloud env-var name back out of a param binding's opaque\n* source. A source not built by `envParam` (a raw `paramSource(...)` or\n* another target's source) carries no name — reject it here. `paramName` runs\n* in preflight and at serialize before any value ever crosses the wire, so a\n* foreign source fails early and clearly rather than producing a broken\n* deploy with an undefined name.\n*/\nfunction paramName(binding) {\n\tconst { binding: bound } = binding;\n\tif (!isEnvParamSource(bound)) throw new Error(`param slot \"${binding.slot}\" of service \"${binding.serviceAddress}\" is bound to a source not created by envParam() — bind env-sourced params with envParam('NAME') from @prisma/composer-prisma-cloud.`);\n\treturn bound.payload.name;\n}\n/**\n* Finds the manifest entry for one service param slot. `serialize` calls this\n* only after confirming `buildConfig` resolved the slot to a `ParamSource`\n* (`isParamSource(value)`), so a miss here means `graph.params` and the\n* resolved `Config` have drifted — a Load invariant violation, surfaced\n* loudly rather than producing a pointer row with an undefined name.\n*/\nfunction paramBindingFor(bindings, serviceAddress, slot) {\n\tconst binding = bindings.find((b) => b.serviceAddress === serviceAddress && b.slot === slot);\n\tif (binding === void 0) throw new Error(`param slot \"${slot}\" of \"${serviceAddress}\" resolved to a source but has no bound entry in the manifest — Load should have recorded it.`);\n\treturn binding;\n}\n//#endregion\n//#region src/secret.ts\n/**\n* Brands the payload `envSecret` builds. Core's `secretSource()` is a public\n* SPI, so a user could bypass `envSecret` and bind a raw `secretSource('x')`;\n* the brand lets `secretName` reject such a source (or another target's) with a\n* clear error instead of reading an absent `.name`.\n*/\nconst PRISMA_CLOUD_SECRET_SOURCE = blindCast(Symbol.for(\"prisma:prisma-cloud-secret-source\"));\nconst RESERVED_SECRET_PREFIX = \"COMPOSER_\";\n/** The names Prisma Cloud owns: it seeds and manages them, so Composer never binds one. */\nconst PLATFORM_OWNED_SECRET_NAMES = /* @__PURE__ */ new Set([\"DATABASE_URL\", \"DATABASE_URL_POOLED\"]);\n/**\n* Binds a secret slot to a named Prisma Cloud platform env var (ADR-0029). The\n* value is provisioned out-of-band; only the name is carried. The name may not\n* use the framework's reserved `COMPOSER_` prefix or the platform-owned\n* `DATABASE_URL(_POOLED)` keys.\n*/\nfunction envSecret(name) {\n\tif (typeof name !== \"string\" || name.length === 0) throw new Error(\"envSecret() requires a non-empty platform env-var name, e.g. envSecret('STRIPE_SECRET_KEY').\");\n\tif (name.startsWith(RESERVED_SECRET_PREFIX)) throw new Error(`envSecret name \"${name}\" may not start with \"${RESERVED_SECRET_PREFIX}\" — that prefix is reserved for the framework's own generated config keys.`);\n\tif (PLATFORM_OWNED_SECRET_NAMES.has(name)) throw new Error(`envSecret name \"${name}\" is reserved — ${[...PLATFORM_OWNED_SECRET_NAMES].join(\" and \")} are seeded and managed by Prisma Cloud itself, so the framework refuses to bind them. Declare the database your service uses and read its url from that connection.`);\n\treturn secretSource({\n\t\t[PRISMA_CLOUD_SECRET_SOURCE]: true,\n\t\tname\n\t});\n}\n/** True only for a payload that `envSecret` built — i.e. one carrying the brand. */\nfunction isEnvSecretPayload(payload) {\n\treturn typeof payload === \"object\" && payload !== null && blindCast(payload)[PRISMA_CLOUD_SECRET_SOURCE] === true;\n}\n/**\n* Reads the Prisma Cloud env-var name back out of an opaque secret source —\n* an `envSecret` leaf of an input binding (ADR-0042). A source not built by\n* `envSecret` (a raw `secretSource(...)` or another target's source) carries\n* no name — reject it here, with `where` naming the leaf's position, so a\n* foreign source fails early and clearly rather than producing a broken\n* deploy with an undefined name.\n*/\nfunction secretName(source, where) {\n\tconst payload = source.payload;\n\tif (!isEnvSecretPayload(payload)) throw new Error(`${where} is bound to a secret source not created by envSecret() — bind secrets with envSecret('NAME') from @prisma/composer-prisma-cloud.`);\n\treturn payload.name;\n}\n//#endregion\nexport { isEnvParamSource as a, paramBindingFor as c, generatedParam as i, paramName as l, secretName as n, isGeneratedParamSource as o, envParam as r, isOriginParamSource as s, envSecret as t, serviceOrigin as u };\n\n//# sourceMappingURL=secret-C__qAfZr.mjs.map","//#region src/casts.ts\n/**\n* **Last-resort escape hatch for unsafe type assertions. Not a sanctioned tool to reach for.**\n*\n* Before reaching for `blindCast`, **rewrite the surrounding code so the cast becomes\n* unnecessary**: tighten an input type, add a runtime check that narrows via a type\n* predicate, restructure a generic so the compiler can see the relationship you're\n* asserting, or use {@link castAs} when the value already satisfies the target type.\n* Only when no rewrite is feasible does `blindCast` become the right answer — and at\n* that point, the `Reason` literal you supply must articulate the compromise in\n* language a reviewer can evaluate.\n*\n* The reviewer **will** validate the `Reason`. If it doesn't hold up under scrutiny,\n* that is not a signal to soften the reason; it is a signal to go back and solve the\n* underlying type-system problem properly. An unconvincing justification is rework,\n* not a free pass.\n*\n* `blindCast` is the auditable form of `as Foo` / `as unknown as Foo`: it bypasses\n* the compiler's checks (the input type is `unknown`, the output type is whatever the\n* caller asks for), but it forces the unsafety to be named at the call site instead of\n* smuggled in via a bare `as`. The `Reason` type parameter exists only at compile\n* time — it is not present in the emitted JavaScript — but it is grep-able and\n* visible to future readers.\n*\n* @example\n* ```typescript\n* const stringValue = blindCast<\n* string,\n* \"JSON.parse returns `unknown`; this field is documented to be a string in the API contract\"\n* >(parsed[key]);\n* ```\n*\n* @typeParam TargetType - The type the caller is asserting the input has.\n* @typeParam _Reason - A string literal describing why bypassing the type system is necessary here.\n* Only meaningful at compile time. The reviewer evaluates whether it justifies the unsafety.\n*/\nfunction blindCast(input) {\n\treturn input;\n}\n/**\n* Type-checked, runtime pass-through alternative to a bare `as Type` cast.\n*\n* Use `castAs` when the value already satisfies the target type but you want to make\n* the type assertion explicit at the call site — for example, when an inferred type is\n* wider than the type you want to publish, or when a literal object should be tagged\n* with its nominal interface. Unlike {@link blindCast}, the compiler still checks that\n* the value is assignable to the target type, so this helper cannot smuggle in an\n* unsafe assertion.\n*\n* `castAs` exists alongside `blindCast` so authors pick the right name at the call\n* site: a `castAs` is type-checked and benign; a `blindCast` is the unsafe escape\n* hatch. The split makes review faster — readers know which casts to scrutinize and\n* which are pure annotations.\n*\n* @example\n* ```typescript\n* interface FancyObject {\n* key: string;\n* keyTwo: {\n* subKey: string;\n* subKeyTwo: number;\n* };\n* }\n*\n* const typedObject = castAs<FancyObject>({\n* key: 'Chookede',\n* keyTwo: {\n* subKey: 'Choookeeeee',\n* subKeyTwo: 2,\n* },\n* });\n* ```\n*\n* @typeParam Type - The type to constrain and tag the value with. The value must be assignable to `Type`.\n*/\nfunction castAs(value) {\n\treturn value;\n}\n//#endregion\nexport { castAs as n, blindCast as t };\n\n//# sourceMappingURL=casts-DpaahrlC.mjs.map"],"mappings":";;;;;;;;;AASA,MAAM,4BAA4B,UAAU,OAAO,IAAI,kCAAkC,CAAC;AAC1F,MAAM,wBAAwB;;AAE9B,MAAM,6CAA6C,IAAI,IAAI,CAAC,gBAAgB,qBAAqB,CAAC;;;;;;;;;AASlG,SAAS,SAAS,MAAM;CACvB,IAAI,OAAO,SAAS,YAAY,KAAK,WAAW,GAAG,MAAM,IAAI,MAAM,qFAAqF;CACxJ,IAAI,KAAK,WAAW,qBAAqB,GAAG,MAAM,IAAI,MAAM,kBAAkB,KAAK,wBAAwB,sBAAsB,2EAA2E;CAC5M,IAAI,2BAA2B,IAAI,IAAI,GAAG,MAAM,IAAI,MAAM,kBAAkB,KAAK,kBAAkB,CAAC,GAAG,0BAA0B,CAAC,CAAC,KAAK,OAAO,EAAE,qKAAqK;CACtT,OAAO,YAAY;GACjB,4BAA4B;EAC7B;CACD,CAAC;AACF;;AAEA,SAAS,kBAAkB,SAAS;CACnC,OAAO,OAAO,YAAY,YAAY,YAAY,QAAQ,UAAU,OAAO,CAAC,CAAC,+BAA+B;AAC7G;;AAEA,SAAS,iBAAiB,OAAO;CAChC,OAAO,cAAc,KAAK,KAAK,kBAAkB,MAAM,OAAO;AAC/D;;;;;;AAMA,MAAM,sCAAsC,UAAU,OAAO,IAAI,4CAA4C,CAAC;AAC9G,MAAM,gCAAgC;AACtC,MAAM,4BAA4B;AAClC,MAAM,4BAA4B;;;;;;;;;AASlC,SAAS,eAAe,OAAO,CAAC,GAAG;CAClC,MAAM,QAAQ,KAAK,SAAS;CAC5B,MAAM,WAAW,KAAK,YAAY;CAClC,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,6BAA6B,QAAQ,2BA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,CAAC,gBAAgB,qBAAqB,CAAC;;;;;;;AAOnG,SAAS,UAAU,MAAM;CACxB,IAAI,OAAO,SAAS,YAAY,KAAK,WAAW,GAAG,MAAM,IAAI,MAAM,8FAA8F;CACjK,IAAI,KAAK,WAAW,sBAAsB,GAAG,MAAM,IAAI,MAAM,mBAAmB,KAAK,wBAAwB,uBAAuB,2EAA2E;CAC/M,IAAI,4BAA4B,IAAI,IAAI,GAAG,MAAM,IAAI,MAAM,mBAAmB,KAAK,kBAAkB,CAAC,GAAG,2BAA2B,CAAC,CAAC,KAAK,OAAO,EAAE,qKAAqK;CACzT,OAAO,aAAa;GAClB,6BAA6B;EAC9B;CACD,CAAC;AACF;;AAEA,SAAS,mBAAmB,SAAS;CACpC,OAAO,OAAO,YAAY,YAAY,YAAY,QAAQ,UAAU,OAAO,CAAC,CAAC,gCAAgC;AAC9G;;;;;;;;;AASA,SAAS,WAAW,QAAQ,OAAO;CAClC,MAAM,UAAU,OAAO;CACvB,IAAI,CAAC,mBAAmB,OAAO,GAAG,MAAM,IAAI,MAAM,GAAG,MAAM,kIAAkI;CAC7L,OAAO,QAAQ;AAChB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACzHA,SAASA,YAAU,OAAO;CACzB,OAAO;AACR"}
|
package/dist/compute-main.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as readOwnVersion, i as readJsonFile, r as isValidSegment, t as StateFile } from "./segments-
|
|
1
|
+
import { a as readOwnVersion, i as readJsonFile, r as isValidSegment, t as StateFile } from "./segments-DRPHe3kK-BNgikNpo.mjs";
|
|
2
2
|
import { n as portNumbers, t as getPorts } from "./get-port-BYnpbW5H.mjs";
|
|
3
3
|
import * as fs from "node:fs";
|
|
4
4
|
import { spawn } from "node:child_process";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compute-main.mjs","names":["getPort"],"sources":["../../../1-prisma-cloud/0-lowering/dev-emulators/dist/compute-main.mjs"],"sourcesContent":["import { c as readOwnVersion, f as StateFile, p as readJsonFile, t as isValidSegment } from \"./segments-D-anjQ84.mjs\";\nimport * as fs from \"node:fs\";\nimport { spawn } from \"node:child_process\";\nimport * as path from \"node:path\";\nimport getPort, { portNumbers } from \"get-port\";\nimport * as http from \"node:http\";\n//#region src/compute-main.ts\n/**\n* The Compute emulator daemon (local-dev spec § 2 `compute-main.ts`): a small\n* local counterpart of the platform's compute service. Owns service child\n* processes (spawned `bun bootstrap.js` from a real packaged artifact),\n* supervises them (crash backoff, held after repeated fast crashes), and\n* serves a loopback JSON admin API plus per-service log streaming.\n*\n* Runs as its own OS process, started by `daemon.ts`'s `ensureDaemon` via\n* `process.execPath <this file> --port <n> --state-dir <dir>`. Everything it\n* needs travels on argv and each request's own body — it reads no\n* environment variable of its own.\n*/\nconst MIN_SERVICE_PORT = 3e3;\nconst MAX_SERVICE_PORT = 65535;\nconst TERMINATE_GRACE_MS = 5e3;\nconst STABLE_UPTIME_MS = 3e4;\nconst BASE_BACKOFF_MS = 1e3;\nconst MAX_BACKOFF_MS = 3e4;\nconst MAX_CONSECUTIVE_FAST_EXITS = 5;\nconst LOG_POLL_INTERVAL_MS = 100;\nconst APPS_STATE_MODE = 384;\nconst BUN_NOT_FOUND_MESSAGE = \"local dev runs services under bun — the Prisma Compute runtime — and `bun` was not found on PATH. Install it: https://bun.sh.\";\nfunction isServiceStatus(value) {\n\treturn value === \"running\" || value === \"backoff\" || value === \"held\" || value === \"stopped\";\n}\nfunction isStringRecord(value) {\n\treturn typeof value === \"object\" && value !== null && Object.values(value).every((v) => typeof v === \"string\");\n}\nfunction isServiceRecord(value) {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tif (!(\"id\" in value) || typeof value.id !== \"string\") return false;\n\tif (!(\"address\" in value) || typeof value.address !== \"string\") return false;\n\tif (!(\"port\" in value) || typeof value.port !== \"number\") return false;\n\tif (!(\"status\" in value) || !isServiceStatus(value.status)) return false;\n\tif (!(\"logPath\" in value) || typeof value.logPath !== \"string\") return false;\n\tif (\"pid\" in value && value.pid !== void 0 && typeof value.pid !== \"number\") return false;\n\tif (\"lastExitCode\" in value && value.lastExitCode !== void 0 && typeof value.lastExitCode !== \"number\") return false;\n\tif (\"artifactHash\" in value && value.artifactHash !== void 0 && typeof value.artifactHash !== \"string\") return false;\n\tif (\"artifactDir\" in value && value.artifactDir !== void 0 && typeof value.artifactDir !== \"string\") return false;\n\tif (\"env\" in value && value.env !== void 0 && !isStringRecord(value.env)) return false;\n\treturn true;\n}\nfunction isAppRecord(value) {\n\treturn typeof value === \"object\" && value !== null && \"services\" in value && typeof value.services === \"object\" && value.services !== null && Object.values(value.services).every(isServiceRecord);\n}\nfunction isAppsState(value) {\n\treturn typeof value === \"object\" && value !== null && Object.values(value).every(isAppRecord);\n}\nfunction isDeploymentBody(value) {\n\treturn typeof value === \"object\" && value !== null && \"address\" in value && typeof value.address === \"string\" && \"artifactDir\" in value && typeof value.artifactDir === \"string\" && \"artifactHash\" in value && typeof value.artifactHash === \"string\" && \"env\" in value && isStringRecord(value.env) && \"port\" in value && typeof value.port === \"number\";\n}\nfunction sleep(ms) {\n\treturn new Promise((resolve) => setTimeout(resolve, ms));\n}\n/** Append-only per-service log file — child stdout/stderr plus `[emulator]` supervision lines. No rotation in v1. */\nvar ServiceLog = class {\n\tfilePath;\n\tfd;\n\tconstructor(filePath) {\n\t\tthis.filePath = filePath;\n\t}\n\tensureOpen() {\n\t\tif (this.fd === void 0) {\n\t\t\tfs.mkdirSync(path.dirname(this.filePath), { recursive: true });\n\t\t\tthis.fd = fs.openSync(this.filePath, \"a\");\n\t\t}\n\t\treturn this.fd;\n\t}\n\twriteRaw(chunk) {\n\t\tfs.writeSync(this.ensureOpen(), chunk);\n\t}\n\twriteLine(line) {\n\t\tfs.writeSync(this.ensureOpen(), `${line}\\n`);\n\t}\n\t/** Empties the file — a fresh service start begins a clean log; past sessions' and past deployments' output is not kept. */\n\tclear() {\n\t\tfs.ftruncateSync(this.ensureOpen(), 0);\n\t}\n\t/** Closes the fd if one was ever opened. Idempotent. */\n\tclose() {\n\t\tif (this.fd === void 0) return;\n\t\tfs.closeSync(this.fd);\n\t\tthis.fd = void 0;\n\t}\n};\nfunction parseArgs(argv) {\n\tlet port;\n\tlet stateDir;\n\tfor (let i = 0; i < argv.length; i++) if (argv[i] === \"--port\") port = Number(argv[i + 1]);\n\telse if (argv[i] === \"--state-dir\") stateDir = argv[i + 1];\n\tif (port === void 0 || Number.isNaN(port)) throw new Error(\"compute-main: --port <n> is required\");\n\tif (stateDir === void 0) throw new Error(\"compute-main: --state-dir <dir> is required\");\n\treturn {\n\t\tport,\n\t\tstateDir\n\t};\n}\n/** Resolves `bun` from THIS request's env PATH — never the daemon's own. POSIX-only (Windows is out of scope). */\nfunction resolveBunOnPath(env) {\n\tconst pathVar = env[\"PATH\"];\n\tif (!pathVar) return void 0;\n\tfor (const dir of pathVar.split(path.delimiter)) {\n\t\tif (dir === \"\") continue;\n\t\tconst candidate = path.join(dir, \"bun\");\n\t\ttry {\n\t\t\tfs.accessSync(candidate, fs.constants.X_OK);\n\t\t\treturn candidate;\n\t\t} catch {}\n\t}\n}\nfunction main() {\n\tconst { port, stateDir } = parseArgs(process.argv.slice(2));\n\tconst ownVersion = readOwnVersion();\n\tconst appsJsonPath = path.join(stateDir, \"apps.json\");\n\tconst stateFile = new StateFile(appsJsonPath, APPS_STATE_MODE);\n\tlet state = {};\n\tconst runtimes = /* @__PURE__ */ new Map();\n\tconst logGeneration = /* @__PURE__ */ new Map();\n\tfunction runtimeKey(app, id) {\n\t\treturn `${app}/${id}`;\n\t}\n\tfunction getRuntime(app, id) {\n\t\tconst key = runtimeKey(app, id);\n\t\tlet rt = runtimes.get(key);\n\t\tif (!rt) {\n\t\t\trt = {\n\t\t\t\tchild: void 0,\n\t\t\t\tconsecutiveFastExits: 0,\n\t\t\t\tstartedAt: void 0,\n\t\t\t\tstableTimer: void 0,\n\t\t\t\tbackoffTimer: void 0,\n\t\t\t\texpectedExit: false,\n\t\t\t\tlog: void 0\n\t\t\t};\n\t\t\truntimes.set(key, rt);\n\t\t}\n\t\treturn rt;\n\t}\n\tfunction serviceLogPath(app, id) {\n\t\treturn path.join(stateDir, \"logs\", app, `${id}.log`);\n\t}\n\tfunction getLog(app, id, logPath) {\n\t\tconst rt = getRuntime(app, id);\n\t\tif (!rt.log) rt.log = new ServiceLog(logPath);\n\t\treturn rt.log;\n\t}\n\tfunction schedulePersist() {\n\t\tstateFile.write(state);\n\t}\n\tfunction clearStableTimer(rt) {\n\t\tif (rt.stableTimer) clearTimeout(rt.stableTimer);\n\t\trt.stableTimer = void 0;\n\t}\n\tfunction clearBackoffTimer(rt) {\n\t\tif (rt.backoffTimer) clearTimeout(rt.backoffTimer);\n\t\trt.backoffTimer = void 0;\n\t}\n\tfunction usedServicePorts() {\n\t\tconst ports = /* @__PURE__ */ new Set();\n\t\tfor (const app of Object.values(state)) for (const svc of Object.values(app.services)) ports.add(svc.port);\n\t\treturn ports;\n\t}\n\t/**\n\t* The smallest genuinely free port at or above `MIN_SERVICE_PORT`,\n\t* excluding this daemon's own persisted allocations — persistence and\n\t* the range policy stay ours; whether a candidate is actually bindable\n\t* is `get-port`'s (spec § 2's dependency razor).\n\t*/\n\tasync function smallestUnusedServicePort() {\n\t\treturn getPort({\n\t\t\tport: portNumbers(MIN_SERVICE_PORT, MAX_SERVICE_PORT),\n\t\t\texclude: usedServicePorts()\n\t\t});\n\t}\n\tasync function getOrCreateService(app, id) {\n\t\tlet appRec = state[app];\n\t\tif (!appRec) {\n\t\t\tappRec = { services: {} };\n\t\t\tstate[app] = appRec;\n\t\t}\n\t\tlet svc = appRec.services[id];\n\t\tif (svc) return svc;\n\t\tsvc = {\n\t\t\tid,\n\t\t\taddress: id,\n\t\t\tport: await smallestUnusedServicePort(),\n\t\t\tstatus: \"stopped\",\n\t\t\tlogPath: serviceLogPath(app, id)\n\t\t};\n\t\tappRec.services[id] = svc;\n\t\tschedulePersist();\n\t\treturn svc;\n\t}\n\tfunction waitForExit(child) {\n\t\treturn new Promise((resolve) => {\n\t\t\tchild.once(\"exit\", () => resolve());\n\t\t});\n\t}\n\t/** SIGTERM, wait up to `graceMs`, SIGKILL. Marks the exit as expected so supervision doesn't fire. */\n\tasync function killChild(rt, graceMs) {\n\t\tconst child = rt.child;\n\t\tif (!child || child.pid === void 0) return;\n\t\trt.expectedExit = true;\n\t\tconst exited = waitForExit(child);\n\t\tchild.kill(\"SIGTERM\");\n\t\tconst timedOut = Symbol(\"timeout\");\n\t\tif (await Promise.race([exited.then(() => void 0), sleep(graceMs).then(() => timedOut)]) === timedOut) {\n\t\t\tchild.kill(\"SIGKILL\");\n\t\t\tawait exited;\n\t\t}\n\t}\n\tfunction handleChildExit(app, id, svc, rt, code) {\n\t\tclearStableTimer(rt);\n\t\trt.child = void 0;\n\t\tdelete svc.pid;\n\t\tif (code !== null) svc.lastExitCode = code;\n\t\tif (rt.expectedExit) {\n\t\t\trt.expectedExit = false;\n\t\t\tschedulePersist();\n\t\t\treturn;\n\t\t}\n\t\tconst uptime = rt.startedAt !== void 0 ? Date.now() - rt.startedAt : 0;\n\t\tif (uptime >= STABLE_UPTIME_MS) rt.consecutiveFastExits = 0;\n\t\tconst attemptNumber = rt.consecutiveFastExits;\n\t\tif (uptime < STABLE_UPTIME_MS) rt.consecutiveFastExits += 1;\n\t\tif (rt.consecutiveFastExits >= MAX_CONSECUTIVE_FAST_EXITS) {\n\t\t\tsvc.status = \"held\";\n\t\t\tschedulePersist();\n\t\t\tgetLog(app, id, svc.logPath).writeLine(`[emulator] held after ${String(MAX_CONSECUTIVE_FAST_EXITS)} consecutive fast exits — send a new deployment to resume`);\n\t\t\treturn;\n\t\t}\n\t\tconst delayMs = Math.min(MAX_BACKOFF_MS, BASE_BACKOFF_MS * 2 ** attemptNumber);\n\t\tsvc.status = \"backoff\";\n\t\tschedulePersist();\n\t\tgetLog(app, id, svc.logPath).writeLine(`[emulator] exited (code ${code === null ? \"null\" : String(code)}) — restarting in ${String(delayMs / 1e3)}s`);\n\t\trt.backoffTimer = setTimeout(() => {\n\t\t\trt.backoffTimer = void 0;\n\t\t\tspawnService(app, id, svc, rt, false);\n\t\t}, delayMs);\n\t}\n\tasync function spawnService(app, id, svc, rt, fresh) {\n\t\tconst env = svc.env ?? {};\n\t\tconst artifactDir = svc.artifactDir ?? \".\";\n\t\tconst bunPath = resolveBunOnPath(env);\n\t\tif (!bunPath) {\n\t\t\tsvc.status = \"stopped\";\n\t\t\tdelete svc.pid;\n\t\t\tschedulePersist();\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tmessage: BUN_NOT_FOUND_MESSAGE\n\t\t\t};\n\t\t}\n\t\tconst log = getLog(app, id, svc.logPath);\n\t\tif (fresh) {\n\t\t\tlog.clear();\n\t\t\tlogGeneration.set(svc.logPath, (logGeneration.get(svc.logPath) ?? 0) + 1);\n\t\t}\n\t\tconst child = spawn(bunPath, [\"bootstrap.js\"], {\n\t\t\tcwd: artifactDir,\n\t\t\tenv,\n\t\t\tstdio: [\n\t\t\t\t\"ignore\",\n\t\t\t\t\"pipe\",\n\t\t\t\t\"pipe\"\n\t\t\t]\n\t\t});\n\t\trt.child = child;\n\t\trt.expectedExit = false;\n\t\trt.startedAt = Date.now();\n\t\tclearStableTimer(rt);\n\t\trt.stableTimer = setTimeout(() => {\n\t\t\trt.consecutiveFastExits = 0;\n\t\t}, STABLE_UPTIME_MS);\n\t\tchild.stdout?.on(\"data\", (chunk) => log.writeRaw(chunk));\n\t\tchild.stderr?.on(\"data\", (chunk) => log.writeRaw(chunk));\n\t\tchild.on(\"exit\", (code) => handleChildExit(app, id, svc, rt, code));\n\t\tsvc.status = \"running\";\n\t\tif (child.pid !== void 0) svc.pid = child.pid;\n\t\tschedulePersist();\n\t\treturn { ok: true };\n\t}\n\tasync function stopService(svc, rt) {\n\t\tclearBackoffTimer(rt);\n\t\tclearStableTimer(rt);\n\t\tawait killChild(rt, TERMINATE_GRACE_MS);\n\t\tsvc.status = \"stopped\";\n\t\tdelete svc.pid;\n\t\tschedulePersist();\n\t}\n\t/**\n\t* The session-resume signal: Alchemy's no-op reconcile never fires a\n\t* deployment PUT, so nothing else restarts a service a previous session\n\t* stopped. Reuses the exact deployment-PUT start rules — same spawn\n\t* path, same supervision reset, and an explicit resume clears `held`\n\t* the same way a deployment PUT does — but from the service's already\n\t* STORED deployment spec, since no new one arrives with a start.\n\t*/\n\tasync function startService(app, id, svc) {\n\t\tif (svc.artifactHash === void 0) return;\n\t\tif (svc.status === \"running\") return;\n\t\tconst rt = getRuntime(app, id);\n\t\tclearBackoffTimer(rt);\n\t\tclearStableTimer(rt);\n\t\trt.consecutiveFastExits = 0;\n\t\tawait spawnService(app, id, svc, rt, true);\n\t}\n\tfunction json(res, status, body) {\n\t\tconst text = JSON.stringify(body);\n\t\tres.writeHead(status, { \"content-type\": \"application/json\" });\n\t\tres.end(text);\n\t}\n\tfunction text(res, status, body) {\n\t\tres.writeHead(status, { \"content-type\": \"text/plain; charset=utf-8\" });\n\t\tres.end(body);\n\t}\n\tfunction badSegment(res, segment) {\n\t\ttext(res, 400, `invalid path segment \"${segment}\": must match /^[a-z0-9][a-z0-9-]*$/ and be at most 63 characters`);\n\t}\n\tfunction readBody(req) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst chunks = [];\n\t\t\treq.on(\"data\", (chunk) => chunks.push(chunk));\n\t\t\treq.on(\"end\", () => resolve(Buffer.concat(chunks)));\n\t\t\treq.on(\"error\", reject);\n\t\t});\n\t}\n\tfunction serviceView(svc) {\n\t\treturn {\n\t\t\tid: svc.id,\n\t\t\taddress: svc.address,\n\t\t\tport: svc.port,\n\t\t\turl: `http://localhost:${String(svc.port)}`,\n\t\t\tstatus: svc.status,\n\t\t\t...svc.pid !== void 0 ? { pid: svc.pid } : {},\n\t\t\t...svc.lastExitCode !== void 0 ? { lastExitCode: svc.lastExitCode } : {},\n\t\t\t...svc.artifactHash !== void 0 ? { artifactHash: svc.artifactHash } : {},\n\t\t\tlogPath: svc.logPath\n\t\t};\n\t}\n\tfunction envEquals(a, b) {\n\t\tif (!a) return false;\n\t\tconst aKeys = Object.keys(a);\n\t\tconst bKeys = Object.keys(b);\n\t\tif (aKeys.length !== bKeys.length) return false;\n\t\treturn aKeys.every((k) => a[k] === b[k]);\n\t}\n\tasync function handleDeployment(req, res, app, id) {\n\t\tconst raw = await readBody(req);\n\t\tlet parsed;\n\t\ttry {\n\t\t\tparsed = JSON.parse(raw.toString(\"utf8\"));\n\t\t} catch {\n\t\t\treturn text(res, 400, \"malformed JSON body\");\n\t\t}\n\t\tif (!isDeploymentBody(parsed)) return text(res, 400, \"malformed deployment body\");\n\t\tconst svc = await getOrCreateService(app, id);\n\t\tconst rt = getRuntime(app, id);\n\t\tconst changed = svc.artifactHash !== parsed.artifactHash || !envEquals(svc.env, parsed.env);\n\t\tif (svc.status === \"running\") {\n\t\t\tif (!changed) {\n\t\t\t\tres.writeHead(204);\n\t\t\t\tres.end();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait killChild(rt, TERMINATE_GRACE_MS);\n\t\t} else clearBackoffTimer(rt);\n\t\tsvc.address = parsed.address;\n\t\tsvc.port = parsed.port;\n\t\tclearStableTimer(rt);\n\t\trt.consecutiveFastExits = 0;\n\t\tsvc.artifactHash = parsed.artifactHash;\n\t\tsvc.env = parsed.env;\n\t\tsvc.artifactDir = parsed.artifactDir;\n\t\tschedulePersist();\n\t\tconst result = await spawnService(app, id, svc, rt, true);\n\t\tif (!result.ok) return text(res, 500, result.message ?? \"failed to start the service\");\n\t\tres.writeHead(204);\n\t\tres.end();\n\t}\n\t/** Byte offset a follow should start at to show the last `tailLines` complete lines; `<= 0` (or an empty file) starts at the current end, no backlog. */\n\tfunction startOffsetForTail(logPath, tailLines) {\n\t\tlet size = 0;\n\t\ttry {\n\t\t\tsize = fs.statSync(logPath).size;\n\t\t} catch {\n\t\t\treturn 0;\n\t\t}\n\t\tif (tailLines <= 0 || size === 0) return size;\n\t\tconst fd = fs.openSync(logPath, \"r\");\n\t\ttry {\n\t\t\tconst buf = Buffer.alloc(size);\n\t\t\tfs.readSync(fd, buf, 0, size, 0);\n\t\t\tlet seen = 0;\n\t\t\tfor (let i = size - 1; i >= 0; i -= 1) {\n\t\t\t\tif (buf[i] !== 10) continue;\n\t\t\t\tif (i === size - 1) continue;\n\t\t\t\tseen += 1;\n\t\t\t\tif (seen === tailLines) return i + 1;\n\t\t\t}\n\t\t\treturn 0;\n\t\t} finally {\n\t\t\tfs.closeSync(fd);\n\t\t}\n\t}\n\tfunction handleFollowLogs(res, logPath, tailLines) {\n\t\tfs.mkdirSync(path.dirname(logPath), { recursive: true });\n\t\tif (!fs.existsSync(logPath)) fs.closeSync(fs.openSync(logPath, \"a\"));\n\t\tres.writeHead(200, { \"content-type\": \"text/plain; charset=utf-8\" });\n\t\tlet offset = startOffsetForTail(logPath, tailLines);\n\t\tlet generation = logGeneration.get(logPath) ?? 0;\n\t\tlet stopped = false;\n\t\tlet timer;\n\t\tconst tick = () => {\n\t\t\tif (stopped) return;\n\t\t\tconst currentGeneration = logGeneration.get(logPath) ?? 0;\n\t\t\tif (currentGeneration !== generation) {\n\t\t\t\tgeneration = currentGeneration;\n\t\t\t\toffset = 0;\n\t\t\t}\n\t\t\tlet stat;\n\t\t\ttry {\n\t\t\t\tstat = fs.statSync(logPath);\n\t\t\t} catch {\n\t\t\t\tstat = void 0;\n\t\t\t}\n\t\t\tif (stat && stat.size < offset) offset = 0;\n\t\t\tif (stat && stat.size > offset) {\n\t\t\t\tconst fd = fs.openSync(logPath, \"r\");\n\t\t\t\tconst buf = Buffer.alloc(stat.size - offset);\n\t\t\t\tfs.readSync(fd, buf, 0, buf.length, offset);\n\t\t\t\tfs.closeSync(fd);\n\t\t\t\toffset = stat.size;\n\t\t\t\tres.write(buf);\n\t\t\t}\n\t\t\tif (!stopped) timer = setTimeout(tick, LOG_POLL_INTERVAL_MS);\n\t\t};\n\t\ttick();\n\t\tconst stop = () => {\n\t\t\tstopped = true;\n\t\t\tif (timer) clearTimeout(timer);\n\t\t};\n\t\tres.on(\"close\", stop);\n\t}\n\tasync function handleRequest(req, res) {\n\t\tconst url = new URL(req.url ?? \"/\", `http://127.0.0.1:${String(port)}`);\n\t\tconst method = req.method ?? \"GET\";\n\t\tconst segments = url.pathname.split(\"/\").filter((s) => s.length > 0).map((s) => decodeURIComponent(s));\n\t\tif (method === \"GET\" && segments.length === 1 && segments[0] === \"health\") return json(res, 200, { version: ownVersion });\n\t\tif (segments[0] === \"apps\" && segments.length >= 2) {\n\t\t\tconst app = segments[1];\n\t\t\tif (app === void 0 || !isValidSegment(app)) return badSegment(res, app ?? \"\");\n\t\t\tif (method === \"PUT\" && segments.length === 4 && segments[2] === \"services\") {\n\t\t\t\tconst id = segments[3];\n\t\t\t\tif (id === void 0 || !isValidSegment(id)) return badSegment(res, id ?? \"\");\n\t\t\t\tconst svc = await getOrCreateService(app, id);\n\t\t\t\treturn json(res, 200, {\n\t\t\t\t\tport: svc.port,\n\t\t\t\t\turl: `http://localhost:${String(svc.port)}`\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (method === \"PUT\" && segments.length === 5 && segments[2] === \"services\" && segments[4] === \"deployment\") {\n\t\t\t\tconst id = segments[3];\n\t\t\t\tif (id === void 0 || !isValidSegment(id)) return badSegment(res, id ?? \"\");\n\t\t\t\treturn handleDeployment(req, res, app, id);\n\t\t\t}\n\t\t\tif (method === \"GET\" && segments.length === 3 && segments[2] === \"services\") {\n\t\t\t\tconst appRec = state[app];\n\t\t\t\treturn json(res, 200, appRec ? Object.values(appRec.services).map(serviceView) : []);\n\t\t\t}\n\t\t\tif (method === \"GET\" && segments.length === 5 && segments[2] === \"services\" && segments[4] === \"logs\") {\n\t\t\t\tconst id = segments[3];\n\t\t\t\tif (id === void 0 || !isValidSegment(id)) return badSegment(res, id ?? \"\");\n\t\t\t\tconst svc = state[app]?.services[id];\n\t\t\t\tif (!svc) return text(res, 404, `no such service \"${id}\" in app \"${app}\"`);\n\t\t\t\tif (url.searchParams.get(\"follow\") === \"1\") {\n\t\t\t\t\tconst tailParam = url.searchParams.get(\"tail\");\n\t\t\t\t\tconst tailLines = tailParam === null ? 0 : Math.max(0, Number.parseInt(tailParam, 10) || 0);\n\t\t\t\t\thandleFollowLogs(res, svc.logPath, tailLines);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst content = fs.existsSync(svc.logPath) ? fs.readFileSync(svc.logPath) : Buffer.alloc(0);\n\t\t\t\tres.writeHead(200, { \"content-type\": \"text/plain; charset=utf-8\" });\n\t\t\t\tres.end(content);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (method === \"POST\" && segments.length === 3 && segments[2] === \"stop\") {\n\t\t\t\tconst appRec = state[app];\n\t\t\t\tif (appRec) await Promise.all(Object.entries(appRec.services).map(([id, svc]) => stopService(svc, getRuntime(app, id))));\n\t\t\t\tres.writeHead(204);\n\t\t\t\tres.end();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (method === \"POST\" && segments.length === 3 && segments[2] === \"start\") {\n\t\t\t\tconst appRec = state[app];\n\t\t\t\tif (appRec) await Promise.all(Object.entries(appRec.services).map(([id, svc]) => startService(app, id, svc)));\n\t\t\t\tres.writeHead(204);\n\t\t\t\tres.end();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (method === \"DELETE\" && segments.length === 2) {\n\t\t\t\tconst appRec = state[app];\n\t\t\t\tif (appRec) {\n\t\t\t\t\tawait Promise.all(Object.entries(appRec.services).map(([id, svc]) => stopService(svc, getRuntime(app, id))));\n\t\t\t\t\tfor (const id of Object.keys(appRec.services)) {\n\t\t\t\t\t\tconst key = runtimeKey(app, id);\n\t\t\t\t\t\truntimes.get(key)?.log?.close();\n\t\t\t\t\t\truntimes.delete(key);\n\t\t\t\t\t}\n\t\t\t\t\tdelete state[app];\n\t\t\t\t\tschedulePersist();\n\t\t\t\t}\n\t\t\t\tawait fs.promises.rm(path.join(stateDir, \"logs\", app), {\n\t\t\t\t\trecursive: true,\n\t\t\t\t\tforce: true\n\t\t\t\t});\n\t\t\t\tres.writeHead(204);\n\t\t\t\tres.end();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tres.writeHead(404);\n\t\tres.end();\n\t}\n\tconst server = http.createServer((req, res) => {\n\t\thandleRequest(req, res).catch((err) => {\n\t\t\tif (!res.headersSent) res.writeHead(500, { \"content-type\": \"text/plain\" });\n\t\t\tres.end(err instanceof Error ? err.message : String(err));\n\t\t});\n\t});\n\tlet shuttingDown = false;\n\tasync function shutdown() {\n\t\tif (shuttingDown) return;\n\t\tshuttingDown = true;\n\t\tconst kills = [];\n\t\tfor (const rt of runtimes.values()) {\n\t\t\tclearBackoffTimer(rt);\n\t\t\tclearStableTimer(rt);\n\t\t\tif (rt.child) kills.push(killChild(rt, TERMINATE_GRACE_MS));\n\t\t}\n\t\tawait Promise.all(kills);\n\t\tawait stateFile.flush();\n\t\tserver.close();\n\t\tprocess.exit(0);\n\t}\n\tprocess.on(\"SIGTERM\", () => void shutdown());\n\tprocess.on(\"SIGINT\", () => void shutdown());\n\treadJsonFile(appsJsonPath, isAppsState).then((loaded) => {\n\t\tif (loaded) {\n\t\t\tfor (const appRec of Object.values(loaded)) for (const svc of Object.values(appRec.services)) if (svc.status === \"running\" || svc.status === \"backoff\") {\n\t\t\t\tsvc.status = \"stopped\";\n\t\t\t\tdelete svc.pid;\n\t\t\t}\n\t\t\tstate = loaded;\n\t\t}\n\t\tserver.listen(port, \"127.0.0.1\", () => {\n\t\t\tconsole.log(`[dev-emulators] compute-main listening on 127.0.0.1:${String(port)}`);\n\t\t});\n\t}).catch((err) => {\n\t\tconsole.error(\"compute-main: failed to load state\", err);\n\t\tprocess.exit(1);\n\t});\n}\nmain();\n//#endregion\nexport {};\n\n//# sourceMappingURL=compute-main.mjs.map"],"mappings":";;;;;;;;;;;;;;;;;;;AAmBA,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;AACzB,MAAM,qBAAq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dev-emulators/dist/compute-main.mjs"],"sourcesContent":["import { l as readOwnVersion, m as readJsonFile, p as StateFile, t as isValidSegment } from \"./segments-DRPHe3kK.mjs\";\nimport * as fs from \"node:fs\";\nimport { spawn } from \"node:child_process\";\nimport * as path from \"node:path\";\nimport getPort, { portNumbers } from \"get-port\";\nimport * as http from \"node:http\";\n//#region src/compute-main.ts\n/**\n* The Compute emulator daemon (local-dev spec § 2 `compute-main.ts`): a small\n* local counterpart of the platform's compute service. Owns service child\n* processes (spawned `bun bootstrap.js` from a real packaged artifact),\n* supervises them (crash backoff, held after repeated fast crashes), and\n* serves a loopback JSON admin API plus per-service log streaming.\n*\n* Runs as its own OS process, started by `daemon.ts`'s `ensureDaemon` via\n* `process.execPath <this file> --port <n> --state-dir <dir>`. Everything it\n* needs travels on argv and each request's own body — it reads no\n* environment variable of its own.\n*/\nconst MIN_SERVICE_PORT = 3e3;\nconst MAX_SERVICE_PORT = 65535;\nconst TERMINATE_GRACE_MS = 5e3;\nconst STABLE_UPTIME_MS = 3e4;\nconst BASE_BACKOFF_MS = 1e3;\nconst MAX_BACKOFF_MS = 3e4;\nconst MAX_CONSECUTIVE_FAST_EXITS = 5;\nconst LOG_POLL_INTERVAL_MS = 100;\nconst APPS_STATE_MODE = 384;\nconst BUN_NOT_FOUND_MESSAGE = \"local dev runs services under bun — the Prisma Compute runtime — and `bun` was not found on PATH. Install it: https://bun.sh.\";\nfunction isServiceStatus(value) {\n\treturn value === \"running\" || value === \"backoff\" || value === \"held\" || value === \"stopped\";\n}\nfunction isStringRecord(value) {\n\treturn typeof value === \"object\" && value !== null && Object.values(value).every((v) => typeof v === \"string\");\n}\nfunction isServiceRecord(value) {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tif (!(\"id\" in value) || typeof value.id !== \"string\") return false;\n\tif (!(\"address\" in value) || typeof value.address !== \"string\") return false;\n\tif (!(\"port\" in value) || typeof value.port !== \"number\") return false;\n\tif (!(\"status\" in value) || !isServiceStatus(value.status)) return false;\n\tif (!(\"logPath\" in value) || typeof value.logPath !== \"string\") return false;\n\tif (\"pid\" in value && value.pid !== void 0 && typeof value.pid !== \"number\") return false;\n\tif (\"lastExitCode\" in value && value.lastExitCode !== void 0 && typeof value.lastExitCode !== \"number\") return false;\n\tif (\"artifactHash\" in value && value.artifactHash !== void 0 && typeof value.artifactHash !== \"string\") return false;\n\tif (\"artifactDir\" in value && value.artifactDir !== void 0 && typeof value.artifactDir !== \"string\") return false;\n\tif (\"env\" in value && value.env !== void 0 && !isStringRecord(value.env)) return false;\n\treturn true;\n}\nfunction isAppRecord(value) {\n\treturn typeof value === \"object\" && value !== null && \"services\" in value && typeof value.services === \"object\" && value.services !== null && Object.values(value.services).every(isServiceRecord);\n}\nfunction isAppsState(value) {\n\treturn typeof value === \"object\" && value !== null && Object.values(value).every(isAppRecord);\n}\nfunction isDeploymentBody(value) {\n\treturn typeof value === \"object\" && value !== null && \"address\" in value && typeof value.address === \"string\" && \"artifactDir\" in value && typeof value.artifactDir === \"string\" && \"artifactHash\" in value && typeof value.artifactHash === \"string\" && \"env\" in value && isStringRecord(value.env) && \"port\" in value && typeof value.port === \"number\";\n}\nfunction sleep(ms) {\n\treturn new Promise((resolve) => setTimeout(resolve, ms));\n}\n/** Append-only per-service log file — child stdout/stderr plus `[emulator]` supervision lines. No rotation in v1. */\nvar ServiceLog = class {\n\tfilePath;\n\tfd;\n\tconstructor(filePath) {\n\t\tthis.filePath = filePath;\n\t}\n\tensureOpen() {\n\t\tif (this.fd === void 0) {\n\t\t\tfs.mkdirSync(path.dirname(this.filePath), { recursive: true });\n\t\t\tthis.fd = fs.openSync(this.filePath, \"a\");\n\t\t}\n\t\treturn this.fd;\n\t}\n\twriteRaw(chunk) {\n\t\tfs.writeSync(this.ensureOpen(), chunk);\n\t}\n\twriteLine(line) {\n\t\tfs.writeSync(this.ensureOpen(), `${line}\\n`);\n\t}\n\t/** Empties the file — a fresh service start begins a clean log; past sessions' and past deployments' output is not kept. */\n\tclear() {\n\t\tfs.ftruncateSync(this.ensureOpen(), 0);\n\t}\n\t/** Closes the fd if one was ever opened. Idempotent. */\n\tclose() {\n\t\tif (this.fd === void 0) return;\n\t\tfs.closeSync(this.fd);\n\t\tthis.fd = void 0;\n\t}\n};\nfunction parseArgs(argv) {\n\tlet port;\n\tlet stateDir;\n\tfor (let i = 0; i < argv.length; i++) if (argv[i] === \"--port\") port = Number(argv[i + 1]);\n\telse if (argv[i] === \"--state-dir\") stateDir = argv[i + 1];\n\tif (port === void 0 || Number.isNaN(port)) throw new Error(\"compute-main: --port <n> is required\");\n\tif (stateDir === void 0) throw new Error(\"compute-main: --state-dir <dir> is required\");\n\treturn {\n\t\tport,\n\t\tstateDir\n\t};\n}\n/** Resolves `bun` from THIS request's env PATH — never the daemon's own. POSIX-only (Windows is out of scope). */\nfunction resolveBunOnPath(env) {\n\tconst pathVar = env[\"PATH\"];\n\tif (!pathVar) return void 0;\n\tfor (const dir of pathVar.split(path.delimiter)) {\n\t\tif (dir === \"\") continue;\n\t\tconst candidate = path.join(dir, \"bun\");\n\t\ttry {\n\t\t\tfs.accessSync(candidate, fs.constants.X_OK);\n\t\t\treturn candidate;\n\t\t} catch {}\n\t}\n}\nfunction main() {\n\tconst { port, stateDir } = parseArgs(process.argv.slice(2));\n\tconst ownVersion = readOwnVersion();\n\tconst appsJsonPath = path.join(stateDir, \"apps.json\");\n\tconst stateFile = new StateFile(appsJsonPath, APPS_STATE_MODE);\n\tlet state = {};\n\tconst runtimes = /* @__PURE__ */ new Map();\n\tconst logGeneration = /* @__PURE__ */ new Map();\n\tfunction runtimeKey(app, id) {\n\t\treturn `${app}/${id}`;\n\t}\n\tfunction getRuntime(app, id) {\n\t\tconst key = runtimeKey(app, id);\n\t\tlet rt = runtimes.get(key);\n\t\tif (!rt) {\n\t\t\trt = {\n\t\t\t\tchild: void 0,\n\t\t\t\tconsecutiveFastExits: 0,\n\t\t\t\tstartedAt: void 0,\n\t\t\t\tstableTimer: void 0,\n\t\t\t\tbackoffTimer: void 0,\n\t\t\t\texpectedExit: false,\n\t\t\t\tlog: void 0\n\t\t\t};\n\t\t\truntimes.set(key, rt);\n\t\t}\n\t\treturn rt;\n\t}\n\tfunction serviceLogPath(app, id) {\n\t\treturn path.join(stateDir, \"logs\", app, `${id}.log`);\n\t}\n\tfunction getLog(app, id, logPath) {\n\t\tconst rt = getRuntime(app, id);\n\t\tif (!rt.log) rt.log = new ServiceLog(logPath);\n\t\treturn rt.log;\n\t}\n\tfunction schedulePersist() {\n\t\tstateFile.write(state);\n\t}\n\tfunction clearStableTimer(rt) {\n\t\tif (rt.stableTimer) clearTimeout(rt.stableTimer);\n\t\trt.stableTimer = void 0;\n\t}\n\tfunction clearBackoffTimer(rt) {\n\t\tif (rt.backoffTimer) clearTimeout(rt.backoffTimer);\n\t\trt.backoffTimer = void 0;\n\t}\n\tfunction usedServicePorts() {\n\t\tconst ports = /* @__PURE__ */ new Set();\n\t\tfor (const app of Object.values(state)) for (const svc of Object.values(app.services)) ports.add(svc.port);\n\t\treturn ports;\n\t}\n\t/**\n\t* The smallest genuinely free port at or above `MIN_SERVICE_PORT`,\n\t* excluding this daemon's own persisted allocations — persistence and\n\t* the range policy stay ours; whether a candidate is actually bindable\n\t* is `get-port`'s (spec § 2's dependency razor).\n\t*/\n\tasync function smallestUnusedServicePort() {\n\t\treturn getPort({\n\t\t\tport: portNumbers(MIN_SERVICE_PORT, MAX_SERVICE_PORT),\n\t\t\texclude: usedServicePorts()\n\t\t});\n\t}\n\tasync function getOrCreateService(app, id) {\n\t\tlet appRec = state[app];\n\t\tif (!appRec) {\n\t\t\tappRec = { services: {} };\n\t\t\tstate[app] = appRec;\n\t\t}\n\t\tlet svc = appRec.services[id];\n\t\tif (svc) return svc;\n\t\tsvc = {\n\t\t\tid,\n\t\t\taddress: id,\n\t\t\tport: await smallestUnusedServicePort(),\n\t\t\tstatus: \"stopped\",\n\t\t\tlogPath: serviceLogPath(app, id)\n\t\t};\n\t\tappRec.services[id] = svc;\n\t\tschedulePersist();\n\t\treturn svc;\n\t}\n\tfunction waitForExit(child) {\n\t\treturn new Promise((resolve) => {\n\t\t\tchild.once(\"exit\", () => resolve());\n\t\t});\n\t}\n\t/** SIGTERM, wait up to `graceMs`, SIGKILL. Marks the exit as expected so supervision doesn't fire. */\n\tasync function killChild(rt, graceMs) {\n\t\tconst child = rt.child;\n\t\tif (!child || child.pid === void 0) return;\n\t\trt.expectedExit = true;\n\t\tconst exited = waitForExit(child);\n\t\tchild.kill(\"SIGTERM\");\n\t\tconst timedOut = Symbol(\"timeout\");\n\t\tif (await Promise.race([exited.then(() => void 0), sleep(graceMs).then(() => timedOut)]) === timedOut) {\n\t\t\tchild.kill(\"SIGKILL\");\n\t\t\tawait exited;\n\t\t}\n\t}\n\tfunction handleChildExit(app, id, svc, rt, code) {\n\t\tclearStableTimer(rt);\n\t\trt.child = void 0;\n\t\tdelete svc.pid;\n\t\tif (code !== null) svc.lastExitCode = code;\n\t\tif (rt.expectedExit) {\n\t\t\trt.expectedExit = false;\n\t\t\tschedulePersist();\n\t\t\treturn;\n\t\t}\n\t\tconst uptime = rt.startedAt !== void 0 ? Date.now() - rt.startedAt : 0;\n\t\tif (uptime >= STABLE_UPTIME_MS) rt.consecutiveFastExits = 0;\n\t\tconst attemptNumber = rt.consecutiveFastExits;\n\t\tif (uptime < STABLE_UPTIME_MS) rt.consecutiveFastExits += 1;\n\t\tif (rt.consecutiveFastExits >= MAX_CONSECUTIVE_FAST_EXITS) {\n\t\t\tsvc.status = \"held\";\n\t\t\tschedulePersist();\n\t\t\tgetLog(app, id, svc.logPath).writeLine(`[emulator] held after ${String(MAX_CONSECUTIVE_FAST_EXITS)} consecutive fast exits — send a new deployment to resume`);\n\t\t\treturn;\n\t\t}\n\t\tconst delayMs = Math.min(MAX_BACKOFF_MS, BASE_BACKOFF_MS * 2 ** attemptNumber);\n\t\tsvc.status = \"backoff\";\n\t\tschedulePersist();\n\t\tgetLog(app, id, svc.logPath).writeLine(`[emulator] exited (code ${code === null ? \"null\" : String(code)}) — restarting in ${String(delayMs / 1e3)}s`);\n\t\trt.backoffTimer = setTimeout(() => {\n\t\t\trt.backoffTimer = void 0;\n\t\t\tspawnService(app, id, svc, rt, false);\n\t\t}, delayMs);\n\t}\n\tasync function spawnService(app, id, svc, rt, fresh) {\n\t\tconst env = svc.env ?? {};\n\t\tconst artifactDir = svc.artifactDir ?? \".\";\n\t\tconst bunPath = resolveBunOnPath(env);\n\t\tif (!bunPath) {\n\t\t\tsvc.status = \"stopped\";\n\t\t\tdelete svc.pid;\n\t\t\tschedulePersist();\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tmessage: BUN_NOT_FOUND_MESSAGE\n\t\t\t};\n\t\t}\n\t\tconst log = getLog(app, id, svc.logPath);\n\t\tif (fresh) {\n\t\t\tlog.clear();\n\t\t\tlogGeneration.set(svc.logPath, (logGeneration.get(svc.logPath) ?? 0) + 1);\n\t\t}\n\t\tconst child = spawn(bunPath, [\"bootstrap.js\"], {\n\t\t\tcwd: artifactDir,\n\t\t\tenv,\n\t\t\tstdio: [\n\t\t\t\t\"ignore\",\n\t\t\t\t\"pipe\",\n\t\t\t\t\"pipe\"\n\t\t\t]\n\t\t});\n\t\trt.child = child;\n\t\trt.expectedExit = false;\n\t\trt.startedAt = Date.now();\n\t\tclearStableTimer(rt);\n\t\trt.stableTimer = setTimeout(() => {\n\t\t\trt.consecutiveFastExits = 0;\n\t\t}, STABLE_UPTIME_MS);\n\t\tchild.stdout?.on(\"data\", (chunk) => log.writeRaw(chunk));\n\t\tchild.stderr?.on(\"data\", (chunk) => log.writeRaw(chunk));\n\t\tchild.on(\"exit\", (code) => handleChildExit(app, id, svc, rt, code));\n\t\tsvc.status = \"running\";\n\t\tif (child.pid !== void 0) svc.pid = child.pid;\n\t\tschedulePersist();\n\t\treturn { ok: true };\n\t}\n\tasync function stopService(svc, rt) {\n\t\tclearBackoffTimer(rt);\n\t\tclearStableTimer(rt);\n\t\tawait killChild(rt, TERMINATE_GRACE_MS);\n\t\tsvc.status = \"stopped\";\n\t\tdelete svc.pid;\n\t\tschedulePersist();\n\t}\n\t/**\n\t* The session-resume signal: Alchemy's no-op reconcile never fires a\n\t* deployment PUT, so nothing else restarts a service a previous session\n\t* stopped. Reuses the exact deployment-PUT start rules — same spawn\n\t* path, same supervision reset, and an explicit resume clears `held`\n\t* the same way a deployment PUT does — but from the service's already\n\t* STORED deployment spec, since no new one arrives with a start.\n\t*/\n\tasync function startService(app, id, svc) {\n\t\tif (svc.artifactHash === void 0) return;\n\t\tif (svc.status === \"running\") return;\n\t\tconst rt = getRuntime(app, id);\n\t\tclearBackoffTimer(rt);\n\t\tclearStableTimer(rt);\n\t\trt.consecutiveFastExits = 0;\n\t\tawait spawnService(app, id, svc, rt, true);\n\t}\n\tfunction json(res, status, body) {\n\t\tconst text = JSON.stringify(body);\n\t\tres.writeHead(status, { \"content-type\": \"application/json\" });\n\t\tres.end(text);\n\t}\n\tfunction text(res, status, body) {\n\t\tres.writeHead(status, { \"content-type\": \"text/plain; charset=utf-8\" });\n\t\tres.end(body);\n\t}\n\tfunction badSegment(res, segment) {\n\t\ttext(res, 400, `invalid path segment \"${segment}\": must match /^[a-z0-9][a-z0-9-]*$/ and be at most 63 characters`);\n\t}\n\tfunction readBody(req) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst chunks = [];\n\t\t\treq.on(\"data\", (chunk) => chunks.push(chunk));\n\t\t\treq.on(\"end\", () => resolve(Buffer.concat(chunks)));\n\t\t\treq.on(\"error\", reject);\n\t\t});\n\t}\n\tfunction serviceView(svc) {\n\t\treturn {\n\t\t\tid: svc.id,\n\t\t\taddress: svc.address,\n\t\t\tport: svc.port,\n\t\t\turl: `http://localhost:${String(svc.port)}`,\n\t\t\tstatus: svc.status,\n\t\t\t...svc.pid !== void 0 ? { pid: svc.pid } : {},\n\t\t\t...svc.lastExitCode !== void 0 ? { lastExitCode: svc.lastExitCode } : {},\n\t\t\t...svc.artifactHash !== void 0 ? { artifactHash: svc.artifactHash } : {},\n\t\t\tlogPath: svc.logPath\n\t\t};\n\t}\n\tfunction envEquals(a, b) {\n\t\tif (!a) return false;\n\t\tconst aKeys = Object.keys(a);\n\t\tconst bKeys = Object.keys(b);\n\t\tif (aKeys.length !== bKeys.length) return false;\n\t\treturn aKeys.every((k) => a[k] === b[k]);\n\t}\n\tasync function handleDeployment(req, res, app, id) {\n\t\tconst raw = await readBody(req);\n\t\tlet parsed;\n\t\ttry {\n\t\t\tparsed = JSON.parse(raw.toString(\"utf8\"));\n\t\t} catch {\n\t\t\treturn text(res, 400, \"malformed JSON body\");\n\t\t}\n\t\tif (!isDeploymentBody(parsed)) return text(res, 400, \"malformed deployment body\");\n\t\tconst svc = await getOrCreateService(app, id);\n\t\tconst rt = getRuntime(app, id);\n\t\tconst changed = svc.artifactHash !== parsed.artifactHash || !envEquals(svc.env, parsed.env);\n\t\tif (svc.status === \"running\") {\n\t\t\tif (!changed) {\n\t\t\t\tres.writeHead(204);\n\t\t\t\tres.end();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait killChild(rt, TERMINATE_GRACE_MS);\n\t\t} else clearBackoffTimer(rt);\n\t\tsvc.address = parsed.address;\n\t\tsvc.port = parsed.port;\n\t\tclearStableTimer(rt);\n\t\trt.consecutiveFastExits = 0;\n\t\tsvc.artifactHash = parsed.artifactHash;\n\t\tsvc.env = parsed.env;\n\t\tsvc.artifactDir = parsed.artifactDir;\n\t\tschedulePersist();\n\t\tconst result = await spawnService(app, id, svc, rt, true);\n\t\tif (!result.ok) return text(res, 500, result.message ?? \"failed to start the service\");\n\t\tres.writeHead(204);\n\t\tres.end();\n\t}\n\t/** Byte offset a follow should start at to show the last `tailLines` complete lines; `<= 0` (or an empty file) starts at the current end, no backlog. */\n\tfunction startOffsetForTail(logPath, tailLines) {\n\t\tlet size = 0;\n\t\ttry {\n\t\t\tsize = fs.statSync(logPath).size;\n\t\t} catch {\n\t\t\treturn 0;\n\t\t}\n\t\tif (tailLines <= 0 || size === 0) return size;\n\t\tconst fd = fs.openSync(logPath, \"r\");\n\t\ttry {\n\t\t\tconst buf = Buffer.alloc(size);\n\t\t\tfs.readSync(fd, buf, 0, size, 0);\n\t\t\tlet seen = 0;\n\t\t\tfor (let i = size - 1; i >= 0; i -= 1) {\n\t\t\t\tif (buf[i] !== 10) continue;\n\t\t\t\tif (i === size - 1) continue;\n\t\t\t\tseen += 1;\n\t\t\t\tif (seen === tailLines) return i + 1;\n\t\t\t}\n\t\t\treturn 0;\n\t\t} finally {\n\t\t\tfs.closeSync(fd);\n\t\t}\n\t}\n\tfunction handleFollowLogs(res, logPath, tailLines) {\n\t\tfs.mkdirSync(path.dirname(logPath), { recursive: true });\n\t\tif (!fs.existsSync(logPath)) fs.closeSync(fs.openSync(logPath, \"a\"));\n\t\tres.writeHead(200, { \"content-type\": \"text/plain; charset=utf-8\" });\n\t\tlet offset = startOffsetForTail(logPath, tailLines);\n\t\tlet generation = logGeneration.get(logPath) ?? 0;\n\t\tlet stopped = false;\n\t\tlet timer;\n\t\tconst tick = () => {\n\t\t\tif (stopped) return;\n\t\t\tconst currentGeneration = logGeneration.get(logPath) ?? 0;\n\t\t\tif (currentGeneration !== generation) {\n\t\t\t\tgeneration = currentGeneration;\n\t\t\t\toffset = 0;\n\t\t\t}\n\t\t\tlet stat;\n\t\t\ttry {\n\t\t\t\tstat = fs.statSync(logPath);\n\t\t\t} catch {\n\t\t\t\tstat = void 0;\n\t\t\t}\n\t\t\tif (stat && stat.size < offset) offset = 0;\n\t\t\tif (stat && stat.size > offset) {\n\t\t\t\tconst fd = fs.openSync(logPath, \"r\");\n\t\t\t\tconst buf = Buffer.alloc(stat.size - offset);\n\t\t\t\tfs.readSync(fd, buf, 0, buf.length, offset);\n\t\t\t\tfs.closeSync(fd);\n\t\t\t\toffset = stat.size;\n\t\t\t\tres.write(buf);\n\t\t\t}\n\t\t\tif (!stopped) timer = setTimeout(tick, LOG_POLL_INTERVAL_MS);\n\t\t};\n\t\ttick();\n\t\tconst stop = () => {\n\t\t\tstopped = true;\n\t\t\tif (timer) clearTimeout(timer);\n\t\t};\n\t\tres.on(\"close\", stop);\n\t}\n\tasync function handleRequest(req, res) {\n\t\tconst url = new URL(req.url ?? \"/\", `http://127.0.0.1:${String(port)}`);\n\t\tconst method = req.method ?? \"GET\";\n\t\tconst segments = url.pathname.split(\"/\").filter((s) => s.length > 0).map((s) => decodeURIComponent(s));\n\t\tif (method === \"GET\" && segments.length === 1 && segments[0] === \"health\") return json(res, 200, { version: ownVersion });\n\t\tif (segments[0] === \"apps\" && segments.length >= 2) {\n\t\t\tconst app = segments[1];\n\t\t\tif (app === void 0 || !isValidSegment(app)) return badSegment(res, app ?? \"\");\n\t\t\tif (method === \"PUT\" && segments.length === 4 && segments[2] === \"services\") {\n\t\t\t\tconst id = segments[3];\n\t\t\t\tif (id === void 0 || !isValidSegment(id)) return badSegment(res, id ?? \"\");\n\t\t\t\tconst svc = await getOrCreateService(app, id);\n\t\t\t\treturn json(res, 200, {\n\t\t\t\t\tport: svc.port,\n\t\t\t\t\turl: `http://localhost:${String(svc.port)}`\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (method === \"PUT\" && segments.length === 5 && segments[2] === \"services\" && segments[4] === \"deployment\") {\n\t\t\t\tconst id = segments[3];\n\t\t\t\tif (id === void 0 || !isValidSegment(id)) return badSegment(res, id ?? \"\");\n\t\t\t\treturn handleDeployment(req, res, app, id);\n\t\t\t}\n\t\t\tif (method === \"GET\" && segments.length === 3 && segments[2] === \"services\") {\n\t\t\t\tconst appRec = state[app];\n\t\t\t\treturn json(res, 200, appRec ? Object.values(appRec.services).map(serviceView) : []);\n\t\t\t}\n\t\t\tif (method === \"GET\" && segments.length === 5 && segments[2] === \"services\" && segments[4] === \"logs\") {\n\t\t\t\tconst id = segments[3];\n\t\t\t\tif (id === void 0 || !isValidSegment(id)) return badSegment(res, id ?? \"\");\n\t\t\t\tconst svc = state[app]?.services[id];\n\t\t\t\tif (!svc) return text(res, 404, `no such service \"${id}\" in app \"${app}\"`);\n\t\t\t\tif (url.searchParams.get(\"follow\") === \"1\") {\n\t\t\t\t\tconst tailParam = url.searchParams.get(\"tail\");\n\t\t\t\t\tconst tailLines = tailParam === null ? 0 : Math.max(0, Number.parseInt(tailParam, 10) || 0);\n\t\t\t\t\thandleFollowLogs(res, svc.logPath, tailLines);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst content = fs.existsSync(svc.logPath) ? fs.readFileSync(svc.logPath) : Buffer.alloc(0);\n\t\t\t\tres.writeHead(200, { \"content-type\": \"text/plain; charset=utf-8\" });\n\t\t\t\tres.end(content);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (method === \"POST\" && segments.length === 3 && segments[2] === \"stop\") {\n\t\t\t\tconst appRec = state[app];\n\t\t\t\tif (appRec) await Promise.all(Object.entries(appRec.services).map(([id, svc]) => stopService(svc, getRuntime(app, id))));\n\t\t\t\tres.writeHead(204);\n\t\t\t\tres.end();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (method === \"POST\" && segments.length === 3 && segments[2] === \"start\") {\n\t\t\t\tconst appRec = state[app];\n\t\t\t\tif (appRec) await Promise.all(Object.entries(appRec.services).map(([id, svc]) => startService(app, id, svc)));\n\t\t\t\tres.writeHead(204);\n\t\t\t\tres.end();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (method === \"DELETE\" && segments.length === 2) {\n\t\t\t\tconst appRec = state[app];\n\t\t\t\tif (appRec) {\n\t\t\t\t\tawait Promise.all(Object.entries(appRec.services).map(([id, svc]) => stopService(svc, getRuntime(app, id))));\n\t\t\t\t\tfor (const id of Object.keys(appRec.services)) {\n\t\t\t\t\t\tconst key = runtimeKey(app, id);\n\t\t\t\t\t\truntimes.get(key)?.log?.close();\n\t\t\t\t\t\truntimes.delete(key);\n\t\t\t\t\t}\n\t\t\t\t\tdelete state[app];\n\t\t\t\t\tschedulePersist();\n\t\t\t\t}\n\t\t\t\tawait fs.promises.rm(path.join(stateDir, \"logs\", app), {\n\t\t\t\t\trecursive: true,\n\t\t\t\t\tforce: true\n\t\t\t\t});\n\t\t\t\tres.writeHead(204);\n\t\t\t\tres.end();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tres.writeHead(404);\n\t\tres.end();\n\t}\n\tconst server = http.createServer((req, res) => {\n\t\thandleRequest(req, res).catch((err) => {\n\t\t\tif (!res.headersSent) res.writeHead(500, { \"content-type\": \"text/plain\" });\n\t\t\tres.end(err instanceof Error ? err.message : String(err));\n\t\t});\n\t});\n\tlet shuttingDown = false;\n\tasync function shutdown() {\n\t\tif (shuttingDown) return;\n\t\tshuttingDown = true;\n\t\tconst kills = [];\n\t\tfor (const rt of runtimes.values()) {\n\t\t\tclearBackoffTimer(rt);\n\t\t\tclearStableTimer(rt);\n\t\t\tif (rt.child) kills.push(killChild(rt, TERMINATE_GRACE_MS));\n\t\t}\n\t\tawait Promise.all(kills);\n\t\tawait stateFile.flush();\n\t\tserver.close();\n\t\tprocess.exit(0);\n\t}\n\tprocess.on(\"SIGTERM\", () => void shutdown());\n\tprocess.on(\"SIGINT\", () => void shutdown());\n\treadJsonFile(appsJsonPath, isAppsState).then((loaded) => {\n\t\tif (loaded) {\n\t\t\tfor (const appRec of Object.values(loaded)) for (const svc of Object.values(appRec.services)) if (svc.status === \"running\" || svc.status === \"backoff\") {\n\t\t\t\tsvc.status = \"stopped\";\n\t\t\t\tdelete svc.pid;\n\t\t\t}\n\t\t\tstate = loaded;\n\t\t}\n\t\tserver.listen(port, \"127.0.0.1\", () => {\n\t\t\tconsole.log(`[dev-emulators] compute-main listening on 127.0.0.1:${String(port)}`);\n\t\t});\n\t}).catch((err) => {\n\t\tconsole.error(\"compute-main: failed to load state\", err);\n\t\tprocess.exit(1);\n\t});\n}\nmain();\n//#endregion\nexport {};\n\n//# sourceMappingURL=compute-main.mjs.map"],"mappings":";;;;;;;;;;;;;;;;;;;AAmBA,MAAM,mBAAmB;AACzB,MAAM,mBAA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